From 0dfe9995cd18fdcbfe61c135dd21a357528068ab Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 03:58:56 +0000 Subject: [PATCH 01/26] Add a plugin hook for Vite plugins Plugin.get_vite_plugins() returns VitePluginEntry objects, each carrying the import statements and the expression to place in the plugins array of the generated vite.config.js, ahead of reactRouter(). Entries keep rxconfig plugin order then entry order, shared imports render once, and a malformed entry raises InvalidVitePluginError naming the plugin. With no entries the rendered file is unchanged. Claude-Session: https://claude.ai/code/session_014AwvTNGETBu7Fzvwjqecm4 --- docs/api-reference/plugins.md | 68 +++++++ news/+vite-plugin-hook.feature.md | 1 + .../news/+vite-plugin-hook.feature.md | 11 ++ .../src/reflex_base/compiler/templates.py | 20 ++- .../src/reflex_base/plugins/__init__.py | 3 + .../src/reflex_base/plugins/base.py | 54 ++++++ .../src/reflex_base/utils/exceptions.py | 4 + reflex/plugins/__init__.py | 2 + reflex/utils/frontend_skeleton.py | 66 +++++++ .../integration/tests_playwright/test_icon.py | 82 ++++++++- .../reflex_base/compiler/test_templates.py | 113 +++++++++++- tests/units/reflex_base/plugins/test_base.py | 5 + tests/units/utils/test_frontend_skeleton.py | 166 ++++++++++++++++++ 13 files changed, 590 insertions(+), 5 deletions(-) create mode 100644 news/+vite-plugin-hook.feature.md create mode 100644 packages/reflex-base/news/+vite-plugin-hook.feature.md diff --git a/docs/api-reference/plugins.md b/docs/api-reference/plugins.md index 3374544c415..3066cc9c7ab 100644 --- a/docs/api-reference/plugins.md +++ b/docs/api-reference/plugins.md @@ -203,6 +203,10 @@ class Plugin: """Get paths to stylesheets required by the plugin.""" return [] + def get_vite_plugins(self, **context) -> Sequence[VitePluginEntry]: + """Get Vite plugins to add to the generated vite.config.js.""" + return [] + def register_route(self, **context) -> None: """Contribute pages before the app's first compilation.""" pass @@ -295,6 +299,70 @@ during collection, while the framework owns the final batch commit. The public API but are intentionally not dispatched during a staged plugin batch, so an override cannot make the batch commit partially. +### Adding Vite Plugins + +Reflex generates the app's `vite.config.js` and rewrites it on every compile. A +plugin adds a Vite plugin to it by overriding `get_vite_plugins`, which returns +`VitePluginEntry` objects. Each entry carries JavaScript source: the import +statements it needs, and the expression to place in the `plugins` array. + +```python +from reflex.plugins import Plugin, VitePluginEntry + + +class InspectPlugin(Plugin): + def get_frontend_development_dependencies(self, **context): + return ["vite-plugin-inspect"] + + def get_vite_plugins(self, **context): + return [ + VitePluginEntry( + imports=['import inspect from "vite-plugin-inspect"'], + call="inspect({ build: true })", + ) + ] +``` + +This renders as: + +```javascript +import inspect from "vite-plugin-inspect"; + +export default defineConfig((config) => ({ + plugins: [ + alwaysUseReactDomServerNode(), + inspect({ build: true }), + reactRouter(), + // ... + ], +})); +``` + +- `imports` is a sequence of import statements, one per string, with or without + the closing semicolon. An entry may need several. A statement that several + entries share is written once, so two plugins can import the same name from + the same package; importing one name from two different modules is a syntax + error in the generated file. +- `call` is any JavaScript expression: usually a call, possibly spanning + several lines. It may evaluate to one Vite plugin or to an array of them. +- Module specifiers resolve from `.web`. Import an npm package by name, and a + file the plugin writes with `get_static_assets` by its relative path, such as + `"./my-vite-plugin.js"`. +- Entries are placed ahead of `reactRouter()` (and after React Compiler, when + `react_compiler` is enabled), in the order of the plugins in `rxconfig.py` + and then in the order each plugin returns them. Vite's own `enforce: "pre"` + and `enforce: "post"` still apply within that order. +- A Vite plugin only runs at build time, so declare its npm packages in + `get_frontend_development_dependencies`. Packages returned from + `get_frontend_dependencies` are also bundled into the app. + +A malformed entry stops the compile with an `InvalidVitePluginError` that names +the plugin and the entry, for example: + +```text +InspectPlugin.get_vite_plugins() returned an invalid entry: entry 0 has 'vite-plugin-inspect' in imports, which is not an import statement. +``` + ### Looking Up Configured Plugins Use `rx.plugins.get_plugin(PluginType)` when runtime behavior needs the plugin diff --git a/news/+vite-plugin-hook.feature.md b/news/+vite-plugin-hook.feature.md new file mode 100644 index 00000000000..a2175f9b013 --- /dev/null +++ b/news/+vite-plugin-hook.feature.md @@ -0,0 +1 @@ +Plugins can add Vite plugins to the app's `vite.config.js` through the new `Plugin.get_vite_plugins()` hook, which returns `rx.plugins.VitePluginEntry` objects. A malformed entry stops the compile with an error naming the plugin. See [Adding Vite Plugins](https://reflex.dev/docs/api-reference/plugins/#adding-vite-plugins). diff --git a/packages/reflex-base/news/+vite-plugin-hook.feature.md b/packages/reflex-base/news/+vite-plugin-hook.feature.md new file mode 100644 index 00000000000..bc834222090 --- /dev/null +++ b/packages/reflex-base/news/+vite-plugin-hook.feature.md @@ -0,0 +1,11 @@ +A plugin can add Vite plugins to the generated `vite.config.js` by overriding `Plugin.get_vite_plugins()`, instead of rewriting the file in `pre_compile`. Each `VitePluginEntry` gives the import statements it needs and the expression placed in the `plugins` array, ahead of `reactRouter()`: + +```python +def get_vite_plugins(self, **context): + return [ + VitePluginEntry( + imports=['import inspect from "vite-plugin-inspect"'], + call="inspect({ build: true })", + ) + ] +``` diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 77f28862881..8223a3d4971 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -15,6 +15,7 @@ if TYPE_CHECKING: from reflex.compiler.utils import _ImportDict from reflex_base.components.component import Component + from reflex_base.plugins.base import VitePluginEntry _STATE_HOOK = re.compile( @@ -772,6 +773,7 @@ def vite_config_template( prod_react: bool = False, warmup_routes: bool = False, react_compiler: bool = False, + vite_plugins: Sequence[VitePluginEntry] = (), ): """Template for vite.config.js. @@ -788,6 +790,9 @@ 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. + vite_plugins: Vite plugins contributed by Reflex plugins, placed ahead + of ``reactRouter()`` in the order given. An import statement that + several entries share is written once. Returns: Rendered vite.config.js content as string. @@ -890,11 +895,22 @@ def vite_config_template( else "" ) react_compiler_plugin = " reactCompiler(),\n" if react_compiler else "" + vite_plugin_imports = "".join( + f"{statement};\n" + for statement in dict.fromkeys( + statement.strip().rstrip(";").rstrip() + for entry in vite_plugins + for statement in entry.imports + ) + ) + vite_plugin_calls = "".join( + f" {entry.call.strip()},\n" for entry in vite_plugins + ) return rf"""import {{ fileURLToPath, URL }} from "url"; import {{ reactRouter }} from "@react-router/dev/vite"; import {{ defineConfig }} from "vite"; import safariCacheBustPlugin from "./vite-plugin-safari-cachebust.js"; -{react_compiler_import} +{react_compiler_import}{vite_plugin_imports} // Ensure that bun always uses the react-dom/server.node functions. function alwaysUseReactDomServerNode() {{ return {{ @@ -961,7 +977,7 @@ def vite_config_template( base: "{base}", plugins: [ alwaysUseReactDomServerNode(), -{react_compiler_plugin} reactRouter(), +{react_compiler_plugin}{vite_plugin_calls} reactRouter(), patchReactRouterHmrRuntime(), safariCacheBustPlugin(), ].concat({"[fullReload()]" if force_full_reload else "[]"}), diff --git a/packages/reflex-base/src/reflex_base/plugins/__init__.py b/packages/reflex-base/src/reflex_base/plugins/__init__.py index c82a36d559f..9e0b2da1fda 100644 --- a/packages/reflex-base/src/reflex_base/plugins/__init__.py +++ b/packages/reflex-base/src/reflex_base/plugins/__init__.py @@ -23,6 +23,7 @@ PostCompileContext, PreCompileContext, RegisterRouteContext, + VitePluginEntry, get_plugin, ) from .compiler import ( @@ -55,6 +56,7 @@ "SitemapPlugin", "TailwindV3Plugin", "TailwindV4Plugin", + "VitePluginEntry", "_ScreenshotPlugin", "embed", "get_plugin", @@ -83,6 +85,7 @@ "PostCompileContext", "PreCompileContext", "RegisterRouteContext", + "VitePluginEntry", "get_plugin", ], "compiler": [ diff --git a/packages/reflex-base/src/reflex_base/plugins/base.py b/packages/reflex-base/src/reflex_base/plugins/base.py index 3f52afe48ee..ddec296d65b 100644 --- a/packages/reflex-base/src/reflex_base/plugins/base.py +++ b/packages/reflex-base/src/reflex_base/plugins/base.py @@ -1,5 +1,6 @@ """Base class for all plugins.""" +import dataclasses from collections.abc import Callable, Mapping, Sequence from enum import Enum from pathlib import Path @@ -118,6 +119,37 @@ class PostBuildContext(CommonContext): static_dir: Path +@dataclasses.dataclass(frozen=True, kw_only=True) +class VitePluginEntry: + """A Vite plugin that a Reflex plugin adds to the generated ``vite.config.js``. + + Both fields are JavaScript source, written to the file as given. A module + specifier resolves from ``.web``, where the file lives: an npm package by + name, a file the plugin wrote with ``get_static_assets`` by its relative + path (``"./my-plugin.js"``). + + Example: + >>> VitePluginEntry( + ... imports=[ + ... 'import myPlugin from "./my-plugin.js"', + ... 'import { Features } from "lightningcss"', + ... ], + ... call="myPlugin({ exclude: Features.LightDark })", + ... ) + + Attributes: + call: The expression placed in the ``plugins`` array, usually a call + such as ``"myPlugin({ fast: true })"``. It may evaluate to one + plugin or to an array of plugins, and may span several lines. + imports: The import statements ``call`` needs, one statement per + string, with or without the closing semicolon. A statement that + several entries share is written once. + """ + + call: str + imports: Sequence[str] = () + + class Plugin: """Base class for all plugins.""" @@ -178,6 +210,28 @@ def get_stylesheet_paths(self, **context: Unpack[CommonContext]) -> Sequence[str """ return [] + def get_vite_plugins( + self, **context: Unpack[CommonContext] + ) -> Sequence[VitePluginEntry]: + """Get the Vite plugins to add to the generated ``vite.config.js``. + + Entries are placed in the ``plugins`` array ahead of ``reactRouter()``, + in the order of the plugins in ``rxconfig.py`` and then in the order + each plugin returns them. The npm packages they import are build-time + only, so declare them in ``get_frontend_development_dependencies``. + + The hook runs each time the file is rendered, on ``reflex init`` and on + every compile, so it must return the same entries for the same + configuration. + + Args: + context: The context for the plugin. + + Returns: + The Vite plugins required by the plugin. + """ + return [] + def register_route(self, **context: Unpack[RegisterRouteContext]) -> None: """Contribute pages before the app's first compilation. diff --git a/packages/reflex-base/src/reflex_base/utils/exceptions.py b/packages/reflex-base/src/reflex_base/utils/exceptions.py index 9a9884b58c6..70b58654971 100644 --- a/packages/reflex-base/src/reflex_base/utils/exceptions.py +++ b/packages/reflex-base/src/reflex_base/utils/exceptions.py @@ -20,6 +20,10 @@ class InvalidPluginConfigError(ConfigError): """Raised when ``Config.plugins`` contains a plugin that could not be loaded.""" +class InvalidVitePluginError(ReflexError, ValueError): + """Raised when a plugin's ``get_vite_plugins`` returns a malformed entry.""" + + class InvalidStateManagerModeError(ReflexError, ValueError): """Raised when an invalid state manager mode is provided.""" diff --git a/reflex/plugins/__init__.py b/reflex/plugins/__init__.py index ba9c0775f54..6e0afeeda05 100644 --- a/reflex/plugins/__init__.py +++ b/reflex/plugins/__init__.py @@ -14,6 +14,7 @@ SitemapPlugin, TailwindV3Plugin, TailwindV4Plugin, + VitePluginEntry, _ScreenshotPlugin, embed, get_plugin, @@ -38,6 +39,7 @@ "SitemapPlugin", "TailwindV3Plugin", "TailwindV4Plugin", + "VitePluginEntry", "_ScreenshotPlugin", "embed", "get_plugin", diff --git a/reflex/utils/frontend_skeleton.py b/reflex/utils/frontend_skeleton.py index c32e1f0e893..226745d5da7 100644 --- a/reflex/utils/frontend_skeleton.py +++ b/reflex/utils/frontend_skeleton.py @@ -2,14 +2,18 @@ import json import logging +import re import uuid +from collections.abc import Sequence from pathlib import Path from typing import Literal from reflex_base import constants from reflex_base.config import Config, get_config from reflex_base.environment import environment +from reflex_base.plugins.base import Plugin, VitePluginEntry from reflex_base.plugins.embed import get_embed_plugin +from reflex_base.utils.exceptions import InvalidVitePluginError from reflex.compiler import templates from reflex.utils import net, path_ops @@ -629,6 +633,67 @@ def initialize_package_json(): _write_package_json(output_path, _compile_package_json()) +# A static import statement; ``import(...)`` and ``import.meta`` are expressions. +_VITE_IMPORT_STATEMENT = re.compile(r"""\s*import[\s"'{*]""") + + +def _vite_plugin_entry_problem(entry: object) -> str | None: + """Find what is wrong with an entry a plugin returned from ``get_vite_plugins``. + + Args: + entry: The entry to check. + + Returns: + The problem, or ``None`` when the entry can be rendered. + """ + if not isinstance(entry, VitePluginEntry): + return f"is a {type(entry).__name__}, not a VitePluginEntry" + call = entry.call + if not isinstance(call, str) or not (call := call.strip()): + return f"has call={entry.call!r}, which is not a JavaScript expression" + if call[-1] in ";,": + return ( + f"has call={entry.call!r}, which must be an expression without a " + f"trailing {call[-1]!r}" + ) + if isinstance(entry.imports, str): + return ( + f"has imports={entry.imports!r}, which must be a sequence of import " + "statements, not a single string" + ) + for statement in entry.imports: + if not isinstance(statement, str) or not _VITE_IMPORT_STATEMENT.match( + statement + ): + return f"has {statement!r} in imports, which is not an import statement" + return None + + +def _get_vite_plugins(plugins: Sequence[Plugin]) -> list[VitePluginEntry]: + """Collect the Vite plugins that the configured Reflex plugins contribute. + + Args: + plugins: The configured plugins, in ``rxconfig.py`` order. + + Returns: + The entries in plugin order, then in the order each plugin returned them. + + Raises: + InvalidVitePluginError: When a plugin returns a malformed entry. + """ + entries: list[VitePluginEntry] = [] + for plugin in plugins: + for index, entry in enumerate(plugin.get_vite_plugins()): + if problem := _vite_plugin_entry_problem(entry): + msg = ( + f"{type(plugin).__name__}.get_vite_plugins() returned an " + f"invalid entry: entry {index} {problem}." + ) + raise InvalidVitePluginError(msg) + entries.append(entry) + return entries + + def _compile_vite_config(config: Config): base = config.prepend_frontend_path("/") embed_plugin = get_embed_plugin() @@ -648,6 +713,7 @@ def _compile_vite_config(config: Config): sourcemap=environment.VITE_SOURCEMAP.get(), minify=environment.VITE_MINIFY.get(), allowed_hosts=config.vite_allowed_hosts, + vite_plugins=_get_vite_plugins(config.plugins), ) diff --git a/tests/integration/tests_playwright/test_icon.py b/tests/integration/tests_playwright/test_icon.py index 0863a3b46e7..99e87554b80 100644 --- a/tests/integration/tests_playwright/test_icon.py +++ b/tests/integration/tests_playwright/test_icon.py @@ -1,4 +1,8 @@ -"""Integration tests for the Icon component.""" +"""Integration tests for the Icon component. + +The app also carries a plugin that adds a Vite plugin, since it already builds +in both dev and prod. +""" from collections.abc import Generator @@ -8,13 +12,70 @@ from reflex.testing import AppHarness +VITE_CONSTANT = "defined by a vite plugin" + + +def Icons(vite_constant: str = VITE_CONSTANT): + """App rendering every icon, built with a plugin-contributed Vite plugin. + + Args: + vite_constant: The value the Vite plugin defines for the page to read. + """ + import json + from pathlib import Path -def Icons(): from reflex_components_lucide.icon import LUCIDE_ICON_LIST import reflex as rx + class DefineConstantPlugin(rx.plugins.Plugin): + """Adds a Vite plugin, shipped in the app, that defines a constant.""" + + def get_static_assets(self, **context): + """Write the Vite plugin's module into ``.web``. + + Args: + context: The context for the plugin. + + Returns: + The module's path and source. + """ + return [ + ( + Path("vite-plugin-define-constants.js"), + ( + "export default function defineConstants(constants) {\n" + ' return { name: "define-constants", config: () => ({ define: constants }) };\n' + "}\n" + ), + ) + ] + + def get_vite_plugins(self, **context): + """Add the Vite plugin to ``vite.config.js``. + + Args: + context: The context for the plugin. + + Returns: + The entry importing and calling the module. + """ + # Doubly encoded: once as a JS string literal in the config, and + # once more because `define` substitutes source text. + value = json.dumps(json.dumps(vite_constant)) + return [ + rx.plugins.VitePluginEntry( + imports=[ + 'import defineConstants from "./vite-plugin-define-constants.js"' + ], + call=f"defineConstants({{ __REFLEX_TEST_VITE_CONSTANT__: {value} }})", + ) + ] + app = rx.App() + # Set plugins after rx.App(), which reloads the config from rxconfig.py. + config = rx.config.get_config() + config.plugins = [*config.plugins, DefineConstantPlugin()] class State(rx.State): """State for the Icons app.""" @@ -33,6 +94,10 @@ def index(): rx.icon(State.dynamic_icon), id="dynamic_icon", ), + rx.el.div( + rx.Var("__REFLEX_TEST_VITE_CONSTANT__", _var_type=str), + id="vite_constant", + ), *[ rx.el.div(rx.icon(icon_name), id=icon_name) for icon_name in LUCIDE_ICON_LIST @@ -74,3 +139,16 @@ def test_icons(icons: AppHarness, page: Page) -> None: for icon_name in [*LUCIDE_ICON_LIST, "dynamic_icon"]: expect(page.locator(f'[id="{icon_name}"] svg')).to_have_count(1) + + +def test_vite_plugin_from_reflex_plugin(icons: AppHarness, page: Page) -> None: + """A constant defined by a plugin-contributed Vite plugin reaches the page. + + Args: + icons: harness for the icon app. + page: Playwright page. + """ + assert icons.frontend_url is not None + page.goto(icons.frontend_url) + + expect(page.locator("#vite_constant")).to_have_text(VITE_CONSTANT) diff --git a/tests/units/reflex_base/compiler/test_templates.py b/tests/units/reflex_base/compiler/test_templates.py index 196a30a218a..a0a4a0f3594 100644 --- a/tests/units/reflex_base/compiler/test_templates.py +++ b/tests/units/reflex_base/compiler/test_templates.py @@ -1,7 +1,12 @@ """Tests for reflex_base.compiler.templates.""" -from reflex_base.compiler.templates import _merge_state_hooks, _render_hooks +from reflex_base.compiler.templates import ( + _merge_state_hooks, + _render_hooks, + vite_config_template, +) from reflex_base.constants.state import FIELD_MARKER +from reflex_base.plugins import VitePluginEntry from reflex_base.utils.format import format_state_name from reflex_base.vars.base import Var, VarData from reflex_components_core.el.elements.typography import Div @@ -78,3 +83,109 @@ def test_render_hooks_declares_a_merged_state_hook_before_its_readers(): f"const parentRead = {state_var}.a{FIELD_MARKER}", f"const childValue = {state_var}.b{FIELD_MARKER}", ]) + + +_VITE_CONFIG_KWARGS = { + "base": "/", + "hmr": True, + "force_full_reload": False, + "experimental_hmr": False, + "sourcemap": False, +} +_VITE_IMPORTS_ANCHOR = ( + 'import safariCacheBustPlugin from "./vite-plugin-safari-cachebust.js";\n' +) +_VITE_PLUGINS_ANCHOR = " reactRouter(),\n" + + +def _vite_config_with( + imports: str, calls: str, *, after_imports: str = _VITE_IMPORTS_ANCHOR, **kwargs +) -> str: + """Build the expected vite.config.js from the one rendered without plugins. + + Args: + imports: The import lines the plugins add. + calls: The lines the plugins add to the ``plugins`` array. + after_imports: The line of the plugin-free file the imports follow. + kwargs: Template arguments on top of the defaults. + + Returns: + The plugin-free file with ``imports`` and ``calls`` inserted. + """ + baseline = vite_config_template(**_VITE_CONFIG_KWARGS, **kwargs) + head, imports_anchor, rest = baseline.partition(after_imports) + body, plugins_anchor, tail = rest.partition(_VITE_PLUGINS_ANCHOR) + assert imports_anchor + assert plugins_anchor + assert _VITE_PLUGINS_ANCHOR not in tail + return head + imports_anchor + imports + body + calls + plugins_anchor + tail + + +def test_vite_config_template_without_vite_plugins_is_unchanged(): + """No entries render the same file as omitting the argument.""" + assert vite_config_template( + **_VITE_CONFIG_KWARGS, vite_plugins=[] + ) == vite_config_template(**_VITE_CONFIG_KWARGS) + + +def test_vite_config_template_one_vite_plugin(): + """An entry's imports follow the built-in ones; its call precedes reactRouter().""" + rendered = vite_config_template( + **_VITE_CONFIG_KWARGS, + vite_plugins=[ + VitePluginEntry( + imports=[ + 'import stylex from "./reflex-ui/vite-plugin-stylex.js"', + 'import { Features } from "lightningcss";', + ], + call="""stylex({ + useCSSLayers: true, + lightningcssOptions: { minify: true, exclude: Features.LightDark }, +})""", + ) + ], + ) + assert rendered == _vite_config_with( + 'import stylex from "./reflex-ui/vite-plugin-stylex.js";\n' + 'import { Features } from "lightningcss";\n', + """ stylex({ + useCSSLayers: true, + lightningcssOptions: { minify: true, exclude: Features.LightDark }, +}), +""", + ) + + +def test_vite_config_template_two_vite_plugins(): + """Entries keep their order, after React Compiler; a shared import is written once.""" + rendered = vite_config_template( + **_VITE_CONFIG_KWARGS, + react_compiler=True, + vite_plugins=[ + VitePluginEntry( + imports=[ + 'import { Features } from "lightningcss"', + 'import second from "second-plugin"', + ], + call="second({ exclude: Features.LightDark })", + ), + VitePluginEntry( + imports=[ + 'import first from "first-plugin";', + ' import { Features } from "lightningcss" ;\n', + ], + call=" [first(), first.extra(Features.Nesting)]\n", + ), + VitePluginEntry(call='{ name: "inline", config: () => ({}) }'), + ], + ) + assert rendered == _vite_config_with( + 'import { Features } from "lightningcss";\n' + 'import second from "second-plugin";\n' + 'import first from "first-plugin";\n', + " second({ exclude: Features.LightDark }),\n" + " [first(), first.extra(Features.Nesting)],\n" + ' { name: "inline", config: () => ({}) },\n', + after_imports='import reactCompiler from "./vite-plugin-react-compiler.js";\n', + react_compiler=True, + ) diff --git a/tests/units/reflex_base/plugins/test_base.py b/tests/units/reflex_base/plugins/test_base.py index 7f4e9aa466b..34504968d6b 100644 --- a/tests/units/reflex_base/plugins/test_base.py +++ b/tests/units/reflex_base/plugins/test_base.py @@ -70,3 +70,8 @@ def test_register_route_default_is_noop(): ) is None ) + + +def test_get_vite_plugins_defaults_to_none(): + """A plugin contributes no Vite plugins unless it overrides the hook.""" + assert Plugin().get_vite_plugins() == [] diff --git a/tests/units/utils/test_frontend_skeleton.py b/tests/units/utils/test_frontend_skeleton.py index f3470a8ee70..452ae4c1aab 100644 --- a/tests/units/utils/test_frontend_skeleton.py +++ b/tests/units/utils/test_frontend_skeleton.py @@ -2,9 +2,14 @@ import json from pathlib import Path +from typing import Any import pytest from reflex_base import constants +from reflex_base.compiler.templates import vite_config_template +from reflex_base.config import Config +from reflex_base.plugins import Plugin, VitePluginEntry +from reflex_base.utils.exceptions import InvalidVitePluginError from reflex.utils import frontend_skeleton @@ -164,3 +169,164 @@ def test_update_package_json_overrides_matches_bun_format( assert frontend_skeleton.update_package_json_overrides() is True _assert_bun_format(package_json_path) + + +class _VitePlugins(Plugin): + """A plugin that contributes the Vite plugin entries it was created with.""" + + def __init__(self, *entries: Any): + """Store the entries to contribute. + + Args: + entries: What ``get_vite_plugins`` returns. + """ + self.entries = entries + + def get_vite_plugins(self, **context) -> Any: + """Contribute the stored entries. + + Args: + context: The context for the plugin. + + Returns: + The stored entries. + """ + return self.entries + + +class _OtherVitePlugins(_VitePlugins): + """A second plugin type, to tell plugins apart in an error.""" + + +_SHARED_IMPORT = 'import { Features } from "lightningcss"' +_FIRST = VitePluginEntry( + imports=['import first from "first-plugin"', _SHARED_IMPORT], + call="first(Features.Nesting)", +) +_SECOND = VitePluginEntry(imports=(_SHARED_IMPORT,), call="[second()]") +_THIRD = VitePluginEntry(call='{ name: "third" }') + + +def test_get_vite_plugins_follows_plugin_then_entry_order(): + """Entries come in ``rxconfig.py`` plugin order, then each plugin's own order.""" + plugins = [_VitePlugins(_SECOND, _THIRD), Plugin(), _OtherVitePlugins(_FIRST)] + + assert frontend_skeleton._get_vite_plugins(plugins) == [_SECOND, _THIRD, _FIRST] + assert frontend_skeleton._get_vite_plugins([Plugin()]) == [] + + +def test_compile_vite_config_renders_plugin_entries(): + """The compiled file is the template rendered with every plugin's entries.""" + config = Config( + app_name="test", plugins=[_VitePlugins(_FIRST), _OtherVitePlugins(_SECOND)] + ) + template_args = { + "base": "/", + "hmr": True, + "force_full_reload": False, + "experimental_hmr": False, + "sourcemap": False, + } + without_plugins = vite_config_template(**template_args) + rendered = frontend_skeleton._compile_vite_config(config) + + assert rendered == vite_config_template( + **template_args, vite_plugins=[_FIRST, _SECOND] + ) + assert rendered != without_plugins + assert ( + frontend_skeleton._compile_vite_config(Config(app_name="test")) + == without_plugins + ) + + +@pytest.mark.parametrize( + ("entry", "problem"), + [ + ( + ('import a from "a"', "a()"), + "is a tuple, not a VitePluginEntry", + ), + ( + VitePluginEntry(call=" "), + "has call=' ', which is not a JavaScript expression", + ), + ( + VitePluginEntry(call=None), # pyright: ignore[reportArgumentType] + "has call=None, which is not a JavaScript expression", + ), + ( + VitePluginEntry(call="a();\n"), + "has call='a();\\n', which must be an expression without a trailing ';'", + ), + ( + VitePluginEntry(call="a(),"), + "has call='a(),', which must be an expression without a trailing ','", + ), + ( + VitePluginEntry(imports='import a from "a"', call="a()"), + ( + "has imports='import a from \"a\"', which must be a sequence of " + "import statements, not a single string" + ), + ), + ( + VitePluginEntry(imports=['import a from "a"', "a"], call="a()"), + "has 'a' in imports, which is not an import statement", + ), + ( + VitePluginEntry(imports=['const a = await import("a")'], call="a()"), + ( + "has 'const a = await import(\"a\")' in imports, which is not an " + "import statement" + ), + ), + ( + VitePluginEntry(imports=['import("a")'], call="a()"), + "has 'import(\"a\")' in imports, which is not an import statement", + ), + ( + VitePluginEntry(imports=[b"import a"], call="a()"), # pyright: ignore[reportArgumentType] + "has b'import a' in imports, which is not an import statement", + ), + ], +) +def test_get_vite_plugins_rejects_malformed_entry(entry: Any, problem: str): + """A malformed entry fails the compile, naming the plugin and the entry. + + Args: + entry: The malformed entry. + problem: What the error says is wrong with it. + """ + plugins = [_VitePlugins(_FIRST), _OtherVitePlugins(_SECOND, entry)] + + with pytest.raises(InvalidVitePluginError) as err: + frontend_skeleton._get_vite_plugins(plugins) + + assert str(err.value) == ( + "_OtherVitePlugins.get_vite_plugins() returned an invalid entry: " + f"entry 1 {problem}." + ) + + +@pytest.mark.parametrize( + "statement", + [ + 'import a from "a"', + "import a, { b } from 'a';", + 'import{ a } from "a"', + 'import * as a from "a"', + 'import "a"', + "import'a'", + '\n import a from "a";\n', + ], +) +def test_get_vite_plugins_accepts_import_statement_forms(statement: str): + """Every static import form is accepted. + + Args: + statement: The import statement. + """ + entry = VitePluginEntry(imports=[statement], call="a()") + + assert frontend_skeleton._get_vite_plugins([_VitePlugins(entry)]) == [entry] From 091afa36e5fb31aa84a7decc41d6ad6237149e37 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 04:07:14 +0000 Subject: [PATCH 02/26] Scaffold reflex-components-ui and the rx.ui namespace An installable, empty package: `pip install 'reflex[ui]'` adds reflex-components-ui, which `rx.ui` resolves on first use. reflex does not depend on it, and without the extra `rx.ui` raises an error that names the extra. The package embeds its javascript, js/src, in the wheel, and reads it in place in a checkout. js/ carries its own tooling: ESLint with the StyleX rules and rules against components and barrel files in js/src, a type check from JSDoc, vitest, and a driver that writes generated files and fails CI when a committed one drifts. Each lint rule has a test that feeds it a file it must reject. Claude-Session: https://claude.ai/code/session_014AwvTNjM7Q5Te2EY2FTHrZ --- .github/workflows/dispatch_release.yml | 5 + .github/workflows/unit_tests.yml | 28 +- .gitignore | 3 +- AGENTS.md | 2 + docs/app/.github/workflows/unit_tests.yml | 3 +- examples/ruff.toml | 1 + news/+rx-ui-extra.feature.md | 1 + .../news/+pyi-ui-subpackage.misc.md | 1 + .../src/reflex_base/utils/pyi_generator.py | 1 + packages/reflex-components-ui/CHANGELOG.md | 1 + packages/reflex-components-ui/README.md | 65 + packages/reflex-components-ui/hatch_build.py | 41 + .../reflex-components-ui/js/eslint.config.js | 105 + .../reflex-components-ui/js/package-lock.json | 3363 +++++++++++++++++ packages/reflex-components-ui/js/package.json | 35 + .../js/scripts/generate.js | 67 + .../reflex-components-ui/js/src/README.md | 8 + .../js/tests/generate.test.js | 58 + .../js/tests/lint.test.js | 228 ++ .../reflex-components-ui/js/tsconfig.json | 24 + .../js/tsconfig.node.json | 10 + .../js/types/globals.d.ts | 4 + .../reflex-components-ui/js/vitest.config.js | 16 + .../news/+scaffold.feature.md | 1 + packages/reflex-components-ui/pyproject.toml | 47 + .../src/reflex_components_ui/__init__.py | 15 + .../src/reflex_components_ui/constants.py | 26 + .../src/reflex_components_ui/py.typed | 0 pyi_hashes.json | 2 +- pyproject.toml | 14 +- reflex/__init__.py | 61 +- scripts/make_pyi.py | 1 + .../utils/pyi_generator/test_unit.py | 22 + tests/units/reflex_components_ui/__init__.py | 0 .../reflex_components_ui/test_constants.py | 26 + .../reflex_components_ui/test_js_package.py | 43 + tests/units/test_build_config.py | 129 + tests/units/test_init.py | 77 + uv.lock | 28 +- 39 files changed, 4544 insertions(+), 18 deletions(-) create mode 100644 news/+rx-ui-extra.feature.md create mode 100644 packages/reflex-base/news/+pyi-ui-subpackage.misc.md create mode 100644 packages/reflex-components-ui/CHANGELOG.md create mode 100644 packages/reflex-components-ui/README.md create mode 100644 packages/reflex-components-ui/hatch_build.py create mode 100644 packages/reflex-components-ui/js/eslint.config.js create mode 100644 packages/reflex-components-ui/js/package-lock.json create mode 100644 packages/reflex-components-ui/js/package.json create mode 100644 packages/reflex-components-ui/js/scripts/generate.js create mode 100644 packages/reflex-components-ui/js/src/README.md create mode 100644 packages/reflex-components-ui/js/tests/generate.test.js create mode 100644 packages/reflex-components-ui/js/tests/lint.test.js create mode 100644 packages/reflex-components-ui/js/tsconfig.json create mode 100644 packages/reflex-components-ui/js/tsconfig.node.json create mode 100644 packages/reflex-components-ui/js/types/globals.d.ts create mode 100644 packages/reflex-components-ui/js/vitest.config.js create mode 100644 packages/reflex-components-ui/news/+scaffold.feature.md create mode 100644 packages/reflex-components-ui/pyproject.toml create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/__init__.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/constants.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/py.typed create mode 100644 tests/units/reflex_components_ui/__init__.py create mode 100644 tests/units/reflex_components_ui/test_constants.py create mode 100644 tests/units/reflex_components_ui/test_js_package.py create mode 100644 tests/units/test_init.py diff --git a/.github/workflows/dispatch_release.yml b/.github/workflows/dispatch_release.yml index e11adc81957..91107ea316f 100644 --- a/.github/workflows/dispatch_release.yml +++ b/.github/workflows/dispatch_release.yml @@ -139,6 +139,10 @@ on: description: "reflex-components-sonner" type: boolean default: false + reflex_components_ui: + description: "reflex-components-ui" + type: boolean + default: false reflex_docgen: description: "reflex-docgen" type: boolean @@ -207,6 +211,7 @@ jobs: ${{ inputs.reflex_components_react_player && 'reflex-components-react-player' || '' }} ${{ inputs.reflex_components_recharts && 'reflex-components-recharts' || '' }} ${{ inputs.reflex_components_sonner && 'reflex-components-sonner' || '' }} + ${{ inputs.reflex_components_ui && 'reflex-components-ui' || '' }} ${{ inputs.reflex_docgen && 'reflex-docgen' || '' }} ${{ inputs.reflex_hosting_cli && 'reflex-hosting-cli' || '' }} ${{ inputs.reflex_otel && 'reflex-otel' || '' }} diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 27e27303b6a..3c6f49d4d8f 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -191,6 +191,32 @@ jobs: if-no-files-found: error retention-days: 7 + ui-js-checks: + # Checks the javascript reflex-components-ui embeds: its lint rules (no + # components, no barrels, StyleX), the type check, the generated files and + # the tests. + needs: changes + if: needs.changes.outputs.run == 'true' + timeout-minutes: 10 + runs-on: ubuntu-latest + defaults: + run: + working-directory: packages/reflex-components-ui/js + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: 22 + cache: npm + cache-dependency-path: packages/reflex-components-ui/js/package-lock.json + - run: npm ci + - run: npm run lint + - run: npm run typecheck + - run: npm run generate:check + - run: npm test + unit-tests-macos: timeout-minutes: 30 if: github.event_name == 'push' && github.ref == 'refs/heads/main' @@ -224,7 +250,7 @@ jobs: # jobs above directly does not survive: check names follow the matrix and the # display names, and a job that a filter skips must not block the merge. unit-tests-gate: - needs: [changes, unit-tests, js-unit-tests, unit-tests-macos] + needs: [changes, unit-tests, js-unit-tests, ui-js-checks, unit-tests-macos] if: always() runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index 85354828f2b..2a8220b8fd5 100644 --- a/.gitignore +++ b/.gitignore @@ -32,8 +32,9 @@ reflex.db .env.* node_modules package-lock.json -# ...except the frontend package, which CI installs with `npm ci`. +# ...except the javascript packages, which CI installs with `npm ci`. !packages/reflex-frontend/package-lock.json +!packages/reflex-components-ui/js/package-lock.json *.pyi .pre-commit-config.yaml .claude/.worktrees diff --git a/AGENTS.md b/AGENTS.md index 9bc22def8d8..3c410c20f89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,8 @@ uv run reflex-release sync # regenerate th uv run python scripts/make_pyi.py # regenerate .pyi stubs uv run pre-commit run --all-files # all pre-commit hooks npm --prefix packages/reflex-frontend ci && npm --prefix packages/reflex-frontend run check # frontend package: lint, type-check (JSDoc) and unit tests +npm --prefix packages/reflex-components-ui/js ci && npm --prefix packages/reflex-components-ui/js run check # rx.ui javascript: lint, type-check (JSDoc), generated files and unit tests +npm --prefix packages/reflex-components-ui/js ci && npm --prefix packages/reflex-components-ui/js run check # rx.ui javascript: lint, type-check (JSDoc), generated files and unit tests ``` ## Layout diff --git a/docs/app/.github/workflows/unit_tests.yml b/docs/app/.github/workflows/unit_tests.yml index 191ab754e4b..be62b49d41d 100644 --- a/docs/app/.github/workflows/unit_tests.yml +++ b/docs/app/.github/workflows/unit_tests.yml @@ -64,7 +64,8 @@ jobs: --upgrade-package reflex-components-radix \ --upgrade-package reflex-components-react-player \ --upgrade-package reflex-components-recharts \ - --upgrade-package reflex-components-sonner + --upgrade-package reflex-components-sonner \ + --upgrade-package reflex-components-ui - name: Install custom reflex version (if specified) if: github.event.inputs.reflex_dep diff --git a/examples/ruff.toml b/examples/ruff.toml index 41393b91a35..338c7ea5a8c 100644 --- a/examples/ruff.toml +++ b/examples/ruff.toml @@ -31,6 +31,7 @@ reflex_components_radix.msg = "Examples import Reflex only as `import reflex as reflex_components_react_player.msg = "Examples import Reflex only as `import reflex as rx`." reflex_components_recharts.msg = "Examples import Reflex only as `import reflex as rx`." reflex_components_sonner.msg = "Examples import Reflex only as `import reflex as rx`." +reflex_components_ui.msg = "Examples import Reflex only as `import reflex as rx`." reflex_docgen.msg = "Examples import Reflex only as `import reflex as rx`." reflex_otel.msg = "Examples import Reflex only as `import reflex as rx`." reflex_release.msg = "Examples import Reflex only as `import reflex as rx`." diff --git a/news/+rx-ui-extra.feature.md b/news/+rx-ui-extra.feature.md new file mode 100644 index 00000000000..8a35dab38ea --- /dev/null +++ b/news/+rx-ui-extra.feature.md @@ -0,0 +1 @@ +Add the `ui` extra. `pip install 'reflex[ui]'` installs `reflex-components-ui`, a pre-release package of components that compile to plain HTML and static CSS, and exposes it as `rx.ui`. Without the extra, `rx.ui` raises an error that says what to install. The package has no components yet. diff --git a/packages/reflex-base/news/+pyi-ui-subpackage.misc.md b/packages/reflex-base/news/+pyi-ui-subpackage.misc.md new file mode 100644 index 00000000000..b682e3ad12f --- /dev/null +++ b/packages/reflex-base/news/+pyi-ui-subpackage.misc.md @@ -0,0 +1 @@ +The stub generator resolves the `ui` component subpackage to `reflex-components-ui`. diff --git a/packages/reflex-base/src/reflex_base/utils/pyi_generator.py b/packages/reflex-base/src/reflex_base/utils/pyi_generator.py index 06280c42e84..0c761cbae05 100644 --- a/packages/reflex-base/src/reflex_base/utils/pyi_generator.py +++ b/packages/reflex-base/src/reflex_base/utils/pyi_generator.py @@ -1500,6 +1500,7 @@ def _write_pyi_file(module_path: Path, source: str) -> None: "react_router": "reflex_components_core.react_router", "recharts": "reflex_components_recharts", "sonner": "reflex_components_sonner", + "ui": "reflex_components_ui", } diff --git a/packages/reflex-components-ui/CHANGELOG.md b/packages/reflex-components-ui/CHANGELOG.md new file mode 100644 index 00000000000..8cf66aa33c9 --- /dev/null +++ b/packages/reflex-components-ui/CHANGELOG.md @@ -0,0 +1 @@ + diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md new file mode 100644 index 00000000000..6c8e0cb9850 --- /dev/null +++ b/packages/reflex-components-ui/README.md @@ -0,0 +1,65 @@ +# reflex-components-ui + +Reflex components that compile to plain HTML elements with static class names. +The styles are compiled by [StyleX](https://stylexjs.com) in the app's own Vite +build, and behaviour comes from the browser and a few small hooks, so no +component library ships to the browser. + +The package is a pre-release and has no components yet. It is an optional extra +of Reflex, exposed as `rx.ui`: + +``` +pip install 'reflex[ui]' +``` + +## Layout + +``` +src/reflex_components_ui/ the python package: the rx.ui namespace +js/ the javascript package, with its own tooling + src/ what ships: copied into an app at .web/reflex-ui/ + tests/ vitest + scripts/generate.js writes and checks the generated files +hatch_build.py embeds js/src in the wheel +``` + +`js/` is not published to npm. A wheel embeds `js/src` as +`reflex_components_ui/js/src`; in a checkout +`reflex_components_ui.constants.JS_SRC` resolves to `js/src` directly, so an +edit needs no rebuild. A change under `js/src` is a change to this package: its +news fragment goes in `news/`. + +## Working on it + +From the repository root: + +``` +uv run pytest tests/units/reflex_components_ui tests/units/test_init.py tests/units/test_build_config.py # python tests +uv run python scripts/make_pyi.py # regenerate the .pyi stubs +npm --prefix packages/reflex-components-ui/js ci # install the javascript tooling +npm --prefix packages/reflex-components-ui/js run check # lint, type-check, generated files, tests: what CI runs +npm --prefix packages/reflex-components-ui/js run generate # rewrite the generated files +``` + +`run check` is `run lint` (ESLint), `run typecheck` (`tsc` over the JSDoc, +nothing emitted), `run generate:check` and `test` (vitest), which also run on +their own. + +## Rules the tooling enforces + +- **No React components in `js/src`.** Markup comes from the Python wrappers. + JSX fails the lint everywhere except `js/tests/behaviors/`, and so do the + imports that build a component without it. +- **No barrel files in `js/src`.** A re-export makes the CSS of everything it + names part of whatever imports one name from it. +- **StyleX's lint rules** apply to `js/src`, and its packages are pinned to one + exact version: StyleX is 0.x and has broken its output in a patch release. + `tests/units/reflex_components_ui/test_js_package.py` fails when a pin moves + alone. +- **Generated files are committed.** Each has an entry in `GENERATED` in + `js/scripts/generate.js`; CI fails when a committed file is not what its + generator produces. +- A lint rule in `js/src` cannot be switched off with a comment. + +`js/tests/lint.test.js` lints a file that breaks each rule, so a rule that stops +matching fails a test. diff --git a/packages/reflex-components-ui/hatch_build.py b/packages/reflex-components-ui/hatch_build.py new file mode 100644 index 00000000000..3bf940e7c3c --- /dev/null +++ b/packages/reflex-components-ui/hatch_build.py @@ -0,0 +1,41 @@ +"""Build hook that embeds the javascript package in reflex-components-ui.""" + +from pathlib import Path +from typing import Any + +from hatchling.builders.hooks.plugin.interface import BuildHookInterface + +# Where the javascript lands inside the reflex_components_ui package. +JS_SRC = "reflex_components_ui/js/src" + + +class JavascriptBuildHook(BuildHookInterface): + """Embed ``js/src`` in the wheel. + + The javascript package lives beside the python source rather than inside + it. An sdist carries ``js/src`` where the repository has it, so a wheel + built from the sdist finds it the same way a wheel built from a checkout + does. + """ + + PLUGIN_NAME = "custom" + + def initialize(self, version: str, build_data: dict[str, Any]) -> None: + """Add the javascript source to a wheel. + + Args: + version: The kind of build: ``standard`` or ``editable``. + build_data: Additional build data. + + Raises: + FileNotFoundError: If there is no javascript to embed. + """ + # An sdist includes js/src as it is. An editable install resolves + # reflex_components_ui to the checkout, which reads js/src in place. + if self.target_name != "wheel" or version == "editable": + return + js_src = Path(self.root) / "js" / "src" + if not js_src.is_dir(): + msg = f"No javascript to embed: {js_src} does not exist." + raise FileNotFoundError(msg) + build_data["force_include"][str(js_src)] = JS_SRC diff --git a/packages/reflex-components-ui/js/eslint.config.js b/packages/reflex-components-ui/js/eslint.config.js new file mode 100644 index 00000000000..e466cae699a --- /dev/null +++ b/packages/reflex-components-ui/js/eslint.config.js @@ -0,0 +1,105 @@ +import js from "@eslint/js"; +import stylex from "@stylexjs/eslint-plugin"; +import globals from "globals"; + +// `src` holds no React components: the markup of every component comes from +// its Python wrapper. JSX is allowed only where the tests of the behaviour +// hooks mount one. +const NO_JSX = [ + { + selector: ":matches(JSXElement, JSXFragment)", + message: + "No JSX here: the markup of an rx.ui component comes from its Python wrapper. Only tests/behaviors may render JSX.", + }, +]; + +// A barrel makes every stylesheet behind it part of whatever imports one name +// from it, so a module is imported from the file that defines it. +const NO_BARREL = [ + { + selector: ":matches(ExportAllDeclaration, ExportNamedDeclaration[source])", + message: + "No barrel files: a re-export leaks the CSS of everything it names. Import from the module that defines the name.", + }, +]; + +// What builds a component without JSX. Hooks are imported by name, so a +// default or namespace import of react has no use here either. +const NO_COMPONENTS = { + paths: [ + { + name: "react", + importNames: [ + "default", + "createElement", + "cloneElement", + "forwardRef", + "memo", + "lazy", + "Component", + "PureComponent", + ], + message: + "No React components in src: import the hooks you need by name.", + }, + ...[ + "react-dom", + "react-dom/client", + "react/jsx-runtime", + "react/jsx-dev-runtime", + ].map((name) => ({ + name, + message: "No React components in src: nothing here renders.", + })), + ], +}; + +export default [ + js.configs.recommended, + { + files: ["**/*.js", "**/*.jsx"], + languageOptions: { + // Parsed everywhere, so that JSX is reported by the rule below rather + // than as a syntax error. + parserOptions: { ecmaFeatures: { jsx: true } }, + globals: globals.node, + }, + linterOptions: { reportUnusedDisableDirectives: "error" }, + rules: { + "no-restricted-syntax": ["error", ...NO_JSX], + }, + }, + { + // What ships: copied verbatim into an app, where StyleX compiles it. + files: ["src/**/*.js", "src/**/*.jsx"], + plugins: { "@stylexjs": stylex }, + languageOptions: { globals: globals.browser }, + // A rule here cannot be switched off from inside the file it rejects. + linterOptions: { noInlineConfig: true }, + rules: { + "no-restricted-syntax": ["error", ...NO_JSX, ...NO_BARREL], + "no-restricted-imports": ["error", NO_COMPONENTS], + // Left off: `sort-keys` is a style preference, `no-conflicting-props` + // only reads JSX, which is not allowed here, and + // `no-lookahead-selectors` is a browser support policy on `:has()`. + "@stylexjs/enforce-extension": "error", + "@stylexjs/no-legacy-contextual-styles": "error", + "@stylexjs/no-nonstandard-styles": "error", + "@stylexjs/no-unused": "error", + "@stylexjs/valid-shorthands": "error", + "@stylexjs/valid-styles": "error", + }, + }, + { + // The build files at the top of `src` run in node. + files: ["src/*.js"], + languageOptions: { globals: globals.node }, + }, + { + files: ["tests/behaviors/**"], + languageOptions: { globals: globals.browser }, + rules: { + "no-restricted-syntax": "off", + }, + }, +]; diff --git a/packages/reflex-components-ui/js/package-lock.json b/packages/reflex-components-ui/js/package-lock.json new file mode 100644 index 00000000000..f30453c34fe --- /dev/null +++ b/packages/reflex-components-ui/js/package-lock.json @@ -0,0 +1,3363 @@ +{ + "name": "reflex-components-ui-js", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "reflex-components-ui-js", + "version": "0.0.0", + "license": "Apache-2.0", + "dependencies": { + "@stylexjs/stylex": "0.19.2", + "@stylexjs/unplugin": "0.19.2" + }, + "devDependencies": { + "@eslint/js": "10.0.1", + "@stylexjs/eslint-plugin": "0.19.2", + "@types/node": "22.20.5", + "eslint": "10.15.0", + "globals": "17.14.0", + "jsdom": "^26.1.0", + "typescript": "5.9.3", + "vitest": "^5.1.0" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.15.tgz", + "integrity": "sha512-gNWJUX0FlevflramOkaInywOMhU1lkln38gAC7TFZv2tsWbLYbN/2WZFGcq8zbX0Z55e4vGa27IB/NaeZoauWQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.15", + "@babel/types": "^7.29.15", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.15.tgz", + "integrity": "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.15.tgz", + "integrity": "sha512-l+ezV2czw3t2d2ELq+3CwPL4WLKK5O8IywBXb9/gpmbCOVZFmRYJPmHVqSCv2k+8iKbE30Zf54siOoIZ52XOxA==", + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.15.tgz", + "integrity": "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.15" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-flow": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.29.7.tgz", + "integrity": "sha512-ajMX6QPcyomotqwpzhkYGxcK2i/us0rs1Qo9QvUpa+Fca0FTmqrzKrctoIYLMxcOhGZldGT/BAVkRGTWBiR8gQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", + "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.15.tgz", + "integrity": "sha512-ZfawBo2i8vvt+BTt37dWDKBPjUfm/H+bw+ltwsCRhW7gPtyNVwUXuNo54eO2Xo+P4VXpalPFfFISbBTRKC8SOQ==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.15", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.15", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.15.tgz", + "integrity": "sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.15", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@cacheable/memory": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", + "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/utils": "^2.5.0", + "@keyv/bigmap": "^1.3.1", + "hookified": "^1.15.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@cacheable/utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", + "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.5.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@dual-bundle/import-meta-resolve": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@dual-bundle/import-meta-resolve/-/import-meta-resolve-4.2.1.tgz", + "integrity": "sha512-id+7YRUgoUX6CgV0DtuhirQWodeeA7Lf4i2x71JS/vtA5pRb/hIGWlw+G6MeXvsM+MXrz0VAydTGElX1rAfgPg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/JounQin" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.3.tgz", + "integrity": "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.23.6", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz", + "integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^3.0.5", + "debug": "^4.3.1", + "minimatch": "^11.0.5" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", + "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/core": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/js": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "eslint": "^10.0.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/object-schema": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", + "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1", + "levn": "^0.4.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@keyv/bigmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.4.0", + "hookified": "^1.15.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.6.0" + } + }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@oxc-project/types": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz", + "integrity": "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.4.tgz", + "integrity": "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.4.tgz", + "integrity": "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.4.tgz", + "integrity": "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.4.tgz", + "integrity": "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.4.tgz", + "integrity": "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.4.tgz", + "integrity": "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.4.tgz", + "integrity": "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.4.tgz", + "integrity": "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.4.tgz", + "integrity": "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.4.tgz", + "integrity": "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.4.tgz", + "integrity": "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.4.tgz", + "integrity": "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.4.tgz", + "integrity": "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@oxc-project/types": "0.160.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.4.tgz", + "integrity": "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.4.tgz", + "integrity": "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@stylexjs/babel-plugin": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@stylexjs/babel-plugin/-/babel-plugin-0.19.2.tgz", + "integrity": "sha512-R6cB7Ym+IAvySNfmtRJ6CZ+83rjZ82Uw4wmG3YtwYY8vrnliUrYy9fOLvZ1nX407zeHNkCnE5AodEnjXXfOSYg==", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.26.8", + "@babel/helper-module-imports": "^7.25.9", + "@babel/traverse": "^7.26.8", + "@babel/types": "^7.26.8", + "@dual-bundle/import-meta-resolve": "^4.1.0", + "@stylexjs/shared": "0.19.2", + "@stylexjs/stylex": "0.19.2", + "postcss-value-parser": "^4.1.0" + } + }, + "node_modules/@stylexjs/eslint-plugin": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@stylexjs/eslint-plugin/-/eslint-plugin-0.19.2.tgz", + "integrity": "sha512-Oynwwe3grD/H1cHOZeUQgodjmhe2CAEhf4MqdWNO95nDw5kANP9Vso/AKifhOrl5za7wpItHCW9bGef5RTl1UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-tokenizer": "^3.0.3", + "@stylexjs/shared": "0.19.2", + "micromatch": "^4.0.5", + "postcss-value-parser": "^4.2.0" + } + }, + "node_modules/@stylexjs/shared": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@stylexjs/shared/-/shared-0.19.2.tgz", + "integrity": "sha512-xjTZ/6T/1FV103F2bspmXoDRDy1gM/ZKYEHpQlUC0h4R5q7PqUV6k+DJbrayRAMwALIdzTf7zSTqteRde0ZXWQ==", + "license": "MIT" + }, + "node_modules/@stylexjs/stylex": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@stylexjs/stylex/-/stylex-0.19.2.tgz", + "integrity": "sha512-l0fRhOBZ4rFiZ0GntYSlp4lYO5dPT11F3mLb7O4ShK6eE1WOjHtv9GHGQZuzHJbQkjcEaRjPSpBn6itI7yXc3Q==", + "license": "MIT", + "dependencies": { + "styleq": "0.2.1" + } + }, + "node_modules/@stylexjs/unplugin": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@stylexjs/unplugin/-/unplugin-0.19.2.tgz", + "integrity": "sha512-kyHrLCVyKNmycPl+WnjVGJmPgKGAYbtVPasuCe3UgQllennwj2himUKQncG98zt+66nDuGpy7Sx2xCYM03nr3Q==", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.26.8", + "@babel/plugin-syntax-flow": "^7.26.0", + "@babel/plugin-syntax-jsx": "^7.25.9", + "@babel/plugin-syntax-typescript": "^7.25.9", + "@stylexjs/babel-plugin": "0.19.2", + "browserslist": "^4.24.0", + "lightningcss": "^1.29.1" + }, + "peerDependencies": { + "unplugin": "^2.3.11" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/esrecurse": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", + "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.11.tgz", + "integrity": "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.2.tgz", + "integrity": "sha512-UGc97wUIy0Ji2+9GxzHEJiOhiwkaukgE7VYcUNnjpX3sWnwQ8XogmNXX4WyOukxYgKb8Nh2XFa7KId0ZjpmVhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.2", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.5" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.2.tgz", + "integrity": "sha512-PQl0/3+p9GaY71+MHywN6oyHfLhVDD5kcbm7oNRldA2F0ExMU3S8RQdnpteJ9gFAdK5P6KCgE6LqCpUgy57KzA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.40", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.40.tgz", + "integrity": "sha512-WJhaQ3kW5+5BpOduI64ewvykhCyK/IHHG5jCIzivmW2nkYPRowUjs0DbBXY4CAr1LLrN7QEzZGL9727aXH9sJA==", + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/brace-expansion": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.0.tgz", + "integrity": "sha512-aa11Dv491GKnYqxaul3aRJ0szew7yMJMfZPnqD44NjGrZXoj62l41OEDDpdpC4eE2P88vBFfLuSyRhpG91NUvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/cacheable": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", + "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/memory": "^2.2.0", + "@cacheable/utils": "^2.5.0", + "hookified": "^1.15.0", + "keyv": "^5.6.0", + "qified": "^0.10.1" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001828", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001828.tgz", + "integrity": "sha512-7MWeT+3DlrpuDybTWHl4Zb1Z80Z1fLLnOXuBjDXebzDVcqnEWUlV8JcbASg8B8BhcW8QT2UiR1KAtzYFIZHZYA==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.495", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.495.tgz", + "integrity": "sha512-dZcmtNbDI5oeT9uP9Z+D7h/H5C1mvBewDTLgZgo9WgyPmqOXSt2cmoCK99evPygUOn9lyXZ4w0Eb8APrkBjqBA==", + "license": "ISC" + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "10.15.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz", + "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "packages/*" + ], + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.2", + "@eslint/config-array": "^0.23.6", + "@eslint/config-helpers": "^0.7.0", + "@eslint/core": "^1.2.1", + "@eslint/plugin-kit": "^0.7.3", + "@humanfs/node": "^0.16.8", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^9.1.2", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "esquery": "^1.7.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "11.1.5 || >11.1.6 <12", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "minimatch": "^11.0.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", + "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@types/esrecurse": "^4.3.1", + "@types/estree": "^1.0.8", + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/file-entry-cache": { + "version": "11.1.5", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", + "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^6.1.23" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "6.1.23", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", + "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cacheable": "^2.5.0", + "flatted": "^3.4.2", + "hookified": "^1.15.0" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "17.14.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", + "integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/hashery": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", + "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^1.15.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/hookified": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", + "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/napi-windows-process-start-time": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/napi-windows-process-start-time/-/napi-windows-process-start-time-0.1.0.tgz", + "integrity": "sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw==", + "cpu": [ + "x64", + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=20" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.66", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.66.tgz", + "integrity": "sha512-uSMWN9/XtWzxaE0d9ZNHe00Hda6028AXH3WRjTsK71neiPCSeL5nGSD9MXTQX/6Qx0k7Op1AyyinmIUw9fBzrg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "license": "MIT" + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qified": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", + "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^2.1.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/qified/node_modules/hookified": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", + "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", + "dev": true, + "license": "MIT" + }, + "node_modules/rolldown": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz", + "integrity": "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@oxc-project/types": "=0.160.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.3.4", + "@rolldown/binding-android-arm64": "1.3.4", + "@rolldown/binding-darwin-arm64": "1.3.4", + "@rolldown/binding-darwin-x64": "1.3.4", + "@rolldown/binding-freebsd-x64": "1.3.4", + "@rolldown/binding-linux-arm-gnueabihf": "1.3.4", + "@rolldown/binding-linux-arm64-gnu": "1.3.4", + "@rolldown/binding-linux-arm64-musl": "1.3.4", + "@rolldown/binding-linux-ppc64-gnu": "1.3.4", + "@rolldown/binding-linux-s390x-gnu": "1.3.4", + "@rolldown/binding-linux-x64-gnu": "1.3.4", + "@rolldown/binding-linux-x64-musl": "1.3.4", + "@rolldown/binding-openharmony-arm64": "1.3.4", + "@rolldown/binding-wasm32-wasi": "1.3.4", + "@rolldown/binding-win32-arm64-msvc": "1.3.4", + "@rolldown/binding-win32-x64-msvc": "1.3.4" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/styleq": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/styleq/-/styleq-0.2.1.tgz", + "integrity": "sha512-L0TR0NQb+X4/ktDEKmjWyp27gla+LUYi/by5k5SjKXf6/pvZP7wbwEB5J+tqxdFVPgzbsuz+d4RTScO/QZquBw==", + "license": "MIT" + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz", + "integrity": "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.4.0.tgz", + "integrity": "sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unplugin": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-2.3.11.tgz", + "integrity": "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww==", + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "acorn": "^8.15.0", + "picomatch": "^4.0.3", + "webpack-virtual-modules": "^0.6.2" + }, + "engines": { + "node": ">=18.12.0" + } + }, + "node_modules/unplugin/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz", + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.4.0.tgz", + "integrity": "sha512-X2nUJg+9cutlz3hzqyO6p+WTwk9H257DjwAEf9EQYUFrQbDItmetadi9gYmb+l7VDy4r3VXLUnmLTwuPmzejDw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.33", + "rolldown": "~1.3.2", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3", + "napi-windows-process-start-time": "^0.1.0" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vitest": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.2.tgz", + "integrity": "sha512-VIa2wXV208WraXUbzH+dQUrGcFpPuaiRA8HlhXS8R6/sy9cynw6OMqGj8fmAlH1hot7huTCtWUE14+FdXU3eLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.2", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.5", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.3", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.2", + "@vitest/browser-preview": "5.1.2", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.2", + "@vitest/coverage-v8": "5.1.2", + "@vitest/ui": "5.1.2", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/webpack-virtual-modules": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", + "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", + "license": "MIT", + "peer": true + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/packages/reflex-components-ui/js/package.json b/packages/reflex-components-ui/js/package.json new file mode 100644 index 00000000000..5889fae0fbe --- /dev/null +++ b/packages/reflex-components-ui/js/package.json @@ -0,0 +1,35 @@ +{ + "name": "reflex-components-ui-js", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "The javascript the rx.ui components are compiled against: design tokens, themes and behaviour hooks.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/reflex-dev/reflex.git", + "directory": "packages/reflex-components-ui/js" + }, + "scripts": { + "lint": "eslint --max-warnings 0", + "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.node.json", + "test": "vitest run", + "generate": "node scripts/generate.js", + "generate:check": "node scripts/generate.js --check", + "check": "npm run lint && npm run typecheck && npm run generate:check && npm test" + }, + "dependencies": { + "@stylexjs/stylex": "0.19.2", + "@stylexjs/unplugin": "0.19.2" + }, + "devDependencies": { + "@eslint/js": "10.0.1", + "@stylexjs/eslint-plugin": "0.19.2", + "@types/node": "22.20.5", + "eslint": "10.15.0", + "globals": "17.14.0", + "jsdom": "^26.1.0", + "typescript": "5.9.3", + "vitest": "^5.1.0" + } +} diff --git a/packages/reflex-components-ui/js/scripts/generate.js b/packages/reflex-components-ui/js/scripts/generate.js new file mode 100644 index 00000000000..ce09527c2e4 --- /dev/null +++ b/packages/reflex-components-ui/js/scripts/generate.js @@ -0,0 +1,67 @@ +// Writes the generated files of the package, or with `--check` fails when a +// committed one is not what its generator produces. + +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +/** + * A committed file that a generator owns. + * + * @typedef {object} Generated + * @property {string} path Where the file goes, relative to the python package's + * root (`packages/reflex-components-ui`). + * @property {() => string | Promise} render Produces the whole file. + */ + +/** + * Every generated file. A generator is added here, so that `npm run generate` + * writes its output and the check in CI covers it. + * + * @type {Generated[]} + */ +export const GENERATED = []; + +const PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url)); + +/** + * Write the generated files, or find the ones that have drifted. + * + * @param {Generated[]} generated The files to produce. + * @param {string} root The directory their paths are relative to. + * @param {boolean} check Compare with what is on disk instead of writing. + * @returns {Promise} The paths written, or with `check` the paths + * whose file is missing or differs from what its generator produces. + */ +export async function generate(generated, root, check) { + const paths = []; + for (const { path, render } of generated) { + const target = resolve(root, path); + const content = await render(); + if (check) { + const current = await readFile(target, "utf8").catch(() => null); + if (current !== content) paths.push(path); + } else { + await mkdir(dirname(target), { recursive: true }); + await writeFile(target, content); + paths.push(path); + } + } + return paths; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const check = process.argv.includes("--check"); + const paths = await generate(GENERATED, PACKAGE_ROOT, check); + if (check && paths.length > 0) { + console.error( + `Generated files are out of date:\n${paths.map((path) => ` ${path}`).join("\n")}\nRun \`npm run generate\` and commit the result.`, + ); + process.exit(1); + } + console.log( + check + ? `${GENERATED.length} generated files are up to date.` + : `Wrote ${paths.length} generated files.`, + ); +} diff --git a/packages/reflex-components-ui/js/src/README.md b/packages/reflex-components-ui/js/src/README.md new file mode 100644 index 00000000000..20d2f7771ea --- /dev/null +++ b/packages/reflex-components-ui/js/src/README.md @@ -0,0 +1,8 @@ +# reflex-ui + +The javascript `rx.ui` components are compiled against. Reflex copies this +directory into an app's `.web/reflex-ui/` from the `reflex-components-ui` +package, so an edit made here in an app is overwritten. + +The source, its tests and its rules live in +[`packages/reflex-components-ui/js`](https://github.com/reflex-dev/reflex/tree/main/packages/reflex-components-ui/js). diff --git a/packages/reflex-components-ui/js/tests/generate.test.js b/packages/reflex-components-ui/js/tests/generate.test.js new file mode 100644 index 00000000000..84ed5b4172f --- /dev/null +++ b/packages/reflex-components-ui/js/tests/generate.test.js @@ -0,0 +1,58 @@ +// @vitest-environment node +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, beforeEach, expect, test } from "vitest"; + +import { generate } from "../scripts/generate.js"; + +const GENERATED = [ + { path: "tokens/space.stylex.js", render: () => "export const space = 1;\n" }, + { path: "style/_css_props.py", render: async () => "PROPS = ()\n" }, +]; + +/** @type {string} */ +let root; + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "reflex-ui-generate-")); +}); + +afterEach(async () => { + await rm(root, { recursive: true }); +}); + +test("writes every file, creating its directory", async () => { + expect(await generate(GENERATED, root, false)).toEqual([ + "tokens/space.stylex.js", + "style/_css_props.py", + ]); + expect(await readFile(join(root, "tokens/space.stylex.js"), "utf8")).toBe( + "export const space = 1;\n", + ); + expect(await readFile(join(root, "style/_css_props.py"), "utf8")).toBe( + "PROPS = ()\n", + ); +}); + +test("check reports nothing for files that match their generator", async () => { + await generate(GENERATED, root, false); + expect(await generate(GENERATED, root, true)).toEqual([]); +}); + +test("check reports an edited file and a missing one, and writes neither", async () => { + await generate(GENERATED, root, false); + await writeFile(join(root, "tokens/space.stylex.js"), "edited by hand\n"); + await rm(join(root, "style/_css_props.py")); + expect(await generate(GENERATED, root, true)).toEqual([ + "tokens/space.stylex.js", + "style/_css_props.py", + ]); + expect(await readFile(join(root, "tokens/space.stylex.js"), "utf8")).toBe( + "edited by hand\n", + ); + await expect(readFile(join(root, "style/_css_props.py"))).rejects.toThrow( + "ENOENT", + ); +}); diff --git a/packages/reflex-components-ui/js/tests/lint.test.js b/packages/reflex-components-ui/js/tests/lint.test.js new file mode 100644 index 00000000000..ac3bcb9cd1e --- /dev/null +++ b/packages/reflex-components-ui/js/tests/lint.test.js @@ -0,0 +1,228 @@ +// @vitest-environment node +// Each rule the package's lint enforces on `src`, shown rejecting a file that +// breaks it: a rule that is only configured can stop matching unnoticed. +import { fileURLToPath } from "node:url"; + +import { ESLint } from "eslint"; +import { expect, test } from "vitest"; + +const eslint = new ESLint({ + cwd: fileURLToPath(new URL("..", import.meta.url)), +}); + +const NO_JSX = + "No JSX here: the markup of an rx.ui component comes from its Python wrapper. Only tests/behaviors may render JSX."; +const NO_BARREL = + "No barrel files: a re-export leaks the CSS of everything it names. Import from the module that defines the name."; +const VARS_EXTENSION = + "Files that export variables from `stylex.defineVars()`, `stylex.defineConsts()`, or `stylex.defineMarker()` must end with a `.stylex.js` extension."; +const NOT_STANDARD = + 'The value "start" is not a standard CSS value for "float". Did you mean "inline-start"?'; + +/** + * Lint source text as if it were the file at a path in the package. + * + * @param {string} filePath The path, relative to the package. + * @param {string} code The content of the file. + * @returns {Promise<{rule: string | null, line: number, message: string}[]>} + * Every problem reported, warnings included. + */ +async function lint(filePath, code) { + const [result] = await eslint.lintText(code, { filePath }); + return result.messages.map(({ ruleId, line, message }) => ({ + rule: ruleId, + line, + message, + })); +} + +test("a behaviour hook that follows the rules is clean", async () => { + const code = `import { useState } from "react"; + +export function useToggle() { + return useState(false); +} +`; + expect(await lint("src/behaviors/useToggle.js", code)).toEqual([]); +}); + +test.each([ + ["src/behaviors/Button.js", "an element", "', + ); + run(); + click(document.getElementById("icon"), { clientX: 7, ctrlKey: true }); + expect(clicks.length).toBe(1); + + await hydrate(); + expect( + clicks.map(({ target, clientX, ctrlKey, bubbles }) => ({ + target: target.id, + clientX, + ctrlKey, + bubbles, + })), + ).toEqual([ + { target: "icon", clientX: 7, ctrlKey: true, bubbles: true }, + { target: "icon", clientX: 7, ctrlKey: true, bubbles: true }, + ]); + expect(clicks[1]).not.toBe(clicks[0]); + expect(window.__reflex_early).toBe(undefined); + + // The page handles its own clicks from here on. + click(target); + await hydrate(); + expect(clicks.length).toBe(3); + }); + + test("only the last one is dispatched again", async () => { + const first = addToPage(''); + run(); + click(first.target); + const other = document.body.appendChild(document.createElement("button")); + const otherClicks = []; + other.addEventListener("click", (event) => otherClicks.push(event)); + click(other); + click(other); + + await hydrate(); + expect(first.clicks.length).toBe(1); + expect(otherClicks.length).toBe(3); + }); + + test.each([ + 'link', + 'link', + '', + '', + '', + '', + '
more
', + '
', + ])("is left alone where the browser acted on it: %s", async (html) => { + const { target, clicks } = addToPage(html); + target.addEventListener("click", (event) => event.preventDefault()); + run(); + click(target); + await hydrate(); + expect(clicks.length).toBe(1); + }); + + test("is dropped when its target has left the page", async () => { + const { target, clicks } = addToPage(''); + run(); + click(target); + target.remove(); + await hydrate(); + expect(clicks.length).toBe(1); + }); + + test("a click after the scripts loaded is not recorded", async () => { + const { target, clicks } = addToPage(''); + run(); + const { record } = window.__reflex_early; + await hydrate(); + click(target); + expect(clicks.length).toBe(1); + record(clicks[0]); + await hydrate(); + expect(clicks.length).toBe(1); + }); + }); +}); diff --git a/packages/reflex-frontend/types/globals.d.ts b/packages/reflex-frontend/types/globals.d.ts index 01de4202d2d..da27fb87598 100644 --- a/packages/reflex-frontend/types/globals.d.ts +++ b/packages/reflex-frontend/types/globals.d.ts @@ -41,6 +41,11 @@ interface Window { /** Loads bundled libraries a dynamic component names, before it is evaluated. */ __reflex_load?: (libraries: string[]) => Promise; __reflex_otel?: ReflexOtelHooks; + /** + * The last click on a prerendered page before its scripts loaded, and the + * listener recording it. Set by the inline script of `utils/scripts.js`. + */ + __reflex_early?: { click: MouseEvent | null; record: (event: Event) => void }; /** Dynamic components are evaluated outside any module and expect a global React. */ React?: any; } diff --git a/pyi_hashes.json b/pyi_hashes.json index fec0b8f2474..f24a28ee764 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -5,7 +5,7 @@ "packages/reflex-components-core/src/reflex_components_core/base/__init__.pyi": "d46e910c03263a8d3456d473de9e76c7", "packages/reflex-components-core/src/reflex_components_core/base/app_wrap.pyi": "4a701f7eaf84ec041c8fd5c8af4e48ff", "packages/reflex-components-core/src/reflex_components_core/base/body.pyi": "8550ac0cdb7f57b35dc639b605294b98", - "packages/reflex-components-core/src/reflex_components_core/base/document.pyi": "92be3177fff806cd44281cb912b21463", + "packages/reflex-components-core/src/reflex_components_core/base/document.pyi": "04d20bcfba980db936b2e88974e0b02c", "packages/reflex-components-core/src/reflex_components_core/base/error_boundary.pyi": "2bec3beeafea96787d10838d73e47bdc", "packages/reflex-components-core/src/reflex_components_core/base/fragment.pyi": "04de5816bc98f33bbf14370af7f787b3", "packages/reflex-components-core/src/reflex_components_core/base/link.pyi": "d39ded31424a9af8532b9d4eb0ce8abf", diff --git a/tests/integration/tests_playwright/test_scripts_after_first_paint.py b/tests/integration/tests_playwright/test_scripts_after_first_paint.py new file mode 100644 index 00000000000..b31796b7b72 --- /dev/null +++ b/tests/integration/tests_playwright/test_scripts_after_first_paint.py @@ -0,0 +1,177 @@ +"""A prerendered page starts its scripts after its first paint, and still hydrates.""" + +import json +import re +from collections.abc import Generator + +import pytest +from playwright.sync_api import Page, expect + +import reflex.constants as constants +import reflex.utils.prerequisites as prerequisites +from reflex.testing import AppHarness, AppHarnessProd +from reflex.utils.misc import preload_color_theme + +HYDRATED = """() => Object.keys(document.getElementById("increment")).some( + (key) => key.startsWith("__reactProps$") +)""" + +# Keeps the page from learning that it painted, and drops the timeout that +# covers for that (FIRST_PAINT_TIMEOUT_MS in utils/scripts.js), while the +# document is parsed: only an input is left to start the scripts. +NEVER_PAINTED = """ +PerformanceObserver.prototype.observe = function () {}; +const setTimeout_ = window.setTimeout; +window.setTimeout = (handler, delay, ...args) => + delay === 1000 ? 0 : setTimeout_(handler, delay, ...args); +document.addEventListener("DOMContentLoaded", () => { + window.setTimeout = setTimeout_; +}); +""" + + +def ScriptsAfterFirstPaintApp(): + """App with prerendered pages and a page that is rendered in the browser.""" + import reflex as rx + + class CounterState(rx.State): + count: int = 0 + + @rx.event + def increment(self): + self.count += 1 + + def counter(heading: rx.Component, *links: rx.Component) -> rx.Component: + return rx.el.main( + heading, + rx.el.p(CounterState.count, id="count"), + rx.el.button("Increment", id="increment", on_click=CounterState.increment), + *links, + ) + + def index(): + return counter(rx.el.h1("Index"), rx.link("Other", href="/other")) + + def other(): + return counter(rx.el.h1("Other")) + + def post(): + return counter(rx.el.h1("Post ", rx.State.post_id)) # pyright: ignore [reportAttributeAccessIssue] + + app = rx.App() + app.add_page(index, title="Index") + app.add_page(other, title="Other") + app.add_page(post, route="/post/[post_id]", title="Post") + + +@pytest.fixture(scope="module") +def scripts_app( + app_harness_env: type[AppHarness], + tmp_path_factory: pytest.TempPathFactory, +) -> Generator[AppHarness, None, None]: + """Start the app in dev or production mode. + + Yields: + The running app harness. + """ + with app_harness_env.create( + root=tmp_path_factory.mktemp("scripts_after_first_paint"), + app_name=f"scriptsafterfirstpaint_{app_harness_env.__name__.lower()}", + app_source=ScriptsAfterFirstPaintApp, + ) as harness: + yield harness + + +def _frontend_url(harness: AppHarness) -> str: + """Get the frontend URL of a running harness. + + Args: + harness: The running app harness. + + Returns: + The URL, without a trailing slash. + """ + assert harness.frontend_url is not None + return harness.frontend_url.rstrip("/") + + +def test_prerendered_head_preloads_no_script(scripts_app: AppHarness): + """The head of a prerendered page holds the stylesheet and no module preload.""" + if not isinstance(scripts_app, AppHarnessProd): + pytest.skip("pages are prerendered in prod only") + static_dir = ( + scripts_app.app_path / prerequisites.get_web_dir() / constants.Dirs.STATIC + ) + html = (static_dir / "index.html").read_text() + head = html[html.index("") : html.index("") + len("")] + theme_script = json.loads( + preload_color_theme("system").render()["children"][0]["contents"] + ) + stylesheet = "/assets/__reflex_global_styles-HASH.css" + assert re.sub(r"-[\w-]{8}\.css", "-HASH.css", head) == ( + '' + '' + f'' + "Index" + '' + f"" + f'' + ) + + +def test_pages_hydrate_and_handle_events(scripts_app: AppHarness, page: Page): + """Prerendered, client-navigated and client-rendered pages all handle a click.""" + frontend_url = _frontend_url(scripts_app) + problems: list[str] = [] + page.on( + "console", + lambda message: ( + problems.append(f"{message.type}: {message.text}") + if message.type in {"warning", "error"} + else None + ), + ) + page.on("pageerror", lambda error: problems.append(f"pageerror: {error}")) + count = page.locator("#count") + increment = page.get_by_role("button", name="Increment") + + # A prerendered page in prod. + page.goto(frontend_url) + expect(page.get_by_role("heading", name="Index")).to_be_visible() + page.wait_for_function(HYDRATED) + increment.click() + expect(count).to_have_text("1") + + # A client-side navigation. + page.get_by_role("link", name="Other").click() + expect(page.get_by_role("heading", name="Other")).to_be_visible() + increment.click() + expect(count).to_have_text("2") + + # A dynamic route, which is rendered in the browser. + page.goto(f"{frontend_url}/post/7") + expect(page.get_by_role("heading", name="Post 7")).to_be_visible() + increment.click() + expect(count).to_have_text("3") + + assert problems == [] + + +def test_input_before_first_paint_starts_scripts(scripts_app: AppHarness, page: Page): + """A click on a page that cannot handle one yet starts its scripts and is not lost.""" + if not isinstance(scripts_app, AppHarnessProd): + pytest.skip("pages are prerendered in prod only") + page.add_init_script(NEVER_PAINTED) + page.goto(_frontend_url(scripts_app), wait_until="load") + modules = page.locator('head script[type="module"]') + increment = page.get_by_role("button", name="Increment") + expect(increment).to_be_visible() + assert modules.count() == 0 + assert not page.evaluate(HYDRATED) + + # No handler is attached yet: the click is dispatched again after hydration. + increment.click() + assert modules.count() == 1 + expect(page.locator("#count")).to_have_text("1") + increment.click() + expect(page.locator("#count")).to_have_text("2") diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..c9719ca765f 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -38,6 +38,7 @@ from reflex.compiler.plugins import default_page_plugins from reflex.state import BaseState from reflex.utils import prerequisites +from reflex.utils.misc import preload_color_theme @pytest.mark.parametrize("with_plugin", [False, True]) @@ -893,6 +894,40 @@ def test_compile_document_root_bakes_default_color_mode(mocker: MockerFixture): assert "|| 'dark'" in code +def test_compile_document_root_prod( + mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch +): + """A production document preloads its stylesheet and no script of its own. + + Its scripts are the Reflex wrapper of react-router's, which starts them + after the first paint on a prerendered page. + """ + monkeypatch.setenv("REFLEX_ENV_MODE", constants.Env.PROD.value) + mocker.patch( + "reflex.compiler.compiler.get_web_dir", + return_value=Path("/tmp/does_not_matter"), + ) + + path, code = compiler.compile_document_root([], default_color_mode="system") + + theme_script = preload_color_theme("system").render()["children"][0]["contents"] + assert path == str(Path("/tmp/does_not_matter/app/_document.js")) + assert ( + code + == f"""import {{Links,Meta,ScrollRestoration}} from "react-router" +import reflexGlobalStyles from "$/styles/__reflex_global_styles.css?url" +import {{Scripts}} from "$/utils/scripts" +import {{jsx}} from "@emotion/react" +import {{Fragment,useEffect}} from "react" + +export function Layout({{children}}) {{ + return ( + jsx("html",{{lang:"en"}},jsx("head",{{}},jsx("script",{{}},{theme_script}),jsx("meta",{{charSet:"utf-8"}},),jsx("meta",{{content:"width=device-width, initial-scale=1",name:"viewport"}},),jsx(Meta,{{}},),jsx("link",{{as:"style",href:reflexGlobalStyles,rel:"preload"}},),jsx("link",{{href:reflexGlobalStyles,rel:"stylesheet",type:"text/css"}},),jsx(Links,{{}},)),jsx("body",{{}},children,jsx(ScrollRestoration,{{}},),jsx(Scripts,{{}},))) + ) +}}""" + ) + + def test_compile_nonexistent_stylesheet(tmp_path, mocker: MockerFixture): """Test that an error is thrown for non-existent stylesheets. diff --git a/tests/units/reflex_components_core/base/__init__.py b/tests/units/reflex_components_core/base/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_components_core/base/test_document.py b/tests/units/reflex_components_core/base/test_document.py new file mode 100644 index 00000000000..ac5552b23cc --- /dev/null +++ b/tests/units/reflex_components_core/base/test_document.py @@ -0,0 +1,13 @@ +"""Tests for the document components.""" + +from reflex_base import constants +from reflex_base.utils.imports import ImportVar +from reflex_components_core.base.document import Scripts + + +def test_scripts_come_from_the_reflex_frontend(): + """The document's scripts are Reflex's wrapper, which the web template ships.""" + scripts = Scripts.create() + assert scripts.render() == {"name": "Scripts", "props": [], "children": []} + assert scripts._get_all_imports() == {"$/utils/scripts": [ImportVar(tag="Scripts")]} + assert (constants.Templates.Dirs.WEB_TEMPLATE / "utils" / "scripts.js").is_file() From c05dd41927e966866d48e67ed429a30b504a1606 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 04:31:27 +0000 Subject: [PATCH 06/26] Document the early click hand-over in the frontend README Claude-Session: https://claude.ai/code/session_014AwvTNacWVsm7SEvVjhfGM --- packages/reflex-frontend/README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/reflex-frontend/README.md b/packages/reflex-frontend/README.md index 712a67f3c6d..e2b9127d43d 100644 --- a/packages/reflex-frontend/README.md +++ b/packages/reflex-frontend/README.md @@ -53,7 +53,10 @@ without it appearing in its arguments. What there is, and where it is pinned: queue or the socket is as it left them. - **Work done on import**: `utils/state.js` creates the cookie reader, always; publishes the client state store on `refs`, when there is a `document`; and - starts a socket transport, when there is a `window`. A production build + starts a socket transport, when there is a `window`. `utils/scripts.js` + takes over the click a prerendered page recorded before its scripts loaded + (`window.__reflex_early`, set by the inline script that module renders), and + dispatches it again once the page is hydrated. A production build evaluates every module in node to prerender pages, so anything added here has to load without either. `tests/public_api.test.js` imports each module in node to keep it that way. From f7e88922a76c03a84ed1fa9e611791c0ba46a5c4 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 04:42:38 +0000 Subject: [PATCH 07/26] Ship the state runtime and the toaster only to apps that use them An app without state bundled Socket.io, the cookie library and the code that connects to the backend, and every app bundled the toaster whether or not it ever showed a toast. State runtime. The connection to the backend (socket, session, browser storage sync, the event loop over the socket) moves out of utils/state.js into utils/socket.js. Only the compiled context module of an app with state imports it; it registers itself with utils/state.js through a registry in the new utils/event_loop.js, which also holds the event queue the two share. utils/state.js keeps every export it had: the ones that need the connection delegate to it, and useEventLoop runs the events the browser handles by itself (scripts, redirects, refs, storage, downloads) when there is none. _remove_cookie writes the expired cookie itself, so it needs no cookie library. Toaster. The app's default toaster is bundled when the app sends a toast: a toast call compiled into a page or an app wrap carries a ToasterRequest app wrap in its var data, an on_load toast is read from the event, and the functions of the state tree are read for references to rx.toast (by name, through helpers in the app's own modules). A toaster passed to rx.App is always bundled. Since code that runs on the backend cannot be ruled out by reading names, an app with state that gets no toaster gets a plain-DOM stand-in for the toast function instead, so a toast sent anyway and a connection error still show. The connection toaster no longer asks for the toaster by itself. Total gzipped client JS of a production build, rx.el only, no Radix or Tailwind plugin: 158.7 kB to 130.8 kB without state, 161.6 kB to 153.9 kB with state and no toast. Claude-Session: https://claude.ai/code/session_014AwvTNmJCFr12bYVhV8efZ --- docs/library/overlay/toast.md | 8 +- news/+state-runtime-on-demand.performance.md | 3 + .../+state-runtime-on-demand.performance.md | 1 + .../src/reflex_base/compiler/templates.py | 11 +- ...+connection-toaster-request.performance.md | 1 + .../src/reflex_components_core/core/banner.py | 12 +- .../news/+toaster-request.feature.md | 1 + .../src/reflex_components_sonner/toast.py | 18 +- packages/reflex-frontend/README.md | 36 +- packages/reflex-frontend/lint.biome.jsonc | 14 + .../reflex-frontend/src/utils/event_loop.js | 82 + .../src/utils/helpers/plain_toast.js | 150 ++ packages/reflex-frontend/src/utils/socket.js | 1355 +++++++++++++++ packages/reflex-frontend/src/utils/state.js | 1451 ++--------------- .../reflex-frontend/tests/plain_toast.test.js | 153 ++ .../reflex-frontend/tests/public_api.test.js | 19 + .../reflex-frontend/tests/run_script.test.js | 2 + packages/reflex-frontend/tests/state.test.js | 3 + .../tests/state_connection.test.js | 8 +- .../tests/state_without_backend.test.js | 229 +++ pyi_hashes.json | 2 +- pyproject.toml | 2 +- reflex/app.py | 27 +- reflex/compiler/compiler.py | 259 ++- .../tests_playwright/test_stateless_app.py | 145 +- .../tests_playwright/test_toast.py | 115 +- tests/integration/utils.py | 65 +- tests/units/compiler/state_js.test.mjs | 52 +- tests/units/compiler/test_compiler.py | 311 ++++ .../compiler/test_context_js_template.py | 54 +- .../units/compiler/test_state_js_template.py | 11 +- tests/units/components/core/test_banner.py | 14 + .../client_event_queue_runtime.mjs | 40 +- .../reflex_components_sonner/test_toast.py | 22 +- tests/units/test_app.py | 155 +- 35 files changed, 3382 insertions(+), 1449 deletions(-) create mode 100644 news/+state-runtime-on-demand.performance.md create mode 100644 packages/reflex-base/news/+state-runtime-on-demand.performance.md create mode 100644 packages/reflex-components-core/news/+connection-toaster-request.performance.md create mode 100644 packages/reflex-components-sonner/news/+toaster-request.feature.md create mode 100644 packages/reflex-frontend/src/utils/event_loop.js create mode 100644 packages/reflex-frontend/src/utils/helpers/plain_toast.js create mode 100644 packages/reflex-frontend/src/utils/socket.js create mode 100644 packages/reflex-frontend/tests/plain_toast.test.js create mode 100644 packages/reflex-frontend/tests/state_without_backend.test.js diff --git a/docs/library/overlay/toast.md b/docs/library/overlay/toast.md index 5991f5b585b..18cd0ae5b9c 100644 --- a/docs/library/overlay/toast.md +++ b/docs/library/overlay/toast.md @@ -114,5 +114,11 @@ Using the `rx.toast` function require to have a toast provider in your app. `rx.toast.provider` is a component that provides a context for displaying toasts. It should be placed at the root of your app. ```md alert warning -# In most case you will not need to include this component directly, as it is already included in `rx.app` as the `overlay_component` for displaying connections errors. +# In most case you will not need to include this component directly, as `rx.App` puts one at the root of the app. +``` + +The toaster is only bundled with an app that sends a toast: a page that calls `rx.toast`, an event handler that refers to it, or an `on_load` toast. An app with state that sends none shows connection errors, and any toast the compiler could not foresee, as plain notices. To bundle the toaster in every case, or to configure it, pass one to the app: + +```python +app = rx.App(toaster=rx.toast.provider(position="top-center")) ``` diff --git a/news/+state-runtime-on-demand.performance.md b/news/+state-runtime-on-demand.performance.md new file mode 100644 index 00000000000..b1d9763de01 --- /dev/null +++ b/news/+state-runtime-on-demand.performance.md @@ -0,0 +1,3 @@ +An app without state no longer bundles Socket.io, the cookie library or the code that connects to the backend, and no app bundles the toaster unless it sends a toast: a static page ships about 28 kB less gzipped JavaScript, and an app with state that sends no toast about 8 kB less. + +The toaster is bundled when a toast call is compiled into a page, when an event handler refers to `rx.toast`, or when `rx.App` is given a `toaster`. A toast the compiler could not foresee, and a connection error, show as a plain notice in an app with state; pass `toaster=rx.toast.provider()` to `rx.App` to always bundle the toaster. diff --git a/packages/reflex-base/news/+state-runtime-on-demand.performance.md b/packages/reflex-base/news/+state-runtime-on-demand.performance.md new file mode 100644 index 00000000000..a700f364cb5 --- /dev/null +++ b/packages/reflex-base/news/+state-runtime-on-demand.performance.md @@ -0,0 +1 @@ +The connection to the backend moved out of `utils/state.js` into `utils/socket.js`, which only the compiled context of an app with state imports, so an app without state bundles neither it nor Socket.io and the cookie library. Every name `$/utils/state` exported is still exported from there. diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 77f28862881..848c6714b73 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -429,6 +429,15 @@ def context_template( """ ) + # Only an app with state imports the connection to the backend, so an app + # without state bundles neither it nor socket.io and the cookie library. + state_imports_str = ( + 'import { applyDelta, ReflexEvent, refs } from "$/utils/state"\n' + 'import { hydrateClientStorage, useEventLoop } from "$/utils/socket"' + if state_name + else 'import { applyDelta, useEventLoop, refs } from "$/utils/state"' + ) + disable_owner_stacks_str = ( r""" // Disable React dev-build owner-stack capture: the per-element Error() @@ -458,7 +467,7 @@ def context_template( ) return rf"""import {"React, " if disable_react_owner_stacks else ""}{{ useContext, useMemo, useState, createElement, useEffect }} from "react" -import {{ applyDelta, ReflexEvent, hydrateClientStorage, useEventLoop, refs }} from "$/utils/state" +{state_imports_str} import {{ ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext, registerApp, eventLoop }} from "$/utils/context-registry" import {{ jsx }} from "@emotion/react"; {disable_owner_stacks_str} diff --git a/packages/reflex-components-core/news/+connection-toaster-request.performance.md b/packages/reflex-components-core/news/+connection-toaster-request.performance.md new file mode 100644 index 00000000000..89e3c958ce7 --- /dev/null +++ b/packages/reflex-components-core/news/+connection-toaster-request.performance.md @@ -0,0 +1 @@ +The connection toaster no longer makes an app bundle the toaster: in an app that sends no toast, a connection error shows as a plain notice instead. diff --git a/packages/reflex-components-core/src/reflex_components_core/core/banner.py b/packages/reflex-components-core/src/reflex_components_core/core/banner.py index 6cf4e97a58b..13ccf0cf27e 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/banner.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/banner.py @@ -16,7 +16,7 @@ from reflex_base.vars.number import BooleanVar from reflex_base.vars.sequence import LiteralArrayVar from reflex_components_lucide.icon import Icon -from reflex_components_sonner.toast import ToastProps, toast_ref +from reflex_components_sonner.toast import ToastProps from reflex_components_core import el from reflex_components_core.base.fragment import Fragment @@ -145,7 +145,15 @@ def add_hooks(self) -> list[str | Var]: ) individual_hooks = [ - Var(f"const toast = {toast_ref};"), + # Whichever toast function the app installed. Unlike ``toast_ref`` + # this does not ask the app for its toaster: a connection error is + # no reason to bundle it, and shows as a plain notice without it. + Var( + "const toast = refs['__toast'];", + _var_data=VarData( + imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]} + ), + ), f"const toast_props = {LiteralVar.create(props)!s};", "const [userDismissed, setUserDismissed] = useState(false);", "const [waitedForBackend, setWaitedForBackend] = useState(false);", diff --git a/packages/reflex-components-sonner/news/+toaster-request.feature.md b/packages/reflex-components-sonner/news/+toaster-request.feature.md new file mode 100644 index 00000000000..67874272c6b --- /dev/null +++ b/packages/reflex-components-sonner/news/+toaster-request.feature.md @@ -0,0 +1 @@ +A toast call now carries a `ToasterRequest` app wrap in its var data, which tells the compiler that the app sends a toast and needs its toaster bundled. diff --git a/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py b/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py index ff6bece4b13..af711f0874c 100644 --- a/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py +++ b/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py @@ -30,9 +30,25 @@ "bottom-right", ] + +class ToasterRequest(Component): + """An empty app wrap that asks the app for its toaster. + + A toast call carries it in its var data, so compiling the call into a page + tells the compiler that the app sends a toast. It renders an empty fragment + wherever it is left in place. + """ + + library = "react" + tag = "Fragment" + + toast_ref = Var( _js_expr="refs['__toast']", - _var_data=VarData(imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]}), + _var_data=VarData( + imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]}, + app_wraps=[(44, ToasterRequest.create())], + ), ) _TOAST_STYLE_PROP_ALIASES = ( diff --git a/packages/reflex-frontend/README.md b/packages/reflex-frontend/README.md index 712a67f3c6d..f2461638647 100644 --- a/packages/reflex-frontend/README.md +++ b/packages/reflex-frontend/README.md @@ -45,23 +45,33 @@ so there is still no compile step between this directory and an app. Several of the bugs found in this code came from state a function reads or writes without it appearing in its arguments. What there is, and where it is pinned: -- **Module-level state in `utils/state.js`**: the event queue, the session - token, the socket warmed up before React mounts, the record of sent - localStorage values. Every mounted event loop and every drain shares them. - A test that needs a clean copy reloads the module (`vi.resetModules()`, as - `tests/state_connection.test.js` does). Code that awaits must not assume the - queue or the socket is as it left them. -- **Work done on import**: `utils/state.js` creates the cookie reader, always; - publishes the client state store on `refs`, when there is a `document`; and - starts a socket transport, when there is a `window`. A production build - evaluates every module in node to prerender pages, so anything added here has - to load without either. `tests/public_api.test.js` imports each module in - node to keep it that way. +- **Module-level state**: the event queue (`utils/event_loop.js`), and in + `utils/socket.js` the session token, the socket warmed up before React + mounts and the record of sent localStorage values. Every mounted event loop + and every drain shares them. A test that needs a clean copy reloads the + modules (`vi.resetModules()`, as `tests/state_connection.test.js` does). + Code that awaits must not assume the queue or the socket is as it left them. +- **Work done on import**: `utils/state.js` publishes the client state store + on `refs`, when there is a `document`. `utils/socket.js` creates the cookie + reader, always; starts a socket transport, when there is a `window`; and + registers itself with `utils/state.js`. A production build evaluates every + module in node to prerender pages, so anything added here has to load + without either. `tests/public_api.test.js` imports each module in node to + keep it that way. +- **Whether the app has state**: only the compiled context module of an app + with state imports `utils/socket.js`, so an app without state bundles + neither it nor socket.io and the cookie library. `utils/state.js` must + therefore never import it: it reaches the connection through the `backend` + registry in `utils/event_loop.js`, which stays empty in an app without + state. Its exports that need the connection (`connect`, + `hydrateClientStorage`) fail with a message there, and `useEventLoop` runs + the events the browser handles by itself. + `tests/state_without_backend.test.js` covers that side. - **Script scope**: event code sent by the backend (`rx.call_script`, event callbacks) runs through `runScript` in `utils/state.js`, which compiles it with the Function constructor and passes in every export of that module, the late-bound `addEvents`, the `socket`, `navigate` and `params` of the event - being applied, and the session `token`. A direct `eval` would see every + being applied, and the session `token` (undefined in an app without state). A direct `eval` would see every module local, but it stops the minifier from mangling the chunk that holds it. So a script sees those names and the globals, and nothing else. Renaming an export changes what compiled callbacks can call. diff --git a/packages/reflex-frontend/lint.biome.jsonc b/packages/reflex-frontend/lint.biome.jsonc index e6b50c0e860..b57dee2cd57 100644 --- a/packages/reflex-frontend/lint.biome.jsonc +++ b/packages/reflex-frontend/lint.biome.jsonc @@ -70,6 +70,20 @@ } } }, + { + // The event loop over the socket was part of state.js, and its effects + // leave dependencies out for the same reason. + "includes": ["src/utils/socket.js"], + "linter": { + "rules": { + "correctness": { + "noUnusedVariables": "off", + "noUnusedFunctionParameters": "off", + "useExhaustiveDependencies": "off" + } + } + } + }, { // The cookie tests write `document.cookie` to set up what the code reads. "includes": ["tests/**"], diff --git a/packages/reflex-frontend/src/utils/event_loop.js b/packages/reflex-frontend/src/utils/event_loop.js new file mode 100644 index 00000000000..ba6a26adad6 --- /dev/null +++ b/packages/reflex-frontend/src/utils/event_loop.js @@ -0,0 +1,82 @@ +// What the event loop in utils/state.js and the backend connection in +// utils/socket.js share. Only an app with state bundles utils/socket.js, so +// utils/state.js cannot import it: the two meet here instead. +import { useEffect, useRef } from "react"; +import { useLocation, useNavigate, useParams } from "react-router"; +import env from "$/env.json"; + +// What utils/socket.js provides, registered when it loads. Empty in an app +// without state, which has no backend to connect to. +export const backend = {}; + +// A frontend event naming one synced localStorage var, turned into an +// update_vars_internal event when it is sent: see syncLocalStorageEvent. +export const SYNC_LOCAL_STORAGE = "_sync_local_storage"; + +// Array holding pending events to be processed. +export const event_queue = []; + +// Mirrors the data router's location so applyEvent can populate router_data +// with the in-widget URL. In embed mode the host page's window.location is +// unrelated to the Reflex route, so the backend's on_load and dynamic-route +// matching rely on this ref instead. Updated by useEventRoute once mounted; +// pre-seeded in embed mode with the memory router's initial path (see +// initialEntries in entry.client.embed.js) so events dispatched before the +// first effect commit don't briefly fall back to the host page's URL. +export const locationRef = { + current: env.MOUNT_TARGET ? { pathname: "/", search: "", hash: "" } : null, +}; + +/** Append nested events to an output array in depth-first order. */ +const appendEvents = (events, normalized) => { + for (const event of events) { + if (Array.isArray(event)) { + appendEvents(event, normalized); + } else if (event !== undefined && event !== null) { + normalized.push(event); + } + } +}; + +/** + * Flatten event lists and discard empty event values. + * @param events Events or nested event lists. + * @returns A flat array of events in depth-first order. + */ +export const normalizeEvents = (events) => { + const normalized = []; + appendEvents(events, normalized); + return normalized; +}; + +/** + * Track the route an event is dispatched from. + * + * Keeps `locationRef` on the router's location, and the route params in a ref + * the event queue reads when it sends an event. + * @returns The navigate function, the ref to the route params, and the location. + */ +export const useEventRoute = () => { + const location = useLocation(); + const navigate = useNavigate(); + const paramsR = useParams(); + // A splat route's segments are kept as a list, so the values are not all strings. + const params = useRef( + /** @type {Record} */ (paramsR), + ); + + useEffect(() => { + const { "*": splat, ...remainingParams } = paramsR; + if (splat) { + params.current = { ...remainingParams, splat: splat.split("/") }; + } else { + params.current = remainingParams; + } + }, [paramsR]); + + useEffect(() => { + locationRef.current = location; + }, [location]); + + return /** @type {const} */ ([navigate, params, location]); +}; diff --git a/packages/reflex-frontend/src/utils/helpers/plain_toast.js b/packages/reflex-frontend/src/utils/helpers/plain_toast.js new file mode 100644 index 00000000000..2de09417d81 --- /dev/null +++ b/packages/reflex-frontend/src/utils/helpers/plain_toast.js @@ -0,0 +1,150 @@ +// A plain notice with the call signature of the toaster's `toast`, for a build +// that leaves the toaster out. The compiler leaves it out when it finds no use +// of `rx.toast`, which it cannot rule out for code that runs on the backend, so +// a toast sent anyway, or a connection error, is shown here rather than lost. +// +// Plain DOM rather than a React component: there is no provider to render it. + +const ACCENTS = { + info: "#0090ff", + success: "#30a46c", + warning: "#ffc53d", + error: "#e5484d", +}; +const DEFAULT_DURATION = 4000; + +// The notices on the page by id, with what removes each. +const notices = new Map(); +let lastId = 0; +let warned = false; + +/** + * Get the element stacking the notices of one position, creating it if needed. + * @param {string} position A toaster position, e.g. "bottom-right". + * @returns {HTMLElement} The element. + */ +const stackAt = (position) => { + const id = `reflex-plain-toasts-${position}`; + let stack = document.getElementById(id); + if (!stack) { + const [vertical, horizontal] = position.split("-"); + stack = document.createElement("div"); + stack.id = id; + stack.style.cssText = + "position:fixed;z-index:2147483647;display:flex;flex-direction:column;" + + `gap:0.5rem;padding:1rem;max-width:min(24rem,100vw);${vertical}:0;` + + (horizontal === "center" + ? "left:50%;transform:translateX(-50%);" + : `${horizontal}:0;`); + document.body.append(stack); + } + return stack; +}; + +/** + * Remove a notice from the page. + * @param {string|number} [id] The id of the notice, or nothing for all of them. + */ +const dismiss = (id) => { + for (const key of id === undefined ? [...notices.keys()] : [id]) { + notices.get(key)?.(); + } +}; + +/** + * Add a button to a notice. + * @param {HTMLElement} notice The notice. + * @param {string} label The text of the button. + * @param {(event: MouseEvent) => void} onClick What the button does. + */ +const addButton = (notice, label, onClick) => { + const button = document.createElement("button"); + button.textContent = label; + button.style.cssText = + "margin:0.5rem 0.5rem 0 0;padding:0.125rem 0.5rem;border:1px solid;" + + "border-radius:4px;background:transparent;color:inherit;font:inherit;" + + "cursor:pointer;"; + button.onclick = onClick; + notice.append(button); +}; + +/** + * Build the function showing notices of one level. + * @param {string} [level] The toast level, or nothing for a plain toast. + * @returns {(message?: string, options?: Record) => string|number} The function, which returns the id of the notice. + */ +const show = + (level) => + (message, options = {}) => { + if (!warned) { + warned = true; + console.warn( + "The toaster is not part of this build, because no use of rx.toast " + + "was found when the app was compiled, so a plain notice is shown " + + "instead. Pass toaster=rx.toast.provider() to rx.App to include it.", + ); + } + const id = options.id ?? ++lastId; + // A notice with the id of one on the page takes its place. + notices.get(id)?.(); + + const notice = document.createElement("div"); + notice.setAttribute("role", level === "error" ? "alert" : "status"); + notice.style.cssText = + "padding:0.75rem 1rem;border:1px solid;border-radius:8px;" + + `border-left:4px solid ${ACCENTS[level] ?? "currentColor"};` + + "background:Canvas;color:CanvasText;font:0.875rem system-ui,sans-serif;" + + "white-space:pre-wrap;box-shadow:0 4px 12px rgba(0,0,0,0.1);"; + const title = document.createElement("div"); + title.style.fontWeight = "600"; + title.append(options.title ?? message ?? ""); + notice.append(title); + if (options.description) { + const description = document.createElement("div"); + description.append(options.description); + notice.append(description); + } + + const seen = { id, title: title.textContent }; + let timer; + const remove = () => { + clearTimeout(timer); + notices.delete(id); + notice.remove(); + }; + notices.set(id, remove); + const close = () => { + remove(); + options.onDismiss?.(seen); + }; + for (const button of [options.action, options.cancel]) { + if (button?.label) { + addButton(notice, button.label, (event) => { + button.onClick?.(event); + if (!event.defaultPrevented) close(); + }); + } + } + if (options.closeButton) { + addButton(notice, "×", close); + } + + const duration = options.duration ?? DEFAULT_DURATION; + if (level !== "loading" && Number.isFinite(duration)) { + timer = setTimeout(() => { + remove(); + options.onAutoClose?.(seen); + }, duration); + } + stackAt(options.position ?? "bottom-right").append(notice); + return id; + }; + +export default Object.assign(show(), { + info: show("info"), + success: show("success"), + warning: show("warning"), + error: show("error"), + loading: show("loading"), + dismiss, +}); diff --git a/packages/reflex-frontend/src/utils/socket.js b/packages/reflex-frontend/src/utils/socket.js new file mode 100644 index 00000000000..e50acc77e5c --- /dev/null +++ b/packages/reflex-frontend/src/utils/socket.js @@ -0,0 +1,1355 @@ +// The connection to the backend: the socket, the session, the browser storage +// the backend state syncs with, and the event loop that drives them. Only an +// app with state imports this module (from its compiled utils/context), so an +// app without state bundles neither it nor socket.io and the cookie library. +import io from "socket.io-client"; +import env from "$/env.json"; +import Cookies from "universal-cookie"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { useSearchParams } from "react-router"; +import { app } from "$/utils/context-registry"; +import { + SYNC_LOCAL_STORAGE, + backend, + event_queue, + locationRef, + normalizeEvents, + useEventRoute, +} from "$/utils/event_loop"; +import { parseJson } from "$/utils/helpers/json"; +import { + ReflexEvent, + applyEventActions, + encodeFormDataArgs, + getBackendURL, + isBackendDisabled, + processEvent, + queueEvents, +} from "$/utils/state"; + +// Endpoint URLs. +const EVENTURL = env.EVENT; + +// Socket event names (must match reflex_base/constants/event.py SocketEvent) +const CLIENT_ERROR_EVENT = "client_error"; +const STATE_MISMATCH_EVENT = "state_mismatch"; +const SESSION_REFRESH_EVENT = "session_refresh"; + +// sessionStorage key with the time of the last automatic reload (must match +// LAST_RELOADED_KEY in reflex/state.py: the reload on a frontend error and the +// reload on a state mismatch share one cooldown, so neither can loop). +const LAST_RELOADED_KEY = "reflex_last_reloaded_on_error"; + +// The id of the banner offering a reload when one already happened recently. +const NEW_VERSION_BANNER_ID = "reflex-new-version-banner"; + +// The cancelable window event dispatched before a prod page acts on a state +// mismatch; a listener calling preventDefault() handles the mismatch instead. +const STATE_MISMATCH_WINDOW_EVENT = "reflex:state-mismatch"; + +// Client error types (must match reflex_base/constants/event.py ClientErrorType) +const ERROR_TYPE_DISPATCH_MISSING = "dispatch_function_missing"; +const ERROR_TYPE_STATE_UPDATE = "state_update_processing_error"; +const ERROR_TYPE_HYDRATION_PAYLOAD_TOO_LARGE = "hydration_payload_too_large"; + +// Global variable to hold the token. +let token; + +// Share cookie exchange and refresh requests in this tab. +let initialSessionExchange; + +// create cookie instance +const cookies = new Cookies(); + +// The event that sends browser storage values to the backend. +const UPDATE_VARS_INTERNAL = + "reflex___state____update_vars_internal_state.update_vars_internal"; + +// Synced localStorage values sent to the backend and not yet echoed back, by +// state key, oldest first, with this tab's localStorage write count at the send. +const sentStorageValues = {}; +// Bounds a key whose echoes a get_delta override changes, so they never match. +const MAX_SENT_STORAGE_VALUES = 256; +// This tab's localStorage write count, and its last write by storage name +// (vars of different state keys may share one). +let localStorageWrites = 0; +const lastLocalStorageWrites = {}; + +/** + * Get the token for the current session. + * @returns The token. + */ +export const getToken = () => { + if (token) { + return token; + } + if (typeof window !== "undefined") { + token = + window.sessionStorage.getItem(clientTokenStorageKey()) || + window.sessionStorage.getItem(LEGACY_TOKEN_STORAGE_KEY) || + ""; + } + return token || ""; +}; + +/** Get the saved client token to warm the transport before the app mounts. */ +const peekToken = () => + token || + window.sessionStorage.getItem(clientTokenStorageKey()) || + window.sessionStorage.getItem(LEGACY_TOKEN_STORAGE_KEY) || + ""; + +/** Namespace browser state by the backend URL, including its port and path. */ +const sessionStorageKey = () => `reflex:${getBackendURL(EVENTURL).href}`; +const LEGACY_TOKEN_STORAGE_KEY = "token"; +const clientTokenStorageKey = () => `${sessionStorageKey()}:token`; +const sessionRefreshStorageKey = () => `${sessionStorageKey()}:expires_at`; + +/** Store only the non-secret tab routing token in JavaScript-accessible storage. */ +const setToken = (value) => { + token = value; + window.sessionStorage.setItem(clientTokenStorageKey(), value); +}; + +/** Wait until credentialed HTTP calls can use the initial session cookie. */ +export const waitForSession = async () => { + await initialSessionExchange; +}; + +/** Exchange an in-band credential or refresh the HTTP-only session cookie. */ +const ensureSession = async (sessionCredential, controller) => { + const endpoint = getBackendURL(EVENTURL); + endpoint.protocol = endpoint.protocol === "wss:" ? "https:" : "http:"; + endpoint.pathname = endpoint.pathname.replace( + /\/_event\/?$/, + "/_reflex/session", + ); + endpoint.search = ""; + const headers = { "Content-Type": "application/json" }; + const previousToken = getToken(); + if (previousToken) headers["Reflex-Client-Token"] = previousToken; + // Abort a stalled cookie exchange after ten seconds. + const timeout = window.setTimeout(() => controller.abort(), 10000); + try { + const response = await window.fetch(endpoint.href, { + method: "POST", + credentials: "include", + headers, + body: JSON.stringify( + sessionCredential ? { session_token: sessionCredential } : {}, + ), + signal: controller.signal, + }); + if (!response.ok) { + /** @type {Error & { status?: number }} */ + const error = new Error(`Session request failed: ${response.status}`); + error.status = response.status; + throw error; + } + const session = await response.json(); + if ( + typeof session.client_token !== "string" || + !session.client_token || + !Number.isFinite(session.expires_in) || + session.expires_in <= 0 + ) { + throw new Error("Invalid session response"); + } + return session; + } finally { + window.clearTimeout(timeout); + } +}; + +/** + * Create a socket without starting its namespace or hydration events. + * @param endpoint The backend URL. + * @param transports The configured transports. + * @param token The session token the backend links the connection to. + * @returns The disconnected socket. + */ +const createSocket = (endpoint, transports, token) => + io(endpoint.href, { + path: endpoint.pathname, + transports, + protocols: [env.REFLEX_VERSION], + autoUnref: false, + autoConnect: false, + withCredentials: true, + query: { token }, + reconnection: false, + }); + +/** + * Measure encoded text the way the Engine.IO server limits a frame. + * @param frame The encoded text. + * @param transport The transport that carries it. + * @returns The code points for a websocket text frame, or the UTF-8 bytes for a polling body. + */ +const frameSize = (frame, transport) => { + if (transport !== "websocket") { + return new TextEncoder().encode(frame).byteLength; + } + let size = 0; + for (const _ of frame) size++; + return size; +}; + +let warmSocket = null; +let cancelWarmup = () => {}; +let socketStarted = false; + +/** Close an unclaimed transport and remove its cleanup handlers. */ +const discardWarmSocket = () => { + const socket = warmSocket; + warmSocket = null; + cancelWarmup(); + socket?.disconnect(); +}; + +// Start only the transport while React is still preparing to mount. The +// namespace stays disconnected until connect() installs all its handlers. +// Defer past module evaluation because context.js imports this module too. +if (typeof window !== "undefined") { + queueMicrotask(() => { + if ( + socketStarted || + Object.keys(app.initialState ?? {}).length <= 1 || + isBackendDisabled() || + document.visibilityState === "hidden" + ) { + return; + } + try { + // A cold transport would capture cookies before the shared session lock. + if ( + !( + Number(window.localStorage.getItem(sessionRefreshStorageKey())) > + Date.now() + ) + ) { + return; + } + warmSocket = createSocket( + getBackendURL(EVENTURL), + [env.TRANSPORT], + peekToken(), + ); + } catch { + // Speculative setup may fail (for example, blocked session storage). + // The normal connection path will report failures when the app mounts. + return; + } + const timeout = setTimeout(discardWarmSocket, 10000); + window.addEventListener("pagehide", discardWarmSocket); + cancelWarmup = () => { + clearTimeout(timeout); + window.removeEventListener("pagehide", discardWarmSocket); + }; + warmSocket.io.open((error) => { + if (error) discardWarmSocket(); + }); + }); +} + +if (import.meta.hot) { + import.meta.hot.dispose(() => { + socketStarted = true; + discardWarmSocket(); + }); +} + +/** + * Build the update_vars_internal event for a synced localStorage var. + * + * The value is read when the event is sent, so it and the write count recorded + * with it come from the same moment. + * @param payload The storage name and the state keys of the vars that use it. + * @returns The update_vars_internal event. + */ +const syncLocalStorageEvent = ({ key, state_keys }) => { + const value = localStorage.getItem(key); + return ReflexEvent(`${app.state_name}.${UPDATE_VARS_INTERNAL}`, { + vars: Object.fromEntries( + state_keys.map((state_key) => [ + state_key, + value ?? storageDefault(state_key), + ]), + ), + }); +}; + +/** + * Get the compiled default of a browser storage var. + * + * A removed storage key resets its vars to their defaults, as a page load does. + * @param state_key The state key of the browser storage var. + * @returns The default value. + */ +const storageDefault = (state_key) => { + const dot = state_key.lastIndexOf("."); + return app.initialState[state_key.slice(0, dot)][state_key.slice(dot + 1)]; +}; + +/** + * Fill in the event's router data from the current location, if missing. + * @param event The event to send. + * @param params The params object from useParams + * @returns The same event, with router_data populated. + */ +const withRouterData = (event, params) => { + if ( + event.router_data === undefined || + Object.keys(event.router_data).length === 0 + ) { + const loc = locationRef.current ?? window.location; + // React Router's location (mirrored in locationRef) does not observe direct + // window.history.pushState/replaceState calls (e.g. via rx.call_script), so + // read the live query string and hash to keep router_data in sync. The + // pathname stays basename-relative (from React Router) so the backend's + // frontend_path prefix is not applied twice. In embed mode the host page's + // window.location is unrelated to the in-widget memory router, so use the + // mirrored location there. + const liveLoc = env.MOUNT_TARGET ? loc : window.location; + const search = liveLoc.search ?? ""; + const hash = liveLoc.hash ?? ""; + event.router_data = { + pathname: loc.pathname, + asPath: loc.pathname + search + hash, + }; + const query = { + ...Object.fromEntries(new URLSearchParams(search)), + ...params.current, + }; + if (query && Object.keys(query).length > 0) { + event.router_data.query = query; + } + } + return event; +}; + +const currentRouteKey = () => { + const loc = locationRef.current ?? window.location; + const liveLoc = env.MOUNT_TARGET ? loc : window.location; + return loc.pathname + (liveLoc.search ?? ""); +}; + +/** + * Send an event to the backend over the socket. + * @param event The event to send. + * @param socket The socket object to send the event on. + * @param params The params object from useParams + */ +const sendEvent = (event, socket, params) => { + const routed_event = withRouterData( + event.name === SYNC_LOCAL_STORAGE + ? syncLocalStorageEvent(event.payload) + : event, + params, + ); + recordSentStorageValues(routed_event); + // Instrumentation hook (installed by reflex-otel): may add a traceparent. + window.__reflex_otel?.onEventSend?.(routed_event); + socket.emit("event", encodeFormDataArgs(routed_event)); +}; + +/** + * Reload the page for a new version of the app, restarting the reload cooldown. + */ +const reloadForNewVersion = () => { + window.sessionStorage.setItem(LAST_RELOADED_KEY, Date.now().toString()); + window.location.reload(); +}; + +/** + * Show a banner saying a new version is available, with a reload button. + * + * Plain DOM rather than a React component: it must show whatever the app + * renders, and stay up while the page keeps working as well as it can. + */ +const showNewVersionBanner = () => { + if (document.getElementById(NEW_VERSION_BANNER_ID)) { + return; + } + const banner = document.createElement("div"); + banner.id = NEW_VERSION_BANNER_ID; + banner.setAttribute("role", "alert"); + banner.style.cssText = + "position:fixed;top:0;left:0;right:0;z-index:2147483647;display:flex;" + + "justify-content:center;align-items:center;gap:1rem;padding:0.5rem 1rem;" + + "background:#1c2024;color:#fff;font:1rem system-ui,sans-serif;"; + banner.append("A new version of this app is available."); + const button = document.createElement("button"); + button.textContent = "Reload"; + button.style.cssText = + "padding:0.25rem 0.75rem;border:1px solid #fff;border-radius:4px;" + + "background:transparent;color:inherit;font:inherit;cursor:pointer;"; + button.onclick = reloadForNewVersion; + banner.append(button); + document.body.append(banner); +}; + +/** + * Handle the backend reporting that this bundle was compiled for another + * state tree than the one it runs (sent on connect, see EventNamespace.on_connect). + * + * In prod the page reloads once per cooldown window. A mismatch inside the + * window means the reload landed on the same skew (a cached bundle, or several + * backend versions behind one load balancer), so a banner with a reload button + * shows instead and the page never loops. The app can take over first: a + * listener on the window's STATE_MISMATCH_WINDOW_EVENT that calls + * preventDefault() skips both. In dev a backend hot reload can reconnect + * before Vite serves the rebuilt bundle, so it only warns. + * @param info The backend's state schema hash and the reload cooldown in ms. + */ +const handleStateMismatch = (info) => { + const message = + "This page was built for another version of the app than the backend it " + + `connected to (state schema ${app.stateSchema}, backend ${info.backend}).`; + if (app.isDevMode) { + console.warn( + message + + " Reload the page if it stays out of date once the frontend rebuilds.", + ); + return; + } + console.warn(message); + const event = new CustomEvent(STATE_MISMATCH_WINDOW_EVENT, { + cancelable: true, + detail: { frontend: app.stateSchema, backend: info.backend }, + }); + if (!window.dispatchEvent(event)) { + return; + } + const last_reload = + parseInt(window.sessionStorage.getItem(LAST_RELOADED_KEY), 10) || 0; + if (Date.now() - last_reload > info.reload_cooldown_ms) { + reloadForNewVersion(); + return; + } + showNewVersionBanner(); +}; + +/** + * Connect to a websocket and set the handlers. + * @param socket The socket object to connect. + * @param dispatch The function to queue state update + * @param transports The transports to use. + * @param setConnectErrors The function to update connection error value. + * @param client_storage The client storage object from context.js + * @param navigate The navigate function from React Router + * @param params The params object from React Router + */ +export const connect = async ( + socket, + dispatch, + transports, + setConnectErrors, + client_storage = {}, + navigate, + params, +) => { + // Socket already allocated, just reconnect it if needed. + if (socket.current) { + if (!socket.current.connected) { + await socket.current.reconnect(); + } + return; + } + + // Get backend URL object from the endpoint. + const endpoint = getBackendURL(EVENTURL); + let bootRoute; + + // The hydrate event rides in the socket.io CONNECT packet, so the backend + // starts loading state as soon as the namespace connects instead of after + // an extra round trip for the connect acknowledgement. The keys are read by + // the backend as CompileVars.CONNECT_AUTH_EVENT and CONNECT_AUTH_STATE_SCHEMA; + // the state schema goes along on every (re)connect, since a reconnect can + // land on another backend version. + const bootAuth = (first) => (callback) => { + const boot_event = withRouterData(app.initialEvents(first)[0], params); + bootRoute = currentRouteKey(); + recordSentStorageValues(boot_event); + // Instrumentation hook (installed by reflex-otel): may add a traceparent. + window.__reflex_otel?.onEventSend?.(boot_event); + callback({ event: boot_event, state_schema: app.stateSchema }); + }; + + // Create the socket. A new session's token is saved here, once the app has + // mounted, even when a transport warmed up with it earlier. + socketStarted = true; + const session_token = getToken(); + if ( + warmSocket && + (warmSocket.io.opts.query.token !== session_token || + warmSocket.io.opts.transports.length !== transports.length || + transports.some( + (transport, i) => transport !== warmSocket.io.opts.transports[i], + )) + ) { + discardWarmSocket(); + } + socket.current = + warmSocket ?? createSocket(endpoint, transports, session_token); + warmSocket = null; + cancelWarmup(); + socket.current.wait_connect = false; + let firstConnect = true; + let finishBootstrap; + let reconnectingSession = false; + let sessionTimer; + // The abort controller of the exchange in progress, if any. + let sessionController; + let resolveSession; + let rejectSession; + let sessionFailures = 0; + // Whether the backend denied the exchange for this page's origin. + let sessionRejected = false; + const currentSocket = socket.current; + const requestSessionRefresh = () => { + window.clearTimeout(sessionTimer); + // A denied exchange gets the same answer until the backend reconnects. + if (sessionRejected) return; + if (socket.current === currentSocket && currentSocket.connected) { + currentSocket.emit(SESSION_REFRESH_EVENT); + } + }; + // Ask for a new credential once the wait has passed. A browser runs a timer + // over 2**31 - 1 ms with no delay, so the wait is capped. + const scheduleSessionRefresh = ( + wait = Number(window.localStorage.getItem(sessionRefreshStorageKey())) - + Date.now(), + ) => { + window.clearTimeout(sessionTimer); + if (wait > 0) { + sessionTimer = window.setTimeout( + requestSessionRefresh, + Math.min(wait, 2 ** 31 - 1), + ); + } else { + requestSessionRefresh(); + } + }; + const finishSessionExchange = () => { + resolveSession?.(); + resolveSession = rejectSession = undefined; + initialSessionExchange = undefined; + }; + const stopSessionExchange = (preserveReadiness = false) => { + window.clearTimeout(sessionTimer); + sessionController?.abort(); + sessionController = undefined; + if (!preserveReadiness) { + reconnectingSession = false; + rejectSession?.(new Error("Session connection closed")); + resolveSession = rejectSession = undefined; + initialSessionExchange = undefined; + } + }; + const releaseBootstrap = () => { + finishBootstrap?.(); + finishBootstrap = null; + }; + socket.current.releaseSessionBootstrap = () => { + stopSessionExchange(); + releaseBootstrap(); + }; + // Ensure undefined fields in events are sent as null instead of removed + socket.current.io.encoder.replacer = (k, v) => (v === undefined ? null : v); + // The server drops a transport whose frame exceeds the limit its handshake + // announced, so a CONNECT packet (type 0) that carries an oversized hydrate + // is reported instead of sent. The page stays offline until browser storage + // shrinks and it reloads: wait_connect stays set, so reconnect() does not + // rebuild the hydrate. + const { encoder } = socket.current.io; + const encode = encoder.encode.bind(encoder); + encoder.encode = (packet) => { + const encoded = encode(packet); + if (packet.type !== 0) { + return encoded; + } + // socket.io-client is pinned; test_hydration_storage.py covers these internals. + const { engine } = socket.current.io; + const transport = engine.transport.name; + // The Engine.IO message type ("4") prefixes the encoded packet. + const size = 1 + frameSize(encoded[0], transport); + if (size > engine._maxPayload) { + const unit = transport === "websocket" ? "characters" : "bytes"; + /** @type {Error & { code?: string }} */ + const error = new Error( + `Hydration payload (${size} ${unit}) exceeds the server limit (${engine._maxPayload} ${unit}). Reduce browser storage data and reload.`, + ); + error.code = ERROR_TYPE_HYDRATION_PAYLOAD_TOO_LARGE; + console.error(error.message); + setConnectErrors((errors) => [...errors.slice(-9), error]); + // No connect or disconnect event follows, so free the cold-tab lock here. + releaseBootstrap(); + socket.current.disconnect(); + return []; + } + return encoded; + }; + socket.current.io.decoder.tryParse = (str) => { + try { + return parseJson(str); + } catch { + return false; + } + }; + // Set up a reconnect helper function + socket.current.reconnect = async () => { + if ( + socket.current && + !socket.current.connected && + !socket.current.wait_connect + ) { + socket.current.wait_connect = true; + const current = socket.current; + const start = () => { + if (socket.current !== current) { + releaseBootstrap(); + return; + } + current.io.opts.query = { token: getToken() }; + current.auth = bootAuth(firstConnect); + current.connect(); + }; + const key = sessionStorageKey(); + if ( + window.navigator?.locks && + !( + Number(window.localStorage.getItem(sessionRefreshStorageKey())) > + Date.now() + ) + ) { + // Only cold tabs wait. The first socket hydrates while its in-band + // credential becomes a cookie; the next tab then shares that cookie. + window.navigator.locks + .request( + `${key}:session`, + () => + new Promise((resolve) => { + finishBootstrap = resolve; + start(); + }), + ) + .catch((error) => { + if (socket.current === current) retryConnect(error); + }); + } else { + start(); + } + } + }; + + function checkVisibility() { + if (!socket.current) { + // The socket was released without stopWatchingVisibility being called. + // Connecting here would open a socket nothing listens to any more. + document.removeEventListener("visibilitychange", checkVisibility); + return; + } + if (document.visibilityState === "visible") { + if (!socket.current.connected) { + console.log("Socket is disconnected, attempting to reconnect "); + socket.current.reconnect(); + } else if (!sessionController) { + // A timer that the browser suspended can be past its refresh time. + scheduleSessionRefresh(); + } + } + } + + const disconnectTrigger = (event) => { + if (socket.current?.connected) { + console.log("Disconnect websocket on page navigation"); + socket.current.disconnect(); + } + }; + + const pagehideHandler = (event) => { + if (!socket.current?.connected) { + return; + } + if (event.persisted) { + console.log("Disconnect backend before bfcache on navigation"); + } else { + console.log("Disconnect websocket on pagehide"); + } + socket.current.disconnect(); + }; + + // Unknown substates already reported on this connection. + const reported_missing_substates = new Set(); + // Failed connection attempts since the last connect, for the retry backoff. + let failed_attempts = 0; + // The scheduled retry of the last failed attempt. + let retry_timer; + + // Once the socket is open, hydrate the page. + socket.current.on("connect", async () => { + if (reconnectingSession) { + reconnectingSession = false; + if (!sessionController) finishSessionExchange(); + } + if (!sessionController) { + releaseBootstrap(); + // The backend can trust this origin after a restart with new settings. + sessionRejected = false; + scheduleSessionRefresh(); + } + firstConnect = false; + socket.current.wait_connect = false; + reported_missing_substates.clear(); + failed_attempts = 0; + window.clearTimeout(retry_timer); + retry_timer = undefined; + setConnectErrors([]); + window.__reflex_otel?.onSocketConnect?.(); + window.addEventListener("pagehide", pagehideHandler); + window.addEventListener("beforeunload", disconnectTrigger); + // The connection auth event already loads its route, and every queued + // on_load loads the route current when it is sent. Keep the last queued + // on_load, after every navigation's storage update, only if the route + // changed after the auth event was built. + let keepOnLoad = bootRoute !== currentRouteKey(); + for (let i = event_queue.length - 1; i >= 0; i--) { + if (event_queue[i].name !== app.on_load_internal_event) continue; + if (keepOnLoad) { + keepOnLoad = false; + } else { + event_queue.splice(i, 1); + } + } + // Drain any initial events from the queue. One call is the whole drain: + // processEvent goes on until the queue is empty, or until the socket has + // dropped again with a stateful event waiting. Looping on the queue length + // would spin in that second case, since nothing can shrink the queue then. + await processEvent(socket.current, navigate, params); + }); + + // Record a failed connection attempt and retry it with incremental backoff. + const retryConnect = (error) => { + releaseBootstrap(); + socket.current.wait_connect = false; + failed_attempts = Math.min(failed_attempts + 1, 10); + setConnectErrors((connectErrors) => [...connectErrors.slice(-9), error]); + window.clearTimeout(retry_timer); + retry_timer = window.setTimeout(() => { + retry_timer = undefined; + if (socket.current && !socket.current.connected) { + return socket.current.reconnect(); + } + }, 200 * failed_attempts); // Incremental backoff + }; + + socket.current.on("connect_error", retryConnect); + + socket.current.on("disconnect", (reason, details) => { + stopSessionExchange( + reconnectingSession && reason === "io client disconnect", + ); + releaseBootstrap(); + firstConnect = false; + // A transport closed before the namespace connected is a failed attempt, + // e.g. a CONNECT packet over the server or a proxy message size limit. + if (socket.current.wait_connect) { + retryConnect( + new Error(`connection closed before connecting (${reason})`), + ); + return; + } + // A transport error reports connect_error first, which scheduled the retry. + if (retry_timer !== undefined) { + return; + } + window.__reflex_otel?.onSocketDisconnect?.(reason); + const try_reconnect = + reason !== "io server disconnect" && reason !== "io client disconnect"; + window.removeEventListener("beforeunload", disconnectTrigger); + window.removeEventListener("pagehide", pagehideHandler); + if (try_reconnect) { + // Attempt to reconnect transient non-intentional disconnects. + socket.current.reconnect(); + } + }); + + // Report a failure to process a state update to the backend, so it surfaces + // in the terminal logs instead of only in the browser console. + const reportStateUpdateError = (error) => { + console.error("Error processing state update:", error); + socket.current?.emit(CLIENT_ERROR_EVENT, { + message: error?.message || String(error), + error_type: ERROR_TYPE_STATE_UPDATE, + }); + }; + + // Warn about unknown substates and surface them in the backend terminal + // logs, once per substate per connection. + const reportUnknownSubstates = (substates) => { + const unreported = substates.filter( + (substate) => !reported_missing_substates.has(substate), + ); + if (unreported.length === 0) { + return; + } + for (const substate of unreported) { + reported_missing_substates.add(substate); + } + const errorMsg = `Skipping state update for unknown substate(s): no dispatch function for "${unreported.join( + '", "', + )}". Try refreshing the page or clearing your browser cache. This usually indicates a mismatch between frontend and backend state definitions. If you are the developer of this app, rebuild the frontend and check that api_url is correct.`; + console.warn(errorMsg); + socket.current.emit(CLIENT_ERROR_EVENT, { + message: errorMsg, + substate: unreported.join(", "), + error_type: ERROR_TYPE_DISPATCH_MISSING, + }); + }; + + // Drop and report substates without a dispatch function. Only a mismatched + // delta is copied; the received update is not mutated. + const withoutUnknownSubstates = (delta) => { + let unknown; + for (const substate in delta) { + if (typeof dispatch[substate] !== "function") { + unknown ??= []; + unknown.push(substate); + } + } + if (unknown === undefined) { + return delta; + } + reportUnknownSubstates(unknown); + const known = { ...delta }; + for (const substate of unknown) { + delete known[substate]; + } + return known; + }; + + // On each received message, queue the updates and events. + socket.current.on("event", (update) => { + // Skip unknown substates in both reducer and client-storage updates. + const delta = withoutUnknownSubstates(update.delta); + try { + if (delta) { + for (const substate in delta) { + dispatch[substate](delta[substate]); + } + applyClientStorageDelta(client_storage, delta); + } + if (update.events && update.events.length > 0) { + queueEvents(update.events, socket, false, navigate, params).catch( + reportStateUpdateError, + ); + } + } catch (error) { + reportStateUpdateError(error); + } + }); + socket.current.on("new_token", async (new_token) => { + setToken(new_token); + }); + socket.current.on(SESSION_REFRESH_EVENT, requestSessionRefresh); + socket.current.on("session_token", async (sessionCredential) => { + if (sessionController) return; + const controller = new AbortController(); + sessionController = controller; + window.clearTimeout(sessionTimer); + // HTTP calls wait while a credential from the socket is exchanged for + // the cookie. After a lasting failure the retries go on, but they hold + // nothing. + if (!resolveSession && sessionCredential && sessionFailures < 3) { + initialSessionExchange = new Promise((resolve, reject) => { + resolveSession = resolve; + rejectSession = reject; + }); + // Readiness may have no HTTP consumer when the connection closes. + initialSessionExchange.catch(() => {}); + } + try { + const previousToken = getToken(); + const session = await ensureSession(sessionCredential, controller); + if (sessionController !== controller) return; + setToken(session.client_token); + const refreshDelay = + (session.refresh_in ?? session.expires_in / 2) * 1000; + sessionRejected = false; + try { + window.localStorage.setItem( + sessionRefreshStorageKey(), + String(Date.now() + refreshDelay), + ); + } catch { + // The cookie is set; the refresh time is only a hint for later loads. + } + sessionFailures = 0; + setConnectErrors([]); + scheduleSessionRefresh(refreshDelay); + if (currentSocket.connected && getToken() !== previousToken) { + // Keep waiting HTTP calls queued until this cookie's socket is accepted. + reconnectingSession = true; + currentSocket.disconnect(); + await currentSocket.reconnect(); + } else { + finishSessionExchange(); + } + } catch (error) { + if (sessionController !== controller) return; + window.localStorage.removeItem(sessionRefreshStorageKey()); + if (error.status === 403) { + // The backend does not trust this page's origin, so a retry gets the + // same answer. The socket works without the cookie: release HTTP calls. + console.error( + `${error.message}. The backend does not trust the origin ${window.location.origin}; ` + + "add it to deploy_url or cors_allowed_origins to persist the browser session.", + ); + sessionRejected = true; + finishSessionExchange(); + return; + } + setConnectErrors((errors) => [...errors.slice(-9), error]); + // Retry on the live socket after one second, backing off to thirty seconds. + // Each attempt requests a fresh credential, including after cookie expiry. + const delay = Math.min(30000, 1000 * 2 ** Math.min(sessionFailures++, 5)); + sessionTimer = window.setTimeout(requestSessionRefresh, delay); + // A failure that lasts is not transient, for example a proxy that does + // not forward this route. Stop holding HTTP calls; the retry goes on. + if (sessionFailures >= 3) finishSessionExchange(); + } finally { + if (sessionController === controller) { + sessionController = undefined; + releaseBootstrap(); + } + } + }); + + socket.current.on(STATE_MISMATCH_EVENT, handleStateMismatch); + + document.addEventListener("visibilitychange", checkVisibility); + // Called by whoever releases the socket: the listener lives on the document, + // so it would otherwise outlive the socket and everything it closes over. + socket.current.stopWatchingVisibility = () => + document.removeEventListener("visibilitychange", checkVisibility); + await socket.current.reconnect(); +}; + +/** + * Package client-side storage values as payload to send to the + * backend with the hydrate event + * @param client_storage The client storage object from context.js + * @returns payload dict of client storage values + */ +export const hydrateClientStorage = (client_storage) => { + const client_storage_values = {}; + if (client_storage.cookies) { + for (const state_key in client_storage.cookies) { + const cookie_options = client_storage.cookies[state_key]; + const cookie_name = cookie_options.name || state_key; + const cookie_value = cookies.get(cookie_name, { doNotParse: true }); + if (cookie_value !== undefined) { + client_storage_values[state_key] = cookie_value; + } + } + } + if (client_storage.local_storage && typeof window !== "undefined") { + for (const state_key in client_storage.local_storage) { + const options = client_storage.local_storage[state_key]; + const local_storage_value = localStorage.getItem( + options.name || state_key, + ); + if (local_storage_value !== null) { + client_storage_values[state_key] = local_storage_value; + } + } + } + if (client_storage.session_storage && typeof window !== "undefined") { + for (const state_key in client_storage.session_storage) { + const session_options = client_storage.session_storage[state_key]; + const session_storage_value = sessionStorage.getItem( + session_options.name || state_key, + ); + if (session_storage_value != null) { + client_storage_values[state_key] = session_storage_value; + } + } + } + if ( + client_storage.cookies || + client_storage.local_storage || + client_storage.session_storage + ) { + return client_storage_values; + } + return {}; +}; + +/** + * Remember the synced localStorage values an event sends, to recognise their echoes. + * + * Only synced vars: the tab sends another tab's newer value only for those. + * @param event The event about to be sent. + */ +const recordSentStorageValues = (event) => { + // ReflexEvent leaves out an empty payload. + const vars = event.payload?.vars; + if ( + vars === undefined || + (event.name !== `${app.state_name}.hydrate_and_load` && + event.name !== `${app.state_name}.${UPDATE_VARS_INTERNAL}`) + ) { + return; + } + const local_storage = app.clientStorage.local_storage; + for (const [state_key, value] of Object.entries(vars)) { + if (!local_storage?.[state_key]?.sync) { + continue; + } + const sent = (sentStorageValues[state_key] ??= []); + sent.push({ value, writes: localStorageWrites }); + if (sent.length > MAX_SENT_STORAGE_VALUES) { + sent.shift(); + } + } +}; + +/** + * Take the sent value that a backend value echoes, and the older ones with it. + * @param state_key The state key of the browser storage var. + * @param value The value the backend sent for it. + * @returns The sent value's entry, or undefined if the value is no echo. + */ +const takeEcho = (state_key, value) => { + const sent = sentStorageValues[state_key]; + const index = sent?.findIndex((entry) => entry.value === value) ?? -1; + // Older values were echoed already, or changed by an override on the way. + return index === -1 ? undefined : sent.splice(0, index + 1)[index]; +}; + +/** + * Update client storage values based on backend state delta. + * @param client_storage The client storage object from context.js + * @param delta The state update from the backend + */ +const applyClientStorageDelta = (client_storage, delta) => { + // find the main state and check for is_hydrated + const unqualified_states = Object.keys(delta).filter( + (key) => key.split(".").length === 1, + ); + if (unqualified_states.length === 1) { + const main_state = delta[unqualified_states[0]]; + if ( + main_state.is_hydrated_rx_state_ !== undefined && + !main_state.is_hydrated_rx_state_ + ) { + // skip if the state is not hydrated yet, since all client storage + // values are sent in the hydrate event + return; + } + } + // Save known client storage values to cookies and localStorage. + for (const substate in delta) { + for (const key in delta[substate]) { + const state_key = `${substate}.${key}`; + const value = delta[substate][key]; + if (client_storage.cookies && state_key in client_storage.cookies) { + const cookie_options = { ...client_storage.cookies[state_key] }; + const cookie_name = cookie_options.name || state_key; + delete cookie_options.name; // name is not a valid cookie option + cookies.set(cookie_name, value, cookie_options); + } else if ( + client_storage.local_storage && + state_key in client_storage.local_storage && + typeof window !== "undefined" + ) { + const name = client_storage.local_storage[state_key].name || state_key; + const echo = takeEcho(state_key, value); + const last = lastLocalStorageWrites[name]; + // Write an echo only over this tab's own later write, which the backend + // applied before the echoed event. Otherwise storage holds the sent + // value or another tab's newer one. + if ( + !echo || + (last?.writes > echo.writes && + localStorage.getItem(name) === last.value) + ) { + localStorage.setItem(name, value); + lastLocalStorageWrites[name] = { + value, + writes: ++localStorageWrites, + }; + } + } else if ( + client_storage.session_storage && + state_key in client_storage.session_storage && + typeof window !== "undefined" + ) { + const session_options = client_storage.session_storage[state_key]; + sessionStorage.setItem(session_options.name || state_key, value); + } + } + } +}; + +/** + * Establish websocket event loop for a React Router page. + * @param dispatch The reducer dispatch function to update state. + * @param initial_events The initial app events. + * @param client_storage The client storage object from context.js + * + * @returns [addEvents, connectErrors] - + * addEvents is used to queue an event, and + * connectErrors is an array of reactive js error from the websocket connection (or null if connected). + */ +export const useEventLoop = ( + dispatch, + initial_events = () => [], + client_storage = {}, +) => { + const socket = useRef(null); + const [navigate, params, location] = useEventRoute(); + const prevLocationRef = useRef(location); + const [searchParams] = useSearchParams(); + const [connectErrors, setConnectErrors] = useState([]); + const mounted = useRef(false); + + const ensureSocketConnected = useCallback(async () => { + if (!mounted.current) { + // During hot reload, some components may still have a reference to + // addEvents, so avoid reconnecting the socket of an unmounted event loop. + return; + } + try { + // only use websockets if state is present and backend is not disabled (reflex cloud). + if ( + Object.keys(app.initialState).length > 1 && + !isBackendDisabled() && + !socket.current?.connected + ) { + // Initialize the websocket connection. + await connect( + socket, + dispatch, + [env.TRANSPORT], + setConnectErrors, + client_storage, + navigate, + params, + ); + } + } catch (error) { + // A connection that cannot even be attempted (the browser blocks the + // storage that holds the token, say) is a connection error like any + // other. It must not reject: callers do not await this, and the handler + // for unhandled rejections reports through addEvents, which calls back + // into here and would fail the same way, forever. + setConnectErrors((errors) => [...errors.slice(-9), error]); + } + }, [ + socket, + dispatch, + setConnectErrors, + client_storage, + navigate, + params, + mounted, + ]); + + // Function to add new events to the event queue. + const addEvents = useCallback((events, args, event_actions) => { + const _events = normalizeEvents(events); + + event_actions = Object.assign( + {}, + event_actions, + ..._events.map((e) => e.event_actions), + ); + + if (!event_actions?.temporal) { + // Reconnect socket if needed for non-temporal events. + void ensureSocketConnected(); + } + + return applyEventActions( + () => queueEvents(_events, socket, false, navigate, params), + event_actions, + args, + _events.map((e) => e.name).join("+++"), + () => !!socket.current?.connected, + ); + }, []); + + // Handle frontend errors and send them to the backend via websocket. + useEffect(() => { + if (typeof window === "undefined") { + return; + } + + window.onerror = function (msg, url, lineNo, columnNo, error) { + addEvents([ + ReflexEvent(`${app.exception_state_name}.handle_frontend_exception`, { + // Some error events (e.g. a ResizeObserver loop) have no Error object. + info: error + ? error.name + ": " + error.message + "\n" + error.stack + : msg + "\n at " + url + ":" + lineNo + ":" + columnNo, + component_stack: "", + }), + ]); + return false; + }; + + //NOTE: Only works in Chrome v49+ + //https://github.com/mknichel/javascript-errors?tab=readme-ov-file#promise-rejection-events + window.onunhandledrejection = function (event) { + addEvents([ + ReflexEvent(`${app.exception_state_name}.handle_frontend_exception`, { + info: + event.reason?.name + + ": " + + event.reason?.message + + "\n" + + event.reason?.stack, + component_stack: "", + }), + ]); + return false; + }; + }, []); + + // Handle socket connect/disconnect. + useEffect(() => { + // Initialize the websocket connection. + mounted.current = true; + void ensureSocketConnected(); + + // Cleanup function. + return () => { + mounted.current = false; + if (socket.current) { + socket.current.releaseSessionBootstrap?.(); + socket.current.disconnect(); + socket.current.off(); + socket.current.stopWatchingVisibility(); + socket.current = null; + } + }; + }, []); + + // Main event loop. + useEffect(() => { + // Skip if the backend is disabled + if (isBackendDisabled() || !socket.current || !socket.current.connected) { + return; + } + void (async () => { + // Process all outstanding events. processEvent drains the queue itself, + // and stops at a stateful event when the socket has dropped; the connect + // handler sends what is left once it is back. + if (event_queue.length > 0) { + await ensureSocketConnected(); + await processEvent(socket.current, navigate, params); + } + })(); + }); + + // localStorage event handling + useEffect(() => { + // A Map, so a storage name like "constructor" is not an inherited property. + const storage_to_state_map = new Map(); + + if (client_storage.local_storage && typeof window !== "undefined") { + for (const state_key in client_storage.local_storage) { + const options = client_storage.local_storage[state_key]; + if (options.sync) { + const local_storage_value_key = options.name || state_key; + // Several vars can share one storage name; sync all of them. + const state_keys = storage_to_state_map.get(local_storage_value_key); + if (state_keys) { + state_keys.push(state_key); + } else { + storage_to_state_map.set(local_storage_value_key, [state_key]); + } + } + } + } + + // e is StorageEvent + const handleStorage = (e) => { + // Session storage changes in same-origin frames raise storage events too. + if (e.storageArea !== localStorage) { + return; + } + // A clear() event has no key and affects every synced storage name. + const entries = + e.key === null + ? storage_to_state_map.entries() + : [[e.key, storage_to_state_map.get(e.key)]]; + const events = []; + for (const [key, state_keys] of entries) { + if (state_keys) { + // Read the value when sent, just like individual-key updates. + events.push(ReflexEvent(SYNC_LOCAL_STORAGE, { key, state_keys })); + } + } + if (events.length) { + addEvents(events, e); + } + }; + + window.addEventListener("storage", handleStorage); + return () => window.removeEventListener("storage", handleStorage); + }); + + const handleNavigationEvents = useRef(false); + // Route after the initial page hydration + useEffect(() => { + // The first time this effect runs is initial load, so don't handle + // any navigation events. + if (!handleNavigationEvents.current) { + handleNavigationEvents.current = true; + return; + } + if (location.state?.fromNotFound) { + // If the redirect is from a 404 page, we skip onLoadInternalEvent, + // since it was already run when the 404 page was first rendered. + return; + } + // This will run when the location changes + if ( + location.pathname + location.search === + prevLocationRef.current.pathname + prevLocationRef.current.search + ) { + if (location.hash) { + // If the hash is the same, we don't need to do anything. + return; + } + } + + // Equivalent to routeChangeStart - runs when navigation begins + const main_state_dispatch = dispatch["reflex___state____state"]; + if (main_state_dispatch !== undefined) { + main_state_dispatch({ is_hydrated_rx_state_: false }); + } + + // Equivalent to routeChangeComplete - runs after navigation completes + addEvents(app.onLoadInternalEvent()); + + // Update the ref + prevLocationRef.current = location; + }, [location, dispatch, addEvents]); + + return [addEvents, connectErrors]; +}; + +// utils/state.js reaches these through the registry: it cannot import this +// module, which an app without state leaves out of its bundle. +Object.assign(backend, { + connect, + getToken, + hydrateClientStorage, + sendEvent, + useEventLoop, + waitForSession, +}); diff --git a/packages/reflex-frontend/src/utils/state.js b/packages/reflex-frontend/src/utils/state.js index afce90ccda9..a6693ce446d 100644 --- a/packages/reflex-frontend/src/utils/state.js +++ b/packages/reflex-frontend/src/utils/state.js @@ -1,16 +1,18 @@ -// State management for Reflex web apps. -import io from "socket.io-client"; +// What every Reflex web app runs on: refs, the event queue and the events the +// browser handles by itself, and the python-semantics helpers compiled code +// calls. The connection to the backend is in utils/socket.js, which only an +// app with state bundles. import { mergician } from "mergician"; import env from "$/env.json"; -import Cookies from "universal-cookie"; -import { useCallback, useEffect, useRef, useState } from "react"; -import { - useLocation, - useNavigate, - useSearchParams, - useParams, -} from "react-router"; +import { useCallback, useRef } from "react"; import { app, eventLoop } from "$/utils/context-registry"; +import { + SYNC_LOCAL_STORAGE, + backend, + event_queue, + normalizeEvents, + useEventRoute, +} from "$/utils/event_loop"; // This module's own exports, passed to server-provided scripts by runScript. import * as stateExports from "$/utils/state"; import { @@ -20,7 +22,6 @@ import { setClientState, } from "$/utils/client_state"; import debounce from "$/utils/helpers/debounce"; -import { parseJson } from "$/utils/helpers/json"; import throttle from "$/utils/helpers/throttle"; import { uploadFiles } from "$/utils/helpers/upload"; @@ -28,45 +29,11 @@ import { uploadFiles } from "$/utils/helpers/upload"; // the server-provided scripts runScript evaluates can call them too. export { getClientState, setClientState }; -// Endpoint URLs. -const EVENTURL = env.EVENT; - -// Socket event names (must match reflex_base/constants/event.py SocketEvent) -const CLIENT_ERROR_EVENT = "client_error"; -const STATE_MISMATCH_EVENT = "state_mismatch"; -const SESSION_REFRESH_EVENT = "session_refresh"; - -// sessionStorage key with the time of the last automatic reload (must match -// LAST_RELOADED_KEY in reflex/state.py: the reload on a frontend error and the -// reload on a state mismatch share one cooldown, so neither can loop). -const LAST_RELOADED_KEY = "reflex_last_reloaded_on_error"; - -// The id of the banner offering a reload when one already happened recently. -const NEW_VERSION_BANNER_ID = "reflex-new-version-banner"; - -// The cancelable window event dispatched before a prod page acts on a state -// mismatch; a listener calling preventDefault() handles the mismatch instead. -const STATE_MISMATCH_WINDOW_EVENT = "reflex:state-mismatch"; - -// Client error types (must match reflex_base/constants/event.py ClientErrorType) -const ERROR_TYPE_DISPATCH_MISSING = "dispatch_function_missing"; -const ERROR_TYPE_STATE_UPDATE = "state_update_processing_error"; -const ERROR_TYPE_HYDRATION_PAYLOAD_TOO_LARGE = "hydration_payload_too_large"; - // These hostnames indicate that the backend and frontend are reachable via the same domain. // They are compared with URL.hostname, which gives an IPv6 address in brackets // and in its shortest form: "[::]" is every spelling of the IPv6 wildcard. const SAME_DOMAIN_HOSTNAMES = ["localhost", "0.0.0.0", "[::]"]; -// Global variable to hold the token. -let token; - -// Share cookie exchange and refresh requests in this tab. -let initialSessionExchange; - -// create cookie instance -const cookies = new Cookies(); - // Dictionary holding component references. Internal: not covered by any // compatibility guarantee. Framework vars reach it through `Var._as_ref()`, // whose var data imports `refs`. It is also published as a global, only so @@ -93,37 +60,6 @@ if (typeof document !== "undefined") { refs[CLIENT_STATE_REF] = getClientStore(); } -// Array holding pending events to be processed. -const event_queue = []; - -// The event that sends browser storage values to the backend. -const UPDATE_VARS_INTERNAL = - "reflex___state____update_vars_internal_state.update_vars_internal"; -// A frontend event naming one synced localStorage var, turned into an -// UPDATE_VARS_INTERNAL event when it is sent: see syncLocalStorageEvent. -const SYNC_LOCAL_STORAGE = "_sync_local_storage"; - -// Synced localStorage values sent to the backend and not yet echoed back, by -// state key, oldest first, with this tab's localStorage write count at the send. -const sentStorageValues = {}; -// Bounds a key whose echoes a get_delta override changes, so they never match. -const MAX_SENT_STORAGE_VALUES = 256; -// This tab's localStorage write count, and its last write by storage name -// (vars of different state keys may share one). -let localStorageWrites = 0; -const lastLocalStorageWrites = {}; - -// Mirrors the data router's location so applyEvent can populate router_data -// with the in-widget URL. In embed mode the host page's window.location is -// unrelated to the Reflex route, so the backend's on_load and dynamic-route -// matching rely on this ref instead. Updated by useEventLoop once mounted; -// pre-seeded in embed mode with the memory router's initial path (see -// initialEntries in entry.client.embed.js) so events dispatched before the -// first effect commit don't briefly fall back to the host page's URL. -const locationRef = { - current: env.MOUNT_TARGET ? { pathname: "/", search: "", hash: "" } : null, -}; - /** * Generate a UUID for component identifiers. * Taken from: https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid @@ -145,30 +81,6 @@ export const generateUUID = () => { }); }; -/** - * Get the token for the current session. - * @returns The token. - */ -export const getToken = () => { - if (token) { - return token; - } - if (typeof window !== "undefined") { - token = - window.sessionStorage.getItem(clientTokenStorageKey()) || - window.sessionStorage.getItem(LEGACY_TOKEN_STORAGE_KEY) || - ""; - } - return token || ""; -}; - -/** Get the saved client token to warm the transport before the app mounts. */ -const peekToken = () => - token || - window.sessionStorage.getItem(clientTokenStorageKey()) || - window.sessionStorage.getItem(LEGACY_TOKEN_STORAGE_KEY) || - ""; - /** * Get the URL for the backend server * @param url_str The URL string to parse. @@ -199,68 +111,6 @@ export const getBackendURL = (url_str) => { return endpoint; }; -/** Namespace browser state by the backend URL, including its port and path. */ -const sessionStorageKey = () => `reflex:${getBackendURL(EVENTURL).href}`; -const LEGACY_TOKEN_STORAGE_KEY = "token"; -const clientTokenStorageKey = () => `${sessionStorageKey()}:token`; -const sessionRefreshStorageKey = () => `${sessionStorageKey()}:expires_at`; - -/** Store only the non-secret tab routing token in JavaScript-accessible storage. */ -const setToken = (value) => { - token = value; - window.sessionStorage.setItem(clientTokenStorageKey(), value); -}; - -/** Wait until credentialed HTTP calls can use the initial session cookie. */ -export const waitForSession = async () => { - await initialSessionExchange; -}; - -/** Exchange an in-band credential or refresh the HTTP-only session cookie. */ -const ensureSession = async (sessionCredential, controller) => { - const endpoint = getBackendURL(EVENTURL); - endpoint.protocol = endpoint.protocol === "wss:" ? "https:" : "http:"; - endpoint.pathname = endpoint.pathname.replace( - /\/_event\/?$/, - "/_reflex/session", - ); - endpoint.search = ""; - const headers = { "Content-Type": "application/json" }; - const previousToken = getToken(); - if (previousToken) headers["Reflex-Client-Token"] = previousToken; - // Abort a stalled cookie exchange after ten seconds. - const timeout = window.setTimeout(() => controller.abort(), 10000); - try { - const response = await window.fetch(endpoint.href, { - method: "POST", - credentials: "include", - headers, - body: JSON.stringify( - sessionCredential ? { session_token: sessionCredential } : {}, - ), - signal: controller.signal, - }); - if (!response.ok) { - /** @type {Error & { status?: number }} */ - const error = new Error(`Session request failed: ${response.status}`); - error.status = response.status; - throw error; - } - const session = await response.json(); - if ( - typeof session.client_token !== "string" || - !session.client_token || - !Number.isFinite(session.expires_in) || - session.expires_in <= 0 - ) { - throw new Error("Invalid session response"); - } - return session; - } finally { - window.clearTimeout(timeout); - } -}; - /** * Check if the backend is disabled. * @@ -274,102 +124,71 @@ export const isBackendDisabled = () => { }; /** - * Create a socket without starting its namespace or hydration events. - * @param endpoint The backend URL. - * @param transports The configured transports. - * @param token The session token the backend links the connection to. - * @returns The disconnected socket. - */ -const createSocket = (endpoint, transports, token) => - io(endpoint.href, { - path: endpoint.pathname, - transports, - protocols: [env.REFLEX_VERSION], - autoUnref: false, - autoConnect: false, - withCredentials: true, - query: { token }, - reconnection: false, - }); - -/** - * Measure encoded text the way the Engine.IO server limits a frame. - * @param frame The encoded text. - * @param transport The transport that carries it. - * @returns The code points for a websocket text frame, or the UTF-8 bytes for a polling body. + * Get the token for the current session. + * @returns The token, or an empty string in an app without state. */ -const frameSize = (frame, transport) => { - if (transport !== "websocket") { - return new TextEncoder().encode(frame).byteLength; - } - let size = 0; - for (const _ of frame) size++; - return size; -}; - -let warmSocket = null; -let cancelWarmup = () => {}; -let socketStarted = false; +export const getToken = () => backend.getToken?.() ?? ""; -/** Close an unclaimed transport and remove its cleanup handlers. */ -const discardWarmSocket = () => { - const socket = warmSocket; - warmSocket = null; - cancelWarmup(); - socket?.disconnect(); +/** Wait until credentialed HTTP calls can use the initial session cookie. */ +export const waitForSession = async () => { + await backend.waitForSession?.(); }; -// Start only the transport while React is still preparing to mount. The -// namespace stays disconnected until connect() installs all its handlers. -// Defer past module evaluation because context.js imports this module too. -if (typeof window !== "undefined") { - queueMicrotask(() => { - if ( - socketStarted || - Object.keys(app.initialState ?? {}).length <= 1 || - isBackendDisabled() || - document.visibilityState === "hidden" - ) { - return; - } - try { - // A cold transport would capture cookies before the shared session lock. - if ( - !( - Number(window.localStorage.getItem(sessionRefreshStorageKey())) > - Date.now() - ) - ) { - return; - } - warmSocket = createSocket( - getBackendURL(EVENTURL), - [env.TRANSPORT], - peekToken(), +/** + * Call a function of the backend connection, which an app without state lacks. + * @param name The name utils/socket.js registers the function under. + * @returns The function, failing with a reason when the app has no state. + */ +const fromBackend = + (name) => + (...args) => { + if (!backend[name]) { + throw new Error( + `${name} needs the connection to the backend, which an app without state does not load.`, ); - } catch { - // Speculative setup may fail (for example, blocked session storage). - // The normal connection path will report failures when the app mounts. - return; } - const timeout = setTimeout(discardWarmSocket, 10000); - window.addEventListener("pagehide", discardWarmSocket); - cancelWarmup = () => { - clearTimeout(timeout); - window.removeEventListener("pagehide", discardWarmSocket); - }; - warmSocket.io.open((error) => { - if (error) discardWarmSocket(); - }); - }); -} + return backend[name](...args); + }; -if (import.meta.hot) { - import.meta.hot.dispose(() => { - socketStarted = true; - discardWarmSocket(); - }); -} +/** + * Connect to a websocket and set the handlers. + * @param socket The socket object to connect. + * @param dispatch The function to queue state update + * @param transports The transports to use. + * @param setConnectErrors The function to update connection error value. + * @param client_storage The client storage object from context.js + * @param navigate The navigate function from React Router + * @param params The params object from React Router + */ +export const connect = fromBackend("connect"); + +/** + * Package client-side storage values as payload to send to the + * backend with the hydrate event + * @param client_storage The client storage object from context.js + * @returns payload dict of client storage values + */ +export const hydrateClientStorage = fromBackend("hydrateClientStorage"); + +/** + * Remove a cookie. + * @param name The name of the cookie. + * @param options The domain, path and flags the cookie was set with. + */ +const removeCookie = (name, options = {}) => { + let cookie = `${name}=; Max-Age=0`; + if (options.domain) cookie += `; Domain=${options.domain}`; + if (options.path) cookie += `; Path=${options.path}`; + cookie += "; Expires=Thu, 01 Jan 1970 00:00:00 GMT"; + if (options.secure) cookie += "; Secure"; + if (options.partitioned) cookie += "; Partitioned"; + if (options.sameSite) { + const sameSite = options.sameSite === true ? "strict" : options.sameSite; + cookie += `; SameSite=${sameSite[0].toUpperCase()}${sameSite.slice(1).toLowerCase()}`; + } + // biome-ignore lint/suspicious/noDocumentCookie: the Cookie Store API is asynchronous, and not in every browser. + document.cookie = cookie; +}; /** * Determine if any event in the event queue is stateful. @@ -388,28 +207,6 @@ export const isStateful = () => { ); }; -/** Append nested events to an output array in depth-first order. */ -const appendEvents = (events, normalized) => { - for (const event of events) { - if (Array.isArray(event)) { - appendEvents(event, normalized); - } else if (event !== undefined && event !== null) { - normalized.push(event); - } - } -}; - -/** - * Flatten event lists and discard empty event values. - * @param events Events or nested event lists. - * @returns A flat array of events in depth-first order. - */ -const normalizeEvents = (events) => { - const normalized = []; - appendEvents(events, normalized); - return normalized; -}; - /** * Whether a value is a plain object (not an array, Date or class instance). * @param value The value to check. @@ -619,7 +416,7 @@ const runScript = (code, addEvents, socket, navigate, params) => { socket, navigate, params, - token, + backend.getToken?.(), code, ); }; @@ -659,38 +456,6 @@ const applyResultCallback = async ( callback(final_result); }; -/** - * Build the update_vars_internal event for a synced localStorage var. - * - * The value is read when the event is sent, so it and the write count recorded - * with it come from the same moment. - * @param payload The storage name and the state keys of the vars that use it. - * @returns The update_vars_internal event. - */ -const syncLocalStorageEvent = ({ key, state_keys }) => { - const value = localStorage.getItem(key); - return ReflexEvent(`${app.state_name}.${UPDATE_VARS_INTERNAL}`, { - vars: Object.fromEntries( - state_keys.map((state_key) => [ - state_key, - value ?? storageDefault(state_key), - ]), - ), - }); -}; - -/** - * Get the compiled default of a browser storage var. - * - * A removed storage key resets its vars to their defaults, as a page load does. - * @param state_key The state key of the browser storage var. - * @returns The default value. - */ -const storageDefault = (state_key) => { - const dot = state_key.lastIndexOf("."); - return app.initialState[state_key.slice(0, dot)][state_key.slice(dot + 1)]; -}; - /** * Handle frontend event or send the event to the backend via Websocket. * @param event The event to send. @@ -735,7 +500,7 @@ export const applyEvent = async (event, socket, navigate, params) => { } if (event.name === "_remove_cookie") { - cookies.remove(event.payload.key, { ...event.payload.options }); + removeCookie(event.payload.key, event.payload.options); void queueEventIfSocketExists( app.initialEvents(), socket, @@ -922,60 +687,8 @@ export const applyEvent = async (event, socket, navigate, params) => { // Send the event to the server. if (socket) { - const routed_event = withRouterData( - event.name === SYNC_LOCAL_STORAGE - ? syncLocalStorageEvent(event.payload) - : event, - params, - ); - recordSentStorageValues(routed_event); - // Instrumentation hook (installed by reflex-otel): may add a traceparent. - window.__reflex_otel?.onEventSend?.(routed_event); - socket.emit("event", encodeFormDataArgs(routed_event)); - } -}; - -/** - * Fill in the event's router data from the current location, if missing. - * @param event The event to send. - * @param params The params object from useParams - * @returns The same event, with router_data populated. - */ -const withRouterData = (event, params) => { - if ( - event.router_data === undefined || - Object.keys(event.router_data).length === 0 - ) { - const loc = locationRef.current ?? window.location; - // React Router's location (mirrored in locationRef) does not observe direct - // window.history.pushState/replaceState calls (e.g. via rx.call_script), so - // read the live query string and hash to keep router_data in sync. The - // pathname stays basename-relative (from React Router) so the backend's - // frontend_path prefix is not applied twice. In embed mode the host page's - // window.location is unrelated to the in-widget memory router, so use the - // mirrored location there. - const liveLoc = env.MOUNT_TARGET ? loc : window.location; - const search = liveLoc.search ?? ""; - const hash = liveLoc.hash ?? ""; - event.router_data = { - pathname: loc.pathname, - asPath: loc.pathname + search + hash, - }; - const query = { - ...Object.fromEntries(new URLSearchParams(search)), - ...params.current, - }; - if (query && Object.keys(query).length > 0) { - event.router_data.query = query; - } + backend.sendEvent(event, socket, params); } - return event; -}; - -const currentRouteKey = () => { - const loc = locationRef.current ?? window.location; - const liveLoc = env.MOUNT_TARGET ? loc : window.location; - return loc.pathname + (liveLoc.search ?? ""); }; /** @@ -1081,589 +794,6 @@ export const processEvent = async (socket, navigate, params) => { } }; -/** - * Reload the page for a new version of the app, restarting the reload cooldown. - */ -const reloadForNewVersion = () => { - window.sessionStorage.setItem(LAST_RELOADED_KEY, Date.now().toString()); - window.location.reload(); -}; - -/** - * Show a banner saying a new version is available, with a reload button. - * - * Plain DOM rather than a React component: it must show whatever the app - * renders, and stay up while the page keeps working as well as it can. - */ -const showNewVersionBanner = () => { - if (document.getElementById(NEW_VERSION_BANNER_ID)) { - return; - } - const banner = document.createElement("div"); - banner.id = NEW_VERSION_BANNER_ID; - banner.setAttribute("role", "alert"); - banner.style.cssText = - "position:fixed;top:0;left:0;right:0;z-index:2147483647;display:flex;" + - "justify-content:center;align-items:center;gap:1rem;padding:0.5rem 1rem;" + - "background:#1c2024;color:#fff;font:1rem system-ui,sans-serif;"; - banner.append("A new version of this app is available."); - const button = document.createElement("button"); - button.textContent = "Reload"; - button.style.cssText = - "padding:0.25rem 0.75rem;border:1px solid #fff;border-radius:4px;" + - "background:transparent;color:inherit;font:inherit;cursor:pointer;"; - button.onclick = reloadForNewVersion; - banner.append(button); - document.body.append(banner); -}; - -/** - * Handle the backend reporting that this bundle was compiled for another - * state tree than the one it runs (sent on connect, see EventNamespace.on_connect). - * - * In prod the page reloads once per cooldown window. A mismatch inside the - * window means the reload landed on the same skew (a cached bundle, or several - * backend versions behind one load balancer), so a banner with a reload button - * shows instead and the page never loops. The app can take over first: a - * listener on the window's STATE_MISMATCH_WINDOW_EVENT that calls - * preventDefault() skips both. In dev a backend hot reload can reconnect - * before Vite serves the rebuilt bundle, so it only warns. - * @param info The backend's state schema hash and the reload cooldown in ms. - */ -const handleStateMismatch = (info) => { - const message = - "This page was built for another version of the app than the backend it " + - `connected to (state schema ${app.stateSchema}, backend ${info.backend}).`; - if (app.isDevMode) { - console.warn( - message + - " Reload the page if it stays out of date once the frontend rebuilds.", - ); - return; - } - console.warn(message); - const event = new CustomEvent(STATE_MISMATCH_WINDOW_EVENT, { - cancelable: true, - detail: { frontend: app.stateSchema, backend: info.backend }, - }); - if (!window.dispatchEvent(event)) { - return; - } - const last_reload = - parseInt(window.sessionStorage.getItem(LAST_RELOADED_KEY), 10) || 0; - if (Date.now() - last_reload > info.reload_cooldown_ms) { - reloadForNewVersion(); - return; - } - showNewVersionBanner(); -}; - -/** - * Connect to a websocket and set the handlers. - * @param socket The socket object to connect. - * @param dispatch The function to queue state update - * @param transports The transports to use. - * @param setConnectErrors The function to update connection error value. - * @param client_storage The client storage object from context.js - * @param navigate The navigate function from React Router - * @param params The params object from React Router - */ -export const connect = async ( - socket, - dispatch, - transports, - setConnectErrors, - client_storage = {}, - navigate, - params, -) => { - // Socket already allocated, just reconnect it if needed. - if (socket.current) { - if (!socket.current.connected) { - await socket.current.reconnect(); - } - return; - } - - // Get backend URL object from the endpoint. - const endpoint = getBackendURL(EVENTURL); - let bootRoute; - - // The hydrate event rides in the socket.io CONNECT packet, so the backend - // starts loading state as soon as the namespace connects instead of after - // an extra round trip for the connect acknowledgement. The keys are read by - // the backend as CompileVars.CONNECT_AUTH_EVENT and CONNECT_AUTH_STATE_SCHEMA; - // the state schema goes along on every (re)connect, since a reconnect can - // land on another backend version. - const bootAuth = (first) => (callback) => { - const boot_event = withRouterData(app.initialEvents(first)[0], params); - bootRoute = currentRouteKey(); - recordSentStorageValues(boot_event); - // Instrumentation hook (installed by reflex-otel): may add a traceparent. - window.__reflex_otel?.onEventSend?.(boot_event); - callback({ event: boot_event, state_schema: app.stateSchema }); - }; - - // Create the socket. A new session's token is saved here, once the app has - // mounted, even when a transport warmed up with it earlier. - socketStarted = true; - const session_token = getToken(); - if ( - warmSocket && - (warmSocket.io.opts.query.token !== session_token || - warmSocket.io.opts.transports.length !== transports.length || - transports.some( - (transport, i) => transport !== warmSocket.io.opts.transports[i], - )) - ) { - discardWarmSocket(); - } - socket.current = - warmSocket ?? createSocket(endpoint, transports, session_token); - warmSocket = null; - cancelWarmup(); - socket.current.wait_connect = false; - let firstConnect = true; - let finishBootstrap; - let reconnectingSession = false; - let sessionTimer; - // The abort controller of the exchange in progress, if any. - let sessionController; - let resolveSession; - let rejectSession; - let sessionFailures = 0; - // Whether the backend denied the exchange for this page's origin. - let sessionRejected = false; - const currentSocket = socket.current; - const requestSessionRefresh = () => { - window.clearTimeout(sessionTimer); - // A denied exchange gets the same answer until the backend reconnects. - if (sessionRejected) return; - if (socket.current === currentSocket && currentSocket.connected) { - currentSocket.emit(SESSION_REFRESH_EVENT); - } - }; - // Ask for a new credential once the wait has passed. A browser runs a timer - // over 2**31 - 1 ms with no delay, so the wait is capped. - const scheduleSessionRefresh = ( - wait = Number(window.localStorage.getItem(sessionRefreshStorageKey())) - - Date.now(), - ) => { - window.clearTimeout(sessionTimer); - if (wait > 0) { - sessionTimer = window.setTimeout( - requestSessionRefresh, - Math.min(wait, 2 ** 31 - 1), - ); - } else { - requestSessionRefresh(); - } - }; - const finishSessionExchange = () => { - resolveSession?.(); - resolveSession = rejectSession = undefined; - initialSessionExchange = undefined; - }; - const stopSessionExchange = (preserveReadiness = false) => { - window.clearTimeout(sessionTimer); - sessionController?.abort(); - sessionController = undefined; - if (!preserveReadiness) { - reconnectingSession = false; - rejectSession?.(new Error("Session connection closed")); - resolveSession = rejectSession = undefined; - initialSessionExchange = undefined; - } - }; - const releaseBootstrap = () => { - finishBootstrap?.(); - finishBootstrap = null; - }; - socket.current.releaseSessionBootstrap = () => { - stopSessionExchange(); - releaseBootstrap(); - }; - // Ensure undefined fields in events are sent as null instead of removed - socket.current.io.encoder.replacer = (k, v) => (v === undefined ? null : v); - // The server drops a transport whose frame exceeds the limit its handshake - // announced, so a CONNECT packet (type 0) that carries an oversized hydrate - // is reported instead of sent. The page stays offline until browser storage - // shrinks and it reloads: wait_connect stays set, so reconnect() does not - // rebuild the hydrate. - const { encoder } = socket.current.io; - const encode = encoder.encode.bind(encoder); - encoder.encode = (packet) => { - const encoded = encode(packet); - if (packet.type !== 0) { - return encoded; - } - // socket.io-client is pinned; test_hydration_storage.py covers these internals. - const { engine } = socket.current.io; - const transport = engine.transport.name; - // The Engine.IO message type ("4") prefixes the encoded packet. - const size = 1 + frameSize(encoded[0], transport); - if (size > engine._maxPayload) { - const unit = transport === "websocket" ? "characters" : "bytes"; - /** @type {Error & { code?: string }} */ - const error = new Error( - `Hydration payload (${size} ${unit}) exceeds the server limit (${engine._maxPayload} ${unit}). Reduce browser storage data and reload.`, - ); - error.code = ERROR_TYPE_HYDRATION_PAYLOAD_TOO_LARGE; - console.error(error.message); - setConnectErrors((errors) => [...errors.slice(-9), error]); - // No connect or disconnect event follows, so free the cold-tab lock here. - releaseBootstrap(); - socket.current.disconnect(); - return []; - } - return encoded; - }; - socket.current.io.decoder.tryParse = (str) => { - try { - return parseJson(str); - } catch { - return false; - } - }; - // Set up a reconnect helper function - socket.current.reconnect = async () => { - if ( - socket.current && - !socket.current.connected && - !socket.current.wait_connect - ) { - socket.current.wait_connect = true; - const current = socket.current; - const start = () => { - if (socket.current !== current) { - releaseBootstrap(); - return; - } - current.io.opts.query = { token: getToken() }; - current.auth = bootAuth(firstConnect); - current.connect(); - }; - const key = sessionStorageKey(); - if ( - window.navigator?.locks && - !( - Number(window.localStorage.getItem(sessionRefreshStorageKey())) > - Date.now() - ) - ) { - // Only cold tabs wait. The first socket hydrates while its in-band - // credential becomes a cookie; the next tab then shares that cookie. - window.navigator.locks - .request( - `${key}:session`, - () => - new Promise((resolve) => { - finishBootstrap = resolve; - start(); - }), - ) - .catch((error) => { - if (socket.current === current) retryConnect(error); - }); - } else { - start(); - } - } - }; - - function checkVisibility() { - if (!socket.current) { - // The socket was released without stopWatchingVisibility being called. - // Connecting here would open a socket nothing listens to any more. - document.removeEventListener("visibilitychange", checkVisibility); - return; - } - if (document.visibilityState === "visible") { - if (!socket.current.connected) { - console.log("Socket is disconnected, attempting to reconnect "); - socket.current.reconnect(); - } else if (!sessionController) { - // A timer that the browser suspended can be past its refresh time. - scheduleSessionRefresh(); - } - } - } - - const disconnectTrigger = (event) => { - if (socket.current?.connected) { - console.log("Disconnect websocket on page navigation"); - socket.current.disconnect(); - } - }; - - const pagehideHandler = (event) => { - if (!socket.current?.connected) { - return; - } - if (event.persisted) { - console.log("Disconnect backend before bfcache on navigation"); - } else { - console.log("Disconnect websocket on pagehide"); - } - socket.current.disconnect(); - }; - - // Unknown substates already reported on this connection. - const reported_missing_substates = new Set(); - // Failed connection attempts since the last connect, for the retry backoff. - let failed_attempts = 0; - // The scheduled retry of the last failed attempt. - let retry_timer; - - // Once the socket is open, hydrate the page. - socket.current.on("connect", async () => { - if (reconnectingSession) { - reconnectingSession = false; - if (!sessionController) finishSessionExchange(); - } - if (!sessionController) { - releaseBootstrap(); - // The backend can trust this origin after a restart with new settings. - sessionRejected = false; - scheduleSessionRefresh(); - } - firstConnect = false; - socket.current.wait_connect = false; - reported_missing_substates.clear(); - failed_attempts = 0; - window.clearTimeout(retry_timer); - retry_timer = undefined; - setConnectErrors([]); - window.__reflex_otel?.onSocketConnect?.(); - window.addEventListener("pagehide", pagehideHandler); - window.addEventListener("beforeunload", disconnectTrigger); - // The connection auth event already loads its route, and every queued - // on_load loads the route current when it is sent. Keep the last queued - // on_load, after every navigation's storage update, only if the route - // changed after the auth event was built. - let keepOnLoad = bootRoute !== currentRouteKey(); - for (let i = event_queue.length - 1; i >= 0; i--) { - if (event_queue[i].name !== app.on_load_internal_event) continue; - if (keepOnLoad) { - keepOnLoad = false; - } else { - event_queue.splice(i, 1); - } - } - // Drain any initial events from the queue. One call is the whole drain: - // processEvent goes on until the queue is empty, or until the socket has - // dropped again with a stateful event waiting. Looping on the queue length - // would spin in that second case, since nothing can shrink the queue then. - await processEvent(socket.current, navigate, params); - }); - - // Record a failed connection attempt and retry it with incremental backoff. - const retryConnect = (error) => { - releaseBootstrap(); - socket.current.wait_connect = false; - failed_attempts = Math.min(failed_attempts + 1, 10); - setConnectErrors((connectErrors) => [...connectErrors.slice(-9), error]); - window.clearTimeout(retry_timer); - retry_timer = window.setTimeout(() => { - retry_timer = undefined; - if (socket.current && !socket.current.connected) { - return socket.current.reconnect(); - } - }, 200 * failed_attempts); // Incremental backoff - }; - - socket.current.on("connect_error", retryConnect); - - socket.current.on("disconnect", (reason, details) => { - stopSessionExchange( - reconnectingSession && reason === "io client disconnect", - ); - releaseBootstrap(); - firstConnect = false; - // A transport closed before the namespace connected is a failed attempt, - // e.g. a CONNECT packet over the server or a proxy message size limit. - if (socket.current.wait_connect) { - retryConnect( - new Error(`connection closed before connecting (${reason})`), - ); - return; - } - // A transport error reports connect_error first, which scheduled the retry. - if (retry_timer !== undefined) { - return; - } - window.__reflex_otel?.onSocketDisconnect?.(reason); - const try_reconnect = - reason !== "io server disconnect" && reason !== "io client disconnect"; - window.removeEventListener("beforeunload", disconnectTrigger); - window.removeEventListener("pagehide", pagehideHandler); - if (try_reconnect) { - // Attempt to reconnect transient non-intentional disconnects. - socket.current.reconnect(); - } - }); - - // Report a failure to process a state update to the backend, so it surfaces - // in the terminal logs instead of only in the browser console. - const reportStateUpdateError = (error) => { - console.error("Error processing state update:", error); - socket.current?.emit(CLIENT_ERROR_EVENT, { - message: error?.message || String(error), - error_type: ERROR_TYPE_STATE_UPDATE, - }); - }; - - // Warn about unknown substates and surface them in the backend terminal - // logs, once per substate per connection. - const reportUnknownSubstates = (substates) => { - const unreported = substates.filter( - (substate) => !reported_missing_substates.has(substate), - ); - if (unreported.length === 0) { - return; - } - for (const substate of unreported) { - reported_missing_substates.add(substate); - } - const errorMsg = `Skipping state update for unknown substate(s): no dispatch function for "${unreported.join( - '", "', - )}". Try refreshing the page or clearing your browser cache. This usually indicates a mismatch between frontend and backend state definitions. If you are the developer of this app, rebuild the frontend and check that api_url is correct.`; - console.warn(errorMsg); - socket.current.emit(CLIENT_ERROR_EVENT, { - message: errorMsg, - substate: unreported.join(", "), - error_type: ERROR_TYPE_DISPATCH_MISSING, - }); - }; - - // Drop and report substates without a dispatch function. Only a mismatched - // delta is copied; the received update is not mutated. - const withoutUnknownSubstates = (delta) => { - let unknown; - for (const substate in delta) { - if (typeof dispatch[substate] !== "function") { - unknown ??= []; - unknown.push(substate); - } - } - if (unknown === undefined) { - return delta; - } - reportUnknownSubstates(unknown); - const known = { ...delta }; - for (const substate of unknown) { - delete known[substate]; - } - return known; - }; - - // On each received message, queue the updates and events. - socket.current.on("event", (update) => { - // Skip unknown substates in both reducer and client-storage updates. - const delta = withoutUnknownSubstates(update.delta); - try { - if (delta) { - for (const substate in delta) { - dispatch[substate](delta[substate]); - } - applyClientStorageDelta(client_storage, delta); - } - if (update.events && update.events.length > 0) { - queueEvents(update.events, socket, false, navigate, params).catch( - reportStateUpdateError, - ); - } - } catch (error) { - reportStateUpdateError(error); - } - }); - socket.current.on("new_token", async (new_token) => { - setToken(new_token); - }); - socket.current.on(SESSION_REFRESH_EVENT, requestSessionRefresh); - socket.current.on("session_token", async (sessionCredential) => { - if (sessionController) return; - const controller = new AbortController(); - sessionController = controller; - window.clearTimeout(sessionTimer); - // HTTP calls wait while a credential from the socket is exchanged for - // the cookie. After a lasting failure the retries go on, but they hold - // nothing. - if (!resolveSession && sessionCredential && sessionFailures < 3) { - initialSessionExchange = new Promise((resolve, reject) => { - resolveSession = resolve; - rejectSession = reject; - }); - // Readiness may have no HTTP consumer when the connection closes. - initialSessionExchange.catch(() => {}); - } - try { - const previousToken = getToken(); - const session = await ensureSession(sessionCredential, controller); - if (sessionController !== controller) return; - setToken(session.client_token); - const refreshDelay = - (session.refresh_in ?? session.expires_in / 2) * 1000; - sessionRejected = false; - try { - window.localStorage.setItem( - sessionRefreshStorageKey(), - String(Date.now() + refreshDelay), - ); - } catch { - // The cookie is set; the refresh time is only a hint for later loads. - } - sessionFailures = 0; - setConnectErrors([]); - scheduleSessionRefresh(refreshDelay); - if (currentSocket.connected && getToken() !== previousToken) { - // Keep waiting HTTP calls queued until this cookie's socket is accepted. - reconnectingSession = true; - currentSocket.disconnect(); - await currentSocket.reconnect(); - } else { - finishSessionExchange(); - } - } catch (error) { - if (sessionController !== controller) return; - window.localStorage.removeItem(sessionRefreshStorageKey()); - if (error.status === 403) { - // The backend does not trust this page's origin, so a retry gets the - // same answer. The socket works without the cookie: release HTTP calls. - console.error( - `${error.message}. The backend does not trust the origin ${window.location.origin}; ` + - "add it to deploy_url or cors_allowed_origins to persist the browser session.", - ); - sessionRejected = true; - finishSessionExchange(); - return; - } - setConnectErrors((errors) => [...errors.slice(-9), error]); - // Retry on the live socket after one second, backing off to thirty seconds. - // Each attempt requests a fresh credential, including after cookie expiry. - const delay = Math.min(30000, 1000 * 2 ** Math.min(sessionFailures++, 5)); - sessionTimer = window.setTimeout(requestSessionRefresh, delay); - // A failure that lasts is not transient, for example a proxy that does - // not forward this route. Stop holding HTTP calls; the retry goes on. - if (sessionFailures >= 3) finishSessionExchange(); - } finally { - if (sessionController === controller) { - sessionController = undefined; - releaseBootstrap(); - } - } - }); - - socket.current.on(STATE_MISMATCH_EVENT, handleStateMismatch); - - document.addEventListener("visibilitychange", checkVisibility); - // Called by whoever releases the socket: the listener lives on the document, - // so it would otherwise outlive the socket and everything it closes over. - socket.current.stopWatchingVisibility = () => - document.removeEventListener("visibilitychange", checkVisibility); - await socket.current.reconnect(); -}; - /** * Create an event object. * @param {string} name The name of the event. @@ -1739,164 +869,33 @@ export const applyEventActions = ( }; /** - * Package client-side storage values as payload to send to the - * backend with the hydrate event - * @param client_storage The client storage object from context.js - * @returns payload dict of client storage values - */ -export const hydrateClientStorage = (client_storage) => { - const client_storage_values = {}; - if (client_storage.cookies) { - for (const state_key in client_storage.cookies) { - const cookie_options = client_storage.cookies[state_key]; - const cookie_name = cookie_options.name || state_key; - const cookie_value = cookies.get(cookie_name, { doNotParse: true }); - if (cookie_value !== undefined) { - client_storage_values[state_key] = cookie_value; - } - } - } - if (client_storage.local_storage && typeof window !== "undefined") { - for (const state_key in client_storage.local_storage) { - const options = client_storage.local_storage[state_key]; - const local_storage_value = localStorage.getItem( - options.name || state_key, - ); - if (local_storage_value !== null) { - client_storage_values[state_key] = local_storage_value; - } - } - } - if (client_storage.session_storage && typeof window !== "undefined") { - for (const state_key in client_storage.session_storage) { - const session_options = client_storage.session_storage[state_key]; - const session_storage_value = sessionStorage.getItem( - session_options.name || state_key, - ); - if (session_storage_value != null) { - client_storage_values[state_key] = session_storage_value; - } - } - } - if ( - client_storage.cookies || - client_storage.local_storage || - client_storage.session_storage - ) { - return client_storage_values; - } - return {}; -}; - -/** - * Remember the synced localStorage values an event sends, to recognise their echoes. - * - * Only synced vars: the tab sends another tab's newer value only for those. - * @param event The event about to be sent. + * Run the event loop of an app without state: there is no backend, so events + * are the ones the browser handles by itself (a redirect, a script, a + * download), and nothing is ever sent. + * @returns [addEvents, connectErrors], as useEventLoop does. connectErrors stays empty. */ -const recordSentStorageValues = (event) => { - // ReflexEvent leaves out an empty payload. - const vars = event.payload?.vars; - if ( - vars === undefined || - (event.name !== `${app.state_name}.hydrate_and_load` && - event.name !== `${app.state_name}.${UPDATE_VARS_INTERNAL}`) - ) { - return; - } - const local_storage = app.clientStorage.local_storage; - for (const [state_key, value] of Object.entries(vars)) { - if (!local_storage?.[state_key]?.sync) { - continue; - } - const sent = (sentStorageValues[state_key] ??= []); - sent.push({ value, writes: localStorageWrites }); - if (sent.length > MAX_SENT_STORAGE_VALUES) { - sent.shift(); - } - } -}; +const useLocalEventLoop = () => { + const [navigate, params] = useEventRoute(); + const connectErrors = useRef([]).current; -/** - * Take the sent value that a backend value echoes, and the older ones with it. - * @param state_key The state key of the browser storage var. - * @param value The value the backend sent for it. - * @returns The sent value's entry, or undefined if the value is no echo. - */ -const takeEcho = (state_key, value) => { - const sent = sentStorageValues[state_key]; - const index = sent?.findIndex((entry) => entry.value === value) ?? -1; - // Older values were echoed already, or changed by an override on the way. - return index === -1 ? undefined : sent.splice(0, index + 1)[index]; -}; + const addEvents = useCallback((events, args, event_actions) => { + const _events = normalizeEvents(events); + return applyEventActions( + () => queueEvents(_events, null, false, navigate, params), + Object.assign({}, event_actions, ..._events.map((e) => e.event_actions)), + args, + _events.map((e) => e.name).join("+++"), + // A temporal event is dropped while the backend is away, as it always is here. + () => false, + ); + }, []); -/** - * Update client storage values based on backend state delta. - * @param client_storage The client storage object from context.js - * @param delta The state update from the backend - */ -const applyClientStorageDelta = (client_storage, delta) => { - // find the main state and check for is_hydrated - const unqualified_states = Object.keys(delta).filter( - (key) => key.split(".").length === 1, - ); - if (unqualified_states.length === 1) { - const main_state = delta[unqualified_states[0]]; - if ( - main_state.is_hydrated_rx_state_ !== undefined && - !main_state.is_hydrated_rx_state_ - ) { - // skip if the state is not hydrated yet, since all client storage - // values are sent in the hydrate event - return; - } - } - // Save known client storage values to cookies and localStorage. - for (const substate in delta) { - for (const key in delta[substate]) { - const state_key = `${substate}.${key}`; - const value = delta[substate][key]; - if (client_storage.cookies && state_key in client_storage.cookies) { - const cookie_options = { ...client_storage.cookies[state_key] }; - const cookie_name = cookie_options.name || state_key; - delete cookie_options.name; // name is not a valid cookie option - cookies.set(cookie_name, value, cookie_options); - } else if ( - client_storage.local_storage && - state_key in client_storage.local_storage && - typeof window !== "undefined" - ) { - const name = client_storage.local_storage[state_key].name || state_key; - const echo = takeEcho(state_key, value); - const last = lastLocalStorageWrites[name]; - // Write an echo only over this tab's own later write, which the backend - // applied before the echoed event. Otherwise storage holds the sent - // value or another tab's newer one. - if ( - !echo || - (last?.writes > echo.writes && - localStorage.getItem(name) === last.value) - ) { - localStorage.setItem(name, value); - lastLocalStorageWrites[name] = { - value, - writes: ++localStorageWrites, - }; - } - } else if ( - client_storage.session_storage && - state_key in client_storage.session_storage && - typeof window !== "undefined" - ) { - const session_options = client_storage.session_storage[state_key]; - sessionStorage.setItem(session_options.name || state_key, value); - } - } - } + return [addEvents, connectErrors]; }; /** - * Establish websocket event loop for a React Router page. + * Establish the event loop for a React Router page: over the websocket when + * the app has state, in the browser alone when it has none. * @param dispatch The reducer dispatch function to update state. * @param initial_events The initial app events. * @param client_storage The client storage object from context.js @@ -1905,264 +904,14 @@ const applyClientStorageDelta = (client_storage, delta) => { * addEvents is used to queue an event, and * connectErrors is an array of reactive js error from the websocket connection (or null if connected). */ -export const useEventLoop = ( - dispatch, - initial_events = () => [], - client_storage = {}, -) => { - const socket = useRef(null); - const location = useLocation(); - const navigate = useNavigate(); - const paramsR = useParams(); - const prevLocationRef = useRef(location); - const [searchParams] = useSearchParams(); - const [connectErrors, setConnectErrors] = useState([]); - // A splat route's segments are kept as a list, so the values are not all strings. - const params = useRef( - /** @type {Record} */ (paramsR), - ); - const mounted = useRef(false); - - useEffect(() => { - const { "*": splat, ...remainingParams } = paramsR; - if (splat) { - params.current = { ...remainingParams, splat: splat.split("/") }; - } else { - params.current = remainingParams; - } - }, [paramsR]); - - useEffect(() => { - locationRef.current = location; - }, [location]); - - const ensureSocketConnected = useCallback(async () => { - if (!mounted.current) { - // During hot reload, some components may still have a reference to - // addEvents, so avoid reconnecting the socket of an unmounted event loop. - return; - } - try { - // only use websockets if state is present and backend is not disabled (reflex cloud). - if ( - Object.keys(app.initialState).length > 1 && - !isBackendDisabled() && - !socket.current?.connected - ) { - // Initialize the websocket connection. - await connect( - socket, - dispatch, - [env.TRANSPORT], - setConnectErrors, - client_storage, - navigate, - params, - ); - } - } catch (error) { - // A connection that cannot even be attempted (the browser blocks the - // storage that holds the token, say) is a connection error like any - // other. It must not reject: callers do not await this, and the handler - // for unhandled rejections reports through addEvents, which calls back - // into here and would fail the same way, forever. - setConnectErrors((errors) => [...errors.slice(-9), error]); - } - }, [ - socket, +export const useEventLoop = (dispatch, initial_events, client_storage) => + // Whether the app has state is settled before the first render, so the + // same hooks run on every one. + (backend.useEventLoop ?? useLocalEventLoop)( dispatch, - setConnectErrors, + initial_events, client_storage, - navigate, - params, - mounted, - ]); - - // Function to add new events to the event queue. - const addEvents = useCallback((events, args, event_actions) => { - const _events = normalizeEvents(events); - - event_actions = Object.assign( - {}, - event_actions, - ..._events.map((e) => e.event_actions), - ); - - if (!event_actions?.temporal) { - // Reconnect socket if needed for non-temporal events. - void ensureSocketConnected(); - } - - return applyEventActions( - () => queueEvents(_events, socket, false, navigate, params), - event_actions, - args, - _events.map((e) => e.name).join("+++"), - () => !!socket.current?.connected, - ); - }, []); - - // Handle frontend errors and send them to the backend via websocket. - useEffect(() => { - if (typeof window === "undefined") { - return; - } - - window.onerror = function (msg, url, lineNo, columnNo, error) { - addEvents([ - ReflexEvent(`${app.exception_state_name}.handle_frontend_exception`, { - // Some error events (e.g. a ResizeObserver loop) have no Error object. - info: error - ? error.name + ": " + error.message + "\n" + error.stack - : msg + "\n at " + url + ":" + lineNo + ":" + columnNo, - component_stack: "", - }), - ]); - return false; - }; - - //NOTE: Only works in Chrome v49+ - //https://github.com/mknichel/javascript-errors?tab=readme-ov-file#promise-rejection-events - window.onunhandledrejection = function (event) { - addEvents([ - ReflexEvent(`${app.exception_state_name}.handle_frontend_exception`, { - info: - event.reason?.name + - ": " + - event.reason?.message + - "\n" + - event.reason?.stack, - component_stack: "", - }), - ]); - return false; - }; - }, []); - - // Handle socket connect/disconnect. - useEffect(() => { - // Initialize the websocket connection. - mounted.current = true; - void ensureSocketConnected(); - - // Cleanup function. - return () => { - mounted.current = false; - if (socket.current) { - socket.current.releaseSessionBootstrap?.(); - socket.current.disconnect(); - socket.current.off(); - socket.current.stopWatchingVisibility(); - socket.current = null; - } - }; - }, []); - - // Main event loop. - useEffect(() => { - // Skip if the backend is disabled - if (isBackendDisabled() || !socket.current || !socket.current.connected) { - return; - } - void (async () => { - // Process all outstanding events. processEvent drains the queue itself, - // and stops at a stateful event when the socket has dropped; the connect - // handler sends what is left once it is back. - if (event_queue.length > 0) { - await ensureSocketConnected(); - await processEvent(socket.current, navigate, params); - } - })(); - }); - - // localStorage event handling - useEffect(() => { - // A Map, so a storage name like "constructor" is not an inherited property. - const storage_to_state_map = new Map(); - - if (client_storage.local_storage && typeof window !== "undefined") { - for (const state_key in client_storage.local_storage) { - const options = client_storage.local_storage[state_key]; - if (options.sync) { - const local_storage_value_key = options.name || state_key; - // Several vars can share one storage name; sync all of them. - const state_keys = storage_to_state_map.get(local_storage_value_key); - if (state_keys) { - state_keys.push(state_key); - } else { - storage_to_state_map.set(local_storage_value_key, [state_key]); - } - } - } - } - - // e is StorageEvent - const handleStorage = (e) => { - // Session storage changes in same-origin frames raise storage events too. - if (e.storageArea !== localStorage) { - return; - } - // A clear() event has no key and affects every synced storage name. - const entries = - e.key === null - ? storage_to_state_map.entries() - : [[e.key, storage_to_state_map.get(e.key)]]; - const events = []; - for (const [key, state_keys] of entries) { - if (state_keys) { - // Read the value when sent, just like individual-key updates. - events.push(ReflexEvent(SYNC_LOCAL_STORAGE, { key, state_keys })); - } - } - if (events.length) { - addEvents(events, e); - } - }; - - window.addEventListener("storage", handleStorage); - return () => window.removeEventListener("storage", handleStorage); - }); - - const handleNavigationEvents = useRef(false); - // Route after the initial page hydration - useEffect(() => { - // The first time this effect runs is initial load, so don't handle - // any navigation events. - if (!handleNavigationEvents.current) { - handleNavigationEvents.current = true; - return; - } - if (location.state?.fromNotFound) { - // If the redirect is from a 404 page, we skip onLoadInternalEvent, - // since it was already run when the 404 page was first rendered. - return; - } - // This will run when the location changes - if ( - location.pathname + location.search === - prevLocationRef.current.pathname + prevLocationRef.current.search - ) { - if (location.hash) { - // If the hash is the same, we don't need to do anything. - return; - } - } - - // Equivalent to routeChangeStart - runs when navigation begins - const main_state_dispatch = dispatch["reflex___state____state"]; - if (main_state_dispatch !== undefined) { - main_state_dispatch({ is_hydrated_rx_state_: false }); - } - - // Equivalent to routeChangeComplete - runs after navigation completes - addEvents(app.onLoadInternalEvent()); - - // Update the ref - prevLocationRef.current = location; - }, [location, dispatch, addEvents]); - - return [addEvents, connectErrors]; -}; + ); /*** * Check if a value is truthy in python. diff --git a/packages/reflex-frontend/tests/plain_toast.test.js b/packages/reflex-frontend/tests/plain_toast.test.js new file mode 100644 index 00000000000..e70a53c1907 --- /dev/null +++ b/packages/reflex-frontend/tests/plain_toast.test.js @@ -0,0 +1,153 @@ +/** + * The plain notice a build without the toaster shows toasts with: what a call + * puts on the page, and what takes it off again. + */ +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +let plainToast; +let warn; + +beforeEach(async () => { + vi.resetModules(); + vi.useFakeTimers(); + warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + ({ default: plainToast } = await import("$/utils/helpers/plain_toast")); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +/** The notices on the page: where each is, its role and its text. */ +const notices = () => + [...document.querySelectorAll("[id^=reflex-plain-toasts-] > div")].map( + (notice) => [ + notice.parentElement.id, + notice.getAttribute("role"), + [...notice.children].map((child) => child.textContent), + ], + ); + +test("a toast shows its message and description, then closes itself", () => { + const closed = []; + const id = plainToast("Saved", { + description: "All changes are stored.", + onAutoClose: (toast) => closed.push(toast), + }); + + expect(id).toBe(1); + expect(notices()).toEqual([ + [ + "reflex-plain-toasts-bottom-right", + "status", + ["Saved", "All changes are stored."], + ], + ]); + vi.advanceTimersByTime(3999); + expect(notices().length).toBe(1); + vi.advanceTimersByTime(1); + expect(notices()).toEqual([]); + expect(closed).toEqual([{ id: 1, title: "Saved" }]); +}); + +test("the level sets the role and the accent, and the position the stack", () => { + plainToast.error("Failed", { position: "top-center" }); + plainToast.success("", { title: "Done", duration: 100 }); + + expect(notices()).toEqual([ + ["reflex-plain-toasts-top-center", "alert", ["Failed"]], + ["reflex-plain-toasts-bottom-right", "status", ["Done"]], + ]); + const [failed, done] = document.querySelectorAll( + "[id^=reflex-plain-toasts-] > div", + ); + expect(failed.style.borderLeft).toBe("4px solid rgb(229, 72, 77)"); + expect(done.style.borderLeft).toBe("4px solid rgb(48, 164, 108)"); + expect(failed.parentElement.style.top).toBe("0px"); + expect(failed.parentElement.style.left).toBe("50%"); + expect(done.parentElement.style.bottom).toBe("0px"); + expect(done.parentElement.style.right).toBe("0px"); +}); + +test("a toast with the id of one on the page replaces it, and dismiss removes it", () => { + plainToast.error("Cannot connect to server: timeout.", { + id: "websocket-error", + duration: 120000, + }); + plainToast.error("Cannot connect to server: refused.", { + id: "websocket-error", + duration: 120000, + }); + plainToast.loading("Working"); + expect(notices()).toEqual([ + [ + "reflex-plain-toasts-bottom-right", + "alert", + ["Cannot connect to server: refused."], + ], + ["reflex-plain-toasts-bottom-right", "status", ["Working"]], + ]); + + plainToast.dismiss("websocket-error"); + plainToast.dismiss("no-such-toast"); + // A loading toast stays until it is replaced or dismissed. + vi.advanceTimersByTime(600000); + expect(notices()).toEqual([ + ["reflex-plain-toasts-bottom-right", "status", ["Working"]], + ]); + plainToast.dismiss(); + expect(notices()).toEqual([]); +}); + +test("the close button and an action close the toast and report it", () => { + const dismissed = []; + const clicked = vi.fn(); + plainToast.info("Update ready", { + id: "update", + duration: Infinity, + closeButton: true, + action: { label: "Reload", onClick: clicked }, + onDismiss: (toast) => dismissed.push(toast), + }); + expect(notices()).toEqual([ + [ + "reflex-plain-toasts-bottom-right", + "status", + ["Update ready", "Reload", "×"], + ], + ]); + vi.advanceTimersByTime(600000); + + const [reload, close] = document.querySelectorAll("button"); + close.click(); + expect(notices()).toEqual([]); + expect(clicked).not.toHaveBeenCalled(); + + plainToast.info("Update ready", { + id: "update", + action: { label: "Reload", onClick: clicked }, + onDismiss: (toast) => dismissed.push(toast), + }); + document.querySelector("button").click(); + expect(reload.isConnected).toBe(false); + expect(clicked).toHaveBeenCalledTimes(1); + expect(notices()).toEqual([]); + expect(dismissed).toEqual([ + { id: "update", title: "Update ready" }, + { id: "update", title: "Update ready" }, + ]); +}); + +test("the first toast says once why it is plain", () => { + plainToast("one"); + plainToast("two"); + expect(warn.mock.calls).toEqual([ + [ + "The toaster is not part of this build, because no use of rx.toast was " + + "found when the app was compiled, so a plain notice is shown instead. " + + "Pass toaster=rx.toast.provider() to rx.App to include it.", + ], + ]); +}); diff --git a/packages/reflex-frontend/tests/public_api.test.js b/packages/reflex-frontend/tests/public_api.test.js index 64c4e883575..889284ab166 100644 --- a/packages/reflex-frontend/tests/public_api.test.js +++ b/packages/reflex-frontend/tests/public_api.test.js @@ -61,6 +61,24 @@ const PUBLIC_API = { "useRegisteredRef", "waitForSession", ], + // Imported by the compiled context module of an app with state, and by no + // other: an app without state leaves it, and what it imports, out. + "$/utils/socket": [ + "connect", + "getToken", + "hydrateClientStorage", + "useEventLoop", + "waitForSession", + ], + // Internal: what utils/state.js and utils/socket.js share. + "$/utils/event_loop": [ + "SYNC_LOCAL_STORAGE", + "backend", + "event_queue", + "locationRef", + "normalizeEvents", + "useEventRoute", + ], "$/utils/client_state": [ "CLIENT_STATE_REF", "ClientStateProvider", @@ -90,6 +108,7 @@ const PUBLIC_API = { "$/utils/helpers/debounce": ["default"], "$/utils/helpers/json": ["parseJson"], "$/utils/helpers/paste": ["default"], + "$/utils/helpers/plain_toast": ["default"], "$/utils/helpers/range": ["default"], "$/utils/helpers/set": [ "pySetDifference", diff --git a/packages/reflex-frontend/tests/run_script.test.js b/packages/reflex-frontend/tests/run_script.test.js index 407ceafebe9..cf8e580ec38 100644 --- a/packages/reflex-frontend/tests/run_script.test.js +++ b/packages/reflex-frontend/tests/run_script.test.js @@ -9,6 +9,8 @@ import { describe, expect, test, vi } from "vitest"; import { getClientState } from "$/utils/client_state"; import { eventLoop } from "$/utils/context-registry"; import { applyEvent, getToken } from "$/utils/state"; +// The connection to the backend, which holds the session token. +import "$/utils/socket"; const callScript = (code, callback, socket = null) => applyEvent( diff --git a/packages/reflex-frontend/tests/state.test.js b/packages/reflex-frontend/tests/state.test.js index 3cd3440e5cf..f49dfcbfa09 100644 --- a/packages/reflex-frontend/tests/state.test.js +++ b/packages/reflex-frontend/tests/state.test.js @@ -41,6 +41,9 @@ import { ReflexEvent, spreadArraysOrObjects, } from "$/utils/state"; +// The connection to the backend, as the context module of an app with state +// loads it: the token and the cookie reader are its. +import "$/utils/socket"; const clearCookies = () => { for (const cookie of document.cookie.split("; ")) { diff --git a/packages/reflex-frontend/tests/state_connection.test.js b/packages/reflex-frontend/tests/state_connection.test.js index b8d40202803..2af4a6fb43e 100644 --- a/packages/reflex-frontend/tests/state_connection.test.js +++ b/packages/reflex-frontend/tests/state_connection.test.js @@ -1,10 +1,10 @@ /** - * The connection lifecycle of `utils/state.js`, with the socket replaced by a + * The connection lifecycle of `utils/socket.js`, with the socket replaced by a * fake the test drives: what happens to queued events when the connection * drops at an awkward moment, and what a torn-down event loop leaves behind. * - * `state.js` keeps its event queue, token and socket bookkeeping in module - * scope, so every test loads a fresh copy of the module. + * The event queue, token and socket bookkeeping are kept in module scope, so + * every test loads a fresh copy of the modules. */ import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; @@ -95,6 +95,8 @@ beforeEach(async () => { looseSockets = []; sessionStorage.clear(); state = await import("$/utils/state"); + // An app with state loads the connection from its compiled context module. + await import("$/utils/socket"); registry = await import("$/utils/context-registry"); // Let the import's speculative transport warmup see an app without state, // then give it one: an app with a single substate never connects. diff --git a/packages/reflex-frontend/tests/state_without_backend.test.js b/packages/reflex-frontend/tests/state_without_backend.test.js new file mode 100644 index 00000000000..47b84595153 --- /dev/null +++ b/packages/reflex-frontend/tests/state_without_backend.test.js @@ -0,0 +1,229 @@ +/** + * `utils/state.js` in an app without state, whose compiled context module + * never imports `utils/socket.js`: the connection to the backend, socket.io + * and the cookie library stay out of the bundle, and what the browser can do + * by itself still works. + * + * The backend registry is module state, so every test loads fresh modules. + */ +import { act, createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { MemoryRouter, useLocation } from "react-router"; +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +// Each factory runs when its module is first imported, and not before. +const loaded = vi.hoisted(() => []); +vi.mock("socket.io-client", () => { + loaded.push("socket.io-client"); + return { default: vi.fn() }; +}); +vi.mock("universal-cookie", () => { + loaded.push("universal-cookie"); + return { default: class {} }; +}); + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +let state; + +beforeEach(async () => { + vi.resetModules(); + loaded.length = 0; + state = await import("$/utils/state"); + const registry = await import("$/utils/context-registry"); + // What the context module of an app without state registers. + registry.registerApp({ + initialState: {}, + clientStorage: {}, + initialEvents: () => [], + onLoadInternalEvent: () => [], + isDevMode: false, + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +/** Mount a component running the event loop, as the app's root layout does. */ +const mountEventLoop = async () => { + const mounted = {}; + const Probe = () => { + [mounted.addEvents, mounted.connectErrors] = state.useEventLoop({}); + mounted.location = useLocation(); + return null; + }; + const root = createRoot( + document.body.appendChild(document.createElement("div")), + ); + await act(async () => { + root.render(createElement(MemoryRouter, null, createElement(Probe))); + }); + return { + mounted, + addEvents: (...args) => act(async () => mounted.addEvents(...args)), + unmount: () => act(async () => root.unmount()), + }; +}; + +test("loading utils/state.js loads neither socket.io nor the cookie library", async () => { + const { backend } = await import("$/utils/event_loop"); + expect(loaded).toEqual([]); + expect(backend).toEqual({}); +}); + +test("loading utils/socket.js registers the connection with utils/state.js", async () => { + const socket = await import("$/utils/socket"); + const { backend } = await import("$/utils/event_loop"); + expect(loaded.sort()).toEqual(["socket.io-client", "universal-cookie"]); + expect(Object.keys(backend).sort()).toEqual([ + "connect", + "getToken", + "hydrateClientStorage", + "sendEvent", + "useEventLoop", + "waitForSession", + ]); + expect(backend.connect).toBe(socket.connect); + expect(backend.useEventLoop).toBe(socket.useEventLoop); +}); + +test("the event loop runs browser events without a backend", async () => { + const loop = await mountEventLoop(); + const called = []; + + await loop.addEvents([ + state.ReflexEvent("_call_function", { function: () => called.push("fn") }), + state.ReflexEvent("_call_script", { + javascript_code: "[typeof socket, typeof token, isTrue([])]", + callback: (result) => called.push(result), + }), + state.ReflexEvent("_redirect", { path: "/other?x=1" }), + ]); + + expect(called).toEqual(["fn", ["object", "undefined", false]]); + expect(loop.mounted.location.pathname + loop.mounted.location.search).toBe( + "/other?x=1", + ); + expect(loop.mounted.connectErrors).toEqual([]); + expect(state.isStateful()).toBe(false); + expect(loaded).toEqual([]); + await loop.unmount(); +}); + +test("the event loop keeps one addEvents and one connectErrors across renders", async () => { + const loop = await mountEventLoop(); + const { addEvents, connectErrors } = loop.mounted; + await loop.addEvents([state.ReflexEvent("_redirect", { path: "/again" })]); + expect(loop.mounted.location.pathname).toBe("/again"); + expect(loop.mounted.addEvents).toBe(addEvents); + expect(loop.mounted.connectErrors).toBe(connectErrors); + await loop.unmount(); +}); + +test("event actions apply, and a temporal event is dropped", async () => { + const loop = await mountEventLoop(); + const called = []; + const dom_event = { preventDefault: vi.fn(), stopPropagation: vi.fn() }; + + await loop.addEvents( + [ + state.ReflexEvent( + "_call_function", + { function: () => called.push("kept") }, + { preventDefault: true }, + ), + ], + [dom_event], + { stopPropagation: true }, + ); + await loop.addEvents( + [state.ReflexEvent("_call_function", { function: () => called.push(1) })], + [], + { temporal: true }, + ); + + expect(called).toEqual(["kept"]); + expect(dom_event.preventDefault).toHaveBeenCalledTimes(1); + expect(dom_event.stopPropagation).toHaveBeenCalledTimes(1); + await loop.unmount(); +}); + +test("an event for the backend is dropped rather than sent", async () => { + const loop = await mountEventLoop(); + const called = []; + await loop.addEvents([ + state.ReflexEvent("some_state.handler", { value: 1 }), + state.ReflexEvent("_call_function", { + function: () => called.push("after"), + }), + ]); + expect(called).toEqual(["after"]); + await loop.unmount(); +}); + +test("_remove_cookie expires the cookie with the options it was set with", async () => { + document.cookie = "kept=1; path=/"; + document.cookie = "gone=1; path=/"; + const written = vi.spyOn(document, "cookie", "set"); + + await state.applyEvent( + state.ReflexEvent("_remove_cookie", { + key: "gone", + options: { path: "/" }, + }), + null, + null, + null, + ); + await state.applyEvent( + state.ReflexEvent("_remove_cookie", { + key: "scoped", + options: { + path: "/app", + domain: "example.com", + secure: true, + partitioned: true, + sameSite: "none", + }, + }), + null, + null, + null, + ); + + expect(written.mock.calls).toEqual([ + ["gone=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT"], + [ + "scoped=; Max-Age=0; Domain=example.com; Path=/app; " + + "Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; Partitioned; SameSite=None", + ], + ]); + written.mockRestore(); + expect(document.cookie).toBe("kept=1"); + expect(loaded).toEqual([]); +}); + +test("the names that need the backend say so, or answer for an app without one", async () => { + expect(state.getToken()).toBe(""); + await expect(state.waitForSession()).resolves.toBeUndefined(); + expect(() => state.hydrateClientStorage({})).toThrow( + new Error( + "hydrateClientStorage needs the connection to the backend, which an app without state does not load.", + ), + ); + expect(() => state.connect({ current: null })).toThrow( + new Error( + "connect needs the connection to the backend, which an app without state does not load.", + ), + ); +}); + +test("with utils/socket.js loaded, the same names reach the connection", async () => { + sessionStorage.setItem("token", "stored-token"); + await import("$/utils/socket"); + expect(state.getToken()).toBe("stored-token"); + expect(state.hydrateClientStorage({})).toEqual({}); + sessionStorage.clear(); +}); diff --git a/pyi_hashes.json b/pyi_hashes.json index fec0b8f2474..8e051f48b49 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -117,7 +117,7 @@ "packages/reflex-components-recharts/src/reflex_components_recharts/general.pyi": "fe22b3cf69e9ae3d425cc88c3511525b", "packages/reflex-components-recharts/src/reflex_components_recharts/polar.pyi": "adc4db1a3ca7cd292b099ec4d97a4346", "packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "f2a9cf6db58d169289fbc76de6813300", - "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "b195e3845260389ced026d2f5c4adb93", + "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "87566e8afc48f0df46be8ca188bac2fb", "reflex/__init__.pyi": "067a60e22fb825072f2f0b690662da5a", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" diff --git a/pyproject.toml b/pyproject.toml index 43f486a5a9c..833c15c984e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,7 @@ dependencies = [ "reflex-components-radix >= 0.11.0", "reflex-components-react-player >= 0.10.0", "reflex-components-recharts >= 0.10.0", - "reflex-components-sonner >= 0.10.0", + "reflex-components-sonner >= 0.10.1.dev0", "reflex-hosting-cli >= 0.2.2.post2.dev0", ] diff --git a/reflex/app.py b/reflex/app.py index 0800bcf2b10..4c71e8d9790 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -78,7 +78,7 @@ ) from reflex_components_core.core.breakpoints import set_breakpoints from reflex_components_core.core.sticky import sticky -from reflex_components_sonner.toast import toast +from reflex_components_sonner.toast import ToasterRequest from socketio import ASGIApp as EngineIOApp from socketio import AsyncNamespace, AsyncServer from starlette.applications import Starlette @@ -264,6 +264,15 @@ def extra_overlay_function() -> Component | None: return None +def default_toaster() -> Component: + """Default toaster: bundled only when the app sends a toast. + + Returns: + The toaster the compiler tells from one the app configured. + """ + return compiler.DEFAULT_TOASTER + + def default_overlay_component() -> Component: """Default overlay component included in the app wraps. @@ -931,7 +940,7 @@ class App(MiddlewareMixin, LifespanMixin): admin_dash: Removed. rx.AdminDash raises with a link to the migration guide. frontend_exception_handler: Frontend [error handler](https://reflex.dev/docs/utility-methods/exception-handlers/) function. backend_exception_handler: Backend [error handler](https://reflex.dev/docs/utility-methods/exception-handlers/) function. - toaster: Put the [toast](https://reflex.dev/docs/library/overlay/toast/) provider in the app wrap. + toaster: Put the [toast](https://reflex.dev/docs/library/overlay/toast/) provider in the app wrap. The default one is bundled only when the app sends a toast; pass a provider to always bundle it, or None for no provider. api_transformer: One or more transforms applied to the backend ASGI app before it runs — mount a FastAPI/Starlette app or wrap it in ASGI middleware. See the [API Transformer docs](https://reflex.dev/docs/api-routes/overview/) for examples. """ @@ -1034,7 +1043,7 @@ class App(MiddlewareMixin, LifespanMixin): [Exception], EventSpec | list[EventSpec] | None ] = default_backend_exception_handler - toaster: Component | None = dataclasses.field(default_factory=toast.provider) + toaster: Component | None = dataclasses.field(default_factory=default_toaster) hydrate_fallback: Component | ComponentCallable | None = None @@ -2168,7 +2177,17 @@ def _get_frontend_package_name(import_name: str) -> str | None: def _app_root(self, app_wrappers: dict[tuple[int, str], Component]) -> Component: for component in tuple(app_wrappers.values()): app_wrappers.update(component._get_all_app_wrap_components()) - order = sorted(app_wrappers, key=operator.itemgetter(0), reverse=True) + # A toast call asks for the toaster with a marker wrap, which the + # compiler answered when it resolved the wraps: it is not rendered. + order = sorted( + ( + key + for key, wrapper in app_wrappers.items() + if not isinstance(wrapper, ToasterRequest) + ), + key=operator.itemgetter(0), + reverse=True, + ) root = copy.deepcopy(app_wrappers[order[0]]) def reducer(parent: Component, key: tuple[int, str]) -> Component: diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 83d72e5dd12..7683a71891d 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -3,12 +3,15 @@ from __future__ import annotations import collections +import contextlib import dataclasses import json import logging +import sys from collections.abc import Callable, Iterable, Sequence from inspect import getattr_static, getmodule from pathlib import Path +from types import CodeType, FunctionType, ModuleType from typing import TYPE_CHECKING, Any, cast from reflex_base import constants, otel @@ -31,6 +34,7 @@ from reflex_base.constants.compiler import PageNames, ResetStylesheet from reflex_base.constants.state import FIELD_MARKER from reflex_base.environment import environment +from reflex_base.event import EventHandler, EventSpec from reflex_base.plugins import CompileContext, CompilerHooks, PageContext, Plugin from reflex_base.registry import RegistrationContext, _default_bundled_libraries from reflex_base.utils import log, memo_paths @@ -41,11 +45,13 @@ ImportVar, ParsedImportDict, ) +from reflex_base.vars import VarData from reflex_base.vars.base import LiteralVar, Var from reflex_base.vars.sequence import 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 reflex_components_sonner.toast import ToasterRequest, toast from rich.progress import Progress from reflex.compiler import templates, utils @@ -58,6 +64,10 @@ logger = logging.getLogger(__name__) +# The toaster of an app that passes none. An app's toaster is told from one it +# configured by identity, and this one is bundled only when a toast is sent. +DEFAULT_TOASTER = toast.provider() + RADIX_THEMES_STYLESHEET = "@radix-ui/themes/styles.css" @@ -1071,6 +1081,219 @@ def compile_unevaluated_page( return component +class _PlainToast(Fragment): + """App wrap that shows toasts as plain notices, without the toaster. + + It takes the place of the toaster the compiler left out of an app with + state, so a toast the backend sends anyway and a connection error still + show. A toaster a page mounts itself keeps precedence. + """ + + def add_hooks(self) -> list[str | Var]: + """Install the plain notice unless a toaster already did. + + Returns: + The hook installing the plain notice. + """ + return [ + Var( + "refs['__toast'] ??= plainToast", + _var_data=VarData( + imports={ + f"$/{constants.Dirs.STATE_PATH}": [ImportVar(tag="refs")], + f"$/{constants.Dirs.UTILS}/helpers/plain_toast": [ + ImportVar(tag="plainToast", is_default=True) + ], + } + ), + ) + ] + + +def _is_reflex_module(name: str) -> bool: + """Check whether a module is part of Reflex itself. + + Args: + name: The dotted name of the module. + + Returns: + Whether the module belongs to one of the packages of this repository. + """ + top_level = name.partition(".")[0] + return top_level in ("reflex", "reflex_base") or top_level.startswith( + "reflex_components_" + ) + + +def _is_app_module(name: str) -> bool: + """Check whether a module is the app's own code. + + Args: + name: The dotted name of the module. + + Returns: + False for the standard library, Reflex, and installed distributions. + """ + if name.partition(".")[0] in sys.stdlib_module_names or _is_reflex_module(name): + return False + file = getattr(sys.modules.get(name), "__file__", None) + return file is not None and not {"site-packages", "dist-packages"}.intersection( + Path(file).parts + ) + + +def _references_toast(roots: Iterable[Any]) -> bool: + """Check whether code reachable from the given objects refers to ``rx.toast``. + + Follows the names a function refers to: a global, a closure variable or an + attribute of a module it imported. A reference counts when its name is + ``toast`` or it resolves to something the toast module defines. Functions + and classes of the app's own modules are followed in turn; installed + distributions are not, which keeps the walk off their call graphs. + + This reads names, it does not run code: a toast reached through a name + computed at runtime, or through an object the code is handed rather than + names, is not found. Reflex's own functions are not read. + + Args: + roots: The functions, event handlers and classes to start from. + + Returns: + Whether a reference to ``rx.toast`` was found. + """ + pending = list(roots) + seen: set[int] = set() + while pending: + obj = pending.pop() + if isinstance(obj, (staticmethod, classmethod)): + obj = obj.__func__ + elif isinstance(obj, EventHandler): + obj = obj.fn + if id(obj) in seen: + continue + seen.add(id(obj)) + if isinstance(obj, type): + pending.extend(vars(obj).values()) + continue + # Reflex's own code is not read: its default handler for a backend + # exception falls back to an alert, and to a plain notice here. A + # function is judged by its own module, since a state class defined + # inside a function is moved to one of Reflex's. + if not isinstance(obj, FunctionType) or _is_reflex_module(obj.__module__): + continue + names: set[str] = set() + codes = [obj.__code__] + while codes: + code = codes.pop() + names.update(code.co_names) + codes.extend( + const for const in code.co_consts if isinstance(const, CodeType) + ) + if "toast" in names: + return True + referenced = [ + obj.__globals__[name] for name in names if name in obj.__globals__ + ] + for cell in obj.__closure__ or (): + with contextlib.suppress(ValueError): + referenced.append(cell.cell_contents) + for value in referenced: + if isinstance(value, ModuleType): + if value.__name__ == ToasterRequest.__module__: + return True + if _is_app_module(value.__name__): + pending.extend( + vars(value)[name] for name in names if name in vars(value) + ) + continue + module = getattr(value, "__module__", None) + if module == ToasterRequest.__module__: + return True + if isinstance(module, str) and _is_app_module(module): + # An object is as good as its class: its methods are read. + pending.append( + value if isinstance(value, (type, FunctionType)) else type(value) + ) + return False + + +def _backend_sends_toast(app: App) -> bool: + """Check whether the backend of the app may send a toast. + + The frontend is compiled before any event handler runs, so this looks at + what the handlers refer to instead: see ``_references_toast``. An ``on_load`` + event is sent by the backend too, and its toast call says so itself. + + Args: + app: The app being compiled. + + Returns: + Whether a toast sent from the backend was found. + """ + roots: list[Any] = [ + app.backend_exception_handler, + app.frontend_exception_handler, + ] + for events in app._load_events.values(): + for event in events: + if not isinstance(event, EventSpec): + roots.append(event) + continue + for _, arg in event.args: + var_data = arg._get_all_var_data() + if var_data is not None and any( + isinstance(wrapper, ToasterRequest) + for _, wrapper in var_data.app_wraps + ): + return True + states = [app._state] if app._state is not None else [] + while states: + state = states.pop() + states.extend(state.get_substates()) + roots.extend(state.__mro__) + return _references_toast(roots) + + +def _resolve_toaster( + app: App, app_wrappers: dict[tuple[int, str], Component] +) -> Component | None: + """Resolve the toast provider to put in the app wrap, if any. + + A toaster the app configured is always used. The default one costs every + page its library, so it is used only when the app sends a toast: from the + frontend, where the compiled toast call asks for it with a + ``ToasterRequest``, or from the backend, as far as ``_backend_sends_toast`` + can tell. Where it cannot tell, an app with state gets plain notices in + place of the toaster, so no toast is lost. + + Args: + app: The app being compiled. + app_wrappers: The app wraps collected from the pages and the other wraps. + + Returns: + The app wrap providing toasts, or None for an app that gets none. + """ + toaster = app.toaster + if toaster is None: + return None + if ( + toaster is DEFAULT_TOASTER + and not any( + isinstance(wrapper, ToasterRequest) for wrapper in app_wrappers.values() + ) + and not _backend_sends_toast(app) + ): + return _PlainToast.create() if app._state is not None else None + + from reflex_base.components.memo import memo + + @memo + def memoized_toast_provider() -> Component: + return toaster + + return Fragment.create(memoized_toast_provider()) + + def _resolve_app_wrap_components( app: App, page_app_wrap_components: dict[tuple[int, str], Component], @@ -1096,15 +1319,6 @@ def _resolve_app_wrap_components( app_wrappers[200, "StrictMode"] = StrictMode.create() - if (toaster := app.toaster) is not None: - from reflex_base.components.memo import memo - - @memo - def memoized_toast_provider() -> Component: - return toaster - - app_wrappers[44, "ToasterProvider"] = Fragment.create(memoized_toast_provider()) - for wrap_mapping in (app.app_wraps, app.extra_app_wraps): for key, app_wrap in wrap_mapping.items(): component = app_wrap(app._state is not None) @@ -1115,16 +1329,23 @@ def memoized_toast_provider() -> Component: # own subtrees (e.g. ``ErrorBoundary``'s fallback render). Surface their # Var-declared ``app_wraps`` here, fixpoint-iterating because newly added # wraps may themselves contain further declarations. - pending: list[Component] = list(app_wrappers.values()) - while pending: - next_pending: list[Component] = [] - for wrapper in pending: - before = set(app_wrappers) - collect_var_app_wraps_in_subtree(app_wrappers, wrapper) - next_pending.extend( - app_wrappers[key] for key in app_wrappers.keys() - before - ) - pending = next_pending + def surface_var_app_wraps(pending: list[Component]) -> None: + while pending: + next_pending: list[Component] = [] + for wrapper in pending: + before = set(app_wrappers) + collect_var_app_wraps_in_subtree(app_wrappers, wrapper) + next_pending.extend( + app_wrappers[key] for key in app_wrappers.keys() - before + ) + pending = next_pending + + surface_var_app_wraps(list(app_wrappers.values())) + + # Decided last: only now is every toast call in the frontend accounted for. + if (toaster := _resolve_toaster(app, app_wrappers)) is not None: + app_wrappers[44, "ToasterProvider"] = toaster + surface_var_app_wraps([toaster]) return app_wrappers diff --git a/tests/integration/tests_playwright/test_stateless_app.py b/tests/integration/tests_playwright/test_stateless_app.py index ef566819f48..c199a9928d0 100644 --- a/tests/integration/tests_playwright/test_stateless_app.py +++ b/tests/integration/tests_playwright/test_stateless_app.py @@ -1,6 +1,7 @@ """Integration tests for a stateless app.""" from collections.abc import Generator +from urllib.parse import urlsplit import httpx2 import pytest @@ -8,31 +9,73 @@ from reflex_base.config import get_config from reflex_base.constants import Endpoint -from reflex.testing import AppHarness +from reflex.testing import AppHarness, AppHarnessProd +from tests.integration.utils import built_scripts, libraries_in_scripts, record_scripts def StatelessApp(): - """A stateless app that renders a heading.""" + """A stateless app whose events all run in the browser.""" import reflex as rx + counter = rx.client_state(0, name="counter") + def index(): - return rx.heading("This is a stateless app") + return rx.el.div( + rx.heading("This is a stateless app"), + rx.el.input(id="field"), + rx.el.p(id="script-output"), + rx.el.button( + "Run script", + id="run-script", + on_click=rx.call_script( + "document.getElementById('script-output').textContent =" + " 'stored: ' + localStorage.getItem('stateless-key')" + ), + ), + rx.el.button( + "Fill", id="fill", on_click=rx.set_value("field", "filled in") + ), + rx.el.button( + "Forget", + id="forget", + on_click=[ + rx.remove_cookie("stateless-cookie"), + rx.remove_local_storage("stateless-key"), + ], + ), + rx.el.button( + counter.value, id="count", on_click=counter.set(lambda v: v + 1) + ), + rx.el.button("Toggle", id="toggle", on_click=rx.toggle_color_mode), + rx.el.button("Go", id="go", on_click=rx.redirect("/other")), + rx.link("Other page", href="/other", id="link"), + ) + + def other(): + return rx.el.div( + rx.heading("The other page"), + rx.el.button("Back", id="back", on_click=rx.redirect("/")), + ) app = rx.App(enable_state=False) app.add_page(index) + app.add_page(other, route="/other") @pytest.fixture(scope="module") -def stateless_app(tmp_path_factory) -> Generator[AppHarness, None, None]: +def stateless_app( + app_harness_env: type[AppHarness], tmp_path_factory +) -> Generator[AppHarness, None, None]: """Create a stateless app AppHarness. Args: + app_harness_env: AppHarness (dev) or AppHarnessProd (prod). tmp_path_factory: pytest fixture for creating temporary directories. Yields: AppHarness: A harness for testing the stateless app. """ - with AppHarness.create( + with app_harness_env.create( root=tmp_path_factory.mktemp("stateless_app"), app_source=StatelessApp, ) as harness: @@ -59,3 +102,95 @@ 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_stateless_app_runs_without_the_state_runtime( + stateless_app: AppHarness, page: Page +): + """The page loads no socket, cookie library or toaster, and its events still run. + + Args: + stateless_app: A harness for testing the stateless app. + page: A Playwright page. + """ + assert stateless_app.frontend_url is not None + websockets: list[str] = [] + page_errors: list[str] = [] + page.on("websocket", lambda ws: websockets.append(ws.url)) + page.on("pageerror", lambda exc: page_errors.append(str(exc))) + scripts = record_scripts(page) + + page.goto(stateless_app.frontend_url) + expect(page.get_by_role("heading")).to_have_text("This is a stateless app") + page.evaluate( + "() => { localStorage.setItem('stateless-key', 'kept');" + " document.cookie = 'stateless-cookie=1; path=/'; }" + ) + + # A script reads browser storage. + page.locator("#run-script").click() + expect(page.locator("#script-output")).to_have_text("stored: kept") + + # Refs, cookies and local storage. + page.locator("#fill").click() + expect(page.locator("#field")).to_have_value("filled in") + page.locator("#forget").click() + page.locator("#run-script").click() + expect(page.locator("#script-output")).to_have_text("stored: null") + assert page.evaluate("() => document.cookie") == "" + + # Client state. + expect(page.locator("#count")).to_have_text("0") + page.locator("#count").click() + page.locator("#count").click() + expect(page.locator("#count")).to_have_text("2") + + # Color mode. + initial_mode = page.evaluate("() => document.documentElement.className") + assert initial_mode in ("light", "dark") + page.locator("#toggle").click() + expect(page.locator("html")).to_have_class( + "dark" if initial_mode == "light" else "light" + ) + + # Navigation, by event and by link. + page.locator("#go").click() + expect(page.get_by_role("heading")).to_have_text("The other page") + page.locator("#back").click() + expect(page.get_by_role("heading")).to_have_text("This is a stateless app") + page.locator("#link").click() + expect(page.get_by_role("heading")).to_have_text("The other page") + + # There is no backend to lose: nothing reports a connection error. + expect(page.locator("[title^='Connection Error']")).to_have_count(0) + expect(page.get_by_text("Cannot connect to server")).to_have_count(0) + + assert page_errors == [] + # The dev server's own hot-reload socket, to the frontend, is the only one. + frontend = urlsplit(stateless_app.frontend_url).netloc + assert [url for url in websockets if urlsplit(url).netloc != frontend] == [] + if isinstance(stateless_app, AppHarnessProd): + assert websockets == [] + assert scripts + assert libraries_in_scripts(scripts) == { + "socket.io": False, + "universal-cookie": False, + "sonner": False, + } + + +def test_stateless_build_contains_no_state_runtime(stateless_app: AppHarness): + """No chunk of the production build holds socket.io, the cookie library or the toaster. + + Args: + stateless_app: A harness for testing the stateless app. + """ + if not isinstance(stateless_app, AppHarnessProd): + pytest.skip("only a production build is bundled") + scripts = built_scripts(stateless_app) + assert scripts + assert libraries_in_scripts(scripts) == { + "socket.io": False, + "universal-cookie": False, + "sonner": False, + } diff --git a/tests/integration/tests_playwright/test_toast.py b/tests/integration/tests_playwright/test_toast.py index d92e5270841..5002b51b863 100644 --- a/tests/integration/tests_playwright/test_toast.py +++ b/tests/integration/tests_playwright/test_toast.py @@ -3,6 +3,9 @@ Regression coverage for the frontend ``ReferenceError: queueEvents is not defined`` that fired when clicking a toast action/cancel button whose ``on_click`` was queued via a toast triggered directly from a frontend event. + +Also covers when the toaster is bundled at all: an app that sends a toast gets +it, and an app that sends none shows a toast it did not expect as a plain notice. """ from collections.abc import Generator @@ -10,7 +13,8 @@ import pytest from playwright.sync_api import Page, expect -from reflex.testing import AppHarness +from reflex.testing import AppHarness, AppHarnessProd +from tests.integration.utils import built_scripts, libraries_in_scripts, record_scripts def ToastApp(): @@ -309,3 +313,112 @@ def test_upload_callbacks( expect(page.locator("#upload-count")).to_have_text("2") expect(page.locator("#uploaded")).to_have_text("[]") assert not page_errors, f"Frontend raised unexpected errors: {page_errors}" + + +def test_app_that_sends_toasts_bundles_the_toaster(toast_app: AppHarness, page: Page): + """An app with a toast call loads the toaster with the page. + + Args: + toast_app: AppHarness running the test app. + page: Playwright page. + """ + assert toast_app.frontend_url is not None + scripts = record_scripts(page) + page.goto(toast_app.frontend_url) + expect(page.locator("#token")).not_to_have_value("") + + with_toaster = {"socket.io": True, "universal-cookie": True, "sonner": True} + assert libraries_in_scripts(scripts) == with_toaster + if isinstance(toast_app, AppHarnessProd): + assert libraries_in_scripts(built_scripts(toast_app)) == with_toaster + + +def NoToastApp(): + """App with state whose code names no toast, and sends one all the same.""" + import reflex as rx + + class NoToastState(rx.State): + count: int = 0 + + @rx.event + def increment(self): + self.count += 1 + + @rx.event + def surprise(self): + """Send a toast through a name the compiler cannot read. + + Returns: + A warning toast. + """ + send = getattr(rx, "to" + "ast") + return send.warning("Surprise", description="Sent anyway", duration=30000) + + def index(): + return rx.el.div( + rx.el.input( + value=NoToastState.router.session.client_token, + read_only=True, + id="token", + ), + rx.el.button( + NoToastState.count, id="count", on_click=NoToastState.increment + ), + rx.el.button("Surprise", id="surprise", on_click=NoToastState.surprise), + ) + + app = rx.App() + app.add_page(index) + + +@pytest.fixture(scope="module") +def no_toast_app( + app_harness_env: type[AppHarness], tmp_path_factory +) -> Generator[AppHarness, None, None]: + """Start NoToastApp in dev or prod mode via AppHarness. + + Args: + app_harness_env: AppHarness (dev) or AppHarnessProd (prod). + tmp_path_factory: pytest fixture for creating temporary directories. + + Yields: + Running AppHarness instance. + """ + with app_harness_env.create( + root=tmp_path_factory.mktemp("no_toast_app"), + app_source=NoToastApp, + ) as harness: + assert harness.app_instance is not None, "app is not running" + yield harness + + +def test_app_that_sends_no_toast_leaves_the_toaster_out( + no_toast_app: AppHarness, page: Page +): + """Handlers work without the toaster, and an unexpected toast shows plainly. + + Args: + no_toast_app: AppHarness running the test app. + page: Playwright page. + """ + assert no_toast_app.frontend_url is not None + page_errors: list[str] = [] + page.on("pageerror", lambda exc: page_errors.append(str(exc))) + scripts = record_scripts(page) + + page.goto(no_toast_app.frontend_url) + expect(page.locator("#token")).not_to_have_value("") + page.locator("#count").click() + expect(page.locator("#count")).to_have_text("1") + + # The state runtime is loaded, the toaster is not. + without_toaster = {"socket.io": True, "universal-cookie": True, "sonner": False} + assert libraries_in_scripts(scripts) == without_toaster + if isinstance(no_toast_app, AppHarnessProd): + assert libraries_in_scripts(built_scripts(no_toast_app)) == without_toaster + + page.locator("#surprise").click() + notice = page.locator("#reflex-plain-toasts-bottom-right > [role=status]") + expect(notice.locator("div")).to_have_text(["Surprise", "Sent anyway"]) + expect(page.locator("[data-sonner-toast]")).to_have_count(0) + assert page_errors == [] diff --git a/tests/integration/utils.py b/tests/integration/utils.py index b4db8a96ce0..8c7871486c6 100644 --- a/tests/integration/utils.py +++ b/tests/integration/utils.py @@ -3,14 +3,14 @@ from __future__ import annotations from collections import Counter -from collections.abc import Generator, Sequence +from collections.abc import Generator, Mapping, Sequence from contextlib import contextmanager from http.client import HTTPConnection from urllib.parse import urlsplit -from playwright.sync_api import Page, expect +from playwright.sync_api import Page, Response, expect -from reflex.testing import DEFAULT_TIMEOUT +from reflex.testing import DEFAULT_TIMEOUT, AppHarness # JavaScript for the client token of a tab. The frontend keeps it in # sessionStorage under a key that is scoped to the backend URL. @@ -219,3 +219,62 @@ def poll_assert_relative_event_order( assert_relative_event_order( events.all_text_contents(), expected_counts, ordering_rules ) + + +# Text only the named library puts in a script: the path socket.io connects to, +# an option of the cookie library, and the attribute the toaster marks toasts with. +LIBRARY_MARKERS = { + "socket.io": "socket.io", + "universal-cookie": "doNotParse", + "sonner": "data-sonner-toast", +} + + +def libraries_in_scripts(scripts: Mapping[str, str]) -> dict[str, bool]: + """Find which libraries of the state runtime and the toaster scripts hold. + + Args: + scripts: The source of each script, by its name or URL. + + Returns: + For each library in ``LIBRARY_MARKERS``, whether any script contains it. + """ + return { + library: any(marker in body for body in scripts.values()) + for library, marker in LIBRARY_MARKERS.items() + } + + +def record_scripts(page: Page) -> dict[str, str]: + """Record the source of every script a page loads from now on. + + Args: + page: Playwright page. + + Returns: + A dict filled, as the page loads them, with the source of each script + by URL. + """ + scripts: dict[str, str] = {} + + def record(response: Response) -> None: + if response.request.resource_type == "script" and response.ok: + scripts[response.url] = response.text() + + page.on("response", record) + return scripts + + +def built_scripts(harness: AppHarness) -> dict[str, str]: + """Read every script of an app's production build. + + Args: + harness: The harness of an app that was exported. + + Returns: + The source of each script of the client build, by file name. + """ + return { + script.name: script.read_text() + for script in (harness.app_path / ".web" / "build" / "client").rglob("*.js") + } diff --git a/tests/units/compiler/state_js.test.mjs b/tests/units/compiler/state_js.test.mjs index 2b4fdd40757..f795c0ddcc9 100644 --- a/tests/units/compiler/state_js.test.mjs +++ b/tests/units/compiler/state_js.test.mjs @@ -3,13 +3,18 @@ import { readFile } from "node:fs/promises"; import test from "node:test"; import vm from "node:vm"; -const source = await readFile( - new URL( - "../../../packages/reflex-frontend/src/utils/state.js", - import.meta.url, - ), - "utf8", -); +// The modules under test: an app with state loads the connection in +// utils/socket.js, which reaches the event queue in utils/state.js. +const sources = {}; +for (const name of ["state", "event_loop", "socket"]) { + sources[`$/utils/${name}`] = await readFile( + new URL( + `../../../packages/reflex-frontend/src/utils/${name}.js`, + import.meta.url, + ), + "utf8", + ); +} const tokenKey = "reflex:ws://localhost:8000/_event:token"; /** Evaluate the actual frontend module with controlled transport and browser APIs. */ @@ -239,19 +244,26 @@ async function setup({ "$/utils/helpers/throttle": { default() {} }, "$/utils/helpers/upload": { uploadFiles() {} }, }; - const module = new vm.SourceTextModule(source, { - context, - initializeImportMeta(meta) { - meta.hot = { - dispose(fn) { - dispose = fn; + const modules = Object.fromEntries( + Object.entries(sources).map(([name, source]) => [ + name, + new vm.SourceTextModule(source, { + context, + initializeImportMeta(meta) { + meta.hot = { + dispose(fn) { + dispose = fn; + }, + }; }, - }; - }, - }); - await module.link((name) => { - // state.js imports itself to hand its exports to server-provided scripts. - if (name === "$/utils/state") return module; + }), + ]), + ); + // What compiled code imports; its calls reach the connection once loaded. + const module = modules["$/utils/state"]; + const connection = modules["$/utils/socket"]; + await connection.link((name) => { + if (modules[name]) return modules[name]; assert.ok(imports[name], `unexpected import: ${name}`); return new vm.SyntheticModule( Object.keys(imports[name]), @@ -262,7 +274,7 @@ async function setup({ { context }, ); }); - await module.evaluate(); + await connection.evaluate(); const socket = { current: null }; return { sockets, diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..52403461832 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -6,10 +6,12 @@ import shutil import sys from pathlib import Path, PureWindowsPath +from typing import Any import pytest from pytest_mock import MockerFixture from reflex_base import constants +from reflex_base.components.app_wraps import collect_subtree_app_wraps from reflex_base.components.component import BaseComponent, Component from reflex_base.components.dynamic import bundle_library, reset_bundled_libraries from reflex_base.components.memo import MEMOS @@ -19,6 +21,7 @@ from reflex_base.plugins import CompileContext, CompilerHooks, PageContext from reflex_base.plugins.sitemap import SitemapPlugin from reflex_base.registry import RegistrationContext +from reflex_base.utils import memo_paths from reflex_base.utils.console import PoorProgress from reflex_base.utils.exceptions import ( DynamicRouteArgShadowsStateVarError, @@ -34,6 +37,7 @@ from reflex_components_core.el.elements.other import Html import reflex as rx +from reflex.app import default_backend_exception_handler from reflex.compiler import compiler, utils from reflex.compiler.plugins import default_page_plugins from reflex.state import BaseState @@ -2402,3 +2406,310 @@ def page() -> Component: assert any("const refs = {};" in code for _, code in memo_files) for code in modules: assert not _IMPORTS_REFS.search(code), code + + +def _notify(message: str) -> rx.event.EventSpec: + """Send a toast, as a helper an event handler calls. + + Args: + message: The text of the toast. + + Returns: + The toast event. + """ + return rx.toast.info(message) + + +def _log(message: str) -> None: + """Do something other than sending a toast. + + Args: + message: The text to print. + """ + print(message) + + +class _Notifier: + """A class whose method sends a toast.""" + + @staticmethod + def warn(message: str) -> rx.event.EventSpec: + """Send a warning toast. + + Args: + message: The text of the toast. + + Returns: + The toast event. + """ + return rx.toast.warning(message) + + +def _closing_over(send: Any) -> Any: + """Build a function that reaches ``send`` through its closure only. + + Args: + send: The function to close over. + + Returns: + A function calling ``send``. + """ + + def inner() -> Any: + return send("closed over") + + return inner + + +_send_error = rx.toast.error +_notifier = _Notifier() +_this_module = sys.modules[__name__] +_closes_over_a_toast = _closing_over(rx.toast.success) +_closes_over_print = _closing_over(print) + + +@pytest.mark.parametrize( + ("root", "expected"), + [ + (lambda: rx.toast("direct"), True), + (lambda: rx.toast.error("a level"), True), + (lambda: [(lambda text: rx.toast(text))(text) for text in "ab"], True), + (lambda: _send_error("an alias of a toast function"), True), + (lambda: _notify("a helper function"), True), + (lambda: _Notifier.warn("a helper class"), True), + (lambda: _notifier.warn("an instance of a helper class"), True), + (lambda: _this_module._notify("a helper reached through its module"), True), + (_closes_over_a_toast, True), + (_Notifier, True), + (staticmethod(_notify), True), + (rx.event.EventHandler(fn=_notify), True), + (lambda: _log("no toast"), False), + (lambda: rx.redirect("/elsewhere"), False), + (lambda: json.dumps({"module": "of the standard library"}), False), + (lambda: pytest.fail("an installed distribution is not followed"), False), + (_closes_over_print, False), + (dataclasses.dataclass, False), + ("not code", False), + ], +) +def test_references_toast(root: Any, expected: bool): + """A toast is found through the names code refers to, in the app's modules. + + Args: + root: The function, handler or class to start from. + expected: Whether it reaches ``rx.toast``. + """ + assert compiler._references_toast([root]) is expected + + +@pytest.mark.parametrize( + ("name", "expected"), + [ + (__name__, True), + ("json", False), + ("reflex.app", False), + ("reflex_base.event", False), + ("reflex_components_sonner.toast", False), + ("pytest", False), + ("a_module_nothing_imported", False), + ], +) +def test_is_app_module(name: str, expected: bool): + """The app's modules are what is neither Reflex, standard nor installed. + + Args: + name: The dotted name of a module. + expected: Whether it is the app's own code. + """ + assert compiler._is_app_module(name) is expected + + +def _toast_wrap(app: rx.App, page: Component | None = None) -> str | None: + """Resolve what an app puts in its app wrap to show toasts. + + Args: + app: The app to resolve the app wraps of. + page: A page of the app, or None for an app with no toast call in a page. + + Returns: + "toaster" for the toaster, "plain" for plain notices, None for neither. + """ + wraps = compiler._resolve_app_wrap_components( + app, collect_subtree_app_wraps(page) if page is not None else {} + ) + wrap = wraps.get((44, "ToasterProvider")) + if wrap is None: + return None + if isinstance(wrap, compiler._PlainToast): + return "plain" + assert [child.tag for child in wrap.children if isinstance(child, Component)] == [ + memo_paths.mirrored_symbol("MemoizedToastProvider", compiler.__name__) + ] + return "toaster" + + +def _toast_button() -> Component: + """Build a page that sends a toast from the frontend. + + Returns: + A button whose click sends a toast. + """ + return rx.el.button("Notify", on_click=rx.toast("Hello")) + + +@pytest.mark.usefixtures("clean_registration_context") +def test_toaster_of_an_app_without_state(mocker: MockerFixture): + """Without state, only a toast call in the frontend can send a toast.""" + mocker.patch( + "reflex_base.config._get_config", return_value=rx.Config(app_name="testing") + ) + app = rx.App(enable_state=False) + + assert _toast_wrap(app) is None + assert _toast_wrap(app, rx.el.div("Static")) is None + assert _toast_wrap(app, _toast_button()) == "toaster" + + app.extra_app_wraps[1, "Notify"] = lambda _stateful: _toast_button() + assert _toast_wrap(app) == "toaster" + del app.extra_app_wraps[1, "Notify"] + + app.add_page(lambda: rx.el.div("Static"), route="/", on_load=rx.toast("Hi")) + assert _toast_wrap(app) == "toaster" + app._load_events["index"] = [lambda: _notify("From a function")] + assert _toast_wrap(app) == "toaster" + app._load_events["index"] = [lambda: rx.redirect("/elsewhere")] + assert _toast_wrap(app) is None + app._load_events.clear() + + app.toaster = rx.toast.provider() + assert _toast_wrap(app) == "toaster" + + app.toaster = None + assert _toast_wrap(app) is None + assert _toast_wrap(app, _toast_button()) is None + + +@pytest.mark.usefixtures("clean_registration_context") +def test_toaster_of_an_app_whose_handlers_send_no_toast(mocker: MockerFixture): + """With state and no toast found, toasts and connection errors show plainly.""" + mocker.patch( + "reflex_base.config._get_config", return_value=rx.Config(app_name="testing") + ) + + class QuietState(rx.State): + """A state whose handlers send no toast.""" + + count: int = 0 + + @rx.event + def increment(self): + """Count up, then go elsewhere. + + Returns: + The redirect event. + """ + self.count += 1 + return rx.redirect("/elsewhere") + + app = rx.App() + + assert _toast_wrap(app) == "plain" + assert _toast_wrap(app, rx.el.div(QuietState.count)) == "plain" + assert _toast_wrap(app, _toast_button()) == "toaster" + + app.backend_exception_handler = lambda exception: _notify(str(exception)) + assert _toast_wrap(app) == "toaster" + app.backend_exception_handler = default_backend_exception_handler + + app.toaster = rx.toast.provider() + assert _toast_wrap(app) == "toaster" + + app.toaster = None + assert _toast_wrap(app) is None + + +@pytest.mark.parametrize("where", ["handler", "helper", "mixin", "substate"]) +@pytest.mark.usefixtures("clean_registration_context") +def test_toaster_of_an_app_whose_backend_sends_a_toast( + where: str, mocker: MockerFixture +): + """A toast an event handler can send bundles the toaster. + + Args: + where: The code of the state tree that refers to the toast. + mocker: Fixture for configuring the test app. + """ + mocker.patch( + "reflex_base.config._get_config", return_value=rx.Config(app_name="testing") + ) + + if where == "handler": + + class HandlerState(rx.State): + """A state whose handler sends a toast.""" + + @rx.event + def notify(self): + """Send a toast. + + Returns: + The toast event. + """ + return rx.toast("From the handler") + + elif where == "helper": + + class HelperState(rx.State): + """A state whose handler sends a toast through a method.""" + + @rx.event + def notify(self): + """Send what the helper method builds. + + Returns: + The toast event. + """ + return self._build() + + def _build(self): + return _notify("From a helper") + + elif where == "mixin": + + class Mixin(rx.State, mixin=True): + """A mixin whose handler sends a toast.""" + + @rx.event + def notify(self): + """Send a toast. + + Returns: + The toast event. + """ + return rx.toast.success("From a mixin") + + class MixedState(Mixin, rx.State): + """A state that takes its handler from the mixin.""" + + else: + + class ParentState(rx.State): + """A state that sends no toast.""" + + @rx.event + def quiet(self): + """Do nothing.""" + + class ChildState(ParentState): + """A substate that sends a toast.""" + + @rx.event + def notify(self): + """Send a toast. + + Returns: + The toast event. + """ + return rx.toast("From a substate") + + assert _toast_wrap(rx.App()) == "toaster" diff --git a/tests/units/compiler/test_context_js_template.py b/tests/units/compiler/test_context_js_template.py index 2e1b6b82468..56dddd8536d 100644 --- a/tests/units/compiler/test_context_js_template.py +++ b/tests/units/compiler/test_context_js_template.py @@ -12,6 +12,13 @@ requires_node = pytest.mark.skipif(shutil.which("node") is None, reason="node missing") +# Stands in for the connection to the backend, which the context of an app +# with state imports. +_SOCKET_STUB = """ +export const hydrateClientStorage = () => ({}); +export const useEventLoop = () => []; +""" + # Stand-ins for the modules context.js imports, keyed by the specifier they # replace. Server tests fail if a client-only hook runs without a dispatcher. _STUB_MODULES = { @@ -46,10 +53,9 @@ "$/utils/state": """ export const applyDelta = () => {}; export const ReflexEvent = () => ({}); -export const hydrateClientStorage = () => ({}); -export const useEventLoop = () => []; export const refs = {}; """, + "$/utils/socket": _SOCKET_STUB, "$/utils/context-registry": """ export const ColorModeContext = {}; export const UploadFilesContext = {}; @@ -111,6 +117,47 @@ def _event_loop_provider_body() -> str: return rendered[start:end] +def _imports(rendered: str) -> list[str]: + """Get the import statements of a rendered context module. + + Args: + rendered: The source of the context module. + + Returns: + Its import statements, in order. + """ + return [line for line in rendered.splitlines() if line.startswith("import ")] + + +def test_stateful_context_imports_the_backend_connection() -> None: + """An app with state loads the socket and what syncs browser storage.""" + rendered = context_template( + is_dev_mode=False, + default_color_mode='"light"', + initial_state={"state": {}}, + state_name="state", + ) + assert _imports(rendered) == [ + 'import { useContext, useMemo, useState, createElement, useEffect } from "react"', + 'import { applyDelta, ReflexEvent, refs } from "$/utils/state"', + 'import { hydrateClientStorage, useEventLoop } from "$/utils/socket"', + 'import { ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext, registerApp, eventLoop } from "$/utils/context-registry"', + 'import { jsx } from "@emotion/react";', + ] + + +def test_stateless_context_does_not_import_the_backend_connection() -> None: + """An app without state bundles no socket: its context never names it.""" + rendered = context_template(is_dev_mode=False, default_color_mode='"light"') + assert _imports(rendered) == [ + 'import { useContext, useMemo, useState, createElement, useEffect } from "react"', + 'import { applyDelta, useEventLoop, refs } from "$/utils/state"', + 'import { ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext, registerApp, eventLoop } from "$/utils/context-registry"', + 'import { jsx } from "@emotion/react";', + ] + assert "utils/socket" not in rendered + + def test_event_loop_provider_memoizes_its_element() -> None: """``EventLoopProvider`` must return a memoized provider element. @@ -247,8 +294,6 @@ def test_client_state_store_notifies_only_substate_subscribers(tmp_path: Path): return out ?? state; }; export const ReflexEvent = () => ({}); -export const hydrateClientStorage = () => ({}); -export const useEventLoop = () => []; export const refs = {}; """ registry_path = Templates.Dirs.WEB_TEMPLATE / "utils" / "context-registry.js" @@ -258,6 +303,7 @@ def test_client_state_store_notifies_only_substate_subscribers(tmp_path: Path): for specifier, source in ( ("react", react_stub), ("$/utils/state", state_stub), + ("$/utils/socket", _SOCKET_STUB), ("$/utils/context-registry", registry_source), ("@emotion/react", "export const jsx = () => null;\n"), ): diff --git a/tests/units/compiler/test_state_js_template.py b/tests/units/compiler/test_state_js_template.py index 7a27a17b030..e33606a592d 100644 --- a/tests/units/compiler/test_state_js_template.py +++ b/tests/units/compiler/test_state_js_template.py @@ -9,6 +9,9 @@ from reflex_base.constants import Templates STATE_JS_TEMPLATE = Templates.Dirs.WEB_TEMPLATE / "utils" / "state.js" +# The connection to the backend, split from state.js so that an app without +# state does not bundle it. +SOCKET_JS_TEMPLATE = Templates.Dirs.WEB_TEMPLATE / "utils" / "socket.js" ADD_EVENTS_ALIAS = "const addEvents = (...args) => eventLoop.addEvents(...args);" @@ -65,7 +68,7 @@ def test_state_js_does_not_register_deprecated_unload_listener() -> None: (tab close, navigation, bfcache), so the deprecated listener must not be re-introduced. """ - content = STATE_JS_TEMPLATE.read_text() + content = STATE_JS_TEMPLATE.read_text() + SOCKET_JS_TEMPLATE.read_text() assert 'addEventListener("unload"' not in content, ( "state.js registers a deprecated `unload` listener; use `pagehide` instead." @@ -82,13 +85,13 @@ def test_state_js_still_handles_page_lifecycle_disconnect() -> None: recommended Web Page Lifecycle pattern; verify the replacement listeners remain wired so the socket is closed when the user navigates away. """ - content = STATE_JS_TEMPLATE.read_text() + content = SOCKET_JS_TEMPLATE.read_text() assert 'addEventListener("pagehide"' in content, ( - "state.js should register a `pagehide` listener to disconnect the socket." + "socket.js should register a `pagehide` listener to disconnect the socket." ) assert 'addEventListener("beforeunload"' in content, ( - "state.js should keep its `beforeunload` listener as a disconnect fallback." + "socket.js should keep its `beforeunload` listener as a disconnect fallback." ) diff --git a/tests/units/components/core/test_banner.py b/tests/units/components/core/test_banner.py index 8ea73a93775..d11c1bf8049 100644 --- a/tests/units/components/core/test_banner.py +++ b/tests/units/components/core/test_banner.py @@ -1,3 +1,4 @@ +from reflex_base.components.app_wraps import collect_subtree_app_wraps from reflex_components_core.core.banner import ( ConnectionBanner, ConnectionModal, @@ -63,3 +64,16 @@ def test_connection_toaster_shows_hydration_errors_at_once(): assert hydration_check < hooks.index("(connectErrors.length >= 2)") assert 'id: "hydration-payload-error"' in hooks assert "duration: Infinity" in hooks + + +def test_connection_toaster_does_not_ask_for_the_toaster(): + """A connection error alone is no reason to bundle the toaster.""" + toaster = ConnectionToaster.create() + hooks = toaster._get_all_hooks() + + # It shows through whichever toast function the app installed. + assert list(hooks)[:2] == [ + "const connectErrors = useContext(EventLoopContext)[1];", + "const toast = refs['__toast'];", + ] + assert collect_subtree_app_wraps(toaster) == {} diff --git a/tests/units/reflex_base/client_event_queue_runtime.mjs b/tests/units/reflex_base/client_event_queue_runtime.mjs index a2970bfe6d7..aa08a324e54 100644 --- a/tests/units/reflex_base/client_event_queue_runtime.mjs +++ b/tests/units/reflex_base/client_event_queue_runtime.mjs @@ -1,6 +1,12 @@ +import fs from "node:fs"; +import path from "node:path"; import { SourceTextModule, SyntheticModule } from "node:vm"; -/** Evaluate the complete frontend module with isolated dependency stubs. */ +// The modules next to utils/state.js that make up the runtime of an app with +// state: the connection to the backend, and what the two share. +const SIBLINGS = ["event_loop", "socket"]; + +/** Evaluate the complete frontend runtime with isolated dependency stubs. */ export async function createQueueRuntime( source, { @@ -78,17 +84,23 @@ export async function createQueueRuntime( }, ...dependencyOverrides, }; - // Let Node parse the unchanged module; only expose private state to tests. - const module = new SourceTextModule( - `import { window, document, localStorage, sessionStorage } from "test:browser"; -${source} -export { event_queue }; + // Let Node parse the unchanged modules, with the browser globals in scope. + const browserModule = (text) => + new SourceTextModule( + `import { window, document, localStorage, sessionStorage } from "test:browser"; +${text} `, - ); + ); + const utils = path.dirname(process.argv[2]); + const modules = { "$/utils/state": browserModule(source) }; + for (const name of SIBLINGS) { + modules[`$/utils/${name}`] = browserModule( + fs.readFileSync(path.join(utils, `${name}.js`), "utf8"), + ); + } const linked = new Map(); - await module.link((specifier) => { - // state.js imports itself to hand its exports to server-provided scripts. - if (specifier === "$/utils/state") return module; + await modules["$/utils/socket"].link((specifier) => { + if (modules[specifier]) return modules[specifier]; if (!linked.has(specifier)) { const exports = dependencies[specifier]; if (!exports) @@ -104,6 +116,10 @@ export { event_queue }; } return linked.get(specifier); }); - await module.evaluate(); - return module.namespace; + await modules["$/utils/socket"].evaluate(); + // What compiled code imports, and the private queue for the tests to read. + return { + ...modules["$/utils/state"].namespace, + event_queue: modules["$/utils/event_loop"].namespace.event_queue, + }; } diff --git a/tests/units/reflex_components_sonner/test_toast.py b/tests/units/reflex_components_sonner/test_toast.py index bca21a536ed..cf87981b5fe 100644 --- a/tests/units/reflex_components_sonner/test_toast.py +++ b/tests/units/reflex_components_sonner/test_toast.py @@ -3,7 +3,7 @@ import json from reflex_base.style import Style -from reflex_components_sonner.toast import Toaster, ToastProps +from reflex_components_sonner.toast import Toaster, ToasterRequest, ToastProps, toast def test_toaster_hotkey_accepts_key_list(): @@ -25,3 +25,23 @@ def test_toast_button_styles_use_sonner_prop_names(): assert serialized["cancelButtonStyle"]["color"] == "white" assert "actionButtonStyles" not in serialized assert "cancelButtonStyles" not in serialized + + +def test_toast_call_asks_the_app_for_its_toaster(): + """Every toast event carries the marker wrap the compiler looks for.""" + for event in ( + toast("Hello"), + toast.error("Failed", description="Try again"), + toast.dismiss("some-id"), + toast.dismiss(), + ): + requests = [ + (priority, type(wrapper), wrapper.render()) + for _, arg in event.args + if (var_data := arg._get_all_var_data()) is not None + for priority, wrapper in var_data.app_wraps + ] + assert requests == [(44, ToasterRequest, ToasterRequest.create().render())] + + # Left in place, the marker renders nothing of its own. + assert str(ToasterRequest.create()) == "jsx(Fragment,{},)" diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 588d3a87162..f2fed9c4e15 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -33,6 +33,7 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter from pytest_mock import MockerFixture from reflex_base import otel +from reflex_base.components.app_wraps import collect_subtree_app_wraps from reflex_base.components.component import Component from reflex_base.constants import Templates from reflex_base.constants.state import FIELD_MARKER @@ -84,6 +85,7 @@ ) from reflex.compiler.compiler import ( _compile_app, + _compile_contexts, _memoize_stateful_app_wraps, _read_stateful_pages_marker, _resolve_app_wrap_components, @@ -2703,6 +2705,8 @@ def test_app_wrap_compile_theme( app, web_dir = compilable_app mocker.patch("reflex.utils.prerequisites.get_web_dir", return_value=web_dir) app.theme = rx.theme(accent_color="plum") + # A toaster the app configures is in the chain whether or not a toast is sent. + app.toaster = rx.toast.provider() app._compile() app_js_contents = ( web_dir / constants.Dirs.PAGES / constants.PageNames.APP_ROOT @@ -3141,6 +3145,8 @@ def test_compile_writes_app_wrap_memo_components( app, web_dir = compilable_app app.add_page(rx.box("Index"), route="/") + # A toaster the app configures is in the chain whether or not a toast is sent. + app.toaster = rx.toast.provider() app._compile() # The overlay/toast app wraps are framework ``@memo`` functions, so they @@ -3357,6 +3363,149 @@ def test_event_provider_app_wrap_order(mocker: MockerFixture) -> None: assert state_index < event_loop_index < children_index +ERROR_BOUNDARY_MEMO_HASH = re.compile(r"(?<=Errorboundary_errorboundary_)[0-9a-f]{32}") + +# What every app root imports after the imports of its app wraps. +APP_ROOT_TEMPLATE_IMPORTS = [ + 'import {jsx} from "@emotion/react"', + 'import { defaultColorMode } from "$/utils/context";', + "import { ThemeProvider } from '$/utils/react-theme';", + "import { Layout as AppLayout } from './_document';", + "import { Outlet } from 'react-router';", + 'import * as React from "react";', + 'import * as emotion_react from "@emotion/react";', + 'import * as utils_context from "$/utils/context";', + 'import * as utils_context_registry from "$/utils/context-registry";', + 'import * as utils_state from "$/utils/state";', +] + + +def _imports(code: str) -> list[str]: + """Get the import statements of a compiled module. + + Args: + code: The source of the module. + + Returns: + Its import statements in order, with the hash that names the error + boundary memo replaced by a placeholder. + """ + return [ + ERROR_BOUNDARY_MEMO_HASH.sub("", line) + for line in code.splitlines() + if line.startswith("import ") + ] + + +def test_stateless_app_imports_no_backend_connection(mocker: MockerFixture) -> None: + """An app without state imports neither the socket nor the toaster. + + A toast call in a page adds the toaster, and nothing else. + """ + conf = rx.Config(app_name="testing") + mocker.patch("reflex_base.config._get_config", return_value=conf) + mocker.patch("reflex.compiler.compiler.is_prod_mode", return_value=True) + app = App(theme=None, enable_state=False) + app_wrap_imports = [ + 'import {Fragment,StrictMode,useEffect} from "react"', + 'import {EventLoopProvider,StateProvider} from "$/utils/context"', + ( + "import {Errorboundary_errorboundary_} " + 'from "$/utils/components/Errorboundary_errorboundary_"' + ), + ] + + assert _imports(compile_app_root_from_page_wraps(app, {})) == [ + *app_wrap_imports, + *APP_ROOT_TEMPLATE_IMPORTS, + ] + assert _imports(_compile_contexts(None, None)) == [ + 'import { useContext, useMemo, useState, createElement, useEffect } from "react"', + 'import { applyDelta, useEventLoop, refs } from "$/utils/state"', + ( + "import { ColorModeContext, UploadFilesContext, DispatchContext, " + "EventLoopContext, StateStoreContext, registerApp, eventLoop } " + 'from "$/utils/context-registry"' + ), + 'import { jsx } from "@emotion/react";', + ] + + toast_page = rx.el.button("Notify", on_click=rx.toast("Hello")) + toast_symbol = memo_paths.mirrored_symbol( + "MemoizedToastProvider", _compile_app.__module__ + ) + assert _imports( + compile_app_root_from_page_wraps(app, collect_subtree_app_wraps(toast_page)) + ) == [ + *app_wrap_imports, + f'import {{{toast_symbol}}} from "$/app_components/reflex/compiler/compiler"', + *APP_ROOT_TEMPLATE_IMPORTS, + ] + + +@pytest.mark.usefixtures("clean_registration_context") +def test_stateful_app_imports_the_backend_connection(mocker: MockerFixture) -> None: + """An app with state imports the socket, and plain notices for the toaster. + + A toaster the app configures takes the place of the plain notices. + """ + conf = rx.Config(app_name="testing") + mocker.patch("reflex_base.config._get_config", return_value=conf) + mocker.patch("reflex.compiler.compiler.is_prod_mode", return_value=True) + + # The only state of the app, so that no handler sends a toast. + class CountState(rx.State): + count: int = 0 + + @rx.event + def increment(self): + self.count += 1 + + app = App(theme=None) + app_wrap_imports = [ + 'import {Fragment,StrictMode,useEffect} from "react"', + 'import {EventLoopProvider,StateProvider} from "$/utils/context"', + ( + "import {Errorboundary_errorboundary_} " + 'from "$/utils/components/Errorboundary_errorboundary_"' + ), + ] + overlay_symbol = memo_paths.mirrored_symbol( + "DefaultOverlayComponents", default_overlay_component.__module__ + ) + overlay_import = f'import {{{overlay_symbol}}} from "$/app_components/reflex/app"' + + assert _imports(compile_app_root_from_page_wraps(app, {})) == [ + *app_wrap_imports, + 'import {refs} from "$/utils/state"', + 'import plainToast from "$/utils/helpers/plain_toast"', + overlay_import, + *APP_ROOT_TEMPLATE_IMPORTS, + ] + assert _imports(_compile_contexts(app._state, None)) == [ + 'import { useContext, useMemo, useState, createElement, useEffect } from "react"', + 'import { applyDelta, ReflexEvent, refs } from "$/utils/state"', + 'import { hydrateClientStorage, useEventLoop } from "$/utils/socket"', + ( + "import { ColorModeContext, UploadFilesContext, DispatchContext, " + "EventLoopContext, StateStoreContext, registerApp, eventLoop } " + 'from "$/utils/context-registry"' + ), + 'import { jsx } from "@emotion/react";', + ] + + app.toaster = rx.toast.provider() + toast_symbol = memo_paths.mirrored_symbol( + "MemoizedToastProvider", _compile_app.__module__ + ) + assert _imports(compile_app_root_from_page_wraps(app, {})) == [ + *app_wrap_imports, + f'import {{{toast_symbol}}} from "$/app_components/reflex/compiler/compiler"', + overlay_import, + *APP_ROOT_TEMPLATE_IMPORTS, + ] + + def test_minimal_static_app_wrap_omits_state_providers( mocker: MockerFixture, ) -> None: @@ -3619,6 +3768,8 @@ def page(): return Fragment1.create(Fragment3.create()) app.add_page(page) + # A toaster the app configures is in the chain whether or not a toast is sent. + app.toaster = rx.toast.provider() app._compile() app_js_contents = ( web_dir / constants.Dirs.PAGES / constants.PageNames.APP_ROOT @@ -5631,11 +5782,11 @@ def test_client_error_event_name_matches_handler(): def test_client_error_constants_match_frontend(): - """The socket event and error types are duplicated as literals in state.js. + """The socket event and error types are duplicated as literals in socket.js. Nothing at runtime keeps the two definitions in sync, so pin them here. """ - state_js = (Templates.Dirs.WEB_TEMPLATE / "utils/state.js").read_text() + state_js = (Templates.Dirs.WEB_TEMPLATE / "utils/socket.js").read_text() assert ( f'const CLIENT_ERROR_EVENT = "{constants.SocketEvent.CLIENT_ERROR}"' in state_js ) From 0bb8a710811f5e813f01aaf647efe2e7317012f4 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 04:56:54 +0000 Subject: [PATCH 08/26] Add UIPlugin and rx.ui.box, compiled to a plain div through StyleX UIPlugin wires StyleX into the app's Vite build: the compiler and its plugin as development dependencies, the javascript package copied to .web/reflex-ui, and base.css imported first by the root stylesheet to declare the cascade layer order. UIComponent renders a plain element. Its style is emitted as a stylex.create declaration into whichever module renders the element, and spread with stylex.props, which StyleX folds to a class name string. A component held in state falls back to an inline style. The Vite wrapper fixes the React Router build (the renamed stylesheet), names the chunk that links the stylesheet after the compiled styles so a changed style never alters a file under an unchanged name, and loads the StyleX development module from the client entry. Claude-Session: https://claude.ai/code/session_014AwvTPBw2eYQiwgtLmDkpC --- news/+ui-plugin.feature.md | 1 + .../+rendering-dynamic-component.feature.md | 1 + .../src/reflex_base/components/dynamic.py | 34 +++ packages/reflex-components-ui/README.md | 62 +++- .../reflex-components-ui/js/src/README.md | 12 +- packages/reflex-components-ui/js/src/base.css | 20 ++ .../js/src/vite-plugin-stylex.js | 136 +++++++++ .../tests/vite-plugin-stylex-version.test.js | 18 ++ .../js/tests/vite-plugin-stylex.test.js | 202 ++++++++++++ .../news/+ui-plugin.feature.md | 7 + packages/reflex-components-ui/pyproject.toml | 2 +- .../src/reflex_components_ui/__init__.py | 4 +- .../src/reflex_components_ui/base.py | 221 ++++++++++++++ .../src/reflex_components_ui/constants.py | 11 + .../reflex_components_ui/layout/__init__.py | 1 + .../src/reflex_components_ui/layout/box.py | 19 ++ .../src/reflex_components_ui/plugin.py | 127 ++++++++ .../reflex_components_ui/style/__init__.py | 1 + .../src/reflex_components_ui/style/emit.py | 169 +++++++++++ .../reflex_components_ui/styles/__init__.py | 1 + .../src/reflex_components_ui/styles/box.py | 10 + pyi_hashes.json | 3 + reflex/plugins/__init__.py | 39 +++ .../tests_playwright/test_ui_components.py | 287 ++++++++++++++++++ tests/units/plugins/test_init.py | 99 ++++++ .../reflex_base/components/test_dynamic.py | 23 ++ tests/units/reflex_components_ui/conftest.py | 63 ++++ .../reflex_components_ui/layout/__init__.py | 0 .../reflex_components_ui/layout/test_box.py | 50 +++ .../reflex_components_ui/style/__init__.py | 0 .../reflex_components_ui/style/test_emit.py | 138 +++++++++ tests/units/reflex_components_ui/test_base.py | 267 ++++++++++++++++ .../reflex_components_ui/test_js_package.py | 6 +- .../units/reflex_components_ui/test_plugin.py | 92 ++++++ 34 files changed, 2117 insertions(+), 9 deletions(-) create mode 100644 news/+ui-plugin.feature.md create mode 100644 packages/reflex-base/news/+rendering-dynamic-component.feature.md create mode 100644 packages/reflex-components-ui/js/src/base.css create mode 100644 packages/reflex-components-ui/js/src/vite-plugin-stylex.js create mode 100644 packages/reflex-components-ui/js/tests/vite-plugin-stylex-version.test.js create mode 100644 packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js create mode 100644 packages/reflex-components-ui/news/+ui-plugin.feature.md create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/base.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/__init__.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/box.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/plugin.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/style/emit.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/__init__.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/box.py create mode 100644 tests/integration/tests_playwright/test_ui_components.py create mode 100644 tests/units/plugins/test_init.py create mode 100644 tests/units/reflex_components_ui/conftest.py create mode 100644 tests/units/reflex_components_ui/layout/__init__.py create mode 100644 tests/units/reflex_components_ui/layout/test_box.py create mode 100644 tests/units/reflex_components_ui/style/__init__.py create mode 100644 tests/units/reflex_components_ui/style/test_emit.py create mode 100644 tests/units/reflex_components_ui/test_base.py create mode 100644 tests/units/reflex_components_ui/test_plugin.py diff --git a/news/+ui-plugin.feature.md b/news/+ui-plugin.feature.md new file mode 100644 index 00000000000..dab4dda3d78 --- /dev/null +++ b/news/+ui-plugin.feature.md @@ -0,0 +1 @@ +Add `rx.plugins.UIPlugin`, which compiles the styles of the `rx.ui` components. It comes with the `ui` extra: `pip install 'reflex[ui]'`. diff --git a/packages/reflex-base/news/+rendering-dynamic-component.feature.md b/packages/reflex-base/news/+rendering-dynamic-component.feature.md new file mode 100644 index 00000000000..31e31fe49d1 --- /dev/null +++ b/packages/reflex-base/news/+rendering-dynamic-component.feature.md @@ -0,0 +1 @@ +Add `reflex_base.components.dynamic.is_rendering_dynamic_component()`, which a component can call while it renders to learn that its code will be evaluated in the browser at runtime and skip what depends on the frontend build. diff --git a/packages/reflex-base/src/reflex_base/components/dynamic.py b/packages/reflex-base/src/reflex_base/components/dynamic.py index a32e4cddff1..d6e22830038 100644 --- a/packages/reflex-base/src/reflex_base/components/dynamic.py +++ b/packages/reflex-base/src/reflex_base/components/dynamic.py @@ -1,5 +1,6 @@ """Components that are dynamically generated on the backend.""" +import contextvars import dataclasses import json from typing import TYPE_CHECKING, Any, Union @@ -17,6 +18,24 @@ if TYPE_CHECKING: from reflex_base.components.component import Component +# Set while the code of a dynamic component is generated. +_RENDERING_DYNAMIC_COMPONENT: contextvars.ContextVar[bool] = contextvars.ContextVar( + "rendering_dynamic_component", default=False +) + + +def is_rendering_dynamic_component() -> bool: + """Whether the code being generated is evaluated in the browser at runtime. + + The code of a dynamic component never passes through the frontend build, so + a component whose output relies on a build step checks this to render + something that works without one. + + Returns: + True while a dynamic component is being serialized. + """ + return _RENDERING_DYNAMIC_COMPONENT.get() + def __getattr__(name: str) -> Any: """Provide the module-level globals that moved onto `RegistrationContext`. @@ -166,6 +185,21 @@ def load_dynamic_serializer(): def make_component(component: Component) -> str: """Generate the code for a dynamic component. + Args: + component: The component to generate code for. + + Returns: + The generated code + """ + token = _RENDERING_DYNAMIC_COMPONENT.set(True) + try: + return generate_component_code(component) + finally: + _RENDERING_DYNAMIC_COMPONENT.reset(token) + + def generate_component_code(component: Component) -> str: + """Generate the module a dynamic component is evaluated from. + Args: component: The component to generate code for. diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 6c8e0cb9850..ca9a800ead3 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -5,19 +5,34 @@ The styles are compiled by [StyleX](https://stylexjs.com) in the app's own Vite build, and behaviour comes from the browser and a few small hooks, so no component library ships to the browser. -The package is a pre-release and has no components yet. It is an optional extra -of Reflex, exposed as `rx.ui`: +The package is a pre-release. It is an optional extra of Reflex, exposed as +`rx.ui`, and its components need the plugin that compiles their styles: ``` pip install 'reflex[ui]' ``` +```python +# rxconfig.py +config = rx.Config(app_name="shop", plugins=[rx.plugins.UIPlugin()]) +``` + +Without the plugin a compile stops with `rx.ui components need +rx.plugins.UIPlugin() in rxconfig.py plugins.` + ## Layout ``` src/reflex_components_ui/ the python package: the rx.ui namespace + plugin.py UIPlugin: the build wiring of an app + base.py UIComponent: a plain element and its StyleX source + style/emit.py a lowered style to a stylex.create declaration + styles/ the look of each component, one table per module + layout/ the components js/ the javascript package, with its own tooling src/ what ships: copied into an app at .web/reflex-ui/ + base.css the cascade layer order and the color scheme switch + vite-plugin-stylex.js the StyleX Vite plugin, fitted to the Reflex build tests/ vitest scripts/generate.js writes and checks the generated files hatch_build.py embeds js/src in the wheel @@ -29,6 +44,43 @@ hatch_build.py embeds js/src in the wheel edit needs no rebuild. A change under `js/src` is a change to this package: its news fragment goes in `news/`. +## How a component reaches the browser + +`rx.ui.box("hello", style={"padding": "4px"})` compiles to a `div`, with its +style declared in the module that renders it: + +```js +import * as stylex from "@stylexjs/stylex" + +const sx_f49d6b3475 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "padding": "4px"} }); + +jsx("div",{...stylex.props(sx_f49d6b3475.s)},"hello") +``` + +StyleX then folds the call into `className: "x9f619 x1lliihq xfawy5m"` and +appends the three rules to the app's stylesheet. It only does so for a style +declared in the same module as the element, with literal arguments, so: + +- A component is a subclass of `UIComponent` with a `styles` table. It imports + nothing: `add_custom_code` emits the declaration, which the compiler places + in whichever module renders the element (a page, or the module of a memo). +- A declaration is named after its content, so equal styles on many elements + are declared once per module. +- A literal `class_name` is folded into the same string. One bound to state is + joined to it at runtime. +- A component held in state is evaluated in the browser and never reaches + StyleX: its styles fall back to an inline `style`, and a conditional style + there is a compile error. + +`base.css` declares the cascade order once: the resets (Reflex, Tailwind's +`theme` and `base`), then `reflex-ui` (a component's styles merged with the +element's `style`), then Tailwind's `components` and `utilities`. Unlayered +CSS, such as an app's stylesheet, Emotion and Radix Themes, beats all of them. + +Until the style package lands (`style/lower.py`, `style/merge.py`), a `style` +takes flat properties with literal values, and `_lower_literal_styles` in +`base.py` stands in for it. + ## Working on it From the repository root: @@ -39,8 +91,14 @@ uv run python scripts/make_pyi.py # regenerate the npm --prefix packages/reflex-components-ui/js ci # install the javascript tooling npm --prefix packages/reflex-components-ui/js run check # lint, type-check, generated files, tests: what CI runs npm --prefix packages/reflex-components-ui/js run generate # rewrite the generated files +uv run pytest tests/integration/tests_playwright/test_ui_components.py # a real app in dev and prod: needs network for the npm packages ``` +The integration test builds one shared app (`UIComponentsApp`) with Tailwind +beside the plugin and reads computed styles, the prerendered page with +JavaScript off, and the files of the production build. Add a page or an +element to that app for a new component rather than a new app. + `run check` is `run lint` (ESLint), `run typecheck` (`tsc` over the JSDoc, nothing emitted), `run generate:check` and `test` (vitest), which also run on their own. diff --git a/packages/reflex-components-ui/js/src/README.md b/packages/reflex-components-ui/js/src/README.md index 20d2f7771ea..0da55a10df3 100644 --- a/packages/reflex-components-ui/js/src/README.md +++ b/packages/reflex-components-ui/js/src/README.md @@ -1,8 +1,14 @@ # reflex-ui -The javascript `rx.ui` components are compiled against. Reflex copies this -directory into an app's `.web/reflex-ui/` from the `reflex-components-ui` -package, so an edit made here in an app is overwritten. +The javascript `rx.ui` components are compiled against. `rx.plugins.UIPlugin` +copies this directory into an app's `.web/reflex-ui/` from the +`reflex-components-ui` package on every compile, so an edit made here in an app +is overwritten. + +- `base.css` is imported first by the app's stylesheet: it orders the cascade + layers and switches the color scheme. +- `vite-plugin-stylex.js` is the plugin `vite.config.js` loads to compile the + styles. The source, its tests and its rules live in [`packages/reflex-components-ui/js`](https://github.com/reflex-dev/reflex/tree/main/packages/reflex-components-ui/js). diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css new file mode 100644 index 00000000000..3d6a5d39f1d --- /dev/null +++ b/packages/reflex-components-ui/js/src/base.css @@ -0,0 +1,20 @@ +/* + * The cascade order of an app that uses rx.ui, declared once so that it does + * not depend on which stylesheet loads first. Later layers win: + * + * __reflex_base, theme, base resets: Reflex's own, Tailwind's theme and preflight + * reflex-ui the components, then the `style` of an element + * components, utilities Tailwind, so a `class_name` utility overrides a component + * + * Unlayered CSS (an app's stylesheets, Emotion, Radix Themes) beats every layer. + */ +@layer __reflex_base, theme, base, reflex-ui, components, utilities; + +/* Reflex's color mode provider sets one of these classes on the root element. */ +html.light { + color-scheme: light; +} + +html.dark { + color-scheme: dark; +} diff --git a/packages/reflex-components-ui/js/src/vite-plugin-stylex.js b/packages/reflex-components-ui/js/src/vite-plugin-stylex.js new file mode 100644 index 00000000000..2e0688c07f0 --- /dev/null +++ b/packages/reflex-components-ui/js/src/vite-plugin-stylex.js @@ -0,0 +1,136 @@ +// The StyleX Vite plugin, adapted to the React Router build of a Reflex app. +// +// StyleX appends the styles it compiled to a stylesheet of the build once every +// chunk is rendered and named, and gives that stylesheet a new name. Three +// things around that are put right here: +// +// - React Router has recorded the old name by then, and fails when it moves +// the assets of the server build. +// - A chunk that holds the address of the stylesheet is edited after its own +// name was derived from its content, so a change of style would alter the +// chunk under an unchanged name, and a cached copy would ask for a +// stylesheet that is gone. +// - React Router renders the document itself, so nothing loads the module +// through which StyleX delivers the styles while developing. + +import { basename } from "node:path"; + +import stylexUnplugin from "@stylexjs/unplugin"; + +// The module of the unplugin that fetches the compiled styles in development +// and fetches them again when one changes. +const DEV_RUNTIME = "virtual:stylex:runtime"; + +// The module of an app that runs first in the browser. +const CLIENT_ENTRY = /\/app\/entry\.client\.[jt]sx?$/; + +/** + * The hooks of a Vite plugin that are used here. + * + * @typedef {object} VitePlugin + * @property {string} name + * @property {"serve" | "build"} [apply] + * @property {(this: any, outputOptions: unknown, bundle: Bundle) => void} [generateBundle] + * @property {(chunk: { moduleIds: string[] }) => string | void} [augmentChunkHash] + * @property {(code: string, id: string) => string | null} [transform] + * @property {() => string} [__stylexCollectCss] Internal to the unplugin: the + * stylesheet of every style compiled so far. + */ + +/** + * The files of a build, by name. + * + * @typedef {Record } }>} Bundle + */ + +/** + * Keep the assets a chunk has recorded in step with the stylesheet StyleX + * renames. + * + * @param {VitePlugin} plugin A plugin of the StyleX unplugin. + * @returns {VitePlugin} The plugin, its `generateBundle` wrapped. + */ +function keepRecordedAssets(plugin) { + const generateBundle = plugin.generateBundle; + if (typeof generateBundle !== "function") return plugin; + return { + ...plugin, + generateBundle(outputOptions, bundle) { + const stylesheets = Object.keys(bundle).filter((name) => + name.endsWith(".css"), + ); + // Rolldown does not expose a file emitted in this hook through `bundle`, + // so record the name the unplugin asks for instead. + /** @type {string | undefined} */ + let renamedTo; + const context = new Proxy(this, { + get(target, key) { + const value = Reflect.get(target, key, target); + if (key === "getFileName") { + return (/** @type {string} */ referenceId) => + (renamedTo = value.call(target, referenceId)); + } + return typeof value === "function" ? value.bind(target) : value; + }, + }); + generateBundle.call(context, outputOptions, bundle); + const removed = stylesheets.filter((name) => !(name in bundle)); + if (removed.length !== 1 || !renamedTo) return; + for (const item of Object.values(bundle)) { + const assets = item.viteMetadata?.importedAssets; + if (assets?.delete(removed[0])) assets.add(renamedTo); + } + }, + }; +} + +/** + * Compile the StyleX styles of a Reflex app into one of its stylesheets. + * + * @param {string} stylesheet The name, without its extension, of the + * stylesheet the compiled styles are appended to. + * @param {Record} [options] Options of `@stylexjs/unplugin`. + * @returns {VitePlugin[]} The plugins to add to the Vite configuration. + */ +export default function stylex(stylesheet, options) { + /** @type {VitePlugin[]} */ + const plugins = [ + stylexUnplugin.vite({ + ...options, + cssInjectionTarget: (/** @type {string} */ fileName) => + basename(fileName).startsWith(stylesheet), + }), + ].flat(); + const collectors = plugins.flatMap( + (plugin) => plugin.__stylexCollectCss ?? [], + ); + if (collectors.length === 0) { + throw new Error( + "reflex-ui: @stylexjs/unplugin no longer exposes the styles it collected (__stylexCollectCss), which the names of the built files depend on. Install the version of @stylexjs/unplugin that reflex-components-ui pins.", + ); + } + return [ + ...plugins.map(keepRecordedAssets), + { + name: "reflex-ui:stylex-hash", + apply: "build", + // The chunk that holds the address of the stylesheet is named after the + // styles too, as they are what moves that address. + augmentChunkHash(chunk) { + const holdsAddress = chunk.moduleIds.some( + (id) => basename(id.split("?")[0]) === `${stylesheet}.css`, + ); + if (holdsAddress) + return collectors.map((collect) => collect()).join(""); + }, + }, + { + name: "reflex-ui:stylex-dev", + apply: "serve", + transform(code, id) { + if (!CLIENT_ENTRY.test(id)) return null; + return `import ${JSON.stringify(DEV_RUNTIME)};\n${code}`; + }, + }, + ]; +} diff --git a/packages/reflex-components-ui/js/tests/vite-plugin-stylex-version.test.js b/packages/reflex-components-ui/js/tests/vite-plugin-stylex-version.test.js new file mode 100644 index 00000000000..1d05a2f620b --- /dev/null +++ b/packages/reflex-components-ui/js/tests/vite-plugin-stylex-version.test.js @@ -0,0 +1,18 @@ +// @vitest-environment node +// The wrapper names the built files after styles it reads from an internal of +// the unplugin. A version without it must stop the build, not degrade it. +import { expect, test, vi } from "vitest"; + +import stylex from "../src/vite-plugin-stylex.js"; + +vi.mock("@stylexjs/unplugin", () => ({ + default: { vite: () => ({ name: "@stylexjs/unplugin" }) }, +})); + +test("an unplugin that does not expose the collected styles is rejected", () => { + expect(() => stylex("__reflex_global_styles")).toThrow( + new Error( + "reflex-ui: @stylexjs/unplugin no longer exposes the styles it collected (__stylexCollectCss), which the names of the built files depend on. Install the version of @stylexjs/unplugin that reflex-components-ui pins.", + ), + ); +}); diff --git a/packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js b/packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js new file mode 100644 index 00000000000..ab017011427 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js @@ -0,0 +1,202 @@ +// @vitest-environment node +// The Vite plugin an app builds with, driven through the hooks Vite calls. +import { beforeEach, expect, test } from "vitest"; + +import stylex from "../src/vite-plugin-stylex.js"; + +const STYLESHEET = "__reflex_global_styles"; + +// The options `UIPlugin.get_vite_plugins()` writes into vite.config.js, with +// the mode pinned: a build compiles for production whatever runs the tests. +const OPTIONS = { + dev: false, + useCSSLayers: { prefix: "reflex-ui" }, + styleResolution: "application-order", + lightningcssOptions: { minify: true }, +}; + +// A page module as the Reflex compiler emits it: one declaration per distinct +// style, and a literal `class_name` carried inside the `stylex.props` call. +const PAGE = `import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" + +const sx_b26ac4fb71 = stylex.create({ s: {"boxSizing": "border-box", "display": "block"} }); +const sx_f49d6b3475 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "padding": "4px"} }); + +export default function Component() { + return jsx("main",{},jsx("div",{...stylex.props(sx_b26ac4fb71.s)},"hello"),jsx("div",{...stylex.props(sx_f49d6b3475.s, { $$css: true, className: "p-8" })},"padded")) +} +`; + +const COMPILED_CSS = + "@layer reflex-ui.priority1{.xfawy5m{padding:4px}}@layer reflex-ui.priority2{.x9f619{box-sizing:border-box}.x1lliihq{display:block}}"; + +beforeEach(() => { + // The unplugin keeps the styles of every build of the process. + delete (/** @type {any} */ (globalThis).__stylex_unplugin_store); +}); + +/** + * Find the plugin that has a hook. + * + * @param {ReturnType} plugins + * @param {"transform" | "generateBundle" | "augmentChunkHash"} hook + * @param {string} [name] The name of the plugin, when several have the hook. + * @returns {any} The plugin. + */ +function withHook(plugins, hook, name) { + const found = plugins.filter( + (plugin) => plugin[hook] && (!name || plugin.name === name), + ); + expect(found.map((plugin) => plugin.name)).toHaveLength(1); + return found[0]; +} + +/** + * Compile a module the way Vite does. + * + * @param {ReturnType} plugins + * @param {string} code + * @param {string} id + * @returns {Promise} The compiled module. + */ +async function transform(plugins, code, id) { + const { transform } = withHook(plugins, "transform", "@stylexjs/unplugin"); + const handler = + typeof transform === "function" ? transform : transform.handler; + const result = await handler.call({}, code, id); + return result.code; +} + +test("a page folds to class name strings and leaves no call into StyleX", async () => { + const plugins = stylex(STYLESHEET, OPTIONS); + expect( + await transform(plugins, PAGE, "/app/.web/app/routes/_index.jsx"), + ).toBe(`import * as stylex from "@stylexjs/stylex"; +import { jsx } from "@emotion/react"; +export default function Component() { + return jsx("main", {}, jsx("div", { + ...{ + className: "x9f619 x1lliihq" + } + }, "hello"), jsx("div", { + ...{ + className: "x9f619 x1lliihq xfawy5m p-8" + } + }, "padded")); +}`); +}); + +test("the styles are appended to the stylesheet, and the chunk that links it follows the rename", async () => { + const plugins = stylex(STYLESHEET, OPTIONS); + await transform(plugins, PAGE, "/app/.web/app/routes/_index.jsx"); + + const oldName = `assets/${STYLESHEET}-AAAAAAAA.css`; + const newName = `assets/${STYLESHEET}-BBBBBBBB.css`; + /** @type {Record} */ + const bundle = { + "assets/other-CCCCCCCC.css": { + type: "asset", + fileName: "assets/other-CCCCCCCC.css", + source: ".other{}", + }, + [oldName]: { type: "asset", fileName: oldName, source: ".reset{}" }, + "assets/root-DDDDDDDD.js": { + type: "chunk", + code: `const href="/${oldName}";`, + viteMetadata: { + importedAssets: new Set([oldName]), + importedCss: new Set(), + }, + }, + "assets/_index-EEEEEEEE.js": { + type: "chunk", + code: "export default 1;", + viteMetadata: { importedAssets: new Set(), importedCss: new Set() }, + }, + }; + /** @type {unknown[]} */ + const emitted = []; + const context = { + emitFile(/** @type {unknown} */ file) { + emitted.push(file); + return "reference"; + }, + getFileName: (/** @type {string} */ reference) => + reference === "reference" ? newName : undefined, + }; + withHook(plugins, "generateBundle").generateBundle.call(context, {}, bundle); + + expect(emitted).toEqual([ + { + type: "asset", + name: `${STYLESHEET}.css`, + source: `.reset{}\n${COMPILED_CSS}`, + }, + ]); + expect(Object.keys(bundle)).toEqual([ + "assets/other-CCCCCCCC.css", + "assets/root-DDDDDDDD.js", + "assets/_index-EEEEEEEE.js", + ]); + expect(bundle["assets/root-DDDDDDDD.js"].code).toBe( + `const href="/${newName}";`, + ); + // What React Router moves from the server build into the client build. + expect(bundle["assets/root-DDDDDDDD.js"].viteMetadata.importedAssets).toEqual( + new Set([newName]), + ); + expect( + bundle["assets/_index-EEEEEEEE.js"].viteMetadata.importedAssets, + ).toEqual(new Set()); +}); + +test("the chunk that links the stylesheet is named after the compiled styles", async () => { + const plugins = stylex(STYLESHEET, OPTIONS); + const plugin = withHook(plugins, "augmentChunkHash"); + expect(plugin.apply).toBe("build"); + const root = { + moduleIds: [ + "/app/.web/app/root.jsx", + `/app/.web/styles/${STYLESHEET}.css?url`, + ], + }; + const page = { + moduleIds: [ + "/app/.web/app/routes/_index.jsx", + "/app/.web/styles/other.css", + ], + }; + + await transform(plugins, PAGE, "/app/.web/app/routes/_index.jsx"); + expect(plugin.augmentChunkHash(root)).toBe(COMPILED_CSS); + // A chunk that does not hold the address keeps its name when a style changes. + expect(plugin.augmentChunkHash(page)).toBe(undefined); + + await transform( + plugins, + PAGE.replace('"padding": "4px"', '"padding": "5px"'), + "/app/.web/app/routes/_index.jsx", + ); + expect(plugin.augmentChunkHash(root)).toBe( + COMPILED_CSS.replace(".xfawy5m{padding:4px}", ".x14odnwx{padding:5px}"), + ); +}); + +test("the development server loads the styles from the client entry", () => { + const plugins = stylex(STYLESHEET, OPTIONS); + const [plugin] = plugins.filter( + ({ name }) => name === "reflex-ui:stylex-dev", + ); + expect(plugin.apply).toBe("serve"); + expect( + plugin.transform?.("hydrate();", "/app/.web/app/entry.client.js"), + ).toBe('import "virtual:stylex:runtime";\nhydrate();'); + expect(plugin.transform?.("render();", "/app/.web/app/root.jsx")).toBe(null); + expect( + plugin.transform?.( + "x();", + "/app/.web/node_modules/pkg/app/entry.client.mjs", + ), + ).toBe(null); +}); diff --git a/packages/reflex-components-ui/news/+ui-plugin.feature.md b/packages/reflex-components-ui/news/+ui-plugin.feature.md new file mode 100644 index 00000000000..f95acd03894 --- /dev/null +++ b/packages/reflex-components-ui/news/+ui-plugin.feature.md @@ -0,0 +1,7 @@ +Add `rx.plugins.UIPlugin` and the first component, `rx.ui.box`: a plain `
` whose styles StyleX compiles into the app's stylesheet, so the page ships class names and no styling runtime. Add the plugin to use any `rx.ui` component: + +```python +config = rx.Config(app_name="shop", plugins=[rx.plugins.UIPlugin()]) +``` + +A box takes literal `style` values for now; a Tailwind utility in `class_name` overrides them, and an app stylesheet overrides both. diff --git a/packages/reflex-components-ui/pyproject.toml b/packages/reflex-components-ui/pyproject.toml index 01c1424d0ad..716454490bf 100644 --- a/packages/reflex-components-ui/pyproject.toml +++ b/packages/reflex-components-ui/pyproject.toml @@ -15,7 +15,7 @@ classifiers = [ "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", ] -dependencies = ["reflex-base >= 0.11.0"] +dependencies = ["reflex-base >= 0.11.1.dev0"] [tool.hatch.version] source = "uv-dynamic-versioning" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py index 67be8207a7a..6733918892b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -6,7 +6,9 @@ _SUBMODULES: set[str] = set() -_SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = {} +_SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { + "layout.box": ["box"], +} __getattr__, __dir__, __all__ = lazy_loader.attach( __name__, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/base.py b/packages/reflex-components-ui/src/reflex_components_ui/base.py new file mode 100644 index 00000000000..8e8623927ea --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -0,0 +1,221 @@ +"""The base class of the rx.ui components.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, ClassVar, TypedDict + +from reflex_base.components.component import Component +from reflex_base.components.dynamic import is_rendering_dynamic_component +from reflex_base.components.tags import CommonTag +from reflex_base.plugins import get_plugin +from reflex_base.utils import format +from reflex_base.utils.exceptions import ConfigError +from reflex_base.utils.imports import ImportDict, ImportVar +from reflex_base.vars.base import Var +from reflex_base.vars.number import LiteralNumberVar +from reflex_base.vars.sequence import LiteralStringVar + +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style.emit import ( + LoweredStyle, + StyleXStyle, + UnsupportedStyleError, + emit, + inline, + props_call, +) + +MISSING_PLUGIN_ERROR = ( + "rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins." +) + +# The styles of an element. The generated TypedDict of step 8a replaces it. +StyleProps = Mapping[str, Any] + + +class CompoundStyle(TypedDict): + """Styles for a combination of props. + + Attributes: + when: The value each prop must have, by prop name. + style: The styles applied when every prop matches. + """ + + when: dict[str, Any] + style: StyleProps + + +class ComponentStyles(TypedDict, total=False): + """The look of a component. + + Attributes: + base: The styles of every instance. + variants: The styles of a prop value: prop name, then prop value. + compound: The styles of a combination of props. + parts: The look of inner elements, such as a switch thumb, by name. + """ + + base: StyleProps + variants: dict[str, dict[str, StyleProps]] + compound: list[CompoundStyle] + parts: dict[str, ComponentStyles] + + +def _lower_literal_styles(component: UIComponent) -> LoweredStyle: + """Merge the base styles of a component with its literal ``style``. + + A stand-in: the ``lower`` and ``merge`` of the style package replace it, + and bring variants, nested blocks, responsive values and shorthands. + + Args: + component: The component to style. + + Returns: + The lowered style of the component's element, the user's style last. + + Raises: + UnsupportedStyleError: If the component or its style needs what only + the real lowering provides. + """ + name = component._display_name() + styles = component.styles + if "variants" in styles or "compound" in styles: + msg = f"{name}: variant and compound styles are not compiled yet." + raise UnsupportedStyleError(msg) + lowered = dict(styles.get("base", {})) + for prop, value in component.style.items(): + if isinstance(value, (LiteralStringVar, LiteralNumberVar)): + value = value._var_value + elif not isinstance(value, Var): + msg = ( + f'{name}: the style "{prop}" is a nested block or a list, which ' + "rx.ui components cannot compile yet. Use flat properties with " + "literal values." + ) + raise UnsupportedStyleError(msg) + lowered[prop] = value + return lowered + + +class UIComponent(Component): + """A component that renders a plain element styled through StyleX. + + No library is imported: the element's styles are declared in the module + that renders it, where the StyleX compiler folds them into class names. + """ + + tag = "div" + + _is_tag_in_global_scope: ClassVar[bool] = True + + # The component's own look. + styles: ClassVar[ComponentStyles] = {} + + @classmethod + def _display_name(cls) -> str: + """Get the name an app refers to the component by. + + Returns: + The name, such as ``rx.ui.box``. + """ + return f"rx.ui.{format.to_snake_case(cls.__name__)}" + + def _stylex(self) -> StyleXStyle | None: + """Get the StyleX source of the element's style. + + Returns: + The declaration of the style, or None when the element has none. + + Raises: + ConfigError: If the plugin that compiles the styles is not configured. + """ + if get_plugin(UIPlugin) is None: + raise ConfigError(MISSING_PLUGIN_ERROR) + return emit(_lower_literal_styles(self), self._display_name()) + + def add_imports(self) -> ImportDict: + """Import StyleX, which the build compiles away. + + Returns: + The import, or nothing for code that never reaches the build. + """ + if is_rendering_dynamic_component(): + return {} + # The plugin installs it as a development dependency. + return { + "@stylexjs/stylex": ImportVar( + tag="*", alias="stylex", is_default=True, install=False + ) + } + + def add_custom_code(self) -> list[str]: + """Declare the element's style in the module that renders it. + + Returns: + The ``stylex.create`` declaration, or nothing for code that never + reaches the build. + """ + if is_rendering_dynamic_component(): + return [] + style = self._stylex() + return [] if style is None else [style.declaration] + + def _get_style(self) -> dict: + """Get the props that carry the style: none, as ``_render`` adds them. + + Returns: + An empty dictionary: an rx.ui component never has a ``css`` prop. + """ + return {} + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the element with its style. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with a ``stylex.props`` spread, or with an inline style in + code that never reaches the build. + """ + tag = super()._render(props) + if is_rendering_dynamic_component(): + style = inline(_lower_literal_styles(self), self._display_name()) + return tag.add_props(style=style) if style else tag + style = self._stylex() + if style is None: + return tag + return _add_stylex_props(tag, style.ref) + + +def _add_stylex_props(tag: CommonTag, ref: str) -> CommonTag: + """Give a tag the class names of a style, beside its own. + + Args: + tag: The rendered element. + ref: The expression naming the style. + + Returns: + The tag with a ``stylex.props`` spread, or with one ``className`` + expression when its own class names come from state. + """ + class_name = tag.props.get("className") + if class_name is None: + return tag.set(special_props=[*tag.special_props, Var(props_call((ref,)))]) + if isinstance(class_name, LiteralStringVar): + # A spread would replace the attribute, so both fold into one string. + return tag.remove_props("className").set( + special_props=[ + *tag.special_props, + Var(props_call((ref,), class_name._var_value)), + ] + ) + return tag.add_props( + class_name=Var( + # Parenthesized: the expression may be a conditional. + f'({class_name!s}) + " " + {props_call((ref,))}.className', + _var_type=str, + _var_data=class_name._get_all_var_data(), + ) + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/constants.py b/packages/reflex-components-ui/src/reflex_components_ui/constants.py index 6538b39d010..8a3ab3360d1 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/constants.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/constants.py @@ -24,3 +24,14 @@ def _js_src_dir(root_dir: Path) -> Path: # The javascript package's source, copied into the web directory of a project. JS_SRC = _js_src_dir(Path(__file__).parent) + +# The directory of the web directory that JS_SRC is copied into. +WEB_DIR = "reflex-ui" + +# StyleX is 0.x and has broken its output between patch releases, so an app +# installs the exact version the javascript package is developed against. +STYLEX_VERSION = "0.19.2" + +# The CSS compiler behind StyleX and Vite. The Vite configuration imports it to +# name the feature it must leave alone. +LIGHTNINGCSS_VERSION = "1.33.0" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/__init__.py new file mode 100644 index 00000000000..fb83de38a52 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/__init__.py @@ -0,0 +1 @@ +"""Layout components.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/box.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/box.py new file mode 100644 index 00000000000..d3cf17be3a1 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/box.py @@ -0,0 +1,19 @@ +"""A box: the plain element other layouts are built from.""" + +from __future__ import annotations + +from typing import ClassVar + +from reflex_components_ui.base import ComponentStyles, UIComponent +from reflex_components_ui.styles.box import BOX + + +class Box(UIComponent): + """A block element with no look of its own.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = BOX + + +box = Box.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/plugin.py b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py new file mode 100644 index 00000000000..af36a153004 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py @@ -0,0 +1,127 @@ +"""The plugin that compiles the styles of the rx.ui components.""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Sequence +from pathlib import Path + +from reflex_base.constants import Dirs, Ext, PageNames +from reflex_base.plugins import Plugin, VitePluginEntry + +from reflex_components_ui.constants import ( + JS_SRC, + LIGHTNINGCSS_VERSION, + STYLEX_VERSION, + WEB_DIR, +) + +# Declares the cascade layers, so it comes before any stylesheet that names one. +BASE_STYLESHEET_IMPORT = f"@import url('../{WEB_DIR}/base.css');" + +# The cascade layer the styles of the components are compiled into. +CSS_LAYER = "reflex-ui" + +_VITE_PLUGIN = VitePluginEntry( + imports=( + f'import reflexUIStylex from "./{WEB_DIR}/vite-plugin-stylex.js"', + 'import { Features as lightningcssFeatures } from "lightningcss"', + ), + call=f"""reflexUIStylex("{PageNames.STYLESHEET_ROOT}", {{ + useCSSLayers: {{ prefix: "{CSS_LAYER}" }}, + styleResolution: "application-order", + lightningcssOptions: {{ minify: true, exclude: lightningcssFeatures.LightDark }}, + }})""", +) + + +def add_base_stylesheet(content: str) -> str: + """Import the base stylesheet ahead of every other one in the root stylesheet. + + Args: + content: The root stylesheet. + + Returns: + The root stylesheet with the import, unchanged when it has it already. + """ + if BASE_STYLESHEET_IMPORT in content: + return content + lines = content.splitlines() + # After the leading `@layer` statement: one placed between two imports + # would make the second import invalid. + first_import = next( + (index for index, line in enumerate(lines) if line.startswith("@import")), + len(lines), + ) + lines.insert(first_import, BASE_STYLESHEET_IMPORT) + return "\n".join(lines) + + +@dataclasses.dataclass +class Theme: + """The look of the rx.ui components across an app. It has no options yet.""" + + +@dataclasses.dataclass +class UIPlugin(Plugin): + """Compile the styles of the rx.ui components into the app's stylesheet. + + Attributes: + theme: The look of the components across the app. + """ + + theme: Theme = dataclasses.field(default_factory=Theme) + + def get_frontend_development_dependencies(self, **context) -> list[str]: + """Get the packages that compile the styles. + + They only run in the build: the compiled pages import none of them. + + Args: + **context: The context for the plugin. + + Returns: + The StyleX compiler and its Vite plugin, at their exact versions. + """ + return [ + f"@stylexjs/stylex@{STYLEX_VERSION}", + f"@stylexjs/unplugin@{STYLEX_VERSION}", + f"lightningcss@{LIGHTNINGCSS_VERSION}", + ] + + def get_static_assets(self, **context) -> Sequence[tuple[Path, str | bytes]]: + """Get the javascript package, as files of the web directory. + + Args: + **context: The context for the plugin. + + Returns: + Every file of the javascript package and where it is written. + """ + return [ + (WEB_DIR / path.relative_to(JS_SRC), path.read_text(encoding="utf-8")) + for path in sorted(JS_SRC.rglob("*")) + if path.is_file() + ] + + def get_vite_plugins(self, **context) -> Sequence[VitePluginEntry]: + """Get the Vite plugin that compiles the styles. + + Args: + **context: The context for the plugin. + + Returns: + The StyleX plugin, wrapped for the React Router build. + """ + return [_VITE_PLUGIN] + + def pre_compile(self, **context) -> None: + """Import the base stylesheet into the root stylesheet. + + Args: + **context: The context for the plugin. + """ + context["add_modify_task"]( + str(Path(Dirs.STYLES) / (PageNames.STYLESHEET_ROOT + Ext.CSS)), + add_base_stylesheet, + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py new file mode 100644 index 00000000000..70ad8d23cd1 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py @@ -0,0 +1 @@ +"""How the style of an rx.ui component becomes StyleX source.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/emit.py b/packages/reflex-components-ui/src/reflex_components_ui/style/emit.py new file mode 100644 index 00000000000..378fdc00f90 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/emit.py @@ -0,0 +1,169 @@ +"""Turn a lowered style into the StyleX source the compiler places in a module. + +A lowered style is a StyleX style object: a mapping from a camelCase CSS +property to a literal, or to a condition map such as +``{"default": "red", ":hover": "blue"}``. + +StyleX folds ``stylex.props(...)`` into a ``className`` string only when the +style is declared in the module that renders the element, so every distinct +style becomes a declaration of its own, named after its content. The compiler +deduplicates custom code by its text: elements that share a style share one +declaration, in whichever module each of them is rendered. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json +from collections.abc import Mapping +from typing import TypeAlias, cast + +from reflex_base.utils.exceptions import ReflexError +from reflex_base.vars.base import Var + +# A literal, or the value of a property under each condition. +LoweredValue: TypeAlias = "str | int | float | Mapping[str, LoweredValue]" +# What `lower` produces and StyleX compiles: camelCase property to value. +LoweredStyle: TypeAlias = Mapping[str, LoweredValue] + +# The key under which a declaration holds its style. +_KEY = "s" + + +class UnsupportedStyleError(ReflexError, TypeError): + """Raised when an rx.ui component has a style that cannot be compiled.""" + + +@dataclasses.dataclass(frozen=True, slots=True) +class StyleXStyle: + """The StyleX source of one style. + + Attributes: + declaration: The module-level ``stylex.create`` statement. + ref: The expression naming the style, an argument of ``stylex.props``. + """ + + declaration: str + ref: str + + +def _check_value( + value: object, prop: str, component: str, conditions: tuple[str, ...] +) -> None: + """Fail on a value StyleX cannot compile to a class. + + Args: + value: The value of the property, or of one of its conditions. + prop: The style property the value belongs to. + component: The name of the component, for the error message. + conditions: The conditions the value is nested under. + + Raises: + UnsupportedStyleError: If the value is bound to state or is not a + literal or a condition map. + """ + if isinstance(value, Mapping): + for condition, nested in value.items(): + _check_value(nested, prop, component, (*conditions, condition)) + return + # A bool is an int to isinstance, and no CSS value. + if isinstance(value, (str, int, float)) and not isinstance(value, bool): + return + where = f'"{prop}"' + "".join(f' under "{c}"' for c in conditions) + if isinstance(value, Var): + msg = ( + f"{component}: the style {where} is bound to state, which rx.ui " + "components cannot compile yet. Give it a literal value, or set it " + "from state with a class_name." + ) + else: + msg = ( + f"{component}: the style {where} is {value!r}, a " + f"{type(value).__name__}. Use a string or a number, or a mapping " + 'from condition to value such as {"default": "red", ":hover": "blue"}.' + ) + raise UnsupportedStyleError(msg) + + +def emit(style: LoweredStyle, component: str) -> StyleXStyle | None: + """Emit the StyleX declaration of a lowered style. + + Args: + style: The lowered style of one element. + component: The name of the component, for error messages. + + Returns: + The declaration and the expression that refers to it, or None when the + style is empty. + + Raises: + UnsupportedStyleError: If a value is bound to state or is not a literal. + """ + if not style: + return None + for prop, value in style.items(): + _check_value(value, prop, component, ()) + source = json.dumps(style, ensure_ascii=False) + # Named after the source rather than the mapping: two declarations of one + # name in a module would not parse. + name = "sx_" + hashlib.sha256(source.encode()).hexdigest()[:10] + return StyleXStyle( + declaration=f"const {name} = stylex.create({{ {_KEY}: {source} }});", + ref=f"{name}.{_KEY}", + ) + + +def props_call(refs: tuple[str, ...], class_name: str | None = None) -> str: + """Build the ``stylex.props`` call that an element spreads into its props. + + A class name given here is folded into the same ``className`` string as the + styles, so the element keeps a single static attribute. + + Args: + refs: The styles to apply, the last one winning a conflict. + class_name: Literal class names the element also carries. + + Returns: + The JavaScript expression. + """ + args = list(refs) + if class_name: + # A compiled style is a map of class names marked with `$$css`; this + # one carries the element's own classes through the fold. + args.append(f"{{ $$css: true, className: {json.dumps(class_name)} }}") + return f"stylex.props({', '.join(args)})" + + +def inline(style: LoweredStyle, component: str) -> dict[str, str | int | float]: + """Check that a lowered style can be an inline ``style`` attribute. + + The fallback for code that is evaluated in the browser and never reaches + the StyleX compiler. An inline style has no conditions. + + Args: + style: The lowered style of one element. + component: The name of the component, for error messages. + + Returns: + The style, every value a literal. + + Raises: + UnsupportedStyleError: If a value has conditions, is bound to state or + is not a literal. + """ + result: dict[str, str | int | float] = {} + for prop, value in style.items(): + if isinstance(value, Mapping): + conditions = ", ".join(f'"{c}"' for c in value) + msg = ( + f'{component}: the style "{prop}" has conditions ' + f"({conditions}), which a component rendered from state cannot " + "apply: its code is evaluated in the browser and never reaches " + "the StyleX compiler. Use an unconditional value there, or " + "render the component in a page and show it with rx.cond." + ) + raise UnsupportedStyleError(msg) + _check_value(value, prop, component, ()) + result[prop] = cast("str | int | float", value) + return result diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/__init__.py new file mode 100644 index 00000000000..c1a1ec8fc4a --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/__init__.py @@ -0,0 +1 @@ +"""The style tables of the rx.ui components, one module per component.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/box.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/box.py new file mode 100644 index 00000000000..089accd2542 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/box.py @@ -0,0 +1,10 @@ +"""The look of the box.""" + +from reflex_components_ui.base import ComponentStyles + +BOX: ComponentStyles = { + "base": { + "boxSizing": "border-box", + "display": "block", + }, +} diff --git a/pyi_hashes.json b/pyi_hashes.json index 4ba18f6c524..ab363937714 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,6 +118,9 @@ "packages/reflex-components-recharts/src/reflex_components_recharts/polar.pyi": "adc4db1a3ca7cd292b099ec4d97a4346", "packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "f2a9cf6db58d169289fbc76de6813300", "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "b195e3845260389ced026d2f5c4adb93", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "0fb77ee40f719777c68b2de2efdf799b", + "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "3a25570b63274a1490fa96a524a241fd", + "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "55e59f481df8cb08185a820f84e0a10d", "reflex/__init__.pyi": "540ab90bd8a7a89647f0bdd0a2fa3590", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" diff --git a/reflex/plugins/__init__.py b/reflex/plugins/__init__.py index 6e0afeeda05..4381860f6c7 100644 --- a/reflex/plugins/__init__.py +++ b/reflex/plugins/__init__.py @@ -1,5 +1,7 @@ """Re-export from reflex_base.plugins.""" +from typing import TYPE_CHECKING + from reflex_base.plugins import ( BaseContext, CommonContext, @@ -24,6 +26,12 @@ ) from reflex_components_radix.plugin import RadixThemesPlugin +# `UIPlugin` comes from the `ui` extra, which may not be installed: it is +# resolved on first use and stays out of `__all__`, so that a star import does +# not need the extra. +if TYPE_CHECKING: + from reflex_components_ui.plugin import UIPlugin + __all__ = [ "BaseContext", "CommonContext", @@ -47,3 +55,34 @@ "tailwind_v3", "tailwind_v4", ] + + +def __getattr__(name: str): + """Resolve `UIPlugin`, which comes from the `ui` extra, on first use. + + Args: + name: The attribute that was not found in the module. + + Returns: + The UIPlugin class. + + Raises: + AttributeError: If the name is not `UIPlugin`. + ModuleNotFoundError: If the `ui` extra is not installed. + """ + if name != "UIPlugin": + msg = f"module {__name__!r} has no attribute {name!r}" + raise AttributeError(msg) + package = "reflex_components_ui" + try: + from reflex_components_ui.plugin import UIPlugin + except ModuleNotFoundError as err: + if err.name != package: + raise + msg = ( + "`rx.plugins.UIPlugin` requires the reflex-components-ui package, " + "which is not installed. Install it with `pip install 'reflex[ui]'`." + ) + raise ModuleNotFoundError(msg, name=package) from None + globals()[name] = UIPlugin + return UIPlugin diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py new file mode 100644 index 00000000000..dd8fb820918 --- /dev/null +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -0,0 +1,287 @@ +"""The rx.ui components in a real app, in dev and prod. + +One app is shared by every test of the components: add a page or an element to +``UIComponentsApp`` rather than a new app. +""" + +import hashlib +import re +import shutil +from collections.abc import Generator +from pathlib import Path + +import pytest +from playwright.sync_api import Browser, Page, expect + +from reflex.testing import AppHarness, AppHarnessProd, chdir +from reflex.utils import build + +# What the box sets on its own, then the `style` and `class_name` of each box +# of the index page: its padding shows which stylesheet won. +BOX_STYLES = { + # The box against the browser's defaults. + "plain": {"display": "block", "box-sizing": "border-box", "padding": "0px"}, + # A `style` beats the resets of Reflex and Tailwind, which zero the padding. + "styled": {"display": "block", "box-sizing": "border-box", "padding": "4px"}, + # A Tailwind utility beats the `style` of the box. + "utility": {"display": "block", "box-sizing": "border-box", "padding": "32px"}, + # An unlayered stylesheet beats both. + "unlayered": {"display": "block", "box-sizing": "border-box", "padding": "2px"}, +} + +# A style of the literal page as it is compiled, and what the caching test +# changes it to. +LITERAL_STYLE = '"padding": "6px"' +CHANGED_STYLE = '"padding": "7px"' + + +def UIComponentsApp(): + """An app with a page for each thing the rx.ui tests look at.""" + from pathlib import Path + + import reflex as rx + + def index(): + return rx.el.main( + rx.ui.box("plain", id="plain"), + rx.ui.box("styled", id="styled", style={"padding": "4px"}), + rx.ui.box( + "utility", id="utility", style={"padding": "4px"}, class_name="p-8" + ), + rx.ui.box( + "unlayered", + id="unlayered", + style={"padding": "4px"}, + class_name="p-8 unlayered", + ), + ) + + def literal(): + return rx.ui.box("literal", id="literal", style={"padding": "6px"}) + + assets = Path.cwd() / "assets" + assets.mkdir(exist_ok=True) + (assets / "unlayered.css").write_text(".unlayered { padding: 2px }") + + app = rx.App(stylesheets=["unlayered.css"], enable_state=False) + app.add_page(index) + app.add_page(literal, route="/literal") + + config = rx.config.get_config() + config.plugins = [rx.plugins.UIPlugin(), rx.plugins.TailwindV4Plugin()] + + +@pytest.fixture(scope="module") +def ui_app( + app_harness_env: type[AppHarness], tmp_path_factory: pytest.TempPathFactory +) -> Generator[AppHarness, None, None]: + """Run the shared app in dev or prod. + + Args: + app_harness_env: AppHarness (dev) or AppHarnessProd (prod). + tmp_path_factory: pytest fixture for creating temporary directories. + + Yields: + The running harness. + """ + name = f"ui_components_{app_harness_env.__name__.lower()}" + with app_harness_env.create( + root=tmp_path_factory.mktemp(name), + app_name=name, + app_source=UIComponentsApp, + ) as harness: + assert harness.app_instance is not None, "app is not running" + yield harness + + +@pytest.fixture +def prod_app(ui_app: AppHarness) -> AppHarness: + """Skip a test of the production build when the app runs in dev. + + Args: + ui_app: The running harness. + + Returns: + The harness, running a production build. + """ + if not isinstance(ui_app, AppHarnessProd): + pytest.skip("only a production build is prerendered and bundled") + return ui_app + + +def _computed_styles(page: Page) -> dict[str, dict[str, str]]: + """Read the computed style of every box of the index page. + + Args: + page: A page showing the index of the app. + + Returns: + The properties in BOX_STYLES as the browser computed them, by box id. + """ + return page.evaluate( + """(boxes) => Object.fromEntries( + Object.entries(boxes).map(([id, properties]) => { + const style = getComputedStyle(document.getElementById(id)); + return [ + id, + Object.fromEntries( + Object.keys(properties).map((name) => [ + name, + style.getPropertyValue(name), + ]), + ), + ]; + }), + )""", + BOX_STYLES, + ) + + +def test_box_is_styled_in_cascade_order(ui_app: AppHarness, page: Page): + """The box is a styled div, between the resets and the utilities.""" + assert ui_app.frontend_url is not None + page.goto(ui_app.frontend_url) + # In dev the styles of a page arrive once its module was compiled. + expect(page.locator("#styled")).to_have_css("padding", "4px") + assert _computed_styles(page) == BOX_STYLES + assert page.locator("#plain").evaluate("(box) => box.tagName") == "DIV" + + +def test_first_paint_is_styled_without_javascript( + prod_app: AppHarness, browser: Browser +): + """The prerendered page links the styles and carries the class names.""" + assert prod_app.frontend_url is not None + context = browser.new_context(java_script_enabled=False) + try: + page = context.new_page() + page.goto(prod_app.frontend_url) + # Evaluating in the page still works: only its own scripts are off. + assert _computed_styles(page) == BOX_STYLES + finally: + context.close() + + +def _client_files(harness: AppHarness) -> dict[str, bytes]: + """Read what the production build serves to the browser. + + Args: + harness: A harness running a production build. + + Returns: + The content of every file, by path. The compressed copies are left + out: each is derived from a file that is included. + """ + client = harness.app_path / ".web" / "build" / "client" + return { + path.relative_to(client).as_posix(): path.read_bytes() + for path in sorted(client.rglob("*")) + if path.is_file() and path.suffix != ".gz" + } + + +def test_literal_page_folds_to_class_names(prod_app: AppHarness, page: Page): + """StyleX leaves a class name string in the page, and none of itself.""" + assert prod_app.frontend_url is not None + page.goto(prod_app.frontend_url.rstrip("/") + "/literal/") + box = page.locator("#literal") + expect(box).to_have_css("padding", "6px") + class_name = box.get_attribute("class") + assert class_name is not None + # Three atomic classes: display, box-sizing and padding. + assert re.fullmatch(r"x\w+ x\w+ x\w+", class_name), class_name + + scripts = { + name: content.decode() + for name, content in _client_files(prod_app).items() + if name.endswith(".js") + } + literal_chunks = [name for name in scripts if name.startswith("assets/_literal_")] + assert len(literal_chunks) == 1, sorted(scripts) + # Every class name the chunk of the page sets is the folded string. + assert re.findall(r"className:`([^`]*)`", scripts[literal_chunks[0]]) == [ + class_name + ] + # No script holds a call into StyleX or a style object it reads at runtime. + assert [ + name for name, code in scripts.items() if re.search(r"stylex|\$\$css", code) + ] == [] + + +def _digests(files: dict[str, bytes]) -> dict[str, str]: + """Reduce files to what tells two versions of one apart. + + Args: + files: The content of every file, by path. + + Returns: + The digest of every file, by path. + """ + return { + name: hashlib.sha256(content).hexdigest() for name, content in files.items() + } + + +def _rebuild_literal_page(harness: AppHarness, old: str, new: str) -> dict[str, str]: + """Change a style of the compiled literal page and build again. + + Args: + harness: A harness running a production build. + old: The style as the page declares it. + new: The style to declare instead. + + Returns: + The digest of every file of the new build, by path. + """ + routes = harness.app_path / ".web" / "app" / "routes" + (page,) = routes.glob("*literal*.jsx") + source = page.read_text() + assert source.count(old) == 1, source + page.write_text(source.replace(old, new)) + with chdir(harness.app_path): + build.build() + return _digests(_client_files(harness)) + + +def test_changed_style_renames_every_changed_file(prod_app: AppHarness, tmp_path: Path): + """A browser never keeps a stale file under the name of a new one. + + StyleX renames the stylesheet after the chunks were named, and writes the + new name into the chunk that links it. + """ + static = prod_app.app_path / ".web" / "build" / "client" + # Outside the web directory: a build removes its output, and Tailwind + # reads class names from every file beside it. + kept = tmp_path / "client" + shutil.copytree(static, kept) + before = _digests(_client_files(prod_app)) + try: + after = _rebuild_literal_page(prod_app, LITERAL_STYLE, CHANGED_STYLE) + restored = _rebuild_literal_page(prod_app, CHANGED_STYLE, LITERAL_STYLE) + finally: + # The other tests of the module read the build the harness serves. + shutil.rmtree(static) + shutil.move(kept, static) + + def named(digests: dict[str, str]) -> dict[str, str]: + # A document is addressed by its route and is not cached by its name. + return { + name: digest + for name, digest in digests.items() + if not name.endswith(".html") + } + + before, after, restored = named(before), named(after), named(restored) + changed_in_place = sorted( + name for name, digest in after.items() if before.get(name, digest) != digest + ) + assert changed_in_place == [] + renamed = sorted(Path(name).name.split("-")[0] for name in after.keys() - before) + assert renamed == [ + "__reflex_global_styles", + "_literal_._index", + "manifest", + "root", + ] + # The same styles build the same files: a name is a function of content. + assert restored == before diff --git a/tests/units/plugins/test_init.py b/tests/units/plugins/test_init.py new file mode 100644 index 00000000000..90f994e0fc8 --- /dev/null +++ b/tests/units/plugins/test_init.py @@ -0,0 +1,99 @@ +"""Tests for the names reflex.plugins resolves on first use.""" + +import subprocess +import sys + +import pytest +import reflex_components_ui.plugin + +import reflex as rx +import reflex.plugins + + +@pytest.fixture +def unresolved_ui_plugin(monkeypatch: pytest.MonkeyPatch): + """Forget that `UIPlugin` was resolved, so the next access imports it again. + + Args: + monkeypatch: The pytest fixture that restores the module afterwards. + """ + monkeypatch.delitem(vars(reflex.plugins), "UIPlugin", raising=False) + + +def test_ui_plugin_resolves_to_the_plugin_of_the_components_package( + unresolved_ui_plugin: None, +): + assert rx.plugins.UIPlugin is reflex_components_ui.plugin.UIPlugin + # Resolved once: the module attribute now answers. + assert vars(reflex.plugins)["UIPlugin"] is reflex_components_ui.plugin.UIPlugin + + +def test_importing_reflex_plugins_does_not_import_the_components_package(): + code = ( + "import sys, reflex.plugins\n" + "from reflex.plugins import *\n" + "print('reflex_components_ui' in sys.modules)\n" + "reflex.plugins.UIPlugin\n" + "print('reflex_components_ui' in sys.modules)\n" + ) + result = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True + ) + assert result.stdout == "False\nTrue\n" + + +class _NotInstalled: + """A finder that answers as the import system does for an absent package.""" + + @staticmethod + def find_spec(name: str, path: object = None, target: object = None) -> None: + """Refuse to find the components package. + + Args: + name: The module being imported. + path: The search path of its parent package. + target: The module being reloaded. + + Raises: + ModuleNotFoundError: If the module belongs to the package. + """ + if name.partition(".")[0] == "reflex_components_ui": + msg = f"No module named {name!r}" + raise ModuleNotFoundError(msg, name="reflex_components_ui") + + +def test_ui_plugin_without_the_extra_says_what_to_install( + unresolved_ui_plugin: None, monkeypatch: pytest.MonkeyPatch +): + for name in [ + name for name in sys.modules if name.startswith("reflex_components_ui") + ]: + monkeypatch.delitem(sys.modules, name) + monkeypatch.setattr(sys, "meta_path", [_NotInstalled, *sys.meta_path]) + with pytest.raises(ModuleNotFoundError) as raised: + rx.plugins.UIPlugin + assert str(raised.value) == ( + "`rx.plugins.UIPlugin` requires the reflex-components-ui package, which is " + "not installed. Install it with `pip install 'reflex[ui]'`." + ) + assert raised.value.name == "reflex_components_ui" + assert "UIPlugin" not in vars(reflex.plugins) + + +def test_ui_plugin_does_not_hide_a_missing_dependency_of_the_package( + unresolved_ui_plugin: None, monkeypatch: pytest.MonkeyPatch +): + """Only the package itself being absent means the extra is not installed.""" + monkeypatch.delitem(sys.modules, "reflex_components_ui.plugin") + monkeypatch.setitem(sys.modules, "reflex_components_ui.constants", None) + with pytest.raises(ModuleNotFoundError) as raised: + rx.plugins.UIPlugin + assert raised.value.name == "reflex_components_ui.constants" + + +def test_unknown_plugin_is_an_attribute_error(): + with pytest.raises(AttributeError) as raised: + rx.plugins.NoSuchPlugin # pyright: ignore[reportAttributeAccessIssue] + assert str(raised.value) == ( + "module 'reflex.plugins' has no attribute 'NoSuchPlugin'" + ) diff --git a/tests/units/reflex_base/components/test_dynamic.py b/tests/units/reflex_base/components/test_dynamic.py index 5f05159f213..3dca98c4a40 100644 --- a/tests/units/reflex_base/components/test_dynamic.py +++ b/tests/units/reflex_base/components/test_dynamic.py @@ -165,3 +165,26 @@ def test_unknown_attribute_raises(module_name: str): module = importlib.import_module(f"{module_name}.components.dynamic") with pytest.raises(AttributeError, match=f"{module.__name__!r}"): _ = module.definitely_not_an_attribute + + +def test_is_rendering_dynamic_component_only_while_one_is_serialized(): + """A component can tell that its code will be evaluated in the browser.""" + from reflex_base.utils.serializers import serialize + + seen = [] + + class Probe(Component): + tag = "div" + + def add_custom_code(self) -> list[str]: + seen.append(dynamic.is_rendering_dynamic_component()) + return [] + + assert dynamic.is_rendering_dynamic_component() is False + serialize(Probe.create()) + assert seen + assert set(seen) == {True} + assert dynamic.is_rendering_dynamic_component() is False + seen.clear() + Probe.create()._get_all_custom_code() + assert seen == [False] diff --git a/tests/units/reflex_components_ui/conftest.py b/tests/units/reflex_components_ui/conftest.py new file mode 100644 index 00000000000..c935bc00426 --- /dev/null +++ b/tests/units/reflex_components_ui/conftest.py @@ -0,0 +1,63 @@ +"""Fixtures for the tests of reflex-components-ui.""" + +import dataclasses +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.components.component import Component +from reflex_base.config import get_config +from reflex_base.plugins import CompileContext, CompilerHooks +from reflex_components_ui.plugin import UIPlugin + +from reflex.compiler.plugins import default_page_plugins + + +@dataclasses.dataclass(slots=True) +class _Page: + route: str + component: Callable[[], Component] + title: Any = None + description: Any = None + image: str = "" + meta: tuple[dict[str, Any], ...] = () + _source_module: str | None = None + + +@pytest.fixture +def ui_plugin(monkeypatch: pytest.MonkeyPatch) -> UIPlugin: + """Configure the plugin, as an app does in its rxconfig.py. + + Args: + monkeypatch: The pytest fixture that undoes the change. + + Returns: + The configured plugin. + """ + plugin = UIPlugin() + monkeypatch.setattr(get_config(), "plugins", [plugin]) + return plugin + + +@pytest.fixture +def compile_page(preserve_memo_registries: None) -> Callable[..., CompileContext]: + """Compile a page the way an app compile does. + + Args: + preserve_memo_registries: Restores the memos a compile registers. + + Returns: + A function from a page to its compile context: the source of the page + is ``compiled_pages["/"].output_code``. + """ + + def compile_page(page: Callable[[], Component]) -> CompileContext: + ctx = CompileContext( + pages=[_Page(route="/", component=page)], + hooks=CompilerHooks(plugins=default_page_plugins()), + ) + with ctx: + ctx.compile() + return ctx + + return compile_page diff --git a/tests/units/reflex_components_ui/layout/__init__.py b/tests/units/reflex_components_ui/layout/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_components_ui/layout/test_box.py b/tests/units/reflex_components_ui/layout/test_box.py new file mode 100644 index 00000000000..c2b5dfe7c55 --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_box.py @@ -0,0 +1,50 @@ +"""Tests for reflex_components_ui.layout.box.""" + +from collections.abc import Callable + +from reflex_base.plugins import CompileContext +from reflex_components_ui.layout.box import Box +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + +BOX_PAGE = """import * as stylex from "@stylexjs/stylex" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + + + +const sx_b26ac4fb71 = stylex.create({ s: {"boxSizing": "border-box", "display": "block"} }); +const sx_f49d6b3475 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "padding": "4px"} }); + +function Component() { + + + return ( + jsx(Fragment,{},jsx("main",{},jsx("div",{...stylex.props(sx_b26ac4fb71.s)},"hello"),jsx("div",{...stylex.props(sx_b26ac4fb71.s)},"again"),jsx("div",{...stylex.props(sx_f49d6b3475.s, { $$css: true, className: "p-8" })},"padded")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + ) +} +Component.displayName = "Component(/)"; + +export default Component; +""" + + +def test_box_page_source( + ui_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + """A box is a div: no component is imported, and equal styles declare once.""" + + def page(): + return rx.el.main( + rx.ui.box("hello"), + rx.ui.box("again"), + rx.ui.box("padded", style={"padding": "4px"}, class_name="p-8"), + ) + + assert compile_page(page).compiled_pages["/"].output_code == BOX_PAGE + + +def test_box_is_a_name_of_the_ui_namespace(): + assert rx.ui.box == Box.create + assert "box" in dir(rx.ui) diff --git a/tests/units/reflex_components_ui/style/__init__.py b/tests/units/reflex_components_ui/style/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_components_ui/style/test_emit.py b/tests/units/reflex_components_ui/style/test_emit.py new file mode 100644 index 00000000000..f38b4b975d1 --- /dev/null +++ b/tests/units/reflex_components_ui/style/test_emit.py @@ -0,0 +1,138 @@ +"""Tests for reflex_components_ui.style.emit.""" + +import pytest +from reflex_base.vars.base import Var +from reflex_components_ui.style.emit import ( + StyleXStyle, + UnsupportedStyleError, + emit, + inline, + props_call, +) + + +def test_emit_declares_a_style_named_after_its_content(): + """Literals and condition maps are written as StyleX takes them.""" + style = { + "padding": "var(--space-3)", + "lineHeight": 1.5, + "zIndex": 2, + "color": { + "default": "red", + ":hover": {"default": "blue", "@media (min-width: 768px)": "green"}, + }, + } + assert emit(style, "rx.ui.box") == StyleXStyle( + declaration=( + 'const sx_163452d900 = stylex.create({ s: {"padding": "var(--space-3)", ' + '"lineHeight": 1.5, "zIndex": 2, "color": {"default": "red", ":hover": ' + '{"default": "blue", "@media (min-width: 768px)": "green"}}} });' + ), + ref="sx_163452d900.s", + ) + + +def test_emit_is_deterministic_and_tells_styles_apart(): + """Equal styles share a declaration; different ones never share a name.""" + assert emit({"padding": "4px"}, "rx.ui.box") == emit( + {"padding": "4px"}, "rx.ui.flex" + ) + names = { + style.ref + for source in ({"padding": "4px"}, {"padding": "5px"}, {"padding": 4}) + if (style := emit(source, "rx.ui.box")) is not None + } + assert len(names) == 3 + + +def test_emit_has_nothing_to_declare_for_an_empty_style(): + assert emit({}, "rx.ui.box") is None + + +@pytest.mark.parametrize( + ("style", "message"), + [ + ( + {"color": Var("state.color")}, + ( + 'rx.ui.box: the style "color" is bound to state, which rx.ui components ' + "cannot compile yet. Give it a literal value, or set it from state with " + "a class_name." + ), + ), + ( + {"color": {"default": "red", ":hover": Var("state.color")}}, + ( + 'rx.ui.box: the style "color" under ":hover" is bound to state, which ' + "rx.ui components cannot compile yet. Give it a literal value, or set it " + "from state with a class_name." + ), + ), + ( + {"width": ["100%", "50%"]}, + ( + "rx.ui.box: the style \"width\" is ['100%', '50%'], a list. Use a string " + "or a number, or a mapping from condition to value such as " + '{"default": "red", ":hover": "blue"}.' + ), + ), + ( + {"display": True}, + ( + 'rx.ui.box: the style "display" is True, a bool. Use a string or a ' + "number, or a mapping from condition to value such as " + '{"default": "red", ":hover": "blue"}.' + ), + ), + ], +) +def test_emit_rejects_what_stylex_cannot_compile(style: dict, message: str): + with pytest.raises(UnsupportedStyleError) as raised: + emit(style, "rx.ui.box") + assert str(raised.value) == message + + +def test_props_call_applies_styles_in_order_with_literal_class_names(): + assert props_call(("sx_a.s",)) == "stylex.props(sx_a.s)" + assert props_call(("sx_a.s", "sx_b.s")) == "stylex.props(sx_a.s, sx_b.s)" + assert props_call(("sx_a.s",), 'p-8 "quoted"') == ( + 'stylex.props(sx_a.s, { $$css: true, className: "p-8 \\"quoted\\"" })' + ) + assert props_call(("sx_a.s",), "") == "stylex.props(sx_a.s)" + + +def test_inline_keeps_literals(): + assert inline({"padding": "4px", "zIndex": 2, "opacity": 0.5}, "rx.ui.box") == { + "padding": "4px", + "zIndex": 2, + "opacity": 0.5, + } + + +@pytest.mark.parametrize( + ("style", "message"), + [ + ( + {"color": {"default": "red", ":hover": "blue"}}, + ( + 'rx.ui.box: the style "color" has conditions ("default", ":hover"), ' + "which a component rendered from state cannot apply: its code is " + "evaluated in the browser and never reaches the StyleX compiler. Use an " + "unconditional value there, or render the component in a page and show " + "it with rx.cond." + ), + ), + ( + {"color": Var("state.color")}, + ( + 'rx.ui.box: the style "color" is bound to state, which rx.ui components ' + "cannot compile yet. Give it a literal value, or set it from state with " + "a class_name." + ), + ), + ], +) +def test_inline_rejects_what_an_inline_style_cannot_hold(style: dict, message: str): + with pytest.raises(UnsupportedStyleError) as raised: + inline(style, "rx.ui.box") + assert str(raised.value) == message diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py new file mode 100644 index 00000000000..5e0cd2dee7a --- /dev/null +++ b/tests/units/reflex_components_ui/test_base.py @@ -0,0 +1,267 @@ +"""Tests for reflex_components_ui.base.""" + +from collections.abc import Callable +from typing import ClassVar + +import pytest +from reflex_base.config import get_config +from reflex_base.plugins import CompileContext +from reflex_base.utils.exceptions import ConfigError +from reflex_base.utils.serializers import serialize +from reflex_base.vars.base import Var +from reflex_components_ui.base import ComponentStyles, UIComponent +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style.emit import UnsupportedStyleError + +import reflex as rx +from reflex.compiler import compiler + +# A page whose only element was moved into a module of its own. +MEMO_PAGE = """import {Card_section_b8f6e6fad3a0fd8c010369e2de15b082} from "$/utils/components/Card_section_b8f6e6fad3a0fd8c010369e2de15b082" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + + + + + +function Component() { + + + return ( + jsx(Fragment,{},jsx(Card_section_b8f6e6fad3a0fd8c010369e2de15b082,{},"hello"),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + ) +} +Component.displayName = "Component(/)"; + +export default Component; +""" + +# The module that renders the element, with the declaration of its style. +MEMO_MODULE = """ +import {ReflexEvent,applyEventActions,isTrue,mergeSlotProps} from "$/utils/state" +import {addEvents} from "$/utils/context" +import {Fragment,memo,useCallback,useEffect} from "react" +import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" + + + +const sx_b5d18f9eca = stylex.create({ s: {"color": {"default": "red", ":hover": "blue"}, "padding": "8px"} }); + + +export const Card_section_b8f6e6fad3a0fd8c010369e2de15b082 = /*#__PURE__*/ (() => { +const Card_section_b8f6e6fad3a0fd8c010369e2de15b082 = memo(({children, ...rest}) => { + const on_click_d7389fe0b34b5da3b1e38e11566dcc81 = useCallback(((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___test_base____base_test_state.noop", ({ }), ({ })))], [_e], ({ })))), []) + return( + jsx("section",{...mergeSlotProps(rest, ({ onClick:on_click_d7389fe0b34b5da3b1e38e11566dcc81, ...stylex.props(sx_b5d18f9eca.s) }))},children) + ) +}); +Card_section_b8f6e6fad3a0fd8c010369e2de15b082.displayName = "Card"; +return Card_section_b8f6e6fad3a0fd8c010369e2de15b082; +})(); +""" + +# What the browser evaluates for a component held in state. +DYNAMIC_MODULE = ( + "//__reflex_evaluate:[]\n" + "const React = window.__reflex.react;\n" + "\n" + "const {jsx} = window.__reflex['@emotion/react']\n" + "const {Fragment,useEffect} = window.__reflex['react']\n" + "const {pyOr} = window.__reflex['$/utils/state']\n" + "\n" + "export default function MySSRComponent () {\n" + " \n" + " return (\n" + ' (jsx("div", ({className:"p-8",style:({ ["padding"] : "4px", ["zIndex"] : 2 })}), "hello"))\n' + " )\n" + "}" +) + + +class Plain(UIComponent): + """An element with no look of its own.""" + + +class Card(UIComponent): + """An element whose look has a condition.""" + + tag = "section" + + styles: ClassVar[ComponentStyles] = { + "base": {"color": {"default": "red", ":hover": "blue"}, "padding": "8px"}, + } + + +class Variants(UIComponent): + """An element whose look depends on a prop.""" + + styles: ClassVar[ComponentStyles] = { + "variants": {"size": {"1": {"padding": "4px"}}} + } + + +class BaseTestState(rx.State): + """State the styles and class names are bound to.""" + + color: str = "red" + names: str = "p-8" + + @rx.event + def noop(self): + """Do nothing.""" + + +def test_rendering_without_the_plugin_says_how_to_configure_it( + monkeypatch: pytest.MonkeyPatch, compile_page: Callable[..., CompileContext] +): + monkeypatch.setattr(get_config(), "plugins", []) + with pytest.raises(ConfigError) as raised: + compile_page(lambda: Card.create("hello")) + assert ( + str(raised.value) + == "rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins." + ) + with pytest.raises(ConfigError) as raised: + Card.create("hello").render() + assert ( + str(raised.value) + == "rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins." + ) + + +def test_element_without_styles_is_a_plain_element(ui_plugin: UIPlugin): + component = Plain.create("hello", class_name="p-8") + assert component.render() == { + "name": '"div"', + "props": ['className:"p-8"'], + "children": [{"contents": '"hello"'}], + } + assert component._get_all_custom_code() == {} + + +def test_style_is_spread_from_a_declaration_and_never_a_css_prop(ui_plugin: UIPlugin): + """The user's style is merged over the component's, by property.""" + component = Card.create("hello", style={"padding": "4px", "margin_top": 2}) + assert component._get_all_custom_code() == { + 'const sx_5579d75d4f = stylex.create({ s: {"color": {"default": "red", ' + '":hover": "blue"}, "padding": "4px", "marginTop": 2} });': None + } + assert component.render() == { + "name": '"section"', + "props": ["...stylex.props(sx_5579d75d4f.s)"], + "children": [{"contents": '"hello"'}], + } + assert component._get_style() == {} + + +def test_literal_class_names_fold_into_the_spread(ui_plugin: UIPlugin): + """A spread would replace a className prop, so there is only the spread.""" + component = Card.create(class_name=["p-8", "m-2"], custom_attrs={"role": "note"}) + assert component.render()["props"] == [ + 'role:"note"', + '...stylex.props(sx_b5d18f9eca.s, { $$css: true, className: "p-8 m-2" })', + ] + + +def test_class_names_from_state_are_joined_with_the_folded_ones(ui_plugin: UIPlugin): + component = Card.create(class_name=BaseTestState.names) + assert component.render()["props"] == [ + ( + f'className:({BaseTestState.names!s}) + " " + ' + "stylex.props(sx_b5d18f9eca.s).className" + ) + ] + + +@pytest.mark.parametrize( + ("create", "message"), + [ + ( + lambda: Card.create(style={"color": BaseTestState.color}), + ( + 'rx.ui.card: the style "color" is bound to state, which rx.ui ' + "components cannot compile yet. Give it a literal value, or set it " + "from state with a class_name." + ), + ), + ( + lambda: Card.create(style={"_hover": {"color": "blue"}}), + ( + 'rx.ui.card: the style "_hover" is a nested block or a list, which ' + "rx.ui components cannot compile yet. Use flat properties with literal " + "values." + ), + ), + ( + lambda: Card.create(style={"width": ["100%", "50%"]}), + ( + 'rx.ui.card: the style "width" is a nested block or a list, which ' + "rx.ui components cannot compile yet. Use flat properties with literal " + "values." + ), + ), + ( + lambda: Variants.create(), + "rx.ui.variants: variant and compound styles are not compiled yet.", + ), + ], +) +def test_style_that_cannot_be_compiled_yet_is_an_error( + ui_plugin: UIPlugin, create: Callable[[], UIComponent], message: str +): + component = create() + with pytest.raises(UnsupportedStyleError) as raised: + component.render() + assert str(raised.value) == message + with pytest.raises(UnsupportedStyleError) as raised: + component._get_all_custom_code() + assert str(raised.value) == message + + +def test_declaration_follows_the_element_into_a_memo_module( + ui_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + """StyleX only folds a style declared in the module that renders it. + + An event handler makes the compiler move the element into a module of its + own: the declaration and the import go there, and leave the page. + """ + ctx = compile_page(lambda: Card.create("hello", on_click=BaseTestState.noop)) + assert ctx.compiled_pages["/"].output_code == MEMO_PAGE + ((_, memo_module),) = compiler.compile_memo_components( + tuple(ctx.auto_memo_components.values()) + )[0] + assert memo_module == MEMO_MODULE + + +def test_dynamic_component_falls_back_to_an_inline_style(): + """Code evaluated in the browser has no build, no plugin and no StyleX.""" + component = Plain.create( + "hello", style={"padding": "4px", "z_index": 2}, class_name="p-8" + ) + assert serialize(component) == DYNAMIC_MODULE + + +def test_dynamic_component_cannot_have_a_conditional_style(): + with pytest.raises(UnsupportedStyleError) as raised: + serialize(Card.create("hello")) + assert str(raised.value) == ( + 'rx.ui.card: the style "color" has conditions ("default", ":hover"), which ' + "a component rendered from state cannot apply: its code is evaluated in " + "the browser and never reaches the StyleX compiler. Use an unconditional " + "value there, or render the component in a page and show it with rx.cond." + ) + + +def test_var_style_values_reach_the_error_of_the_emitter(ui_plugin: UIPlugin): + """A state-bound value is not mistaken for a literal on its way down.""" + component = Card.create(style={"color": Var("state.color", _var_type=str)}) + with pytest.raises(UnsupportedStyleError) as raised: + component.render() + assert str(raised.value) == ( + 'rx.ui.card: the style "color" is bound to state, which rx.ui components ' + "cannot compile yet. Give it a literal value, or set it from state with a " + "class_name." + ) diff --git a/tests/units/reflex_components_ui/test_js_package.py b/tests/units/reflex_components_ui/test_js_package.py index 73afb438602..48ad47a6122 100644 --- a/tests/units/reflex_components_ui/test_js_package.py +++ b/tests/units/reflex_components_ui/test_js_package.py @@ -3,11 +3,13 @@ import json from pathlib import Path +from reflex_components_ui.constants import STYLEX_VERSION + JS_PACKAGE = Path(__file__).parents[3] / "packages/reflex-components-ui/js" # StyleX is 0.x and has broken its output between patch releases, so every -# package of it moves together and by an exact pin. -STYLEX_VERSION = "0.19.2" +# package of it moves together and by an exact pin: the version an app +# installs is the version the javascript package is developed against. def test_stylex_packages_are_pinned_to_one_exact_version(): diff --git a/tests/units/reflex_components_ui/test_plugin.py b/tests/units/reflex_components_ui/test_plugin.py new file mode 100644 index 00000000000..f7565a436e8 --- /dev/null +++ b/tests/units/reflex_components_ui/test_plugin.py @@ -0,0 +1,92 @@ +"""Tests for reflex_components_ui.plugin.""" + +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest +from reflex_base.plugins import VitePluginEntry +from reflex_components_ui.constants import JS_SRC +from reflex_components_ui.plugin import Theme, UIPlugin, add_base_stylesheet + + +def test_plugin_installs_the_style_compiler_for_the_build_only(): + plugin = UIPlugin() + assert plugin.get_frontend_development_dependencies() == [ + "@stylexjs/stylex@0.19.2", + "@stylexjs/unplugin@0.19.2", + "lightningcss@1.33.0", + ] + assert plugin.get_frontend_dependencies() == [] + + +def test_plugin_adds_the_wrapped_stylex_plugin_to_vite(): + assert UIPlugin().get_vite_plugins() == [ + VitePluginEntry( + imports=( + 'import reflexUIStylex from "./reflex-ui/vite-plugin-stylex.js"', + 'import { Features as lightningcssFeatures } from "lightningcss"', + ), + call="""reflexUIStylex("__reflex_global_styles", { + useCSSLayers: { prefix: "reflex-ui" }, + styleResolution: "application-order", + lightningcssOptions: { minify: true, exclude: lightningcssFeatures.LightDark }, + })""", + ) + ] + + +def test_plugin_writes_every_file_of_the_javascript_package(): + """The assets are the files under js/src, each where the app imports it.""" + shipped = { + path.relative_to(JS_SRC).as_posix(): path.read_text() + for path in JS_SRC.rglob("*") + if path.is_file() + } + # The files this plugin itself relies on; others come with the components. + assert {"README.md", "base.css", "vite-plugin-stylex.js"} <= shipped.keys() + assets = UIPlugin().get_static_assets() + assert [path for path, _ in assets] == [ + Path("reflex-ui") / name for name in sorted(shipped) + ] + assert { + path.relative_to("reflex-ui").as_posix(): content for path, content in assets + } == shipped + + +def test_plugin_imports_the_base_stylesheet_before_compile(): + modified = {} + + def add_save_task(task: Callable[..., Any], /, *args: Any, **kwargs: Any) -> None: + pytest.fail("the plugin writes no file of its own before a compile") + + UIPlugin().pre_compile( + add_save_task=add_save_task, + add_modify_task=modified.__setitem__, + radix_themes_plugin=None, + unevaluated_pages=[], + ) + assert modified == {"styles/__reflex_global_styles.css": add_base_stylesheet} + + +def test_base_stylesheet_is_imported_ahead_of_every_other_stylesheet(): + """Tailwind adds its import after the reset, so base.css goes before it.""" + root = ( + "@layer __reflex_base;\n" + "@import url('./__reflex_style_reset.css');\n" + "@import url('./tailwind.css');" + ) + with_base = ( + "@layer __reflex_base;\n" + "@import url('../reflex-ui/base.css');\n" + "@import url('./__reflex_style_reset.css');\n" + "@import url('./tailwind.css');" + ) + assert add_base_stylesheet(root) == with_base + assert add_base_stylesheet(with_base) == with_base + assert add_base_stylesheet("") == "@import url('../reflex-ui/base.css');" + + +def test_plugin_has_a_theme(): + assert UIPlugin().theme == Theme() + assert repr(UIPlugin()) == "UIPlugin(theme=Theme())" From 257e5e048cddc53fb7d8d87818401be274244b0e Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 04:57:58 +0000 Subject: [PATCH 09/26] Remove a duplicated command line from AGENTS.md Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- AGENTS.md | 1 - 1 file changed, 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 3c410c20f89..81af9d2ab5e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,7 +26,6 @@ uv run python scripts/make_pyi.py # regenerate .p uv run pre-commit run --all-files # all pre-commit hooks npm --prefix packages/reflex-frontend ci && npm --prefix packages/reflex-frontend run check # frontend package: lint, type-check (JSDoc) and unit tests npm --prefix packages/reflex-components-ui/js ci && npm --prefix packages/reflex-components-ui/js run check # rx.ui javascript: lint, type-check (JSDoc), generated files and unit tests -npm --prefix packages/reflex-components-ui/js ci && npm --prefix packages/reflex-components-ui/js run check # rx.ui javascript: lint, type-check (JSDoc), generated files and unit tests ``` ## Layout From d3b3fc985d1d7ae2e84069c81930d3df6ce1162a Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 04:59:56 +0000 Subject: [PATCH 10/26] Take the early click over right before hydration Recording stopped when the scripts module was imported, which left the time until hydrateRoot with no one handling a click. The entry points now take the click over immediately before they hydrate. Claude-Session: https://claude.ai/code/session_014AwvTNacWVsm7SEvVjhfGM --- packages/reflex-frontend/README.md | 10 +++--- .../src/app/entry.client.embed.js | 2 ++ .../reflex-frontend/src/app/entry.client.js | 2 ++ packages/reflex-frontend/src/utils/scripts.js | 24 +++++++++----- .../reflex-frontend/tests/public_api.test.js | 1 + .../reflex-frontend/tests/scripts.test.js | 33 +++++++++++++++---- 6 files changed, 53 insertions(+), 19 deletions(-) diff --git a/packages/reflex-frontend/README.md b/packages/reflex-frontend/README.md index e2b9127d43d..9933282d892 100644 --- a/packages/reflex-frontend/README.md +++ b/packages/reflex-frontend/README.md @@ -53,10 +53,7 @@ without it appearing in its arguments. What there is, and where it is pinned: queue or the socket is as it left them. - **Work done on import**: `utils/state.js` creates the cookie reader, always; publishes the client state store on `refs`, when there is a `document`; and - starts a socket transport, when there is a `window`. `utils/scripts.js` - takes over the click a prerendered page recorded before its scripts loaded - (`window.__reflex_early`, set by the inline script that module renders), and - dispatches it again once the page is hydrated. A production build + starts a socket transport, when there is a `window`. A production build evaluates every module in node to prerender pages, so anything added here has to load without either. `tests/public_api.test.js` imports each module in node to keep it that way. @@ -68,6 +65,11 @@ without it appearing in its arguments. What there is, and where it is pinned: module local, but it stops the minifier from mangling the chunk that holds it. So a script sees those names and the globals, and nothing else. Renaming an export changes what compiled callbacks can call. +- **The click before hydration**: the inline script `utils/scripts.js` renders + into a prerendered page records the last click in `window.__reflex_early`. + The entry point calls `takeEarlyClick` right before `hydrateRoot`, and the + click is dispatched again once the page is hydrated. An entry point that + hydrates without calling it loses that click, as before. - **Globals the runtime reads**: hooks other code installs on `window` (`__reflex_otel`, `__reflex`, `__reflex_load`) and the per-app `$/env.json`. Each is declared in `types/globals.d.ts`; reading one that is not fails the diff --git a/packages/reflex-frontend/src/app/entry.client.embed.js b/packages/reflex-frontend/src/app/entry.client.embed.js index 57ef621468e..66cc59c743d 100644 --- a/packages/reflex-frontend/src/app/entry.client.embed.js +++ b/packages/reflex-frontend/src/app/entry.client.embed.js @@ -2,6 +2,7 @@ import { startTransition, createElement } from "react"; import { createRoot, hydrateRoot } from "react-dom/client"; import { HydratedRouter } from "react-router/dom"; import env from "$/env.json"; +import { takeEarlyClick } from "$/utils/scripts"; const selector = env.MOUNT_TARGET; @@ -57,6 +58,7 @@ if (selector) { }); } } else { + takeEarlyClick(); startTransition(() => { hydrateRoot(document, createElement(HydratedRouter)); }); diff --git a/packages/reflex-frontend/src/app/entry.client.js b/packages/reflex-frontend/src/app/entry.client.js index 9545bc28309..7cc5f07f9cd 100644 --- a/packages/reflex-frontend/src/app/entry.client.js +++ b/packages/reflex-frontend/src/app/entry.client.js @@ -2,7 +2,9 @@ import { startTransition } from "react"; import { hydrateRoot } from "react-dom/client"; import { HydratedRouter } from "react-router/dom"; import { createElement } from "react"; +import { takeEarlyClick } from "$/utils/scripts"; +takeEarlyClick(); startTransition(() => { hydrateRoot(document, createElement(HydratedRouter)); }); diff --git a/packages/reflex-frontend/src/utils/scripts.js b/packages/reflex-frontend/src/utils/scripts.js index bfd7bfa82cd..3db32d083a4 100644 --- a/packages/reflex-frontend/src/utils/scripts.js +++ b/packages/reflex-frontend/src/utils/scripts.js @@ -69,22 +69,30 @@ observer.observe({type:"paint",buffered:true}); const ACTS_WITHOUT_SCRIPTS = "a[href],area[href],input,select,textarea,label,summary,[contenteditable]"; -// From here on React handles a click itself, hydrating first if it has to: -// what the inline script recorded stops at the import of this module, and the -// last click it saw is dispatched again once the page is hydrated. let earlyClick = null; -if (typeof window !== "undefined" && window.__reflex_early) { - document.removeEventListener("click", window.__reflex_early.record, true); - earlyClick = window.__reflex_early.click; + +/** + * Stop the inline script recording clicks, and keep the last one it saw. + * + * Called right before the page is hydrated. From then on React handles a + * click itself, hydrating first if it has to, so a click recorded any later + * would run its handler twice. + */ +export const takeEarlyClick = () => { + const early = window.__reflex_early; + if (!early) return; + document.removeEventListener("click", early.record, true); + earlyClick = early.click; window.__reflex_early = undefined; -} +}; /** * Dispatch again the click a prerendered page got before it was hydrated. * * Without this the click is lost: the page is visible, and no handler is * attached yet. Only the last click counts, and only where the browser did - * nothing with the first one. + * nothing with the first one. An entry point that never took the click over + * gets none dispatched: there is no telling whether React handled it. */ const replayEarlyClick = () => { const click = earlyClick; diff --git a/packages/reflex-frontend/tests/public_api.test.js b/packages/reflex-frontend/tests/public_api.test.js index 9cc68cd4114..00dd367fbc7 100644 --- a/packages/reflex-frontend/tests/public_api.test.js +++ b/packages/reflex-frontend/tests/public_api.test.js @@ -108,6 +108,7 @@ const PUBLIC_API = { "FIRST_PAINT_TIMEOUT_MS", "START_AFTER_FIRST_PAINT", "Scripts", + "takeEarlyClick", ], "$/components/reflex/radix_themes_color_mode_provider": ["default"], "$/components/shiki/code": ["Code"], diff --git a/packages/reflex-frontend/tests/scripts.test.js b/packages/reflex-frontend/tests/scripts.test.js index 952c007aca3..b27b45a9ccc 100644 --- a/packages/reflex-frontend/tests/scripts.test.js +++ b/packages/reflex-frontend/tests/scripts.test.js @@ -299,15 +299,19 @@ describe("START_AFTER_FIRST_PAINT", () => { }; /** - * Load the module as the page's scripts do, and mount the scripts - * component, which is when a hydrated page runs its effects. + * Load the module as the page's scripts do, take the click over as the + * entry point does, and mount the scripts component, which is when a + * hydrated page runs its effects. + * @param {object} [options] How the page is hydrated. + * @param {boolean} [options.take] Whether the entry point takes the click over. */ - const hydrate = async () => { + const hydrate = async ({ take = true } = {}) => { vi.resetModules(); const { act, createElement } = await import("react"); const { createRoot } = await import("react-dom/client"); const { createRoutesStub } = await import("react-router"); - const { Scripts } = await import("$/utils/scripts"); + const { Scripts, takeEarlyClick } = await import("$/utils/scripts"); + if (take) takeEarlyClick(); const Stub = createRoutesStub([ { path: "/", Component: () => createElement(Scripts) }, ]); @@ -393,16 +397,31 @@ describe("START_AFTER_FIRST_PAINT", () => { expect(clicks.length).toBe(1); }); - test("a click after the scripts loaded is not recorded", async () => { + test("is not recorded once the entry point took it over", async () => { const { target, clicks } = addToPage(''); run(); const { record } = window.__reflex_early; + const removed = vi.spyOn(document, "removeEventListener"); await hydrate(); + expect(removed.mock.calls).toEqual([["click", record, true]]); click(target); - expect(clicks.length).toBe(1); - record(clicks[0]); await hydrate(); expect(clicks.length).toBe(1); }); + + test("is not dispatched again by an entry point that did not take it over", async () => { + const { target, clicks } = addToPage(''); + run(); + click(target); + await hydrate({ take: false }); + expect(clicks.length).toBe(1); + }); + + test("taking it over on a page without the inline script does nothing", async () => { + const { clicks } = addToPage(''); + await hydrate(); + expect(clicks).toEqual([]); + expect(window.__reflex_early).toBe(undefined); + }); }); }); From 698cb496c969f39821b859f15cac8eeb8ce53a1e Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 05:04:43 +0000 Subject: [PATCH 11/26] Add typed rx.ui styles with lowering and merging StyleProps is generated from the type definitions of the pinned StyleX package, so a type checker catches a misspelt CSS property or keyword. lower() turns a style into the style object StyleX compiles: conditions per property, media queries for responsive values, color scales with the module each needs, and shorthands split into longhands. merge() resolves a component's style table against the props and the style of one element, by property with the last one winning, and returns the alternatives of a prop bound to state without resolving them. StyleX silently drops the border and background shorthands, so both are always split, and animation is refused with what to set instead. Claude-Session: https://claude.ai/code/session_014AwvTMtxnRhQBAehyWjUwF --- packages/reflex-components-ui/README.md | 50 + .../js/scripts/css-props.js | 304 ++ .../js/scripts/generate.js | 9 +- .../js/tests/css-props.test.js | 165 ++ .../news/+style-lowering.feature.md | 1 + .../reflex_components_ui/style/__init__.py | 33 + .../reflex_components_ui/style/_css_props.py | 2634 +++++++++++++++++ .../src/reflex_components_ui/style/lower.py | 1256 ++++++++ .../src/reflex_components_ui/style/merge.py | 605 ++++ .../reflex_components_ui/style/__init__.py | 0 .../style/fixtures/style_errors.py.txt | 32 + .../style/fixtures/style_valid.py.txt | 115 + .../style/test_css_props.py | 227 ++ .../reflex_components_ui/style/test_lower.py | 1361 +++++++++ .../reflex_components_ui/style/test_merge.py | 508 ++++ 15 files changed, 7299 insertions(+), 1 deletion(-) create mode 100644 packages/reflex-components-ui/js/scripts/css-props.js create mode 100644 packages/reflex-components-ui/js/tests/css-props.test.js create mode 100644 packages/reflex-components-ui/news/+style-lowering.feature.md create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/style/_css_props.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/style/lower.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/style/merge.py create mode 100644 tests/units/reflex_components_ui/style/__init__.py create mode 100644 tests/units/reflex_components_ui/style/fixtures/style_errors.py.txt create mode 100644 tests/units/reflex_components_ui/style/fixtures/style_valid.py.txt create mode 100644 tests/units/reflex_components_ui/style/test_css_props.py create mode 100644 tests/units/reflex_components_ui/style/test_lower.py create mode 100644 tests/units/reflex_components_ui/style/test_merge.py diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 6c8e0cb9850..1a10b4c6118 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -29,6 +29,56 @@ hatch_build.py embeds js/src in the wheel edit needs no rebuild. A change under `js/src` is a change to this package: its news fragment goes in `news/`. +## Styles + +`reflex_components_ui.style` holds what turns the styles a user writes into +the style objects StyleX compiles. Nothing in it depends on a component. + +- `StyleProps` types one style: the CSS properties under the snake_case names + Reflex users write, the keywords of each one, and blocks under a condition + such as `_hover` or `":focus-visible"`. `style/_css_props.py` is generated + from the type definitions of the pinned StyleX by `js/scripts/css-props.js`. + At runtime the name is a plain `dict`: only a type checker reads the table. +- `ComponentStyles` types the look of a component: `base`, `variants` by prop + and value, `compound` styles for a combination of props, and `parts` for + inner elements. +- `lower(name, style, layout)` returns a `Lowered`: `style` maps a camelCase + CSS property to a literal, a `Var` or a condition map such as + `{"default": v, ":hover": v, "@media ...": v}`; `imports` names the modules + whose CSS the values need, such as a color scale; `inline` carries a `Var` + that holds a whole dict of styles. +- `merge(name, styles, props, style, layout)` returns a `Merged`: the `style` + of the element with every prop known at compile time resolved, `dynamic` + alternatives for the props bound to state, and the `Merged` of each part. + The table is lowered once and kept by identity, so it is a module constant. + +Both results are hashable and equal when they compile to the same +declarations. Errors are `StyleError`s that start with the display name passed +as `name`, such as `rx.ui.card: unknown CSS property "paddng". Did you mean +"padding"?`. + +What lowering does to each input: + +| Input | Lowered form | +| --- | --- | +| A literal | The literal | +| A `Var`, or a string with one inside | The `Var` | +| `_hover`, `":hover"`, `"[data-open]"`, `"@media ..."` blocks | A condition on each property inside | +| A list or `rx.breakpoints(...)` | Conditions `@media screen and (min-width: ...)` on the app's breakpoints | +| `rx.color("ruby", 9)` | `var(--ruby-9)`, and the ruby module in `imports` | +| `margin`, `padding`, `inset`, `gap`, `overflow`, `border_width`, `border_radius`... | Their longhands | +| `border`, `border_top`..., `background` | Their longhands always: StyleX compiles neither | +| `padding_x`, `margin_y`, `bg`, `bg_color` | The properties they stand for | +| Layout props (`p`, `m`, `gap`, `columns`, `direction`...) | Styles, with steps of the space scale as `var(--space-N)` | +| A shorthand bound to state, or holding `var(...)` | Kept whole; it removes its longhands from the styles before it | +| `None` | The property is unset | +| A nested selector, an unknown property, `animation` | `StyleError` | + +Styles merge by property and the last one wins: base, variants, compound +styles, layout props, then the user's style. A style that sets a property only +under a condition, as a `_hover` block does, keeps the earlier value everywhere +else; one that sets it outright replaces the earlier conditions too. + ## Working on it From the repository root: diff --git a/packages/reflex-components-ui/js/scripts/css-props.js b/packages/reflex-components-ui/js/scripts/css-props.js new file mode 100644 index 00000000000..6608771269b --- /dev/null +++ b/packages/reflex-components-ui/js/scripts/css-props.js @@ -0,0 +1,304 @@ +// Renders `style/_css_props.py`: the CSS properties an rx.ui style accepts and +// the values each one takes, read from the type definitions of the pinned +// `@stylexjs/stylex` package. + +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +import ts from "typescript"; + +const TYPES_DIR = fileURLToPath( + new URL("../node_modules/@stylexjs/stylex/lib/es/types/", import.meta.url), +); + +// Keys of StyleX's `CSSProperties` that are not CSS properties. +const NOT_CSS = new Set(["theme"]); + +// The pseudo-classes a style can be conditioned on with an underscore key, +// such as `_hover`. StyleX types them as `:${string}`, so the list is kept +// here. Any other one, and every functional one, is written with its colon. +export const PSEUDO_CLASSES = [ + "active", + "any-link", + "autofill", + "checked", + "default", + "disabled", + "empty", + "enabled", + "first-child", + "first-of-type", + "focus", + "focus-visible", + "focus-within", + "fullscreen", + "hover", + "in-range", + "indeterminate", + "invalid", + "last-child", + "last-of-type", + "link", + "modal", + "only-child", + "only-of-type", + "open", + "optional", + "out-of-range", + "placeholder-shown", + "popover-open", + "read-only", + "read-write", + "required", + "target", + "user-invalid", + "user-valid", + "valid", + "visited", +]; + +// The style keys Reflex adds to CSS, and the kind of value each takes. +const REFLEX_KEYS = [ + ["bg", "_Color"], + ["bg_color", "_Color"], + ["margin_x", "_Size"], + ["margin_y", "_Size"], + ["padding_x", "_Size"], + ["padding_y", "_Size"], +]; + +/** + * What one CSS property accepts. + * + * @typedef {object} Property + * @property {string} name The name StyleX gives it, such as `alignItems`. + * @property {string} key The name a Reflex user writes, such as `align_items`. + * @property {string[]} literals The keywords it takes, when it takes nothing + * else. + * @property {"_Color" | "_Size" | "_Str" | null} open The kind of free-form + * value it takes, or null when only `literals` are accepted. + */ + +/** + * Convert a StyleX property name to the name a Reflex user writes. + * + * @param {string} name A camelCase name, capitalised when it has a vendor + * prefix. + * @returns {string} The snake_case name. + */ +export function snakeCase(name) { + return name.replace( + /[A-Z]/g, + (letter, index) => (index ? "_" : "") + letter.toLowerCase(), + ); +} + +/** + * Collect the names of the type aliases a type is built from. + * + * @param {ts.Node} node The type to walk. + * @param {Map} aliases The aliases of the file by name. + * @param {Set} seen The names found so far, added to in place. + */ +function collectAliases(node, aliases, seen) { + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) { + const name = node.typeName.text; + const alias = aliases.get(name); + if (alias && !seen.has(name)) { + seen.add(name); + collectAliases(alias, aliases, seen); + } + } + ts.forEachChild(node, (child) => collectAliases(child, aliases, seen)); +} + +/** + * Read the properties of StyleX's `CSSProperties` type. + * + * @returns {Property[]} The properties, sorted by the key a user writes. + */ +export function readProperties() { + const file = `${TYPES_DIR}StyleXCSSTypes.d.ts`; + const program = ts.createProgram([file], { strict: true, noEmit: true }); + const checker = program.getTypeChecker(); + const source = program.getSourceFile(file); + if (!source) throw new Error(`Cannot read ${file}`); + + /** @type {Map} */ + const aliases = new Map(); + for (const statement of source.statements) { + if (ts.isTypeAliasDeclaration(statement)) { + aliases.set(statement.name.text, statement.type); + } + } + const declared = aliases.get("CSSProperties"); + if (!declared) throw new Error("StyleX no longer declares CSSProperties"); + + /** @type {Property[]} */ + const properties = []; + const type = checker.getTypeFromTypeNode(declared); + for (const symbol of checker.getPropertiesOfType(type)) { + const name = symbol.getName(); + if (NOT_CSS.has(name)) continue; + const valueType = checker.getTypeOfSymbol(symbol); + const members = valueType.isUnion() ? valueType.types : [valueType]; + /** @type {string[]} */ + const literals = []; + let anyString = false; + let anyNumber = false; + for (const member of members) { + if (member.isStringLiteral()) literals.push(member.value); + else if (member.flags & ts.TypeFlags.String) anyString = true; + else if (member.flags & ts.TypeFlags.NumberLike) anyNumber = true; + } + const used = new Set(); + for (const declaration of symbol.getDeclarations() ?? []) { + collectAliases(declaration, aliases, used); + } + /** @type {Property["open"]} */ + let open = null; + if (used.has("color")) open = "_Color"; + else if (anyNumber) open = "_Size"; + else if (anyString || literals.length === 0) open = "_Str"; + properties.push({ + name, + key: snakeCase(name), + literals: open ? [] : literals.sort(), + open, + }); + } + return properties.sort((a, b) => (a.key < b.key ? -1 : 1)); +} + +/** + * Read the pseudo-elements StyleX types. + * + * @returns {string[]} Their names without the colons, sorted. + */ +export function readPseudoElements() { + const text = readFileSync(`${TYPES_DIR}StyleXTypes.d.ts`, "utf8"); + return [...text.matchAll(/^\s*'::([a-z-]+)'\??:/gm)] + .map((match) => match[1]) + .sort(); +} + +/** + * Render a python collection with one item per line, as the formatter does. + * + * @param {string} open The text up to and including the opening bracket. + * @param {string[]} items The items, already rendered. + * @param {string} close The closing bracket and what follows it. + * @param {string} [indent] The indentation of the opening line. + * @returns {string} The lines, ending in a newline. + */ +function block(open, items, close, indent = "") { + return `${indent}${open}\n${items.map((item) => `${indent} ${item},\n`).join("")}${indent}${close}\n`; +} + +/** + * Render the python module. + * + * @param {Property[]} properties The CSS properties. + * @param {string[]} pseudoElements The pseudo-elements, without their colons. + * @returns {string} The whole file. + */ +export function renderCssProps(properties, pseudoElements) { + // Properties with the same keywords share one alias, named after the first. + /** @type {Map} */ + const aliasOf = new Map(); + let aliases = ""; + let fields = ""; + for (const { name, key, literals, open } of properties) { + /** @type {string | null} */ + let value = open; + if (!value) { + const signature = literals.join("|"); + let alias = aliasOf.get(signature); + if (!alias) { + alias = `_${name[0].toUpperCase()}${name.slice(1)}`; + aliasOf.set(signature, alias); + aliases += `\n${block( + `${alias}: TypeAlias = Literal[`, + literals.map((literal) => JSON.stringify(literal)), + "]", + " ", + )}`; + } + value = `${alias} | _StrVar`; + } + fields += ` ${key}: _Value[${value}]\n`; + } + for (const [key, kind] of REFLEX_KEYS) { + fields += ` ${key}: _Value[${kind}]\n`; + } + + const plainElements = pseudoElements.filter((name) => !name.startsWith("-")); + const underscored = [...PSEUDO_CLASSES, ...plainElements] + .sort() + .map((name) => ` _${name.replaceAll("-", "_")}: StyleProps\n`) + .join(""); + const selectors = [ + ...PSEUDO_CLASSES.map((name) => `":${name}": "StyleProps"`), + ...pseudoElements.map((name) => `"::${name}": "StyleProps"`), + ]; + + return `"""The CSS properties of an rx.ui style and the values each one takes. + +Generated by js/scripts/css-props.js from the type definitions of the pinned +@stylexjs/stylex package. Do not edit: run \`npm run generate\` in js/. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from typing import Any, Literal, TypeAlias, TypedDict, TypeVar + + from reflex_base.breakpoints import Breakpoints + from reflex_base.constants.colors import Color + from reflex_base.vars.base import Var + + _T = TypeVar("_T") + + # A value, one per breakpoint, or one per condition such as ":hover". + _Value: TypeAlias = ( + _T | Sequence[_T] | Breakpoints[Any, Any] | Mapping[str, _T | Mapping[str, _T]] + ) + _StrVar: TypeAlias = Var[str] + _Str: TypeAlias = str | Var[str] + _Size: TypeAlias = str | int | float | Var[str | int | float] + _Color: TypeAlias = str | Color | Var[str] | Var[Color] +${aliases} +${block("_Selectors = TypedDict(", ['"_Selectors"', `{\n${selectors.map((item) => ` ${item},\n`).join("")} }`, "total=False"], ")", " ")} + class StyleProps(_Selectors, total=False): + """The styles of one element: CSS properties and conditional blocks of them.""" + +${fields}${underscored} +else: + # A TypedDict of this size takes milliseconds to build, and nothing reads + # it at runtime, where a style is a plain dict. + StyleProps = dict + +${block("CSS_PROPS: dict[str, str] = {", [...properties.map(({ key, name }) => `"${key}": "${name}"`)], "}")} +${block( + "PSEUDO_CLASSES: frozenset[str] = frozenset({", + PSEUDO_CLASSES.map((name) => `"${name}"`), + "})", +)} +${block( + "PSEUDO_ELEMENTS: frozenset[str] = frozenset({", + pseudoElements.map((name) => `"${name}"`), + "})", +)}`; +} + +/** + * Render `_css_props.py` from the installed StyleX package. + * + * @returns {string} The whole file. + */ +export function render() { + return renderCssProps(readProperties(), readPseudoElements()); +} diff --git a/packages/reflex-components-ui/js/scripts/generate.js b/packages/reflex-components-ui/js/scripts/generate.js index ce09527c2e4..5e2b98e22d7 100644 --- a/packages/reflex-components-ui/js/scripts/generate.js +++ b/packages/reflex-components-ui/js/scripts/generate.js @@ -5,6 +5,8 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { render as renderCssProps } from "./css-props.js"; + /** * A committed file that a generator owns. * @@ -20,7 +22,12 @@ import { fileURLToPath } from "node:url"; * * @type {Generated[]} */ -export const GENERATED = []; +export const GENERATED = [ + { + path: "src/reflex_components_ui/style/_css_props.py", + render: renderCssProps, + }, +]; const PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url)); diff --git a/packages/reflex-components-ui/js/tests/css-props.test.js b/packages/reflex-components-ui/js/tests/css-props.test.js new file mode 100644 index 00000000000..5955a2a6593 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/css-props.test.js @@ -0,0 +1,165 @@ +// @vitest-environment node +import { expect, test } from "vitest"; + +import { + PSEUDO_CLASSES, + readProperties, + readPseudoElements, + renderCssProps, + snakeCase, +} from "../scripts/css-props.js"; + +test("names a property as a Reflex user writes it", () => { + expect( + ["color", "backgroundColor", "WebkitFontSmoothing", "zIndex"].map( + snakeCase, + ), + ).toEqual(["color", "background_color", "webkit_font_smoothing", "z_index"]); +}); + +test("reads what each kind of property accepts from StyleX's types", () => { + const properties = new Map( + readProperties().map((property) => [property.key, property]), + ); + expect(properties.size).toBe(521); + expect(properties.has("theme")).toBe(false); + expect(properties.get("box_sizing")).toEqual({ + name: "boxSizing", + key: "box_sizing", + literals: ["border-box", "content-box", "inherit", "initial", "unset"], + open: null, + }); + expect( + ["background_color", "border", "padding", "z_index", "content"].map((key) => + properties.get(key), + ), + ).toEqual([ + { + name: "backgroundColor", + key: "background_color", + literals: [], + open: "_Color", + }, + { name: "border", key: "border", literals: [], open: "_Color" }, + { name: "padding", key: "padding", literals: [], open: "_Size" }, + { name: "zIndex", key: "z_index", literals: [], open: "_Size" }, + { name: "content", key: "content", literals: [], open: "_Str" }, + ]); +}); + +test("reads the pseudo-elements StyleX types", () => { + const elements = readPseudoElements(); + expect(elements.length).toBe(33); + expect(elements.filter((name) => !name.startsWith("-"))).toEqual([ + "after", + "backdrop", + "before", + "cue", + "cue-region", + "file-selector-button", + "first-letter", + "first-line", + "grammar-error", + "marker", + "placeholder", + "selection", + "spelling-error", + "target-text", + ]); +}); + +test("renders the types and the runtime tables", () => { + const rendered = renderCssProps( + [ + { name: "color", key: "color", literals: [], open: "_Color" }, + { + name: "boxSizing", + key: "box_sizing", + literals: ["border-box", "content-box"], + open: null, + }, + { + name: "backgroundOrigin", + key: "background_origin", + literals: ["border-box", "content-box"], + open: null, + }, + ], + ["before"], + ); + const typed = rendered.slice( + rendered.indexOf(" _BoxSizing"), + rendered.indexOf(" _Selectors"), + ); + expect(typed).toBe(` _BoxSizing: TypeAlias = Literal[ + "border-box", + "content-box", + ] + +`); + const fields = rendered.slice( + rendered.indexOf(" class StyleProps"), + rendered.indexOf(" _active"), + ); + expect(fields).toBe(` class StyleProps(_Selectors, total=False): + """The styles of one element: CSS properties and conditional blocks of them.""" + + color: _Value[_Color] + box_sizing: _Value[_BoxSizing | _StrVar] + background_origin: _Value[_BoxSizing | _StrVar] + bg: _Value[_Color] + bg_color: _Value[_Color] + margin_x: _Value[_Size] + margin_y: _Value[_Size] + padding_x: _Value[_Size] + padding_y: _Value[_Size] +`); + expect( + rendered.slice( + rendered.indexOf("else:"), + rendered.indexOf("PSEUDO_CLASSES"), + ), + ).toBe(`else: + # A TypedDict of this size takes milliseconds to build, and nothing reads + # it at runtime, where a style is a plain dict. + StyleProps = dict + +CSS_PROPS: dict[str, str] = { + "color": "color", + "box_sizing": "boxSizing", + "background_origin": "backgroundOrigin", +} + +`); + expect( + rendered.slice(rendered.indexOf("PSEUDO_ELEMENTS:")), + ).toBe(`PSEUDO_ELEMENTS: frozenset[str] = frozenset({ + "before", +}) +`); + expect( + rendered.slice( + rendered.indexOf(" _Selectors"), + rendered.indexOf(" class StyleProps"), + ), + ).toBe(` _Selectors = TypedDict( + "_Selectors", + { +${PSEUDO_CLASSES.map((name) => ` ":${name}": "StyleProps",\n`).join("")} "::before": "StyleProps", + }, + total=False, + ) + +`); + expect( + rendered.slice( + rendered.indexOf(" _active"), + rendered.indexOf("else:"), + ), + ).toBe( + `${[...PSEUDO_CLASSES, "before"] + .sort() + .map((name) => ` _${name.replaceAll("-", "_")}: StyleProps\n`) + .join("")}\n`, + ); +}); diff --git a/packages/reflex-components-ui/news/+style-lowering.feature.md b/packages/reflex-components-ui/news/+style-lowering.feature.md new file mode 100644 index 00000000000..7fb0670354b --- /dev/null +++ b/packages/reflex-components-ui/news/+style-lowering.feature.md @@ -0,0 +1 @@ +Add `reflex_components_ui.style`: `StyleProps`, a typed dict of the CSS properties and conditions a style can hold, generated from StyleX's own types so that a type checker catches a misspelt property or keyword; `ComponentStyles`, the typed style table of a component; and `lower` and `merge`, which turn them into the style objects the compiler emits. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py new file mode 100644 index 00000000000..ebd7f21f19c --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py @@ -0,0 +1,33 @@ +"""The styles of the rx.ui components: their types, lowering and merging.""" + +from __future__ import annotations + +from reflex_components_ui.style._css_props import StyleProps +from reflex_components_ui.style.lower import ( + LAYOUT_PROPS, + VAR_MODULES, + Lowered, + StyleError, + lower, +) +from reflex_components_ui.style.merge import ( + Alternatives, + ComponentStyles, + CompoundStyle, + Merged, + merge, +) + +__all__ = [ + "LAYOUT_PROPS", + "VAR_MODULES", + "Alternatives", + "ComponentStyles", + "CompoundStyle", + "Lowered", + "Merged", + "StyleError", + "StyleProps", + "lower", + "merge", +] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/_css_props.py b/packages/reflex-components-ui/src/reflex_components_ui/style/_css_props.py new file mode 100644 index 00000000000..b4b021fe312 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/_css_props.py @@ -0,0 +1,2634 @@ +"""The CSS properties of an rx.ui style and the values each one takes. + +Generated by js/scripts/css-props.js from the type definitions of the pinned +@stylexjs/stylex package. Do not edit: run `npm run generate` in js/. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from typing import Any, Literal, TypeAlias, TypedDict, TypeVar + + from reflex_base.breakpoints import Breakpoints + from reflex_base.constants.colors import Color + from reflex_base.vars.base import Var + + _T = TypeVar("_T") + + # A value, one per breakpoint, or one per condition such as ":hover". + _Value: TypeAlias = ( + _T | Sequence[_T] | Breakpoints[Any, Any] | Mapping[str, _T | Mapping[str, _T]] + ) + _StrVar: TypeAlias = Var[str] + _Str: TypeAlias = str | Var[str] + _Size: TypeAlias = str | int | float | Var[str | int | float] + _Color: TypeAlias = str | Color | Var[str] | Var[Color] + + _AlignContent: TypeAlias = Literal[ + "baseline", + "center", + "end", + "first baseline", + "flex-end", + "flex-start", + "inherit", + "initial", + "last baseline", + "normal", + "safe center", + "space-around", + "space-between", + "space-evenly", + "start", + "stretch", + "unsafe center", + "unset", + ] + + _AlignItems: TypeAlias = Literal[ + "baseline", + "center", + "end", + "first baseline", + "flex-end", + "flex-start", + "inherit", + "initial", + "last baseline", + "normal", + "safe center", + "self-end", + "self-start", + "start", + "stretch", + "unsafe center", + "unset", + ] + + _AlignSelf: TypeAlias = Literal[ + "auto", + "baseline", + "center", + "end", + "first baseline", + "flex-end", + "flex-start", + "inherit", + "initial", + "last baseline", + "normal", + "safe center", + "self-end", + "self-start", + "start", + "stretch", + "unsafe center", + "unset", + ] + + _AlignmentBaseline: TypeAlias = Literal[ + "after-edge", + "alphabetic", + "auto", + "baseline", + "before-edge", + "central", + "hanging", + "ideographic", + "inherit", + "initial", + "mathematical", + "middle", + "text-after-edge", + "text-before-edge", + "unset", + ] + + _AnimationDirection: TypeAlias = Literal[ + "alternate", + "alternate-reverse", + "inherit", + "initial", + "normal", + "reverse", + "unset", + ] + + _AnimationFillMode: TypeAlias = Literal[ + "backwards", + "both", + "forwards", + "inherit", + "initial", + "none", + "unset", + ] + + _AnimationPlayState: TypeAlias = Literal[ + "inherit", + "initial", + "paused", + "running", + "unset", + ] + + _BackfaceVisibility: TypeAlias = Literal[ + "hidden", + "inherit", + "initial", + "unset", + "visible", + ] + + _BackgroundAttachment: TypeAlias = Literal[ + "fixed", + "inherit", + "initial", + "local", + "scroll", + "unset", + ] + + _BackgroundBlendMode: TypeAlias = Literal[ + "color", + "color-burn", + "color-dodge", + "darken", + "difference", + "exclusion", + "hard-light", + "hue", + "inherit", + "initial", + "lighten", + "luminosity", + "multiply", + "normal", + "overlay", + "saturation", + "screen", + "soft-light", + "unset", + ] + + _BackgroundClip: TypeAlias = Literal[ + "border-box", + "content-box", + "inherit", + "initial", + "padding-box", + "text", + "unset", + ] + + _BackgroundOrigin: TypeAlias = Literal[ + "border-box", + "content-box", + "inherit", + "initial", + "padding-box", + "unset", + ] + + _BorderBlockEndStyle: TypeAlias = Literal[ + "dashed", + "dotted", + "double", + "groove", + "hidden", + "inherit", + "initial", + "inset", + "none", + "outset", + "ridge", + "solid", + "unset", + ] + + _BorderCollapse: TypeAlias = Literal[ + "collapse", + "inherit", + "initial", + "separate", + "unset", + ] + + _BoxAlign: TypeAlias = Literal[ + "baseline", + "center", + "end", + "inherit", + "initial", + "start", + "stretch", + "unset", + ] + + _BoxDecorationBreak: TypeAlias = Literal[ + "clone", + "inherit", + "initial", + "slice", + "unset", + ] + + _BoxDirection: TypeAlias = Literal[ + "inherit", + "initial", + "normal", + "reverse", + "unset", + ] + + _BoxLines: TypeAlias = Literal[ + "inherit", + "initial", + "multiple", + "single", + "unset", + ] + + _BoxOrient: TypeAlias = Literal[ + "block-axis", + "horizontal", + "inherit", + "initial", + "inline-axis", + "unset", + "vertical", + ] + + _BoxSizing: TypeAlias = Literal[ + "border-box", + "content-box", + "inherit", + "initial", + "unset", + ] + + _BoxSuppress: TypeAlias = Literal[ + "discard", + "hide", + "inherit", + "initial", + "show", + "unset", + ] + + _BreakAfter: TypeAlias = Literal[ + "auto", + "avoid", + "avoid-column", + "avoid-page", + "avoid-region", + "column", + "inherit", + "initial", + "left", + "page", + "recto", + "region", + "right", + "unset", + "verso", + ] + + _BreakInside: TypeAlias = Literal[ + "auto", + "avoid", + "avoid-column", + "avoid-page", + "avoid-region", + "inherit", + "initial", + "unset", + ] + + _CaptionSide: TypeAlias = Literal[ + "block-end", + "block-start", + "bottom", + "inherit", + "initial", + "inline-end", + "inline-start", + "top", + "unset", + ] + + _Clear: TypeAlias = Literal[ + "both", + "inherit", + "initial", + "inline-end", + "inline-start", + "left", + "none", + "right", + "unset", + ] + + _ClipRule: TypeAlias = Literal[ + "evenodd", + "inherit", + "initial", + "nonzero", + "unset", + ] + + _ColorScheme: TypeAlias = Literal[ + "dark", + "light", + "light dark", + "normal", + "only dark", + "only light", + ] + + _ColumnFill: TypeAlias = Literal[ + "auto", + "balance", + "inherit", + "initial", + "unset", + ] + + _ColumnSpan: TypeAlias = Literal[ + "all", + "inherit", + "initial", + "none", + "unset", + ] + + _ContainerType: TypeAlias = Literal[ + "inherit", + "initial", + "inline-size", + "normal", + "size", + "unset", + ] + + _ContentVisibility: TypeAlias = Literal[ + "auto", + "hidden", + "inherit", + "initial", + "unset", + "visible", + ] + + _Cursor: TypeAlias = Literal[ + "-webkit-grab", + "-webkit-grabbing", + "alias", + "all-scroll", + "auto", + "cell", + "col-resize", + "context-menu", + "copy", + "crosshair", + "default", + "e-resize", + "ew-resize", + "grab", + "grabbing", + "help", + "inherit", + "initial", + "move", + "n-resize", + "ne-resize", + "nesw-resize", + "no-drop", + "none", + "not-allowed", + "ns-resize", + "nw-resize", + "nwse-resize", + "pointer", + "progress", + "row-resize", + "s-resize", + "se-resize", + "sw-resize", + "text", + "unset", + "vertical-text", + "w-resize", + "wait", + "zoom-in", + "zoom-out", + ] + + _Direction: TypeAlias = Literal[ + "inherit", + "initial", + "ltr", + "rtl", + "unset", + ] + + _Display: TypeAlias = Literal[ + "-webkit-box", + "block", + "contents", + "flex", + "flow-root", + "grid", + "inherit", + "initial", + "inline", + "inline-block", + "inline-flex", + "inline-grid", + "inline-list-item", + "inline-table", + "list-item", + "none", + "ruby", + "ruby-base", + "ruby-base-container", + "ruby-text", + "ruby-text-container", + "run-in", + "table", + "table-cell", + "table-column", + "table-column-group", + "table-footer-group", + "table-header-group", + "table-row", + "table-row-group", + "unset", + ] + + _DisplayInside: TypeAlias = Literal[ + "auto", + "block", + "flex", + "grid", + "inherit", + "initial", + "ruby", + "table", + "unset", + ] + + _DisplayList: TypeAlias = Literal[ + "inherit", + "initial", + "list-item", + "none", + "unset", + ] + + _DisplayOutside: TypeAlias = Literal[ + "block-level", + "contents", + "inherit", + "initial", + "inline-level", + "none", + "ruby-base", + "ruby-base-container", + "ruby-text", + "ruby-text-container", + "run-in", + "table-caption", + "table-cell", + "table-column", + "table-column-group", + "table-footer-group", + "table-header-group", + "table-row", + "table-row-group", + "unset", + ] + + _DominantBaseline: TypeAlias = Literal[ + "alphabetic", + "auto", + "central", + "hanging", + "ideographic", + "inherit", + "initial", + "mathematical", + "middle", + "no-change", + "reset-size", + "text-after-edge", + "text-before-edge", + "unset", + "use-script", + ] + + _EmptyCells: TypeAlias = Literal[ + "hide", + "inherit", + "initial", + "show", + "unset", + ] + + _FlexDirection: TypeAlias = Literal[ + "column", + "column-reverse", + "inherit", + "initial", + "row", + "row-reverse", + "unset", + ] + + _FlexFlow: TypeAlias = Literal[ + "column", + "column-reverse", + "inherit", + "initial", + "nowrap", + "row", + "row-reverse", + "unset", + "wrap", + "wrap-reverse", + ] + + _FlexWrap: TypeAlias = Literal[ + "inherit", + "initial", + "nowrap", + "unset", + "wrap", + "wrap-reverse", + ] + + _Float: TypeAlias = Literal[ + "end", + "inherit", + "initial", + "inline-end", + "inline-start", + "left", + "none", + "right", + "start", + "unset", + ] + + _FontKerning: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "none", + "normal", + "unset", + ] + + _FontOpticalSizing: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "none", + "unset", + ] + + _FontStyle: TypeAlias = Literal[ + "inherit", + "initial", + "italic", + "normal", + "oblique", + "unset", + ] + + _FontVariantCaps: TypeAlias = Literal[ + "all-petite-caps", + "all-small-caps", + "inherit", + "initial", + "normal", + "petite-caps", + "small-caps", + "titling-caps", + "unicase", + "unset", + ] + + _FontVariantPosition: TypeAlias = Literal[ + "inherit", + "initial", + "normal", + "sub", + "super", + "unset", + ] + + _Hyphens: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "manual", + "none", + "unset", + ] + + _ImeMode: TypeAlias = Literal[ + "active", + "auto", + "disabled", + "inactive", + "inherit", + "initial", + "normal", + "unset", + ] + + _InterpolateSize: TypeAlias = Literal[ + "allow-keywords", + "inherit", + "initial", + "numeric-only", + "unset", + ] + + _Isolation: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "isolate", + "unset", + ] + + _JustifyContent: TypeAlias = Literal[ + "center", + "end", + "flex-end", + "flex-start", + "inherit", + "initial", + "left", + "normal", + "right", + "safe center", + "space-around", + "space-between", + "space-evenly", + "start", + "stretch", + "unsafe center", + "unset", + ] + + _JustifyItems: TypeAlias = Literal[ + "baseline", + "center", + "end", + "first baseline", + "flex-end", + "flex-start", + "inherit", + "initial", + "last baseline", + "left", + "legacy center", + "legacy left", + "legacy right", + "normal", + "right", + "safe center", + "self-end", + "self-start", + "start", + "stretch", + "unsafe center", + "unset", + ] + + _JustifySelf: TypeAlias = Literal[ + "auto", + "baseline", + "center", + "end", + "first baseline", + "flex-end", + "flex-start", + "inherit", + "initial", + "last baseline", + "left", + "normal", + "right", + "safe center", + "self-end", + "self-start", + "start", + "stretch", + "unsafe center", + "unset", + ] + + _LineBreak: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "loose", + "normal", + "strict", + "unset", + ] + + _ListStylePosition: TypeAlias = Literal[ + "inherit", + "initial", + "inside", + "outside", + "unset", + ] + + _MarginTrim: TypeAlias = Literal[ + "block", + "block-end", + "block-start", + "inline", + "inline-end", + "inline-start", + "none", + ] + + _MaskBorderMode: TypeAlias = Literal[ + "alpha", + "inherit", + "initial", + "luminance", + "unset", + ] + + _MaskBorderRepeat: TypeAlias = Literal[ + "inherit", + "initial", + "repeat", + "round", + "space", + "stretch", + "unset", + ] + + _MaskComposite: TypeAlias = Literal[ + "add", + "exclude", + "inherit", + "initial", + "intersect", + "subtract", + "unset", + ] + + _MaskMode: TypeAlias = Literal[ + "alpha", + "inherit", + "initial", + "luminance", + "match-source", + "unset", + ] + + _MaskOrigin: TypeAlias = Literal[ + "border-box", + "content-box", + "fill-box", + "inherit", + "initial", + "margin-box", + "padding-box", + "stroke-box", + "unset", + "view-box", + ] + + _MathShift: TypeAlias = Literal[ + "compact", + "inherit", + "initial", + "normal", + "unset", + ] + + _MozOsxFontSmoothing: TypeAlias = Literal[ + "grayscale", + "inherit", + "initial", + "unset", + ] + + _MsOverflowStyle: TypeAlias = Literal[ + "-ms-autohiding-scrollbar", + "auto", + "inherit", + "initial", + "none", + "scrollbar", + "unset", + ] + + _ObjectFit: TypeAlias = Literal[ + "contain", + "cover", + "fill", + "inherit", + "initial", + "none", + "scale-down", + "unset", + ] + + _OutlineStyle: TypeAlias = Literal[ + "auto", + "dashed", + "dotted", + "double", + "groove", + "hidden", + "inherit", + "initial", + "inset", + "none", + "outset", + "ridge", + "solid", + "unset", + ] + + _Overflow: TypeAlias = Literal[ + "auto", + "clip", + "hidden", + "inherit", + "initial", + "scroll", + "unset", + "visible", + ] + + _OverflowWrap: TypeAlias = Literal[ + "anywhere", + "break-word", + "inherit", + "initial", + "normal", + "unset", + ] + + _OverscrollBehavior: TypeAlias = Literal[ + "auto", + "contain", + "inherit", + "initial", + "none", + "unset", + ] + + _PageBreakAfter: TypeAlias = Literal[ + "always", + "auto", + "avoid", + "inherit", + "initial", + "left", + "right", + "unset", + ] + + _PageBreakInside: TypeAlias = Literal[ + "auto", + "avoid", + "inherit", + "initial", + "unset", + ] + + _PaintOrder: TypeAlias = Literal[ + "fill", + "fill markers", + "markers", + "normal", + "stroke", + "stroke fill", + "stroke fill markers", + "stroke markers", + ] + + _PointerEvents: TypeAlias = Literal[ + "all", + "auto", + "fill", + "inherit", + "initial", + "none", + "painted", + "stroke", + "unset", + "visible", + "visibleFill", + "visiblePainted", + "visibleStroke", + ] + + _Position: TypeAlias = Literal[ + "absolute", + "fixed", + "inherit", + "initial", + "relative", + "static", + "sticky", + "unset", + ] + + _PositionArea: TypeAlias = Literal[ + "block-end", + "block-start", + "bottom", + "center", + "inherit", + "initial", + "inline-end", + "inline-start", + "left", + "right", + "span-block-end", + "span-block-start", + "span-inline-end", + "span-inline-start", + "top", + "unset", + ] + + _PositionVisibility: TypeAlias = Literal[ + "always", + "anchors-visible", + "inherit", + "initial", + "no-overflow", + "unset", + ] + + _PrintColorAdjust: TypeAlias = Literal[ + "economy", + "exact", + "inherit", + "initial", + "unset", + ] + + _Resize: TypeAlias = Literal[ + "both", + "horizontal", + "inherit", + "initial", + "none", + "unset", + "vertical", + ] + + _RubyAlign: TypeAlias = Literal[ + "center", + "inherit", + "initial", + "space-around", + "space-between", + "start", + "unset", + ] + + _RubyMerge: TypeAlias = Literal[ + "auto", + "collapse", + "inherit", + "initial", + "separate", + "unset", + ] + + _RubyPosition: TypeAlias = Literal[ + "inherit", + "initial", + "inter-character", + "over", + "under", + "unset", + ] + + _ScrollBehavior: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "smooth", + "unset", + ] + + _ScrollSnapAlign: TypeAlias = Literal[ + "center", + "end", + "inherit", + "initial", + "none", + "start", + "unset", + ] + + _ScrollSnapStop: TypeAlias = Literal[ + "always", + "inherit", + "initial", + "normal", + "unset", + ] + + _ScrollSnapType: TypeAlias = Literal[ + "block", + "block mandatory", + "block proximity", + "both", + "both mandatory", + "both proximity", + "inherit", + "initial", + "inline", + "inline mandatory", + "inline proximity", + "none", + "unset", + "x", + "x mandatory", + "x proximity", + "y", + "y mandatory", + "y proximity", + ] + + _ScrollTimelineAxis: TypeAlias = Literal[ + "block", + "inherit", + "initial", + "inline", + "unset", + "x", + "y", + ] + + _ScrollbarGutter: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "stable", + "stable both-edges", + "unset", + ] + + _ScrollbarWidth: TypeAlias = Literal[ + "auto", + "inherit", + "initial", + "none", + "thin", + "unset", + ] + + _ShapeRendering: TypeAlias = Literal[ + "auto", + "crispEdges", + "geometricPrecision", + "inherit", + "initial", + "optimizeSpeed", + "unset", + ] + + _StrokeLinecap: TypeAlias = Literal[ + "butt", + "inherit", + "initial", + "round", + "square", + "unset", + ] + + _StrokeLinejoin: TypeAlias = Literal[ + "bevel", + "inherit", + "initial", + "miter", + "round", + "unset", + ] + + _TableLayout: TypeAlias = Literal[ + "auto", + "fixed", + "inherit", + "initial", + "unset", + ] + + _TextAlign: TypeAlias = Literal[ + "center", + "end", + "inherit", + "initial", + "justify", + "left", + "match-parent", + "right", + "start", + "unset", + ] + + _TextAlignLast: TypeAlias = Literal[ + "auto", + "center", + "end", + "inherit", + "initial", + "justify", + "left", + "right", + "start", + "unset", + ] + + _TextAnchor: TypeAlias = Literal[ + "end", + "inherit", + "initial", + "middle", + "start", + "unset", + ] + + _TextDecorationSkipInk: TypeAlias = Literal[ + "all", + "auto", + "inherit", + "initial", + "none", + "unset", + ] + + _TextDecorationStyle: TypeAlias = Literal[ + "dashed", + "dotted", + "double", + "inherit", + "initial", + "solid", + "unset", + "wavy", + ] + + _TextJustify: TypeAlias = Literal[ + "auto", + "distribute", + "inter-character", + "inter-word", + "none", + ] + + _TextOrientation: TypeAlias = Literal[ + "inherit", + "initial", + "mixed", + "sideways", + "unset", + "upright", + ] + + _TextRendering: TypeAlias = Literal[ + "auto", + "geometricPrecision", + "inherit", + "initial", + "optimizeLegibility", + "optimizeSpeed", + "unset", + ] + + _TextTransform: TypeAlias = Literal[ + "capitalize", + "full-width", + "inherit", + "initial", + "lowercase", + "none", + "unset", + "uppercase", + ] + + _TextWrap: TypeAlias = Literal[ + "balance", + "inherit", + "initial", + "nowrap", + "pretty", + "stable", + "unset", + "wrap", + ] + + _TransformBox: TypeAlias = Literal[ + "border-box", + "fill-box", + "inherit", + "initial", + "unset", + "view-box", + ] + + _TransformStyle: TypeAlias = Literal[ + "flat", + "inherit", + "initial", + "preserve-3d", + "unset", + ] + + _UnicodeBidi: TypeAlias = Literal[ + "bidi-override", + "embed", + "inherit", + "initial", + "isolate", + "isolate-override", + "normal", + "plaintext", + "unset", + ] + + _UserSelect: TypeAlias = Literal[ + "all", + "auto", + "contain", + "inherit", + "initial", + "none", + "text", + "unset", + ] + + _Visibility: TypeAlias = Literal[ + "collapse", + "hidden", + "inherit", + "initial", + "unset", + "visible", + ] + + _VoiceStress: TypeAlias = Literal[ + "inherit", + "initial", + "moderate", + "none", + "normal", + "reduced", + "strong", + "unset", + ] + + _WebkitBackgroundClip: TypeAlias = Literal[ + "border-box", + "content-box", + "padding-box", + "text", + ] + + _WebkitBoxOrient: TypeAlias = Literal[ + "block-axis", + "horizontal", + "inline-axis", + "vertical", + ] + + _WebkitFontSmoothing: TypeAlias = Literal[ + "antialiased", + "inherit", + "initial", + "unset", + ] + + _WhiteSpace: TypeAlias = Literal[ + "inherit", + "initial", + "normal", + "nowrap", + "pre", + "pre-line", + "pre-wrap", + "unset", + ] + + _WordBreak: TypeAlias = Literal[ + "break-all", + "break-word", + "inherit", + "initial", + "keep-all", + "normal", + "unset", + ] + + _WordWrap: TypeAlias = Literal[ + "break-word", + "inherit", + "initial", + "normal", + "unset", + ] + + _WritingMode: TypeAlias = Literal[ + "horizontal-tb", + "inherit", + "initial", + "lr", + "lr-tb", + "rl", + "rl-tb", + "sideways-lr", + "sideways-rl", + "tb", + "tb-rl", + "unset", + "vertical-lr", + "vertical-rl", + ] + + _Selectors = TypedDict( + "_Selectors", + { + ":active": "StyleProps", + ":any-link": "StyleProps", + ":autofill": "StyleProps", + ":checked": "StyleProps", + ":default": "StyleProps", + ":disabled": "StyleProps", + ":empty": "StyleProps", + ":enabled": "StyleProps", + ":first-child": "StyleProps", + ":first-of-type": "StyleProps", + ":focus": "StyleProps", + ":focus-visible": "StyleProps", + ":focus-within": "StyleProps", + ":fullscreen": "StyleProps", + ":hover": "StyleProps", + ":in-range": "StyleProps", + ":indeterminate": "StyleProps", + ":invalid": "StyleProps", + ":last-child": "StyleProps", + ":last-of-type": "StyleProps", + ":link": "StyleProps", + ":modal": "StyleProps", + ":only-child": "StyleProps", + ":only-of-type": "StyleProps", + ":open": "StyleProps", + ":optional": "StyleProps", + ":out-of-range": "StyleProps", + ":placeholder-shown": "StyleProps", + ":popover-open": "StyleProps", + ":read-only": "StyleProps", + ":read-write": "StyleProps", + ":required": "StyleProps", + ":target": "StyleProps", + ":user-invalid": "StyleProps", + ":user-valid": "StyleProps", + ":valid": "StyleProps", + ":visited": "StyleProps", + "::-moz-progress-bar": "StyleProps", + "::-moz-range-progress": "StyleProps", + "::-moz-range-thumb": "StyleProps", + "::-moz-range-track": "StyleProps", + "::-webkit-progress-bar": "StyleProps", + "::-webkit-progress-value": "StyleProps", + "::-webkit-resizer": "StyleProps", + "::-webkit-scrollbar": "StyleProps", + "::-webkit-scrollbar-button": "StyleProps", + "::-webkit-scrollbar-corner": "StyleProps", + "::-webkit-scrollbar-thumb": "StyleProps", + "::-webkit-scrollbar-track": "StyleProps", + "::-webkit-scrollbar-track-piece": "StyleProps", + "::-webkit-search-cancel-button": "StyleProps", + "::-webkit-search-decoration": "StyleProps", + "::-webkit-search-results-button": "StyleProps", + "::-webkit-search-results-decoration": "StyleProps", + "::-webkit-slider-runnable-track": "StyleProps", + "::-webkit-slider-thumb": "StyleProps", + "::after": "StyleProps", + "::backdrop": "StyleProps", + "::before": "StyleProps", + "::cue": "StyleProps", + "::cue-region": "StyleProps", + "::file-selector-button": "StyleProps", + "::first-letter": "StyleProps", + "::first-line": "StyleProps", + "::grammar-error": "StyleProps", + "::marker": "StyleProps", + "::placeholder": "StyleProps", + "::selection": "StyleProps", + "::spelling-error": "StyleProps", + "::target-text": "StyleProps", + }, + total=False, + ) + + class StyleProps(_Selectors, total=False): + """The styles of one element: CSS properties and conditional blocks of them.""" + + accent_color: _Value[_Color] + align_content: _Value[_AlignContent | _StrVar] + align_items: _Value[_AlignItems | _StrVar] + align_self: _Value[_AlignSelf | _StrVar] + align_tracks: _Value[_Str] + alignment_baseline: _Value[_AlignmentBaseline | _StrVar] + anchor_name: _Value[_Str] + animation: _Value[_Str] + animation_composition: _Value[_Str] + animation_delay: _Value[_Str] + animation_direction: _Value[_AnimationDirection | _StrVar] + animation_duration: _Value[_Str] + animation_fill_mode: _Value[_AnimationFillMode | _StrVar] + animation_iteration_count: _Value[_Size] + animation_name: _Value[_Str] + animation_play_state: _Value[_AnimationPlayState | _StrVar] + animation_range: _Value[_Str] + animation_range_end: _Value[_Str] + animation_range_start: _Value[_Str] + animation_timeline: _Value[_Str] + animation_timing_function: _Value[_Str] + appearance: _Value[_Str] + aspect_ratio: _Value[_Size] + azimuth: _Value[_Str] + backdrop_filter: _Value[_Str] + backface_visibility: _Value[_BackfaceVisibility | _StrVar] + background: _Value[_Str] + background_attachment: _Value[_BackgroundAttachment | _StrVar] + background_blend_mode: _Value[_BackgroundBlendMode | _StrVar] + background_clip: _Value[_BackgroundClip | _StrVar] + background_color: _Value[_Color] + background_image: _Value[_Str] + background_origin: _Value[_BackgroundOrigin | _StrVar] + background_position: _Value[_Str] + background_position_x: _Value[_Str] + background_position_y: _Value[_Str] + background_repeat: _Value[_Str] + background_size: _Value[_Str] + baseline_shift: _Value[_Size] + behavior: _Value[_Str] + block_size: _Value[_Size] + border: _Value[_Color] + border_block: _Value[_Color] + border_block_color: _Value[_Color] + border_block_end: _Value[_Color] + border_block_end_color: _Value[_Color] + border_block_end_style: _Value[_BorderBlockEndStyle | _StrVar] + border_block_end_width: _Value[_Size] + border_block_start: _Value[_Color] + border_block_start_color: _Value[_Color] + border_block_start_style: _Value[_BorderBlockEndStyle | _StrVar] + border_block_start_width: _Value[_Size] + border_block_style: _Value[_BorderBlockEndStyle | _StrVar] + border_block_width: _Value[_Size] + border_bottom: _Value[_Color] + border_bottom_color: _Value[_Color] + border_bottom_left_radius: _Value[_Size] + border_bottom_right_radius: _Value[_Size] + border_bottom_style: _Value[_BorderBlockEndStyle | _StrVar] + border_bottom_width: _Value[_Size] + border_collapse: _Value[_BorderCollapse | _StrVar] + border_color: _Value[_Color] + border_end_end_radius: _Value[_Size] + border_end_start_radius: _Value[_Size] + border_image: _Value[_Size] + border_image_outset: _Value[_Str] + border_image_repeat: _Value[_Str] + border_image_slice: _Value[_Size] + border_image_source: _Value[_Str] + border_image_width: _Value[_Str] + border_inline: _Value[_Color] + border_inline_color: _Value[_Color] + border_inline_end: _Value[_Color] + border_inline_end_color: _Value[_Color] + border_inline_end_style: _Value[_BorderBlockEndStyle | _StrVar] + border_inline_end_width: _Value[_Size] + border_inline_start: _Value[_Color] + border_inline_start_color: _Value[_Color] + border_inline_start_style: _Value[_BorderBlockEndStyle | _StrVar] + border_inline_start_width: _Value[_Size] + border_inline_style: _Value[_BorderBlockEndStyle | _StrVar] + border_inline_width: _Value[_Size] + border_left: _Value[_Color] + border_left_color: _Value[_Color] + border_left_style: _Value[_BorderBlockEndStyle | _StrVar] + border_left_width: _Value[_Size] + border_radius: _Value[_Size] + border_right: _Value[_Color] + border_right_color: _Value[_Color] + border_right_style: _Value[_BorderBlockEndStyle | _StrVar] + border_right_width: _Value[_Size] + border_spacing: _Value[_Size] + border_start_end_radius: _Value[_Size] + border_start_start_radius: _Value[_Size] + border_style: _Value[_BorderBlockEndStyle | _StrVar] + border_top: _Value[_Color] + border_top_color: _Value[_Color] + border_top_left_radius: _Value[_Size] + border_top_right_radius: _Value[_Size] + border_top_style: _Value[_BorderBlockEndStyle | _StrVar] + border_top_width: _Value[_Size] + border_width: _Value[_Size] + bottom: _Value[_Size] + box_align: _Value[_BoxAlign | _StrVar] + box_decoration_break: _Value[_BoxDecorationBreak | _StrVar] + box_direction: _Value[_BoxDirection | _StrVar] + box_flex: _Value[_Size] + box_flex_group: _Value[_Size] + box_lines: _Value[_BoxLines | _StrVar] + box_ordinal_group: _Value[_Size] + box_orient: _Value[_BoxOrient | _StrVar] + box_shadow: _Value[_Str] + box_sizing: _Value[_BoxSizing | _StrVar] + box_suppress: _Value[_BoxSuppress | _StrVar] + break_after: _Value[_BreakAfter | _StrVar] + break_before: _Value[_BreakAfter | _StrVar] + break_inside: _Value[_BreakInside | _StrVar] + caption_side: _Value[_CaptionSide | _StrVar] + caret: _Value[_Str] + caret_color: _Value[_Color] + caret_shape: _Value[_Str] + clear: _Value[_Clear | _StrVar] + clip: _Value[_Str] + clip_path: _Value[_Str] + clip_rule: _Value[_ClipRule | _StrVar] + color: _Value[_Color] + color_scheme: _Value[_ColorScheme | _StrVar] + column_count: _Value[_Size] + column_fill: _Value[_ColumnFill | _StrVar] + column_gap: _Value[_Size] + column_rule: _Value[_Color] + column_rule_color: _Value[_Color] + column_rule_style: _Value[_BorderBlockEndStyle | _StrVar] + column_rule_width: _Value[_Size] + column_span: _Value[_ColumnSpan | _StrVar] + column_width: _Value[_Size] + columns: _Value[_Size] + contain: _Value[_Str] + contain_intrinsic_block_size: _Value[_Size] + contain_intrinsic_height: _Value[_Size] + contain_intrinsic_inline_size: _Value[_Size] + contain_intrinsic_size: _Value[_Size] + contain_intrinsic_width: _Value[_Size] + container: _Value[_Str] + container_name: _Value[_Str] + container_type: _Value[_ContainerType | _StrVar] + content: _Value[_Str] + content_visibility: _Value[_ContentVisibility | _StrVar] + corner_bottom_left_shape: _Value[_Str] + corner_bottom_right_shape: _Value[_Str] + corner_end_end_shape: _Value[_Str] + corner_end_start_shape: _Value[_Str] + corner_shape: _Value[_Str] + corner_start_end_shape: _Value[_Str] + corner_start_start_shape: _Value[_Str] + corner_top_left_shape: _Value[_Str] + corner_top_right_shape: _Value[_Str] + counter_increment: _Value[_Str] + counter_reset: _Value[_Str] + counter_set: _Value[_Size] + cue: _Value[_Size] + cue_after: _Value[_Size] + cue_before: _Value[_Size] + cursor: _Value[_Cursor | _StrVar] + direction: _Value[_Direction | _StrVar] + display: _Value[_Display | _StrVar] + display_inside: _Value[_DisplayInside | _StrVar] + display_list: _Value[_DisplayList | _StrVar] + display_outside: _Value[_DisplayOutside | _StrVar] + dominant_baseline: _Value[_DominantBaseline | _StrVar] + empty_cells: _Value[_EmptyCells | _StrVar] + end: _Value[_Size] + fill: _Value[_Color] + fill_opacity: _Value[_Size] + fill_rule: _Value[_ClipRule | _StrVar] + filter: _Value[_Str] + flex: _Value[_Size] + flex_basis: _Value[_Size] + flex_direction: _Value[_FlexDirection | _StrVar] + flex_flow: _Value[_FlexFlow | _StrVar] + flex_grow: _Value[_Size] + flex_shrink: _Value[_Size] + flex_wrap: _Value[_FlexWrap | _StrVar] + float: _Value[_Float | _StrVar] + font: _Value[_Str] + font_family: _Value[_Str] + font_feature_settings: _Value[_Str] + font_kerning: _Value[_FontKerning | _StrVar] + font_language_override: _Value[_Str] + font_optical_sizing: _Value[_FontOpticalSizing | _StrVar] + font_palette: _Value[_Str] + font_size: _Value[_Size] + font_size_adjust: _Value[_Size] + font_stretch: _Value[_Str] + font_style: _Value[_FontStyle | _StrVar] + font_synthesis: _Value[_Str] + font_synthesis_position: _Value[_FontOpticalSizing | _StrVar] + font_synthesis_small_caps: _Value[_FontOpticalSizing | _StrVar] + font_synthesis_style: _Value[_FontOpticalSizing | _StrVar] + font_synthesis_weight: _Value[_FontOpticalSizing | _StrVar] + font_variant: _Value[_Str] + font_variant_alternates: _Value[_Str] + font_variant_caps: _Value[_FontVariantCaps | _StrVar] + font_variant_east_asian: _Value[_Str] + font_variant_ligatures: _Value[_Str] + font_variant_numeric: _Value[_Str] + font_variant_position: _Value[_FontVariantPosition | _StrVar] + font_variation_settings: _Value[_Str] + font_weight: _Value[_Size] + forced_color_adjust: _Value[_FontOpticalSizing | _StrVar] + gap: _Value[_Size] + glyph_orientation_horizontal: _Value[_Size] + glyph_orientation_vertical: _Value[_Size] + grid: _Value[_Str] + grid_area: _Value[_Str] + grid_auto_columns: _Value[_Size] + grid_auto_flow: _Value[_Str] + grid_auto_rows: _Value[_Size] + grid_column: _Value[_Str] + grid_column_end: _Value[_Str] + grid_column_gap: _Value[_Size] + grid_column_start: _Value[_Str] + grid_gap: _Value[_Size] + grid_row: _Value[_Str] + grid_row_end: _Value[_Str] + grid_row_gap: _Value[_Size] + grid_row_start: _Value[_Str] + grid_template: _Value[_Str] + grid_template_areas: _Value[_Str] + grid_template_columns: _Value[_Str] + grid_template_rows: _Value[_Str] + hanging_punctuation: _Value[_Str] + height: _Value[_Size] + hyphenate_character: _Value[_Str] + hyphenate_limit_chars: _Value[_Size] + hyphens: _Value[_Hyphens | _StrVar] + image_orientation: _Value[_Size] + image_rendering: _Value[_Str] + image_resolution: _Value[_Str] + ime_mode: _Value[_ImeMode | _StrVar] + initial_letter: _Value[_Str] + initial_letter_align: _Value[_Str] + inline_size: _Value[_Size] + inset: _Value[_Size] + inset_block: _Value[_Size] + inset_block_end: _Value[_Size] + inset_block_start: _Value[_Size] + inset_inline: _Value[_Size] + inset_inline_end: _Value[_Size] + inset_inline_start: _Value[_Size] + interpolate_size: _Value[_InterpolateSize | _StrVar] + isolation: _Value[_Isolation | _StrVar] + justify_content: _Value[_JustifyContent | _StrVar] + justify_items: _Value[_JustifyItems | _StrVar] + justify_self: _Value[_JustifySelf | _StrVar] + justify_tracks: _Value[_Str] + kerning: _Value[_Size] + left: _Value[_Size] + letter_spacing: _Value[_Size] + line_break: _Value[_LineBreak | _StrVar] + line_height: _Value[_Size] + line_height_step: _Value[_Size] + list_style: _Value[_Str] + list_style_image: _Value[_Str] + list_style_position: _Value[_ListStylePosition | _StrVar] + list_style_type: _Value[_Str] + margin: _Value[_Size] + margin_block: _Value[_Size] + margin_block_end: _Value[_Size] + margin_block_start: _Value[_Size] + margin_bottom: _Value[_Size] + margin_inline: _Value[_Size] + margin_inline_end: _Value[_Size] + margin_inline_start: _Value[_Size] + margin_left: _Value[_Size] + margin_right: _Value[_Size] + margin_top: _Value[_Size] + margin_trim: _Value[_MarginTrim | _StrVar] + marker: _Value[_Str] + marker_end: _Value[_Str] + marker_mid: _Value[_Str] + marker_offset: _Value[_Size] + marker_start: _Value[_Str] + mask: _Value[_Str] + mask_border: _Value[_Str] + mask_border_mode: _Value[_MaskBorderMode | _StrVar] + mask_border_outset: _Value[_Size] + mask_border_repeat: _Value[_MaskBorderRepeat | _StrVar] + mask_border_slice: _Value[_Size] + mask_border_source: _Value[_Str] + mask_border_width: _Value[_Size] + mask_clip: _Value[_Str] + mask_composite: _Value[_MaskComposite | _StrVar] + mask_image: _Value[_Str] + mask_mode: _Value[_MaskMode | _StrVar] + mask_origin: _Value[_MaskOrigin | _StrVar] + mask_position: _Value[_Str] + mask_repeat: _Value[_Str] + mask_size: _Value[_Str] + mask_type: _Value[_MaskBorderMode | _StrVar] + masonry_auto_flow: _Value[_Str] + math_depth: _Value[_Size] + math_shift: _Value[_MathShift | _StrVar] + math_style: _Value[_MathShift | _StrVar] + max_block_size: _Value[_Size] + max_height: _Value[_Size] + max_inline_size: _Value[_Size] + max_width: _Value[_Size] + min_block_size: _Value[_Size] + min_height: _Value[_Size] + min_inline_size: _Value[_Size] + min_width: _Value[_Size] + mix_blend_mode: _Value[_BackgroundBlendMode | _StrVar] + motion: _Value[_Size] + motion_offset: _Value[_Size] + motion_path: _Value[_Str] + motion_rotation: _Value[_Size] + moz_osx_font_smoothing: _Value[_MozOsxFontSmoothing | _StrVar] + ms_overflow_style: _Value[_MsOverflowStyle | _StrVar] + object_fit: _Value[_ObjectFit | _StrVar] + object_position: _Value[_Str] + offset: _Value[_Str] + offset_anchor: _Value[_Str] + offset_distance: _Value[_Size] + offset_path: _Value[_Str] + offset_position: _Value[_Str] + offset_rotate: _Value[_Str] + opacity: _Value[_Size] + order: _Value[_Size] + orphans: _Value[_Size] + outline: _Value[_Str] + outline_color: _Value[_Color] + outline_offset: _Value[_Size] + outline_style: _Value[_OutlineStyle | _StrVar] + outline_width: _Value[_Size] + overflow: _Value[_Overflow | _StrVar] + overflow_anchor: _Value[_FontOpticalSizing | _StrVar] + overflow_block: _Value[_Overflow | _StrVar] + overflow_block_x: _Value[_Overflow | _StrVar] + overflow_clip_margin: _Value[_Str] + overflow_wrap: _Value[_OverflowWrap | _StrVar] + overflow_x: _Value[_Overflow | _StrVar] + overflow_y: _Value[_Overflow | _StrVar] + overscroll_behavior: _Value[_OverscrollBehavior | _StrVar] + overscroll_behavior_block: _Value[_OverscrollBehavior | _StrVar] + overscroll_behavior_inline: _Value[_OverscrollBehavior | _StrVar] + overscroll_behavior_x: _Value[_OverscrollBehavior | _StrVar] + overscroll_behavior_y: _Value[_OverscrollBehavior | _StrVar] + padding: _Value[_Size] + padding_block: _Value[_Size] + padding_block_end: _Value[_Size] + padding_block_start: _Value[_Size] + padding_bottom: _Value[_Size] + padding_inline: _Value[_Size] + padding_inline_end: _Value[_Size] + padding_inline_start: _Value[_Size] + padding_left: _Value[_Size] + padding_right: _Value[_Size] + padding_top: _Value[_Size] + page: _Value[_Str] + page_break_after: _Value[_PageBreakAfter | _StrVar] + page_break_before: _Value[_PageBreakAfter | _StrVar] + page_break_inside: _Value[_PageBreakInside | _StrVar] + paint_order: _Value[_PaintOrder | _StrVar] + pause: _Value[_Size] + pause_after: _Value[_Size] + pause_before: _Value[_Size] + perspective: _Value[_Size] + perspective_origin: _Value[_Str] + place_content: _Value[_Str] + place_items: _Value[_Str] + place_self: _Value[_Str] + pointer_events: _Value[_PointerEvents | _StrVar] + position: _Value[_Position | _StrVar] + position_anchor: _Value[_Str] + position_area: _Value[_PositionArea | _StrVar] + position_try: _Value[_Str] + position_try_fallbacks: _Value[_Str] + position_try_options: _Value[_Str] + position_visibility: _Value[_PositionVisibility | _StrVar] + print_color_adjust: _Value[_PrintColorAdjust | _StrVar] + quotes: _Value[_Str] + resize: _Value[_Resize | _StrVar] + rest: _Value[_Size] + rest_after: _Value[_Size] + rest_before: _Value[_Size] + right: _Value[_Size] + rotate: _Value[_Size] + row_gap: _Value[_Size] + ruby_align: _Value[_RubyAlign | _StrVar] + ruby_merge: _Value[_RubyMerge | _StrVar] + ruby_position: _Value[_RubyPosition | _StrVar] + scale: _Value[_Size] + scroll_behavior: _Value[_ScrollBehavior | _StrVar] + scroll_margin: _Value[_Size] + scroll_margin_block: _Value[_Size] + scroll_margin_block_end: _Value[_Size] + scroll_margin_block_start: _Value[_Size] + scroll_margin_bottom: _Value[_Size] + scroll_margin_inline: _Value[_Size] + scroll_margin_inline_end: _Value[_Size] + scroll_margin_inline_start: _Value[_Size] + scroll_margin_left: _Value[_Size] + scroll_margin_right: _Value[_Size] + scroll_margin_top: _Value[_Size] + scroll_padding: _Value[_Size] + scroll_padding_block: _Value[_Size] + scroll_padding_block_end: _Value[_Size] + scroll_padding_block_start: _Value[_Size] + scroll_padding_bottom: _Value[_Size] + scroll_padding_inline: _Value[_Size] + scroll_padding_inline_end: _Value[_Size] + scroll_padding_inline_start: _Value[_Size] + scroll_padding_left: _Value[_Size] + scroll_padding_right: _Value[_Size] + scroll_padding_top: _Value[_Size] + scroll_snap_align: _Value[_ScrollSnapAlign | _StrVar] + scroll_snap_stop: _Value[_ScrollSnapStop | _StrVar] + scroll_snap_type: _Value[_ScrollSnapType | _StrVar] + scroll_timeline: _Value[_Str] + scroll_timeline_axis: _Value[_ScrollTimelineAxis | _StrVar] + scroll_timeline_name: _Value[_Str] + scrollbar_color: _Value[_Color] + scrollbar_gutter: _Value[_ScrollbarGutter | _StrVar] + scrollbar_width: _Value[_ScrollbarWidth | _StrVar] + shape_image_threshold: _Value[_Size] + shape_margin: _Value[_Size] + shape_outside: _Value[_Str] + shape_rendering: _Value[_ShapeRendering | _StrVar] + speak: _Value[_FontKerning | _StrVar] + speak_as: _Value[_Str] + src: _Value[_Str] + start: _Value[_Size] + stroke: _Value[_Color] + stroke_dasharray: _Value[_Str] + stroke_dashoffset: _Value[_Size] + stroke_linecap: _Value[_StrokeLinecap | _StrVar] + stroke_linejoin: _Value[_StrokeLinejoin | _StrVar] + stroke_miterlimit: _Value[_Size] + stroke_opacity: _Value[_Size] + stroke_width: _Value[_Size] + tab_size: _Value[_Size] + table_layout: _Value[_TableLayout | _StrVar] + text_align: _Value[_TextAlign | _StrVar] + text_align_last: _Value[_TextAlignLast | _StrVar] + text_anchor: _Value[_TextAnchor | _StrVar] + text_combine_upright: _Value[_Str] + text_decoration: _Value[_Color] + text_decoration_color: _Value[_Color] + text_decoration_line: _Value[_Str] + text_decoration_skip: _Value[_Str] + text_decoration_skip_ink: _Value[_TextDecorationSkipInk | _StrVar] + text_decoration_style: _Value[_TextDecorationStyle | _StrVar] + text_decoration_thickness: _Value[_Size] + text_emphasis: _Value[_Color] + text_emphasis_color: _Value[_Color] + text_emphasis_position: _Value[_Str] + text_emphasis_style: _Value[_Str] + text_fill_color: _Value[_Color] + text_indent: _Value[_Size] + text_justify: _Value[_TextJustify | _StrVar] + text_orientation: _Value[_TextOrientation | _StrVar] + text_overflow: _Value[_Str] + text_rendering: _Value[_TextRendering | _StrVar] + text_shadow: _Value[_Str] + text_size_adjust: _Value[_Str] + text_transform: _Value[_TextTransform | _StrVar] + text_underline_offset: _Value[_Size] + text_underline_position: _Value[_Str] + text_wrap: _Value[_TextWrap | _StrVar] + timeline_scope: _Value[_Str] + top: _Value[_Size] + touch_action: _Value[_Str] + transform: _Value[_Str] + transform_box: _Value[_TransformBox | _StrVar] + transform_origin: _Value[_Size] + transform_style: _Value[_TransformStyle | _StrVar] + transition: _Value[_Size] + transition_delay: _Value[_Str] + transition_duration: _Value[_Str] + transition_property: _Value[_Str] + transition_timing_function: _Value[_Str] + translate: _Value[_Size] + unicode_bidi: _Value[_UnicodeBidi | _StrVar] + unicode_range: _Value[_Str] + user_select: _Value[_UserSelect | _StrVar] + vertical_align: _Value[_Size] + view_timeline: _Value[_Str] + view_timeline_axis: _Value[_ScrollTimelineAxis | _StrVar] + view_timeline_inset: _Value[_Size] + view_timeline_name: _Value[_Str] + view_transition_name: _Value[_Str] + visibility: _Value[_Visibility | _StrVar] + voice_balance: _Value[_Size] + voice_duration: _Value[_Str] + voice_family: _Value[_Str] + voice_pitch: _Value[_Size] + voice_range: _Value[_Size] + voice_rate: _Value[_Str] + voice_stress: _Value[_VoiceStress | _StrVar] + voice_volume: _Value[_Str] + webkit_appearance: _Value[_Str] + webkit_background_clip: _Value[_WebkitBackgroundClip | _StrVar] + webkit_box_orient: _Value[_WebkitBoxOrient | _StrVar] + webkit_font_smoothing: _Value[_WebkitFontSmoothing | _StrVar] + webkit_line_clamp: _Value[_Size] + webkit_mask_image: _Value[_Str] + webkit_tap_highlight_color: _Value[_Color] + webkit_text_fill_color: _Value[_Color] + webkit_text_stroke_color: _Value[_Color] + webkit_text_stroke_width: _Value[_Size] + white_space: _Value[_WhiteSpace | _StrVar] + widows: _Value[_Size] + width: _Value[_Size] + will_change: _Value[_Str] + word_break: _Value[_WordBreak | _StrVar] + word_spacing: _Value[_Size] + word_wrap: _Value[_WordWrap | _StrVar] + writing_mode: _Value[_WritingMode | _StrVar] + z_index: _Value[_Size] + zoom: _Value[_Size] + bg: _Value[_Color] + bg_color: _Value[_Color] + margin_x: _Value[_Size] + margin_y: _Value[_Size] + padding_x: _Value[_Size] + padding_y: _Value[_Size] + _active: StyleProps + _after: StyleProps + _any_link: StyleProps + _autofill: StyleProps + _backdrop: StyleProps + _before: StyleProps + _checked: StyleProps + _cue: StyleProps + _cue_region: StyleProps + _default: StyleProps + _disabled: StyleProps + _empty: StyleProps + _enabled: StyleProps + _file_selector_button: StyleProps + _first_child: StyleProps + _first_letter: StyleProps + _first_line: StyleProps + _first_of_type: StyleProps + _focus: StyleProps + _focus_visible: StyleProps + _focus_within: StyleProps + _fullscreen: StyleProps + _grammar_error: StyleProps + _hover: StyleProps + _in_range: StyleProps + _indeterminate: StyleProps + _invalid: StyleProps + _last_child: StyleProps + _last_of_type: StyleProps + _link: StyleProps + _marker: StyleProps + _modal: StyleProps + _only_child: StyleProps + _only_of_type: StyleProps + _open: StyleProps + _optional: StyleProps + _out_of_range: StyleProps + _placeholder: StyleProps + _placeholder_shown: StyleProps + _popover_open: StyleProps + _read_only: StyleProps + _read_write: StyleProps + _required: StyleProps + _selection: StyleProps + _spelling_error: StyleProps + _target: StyleProps + _target_text: StyleProps + _user_invalid: StyleProps + _user_valid: StyleProps + _valid: StyleProps + _visited: StyleProps + +else: + # A TypedDict of this size takes milliseconds to build, and nothing reads + # it at runtime, where a style is a plain dict. + StyleProps = dict + +CSS_PROPS: dict[str, str] = { + "accent_color": "accentColor", + "align_content": "alignContent", + "align_items": "alignItems", + "align_self": "alignSelf", + "align_tracks": "alignTracks", + "alignment_baseline": "alignmentBaseline", + "anchor_name": "anchorName", + "animation": "animation", + "animation_composition": "animationComposition", + "animation_delay": "animationDelay", + "animation_direction": "animationDirection", + "animation_duration": "animationDuration", + "animation_fill_mode": "animationFillMode", + "animation_iteration_count": "animationIterationCount", + "animation_name": "animationName", + "animation_play_state": "animationPlayState", + "animation_range": "animationRange", + "animation_range_end": "animationRangeEnd", + "animation_range_start": "animationRangeStart", + "animation_timeline": "animationTimeline", + "animation_timing_function": "animationTimingFunction", + "appearance": "appearance", + "aspect_ratio": "aspectRatio", + "azimuth": "azimuth", + "backdrop_filter": "backdropFilter", + "backface_visibility": "backfaceVisibility", + "background": "background", + "background_attachment": "backgroundAttachment", + "background_blend_mode": "backgroundBlendMode", + "background_clip": "backgroundClip", + "background_color": "backgroundColor", + "background_image": "backgroundImage", + "background_origin": "backgroundOrigin", + "background_position": "backgroundPosition", + "background_position_x": "backgroundPositionX", + "background_position_y": "backgroundPositionY", + "background_repeat": "backgroundRepeat", + "background_size": "backgroundSize", + "baseline_shift": "baselineShift", + "behavior": "behavior", + "block_size": "blockSize", + "border": "border", + "border_block": "borderBlock", + "border_block_color": "borderBlockColor", + "border_block_end": "borderBlockEnd", + "border_block_end_color": "borderBlockEndColor", + "border_block_end_style": "borderBlockEndStyle", + "border_block_end_width": "borderBlockEndWidth", + "border_block_start": "borderBlockStart", + "border_block_start_color": "borderBlockStartColor", + "border_block_start_style": "borderBlockStartStyle", + "border_block_start_width": "borderBlockStartWidth", + "border_block_style": "borderBlockStyle", + "border_block_width": "borderBlockWidth", + "border_bottom": "borderBottom", + "border_bottom_color": "borderBottomColor", + "border_bottom_left_radius": "borderBottomLeftRadius", + "border_bottom_right_radius": "borderBottomRightRadius", + "border_bottom_style": "borderBottomStyle", + "border_bottom_width": "borderBottomWidth", + "border_collapse": "borderCollapse", + "border_color": "borderColor", + "border_end_end_radius": "borderEndEndRadius", + "border_end_start_radius": "borderEndStartRadius", + "border_image": "borderImage", + "border_image_outset": "borderImageOutset", + "border_image_repeat": "borderImageRepeat", + "border_image_slice": "borderImageSlice", + "border_image_source": "borderImageSource", + "border_image_width": "borderImageWidth", + "border_inline": "borderInline", + "border_inline_color": "borderInlineColor", + "border_inline_end": "borderInlineEnd", + "border_inline_end_color": "borderInlineEndColor", + "border_inline_end_style": "borderInlineEndStyle", + "border_inline_end_width": "borderInlineEndWidth", + "border_inline_start": "borderInlineStart", + "border_inline_start_color": "borderInlineStartColor", + "border_inline_start_style": "borderInlineStartStyle", + "border_inline_start_width": "borderInlineStartWidth", + "border_inline_style": "borderInlineStyle", + "border_inline_width": "borderInlineWidth", + "border_left": "borderLeft", + "border_left_color": "borderLeftColor", + "border_left_style": "borderLeftStyle", + "border_left_width": "borderLeftWidth", + "border_radius": "borderRadius", + "border_right": "borderRight", + "border_right_color": "borderRightColor", + "border_right_style": "borderRightStyle", + "border_right_width": "borderRightWidth", + "border_spacing": "borderSpacing", + "border_start_end_radius": "borderStartEndRadius", + "border_start_start_radius": "borderStartStartRadius", + "border_style": "borderStyle", + "border_top": "borderTop", + "border_top_color": "borderTopColor", + "border_top_left_radius": "borderTopLeftRadius", + "border_top_right_radius": "borderTopRightRadius", + "border_top_style": "borderTopStyle", + "border_top_width": "borderTopWidth", + "border_width": "borderWidth", + "bottom": "bottom", + "box_align": "boxAlign", + "box_decoration_break": "boxDecorationBreak", + "box_direction": "boxDirection", + "box_flex": "boxFlex", + "box_flex_group": "boxFlexGroup", + "box_lines": "boxLines", + "box_ordinal_group": "boxOrdinalGroup", + "box_orient": "boxOrient", + "box_shadow": "boxShadow", + "box_sizing": "boxSizing", + "box_suppress": "boxSuppress", + "break_after": "breakAfter", + "break_before": "breakBefore", + "break_inside": "breakInside", + "caption_side": "captionSide", + "caret": "caret", + "caret_color": "caretColor", + "caret_shape": "caretShape", + "clear": "clear", + "clip": "clip", + "clip_path": "clipPath", + "clip_rule": "clipRule", + "color": "color", + "color_scheme": "colorScheme", + "column_count": "columnCount", + "column_fill": "columnFill", + "column_gap": "columnGap", + "column_rule": "columnRule", + "column_rule_color": "columnRuleColor", + "column_rule_style": "columnRuleStyle", + "column_rule_width": "columnRuleWidth", + "column_span": "columnSpan", + "column_width": "columnWidth", + "columns": "columns", + "contain": "contain", + "contain_intrinsic_block_size": "containIntrinsicBlockSize", + "contain_intrinsic_height": "containIntrinsicHeight", + "contain_intrinsic_inline_size": "containIntrinsicInlineSize", + "contain_intrinsic_size": "containIntrinsicSize", + "contain_intrinsic_width": "containIntrinsicWidth", + "container": "container", + "container_name": "containerName", + "container_type": "containerType", + "content": "content", + "content_visibility": "contentVisibility", + "corner_bottom_left_shape": "cornerBottomLeftShape", + "corner_bottom_right_shape": "cornerBottomRightShape", + "corner_end_end_shape": "cornerEndEndShape", + "corner_end_start_shape": "cornerEndStartShape", + "corner_shape": "cornerShape", + "corner_start_end_shape": "cornerStartEndShape", + "corner_start_start_shape": "cornerStartStartShape", + "corner_top_left_shape": "cornerTopLeftShape", + "corner_top_right_shape": "cornerTopRightShape", + "counter_increment": "counterIncrement", + "counter_reset": "counterReset", + "counter_set": "counterSet", + "cue": "cue", + "cue_after": "cueAfter", + "cue_before": "cueBefore", + "cursor": "cursor", + "direction": "direction", + "display": "display", + "display_inside": "displayInside", + "display_list": "displayList", + "display_outside": "displayOutside", + "dominant_baseline": "dominantBaseline", + "empty_cells": "emptyCells", + "end": "end", + "fill": "fill", + "fill_opacity": "fillOpacity", + "fill_rule": "fillRule", + "filter": "filter", + "flex": "flex", + "flex_basis": "flexBasis", + "flex_direction": "flexDirection", + "flex_flow": "flexFlow", + "flex_grow": "flexGrow", + "flex_shrink": "flexShrink", + "flex_wrap": "flexWrap", + "float": "float", + "font": "font", + "font_family": "fontFamily", + "font_feature_settings": "fontFeatureSettings", + "font_kerning": "fontKerning", + "font_language_override": "fontLanguageOverride", + "font_optical_sizing": "fontOpticalSizing", + "font_palette": "fontPalette", + "font_size": "fontSize", + "font_size_adjust": "fontSizeAdjust", + "font_stretch": "fontStretch", + "font_style": "fontStyle", + "font_synthesis": "fontSynthesis", + "font_synthesis_position": "fontSynthesisPosition", + "font_synthesis_small_caps": "fontSynthesisSmallCaps", + "font_synthesis_style": "fontSynthesisStyle", + "font_synthesis_weight": "fontSynthesisWeight", + "font_variant": "fontVariant", + "font_variant_alternates": "fontVariantAlternates", + "font_variant_caps": "fontVariantCaps", + "font_variant_east_asian": "fontVariantEastAsian", + "font_variant_ligatures": "fontVariantLigatures", + "font_variant_numeric": "fontVariantNumeric", + "font_variant_position": "fontVariantPosition", + "font_variation_settings": "fontVariationSettings", + "font_weight": "fontWeight", + "forced_color_adjust": "forcedColorAdjust", + "gap": "gap", + "glyph_orientation_horizontal": "glyphOrientationHorizontal", + "glyph_orientation_vertical": "glyphOrientationVertical", + "grid": "grid", + "grid_area": "gridArea", + "grid_auto_columns": "gridAutoColumns", + "grid_auto_flow": "gridAutoFlow", + "grid_auto_rows": "gridAutoRows", + "grid_column": "gridColumn", + "grid_column_end": "gridColumnEnd", + "grid_column_gap": "gridColumnGap", + "grid_column_start": "gridColumnStart", + "grid_gap": "gridGap", + "grid_row": "gridRow", + "grid_row_end": "gridRowEnd", + "grid_row_gap": "gridRowGap", + "grid_row_start": "gridRowStart", + "grid_template": "gridTemplate", + "grid_template_areas": "gridTemplateAreas", + "grid_template_columns": "gridTemplateColumns", + "grid_template_rows": "gridTemplateRows", + "hanging_punctuation": "hangingPunctuation", + "height": "height", + "hyphenate_character": "hyphenateCharacter", + "hyphenate_limit_chars": "hyphenateLimitChars", + "hyphens": "hyphens", + "image_orientation": "imageOrientation", + "image_rendering": "imageRendering", + "image_resolution": "imageResolution", + "ime_mode": "imeMode", + "initial_letter": "initialLetter", + "initial_letter_align": "initialLetterAlign", + "inline_size": "inlineSize", + "inset": "inset", + "inset_block": "insetBlock", + "inset_block_end": "insetBlockEnd", + "inset_block_start": "insetBlockStart", + "inset_inline": "insetInline", + "inset_inline_end": "insetInlineEnd", + "inset_inline_start": "insetInlineStart", + "interpolate_size": "interpolateSize", + "isolation": "isolation", + "justify_content": "justifyContent", + "justify_items": "justifyItems", + "justify_self": "justifySelf", + "justify_tracks": "justifyTracks", + "kerning": "kerning", + "left": "left", + "letter_spacing": "letterSpacing", + "line_break": "lineBreak", + "line_height": "lineHeight", + "line_height_step": "lineHeightStep", + "list_style": "listStyle", + "list_style_image": "listStyleImage", + "list_style_position": "listStylePosition", + "list_style_type": "listStyleType", + "margin": "margin", + "margin_block": "marginBlock", + "margin_block_end": "marginBlockEnd", + "margin_block_start": "marginBlockStart", + "margin_bottom": "marginBottom", + "margin_inline": "marginInline", + "margin_inline_end": "marginInlineEnd", + "margin_inline_start": "marginInlineStart", + "margin_left": "marginLeft", + "margin_right": "marginRight", + "margin_top": "marginTop", + "margin_trim": "marginTrim", + "marker": "marker", + "marker_end": "markerEnd", + "marker_mid": "markerMid", + "marker_offset": "markerOffset", + "marker_start": "markerStart", + "mask": "mask", + "mask_border": "maskBorder", + "mask_border_mode": "maskBorderMode", + "mask_border_outset": "maskBorderOutset", + "mask_border_repeat": "maskBorderRepeat", + "mask_border_slice": "maskBorderSlice", + "mask_border_source": "maskBorderSource", + "mask_border_width": "maskBorderWidth", + "mask_clip": "maskClip", + "mask_composite": "maskComposite", + "mask_image": "maskImage", + "mask_mode": "maskMode", + "mask_origin": "maskOrigin", + "mask_position": "maskPosition", + "mask_repeat": "maskRepeat", + "mask_size": "maskSize", + "mask_type": "maskType", + "masonry_auto_flow": "masonryAutoFlow", + "math_depth": "mathDepth", + "math_shift": "mathShift", + "math_style": "mathStyle", + "max_block_size": "maxBlockSize", + "max_height": "maxHeight", + "max_inline_size": "maxInlineSize", + "max_width": "maxWidth", + "min_block_size": "minBlockSize", + "min_height": "minHeight", + "min_inline_size": "minInlineSize", + "min_width": "minWidth", + "mix_blend_mode": "mixBlendMode", + "motion": "motion", + "motion_offset": "motionOffset", + "motion_path": "motionPath", + "motion_rotation": "motionRotation", + "moz_osx_font_smoothing": "MozOsxFontSmoothing", + "ms_overflow_style": "MsOverflowStyle", + "object_fit": "objectFit", + "object_position": "objectPosition", + "offset": "offset", + "offset_anchor": "offsetAnchor", + "offset_distance": "offsetDistance", + "offset_path": "offsetPath", + "offset_position": "offsetPosition", + "offset_rotate": "offsetRotate", + "opacity": "opacity", + "order": "order", + "orphans": "orphans", + "outline": "outline", + "outline_color": "outlineColor", + "outline_offset": "outlineOffset", + "outline_style": "outlineStyle", + "outline_width": "outlineWidth", + "overflow": "overflow", + "overflow_anchor": "overflowAnchor", + "overflow_block": "overflowBlock", + "overflow_block_x": "overflowBlockX", + "overflow_clip_margin": "overflowClipMargin", + "overflow_wrap": "overflowWrap", + "overflow_x": "overflowX", + "overflow_y": "overflowY", + "overscroll_behavior": "overscrollBehavior", + "overscroll_behavior_block": "overscrollBehaviorBlock", + "overscroll_behavior_inline": "overscrollBehaviorInline", + "overscroll_behavior_x": "overscrollBehaviorX", + "overscroll_behavior_y": "overscrollBehaviorY", + "padding": "padding", + "padding_block": "paddingBlock", + "padding_block_end": "paddingBlockEnd", + "padding_block_start": "paddingBlockStart", + "padding_bottom": "paddingBottom", + "padding_inline": "paddingInline", + "padding_inline_end": "paddingInlineEnd", + "padding_inline_start": "paddingInlineStart", + "padding_left": "paddingLeft", + "padding_right": "paddingRight", + "padding_top": "paddingTop", + "page": "page", + "page_break_after": "pageBreakAfter", + "page_break_before": "pageBreakBefore", + "page_break_inside": "pageBreakInside", + "paint_order": "paintOrder", + "pause": "pause", + "pause_after": "pauseAfter", + "pause_before": "pauseBefore", + "perspective": "perspective", + "perspective_origin": "perspectiveOrigin", + "place_content": "placeContent", + "place_items": "placeItems", + "place_self": "placeSelf", + "pointer_events": "pointerEvents", + "position": "position", + "position_anchor": "positionAnchor", + "position_area": "positionArea", + "position_try": "positionTry", + "position_try_fallbacks": "positionTryFallbacks", + "position_try_options": "positionTryOptions", + "position_visibility": "positionVisibility", + "print_color_adjust": "printColorAdjust", + "quotes": "quotes", + "resize": "resize", + "rest": "rest", + "rest_after": "restAfter", + "rest_before": "restBefore", + "right": "right", + "rotate": "rotate", + "row_gap": "rowGap", + "ruby_align": "rubyAlign", + "ruby_merge": "rubyMerge", + "ruby_position": "rubyPosition", + "scale": "scale", + "scroll_behavior": "scrollBehavior", + "scroll_margin": "scrollMargin", + "scroll_margin_block": "scrollMarginBlock", + "scroll_margin_block_end": "scrollMarginBlockEnd", + "scroll_margin_block_start": "scrollMarginBlockStart", + "scroll_margin_bottom": "scrollMarginBottom", + "scroll_margin_inline": "scrollMarginInline", + "scroll_margin_inline_end": "scrollMarginInlineEnd", + "scroll_margin_inline_start": "scrollMarginInlineStart", + "scroll_margin_left": "scrollMarginLeft", + "scroll_margin_right": "scrollMarginRight", + "scroll_margin_top": "scrollMarginTop", + "scroll_padding": "scrollPadding", + "scroll_padding_block": "scrollPaddingBlock", + "scroll_padding_block_end": "scrollPaddingBlockEnd", + "scroll_padding_block_start": "scrollPaddingBlockStart", + "scroll_padding_bottom": "scrollPaddingBottom", + "scroll_padding_inline": "scrollPaddingInline", + "scroll_padding_inline_end": "scrollPaddingInlineEnd", + "scroll_padding_inline_start": "scrollPaddingInlineStart", + "scroll_padding_left": "scrollPaddingLeft", + "scroll_padding_right": "scrollPaddingRight", + "scroll_padding_top": "scrollPaddingTop", + "scroll_snap_align": "scrollSnapAlign", + "scroll_snap_stop": "scrollSnapStop", + "scroll_snap_type": "scrollSnapType", + "scroll_timeline": "scrollTimeline", + "scroll_timeline_axis": "scrollTimelineAxis", + "scroll_timeline_name": "scrollTimelineName", + "scrollbar_color": "scrollbarColor", + "scrollbar_gutter": "scrollbarGutter", + "scrollbar_width": "scrollbarWidth", + "shape_image_threshold": "shapeImageThreshold", + "shape_margin": "shapeMargin", + "shape_outside": "shapeOutside", + "shape_rendering": "shapeRendering", + "speak": "speak", + "speak_as": "speakAs", + "src": "src", + "start": "start", + "stroke": "stroke", + "stroke_dasharray": "strokeDasharray", + "stroke_dashoffset": "strokeDashoffset", + "stroke_linecap": "strokeLinecap", + "stroke_linejoin": "strokeLinejoin", + "stroke_miterlimit": "strokeMiterlimit", + "stroke_opacity": "strokeOpacity", + "stroke_width": "strokeWidth", + "tab_size": "tabSize", + "table_layout": "tableLayout", + "text_align": "textAlign", + "text_align_last": "textAlignLast", + "text_anchor": "textAnchor", + "text_combine_upright": "textCombineUpright", + "text_decoration": "textDecoration", + "text_decoration_color": "textDecorationColor", + "text_decoration_line": "textDecorationLine", + "text_decoration_skip": "textDecorationSkip", + "text_decoration_skip_ink": "textDecorationSkipInk", + "text_decoration_style": "textDecorationStyle", + "text_decoration_thickness": "textDecorationThickness", + "text_emphasis": "textEmphasis", + "text_emphasis_color": "textEmphasisColor", + "text_emphasis_position": "textEmphasisPosition", + "text_emphasis_style": "textEmphasisStyle", + "text_fill_color": "textFillColor", + "text_indent": "textIndent", + "text_justify": "textJustify", + "text_orientation": "textOrientation", + "text_overflow": "textOverflow", + "text_rendering": "textRendering", + "text_shadow": "textShadow", + "text_size_adjust": "textSizeAdjust", + "text_transform": "textTransform", + "text_underline_offset": "textUnderlineOffset", + "text_underline_position": "textUnderlinePosition", + "text_wrap": "textWrap", + "timeline_scope": "timelineScope", + "top": "top", + "touch_action": "touchAction", + "transform": "transform", + "transform_box": "transformBox", + "transform_origin": "transformOrigin", + "transform_style": "transformStyle", + "transition": "transition", + "transition_delay": "transitionDelay", + "transition_duration": "transitionDuration", + "transition_property": "transitionProperty", + "transition_timing_function": "transitionTimingFunction", + "translate": "translate", + "unicode_bidi": "unicodeBidi", + "unicode_range": "unicodeRange", + "user_select": "userSelect", + "vertical_align": "verticalAlign", + "view_timeline": "viewTimeline", + "view_timeline_axis": "viewTimelineAxis", + "view_timeline_inset": "viewTimelineInset", + "view_timeline_name": "viewTimelineName", + "view_transition_name": "viewTransitionName", + "visibility": "visibility", + "voice_balance": "voiceBalance", + "voice_duration": "voiceDuration", + "voice_family": "voiceFamily", + "voice_pitch": "voicePitch", + "voice_range": "voiceRange", + "voice_rate": "voiceRate", + "voice_stress": "voiceStress", + "voice_volume": "voiceVolume", + "webkit_appearance": "WebkitAppearance", + "webkit_background_clip": "WebkitBackgroundClip", + "webkit_box_orient": "WebkitBoxOrient", + "webkit_font_smoothing": "WebkitFontSmoothing", + "webkit_line_clamp": "WebkitLineClamp", + "webkit_mask_image": "WebkitMaskImage", + "webkit_tap_highlight_color": "WebkitTapHighlightColor", + "webkit_text_fill_color": "WebkitTextFillColor", + "webkit_text_stroke_color": "WebkitTextStrokeColor", + "webkit_text_stroke_width": "WebkitTextStrokeWidth", + "white_space": "whiteSpace", + "widows": "widows", + "width": "width", + "will_change": "willChange", + "word_break": "wordBreak", + "word_spacing": "wordSpacing", + "word_wrap": "wordWrap", + "writing_mode": "writingMode", + "z_index": "zIndex", + "zoom": "zoom", +} + +PSEUDO_CLASSES: frozenset[str] = frozenset({ + "active", + "any-link", + "autofill", + "checked", + "default", + "disabled", + "empty", + "enabled", + "first-child", + "first-of-type", + "focus", + "focus-visible", + "focus-within", + "fullscreen", + "hover", + "in-range", + "indeterminate", + "invalid", + "last-child", + "last-of-type", + "link", + "modal", + "only-child", + "only-of-type", + "open", + "optional", + "out-of-range", + "placeholder-shown", + "popover-open", + "read-only", + "read-write", + "required", + "target", + "user-invalid", + "user-valid", + "valid", + "visited", +}) + +PSEUDO_ELEMENTS: frozenset[str] = frozenset({ + "-moz-progress-bar", + "-moz-range-progress", + "-moz-range-thumb", + "-moz-range-track", + "-webkit-progress-bar", + "-webkit-progress-value", + "-webkit-resizer", + "-webkit-scrollbar", + "-webkit-scrollbar-button", + "-webkit-scrollbar-corner", + "-webkit-scrollbar-thumb", + "-webkit-scrollbar-track", + "-webkit-scrollbar-track-piece", + "-webkit-search-cancel-button", + "-webkit-search-decoration", + "-webkit-search-results-button", + "-webkit-search-results-decoration", + "-webkit-slider-runnable-track", + "-webkit-slider-thumb", + "after", + "backdrop", + "before", + "cue", + "cue-region", + "file-selector-button", + "first-letter", + "first-line", + "grammar-error", + "marker", + "placeholder", + "selection", + "spelling-error", + "target-text", +}) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py b/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py new file mode 100644 index 00000000000..f9340efa21a --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py @@ -0,0 +1,1256 @@ +"""Lower the styles a user writes into the style objects StyleX compiles. + +The lowered form of a style is a mapping from a CSS property, in camelCase, to +its value. A value is one of: + +- a literal, ``str``, ``int`` or ``float``, which becomes an atomic class; +- a ``Var``, which becomes a CSS variable set inline on the element; +- a condition map such as ``{"default": v, ":hover": v, "@media ...": v}``, + whose values are again literals, Vars or condition maps. ``"default"`` is + left out when the style gives the property no unconditional value; +- ``None``, which unsets the property. It only appears as the ``"default"`` of a + condition map and in the alternatives of a state-bound variant. + +Every shorthand that can be split is expanded to its longhands, so that two +styles that set the same thing set the same keys and the last one wins. The +``border`` and ``background`` shorthands are always split, because StyleX drops +them; ``animation``, which cannot be split here, is refused. A shorthand that +is kept whole, such as ``padding`` bound to state, removes its longhands from +the styles merged before it, since StyleX lets a longhand win over a shorthand +whatever their order. + +Logical and physical longhands, such as ``marginInlineStart`` and +``marginLeft``, are different keys, and StyleX lets the physical one win. +""" + +from __future__ import annotations + +import difflib +import re +from collections.abc import Callable, Mapping +from typing import TYPE_CHECKING, Any + +from reflex_base.breakpoints import Breakpoints, breakpoint_names, breakpoints_values +from reflex_base.constants.base import REFLEX_VAR_OPENING_TAG +from reflex_base.constants.colors import COLORS, Color +from reflex_base.style import media_query +from reflex_base.utils import format +from reflex_base.utils.exceptions import ReflexError +from reflex_base.vars.base import LiteralVar, Var + +from reflex_components_ui.style._css_props import ( + CSS_PROPS, + PSEUDO_CLASSES, + PSEUDO_ELEMENTS, +) + +if TYPE_CHECKING: + from reflex_components_ui.style._css_props import StyleProps + +# A property of a lowered style: a literal, a Var, a condition map or None. +LoweredValue = Any + +# The properties one style sets, and the properties of earlier styles that a +# shorthand it could not expand replaces. +Layer = tuple[dict[str, LoweredValue], tuple[str, ...]] + +# How a style key is lowered: the camelCase property, the longhands it expands +# to, how its value is shared between them, and what it replaces when it is +# kept whole. The third item is None when every longhand takes the whole value, +# a dict from the number of values to the longhand each goes to, or a function +# that splits the value itself. A condition has no property and its text in the +# second place. +_Entry = tuple[Any, Any, Any, Any] + + +class StyleError(ReflexError, ValueError): + """A style that cannot be compiled.""" + + +# The module whose import emits the CSS of a custom property, by the first word +# of the property's name: ``var(--ruby-9)`` needs the ruby scale. The accent +# scale is an alias the theme defines, so it has no module of its own. +VAR_MODULES: dict[str, str] = { + scale: f"$/reflex-ui/colors/{scale}.stylex.js" + for scale in sorted(COLORS - {"accent"}) +} + +_VAR_NAME = re.compile(r"var\(--([a-z]+)-") +_IDENTIFIER = re.compile(r"-?[A-Za-z_][\w-]*") +_PARENTHESISED = re.compile(r"\([^()]*\)") +_COMBINATOR = re.compile(r"[\s>+~,&]") +_AT_RULES = ("@media ", "@container ", "@supports ", "@starting-style") +_MISSING: Any = object() + +# Which value goes to which longhand, by the number of values given. +_FOUR = {1: (0, 0, 0, 0), 2: (0, 1, 0, 1), 3: (0, 1, 2, 1), 4: (0, 1, 2, 3)} +_TWO = {1: (0, 0), 2: (0, 1)} + + +def _sides(prefix: str, suffix: str = "") -> tuple[str, ...]: + """Name the four physical longhands of a box shorthand. + + Args: + prefix: What comes before the side, such as ``border``. + suffix: What comes after it, such as ``Width``. + + Returns: + The top, right, bottom and left properties. + """ + return tuple([ + f"{prefix}{side}{suffix}" for side in ("Top", "Right", "Bottom", "Left") + ]) + + +def _ends(prefix: str) -> tuple[str, str]: + """Name the two logical longhands of an axis shorthand. + + Args: + prefix: The shorthand, such as ``marginInline``. + + Returns: + The start and end properties. + """ + return f"{prefix}Start", f"{prefix}End" + + +# The shorthands that are split into longhands, with their longhands in the +# order the values of the shorthand are given. +_EXPANSIONS: dict[str, tuple[tuple[str, ...], dict[int, tuple[int, ...]]]] = { + "margin": (_sides("margin"), _FOUR), + "padding": (_sides("padding"), _FOUR), + "inset": (("top", "right", "bottom", "left"), _FOUR), + "scrollMargin": (_sides("scrollMargin"), _FOUR), + "scrollPadding": (_sides("scrollPadding"), _FOUR), + "borderWidth": (_sides("border", "Width"), _FOUR), + "borderStyle": (_sides("border", "Style"), _FOUR), + "borderColor": (_sides("border", "Color"), _FOUR), + "borderRadius": ( + ( + "borderTopLeftRadius", + "borderTopRightRadius", + "borderBottomRightRadius", + "borderBottomLeftRadius", + ), + _FOUR, + ), + "gap": (("rowGap", "columnGap"), _TWO), + "overflow": (("overflowX", "overflowY"), _TWO), + "overscrollBehavior": (("overscrollBehaviorX", "overscrollBehaviorY"), _TWO), + "marginInline": (_ends("marginInline"), _TWO), + "marginBlock": (_ends("marginBlock"), _TWO), + "paddingInline": (_ends("paddingInline"), _TWO), + "paddingBlock": (_ends("paddingBlock"), _TWO), + "insetInline": (_ends("insetInline"), _TWO), + "insetBlock": (_ends("insetBlock"), _TWO), +} + +# The style keys Reflex adds to CSS: each gives its one value to every target. +_REFLEX_KEYS: dict[str, tuple[str, ...]] = { + "paddingX": ("paddingLeft", "paddingRight"), + "paddingY": ("paddingTop", "paddingBottom"), + "marginX": ("marginLeft", "marginRight"), + "marginY": ("marginTop", "marginBottom"), + "bgColor": ("backgroundColor",), +} + +# The border shorthands and the sides each one sets. StyleX compiles none of +# them, so each is split into the width, style and color of its sides. +_BORDERS: dict[str, tuple[str, ...]] = { + "border": _sides("border"), + "borderTop": ("borderTop",), + "borderRight": ("borderRight",), + "borderBottom": ("borderBottom",), + "borderLeft": ("borderLeft",), + "borderBlock": ("borderTop", "borderBottom"), + "borderBlockStart": ("borderTop",), + "borderBlockEnd": ("borderBottom",), + "borderInline": ("borderInlineStart", "borderInlineEnd"), + "borderInlineStart": ("borderInlineStart",), + "borderInlineEnd": ("borderInlineEnd",), +} + +# The shorthands StyleX does not compile and that cannot be split here, with +# what to set in their place. +_UNSUPPORTED: dict[str, str] = { + "animation": "animation_name, animation_duration and its other longhands", +} + +_BORDER_STYLES = frozenset(( + "none", + "hidden", + "dotted", + "dashed", + "solid", + "double", + "groove", + "ridge", + "inset", + "outset", +)) +_BORDER_WIDTH = re.compile( + r"thin|medium|thick|-?(?:\d+\.?\d*|\.\d+)[a-z%]*|(?:calc|min|max|clamp)\(.*\)" +) +_IMAGE = re.compile( + r"none$|(?:url|image|image-set|cross-fade|element|paint" + r"|(?:repeating-)?(?:linear|radial|conic)-gradient)\(" +) + +# What a shorthand that is kept whole replaces in the styles before it: StyleX +# lets a longhand win over a shorthand whatever their order, so the longhands +# of an earlier style have to go for the later shorthand to win. +_REPLACES: dict[str, tuple[str, ...]] = { + **{shorthand: longhands for shorthand, (longhands, _) in _EXPANSIONS.items()}, + "margin": ( + *_sides("margin"), + "marginInline", + "marginBlock", + *_ends("marginInline"), + *_ends("marginBlock"), + ), + "padding": ( + *_sides("padding"), + "paddingInline", + "paddingBlock", + *_ends("paddingInline"), + *_ends("paddingBlock"), + ), + "inset": ( + "top", + "right", + "bottom", + "left", + "insetInline", + "insetBlock", + *_ends("insetInline"), + *_ends("insetBlock"), + ), + "outline": ("outlineColor", "outlineStyle", "outlineWidth"), + "flex": ("flexGrow", "flexShrink", "flexBasis"), + "flexFlow": ("flexDirection", "flexWrap"), + "font": ( + "fontFamily", + "fontSize", + "fontStretch", + "fontStyle", + "fontVariant", + "fontWeight", + "lineHeight", + ), + "transition": ( + "transitionDelay", + "transitionDuration", + "transitionProperty", + "transitionTimingFunction", + ), + "gridArea": ( + "gridRow", + "gridColumn", + "gridRowStart", + "gridRowEnd", + "gridColumnStart", + "gridColumnEnd", + ), + "gridRow": ("gridRowStart", "gridRowEnd"), + "gridColumn": ("gridColumnStart", "gridColumnEnd"), + "gridTemplate": ("gridTemplateRows", "gridTemplateColumns", "gridTemplateAreas"), + "placeContent": ("alignContent", "justifyContent"), + "placeItems": ("alignItems", "justifyItems"), + "placeSelf": ("alignSelf", "justifySelf"), + "textDecoration": ( + "textDecorationLine", + "textDecorationStyle", + "textDecorationColor", + "textDecorationThickness", + ), + "listStyle": ("listStyleType", "listStylePosition", "listStyleImage"), + "columns": ("columnWidth", "columnCount"), + "columnRule": ("columnRuleWidth", "columnRuleStyle", "columnRuleColor"), +} + + +def _suggest(key: str, candidates: Any) -> str: + """Word the suggestion that ends an error about a misspelt key. + + Args: + key: What the user wrote. + candidates: The keys that exist. + + Returns: + A sentence naming the closest key, or nothing when none is close. + """ + close = difflib.get_close_matches(key, candidates, n=1) + return f' Did you mean "{close[0]}"?' if close else "" + + +def _condition(name: str, key: str) -> str | None: + """Read a style key as the condition a block of styles applies under. + + Args: + name: The display name of the component, for error messages. + key: The style key. + + Returns: + The condition as StyleX takes it, or None if the key is not one. + + Raises: + StyleError: If the key is a selector or at-rule that styles cannot use. + """ + first = key[:1] + if first == "_": + pseudo = format.to_kebab_case(key[1:]) + if pseudo in PSEUDO_ELEMENTS: + return f"::{pseudo}" + if pseudo in PSEUDO_CLASSES: + return f":{pseudo}" + if _IDENTIFIER.fullmatch(key): + known = [ + f"_{pseudo.replace('-', '_')}" + for pseudo in sorted(PSEUDO_CLASSES | PSEUDO_ELEMENTS) + if not pseudo.startswith("-") + ] + msg = f'{name}: unknown pseudo-class "{key}".{_suggest(key, known)}' + raise StyleError(msg) + elif first == "@": + if key.startswith(_AT_RULES): + return key + msg = ( + f'{name}: style key "{key}" is an at-rule that rx.ui styles do not ' + "support. Use @media, @container, @supports or @starting-style." + ) + raise StyleError(msg) + elif first in (":", "[", "&"): + selector = key[1:] if first == "&" else key + flat = selector + while "(" in flat: + flat, count = _PARENTHESISED.subn("", flat) + if not count: + break + if ( + selector[:1] in (":", "[") + and not _COMBINATOR.search(flat) + and (selector[0] == ":" or (flat.endswith("]") and flat.count("[") == 1)) + ): + return selector + elif _IDENTIFIER.fullmatch(key): + return None + msg = ( + f'{name}: style key "{key}" is a nested selector, which rx.ui styles do ' + "not support. Style the child component directly, or keep " + f"{name.replace('rx.ui.', 'rx.', 1)} for this element." + ) + raise StyleError(msg) + + +def _resolve(name: str, key: Any) -> _Entry: + """Work out how a style key that is not a snake_case property is lowered. + + Args: + name: The display name of the component, for error messages. + key: The style key. + + Returns: + The entry of the key, which is remembered for the next style. + + Raises: + StyleError: If the key is neither a CSS property nor a condition. + """ + if not isinstance(key, str): + msg = f"{name}: a style key must be a string, not {key!r}." + raise StyleError(msg) + if key.startswith("--"): + entry = (key, None, None, None) + else: + entry = _BY_CAMEL.get(format.to_camel_case(key)) + if entry is None: + condition = _condition(name, key) + if condition is None: + candidates = ( + _BY_CAMEL if "_" not in key and "-" not in key else _SNAKE_KEYS + ) + msg = ( + f'{name}: unknown CSS property "{key}".' + f"{_suggest(key.replace('-', '_'), candidates)}" + ) + raise StyleError(msg) + entry = (None, condition, None, None) + _ENTRIES[key] = entry + return entry + + +def _tokens(value: str) -> list[str]: + """Split a value at the white space outside its parentheses. + + Args: + value: The value as written. + + Returns: + Its parts. + """ + if "(" not in value: + return value.split() + tokens = [] + depth = start = 0 + for index, char in enumerate(value): + if char == "(": + depth += 1 + elif char == ")": + depth -= 1 + elif char.isspace() and not depth: + if index > start: + tokens.append(value[start:index]) + start = index + 1 + if len(value) > start: + tokens.append(value[start:]) + return tokens + + +def _split(value: str) -> list[str] | None: + """Split the value of a shorthand into the values of its longhands. + + Args: + value: The value as written. + + Returns: + The values, or None when the value cannot be split safely: a custom + property may hold several values, and a slash or a comma separates + groups of them. + """ + if "var(" in value or "/" in value or "," in value or "!" in value: + return None + return _tokens(value) + + +def _cannot_split(name: str, key: str, value: Any, instead: str) -> StyleError: + """Word the error for a shorthand that has to be split and cannot be. + + Args: + name: The display name of the component. + key: The style key as written. + value: Its value. + instead: The styles to set in its place. + + Returns: + The error to raise. + """ + if isinstance(value, Var): + return StyleError( + f'{name}: style "{key}" is bound to state, but rx.ui styles split ' + f"this shorthand into longhands at compile time. Bind {instead} " + "instead." + ) + return StyleError( + f'{name}: style "{key}" has the value "{value}", which rx.ui styles ' + f"cannot split into longhands. Set {instead} instead." + ) + + +def _border(sides: tuple[str, ...]) -> Callable[[str, str, Any], list[tuple[str, Any]]]: + """Make the expansion of a border shorthand. + + Args: + sides: The sides the shorthand sets, such as ``borderTop``. + + Returns: + A function that splits a value into the width, style and color of + every side. A part the value leaves out gets its initial value, as it + does in CSS, so that the shorthand replaces what an earlier style set. + """ + instead = "its width, style and color" + + def expand(name: str, key: str, value: Any) -> list[tuple[str, Any]]: + """Split one value of the shorthand. + + Args: + name: The display name of the component, for error messages. + key: The style key as written, for error messages. + value: The value as written. + + Returns: + The longhands and their values. + + Raises: + StyleError: If the value is bound to state or its parts cannot be + told apart. + """ + width = style = color = None + if value.__class__ is str: + for token in _tokens(value): + lowered = token.lower() + if style is None and lowered in _BORDER_STYLES: + style = token + elif width is None and _BORDER_WIDTH.fullmatch(lowered): + width = token + elif ( + color is None + and "!" not in token + and lowered not in _BORDER_STYLES + and not _BORDER_WIDTH.fullmatch(lowered) + ): + color = token + else: + raise _cannot_split(name, key, value, instead) + elif value is None: + return [ + (f"{side}{part}", None) + for side in sides + for part in ("Width", "Style", "Color") + ] + elif isinstance(value, Var): + raise _cannot_split(name, key, value, instead) + else: + width = value + parts = ( + ("Width", "medium" if width is None else width), + ("Style", style or "none"), + ("Color", color or "currentcolor"), + ) + return [(f"{side}{part}", item) for side in sides for part, item in parts] + + return expand + + +def _background(name: str, key: str, value: Any) -> list[tuple[str, Any]]: + """Split the background shorthand, which StyleX does not compile. + + Args: + name: The display name of the component, for error messages. + key: The style key as written, for error messages. + value: A color or an image. A custom property is read as a color. + + Returns: + The color and the image, one of them reset as the shorthand does. + + Raises: + StyleError: If the value is bound to state or holds more than one of + the two. + """ + if value is None: + return [("backgroundColor", None), ("backgroundImage", None)] + if value.__class__ is str: + tokens = _tokens(value) + if len(tokens) == 1 and "!" not in value: + if _IMAGE.match(value.strip().lower()): + return [("backgroundColor", "transparent"), ("backgroundImage", value)] + return [("backgroundColor", value), ("backgroundImage", "none")] + raise _cannot_split( + name, + key, + value, + "background_color, background_image and its other longhands", + ) + + +def _unsupported(instead: str) -> Callable[[str, str, Any], list[tuple[str, Any]]]: + """Make the refusal of a shorthand that cannot be compiled or split. + + Args: + instead: The styles to set in its place. + + Returns: + A function that raises for any value. + """ + + def expand(name: str, key: str, value: Any) -> list[tuple[str, Any]]: + """Refuse the shorthand. + + Args: + name: The display name of the component. + key: The style key as written. + value: The value as written. + + Raises: + StyleError: Always. + """ + msg = ( + f'{name}: style "{key}" is a shorthand that rx.ui styles do not ' + f"support. Set {instead} instead." + ) + raise StyleError(msg) + + return expand + + +def _entries() -> tuple[dict[str, _Entry], dict[str, _Entry]]: + """Build the tables of style keys from the generated CSS properties. + + Returns: + How each key is lowered, by the snake_case key a user writes and by + the camelCase name of the property. + """ + by_key: dict[str, _Entry] = {} + by_camel: dict[str, _Entry] = {} + custom = { + "background": _background, + **{camel: _border(sides) for camel, sides in _BORDERS.items()}, + **{camel: _unsupported(instead) for camel, instead in _UNSUPPORTED.items()}, + } + for key, camel in CSS_PROPS.items(): + if camel in custom: + entry = (camel, (), custom[camel], None) + elif camel in _EXPANSIONS: + entry = (camel, *_EXPANSIONS[camel], _REPLACES[camel]) + else: + entry = (camel, None, None, _REPLACES.get(camel)) + by_key[key] = by_camel[camel] = entry + for camel, targets in _REFLEX_KEYS.items(): + entry = (camel, targets, None, None) + by_key[format.to_snake_case(camel)] = by_camel[camel] = entry + by_key["bg"] = by_camel["bg"] = by_camel["background"] + return by_key, by_camel + + +# How every style key seen so far is lowered. It starts with the snake_case +# keys and learns the other spellings and the conditions as styles use them. +_ENTRIES, _BY_CAMEL = _entries() +# The snake_case keys, to suggest one for a key that is misspelt. +_SNAKE_KEYS = tuple(_ENTRIES) + + +def _put( + out: dict[str, LoweredValue], prop: str, path: tuple[str, ...], value: Any +) -> None: + """Give a property its value under the conditions of a path. + + Args: + out: The lowered style being built. + prop: The camelCase property. + path: The conditions the value applies under, outermost first. + value: The lowered value. + """ + node = out.get(prop, _MISSING) + if not path: + if node.__class__ is dict and "default" not in node: + out[prop] = {"default": value, **node} + else: + out[prop] = value + return + if node.__class__ is not dict: + node = out[prop] = {} if node is _MISSING else {"default": node} + for condition in path[:-1]: + child = node.get(condition, _MISSING) + if child.__class__ is not dict: + child = node[condition] = {} if child is _MISSING else {"default": child} + node = child + last = path[-1] + child: Any = node.get(last) + if child.__class__ is dict and "default" not in child: + node[last] = {"default": value, **child} + else: + node[last] = value + + +def _leaf( + name: str, + key: str, + entry: _Entry, + value: Any, + path: tuple[str, ...], + out: dict[str, LoweredValue], + replaced: list[str], +) -> None: + """Lower one literal or Var, expanding the shorthand it is given to. + + Args: + name: The display name of the component, for error messages. + key: The style key as written, for error messages. + entry: How the style key is lowered. + value: A literal, a Var or None. + path: The conditions the value applies under. + out: The lowered style being built. + replaced: The properties of earlier styles this style replaces. + """ + camel, targets, spread, replaces = entry + if targets is not None: + if spread is None: + for target in targets: + _put(out, target, path, value) + return + if spread.__class__ is not dict: + for target, item in spread(name, key, value): + _put(out, target, path, item) + return + if value.__class__ is str: + tokens = _split(value) + if tokens: + order = spread.get(len(tokens)) + if order is not None: + for target, index in zip(targets, order, strict=True): + _put(out, target, path, tokens[index]) + return + elif not isinstance(value, Var): + for target in targets: + _put(out, target, path, value) + return + _put(out, camel, path, value) + if replaces is not None and not path: + replaced.extend(replaces) + + +def _value( + name: str, + key: str, + entry: _Entry, + value: Any, + path: tuple[str, ...], + out: dict[str, LoweredValue], + replaced: list[str], +) -> None: + """Lower the value of one CSS property. + + Args: + name: The display name of the component, for error messages. + key: The style key as written, for error messages. + entry: How the style key is lowered. + value: The value as written. + path: The conditions the value applies under. + out: The lowered style being built. + replaced: The properties of earlier styles this style replaces. + + Raises: + StyleError: If the value is not one a style can take. + """ + cls = value.__class__ + if cls is str: + if REFLEX_VAR_OPENING_TAG in value: + value = LiteralVar.create(value) + elif entry[1] is None: + _put(out, entry[0], path, value) + if entry[3] is not None and not path: + replaced.extend(entry[3]) + return + elif cls is int or cls is float or value is None: + pass + elif isinstance(value, Color): + if ( + value.color.__class__ is not str + or value.shade.__class__ is not int + or value.alpha.__class__ is not bool + ): + _leaf(name, key, entry, LiteralVar.create(value), path, out, replaced) + return + value = f"{value}" + if entry[2].__class__ is dict: + # A color is one value, so every longhand takes its custom property. + for target in entry[1]: + _put(out, target, path, value) + return + elif isinstance(value, Mapping): + named = isinstance(value, Breakpoints) + for condition, item in value.items(): + if condition == "default" or condition == "initial": + inner = path + elif condition in breakpoint_names: + width = breakpoints_values[breakpoint_names.index(condition)] + inner = (*path, media_query(width)) + else: + entry_ = _ENTRIES.get(condition) + text = ( + entry_[1] + if entry_ is not None and entry_[0] is None + else _value_condition(name, key, condition, named) + ) + inner = (*path, text) + _value(name, key, entry, item, inner, out, replaced) + return + elif cls is list or cls is tuple: + if len(value) > len(breakpoints_values) + 1: + msg = ( + f'{name}: style "{key}" has {len(value)} responsive values, but ' + f"there are only {len(breakpoints_values) + 1} breakpoints." + ) + raise StyleError(msg) + for index, item in enumerate(value): + if item is not None: + inner = ( + (*path, media_query(breakpoints_values[index - 1])) + if index + else path + ) + _value(name, key, entry, item, inner, out, replaced) + return + elif not isinstance(value, Var): + msg = ( + f'{name}: style "{key}" cannot take a value of type ' + f"{cls.__name__}. Use a string, a number, a Var, a responsive list " + "or a dict of conditions." + ) + raise StyleError(msg) + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + literal = value._var_value + if literal.__class__ in (str, int, float) or isinstance(literal, Color): + _value(name, key, entry, literal, path, out, replaced) + return + _leaf(name, key, entry, value, path, out, replaced) + + +def _value_condition(name: str, key: str, condition: Any, named: bool) -> str: + """Read a key of a property's value as the condition its item applies under. + + Args: + name: The display name of the component, for error messages. + key: The style key the value belongs to, for error messages. + condition: The key inside the value. + named: Whether the value is an ``rx.breakpoints``, whose other keys + are the widths of custom breakpoints. + + Returns: + The condition as StyleX takes it. + + Raises: + StyleError: If the key is not a condition. + """ + if not isinstance(condition, str): + text = None + elif named and condition[:1] not in (":", "@", "[", "_", "&"): + return media_query(condition) + else: + text = _condition(name, condition) + if text is None: + msg = ( + f'{name}: style "{key}" is given a value under "{condition}", which ' + 'is not a condition. Use "default", a pseudo-class such as ' + '":hover", an at-rule such as "@media (min-width: 48em)" or the ' + "name of a breakpoint." + ) + raise StyleError(msg) + _ENTRIES[condition] = (None, text, None, None) + return text + + +def _block( + name: str, + style: Mapping[str, Any], + path: tuple[str, ...], + out: dict[str, LoweredValue], + replaced: list[str], +) -> None: + """Lower a dict of styles into the style being built. + + Args: + name: The display name of the component, for error messages. + style: The styles as written. + path: The conditions the styles apply under. + out: The lowered style being built. + replaced: The properties of earlier styles this style replaces. + + Raises: + StyleError: If a key or a value is not one a style can take. + """ + entries = _ENTRIES + for key, value in style.items(): + entry = entries.get(key) or _resolve(name, key) + if entry[0] is not None: + _value(name, key, entry, value, path, out, replaced) + elif isinstance(value, Var): + msg = ( + f'{name}: style key "{key}" is bound to state, but the styles ' + "under a condition are compiled ahead of time. Bind the values " + "of its properties instead." + ) + raise StyleError(msg) + elif not isinstance(value, Mapping) or isinstance(value, Breakpoints): + msg = ( + f'{name}: style key "{key}" is a condition, so its value must ' + f"be a dict of styles, not {type(value).__name__}." + ) + raise StyleError(msg) + else: + _block(name, value, (*path, entry[1]), out, replaced) + + +def _space(value: Any) -> Any: + """Read a step of the space scale. + + Args: + value: A step from "0" to "9", negative for a margin, or any CSS value. + + Returns: + The custom property of the step, or the value as given. + """ + if value.__class__ is str: + negative = value[:1] == "-" + step = value[1:] if negative else value + if len(step) == 1 and step.isdigit(): + if step == "0": + return "0" + return ( + f"calc(-1 * var(--space-{step}))" + if negative + else f"var(--space-{step})" + ) + return value + + +def _tracks(value: Any) -> Any: + """Read a number of grid tracks. + + Args: + value: A count such as "3", or any CSS value. + + Returns: + That many tracks of equal size, or the value as given. + """ + if value.__class__ is str and value.isdigit(): + return f"repeat({value}, minmax(0, 1fr))" + return value + + +def _keywords(names: dict[str, str]) -> Callable[[Any], Any]: + """Make the reading of a layout prop whose keywords are not the ones of CSS. + + Args: + names: The CSS keyword of each keyword of the prop that differs. + + Returns: + A function that reads one value of the prop. + """ + return lambda value: names.get(value, value) + + +_ALIGN = {"start": "flex-start", "end": "flex-end"} + +# The layout props: the style each one stands for, the longhands it sets, and +# how its values are read. A prop with no reading takes CSS values as they are. +_LAYOUT: dict[str, tuple[str, tuple[str, ...], Callable[[Any], Any] | None]] = { + "p": ("padding", _sides("padding"), _space), + "px": ("padding_x", ("paddingLeft", "paddingRight"), _space), + "py": ("padding_y", ("paddingTop", "paddingBottom"), _space), + "pt": ("padding_top", ("paddingTop",), _space), + "pr": ("padding_right", ("paddingRight",), _space), + "pb": ("padding_bottom", ("paddingBottom",), _space), + "pl": ("padding_left", ("paddingLeft",), _space), + "m": ("margin", _sides("margin"), _space), + "mx": ("margin_x", ("marginLeft", "marginRight"), _space), + "my": ("margin_y", ("marginTop", "marginBottom"), _space), + "mt": ("margin_top", ("marginTop",), _space), + "mr": ("margin_right", ("marginRight",), _space), + "mb": ("margin_bottom", ("marginBottom",), _space), + "ml": ("margin_left", ("marginLeft",), _space), + "gap": ("gap", ("rowGap", "columnGap"), _space), + "spacing": ("gap", ("rowGap", "columnGap"), _space), + "gap_x": ("column_gap", ("columnGap",), _space), + "gap_y": ("row_gap", ("rowGap",), _space), + "columns": ("grid_template_columns", ("gridTemplateColumns",), _tracks), + "rows": ("grid_template_rows", ("gridTemplateRows",), _tracks), + "direction": ("flex_direction", ("flexDirection",), None), + "wrap": ("flex_wrap", ("flexWrap",), None), + "align": ("align_items", ("alignItems",), _keywords(_ALIGN)), + "justify": ( + "justify_content", + ("justifyContent",), + _keywords({**_ALIGN, "between": "space-between"}), + ), + "flow": ( + "grid_auto_flow", + ("gridAutoFlow",), + _keywords({"row-dense": "row dense", "column-dense": "column dense"}), + ), +} + +# The props that set layout styles through a scale rather than a CSS value. +LAYOUT_PROPS: frozenset[str] = frozenset(_LAYOUT) + + +def _read_layout(name: str, prop: str, value: Any, read: Callable[[Any], Any]) -> Any: + """Read the values of a layout prop, whatever their breakpoints. + + Args: + name: The display name of the component, for error messages. + prop: The layout prop. + value: Its value: one, a list of them or a dict of them. + read: How one value is read. + + Returns: + The same shape, holding CSS values. + + Raises: + StyleError: If a value is bound to state. + """ + if value.__class__ is str: + return read(value) + if isinstance(value, Mapping): + read_items = { + key: _read_layout(name, prop, item, read) for key, item in value.items() + } + return Breakpoints(read_items) if isinstance(value, Breakpoints) else read_items + if isinstance(value, (list, tuple)): + return [_read_layout(name, prop, item, read) for item in value] + if isinstance(value, Var): + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + return _read_layout(name, prop, value._var_value, read) + msg = ( + f'{name}: layout prop "{prop}" is bound to state, but its values ' + f'are read at compile time. Bind the "{_LAYOUT[prop][0]}" style ' + "instead, which takes any CSS value." + ) + raise StyleError(msg) + return value + + +def lower_layer( + name: str, + style: Mapping[str, Any] | None = None, + layout: Mapping[str, Any] | None = None, +) -> Layer: + """Lower one style, keeping what merging it over another style needs. + + Args: + name: The display name of the component, for error messages. + style: The styles as written. + layout: Layout props, lowered before the styles. + + Returns: + The lowered properties, which may hold None for a property the style + unsets, and the properties of earlier styles it replaces. + + Raises: + StyleError: If the style or a layout prop cannot be compiled. + """ + out: dict[str, LoweredValue] = {} + replaced: list[str] = [] + if layout: + for prop, value in layout.items(): + if value is None: + continue + try: + key, targets, read = _LAYOUT[prop] + except KeyError: + msg = ( + f'{name}: unknown layout prop "{prop}".' + f"{_suggest(prop, sorted(_LAYOUT))}" + ) + raise StyleError(msg) from None + if read is not None: + value = _read_layout(name, prop, value, read) + _value(name, key, (key, targets, None, None), value, (), out, replaced) + if style: + _block(name, style, (), out, replaced) + return out, tuple(replaced) + + +def _overlay(old: Any, new: dict[str, Any]) -> dict[str, Any]: + """Add the conditions of a later style to the value of an earlier one. + + Args: + old: The earlier value of the property. + new: A condition map without a default. + + Returns: + A condition map holding both. + """ + merged = dict(old) if old.__class__ is dict else {"default": old} + for condition, value in new.items(): + if value.__class__ is dict and "default" not in value and condition in merged: + merged[condition] = _overlay(merged[condition], value) + else: + merged[condition] = value + return merged + + +def apply_layer(target: dict[str, LoweredValue], layer: Layer) -> None: + """Merge a later style over the properties merged so far, in place. + + A property the later style sets replaces the earlier value, conditions + included. A property it only sets under a condition, as a ``_hover`` block + does, keeps the earlier value everywhere else. + + Args: + target: The properties merged so far. + layer: The later style. + """ + props, replaced = layer + for prop in replaced: + target.pop(prop, None) + for prop, value in props.items(): + if value.__class__ is dict and "default" not in value: + old = target.get(prop) + target[prop] = value if old is None else _overlay(old, value) + else: + target[prop] = value + + +def freeze(value: LoweredValue) -> Any: + """Turn a lowered value into one that can be compared and hashed. + + A Var builds an expression when compared, so it stands in as its identity. + + Args: + value: The lowered value. + + Returns: + The value, with every dict and Var inside it replaced. + """ + cls = value.__class__ + if cls is str or cls is int or cls is float or value is None: + return value + if cls is dict: + return tuple([(key, freeze(item)) for key, item in value.items()]) + if cls is Lowered: + return value.key + return (Var, value._hash_key()) + + +def _modules(value: LoweredValue, found: set[str]) -> None: + """Collect the modules that define the custom properties a value uses. + + Args: + value: The lowered value. + found: The modules found so far, added to in place. + """ + if value.__class__ is str: + if "var(--" in value: + for match in _VAR_NAME.finditer(value): + module = VAR_MODULES.get(match[1]) + if module is not None: + found.add(module) + elif value.__class__ is dict: + for item in value.values(): + _modules(item, found) + + +class Lowered: + """A style in the form StyleX compiles. + + Two of them are equal, and hash the same, when they would compile to the + same declaration, so one can be the key that declarations are shared by. + The order of the properties does not count. + + Attributes: + style: The lowered value of each camelCase CSS property. Shared with + every equal result: read it, never change it. + imports: The modules to import so that the CSS of the custom + properties the style uses is emitted, sorted. + inline: A Var holding a whole dict of styles, to be set as the inline + ``style`` of the element after the compiled ones. + """ + + __slots__ = ("_key", "imports", "inline", "style") + + def __init__( + self, + style: dict[str, LoweredValue], + imports: tuple[str, ...] = (), + inline: Var | None = None, + ): + """Hold a lowered style. + + Args: + style: The lowered value of each camelCase CSS property. + imports: The modules the style needs, sorted. + inline: A Var holding a whole dict of styles. + """ + self.style = style + self.imports = imports + self.inline = inline + self._key = None + + @property + def key(self) -> tuple[Any, ...]: + """What the style is compared and hashed by. + + Returns: + A hashable tuple that holds no Var. + """ + key = self._key + if key is None: + key = self._key = ( + tuple(sorted([(prop, freeze(v)) for prop, v in self.style.items()])), + self.imports, + None if self.inline is None else self.inline._hash_key(), + ) + return key + + def __eq__(self, other: object) -> bool: + """Compare with another lowered style. + + Args: + other: What to compare with. + + Returns: + Whether both would compile to the same declaration. + """ + return isinstance(other, Lowered) and self.key == other.key + + def __hash__(self) -> int: + """Hash consistently with equality. + + Returns: + The hash of the key. + """ + return hash(self.key) + + def __repr__(self) -> str: + """Show what the style holds. + + Returns: + The constructor call that would rebuild it. + """ + return f"Lowered({self.style!r}, {self.imports!r}, {self.inline!r})" + + +EMPTY = Lowered({}) + + +def finish( + props: dict[str, LoweredValue], inline: Var | None = None, unset: bool = False +) -> Lowered: + """Wrap merged properties as a lowered style. + + Args: + props: The merged properties, which the result takes over. + inline: A Var holding a whole dict of styles. + unset: Whether to keep the properties set to None. They are dropped + otherwise, there being nothing before the style for them to unset. + + Returns: + The lowered style, with the modules its values need. + """ + found: set[str] = set() + dropped = False + for value in props.values(): + cls = value.__class__ + if cls is str: + if "var(--" in value: + _modules(value, found) + elif cls is dict: + _modules(value, found) + elif value is None: + dropped = True + if dropped and not unset: + props = {prop: value for prop, value in props.items() if value is not None} + if not props and inline is None: + return EMPTY + return Lowered(props, tuple(sorted(found)) if found else (), inline) + + +def lower( + name: str, + style: StyleProps | Mapping[str, Any] | Var | None = None, + layout: Mapping[str, Any] | None = None, +) -> Lowered: + """Lower the style of one element into the form StyleX compiles. + + Args: + name: The display name of the component, such as ``"rx.ui.card"``, + which starts every error message. + style: The styles as a user writes them, or a Var holding a whole dict + of them, which becomes the inline style of the element. + layout: Layout props such as ``p`` and ``gap``, lowered to styles that + the ones in ``style`` are merged over. + + Returns: + The lowered style. + + Raises: + StyleError: If a key, a value or a layout prop cannot be compiled. + """ + if isinstance(style, Var): + if not layout: + return Lowered({}, (), style) + return finish(lower_layer(name, None, layout)[0], style) + if not layout: + return finish(lower_layer(name, style)[0]) + props, _ = lower_layer(name, None, layout) + apply_layer(props, lower_layer(name, style)) + return finish(props) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/merge.py b/packages/reflex-components-ui/src/reflex_components_ui/style/merge.py new file mode 100644 index 00000000000..7804d61eb30 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/merge.py @@ -0,0 +1,605 @@ +"""Merge the style table of a component with the style of one element. + +The styles are merged by property and the last one wins: the base of the +table, each variant the props of the element select, the compound styles that +match, the layout props and then the style the user wrote. The result is what +the compiler emits as StyleX declarations, so nothing has to be overridden in +the browser. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from itertools import product +from typing import TYPE_CHECKING, Any, TypedDict + +from reflex_base.breakpoints import breakpoints_values +from reflex_base.vars.base import LiteralVar, Var + +from reflex_components_ui.style.lower import ( + Layer, + Lowered, + LoweredValue, + StyleError, + apply_layer, + finish, + freeze, + lower_layer, +) + +if TYPE_CHECKING: + from reflex_components_ui.style._css_props import StyleProps + + +class CompoundStyle(TypedDict): + """Styles for an element whose props have a combination of values.""" + + props: dict[str, str] + style: StyleProps + + +class ComponentStyles(TypedDict, total=False): + """The look of a component: a table of styles selected by its props. + + A variant is keyed by the name of a prop and then by its values, written + as strings: ``"true"`` and ``"false"`` for a boolean prop. + """ + + base: StyleProps + variants: dict[str, dict[str, StyleProps]] + compound: list[CompoundStyle] + parts: dict[str, ComponentStyles] + + +_TABLE_KEYS = frozenset(("base", "variants", "compound", "parts")) +_NO_PROPS: Mapping[str, Any] = {} + + +class Alternatives: + """The styles of the props of an element that are bound to state. + + The compiler emits one declaration per entry of ``values`` and the page + picks one at runtime, by the values the Vars then have, applying it after + the style of the element. Each entry holds only what differs from that + style, with None for a property to unset. Props that set the same + property, or that a compound style combines, are grouped so that every + group can be picked independently of the others. + + Attributes: + props: The names of the props. + vars: The Var each prop is bound to. + values: The style for each combination of values of the props that + changes anything, keyed by the values in the order of ``props``. + """ + + __slots__ = ("_key", "props", "values", "vars") + + def __init__( + self, + props: tuple[str, ...], + vars: tuple[Var, ...], + values: dict[tuple[str, ...], Lowered], + ): + """Hold the alternatives of a group of props. + + Args: + props: The names of the props. + vars: The Var each prop is bound to. + values: The style for each combination of their values. + """ + self.props = props + self.vars = vars + self.values = values + self._key = None + + @property + def key(self) -> tuple[Any, ...]: + """What the alternatives are compared and hashed by. + + Returns: + A hashable tuple that holds no Var. + """ + key = self._key + if key is None: + key = self._key = ( + self.props, + tuple([var._hash_key() for var in self.vars]), + tuple([(combo, style.key) for combo, style in self.values.items()]), + ) + return key + + def __eq__(self, other: object) -> bool: + """Compare with other alternatives. + + Args: + other: What to compare with. + + Returns: + Whether both hold the same styles for the same Vars. + """ + return isinstance(other, Alternatives) and self.key == other.key + + def __hash__(self) -> int: + """Hash consistently with equality. + + Returns: + The hash of the key. + """ + return hash(self.key) + + def __repr__(self) -> str: + """Show what the alternatives hold. + + Returns: + The constructor call that would rebuild them. + """ + return f"Alternatives({self.props!r}, {self.vars!r}, {self.values!r})" + + +class Merged: + """The styles of one element of a component and of its inner elements. + + Two of them are equal, and hash the same, when they would compile to the + same declarations. + + Attributes: + style: The style of the element, with every prop that has a value at + compile time resolved. + dynamic: The styles of the props that are bound to state, in the order + they apply after ``style``. + parts: The merged styles of each inner element, by its name. + """ + + __slots__ = ("_key", "dynamic", "parts", "style") + + def __init__( + self, + style: Lowered, + dynamic: tuple[Alternatives, ...] = (), + parts: Mapping[str, Merged] = _NO_PROPS, + ): + """Hold the merged styles of an element. + + Args: + style: The style of the element. + dynamic: The styles of the props that are bound to state. + parts: The merged styles of each inner element. + """ + self.style = style + self.dynamic = dynamic + self.parts = parts + self._key = None + + @property + def key(self) -> tuple[Any, ...]: + """What the merged styles are compared and hashed by. + + Returns: + A hashable tuple that holds no Var. + """ + key = self._key + if key is None: + key = self._key = ( + self.style.key, + tuple([alternatives.key for alternatives in self.dynamic]), + tuple([(part, merged.key) for part, merged in self.parts.items()]), + ) + return key + + def __eq__(self, other: object) -> bool: + """Compare with other merged styles. + + Args: + other: What to compare with. + + Returns: + Whether both would compile to the same declarations. + """ + return isinstance(other, Merged) and self.key == other.key + + def __hash__(self) -> int: + """Hash consistently with equality. + + Returns: + The hash of the key. + """ + return hash(self.key) + + def __repr__(self) -> str: + """Show what the merged styles hold. + + Returns: + The constructor call that would rebuild them. + """ + return f"Merged({self.style!r}, {self.dynamic!r}, {dict(self.parts)!r})" + + +class _Table: + """A style table with every style in it lowered once. + + Attributes: + source: The table as written, kept so that its id stays its own. + breakpoints: The breakpoints the table was lowered with. + consulted: The props the table or one of its parts reads, in the order + their values are keyed by. + base: The lowered base style. + variants: For each variant, the position of its prop in ``consulted`` + and the lowered style of each value. + compound: For each compound style, the positions and values of the + props it needs and its lowered style. + parts: The table of each inner element. + resolved: The properties the table gives for each choice of values. + merged: The result for each choice of values without a user style. + """ + + __slots__ = ( + "base", + "breakpoints", + "compound", + "consulted", + "merged", + "parts", + "resolved", + "source", + "variants", + ) + + def __init__(self, name: str, source: Mapping[str, Any]): + """Lower a style table. + + Args: + name: The display name of the component, for error messages. + source: The table as written. + + Raises: + StyleError: If the table has a key that is not part of one, or a + style in it cannot be compiled. + """ + for key in source: + if key not in _TABLE_KEYS: + msg = ( + f'{name}: unknown key "{key}" in a style table. Use "base", ' + '"variants", "compound" or "parts".' + ) + raise StyleError(msg) + self.source = source + self.breakpoints = list(breakpoints_values) + self.base = lower_layer(name, source.get("base")) + self.parts = tuple([ + (part, _Table(name, table)) + for part, table in source.get("parts", _NO_PROPS).items() + ]) + variants = source.get("variants", _NO_PROPS) + compound = source.get("compound", ()) + positions: dict[str, int] = dict.fromkeys(variants, 0) + for item in compound: + positions.update(dict.fromkeys(item["props"], 0)) + for _, part in self.parts: + positions.update(dict.fromkeys(part.consulted, 0)) + positions = {prop: position for position, prop in enumerate(positions)} + self.consulted = tuple(positions) + self.variants: tuple[tuple[int, dict[str | None, Layer]], ...] = tuple([ + ( + positions[prop], + {value: lower_layer(name, style) for value, style in values.items()}, + ) + for prop, values in variants.items() + ]) + self.compound: tuple[tuple[tuple[tuple[int, str], ...], Layer], ...] = tuple([ + ( + tuple([ + (positions[prop], value) for prop, value in item["props"].items() + ]), + lower_layer(name, item["style"]), + ) + for item in compound + ]) + self.resolved: dict[tuple[str | None, ...], dict[str, LoweredValue]] = {} + self.merged: dict[tuple[str | None, ...], Merged] = {} + + def resolve(self, keys: tuple[str | None, ...]) -> dict[str, LoweredValue]: + """Merge the styles of the table that a choice of prop values selects. + + Args: + keys: The value of each consulted prop, or None for one that is + not set. + + Returns: + The merged properties, shared by every element with these values. + """ + props = self.resolved.get(keys) + if props is None: + props = dict(self.base[0]) + for position, values in self.variants: + layer = values.get(keys[position]) + if layer is not None: + apply_layer(props, layer) + for needed, layer in self.compound: + for position, value in needed: + if keys[position] != value: + break + else: + apply_layer(props, layer) + self.resolved[keys] = props + return props + + +# The lowered form of every style table merged so far, by the id of the table. +_TABLES: dict[int, _Table] = {} + + +def _table(name: str, styles: Mapping[str, Any]) -> _Table: + """Find the lowered form of a style table, lowering it the first time. + + Args: + name: The display name of the component, for error messages. + styles: The style table. + + Returns: + The lowered table. + """ + table = _TABLES.get(id(styles)) + if ( + table is None + or table.source is not styles + or table.breakpoints != breakpoints_values + ): + table = _TABLES[id(styles)] = _Table(name, styles) + return table + + +def _variant_key(value: Any) -> Any: + """Read the value of a prop as the key its variant is listed under. + + Args: + value: The value of the prop, which is neither a string nor None. + + Returns: + The key, or the Var itself for a prop that is bound to state. + """ + if value is True: + return "true" + if value is False: + return "false" + if isinstance(value, Var): + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + literal = value._var_value + return literal if literal.__class__ is str else _variant_key(literal) + return value + return str(value) + + +def _difference( + static: dict[str, LoweredValue], full: dict[str, LoweredValue] +) -> dict[str, LoweredValue]: + """Find what a style changes in another one. + + Args: + static: The style of the element without a prop. + full: Its style with a value for the prop. + + Returns: + The properties whose value differs, with None for one that goes away. + """ + changed = { + prop: value + for prop, value in full.items() + if prop not in static or freeze(static[prop]) != freeze(value) + } + for prop in static: + if prop not in full: + changed[prop] = None + return changed + + +def _merge_dynamic( + table: _Table, + keys: tuple[str | None, ...], + bound: dict[int, Var], + layers: list[Layer], +) -> tuple[dict[str, LoweredValue], tuple[Alternatives, ...]]: + """Merge the styles of an element some of whose props are bound to state. + + Args: + table: The lowered style table. + keys: The value of each consulted prop, None for the bound ones. + bound: The Var of each bound prop, by its position in ``keys``. + layers: The lowered layout props and user style. + + Returns: + The properties of the element without the bound props, and the + alternatives that the values of the bound props select. + """ + + def merged_with(assigned: dict[int, str]) -> dict[str, LoweredValue]: + """Merge the styles of the element for a choice of the bound props. + + Args: + assigned: The value of each bound prop that has one, by position. + + Returns: + The merged properties. + """ + chosen = list(keys) + for position, value in assigned.items(): + chosen[position] = value + props = dict(table.resolve(tuple(chosen))) + for layer in layers: + apply_layer(props, layer) + return props + + static = merged_with({}) + domains: dict[int, dict[Any, None]] = {position: {} for position in bound} + for position, values in table.variants: + if position in bound: + domains[position].update(dict.fromkeys(values)) + # Each bound prop starts in a group of its own. + group_of = {position: [position] for position in bound} + for needed, _ in table.compound: + together = [position for position, _ in needed if position in bound] + for position, value in needed: + if position in bound: + domains[position][value] = None + _join(group_of, together) + + changes: dict[int, dict[str, dict[str, LoweredValue]]] = {} + for position, domain in domains.items(): + changes[position] = { + value: _difference(static, merged_with({position: value})) + for value in domain + } + touched: dict[str, int] = {} + for position, by_value in changes.items(): + for change in by_value.values(): + for prop in change: + _join(group_of, [touched.setdefault(prop, position), position]) + + alternatives = [] + for position in bound: + group = group_of[position] + if group[0] != position: + continue + if len(group) == 1: + values = { + (value,): finish(change, unset=True) + for value, change in changes[position].items() + if change + } + else: + values = {} + for combo in product(*[domains[member] for member in group]): + change = _difference( + static, merged_with(dict(zip(group, combo, strict=True))) + ) + if change: + values[combo] = finish(change, unset=True) + if values: + alternatives.append( + Alternatives( + tuple([table.consulted[member] for member in group]), + tuple([bound[member] for member in group]), + values, + ) + ) + return static, tuple(alternatives) + + +def _join(group_of: dict[int, list[int]], members: list[int]) -> None: + """Put props that depend on each other in one group. + + Args: + group_of: The group of each prop, shared by its members and changed in + place. + members: Props that have to be in the same group. + """ + first = group_of[members[0]] if members else [] + for member in members[1:]: + group = group_of[member] + if group is not first: + first.extend(group) + first.sort() + for moved in group: + group_of[moved] = first + + +def _merge( + name: str, + table: _Table, + props: Mapping[str, Any], + style: Mapping[str, Any] | Var | None, + layout: Mapping[str, Any] | None, +) -> Merged: + """Merge a lowered style table with the style of one element. + + Args: + name: The display name of the component, for error messages. + table: The lowered style table. + props: The props of the element. + style: The style the user wrote. + layout: The layout props of the element. + + Returns: + The merged styles. + """ + chosen = [] + bound = None + for prop in table.consulted: + value = props.get(prop) + if value.__class__ is not str and value is not None: + value = _variant_key(value) + if value.__class__ is not str: + if bound is None: + bound = {} + bound[len(chosen)] = value + value = None + chosen.append(value) + keys = tuple(chosen) + + if bound is None: + merged = table.merged.get(keys) + if merged is None: + merged = table.merged[keys] = Merged( + finish(table.resolve(keys)), + (), + { + part: _merge(name, inner, props, None, None) + for part, inner in table.parts + }, + ) + if style is None and not layout: + return merged + parts = merged.parts + else: + parts = { + part: _merge(name, inner, props, None, None) for part, inner in table.parts + } + + layers = [lower_layer(name, None, layout)] if layout else [] + inline = None + if isinstance(style, Var): + inline = style + elif style: + layers.append(lower_layer(name, style)) + + if bound is None: + merged_props = dict(table.resolve(keys)) + for layer in layers: + apply_layer(merged_props, layer) + return Merged(finish(merged_props, inline), (), parts) + merged_props, dynamic = _merge_dynamic(table, keys, bound, layers) + return Merged(finish(merged_props, inline), dynamic, parts) + + +def merge( + name: str, + styles: ComponentStyles | Mapping[str, Any], + props: Mapping[str, Any] | None = None, + style: StyleProps | Mapping[str, Any] | Var | None = None, + layout: Mapping[str, Any] | None = None, +) -> Merged: + """Merge the style table of a component with the style of one element. + + The table is lowered the first time it is seen and kept by its identity, + so it has to be a constant that is not changed afterwards. + + Args: + name: The display name of the component, such as ``"rx.ui.button"``, + which starts every error message. + styles: The style table of the component. + props: The props of the element that select variants and compound + styles, defaults included. A value is a string, a bool, a number + or, for a prop bound to state, a Var. Props the table does not + read are ignored. + style: The style the user wrote, or a Var holding a whole dict of + styles, which becomes the inline style of the element. + layout: The layout props of the element, such as ``p`` and ``gap``, + which are merged after the table and before ``style``. + + Returns: + The merged styles of the element and of each of its parts. + + Raises: + StyleError: If the table, the style or a layout prop cannot be + compiled. + """ + return _merge(name, _table(name, styles), props or _NO_PROPS, style, layout) diff --git a/tests/units/reflex_components_ui/style/__init__.py b/tests/units/reflex_components_ui/style/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_components_ui/style/fixtures/style_errors.py.txt b/tests/units/reflex_components_ui/style/fixtures/style_errors.py.txt new file mode 100644 index 00000000000..9bf2700fa0c --- /dev/null +++ b/tests/units/reflex_components_ui/style/fixtures/style_errors.py.txt @@ -0,0 +1,32 @@ +"""Styles that must not type-check: every assignment below is an error.""" + +import reflex as rx +from reflex_components_ui.style import ComponentStyles, CompoundStyle, StyleProps + +unknown_property: StyleProps = {"paddng": "1em"} + +unknown_keyword: StyleProps = {"display": "flx"} + +keyword_as_number: StyleProps = {"position": 1} + +unknown_keyword_under_a_condition: StyleProps = {"display": {":hover": "flx"}} + +unknown_keyword_at_a_breakpoint: StyleProps = {"display": ["none", "flx"]} + +unknown_property_in_a_block: StyleProps = {"_hover": {"colr": "red"}} + +unknown_pseudo_class: StyleProps = {"_hovr": {"color": "red"}} + +component_as_value: StyleProps = {"color": rx.text("red")} + +unknown_table_key: ComponentStyles = {"variant": {"size": {"1": {"height": "1em"}}}} + +unknown_property_in_a_variant: ComponentStyles = { + "variants": {"size": {"1": {"heght": "1em"}}}, +} + +unknown_keyword_in_a_part: ComponentStyles = { + "parts": {"thumb": {"base": {"visibility": "invisible"}}}, +} + +compound_without_props: CompoundStyle = {"style": {"color": "red"}} diff --git a/tests/units/reflex_components_ui/style/fixtures/style_valid.py.txt b/tests/units/reflex_components_ui/style/fixtures/style_valid.py.txt new file mode 100644 index 00000000000..73f7d63e82c --- /dev/null +++ b/tests/units/reflex_components_ui/style/fixtures/style_valid.py.txt @@ -0,0 +1,115 @@ +"""Styles that type-check: what Reflex users write today and what rx.ui adds.""" + +import reflex as rx +from reflex_components_ui.style import ComponentStyles, CompoundStyle, StyleProps + + +class State(rx.State): + """State whose fields are bound to styles.""" + + width: rx.Field[int] = rx.field(320) + color: rx.Field[str] = rx.field("tomato") + hidden: rx.Field[bool] = rx.field(False) + + +literals: StyleProps = { + "display": "flex", + "flex_direction": "column", + "align_items": "center", + "justify_content": "space-between", + "position": "relative", + "overflow": "hidden", + "padding": "1em", + "margin": "0 auto", + "width": "100%", + "max_width": 960, + "line_height": 1.5, + "opacity": "0.8", + "z_index": "10", + "font_weight": "bold", + "border": "1px solid #eaeaea", + "border_radius": "0.5em", + "box_shadow": "rgba(0, 0, 0, 0.1) 0px 4px 12px", + "background_image": "linear-gradient(271.68deg, #EE756A 0.75%, #756AEE 88.52%)", + "transition": "all 0.2s ease-in-out", + "cursor": "pointer", +} + +reflex_keys: StyleProps = { + "bg": "white", + "bg_color": rx.color("gray", 2), + "padding_x": "1em", + "padding_y": ["0.5em", "1em"], + "margin_x": "auto", + "margin_y": 4, +} + +colors: StyleProps = { + "color": rx.color("accent", 11), + "background_color": rx.color("ruby", 3, alpha=True), + "border_color": rx.color(State.color, 6), + "outline_color": "var(--accent-8)", +} + +state: StyleProps = { + "width": State.width, + "height": f"{State.width}px", + "color": State.color, + "display": rx.cond(State.hidden, "none", "block"), + "opacity": rx.cond(State.hidden, 0, 1), +} + +responsive: StyleProps = { + "font_size": ["1em", "1.25em", "1.5em"], + "display": ["none", "none", "flex"], + "flex_direction": rx.breakpoints(initial="column", md="row"), + "padding": rx.breakpoints(initial="1em", sm="2em", lg="4em"), + "width": {"initial": "100%", "md": "50%"}, +} + +conditions: StyleProps = { + "color": {"default": "black", ":hover": "blue", "[data-disabled]": "gray"}, + "display": {"default": "block", "@media print": "none"}, + "_hover": {"background_color": rx.color("accent", 4), "cursor": "pointer"}, + "_focus_visible": {"outline": "2px solid", "outline_offset": "2px"}, + "_before": {"content": '""', "position": "absolute"}, + "_placeholder": {"color": rx.color("gray", 9)}, + ":active": {"transform": "scale(0.98)"}, + "::selection": {"background_color": "highlight"}, + "::-webkit-scrollbar": {"display": "none"}, + "_disabled": {"_hover": {"cursor": "not-allowed"}}, +} + +BUTTON: ComponentStyles = { + "base": {"display": "inline-flex", "align_items": "center", "font_weight": "500"}, + "variants": { + "variant": { + "solid": { + "background_color": { + "default": "var(--accent-9)", + ":hover": "var(--accent-10)", + }, + "color": "var(--accent-contrast)", + }, + "soft": { + "background_color": rx.color("accent", 3, alpha=True), + "color": rx.color("accent", 11, alpha=True), + }, + }, + "size": { + "1": {"height": "var(--space-5)"}, + "2": {"height": "var(--space-6)"}, + }, + }, + "compound": [ + {"props": {"variant": "solid", "size": "2"}, "style": {"font_weight": "700"}}, + ], + "parts": { + "icon": { + "base": {"flex_shrink": 0}, + "variants": {"size": {"2": {"width": "1.25em"}}}, + }, + }, +} + +compound: CompoundStyle = {"props": {"size": "1"}, "style": {"padding": 0}} diff --git a/tests/units/reflex_components_ui/style/test_css_props.py b/tests/units/reflex_components_ui/style/test_css_props.py new file mode 100644 index 00000000000..fc983a9c8ea --- /dev/null +++ b/tests/units/reflex_components_ui/style/test_css_props.py @@ -0,0 +1,227 @@ +"""Tests for what a type checker makes of the generated style types.""" + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +FIXTURES = Path(__file__).parent / "fixtures" + + +def _pyright(tmp_path: Path, fixture: str) -> list[tuple[int, str, str]]: + """Run pyright over a fixture, outside the configuration of the repository. + + The fixtures are kept as text so that no other tool checks them. + + Args: + tmp_path: A directory to copy the fixture to. + fixture: The name of the fixture, without its extension. + + Returns: + The line, rule and whole message of every diagnostic. + """ + target = tmp_path / f"{fixture}.py" + shutil.copy(FIXTURES / f"{fixture}.py.txt", target) + result = subprocess.run( + [ + sys.executable, + "-m", + "pyright", + "--outputjson", + "--pythonpath", + sys.executable, + str(target), + ], + capture_output=True, + text=True, + cwd=tmp_path, + check=False, + ) + diagnostics = json.loads(result.stdout)["generalDiagnostics"] + assert {diagnostic["file"] for diagnostic in diagnostics} <= {str(target)} + return [ + ( + diagnostic["range"]["start"]["line"] + 1, + diagnostic["rule"], + diagnostic["message"], + ) + for diagnostic in diagnostics + ] + + +def test_valid_styles_type_check(tmp_path: Path): + """What Reflex users write today, and a style table, raise nothing.""" + assert _pyright(tmp_path, "style_valid") == [] + + +def test_invalid_styles_are_type_errors(tmp_path: Path): + """A misspelt property, keyword or table key is caught before compiling.""" + assert _pyright(tmp_path, "style_errors") == EXPECTED_ERRORS + + +EXPECTED_ERRORS: list[tuple[int, str, str]] = [ + ( + 6, + "reportAssignmentType", + ( + 'Type "dict[str, str]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0"paddng" is an undefined item in type "StyleProps"' + ), + ), + ( + 8, + "reportAssignmentType", + ( + 'Type "dict[str, str]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0Type "Literal[\'flx\']" is not assignable to type "_Value[_Display | ' + '_StrVar]"\n' + '\xa0\xa0\xa0\xa0"Literal[\'flx\']" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0"Literal[\'flx\']" is not assignable to "Sequence[_Display | ' + '_StrVar]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' + 'not a subtype of "_Display | _StrVar"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Display | ' + '_StrVar"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type ' + "\"Literal['-webkit-box']\"\n" + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type ' + "\"Literal['block']\"" + ), + ), + ( + 10, + "reportAssignmentType", + ( + 'Type "dict[str, int]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0Type "Literal[1]" is not assignable to type "_Value[_Position | _StrVar]"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Sequence[_Position | _StrVar]"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Breakpoints[Any, Any]"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Mapping[str, _Position | _StrVar ' + '| Mapping[str, _Position | _StrVar]]"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Literal[\'absolute\']"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Literal[\'fixed\']"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Literal[\'inherit\']"' + ), + ), + ( + 12, + "reportAssignmentType", + ( + 'Type "dict[str, dict[str, str]]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0Type "dict[str, str]" is not assignable to type "_Value[_Display | ' + '_StrVar]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Sequence[_Display | ' + '_StrVar]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Breakpoints[Any, Any]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Mapping[str, _Display | ' + '_StrVar | Mapping[str, _Display | _StrVar]]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_VT_co@Mapping" is covariant, but "str" is ' + 'not a subtype of "_Display | _StrVar | Mapping[str, _Display | _StrVar]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Display | ' + '_StrVar | Mapping[str, _Display | _StrVar]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "Var[str]"' + ), + ), + ( + 14, + "reportAssignmentType", + ( + 'Type "dict[str, list[str]]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0Type "Literal[\'flx\']" is not assignable to type "_Display | _StrVar"\n' + '\xa0\xa0\xa0\xa0"Literal[\'flx\']" is not assignable to "Var[str]"\n' + "\xa0\xa0\xa0\xa0\"Literal['flx']\" is not assignable to type " + "\"Literal['-webkit-box']\"\n" + "\xa0\xa0\xa0\xa0\"Literal['flx']\" is not assignable to type \"Literal['block']\"\n" + "\xa0\xa0\xa0\xa0\"Literal['flx']\" is not assignable to type " + "\"Literal['contents']\"\n" + "\xa0\xa0\xa0\xa0\"Literal['flx']\" is not assignable to type \"Literal['flex']\"\n" + "\xa0\xa0\xa0\xa0\"Literal['flx']\" is not assignable to type " + "\"Literal['flow-root']\"\n" + "\xa0\xa0\xa0\xa0\"Literal['flx']\" is not assignable to type \"Literal['grid']\"" + ), + ), + ( + 16, + "reportAssignmentType", + ( + 'Type "dict[str, dict[str, str]]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0"colr" is an undefined item in type "StyleProps"' + ), + ), + ( + 18, + "reportAssignmentType", + ( + 'Type "dict[str, dict[str, str]]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0"_hovr" is an undefined item in type "StyleProps"' + ), + ), + ( + 20, + "reportAssignmentType", + ( + 'Type "dict[str, Text]" is not assignable to declared type "StyleProps"\n' + '\xa0\xa0Type "Text" is not assignable to type "_Value[_Color]"\n' + '\xa0\xa0\xa0\xa0"Text" is not assignable to "str"\n' + '\xa0\xa0\xa0\xa0"Text" is not assignable to "Color"\n' + '\xa0\xa0\xa0\xa0"Text" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0"Text" is not assignable to "Var[Color]"\n' + '\xa0\xa0\xa0\xa0"Text" is not assignable to "Sequence[_Color]"\n' + '\xa0\xa0\xa0\xa0"Text" is not assignable to "Breakpoints[Any, Any]"\n' + '\xa0\xa0\xa0\xa0"Text" is not assignable to "Mapping[str, _Color | Mapping[str, ' + '_Color]]"' + ), + ), + ( + 22, + "reportAssignmentType", + ( + 'Type "dict[str, dict[str, dict[str, dict[str, str]]]]" is not assignable to ' + 'declared type "ComponentStyles"\n' + '\xa0\xa0"variant" is an undefined item in type "ComponentStyles"' + ), + ), + ( + 25, + "reportAssignmentType", + ( + 'Type "dict[str, dict[str, dict[str, dict[str, str]]]]" is not assignable to ' + 'declared type "ComponentStyles"\n' + '\xa0\xa0"heght" is an undefined item in type "StyleProps"' + ), + ), + ( + 29, + "reportAssignmentType", + ( + 'Type "dict[str, dict[str, dict[str, dict[str, str]]]]" is not assignable to ' + 'declared type "ComponentStyles"\n' + '\xa0\xa0Type "Literal[\'invisible\']" is not assignable to type "_Value[_Visibility ' + '| _StrVar]"\n' + '\xa0\xa0\xa0\xa0"Literal[\'invisible\']" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0"Literal[\'invisible\']" is not assignable to "Sequence[_Visibility ' + '| _StrVar]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' + 'not a subtype of "_Visibility | _StrVar"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Visibility | ' + '_StrVar"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type ' + "\"Literal['collapse']\"\n" + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type ' + "\"Literal['hidden']\"" + ), + ), + ( + 32, + "reportAssignmentType", + ( + 'Type "dict[str, StyleProps]" is not assignable to declared type "CompoundStyle"\n' + '\xa0\xa0"props" is required in "CompoundStyle"' + ), + ), +] diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py new file mode 100644 index 00000000000..ec03014faa6 --- /dev/null +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -0,0 +1,1361 @@ +"""Tests for lowering the styles a user writes into what StyleX compiles.""" + +from typing import Any + +import pytest +from reflex_base.breakpoints import breakpoints_values, set_breakpoints +from reflex_base.constants.colors import Color +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_ui.style import _css_props +from reflex_components_ui.style.lower import ( + _BORDERS, + _EXPANSIONS, + _LAYOUT, + _REFLEX_KEYS, + _REPLACES, + _UNSUPPORTED, + LAYOUT_PROPS, + VAR_MODULES, + Lowered, + StyleError, + apply_layer, + finish, + lower, + lower_layer, +) + +import reflex as rx + +RUBY = "$/reflex-ui/colors/ruby.stylex.js" +GRAY = "$/reflex-ui/colors/gray.stylex.js" +XS = "@media screen and (min-width: 30em)" +SM = "@media screen and (min-width: 48em)" +MD = "@media screen and (min-width: 62em)" +LG = "@media screen and (min-width: 80em)" +XL = "@media screen and (min-width: 96em)" + + +class StyleState(rx.State): + """State whose fields are bound to styles.""" + + width: rx.Field[int] = rx.field(320) + scale: rx.Field[str] = rx.field("ruby") + style: rx.Field[dict[str, str]] = rx.field({}) + + +WIDTH = StyleState.width +SCALE = StyleState.scale + + +def test_generated_tables_cover_what_lowering_names(): + """Every property lowering expands to, replaces or sets is a known one.""" + known = set(_css_props.CSS_PROPS.values()) + named = { + *_EXPANSIONS, + *(prop for longhands, _ in _EXPANSIONS.values() for prop in longhands), + *_REPLACES, + *(prop for replaced in _REPLACES.values() for prop in replaced), + *(prop for targets in _REFLEX_KEYS.values() for prop in targets), + *_BORDERS, + *_UNSUPPORTED, + *( + f"{side}{part}" + for sides in _BORDERS.values() + for side in sides + for part in ("Width", "Style", "Color") + ), + *(prop for _, targets, _ in _LAYOUT.values() for prop in targets), + } + assert named - known == set() + assert {key: _css_props.CSS_PROPS.get(key) for key, _, _ in _LAYOUT.values()} == { + "padding": "padding", + "padding_x": None, + "padding_y": None, + "padding_top": "paddingTop", + "padding_right": "paddingRight", + "padding_bottom": "paddingBottom", + "padding_left": "paddingLeft", + "margin": "margin", + "margin_x": None, + "margin_y": None, + "margin_top": "marginTop", + "margin_right": "marginRight", + "margin_bottom": "marginBottom", + "margin_left": "marginLeft", + "gap": "gap", + "column_gap": "columnGap", + "row_gap": "rowGap", + "grid_template_columns": "gridTemplateColumns", + "grid_template_rows": "gridTemplateRows", + "flex_direction": "flexDirection", + "flex_wrap": "flexWrap", + "align_items": "alignItems", + "justify_content": "justifyContent", + "grid_auto_flow": "gridAutoFlow", + } + + +def test_generated_table_spells_properties_as_users_do(): + """A sample of the generated keys, vendor prefixes included.""" + sample = ( + "background_color", + "border_top_left_radius", + "webkit_font_smoothing", + "moz_osx_font_smoothing", + "z_index", + "float", + "theme", + ) + assert {key: _css_props.CSS_PROPS.get(key) for key in sample} == { + "background_color": "backgroundColor", + "border_top_left_radius": "borderTopLeftRadius", + "webkit_font_smoothing": "WebkitFontSmoothing", + "moz_osx_font_smoothing": "MozOsxFontSmoothing", + "z_index": "zIndex", + "float": "float", + "theme": None, + } + assert len(_css_props.CSS_PROPS) == 521 + assert _css_props.StyleProps is dict + + +@pytest.mark.parametrize( + ("style", "expected"), + [ + ({}, {}), + (None, {}), + ( + {"display": "flex", "z_index": 3, "line_height": 1.5, "color": "red"}, + {"display": "flex", "zIndex": 3, "lineHeight": 1.5, "color": "red"}, + ), + ( + {"backgroundColor": "red", "font-size": "2em", "--card-gap": "4px"}, + {"backgroundColor": "red", "fontSize": "2em", "--card-gap": "4px"}, + ), + ( + {"_webkit_font_smoothing": "antialiased", "webkit_appearance": "none"}, + {"WebkitFontSmoothing": "antialiased", "WebkitAppearance": "none"}, + ), + ( + {"width": LiteralVar.create("10px"), "order": LiteralVar.create(2)}, + {"width": "10px", "order": 2}, + ), + ({"color": "red", "width": None}, {"color": "red"}), + ], +) +def test_literal_values(style: Any, expected: dict[str, Any]): + """A literal value stays a literal under the camelCase name of its property. + + Args: + style: The style as written. + expected: The lowered properties. + """ + assert lower("rx.ui.card", style) == Lowered(expected) + + +def test_literal_values_keep_their_order(): + """The properties come out in the order they were written.""" + lowered = lower("rx.ui.card", {"width": "1px", "color": "red", "top": 0}) + assert list(lowered.style.items()) == [ + ("width", "1px"), + ("color", "red"), + ("top", 0), + ] + assert (lowered.imports, lowered.inline) == ((), None) + + +def test_state_var_values(): + """A value bound to state is kept as its Var, wherever it is written.""" + concatenated = LiteralVar.create(f"{WIDTH}px") + assert lower( + "rx.ui.card", + { + "width": WIDTH, + "height": f"{WIDTH}px", + "min_width": [WIDTH, "50%"], + "_hover": {"max_width": WIDTH}, + "padding": WIDTH, + "padding_x": WIDTH, + }, + ) == Lowered({ + "width": WIDTH, + "height": concatenated, + "minWidth": {"default": WIDTH, XS: "50%"}, + "maxWidth": {":hover": WIDTH}, + "padding": WIDTH, + "paddingLeft": WIDTH, + "paddingRight": WIDTH, + }) + + +def test_whole_dict_var_becomes_the_inline_style(): + """A Var holding a dict of styles is not lowered, only carried.""" + lowered = lower("rx.ui.card", StyleState.style) + assert lowered == Lowered({}, (), StyleState.style) + assert lowered.style == {} + assert lowered.inline is not None + assert lowered.inline.equals(StyleState.style) + assert lower("rx.ui.card", StyleState.style, {"p": "2"}) == Lowered( + { + "paddingTop": "var(--space-2)", + "paddingRight": "var(--space-2)", + "paddingBottom": "var(--space-2)", + "paddingLeft": "var(--space-2)", + }, + (), + StyleState.style, + ) + + +@pytest.mark.parametrize( + ("style", "expected"), + [ + ( + {"color": "black", "_hover": {"color": "blue"}}, + {"color": {"default": "black", ":hover": "blue"}}, + ), + ( + {"_hover": {"color": "blue"}, "color": "black"}, + {"color": {"default": "black", ":hover": "blue"}}, + ), + ( + {":focus-visible": {"outline_style": "solid"}}, + {"outlineStyle": {":focus-visible": "solid"}}, + ), + ( + {"_focus_visible": {"color": "red"}, "_focusWithin": {"color": "blue"}}, + {"color": {":focus-visible": "red", ":focus-within": "blue"}}, + ), + ( + {"_before": {"content": '""'}, "_placeholder": {"color": "gray"}}, + {"content": {"::before": '""'}, "color": {"::placeholder": "gray"}}, + ), + ( + {"::-webkit-scrollbar": {"display": "none"}, "&:hover": {"top": 0}}, + {"display": {"::-webkit-scrollbar": "none"}, "top": {":hover": 0}}, + ), + ( + { + "[data-open]": {"opacity": 1}, + "&[data-disabled]": {"opacity": 0.5}, + ":not(:first-child)": {"opacity": 0}, + ":nth-child(2n + 1)": {"opacity": 0.2}, + }, + { + "opacity": { + "[data-open]": 1, + "[data-disabled]": 0.5, + ":not(:first-child)": 0, + ":nth-child(2n + 1)": 0.2, + } + }, + ), + ( + { + "@media (min-width: 768px)": {"color": "red"}, + "@container (min-width: 20em)": {"color": "blue"}, + "@supports (display: grid)": {"color": "green"}, + "@starting-style": {"color": "pink"}, + }, + { + "color": { + "@media (min-width: 768px)": "red", + "@container (min-width: 20em)": "blue", + "@supports (display: grid)": "green", + "@starting-style": "pink", + } + }, + ), + ( + {"_hover": {"color": "red", "_disabled": {"color": "gray"}}}, + {"color": {":hover": {"default": "red", ":disabled": "gray"}}}, + ), + ( + {"_hover": {"_disabled": {"color": "gray"}, "color": "red"}}, + {"color": {":hover": {"default": "red", ":disabled": "gray"}}}, + ), + ( + {"color": {"default": "black", ":hover": "blue", "_active": "red"}}, + {"color": {"default": "black", ":hover": "blue", ":active": "red"}}, + ), + ( + {"color": {":hover": {"default": "blue", "@media print": "black"}}}, + {"color": {":hover": {"default": "blue", "@media print": "black"}}}, + ), + ( + {"color": None, "_hover": {"color": "blue"}}, + {"color": {"default": None, ":hover": "blue"}}, + ), + ( + {"_hover": {"margin": "0 auto"}}, + { + "marginTop": {":hover": "0"}, + "marginRight": {":hover": "auto"}, + "marginBottom": {":hover": "0"}, + "marginLeft": {":hover": "auto"}, + }, + ), + ], +) +def test_condition_blocks(style: Any, expected: dict[str, Any]): + """A block of styles under a condition becomes per-property conditions. + + Args: + style: The style as written. + expected: The lowered properties. + """ + assert lower("rx.ui.card", style) == Lowered(expected) + + +@pytest.mark.parametrize( + ("style", "expected"), + [ + ({"width": ["100%"]}, {"width": "100%"}), + ({"width": ["100%", "50%"]}, {"width": {"default": "100%", XS: "50%"}}), + ( + {"width": ("1px", "2px", "3px", "4px", "5px", "6px")}, + { + "width": { + "default": "1px", + XS: "2px", + SM: "3px", + MD: "4px", + LG: "5px", + XL: "6px", + } + }, + ), + ({"width": [None, None, "50%"]}, {"width": {SM: "50%"}}), + ( + {"width": rx.breakpoints(initial="100%", sm="50%", xl="25%")}, + {"width": {"default": "100%", SM: "50%", XL: "25%"}}, + ), + ({"width": rx.breakpoints(md="50%")}, {"width": {MD: "50%"}}), + ( + {"width": rx.breakpoints(custom={"500px": "50%", "xs": "75%"})}, + { + "width": { + "@media screen and (min-width: 500px)": "50%", + XS: "75%", + } + }, + ), + ( + {"width": {"initial": "100%", "lg": "50%"}}, + {"width": {"default": "100%", LG: "50%"}}, + ), + ( + {"_hover": {"width": ["100%", "50%"]}}, + {"width": {":hover": {"default": "100%", XS: "50%"}}}, + ), + ( + {"width": ["100%", {"default": "50%", ":hover": "60%"}]}, + {"width": {"default": "100%", XS: {"default": "50%", ":hover": "60%"}}}, + ), + ( + {"padding_x": ["1em", "2em"]}, + { + "paddingLeft": {"default": "1em", XS: "2em"}, + "paddingRight": {"default": "1em", XS: "2em"}, + }, + ), + ( + {"gap": rx.breakpoints(initial="1em", sm="1em 2em")}, + { + "rowGap": {"default": "1em", SM: "1em"}, + "columnGap": {"default": "1em", SM: "2em"}, + }, + ), + ], +) +def test_responsive_values(style: Any, expected: dict[str, Any]): + """A responsive value becomes media queries on the five breakpoints. + + Args: + style: The style as written. + expected: The lowered properties. + """ + assert lower("rx.ui.card", style) == Lowered(expected) + + +def test_responsive_values_follow_the_configured_breakpoints(): + """The media queries are read from the breakpoints of the app.""" + original = tuple(breakpoints_values) + set_breakpoints(("10px", "20px", "30px", "40px", "50px")) + try: + lowered = lower( + "rx.ui.card", {"width": ["1px", "2px"], "top": rx.breakpoints(xl="0")} + ) + finally: + set_breakpoints(original) # pyright: ignore [reportArgumentType] + assert lowered == Lowered({ + "width": {"default": "1px", "@media screen and (min-width: 10px)": "2px"}, + "top": {"@media screen and (min-width: 50px)": "0"}, + }) + + +@pytest.mark.parametrize( + ("style", "expected", "imports"), + [ + ({"color": rx.color("ruby", 9)}, {"color": "var(--ruby-9)"}, (RUBY,)), + ({"color": rx.color("ruby", 3, True)}, {"color": "var(--ruby-a3)"}, (RUBY,)), + ( + {"color": LiteralVar.create(rx.color("gray", 11))}, + {"color": "var(--gray-11)"}, + (GRAY,), + ), + ({"color": rx.color("accent", 9)}, {"color": "var(--accent-9)"}, ()), + ( + {"outline": f"1px solid {rx.color('ruby', 6)}", "color": "var(--gray-a11)"}, + {"outline": "1px solid var(--ruby-6)", "color": "var(--gray-a11)"}, + (GRAY, RUBY), + ), + ( + { + "color": { + "default": rx.color("gray", 12), + ":hover": [rx.color("ruby", 9), rx.color("ruby", 10)], + } + }, + { + "color": { + "default": "var(--gray-12)", + ":hover": {"default": "var(--ruby-9)", XS: "var(--ruby-10)"}, + } + }, + (GRAY, RUBY), + ), + ( + {"border_color": rx.color("ruby", 6)}, + { + "borderTopColor": "var(--ruby-6)", + "borderRightColor": "var(--ruby-6)", + "borderBottomColor": "var(--ruby-6)", + "borderLeftColor": "var(--ruby-6)", + }, + (RUBY,), + ), + ( + {"color": "var(--my-color)", "width": "var(--space-4)"}, + {"color": "var(--my-color)", "width": "var(--space-4)"}, + (), + ), + ( + {"color": rx.color(SCALE, 9)}, + {"color": LiteralVar.create(Color(SCALE, 9))}, + (), + ), + ], +) +def test_colors_and_tokens( + style: Any, expected: dict[str, Any], imports: tuple[str, ...] +): + """A color becomes its custom property and names the module of its scale. + + Args: + style: The style as written. + expected: The lowered properties. + imports: The modules the style needs. + """ + lowered = lower("rx.ui.card", style) + assert lowered == Lowered(expected, imports) + assert lowered.imports == imports + + +def test_var_modules_name_a_module_per_color_scale(): + """Every Radix scale has a module, and a token can register its own.""" + assert VAR_MODULES["ruby"] == RUBY + assert sorted(VAR_MODULES) == [ + "amber", + "black", + "blue", + "bronze", + "brown", + "crimson", + "cyan", + "gold", + "grass", + "gray", + "green", + "indigo", + "iris", + "jade", + "lime", + "mauve", + "mint", + "olive", + "orange", + "pink", + "plum", + "purple", + "red", + "ruby", + "sage", + "sand", + "sky", + "slate", + "teal", + "tomato", + "violet", + "white", + "yellow", + ] + VAR_MODULES["space"] = "$/reflex-ui/tokens/space.stylex.js" + try: + lowered = lower("rx.ui.card", {"width": "calc(2 * var(--space-4))"}) + finally: + del VAR_MODULES["space"] + assert lowered.imports == ("$/reflex-ui/tokens/space.stylex.js",) + + +def _sides(prefix: str, suffix: str, *values: Any) -> dict[str, Any]: + """Build the four longhands of a box shorthand. + + Args: + prefix: What comes before the side. + suffix: What comes after it. + values: The top, right, bottom and left values. + + Returns: + The lowered properties. + """ + sides = ("Top", "Right", "Bottom", "Left") + return { + f"{prefix}{side}{suffix}": value + for side, value in zip(sides, values, strict=True) + } + + +@pytest.mark.parametrize( + ("style", "expected"), + [ + ({"margin": "0 auto"}, _sides("margin", "", "0", "auto", "0", "auto")), + ({"margin": "1em"}, _sides("margin", "", "1em", "1em", "1em", "1em")), + ({"margin": 4}, _sides("margin", "", 4, 4, 4, 4)), + ({"padding": "1px 2px 3px"}, _sides("padding", "", "1px", "2px", "3px", "2px")), + ( + {"padding": "1px 2px 3px 4px"}, + _sides("padding", "", "1px", "2px", "3px", "4px"), + ), + ( + {"padding": "calc(1px + 2px) max(1em, 4px)"}, + {"padding": "calc(1px + 2px) max(1em, 4px)"}, + ), + ( + {"padding": "calc(1px + 2px) min(1em 4px)"}, + _sides( + "padding", + "", + "calc(1px + 2px)", + "min(1em 4px)", + "calc(1px + 2px)", + "min(1em 4px)", + ), + ), + ({"padding": "var(--card-padding)"}, {"padding": "var(--card-padding)"}), + ({"padding": "1px 2px 3px 4px 5px"}, {"padding": "1px 2px 3px 4px 5px"}), + ({"margin": "0 !important"}, {"margin": "0 !important"}), + ( + {"inset": "0 auto"}, + {"top": "0", "right": "auto", "bottom": "0", "left": "auto"}, + ), + ( + {"border_width": "1px 2px"}, + _sides("border", "Width", "1px", "2px", "1px", "2px"), + ), + ( + {"border_style": "solid"}, + _sides("border", "Style", "solid", "solid", "solid", "solid"), + ), + ( + {"border_color": "rgb(0 0 0) red"}, + _sides("border", "Color", "rgb(0 0 0)", "red", "rgb(0 0 0)", "red"), + ), + ( + {"border_radius": "4px 8px"}, + { + "borderTopLeftRadius": "4px", + "borderTopRightRadius": "8px", + "borderBottomRightRadius": "4px", + "borderBottomLeftRadius": "8px", + }, + ), + ({"border_radius": "50% / 10%"}, {"borderRadius": "50% / 10%"}), + ({"gap": "1em"}, {"rowGap": "1em", "columnGap": "1em"}), + ({"gap": "1em 2em"}, {"rowGap": "1em", "columnGap": "2em"}), + ({"overflow": "hidden auto"}, {"overflowX": "hidden", "overflowY": "auto"}), + ( + {"margin_inline": "1em 2em", "padding_block": "3em"}, + { + "marginInlineStart": "1em", + "marginInlineEnd": "2em", + "paddingBlockStart": "3em", + "paddingBlockEnd": "3em", + }, + ), + ( + {"padding_x": "1em 2em", "margin_y": 0}, + { + "paddingLeft": "1em 2em", + "paddingRight": "1em 2em", + "marginTop": 0, + "marginBottom": 0, + }, + ), + ( + {"bg": "red", "bg_color": "blue", "paddingX": "1px", "margin-x": "2px"}, + { + "backgroundColor": "blue", + "backgroundImage": "none", + "paddingLeft": "1px", + "paddingRight": "1px", + "marginLeft": "2px", + "marginRight": "2px", + }, + ), + ( + {"margin_top": "1em", "margin": "0"}, + _sides("margin", "", "0", "0", "0", "0"), + ), + ( + {"margin": "0", "margin_top": "1em"}, + _sides("margin", "", "1em", "0", "0", "0"), + ), + ( + {"outline": "1px solid red", "transition": "all 0.2s", "flex": "1 1 0"}, + {"outline": "1px solid red", "transition": "all 0.2s", "flex": "1 1 0"}, + ), + ], +) +def test_shorthands(style: Any, expected: dict[str, Any]): + """A shorthand whose values can be told apart is expanded to longhands. + + Args: + style: The style as written. + expected: The lowered properties. + """ + assert lower("rx.ui.card", style) == Lowered(expected) + + +def _border(sides: tuple[str, ...], width: Any, style: Any, color: Any) -> dict: + """Build the longhands of a border shorthand. + + Args: + sides: The sides it sets, such as ``borderTop``. + width: The width of each side. + style: The style of each side. + color: The color of each side. + + Returns: + The lowered properties. + """ + parts = (("Width", width), ("Style", style), ("Color", color)) + return {f"{side}{part}": value for side in sides for part, value in parts} + + +ALL_SIDES = ("borderTop", "borderRight", "borderBottom", "borderLeft") + + +@pytest.mark.parametrize( + ("style", "expected", "imports"), + [ + ({"border": "1px solid red"}, _border(ALL_SIDES, "1px", "solid", "red"), ()), + ({"border": "red solid 1px"}, _border(ALL_SIDES, "1px", "solid", "red"), ()), + ( + {"border": f"1px solid {rx.color('gray', 6)}"}, + _border(ALL_SIDES, "1px", "solid", "var(--gray-6)"), + (GRAY,), + ), + ( + {"border": "calc(1px + 1px) dashed rgb(0 0 0 / 50%)"}, + _border(ALL_SIDES, "calc(1px + 1px)", "dashed", "rgb(0 0 0 / 50%)"), + (), + ), + ({"border": "none"}, _border(ALL_SIDES, "medium", "none", "currentcolor"), ()), + ({"border": 0}, _border(ALL_SIDES, 0, "none", "currentcolor"), ()), + ({"border": "thin"}, _border(ALL_SIDES, "thin", "none", "currentcolor"), ()), + ( + {"border": rx.color("ruby", 6)}, + _border(ALL_SIDES, "medium", "none", "var(--ruby-6)"), + (RUBY,), + ), + ( + {"border_top": "2px dotted", "borderLeft": ".5em solid blue"}, + { + **_border(("borderTop",), "2px", "dotted", "currentcolor"), + **_border(("borderLeft",), ".5em", "solid", "blue"), + }, + (), + ), + ( + {"border_right": "1px solid", "border_bottom": "1px solid"}, + _border(("borderRight", "borderBottom"), "1px", "solid", "currentcolor"), + (), + ), + ( + {"border_block": "1px solid", "border_inline": "2px solid"}, + { + **_border( + ("borderTop", "borderBottom"), "1px", "solid", "currentcolor" + ), + **_border( + ("borderInlineStart", "borderInlineEnd"), + "2px", + "solid", + "currentcolor", + ), + }, + (), + ), + ( + { + "border_block_start": "1px solid", + "border_block_end": "2px solid", + "border_inline_start": "3px solid", + "border_inline_end": "4px solid", + }, + { + **_border(("borderTop",), "1px", "solid", "currentcolor"), + **_border(("borderBottom",), "2px", "solid", "currentcolor"), + **_border(("borderInlineStart",), "3px", "solid", "currentcolor"), + **_border(("borderInlineEnd",), "4px", "solid", "currentcolor"), + }, + (), + ), + ( + {"border": "1px solid red", "border_top": None}, + { + **_border(ALL_SIDES[1:], "1px", "solid", "red"), + }, + (), + ), + ( + {"border": "1px solid red", "_hover": {"border_color": "blue"}}, + { + **_border( + ALL_SIDES, "1px", "solid", {"default": "red", ":hover": "blue"} + ), + }, + (), + ), + ( + {"background": "red", "bg": "blue"}, + {"backgroundColor": "blue", "backgroundImage": "none"}, + (), + ), + ( + {"bg": rx.color("ruby", 3), "_hover": {"background": "none"}}, + { + "backgroundColor": { + "default": "var(--ruby-3)", + ":hover": "transparent", + }, + "backgroundImage": {"default": "none", ":hover": "none"}, + }, + (RUBY,), + ), + ( + {"background": "var(--surface)"}, + {"backgroundColor": "var(--surface)", "backgroundImage": "none"}, + (), + ), + ( + {"background": "linear-gradient(90deg, red 0%, blue 100%)"}, + { + "backgroundColor": "transparent", + "backgroundImage": "linear-gradient(90deg, red 0%, blue 100%)", + }, + (), + ), + ( + {"background": ["URL(a.png)", "repeating-conic-gradient(red, blue)"]}, + { + "backgroundColor": {"default": "transparent", XS: "transparent"}, + "backgroundImage": { + "default": "URL(a.png)", + XS: "repeating-conic-gradient(red, blue)", + }, + }, + (), + ), + ({"background": None, "color": "red"}, {"color": "red"}, ()), + ], +) +def test_shorthands_stylex_does_not_compile( + style: Any, expected: dict[str, Any], imports: tuple[str, ...] +): + """The border and background shorthands are split, having no other form. + + Args: + style: The style as written. + expected: The lowered properties. + imports: The modules the style needs. + """ + assert lower("rx.ui.card", style) == Lowered(expected, imports) + + +@pytest.mark.parametrize( + ("layout", "expected"), + [ + ({"p": "4"}, _sides("padding", "", *["var(--space-4)"] * 4)), + ( + {"p": "0", "m": "-0"}, + {**_sides("padding", "", *["0"] * 4), **_sides("margin", "", *["0"] * 4)}, + ), + ({"m": "-2"}, _sides("margin", "", *["calc(-1 * var(--space-2))"] * 4)), + ( + {"m": "auto", "p": "10px", "pt": 3}, + { + **_sides("margin", "", *["auto"] * 4), + **_sides("padding", "", 3, "10px", "10px", "10px"), + }, + ), + ( + {"px": "1", "py": "2", "mx": "3", "my": "4"}, + { + "paddingLeft": "var(--space-1)", + "paddingRight": "var(--space-1)", + "paddingTop": "var(--space-2)", + "paddingBottom": "var(--space-2)", + "marginLeft": "var(--space-3)", + "marginRight": "var(--space-3)", + "marginTop": "var(--space-4)", + "marginBottom": "var(--space-4)", + }, + ), + ( + {"pt": "1", "pr": "2", "pb": "3", "pl": "4"}, + _sides("padding", "", *[f"var(--space-{step})" for step in "1234"]), + ), + ( + {"mt": "1", "mr": "2", "mb": "3", "ml": "4"}, + _sides("margin", "", *[f"var(--space-{step})" for step in "1234"]), + ), + ({"gap": "3"}, {"rowGap": "var(--space-3)", "columnGap": "var(--space-3)"}), + ({"spacing": "9"}, {"rowGap": "var(--space-9)", "columnGap": "var(--space-9)"}), + ({"gap": "10"}, {"rowGap": "10", "columnGap": "10"}), + ( + {"gap_x": "1", "gap_y": "2"}, + {"columnGap": "var(--space-1)", "rowGap": "var(--space-2)"}, + ), + ( + {"gap": ["1", "2"]}, + { + "rowGap": {"default": "var(--space-1)", XS: "var(--space-2)"}, + "columnGap": {"default": "var(--space-1)", XS: "var(--space-2)"}, + }, + ), + ( + {"p": rx.breakpoints(initial="1", md="4")}, + _sides( + "padding", + "", + *[{"default": "var(--space-1)", MD: "var(--space-4)"}] * 4, + ), + ), + ( + {"columns": "3", "rows": "2"}, + { + "gridTemplateColumns": "repeat(3, minmax(0, 1fr))", + "gridTemplateRows": "repeat(2, minmax(0, 1fr))", + }, + ), + ( + {"columns": {"initial": "1", "sm": "repeat(2, 10em)"}}, + { + "gridTemplateColumns": { + "default": "repeat(1, minmax(0, 1fr))", + SM: "repeat(2, 10em)", + } + }, + ), + ( + {"direction": "column", "wrap": "wrap", "flow": "row-dense"}, + { + "flexDirection": "column", + "flexWrap": "wrap", + "gridAutoFlow": "row dense", + }, + ), + ( + {"direction": ["column", "row"], "align": "start", "justify": "between"}, + { + "flexDirection": {"default": "column", XS: "row"}, + "alignItems": "flex-start", + "justifyContent": "space-between", + }, + ), + ( + {"align": ["end", "center"], "justify": {"initial": "end", "lg": "start"}}, + { + "alignItems": {"default": "flex-end", XS: "center"}, + "justifyContent": {"default": "flex-end", LG: "flex-start"}, + }, + ), + ({"direction": SCALE}, {"flexDirection": SCALE}), + ( + {"gap": LiteralVar.create("2"), "p": None}, + {"rowGap": "var(--space-2)", "columnGap": "var(--space-2)"}, + ), + ], +) +def test_layout_props(layout: dict[str, Any], expected: dict[str, Any]): + """A layout prop becomes the styles it stands for, at every breakpoint. + + Args: + layout: The layout props. + expected: The lowered properties. + """ + assert lower("rx.ui.flex", None, layout) == Lowered(expected) + + +def test_layout_props_are_merged_under_the_style(): + """The style of the element wins over its layout props, by property.""" + assert lower( + "rx.ui.flex", + {"padding_top": "1px", "_hover": {"row_gap": "0"}, "margin": WIDTH}, + {"p": "2", "gap": "3", "mt": "1"}, + ) == Lowered({ + "paddingTop": "1px", + "paddingRight": "var(--space-2)", + "paddingBottom": "var(--space-2)", + "paddingLeft": "var(--space-2)", + "rowGap": {"default": "var(--space-3)", ":hover": "0"}, + "columnGap": "var(--space-3)", + "margin": WIDTH, + }) + assert ( + frozenset({ + "p", + "px", + "py", + "pt", + "pr", + "pb", + "pl", + "m", + "mx", + "my", + "mt", + "mr", + "mb", + "ml", + "gap", + "spacing", + "gap_x", + "gap_y", + "columns", + "rows", + "direction", + "wrap", + "align", + "justify", + "flow", + }) + == LAYOUT_PROPS + ) + + +@pytest.mark.parametrize( + ("name", "style", "layout", "message"), + [ + ( + "rx.ui.card", + {"& > div": {"color": "red"}}, + None, + ( + 'rx.ui.card: style key "& > div" is a nested selector, which rx.ui ' + "styles do not support. Style the child component directly, or keep " + "rx.card for this element." + ), + ), + ( + "rx.ui.card", + {"paddng": "1em"}, + None, + 'rx.ui.card: unknown CSS property "paddng". Did you mean "padding"?', + ), + ( + "rx.ui.stack", + {"& :where(.rx-Stack)": {"width": "100%"}}, + None, + ( + 'rx.ui.stack: style key "& :where(.rx-Stack)" is a nested selector, ' + "which rx.ui styles do not support. Style the child component " + "directly, or keep rx.stack for this element." + ), + ), + ( + "rx.ui.card", + {":hover > div": {"color": "red"}}, + None, + ( + 'rx.ui.card: style key ":hover > div" is a nested selector, which ' + "rx.ui styles do not support. Style the child component directly, " + "or keep rx.card for this element." + ), + ), + ( + "rx.ui.card", + {"[data-open] span": {"color": "red"}}, + None, + ( + 'rx.ui.card: style key "[data-open] span" is a nested selector, ' + "which rx.ui styles do not support. Style the child component " + "directly, or keep rx.card for this element." + ), + ), + ( + "rx.ui.card", + {".child": {"color": "red"}}, + None, + ( + 'rx.ui.card: style key ".child" is a nested selector, which rx.ui ' + "styles do not support. Style the child component directly, or keep " + "rx.card for this element." + ), + ), + ( + "rx.ui.card", + {"_hover": {"&::after, &::before": {"color": "red"}}}, + None, + ( + 'rx.ui.card: style key "&::after, &::before" is a nested selector, ' + "which rx.ui styles do not support. Style the child component " + "directly, or keep rx.card for this element." + ), + ), + ( + "rx.ui.card", + {"background_colour": "red"}, + None, + ( + 'rx.ui.card: unknown CSS property "background_colour". Did you mean ' + '"background_color"?' + ), + ), + ( + "rx.ui.card", + {"backgroundColr": "red"}, + None, + ( + 'rx.ui.card: unknown CSS property "backgroundColr". Did you mean ' + '"backgroundColor"?' + ), + ), + ( + "rx.ui.card", + {"font-sise": "red"}, + None, + 'rx.ui.card: unknown CSS property "font-sise". Did you mean "font_size"?', + ), + ( + "rx.ui.card", + {"xyzzy": "red"}, + None, + 'rx.ui.card: unknown CSS property "xyzzy".', + ), + ( + "rx.ui.card", + {"_hover": {"colr": "red"}}, + None, + 'rx.ui.card: unknown CSS property "colr". Did you mean "color"?', + ), + ( + "rx.ui.card", + {"_hovr": {"color": "red"}}, + None, + 'rx.ui.card: unknown pseudo-class "_hovr". Did you mean "_hover"?', + ), + ( + "rx.ui.card", + {"_zzzzzz": {"color": "red"}}, + None, + 'rx.ui.card: unknown pseudo-class "_zzzzzz".', + ), + ( + "rx.ui.card", + {"@keyframes spin": {"color": "red"}}, + None, + ( + 'rx.ui.card: style key "@keyframes spin" is an at-rule that rx.ui ' + "styles do not support. Use @media, @container, @supports or " + "@starting-style." + ), + ), + ( + "rx.ui.card", + {"_hover": StyleState.style}, + None, + ( + 'rx.ui.card: style key "_hover" is bound to state, but the styles ' + "under a condition are compiled ahead of time. Bind the values of " + "its properties instead." + ), + ), + ( + "rx.ui.card", + {"_hover": "red"}, + None, + ( + 'rx.ui.card: style key "_hover" is a condition, so its value must be ' + "a dict of styles, not str." + ), + ), + ( + "rx.ui.card", + {"_hover": rx.breakpoints(sm={"color": "red"})}, + None, + ( + 'rx.ui.card: style key "_hover" is a condition, so its value must be ' + "a dict of styles, not Breakpoints." + ), + ), + ( + "rx.ui.card", + {"color": {"default": "red", "hover": "blue"}}, + None, + ( + 'rx.ui.card: style "color" is given a value under "hover", which is ' + 'not a condition. Use "default", a pseudo-class such as ":hover", an ' + 'at-rule such as "@media (min-width: 48em)" or the name of a ' + "breakpoint." + ), + ), + ( + "rx.ui.card", + {"color": {"default": "red", 3: "blue"}}, + None, + ( + 'rx.ui.card: style "color" is given a value under "3", which is ' + 'not a condition. Use "default", a pseudo-class such as ":hover", an ' + 'at-rule such as "@media (min-width: 48em)" or the name of a ' + "breakpoint." + ), + ), + ( + "rx.ui.card", + {"width": ["1px", "2px", "3px", "4px", "5px", "6px", "7px"]}, + None, + ( + 'rx.ui.card: style "width" has 7 responsive values, but there are ' + "only 6 breakpoints." + ), + ), + ( + "rx.ui.card", + {"visibility": True}, + None, + ( + 'rx.ui.card: style "visibility" cannot take a value of type bool. ' + "Use a string, a number, a Var, a responsive list or a dict of " + "conditions." + ), + ), + ( + "rx.ui.card", + {"padding_x": [{"wat"}]}, + None, + ( + 'rx.ui.card: style "padding_x" cannot take a value of type set. Use ' + "a string, a number, a Var, a responsive list or a dict of " + "conditions." + ), + ), + ( + "rx.ui.card", + {3: "red"}, + None, + "rx.ui.card: a style key must be a string, not 3.", + ), + ( + "rx.ui.card", + {"border": WIDTH}, + None, + ( + 'rx.ui.card: style "border" is bound to state, but rx.ui styles ' + "split this shorthand into longhands at compile time. Bind its " + "width, style and color instead." + ), + ), + ( + "rx.ui.card", + {"border_top": "1px 2px"}, + None, + ( + 'rx.ui.card: style "border_top" has the value "1px 2px", which ' + "rx.ui styles cannot split into longhands. Set its width, style and " + "color instead." + ), + ), + ( + "rx.ui.card", + {"border": "1px solid red !important"}, + None, + ( + 'rx.ui.card: style "border" has the value "1px solid red ' + '!important", which rx.ui styles cannot split into longhands. Set ' + "its width, style and color instead." + ), + ), + ( + "rx.ui.card", + {"bg": "url(a.png) center / cover"}, + None, + ( + 'rx.ui.card: style "bg" has the value "url(a.png) center / cover", ' + "which rx.ui styles cannot split into longhands. Set " + "background_color, background_image and its other longhands instead." + ), + ), + ( + "rx.ui.card", + {"background": 3}, + None, + ( + 'rx.ui.card: style "background" has the value "3", which rx.ui ' + "styles cannot split into longhands. Set background_color, " + "background_image and its other longhands instead." + ), + ), + ( + "rx.ui.card", + {"background": SCALE}, + None, + ( + 'rx.ui.card: style "background" is bound to state, but rx.ui styles ' + "split this shorthand into longhands at compile time. Bind " + "background_color, background_image and its other longhands instead." + ), + ), + ( + "rx.ui.card", + {"animation": "spin 1s linear infinite"}, + None, + ( + 'rx.ui.card: style "animation" is a shorthand that rx.ui styles do ' + "not support. Set animation_name, animation_duration and its other " + "longhands instead." + ), + ), + ( + "rx.ui.card", + {"all": "unset"}, + None, + 'rx.ui.card: unknown CSS property "all".', + ), + ( + "rx.ui.flex", + None, + {"gap": SCALE}, + ( + 'rx.ui.flex: layout prop "gap" is bound to state, but its values are ' + 'read at compile time. Bind the "gap" style instead, which takes any ' + "CSS value." + ), + ), + ( + "rx.ui.flex", + None, + {"justify": ["start", SCALE]}, + ( + 'rx.ui.flex: layout prop "justify" is bound to state, but its values ' + 'are read at compile time. Bind the "justify_content" style instead, ' + "which takes any CSS value." + ), + ), + ( + "rx.ui.flex", + None, + {"gapp": "2"}, + 'rx.ui.flex: unknown layout prop "gapp". Did you mean "gap"?', + ), + ], +) +def test_errors(name: str, style: Any, layout: Any, message: str): + """A style that cannot be compiled is refused with what to do about it. + + Args: + name: The display name of the component. + style: The style as written. + layout: The layout props. + message: The whole error message. + """ + with pytest.raises(StyleError) as error: + lower(name, style, layout) + assert str(error.value) == message + assert isinstance(error.value, ValueError) + + +def test_layers_merge_by_property_and_the_last_one_wins(): + """A later style replaces a property, or adds conditions to it.""" + props, replaced = lower_layer( + "rx.ui.card", + { + "color": {"default": "black", ":hover": "blue"}, + "width": "1px", + "outline_color": "red", + "margin_top": "1px", + "top": {":hover": {"default": "1px", XS: "2px"}}, + "left": {":hover": {"default": "1px", XS: "2px"}}, + "opacity": 1, + }, + ) + assert replaced == () + later = lower_layer( + "rx.ui.card", + { + "color": "green", + "_focus": {"width": "2px"}, + "outline": WIDTH, + "margin": "var(--gap)", + "_hover": {"left": "3px", "_active": {"top": "4px"}}, + "opacity": None, + }, + ) + assert later[1] == (*_REPLACES["outline"], *_REPLACES["margin"]) + apply_layer(props, later) + assert finish(props) == Lowered({ + "color": "green", + "width": {"default": "1px", ":focus": "2px"}, + "outline": WIDTH, + "margin": "var(--gap)", + "top": {":hover": {"default": "1px", XS: "2px", ":active": "4px"}}, + "left": {":hover": "3px"}, + }) + assert finish({"color": None}) == Lowered({}) + assert finish({"color": None, "top": 0}, unset=True) == Lowered({ + "color": None, + "top": 0, + }) + + +def test_lowered_styles_compare_and_hash_by_what_they_compile_to(): + """Equal styles are one key, whatever the order of their properties.""" + first = lower("rx.ui.card", {"color": "red", "width": WIDTH, "_hover": {"top": 0}}) + second = lower("rx.ui.box", {"width": WIDTH, "_hover": {"top": 0}, "color": "red"}) + assert first == second + assert hash(first) == hash(second) + assert len({first, second}) == 1 + different = [ + lower("rx.ui.card", {"color": "red", "width": WIDTH, "_hover": {"top": 1}}), + lower("rx.ui.card", {"color": "red", "width": SCALE, "_hover": {"top": 0}}), + lower("rx.ui.card", {"color": "red", "width": WIDTH, "_focus": {"top": 0}}), + lower("rx.ui.card", {"color": "red", "width": WIDTH}), + Lowered(dict(first.style), (RUBY,)), + Lowered(dict(first.style), (), StyleState.style), + ] + assert [style == first for style in different] == [False] * 6 + assert first != dict(first.style) + assert lower("rx.ui.card", {}) is lower("rx.ui.card", None) + assert repr(lower("rx.ui.card", {"color": rx.color("ruby", 9)})) == ( + "Lowered({'color': 'var(--ruby-9)'}, " + "('$/reflex-ui/colors/ruby.stylex.js',), None)" + ) + + +def test_var_values_are_vars(): + """A Var in a lowered style is the Var that was written.""" + value = lower("rx.ui.card", {"width": WIDTH}).style["width"] + assert isinstance(value, Var) + assert value.equals(WIDTH) diff --git a/tests/units/reflex_components_ui/style/test_merge.py b/tests/units/reflex_components_ui/style/test_merge.py new file mode 100644 index 00000000000..2a5cdad8429 --- /dev/null +++ b/tests/units/reflex_components_ui/style/test_merge.py @@ -0,0 +1,508 @@ +"""Tests for merging the style table of a component with a user's style.""" + +from typing import Any + +import pytest +from reflex_base.breakpoints import breakpoints_values, set_breakpoints +from reflex_base.vars.base import LiteralVar +from reflex_components_ui.style.lower import Lowered, StyleError +from reflex_components_ui.style.merge import ( + Alternatives, + ComponentStyles, + Merged, + merge, +) + +import reflex as rx + +RUBY = "$/reflex-ui/colors/ruby.stylex.js" +XS = "@media screen and (min-width: 30em)" + + +class MergeState(rx.State): + """State whose fields are bound to props and styles.""" + + variant: rx.Field[str] = rx.field("solid") + size: rx.Field[str] = rx.field("1") + loading: rx.Field[bool] = rx.field(False) + style: rx.Field[dict[str, str]] = rx.field({}) + + +VARIANT = MergeState.variant +SIZE = MergeState.size +LOADING = MergeState.loading + +BUTTON: ComponentStyles = { + "base": { + "display": "inline-flex", + "color": "black", + "margin_top": "1px", + "outline_width": "1px", + }, + "variants": { + "variant": { + "solid": { + "background_color": { + "default": "var(--accent-9)", + ":hover": "var(--accent-10)", + }, + "color": "white", + }, + "soft": {"background_color": rx.color("ruby", 3)}, + "ghost": {"outline": "none"}, + }, + "size": { + "1": {"height": "var(--space-5)"}, + "2": {"height": "var(--space-6)", "_hover": {"color": "gray"}}, + }, + "loading": {"true": {"opacity": 0.5}}, + }, + "compound": [ + {"props": {"variant": "solid", "size": "2"}, "style": {"font_weight": "700"}}, + {"props": {"loading": "true"}, "style": {"cursor": "wait"}}, + ], + "parts": { + "icon": { + "base": {"width": "1em"}, + "variants": {"size": {"2": {"width": "2em"}}}, + "parts": {"dot": {"base": {"top": 0}}}, + }, + "label": {"base": {"flex_grow": 1}}, + }, +} + +BASE = { + "display": "inline-flex", + "color": "black", + "marginTop": "1px", + "outlineWidth": "1px", +} +SOLID_BACKGROUND = {"default": "var(--accent-9)", ":hover": "var(--accent-10)"} +DOT = Merged(Lowered({"top": 0})) +LABEL = Merged(Lowered({"flexGrow": 1})) +SMALL_PARTS = { + "icon": Merged(Lowered({"width": "1em"}), (), {"dot": DOT}), + "label": LABEL, +} +LARGE_PARTS = { + "icon": Merged(Lowered({"width": "2em"}), (), {"dot": DOT}), + "label": LABEL, +} + + +@pytest.mark.parametrize( + ("props", "style", "expected", "parts"), + [ + (None, None, BASE, SMALL_PARTS), + ({}, {}, BASE, SMALL_PARTS), + ( + {"variant": "unknown", "size": None, "disabled": True}, + None, + BASE, + SMALL_PARTS, + ), + ( + {"variant": "solid", "size": "1"}, + None, + { + **BASE, + "backgroundColor": SOLID_BACKGROUND, + "color": "white", + "height": "var(--space-5)", + }, + SMALL_PARTS, + ), + ( + {"variant": "solid", "size": "2", "loading": True}, + None, + { + **BASE, + "backgroundColor": SOLID_BACKGROUND, + "color": {"default": "white", ":hover": "gray"}, + "height": "var(--space-6)", + "opacity": 0.5, + "fontWeight": "700", + "cursor": "wait", + }, + LARGE_PARTS, + ), + ( + {"variant": "ghost", "size": 2, "loading": False}, + None, + { + "display": "inline-flex", + "color": {"default": "black", ":hover": "gray"}, + "marginTop": "1px", + "outline": "none", + "height": "var(--space-6)", + }, + LARGE_PARTS, + ), + ( + {"variant": LiteralVar.create("soft"), "loading": LiteralVar.create(True)}, + None, + { + **BASE, + "backgroundColor": "var(--ruby-3)", + "opacity": 0.5, + "cursor": "wait", + }, + SMALL_PARTS, + ), + ( + {"variant": "solid", "size": "2"}, + { + "color": "pink", + "_hover": {"background_color": "red"}, + "_focus": {"height": "1px"}, + "margin": "0", + "font_weight": None, + "width": ["1px", "2px"], + }, + { + "display": "inline-flex", + "color": "pink", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "outlineWidth": "1px", + "backgroundColor": {"default": "var(--accent-9)", ":hover": "red"}, + "height": {"default": "var(--space-6)", ":focus": "1px"}, + "width": {"default": "1px", XS: "2px"}, + }, + LARGE_PARTS, + ), + ( + {"variant": "solid"}, + { + "background_color": "red", + "outline": "2px solid", + "margin": MergeState.size, + }, + { + "display": "inline-flex", + "color": "white", + "backgroundColor": "red", + "outline": "2px solid", + "margin": SIZE, + }, + SMALL_PARTS, + ), + ], +) +def test_merge_order(props: Any, style: Any, expected: dict[str, Any], parts: Any): + """Base, variants, compound styles and the user style merge in that order. + + Args: + props: The props of the element. + style: The style the user wrote. + expected: The lowered properties of the element. + parts: The merged styles of its inner elements. + """ + merged = merge("rx.ui.button", BUTTON, props, style) + imports = (RUBY,) if expected.get("backgroundColor") == "var(--ruby-3)" else () + assert merged == Merged(Lowered(expected, imports), (), parts) + assert merged.style.imports == imports + assert merged.dynamic == () + assert list(merged.parts) == ["icon", "label"] + + +def test_layout_props_merge_between_the_table_and_the_style(): + """A layout prop wins over the table and loses to the user style.""" + assert merge( + "rx.ui.button", + BUTTON, + {"size": "1"}, + {"margin_left": "auto"}, + {"m": "2", "gap": "1"}, + ) == Merged( + Lowered({ + "display": "inline-flex", + "color": "black", + "marginTop": "var(--space-2)", + "marginRight": "var(--space-2)", + "marginBottom": "var(--space-2)", + "marginLeft": "auto", + "outlineWidth": "1px", + "height": "var(--space-5)", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + }), + (), + SMALL_PARTS, + ) + + +def test_whole_dict_var_style_is_carried_with_the_table_styles(): + """A Var holding the user style leaves the table styles compiled.""" + merged = merge("rx.ui.button", BUTTON, {"size": "1"}, MergeState.style) + assert merged == Merged( + Lowered({**BASE, "height": "var(--space-5)"}, (), MergeState.style), + (), + SMALL_PARTS, + ) + assert merged != merge("rx.ui.button", BUTTON, {"size": "1"}) + + +def test_identical_inputs_give_one_hashable_result(): + """The emitter can share a declaration between elements that match.""" + plain = merge("rx.ui.button", BUTTON, {"variant": "solid", "size": "1"}) + assert merge("rx.ui.button", BUTTON, {"size": "1", "variant": "solid"}) is plain + assert merge("rx.ui.button", BUTTON, {"size": 1, "variant": "solid"}) is plain + + styled = [ + merge("rx.ui.button", BUTTON, {"size": "1"}, {"color": SIZE, "top": 0}), + merge("rx.ui.button", BUTTON, {"size": "1"}, {"top": 0, "color": SIZE}), + merge("rx.ui.button", BUTTON, {"size": SIZE}, {"color": SIZE, "top": 0}), + merge("rx.ui.button", BUTTON, {"size": SIZE}, {"color": SIZE, "top": 0}), + ] + assert styled[0] == styled[1] + assert styled[2] == styled[3] + assert styled[0] != styled[2] + assert styled[0] != plain + assert styled[0] != styled[0].style + assert [hash(merged) for merged in styled[:2]] == [hash(styled[0])] * 2 + assert len(set(styled)) == 2 + assert styled[2].dynamic[0] == styled[3].dynamic[0] + assert styled[2].dynamic[0] != styled[2] + assert len({styled[2].dynamic[0], styled[3].dynamic[0]}) == 1 + + +def test_state_bound_variant_returns_every_value_unresolved(): + """A prop bound to state gives one alternative per value of its variant.""" + merged = merge( + "rx.ui.button", + BUTTON, + {"variant": VARIANT, "size": "2"}, + {"color": "pink", "_hover": {"background_color": "red"}}, + ) + assert merged == Merged( + Lowered({ + **BASE, + "color": "pink", + "height": "var(--space-6)", + "backgroundColor": {":hover": "red"}, + }), + ( + Alternatives( + ("variant",), + (VARIANT,), + { + ("solid",): Lowered({ + "backgroundColor": { + "default": "var(--accent-9)", + ":hover": "red", + }, + "fontWeight": "700", + }), + ("soft",): Lowered( + { + "backgroundColor": { + "default": "var(--ruby-3)", + ":hover": "red", + } + }, + (RUBY,), + ), + ("ghost",): Lowered({"outline": "none", "outlineWidth": None}), + }, + ), + ), + LARGE_PARTS, + ) + assert merged.dynamic[0].props == ("variant",) + assert merged.dynamic[0].vars[0].equals(VARIANT) + assert list(merged.dynamic[0].values) == [("solid",), ("soft",), ("ghost",)] + assert merged.dynamic[0].values["ghost",].style == { + "outline": "none", + "outlineWidth": None, + } + + +def test_independent_state_bound_props_are_separate_alternatives(): + """Props that set different properties are picked one by one.""" + assert merge( + "rx.ui.button", BUTTON, {"variant": "soft", "size": SIZE, "loading": LOADING} + ) == Merged( + Lowered({**BASE, "backgroundColor": "var(--ruby-3)"}, (RUBY,)), + ( + Alternatives( + ("size",), + (SIZE,), + { + ("1",): Lowered({"height": "var(--space-5)"}), + ("2",): Lowered({ + "height": "var(--space-6)", + "color": {"default": "black", ":hover": "gray"}, + }), + }, + ), + Alternatives( + ("loading",), + (LOADING,), + {("true",): Lowered({"opacity": 0.5, "cursor": "wait"})}, + ), + ), + { + "icon": Merged( + Lowered({"width": "1em"}), + ( + Alternatives( + ("size",), (SIZE,), {("2",): Lowered({"width": "2em"})} + ), + ), + {"dot": DOT}, + ), + "label": LABEL, + }, + ) + + +def test_state_bound_props_that_depend_on_each_other_are_one_alternative(): + """Props that share a property or a compound style are picked together.""" + solid = {"backgroundColor": SOLID_BACKGROUND} + soft = Lowered({"backgroundColor": "var(--ruby-3)"}, (RUBY,)) + ghost = {"outline": "none", "outlineWidth": None} + assert merge( + "rx.ui.button", BUTTON, {"variant": VARIANT, "size": SIZE} + ).dynamic == ( + Alternatives( + ("variant", "size"), + (VARIANT, SIZE), + { + ("solid", "1"): Lowered({ + **solid, + "color": "white", + "height": "var(--space-5)", + }), + ("solid", "2"): Lowered({ + **solid, + "color": {"default": "white", ":hover": "gray"}, + "height": "var(--space-6)", + "fontWeight": "700", + }), + ("soft", "1"): Lowered( + {**soft.style, "height": "var(--space-5)"}, (RUBY,) + ), + ("soft", "2"): Lowered( + { + **soft.style, + "height": "var(--space-6)", + "color": {"default": "black", ":hover": "gray"}, + }, + (RUBY,), + ), + ("ghost", "1"): Lowered({**ghost, "height": "var(--space-5)"}), + ("ghost", "2"): Lowered({ + **ghost, + "height": "var(--space-6)", + "color": {"default": "black", ":hover": "gray"}, + }), + }, + ), + ) + + +def test_state_bound_prop_that_only_a_compound_style_reads(): + """The values a compound style names are the alternatives of its prop.""" + table: ComponentStyles = { + "base": {"color": "black"}, + "variants": {"size": {"1": {"top": 0}}}, + "compound": [ + {"props": {"size": "1", "tone": "loud"}, "style": {"color": "red"}}, + {"props": {"tone": "quiet"}, "style": {"color": "gray"}}, + ], + } + tone = MergeState.variant + assert merge("rx.ui.badge", table, {"size": "1", "tone": tone}) == Merged( + Lowered({"color": "black", "top": 0}), + ( + Alternatives( + ("tone",), + (tone,), + { + ("loud",): Lowered({"color": "red"}), + ("quiet",): Lowered({"color": "gray"}), + }, + ), + ), + ) + assert merge("rx.ui.badge", table, {"tone": tone}, {"color": "blue"}) == Merged( + Lowered({"color": "blue"}) + ) + assert repr(merge("rx.ui.badge", table, {"tone": "quiet"})) == ( + "Merged(Lowered({'color': 'gray'}, (), None), (), {})" + ) + assert repr(Alternatives(("tone",), (), {("loud",): Lowered({"top": 0})})) == ( + "Alternatives(('tone',), (), {('loud',): Lowered({'top': 0}, (), None)})" + ) + + +def test_table_is_lowered_again_when_the_breakpoints_change(): + """A table lowered before `set_breakpoints` does not keep the old widths.""" + table: ComponentStyles = {"base": {"width": ["1px", "2px"]}} + before = merge("rx.ui.box", table) + original = tuple(breakpoints_values) + set_breakpoints(("10px", "20px", "30px", "40px", "50px")) + try: + changed = merge("rx.ui.box", table) + finally: + set_breakpoints(original) # pyright: ignore [reportArgumentType] + assert before == Merged(Lowered({"width": {"default": "1px", XS: "2px"}})) + assert changed == Merged( + Lowered({ + "width": {"default": "1px", "@media screen and (min-width: 10px)": "2px"} + }) + ) + assert merge("rx.ui.box", table) == before + + +@pytest.mark.parametrize( + ("table", "style", "message"), + [ + ( + {"variant": {"size": {"1": {"top": 0}}}}, + None, + ( + 'rx.ui.card: unknown key "variant" in a style table. Use "base", ' + '"variants", "compound" or "parts".' + ), + ), + ( + {"variants": {"size": {"1": {"heght": "1em"}}}}, + None, + 'rx.ui.card: unknown CSS property "heght". Did you mean "height"?', + ), + ( + {"parts": {"thumb": {"base": {"& > div": {"top": 0}}}}}, + None, + ( + 'rx.ui.card: style key "& > div" is a nested selector, which rx.ui ' + "styles do not support. Style the child component directly, or keep " + "rx.card for this element." + ), + ), + ( + {"compound": [{"props": {"size": "1"}, "style": {"colr": "red"}}]}, + None, + 'rx.ui.card: unknown CSS property "colr". Did you mean "color"?', + ), + ( + {"base": {"top": 0}}, + {"paddng": "1em"}, + 'rx.ui.card: unknown CSS property "paddng". Did you mean "padding"?', + ), + ], +) +def test_errors(table: Any, style: Any, message: str): + """A table or a style that cannot be compiled is refused in full. + + Args: + table: The style table. + style: The style the user wrote. + message: The whole error message. + """ + with pytest.raises(StyleError) as error: + merge("rx.ui.card", table, None, style) + assert str(error.value) == message From 0cfa6b5f2620ab9045322e41c038f95bef3e84df Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 10:50:19 +0000 Subject: [PATCH 12/26] Generate the rx.ui tokens, color scales and themes from Radix Themes Every custom property Radix Themes defines becomes a StyleX variable with the same name and value, generated from the token stylesheet of the version the Radix components install. A color is one light-dark() value with a display-P3 variant, so an appearance is the color-scheme of an element; accent, gray, radius, scaling and panel are createTheme classes, one module per accent and per gray so an app carries only what it imports. A sweep in headless Chromium compares every custom property under these modules with @radix-ui/themes and its Theme component: part of it in npm test, the whole product of the theme props in npm run sweep. Claude-Session: https://claude.ai/code/session_014AwvTMTA184ecs3JHWuggN --- .github/workflows/unit_tests.yml | 2 + packages/reflex-components-ui/README.md | 60 + .../reflex-components-ui/js/eslint.config.js | 6 + .../reflex-components-ui/js/package-lock.json | 2305 +++++++++++++++-- packages/reflex-components-ui/js/package.json | 10 + .../js/scripts/generate.js | 40 +- .../js/scripts/radix-tokens.js | 803 ++++++ .../js/src/colors/amber.stylex.js | 209 ++ .../js/src/colors/black.stylex.js | 90 + .../js/src/colors/blue.stylex.js | 208 ++ .../js/src/colors/bronze.stylex.js | 208 ++ .../js/src/colors/brown.stylex.js | 208 ++ .../js/src/colors/crimson.stylex.js | 208 ++ .../js/src/colors/cyan.stylex.js | 208 ++ .../js/src/colors/gold.stylex.js | 208 ++ .../js/src/colors/grass.stylex.js | 208 ++ .../js/src/colors/green.stylex.js | 208 ++ .../js/src/colors/indigo.stylex.js | 208 ++ .../js/src/colors/iris.stylex.js | 208 ++ .../js/src/colors/jade.stylex.js | 208 ++ .../js/src/colors/lime.stylex.js | 209 ++ .../js/src/colors/mauve.stylex.js | 209 ++ .../js/src/colors/mint.stylex.js | 209 ++ .../js/src/colors/olive.stylex.js | 209 ++ .../js/src/colors/orange.stylex.js | 208 ++ .../js/src/colors/pink.stylex.js | 208 ++ .../js/src/colors/plum.stylex.js | 208 ++ .../js/src/colors/purple.stylex.js | 208 ++ .../js/src/colors/red.stylex.js | 208 ++ .../js/src/colors/ruby.stylex.js | 208 ++ .../js/src/colors/sage.stylex.js | 209 ++ .../js/src/colors/sand.stylex.js | 209 ++ .../js/src/colors/sky.stylex.js | 209 ++ .../js/src/colors/slate.stylex.js | 209 ++ .../js/src/colors/teal.stylex.js | 208 ++ .../js/src/colors/tomato.stylex.js | 208 ++ .../js/src/colors/violet.stylex.js | 208 ++ .../js/src/colors/white.stylex.js | 90 + .../js/src/colors/yellow.stylex.js | 209 ++ .../js/src/themes/accent/amber.js | 37 + .../js/src/themes/accent/blue.js | 37 + .../js/src/themes/accent/bronze.js | 37 + .../js/src/themes/accent/brown.js | 37 + .../js/src/themes/accent/crimson.js | 37 + .../js/src/themes/accent/cyan.js | 37 + .../js/src/themes/accent/gold.js | 37 + .../js/src/themes/accent/grass.js | 37 + .../js/src/themes/accent/gray.js | 37 + .../js/src/themes/accent/green.js | 37 + .../js/src/themes/accent/indigo.js | 37 + .../js/src/themes/accent/iris.js | 37 + .../js/src/themes/accent/jade.js | 37 + .../js/src/themes/accent/lime.js | 37 + .../js/src/themes/accent/mint.js | 37 + .../js/src/themes/accent/orange.js | 37 + .../js/src/themes/accent/pink.js | 37 + .../js/src/themes/accent/plum.js | 37 + .../js/src/themes/accent/purple.js | 37 + .../js/src/themes/accent/red.js | 37 + .../js/src/themes/accent/ruby.js | 37 + .../js/src/themes/accent/sky.js | 37 + .../js/src/themes/accent/teal.js | 37 + .../js/src/themes/accent/tomato.js | 37 + .../js/src/themes/accent/violet.js | 37 + .../js/src/themes/accent/yellow.js | 37 + .../js/src/themes/focus.js | 7 + .../js/src/themes/gray/gray.js | 215 ++ .../js/src/themes/gray/mauve.js | 37 + .../js/src/themes/gray/olive.js | 37 + .../js/src/themes/gray/sage.js | 37 + .../js/src/themes/gray/sand.js | 37 + .../js/src/themes/gray/slate.js | 37 + .../js/src/themes/panel.js | 15 + .../js/src/themes/radius.js | 35 + .../js/src/themes/scaling.js | 25 + .../js/src/themes/scope.js | 19 + .../js/src/themes/theme.js | 32 + .../js/src/tokens/accent.stylex.js | 34 + .../js/src/tokens/color.stylex.js | 26 + .../js/src/tokens/cursor.stylex.js | 15 + .../js/src/tokens/focus.stylex.js | 32 + .../js/src/tokens/gray.stylex.js | 34 + .../js/src/tokens/panel.stylex.js | 8 + .../js/src/tokens/radius.stylex.js | 20 + .../js/src/tokens/scaling.stylex.js | 7 + .../js/src/tokens/shadow.stylex.js | 15 + .../js/src/tokens/space.stylex.js | 17 + .../js/src/tokens/typography.stylex.js | 92 + .../expected/js/src/colors/black.stylex.js | 7 + .../expected/js/src/colors/red.stylex.js | 19 + .../expected/js/src/colors/slate.stylex.js | 16 + .../expected/js/src/themes/accent/gray.js | 12 + .../expected/js/src/themes/accent/red.js | 12 + .../expected/js/src/themes/focus.js | 7 + .../expected/js/src/themes/gray/gray.js | 22 + .../expected/js/src/themes/gray/slate.js | 12 + .../expected/js/src/themes/panel.js | 15 + .../expected/js/src/themes/radius.js | 15 + .../expected/js/src/themes/scaling.js | 13 + .../expected/js/src/themes/scope.js | 19 + .../expected/js/src/themes/theme.js | 27 + .../expected/js/src/tokens/accent.stylex.js | 9 + .../expected/js/src/tokens/color.stylex.js | 22 + .../expected/js/src/tokens/cursor.stylex.js | 7 + .../expected/js/src/tokens/focus.stylex.js | 9 + .../expected/js/src/tokens/gray.stylex.js | 9 + .../expected/js/src/tokens/panel.stylex.js | 8 + .../expected/js/src/tokens/radius.stylex.js | 14 + .../expected/js/src/tokens/scaling.stylex.js | 7 + .../expected/js/src/tokens/shadow.stylex.js | 11 + .../expected/js/src/tokens/space.stylex.js | 9 + .../js/src/tokens/typography.stylex.js | 13 + .../src/reflex_components_ui/_radix_tokens.py | 159 ++ .../js/tests/fixtures/radix-tokens/tokens.css | 196 ++ .../js/tests/harness/base.css | 9 + .../js/tests/harness/browser.js | 184 ++ .../js/tests/harness/build.js | 40 + .../js/tests/harness/configs.js | 90 + .../js/tests/harness/exceptions.js | 36 + .../js/tests/harness/ours.html | 10 + .../js/tests/harness/ours.js | 101 + .../js/tests/harness/page.js | 95 + .../js/tests/harness/probe.js | 114 + .../js/tests/harness/radix.html | 10 + .../js/tests/harness/radix.js | 42 + .../js/tests/harness/size/accents.js | 33 + .../js/tests/harness/size/baseline.js | 11 + .../js/tests/harness/size/theme.js | 32 + .../js/tests/harness/size/tokens.js | 14 + .../js/tests/harness/sweep.js | 27 + .../js/tests/radix-tokens.test.js | 211 ++ .../js/tests/size.test.js | 71 + .../js/tests/themes.test.js | 312 +++ .../js/tsconfig.node.json | 4 +- .../news/+tokens-themes.feature.md | 1 + .../src/reflex_components_ui/_radix_tokens.py | 1411 ++++++++++ pyproject.toml | 3 +- .../test__radix_tokens.py | 209 ++ .../reflex_components_ui/test_js_package.py | 27 + 139 files changed, 15060 insertions(+), 157 deletions(-) create mode 100644 packages/reflex-components-ui/js/scripts/radix-tokens.js create mode 100644 packages/reflex-components-ui/js/src/colors/amber.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/black.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/blue.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/bronze.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/brown.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/crimson.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/cyan.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/gold.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/grass.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/green.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/indigo.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/iris.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/jade.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/lime.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/mauve.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/mint.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/olive.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/orange.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/pink.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/plum.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/purple.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/red.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/ruby.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/sage.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/sand.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/sky.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/slate.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/teal.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/tomato.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/violet.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/white.stylex.js create mode 100644 packages/reflex-components-ui/js/src/colors/yellow.stylex.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/amber.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/blue.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/bronze.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/brown.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/crimson.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/cyan.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/gold.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/grass.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/gray.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/green.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/indigo.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/iris.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/jade.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/lime.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/mint.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/orange.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/pink.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/plum.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/purple.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/red.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/ruby.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/sky.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/teal.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/tomato.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/violet.js create mode 100644 packages/reflex-components-ui/js/src/themes/accent/yellow.js create mode 100644 packages/reflex-components-ui/js/src/themes/focus.js create mode 100644 packages/reflex-components-ui/js/src/themes/gray/gray.js create mode 100644 packages/reflex-components-ui/js/src/themes/gray/mauve.js create mode 100644 packages/reflex-components-ui/js/src/themes/gray/olive.js create mode 100644 packages/reflex-components-ui/js/src/themes/gray/sage.js create mode 100644 packages/reflex-components-ui/js/src/themes/gray/sand.js create mode 100644 packages/reflex-components-ui/js/src/themes/gray/slate.js create mode 100644 packages/reflex-components-ui/js/src/themes/panel.js create mode 100644 packages/reflex-components-ui/js/src/themes/radius.js create mode 100644 packages/reflex-components-ui/js/src/themes/scaling.js create mode 100644 packages/reflex-components-ui/js/src/themes/scope.js create mode 100644 packages/reflex-components-ui/js/src/themes/theme.js create mode 100644 packages/reflex-components-ui/js/src/tokens/accent.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/color.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/cursor.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/focus.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/gray.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/panel.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/radius.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/scaling.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/shadow.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/space.stylex.js create mode 100644 packages/reflex-components-ui/js/src/tokens/typography.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/black.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/red.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/slate.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/gray.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/red.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/focus.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/gray.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/slate.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/panel.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/radius.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scaling.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scope.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/theme.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/accent.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/color.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/cursor.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/focus.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/gray.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/panel.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/radius.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/scaling.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/shadow.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/space.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/typography.stylex.js create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/src/reflex_components_ui/_radix_tokens.py create mode 100644 packages/reflex-components-ui/js/tests/fixtures/radix-tokens/tokens.css create mode 100644 packages/reflex-components-ui/js/tests/harness/base.css create mode 100644 packages/reflex-components-ui/js/tests/harness/browser.js create mode 100644 packages/reflex-components-ui/js/tests/harness/build.js create mode 100644 packages/reflex-components-ui/js/tests/harness/configs.js create mode 100644 packages/reflex-components-ui/js/tests/harness/exceptions.js create mode 100644 packages/reflex-components-ui/js/tests/harness/ours.html create mode 100644 packages/reflex-components-ui/js/tests/harness/ours.js create mode 100644 packages/reflex-components-ui/js/tests/harness/page.js create mode 100644 packages/reflex-components-ui/js/tests/harness/probe.js create mode 100644 packages/reflex-components-ui/js/tests/harness/radix.html create mode 100644 packages/reflex-components-ui/js/tests/harness/radix.js create mode 100644 packages/reflex-components-ui/js/tests/harness/size/accents.js create mode 100644 packages/reflex-components-ui/js/tests/harness/size/baseline.js create mode 100644 packages/reflex-components-ui/js/tests/harness/size/theme.js create mode 100644 packages/reflex-components-ui/js/tests/harness/size/tokens.js create mode 100644 packages/reflex-components-ui/js/tests/harness/sweep.js create mode 100644 packages/reflex-components-ui/js/tests/radix-tokens.test.js create mode 100644 packages/reflex-components-ui/js/tests/size.test.js create mode 100644 packages/reflex-components-ui/js/tests/themes.test.js create mode 100644 packages/reflex-components-ui/news/+tokens-themes.feature.md create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/_radix_tokens.py create mode 100644 tests/units/reflex_components_ui/test__radix_tokens.py diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 3c6f49d4d8f..004885ccfad 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -215,6 +215,8 @@ jobs: - run: npm run lint - run: npm run typecheck - run: npm run generate:check + # The tests of the tokens and themes read computed styles in a browser. + - run: npx playwright install --with-deps --only-shell chromium - run: npm test unit-tests-macos: diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 6c8e0cb9850..924b29c4644 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -16,10 +16,16 @@ pip install 'reflex[ui]' ``` src/reflex_components_ui/ the python package: the rx.ui namespace + _radix_tokens.py generated: the modules below and what they define js/ the javascript package, with its own tooling src/ what ships: copied into an app at .web/reflex-ui/ + colors/ generated: one module for each Radix color scale + tokens/ generated: space, radius, typography, shadow, ... + themes/ generated: accent/, gray/, radius, scaling, ... tests/ vitest + harness/ the pages the live tests build and open in Chromium scripts/generate.js writes and checks the generated files + scripts/radix-tokens.js the generator of the colors, tokens and themes hatch_build.py embeds js/src in the wheel ``` @@ -39,6 +45,7 @@ uv run python scripts/make_pyi.py # regenerate the npm --prefix packages/reflex-components-ui/js ci # install the javascript tooling npm --prefix packages/reflex-components-ui/js run check # lint, type-check, generated files, tests: what CI runs npm --prefix packages/reflex-components-ui/js run generate # rewrite the generated files +npm --prefix packages/reflex-components-ui/js run sweep # the whole token sweep against Radix Themes, about four minutes ``` `run check` is `run lint` (ESLint), `run typecheck` (`tsc` over the JSDoc, @@ -61,5 +68,58 @@ their own. generator produces. - A lint rule in `js/src` cannot be switched off with a comment. +## Tokens and themes + +Every design token is a CSS custom property with the name and the value +[Radix Themes](https://www.radix-ui.com/themes) gives it, so that a page can +mix these components with the Radix ones and show one palette. +`js/scripts/radix-tokens.js` generates them from the token stylesheet of the +`@radix-ui/themes` the Radix components install, as StyleX modules: a module +adds its CSS to an app only when something imports it. + +- `colors/.stylex.js` defines a color scale. A color is one + `light-dark()` value, with a display-P3 one for the screens that have it. +- `tokens/*.stylex.js` define the other tokens, and the variables a theme sets: + `accent`, `gray`, `focus`, `scaling`, `radiusFactor` and `panel`. No accent + and no gray is defined outside a theme. +- `themes/accent/.js`, `themes/gray/.js`, `themes/radius.js`, + `themes/scaling.js` and `themes/panel.js` export a StyleX theme for each value + of a prop of the Radix `Theme`. They are `.js` and not `.stylex.js`: StyleX + keeps that extension for modules that only define variables. +- `themes/scope.js` and `themes/focus.js` are what make an element a theme. A + token such as `--space-1` reads `--scaling`, and a custom property takes the + value it reads from the element it is declared on. A StyleX theme declares + its whole group again on its element, so a scope theme overrides nothing and + is applied wherever a theme changes what the group reads. An accent on a + single element needs `focusScope` only. +- `themes/theme.js` holds the styles of a theme element itself: `root`, + `background`, and `light` and `dark`, which set `color-scheme`. + +An appearance is the `color-scheme` of an element. The stylesheet every page +loads has to set it for `html.light` and `html.dark`, as +`js/tests/harness/base.css` does for the tests; a nested appearance is +`theme.light` or `theme.dark` on its element. Nothing else changes between the +two, and nothing here depends on being at the root: a popover or a dialog in +the top layer inherits from where it is declared. + +Two things differ from Radix, both by construction: + +- `--shadow-1` to `--shadow-6` list the layers of both appearances, and a layer + the current appearance does not have is `transparent`. It paints the same. +- A nested theme that sets a gray while it inherits the gray accent has to name + the gray accent again. Radix knows what a nested `Theme` inherits; the + cascade does not. + +`npm test` reads every custom property Radix defines under both, in headless +Chromium, for each value of each theme prop. `npm run sweep` does it for the +whole product of accent, gray, appearance, radius and scaling: 10,556 themes on +an sRGB screen and on a display-P3 one. A value that is allowed to differ is +listed with its reason in `js/tests/harness/exceptions.js`. The tests need +Chromium: `npx playwright install chromium` in `js/`. + +To move to another version of Radix Themes, change `RADIX_THEMES_PACKAGE` in +`reflex-components-radix` and the pin in `js/package.json` together, then run +`npm run generate` and `npm run sweep`. + `js/tests/lint.test.js` lints a file that breaks each rule, so a rule that stops matching fails a test. diff --git a/packages/reflex-components-ui/js/eslint.config.js b/packages/reflex-components-ui/js/eslint.config.js index f4028785859..2cde2c36264 100644 --- a/packages/reflex-components-ui/js/eslint.config.js +++ b/packages/reflex-components-ui/js/eslint.config.js @@ -94,6 +94,12 @@ export default [ files: ["src/*.js"], languageOptions: { globals: globals.node }, }, + { + // The pages the live tests build and open in a browser, and the test + // whose callbacks run in them. + files: ["tests/harness/**", "tests/themes.test.js"], + languageOptions: { globals: { ...globals.node, ...globals.browser } }, + }, { files: ["tests/behaviors/**"], languageOptions: { globals: globals.browser }, diff --git a/packages/reflex-components-ui/js/package-lock.json b/packages/reflex-components-ui/js/package-lock.json index f30453c34fe..d44c6bf6b0d 100644 --- a/packages/reflex-components-ui/js/package-lock.json +++ b/packages/reflex-components-ui/js/package-lock.json @@ -14,12 +14,21 @@ }, "devDependencies": { "@eslint/js": "10.0.1", + "@radix-ui/themes": "3.3.0", "@stylexjs/eslint-plugin": "0.19.2", "@types/node": "22.20.5", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", "eslint": "10.15.0", "globals": "17.14.0", "jsdom": "^26.1.0", + "lightningcss": "1.33.0", + "playwright": "1.63.0", + "postcss": "8.5.33", + "react": "19.3.1", + "react-dom": "19.3.1", "typescript": "5.9.3", + "vite": "8.3.4", "vitest": "^5.1.0" } }, @@ -471,6 +480,40 @@ "url": "https://github.com/sponsors/JounQin" } }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.10.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", @@ -599,6 +642,48 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "dev": true, + "license": "MIT" + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -701,61 +786,1679 @@ "node": ">=6.0.0" } }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", - "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@keyv/bigmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.4.0", + "hookified": "^1.15.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.6.0" + } + }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@radix-ui/colors": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@radix-ui/colors/-/colors-3.0.0.tgz", + "integrity": "sha512-FUOsGBkHrYJwCSEtWRCIfQbZG7q1e6DgxCIOe1SUQzDe/7rXXeA47s8yCn6fuTNQAj1Zq4oTFi9Yjp3wzElcxg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@radix-ui/number": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.3.tgz", + "integrity": "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@radix-ui/react-accessible-icon": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accessible-icon/-/react-accessible-icon-1.2.0.tgz", + "integrity": "sha512-BB4+HHkFl3HipEAhm/mLhrpXV+2kRX7MvY4AaImUcQVeWQt5KhV1JEByNs8NGfJOcr95RcQGijt9+OrCo68xGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-accordion": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.3.1.tgz", + "integrity": "sha512-lCZ6sbGS/7WO0j84yx4srIgOf0MRJ/sZ13RonADXxvKBym8xrxNCq5f6DibGcr38sIlwPk8/52uYdXeOPsbEDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collapsible": "1.2.1", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-alert-dialog": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.2.1.tgz", + "integrity": "sha512-MWC4N7RY+qsbNrFNo7yQ9ZbdoZEW+B5DtpWxJfUnVCqcQxxqqg3qis3RMPTDbCNaTIdHJSn5XDkl9ZdVWXknLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dialog": "1.3.1", + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-arrow": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.17.tgz", + "integrity": "sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-aspect-ratio": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-aspect-ratio/-/react-aspect-ratio-1.2.0.tgz", + "integrity": "sha512-gHEU+Lx8DlT/FYIjZQvvBJrFSwUngXTjh7FeL9QvJaNALDLez6pgDj2axCUihBjtPBy82LN0gNb25+sTcSXNmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-avatar": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.3.1.tgz", + "integrity": "sha512-ssZOkfQNkFpYVmCPQlr978xSaU7moSrGXdwg4j2Xs2WlGl/1KsSZtfpK+WnLnx0Rwll1BAh6oUrAy/uR31SBvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-checkbox": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.4.1.tgz", + "integrity": "sha512-KWtwhh+98ML3seZ9vO9yRY2OwaQG90dCiDAxjpSNY2AaZ3Hik3B0dsk6m0ILywo/no3A9/SozadyPMNweVT8yw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collapsible": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.2.1.tgz", + "integrity": "sha512-fSzLb/qy1wuZSxQBcxpW0hNXYHDMWiIXDGyJGdA4+FSLknOWZsNRrTCUavxb4PI8b8lvHo/CysO6NVi5zLpo5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collection": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.2.0.tgz", + "integrity": "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context-menu": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.4.1.tgz", + "integrity": "sha512-Pddn3Z8lio3/ChxyXaEP3jHTTo1LTHCWwF8+mG1chQlWijP+ttVHBKwezrQTiV6Mj670ojvumqvuGh+mdv33iQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dialog": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.3.1.tgz", + "integrity": "sha512-+0E4qvVTwjAWra9sEhJ+9BTsvHE00zkUuNw1VGh7S+Gc13dfYk+S1PVQdchWDj+XYHhAai7Z7IpzXVDCGsDplg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-direction": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.2.0.tgz", + "integrity": "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.2.1.tgz", + "integrity": "sha512-KIfDcAsx+oVylFZ4xryVKusJUrLLhTQmfnJW4kwk4Km5myvhHCrj04hnWWUC166+xD4DHdH8tQGylwYX1h6+Pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-effect-event": "0.0.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dropdown-menu": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.2.1.tgz", + "integrity": "sha512-XsHcmYG2AcqnvTqrOXXWcMrhquEIlqucizuDH1MV/qMRW+DndpBCMvNeTRXOxqmG1H5j89M/+I0/34Zdd+zDcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-guards": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.2.0.tgz", + "integrity": "sha512-MPm5R0iRGUDrDnPNxmLBkv+X7pN4XKzt+MbWJEuJQsH3NFH4omrbpXpucyYCCKTSt+na/ZxGhEWQrWTZ0285cA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-scope": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.3.1.tgz", + "integrity": "sha512-ugeMhbXt4y5S2T1GnIqbWDKEN962PDwnX1fN0eKOOgf5f63Dh2mn8F1FUySlgW0iF6GiVsRF32DzuDIWTUyQJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-form": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-form/-/react-form-0.3.0.tgz", + "integrity": "sha512-KnmrCM27m7Jo1R8S6cFDPrEeq20Jfn5dqde0SZrJr2lVXlj6/QZSUCyFoYh1d8ti0uUrMNK5Lx6dUDuINT+f4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-label": "2.1.17", + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-hover-card": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.2.1.tgz", + "integrity": "sha512-4QooHxgmpCKRjj1Pft+hETKidYcrbPKcVwMGtk2Oa5DcWY2IH1fHuQt9LG6q5hUQBBV2MhQxSvtx6B/C1xfiTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-label": { + "version": "2.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.17.tgz", + "integrity": "sha512-xmj7MN/drx1oUAXkfiFIvyDmGNUIN/omGobvA5oAoNqu9zO2MkISYGZOkBcqSzs/UZXXwV+/3ACRE7q7mGcmkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menu": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.2.1.tgz", + "integrity": "sha512-G34BsU90SBj5foYpz8pQqq/Q0Dlfyyl6KitWEfRwXC0QvfwhWNAwS49DWP2+rRJ0iwv20Z2Qx7Sk+T03bGo5JA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menubar": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menubar/-/react-menubar-1.2.1.tgz", + "integrity": "sha512-bRTYtS9JITV2dUYqYZb7+N5SooQBkZrNRejfmyrSKe3Y57aXhKgx//kBUP0kY7pEpsWR/U1AHsAJRzjwCrK3PA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-navigation-menu": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-navigation-menu/-/react-navigation-menu-1.4.1.tgz", + "integrity": "sha512-XPPZjkeyCSMNNvt0FyDv/PUauG7Ow4GwHQ/XZSwW36F/TS7rR4HFTsXH8ewLnXTOLn3x96/pmTPNQIVoTX/86g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-previous": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-one-time-password-field": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-one-time-password-field/-/react-one-time-password-field-0.2.1.tgz", + "integrity": "sha512-KtHdcgnaAK6rohQ/MMJoGYcbgSRJsIuGBdHrFeTB1/9SaKlDs14oSOniW6BL6M43HqvgCO3u4WuVdFLkuc6sqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-password-toggle-field": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-password-toggle-field/-/react-password-toggle-field-0.2.1.tgz", + "integrity": "sha512-vu4+ZoJAaFjdI7l1lDSZRs+4dEv83Jmu7lyzajPrAeQzX74y84n0rUNWbWSgN9XB5NE8IY86Z02kGH6oRrzR+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popover": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.3.1.tgz", + "integrity": "sha512-ZNxvXRx5W2Wos4fXCXb5lpdqN0Z5chf+mStOUOTr4ik7d+62MRvoe9rzCA/eGNg36lxXqSrKEKmwuZEcUrIstw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popper": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.4.0.tgz", + "integrity": "sha512-yCWRvLeGv9Pz3+efwHqGPp70mZ56r3kfIgQVF56Oj2aAa4uP/Tb+IE59wNcc+758rctqbCKx4LbK8II/r7Bn0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-rect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-portal": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.2.0.tgz", + "integrity": "sha512-StX7xXnaRU41VvFtMm9zlhVGz8XF6GmWWTXftkQaY+tqVkbs/R9UmAp5mLzHHapk5hM9RMZQvO/3usyIP/g42g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-progress": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.2.1.tgz", + "integrity": "sha512-yQBiM6J3YM8Ums1orkEFpbznK47geKxa0igikzcaS1xHgdba3DdAQBsGbCTt5BVfR8zhEvgxQ0poGcINaD3lvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.5.1.tgz", + "integrity": "sha512-QbyVT1ddnjqB9H+CUYKkNWdU9fIK3QHCYtjf7mS6ekSqiuXkWtWn5UZW9mhA8qtl3vrVyIsmR9gePstAtKrqkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-roving-focus": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.2.1.tgz", + "integrity": "sha512-UwraORzVUeEPMclhO1p0vz0qI+TbdDLO9i+FiOqhJyHKwdpCRCck9yVEscUnAMIzCiuNoQa8D4A9bIpOPXGt6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-scroll-area": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.4.0.tgz", + "integrity": "sha512-CFrLqHNejWq5FhKAcj9V/WPGRsol76HBQto81NdOBVFEOqIEkJkKIJt0Z824A/9hHLCtoiR/Kw3euRgzXP2pxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.4.1.tgz", + "integrity": "sha512-888ZwW0Md6GyptuqYABRX9nLKgoYfcooCyBBvVaX5Jp3e+8Jp2i4Zo/Uy50Hm+Ysn2JfloQXstW4U36w8teVtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-separator": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.2.0.tgz", + "integrity": "sha512-1jUAap0wZEqVP05Ou7kJgRxe/W+Qftng+rUNWGa0qkKbv9r5pWTG3E7a3ELKo2eJoHKMECnzuYrZpSyO1YgcYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.6.1.tgz", + "integrity": "sha512-IRNRR90moPqxfwCJ0XbMJIxo70W0/1ZExT/sNCxEHMaPx0SF9HoQrcPEC75+H28cFKa0b+KH63anfLYJmwKacw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-switch": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.4.1.tgz", + "integrity": "sha512-NpBGwc40rY02ZmSvuyeKk0Bvc8ZsNeTMi4qHvJ+ZH4EiYCv0zIXEgdCW4bVdzgIUeP9xxbLJSxKOUfqITYNmkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.2.1.tgz", + "integrity": "sha512-hRoJlode+hg5ZNlR+3tkfkUliIybdTpD5lkAvHQ9yaXseGf7XVO9Ib2GPEIOuaJJbo7YWYbNpDDRfo8Dhf6/xA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toast": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.3.1.tgz", + "integrity": "sha512-iQvL0J7XK4HtJNGkkWMyYrboNseI7vtotFeUkIno8YNxVA9oM7B6//fh0Mc6TSKI96+zioLWi98lQLso88yJmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.2.1.tgz", + "integrity": "sha512-+3MUq+WyiBplXYqQ0EIYlq8R4sLQ0T5NbOK7DMdDLCKO93pe2uE0DUJTWWfTBprpJJXxfoF3eMW0xpakVZrYsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle-group": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.2.1.tgz", + "integrity": "sha512-O8Ldx5ao4p4KoW+DO8/PmkOe5mdKNi3F2SseqjVj88wvDGDHe60cUmO0Zm/uHsKrvNgQGV8Efpuh95Tht/h4vw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-toggle": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toolbar": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toolbar/-/react-toolbar-1.2.1.tgz", + "integrity": "sha512-Cm8m7JTEeUdbfA6T9xgyu8HfOpyvSx8pB/wj0DlEuWaJe9FilIs4Az9wci/lU9RbthV/UkltszMw5WnnD+m/Ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-separator": "1.2.0", + "@radix-ui/react-toggle-group": "1.2.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.4.1.tgz", + "integrity": "sha512-NxLFGSFtZ78zVfcoOhTwR1xwqo5qx1Jh8Pw6FMZ9McCaqfRzz7/gIRahs2Oy5XlPgQ+8QkUcKbN5B0U44J/kCg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.5.tgz", + "integrity": "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-escape-keydown": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.6.tgz", + "integrity": "sha512-9cRullnQRv+kqnRmFlmh0WC3kAPuGmHiQ9VwsXdrYk//sBhgCKEttcpPEPgIQbyx6TGUmooVEHYTyohwz/lSJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-is-hydrated": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.3.tgz", + "integrity": "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-previous": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.4.tgz", + "integrity": "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-rect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.4.tgz", + "integrity": "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "dev": true, "license": "MIT", "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } } }, - "node_modules/@keyv/bigmap": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", - "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "node_modules/@radix-ui/react-visually-hidden": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.13.tgz", + "integrity": "sha512-feijiN1oPk4rck4u9Dm9tsU4mT6Wp9oeEEhaz1WUEs1VuqLf8xzsFG+Qk+uWq6TnMH9O+WRECRg0NftyP9E4Fw==", "dev": true, "license": "MIT", "dependencies": { - "hashery": "^1.4.0", - "hookified": "^1.15.0" - }, - "engines": { - "node": ">= 18" + "@radix-ui/react-primitive": "2.2.0" }, "peerDependencies": { - "keyv": "^5.6.0" + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } } }, - "node_modules/@keyv/serialize": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", - "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "node_modules/@radix-ui/rect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.3.tgz", + "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", "dev": true, "license": "MIT" }, - "node_modules/@oxc-project/types": { - "version": "0.160.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz", - "integrity": "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==", + "node_modules/@radix-ui/themes": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/themes/-/themes-3.3.0.tgz", + "integrity": "sha512-I0/h2CRNTpYNB7Mi3xFIvSsQq5a108d7kK8dTO5zp5b9HR5QJXKag6B8tjpz2ITkVYkFdkGk45doNkSr7OxwNw==", "dev": true, "license": "MIT", - "peer": true, - "funding": { - "url": "https://github.com/sponsors/oxc-project" + "dependencies": { + "@radix-ui/colors": "^3.0.0", + "classnames": "^2.3.2", + "radix-ui": "^1.1.3", + "react-remove-scroll-bar": "^2.3.8" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } } }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.4.tgz", - "integrity": "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", "cpu": [ "arm" ], @@ -765,15 +2468,14 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.4.tgz", - "integrity": "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", "cpu": [ "arm64" ], @@ -783,15 +2485,14 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.4.tgz", - "integrity": "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", "cpu": [ "arm64" ], @@ -801,15 +2502,14 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.4.tgz", - "integrity": "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", "cpu": [ "x64" ], @@ -819,15 +2519,14 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.4.tgz", - "integrity": "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", "cpu": [ "x64" ], @@ -837,15 +2536,14 @@ "os": [ "freebsd" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.4.tgz", - "integrity": "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", "cpu": [ "arm" ], @@ -855,15 +2553,14 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.4.tgz", - "integrity": "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", "cpu": [ "arm64" ], @@ -873,15 +2570,14 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.4.tgz", - "integrity": "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", "cpu": [ "arm64" ], @@ -891,15 +2587,14 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.4.tgz", - "integrity": "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", "cpu": [ "ppc64" ], @@ -909,15 +2604,14 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.4.tgz", - "integrity": "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", "cpu": [ "s390x" ], @@ -927,15 +2621,14 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.4.tgz", - "integrity": "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", "cpu": [ "x64" ], @@ -945,15 +2638,14 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.4.tgz", - "integrity": "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", "cpu": [ "x64" ], @@ -963,15 +2655,14 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.4.tgz", - "integrity": "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", "cpu": [ "arm64" ], @@ -981,33 +2672,33 @@ "os": [ "openharmony" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.4.tgz", - "integrity": "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", "cpu": [ "wasm32" ], "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { - "@oxc-project/types": "0.160.0" + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" }, "engines": { "node": "^20.19.0 || ^22.13.0 || >=23.5.0" } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.4.tgz", - "integrity": "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", "cpu": [ "arm64" ], @@ -1017,15 +2708,14 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.4.tgz", - "integrity": "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", "cpu": [ "x64" ], @@ -1035,7 +2725,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1045,8 +2734,7 @@ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@stylexjs/babel-plugin": { "version": "0.19.2", @@ -1110,6 +2798,17 @@ "unplugin": "^2.3.11" } }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -1159,6 +2858,26 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, "node_modules/@vitest/mocker": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.2.tgz", @@ -1246,6 +2965,19 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/aria-hidden": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz", + "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1381,6 +3113,13 @@ "node": ">=18" } }, + "node_modules/classnames": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", + "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==", + "dev": true, + "license": "MIT" + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1416,6 +3155,13 @@ "node": ">=18" } }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "dev": true, + "license": "MIT" + }, "node_modules/data-urls": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", @@ -1470,6 +3216,13 @@ "node": ">=8" } }, + "node_modules/detect-node-es": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", + "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", + "dev": true, + "license": "MIT" + }, "node_modules/electron-to-chromium": { "version": "1.5.495", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.495.tgz", @@ -1784,7 +3537,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } @@ -1798,6 +3550,16 @@ "node": ">=6.9.0" } }, + "node_modules/get-nonce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", + "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -2406,7 +4168,6 @@ } ], "license": "MIT", - "peer": true, "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -2414,25 +4175,6 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, - "node_modules/napi-windows-process-start-time": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/napi-windows-process-start-time/-/napi-windows-process-start-time-0.1.0.tgz", - "integrity": "sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw==", - "cpu": [ - "x64", - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "engines": { - "node": ">=20" - } - }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -2572,6 +4314,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/postcss": { "version": "8.5.33", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", @@ -2592,7 +4363,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", @@ -2648,15 +4418,187 @@ "dev": true, "license": "MIT" }, + "node_modules/radix-ui": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/radix-ui/-/radix-ui-1.8.1.tgz", + "integrity": "sha512-HPfpVGizO9xANlsFSauruLhRe/3+iOt3vPX0MXYle/UQi3gorQrSYtBcdiv0BZYewcl2rvL59qrIuLFMGAmUrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-accessible-icon": "1.2.0", + "@radix-ui/react-accordion": "1.3.1", + "@radix-ui/react-alert-dialog": "1.2.1", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-aspect-ratio": "1.2.0", + "@radix-ui/react-avatar": "1.3.1", + "@radix-ui/react-checkbox": "1.4.1", + "@radix-ui/react-collapsible": "1.2.1", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-context-menu": "2.4.1", + "@radix-ui/react-dialog": "1.3.1", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-dropdown-menu": "2.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-form": "0.3.0", + "@radix-ui/react-hover-card": "1.2.1", + "@radix-ui/react-label": "2.1.17", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-menubar": "1.2.1", + "@radix-ui/react-navigation-menu": "1.4.1", + "@radix-ui/react-one-time-password-field": "0.2.1", + "@radix-ui/react-password-toggle-field": "0.2.1", + "@radix-ui/react-popover": "1.3.1", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-progress": "1.2.1", + "@radix-ui/react-radio-group": "1.5.1", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-scroll-area": "1.4.0", + "@radix-ui/react-select": "2.4.1", + "@radix-ui/react-separator": "1.2.0", + "@radix-ui/react-slider": "1.6.1", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-switch": "1.4.1", + "@radix-ui/react-tabs": "1.2.1", + "@radix-ui/react-toast": "1.3.1", + "@radix-ui/react-toggle": "1.2.1", + "@radix-ui/react-toggle-group": "1.2.1", + "@radix-ui/react-toolbar": "1.2.1", + "@radix-ui/react-tooltip": "1.4.1", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-escape-keydown": "1.1.6", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-remove-scroll": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", + "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "react-remove-scroll-bar": "^2.3.7", + "react-style-singleton": "^2.2.3", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.3", + "use-sidecar": "^1.1.3" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-remove-scroll-bar": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz", + "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "react-style-singleton": "^2.2.2", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-style-singleton": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", + "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-nonce": "^1.0.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/rolldown": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz", - "integrity": "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "@oxc-project/types": "=0.160.0", + "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -2666,22 +4608,22 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.3.4", - "@rolldown/binding-android-arm64": "1.3.4", - "@rolldown/binding-darwin-arm64": "1.3.4", - "@rolldown/binding-darwin-x64": "1.3.4", - "@rolldown/binding-freebsd-x64": "1.3.4", - "@rolldown/binding-linux-arm-gnueabihf": "1.3.4", - "@rolldown/binding-linux-arm64-gnu": "1.3.4", - "@rolldown/binding-linux-arm64-musl": "1.3.4", - "@rolldown/binding-linux-ppc64-gnu": "1.3.4", - "@rolldown/binding-linux-s390x-gnu": "1.3.4", - "@rolldown/binding-linux-x64-gnu": "1.3.4", - "@rolldown/binding-linux-x64-musl": "1.3.4", - "@rolldown/binding-openharmony-arm64": "1.3.4", - "@rolldown/binding-wasm32-wasi": "1.3.4", - "@rolldown/binding-win32-arm64-msvc": "1.3.4", - "@rolldown/binding-win32-x64-msvc": "1.3.4" + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, "node_modules/rrweb-cssom": { @@ -2711,6 +4653,13 @@ "node": ">=v12.22.7" } }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "dev": true, + "license": "MIT" + }, "node_modules/semver": { "version": "6.3.2", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", @@ -2749,7 +4698,6 @@ "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", "dev": true, "license": "BSD-3-Clause", - "peer": true, "engines": { "node": ">=6.0.0" } @@ -2901,6 +4849,13 @@ "node": ">=18" } }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -3004,18 +4959,62 @@ "punycode": "^2.1.0" } }, + "node_modules/use-callback-ref": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", + "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sidecar": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz", + "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-node-es": "^1.1.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/vite": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.4.0.tgz", - "integrity": "sha512-X2nUJg+9cutlz3hzqyO6p+WTwk9H257DjwAEf9EQYUFrQbDItmetadi9gYmb+l7VDy4r3VXLUnmLTwuPmzejDw==", + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", + "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", - "postcss": "^8.5.33", - "rolldown": "~1.3.2", + "postcss": "^8.5.29", + "rolldown": "~1.2.12", "tinyglobby": "^0.2.17" }, "bin": { @@ -3028,12 +5027,11 @@ "url": "https://github.com/vitejs/vite?sponsor=1" }, "optionalDependencies": { - "fsevents": "~2.3.3", - "napi-windows-process-start-time": "^0.1.0" + "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", @@ -3090,7 +5088,6 @@ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, diff --git a/packages/reflex-components-ui/js/package.json b/packages/reflex-components-ui/js/package.json index 5889fae0fbe..ea73a6f24d6 100644 --- a/packages/reflex-components-ui/js/package.json +++ b/packages/reflex-components-ui/js/package.json @@ -16,6 +16,7 @@ "test": "vitest run", "generate": "node scripts/generate.js", "generate:check": "node scripts/generate.js --check", + "sweep": "node tests/harness/sweep.js", "check": "npm run lint && npm run typecheck && npm run generate:check && npm test" }, "dependencies": { @@ -24,12 +25,21 @@ }, "devDependencies": { "@eslint/js": "10.0.1", + "@radix-ui/themes": "3.3.0", "@stylexjs/eslint-plugin": "0.19.2", "@types/node": "22.20.5", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", "eslint": "10.15.0", "globals": "17.14.0", "jsdom": "^26.1.0", + "lightningcss": "1.33.0", + "playwright": "1.63.0", + "postcss": "8.5.33", + "react": "19.3.1", + "react-dom": "19.3.1", "typescript": "5.9.3", + "vite": "8.3.4", "vitest": "^5.1.0" } } diff --git a/packages/reflex-components-ui/js/scripts/generate.js b/packages/reflex-components-ui/js/scripts/generate.js index ce09527c2e4..5e4fbaef13e 100644 --- a/packages/reflex-components-ui/js/scripts/generate.js +++ b/packages/reflex-components-ui/js/scripts/generate.js @@ -1,10 +1,48 @@ // Writes the generated files of the package, or with `--check` fails when a // committed one is not what its generator produces. +import { readFileSync } from "node:fs"; import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { getMatchingGrayColor } from "@radix-ui/themes/helpers"; +import { themePropDefs } from "@radix-ui/themes/props"; + +import { radixTokens } from "./radix-tokens.js"; + +const require = createRequire(import.meta.url); + +/** + * The colors, tokens and themes, from the stylesheet of the Radix Themes + * this package installs. + * + * @returns {Generated[]} The StyleX modules and the python module listing them. + */ +function radixThemes() { + const { version } = require("@radix-ui/themes/package.json"); + const { radius, scaling, panelBackground, accentColor, grayColor } = + themePropDefs; + return radixTokens( + readFileSync(require.resolve("@radix-ui/themes/tokens.css"), "utf8"), + { + version, + defaults: { + radius: radius.default, + scaling: scaling.default, + panelBackground: panelBackground.default, + accentColor: accentColor.default, + grayColor: grayColor.default, + }, + matchingGray: (accent) => + getMatchingGrayColor( + /** @type {(typeof accentColor.values)[number]} */ (accent), + ), + }, + ); +} + /** * A committed file that a generator owns. * @@ -20,7 +58,7 @@ import { fileURLToPath } from "node:url"; * * @type {Generated[]} */ -export const GENERATED = []; +export const GENERATED = [...radixThemes()]; const PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url)); diff --git a/packages/reflex-components-ui/js/scripts/radix-tokens.js b/packages/reflex-components-ui/js/scripts/radix-tokens.js new file mode 100644 index 00000000000..ec708ed6008 --- /dev/null +++ b/packages/reflex-components-ui/js/scripts/radix-tokens.js @@ -0,0 +1,803 @@ +// Turns the token stylesheet of @radix-ui/themes into the StyleX modules of +// `src/colors`, `src/tokens` and `src/themes`, and into the python module that +// lists them. Every custom property keeps the name and the value Radix gives +// it; what changes is where the value is decided: +// +// - Radix defines a color once under `.light` and once under `.dark`. Here it is +// one `light-dark()` value, picked by the `color-scheme` of the element that +// uses it, so an appearance is one CSS property and not a second stylesheet. +// - Radix repeats every derived token on each `.radix-themes` element, so that +// `--space-1` follows the `--scaling` of the nearest theme. Here the tokens +// are defined on `:root`, and a StyleX theme defines every variable of its +// group again on the element it is applied to. The scope themes override +// nothing and exist for that: they are what makes an element a theme. + +import { dirname, posix } from "node:path"; + +import postcss from "postcss"; + +/** + * The value of a custom property in each context Radix defines it for. + * + * @typedef {object} Token + * @property {string} [light] In the light appearance. + * @property {string} [dark] In the dark appearance. + * @property {string} [p3Light] On a display-P3 screen, when it differs. + * @property {string} [p3Dark] On a display-P3 screen, when it differs. + */ + +/** + * A value as StyleX takes it: one string, or a default with the one a + * display-P3 screen gets. + * + * @typedef {string | { default: string, p3: string }} Value + */ + +/** + * What the stylesheet says, before any of it is arranged into modules. + * + * @typedef {object} Model + * @property {Map} tokens The custom properties defined outside a + * theme attribute. + * @property {Record>>} themes The + * declarations of each value of each theme attribute, such as + * `themes["accent-color"].get("red")`. + * @property {Record} element The properties Radix + * sets on a theme element itself, by the key they get in `themes/theme.js`. + */ + +/** + * What the generator needs that the stylesheet does not say. + * + * @typedef {object} Options + * @property {string} version The version of Radix Themes that was read. + * @property {{ radius: string, scaling: string, panelBackground: string, accentColor: string, grayColor: string }} defaults + * The props of a Radix `Theme` that is given none. + * @property {(accent: string) => string} matchingGray The gray an accent is + * paired with when the gray is `auto`. + */ + +/** @typedef {import("./generate.js").Generated} Generated */ + +const P3_SUPPORTS = "@supports (color: color(display-p3 1 1 1))"; +const P3_MEDIA = "@media (color-gamut: p3)"; + +// The conditions a rule may sit in. Every browser with `light-dark()` has +// `color-mix()`, so the value Radix gives the ones that do is the only value. +const CONDITIONS = new Map([ + ["", false], + ["@supports (color: color-mix(in oklab, white, black))", false], + [`${P3_SUPPORTS} > ${P3_MEDIA}`, true], +]); + +const DARK = ":is(.dark, .dark-theme)"; + +// The appearance a rule outside a theme attribute applies to. +const TOKEN_SELECTORS = new Map([ + [":root", "both"], + [":root, .light, .light-theme", "light"], + [".dark, .dark-theme", "dark"], + [".radix-themes", "both"], + [":where(.radix-themes)", "both"], + [`${DARK}, ${DARK} :where(.radix-themes:not(.light, .light-theme))`, "dark"], + ["[data-radius]", "both"], + [ + ".radix-themes, [data-accent-color]:where(:not([data-accent-color=''], [data-accent-color='gray']))", + "both", + ], +]); + +// The attributes a Radix `Theme` puts its props in. +const ATTRIBUTES = [ + "accent-color", + "gray-color", + "radius", + "scaling", + "panel-background", +]; + +const THEME_SELECTOR = new RegExp( + `^(?:\\.radix-themes:where\\()?\\[data-(${ATTRIBUTES.join("|")})='([^']+)'\\]\\)?$`, +); + +/** + * The selector that forces an appearance on a theme element. + * + * @param {string} appearance `light` or `dark`. + * @returns {string} The selector as Radix writes it. + */ +function appearanceSelector(appearance) { + const forced = `:where(.${appearance}, .${appearance}-theme)`; + return `.radix-themes${forced}, :root:where(:has(.radix-themes[data-is-root-theme='true']${forced}))`; +} + +// The rules that style a theme element, by their key in `themes/theme.js`. +const ELEMENT_SELECTORS = new Map([ + [".radix-themes", "root"], + [".radix-themes:where([data-has-background='true'])", "background"], + [appearanceSelector("light"), "light"], + [appearanceSelector("dark"), "dark"], +]); + +// Rules that reach below the theme element, which a class on it cannot do. They +// belong to the stylesheet every page loads. +const GLOBAL_SELECTORS = new Set([".radix-themes ::selection"]); + +// The variable groups that are not a color scale: the name they are exported +// under, their module and the custom properties they hold. The first match +// wins. +const GROUPS = /** @type {const} */ ([ + ["space", "tokens/space.stylex.js", /^--space-/], + ["scaling", "tokens/scaling.stylex.js", /^--scaling$/], + ["radiusFactor", "tokens/radius.stylex.js", /^--radius-(factor|full|thumb)$/], + ["radius", "tokens/radius.stylex.js", /^--radius-/], + ["shadow", "tokens/shadow.stylex.js", /^--shadow-/], + ["cursor", "tokens/cursor.stylex.js", /^--cursor-/], + [ + "panel", + "tokens/panel.stylex.js", + /^--(panel-solid|backdrop-filter-panel)$/, + ], + ["color", "tokens/color.stylex.js", /^--color-/], + ["accent", "tokens/accent.stylex.js", /^--accent-/], + ["focus", "tokens/focus.stylex.js", /^--focus-/], + ["gray", "tokens/gray.stylex.js", /^--gray-/], + [ + "typography", + "tokens/typography.stylex.js", + /^--(font|line-height|letter-spacing|default|heading|code|strong|em|quote|tab)-/, + ], +]); + +// The groups with tokens that read another variable, which a scope theme +// defines again on a theme element. `focus` has a module of its own, because an +// accent on a single element needs it without the rest. +const SCOPED = ["space", "radius", "typography", "shadow", "color"]; + +/** + * Read the custom properties and the theme element's styles from a stylesheet. + * + * @param {string} css The token stylesheet of Radix Themes. + * @returns {Model} What it defines. + */ +export function parseTokens(css) { + /** @type {Model} */ + const model = { tokens: new Map(), themes: {}, element: {} }; + postcss.parse(css).walkRules((rule) => { + const conditions = []; + for ( + let parent = rule.parent; + parent?.type === "atrule"; + parent = parent.parent + ) { + const atRule = /** @type {import("postcss").AtRule} */ (parent); + conditions.unshift(`@${atRule.name} ${atRule.params}`); + } + const p3 = CONDITIONS.get(conditions.join(" > ")); + const selector = rule.selector.replace(/\s+/g, " "); + if (p3 === undefined) { + throw new Error( + `Unknown condition on ${selector}: ${conditions.join(" > ")}`, + ); + } + const appearance = TOKEN_SELECTORS.get(selector); + const theme = THEME_SELECTOR.exec(selector); + const element = ELEMENT_SELECTORS.get(selector); + if (!appearance && !theme && !element && !GLOBAL_SELECTORS.has(selector)) { + throw new Error(`Unknown selector: ${selector}`); + } + rule.walkDecls((decl) => { + const value = decl.value.replace(/\s+/g, " "); + if (!decl.prop.startsWith("--")) { + // A prefixed copy of a property the rule also sets is the work of + // Radix's build, and StyleX takes the standard name only. + const standard = decl.prop.replace(/^-(webkit|moz)-/, ""); + const prefixed = + standard !== decl.prop && + rule.some((node) => node.type === "decl" && node.prop === standard); + if (element && !prefixed) { + (model.element[element] ??= []).push([decl.prop, value]); + } + } else if (theme) { + const values = (model.themes[theme[1]] ??= new Map()); + let declarations = values.get(theme[2]); + if (!declarations) values.set(theme[2], (declarations = new Map())); + declarations.set(decl.prop, value); + } else if (appearance) { + let token = model.tokens.get(decl.prop); + if (!token) model.tokens.set(decl.prop, (token = {})); + if (appearance !== "dark") token[p3 ? "p3Light" : "light"] = value; + if (appearance !== "light") token[p3 ? "p3Dark" : "dark"] = value; + } else { + throw new Error(`${decl.prop} is set by ${selector}`); + } + }); + }); + return model; +} + +/** + * Split a value at the separators that are not inside parentheses. + * + * @param {string} value The value to split. + * @param {string} separator One character. + * @returns {string[]} The trimmed parts. + */ +function splitTopLevel(value, separator) { + const parts = []; + let depth = 0; + let start = 0; + for (let index = 0; index < value.length; index++) { + const character = value[index]; + if (character === "(") depth++; + else if (character === ")") depth--; + else if (character === separator && depth === 0) { + parts.push(value.slice(start, index).trim()); + start = index + 1; + } + } + parts.push(value.slice(start).trim()); + return parts.filter(Boolean); +} + +/** + * One value for both appearances of a color. + * + * @param {string} light The color in the light appearance. + * @param {string} dark The color in the dark appearance. + * @returns {string} The color, or a `light-dark()` of the two. + */ +export function lightDark(light, dark) { + return light === dark ? light : `light-dark(${light}, ${dark})`; +} + +/** + * One shadow list for both appearances. + * + * `light-dark()` only chooses between colors, and the two appearances of a + * Radix shadow differ in geometry too. Layers that share their geometry keep + * it and choose their color; a layer only one appearance has is transparent in + * the other, where it paints nothing. Both appearances keep their paint order. + * + * @param {string} light The `box-shadow` value of the light appearance. + * @param {string} dark The `box-shadow` value of the dark appearance. + * @returns {string} A `box-shadow` value that paints as `light` or as `dark` + * according to the color scheme. + */ +export function mergeShadows(light, dark) { + if (light === dark) return light; + const [lights, darks] = [light, dark].map((shadow) => + splitTopLevel(shadow, ",").map((layer) => { + const parts = splitTopLevel(layer, " "); + const color = parts.findIndex( + (part) => part !== "inset" && !/^-?[\d.]+(px)?$/.test(part), + ); + return { + color: parts[color], + geometry: parts.toSpliced(color, 1).join(" "), + }; + }), + ); + // The longest common subsequence of the two lists of geometries. + const common = lights.map(() => new Array(darks.length + 1).fill(0)); + common.push(new Array(darks.length + 1).fill(0)); + for (let l = lights.length - 1; l >= 0; l--) { + for (let d = darks.length - 1; d >= 0; d--) { + common[l][d] = + lights[l].geometry === darks[d].geometry + ? common[l + 1][d + 1] + 1 + : Math.max(common[l + 1][d], common[l][d + 1]); + } + } + const layers = []; + let l = 0; + let d = 0; + while (l < lights.length || d < darks.length) { + if ( + l < lights.length && + d < darks.length && + lights[l].geometry === darks[d].geometry + ) { + const color = lightDark(lights[l].color, darks[d++].color); + layers.push(`${lights[l++].geometry} ${color}`); + } else if ( + d === darks.length || + (l < lights.length && common[l + 1][d] >= common[l][d + 1]) + ) { + const { geometry, color } = lights[l++]; + layers.push(`${geometry} light-dark(${color}, transparent)`); + } else { + const { geometry, color } = darks[d++]; + layers.push(`${geometry} light-dark(transparent, ${color})`); + } + } + return layers.join(", "); +} + +/** + * The single value of a token. + * + * @param {string} name The custom property. + * @param {Token} token Its value in each context. + * @returns {Value} The value for every appearance, and the one a display-P3 + * screen gets when Radix has one. + */ +function resolve(name, { light, dark, p3Light, p3Dark }) { + if (light === undefined || dark === undefined) { + throw new Error(`${name} has no value in one appearance.`); + } + const merge = name.startsWith("--shadow-") ? mergeShadows : lightDark; + const value = merge(light, dark); + if (p3Light === undefined && p3Dark === undefined) return value; + return { default: value, p3: merge(p3Light ?? light, p3Dark ?? dark) }; +} + +/** + * The name a theme is exported under. + * + * @param {string} prefix What the theme sets, such as `accent`. + * @param {string} name The value of the theme prop, such as `red` or `90%`. + * @returns {string} A javascript identifier, such as `accentRed`. + */ +function themeExport(prefix, name) { + const word = name.replace(/\W/g, ""); + return prefix + word[0].toUpperCase() + word.slice(1); +} + +/** + * The property name StyleX takes for a CSS property. + * + * @param {string} property A CSS property, such as `-webkit-font-smoothing`. + * @returns {string} Its camel case name, such as `WebkitFontSmoothing`. + */ +function camelCase(property) { + return property.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()); +} + +/** + * A property of an object literal, laid out the way the repository's formatter + * leaves it: a string that does not fit on the line of its key goes below it. + * + * @param {string} indent The indentation of the property. + * @param {string} key The key, as it is written. + * @param {string} expression The javascript of the value. + * @returns {string} The lines of the property. + */ +function property(indent, key, expression) { + const line = `${indent}${key}: ${expression},`; + return line.length > 80 && expression.startsWith('"') + ? `${indent}${key}:\n${indent} ${expression},\n` + : `${line}\n`; +} + +/** + * Builds the modules, remembering which module defines each custom property so + * that a value which reads one imports it. + */ +class Modules { + /** + * @param {string} version The version of Radix Themes that was read. + */ + constructor(version) { + this.header = `// Generated by scripts/generate.js from @radix-ui/themes ${version}. Do not edit.\n`; + /** @type {Map} */ + this.owners = new Map(); + /** @type {Map} */ + this.groups = new Map(); + /** @type {Map} */ + this.groupModules = new Map(); + /** @type {Generated[]} */ + this.files = []; + } + + /** + * Add a group of variables to the module that defines it. + * + * @param {string} module The module, relative to `src`. + * @param {string} name The name the group is exported under. + * @param {[string, Value][]} vars The custom properties and their values. + */ + define(module, name, vars) { + const groups = this.groups.get(module) ?? []; + this.groups.set(module, groups); + groups.push({ name, vars }); + this.groupModules.set(name, module); + for (const [variable] of vars) this.owners.set(variable, { module, name }); + } + + /** + * The javascript for a value, reading the variables other modules define + * through an import, which is what makes their CSS part of the build. + * + * @param {string} value The CSS value. + * @param {string} module The module the value is written in. + * @param {Map>} imports The names to import, by module. + * @returns {string} A string literal, a member of an imported group or a + * template literal of both. + */ + expression(value, module, imports) { + const parts = value.split(/var\((--[\w-]+)\)/); + let foreign = false; + for (let index = 1; index < parts.length; index += 2) { + const owner = this.owners.get(parts[index]); + if (!owner || owner.module === module) { + parts[index] = `var(${parts[index]})`; + continue; + } + foreign = true; + if (!imports.has(owner.module)) imports.set(owner.module, new Set()); + /** @type {Set} */ (imports.get(owner.module)).add(owner.name); + parts[index] = `\${${owner.name}["${parts[index]}"]}`; + } + if (!foreign) return JSON.stringify(parts.join("")); + if (parts.length === 3 && parts[0] === "" && parts[2] === "") { + return parts[1].slice(2, -1); + } + return `\`${parts.join("")}\``; + } + + /** + * The properties of an object literal of variables. + * + * @param {[string, Value][]} vars The custom properties and their values. + * @param {string} module The module the object is written in. + * @param {Map>} imports The names to import, by module. + * @param {string} [none] The expression for a level that has no value. + * @returns {string} One property a line, indented. + */ + properties(vars, module, imports, none = "null") { + /** @type {(value: string) => string} */ + const expression = (value) => this.expression(value, module, imports); + return vars + .map(([name, value]) => + typeof value === "string" + ? property(" ", `"${name}"`, expression(value)) + : ` "${name}": {\n` + + property(" ", "default", expression(value.default)) + + ` "${P3_SUPPORTS}": {\n` + + property(" ", "default", none) + + property(" ", `"${P3_MEDIA}"`, expression(value.p3)) + + ` },\n` + + ` },\n`, + ) + .join(""); + } + + /** + * Add a module to the generated files. + * + * @param {string} module The module, relative to `src`. + * @param {Map>} imports The names it imports, by module. + * @param {string[]} statements The exports of the module. + */ + write(module, imports, statements) { + const lines = [...imports] + .map(([from, names]) => { + let path = posix.relative(dirname(module), from); + if (!path.startsWith(".")) path = `./${path}`; + return `import { ${[...names].sort().join(", ")} } from "${path}";\n`; + }) + .sort(); + const content = `${this.header}\nimport * as stylex from "@stylexjs/stylex";\n\n${lines.join("")}${lines.length ? "\n" : ""}${statements.join("\n")}`; + this.files.push({ path: `js/src/${module}`, render: () => content }); + } + + /** + * Write every module of variables that was defined. + */ + writeGroups() { + for (const [module, groups] of this.groups) { + /** @type {Map>} */ + const imports = new Map(); + const statements = groups.map( + ({ name, vars }) => + `export const ${name} = stylex.defineVars({\n${this.properties(vars, module, imports)}});\n`, + ); + this.write(module, imports, statements); + } + } + + /** + * Write a module of themes. + * + * @param {string} module The module, relative to `src`. + * @param {[name: string, group: string, vars: [string, Value][]][]} themes + * The name each theme is exported under, the group of variables it + * overrides and the values it gives them. + * @returns {[string, string][]} The module and the name of each theme. + */ + writeThemes(module, themes) { + /** @type {Map>} */ + const imports = new Map(); + let conditional = false; + const statements = themes.map(([name, group, vars]) => { + conditional ||= vars.some(([, value]) => typeof value !== "string"); + const from = /** @type {string} */ (this.groupModules.get(group)); + if (!imports.has(from)) imports.set(from, new Set()); + /** @type {Set} */ (imports.get(from)).add(group); + const overrides = this.properties(vars, module, imports, "NONE"); + return `export const ${name} = stylex.createTheme(${group}, {${overrides && "\n"}${overrides}});\n`; + }); + if (conditional) { + statements.unshift( + "// StyleX leaves a null level out, which the type of a string token does\n// not say.\nconst NONE = /** @type {string} */ (/** @type {unknown} */ (null));\n", + ); + } + this.write(module, imports, statements); + return themes.map(([name]) => [module, name]); + } +} + +/** + * Order entries by their name. + * + * @param {[string, unknown]} a An entry. + * @param {[string, unknown]} b Another. + * @returns {number} Negative when `a` goes first. + */ +function byName([a], [b]) { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * The declarations of a value of a theme attribute. + * + * @param {Map>} values The values of the attribute. + * @param {string} name The value. + * @returns {Map} What it declares. + */ +function required(values, name) { + const declarations = values.get(name); + if (!declarations) throw new Error(`Radix has no rule for ${name}.`); + return declarations; +} + +/** + * A python literal, laid out the way `ruff format` leaves it. + * + * @param {unknown} value Strings, arrays (written as tuples) and plain objects + * (written as dicts). + * @param {string} indent The indentation of the line the literal starts on. + * @returns {string} The literal. + */ +function python(value, indent = "") { + if (typeof value === "string") return JSON.stringify(value); + const inner = `${indent} `; + if (Array.isArray(value)) { + const flat = `(${value.map((item) => python(item)).join(", ")}${value.length === 1 ? "," : ""})`; + if (value.every((item) => typeof item === "string") && value.length <= 2) { + return flat; + } + return `(\n${value.map((item) => `${inner}${python(item, inner)},\n`).join("")}${indent})`; + } + const entries = Object.entries(/** @type {object} */ (value)); + return `{\n${entries.map(([key, item]) => `${inner}${JSON.stringify(key)}: ${python(item, inner)},\n`).join("")}${indent}}`; +} + +/** + * The generated files for a token stylesheet. + * + * @param {string} css The token stylesheet of Radix Themes. + * @param {Options} options What the stylesheet does not say. + * @returns {Generated[]} The StyleX modules under `js/src` and the python + * module that lists them. + */ +export function radixTokens(css, { version, defaults, matchingGray }) { + const { tokens, themes, element } = parseTokens(css); + for (const attribute of ATTRIBUTES) { + if (!themes[attribute]) { + throw new Error(`Radix has no rule for data-${attribute}.`); + } + } + const modules = new Modules(version); + const accents = themes["accent-color"]; + const panels = themes["panel-background"]; + + // The solid panel is a space toggle: `--color-panel` has to choose between + // two variables that follow the gray scale of the element it is used on, so + // a theme cannot hand it either of them as a value. + for (const [name, panel] of panels) { + if (panel.get("--color-panel") !== `var(--color-panel-${name})`) { + throw new Error(`The ${name} panel is not --color-panel-${name}.`); + } + panel.delete("--color-panel"); + panel.set("--panel-solid", name === "solid" ? " " : "initial"); + } + /** @type {Map} */ + const values = new Map( + [...tokens].map(([name, token]) => [name, resolve(name, token)]), + ); + const defaultTheme = [ + ...required(themes.scaling, defaults.scaling), + ...required(themes.radius, defaults.radius), + ...required(panels, defaults.panelBackground), + ["--color-panel-if-solid", "var(--panel-solid) var(--color-panel-solid)"], + [ + "--color-panel", + "var(--color-panel-if-solid, var(--color-panel-translucent))", + ], + ]; + for (const [name, value] of defaultTheme) values.set(name, value); + + // Radix defines its pure gray as `--gray-*` on `:root` and lets a gray theme + // replace it. Here it is the `gray` gray theme, and no accent or gray is + // defined outside a theme, so that an app pays for the scales it uses. + /** @type {[string, Value][]} */ + const pureGray = []; + for (const [name, value] of values) { + if (GROUPS.find(([, , pattern]) => pattern.test(name))?.[0] === "gray") { + pureGray.push([name, value]); + values.set(name, "initial"); + } + } + for (const name of required(accents, defaults.accentColor).keys()) { + values.set(name, "initial"); + } + + /** @type {Map} */ + const grouped = new Map(); + /** @type {Map} */ + const scales = new Map(); + for (const entry of values) { + const group = GROUPS.find(([, , pattern]) => pattern.test(entry[0]))?.[0]; + const scale = /^--([a-z]+)-/.exec(entry[0])?.[1] ?? ""; + if (!group && !values.has(`--${scale}-a9`)) { + throw new Error(`${entry[0]} is in no group and in no color scale.`); + } + const target = group ? grouped : scales; + if (!target.has(group ?? scale)) target.set(group ?? scale, []); + /** @type {[string, Value][]} */ (target.get(group ?? scale)).push(entry); + } + for (const [scale, vars] of [...scales].sort(byName)) { + modules.define(`colors/${scale}.stylex.js`, scale, vars); + } + for (const [name, module] of GROUPS) { + modules.define(module, name, grouped.get(name) ?? []); + } + modules.writeGroups(); + + /** + * Write one module for each value of a theme attribute. + * + * @param {string} attribute The attribute, such as `accent-color`. + * @param {string} prefix What the names of its themes start with. + * @param {string} group The group its themes override. + * @param {(name: string) => string} module The module of a value. + * @param {[string, [string, Value][]][]} [extra] Themes Radix has no rule for. + * @returns {Record} The module and the export of + * the theme of each value. + */ + const themeModules = (attribute, prefix, group, module, extra = []) => { + /** @type {Record} */ + const written = {}; + /** @type {[string, [string, Value][]][]} */ + const all = [ + ...extra, + ...[...themes[attribute]].map( + ([name, vars]) => + /** @type {[string, [string, Value][]]} */ ([name, [...vars]]), + ), + ]; + /** @type {Map} */ + const byModule = new Map(); + for (const [name, vars] of all.sort(byName)) { + const path = module(name); + if (!byModule.has(path)) byModule.set(path, []); + /** @type {[string, string, [string, Value][]][]} */ ( + byModule.get(path) + ).push([themeExport(prefix, name), group, vars]); + written[name] = [path, themeExport(prefix, name)]; + } + for (const [path, list] of byModule) modules.writeThemes(path, list); + return written; + }; + + const accentThemes = themeModules( + "accent-color", + "accent", + "accent", + (name) => `themes/accent/${name}.js`, + ); + const grayThemes = themeModules( + "gray-color", + "gray", + "gray", + (name) => `themes/gray/${name}.js`, + [["gray", pureGray]], + ); + const radiusThemes = themeModules( + "radius", + "radius", + "radiusFactor", + () => "themes/radius.js", + ); + const scalingThemes = themeModules( + "scaling", + "scaling", + "scaling", + () => "themes/scaling.js", + ); + const panelThemes = themeModules( + "panel-background", + "panel", + "panel", + () => "themes/panel.js", + ); + + for (const [group, vars] of grouped) { + const derived = vars.some(([, value]) => + (typeof value === "string" ? value : value.default).includes("var("), + ); + if (derived && group !== "focus" && !SCOPED.includes(group)) { + throw new Error(`${group} reads a variable and has no scope theme.`); + } + } + const [focusTheme] = modules.writeThemes("themes/focus.js", [ + ["focusScope", "focus", []], + ]); + const scopeThemes = modules.writeThemes( + "themes/scope.js", + SCOPED.map((group) => [`${group}Scope`, group, []]), + ); + + /** @type {Map>} */ + const imports = new Map(); + const styles = Object.entries(element).map( + ([key, declarations]) => + ` ${key}: {\n${declarations.map(([name, value]) => property(" ", camelCase(name), modules.expression(value, "themes/theme.js", imports))).join("")} },\n`, + ); + modules.write("themes/theme.js", imports, [ + `export const theme = stylex.create({\n${styles.join("")}});\n`, + ]); + + /** @type {Record} */ + const varGroups = {}; + for (const [module, groups] of modules.groups) { + for (const { name, vars } of groups) { + varGroups[name] = [module, vars.map(([variable]) => variable)]; + } + } + const data = [ + ["RADIX_THEMES_VERSION", "str", version], + ["VAR_GROUPS", "dict[str, tuple[str, tuple[str, ...]]]", varGroups], + ["ACCENT_THEMES", "dict[str, tuple[str, str]]", accentThemes], + ["GRAY_THEMES", "dict[str, tuple[str, str]]", grayThemes], + ["RADIUS_THEMES", "dict[str, tuple[str, str]]", radiusThemes], + ["SCALING_THEMES", "dict[str, tuple[str, str]]", scalingThemes], + ["PANEL_BACKGROUND_THEMES", "dict[str, tuple[str, str]]", panelThemes], + ["SCOPE_THEMES", "tuple[tuple[str, str], ...]", scopeThemes], + ["FOCUS_THEME", "tuple[str, str]", focusTheme], + [ + "THEME_STYLES", + "tuple[str, str, tuple[str, ...]]", + ["themes/theme.js", "theme", Object.keys(element)], + ], + [ + "MATCHING_GRAY", + "dict[str, str]", + Object.fromEntries( + Object.keys(accentThemes).map((accent) => [ + accent, + matchingGray(accent), + ]), + ), + ], + [ + "DEFAULTS", + "dict[str, str]", + { + accent_color: defaults.accentColor, + gray_color: defaults.grayColor, + radius: defaults.radius, + scaling: defaults.scaling, + panel_background: defaults.panelBackground, + }, + ], + ]; + modules.files.push({ + path: "src/reflex_components_ui/_radix_tokens.py", + render: () => + `"""The StyleX modules generated from @radix-ui/themes, and what they define.\n\nGenerated by js/scripts/generate.js. Do not edit.\n"""\n\n${data.map(([name, type, value]) => `${name}: ${type} = ${python(value)}\n`).join("\n")}`, + }); + return modules.files; +} diff --git a/packages/reflex-components-ui/js/src/colors/amber.stylex.js b/packages/reflex-components-ui/js/src/colors/amber.stylex.js new file mode 100644 index 00000000000..1c48e05927e --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/amber.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const amber = stylex.defineVars({ + "--amber-1": { + default: "light-dark(#fefdfb, #16120c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.992 0.985), color(display-p3 0.082 0.07 0.05))", + }, + }, + "--amber-2": { + default: "light-dark(#fefbe9, #1d180f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.994 0.986 0.921), color(display-p3 0.111 0.094 0.064))", + }, + }, + "--amber-3": { + default: "light-dark(#fff7c2, #302008)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.994 0.969 0.782), color(display-p3 0.178 0.128 0.049))", + }, + }, + "--amber-4": { + default: "light-dark(#ffee9c, #3f2700)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.989 0.937 0.65), color(display-p3 0.239 0.156 0))", + }, + }, + "--amber-5": { + default: "light-dark(#fbe577, #4d3000)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.97 0.902 0.527), color(display-p3 0.29 0.193 0))", + }, + }, + "--amber-6": { + default: "light-dark(#f3d673, #5c3d05)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.936 0.844 0.506), color(display-p3 0.344 0.245 0.076))", + }, + }, + "--amber-7": { + default: "light-dark(#e9c162, #714f19)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.89 0.762 0.443), color(display-p3 0.422 0.314 0.141))", + }, + }, + "--amber-8": { + default: "light-dark(#e2a336, #8f6424)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.85 0.65 0.3), color(display-p3 0.535 0.399 0.189))", + }, + }, + "--amber-9": { + default: "#ffc53d", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 0.77 0.26)", + }, + }, + "--amber-10": { + default: "light-dark(#ffba18, #ffd60a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.959 0.741 0.274), color(display-p3 1 0.87 0.15))", + }, + }, + "--amber-11": { + default: "light-dark(#ab6400, #ffca16)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.64 0.4 0), color(display-p3 1 0.8 0.29))", + }, + }, + "--amber-12": { + default: "light-dark(#4f3422, #ffe7b3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.294 0.208 0.145), color(display-p3 0.984 0.909 0.726))", + }, + }, + "--amber-a1": { + default: "light-dark(#c0800004, #e63c0006)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.757 0.514 0.024 / 0.016), color(display-p3 0.992 0.298 0 / 0.017))", + }, + }, + "--amber-a2": { + default: "light-dark(#f4d10016, #fd9b000d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.902 0.804 0.008 / 0.079), color(display-p3 0.988 0.651 0 / 0.047))", + }, + }, + "--amber-a3": { + default: "light-dark(#ffde003d, #fa820022)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.965 0.859 0.004 / 0.22), color(display-p3 1 0.6 0 / 0.118))", + }, + }, + "--amber-a4": { + default: "light-dark(#ffd40063, #fc820032)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.969 0.82 0.004 / 0.35), color(display-p3 1 0.557 0 / 0.185))", + }, + }, + "--amber-a5": { + default: "light-dark(#f8cf0088, #fd8b0041)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.933 0.796 0.004 / 0.475), color(display-p3 1 0.592 0 / 0.24))", + }, + }, + "--amber-a6": { + default: "light-dark(#eab5008c, #fd9b0051)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.875 0.682 0.004 / 0.495), color(display-p3 1 0.659 0.094 / 0.299))", + }, + }, + "--amber-a7": { + default: "light-dark(#dc9b009d, #ffab2567)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.804 0.573 0 / 0.557), color(display-p3 1 0.714 0.263 / 0.383))", + }, + }, + "--amber-a8": { + default: "light-dark(#da8a00c9, #ffae3587)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.788 0.502 0 / 0.699), color(display-p3 0.996 0.729 0.306 / 0.5))", + }, + }, + "--amber-a9": { + default: "light-dark(#ffb300c2, #ffc53d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 0.686 0 / 0.742), color(display-p3 1 0.769 0.259))", + }, + }, + "--amber-a10": { + default: "light-dark(#ffb300e7, #ffd60a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.945 0.643 0 / 0.726), color(display-p3 1 0.871 0.149))", + }, + }, + "--amber-a11": { + default: "light-dark(#ab6400, #ffca16)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.64 0.4 0), color(display-p3 1 0.8 0.29))", + }, + }, + "--amber-a12": { + default: "light-dark(#341500dd, #ffe7b3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.294 0.208 0.145), color(display-p3 0.984 0.909 0.726))", + }, + }, + "--amber-surface": { + default: "light-dark(#fefae4cc, #271f1380)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9922 0.9843 0.902 / 0.8), color(display-p3 0.1412 0.1176 0.0784 / 0.5))", + }, + }, + "--amber-indicator": "var(--amber-9)", + "--amber-track": + "light-dark(var(--amber-9), color-mix(in oklab, var(--amber-8), var(--amber-9) 75%))", + "--amber-contrast": "#21201c", +}); diff --git a/packages/reflex-components-ui/js/src/colors/black.stylex.js b/packages/reflex-components-ui/js/src/colors/black.stylex.js new file mode 100644 index 00000000000..0b72ded3023 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/black.stylex.js @@ -0,0 +1,90 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const black = stylex.defineVars({ + "--black-a1": { + default: "rgba(0, 0, 0, 0.05)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.05)", + }, + }, + "--black-a2": { + default: "rgba(0, 0, 0, 0.1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.1)", + }, + }, + "--black-a3": { + default: "rgba(0, 0, 0, 0.15)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.15)", + }, + }, + "--black-a4": { + default: "rgba(0, 0, 0, 0.2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.2)", + }, + }, + "--black-a5": { + default: "rgba(0, 0, 0, 0.3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.3)", + }, + }, + "--black-a6": { + default: "rgba(0, 0, 0, 0.4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.4)", + }, + }, + "--black-a7": { + default: "rgba(0, 0, 0, 0.5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.5)", + }, + }, + "--black-a8": { + default: "rgba(0, 0, 0, 0.6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.6)", + }, + }, + "--black-a9": { + default: "rgba(0, 0, 0, 0.7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.7)", + }, + }, + "--black-a10": { + default: "rgba(0, 0, 0, 0.8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.8)", + }, + }, + "--black-a11": { + default: "rgba(0, 0, 0, 0.9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.9)", + }, + }, + "--black-a12": { + default: "rgba(0, 0, 0, 0.95)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0.95)", + }, + }, +}); diff --git a/packages/reflex-components-ui/js/src/colors/blue.stylex.js b/packages/reflex-components-ui/js/src/colors/blue.stylex.js new file mode 100644 index 00000000000..2b8ecf5161b --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/blue.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const blue = stylex.defineVars({ + "--blue-1": { + default: "light-dark(#fbfdff, #0d1520)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.986 0.992 0.999), color(display-p3 0.057 0.081 0.122))", + }, + }, + "--blue-2": { + default: "light-dark(#f4faff, #111927)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.96 0.979 0.998), color(display-p3 0.072 0.098 0.147))", + }, + }, + "--blue-3": { + default: "light-dark(#e6f4fe, #0d2847)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.912 0.956 0.991), color(display-p3 0.078 0.154 0.27))", + }, + }, + "--blue-4": { + default: "light-dark(#d5efff, #003362)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.853 0.932 1), color(display-p3 0.033 0.197 0.37))", + }, + }, + "--blue-5": { + default: "light-dark(#c2e5ff, #004074)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.788 0.894 0.998), color(display-p3 0.08 0.245 0.441))", + }, + }, + "--blue-6": { + default: "light-dark(#acd8fc, #104d87)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.709 0.843 0.976), color(display-p3 0.14 0.298 0.511))", + }, + }, + "--blue-7": { + default: "light-dark(#8ec8f6, #205d9e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.606 0.777 0.947), color(display-p3 0.195 0.361 0.6))", + }, + }, + "--blue-8": { + default: "light-dark(#5eb1ef, #2870bd)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.451 0.688 0.917), color(display-p3 0.239 0.434 0.72))", + }, + }, + "--blue-9": { + default: "#0090ff", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.247 0.556 0.969)", + }, + }, + "--blue-10": { + default: "light-dark(#0588f0, #3b9eff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.234 0.523 0.912), color(display-p3 0.344 0.612 0.973))", + }, + }, + "--blue-11": { + default: "light-dark(#0d74ce, #70b8ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.15 0.44 0.84), color(display-p3 0.49 0.72 1))", + }, + }, + "--blue-12": { + default: "light-dark(#113264, #c2e6ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.102 0.193 0.379), color(display-p3 0.788 0.898 0.99))", + }, + }, + "--blue-a1": { + default: "light-dark(#0080ff04, #004df211)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.514 1 / 0.016), color(display-p3 0 0.333 1 / 0.059))", + }, + }, + "--blue-a2": { + default: "light-dark(#008cff0b, #1166fb18)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.514 0.906 / 0.04), color(display-p3 0.114 0.435 0.988 / 0.085))", + }, + }, + "--blue-a3": { + default: "light-dark(#008ff519, #0077ff3a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.506 0.914 / 0.087), color(display-p3 0.122 0.463 1 / 0.219))", + }, + }, + "--blue-a4": { + default: "light-dark(#009eff2a, #0075ff57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.545 1 / 0.146), color(display-p3 0 0.467 1 / 0.324))", + }, + }, + "--blue-a5": { + default: "light-dark(#0093ff3d, #0081fd6b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.502 0.984 / 0.212), color(display-p3 0.098 0.51 1 / 0.4))", + }, + }, + "--blue-a6": { + default: "light-dark(#0088f653, #0f89fd7f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.463 0.922 / 0.291), color(display-p3 0.224 0.557 1 / 0.475))", + }, + }, + "--blue-a7": { + default: "light-dark(#0083eb71, #2a91fe98)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.431 0.863 / 0.393), color(display-p3 0.294 0.584 1 / 0.572))", + }, + }, + "--blue-a8": { + default: "light-dark(#0084e6a1, #3094feb9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.427 0.851 / 0.55), color(display-p3 0.314 0.592 1 / 0.702))", + }, + }, + "--blue-a9": { + default: "#0090ff", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.412 0.961 / 0.753), color(display-p3 0.251 0.573 0.996 / 0.967))", + }, + }, + "--blue-a10": { + default: "light-dark(#0086f0fa, #3b9eff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.376 0.886 / 0.765), color(display-p3 0.357 0.631 1 / 0.971))", + }, + }, + "--blue-a11": { + default: "light-dark(#006dcbf2, #70b8ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.15 0.44 0.84), color(display-p3 0.49 0.72 1))", + }, + }, + "--blue-a12": { + default: "light-dark(#002359ee, #c2e6ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.102 0.193 0.379), color(display-p3 0.788 0.898 0.99))", + }, + }, + "--blue-surface": { + default: "light-dark(#f1f9ffcc, #11213d80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9529 0.9765 0.9961 / 0.8), color(display-p3 0.0706 0.1255 0.2196 / 0.5))", + }, + }, + "--blue-indicator": "var(--blue-9)", + "--blue-track": "var(--blue-9)", + "--blue-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/bronze.stylex.js b/packages/reflex-components-ui/js/src/colors/bronze.stylex.js new file mode 100644 index 00000000000..6659b95ac2f --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/bronze.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const bronze = stylex.defineVars({ + "--bronze-1": { + default: "light-dark(#fdfcfc, #141110)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.991 0.988 0.988), color(display-p3 0.076 0.067 0.063))", + }, + }, + "--bronze-2": { + default: "light-dark(#fdf7f5, #1c1917)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.989 0.97 0.961), color(display-p3 0.106 0.097 0.093))", + }, + }, + "--bronze-3": { + default: "light-dark(#f6edea, #262220)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.958 0.932 0.919), color(display-p3 0.147 0.132 0.125))", + }, + }, + "--bronze-4": { + default: "light-dark(#efe4df, #302a27)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.929 0.894 0.877), color(display-p3 0.185 0.166 0.156))", + }, + }, + "--bronze-5": { + default: "light-dark(#e7d9d3, #3b3330)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.898 0.853 0.832), color(display-p3 0.227 0.202 0.19))", + }, + }, + "--bronze-6": { + default: "light-dark(#dfcdc5, #493e3a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.861 0.805 0.778), color(display-p3 0.278 0.246 0.23))", + }, + }, + "--bronze-7": { + default: "light-dark(#d3bcb3, #5a4c47)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.812 0.739 0.706), color(display-p3 0.343 0.302 0.281))", + }, + }, + "--bronze-8": { + default: "light-dark(#c2a499, #6f5f58)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.741 0.647 0.606), color(display-p3 0.426 0.374 0.347))", + }, + }, + "--bronze-9": { + default: "#a18072", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.611 0.507 0.455)", + }, + }, + "--bronze-10": { + default: "light-dark(#957468, #ae8c7e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.563 0.461 0.414), color(display-p3 0.66 0.556 0.504))", + }, + }, + "--bronze-11": { + default: "light-dark(#7d5e54, #d4b3a5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.471 0.373 0.336), color(display-p3 0.81 0.707 0.655))", + }, + }, + "--bronze-12": { + default: "light-dark(#43302b, #ede0d9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.251 0.191 0.172), color(display-p3 0.921 0.88 0.854))", + }, + }, + "--bronze-a1": { + default: "light-dark(#55000003, #d1110004)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.349 0.024 0.024 / 0.012), color(display-p3 0.941 0.067 0 / 0.009))", + }, + }, + "--bronze-a2": { + default: "light-dark(#cc33000a, #fbbc910c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.71 0.22 0.024 / 0.04), color(display-p3 0.98 0.8 0.706 / 0.043))", + }, + }, + "--bronze-a3": { + default: "light-dark(#92250015, #faceb817)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.482 0.2 0.008 / 0.083), color(display-p3 0.988 0.851 0.761 / 0.085))", + }, + }, + "--bronze-a4": { + default: "light-dark(#80280020, #facdb622)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.424 0.133 0.004 / 0.122), color(display-p3 0.996 0.839 0.78 / 0.127))", + }, + }, + "--bronze-a5": { + default: "light-dark(#7423002c, #ffd2c12d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.4 0.145 0.004 / 0.169), color(display-p3 0.996 0.863 0.773 / 0.173))", + }, + }, + "--bronze-a6": { + default: "light-dark(#7324003a, #ffd1c03c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.388 0.125 0.004 / 0.224), color(display-p3 1 0.863 0.796 / 0.227))", + }, + }, + "--bronze-a7": { + default: "light-dark(#6c1f004c, #fdd0c04f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.365 0.11 0.004 / 0.295), color(display-p3 1 0.867 0.8 / 0.295))", + }, + }, + "--bronze-a8": { + default: "light-dark(#671c0066, #ffd6c565)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.341 0.102 0.004 / 0.393), color(display-p3 1 0.859 0.788 / 0.387))", + }, + }, + "--bronze-a9": { + default: "light-dark(#551a008d, #fec7b09b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.29 0.094 0 / 0.546), color(display-p3 1 0.82 0.733 / 0.585))", + }, + }, + "--bronze-a10": { + default: "light-dark(#4c150097, #fecab5a9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.255 0.082 0 / 0.585), color(display-p3 1 0.839 0.761 / 0.635))", + }, + }, + "--bronze-a11": { + default: "light-dark(#3d0f00ab, #ffd7c6d1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.471 0.373 0.336), color(display-p3 0.81 0.707 0.655))", + }, + }, + "--bronze-a12": { + default: "light-dark(#1d0600d4, #fff1e9ec)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.251 0.191 0.172), color(display-p3 0.921 0.88 0.854))", + }, + }, + "--bronze-surface": { + default: "light-dark(#fdf5f3cc, #27211d80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9843 0.9608 0.9529 / 0.8), color(display-p3 0.1412 0.1255 0.1176 / 0.5))", + }, + }, + "--bronze-indicator": "var(--bronze-9)", + "--bronze-track": "var(--bronze-9)", + "--bronze-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/brown.stylex.js b/packages/reflex-components-ui/js/src/colors/brown.stylex.js new file mode 100644 index 00000000000..66972b307e9 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/brown.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const brown = stylex.defineVars({ + "--brown-1": { + default: "light-dark(#fefdfc, #12110f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.992 0.989), color(display-p3 0.071 0.067 0.059))", + }, + }, + "--brown-2": { + default: "light-dark(#fcf9f6, #1c1816)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.987 0.976 0.964), color(display-p3 0.107 0.095 0.087))", + }, + }, + "--brown-3": { + default: "light-dark(#f6eee7, #28211d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.959 0.936 0.909), color(display-p3 0.151 0.13 0.115))", + }, + }, + "--brown-4": { + default: "light-dark(#f0e4d9, #322922)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.934 0.897 0.855), color(display-p3 0.191 0.161 0.138))", + }, + }, + "--brown-5": { + default: "light-dark(#ebdaca, #3e3128)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.909 0.856 0.798), color(display-p3 0.235 0.194 0.162))", + }, + }, + "--brown-6": { + default: "light-dark(#e4cdb7, #4d3c2f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.88 0.808 0.73), color(display-p3 0.291 0.237 0.192))", + }, + }, + "--brown-7": { + default: "light-dark(#dcbc9f, #614a39)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.841 0.742 0.639), color(display-p3 0.365 0.295 0.232))", + }, + }, + "--brown-8": { + default: "light-dark(#cea37e, #7c5f46)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.782 0.647 0.514), color(display-p3 0.469 0.377 0.287))", + }, + }, + "--brown-9": { + default: "#ad7f58", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.651 0.505 0.368)", + }, + }, + "--brown-10": { + default: "light-dark(#a07553, #b88c67)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.601 0.465 0.344), color(display-p3 0.697 0.557 0.423))", + }, + }, + "--brown-11": { + default: "light-dark(#815e46, #dbb594)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.485 0.374 0.288), color(display-p3 0.835 0.715 0.597))", + }, + }, + "--brown-12": { + default: "light-dark(#3e332e, #f2e1ca)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.236 0.202 0.183), color(display-p3 0.938 0.885 0.802))", + }, + }, + "--brown-a1": { + default: "light-dark(#aa550003, #91110002)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.349 0.024 / 0.012), color(display-p3 0.855 0.071 0 / 0.005))", + }, + }, + "--brown-a2": { + default: "light-dark(#aa550009, #fba67c0c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.349 0.024 / 0.036), color(display-p3 0.98 0.706 0.525 / 0.043))", + }, + }, + "--brown-a3": { + default: "light-dark(#a04b0018, #fcb58c19)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.573 0.314 0.012 / 0.091), color(display-p3 0.996 0.745 0.576 / 0.093))", + }, + }, + "--brown-a4": { + default: "light-dark(#9b4a0026, #fbbb8a24)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.545 0.302 0.008 / 0.146), color(display-p3 1 0.765 0.592 / 0.135))", + }, + }, + "--brown-a5": { + default: "light-dark(#9f4d0035, #fcb88931)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.561 0.29 0.004 / 0.204), color(display-p3 1 0.761 0.588 / 0.181))", + }, + }, + "--brown-a6": { + default: "light-dark(#a04e0048, #fdba8741)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.553 0.294 0.004 / 0.271), color(display-p3 1 0.773 0.592 / 0.24))", + }, + }, + "--brown-a7": { + default: "light-dark(#a34e0060, #ffbb8856)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.557 0.286 0.004 / 0.361), color(display-p3 0.996 0.776 0.58 / 0.32))", + }, + }, + "--brown-a8": { + default: "light-dark(#9f4a0081, #ffbe8773)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.549 0.275 0.004 / 0.487), color(display-p3 1 0.78 0.573 / 0.433))", + }, + }, + "--brown-a9": { + default: "light-dark(#823c00a7, #feb87da8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.447 0.22 0 / 0.632), color(display-p3 1 0.769 0.549 / 0.627))", + }, + }, + "--brown-a10": { + default: "light-dark(#723300ac, #ffc18cb3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.388 0.188 0 / 0.655), color(display-p3 1 0.792 0.596 / 0.677))", + }, + }, + "--brown-a11": { + default: "light-dark(#522100b9, #fed1aad9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.485 0.374 0.288), color(display-p3 0.835 0.715 0.597))", + }, + }, + "--brown-a12": { + default: "light-dark(#140600d1, #feecd4f2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.236 0.202 0.183), color(display-p3 0.938 0.885 0.802))", + }, + }, + "--brown-surface": { + default: "light-dark(#fbf8f4cc, #271f1b80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9843 0.9725 0.9569 / 0.8), color(display-p3 0.1412 0.1176 0.102 / 0.5))", + }, + }, + "--brown-indicator": "var(--brown-9)", + "--brown-track": "var(--brown-9)", + "--brown-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/crimson.stylex.js b/packages/reflex-components-ui/js/src/colors/crimson.stylex.js new file mode 100644 index 00000000000..295be72940e --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/crimson.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const crimson = stylex.defineVars({ + "--crimson-1": { + default: "light-dark(#fffcfd, #191114)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.998 0.989 0.992), color(display-p3 0.093 0.068 0.078))", + }, + }, + "--crimson-2": { + default: "light-dark(#fef7f9, #201318)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.991 0.969 0.976), color(display-p3 0.117 0.078 0.095))", + }, + }, + "--crimson-3": { + default: "light-dark(#ffe9f0, #381525)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.987 0.917 0.941), color(display-p3 0.203 0.091 0.143))", + }, + }, + "--crimson-4": { + default: "light-dark(#fedce7, #4d122f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.975 0.866 0.904), color(display-p3 0.277 0.087 0.182))", + }, + }, + "--crimson-5": { + default: "light-dark(#facedd, #5c1839)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.953 0.813 0.864), color(display-p3 0.332 0.115 0.22))", + }, + }, + "--crimson-6": { + default: "light-dark(#f3bed1, #6d2545)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.921 0.755 0.817), color(display-p3 0.394 0.162 0.268))", + }, + }, + "--crimson-7": { + default: "light-dark(#eaacc3, #873356)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.88 0.683 0.761), color(display-p3 0.489 0.222 0.336))", + }, + }, + "--crimson-8": { + default: "light-dark(#e093b2, #b0436e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.834 0.592 0.694), color(display-p3 0.638 0.289 0.429))", + }, + }, + "--crimson-9": { + default: "#e93d82", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.843 0.298 0.507)", + }, + }, + "--crimson-10": { + default: "light-dark(#df3478, #ee518a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.807 0.266 0.468), color(display-p3 0.864 0.364 0.539))", + }, + }, + "--crimson-11": { + default: "light-dark(#cb1d63, #ff92ad)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.731 0.195 0.388), color(display-p3 1 0.56 0.66))", + }, + }, + "--crimson-12": { + default: "light-dark(#621639, #fdd3e8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.352 0.111 0.221), color(display-p3 0.966 0.834 0.906))", + }, + }, + "--crimson-a1": { + default: "light-dark(#ff005503, #f4126709)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.024 0.349 / 0.012), color(display-p3 0.984 0.071 0.463 / 0.03))", + }, + }, + "--crimson-a2": { + default: "light-dark(#e0004008, #f22f7a11)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.757 0.02 0.267 / 0.032), color(display-p3 0.996 0.282 0.569 / 0.055))", + }, + }, + "--crimson-a3": { + default: "light-dark(#ff005216, #fe2a8b2a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.859 0.008 0.294 / 0.083), color(display-p3 0.996 0.227 0.573 / 0.148))", + }, + }, + "--crimson-a4": { + default: "light-dark(#f8005123, #fd158741)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.827 0.008 0.298 / 0.134), color(display-p3 1 0.157 0.569 / 0.227))", + }, + }, + "--crimson-a5": { + default: "light-dark(#e5004f31, #fd278f51)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.753 0.008 0.275 / 0.189), color(display-p3 1 0.231 0.604 / 0.286))", + }, + }, + "--crimson-a6": { + default: "light-dark(#d0004b41, #fe459763)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.682 0.004 0.247 / 0.244), color(display-p3 1 0.337 0.643 / 0.349))", + }, + }, + "--crimson-a7": { + default: "light-dark(#bf004753, #fd559b7f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.62 0.004 0.251 / 0.318), color(display-p3 1 0.416 0.663 / 0.454))", + }, + }, + "--crimson-a8": { + default: "light-dark(#b6004a6c, #fe5b9bab)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.6 0.004 0.251 / 0.408), color(display-p3 0.996 0.427 0.651 / 0.614))", + }, + }, + "--crimson-a9": { + default: "light-dark(#e2005bc2, #fe418de8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.776 0 0.298 / 0.702), color(display-p3 1 0.345 0.596 / 0.832))", + }, + }, + "--crimson-a10": { + default: "light-dark(#d70056cb, #ff5693ed)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.737 0 0.275 / 0.734), color(display-p3 1 0.42 0.62 / 0.853))", + }, + }, + "--crimson-a11": { + default: "light-dark(#c4004fe2, #ff92ad)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.731 0.195 0.388), color(display-p3 1 0.56 0.66))", + }, + }, + "--crimson-a12": { + default: "light-dark(#530026e9, #ffd5eafd)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.352 0.111 0.221), color(display-p3 0.966 0.834 0.906))", + }, + }, + "--crimson-surface": { + default: "light-dark(#fef5f8cc, #2f151f80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9922 0.9608 0.9725 / 0.8), color(display-p3 0.1647 0.0863 0.1176 / 0.5))", + }, + }, + "--crimson-indicator": "var(--crimson-9)", + "--crimson-track": "var(--crimson-9)", + "--crimson-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/cyan.stylex.js b/packages/reflex-components-ui/js/src/colors/cyan.stylex.js new file mode 100644 index 00000000000..37f9d06178f --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/cyan.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const cyan = stylex.defineVars({ + "--cyan-1": { + default: "light-dark(#fafdfe, #0b161a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.982 0.992 0.996), color(display-p3 0.053 0.085 0.098))", + }, + }, + "--cyan-2": { + default: "light-dark(#f2fafb, #101b20)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.955 0.981 0.984), color(display-p3 0.072 0.105 0.122))", + }, + }, + "--cyan-3": { + default: "light-dark(#def7f9, #082c36)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.888 0.965 0.975), color(display-p3 0.073 0.168 0.209))", + }, + }, + "--cyan-4": { + default: "light-dark(#caf1f6, #003848)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.821 0.941 0.959), color(display-p3 0.063 0.216 0.277))", + }, + }, + "--cyan-5": { + default: "light-dark(#b5e9f0, #004558)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.751 0.907 0.935), color(display-p3 0.091 0.267 0.336))", + }, + }, + "--cyan-6": { + default: "light-dark(#9ddde7, #045468)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.671 0.862 0.9), color(display-p3 0.137 0.324 0.4))", + }, + }, + "--cyan-7": { + default: "light-dark(#7dcedc, #12677e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.564 0.8 0.854), color(display-p3 0.186 0.398 0.484))", + }, + }, + "--cyan-8": { + default: "light-dark(#3db9cf, #11809c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.388 0.715 0.798), color(display-p3 0.23 0.496 0.6))", + }, + }, + "--cyan-9": { + default: "#00a2c7", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.282 0.627 0.765)", + }, + }, + "--cyan-10": { + default: "light-dark(#0797b9, #23afd0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.264 0.583 0.71), color(display-p3 0.331 0.675 0.801))", + }, + }, + "--cyan-11": { + default: "light-dark(#107d98, #4ccce6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.08 0.48 0.63), color(display-p3 0.446 0.79 0.887))", + }, + }, + "--cyan-12": { + default: "light-dark(#0d3c48, #b6ecf7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.108 0.232 0.277), color(display-p3 0.757 0.919 0.962))", + }, + }, + "--cyan-a1": { + default: "light-dark(#0099cc05, #0091f70a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.608 0.804 / 0.02), color(display-p3 0 0.647 0.992 / 0.034))", + }, + }, + "--cyan-a2": { + default: "light-dark(#009db10d, #02a7f211)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.557 0.647 / 0.044), color(display-p3 0.133 0.733 1 / 0.059))", + }, + }, + "--cyan-a3": { + default: "light-dark(#00c2d121, #00befd28)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.694 0.796 / 0.114), color(display-p3 0.122 0.741 0.996 / 0.152))", + }, + }, + "--cyan-a4": { + default: "light-dark(#00bcd435, #00baff3b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.678 0.784 / 0.181), color(display-p3 0.051 0.725 1 / 0.227))", + }, + }, + "--cyan-a5": { + default: "light-dark(#01b4cc4a, #00befd4d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.624 0.733 / 0.248), color(display-p3 0.149 0.757 1 / 0.29))", + }, + }, + "--cyan-a6": { + default: "light-dark(#00a7c162, #00c7fd5e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.584 0.706 / 0.33), color(display-p3 0.267 0.792 1 / 0.358))", + }, + }, + "--cyan-a7": { + default: "light-dark(#009fbb82, #14cdff75)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.541 0.667 / 0.436), color(display-p3 0.333 0.808 1 / 0.446))", + }, + }, + "--cyan-a8": { + default: "light-dark(#00a3c0c2, #11cfff95)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.533 0.667 / 0.612), color(display-p3 0.357 0.816 1 / 0.572))", + }, + }, + "--cyan-a9": { + default: "light-dark(#00a2c7, #00cfffc3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.482 0.675 / 0.718), color(display-p3 0.357 0.82 1 / 0.748))", + }, + }, + "--cyan-a10": { + default: "light-dark(#0094b7f8, #28d6ffcd)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.435 0.608 / 0.738), color(display-p3 0.4 0.839 1 / 0.786))", + }, + }, + "--cyan-a11": { + default: "light-dark(#007491ef, #52e1fee5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.08 0.48 0.63), color(display-p3 0.446 0.79 0.887))", + }, + }, + "--cyan-a12": { + default: "light-dark(#00323ef2, #bbf3fef7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.108 0.232 0.277), color(display-p3 0.757 0.919 0.962))", + }, + }, + "--cyan-surface": { + default: "light-dark(#eff9facc, #11252d80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9412 0.9765 0.9804 / 0.8), color(display-p3 0.0784 0.1412 0.1725 / 0.5))", + }, + }, + "--cyan-indicator": "var(--cyan-9)", + "--cyan-track": "var(--cyan-9)", + "--cyan-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/gold.stylex.js b/packages/reflex-components-ui/js/src/colors/gold.stylex.js new file mode 100644 index 00000000000..d0140c60a35 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/gold.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const gold = stylex.defineVars({ + "--gold-1": { + default: "light-dark(#fdfdfc, #121211)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.992 0.992 0.989), color(display-p3 0.071 0.071 0.067))", + }, + }, + "--gold-2": { + default: "light-dark(#faf9f2, #1b1a17)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.98 0.976 0.953), color(display-p3 0.104 0.101 0.09))", + }, + }, + "--gold-3": { + default: "light-dark(#f2f0e7, #24231f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.947 0.94 0.909), color(display-p3 0.141 0.136 0.122))", + }, + }, + "--gold-4": { + default: "light-dark(#eae6db, #2d2b26)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.914 0.904 0.865), color(display-p3 0.177 0.17 0.152))", + }, + }, + "--gold-5": { + default: "light-dark(#e1dccf, #38352e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.88 0.865 0.816), color(display-p3 0.217 0.207 0.185))", + }, + }, + "--gold-6": { + default: "light-dark(#d8d0bf, #444039)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.84 0.818 0.756), color(display-p3 0.265 0.252 0.225))", + }, + }, + "--gold-7": { + default: "light-dark(#cbc0aa, #544f46)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.788 0.753 0.677), color(display-p3 0.327 0.31 0.277))", + }, + }, + "--gold-8": { + default: "light-dark(#b9a88d, #696256)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.715 0.66 0.565), color(display-p3 0.407 0.384 0.342))", + }, + }, + "--gold-9": { + default: "#978365", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.579 0.517 0.41)", + }, + }, + "--gold-10": { + default: "light-dark(#8c7a5e, #a39073)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.538 0.479 0.38), color(display-p3 0.628 0.566 0.463))", + }, + }, + "--gold-11": { + default: "light-dark(#71624b, #cbb99f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.433 0.386 0.305), color(display-p3 0.784 0.728 0.635))", + }, + }, + "--gold-12": { + default: "light-dark(#3b352b, #e8e2d9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.227 0.209 0.173), color(display-p3 0.906 0.887 0.855))", + }, + }, + "--gold-a1": { + default: "light-dark(#55550003, #91911102)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.349 0.349 0.024 / 0.012), color(display-p3 0.855 0.855 0.071 / 0.005))", + }, + }, + "--gold-a2": { + default: "light-dark(#9d8a000d, #f9e29d0b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.592 0.514 0.024 / 0.048), color(display-p3 0.98 0.89 0.616 / 0.043))", + }, + }, + "--gold-a3": { + default: "light-dark(#75600018, #f8ecbb15)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.4 0.357 0.012 / 0.091), color(display-p3 1 0.949 0.753 / 0.08))", + }, + }, + "--gold-a4": { + default: "light-dark(#6b4e0024, #ffeec41e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.357 0.298 0.008 / 0.134), color(display-p3 1 0.933 0.8 / 0.118))", + }, + }, + "--gold-a5": { + default: "light-dark(#60460030, #feecc22a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.345 0.282 0.004 / 0.185), color(display-p3 1 0.949 0.804 / 0.16))", + }, + }, + "--gold-a6": { + default: "light-dark(#64440040, #feebcb37)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.341 0.263 0.004 / 0.244), color(display-p3 1 0.925 0.8 / 0.215))", + }, + }, + "--gold-a7": { + default: "light-dark(#63420055, #ffedcd48)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.345 0.235 0.004 / 0.322), color(display-p3 1 0.945 0.831 / 0.278))", + }, + }, + "--gold-a8": { + default: "light-dark(#633d0072, #fdeaca5f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.345 0.22 0.004 / 0.436), color(display-p3 1 0.937 0.82 / 0.366))", + }, + }, + "--gold-a9": { + default: "light-dark(#5332009a, #ffdba690)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.286 0.18 0 / 0.589), color(display-p3 0.996 0.882 0.69 / 0.551))", + }, + }, + "--gold-a10": { + default: "light-dark(#492d00a1, #fedfb09d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.255 0.161 0 / 0.62), color(display-p3 1 0.894 0.725 / 0.601))", + }, + }, + "--gold-a11": { + default: "light-dark(#362100b4, #fee7c6c8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.433 0.386 0.305), color(display-p3 0.784 0.728 0.635))", + }, + }, + "--gold-a12": { + default: "light-dark(#130c00d4, #fef7ede7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.227 0.209 0.173), color(display-p3 0.906 0.887 0.855))", + }, + }, + "--gold-surface": { + default: "light-dark(#f9f8efcc, #25231d80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9765 0.9725 0.9412 / 0.8), color(display-p3 0.1412 0.1333 0.1098 / 0.5))", + }, + }, + "--gold-indicator": "var(--gold-9)", + "--gold-track": "var(--gold-9)", + "--gold-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/grass.stylex.js b/packages/reflex-components-ui/js/src/colors/grass.stylex.js new file mode 100644 index 00000000000..a5445b0b4ea --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/grass.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const grass = stylex.defineVars({ + "--grass-1": { + default: "light-dark(#fbfefb, #0e1511)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.986 0.996 0.985), color(display-p3 0.062 0.083 0.067))", + }, + }, + "--grass-2": { + default: "light-dark(#f5fbf5, #141a15)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.966 0.983 0.964), color(display-p3 0.083 0.103 0.085))", + }, + }, + "--grass-3": { + default: "light-dark(#e9f6e9, #1b2a1e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.923 0.965 0.917), color(display-p3 0.118 0.163 0.122))", + }, + }, + "--grass-4": { + default: "light-dark(#daf1db, #1d3a24)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.872 0.94 0.865), color(display-p3 0.142 0.225 0.15))", + }, + }, + "--grass-5": { + default: "light-dark(#c9e8ca, #25482d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.811 0.908 0.802), color(display-p3 0.178 0.279 0.186))", + }, + }, + "--grass-6": { + default: "light-dark(#b2ddb5, #2d5736)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.733 0.864 0.724), color(display-p3 0.217 0.337 0.224))", + }, + }, + "--grass-7": { + default: "light-dark(#94ce9a, #366740)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.628 0.803 0.622), color(display-p3 0.258 0.4 0.264))", + }, + }, + "--grass-8": { + default: "light-dark(#65ba74, #3e7949)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.477 0.72 0.482), color(display-p3 0.302 0.47 0.305))", + }, + }, + "--grass-9": { + default: "#46a758", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.38 0.647 0.378)", + }, + }, + "--grass-10": { + default: "light-dark(#3e9b4f, #53b365)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.344 0.598 0.342), color(display-p3 0.426 0.694 0.426))", + }, + }, + "--grass-11": { + default: "light-dark(#2a7e3b, #71d083)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.263 0.488 0.261), color(display-p3 0.535 0.807 0.542))", + }, + }, + "--grass-12": { + default: "light-dark(#203c25, #c2f0c2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.151 0.233 0.153), color(display-p3 0.797 0.936 0.776))", + }, + }, + "--grass-a1": { + default: "light-dark(#00c00004, #00de1205)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.757 0.024 / 0.016), color(display-p3 0 0.992 0.071 / 0.017))", + }, + }, + "--grass-a2": { + default: "light-dark(#0099000a, #5ef7780a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.565 0.024 / 0.036), color(display-p3 0.482 0.996 0.584 / 0.038))", + }, + }, + "--grass-a3": { + default: "light-dark(#00970016, #70fe8c1b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.059 0.576 0.008 / 0.083), color(display-p3 0.549 0.992 0.588 / 0.106))", + }, + }, + "--grass-a4": { + default: "light-dark(#009f0725, #57ff802c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.035 0.565 0.008 / 0.134), color(display-p3 0.51 0.996 0.557 / 0.169))", + }, + }, + "--grass-a5": { + default: "light-dark(#00930536, #68ff8b3b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.047 0.545 0.008 / 0.197), color(display-p3 0.553 1 0.588 / 0.227))", + }, + }, + "--grass-a6": { + default: "light-dark(#008f0a4d, #71ff8f4b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.031 0.502 0.004 / 0.275), color(display-p3 0.584 1 0.608 / 0.29))", + }, + }, + "--grass-a7": { + default: "light-dark(#018b0f6b, #77fd925d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.482 0.004 / 0.377), color(display-p3 0.604 1 0.616 / 0.358))", + }, + }, + "--grass-a8": { + default: "light-dark(#008d199a, #77fd9070)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.467 0.008 / 0.522), color(display-p3 0.608 1 0.62 / 0.433))", + }, + }, + "--grass-a9": { + default: "light-dark(#008619b9, #65ff82a1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.435 0 / 0.624), color(display-p3 0.573 1 0.569 / 0.622))", + }, + }, + "--grass-a10": { + default: "light-dark(#007b17c1, #72ff8dae)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.388 0 / 0.659), color(display-p3 0.6 0.996 0.6 / 0.673))", + }, + }, + "--grass-a11": { + default: "light-dark(#006514d5, #89ff9fcd)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.263 0.488 0.261), color(display-p3 0.535 0.807 0.542))", + }, + }, + "--grass-a12": { + default: "light-dark(#002006df, #ceffceef)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.151 0.233 0.153), color(display-p3 0.797 0.936 0.776))", + }, + }, + "--grass-surface": { + default: "light-dark(#f3faf3cc, #19231b80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9569 0.9804 0.9569 / 0.8), color(display-p3 0.102 0.1333 0.102 / 0.5))", + }, + }, + "--grass-indicator": "var(--grass-9)", + "--grass-track": "var(--grass-9)", + "--grass-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/green.stylex.js b/packages/reflex-components-ui/js/src/colors/green.stylex.js new file mode 100644 index 00000000000..daa03e9e9da --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/green.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const green = stylex.defineVars({ + "--green-1": { + default: "light-dark(#fbfefc, #0e1512)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.986 0.996 0.989), color(display-p3 0.062 0.083 0.071))", + }, + }, + "--green-2": { + default: "light-dark(#f4fbf6, #121b17)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.963 0.983 0.967), color(display-p3 0.079 0.106 0.09))", + }, + }, + "--green-3": { + default: "light-dark(#e6f6eb, #132d21)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.913 0.964 0.925), color(display-p3 0.1 0.173 0.133))", + }, + }, + "--green-4": { + default: "light-dark(#d6f1df, #113b29)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.859 0.94 0.879), color(display-p3 0.115 0.229 0.166))", + }, + }, + "--green-5": { + default: "light-dark(#c4e8d1, #174933)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.796 0.907 0.826), color(display-p3 0.147 0.282 0.206))", + }, + }, + "--green-6": { + default: "light-dark(#adddc0, #20573e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.718 0.863 0.761), color(display-p3 0.185 0.338 0.25))", + }, + }, + "--green-7": { + default: "light-dark(#8eceaa, #28684a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.61 0.801 0.675), color(display-p3 0.227 0.403 0.298))", + }, + }, + "--green-8": { + default: "light-dark(#5bb98b, #2f7c57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.451 0.715 0.559), color(display-p3 0.27 0.479 0.351))", + }, + }, + "--green-9": { + default: "#30a46c", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.332 0.634 0.442)", + }, + }, + "--green-10": { + default: "light-dark(#2b9a66, #33b074)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.308 0.595 0.417), color(display-p3 0.357 0.682 0.474))", + }, + }, + "--green-11": { + default: "light-dark(#218358, #3dd68c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.19 0.5 0.32), color(display-p3 0.434 0.828 0.573))", + }, + }, + "--green-12": { + default: "light-dark(#193b2d, #b1f1cb)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.132 0.228 0.18), color(display-p3 0.747 0.938 0.807))", + }, + }, + "--green-a1": { + default: "light-dark(#00c04004, #00de4505)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.757 0.267 / 0.016), color(display-p3 0 0.992 0.298 / 0.017))", + }, + }, + "--green-a2": { + default: "light-dark(#00a32f0b, #29f99d0b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.565 0.129 / 0.036), color(display-p3 0.341 0.98 0.616 / 0.043))", + }, + }, + "--green-a3": { + default: "light-dark(#00a43319, #22ff991e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.596 0.145 / 0.087), color(display-p3 0.376 0.996 0.655 / 0.114))", + }, + }, + "--green-a4": { + default: "light-dark(#00a83829, #11ff992d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.588 0.145 / 0.142), color(display-p3 0.341 0.996 0.635 / 0.173))", + }, + }, + "--green-a5": { + default: "light-dark(#019c393b, #2bffa23c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.541 0.157 / 0.204), color(display-p3 0.408 1 0.678 / 0.232))", + }, + }, + "--green-a6": { + default: "light-dark(#00963c52, #44ffaa4b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.518 0.157 / 0.283), color(display-p3 0.475 1 0.706 / 0.29))", + }, + }, + "--green-a7": { + default: "light-dark(#00914071, #50fdac5e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.486 0.165 / 0.389), color(display-p3 0.514 1 0.706 / 0.362))", + }, + }, + "--green-a8": { + default: "light-dark(#00924ba4, #54ffad73)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.478 0.2 / 0.55), color(display-p3 0.529 1 0.718 / 0.442))", + }, + }, + "--green-a9": { + default: "light-dark(#008f4acf, #44ffa49e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.455 0.165 / 0.667), color(display-p3 0.502 0.996 0.682 / 0.61))", + }, + }, + "--green-a10": { + default: "light-dark(#008647d4, #43fea4ab)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.416 0.153 / 0.691), color(display-p3 0.506 1 0.682 / 0.66))", + }, + }, + "--green-a11": { + default: "light-dark(#00713fde, #46fea5d4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.19 0.5 0.32), color(display-p3 0.434 0.828 0.573))", + }, + }, + "--green-a12": { + default: "light-dark(#002616e6, #bbffd7f0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.132 0.228 0.18), color(display-p3 0.747 0.938 0.807))", + }, + }, + "--green-surface": { + default: "light-dark(#f1faf4cc, #15251d80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9569 0.9804 0.9608 / 0.8), color(display-p3 0.0941 0.1412 0.1098 / 0.5))", + }, + }, + "--green-indicator": "var(--green-9)", + "--green-track": "var(--green-9)", + "--green-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/indigo.stylex.js b/packages/reflex-components-ui/js/src/colors/indigo.stylex.js new file mode 100644 index 00000000000..8737deb9e18 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/indigo.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const indigo = stylex.defineVars({ + "--indigo-1": { + default: "light-dark(#fdfdfe, #11131f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.992 0.992 0.996), color(display-p3 0.068 0.074 0.118))", + }, + }, + "--indigo-2": { + default: "light-dark(#f7f9ff, #141726)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.971 0.977 0.998), color(display-p3 0.081 0.089 0.144))", + }, + }, + "--indigo-3": { + default: "light-dark(#edf2fe, #182449)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.933 0.948 0.992), color(display-p3 0.105 0.141 0.275))", + }, + }, + "--indigo-4": { + default: "light-dark(#e1e9ff, #1d2e62)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.885 0.914 1), color(display-p3 0.129 0.18 0.369))", + }, + }, + "--indigo-5": { + default: "light-dark(#d2deff, #253974)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.831 0.87 1), color(display-p3 0.163 0.22 0.439))", + }, + }, + "--indigo-6": { + default: "light-dark(#c1d0ff, #304384)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.767 0.814 0.995), color(display-p3 0.203 0.262 0.5))", + }, + }, + "--indigo-7": { + default: "light-dark(#abbdf9, #3a4f97)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.685 0.74 0.957), color(display-p3 0.245 0.309 0.575))", + }, + }, + "--indigo-8": { + default: "light-dark(#8da4ef, #435db1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.569 0.639 0.916), color(display-p3 0.285 0.362 0.674))", + }, + }, + "--indigo-9": { + default: "#3e63dd", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.276 0.384 0.837)", + }, + }, + "--indigo-10": { + default: "light-dark(#3358d4, #5472e4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.234 0.343 0.801), color(display-p3 0.354 0.445 0.866))", + }, + }, + "--indigo-11": { + default: "light-dark(#3a5bc7, #9eb1ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.256 0.354 0.755), color(display-p3 0.63 0.69 1))", + }, + }, + "--indigo-12": { + default: "light-dark(#1f2d5c, #d6e1ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.133 0.175 0.348), color(display-p3 0.848 0.881 0.99))", + }, + }, + "--indigo-a1": { + default: "light-dark(#00008002, #1133ff0f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.02 0.51 / 0.008), color(display-p3 0.071 0.212 0.996 / 0.055))", + }, + }, + "--indigo-a2": { + default: "light-dark(#0040ff08, #3354fa17)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.161 0.863 / 0.028), color(display-p3 0.251 0.345 0.988 / 0.085))", + }, + }, + "--indigo-a3": { + default: "light-dark(#0047f112, #2f62ff3c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.239 0.886 / 0.067), color(display-p3 0.243 0.404 1 / 0.223))", + }, + }, + "--indigo-a4": { + default: "light-dark(#0044ff1e, #3566ff57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.247 1 / 0.114), color(display-p3 0.263 0.42 1 / 0.324))", + }, + }, + "--indigo-a5": { + default: "light-dark(#0044ff2d, #4171fd6b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.235 1 / 0.169), color(display-p3 0.314 0.451 1 / 0.4))", + }, + }, + "--indigo-a6": { + default: "light-dark(#003eff3e, #5178fd7c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.208 0.984 / 0.232), color(display-p3 0.361 0.49 1 / 0.467))", + }, + }, + "--indigo-a7": { + default: "light-dark(#0037ed54, #5a7fff90)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.176 0.863 / 0.314), color(display-p3 0.388 0.51 1 / 0.547))", + }, + }, + "--indigo-a8": { + default: "light-dark(#0034dc72, #5b81feac)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.165 0.812 / 0.432), color(display-p3 0.404 0.518 1 / 0.652))", + }, + }, + "--indigo-a9": { + default: "light-dark(#0031d2c1, #4671ffdb)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.153 0.773 / 0.726), color(display-p3 0.318 0.451 1 / 0.824))", + }, + }, + "--indigo-a10": { + default: "light-dark(#002ec9cc, #5c7efee3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.137 0.737 / 0.765), color(display-p3 0.404 0.506 1 / 0.858))", + }, + }, + "--indigo-a11": { + default: "light-dark(#002bb7c5, #9eb1ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.256 0.354 0.755), color(display-p3 0.63 0.69 1))", + }, + }, + "--indigo-a12": { + default: "light-dark(#001046e0, #d6e1ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.133 0.175 0.348), color(display-p3 0.848 0.881 0.99))", + }, + }, + "--indigo-surface": { + default: "light-dark(#f5f8ffcc, #171d3b80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9647 0.9725 0.9961 / 0.8), color(display-p3 0.0941 0.1098 0.2196 / 0.5))", + }, + }, + "--indigo-indicator": "var(--indigo-9)", + "--indigo-track": "var(--indigo-9)", + "--indigo-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/iris.stylex.js b/packages/reflex-components-ui/js/src/colors/iris.stylex.js new file mode 100644 index 00000000000..208c19bf463 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/iris.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const iris = stylex.defineVars({ + "--iris-1": { + default: "light-dark(#fdfdff, #13131e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.992 0.992 0.999), color(display-p3 0.075 0.075 0.114))", + }, + }, + "--iris-2": { + default: "light-dark(#f8f8ff, #171625)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.972 0.973 0.998), color(display-p3 0.089 0.086 0.14))", + }, + }, + "--iris-3": { + default: "light-dark(#f0f1fe, #202248)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.943 0.945 0.992), color(display-p3 0.128 0.134 0.272))", + }, + }, + "--iris-4": { + default: "light-dark(#e6e7ff, #262a65)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.902 0.906 1), color(display-p3 0.153 0.165 0.382))", + }, + }, + "--iris-5": { + default: "light-dark(#dadcff, #303374)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.857 0.861 1), color(display-p3 0.192 0.201 0.44))", + }, + }, + "--iris-6": { + default: "light-dark(#cbcdff, #3d3e82)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.799 0.805 0.987), color(display-p3 0.239 0.241 0.491))", + }, + }, + "--iris-7": { + default: "light-dark(#b8baf8, #4a4a95)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.721 0.727 0.955), color(display-p3 0.291 0.289 0.565))", + }, + }, + "--iris-8": { + default: "light-dark(#9b9ef0, #5958b1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.61 0.619 0.918), color(display-p3 0.35 0.345 0.673))", + }, + }, + "--iris-9": { + default: "#5b5bd6", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.357 0.357 0.81)", + }, + }, + "--iris-10": { + default: "light-dark(#5151cd, #6e6ade)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.318 0.318 0.774), color(display-p3 0.428 0.416 0.843))", + }, + }, + "--iris-11": { + default: "light-dark(#5753c6, #b1a9ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.337 0.326 0.748), color(display-p3 0.685 0.662 1))", + }, + }, + "--iris-12": { + default: "light-dark(#272962, #e0dffe)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.154 0.161 0.371), color(display-p3 0.878 0.875 0.986))", + }, + }, + "--iris-a1": { + default: "light-dark(#0000ff02, #3636fe0e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.02 1 / 0.008), color(display-p3 0.224 0.224 0.992 / 0.051))", + }, + }, + "--iris-a2": { + default: "light-dark(#0000ff07, #564bf916)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.024 0.863 / 0.028), color(display-p3 0.361 0.314 1 / 0.08))", + }, + }, + "--iris-a3": { + default: "light-dark(#0011ee0f, #525bff3b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.071 0.871 / 0.059), color(display-p3 0.357 0.373 1 / 0.219))", + }, + }, + "--iris-a4": { + default: "light-dark(#000bff19, #4d58ff5a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.051 1 / 0.099), color(display-p3 0.325 0.361 1 / 0.337))", + }, + }, + "--iris-a5": { + default: "light-dark(#000eff25, #5b62fd6b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.035 1 / 0.142), color(display-p3 0.38 0.4 1 / 0.4))", + }, + }, + "--iris-a6": { + default: "light-dark(#000aff34, #6d6ffd7a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.02 0.941 / 0.2), color(display-p3 0.447 0.447 1 / 0.454))", + }, + }, + "--iris-a7": { + default: "light-dark(#0008e647, #7777fe8e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.02 0.847 / 0.279), color(display-p3 0.486 0.486 1 / 0.534))", + }, + }, + "--iris-a8": { + default: "light-dark(#0008d964, #7b7afeac)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.024 0.788 / 0.389), color(display-p3 0.502 0.494 1 / 0.652))", + }, + }, + "--iris-a9": { + default: "light-dark(#0000c0a4, #6a6afed4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0.706 / 0.644), color(display-p3 0.431 0.431 1 / 0.799))", + }, + }, + "--iris-a10": { + default: "light-dark(#0000b6ae, #7d79ffdc)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0.667 / 0.683), color(display-p3 0.502 0.486 1 / 0.832))", + }, + }, + "--iris-a11": { + default: "light-dark(#0600abac, #b1a9ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.337 0.326 0.748), color(display-p3 0.685 0.662 1))", + }, + }, + "--iris-a12": { + default: "light-dark(#000246d8, #e1e0fffe)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.154 0.161 0.371), color(display-p3 0.878 0.875 0.986))", + }, + }, + "--iris-surface": { + default: "light-dark(#f6f6ffcc, #1d1b3980)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9647 0.9647 0.9961 / 0.8), color(display-p3 0.1098 0.102 0.2118 / 0.5))", + }, + }, + "--iris-indicator": "var(--iris-9)", + "--iris-track": "var(--iris-9)", + "--iris-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/jade.stylex.js b/packages/reflex-components-ui/js/src/colors/jade.stylex.js new file mode 100644 index 00000000000..ee703544f9a --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/jade.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const jade = stylex.defineVars({ + "--jade-1": { + default: "light-dark(#fbfefd, #0d1512)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.986 0.996 0.992), color(display-p3 0.059 0.083 0.071))", + }, + }, + "--jade-2": { + default: "light-dark(#f4fbf7, #121c18)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.962 0.983 0.969), color(display-p3 0.078 0.11 0.094))", + }, + }, + "--jade-3": { + default: "light-dark(#e6f7ed, #0f2e22)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.912 0.965 0.932), color(display-p3 0.091 0.176 0.138))", + }, + }, + "--jade-4": { + default: "light-dark(#d6f1e3, #0b3b2c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.858 0.941 0.893), color(display-p3 0.102 0.228 0.177))", + }, + }, + "--jade-5": { + default: "light-dark(#c3e9d7, #114837)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.795 0.909 0.847), color(display-p3 0.133 0.279 0.221))", + }, + }, + "--jade-6": { + default: "light-dark(#acdec8, #1b5745)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.715 0.864 0.791), color(display-p3 0.174 0.334 0.273))", + }, + }, + "--jade-7": { + default: "light-dark(#8bceb6, #246854)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.603 0.802 0.718), color(display-p3 0.219 0.402 0.335))", + }, + }, + "--jade-8": { + default: "light-dark(#56ba9f, #2a7e68)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.44 0.72 0.629), color(display-p3 0.263 0.488 0.411))", + }, + }, + "--jade-9": { + default: "#29a383", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.319 0.63 0.521)", + }, + }, + "--jade-10": { + default: "light-dark(#26997b, #27b08b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.299 0.592 0.488), color(display-p3 0.338 0.68 0.555))", + }, + }, + "--jade-11": { + default: "light-dark(#208368, #1fd8a4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.15 0.5 0.37), color(display-p3 0.4 0.835 0.656))", + }, + }, + "--jade-12": { + default: "light-dark(#1d3b31, #adf0d4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.142 0.229 0.194), color(display-p3 0.734 0.934 0.838))", + }, + }, + "--jade-a1": { + default: "light-dark(#00c08004, #00de4505)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.757 0.514 / 0.016), color(display-p3 0 0.992 0.298 / 0.017))", + }, + }, + "--jade-a2": { + default: "light-dark(#00a3460b, #27fba60c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.612 0.22 / 0.04), color(display-p3 0.318 0.988 0.651 / 0.047))", + }, + }, + "--jade-a3": { + default: "light-dark(#00ae4819, #02f99920)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.596 0.235 / 0.087), color(display-p3 0.267 1 0.667 / 0.118))", + }, + }, + "--jade-a4": { + default: "light-dark(#00a85129, #00ffaa2d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.588 0.255 / 0.142), color(display-p3 0.275 0.996 0.702 / 0.173))", + }, + }, + "--jade-a5": { + default: "light-dark(#00a2553c, #11ffb63b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.561 0.251 / 0.204), color(display-p3 0.361 1 0.741 / 0.227))", + }, + }, + "--jade-a6": { + default: "light-dark(#009a5753, #34ffc24b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.525 0.278 / 0.287), color(display-p3 0.439 1 0.796 / 0.286))", + }, + }, + "--jade-a7": { + default: "light-dark(#00945f74, #45fdc75e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.506 0.29 / 0.397), color(display-p3 0.49 1 0.804 / 0.362))", + }, + }, + "--jade-a8": { + default: "light-dark(#00976ea9, #48ffcf75)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.506 0.337 / 0.561), color(display-p3 0.506 1 0.835 / 0.45))", + }, + }, + "--jade-a9": { + default: "light-dark(#00916bd6, #38feca9d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.459 0.298 / 0.683), color(display-p3 0.478 0.996 0.816 / 0.606))", + }, + }, + "--jade-a10": { + default: "light-dark(#008764d9, #31fec7ab)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.42 0.271 / 0.702), color(display-p3 0.478 1 0.816 / 0.656))", + }, + }, + "--jade-a11": { + default: "light-dark(#007152df, #21fec0d6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.15 0.5 0.37), color(display-p3 0.4 0.835 0.656))", + }, + }, + "--jade-a12": { + default: "light-dark(#002217e2, #b8ffe1ef)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.142 0.229 0.194), color(display-p3 0.734 0.934 0.838))", + }, + }, + "--jade-surface": { + default: "light-dark(#f1faf5cc, #13271f80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9529 0.9804 0.9608 / 0.8), color(display-p3 0.0863 0.149 0.1176 / 0.5))", + }, + }, + "--jade-indicator": "var(--jade-9)", + "--jade-track": "var(--jade-9)", + "--jade-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/lime.stylex.js b/packages/reflex-components-ui/js/src/colors/lime.stylex.js new file mode 100644 index 00000000000..fb2b9f367c5 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/lime.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const lime = stylex.defineVars({ + "--lime-1": { + default: "light-dark(#fcfdfa, #11130c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.989 0.992 0.981), color(display-p3 0.067 0.073 0.048))", + }, + }, + "--lime-2": { + default: "light-dark(#f8faf3, #151a10)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.975 0.98 0.954), color(display-p3 0.086 0.1 0.067))", + }, + }, + "--lime-3": { + default: "light-dark(#eef6d6, #1f2917)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.939 0.965 0.851), color(display-p3 0.13 0.16 0.099))", + }, + }, + "--lime-4": { + default: "light-dark(#e2f0bd, #29371d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.896 0.94 0.76), color(display-p3 0.172 0.214 0.126))", + }, + }, + "--lime-5": { + default: "light-dark(#d3e7a6, #334423)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.843 0.903 0.678), color(display-p3 0.213 0.266 0.153))", + }, + }, + "--lime-6": { + default: "light-dark(#c2da91, #3d522a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.778 0.852 0.599), color(display-p3 0.257 0.321 0.182))", + }, + }, + "--lime-7": { + default: "light-dark(#abc978, #496231)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.694 0.784 0.508), color(display-p3 0.307 0.383 0.215))", + }, + }, + "--lime-8": { + default: "light-dark(#8db654, #577538)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.585 0.707 0.378), color(display-p3 0.365 0.456 0.25))", + }, + }, + "--lime-9": { + default: "#bdee63", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.78 0.928 0.466)", + }, + }, + "--lime-10": { + default: "light-dark(#b0e64c, #d4ff70)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.734 0.896 0.397), color(display-p3 0.865 0.995 0.519))", + }, + }, + "--lime-11": { + default: "light-dark(#5c7c2f, #bde56c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.386 0.482 0.227), color(display-p3 0.771 0.893 0.485))", + }, + }, + "--lime-12": { + default: "light-dark(#37401c, #e3f7ba)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.222 0.25 0.128), color(display-p3 0.905 0.966 0.753))", + }, + }, + "--lime-a1": { + default: "light-dark(#66990005, #11bb0003)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.412 0.608 0.02 / 0.02), color(display-p3 0.067 0.941 0 / 0.009))", + }, + }, + "--lime-a2": { + default: "light-dark(#6b95000c, #78f7000a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.514 0.592 0.024 / 0.048), color(display-p3 0.584 0.996 0.071 / 0.038))", + }, + }, + "--lime-a3": { + default: "light-dark(#96c80029, #9bfd4c1a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.584 0.765 0.008 / 0.15), color(display-p3 0.69 1 0.38 / 0.101))", + }, + }, + "--lime-a4": { + default: "light-dark(#8fc60042, #a7fe5c29)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.561 0.757 0.004 / 0.24), color(display-p3 0.729 1 0.435 / 0.16))", + }, + }, + "--lime-a5": { + default: "light-dark(#81bb0059, #affe6537)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.514 0.698 0.004 / 0.322), color(display-p3 0.745 1 0.471 / 0.215))", + }, + }, + "--lime-a6": { + default: "light-dark(#72aa006e, #b2fe6d46)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.443 0.627 0 / 0.4), color(display-p3 0.769 1 0.482 / 0.274))", + }, + }, + "--lime-a7": { + default: "light-dark(#61990087, #b6ff6f57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.376 0.561 0.004 / 0.491), color(display-p3 0.769 1 0.506 / 0.341))", + }, + }, + "--lime-a8": { + default: "light-dark(#559200ab, #b6fd6d6c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.333 0.529 0 / 0.624), color(display-p3 0.784 1 0.51 / 0.416))", + }, + }, + "--lime-a9": { + default: "light-dark(#93e4009c, #caff69ed)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.588 0.867 0 / 0.534), color(display-p3 0.839 1 0.502 / 0.925))", + }, + }, + "--lime-a10": { + default: "light-dark(#8fdc00b3, #d4ff70)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.561 0.827 0 / 0.604), color(display-p3 0.871 1 0.522 / 0.996))", + }, + }, + "--lime-a11": { + default: "light-dark(#375f00d0, #d1fe77e4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.386 0.482 0.227), color(display-p3 0.771 0.893 0.485))", + }, + }, + "--lime-a12": { + default: "light-dark(#1e2900e3, #e9febff7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.222 0.25 0.128), color(display-p3 0.905 0.966 0.753))", + }, + }, + "--lime-surface": { + default: "light-dark(#f6f9f0cc, #1b211580)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9725 0.9765 0.9412 / 0.8), color(display-p3 0.1098 0.1255 0.0784 / 0.5))", + }, + }, + "--lime-indicator": "var(--lime-9)", + "--lime-track": + "light-dark(var(--lime-9), color-mix(in oklab, var(--lime-8), var(--lime-9) 65%))", + "--lime-contrast": "#1d211c", +}); diff --git a/packages/reflex-components-ui/js/src/colors/mauve.stylex.js b/packages/reflex-components-ui/js/src/colors/mauve.stylex.js new file mode 100644 index 00000000000..5486c849cd8 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/mauve.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const mauve = stylex.defineVars({ + "--mauve-1": { + default: "light-dark(#fdfcfd, #121113)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.991 0.988 0.992), color(display-p3 0.07 0.067 0.074))", + }, + }, + "--mauve-2": { + default: "light-dark(#faf9fb, #1a191b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.98 0.976 0.984), color(display-p3 0.101 0.098 0.105))", + }, + }, + "--mauve-3": { + default: "light-dark(#f2eff3, #232225)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.946 0.938 0.952), color(display-p3 0.138 0.134 0.144))", + }, + }, + "--mauve-4": { + default: "light-dark(#eae7ec, #2b292d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.915 0.906 0.925), color(display-p3 0.167 0.161 0.175))", + }, + }, + "--mauve-5": { + default: "light-dark(#e3dfe6, #323035)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.886 0.876 0.901), color(display-p3 0.196 0.189 0.206))", + }, + }, + "--mauve-6": { + default: "light-dark(#dbd8e0, #3c393f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.856 0.846 0.875), color(display-p3 0.232 0.225 0.245))", + }, + }, + "--mauve-7": { + default: "light-dark(#d0cdd7, #49474e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.814 0.804 0.84), color(display-p3 0.286 0.277 0.302))", + }, + }, + "--mauve-8": { + default: "light-dark(#bcbac7, #625f69)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.735 0.728 0.777), color(display-p3 0.383 0.373 0.408))", + }, + }, + "--mauve-9": { + default: "light-dark(#8e8c99, #6f6d78)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.555 0.549 0.596), color(display-p3 0.434 0.428 0.467))", + }, + }, + "--mauve-10": { + default: "light-dark(#84828e, #7c7a85)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.514 0.508 0.552), color(display-p3 0.487 0.48 0.519))", + }, + }, + "--mauve-11": { + default: "light-dark(#65636d, #b5b2bc)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.395 0.388 0.424), color(display-p3 0.707 0.7 0.735))", + }, + }, + "--mauve-12": { + default: "light-dark(#211f26, #eeeef0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.128 0.122 0.147), color(display-p3 0.933 0.933 0.94))", + }, + }, + "--mauve-a1": { + default: "light-dark(#55005503, #00000000)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.349 0.024 0.349 / 0.012), color(display-p3 0 0 0 / 0))", + }, + }, + "--mauve-a2": { + default: "light-dark(#2b005506, #f5f4f609)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.184 0.024 0.349 / 0.024), color(display-p3 0.996 0.992 1 / 0.034))", + }, + }, + "--mauve-a3": { + default: "light-dark(#30004010, #ebeaf814)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.129 0.008 0.255 / 0.063), color(display-p3 0.937 0.933 0.992 / 0.077))", + }, + }, + "--mauve-a4": { + default: "light-dark(#20003618, #eee5f81d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.094 0.012 0.216 / 0.095), color(display-p3 0.957 0.918 0.996 / 0.111))", + }, + }, + "--mauve-a5": { + default: "light-dark(#20003820, #efe6fe25)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.098 0.008 0.224 / 0.126), color(display-p3 0.937 0.906 0.996 / 0.145))", + }, + }, + "--mauve-a6": { + default: "light-dark(#14003527, #f1e6fd30)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.055 0.004 0.18 / 0.153), color(display-p3 0.953 0.925 0.996 / 0.183))", + }, + }, + "--mauve-a7": { + default: "light-dark(#10003332, #eee9ff40)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.067 0.008 0.184 / 0.197), color(display-p3 0.945 0.929 1 / 0.246))", + }, + }, + "--mauve-a8": { + default: "light-dark(#08003145, #eee7ff5d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.004 0.176 / 0.271), color(display-p3 0.937 0.918 1 / 0.361))", + }, + }, + "--mauve-a9": { + default: "light-dark(#05001d73, #eae6fd6e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.004 0.106 / 0.451), color(display-p3 0.933 0.918 1 / 0.424))", + }, + }, + "--mauve-a10": { + default: "light-dark(#0500197d, #ece9fd7c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.004 0.09 / 0.491), color(display-p3 0.941 0.925 1 / 0.479))", + }, + }, + "--mauve-a11": { + default: "light-dark(#0400119c, #f5f1ffb7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.016 0 0.059 / 0.612), color(display-p3 0.965 0.961 1 / 0.712))", + }, + }, + "--mauve-a12": { + default: "light-dark(#020008e0, #fdfdffef)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0 0.027 / 0.879), color(display-p3 0.992 0.992 1 / 0.937))", + }, + }, + "--mauve-surface": { + default: "light-dark(#ffffffcc, #22212380)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 1 1 / 0.8), color(display-p3 0.1333 0.1255 0.1333 / 0.5))", + }, + }, + "--mauve-indicator": "var(--mauve-9)", + "--mauve-track": "var(--mauve-9)", + "--mauve-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/mint.stylex.js b/packages/reflex-components-ui/js/src/colors/mint.stylex.js new file mode 100644 index 00000000000..00b1c97b4e3 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/mint.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const mint = stylex.defineVars({ + "--mint-1": { + default: "light-dark(#f9fefd, #0e1515)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.98 0.995 0.992), color(display-p3 0.059 0.082 0.081))", + }, + }, + "--mint-2": { + default: "light-dark(#f2fbf9, #0f1b1b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.957 0.985 0.977), color(display-p3 0.068 0.104 0.105))", + }, + }, + "--mint-3": { + default: "light-dark(#ddf9f2, #092c2b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.888 0.972 0.95), color(display-p3 0.077 0.17 0.168))", + }, + }, + "--mint-4": { + default: "light-dark(#c8f4e9, #003a38)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.819 0.951 0.916), color(display-p3 0.068 0.224 0.22))", + }, + }, + "--mint-5": { + default: "light-dark(#b3ecde, #004744)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.747 0.918 0.873), color(display-p3 0.104 0.275 0.264))", + }, + }, + "--mint-6": { + default: "light-dark(#9ce0d0, #105650)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.668 0.87 0.818), color(display-p3 0.154 0.332 0.313))", + }, + }, + "--mint-7": { + default: "light-dark(#7ecfbd, #1e685f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.567 0.805 0.744), color(display-p3 0.207 0.403 0.373))", + }, + }, + "--mint-8": { + default: "light-dark(#4cbba5, #277f70)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.42 0.724 0.649), color(display-p3 0.258 0.49 0.441))", + }, + }, + "--mint-9": { + default: "#86ead4", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.62 0.908 0.834)", + }, + }, + "--mint-10": { + default: "light-dark(#7de0cb, #a8f5e5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.585 0.871 0.797), color(display-p3 0.725 0.954 0.898))", + }, + }, + "--mint-11": { + default: "light-dark(#027864, #58d5ba)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.203 0.463 0.397), color(display-p3 0.482 0.825 0.733))", + }, + }, + "--mint-12": { + default: "light-dark(#16433c, #c4f5e1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.136 0.259 0.236), color(display-p3 0.807 0.955 0.887))", + }, + }, + "--mint-a1": { + default: "light-dark(#00d5aa06, #00dede05)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.804 0.608 / 0.02), color(display-p3 0 0.992 0.992 / 0.017))", + }, + }, + "--mint-a2": { + default: "light-dark(#00b18a0d, #00f9f90b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.647 0.467 / 0.044), color(display-p3 0.071 0.98 0.98 / 0.043))", + }, + }, + "--mint-a3": { + default: "light-dark(#00d29e22, #00fff61d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.761 0.553 / 0.114), color(display-p3 0.176 0.996 0.996 / 0.11))", + }, + }, + "--mint-a4": { + default: "light-dark(#00cc9937, #00fff42c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.741 0.545 / 0.181), color(display-p3 0.071 0.996 0.973 / 0.169))", + }, + }, + "--mint-a5": { + default: "light-dark(#00c0914c, #00fff23a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.678 0.51 / 0.255), color(display-p3 0.243 1 0.949 / 0.223))", + }, + }, + "--mint-a6": { + default: "light-dark(#00b08663, #0effeb4a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.616 0.463 / 0.334), color(display-p3 0.369 1 0.933 / 0.286))", + }, + }, + "--mint-a7": { + default: "light-dark(#00a17d81, #34fde55e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.549 0.412 / 0.432), color(display-p3 0.459 1 0.914 / 0.362))", + }, + }, + "--mint-a8": { + default: "light-dark(#009e7fb3, #41ffdf76)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.529 0.392 / 0.581), color(display-p3 0.49 1 0.89 / 0.454))", + }, + }, + "--mint-a9": { + default: "light-dark(#00d3a579, #92ffe7e9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.765 0.569 / 0.381), color(display-p3 0.678 0.996 0.914 / 0.904))", + }, + }, + "--mint-a10": { + default: "light-dark(#00c39982, #aefeedf5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.69 0.51 / 0.416), color(display-p3 0.761 1 0.941 / 0.95))", + }, + }, + "--mint-a11": { + default: "light-dark(#007763fd, #67ffded2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.203 0.463 0.397), color(display-p3 0.482 0.825 0.733))", + }, + }, + "--mint-a12": { + default: "light-dark(#00312ae9, #cbfee9f5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.136 0.259 0.236), color(display-p3 0.807 0.955 0.887))", + }, + }, + "--mint-surface": { + default: "light-dark(#effaf8cc, #15272780)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9451 0.9804 0.9725 / 0.8), color(display-p3 0.0941 0.149 0.1412 / 0.5))", + }, + }, + "--mint-indicator": "var(--mint-9)", + "--mint-track": + "light-dark(var(--mint-9), color-mix(in oklab, var(--mint-8), var(--mint-9) 65%))", + "--mint-contrast": "#1a211e", +}); diff --git a/packages/reflex-components-ui/js/src/colors/olive.stylex.js b/packages/reflex-components-ui/js/src/colors/olive.stylex.js new file mode 100644 index 00000000000..40766aa58a1 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/olive.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const olive = stylex.defineVars({ + "--olive-1": { + default: "light-dark(#fcfdfc, #111210)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.989 0.992 0.989), color(display-p3 0.067 0.07 0.063))", + }, + }, + "--olive-2": { + default: "light-dark(#f8faf8, #181917)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.974 0.98 0.973), color(display-p3 0.095 0.098 0.091))", + }, + }, + "--olive-3": { + default: "light-dark(#eff1ef, #212220)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.939 0.945 0.937), color(display-p3 0.131 0.135 0.126))", + }, + }, + "--olive-4": { + default: "light-dark(#e7e9e7, #282a27)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.907 0.914 0.905), color(display-p3 0.158 0.163 0.153))", + }, + }, + "--olive-5": { + default: "light-dark(#dfe2df, #2f312e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.878 0.885 0.875), color(display-p3 0.186 0.192 0.18))", + }, + }, + "--olive-6": { + default: "light-dark(#d7dad7, #383a36)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.846 0.855 0.843), color(display-p3 0.221 0.229 0.215))", + }, + }, + "--olive-7": { + default: "light-dark(#cccfcc, #454843)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.803 0.812 0.8), color(display-p3 0.273 0.284 0.266))", + }, + }, + "--olive-8": { + default: "light-dark(#b9bcb8, #5c625b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.727 0.738 0.723), color(display-p3 0.365 0.382 0.359))", + }, + }, + "--olive-9": { + default: "light-dark(#898e87, #687066)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.541 0.556 0.532), color(display-p3 0.414 0.438 0.404))", + }, + }, + "--olive-10": { + default: "light-dark(#7f847d, #767d74)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.5 0.515 0.491), color(display-p3 0.467 0.49 0.458))", + }, + }, + "--olive-11": { + default: "light-dark(#60655f, #afb5ad)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.38 0.395 0.374), color(display-p3 0.69 0.709 0.682))", + }, + }, + "--olive-12": { + default: "light-dark(#1d211c, #eceeec)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.117 0.129 0.111), color(display-p3 0.927 0.933 0.926))", + }, + }, + "--olive-a1": { + default: "light-dark(#00550003, #00000000)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.349 0.024 / 0.012), color(display-p3 0 0 0 / 0))", + }, + }, + "--olive-a2": { + default: "light-dark(#00490007, #f1f2f008)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.302 0.024 / 0.028), color(display-p3 0.984 0.988 0.976 / 0.03))", + }, + }, + "--olive-a3": { + default: "light-dark(#00200010, #f4f5f312)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.129 0.008 / 0.063), color(display-p3 0.992 0.996 0.988 / 0.068))", + }, + }, + "--olive-a4": { + default: "light-dark(#00160018, #f3fef21a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.094 0.012 / 0.095), color(display-p3 0.953 0.996 0.949 / 0.102))", + }, + }, + "--olive-a5": { + default: "light-dark(#00180020, #f2fbf122)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.035 0.098 0.008 / 0.126), color(display-p3 0.969 1 0.965 / 0.131))", + }, + }, + "--olive-a6": { + default: "light-dark(#00140028, #f4faed2c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.027 0.078 0.004 / 0.157), color(display-p3 0.973 1 0.969 / 0.169))", + }, + }, + "--olive-a7": { + default: "light-dark(#000f0033, #f2fced3b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.059 0 / 0.2), color(display-p3 0.98 1 0.961 / 0.228))", + }, + }, + "--olive-a8": { + default: "light-dark(#040f0047, #edfdeb57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.059 0.004 / 0.279), color(display-p3 0.961 1 0.957 / 0.334))", + }, + }, + "--olive-a9": { + default: "light-dark(#050f0078, #ebfde766)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.051 0.004 / 0.467), color(display-p3 0.949 1 0.922 / 0.397))", + }, + }, + "--olive-a10": { + default: "light-dark(#040e0082, #f0fdec74)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.047 0 / 0.51), color(display-p3 0.953 1 0.941 / 0.452))", + }, + }, + "--olive-a11": { + default: "light-dark(#020a00a0, #f6fef4b0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.039 0 / 0.628), color(display-p3 0.976 1 0.965 / 0.688))", + }, + }, + "--olive-a12": { + default: "light-dark(#010600e3, #fdfffded)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.024 0 / 0.891), color(display-p3 0.992 1 0.992 / 0.929))", + }, + }, + "--olive-surface": { + default: "light-dark(#ffffffcc, #1f201e80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 1 1 / 0.8), color(display-p3 0.1176 0.1255 0.1176 / 0.5))", + }, + }, + "--olive-indicator": "var(--olive-9)", + "--olive-track": "var(--olive-9)", + "--olive-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/orange.stylex.js b/packages/reflex-components-ui/js/src/colors/orange.stylex.js new file mode 100644 index 00000000000..ee326505781 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/orange.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const orange = stylex.defineVars({ + "--orange-1": { + default: "light-dark(#fefcfb, #17120e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.988 0.985), color(display-p3 0.088 0.07 0.057))", + }, + }, + "--orange-2": { + default: "light-dark(#fff7ed, #1e160f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.994 0.968 0.934), color(display-p3 0.113 0.089 0.061))", + }, + }, + "--orange-3": { + default: "light-dark(#ffefd6, #331e0b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.989 0.938 0.85), color(display-p3 0.189 0.12 0.056))", + }, + }, + "--orange-4": { + default: "light-dark(#ffdfb5, #462100)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 0.874 0.687), color(display-p3 0.262 0.132 0))", + }, + }, + "--orange-5": { + default: "light-dark(#ffd19a, #562800)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 0.821 0.583), color(display-p3 0.315 0.168 0.016))", + }, + }, + "--orange-6": { + default: "light-dark(#ffc182, #66350c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.975 0.767 0.545), color(display-p3 0.376 0.219 0.088))", + }, + }, + "--orange-7": { + default: "light-dark(#f5ae73, #7e451d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.919 0.693 0.486), color(display-p3 0.465 0.283 0.147))", + }, + }, + "--orange-8": { + default: "light-dark(#ec9455, #a35829)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.877 0.597 0.379), color(display-p3 0.601 0.359 0.201))", + }, + }, + "--orange-9": { + default: "#f76b15", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.9 0.45 0.2)", + }, + }, + "--orange-10": { + default: "light-dark(#ef5f00, #ff801f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.87 0.409 0.164), color(display-p3 0.98 0.51 0.23))", + }, + }, + "--orange-11": { + default: "light-dark(#cc4e00, #ffa057)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.76 0.34 0), color(display-p3 1 0.63 0.38))", + }, + }, + "--orange-12": { + default: "light-dark(#582d1d, #ffe0c2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.323 0.185 0.127), color(display-p3 0.98 0.883 0.775))", + }, + }, + "--orange-a1": { + default: "light-dark(#c0400004, #ec360007)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.757 0.267 0.024 / 0.016), color(display-p3 0.961 0.247 0 / 0.022))", + }, + }, + "--orange-a2": { + default: "light-dark(#ff8e0012, #fe6d000e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.886 0.533 0.008 / 0.067), color(display-p3 0.992 0.529 0 / 0.051))", + }, + }, + "--orange-a3": { + default: "light-dark(#ff9c0029, #fb6a0025)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.922 0.584 0.008 / 0.15), color(display-p3 0.996 0.486 0 / 0.131))", + }, + }, + "--orange-a4": { + default: "light-dark(#ff91014a, #ff590039)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 0.604 0.004 / 0.314), color(display-p3 0.996 0.384 0 / 0.211))", + }, + }, + "--orange-a5": { + default: "light-dark(#ff8b0065, #ff61004a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 0.569 0.004 / 0.416), color(display-p3 1 0.455 0 / 0.265))", + }, + }, + "--orange-a6": { + default: "light-dark(#ff81007d, #fd75045c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.949 0.494 0.004 / 0.455), color(display-p3 1 0.529 0.129 / 0.332))", + }, + }, + "--orange-a7": { + default: "light-dark(#ed6c008c, #ff832c75)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.839 0.408 0 / 0.514), color(display-p3 1 0.569 0.251 / 0.429))", + }, + }, + "--orange-a8": { + default: "light-dark(#e35f00aa, #fe84389d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.804 0.349 0 / 0.62), color(display-p3 1 0.584 0.302 / 0.572))", + }, + }, + "--orange-a9": { + default: "light-dark(#f65e00ea, #fe6d15f7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.878 0.314 0 / 0.8), color(display-p3 1 0.494 0.216 / 0.895))", + }, + }, + "--orange-a10": { + default: "light-dark(#ef5f00, #ff801f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.843 0.29 0 / 0.836), color(display-p3 1 0.522 0.235 / 0.979))", + }, + }, + "--orange-a11": { + default: "light-dark(#cc4e00, #ffa057)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.76 0.34 0), color(display-p3 1 0.63 0.38))", + }, + }, + "--orange-a12": { + default: "light-dark(#431200e2, #ffe0c2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.323 0.185 0.127), color(display-p3 0.98 0.883 0.775))", + }, + }, + "--orange-surface": { + default: "light-dark(#fff5e9cc, #271d1380)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9961 0.9608 0.9176 / 0.8), color(display-p3 0.1412 0.1098 0.0706 / 0.5))", + }, + }, + "--orange-indicator": "var(--orange-9)", + "--orange-track": "var(--orange-9)", + "--orange-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/pink.stylex.js b/packages/reflex-components-ui/js/src/colors/pink.stylex.js new file mode 100644 index 00000000000..5f03925f6ce --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/pink.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const pink = stylex.defineVars({ + "--pink-1": { + default: "light-dark(#fffcfe, #191117)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.998 0.989 0.996), color(display-p3 0.093 0.068 0.089))", + }, + }, + "--pink-2": { + default: "light-dark(#fef7fb, #21121d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.992 0.97 0.985), color(display-p3 0.121 0.073 0.11))", + }, + }, + "--pink-3": { + default: "light-dark(#fee9f5, #37172f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.981 0.917 0.96), color(display-p3 0.198 0.098 0.179))", + }, + }, + "--pink-4": { + default: "light-dark(#fbdcef, #4b143d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.963 0.867 0.932), color(display-p3 0.271 0.095 0.231))", + }, + }, + "--pink-5": { + default: "light-dark(#f6cee7, #591c47)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.939 0.815 0.899), color(display-p3 0.32 0.127 0.273))", + }, + }, + "--pink-6": { + default: "light-dark(#efbfdd, #692955)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.907 0.756 0.859), color(display-p3 0.382 0.177 0.326))", + }, + }, + "--pink-7": { + default: "light-dark(#e7acd0, #833869)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.869 0.683 0.81), color(display-p3 0.477 0.238 0.405))", + }, + }, + "--pink-8": { + default: "light-dark(#dd93c2, #a84885)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.825 0.59 0.751), color(display-p3 0.612 0.304 0.51))", + }, + }, + "--pink-9": { + default: "#d6409f", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.775 0.297 0.61)", + }, + }, + "--pink-10": { + default: "light-dark(#cf3897, #de51a8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.748 0.27 0.581), color(display-p3 0.808 0.356 0.645))", + }, + }, + "--pink-11": { + default: "light-dark(#c2298a, #ff8dcc)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.698 0.219 0.528), color(display-p3 1 0.535 0.78))", + }, + }, + "--pink-12": { + default: "light-dark(#651249, #fdd1ea)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.363 0.101 0.279), color(display-p3 0.964 0.826 0.912))", + }, + }, + "--pink-a1": { + default: "light-dark(#ff00aa03, #f412bc09)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.024 0.675 / 0.012), color(display-p3 0.984 0.071 0.855 / 0.03))", + }, + }, + "--pink-a2": { + default: "light-dark(#e0008008, #f420bb12)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.757 0.02 0.51 / 0.032), color(display-p3 1 0.2 0.8 / 0.059))", + }, + }, + "--pink-a3": { + default: "light-dark(#f4008c16, #fe37cc29)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.765 0.008 0.529 / 0.083), color(display-p3 1 0.294 0.886 / 0.139))", + }, + }, + "--pink-a4": { + default: "light-dark(#e2008b23, #fc1ec43f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.737 0.008 0.506 / 0.134), color(display-p3 1 0.192 0.82 / 0.219))", + }, + }, + "--pink-a5": { + default: "light-dark(#d1008331, #fd35c24e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.663 0.004 0.451 / 0.185), color(display-p3 1 0.282 0.827 / 0.274))", + }, + }, + "--pink-a6": { + default: "light-dark(#c0007840, #fd51c75f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.616 0.004 0.424 / 0.244), color(display-p3 1 0.396 0.835 / 0.337))", + }, + }, + "--pink-a7": { + default: "light-dark(#b6006f53, #fd62c87b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.596 0.004 0.412 / 0.318), color(display-p3 1 0.459 0.831 / 0.442))", + }, + }, + "--pink-a8": { + default: "light-dark(#af006f6c, #ff68c8a2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.573 0.004 0.404 / 0.412), color(display-p3 1 0.478 0.827 / 0.585))", + }, + }, + "--pink-a9": { + default: "light-dark(#c8007fbf, #fe49bcd4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.682 0 0.447 / 0.702), color(display-p3 1 0.373 0.784 / 0.761))", + }, + }, + "--pink-a10": { + default: "light-dark(#c2007ac7, #ff5cc0dc)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.655 0 0.424 / 0.73), color(display-p3 1 0.435 0.792 / 0.795))", + }, + }, + "--pink-a11": { + default: "light-dark(#b60074d6, #ff8dcc)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.698 0.219 0.528), color(display-p3 1 0.535 0.78))", + }, + }, + "--pink-a12": { + default: "light-dark(#59003bed, #ffd3ecfd)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.363 0.101 0.279), color(display-p3 0.964 0.826 0.912))", + }, + }, + "--pink-surface": { + default: "light-dark(#fef5facc, #31132980)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9922 0.9608 0.9804 / 0.8), color(display-p3 0.1725 0.0784 0.149 / 0.5))", + }, + }, + "--pink-indicator": "var(--pink-9)", + "--pink-track": "var(--pink-9)", + "--pink-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/plum.stylex.js b/packages/reflex-components-ui/js/src/colors/plum.stylex.js new file mode 100644 index 00000000000..d16bbd6c6ed --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/plum.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const plum = stylex.defineVars({ + "--plum-1": { + default: "light-dark(#fefcff, #181118)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.988 0.999), color(display-p3 0.09 0.068 0.092))", + }, + }, + "--plum-2": { + default: "light-dark(#fdf7fd, #201320)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.988 0.971 0.99), color(display-p3 0.118 0.077 0.121))", + }, + }, + "--plum-3": { + default: "light-dark(#fbebfb, #351a35)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.973 0.923 0.98), color(display-p3 0.192 0.105 0.202))", + }, + }, + "--plum-4": { + default: "light-dark(#f7def8, #451d47)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.953 0.875 0.966), color(display-p3 0.25 0.121 0.271))", + }, + }, + "--plum-5": { + default: "light-dark(#f2d1f3, #512454)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.926 0.825 0.945), color(display-p3 0.293 0.152 0.319))", + }, + }, + "--plum-6": { + default: "light-dark(#e9c2ec, #5e3061)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.89 0.765 0.916), color(display-p3 0.343 0.198 0.372))", + }, + }, + "--plum-7": { + default: "light-dark(#deade3, #734079)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.84 0.686 0.877), color(display-p3 0.424 0.262 0.461))", + }, + }, + "--plum-8": { + default: "light-dark(#cf91d8, #92549c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.775 0.58 0.832), color(display-p3 0.54 0.341 0.595))", + }, + }, + "--plum-9": { + default: "#ab4aba", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.624 0.313 0.708)", + }, + }, + "--plum-10": { + default: "light-dark(#a144af, #b658c4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.587 0.29 0.667), color(display-p3 0.666 0.365 0.748))", + }, + }, + "--plum-11": { + default: "light-dark(#953ea3, #e796f3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.543 0.263 0.619), color(display-p3 0.86 0.602 0.933))", + }, + }, + "--plum-12": { + default: "light-dark(#53195d, #f4d4f4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.299 0.114 0.352), color(display-p3 0.936 0.836 0.949))", + }, + }, + "--plum-a1": { + default: "light-dark(#aa00ff03, #f112f108)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.024 1 / 0.012), color(display-p3 0.973 0.071 0.973 / 0.026))", + }, + }, + "--plum-a2": { + default: "light-dark(#c000c008, #f22ff211)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.58 0.024 0.58 / 0.028), color(display-p3 0.933 0.267 1 / 0.059))", + }, + }, + "--plum-a3": { + default: "light-dark(#cc00cc14, #fd4cfd27)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.655 0.008 0.753 / 0.079), color(display-p3 0.918 0.333 0.996 / 0.148))", + }, + }, + "--plum-a4": { + default: "light-dark(#c200c921, #f646ff3a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.627 0.008 0.722 / 0.126), color(display-p3 0.91 0.318 1 / 0.219))", + }, + }, + "--plum-a5": { + default: "light-dark(#b700bd2e, #f455ff48)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.58 0.004 0.69 / 0.177), color(display-p3 0.914 0.388 1 / 0.269))", + }, + }, + "--plum-a6": { + default: "light-dark(#a400b03d, #f66dff56)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.537 0.004 0.655 / 0.236), color(display-p3 0.906 0.463 1 / 0.328))", + }, + }, + "--plum-a7": { + default: "light-dark(#9900a852, #f07cfd70)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.49 0.004 0.616 / 0.314), color(display-p3 0.906 0.529 1 / 0.425))", + }, + }, + "--plum-a8": { + default: "light-dark(#9000a56e, #ee84ff95)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.471 0.004 0.6 / 0.42), color(display-p3 0.906 0.553 1 / 0.568))", + }, + }, + "--plum-a9": { + default: "light-dark(#89009eb5, #e961feb6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.451 0 0.576 / 0.687), color(display-p3 0.875 0.427 1 / 0.69))", + }, + }, + "--plum-a10": { + default: "light-dark(#7f0092bb, #ed70ffc0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.42 0 0.529 / 0.71), color(display-p3 0.886 0.471 0.996 / 0.732))", + }, + }, + "--plum-a11": { + default: "light-dark(#730086c1, #f19cfef3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.543 0.263 0.619), color(display-p3 0.86 0.602 0.933))", + }, + }, + "--plum-a12": { + default: "light-dark(#40004be6, #feddfef4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.299 0.114 0.352), color(display-p3 0.936 0.836 0.949))", + }, + }, + "--plum-surface": { + default: "light-dark(#fdf5fdcc, #2f152f80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9843 0.9647 0.9843 / 0.8), color(display-p3 0.1647 0.0863 0.1725 / 0.5))", + }, + }, + "--plum-indicator": "var(--plum-9)", + "--plum-track": "var(--plum-9)", + "--plum-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/purple.stylex.js b/packages/reflex-components-ui/js/src/colors/purple.stylex.js new file mode 100644 index 00000000000..e87723f4e5f --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/purple.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const purple = stylex.defineVars({ + "--purple-1": { + default: "light-dark(#fefcfe, #18111b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.988 0.996), color(display-p3 0.09 0.068 0.103))", + }, + }, + "--purple-2": { + default: "light-dark(#fbf7fe, #1e1523)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.983 0.971 0.993), color(display-p3 0.113 0.082 0.134))", + }, + }, + "--purple-3": { + default: "light-dark(#f7edfe, #301c3b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.963 0.931 0.989), color(display-p3 0.175 0.112 0.224))", + }, + }, + "--purple-4": { + default: "light-dark(#f2e2fc, #3d224e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.937 0.888 0.981), color(display-p3 0.224 0.137 0.297))", + }, + }, + "--purple-5": { + default: "light-dark(#ead5f9, #48295c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.904 0.837 0.966), color(display-p3 0.264 0.167 0.349))", + }, + }, + "--purple-6": { + default: "light-dark(#e0c4f4, #54346b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.86 0.774 0.942), color(display-p3 0.311 0.208 0.406))", + }, + }, + "--purple-7": { + default: "light-dark(#d1afec, #664282)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.799 0.69 0.91), color(display-p3 0.381 0.266 0.496))", + }, + }, + "--purple-8": { + default: "light-dark(#be93e4, #8457aa)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.719 0.583 0.874), color(display-p3 0.49 0.349 0.649))", + }, + }, + "--purple-9": { + default: "#8e4ec6", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.523 0.318 0.751)", + }, + }, + "--purple-10": { + default: "light-dark(#8347b9, #9a5cd0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.483 0.289 0.7), color(display-p3 0.57 0.373 0.791))", + }, + }, + "--purple-11": { + default: "light-dark(#8145b5, #d19dff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.473 0.281 0.687), color(display-p3 0.8 0.62 1))", + }, + }, + "--purple-12": { + default: "light-dark(#402060, #ecd9fa)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.234 0.132 0.363), color(display-p3 0.913 0.854 0.971))", + }, + }, + "--purple-a1": { + default: "light-dark(#aa00aa03, #b412f90b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.024 0.675 / 0.012), color(display-p3 0.686 0.071 0.996 / 0.038))", + }, + }, + "--purple-a2": { + default: "light-dark(#8000e008, #b744f714)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.443 0.024 0.722 / 0.028), color(display-p3 0.722 0.286 0.996 / 0.072))", + }, + }, + "--purple-a3": { + default: "light-dark(#8e00f112, #c150ff2d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.506 0.008 0.835 / 0.071), color(display-p3 0.718 0.349 0.996 / 0.169))", + }, + }, + "--purple-a4": { + default: "light-dark(#8d00e51d, #bb53fd42)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.451 0.004 0.831 / 0.114), color(display-p3 0.702 0.353 1 / 0.248))", + }, + }, + "--purple-a5": { + default: "light-dark(#8000db2a, #be5cfd51)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.431 0.004 0.788 / 0.165), color(display-p3 0.718 0.404 1 / 0.303))", + }, + }, + "--purple-a6": { + default: "light-dark(#7a01d03b, #c16dfd61)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.384 0.004 0.745 / 0.228), color(display-p3 0.733 0.455 1 / 0.366))", + }, + }, + "--purple-a7": { + default: "light-dark(#6d00c350, #c378fd7a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.357 0.004 0.71 / 0.31), color(display-p3 0.753 0.506 1 / 0.458))", + }, + }, + "--purple-a8": { + default: "light-dark(#6600c06c, #c47effa4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.322 0.004 0.702 / 0.416), color(display-p3 0.749 0.522 1 / 0.622))", + }, + }, + "--purple-a9": { + default: "light-dark(#5c00adb1, #b661ffc2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.298 0 0.639 / 0.683), color(display-p3 0.686 0.408 1 / 0.736))", + }, + }, + "--purple-a10": { + default: "light-dark(#53009eb8, #bc6fffcd)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.271 0 0.58 / 0.71), color(display-p3 0.71 0.459 1 / 0.778))", + }, + }, + "--purple-a11": { + default: "light-dark(#52009aba, #d19dff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.473 0.281 0.687), color(display-p3 0.8 0.62 1))", + }, + }, + "--purple-a12": { + default: "light-dark(#250049df, #f1ddfffa)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.234 0.132 0.363), color(display-p3 0.913 0.854 0.971))", + }, + }, + "--purple-surface": { + default: "light-dark(#faf5fecc, #2b173580)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9804 0.9647 0.9922 / 0.8), color(display-p3 0.149 0.0941 0.1961 / 0.5))", + }, + }, + "--purple-indicator": "var(--purple-9)", + "--purple-track": "var(--purple-9)", + "--purple-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/red.stylex.js b/packages/reflex-components-ui/js/src/colors/red.stylex.js new file mode 100644 index 00000000000..75edcef6e85 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/red.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const red = stylex.defineVars({ + "--red-1": { + default: "light-dark(#fffcfc, #191111)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.998 0.989 0.988), color(display-p3 0.093 0.068 0.067))", + }, + }, + "--red-2": { + default: "light-dark(#fff7f7, #201314)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.971 0.971), color(display-p3 0.118 0.077 0.079))", + }, + }, + "--red-3": { + default: "light-dark(#feebec, #3b1219)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.985 0.925 0.925), color(display-p3 0.211 0.081 0.099))", + }, + }, + "--red-4": { + default: "light-dark(#ffdbdc, #500f1c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.999 0.866 0.866), color(display-p3 0.287 0.079 0.113))", + }, + }, + "--red-5": { + default: "light-dark(#ffcdce, #611623)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.984 0.812 0.811), color(display-p3 0.348 0.11 0.142))", + }, + }, + "--red-6": { + default: "light-dark(#fdbdbe, #72232d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.955 0.751 0.749), color(display-p3 0.414 0.16 0.183))", + }, + }, + "--red-7": { + default: "light-dark(#f4a9aa, #8c333a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.915 0.675 0.672), color(display-p3 0.508 0.224 0.236))", + }, + }, + "--red-8": { + default: "light-dark(#eb8e90, #b54548)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.872 0.575 0.572), color(display-p3 0.659 0.298 0.297))", + }, + }, + "--red-9": { + default: "#e5484d", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.83 0.329 0.324)", + }, + }, + "--red-10": { + default: "light-dark(#dc3e42, #ec5d5e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.798 0.294 0.285), color(display-p3 0.861 0.403 0.387))", + }, + }, + "--red-11": { + default: "light-dark(#ce2c31, #ff9592)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.744 0.234 0.222), color(display-p3 1 0.57 0.55))", + }, + }, + "--red-12": { + default: "light-dark(#641723, #ffd1d9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.36 0.115 0.143), color(display-p3 0.971 0.826 0.852))", + }, + }, + "--red-a1": { + default: "light-dark(#ff000003, #f4121209)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.024 0.024 / 0.012), color(display-p3 0.984 0.071 0.071 / 0.03))", + }, + }, + "--red-a2": { + default: "light-dark(#ff000008, #f22f3e11)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.863 0.024 0.024 / 0.028), color(display-p3 0.996 0.282 0.282 / 0.055))", + }, + }, + "--red-a3": { + default: "light-dark(#f3000d14, #ff173f2d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.792 0.008 0.008 / 0.075), color(display-p3 1 0.169 0.271 / 0.156))", + }, + }, + "--red-a4": { + default: "light-dark(#ff000824, #fe0a3b44)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 0.008 0.008 / 0.134), color(display-p3 1 0.118 0.267 / 0.236))", + }, + }, + "--red-a5": { + default: "light-dark(#ff000632, #ff204756)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.918 0.008 0.008 / 0.189), color(display-p3 1 0.212 0.314 / 0.303))", + }, + }, + "--red-a6": { + default: "light-dark(#f8000442, #ff3e5668)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.831 0.02 0.004 / 0.251), color(display-p3 1 0.318 0.38 / 0.374))", + }, + }, + "--red-a7": { + default: "light-dark(#df000356, #ff536184)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.741 0.016 0.004 / 0.33), color(display-p3 1 0.4 0.424 / 0.475))", + }, + }, + "--red-a8": { + default: "light-dark(#d2000571, #ff5d61b0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.698 0.012 0.004 / 0.428), color(display-p3 1 0.431 0.431 / 0.635))", + }, + }, + "--red-a9": { + default: "light-dark(#db0007b7, #fe4e54e4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.749 0.008 0 / 0.675), color(display-p3 1 0.388 0.384 / 0.82))", + }, + }, + "--red-a10": { + default: "light-dark(#d10005c1, #ff6465eb)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.714 0.012 0 / 0.714), color(display-p3 1 0.463 0.447 / 0.853))", + }, + }, + "--red-a11": { + default: "light-dark(#c40006d3, #ff9592)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.744 0.234 0.222), color(display-p3 1 0.57 0.55))", + }, + }, + "--red-a12": { + default: "light-dark(#55000de8, #ffd1d9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.36 0.115 0.143), color(display-p3 0.971 0.826 0.852))", + }, + }, + "--red-surface": { + default: "light-dark(#fff5f5cc, #2f151780)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9961 0.9647 0.9647 / 0.8), color(display-p3 0.1647 0.0863 0.0863 / 0.5))", + }, + }, + "--red-indicator": "var(--red-9)", + "--red-track": "var(--red-9)", + "--red-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/ruby.stylex.js b/packages/reflex-components-ui/js/src/colors/ruby.stylex.js new file mode 100644 index 00000000000..13172a361cd --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/ruby.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const ruby = stylex.defineVars({ + "--ruby-1": { + default: "light-dark(#fffcfd, #191113)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.998 0.989 0.992), color(display-p3 0.093 0.068 0.074))", + }, + }, + "--ruby-2": { + default: "light-dark(#fff7f8, #1e1517)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.971 0.974), color(display-p3 0.113 0.083 0.089))", + }, + }, + "--ruby-3": { + default: "light-dark(#feeaed, #3a141e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.983 0.92 0.928), color(display-p3 0.208 0.088 0.117))", + }, + }, + "--ruby-4": { + default: "light-dark(#ffdce1, #4e1325)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.987 0.869 0.885), color(display-p3 0.279 0.092 0.147))", + }, + }, + "--ruby-5": { + default: "light-dark(#ffced6, #5e1a2e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.968 0.817 0.839), color(display-p3 0.337 0.12 0.18))", + }, + }, + "--ruby-6": { + default: "light-dark(#f8bfc8, #6f2539)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.937 0.758 0.786), color(display-p3 0.401 0.166 0.223))", + }, + }, + "--ruby-7": { + default: "light-dark(#efacb8, #883447)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.897 0.685 0.721), color(display-p3 0.495 0.224 0.281))", + }, + }, + "--ruby-8": { + default: "light-dark(#e592a3, #b3445a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.851 0.588 0.639), color(display-p3 0.652 0.295 0.359))", + }, + }, + "--ruby-9": { + default: "#e54666", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.83 0.323 0.408)", + }, + }, + "--ruby-10": { + default: "light-dark(#dc3b5d, #ec5a72)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.795 0.286 0.375), color(display-p3 0.857 0.392 0.455))", + }, + }, + "--ruby-11": { + default: "light-dark(#ca244d, #ff949d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.728 0.211 0.311), color(display-p3 1 0.57 0.59))", + }, + }, + "--ruby-12": { + default: "light-dark(#64172b, #fed2e1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.36 0.115 0.171), color(display-p3 0.968 0.83 0.88))", + }, + }, + "--ruby-a1": { + default: "light-dark(#ff005503, #f4124a09)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.024 0.349 / 0.012), color(display-p3 0.984 0.071 0.329 / 0.03))", + }, + }, + "--ruby-a2": { + default: "light-dark(#ff002008, #fe5a7f0e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.863 0.024 0.024 / 0.028), color(display-p3 0.992 0.376 0.529 / 0.051))", + }, + }, + "--ruby-a3": { + default: "light-dark(#f3002515, #ff235d2c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.804 0.008 0.11 / 0.079), color(display-p3 0.996 0.196 0.404 / 0.152))", + }, + }, + "--ruby-a4": { + default: "light-dark(#ff002523, #fd195e42)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.91 0.008 0.125 / 0.13), color(display-p3 1 0.173 0.416 / 0.227))", + }, + }, + "--ruby-a5": { + default: "light-dark(#ff002a31, #fe2d6b53)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.831 0.004 0.133 / 0.185), color(display-p3 1 0.259 0.459 / 0.29))", + }, + }, + "--ruby-a6": { + default: "light-dark(#e4002440, #ff447665)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.745 0.004 0.118 / 0.244), color(display-p3 1 0.341 0.506 / 0.358))", + }, + }, + "--ruby-a7": { + default: "light-dark(#ce002553, #ff577d80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.678 0.004 0.114 / 0.314), color(display-p3 1 0.412 0.541 / 0.458))", + }, + }, + "--ruby-a8": { + default: "light-dark(#c300286d, #ff5c7cae)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.639 0.004 0.125 / 0.412), color(display-p3 1 0.431 0.537 / 0.627))", + }, + }, + "--ruby-a9": { + default: "light-dark(#db002cb9, #fe4c70e4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.753 0 0.129 / 0.679), color(display-p3 1 0.376 0.482 / 0.82))", + }, + }, + "--ruby-a10": { + default: "light-dark(#d2002cc4, #ff617beb)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.714 0 0.125 / 0.714), color(display-p3 1 0.447 0.522 / 0.849))", + }, + }, + "--ruby-a11": { + default: "light-dark(#c10030db, #ff949d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.728 0.211 0.311), color(display-p3 1 0.57 0.59))", + }, + }, + "--ruby-a12": { + default: "light-dark(#550016e8, #ffd3e2fe)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.36 0.115 0.171), color(display-p3 0.968 0.83 0.88))", + }, + }, + "--ruby-surface": { + default: "light-dark(#fff5f6cc, #2b191d80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9961 0.9647 0.9647 / 0.8), color(display-p3 0.1569 0.0941 0.1098 / 0.5))", + }, + }, + "--ruby-indicator": "var(--ruby-9)", + "--ruby-track": "var(--ruby-9)", + "--ruby-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/sage.stylex.js b/packages/reflex-components-ui/js/src/colors/sage.stylex.js new file mode 100644 index 00000000000..4f59b74a174 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/sage.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const sage = stylex.defineVars({ + "--sage-1": { + default: "light-dark(#fbfdfc, #101211)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.986 0.992 0.988), color(display-p3 0.064 0.07 0.067))", + }, + }, + "--sage-2": { + default: "light-dark(#f7f9f8, #171918)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.97 0.977 0.974), color(display-p3 0.092 0.098 0.094))", + }, + }, + "--sage-3": { + default: "light-dark(#eef1f0, #202221)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.935 0.944 0.94), color(display-p3 0.128 0.135 0.131))", + }, + }, + "--sage-4": { + default: "light-dark(#e6e9e8, #272a29)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.904 0.913 0.909), color(display-p3 0.155 0.164 0.159))", + }, + }, + "--sage-5": { + default: "light-dark(#dfe2e0, #2e3130)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.875 0.885 0.88), color(display-p3 0.183 0.193 0.188))", + }, + }, + "--sage-6": { + default: "light-dark(#d7dad9, #373b39)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.844 0.854 0.849), color(display-p3 0.218 0.23 0.224))", + }, + }, + "--sage-7": { + default: "light-dark(#cbcfcd, #444947)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.8 0.811 0.806), color(display-p3 0.269 0.285 0.277))", + }, + }, + "--sage-8": { + default: "light-dark(#b8bcba, #5b625f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.725 0.738 0.732), color(display-p3 0.362 0.382 0.373))", + }, + }, + "--sage-9": { + default: "light-dark(#868e8b, #63706b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.531 0.556 0.546), color(display-p3 0.398 0.438 0.421))", + }, + }, + "--sage-10": { + default: "light-dark(#7c8481, #717d79)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.492 0.515 0.506), color(display-p3 0.453 0.49 0.474))", + }, + }, + "--sage-11": { + default: "light-dark(#5f6563, #adb5b2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.377 0.395 0.389), color(display-p3 0.685 0.709 0.697))", + }, + }, + "--sage-12": { + default: "light-dark(#1a211e, #eceeed)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.107 0.129 0.118), color(display-p3 0.927 0.933 0.93))", + }, + }, + "--sage-a1": { + default: "light-dark(#00804004, #00000000)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.514 0.267 / 0.016), color(display-p3 0 0 0 / 0))", + }, + }, + "--sage-a2": { + default: "light-dark(#00402008, #f0f2f108)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.267 0.145 / 0.032), color(display-p3 0.976 0.988 0.984 / 0.03))", + }, + }, + "--sage-a3": { + default: "light-dark(#002d1e11, #f3f5f412)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.184 0.125 / 0.067), color(display-p3 0.992 0.945 0.941 / 0.072))", + }, + }, + "--sage-a4": { + default: "light-dark(#001f1519, #f2fefd1a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.094 0.051 / 0.095), color(display-p3 0.988 0.996 0.992 / 0.102))", + }, + }, + "--sage-a5": { + default: "light-dark(#00180820, #f1fbfa22)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.098 0.035 / 0.126), color(display-p3 0.992 1 0.996 / 0.131))", + }, + }, + "--sage-a6": { + default: "light-dark(#00140d28, #edfbf42d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.078 0.027 / 0.157), color(display-p3 0.973 1 0.976 / 0.173))", + }, + }, + "--sage-a7": { + default: "light-dark(#00140a34, #edfcf73c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.059 0.039 / 0.2), color(display-p3 0.957 1 0.976 / 0.233))", + }, + }, + "--sage-a8": { + default: "light-dark(#000f0847, #ebfdf657)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.047 0.031 / 0.275), color(display-p3 0.957 1 0.984 / 0.334))", + }, + }, + "--sage-a9": { + default: "light-dark(#00110b79, #dffdf266)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.059 0.035 / 0.471), color(display-p3 0.902 1 0.957 / 0.397))", + }, + }, + "--sage-a10": { + default: "light-dark(#00100a83, #e5fdf674)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.047 0.031 / 0.51), color(display-p3 0.929 1 0.973 / 0.452))", + }, + }, + "--sage-a11": { + default: "light-dark(#000a07a0, #f4fefbb0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.031 0.02 / 0.624), color(display-p3 0.969 1 0.988 / 0.688))", + }, + }, + "--sage-a12": { + default: "light-dark(#000805e5, #fdfffeed)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.027 0.012 / 0.895), color(display-p3 0.992 1 0.996 / 0.929))", + }, + }, + "--sage-surface": { + default: "light-dark(#ffffffcc, #1e201f80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 1 1 / 0.8), color(display-p3 0.1176 0.1255 0.1176 / 0.5))", + }, + }, + "--sage-indicator": "var(--sage-9)", + "--sage-track": "var(--sage-9)", + "--sage-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/sand.stylex.js b/packages/reflex-components-ui/js/src/colors/sand.stylex.js new file mode 100644 index 00000000000..eb2770a1063 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/sand.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const sand = stylex.defineVars({ + "--sand-1": { + default: "light-dark(#fdfdfc, #111110)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.992 0.992 0.989), color(display-p3 0.067 0.067 0.063))", + }, + }, + "--sand-2": { + default: "light-dark(#f9f9f8, #191918)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.977 0.977 0.973), color(display-p3 0.098 0.098 0.094))", + }, + }, + "--sand-3": { + default: "light-dark(#f1f0ef, #222221)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.943 0.942 0.936), color(display-p3 0.135 0.135 0.129))", + }, + }, + "--sand-4": { + default: "light-dark(#e9e8e6, #2a2a28)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.913 0.912 0.903), color(display-p3 0.164 0.163 0.156))", + }, + }, + "--sand-5": { + default: "light-dark(#e2e1de, #31312e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.885 0.883 0.873), color(display-p3 0.193 0.192 0.183))", + }, + }, + "--sand-6": { + default: "light-dark(#dad9d6, #3b3a37)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.854 0.852 0.839), color(display-p3 0.23 0.229 0.217))", + }, + }, + "--sand-7": { + default: "light-dark(#cfceca, #494844)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.813 0.81 0.794), color(display-p3 0.285 0.282 0.267))", + }, + }, + "--sand-8": { + default: "light-dark(#bcbbb5, #62605b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.738 0.734 0.713), color(display-p3 0.384 0.378 0.357))", + }, + }, + "--sand-9": { + default: "light-dark(#8d8d86, #6f6d66)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.553 0.553 0.528), color(display-p3 0.434 0.428 0.403))", + }, + }, + "--sand-10": { + default: "light-dark(#82827c, #7c7b74)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.511 0.511 0.488), color(display-p3 0.487 0.481 0.456))", + }, + }, + "--sand-11": { + default: "light-dark(#63635e, #b5b3ad)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.388 0.388 0.37), color(display-p3 0.707 0.703 0.68))", + }, + }, + "--sand-12": { + default: "light-dark(#21201c, #eeeeec)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.129 0.126 0.111), color(display-p3 0.933 0.933 0.926))", + }, + }, + "--sand-a1": { + default: "light-dark(#55550003, #00000000)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.349 0.349 0.024 / 0.012), color(display-p3 0 0 0 / 0))", + }, + }, + "--sand-a2": { + default: "light-dark(#25250007, #f4f4f309)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.161 0.161 0.024 / 0.028), color(display-p3 0.992 0.992 0.988 / 0.034))", + }, + }, + "--sand-a3": { + default: "light-dark(#20100010, #f6f6f513)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.067 0.067 0.008 / 0.063), color(display-p3 0.996 0.996 0.992 / 0.072))", + }, + }, + "--sand-a4": { + default: "light-dark(#1f150019, #fefef31b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.129 0.129 0.012 / 0.099), color(display-p3 0.992 0.992 0.953 / 0.106))", + }, + }, + "--sand-a5": { + default: "light-dark(#1f180021, #fbfbeb23)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.098 0.067 0.008 / 0.126), color(display-p3 1 1 0.965 / 0.135))", + }, + }, + "--sand-a6": { + default: "light-dark(#19130029, #fffaed2d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.102 0.075 0.004 / 0.161), color(display-p3 1 0.976 0.929 / 0.177))", + }, + }, + "--sand-a7": { + default: "light-dark(#19140035, #fffbed3c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.098 0.098 0.004 / 0.208), color(display-p3 1 0.984 0.929 / 0.236))", + }, + }, + "--sand-a8": { + default: "light-dark(#1915014a, #fff9eb57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.086 0.075 0.004 / 0.287), color(display-p3 1 0.976 0.925 / 0.341))", + }, + }, + "--sand-a9": { + default: "light-dark(#0f0f0079, #fffae965)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.051 0.051 0.004 / 0.471), color(display-p3 1 0.98 0.925 / 0.395))", + }, + }, + "--sand-a10": { + default: "light-dark(#0c0c0083, #fffdee73)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.047 0.047 0 / 0.514), color(display-p3 1 0.992 0.933 / 0.45))", + }, + }, + "--sand-a11": { + default: "light-dark(#080800a1, #fffcf4b0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.031 0.031 0 / 0.632), color(display-p3 1 0.996 0.961 / 0.685))", + }, + }, + "--sand-a12": { + default: "light-dark(#060500e3, #fffffded)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.02 0 / 0.891), color(display-p3 1 1 0.992 / 0.929))", + }, + }, + "--sand-surface": { + default: "light-dark(#ffffffcc, #21212080)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 1 1 / 0.8), color(display-p3 0.1255 0.1255 0.1255 / 0.5))", + }, + }, + "--sand-indicator": "var(--sand-9)", + "--sand-track": "var(--sand-9)", + "--sand-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/sky.stylex.js b/packages/reflex-components-ui/js/src/colors/sky.stylex.js new file mode 100644 index 00000000000..a2670da136a --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/sky.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const sky = stylex.defineVars({ + "--sky-1": { + default: "light-dark(#f9feff, #0d141f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.98 0.995 0.999), color(display-p3 0.056 0.078 0.116))", + }, + }, + "--sky-2": { + default: "light-dark(#f1fafd, #111a27)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.953 0.98 0.99), color(display-p3 0.075 0.101 0.149))", + }, + }, + "--sky-3": { + default: "light-dark(#e1f6fd, #112840)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.899 0.963 0.989), color(display-p3 0.089 0.154 0.244))", + }, + }, + "--sky-4": { + default: "light-dark(#d1f0fa, #113555)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.842 0.937 0.977), color(display-p3 0.106 0.207 0.323))", + }, + }, + "--sky-5": { + default: "light-dark(#bee7f5, #154467)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.777 0.9 0.954), color(display-p3 0.135 0.261 0.394))", + }, + }, + "--sky-6": { + default: "light-dark(#a9daed, #1b537b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.701 0.851 0.921), color(display-p3 0.17 0.322 0.469))", + }, + }, + "--sky-7": { + default: "light-dark(#8dcae3, #1f6692)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.604 0.785 0.879), color(display-p3 0.205 0.394 0.557))", + }, + }, + "--sky-8": { + default: "light-dark(#60b3d7, #197cae)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.457 0.696 0.829), color(display-p3 0.232 0.48 0.665))", + }, + }, + "--sky-9": { + default: "#7ce2fe", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.585 0.877 0.983)", + }, + }, + "--sky-10": { + default: "light-dark(#74daf8, #a8eeff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.555 0.845 0.959), color(display-p3 0.718 0.925 0.991))", + }, + }, + "--sky-11": { + default: "light-dark(#00749e, #75c7f0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.193 0.448 0.605), color(display-p3 0.536 0.772 0.924))", + }, + }, + "--sky-12": { + default: "light-dark(#1d3e56, #c2f3ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.145 0.241 0.329), color(display-p3 0.799 0.947 0.993))", + }, + }, + "--sky-a1": { + default: "light-dark(#00d5ff06, #0044ff0f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.804 1 / 0.02), color(display-p3 0 0.282 0.996 / 0.055))", + }, + }, + "--sky-a2": { + default: "light-dark(#00a4db0e, #1171fb18)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.592 0.757 / 0.048), color(display-p3 0.157 0.467 0.992 / 0.089))", + }, + }, + "--sky-a3": { + default: "light-dark(#00b3ee1e, #1184fc33)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.655 0.886 / 0.102), color(display-p3 0.192 0.522 0.996 / 0.19))", + }, + }, + "--sky-a4": { + default: "light-dark(#00ace42e, #128fff49)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.604 0.851 / 0.157), color(display-p3 0.212 0.584 1 / 0.274))", + }, + }, + "--sky-a5": { + default: "light-dark(#00a1d841, #1c9dfd5d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.565 0.792 / 0.224), color(display-p3 0.259 0.631 1 / 0.349))", + }, + }, + "--sky-a6": { + default: "light-dark(#0092ca56, #28a5ff72)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.502 0.737 / 0.299), color(display-p3 0.302 0.655 1 / 0.433))", + }, + }, + "--sky-a7": { + default: "light-dark(#0089c172, #2badfe8b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.459 0.694 / 0.397), color(display-p3 0.329 0.686 1 / 0.526))", + }, + }, + "--sky-a8": { + default: "light-dark(#0085bf9f, #1db2fea9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.435 0.682 / 0.542), color(display-p3 0.325 0.71 1 / 0.643))", + }, + }, + "--sky-a9": { + default: "light-dark(#00c7fe83, #7ce3fffe)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.71 0.965 / 0.416), color(display-p3 0.592 0.894 1 / 0.984))", + }, + }, + "--sky-a10": { + default: "light-dark(#00bcf38b, #a8eeff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.647 0.914 / 0.444), color(display-p3 0.722 0.933 1 / 0.992))", + }, + }, + "--sky-a11": { + default: "light-dark(#00749e, #7cd3ffef)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.193 0.448 0.605), color(display-p3 0.536 0.772 0.924))", + }, + }, + "--sky-a12": { + default: "light-dark(#002540e2, #c2f3ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.145 0.241 0.329), color(display-p3 0.799 0.947 0.993))", + }, + }, + "--sky-surface": { + default: "light-dark(#eef9fdcc, #13233b80)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9412 0.9765 0.9843 / 0.8), color(display-p3 0.0863 0.1333 0.2196 / 0.5))", + }, + }, + "--sky-indicator": "var(--sky-9)", + "--sky-track": + "light-dark(var(--sky-9), color-mix(in oklab, var(--sky-8), var(--sky-9) 65%))", + "--sky-contrast": "#1c2024", +}); diff --git a/packages/reflex-components-ui/js/src/colors/slate.stylex.js b/packages/reflex-components-ui/js/src/colors/slate.stylex.js new file mode 100644 index 00000000000..6b38158c63f --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/slate.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const slate = stylex.defineVars({ + "--slate-1": { + default: "light-dark(#fcfcfd, #111113)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.988 0.988 0.992), color(display-p3 0.067 0.067 0.074))", + }, + }, + "--slate-2": { + default: "light-dark(#f9f9fb, #18191b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.976 0.976 0.984), color(display-p3 0.095 0.098 0.105))", + }, + }, + "--slate-3": { + default: "light-dark(#f0f0f3, #212225)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.94 0.941 0.953), color(display-p3 0.13 0.135 0.145))", + }, + }, + "--slate-4": { + default: "light-dark(#e8e8ec, #272a2d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.908 0.909 0.925), color(display-p3 0.156 0.163 0.176))", + }, + }, + "--slate-5": { + default: "light-dark(#e0e1e6, #2e3135)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.88 0.881 0.901), color(display-p3 0.183 0.191 0.206))", + }, + }, + "--slate-6": { + default: "light-dark(#d9d9e0, #363a3f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.85 0.852 0.876), color(display-p3 0.215 0.226 0.244))", + }, + }, + "--slate-7": { + default: "light-dark(#cdced6, #43484e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.805 0.808 0.838), color(display-p3 0.265 0.28 0.302))", + }, + }, + "--slate-8": { + default: "light-dark(#b9bbc6, #5a6169)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.727 0.733 0.773), color(display-p3 0.357 0.381 0.409))", + }, + }, + "--slate-9": { + default: "light-dark(#8b8d98, #696e77)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.547 0.553 0.592), color(display-p3 0.415 0.431 0.463))", + }, + }, + "--slate-10": { + default: "light-dark(#80838d, #777b84)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.503 0.512 0.549), color(display-p3 0.469 0.483 0.514))", + }, + }, + "--slate-11": { + default: "light-dark(#60646c, #b0b4ba)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.379 0.392 0.421), color(display-p3 0.692 0.704 0.728))", + }, + }, + "--slate-12": { + default: "light-dark(#1c2024, #edeef0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.113 0.125 0.14), color(display-p3 0.93 0.933 0.94))", + }, + }, + "--slate-a1": { + default: "light-dark(#00005503, #00000000)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.024 0.349 / 0.012), color(display-p3 0 0 0 / 0))", + }, + }, + "--slate-a2": { + default: "light-dark(#00005506, #d8f4f609)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.024 0.349 / 0.024), color(display-p3 0.875 0.992 1 / 0.034))", + }, + }, + "--slate-a3": { + default: "light-dark(#0000330f, #ddeaf814)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.004 0.204 / 0.059), color(display-p3 0.882 0.933 0.992 / 0.077))", + }, + }, + "--slate-a4": { + default: "light-dark(#00002d17, #d3edf81d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.012 0.012 0.184 / 0.091), color(display-p3 0.882 0.953 0.996 / 0.111))", + }, + }, + "--slate-a5": { + default: "light-dark(#0009321f, #d9edfe25)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.039 0.2 / 0.122), color(display-p3 0.878 0.929 0.996 / 0.145))", + }, + }, + "--slate-a6": { + default: "light-dark(#00002f26, #d6ebfd30)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.008 0.165 / 0.15), color(display-p3 0.882 0.949 0.996 / 0.183))", + }, + }, + "--slate-a7": { + default: "light-dark(#00062e32, #d9edff40)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.008 0.027 0.184 / 0.197), color(display-p3 0.882 0.929 1 / 0.246))", + }, + }, + "--slate-a8": { + default: "light-dark(#00083046, #d9edff5d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.031 0.176 / 0.275), color(display-p3 0.871 0.937 1 / 0.361))", + }, + }, + "--slate-a9": { + default: "light-dark(#00051d74, #dfebfd6d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.02 0.106 / 0.455), color(display-p3 0.898 0.937 1 / 0.42))", + }, + }, + "--slate-a10": { + default: "light-dark(#00071b7f, #e5edfd7b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.027 0.098 / 0.499), color(display-p3 0.918 0.945 1 / 0.475))", + }, + }, + "--slate-a11": { + default: "light-dark(#0007149f, #f1f7feb5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.02 0.063 / 0.62), color(display-p3 0.949 0.969 0.996 / 0.708))", + }, + }, + "--slate-a12": { + default: "light-dark(#000509e3, #fcfdffef)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.012 0.031 / 0.887), color(display-p3 0.988 0.992 1 / 0.937))", + }, + }, + "--slate-surface": { + default: "light-dark(#ffffffcc, #1f212380)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 1 1 / 0.8), color(display-p3 0.1176 0.1255 0.1333 / 0.5))", + }, + }, + "--slate-indicator": "var(--slate-9)", + "--slate-track": "var(--slate-9)", + "--slate-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/teal.stylex.js b/packages/reflex-components-ui/js/src/colors/teal.stylex.js new file mode 100644 index 00000000000..88b43508b07 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/teal.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const teal = stylex.defineVars({ + "--teal-1": { + default: "light-dark(#fafefd, #0d1514)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.983 0.996 0.992), color(display-p3 0.059 0.083 0.079))", + }, + }, + "--teal-2": { + default: "light-dark(#f3fbf9, #111c1b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.958 0.983 0.976), color(display-p3 0.075 0.11 0.107))", + }, + }, + "--teal-3": { + default: "light-dark(#e0f8f3, #0d2d2a)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.895 0.971 0.952), color(display-p3 0.087 0.175 0.165))", + }, + }, + "--teal-4": { + default: "light-dark(#ccf3ea, #023b37)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.831 0.949 0.92), color(display-p3 0.087 0.227 0.214))", + }, + }, + "--teal-5": { + default: "light-dark(#b8eae0, #084843)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.761 0.914 0.878), color(display-p3 0.12 0.277 0.261))", + }, + }, + "--teal-6": { + default: "light-dark(#a1ded2, #145750)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.682 0.864 0.825), color(display-p3 0.162 0.335 0.314))", + }, + }, + "--teal-7": { + default: "light-dark(#83cdc1, #1c6961)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.581 0.798 0.756), color(display-p3 0.205 0.406 0.379))", + }, + }, + "--teal-8": { + default: "light-dark(#53b9ab, #207e73)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.433 0.716 0.671), color(display-p3 0.245 0.489 0.453))", + }, + }, + "--teal-9": { + default: "#12a594", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.297 0.637 0.581)", + }, + }, + "--teal-10": { + default: "light-dark(#0d9b8a, #0eb39e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.275 0.599 0.542), color(display-p3 0.319 0.69 0.62))", + }, + }, + "--teal-11": { + default: "light-dark(#008573, #0bd8b6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.08 0.5 0.43), color(display-p3 0.388 0.835 0.719))", + }, + }, + "--teal-12": { + default: "light-dark(#0d3d38, #adf0dd)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.11 0.235 0.219), color(display-p3 0.734 0.934 0.87))", + }, + }, + "--teal-a1": { + default: "light-dark(#00cc9905, #00deab05)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.024 0.757 0.514 / 0.016), color(display-p3 0 0.992 0.761 / 0.017))", + }, + }, + "--teal-a2": { + default: "light-dark(#00aa800c, #12fbe60c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.02 0.647 0.467 / 0.044), color(display-p3 0.235 0.988 0.902 / 0.047))", + }, + }, + "--teal-a3": { + default: "light-dark(#00c69d1f, #00ffe61e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.741 0.557 / 0.106), color(display-p3 0.235 1 0.898 / 0.118))", + }, + }, + "--teal-a4": { + default: "light-dark(#00c39633, #00ffe92d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.702 0.537 / 0.169), color(display-p3 0.18 0.996 0.929 / 0.173))", + }, + }, + "--teal-a5": { + default: "light-dark(#00b49047, #00ffea3b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.643 0.494 / 0.24), color(display-p3 0.31 1 0.933 / 0.227))", + }, + }, + "--teal-a6": { + default: "light-dark(#00a6855e, #1cffe84b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.569 0.447 / 0.318), color(display-p3 0.396 1 0.933 / 0.286))", + }, + }, + "--teal-a7": { + default: "light-dark(#0099807c, #2efde85f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.004 0.518 0.424 / 0.42), color(display-p3 0.443 1 0.925 / 0.366))", + }, + }, + "--teal-a8": { + default: "light-dark(#009783ac, #32ffe775)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.506 0.424 / 0.569), color(display-p3 0.459 1 0.925 / 0.454))", + }, + }, + "--teal-a9": { + default: "light-dark(#009e8ced, #13ffe49f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.482 0.404 / 0.702), color(display-p3 0.443 0.996 0.906 / 0.61))", + }, + }, + "--teal-a10": { + default: "light-dark(#009684f2, #0dffe0ae)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0.451 0.369 / 0.726), color(display-p3 0.439 0.996 0.89 / 0.669))", + }, + }, + "--teal-a11": { + default: "light-dark(#008573, #0afed5d6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.08 0.5 0.43), color(display-p3 0.388 0.835 0.719))", + }, + }, + "--teal-a12": { + default: "light-dark(#00332df2, #b8ffebef)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.11 0.235 0.219), color(display-p3 0.734 0.934 0.87))", + }, + }, + "--teal-surface": { + default: "light-dark(#f0faf8cc, #13272580)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9451 0.9804 0.9725 / 0.8), color(display-p3 0.0863 0.149 0.1412 / 0.5))", + }, + }, + "--teal-indicator": "var(--teal-9)", + "--teal-track": "var(--teal-9)", + "--teal-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/tomato.stylex.js b/packages/reflex-components-ui/js/src/colors/tomato.stylex.js new file mode 100644 index 00000000000..91f4a30e761 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/tomato.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const tomato = stylex.defineVars({ + "--tomato-1": { + default: "light-dark(#fffcfc, #181111)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.998 0.989 0.988), color(display-p3 0.09 0.068 0.067))", + }, + }, + "--tomato-2": { + default: "light-dark(#fff8f7, #1f1513)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.994 0.974 0.969), color(display-p3 0.115 0.084 0.076))", + }, + }, + "--tomato-3": { + default: "light-dark(#feebe7, #391714)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.985 0.924 0.909), color(display-p3 0.205 0.097 0.083))", + }, + }, + "--tomato-4": { + default: "light-dark(#ffdcd3, #4e1511)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.996 0.868 0.835), color(display-p3 0.282 0.099 0.077))", + }, + }, + "--tomato-5": { + default: "light-dark(#ffcdc2, #5e1c16)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.98 0.812 0.77), color(display-p3 0.339 0.129 0.101))", + }, + }, + "--tomato-6": { + default: "light-dark(#fdbdaf, #6e2920)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.953 0.75 0.698), color(display-p3 0.398 0.179 0.141))", + }, + }, + "--tomato-7": { + default: "light-dark(#f5a898, #853a2d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.917 0.673 0.611), color(display-p3 0.487 0.245 0.194))", + }, + }, + "--tomato-8": { + default: "light-dark(#ec8e7b, #ac4d39)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.875 0.575 0.502), color(display-p3 0.629 0.322 0.248))", + }, + }, + "--tomato-9": { + default: "#e54d2e", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.831 0.345 0.231)", + }, + }, + "--tomato-10": { + default: "light-dark(#dd4425, #ec6142)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.802 0.313 0.2), color(display-p3 0.862 0.415 0.298))", + }, + }, + "--tomato-11": { + default: "light-dark(#d13415, #ff977d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.755 0.259 0.152), color(display-p3 1 0.585 0.455))", + }, + }, + "--tomato-12": { + default: "light-dark(#5c271f, #fbd3cb)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.335 0.165 0.132), color(display-p3 0.959 0.833 0.802))", + }, + }, + "--tomato-a1": { + default: "light-dark(#ff000003, #f1121208)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.024 0.024 / 0.012), color(display-p3 0.973 0.071 0.071 / 0.026))", + }, + }, + "--tomato-a2": { + default: "light-dark(#ff200008, #ff55330f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.757 0.145 0.02 / 0.032), color(display-p3 0.992 0.376 0.224 / 0.051))", + }, + }, + "--tomato-a3": { + default: "light-dark(#f52b0018, #ff35232b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.831 0.184 0.012 / 0.091), color(display-p3 0.996 0.282 0.176 / 0.148))", + }, + }, + "--tomato-a4": { + default: "light-dark(#ff35002c, #fd201142)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.976 0.192 0.004 / 0.165), color(display-p3 1 0.204 0.118 / 0.232))", + }, + }, + "--tomato-a5": { + default: "light-dark(#ff2e003d, #fe332153)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.918 0.192 0.004 / 0.232), color(display-p3 1 0.286 0.192 / 0.29))", + }, + }, + "--tomato-a6": { + default: "light-dark(#f92d0050, #ff4f3864)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.847 0.173 0.004 / 0.302), color(display-p3 1 0.392 0.278 / 0.353))", + }, + }, + "--tomato-a7": { + default: "light-dark(#e7280067, #fd644a7d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.788 0.165 0.004 / 0.389), color(display-p3 1 0.459 0.349 / 0.45))", + }, + }, + "--tomato-a8": { + default: "light-dark(#db250084, #fe6d4ea7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.749 0.153 0.004 / 0.499), color(display-p3 1 0.49 0.369 / 0.601))", + }, + }, + "--tomato-a9": { + default: "light-dark(#df2600d1, #fe5431e4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.78 0.149 0 / 0.769), color(display-p3 1 0.408 0.267 / 0.82))", + }, + }, + "--tomato-a10": { + default: "light-dark(#d72400da, #ff6847eb)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.757 0.141 0 / 0.8), color(display-p3 1 0.478 0.341 / 0.853))", + }, + }, + "--tomato-a11": { + default: "light-dark(#cd2200ea, #ff977d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.755 0.259 0.152), color(display-p3 1 0.585 0.455))", + }, + }, + "--tomato-a12": { + default: "light-dark(#460900e0, #ffd6cefb)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.335 0.165 0.132), color(display-p3 0.959 0.833 0.802))", + }, + }, + "--tomato-surface": { + default: "light-dark(#fff6f5cc, #2d191580)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9922 0.9647 0.9608 / 0.8), color(display-p3 0.1569 0.0941 0.0784 / 0.5))", + }, + }, + "--tomato-indicator": "var(--tomato-9)", + "--tomato-track": "var(--tomato-9)", + "--tomato-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/violet.stylex.js b/packages/reflex-components-ui/js/src/colors/violet.stylex.js new file mode 100644 index 00000000000..d37640ba998 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/violet.stylex.js @@ -0,0 +1,208 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const violet = stylex.defineVars({ + "--violet-1": { + default: "light-dark(#fdfcfe, #14121f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.991 0.988 0.995), color(display-p3 0.077 0.071 0.118))", + }, + }, + "--violet-2": { + default: "light-dark(#faf8ff, #1b1525)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.978 0.974 0.998), color(display-p3 0.101 0.084 0.141))", + }, + }, + "--violet-3": { + default: "light-dark(#f4f0fe, #291f43)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.953 0.943 0.993), color(display-p3 0.154 0.123 0.256))", + }, + }, + "--violet-4": { + default: "light-dark(#ebe4ff, #33255b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.916 0.897 1), color(display-p3 0.191 0.148 0.345))", + }, + }, + "--violet-5": { + default: "light-dark(#e1d9ff, #3c2e69)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.876 0.851 1), color(display-p3 0.226 0.182 0.396))", + }, + }, + "--violet-6": { + default: "light-dark(#d4cafe, #473876)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.825 0.793 0.981), color(display-p3 0.269 0.223 0.449))", + }, + }, + "--violet-7": { + default: "light-dark(#c2b5f5, #56468b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.752 0.712 0.943), color(display-p3 0.326 0.277 0.53))", + }, + }, + "--violet-8": { + default: "light-dark(#aa99ec, #6958ad)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.654 0.602 0.902), color(display-p3 0.399 0.346 0.656))", + }, + }, + "--violet-9": { + default: "#6e56cf", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0.417 0.341 0.784)", + }, + }, + "--violet-10": { + default: "light-dark(#654dc4, #7d66d9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.381 0.306 0.741), color(display-p3 0.477 0.402 0.823))", + }, + }, + "--violet-11": { + default: "light-dark(#6550b9, #baa7ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.383 0.317 0.702), color(display-p3 0.72 0.65 1))", + }, + }, + "--violet-12": { + default: "light-dark(#2f265f, #e2ddfe)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.179 0.15 0.359), color(display-p3 0.883 0.867 0.986))", + }, + }, + "--violet-a1": { + default: "light-dark(#5500aa03, #4422ff0f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.349 0.024 0.675 / 0.012), color(display-p3 0.282 0.141 0.996 / 0.055))", + }, + }, + "--violet-a2": { + default: "light-dark(#4900ff07, #853ff916)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.161 0.024 0.863 / 0.028), color(display-p3 0.51 0.263 1 / 0.08))", + }, + }, + "--violet-a3": { + default: "light-dark(#4400ee0f, #8354fe36)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.204 0.004 0.871 / 0.059), color(display-p3 0.494 0.337 0.996 / 0.202))", + }, + }, + "--violet-a4": { + default: "light-dark(#4300ff1b, #7d51fd50)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.196 0.004 1 / 0.102), color(display-p3 0.49 0.345 1 / 0.299))", + }, + }, + "--violet-a5": { + default: "light-dark(#3600ff26, #845ffd5f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.165 0.008 1 / 0.15), color(display-p3 0.525 0.392 1 / 0.353))", + }, + }, + "--violet-a6": { + default: "light-dark(#3100fb35, #8f6cfd6d)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.153 0.004 0.906 / 0.208), color(display-p3 0.569 0.455 1 / 0.408))", + }, + }, + "--violet-a7": { + default: "light-dark(#2d01dd4a, #9879ff83)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.141 0.004 0.796 / 0.287), color(display-p3 0.588 0.494 1 / 0.496))", + }, + }, + "--violet-a8": { + default: "light-dark(#2b00d066, #977dfea8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.133 0.004 0.753 / 0.397), color(display-p3 0.596 0.51 1 / 0.631))", + }, + }, + "--violet-a9": { + default: "light-dark(#2400b7a9, #8668ffcc)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.114 0 0.675 / 0.659), color(display-p3 0.522 0.424 1 / 0.769))", + }, + }, + "--violet-a10": { + default: "light-dark(#2300abb2, #9176fed7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.11 0 0.627 / 0.695), color(display-p3 0.576 0.482 1 / 0.811))", + }, + }, + "--violet-a11": { + default: "light-dark(#1f0099af, #baa7ff)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.383 0.317 0.702), color(display-p3 0.72 0.65 1))", + }, + }, + "--violet-a12": { + default: "light-dark(#0b0043d9, #e3defffe)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.179 0.15 0.359), color(display-p3 0.883 0.867 0.986))", + }, + }, + "--violet-surface": { + default: "light-dark(#f9f6ffcc, #25193980)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9725 0.9647 0.9961 / 0.8), color(display-p3 0.1333 0.102 0.2118 / 0.5))", + }, + }, + "--violet-indicator": "var(--violet-9)", + "--violet-track": "var(--violet-9)", + "--violet-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/colors/white.stylex.js b/packages/reflex-components-ui/js/src/colors/white.stylex.js new file mode 100644 index 00000000000..d68947c3353 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/white.stylex.js @@ -0,0 +1,90 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const white = stylex.defineVars({ + "--white-a1": { + default: "rgba(255, 255, 255, 0.05)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.05)", + }, + }, + "--white-a2": { + default: "rgba(255, 255, 255, 0.1)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.1)", + }, + }, + "--white-a3": { + default: "rgba(255, 255, 255, 0.15)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.15)", + }, + }, + "--white-a4": { + default: "rgba(255, 255, 255, 0.2)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.2)", + }, + }, + "--white-a5": { + default: "rgba(255, 255, 255, 0.3)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.3)", + }, + }, + "--white-a6": { + default: "rgba(255, 255, 255, 0.4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.4)", + }, + }, + "--white-a7": { + default: "rgba(255, 255, 255, 0.5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.5)", + }, + }, + "--white-a8": { + default: "rgba(255, 255, 255, 0.6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.6)", + }, + }, + "--white-a9": { + default: "rgba(255, 255, 255, 0.7)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.7)", + }, + }, + "--white-a10": { + default: "rgba(255, 255, 255, 0.8)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.8)", + }, + }, + "--white-a11": { + default: "rgba(255, 255, 255, 0.9)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.9)", + }, + }, + "--white-a12": { + default: "rgba(255, 255, 255, 0.95)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 1 1 / 0.95)", + }, + }, +}); diff --git a/packages/reflex-components-ui/js/src/colors/yellow.stylex.js b/packages/reflex-components-ui/js/src/colors/yellow.stylex.js new file mode 100644 index 00000000000..e1776df5d29 --- /dev/null +++ b/packages/reflex-components-ui/js/src/colors/yellow.stylex.js @@ -0,0 +1,209 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const yellow = stylex.defineVars({ + "--yellow-1": { + default: "light-dark(#fdfdf9, #14120b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.992 0.992 0.978), color(display-p3 0.078 0.069 0.047))", + }, + }, + "--yellow-2": { + default: "light-dark(#fefce9, #1b180f)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.995 0.99 0.922), color(display-p3 0.103 0.094 0.063))", + }, + }, + "--yellow-3": { + default: "light-dark(#fffab8, #2d2305)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.997 0.982 0.749), color(display-p3 0.168 0.137 0.039))", + }, + }, + "--yellow-4": { + default: "light-dark(#fff394, #362b00)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.992 0.953 0.627), color(display-p3 0.209 0.169 0))", + }, + }, + "--yellow-5": { + default: "light-dark(#ffe770, #433500)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.984 0.91 0.51), color(display-p3 0.255 0.209 0))", + }, + }, + "--yellow-6": { + default: "light-dark(#f3d768, #524202)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.934 0.847 0.474), color(display-p3 0.31 0.261 0.07))", + }, + }, + "--yellow-7": { + default: "light-dark(#e4c767, #665417)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.876 0.785 0.46), color(display-p3 0.389 0.331 0.135))", + }, + }, + "--yellow-8": { + default: "light-dark(#d5ae39, #836a21)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.811 0.689 0.313), color(display-p3 0.497 0.42 0.182))", + }, + }, + "--yellow-9": { + default: "#ffe629", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 1 0.92 0.22)", + }, + }, + "--yellow-10": { + default: "light-dark(#ffdc00, #ffff57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.977 0.868 0.291), color(display-p3 1 1 0.456))", + }, + }, + "--yellow-11": { + default: "light-dark(#9e6c00, #f5e147)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.6 0.44 0), color(display-p3 0.948 0.885 0.392))", + }, + }, + "--yellow-12": { + default: "light-dark(#473b1f, #f6eeb4)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.271 0.233 0.137), color(display-p3 0.959 0.934 0.731))", + }, + }, + "--yellow-a1": { + default: "light-dark(#aaaa0006, #d1510004)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.675 0.675 0.024 / 0.024), color(display-p3 0.973 0.369 0 / 0.013))", + }, + }, + "--yellow-a2": { + default: "light-dark(#f4dd0016, #f9b4000b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.953 0.855 0.008 / 0.079), color(display-p3 0.996 0.792 0 / 0.038))", + }, + }, + "--yellow-a3": { + default: "light-dark(#ffee0047, #ffaa001e)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.988 0.925 0.004 / 0.251), color(display-p3 0.996 0.71 0 / 0.11))", + }, + }, + "--yellow-a4": { + default: "light-dark(#ffe3016b, #fdb70028)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.98 0.875 0.004 / 0.373), color(display-p3 0.996 0.741 0 / 0.152))", + }, + }, + "--yellow-a5": { + default: "light-dark(#ffd5008f, #febb0036)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.969 0.816 0.004 / 0.491), color(display-p3 0.996 0.765 0 / 0.202))", + }, + }, + "--yellow-a6": { + default: "light-dark(#ebbc0097, #fec40046)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.875 0.71 0 / 0.526), color(display-p3 0.996 0.816 0.082 / 0.261))", + }, + }, + "--yellow-a7": { + default: "light-dark(#d2a10098, #fdcb225c)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.769 0.604 0 / 0.542), color(display-p3 1 0.831 0.263 / 0.345))", + }, + }, + "--yellow-a8": { + default: "light-dark(#c99700c6, #fdca327b)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.725 0.549 0 / 0.687), color(display-p3 1 0.831 0.314 / 0.463))", + }, + }, + "--yellow-a9": { + default: "light-dark(#ffe100d6, #ffe629)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 0.898 0 / 0.781), color(display-p3 1 0.922 0.22))", + }, + }, + "--yellow-a10": { + default: "light-dark(#ffdc00, #ffff57)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.969 0.812 0 / 0.71), color(display-p3 1 1 0.455))", + }, + }, + "--yellow-a11": { + default: "light-dark(#9e6c00, #fee949f5)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.6 0.44 0), color(display-p3 0.948 0.885 0.392))", + }, + }, + "--yellow-a12": { + default: "light-dark(#2e2000e0, #fef6baf6)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.271 0.233 0.137), color(display-p3 0.959 0.934 0.731))", + }, + }, + "--yellow-surface": { + default: "light-dark(#fefbe4cc, #231f1380)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.9961 0.9922 0.902 / 0.8), color(display-p3 0.1333 0.1176 0.0706 / 0.5))", + }, + }, + "--yellow-indicator": "light-dark(var(--yellow-10), var(--yellow-9))", + "--yellow-track": + "light-dark(var(--yellow-10), color-mix(in oklab, var(--yellow-8), var(--yellow-9) 65%))", + "--yellow-contrast": "#21201c", +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/amber.js b/packages/reflex-components-ui/js/src/themes/accent/amber.js new file mode 100644 index 00000000000..8b7183d0431 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/amber.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { amber } from "../../colors/amber.stylex.js"; + +export const accentAmber = stylex.createTheme(accent, { + "--accent-1": amber["--amber-1"], + "--accent-2": amber["--amber-2"], + "--accent-3": amber["--amber-3"], + "--accent-4": amber["--amber-4"], + "--accent-5": amber["--amber-5"], + "--accent-6": amber["--amber-6"], + "--accent-7": amber["--amber-7"], + "--accent-8": amber["--amber-8"], + "--accent-9": amber["--amber-9"], + "--accent-10": amber["--amber-10"], + "--accent-11": amber["--amber-11"], + "--accent-12": amber["--amber-12"], + "--accent-a1": amber["--amber-a1"], + "--accent-a2": amber["--amber-a2"], + "--accent-a3": amber["--amber-a3"], + "--accent-a4": amber["--amber-a4"], + "--accent-a5": amber["--amber-a5"], + "--accent-a6": amber["--amber-a6"], + "--accent-a7": amber["--amber-a7"], + "--accent-a8": amber["--amber-a8"], + "--accent-a9": amber["--amber-a9"], + "--accent-a10": amber["--amber-a10"], + "--accent-a11": amber["--amber-a11"], + "--accent-a12": amber["--amber-a12"], + "--accent-contrast": amber["--amber-contrast"], + "--accent-surface": amber["--amber-surface"], + "--accent-indicator": amber["--amber-indicator"], + "--accent-track": amber["--amber-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/blue.js b/packages/reflex-components-ui/js/src/themes/accent/blue.js new file mode 100644 index 00000000000..e03a9285c5c --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/blue.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { blue } from "../../colors/blue.stylex.js"; + +export const accentBlue = stylex.createTheme(accent, { + "--accent-1": blue["--blue-1"], + "--accent-2": blue["--blue-2"], + "--accent-3": blue["--blue-3"], + "--accent-4": blue["--blue-4"], + "--accent-5": blue["--blue-5"], + "--accent-6": blue["--blue-6"], + "--accent-7": blue["--blue-7"], + "--accent-8": blue["--blue-8"], + "--accent-9": blue["--blue-9"], + "--accent-10": blue["--blue-10"], + "--accent-11": blue["--blue-11"], + "--accent-12": blue["--blue-12"], + "--accent-a1": blue["--blue-a1"], + "--accent-a2": blue["--blue-a2"], + "--accent-a3": blue["--blue-a3"], + "--accent-a4": blue["--blue-a4"], + "--accent-a5": blue["--blue-a5"], + "--accent-a6": blue["--blue-a6"], + "--accent-a7": blue["--blue-a7"], + "--accent-a8": blue["--blue-a8"], + "--accent-a9": blue["--blue-a9"], + "--accent-a10": blue["--blue-a10"], + "--accent-a11": blue["--blue-a11"], + "--accent-a12": blue["--blue-a12"], + "--accent-contrast": blue["--blue-contrast"], + "--accent-surface": blue["--blue-surface"], + "--accent-indicator": blue["--blue-indicator"], + "--accent-track": blue["--blue-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/bronze.js b/packages/reflex-components-ui/js/src/themes/accent/bronze.js new file mode 100644 index 00000000000..9bd594d68da --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/bronze.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { bronze } from "../../colors/bronze.stylex.js"; + +export const accentBronze = stylex.createTheme(accent, { + "--accent-1": bronze["--bronze-1"], + "--accent-2": bronze["--bronze-2"], + "--accent-3": bronze["--bronze-3"], + "--accent-4": bronze["--bronze-4"], + "--accent-5": bronze["--bronze-5"], + "--accent-6": bronze["--bronze-6"], + "--accent-7": bronze["--bronze-7"], + "--accent-8": bronze["--bronze-8"], + "--accent-9": bronze["--bronze-9"], + "--accent-10": bronze["--bronze-10"], + "--accent-11": bronze["--bronze-11"], + "--accent-12": bronze["--bronze-12"], + "--accent-a1": bronze["--bronze-a1"], + "--accent-a2": bronze["--bronze-a2"], + "--accent-a3": bronze["--bronze-a3"], + "--accent-a4": bronze["--bronze-a4"], + "--accent-a5": bronze["--bronze-a5"], + "--accent-a6": bronze["--bronze-a6"], + "--accent-a7": bronze["--bronze-a7"], + "--accent-a8": bronze["--bronze-a8"], + "--accent-a9": bronze["--bronze-a9"], + "--accent-a10": bronze["--bronze-a10"], + "--accent-a11": bronze["--bronze-a11"], + "--accent-a12": bronze["--bronze-a12"], + "--accent-contrast": bronze["--bronze-contrast"], + "--accent-surface": bronze["--bronze-surface"], + "--accent-indicator": bronze["--bronze-indicator"], + "--accent-track": bronze["--bronze-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/brown.js b/packages/reflex-components-ui/js/src/themes/accent/brown.js new file mode 100644 index 00000000000..a933aeda0e0 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/brown.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { brown } from "../../colors/brown.stylex.js"; + +export const accentBrown = stylex.createTheme(accent, { + "--accent-1": brown["--brown-1"], + "--accent-2": brown["--brown-2"], + "--accent-3": brown["--brown-3"], + "--accent-4": brown["--brown-4"], + "--accent-5": brown["--brown-5"], + "--accent-6": brown["--brown-6"], + "--accent-7": brown["--brown-7"], + "--accent-8": brown["--brown-8"], + "--accent-9": brown["--brown-9"], + "--accent-10": brown["--brown-10"], + "--accent-11": brown["--brown-11"], + "--accent-12": brown["--brown-12"], + "--accent-a1": brown["--brown-a1"], + "--accent-a2": brown["--brown-a2"], + "--accent-a3": brown["--brown-a3"], + "--accent-a4": brown["--brown-a4"], + "--accent-a5": brown["--brown-a5"], + "--accent-a6": brown["--brown-a6"], + "--accent-a7": brown["--brown-a7"], + "--accent-a8": brown["--brown-a8"], + "--accent-a9": brown["--brown-a9"], + "--accent-a10": brown["--brown-a10"], + "--accent-a11": brown["--brown-a11"], + "--accent-a12": brown["--brown-a12"], + "--accent-contrast": brown["--brown-contrast"], + "--accent-surface": brown["--brown-surface"], + "--accent-indicator": brown["--brown-indicator"], + "--accent-track": brown["--brown-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/crimson.js b/packages/reflex-components-ui/js/src/themes/accent/crimson.js new file mode 100644 index 00000000000..816043536de --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/crimson.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { crimson } from "../../colors/crimson.stylex.js"; + +export const accentCrimson = stylex.createTheme(accent, { + "--accent-1": crimson["--crimson-1"], + "--accent-2": crimson["--crimson-2"], + "--accent-3": crimson["--crimson-3"], + "--accent-4": crimson["--crimson-4"], + "--accent-5": crimson["--crimson-5"], + "--accent-6": crimson["--crimson-6"], + "--accent-7": crimson["--crimson-7"], + "--accent-8": crimson["--crimson-8"], + "--accent-9": crimson["--crimson-9"], + "--accent-10": crimson["--crimson-10"], + "--accent-11": crimson["--crimson-11"], + "--accent-12": crimson["--crimson-12"], + "--accent-a1": crimson["--crimson-a1"], + "--accent-a2": crimson["--crimson-a2"], + "--accent-a3": crimson["--crimson-a3"], + "--accent-a4": crimson["--crimson-a4"], + "--accent-a5": crimson["--crimson-a5"], + "--accent-a6": crimson["--crimson-a6"], + "--accent-a7": crimson["--crimson-a7"], + "--accent-a8": crimson["--crimson-a8"], + "--accent-a9": crimson["--crimson-a9"], + "--accent-a10": crimson["--crimson-a10"], + "--accent-a11": crimson["--crimson-a11"], + "--accent-a12": crimson["--crimson-a12"], + "--accent-contrast": crimson["--crimson-contrast"], + "--accent-surface": crimson["--crimson-surface"], + "--accent-indicator": crimson["--crimson-indicator"], + "--accent-track": crimson["--crimson-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/cyan.js b/packages/reflex-components-ui/js/src/themes/accent/cyan.js new file mode 100644 index 00000000000..830edeb79d8 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/cyan.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { cyan } from "../../colors/cyan.stylex.js"; + +export const accentCyan = stylex.createTheme(accent, { + "--accent-1": cyan["--cyan-1"], + "--accent-2": cyan["--cyan-2"], + "--accent-3": cyan["--cyan-3"], + "--accent-4": cyan["--cyan-4"], + "--accent-5": cyan["--cyan-5"], + "--accent-6": cyan["--cyan-6"], + "--accent-7": cyan["--cyan-7"], + "--accent-8": cyan["--cyan-8"], + "--accent-9": cyan["--cyan-9"], + "--accent-10": cyan["--cyan-10"], + "--accent-11": cyan["--cyan-11"], + "--accent-12": cyan["--cyan-12"], + "--accent-a1": cyan["--cyan-a1"], + "--accent-a2": cyan["--cyan-a2"], + "--accent-a3": cyan["--cyan-a3"], + "--accent-a4": cyan["--cyan-a4"], + "--accent-a5": cyan["--cyan-a5"], + "--accent-a6": cyan["--cyan-a6"], + "--accent-a7": cyan["--cyan-a7"], + "--accent-a8": cyan["--cyan-a8"], + "--accent-a9": cyan["--cyan-a9"], + "--accent-a10": cyan["--cyan-a10"], + "--accent-a11": cyan["--cyan-a11"], + "--accent-a12": cyan["--cyan-a12"], + "--accent-contrast": cyan["--cyan-contrast"], + "--accent-surface": cyan["--cyan-surface"], + "--accent-indicator": cyan["--cyan-indicator"], + "--accent-track": cyan["--cyan-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/gold.js b/packages/reflex-components-ui/js/src/themes/accent/gold.js new file mode 100644 index 00000000000..55b50db820b --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/gold.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { gold } from "../../colors/gold.stylex.js"; + +export const accentGold = stylex.createTheme(accent, { + "--accent-1": gold["--gold-1"], + "--accent-2": gold["--gold-2"], + "--accent-3": gold["--gold-3"], + "--accent-4": gold["--gold-4"], + "--accent-5": gold["--gold-5"], + "--accent-6": gold["--gold-6"], + "--accent-7": gold["--gold-7"], + "--accent-8": gold["--gold-8"], + "--accent-9": gold["--gold-9"], + "--accent-10": gold["--gold-10"], + "--accent-11": gold["--gold-11"], + "--accent-12": gold["--gold-12"], + "--accent-a1": gold["--gold-a1"], + "--accent-a2": gold["--gold-a2"], + "--accent-a3": gold["--gold-a3"], + "--accent-a4": gold["--gold-a4"], + "--accent-a5": gold["--gold-a5"], + "--accent-a6": gold["--gold-a6"], + "--accent-a7": gold["--gold-a7"], + "--accent-a8": gold["--gold-a8"], + "--accent-a9": gold["--gold-a9"], + "--accent-a10": gold["--gold-a10"], + "--accent-a11": gold["--gold-a11"], + "--accent-a12": gold["--gold-a12"], + "--accent-contrast": gold["--gold-contrast"], + "--accent-surface": gold["--gold-surface"], + "--accent-indicator": gold["--gold-indicator"], + "--accent-track": gold["--gold-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/grass.js b/packages/reflex-components-ui/js/src/themes/accent/grass.js new file mode 100644 index 00000000000..8da8cc7db75 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/grass.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { grass } from "../../colors/grass.stylex.js"; + +export const accentGrass = stylex.createTheme(accent, { + "--accent-1": grass["--grass-1"], + "--accent-2": grass["--grass-2"], + "--accent-3": grass["--grass-3"], + "--accent-4": grass["--grass-4"], + "--accent-5": grass["--grass-5"], + "--accent-6": grass["--grass-6"], + "--accent-7": grass["--grass-7"], + "--accent-8": grass["--grass-8"], + "--accent-9": grass["--grass-9"], + "--accent-10": grass["--grass-10"], + "--accent-11": grass["--grass-11"], + "--accent-12": grass["--grass-12"], + "--accent-a1": grass["--grass-a1"], + "--accent-a2": grass["--grass-a2"], + "--accent-a3": grass["--grass-a3"], + "--accent-a4": grass["--grass-a4"], + "--accent-a5": grass["--grass-a5"], + "--accent-a6": grass["--grass-a6"], + "--accent-a7": grass["--grass-a7"], + "--accent-a8": grass["--grass-a8"], + "--accent-a9": grass["--grass-a9"], + "--accent-a10": grass["--grass-a10"], + "--accent-a11": grass["--grass-a11"], + "--accent-a12": grass["--grass-a12"], + "--accent-contrast": grass["--grass-contrast"], + "--accent-surface": grass["--grass-surface"], + "--accent-indicator": grass["--grass-indicator"], + "--accent-track": grass["--grass-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/gray.js b/packages/reflex-components-ui/js/src/themes/accent/gray.js new file mode 100644 index 00000000000..b5ec90d2c36 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/gray.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { gray } from "../../tokens/gray.stylex.js"; + +export const accentGray = stylex.createTheme(accent, { + "--accent-1": gray["--gray-1"], + "--accent-2": gray["--gray-2"], + "--accent-3": gray["--gray-3"], + "--accent-4": gray["--gray-4"], + "--accent-5": gray["--gray-5"], + "--accent-6": gray["--gray-6"], + "--accent-7": gray["--gray-7"], + "--accent-8": gray["--gray-8"], + "--accent-9": gray["--gray-9"], + "--accent-10": gray["--gray-10"], + "--accent-11": gray["--gray-11"], + "--accent-12": gray["--gray-12"], + "--accent-a1": gray["--gray-a1"], + "--accent-a2": gray["--gray-a2"], + "--accent-a3": gray["--gray-a3"], + "--accent-a4": gray["--gray-a4"], + "--accent-a5": gray["--gray-a5"], + "--accent-a6": gray["--gray-a6"], + "--accent-a7": gray["--gray-a7"], + "--accent-a8": gray["--gray-a8"], + "--accent-a9": gray["--gray-a9"], + "--accent-a10": gray["--gray-a10"], + "--accent-a11": gray["--gray-a11"], + "--accent-a12": gray["--gray-a12"], + "--accent-contrast": gray["--gray-contrast"], + "--accent-surface": gray["--gray-surface"], + "--accent-indicator": gray["--gray-indicator"], + "--accent-track": gray["--gray-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/green.js b/packages/reflex-components-ui/js/src/themes/accent/green.js new file mode 100644 index 00000000000..63028e6e3b5 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/green.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { green } from "../../colors/green.stylex.js"; + +export const accentGreen = stylex.createTheme(accent, { + "--accent-1": green["--green-1"], + "--accent-2": green["--green-2"], + "--accent-3": green["--green-3"], + "--accent-4": green["--green-4"], + "--accent-5": green["--green-5"], + "--accent-6": green["--green-6"], + "--accent-7": green["--green-7"], + "--accent-8": green["--green-8"], + "--accent-9": green["--green-9"], + "--accent-10": green["--green-10"], + "--accent-11": green["--green-11"], + "--accent-12": green["--green-12"], + "--accent-a1": green["--green-a1"], + "--accent-a2": green["--green-a2"], + "--accent-a3": green["--green-a3"], + "--accent-a4": green["--green-a4"], + "--accent-a5": green["--green-a5"], + "--accent-a6": green["--green-a6"], + "--accent-a7": green["--green-a7"], + "--accent-a8": green["--green-a8"], + "--accent-a9": green["--green-a9"], + "--accent-a10": green["--green-a10"], + "--accent-a11": green["--green-a11"], + "--accent-a12": green["--green-a12"], + "--accent-contrast": green["--green-contrast"], + "--accent-surface": green["--green-surface"], + "--accent-indicator": green["--green-indicator"], + "--accent-track": green["--green-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/indigo.js b/packages/reflex-components-ui/js/src/themes/accent/indigo.js new file mode 100644 index 00000000000..067bf28ee60 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/indigo.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { indigo } from "../../colors/indigo.stylex.js"; + +export const accentIndigo = stylex.createTheme(accent, { + "--accent-1": indigo["--indigo-1"], + "--accent-2": indigo["--indigo-2"], + "--accent-3": indigo["--indigo-3"], + "--accent-4": indigo["--indigo-4"], + "--accent-5": indigo["--indigo-5"], + "--accent-6": indigo["--indigo-6"], + "--accent-7": indigo["--indigo-7"], + "--accent-8": indigo["--indigo-8"], + "--accent-9": indigo["--indigo-9"], + "--accent-10": indigo["--indigo-10"], + "--accent-11": indigo["--indigo-11"], + "--accent-12": indigo["--indigo-12"], + "--accent-a1": indigo["--indigo-a1"], + "--accent-a2": indigo["--indigo-a2"], + "--accent-a3": indigo["--indigo-a3"], + "--accent-a4": indigo["--indigo-a4"], + "--accent-a5": indigo["--indigo-a5"], + "--accent-a6": indigo["--indigo-a6"], + "--accent-a7": indigo["--indigo-a7"], + "--accent-a8": indigo["--indigo-a8"], + "--accent-a9": indigo["--indigo-a9"], + "--accent-a10": indigo["--indigo-a10"], + "--accent-a11": indigo["--indigo-a11"], + "--accent-a12": indigo["--indigo-a12"], + "--accent-contrast": indigo["--indigo-contrast"], + "--accent-surface": indigo["--indigo-surface"], + "--accent-indicator": indigo["--indigo-indicator"], + "--accent-track": indigo["--indigo-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/iris.js b/packages/reflex-components-ui/js/src/themes/accent/iris.js new file mode 100644 index 00000000000..3533d30ada6 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/iris.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { iris } from "../../colors/iris.stylex.js"; + +export const accentIris = stylex.createTheme(accent, { + "--accent-1": iris["--iris-1"], + "--accent-2": iris["--iris-2"], + "--accent-3": iris["--iris-3"], + "--accent-4": iris["--iris-4"], + "--accent-5": iris["--iris-5"], + "--accent-6": iris["--iris-6"], + "--accent-7": iris["--iris-7"], + "--accent-8": iris["--iris-8"], + "--accent-9": iris["--iris-9"], + "--accent-10": iris["--iris-10"], + "--accent-11": iris["--iris-11"], + "--accent-12": iris["--iris-12"], + "--accent-a1": iris["--iris-a1"], + "--accent-a2": iris["--iris-a2"], + "--accent-a3": iris["--iris-a3"], + "--accent-a4": iris["--iris-a4"], + "--accent-a5": iris["--iris-a5"], + "--accent-a6": iris["--iris-a6"], + "--accent-a7": iris["--iris-a7"], + "--accent-a8": iris["--iris-a8"], + "--accent-a9": iris["--iris-a9"], + "--accent-a10": iris["--iris-a10"], + "--accent-a11": iris["--iris-a11"], + "--accent-a12": iris["--iris-a12"], + "--accent-contrast": iris["--iris-contrast"], + "--accent-surface": iris["--iris-surface"], + "--accent-indicator": iris["--iris-indicator"], + "--accent-track": iris["--iris-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/jade.js b/packages/reflex-components-ui/js/src/themes/accent/jade.js new file mode 100644 index 00000000000..a40749f03bf --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/jade.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { jade } from "../../colors/jade.stylex.js"; + +export const accentJade = stylex.createTheme(accent, { + "--accent-1": jade["--jade-1"], + "--accent-2": jade["--jade-2"], + "--accent-3": jade["--jade-3"], + "--accent-4": jade["--jade-4"], + "--accent-5": jade["--jade-5"], + "--accent-6": jade["--jade-6"], + "--accent-7": jade["--jade-7"], + "--accent-8": jade["--jade-8"], + "--accent-9": jade["--jade-9"], + "--accent-10": jade["--jade-10"], + "--accent-11": jade["--jade-11"], + "--accent-12": jade["--jade-12"], + "--accent-a1": jade["--jade-a1"], + "--accent-a2": jade["--jade-a2"], + "--accent-a3": jade["--jade-a3"], + "--accent-a4": jade["--jade-a4"], + "--accent-a5": jade["--jade-a5"], + "--accent-a6": jade["--jade-a6"], + "--accent-a7": jade["--jade-a7"], + "--accent-a8": jade["--jade-a8"], + "--accent-a9": jade["--jade-a9"], + "--accent-a10": jade["--jade-a10"], + "--accent-a11": jade["--jade-a11"], + "--accent-a12": jade["--jade-a12"], + "--accent-contrast": jade["--jade-contrast"], + "--accent-surface": jade["--jade-surface"], + "--accent-indicator": jade["--jade-indicator"], + "--accent-track": jade["--jade-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/lime.js b/packages/reflex-components-ui/js/src/themes/accent/lime.js new file mode 100644 index 00000000000..e0388650f91 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/lime.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { lime } from "../../colors/lime.stylex.js"; + +export const accentLime = stylex.createTheme(accent, { + "--accent-1": lime["--lime-1"], + "--accent-2": lime["--lime-2"], + "--accent-3": lime["--lime-3"], + "--accent-4": lime["--lime-4"], + "--accent-5": lime["--lime-5"], + "--accent-6": lime["--lime-6"], + "--accent-7": lime["--lime-7"], + "--accent-8": lime["--lime-8"], + "--accent-9": lime["--lime-9"], + "--accent-10": lime["--lime-10"], + "--accent-11": lime["--lime-11"], + "--accent-12": lime["--lime-12"], + "--accent-a1": lime["--lime-a1"], + "--accent-a2": lime["--lime-a2"], + "--accent-a3": lime["--lime-a3"], + "--accent-a4": lime["--lime-a4"], + "--accent-a5": lime["--lime-a5"], + "--accent-a6": lime["--lime-a6"], + "--accent-a7": lime["--lime-a7"], + "--accent-a8": lime["--lime-a8"], + "--accent-a9": lime["--lime-a9"], + "--accent-a10": lime["--lime-a10"], + "--accent-a11": lime["--lime-a11"], + "--accent-a12": lime["--lime-a12"], + "--accent-contrast": lime["--lime-contrast"], + "--accent-surface": lime["--lime-surface"], + "--accent-indicator": lime["--lime-indicator"], + "--accent-track": lime["--lime-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/mint.js b/packages/reflex-components-ui/js/src/themes/accent/mint.js new file mode 100644 index 00000000000..54fbdae09d1 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/mint.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { mint } from "../../colors/mint.stylex.js"; + +export const accentMint = stylex.createTheme(accent, { + "--accent-1": mint["--mint-1"], + "--accent-2": mint["--mint-2"], + "--accent-3": mint["--mint-3"], + "--accent-4": mint["--mint-4"], + "--accent-5": mint["--mint-5"], + "--accent-6": mint["--mint-6"], + "--accent-7": mint["--mint-7"], + "--accent-8": mint["--mint-8"], + "--accent-9": mint["--mint-9"], + "--accent-10": mint["--mint-10"], + "--accent-11": mint["--mint-11"], + "--accent-12": mint["--mint-12"], + "--accent-a1": mint["--mint-a1"], + "--accent-a2": mint["--mint-a2"], + "--accent-a3": mint["--mint-a3"], + "--accent-a4": mint["--mint-a4"], + "--accent-a5": mint["--mint-a5"], + "--accent-a6": mint["--mint-a6"], + "--accent-a7": mint["--mint-a7"], + "--accent-a8": mint["--mint-a8"], + "--accent-a9": mint["--mint-a9"], + "--accent-a10": mint["--mint-a10"], + "--accent-a11": mint["--mint-a11"], + "--accent-a12": mint["--mint-a12"], + "--accent-contrast": mint["--mint-contrast"], + "--accent-surface": mint["--mint-surface"], + "--accent-indicator": mint["--mint-indicator"], + "--accent-track": mint["--mint-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/orange.js b/packages/reflex-components-ui/js/src/themes/accent/orange.js new file mode 100644 index 00000000000..8ab839d8138 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/orange.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { orange } from "../../colors/orange.stylex.js"; + +export const accentOrange = stylex.createTheme(accent, { + "--accent-1": orange["--orange-1"], + "--accent-2": orange["--orange-2"], + "--accent-3": orange["--orange-3"], + "--accent-4": orange["--orange-4"], + "--accent-5": orange["--orange-5"], + "--accent-6": orange["--orange-6"], + "--accent-7": orange["--orange-7"], + "--accent-8": orange["--orange-8"], + "--accent-9": orange["--orange-9"], + "--accent-10": orange["--orange-10"], + "--accent-11": orange["--orange-11"], + "--accent-12": orange["--orange-12"], + "--accent-a1": orange["--orange-a1"], + "--accent-a2": orange["--orange-a2"], + "--accent-a3": orange["--orange-a3"], + "--accent-a4": orange["--orange-a4"], + "--accent-a5": orange["--orange-a5"], + "--accent-a6": orange["--orange-a6"], + "--accent-a7": orange["--orange-a7"], + "--accent-a8": orange["--orange-a8"], + "--accent-a9": orange["--orange-a9"], + "--accent-a10": orange["--orange-a10"], + "--accent-a11": orange["--orange-a11"], + "--accent-a12": orange["--orange-a12"], + "--accent-contrast": orange["--orange-contrast"], + "--accent-surface": orange["--orange-surface"], + "--accent-indicator": orange["--orange-indicator"], + "--accent-track": orange["--orange-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/pink.js b/packages/reflex-components-ui/js/src/themes/accent/pink.js new file mode 100644 index 00000000000..02c4a8f48e0 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/pink.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { pink } from "../../colors/pink.stylex.js"; + +export const accentPink = stylex.createTheme(accent, { + "--accent-1": pink["--pink-1"], + "--accent-2": pink["--pink-2"], + "--accent-3": pink["--pink-3"], + "--accent-4": pink["--pink-4"], + "--accent-5": pink["--pink-5"], + "--accent-6": pink["--pink-6"], + "--accent-7": pink["--pink-7"], + "--accent-8": pink["--pink-8"], + "--accent-9": pink["--pink-9"], + "--accent-10": pink["--pink-10"], + "--accent-11": pink["--pink-11"], + "--accent-12": pink["--pink-12"], + "--accent-a1": pink["--pink-a1"], + "--accent-a2": pink["--pink-a2"], + "--accent-a3": pink["--pink-a3"], + "--accent-a4": pink["--pink-a4"], + "--accent-a5": pink["--pink-a5"], + "--accent-a6": pink["--pink-a6"], + "--accent-a7": pink["--pink-a7"], + "--accent-a8": pink["--pink-a8"], + "--accent-a9": pink["--pink-a9"], + "--accent-a10": pink["--pink-a10"], + "--accent-a11": pink["--pink-a11"], + "--accent-a12": pink["--pink-a12"], + "--accent-contrast": pink["--pink-contrast"], + "--accent-surface": pink["--pink-surface"], + "--accent-indicator": pink["--pink-indicator"], + "--accent-track": pink["--pink-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/plum.js b/packages/reflex-components-ui/js/src/themes/accent/plum.js new file mode 100644 index 00000000000..5494f737394 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/plum.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { plum } from "../../colors/plum.stylex.js"; + +export const accentPlum = stylex.createTheme(accent, { + "--accent-1": plum["--plum-1"], + "--accent-2": plum["--plum-2"], + "--accent-3": plum["--plum-3"], + "--accent-4": plum["--plum-4"], + "--accent-5": plum["--plum-5"], + "--accent-6": plum["--plum-6"], + "--accent-7": plum["--plum-7"], + "--accent-8": plum["--plum-8"], + "--accent-9": plum["--plum-9"], + "--accent-10": plum["--plum-10"], + "--accent-11": plum["--plum-11"], + "--accent-12": plum["--plum-12"], + "--accent-a1": plum["--plum-a1"], + "--accent-a2": plum["--plum-a2"], + "--accent-a3": plum["--plum-a3"], + "--accent-a4": plum["--plum-a4"], + "--accent-a5": plum["--plum-a5"], + "--accent-a6": plum["--plum-a6"], + "--accent-a7": plum["--plum-a7"], + "--accent-a8": plum["--plum-a8"], + "--accent-a9": plum["--plum-a9"], + "--accent-a10": plum["--plum-a10"], + "--accent-a11": plum["--plum-a11"], + "--accent-a12": plum["--plum-a12"], + "--accent-contrast": plum["--plum-contrast"], + "--accent-surface": plum["--plum-surface"], + "--accent-indicator": plum["--plum-indicator"], + "--accent-track": plum["--plum-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/purple.js b/packages/reflex-components-ui/js/src/themes/accent/purple.js new file mode 100644 index 00000000000..65346307631 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/purple.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { purple } from "../../colors/purple.stylex.js"; + +export const accentPurple = stylex.createTheme(accent, { + "--accent-1": purple["--purple-1"], + "--accent-2": purple["--purple-2"], + "--accent-3": purple["--purple-3"], + "--accent-4": purple["--purple-4"], + "--accent-5": purple["--purple-5"], + "--accent-6": purple["--purple-6"], + "--accent-7": purple["--purple-7"], + "--accent-8": purple["--purple-8"], + "--accent-9": purple["--purple-9"], + "--accent-10": purple["--purple-10"], + "--accent-11": purple["--purple-11"], + "--accent-12": purple["--purple-12"], + "--accent-a1": purple["--purple-a1"], + "--accent-a2": purple["--purple-a2"], + "--accent-a3": purple["--purple-a3"], + "--accent-a4": purple["--purple-a4"], + "--accent-a5": purple["--purple-a5"], + "--accent-a6": purple["--purple-a6"], + "--accent-a7": purple["--purple-a7"], + "--accent-a8": purple["--purple-a8"], + "--accent-a9": purple["--purple-a9"], + "--accent-a10": purple["--purple-a10"], + "--accent-a11": purple["--purple-a11"], + "--accent-a12": purple["--purple-a12"], + "--accent-contrast": purple["--purple-contrast"], + "--accent-surface": purple["--purple-surface"], + "--accent-indicator": purple["--purple-indicator"], + "--accent-track": purple["--purple-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/red.js b/packages/reflex-components-ui/js/src/themes/accent/red.js new file mode 100644 index 00000000000..a68687d391d --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/red.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { red } from "../../colors/red.stylex.js"; + +export const accentRed = stylex.createTheme(accent, { + "--accent-1": red["--red-1"], + "--accent-2": red["--red-2"], + "--accent-3": red["--red-3"], + "--accent-4": red["--red-4"], + "--accent-5": red["--red-5"], + "--accent-6": red["--red-6"], + "--accent-7": red["--red-7"], + "--accent-8": red["--red-8"], + "--accent-9": red["--red-9"], + "--accent-10": red["--red-10"], + "--accent-11": red["--red-11"], + "--accent-12": red["--red-12"], + "--accent-a1": red["--red-a1"], + "--accent-a2": red["--red-a2"], + "--accent-a3": red["--red-a3"], + "--accent-a4": red["--red-a4"], + "--accent-a5": red["--red-a5"], + "--accent-a6": red["--red-a6"], + "--accent-a7": red["--red-a7"], + "--accent-a8": red["--red-a8"], + "--accent-a9": red["--red-a9"], + "--accent-a10": red["--red-a10"], + "--accent-a11": red["--red-a11"], + "--accent-a12": red["--red-a12"], + "--accent-contrast": red["--red-contrast"], + "--accent-surface": red["--red-surface"], + "--accent-indicator": red["--red-indicator"], + "--accent-track": red["--red-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/ruby.js b/packages/reflex-components-ui/js/src/themes/accent/ruby.js new file mode 100644 index 00000000000..f5216066959 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/ruby.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { ruby } from "../../colors/ruby.stylex.js"; + +export const accentRuby = stylex.createTheme(accent, { + "--accent-1": ruby["--ruby-1"], + "--accent-2": ruby["--ruby-2"], + "--accent-3": ruby["--ruby-3"], + "--accent-4": ruby["--ruby-4"], + "--accent-5": ruby["--ruby-5"], + "--accent-6": ruby["--ruby-6"], + "--accent-7": ruby["--ruby-7"], + "--accent-8": ruby["--ruby-8"], + "--accent-9": ruby["--ruby-9"], + "--accent-10": ruby["--ruby-10"], + "--accent-11": ruby["--ruby-11"], + "--accent-12": ruby["--ruby-12"], + "--accent-a1": ruby["--ruby-a1"], + "--accent-a2": ruby["--ruby-a2"], + "--accent-a3": ruby["--ruby-a3"], + "--accent-a4": ruby["--ruby-a4"], + "--accent-a5": ruby["--ruby-a5"], + "--accent-a6": ruby["--ruby-a6"], + "--accent-a7": ruby["--ruby-a7"], + "--accent-a8": ruby["--ruby-a8"], + "--accent-a9": ruby["--ruby-a9"], + "--accent-a10": ruby["--ruby-a10"], + "--accent-a11": ruby["--ruby-a11"], + "--accent-a12": ruby["--ruby-a12"], + "--accent-contrast": ruby["--ruby-contrast"], + "--accent-surface": ruby["--ruby-surface"], + "--accent-indicator": ruby["--ruby-indicator"], + "--accent-track": ruby["--ruby-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/sky.js b/packages/reflex-components-ui/js/src/themes/accent/sky.js new file mode 100644 index 00000000000..3f2c0179c71 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/sky.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { sky } from "../../colors/sky.stylex.js"; + +export const accentSky = stylex.createTheme(accent, { + "--accent-1": sky["--sky-1"], + "--accent-2": sky["--sky-2"], + "--accent-3": sky["--sky-3"], + "--accent-4": sky["--sky-4"], + "--accent-5": sky["--sky-5"], + "--accent-6": sky["--sky-6"], + "--accent-7": sky["--sky-7"], + "--accent-8": sky["--sky-8"], + "--accent-9": sky["--sky-9"], + "--accent-10": sky["--sky-10"], + "--accent-11": sky["--sky-11"], + "--accent-12": sky["--sky-12"], + "--accent-a1": sky["--sky-a1"], + "--accent-a2": sky["--sky-a2"], + "--accent-a3": sky["--sky-a3"], + "--accent-a4": sky["--sky-a4"], + "--accent-a5": sky["--sky-a5"], + "--accent-a6": sky["--sky-a6"], + "--accent-a7": sky["--sky-a7"], + "--accent-a8": sky["--sky-a8"], + "--accent-a9": sky["--sky-a9"], + "--accent-a10": sky["--sky-a10"], + "--accent-a11": sky["--sky-a11"], + "--accent-a12": sky["--sky-a12"], + "--accent-contrast": sky["--sky-contrast"], + "--accent-surface": sky["--sky-surface"], + "--accent-indicator": sky["--sky-indicator"], + "--accent-track": sky["--sky-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/teal.js b/packages/reflex-components-ui/js/src/themes/accent/teal.js new file mode 100644 index 00000000000..de7dc6e3fdb --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/teal.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { teal } from "../../colors/teal.stylex.js"; + +export const accentTeal = stylex.createTheme(accent, { + "--accent-1": teal["--teal-1"], + "--accent-2": teal["--teal-2"], + "--accent-3": teal["--teal-3"], + "--accent-4": teal["--teal-4"], + "--accent-5": teal["--teal-5"], + "--accent-6": teal["--teal-6"], + "--accent-7": teal["--teal-7"], + "--accent-8": teal["--teal-8"], + "--accent-9": teal["--teal-9"], + "--accent-10": teal["--teal-10"], + "--accent-11": teal["--teal-11"], + "--accent-12": teal["--teal-12"], + "--accent-a1": teal["--teal-a1"], + "--accent-a2": teal["--teal-a2"], + "--accent-a3": teal["--teal-a3"], + "--accent-a4": teal["--teal-a4"], + "--accent-a5": teal["--teal-a5"], + "--accent-a6": teal["--teal-a6"], + "--accent-a7": teal["--teal-a7"], + "--accent-a8": teal["--teal-a8"], + "--accent-a9": teal["--teal-a9"], + "--accent-a10": teal["--teal-a10"], + "--accent-a11": teal["--teal-a11"], + "--accent-a12": teal["--teal-a12"], + "--accent-contrast": teal["--teal-contrast"], + "--accent-surface": teal["--teal-surface"], + "--accent-indicator": teal["--teal-indicator"], + "--accent-track": teal["--teal-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/tomato.js b/packages/reflex-components-ui/js/src/themes/accent/tomato.js new file mode 100644 index 00000000000..ea55b8075c7 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/tomato.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { tomato } from "../../colors/tomato.stylex.js"; + +export const accentTomato = stylex.createTheme(accent, { + "--accent-1": tomato["--tomato-1"], + "--accent-2": tomato["--tomato-2"], + "--accent-3": tomato["--tomato-3"], + "--accent-4": tomato["--tomato-4"], + "--accent-5": tomato["--tomato-5"], + "--accent-6": tomato["--tomato-6"], + "--accent-7": tomato["--tomato-7"], + "--accent-8": tomato["--tomato-8"], + "--accent-9": tomato["--tomato-9"], + "--accent-10": tomato["--tomato-10"], + "--accent-11": tomato["--tomato-11"], + "--accent-12": tomato["--tomato-12"], + "--accent-a1": tomato["--tomato-a1"], + "--accent-a2": tomato["--tomato-a2"], + "--accent-a3": tomato["--tomato-a3"], + "--accent-a4": tomato["--tomato-a4"], + "--accent-a5": tomato["--tomato-a5"], + "--accent-a6": tomato["--tomato-a6"], + "--accent-a7": tomato["--tomato-a7"], + "--accent-a8": tomato["--tomato-a8"], + "--accent-a9": tomato["--tomato-a9"], + "--accent-a10": tomato["--tomato-a10"], + "--accent-a11": tomato["--tomato-a11"], + "--accent-a12": tomato["--tomato-a12"], + "--accent-contrast": tomato["--tomato-contrast"], + "--accent-surface": tomato["--tomato-surface"], + "--accent-indicator": tomato["--tomato-indicator"], + "--accent-track": tomato["--tomato-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/violet.js b/packages/reflex-components-ui/js/src/themes/accent/violet.js new file mode 100644 index 00000000000..8802b28994b --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/violet.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { violet } from "../../colors/violet.stylex.js"; + +export const accentViolet = stylex.createTheme(accent, { + "--accent-1": violet["--violet-1"], + "--accent-2": violet["--violet-2"], + "--accent-3": violet["--violet-3"], + "--accent-4": violet["--violet-4"], + "--accent-5": violet["--violet-5"], + "--accent-6": violet["--violet-6"], + "--accent-7": violet["--violet-7"], + "--accent-8": violet["--violet-8"], + "--accent-9": violet["--violet-9"], + "--accent-10": violet["--violet-10"], + "--accent-11": violet["--violet-11"], + "--accent-12": violet["--violet-12"], + "--accent-a1": violet["--violet-a1"], + "--accent-a2": violet["--violet-a2"], + "--accent-a3": violet["--violet-a3"], + "--accent-a4": violet["--violet-a4"], + "--accent-a5": violet["--violet-a5"], + "--accent-a6": violet["--violet-a6"], + "--accent-a7": violet["--violet-a7"], + "--accent-a8": violet["--violet-a8"], + "--accent-a9": violet["--violet-a9"], + "--accent-a10": violet["--violet-a10"], + "--accent-a11": violet["--violet-a11"], + "--accent-a12": violet["--violet-a12"], + "--accent-contrast": violet["--violet-contrast"], + "--accent-surface": violet["--violet-surface"], + "--accent-indicator": violet["--violet-indicator"], + "--accent-track": violet["--violet-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/accent/yellow.js b/packages/reflex-components-ui/js/src/themes/accent/yellow.js new file mode 100644 index 00000000000..940747c2443 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/accent/yellow.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { yellow } from "../../colors/yellow.stylex.js"; + +export const accentYellow = stylex.createTheme(accent, { + "--accent-1": yellow["--yellow-1"], + "--accent-2": yellow["--yellow-2"], + "--accent-3": yellow["--yellow-3"], + "--accent-4": yellow["--yellow-4"], + "--accent-5": yellow["--yellow-5"], + "--accent-6": yellow["--yellow-6"], + "--accent-7": yellow["--yellow-7"], + "--accent-8": yellow["--yellow-8"], + "--accent-9": yellow["--yellow-9"], + "--accent-10": yellow["--yellow-10"], + "--accent-11": yellow["--yellow-11"], + "--accent-12": yellow["--yellow-12"], + "--accent-a1": yellow["--yellow-a1"], + "--accent-a2": yellow["--yellow-a2"], + "--accent-a3": yellow["--yellow-a3"], + "--accent-a4": yellow["--yellow-a4"], + "--accent-a5": yellow["--yellow-a5"], + "--accent-a6": yellow["--yellow-a6"], + "--accent-a7": yellow["--yellow-a7"], + "--accent-a8": yellow["--yellow-a8"], + "--accent-a9": yellow["--yellow-a9"], + "--accent-a10": yellow["--yellow-a10"], + "--accent-a11": yellow["--yellow-a11"], + "--accent-a12": yellow["--yellow-a12"], + "--accent-contrast": yellow["--yellow-contrast"], + "--accent-surface": yellow["--yellow-surface"], + "--accent-indicator": yellow["--yellow-indicator"], + "--accent-track": yellow["--yellow-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/focus.js b/packages/reflex-components-ui/js/src/themes/focus.js new file mode 100644 index 00000000000..c9ce54c90b7 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/focus.js @@ -0,0 +1,7 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { focus } from "../tokens/focus.stylex.js"; + +export const focusScope = stylex.createTheme(focus, {}); diff --git a/packages/reflex-components-ui/js/src/themes/gray/gray.js b/packages/reflex-components-ui/js/src/themes/gray/gray.js new file mode 100644 index 00000000000..d2e24215df3 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/gray/gray.js @@ -0,0 +1,215 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; + +// StyleX leaves a null level out, which the type of a string token does +// not say. +const NONE = /** @type {string} */ (/** @type {unknown} */ (null)); + +export const grayGray = stylex.createTheme(gray, { + "--gray-1": { + default: "light-dark(#fcfcfc, #111111)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.988 0.988 0.988), color(display-p3 0.067 0.067 0.067))", + }, + }, + "--gray-2": { + default: "light-dark(#f9f9f9, #191919)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.975 0.975 0.975), color(display-p3 0.098 0.098 0.098))", + }, + }, + "--gray-3": { + default: "light-dark(#f0f0f0, #222222)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.939 0.939 0.939), color(display-p3 0.135 0.135 0.135))", + }, + }, + "--gray-4": { + default: "light-dark(#e8e8e8, #2a2a2a)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.908 0.908 0.908), color(display-p3 0.163 0.163 0.163))", + }, + }, + "--gray-5": { + default: "light-dark(#e0e0e0, #313131)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.88 0.88 0.88), color(display-p3 0.192 0.192 0.192))", + }, + }, + "--gray-6": { + default: "light-dark(#d9d9d9, #3a3a3a)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.849 0.849 0.849), color(display-p3 0.228 0.228 0.228))", + }, + }, + "--gray-7": { + default: "light-dark(#cecece, #484848)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.807 0.807 0.807), color(display-p3 0.283 0.283 0.283))", + }, + }, + "--gray-8": { + default: "light-dark(#bbbbbb, #606060)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.732 0.732 0.732), color(display-p3 0.375 0.375 0.375))", + }, + }, + "--gray-9": { + default: "light-dark(#8d8d8d, #6e6e6e)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.553 0.553 0.553), color(display-p3 0.431 0.431 0.431))", + }, + }, + "--gray-10": { + default: "light-dark(#838383, #7b7b7b)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.512 0.512 0.512), color(display-p3 0.484 0.484 0.484))", + }, + }, + "--gray-11": { + default: "light-dark(#646464, #b4b4b4)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.392 0.392 0.392), color(display-p3 0.706 0.706 0.706))", + }, + }, + "--gray-12": { + default: "light-dark(#202020, #eeeeee)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.125 0.125 0.125), color(display-p3 0.933 0.933 0.933))", + }, + }, + "--gray-a1": { + default: "light-dark(#00000003, #00000000)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.012), color(display-p3 0 0 0 / 0))", + }, + }, + "--gray-a2": { + default: "light-dark(#00000006, #ffffff09)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.024), color(display-p3 1 1 1 / 0.034))", + }, + }, + "--gray-a3": { + default: "light-dark(#0000000f, #ffffff12)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.063), color(display-p3 1 1 1 / 0.071))", + }, + }, + "--gray-a4": { + default: "light-dark(#00000017, #ffffff1b)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.09), color(display-p3 1 1 1 / 0.105))", + }, + }, + "--gray-a5": { + default: "light-dark(#0000001f, #ffffff22)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.122), color(display-p3 1 1 1 / 0.134))", + }, + }, + "--gray-a6": { + default: "light-dark(#00000026, #ffffff2c)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.153), color(display-p3 1 1 1 / 0.172))", + }, + }, + "--gray-a7": { + default: "light-dark(#00000031, #ffffff3b)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.192), color(display-p3 1 1 1 / 0.231))", + }, + }, + "--gray-a8": { + default: "light-dark(#00000044, #ffffff55)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.267), color(display-p3 1 1 1 / 0.332))", + }, + }, + "--gray-a9": { + default: "light-dark(#00000072, #ffffff64)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.447), color(display-p3 1 1 1 / 0.391))", + }, + }, + "--gray-a10": { + default: "light-dark(#0000007c, #ffffff72)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.486), color(display-p3 1 1 1 / 0.445))", + }, + }, + "--gray-a11": { + default: "light-dark(#0000009b, #ffffffaf)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.608), color(display-p3 1 1 1 / 0.685))", + }, + }, + "--gray-a12": { + default: "light-dark(#000000df, #ffffffed)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0 0 0 / 0.875), color(display-p3 1 1 1 / 0.929))", + }, + }, + "--gray-surface": { + default: "light-dark(#ffffffcc, #21212180)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 1 1 1 / 0.8), color(display-p3 0.1255 0.1255 0.1255 / 0.5))", + }, + }, + "--gray-indicator": gray["--gray-9"], + "--gray-track": gray["--gray-9"], + "--gray-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/src/themes/gray/mauve.js b/packages/reflex-components-ui/js/src/themes/gray/mauve.js new file mode 100644 index 00000000000..cbfc531c944 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/gray/mauve.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; +import { mauve } from "../../colors/mauve.stylex.js"; + +export const grayMauve = stylex.createTheme(gray, { + "--gray-1": mauve["--mauve-1"], + "--gray-2": mauve["--mauve-2"], + "--gray-3": mauve["--mauve-3"], + "--gray-4": mauve["--mauve-4"], + "--gray-5": mauve["--mauve-5"], + "--gray-6": mauve["--mauve-6"], + "--gray-7": mauve["--mauve-7"], + "--gray-8": mauve["--mauve-8"], + "--gray-9": mauve["--mauve-9"], + "--gray-10": mauve["--mauve-10"], + "--gray-11": mauve["--mauve-11"], + "--gray-12": mauve["--mauve-12"], + "--gray-a1": mauve["--mauve-a1"], + "--gray-a2": mauve["--mauve-a2"], + "--gray-a3": mauve["--mauve-a3"], + "--gray-a4": mauve["--mauve-a4"], + "--gray-a5": mauve["--mauve-a5"], + "--gray-a6": mauve["--mauve-a6"], + "--gray-a7": mauve["--mauve-a7"], + "--gray-a8": mauve["--mauve-a8"], + "--gray-a9": mauve["--mauve-a9"], + "--gray-a10": mauve["--mauve-a10"], + "--gray-a11": mauve["--mauve-a11"], + "--gray-a12": mauve["--mauve-a12"], + "--gray-contrast": mauve["--mauve-contrast"], + "--gray-surface": mauve["--mauve-surface"], + "--gray-indicator": mauve["--mauve-indicator"], + "--gray-track": mauve["--mauve-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/gray/olive.js b/packages/reflex-components-ui/js/src/themes/gray/olive.js new file mode 100644 index 00000000000..14ef616b389 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/gray/olive.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; +import { olive } from "../../colors/olive.stylex.js"; + +export const grayOlive = stylex.createTheme(gray, { + "--gray-1": olive["--olive-1"], + "--gray-2": olive["--olive-2"], + "--gray-3": olive["--olive-3"], + "--gray-4": olive["--olive-4"], + "--gray-5": olive["--olive-5"], + "--gray-6": olive["--olive-6"], + "--gray-7": olive["--olive-7"], + "--gray-8": olive["--olive-8"], + "--gray-9": olive["--olive-9"], + "--gray-10": olive["--olive-10"], + "--gray-11": olive["--olive-11"], + "--gray-12": olive["--olive-12"], + "--gray-a1": olive["--olive-a1"], + "--gray-a2": olive["--olive-a2"], + "--gray-a3": olive["--olive-a3"], + "--gray-a4": olive["--olive-a4"], + "--gray-a5": olive["--olive-a5"], + "--gray-a6": olive["--olive-a6"], + "--gray-a7": olive["--olive-a7"], + "--gray-a8": olive["--olive-a8"], + "--gray-a9": olive["--olive-a9"], + "--gray-a10": olive["--olive-a10"], + "--gray-a11": olive["--olive-a11"], + "--gray-a12": olive["--olive-a12"], + "--gray-contrast": olive["--olive-contrast"], + "--gray-surface": olive["--olive-surface"], + "--gray-indicator": olive["--olive-indicator"], + "--gray-track": olive["--olive-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/gray/sage.js b/packages/reflex-components-ui/js/src/themes/gray/sage.js new file mode 100644 index 00000000000..e7d062895d7 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/gray/sage.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; +import { sage } from "../../colors/sage.stylex.js"; + +export const graySage = stylex.createTheme(gray, { + "--gray-1": sage["--sage-1"], + "--gray-2": sage["--sage-2"], + "--gray-3": sage["--sage-3"], + "--gray-4": sage["--sage-4"], + "--gray-5": sage["--sage-5"], + "--gray-6": sage["--sage-6"], + "--gray-7": sage["--sage-7"], + "--gray-8": sage["--sage-8"], + "--gray-9": sage["--sage-9"], + "--gray-10": sage["--sage-10"], + "--gray-11": sage["--sage-11"], + "--gray-12": sage["--sage-12"], + "--gray-a1": sage["--sage-a1"], + "--gray-a2": sage["--sage-a2"], + "--gray-a3": sage["--sage-a3"], + "--gray-a4": sage["--sage-a4"], + "--gray-a5": sage["--sage-a5"], + "--gray-a6": sage["--sage-a6"], + "--gray-a7": sage["--sage-a7"], + "--gray-a8": sage["--sage-a8"], + "--gray-a9": sage["--sage-a9"], + "--gray-a10": sage["--sage-a10"], + "--gray-a11": sage["--sage-a11"], + "--gray-a12": sage["--sage-a12"], + "--gray-contrast": sage["--sage-contrast"], + "--gray-surface": sage["--sage-surface"], + "--gray-indicator": sage["--sage-indicator"], + "--gray-track": sage["--sage-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/gray/sand.js b/packages/reflex-components-ui/js/src/themes/gray/sand.js new file mode 100644 index 00000000000..95e4d488006 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/gray/sand.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; +import { sand } from "../../colors/sand.stylex.js"; + +export const graySand = stylex.createTheme(gray, { + "--gray-1": sand["--sand-1"], + "--gray-2": sand["--sand-2"], + "--gray-3": sand["--sand-3"], + "--gray-4": sand["--sand-4"], + "--gray-5": sand["--sand-5"], + "--gray-6": sand["--sand-6"], + "--gray-7": sand["--sand-7"], + "--gray-8": sand["--sand-8"], + "--gray-9": sand["--sand-9"], + "--gray-10": sand["--sand-10"], + "--gray-11": sand["--sand-11"], + "--gray-12": sand["--sand-12"], + "--gray-a1": sand["--sand-a1"], + "--gray-a2": sand["--sand-a2"], + "--gray-a3": sand["--sand-a3"], + "--gray-a4": sand["--sand-a4"], + "--gray-a5": sand["--sand-a5"], + "--gray-a6": sand["--sand-a6"], + "--gray-a7": sand["--sand-a7"], + "--gray-a8": sand["--sand-a8"], + "--gray-a9": sand["--sand-a9"], + "--gray-a10": sand["--sand-a10"], + "--gray-a11": sand["--sand-a11"], + "--gray-a12": sand["--sand-a12"], + "--gray-contrast": sand["--sand-contrast"], + "--gray-surface": sand["--sand-surface"], + "--gray-indicator": sand["--sand-indicator"], + "--gray-track": sand["--sand-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/gray/slate.js b/packages/reflex-components-ui/js/src/themes/gray/slate.js new file mode 100644 index 00000000000..49edc7b1244 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/gray/slate.js @@ -0,0 +1,37 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; +import { slate } from "../../colors/slate.stylex.js"; + +export const graySlate = stylex.createTheme(gray, { + "--gray-1": slate["--slate-1"], + "--gray-2": slate["--slate-2"], + "--gray-3": slate["--slate-3"], + "--gray-4": slate["--slate-4"], + "--gray-5": slate["--slate-5"], + "--gray-6": slate["--slate-6"], + "--gray-7": slate["--slate-7"], + "--gray-8": slate["--slate-8"], + "--gray-9": slate["--slate-9"], + "--gray-10": slate["--slate-10"], + "--gray-11": slate["--slate-11"], + "--gray-12": slate["--slate-12"], + "--gray-a1": slate["--slate-a1"], + "--gray-a2": slate["--slate-a2"], + "--gray-a3": slate["--slate-a3"], + "--gray-a4": slate["--slate-a4"], + "--gray-a5": slate["--slate-a5"], + "--gray-a6": slate["--slate-a6"], + "--gray-a7": slate["--slate-a7"], + "--gray-a8": slate["--slate-a8"], + "--gray-a9": slate["--slate-a9"], + "--gray-a10": slate["--slate-a10"], + "--gray-a11": slate["--slate-a11"], + "--gray-a12": slate["--slate-a12"], + "--gray-contrast": slate["--slate-contrast"], + "--gray-surface": slate["--slate-surface"], + "--gray-indicator": slate["--slate-indicator"], + "--gray-track": slate["--slate-track"], +}); diff --git a/packages/reflex-components-ui/js/src/themes/panel.js b/packages/reflex-components-ui/js/src/themes/panel.js new file mode 100644 index 00000000000..fafdcb3a87c --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/panel.js @@ -0,0 +1,15 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { panel } from "../tokens/panel.stylex.js"; + +export const panelSolid = stylex.createTheme(panel, { + "--backdrop-filter-panel": "none", + "--panel-solid": " ", +}); + +export const panelTranslucent = stylex.createTheme(panel, { + "--backdrop-filter-panel": "blur(64px)", + "--panel-solid": "initial", +}); diff --git a/packages/reflex-components-ui/js/src/themes/radius.js b/packages/reflex-components-ui/js/src/themes/radius.js new file mode 100644 index 00000000000..18eb9cdf8ff --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/radius.js @@ -0,0 +1,35 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { radiusFactor } from "../tokens/radius.stylex.js"; + +export const radiusFull = stylex.createTheme(radiusFactor, { + "--radius-factor": "1.5", + "--radius-full": "9999px", + "--radius-thumb": "9999px", +}); + +export const radiusLarge = stylex.createTheme(radiusFactor, { + "--radius-factor": "1.5", + "--radius-full": "0px", + "--radius-thumb": "9999px", +}); + +export const radiusMedium = stylex.createTheme(radiusFactor, { + "--radius-factor": "1", + "--radius-full": "0px", + "--radius-thumb": "9999px", +}); + +export const radiusNone = stylex.createTheme(radiusFactor, { + "--radius-factor": "0", + "--radius-full": "0px", + "--radius-thumb": "0.5px", +}); + +export const radiusSmall = stylex.createTheme(radiusFactor, { + "--radius-factor": "0.75", + "--radius-full": "0px", + "--radius-thumb": "0.5px", +}); diff --git a/packages/reflex-components-ui/js/src/themes/scaling.js b/packages/reflex-components-ui/js/src/themes/scaling.js new file mode 100644 index 00000000000..f2f9ca6c230 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/scaling.js @@ -0,0 +1,25 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "../tokens/scaling.stylex.js"; + +export const scaling100 = stylex.createTheme(scaling, { + "--scaling": "1", +}); + +export const scaling105 = stylex.createTheme(scaling, { + "--scaling": "1.05", +}); + +export const scaling110 = stylex.createTheme(scaling, { + "--scaling": "1.1", +}); + +export const scaling90 = stylex.createTheme(scaling, { + "--scaling": "0.9", +}); + +export const scaling95 = stylex.createTheme(scaling, { + "--scaling": "0.95", +}); diff --git a/packages/reflex-components-ui/js/src/themes/scope.js b/packages/reflex-components-ui/js/src/themes/scope.js new file mode 100644 index 00000000000..0c496e45e6d --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/scope.js @@ -0,0 +1,19 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { color } from "../tokens/color.stylex.js"; +import { radius } from "../tokens/radius.stylex.js"; +import { shadow } from "../tokens/shadow.stylex.js"; +import { space } from "../tokens/space.stylex.js"; +import { typography } from "../tokens/typography.stylex.js"; + +export const spaceScope = stylex.createTheme(space, {}); + +export const radiusScope = stylex.createTheme(radius, {}); + +export const typographyScope = stylex.createTheme(typography, {}); + +export const shadowScope = stylex.createTheme(shadow, {}); + +export const colorScope = stylex.createTheme(color, {}); diff --git a/packages/reflex-components-ui/js/src/themes/theme.js b/packages/reflex-components-ui/js/src/themes/theme.js new file mode 100644 index 00000000000..e9693fb9974 --- /dev/null +++ b/packages/reflex-components-ui/js/src/themes/theme.js @@ -0,0 +1,32 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { color } from "../tokens/color.stylex.js"; +import { gray } from "../tokens/gray.stylex.js"; +import { typography } from "../tokens/typography.stylex.js"; + +export const theme = stylex.create({ + light: { + colorScheme: "light", + }, + dark: { + colorScheme: "dark", + }, + background: { + backgroundColor: color["--color-background"], + }, + root: { + overflowWrap: "break-word", + fontFamily: typography["--default-font-family"], + fontSize: typography["--default-font-size"], + fontWeight: typography["--default-font-weight"], + fontStyle: typography["--default-font-style"], + lineHeight: typography["--default-line-height"], + letterSpacing: typography["--default-letter-spacing"], + textSizeAdjust: "none", + WebkitFontSmoothing: "antialiased", + MozOsxFontSmoothing: "grayscale", + color: gray["--gray-12"], + }, +}); diff --git a/packages/reflex-components-ui/js/src/tokens/accent.stylex.js b/packages/reflex-components-ui/js/src/tokens/accent.stylex.js new file mode 100644 index 00000000000..f7953c0a9f7 --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/accent.stylex.js @@ -0,0 +1,34 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const accent = stylex.defineVars({ + "--accent-1": "initial", + "--accent-2": "initial", + "--accent-3": "initial", + "--accent-4": "initial", + "--accent-5": "initial", + "--accent-6": "initial", + "--accent-7": "initial", + "--accent-8": "initial", + "--accent-9": "initial", + "--accent-10": "initial", + "--accent-11": "initial", + "--accent-12": "initial", + "--accent-a1": "initial", + "--accent-a2": "initial", + "--accent-a3": "initial", + "--accent-a4": "initial", + "--accent-a5": "initial", + "--accent-a6": "initial", + "--accent-a7": "initial", + "--accent-a8": "initial", + "--accent-a9": "initial", + "--accent-a10": "initial", + "--accent-a11": "initial", + "--accent-a12": "initial", + "--accent-contrast": "initial", + "--accent-surface": "initial", + "--accent-indicator": "initial", + "--accent-track": "initial", +}); diff --git a/packages/reflex-components-ui/js/src/tokens/color.stylex.js b/packages/reflex-components-ui/js/src/tokens/color.stylex.js new file mode 100644 index 00000000000..d7b54f2494a --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/color.stylex.js @@ -0,0 +1,26 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { black } from "../colors/black.stylex.js"; +import { gray } from "./gray.stylex.js"; +import { panel } from "./panel.stylex.js"; + +export const color = stylex.defineVars({ + "--color-background": `light-dark(white, ${gray["--gray-1"]})`, + "--color-overlay": `light-dark(${black["--black-a6"]}, ${black["--black-a8"]})`, + "--color-panel-solid": `light-dark(white, ${gray["--gray-2"]})`, + "--color-panel-translucent": `light-dark(rgba(255, 255, 255, 0.7), ${gray["--gray-a2"]})`, + "--color-surface": + "light-dark(rgba(255, 255, 255, 0.85), rgba(0, 0, 0, 0.25))", + "--color-transparent": { + default: "rgb(0 0 0 / 0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0)", + }, + }, + "--color-panel-if-solid": `${panel["--panel-solid"]} var(--color-panel-solid)`, + "--color-panel": + "var(--color-panel-if-solid, var(--color-panel-translucent))", +}); diff --git a/packages/reflex-components-ui/js/src/tokens/cursor.stylex.js b/packages/reflex-components-ui/js/src/tokens/cursor.stylex.js new file mode 100644 index 00000000000..671007ded78 --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/cursor.stylex.js @@ -0,0 +1,15 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const cursor = stylex.defineVars({ + "--cursor-button": "default", + "--cursor-checkbox": "default", + "--cursor-disabled": "not-allowed", + "--cursor-link": "pointer", + "--cursor-menu-item": "default", + "--cursor-radio": "default", + "--cursor-slider-thumb": "default", + "--cursor-slider-thumb-active": "default", + "--cursor-switch": "default", +}); diff --git a/packages/reflex-components-ui/js/src/tokens/focus.stylex.js b/packages/reflex-components-ui/js/src/tokens/focus.stylex.js new file mode 100644 index 00000000000..a3a92e3f495 --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/focus.stylex.js @@ -0,0 +1,32 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "./accent.stylex.js"; + +export const focus = stylex.defineVars({ + "--focus-1": accent["--accent-1"], + "--focus-2": accent["--accent-2"], + "--focus-3": accent["--accent-3"], + "--focus-4": accent["--accent-4"], + "--focus-5": accent["--accent-5"], + "--focus-6": accent["--accent-6"], + "--focus-7": accent["--accent-7"], + "--focus-8": accent["--accent-8"], + "--focus-9": accent["--accent-9"], + "--focus-10": accent["--accent-10"], + "--focus-11": accent["--accent-11"], + "--focus-12": accent["--accent-12"], + "--focus-a1": accent["--accent-a1"], + "--focus-a2": accent["--accent-a2"], + "--focus-a3": accent["--accent-a3"], + "--focus-a4": accent["--accent-a4"], + "--focus-a5": accent["--accent-a5"], + "--focus-a6": accent["--accent-a6"], + "--focus-a7": accent["--accent-a7"], + "--focus-a8": accent["--accent-a8"], + "--focus-a9": accent["--accent-a9"], + "--focus-a10": accent["--accent-a10"], + "--focus-a11": accent["--accent-a11"], + "--focus-a12": accent["--accent-a12"], +}); diff --git a/packages/reflex-components-ui/js/src/tokens/gray.stylex.js b/packages/reflex-components-ui/js/src/tokens/gray.stylex.js new file mode 100644 index 00000000000..f0222cf3049 --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/gray.stylex.js @@ -0,0 +1,34 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const gray = stylex.defineVars({ + "--gray-1": "initial", + "--gray-2": "initial", + "--gray-3": "initial", + "--gray-4": "initial", + "--gray-5": "initial", + "--gray-6": "initial", + "--gray-7": "initial", + "--gray-8": "initial", + "--gray-9": "initial", + "--gray-10": "initial", + "--gray-11": "initial", + "--gray-12": "initial", + "--gray-a1": "initial", + "--gray-a2": "initial", + "--gray-a3": "initial", + "--gray-a4": "initial", + "--gray-a5": "initial", + "--gray-a6": "initial", + "--gray-a7": "initial", + "--gray-a8": "initial", + "--gray-a9": "initial", + "--gray-a10": "initial", + "--gray-a11": "initial", + "--gray-a12": "initial", + "--gray-surface": "initial", + "--gray-indicator": "initial", + "--gray-track": "initial", + "--gray-contrast": "initial", +}); diff --git a/packages/reflex-components-ui/js/src/tokens/panel.stylex.js b/packages/reflex-components-ui/js/src/tokens/panel.stylex.js new file mode 100644 index 00000000000..62945160ebf --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/panel.stylex.js @@ -0,0 +1,8 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const panel = stylex.defineVars({ + "--backdrop-filter-panel": "blur(64px)", + "--panel-solid": "initial", +}); diff --git a/packages/reflex-components-ui/js/src/tokens/radius.stylex.js b/packages/reflex-components-ui/js/src/tokens/radius.stylex.js new file mode 100644 index 00000000000..aa3ffc63083 --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/radius.stylex.js @@ -0,0 +1,20 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "./scaling.stylex.js"; + +export const radiusFactor = stylex.defineVars({ + "--radius-factor": "1", + "--radius-full": "0px", + "--radius-thumb": "9999px", +}); + +export const radius = stylex.defineVars({ + "--radius-1": `calc(3px * ${scaling["--scaling"]} * var(--radius-factor))`, + "--radius-2": `calc(4px * ${scaling["--scaling"]} * var(--radius-factor))`, + "--radius-3": `calc(6px * ${scaling["--scaling"]} * var(--radius-factor))`, + "--radius-4": `calc(8px * ${scaling["--scaling"]} * var(--radius-factor))`, + "--radius-5": `calc(12px * ${scaling["--scaling"]} * var(--radius-factor))`, + "--radius-6": `calc(16px * ${scaling["--scaling"]} * var(--radius-factor))`, +}); diff --git a/packages/reflex-components-ui/js/src/tokens/scaling.stylex.js b/packages/reflex-components-ui/js/src/tokens/scaling.stylex.js new file mode 100644 index 00000000000..12a4d259073 --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/scaling.stylex.js @@ -0,0 +1,7 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const scaling = stylex.defineVars({ + "--scaling": "1", +}); diff --git a/packages/reflex-components-ui/js/src/tokens/shadow.stylex.js b/packages/reflex-components-ui/js/src/tokens/shadow.stylex.js new file mode 100644 index 00000000000..0a533f5ab7a --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/shadow.stylex.js @@ -0,0 +1,15 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { black } from "../colors/black.stylex.js"; +import { gray } from "./gray.stylex.js"; + +export const shadow = stylex.defineVars({ + "--shadow-1": `inset 0 -1px 1px 0 light-dark(transparent, ${gray["--gray-a3"]}), inset 0 0 0 1px light-dark(${gray["--gray-a5"]}, ${gray["--gray-a3"]}), inset 0 1.5px 2px 0 light-dark(${gray["--gray-a2"]}, transparent), inset 0 1.5px 2px 0 light-dark(${black["--black-a2"]}, transparent), inset 0 3px 4px 0 light-dark(transparent, ${black["--black-a5"]}), inset 0 0 0 1px light-dark(transparent, ${gray["--gray-a4"]})`, + "--shadow-2": `0 0 0 1px light-dark(color-mix(in oklab, ${gray["--gray-a3"]}, ${gray["--gray-3"]} 25%), color-mix(in oklab, ${gray["--gray-a6"]}, ${gray["--gray-6"]} 25%)), 0 0 0 0.5px light-dark(${black["--black-a1"]}, ${black["--black-a3"]}), 0 1px 1px 0 light-dark(${gray["--gray-a2"]}, ${black["--black-a6"]}), 0 2px 1px -1px light-dark(${black["--black-a1"]}, ${black["--black-a6"]}), 0 1px 3px 0 light-dark(${black["--black-a1"]}, ${black["--black-a5"]})`, + "--shadow-3": `0 0 0 1px light-dark(color-mix(in oklab, ${gray["--gray-a3"]}, ${gray["--gray-3"]} 25%), color-mix(in oklab, ${gray["--gray-a6"]}, ${gray["--gray-6"]} 25%)), 0 2px 3px -2px light-dark(${gray["--gray-a3"]}, ${black["--black-a3"]}), 0 3px 12px -4px light-dark(${black["--black-a2"]}, transparent), 0 4px 16px -8px light-dark(${black["--black-a2"]}, transparent), 0 3px 8px -2px light-dark(transparent, ${black["--black-a6"]}), 0 4px 12px -4px light-dark(transparent, ${black["--black-a7"]})`, + "--shadow-4": `0 0 0 1px light-dark(color-mix(in oklab, ${gray["--gray-a3"]}, ${gray["--gray-3"]} 25%), color-mix(in oklab, ${gray["--gray-a6"]}, ${gray["--gray-6"]} 25%)), 0 8px 40px light-dark(${black["--black-a1"]}, ${black["--black-a3"]}), 0 12px 32px -16px light-dark(${gray["--gray-a3"]}, ${black["--black-a5"]})`, + "--shadow-5": `0 0 0 1px light-dark(color-mix(in oklab, ${gray["--gray-a3"]}, ${gray["--gray-3"]} 25%), color-mix(in oklab, ${gray["--gray-a6"]}, ${gray["--gray-6"]} 25%)), 0 12px 60px light-dark(${black["--black-a3"]}, ${black["--black-a5"]}), 0 12px 32px -16px light-dark(${gray["--gray-a5"]}, ${black["--black-a7"]})`, + "--shadow-6": `0 0 0 1px light-dark(color-mix(in oklab, ${gray["--gray-a3"]}, ${gray["--gray-3"]} 25%), color-mix(in oklab, ${gray["--gray-a6"]}, ${gray["--gray-6"]} 25%)), 0 12px 60px light-dark(${black["--black-a3"]}, ${black["--black-a4"]}), 0 16px 64px light-dark(${gray["--gray-a2"]}, ${black["--black-a6"]}), 0 16px 36px -20px light-dark(${gray["--gray-a7"]}, ${black["--black-a11"]})`, +}); diff --git a/packages/reflex-components-ui/js/src/tokens/space.stylex.js b/packages/reflex-components-ui/js/src/tokens/space.stylex.js new file mode 100644 index 00000000000..5ba6c7f203f --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/space.stylex.js @@ -0,0 +1,17 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "./scaling.stylex.js"; + +export const space = stylex.defineVars({ + "--space-1": `calc(4px * ${scaling["--scaling"]})`, + "--space-2": `calc(8px * ${scaling["--scaling"]})`, + "--space-3": `calc(12px * ${scaling["--scaling"]})`, + "--space-4": `calc(16px * ${scaling["--scaling"]})`, + "--space-5": `calc(24px * ${scaling["--scaling"]})`, + "--space-6": `calc(32px * ${scaling["--scaling"]})`, + "--space-7": `calc(40px * ${scaling["--scaling"]})`, + "--space-8": `calc(48px * ${scaling["--scaling"]})`, + "--space-9": `calc(64px * ${scaling["--scaling"]})`, +}); diff --git a/packages/reflex-components-ui/js/src/tokens/typography.stylex.js b/packages/reflex-components-ui/js/src/tokens/typography.stylex.js new file mode 100644 index 00000000000..cf6b80720cd --- /dev/null +++ b/packages/reflex-components-ui/js/src/tokens/typography.stylex.js @@ -0,0 +1,92 @@ +// Generated by scripts/generate.js from @radix-ui/themes 3.3.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "./scaling.stylex.js"; + +export const typography = stylex.defineVars({ + "--font-size-1": `calc(12px * ${scaling["--scaling"]})`, + "--font-size-2": `calc(14px * ${scaling["--scaling"]})`, + "--font-size-3": `calc(16px * ${scaling["--scaling"]})`, + "--font-size-4": `calc(18px * ${scaling["--scaling"]})`, + "--font-size-5": `calc(20px * ${scaling["--scaling"]})`, + "--font-size-6": `calc(24px * ${scaling["--scaling"]})`, + "--font-size-7": `calc(28px * ${scaling["--scaling"]})`, + "--font-size-8": `calc(35px * ${scaling["--scaling"]})`, + "--font-size-9": `calc(60px * ${scaling["--scaling"]})`, + "--font-weight-light": "300", + "--font-weight-regular": "400", + "--font-weight-medium": "500", + "--font-weight-bold": "700", + "--line-height-1": `calc(16px * ${scaling["--scaling"]})`, + "--line-height-2": `calc(20px * ${scaling["--scaling"]})`, + "--line-height-3": `calc(24px * ${scaling["--scaling"]})`, + "--line-height-4": `calc(26px * ${scaling["--scaling"]})`, + "--line-height-5": `calc(28px * ${scaling["--scaling"]})`, + "--line-height-6": `calc(30px * ${scaling["--scaling"]})`, + "--line-height-7": `calc(36px * ${scaling["--scaling"]})`, + "--line-height-8": `calc(40px * ${scaling["--scaling"]})`, + "--line-height-9": `calc(60px * ${scaling["--scaling"]})`, + "--letter-spacing-1": "0.0025em", + "--letter-spacing-2": "0em", + "--letter-spacing-3": "0em", + "--letter-spacing-4": "-0.0025em", + "--letter-spacing-5": "-0.005em", + "--letter-spacing-6": "-0.00625em", + "--letter-spacing-7": "-0.0075em", + "--letter-spacing-8": "-0.01em", + "--letter-spacing-9": "-0.025em", + "--default-font-family": + "-apple-system, BlinkMacSystemFont, 'Segoe UI (Custom)', Roboto, 'Helvetica Neue', 'Open Sans (Custom)', system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji'", + "--default-font-size": "var(--font-size-3)", + "--default-font-style": "normal", + "--default-font-weight": "var(--font-weight-regular)", + "--default-line-height": "1.5", + "--default-letter-spacing": "0em", + "--default-leading-trim-start": "0.42em", + "--default-leading-trim-end": "0.36em", + "--heading-font-family": "var(--default-font-family)", + "--heading-font-size-adjust": "1", + "--heading-font-style": "normal", + "--heading-leading-trim-start": "var(--default-leading-trim-start)", + "--heading-leading-trim-end": "var(--default-leading-trim-end)", + "--heading-letter-spacing": "0em", + "--heading-line-height-1": `calc(16px * ${scaling["--scaling"]})`, + "--heading-line-height-2": `calc(18px * ${scaling["--scaling"]})`, + "--heading-line-height-3": `calc(22px * ${scaling["--scaling"]})`, + "--heading-line-height-4": `calc(24px * ${scaling["--scaling"]})`, + "--heading-line-height-5": `calc(26px * ${scaling["--scaling"]})`, + "--heading-line-height-6": `calc(30px * ${scaling["--scaling"]})`, + "--heading-line-height-7": `calc(36px * ${scaling["--scaling"]})`, + "--heading-line-height-8": `calc(40px * ${scaling["--scaling"]})`, + "--heading-line-height-9": `calc(60px * ${scaling["--scaling"]})`, + "--code-font-family": + "'Menlo', 'Consolas (Custom)', 'Bitstream Vera Sans Mono', monospace, 'Apple Color Emoji', 'Segoe UI Emoji'", + "--code-font-size-adjust": "0.95", + "--code-font-style": "normal", + "--code-font-weight": "inherit", + "--code-letter-spacing": "-0.007em", + "--code-padding-top": "0.1em", + "--code-padding-bottom": "0.1em", + "--code-padding-left": "0.25em", + "--code-padding-right": "0.25em", + "--strong-font-family": "var(--default-font-family)", + "--strong-font-size-adjust": "1", + "--strong-font-style": "inherit", + "--strong-font-weight": "var(--font-weight-bold)", + "--strong-letter-spacing": "0em", + "--em-font-family": "'Times New Roman', 'Times', serif", + "--em-font-size-adjust": "1.18", + "--em-font-style": "italic", + "--em-font-weight": "inherit", + "--em-letter-spacing": "-0.025em", + "--quote-font-family": "'Times New Roman', 'Times', serif", + "--quote-font-size-adjust": "1.18", + "--quote-font-style": "italic", + "--quote-font-weight": "inherit", + "--quote-letter-spacing": "-0.025em", + "--tab-active-letter-spacing": "-0.01em", + "--tab-active-word-spacing": "0em", + "--tab-inactive-letter-spacing": "0em", + "--tab-inactive-word-spacing": "0em", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/black.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/black.stylex.js new file mode 100644 index 00000000000..b2372a3d471 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/black.stylex.js @@ -0,0 +1,7 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const black = stylex.defineVars({ + "--black-a9": "rgba(0, 0, 0, 0.7)", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/red.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/red.stylex.js new file mode 100644 index 00000000000..5e2fe56f5c1 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/red.stylex.js @@ -0,0 +1,19 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const red = stylex.defineVars({ + "--red-9": { + default: "#e5484d", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.83 0.329 0.324), #e5484d)", + }, + }, + "--red-a9": "light-dark(#db0007b7, #ff5d61b0)", + "--red-contrast": "white", + "--red-track": + "light-dark(var(--red-9), color-mix(in oklab, var(--red-a9), var(--red-9) 65%))", + "--red-surface": "light-dark(#fff7f7cc, #2f151780)", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/slate.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/slate.stylex.js new file mode 100644 index 00000000000..4f72d6ae326 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/colors/slate.stylex.js @@ -0,0 +1,16 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const slate = stylex.defineVars({ + "--slate-9": { + default: "light-dark(#8b8d98, #696e77)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.547 0.553 0.592), color(display-p3 0.415 0.431 0.463))", + }, + }, + "--slate-a9": "light-dark(#00051d74, #d9edff5d)", + "--slate-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/gray.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/gray.js new file mode 100644 index 00000000000..941a70f150a --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/gray.js @@ -0,0 +1,12 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { gray } from "../../tokens/gray.stylex.js"; + +export const accentGray = stylex.createTheme(accent, { + "--accent-9": gray["--gray-9"], + "--accent-a9": gray["--gray-a9"], + "--accent-contrast": gray["--gray-contrast"], +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/red.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/red.js new file mode 100644 index 00000000000..c12e2ac87ac --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/accent/red.js @@ -0,0 +1,12 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "../../tokens/accent.stylex.js"; +import { red } from "../../colors/red.stylex.js"; + +export const accentRed = stylex.createTheme(accent, { + "--accent-9": red["--red-9"], + "--accent-a9": red["--red-a9"], + "--accent-contrast": red["--red-contrast"], +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/focus.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/focus.js new file mode 100644 index 00000000000..267ffc23df4 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/focus.js @@ -0,0 +1,7 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { focus } from "../tokens/focus.stylex.js"; + +export const focusScope = stylex.createTheme(focus, {}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/gray.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/gray.js new file mode 100644 index 00000000000..e6a689f9b0f --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/gray.js @@ -0,0 +1,22 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; + +// StyleX leaves a null level out, which the type of a string token does +// not say. +const NONE = /** @type {string} */ (/** @type {unknown} */ (null)); + +export const grayGray = stylex.createTheme(gray, { + "--gray-9": { + default: "light-dark(#8d8d8d, #6e6e6e)", + "@supports (color: color(display-p3 1 1 1))": { + default: NONE, + "@media (color-gamut: p3)": + "light-dark(color(display-p3 0.553 0.553 0.553), color(display-p3 0.431 0.431 0.431))", + }, + }, + "--gray-a9": "light-dark(#00000072, #ffffff69)", + "--gray-contrast": "white", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/slate.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/slate.js new file mode 100644 index 00000000000..f2820797ec9 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/gray/slate.js @@ -0,0 +1,12 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "../../tokens/gray.stylex.js"; +import { slate } from "../../colors/slate.stylex.js"; + +export const graySlate = stylex.createTheme(gray, { + "--gray-9": slate["--slate-9"], + "--gray-a9": slate["--slate-a9"], + "--gray-contrast": slate["--slate-contrast"], +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/panel.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/panel.js new file mode 100644 index 00000000000..79e7076c5eb --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/panel.js @@ -0,0 +1,15 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { panel } from "../tokens/panel.stylex.js"; + +export const panelSolid = stylex.createTheme(panel, { + "--backdrop-filter-panel": "none", + "--panel-solid": " ", +}); + +export const panelTranslucent = stylex.createTheme(panel, { + "--backdrop-filter-panel": "blur(64px)", + "--panel-solid": "initial", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/radius.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/radius.js new file mode 100644 index 00000000000..3975e96715e --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/radius.js @@ -0,0 +1,15 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { radiusFactor } from "../tokens/radius.stylex.js"; + +export const radiusFull = stylex.createTheme(radiusFactor, { + "--radius-factor": "1.5", + "--radius-full": "9999px", +}); + +export const radiusMedium = stylex.createTheme(radiusFactor, { + "--radius-factor": "1", + "--radius-full": "0px", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scaling.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scaling.js new file mode 100644 index 00000000000..b7a2903b5d4 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scaling.js @@ -0,0 +1,13 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "../tokens/scaling.stylex.js"; + +export const scaling100 = stylex.createTheme(scaling, { + "--scaling": "1", +}); + +export const scaling90 = stylex.createTheme(scaling, { + "--scaling": "0.9", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scope.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scope.js new file mode 100644 index 00000000000..fc87f649d1a --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/scope.js @@ -0,0 +1,19 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { color } from "../tokens/color.stylex.js"; +import { radius } from "../tokens/radius.stylex.js"; +import { shadow } from "../tokens/shadow.stylex.js"; +import { space } from "../tokens/space.stylex.js"; +import { typography } from "../tokens/typography.stylex.js"; + +export const spaceScope = stylex.createTheme(space, {}); + +export const radiusScope = stylex.createTheme(radius, {}); + +export const typographyScope = stylex.createTheme(typography, {}); + +export const shadowScope = stylex.createTheme(shadow, {}); + +export const colorScope = stylex.createTheme(color, {}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/theme.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/theme.js new file mode 100644 index 00000000000..d84a0fa4751 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/themes/theme.js @@ -0,0 +1,27 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { color } from "../tokens/color.stylex.js"; +import { gray } from "../tokens/gray.stylex.js"; +import { typography } from "../tokens/typography.stylex.js"; + +export const theme = stylex.create({ + light: { + colorScheme: "light", + }, + dark: { + colorScheme: "dark", + }, + background: { + backgroundColor: color["--color-background"], + }, + root: { + overflowWrap: "break-word", + fontFamily: typography["--default-font-family"], + fontSize: typography["--default-font-size"], + textSizeAdjust: "none", + WebkitFontSmoothing: "antialiased", + color: gray["--gray-9"], + }, +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/accent.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/accent.stylex.js new file mode 100644 index 00000000000..619d6c92737 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/accent.stylex.js @@ -0,0 +1,9 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const accent = stylex.defineVars({ + "--accent-9": "initial", + "--accent-a9": "initial", + "--accent-contrast": "initial", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/color.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/color.stylex.js new file mode 100644 index 00000000000..a7ad4d784cc --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/color.stylex.js @@ -0,0 +1,22 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { gray } from "./gray.stylex.js"; +import { panel } from "./panel.stylex.js"; + +export const color = stylex.defineVars({ + "--color-background": `light-dark(white, ${gray["--gray-9"]})`, + "--color-panel-solid": `light-dark(white, ${gray["--gray-9"]})`, + "--color-panel-translucent": `light-dark(rgba(255, 255, 255, 0.7), ${gray["--gray-a9"]})`, + "--color-transparent": { + default: "rgb(0 0 0 / 0)", + "@supports (color: color(display-p3 1 1 1))": { + default: null, + "@media (color-gamut: p3)": "color(display-p3 0 0 0 / 0)", + }, + }, + "--color-panel-if-solid": `${panel["--panel-solid"]} var(--color-panel-solid)`, + "--color-panel": + "var(--color-panel-if-solid, var(--color-panel-translucent))", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/cursor.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/cursor.stylex.js new file mode 100644 index 00000000000..bb7c709289c --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/cursor.stylex.js @@ -0,0 +1,7 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const cursor = stylex.defineVars({ + "--cursor-button": "default", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/focus.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/focus.stylex.js new file mode 100644 index 00000000000..dd324aec674 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/focus.stylex.js @@ -0,0 +1,9 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { accent } from "./accent.stylex.js"; + +export const focus = stylex.defineVars({ + "--focus-9": accent["--accent-9"], +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/gray.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/gray.stylex.js new file mode 100644 index 00000000000..fce237af53f --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/gray.stylex.js @@ -0,0 +1,9 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const gray = stylex.defineVars({ + "--gray-9": "initial", + "--gray-a9": "initial", + "--gray-contrast": "initial", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/panel.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/panel.stylex.js new file mode 100644 index 00000000000..dba7800ad14 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/panel.stylex.js @@ -0,0 +1,8 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const panel = stylex.defineVars({ + "--backdrop-filter-panel": "blur(64px)", + "--panel-solid": "initial", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/radius.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/radius.stylex.js new file mode 100644 index 00000000000..9ba4889dad5 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/radius.stylex.js @@ -0,0 +1,14 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "./scaling.stylex.js"; + +export const radiusFactor = stylex.defineVars({ + "--radius-factor": "1", + "--radius-full": "0px", +}); + +export const radius = stylex.defineVars({ + "--radius-1": `calc(3px * ${scaling["--scaling"]} * var(--radius-factor))`, +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/scaling.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/scaling.stylex.js new file mode 100644 index 00000000000..dbde33599a3 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/scaling.stylex.js @@ -0,0 +1,7 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +export const scaling = stylex.defineVars({ + "--scaling": "1", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/shadow.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/shadow.stylex.js new file mode 100644 index 00000000000..25d2bfcdda9 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/shadow.stylex.js @@ -0,0 +1,11 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { black } from "../colors/black.stylex.js"; +import { gray } from "./gray.stylex.js"; + +export const shadow = stylex.defineVars({ + "--shadow-1": `inset 0 -1px 1px 0 light-dark(transparent, ${gray["--gray-a9"]}), inset 0 0 0 1px ${gray["--gray-a9"]}, inset 0 1.5px 2px 0 light-dark(${black["--black-a9"]}, transparent)`, + "--shadow-2": `0 0 0 1px color-mix(in oklab, ${gray["--gray-a9"]}, ${gray["--gray-9"]} 25%), 0 1px 3px 0 ${black["--black-a9"]}`, +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/space.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/space.stylex.js new file mode 100644 index 00000000000..e5927e4e3a0 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/space.stylex.js @@ -0,0 +1,9 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "./scaling.stylex.js"; + +export const space = stylex.defineVars({ + "--space-1": `calc(4px * ${scaling["--scaling"]})`, +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/typography.stylex.js b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/typography.stylex.js new file mode 100644 index 00000000000..b7434979258 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/js/src/tokens/typography.stylex.js @@ -0,0 +1,13 @@ +// Generated by scripts/generate.js from @radix-ui/themes 0.0.0. Do not edit. + +import * as stylex from "@stylexjs/stylex"; + +import { scaling } from "./scaling.stylex.js"; + +export const typography = stylex.defineVars({ + "--font-size-3": `calc(16px * ${scaling["--scaling"]})`, + "--font-weight-regular": "400", + "--default-font-family": "-apple-system, 'Segoe UI (Custom)', sans-serif", + "--default-font-size": "var(--font-size-3)", + "--code-font-weight": "inherit", +}); diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/src/reflex_components_ui/_radix_tokens.py b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/src/reflex_components_ui/_radix_tokens.py new file mode 100644 index 00000000000..6467c5b795c --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/expected/src/reflex_components_ui/_radix_tokens.py @@ -0,0 +1,159 @@ +"""The StyleX modules generated from @radix-ui/themes, and what they define. + +Generated by js/scripts/generate.js. Do not edit. +""" + +RADIX_THEMES_VERSION: str = "0.0.0" + +VAR_GROUPS: dict[str, tuple[str, tuple[str, ...]]] = { + "black": ( + "colors/black.stylex.js", + ("--black-a9",), + ), + "red": ( + "colors/red.stylex.js", + ( + "--red-9", + "--red-a9", + "--red-contrast", + "--red-track", + "--red-surface", + ), + ), + "slate": ( + "colors/slate.stylex.js", + ( + "--slate-9", + "--slate-a9", + "--slate-contrast", + ), + ), + "space": ( + "tokens/space.stylex.js", + ("--space-1",), + ), + "scaling": ( + "tokens/scaling.stylex.js", + ("--scaling",), + ), + "radiusFactor": ( + "tokens/radius.stylex.js", + ("--radius-factor", "--radius-full"), + ), + "radius": ( + "tokens/radius.stylex.js", + ("--radius-1",), + ), + "shadow": ( + "tokens/shadow.stylex.js", + ("--shadow-1", "--shadow-2"), + ), + "cursor": ( + "tokens/cursor.stylex.js", + ("--cursor-button",), + ), + "panel": ( + "tokens/panel.stylex.js", + ("--backdrop-filter-panel", "--panel-solid"), + ), + "color": ( + "tokens/color.stylex.js", + ( + "--color-background", + "--color-panel-solid", + "--color-panel-translucent", + "--color-transparent", + "--color-panel-if-solid", + "--color-panel", + ), + ), + "accent": ( + "tokens/accent.stylex.js", + ( + "--accent-9", + "--accent-a9", + "--accent-contrast", + ), + ), + "focus": ( + "tokens/focus.stylex.js", + ("--focus-9",), + ), + "gray": ( + "tokens/gray.stylex.js", + ( + "--gray-9", + "--gray-a9", + "--gray-contrast", + ), + ), + "typography": ( + "tokens/typography.stylex.js", + ( + "--font-size-3", + "--font-weight-regular", + "--default-font-family", + "--default-font-size", + "--code-font-weight", + ), + ), +} + +ACCENT_THEMES: dict[str, tuple[str, str]] = { + "gray": ("themes/accent/gray.js", "accentGray"), + "red": ("themes/accent/red.js", "accentRed"), +} + +GRAY_THEMES: dict[str, tuple[str, str]] = { + "gray": ("themes/gray/gray.js", "grayGray"), + "slate": ("themes/gray/slate.js", "graySlate"), +} + +RADIUS_THEMES: dict[str, tuple[str, str]] = { + "full": ("themes/radius.js", "radiusFull"), + "medium": ("themes/radius.js", "radiusMedium"), +} + +SCALING_THEMES: dict[str, tuple[str, str]] = { + "100%": ("themes/scaling.js", "scaling100"), + "90%": ("themes/scaling.js", "scaling90"), +} + +PANEL_BACKGROUND_THEMES: dict[str, tuple[str, str]] = { + "solid": ("themes/panel.js", "panelSolid"), + "translucent": ("themes/panel.js", "panelTranslucent"), +} + +SCOPE_THEMES: tuple[tuple[str, str], ...] = ( + ("themes/scope.js", "spaceScope"), + ("themes/scope.js", "radiusScope"), + ("themes/scope.js", "typographyScope"), + ("themes/scope.js", "shadowScope"), + ("themes/scope.js", "colorScope"), +) + +FOCUS_THEME: tuple[str, str] = ("themes/focus.js", "focusScope") + +THEME_STYLES: tuple[str, str, tuple[str, ...]] = ( + "themes/theme.js", + "theme", + ( + "light", + "dark", + "background", + "root", + ), +) + +MATCHING_GRAY: dict[str, str] = { + "gray": "gray", + "red": "slate", +} + +DEFAULTS: dict[str, str] = { + "accent_color": "red", + "gray_color": "auto", + "radius": "medium", + "scaling": "100%", + "panel_background": "translucent", +} diff --git a/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/tokens.css b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/tokens.css new file mode 100644 index 00000000000..98610a49037 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/fixtures/radix-tokens/tokens.css @@ -0,0 +1,196 @@ +/* The shapes the token stylesheet of @radix-ui/themes is made of, with two + steps of each scale and a few tokens of each kind. */ +:root, .light, .light-theme { + --gray-9: #8d8d8d; + --gray-a9: #00000072; + --slate-9: #8b8d98; + --slate-a9: #00051d74; + --red-9: #e5484d; + --red-a9: #db0007b7; +} + +@supports (color: color(display-p3 1 1 1)) { + @media (color-gamut: p3) { + :root, .light, .light-theme { + --gray-9: color(display-p3 0.553 0.553 0.553); + --slate-9: color(display-p3 0.547 0.553 0.592); + --red-9: color(display-p3 0.83 0.329 0.324); + } + } +} + +.dark, .dark-theme { + --gray-9: #6e6e6e; + --gray-a9: #ffffff69; + --slate-9: #696e77; + --slate-a9: #d9edff5d; + --red-9: #e5484d; + --red-a9: #ff5d61b0; +} + +@supports (color: color(display-p3 1 1 1)) { + @media (color-gamut: p3) { + .dark, .dark-theme { + --gray-9: color(display-p3 0.431 0.431 0.431); + --slate-9: color(display-p3 0.415 0.431 0.463); + } + } +} + +:root { + --black-a9: rgba(0, 0, 0, 0.7); + --red-contrast: white; + --slate-contrast: white; + --gray-contrast: white; +} + +:root, .light, .light-theme { + --red-track: var(--red-9); + --red-surface: #fff7f7cc; +} + +.dark, .dark-theme { + --red-track: var(--red-9); + --red-surface: #2f151780; +} + +@supports (color: color-mix(in oklab, white, black)) { + .dark, .dark-theme { + --red-track: color-mix(in oklab, var(--red-a9), var(--red-9) 65%); + } +} + +:where(.radix-themes) { + --color-background: white; + --color-panel-solid: white; + --color-panel-translucent: rgba(255, 255, 255, 0.7); + --color-transparent: rgb(0 0 0 / 0); + --shadow-1: + inset 0 0 0 1px var(--gray-a9), + inset 0 1.5px 2px 0 var(--black-a9); + --shadow-2: + 0 0 0 1px var(--gray-a9), + 0 1px 3px 0 var(--black-a9); +} + +:is(.dark, .dark-theme), +:is(.dark, .dark-theme) :where(.radix-themes:not(.light, .light-theme)) { + --color-background: var(--gray-9); + --color-panel-solid: var(--gray-9); + --color-panel-translucent: var(--gray-a9); + --shadow-1: + inset 0 -1px 1px 0 var(--gray-a9), + inset 0 0 0 1px var(--gray-a9); + --shadow-2: + 0 0 0 1px var(--gray-a9), + 0 1px 3px 0 var(--black-a9); +} + +@supports (color: color-mix(in oklab, white, black)) { + :where(.radix-themes) { + --shadow-2: + 0 0 0 1px color-mix(in oklab, var(--gray-a9), var(--gray-9) 25%), + 0 1px 3px 0 var(--black-a9); + } +} + +@supports (color: color(display-p3 1 1 1)) { + @media (color-gamut: p3) { + .radix-themes { + --color-transparent: color(display-p3 0 0 0 / 0); + } + } +} + +.radix-themes:where(.light, .light-theme), :root:where(:has(.radix-themes[data-is-root-theme='true']:where(.light, .light-theme))) { + color-scheme: light; +} + +.radix-themes:where(.dark, .dark-theme), :root:where(:has(.radix-themes[data-is-root-theme='true']:where(.dark, .dark-theme))) { + color-scheme: dark; +} + +.radix-themes, +[data-accent-color]:where(:not([data-accent-color=''], [data-accent-color='gray'])) { + --focus-9: var(--accent-9); +} + +.radix-themes ::selection { + background-color: var(--focus-9); +} + +.radix-themes:where([data-has-background='true']) { + background-color: var(--color-background); +} + +.radix-themes:where([data-panel-background='solid']) { + --color-panel: var(--color-panel-solid); + --backdrop-filter-panel: none; +} + +.radix-themes:where([data-panel-background='translucent']) { + --color-panel: var(--color-panel-translucent); + --backdrop-filter-panel: blur(64px); +} + +[data-accent-color='gray'] { + --accent-9: var(--gray-9); + --accent-a9: var(--gray-a9); + --accent-contrast: var(--gray-contrast); +} + +[data-accent-color='red'] { + --accent-9: var(--red-9); + --accent-a9: var(--red-a9); + --accent-contrast: var(--red-contrast); +} + +.radix-themes:where([data-gray-color='slate']) { + --gray-9: var(--slate-9); + --gray-a9: var(--slate-a9); + --gray-contrast: var(--slate-contrast); +} + +.radix-themes { + --cursor-button: default; + --space-1: calc(4px * var(--scaling)); + --font-size-3: calc(16px * var(--scaling)); + --font-weight-regular: 400; + --default-font-family: -apple-system, 'Segoe UI (Custom)', sans-serif; + --default-font-size: var(--font-size-3); + --code-font-weight: inherit; + overflow-wrap: break-word; + font-family: var(--default-font-family); + font-size: var(--default-font-size); + -webkit-text-size-adjust: none; + text-size-adjust: none; + -webkit-font-smoothing: antialiased; + color: var(--gray-9); +} + +.radix-themes:where([data-scaling='90%']) { + --scaling: 0.9; +} + +.radix-themes:where([data-scaling='100%']) { + --scaling: 1; +} + +[data-radius] { + --radius-1: calc(3px * var(--scaling) * var(--radius-factor)); +} + +[data-radius='medium'] { + --radius-factor: 1; + --radius-full: 0px; +} + +[data-radius='full'] { + --radius-factor: 1.5; + --radius-full: 9999px; +} + +@font-face { + font-family: 'Segoe UI (Custom)'; + src: local('Segoe UI'); +} diff --git a/packages/reflex-components-ui/js/tests/harness/base.css b/packages/reflex-components-ui/js/tests/harness/base.css new file mode 100644 index 00000000000..8afe7759719 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/base.css @@ -0,0 +1,9 @@ +/* What the stylesheet every page loads has to say for the themes to work. The + stylesheet itself belongs to the app's build, not to these modules. */ +html, +html.light { + color-scheme: light; +} +html.dark { + color-scheme: dark; +} diff --git a/packages/reflex-components-ui/js/tests/harness/browser.js b/packages/reflex-components-ui/js/tests/harness/browser.js new file mode 100644 index 00000000000..b0b1d7db98f --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/browser.js @@ -0,0 +1,184 @@ +// Opens the two pages of the sweep in headless Chromium and compares what they +// read. + +import { readFileSync } from "node:fs"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { chromium } from "playwright"; + +import { buildHarness } from "./build.js"; +import { labels } from "./probe.js"; + +/** @typedef {import("./page.js").Config} Config */ +/** @typedef {import("./page.js").Harness} Harness */ +/** @typedef {"srgb" | "p3"} Gamut */ + +/** + * A value the two pages disagree on, or that one of them could not read. + * + * @typedef {object} Difference + * @property {Config} config The page that was shown. + * @property {Gamut} gamut The gamut of the screen. + * @property {string} label The custom property, or the property of the theme + * element. + * @property {string} ours What the StyleX modules give. + * @property {string} radix What @radix-ui/themes gives. + */ + +const ORIGIN = "http://harness.test"; +const TYPES = { html: "text/html", js: "text/javascript", css: "text/css" }; +const CHUNK = 250; + +/** + * Every custom property the token stylesheet of @radix-ui/themes defines. + * + * @returns {string[]} Their names, in the order they first appear. + */ +export function radixCustomProperties() { + const css = readFileSync( + createRequire(import.meta.url).resolve("@radix-ui/themes/tokens.css"), + "utf8", + ); + return [ + ...new Set( + Array.from(css.matchAll(/^\s*(--[\w-]+):/gm), ([, name]) => name), + ), + ]; +} + +/** + * Build the two pages and open them. + * + * @returns {Promise<{ + * names: string[], + * ours: import("playwright").Page, + * radix: import("playwright").Page, + * setGamut: (gamut: Gamut) => Promise, + * read: (page: import("playwright").Page, config: Config) => Promise>, + * compare: (configs: Config[], gamut: Gamut) => Promise<{ differences: Difference[], distinct: number }>, + * close: () => Promise, + * }>} The pages, and what drives them. + */ +export async function openHarness() { + const dist = await mkdtemp(join(tmpdir(), "reflex-ui-harness-")); + await buildHarness(["ours.html", "radix.html"], dist); + const browser = await chromium.launch(); + const context = await browser.newContext(); + await context.route(`${ORIGIN}/**`, async (route) => { + const path = new URL(route.request().url()).pathname; + const extension = /** @type {keyof typeof TYPES} */ (path.split(".").pop()); + await route.fulfill({ + body: await readFile(join(dist, path)), + contentType: TYPES[extension], + }); + }); + const names = radixCustomProperties(); + const all = labels(names); + const pages = await Promise.all( + ["ours", "radix"].map(async (name) => { + const page = await context.newPage(); + page.on("pageerror", (error) => { + throw error; + }); + await page.goto(`${ORIGIN}/${name}.html`); + await page.waitForFunction(() => "harness" in window); + await page.evaluate( + (properties) => + /** @type {{ harness: Harness }} */ ( + /** @type {unknown} */ (window) + ).harness.setup(properties), + names, + ); + return { page, session: await context.newCDPSession(page) }; + }), + ); + const [ours, radix] = pages.map(({ page }) => page); + + /** @type {(gamut: Gamut) => Promise} */ + const setGamut = async (gamut) => { + for (const { session } of pages) { + await session.send("Emulation.setEmulatedMedia", { + features: [{ name: "color-gamut", value: gamut }], + }); + } + }; + + /** + * Show pages in one of the two documents. + * + * @template {"show" | "sweep"} Method + * @param {import("playwright").Page} page The document. + * @param {Method} method How much to bring back. + * @param {Parameters[0]} argument What to show. + * @returns {Promise>>} What was read. + */ + const run = (page, method, argument) => + page.evaluate( + ([name, value]) => + /** @type {any} */ (window).harness[/** @type {string} */ (name)]( + value, + ), + [method, argument], + ); + + return { + names, + ours, + radix, + setGamut, + read: async (page, config) => { + const values = await run(page, "show", config); + return Object.fromEntries( + all.map((label, position) => [label, values[position]]), + ); + }, + compare: async (configs, gamut) => { + await setGamut(gamut); + /** @type {Difference[]} */ + const differences = []; + const hashes = new Set(); + for (let start = 0; start < configs.length; start += CHUNK) { + const chunk = configs.slice(start, start + CHUNK); + const [mine, theirs] = await Promise.all([ + run(ours, "sweep", chunk), + run(radix, "sweep", chunk), + ]); + for (const [index, config] of chunk.entries()) { + hashes.add(theirs[index].hash); + if ( + mine[index].hash === theirs[index].hash && + mine[index].invalid + theirs[index].invalid === 0 + ) { + continue; + } + const [mineValues, theirValues] = await Promise.all([ + run(ours, "show", config), + run(radix, "show", config), + ]); + for (const [position, label] of all.entries()) { + if ( + mineValues[position] !== theirValues[position] || + theirValues[position].startsWith("INVALID") + ) { + differences.push({ + config, + gamut, + label, + ours: mineValues[position], + radix: theirValues[position], + }); + } + } + } + } + return { differences, distinct: hashes.size }; + }, + close: async () => { + await browser.close(); + await rm(dist, { recursive: true }); + }, + }; +} diff --git a/packages/reflex-components-ui/js/tests/harness/build.js b/packages/reflex-components-ui/js/tests/harness/build.js new file mode 100644 index 00000000000..b89e8063c63 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/build.js @@ -0,0 +1,40 @@ +// Builds the pages the live tests load: plain Vite with the StyleX plugin, set +// up the way an app's build sets it up. + +import { fileURLToPath } from "node:url"; + +import stylex from "@stylexjs/unplugin"; +import { Features } from "lightningcss"; +import { build } from "vite"; + +const ROOT = fileURLToPath(new URL("./", import.meta.url)); + +// The options Reflex gives StyleX in an app. +export const STYLEX_OPTIONS = { + useCSSLayers: true, + styleResolution: /** @type {const} */ ("application-order"), + lightningcssOptions: { minify: true, exclude: Features.LightDark }, +}; + +/** + * Build entries of the harness. + * + * @param {string[]} entries The html or javascript files to build, relative to + * this directory. + * @param {string} outDir Where the build goes. + * @returns {Promise} + */ +export async function buildHarness(entries, outDir) { + await build({ + root: ROOT, + base: "./", + configFile: false, + logLevel: "error", + plugins: [stylex.vite(STYLEX_OPTIONS)], + build: { + outDir, + emptyOutDir: true, + rollupOptions: { input: entries.map((entry) => `${ROOT}${entry}`) }, + }, + }); +} diff --git a/packages/reflex-components-ui/js/tests/harness/configs.js b/packages/reflex-components-ui/js/tests/harness/configs.js new file mode 100644 index 00000000000..6353086efd2 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/configs.js @@ -0,0 +1,90 @@ +// The pages the sweep shows: every value of every prop of a Radix `Theme`. + +import { themePropDefs } from "@radix-ui/themes/props"; + +/** @typedef {import("./page.js").Config} Config */ + +const { accentColor, grayColor, radius, scaling, panelBackground } = + themePropDefs; + +export const APPEARANCES = /** @type {const} */ (["light", "dark"]); +export const ACCENTS = accentColor.values; +export const GRAYS = grayColor.values; +export const RADII = radius.values; +export const SCALINGS = scaling.values; +export const PANELS = panelBackground.values; + +/** @type {Config["theme"]} */ +export const DEFAULT_THEME = { + accentColor: accentColor.default, + grayColor: grayColor.default, + radius: radius.default, + scaling: scaling.default, + panelBackground: panelBackground.default, + hasBackground: true, +}; + +/** + * Every combination of the values of some props, the others at their default. + * + * @param {{ [Key in keyof Config["theme"]]?: readonly Config["theme"][Key][] }} props + * The values to combine. + * @returns {Config[]} One page for each combination, in each appearance. + */ +export function combinations(props) { + /** @type {Config[]} */ + let configs = APPEARANCES.map((appearance) => ({ + appearance, + theme: DEFAULT_THEME, + })); + for (const [prop, values] of Object.entries(props)) { + configs = configs.flatMap((config) => + values.map((value) => ({ + ...config, + theme: { ...config.theme, [prop]: value }, + })), + ); + } + return configs; +} + +/** + * The whole sweep: the product of every accent, gray, appearance, radius and + * scaling, then the panel and the background against every color. + * + * @returns {Config[]} 10,556 pages. + */ +export function fullSweep() { + return [ + ...combinations({ + accentColor: ACCENTS, + grayColor: GRAYS, + radius: RADII, + scaling: SCALINGS, + }), + ...combinations({ + accentColor: ACCENTS, + grayColor: GRAYS, + panelBackground: PANELS, + hasBackground: [true, false], + }), + ]; +} + +/** + * The part of the sweep `npm test` runs: every value of every prop, combined + * only with the props its tokens depend on. + * + * @returns {Config[]} 470 pages. + */ +export function fastSweep() { + return [ + ...combinations({ accentColor: ACCENTS, grayColor: GRAYS }), + ...combinations({ radius: RADII, scaling: SCALINGS }), + ...combinations({ + grayColor: GRAYS, + panelBackground: PANELS, + hasBackground: [true, false], + }), + ]; +} diff --git a/packages/reflex-components-ui/js/tests/harness/exceptions.js b/packages/reflex-components-ui/js/tests/harness/exceptions.js new file mode 100644 index 00000000000..9327aecc0ca --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/exceptions.js @@ -0,0 +1,36 @@ +// Where a value read under the StyleX modules is allowed to differ from the +// one read under @radix-ui/themes, and why. Both pages put what they read +// through `normalize` before the two are compared, so an entry here has to say +// why the difference cannot be seen. + +/** + * @typedef {object} Exception + * @property {RegExp} pattern The custom properties it applies to. + * @property {string} reason Why the difference is not one. + * @property {(value: string) => string} [normalize] Removes the difference + * from a computed value. + * @property {true} [undefined] Neither page defines the custom property, which + * is otherwise a failure of the sweep. + */ + +/** @type {Exception[]} */ +export const EXCEPTIONS = [ + { + pattern: + /^--(code-font-weight|strong-font-style|em-font-weight|quote-font-weight)$/, + reason: + "Radix declares these as `inherit`. That is a CSS-wide keyword on a custom property too: the property inherits from the parent, which has none, so it is not defined and `var()` of it is invalid. The modules declare the same and get the same.", + undefined: true, + }, + { + pattern: /^--shadow-\d$/, + reason: + "The light and dark shadows of Radix differ in geometry, and `light-dark()` only chooses between colors. A shadow here lists the layers of both appearances, and a layer the current appearance does not have is `transparent`: it paints nothing, but it is in the computed value.", + normalize: (value) => { + const layers = value + .split(/, (?![^(]*\))/) + .filter((layer) => !layer.startsWith("rgba(0, 0, 0, 0) ")); + return layers.join(", ") || "none"; + }, + }, +]; diff --git a/packages/reflex-components-ui/js/tests/harness/ours.html b/packages/reflex-components-ui/js/tests/harness/ours.html new file mode 100644 index 00000000000..daca2566ff8 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/ours.html @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/packages/reflex-components-ui/js/tests/harness/ours.js b/packages/reflex-components-ui/js/tests/harness/ours.js new file mode 100644 index 00000000000..6530796283c --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/ours.js @@ -0,0 +1,101 @@ +// The page under test: the StyleX modules of `src`, applied the way the python +// side applies them. Nothing here is specific to the root: a nested theme is +// the same classes on another element. + +import { getMatchingGrayColor } from "@radix-ui/themes/helpers"; +import * as stylex from "@stylexjs/stylex"; + +import { focusScope } from "../../src/themes/focus.js"; +import * as panels from "../../src/themes/panel.js"; +import * as radii from "../../src/themes/radius.js"; +import * as scalings from "../../src/themes/scaling.js"; +import * as scopes from "../../src/themes/scope.js"; +import { theme as styles } from "../../src/themes/theme.js"; +import { install } from "./page.js"; + +/** @typedef {import("@stylexjs/stylex").Theme} StyleXTheme */ + +/** + * The themes of a directory with one module for each. + * + * @param {Record>} modules What + * `import.meta.glob` found. + * @returns {Record} The theme of each module, by the name + * of its file. + */ +function byName(modules) { + return Object.fromEntries( + Object.entries(modules).map(([path, module]) => [ + path.replace(/^.*\/|\.js$/g, ""), + Object.values(module)[0], + ]), + ); +} + +// Every scale and every token is on the page, as the sweep reads them all. An +// app only has the ones something imports. +import.meta.glob("../../src/{colors,tokens}/*.stylex.js", { eager: true }); + +const accents = byName( + import.meta.glob("../../src/themes/accent/*.js", { eager: true }), +); +const grays = byName( + import.meta.glob("../../src/themes/gray/*.js", { eager: true }), +); + +/** + * The export of a module with a theme for each value of a prop. + * + * @param {Record} module The module. + * @param {string} prefix What its exports start with. + * @param {string | undefined} value The value of the prop. + * @returns {StyleXTheme | undefined} The theme, when the prop is set. + */ +function member(module, prefix, value) { + if (value === undefined) return undefined; + const word = value.replace(/\W/g, ""); + return module[prefix + word[0].toUpperCase() + word.slice(1)]; +} + +/** + * The classes of a theme element. + * + * @param {import("./page.js").ThemeProps} props What the theme sets. A prop + * that is left out is inherited. + * @returns {string} The class names. + */ +function themeClass(props) { + const { accentColor, hasBackground, appearance } = props; + const grayColor = + props.grayColor === "auto" + ? getMatchingGrayColor(/** @type {any} */ (accentColor)) + : props.grayColor; + return /** @type {string} */ ( + stylex.props( + Object.values(scopes), + focusScope, + accentColor ? accents[accentColor] : null, + grayColor ? grays[grayColor] : null, + member(radii, "radius", props.radius), + member(scalings, "scaling", props.scaling), + member(panels, "panel", props.panelBackground), + styles.root, + hasBackground && styles.background, + appearance && styles[appearance], + ).className + ); +} + +const root = document.body.appendChild(document.createElement("div")); +const inner = document.createElement("div"); + +install(({ theme, nested }) => { + root.className = themeClass(theme); + if (nested) { + inner.className = themeClass(nested); + root.append(inner); + return inner; + } + inner.remove(); + return root; +}); diff --git a/packages/reflex-components-ui/js/tests/harness/page.js b/packages/reflex-components-ui/js/tests/harness/page.js new file mode 100644 index 00000000000..e001b246f35 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/page.js @@ -0,0 +1,95 @@ +// What the two pages of the sweep share: the theme a page is asked to show, +// and reading it back. + +import { digest, mount, read } from "./probe.js"; + +/** + * The props of a Radix `Theme`, by their Radix names. + * + * @typedef {object} ThemeProps + * @property {string} [accentColor] + * @property {string} [grayColor] + * @property {string} [radius] + * @property {string} [scaling] + * @property {string} [panelBackground] + * @property {boolean} [hasBackground] + * @property {"light" | "dark"} [appearance] On a nested theme only: the page's + * own appearance is the class of `html`. + */ + +/** + * A page to show. + * + * @typedef {object} Config + * @property {"light" | "dark"} appearance The class of `html`. + * @property {Required>} theme The root theme. + * @property {ThemeProps} [nested] A theme inside it, around what is read. + * @property {boolean} [popover] Read from an open popover, which the browser + * renders in the top layer. + */ + +/** + * The functions the test drives a page with. + * + * @typedef {object} Harness + * @property {(names: string[]) => void} setup Says which custom properties to + * read. + * @property {(config: Config) => string[]} show Shows a page and reads it. + * @property {(configs: Config[]) => Promise[]>} sweep + * Shows each page and digests what it reads. + */ + +// React counts the renders it is asked for without a task ending between them, +// and stops at fifty. +const channel = new MessageChannel(); + +/** + * Let the current task end. + * + * @returns {Promise} Resolved in a task of its own. + */ +function nextTask() { + return new Promise((resolve) => { + channel.port1.onmessage = () => resolve(); + channel.port2.postMessage(null); + }); +} + +/** + * Give the page its harness. + * + * @param {(config: Config) => Element} render Shows the themes of a + * configuration and returns the innermost theme element. + */ +export function install(render) { + const container = document.createElement("div"); + /** @type {ReturnType} */ + let probes = []; + /** @type {Harness["show"]} */ + const show = (config) => { + if (container.matches(":popover-open")) container.hidePopover(); + container.toggleAttribute("popover", config.popover === true); + document.documentElement.className = config.appearance; + const theme = render(config); + theme.append(container); + if (config.popover) container.showPopover(); + return read(probes, theme); + }; + /** @type {Harness} */ + const harness = { + setup: (names) => { + container.replaceChildren(); + probes = mount(container, names); + }, + show, + sweep: async (configs) => { + const digests = []; + for (const config of configs) { + digests.push(digest(show(config))); + await nextTask(); + } + return digests; + }, + }; + Object.assign(window, { harness }); +} diff --git a/packages/reflex-components-ui/js/tests/harness/probe.js b/packages/reflex-components-ui/js/tests/harness/probe.js new file mode 100644 index 00000000000..c85ebe6d675 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/probe.js @@ -0,0 +1,114 @@ +// Runs in both pages of the sweep: reads what every custom property resolves to +// on an element, through a property of the type the value has. The computed +// value of the custom property itself would not do: here it is the +// `light-dark()` pair, in Radix the color of one appearance. + +import { EXCEPTIONS } from "./exceptions.js"; + +// The property each custom property is read through. The first match wins, and +// a custom property with no match fails the sweep. +const PROBES = /** @type {const} */ ([ + [/^--shadow-/, "box-shadow"], + [/^--cursor-/, "cursor"], + [/^--backdrop-filter-/, "backdrop-filter"], + [/-font-family$/, "font-family"], + [/-font-style$/, "font-style"], + [/^--font-weight-|-font-weight$/, "font-weight"], + [/^--default-line-height$/, "line-height"], + [/^--scaling$|^--radius-factor$|-font-size-adjust$/, "flex-grow"], + [ + /^--(space|radius|font-size|line-height|heading-line-height|letter-spacing)-|^--default-font-size$|-(letter|word)-spacing$|-leading-trim-(start|end)$|^--code-padding-/, + "margin-left", + ], + [/^--color-|^--[a-z]+-(a?\d+|contrast|surface|indicator|track)$/, "color"], +]); + +// What Radix sets on a theme element itself. +const ELEMENT = [ + "color", + "background-color", + "font-family", + "font-size", + "font-weight", + "font-style", + "line-height", + "letter-spacing", + "overflow-wrap", + "text-size-adjust", + "-webkit-font-smoothing", +]; + +/** + * The names of the values `read` returns. + * + * @param {string[]} names The custom properties. + * @returns {string[]} Them, then the properties of the theme element. + */ +export function labels(names) { + return [...names, ...ELEMENT.map((property) => `(element) ${property}`)]; +} + +/** + * Add an element for each custom property, styled with it. + * + * @param {Element} container Where the elements go. + * @param {string[]} names The custom properties. + * @returns {{ name: string, property: string, style: CSSStyleDeclaration, exception?: import("./exceptions.js").Exception }[]} + * What to read each one from. + */ +export function mount(container, names) { + return names.map((name) => { + const property = PROBES.find(([pattern]) => pattern.test(name))?.[1]; + if (!property) throw new Error(`No probe for ${name}`); + const element = document.createElement("i"); + element.style.setProperty(property, `var(${name})`); + container.append(element); + const exception = EXCEPTIONS.find(({ pattern }) => pattern.test(name)); + return { name, property, style: getComputedStyle(element), exception }; + }); +} + +/** + * What every custom property resolves to, and the theme element's own styles. + * + * @param {ReturnType} probes What `mount` returned. + * @param {Element} theme The theme element the probes are in. + * @returns {string[]} A value for each of `labels`. A custom property that is + * not defined, or whose value is not one its probe takes, reads as `INVALID` + * and what it holds, as both pages would otherwise agree on the fallback. + */ +export function read(probes, theme) { + const inherited = getComputedStyle(theme); + const values = probes.map(({ name, property, style, exception }) => { + const raw = style.getPropertyValue(name); + if (raw === "" && exception?.undefined) return "undefined"; + if (raw === "" || !CSS.supports(property, raw)) return `INVALID ${raw}`; + const value = style.getPropertyValue(property); + return exception?.normalize ? exception.normalize(value) : value; + }); + for (const property of ELEMENT) { + values.push(inherited.getPropertyValue(property)); + } + return values; +} + +/** + * A short digest of the values, to compare a combination without moving them + * all out of the page. + * + * @param {string[]} values What `read` returned. + * @returns {{ hash: number, invalid: number }} An FNV-1a hash, and how many of + * the values are invalid. + */ +export function digest(values) { + let hash = 0x811c9dc5; + let invalid = 0; + for (const value of values) { + if (value.startsWith("INVALID")) invalid++; + for (let index = 0; index < value.length; index++) { + hash = Math.imul(hash ^ value.charCodeAt(index), 0x01000193); + } + hash = Math.imul(hash ^ 0xff, 0x01000193); + } + return { hash: hash >>> 0, invalid }; +} diff --git a/packages/reflex-components-ui/js/tests/harness/radix.html b/packages/reflex-components-ui/js/tests/harness/radix.html new file mode 100644 index 00000000000..d3b85af6435 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/radix.html @@ -0,0 +1,10 @@ + + + + + + +
+ + + diff --git a/packages/reflex-components-ui/js/tests/harness/radix.js b/packages/reflex-components-ui/js/tests/harness/radix.js new file mode 100644 index 00000000000..f12acac30d8 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/radix.js @@ -0,0 +1,42 @@ +// The reference page: the stylesheet of @radix-ui/themes and its `Theme` +// component, which decides the attributes the stylesheet selects on. + +import "@radix-ui/themes/styles.css"; + +import { Theme } from "@radix-ui/themes"; +import { createElement } from "react"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; + +import { install } from "./page.js"; + +const root = createRoot( + /** @type {Element} */ (document.getElementById("root")), +); + +install(({ theme, nested }) => { + const target = createElement("div", { id: "target" }); + flushSync(() => + root.render( + createElement( + Theme, + // A root `Theme` copies its props into state after it has painted. A + // new one for each theme starts from the props it is given. + /** @type {import("@radix-ui/themes").ThemeProps} */ ({ + key: JSON.stringify(theme), + ...theme, + }), + nested + ? createElement( + Theme, + /** @type {import("@radix-ui/themes").ThemeProps} */ (nested), + target, + ) + : target, + ), + ), + ); + return /** @type {Element} */ ( + document.querySelector(".radix-themes:has(> #target)") + ); +}); diff --git a/packages/reflex-components-ui/js/tests/harness/size/accents.js b/packages/reflex-components-ui/js/tests/harness/size/accents.js new file mode 100644 index 00000000000..745fe5e3e31 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/size/accents.js @@ -0,0 +1,33 @@ +// The whole theme and the other twenty-five accents, which is what an accent +// bound to state costs. + +import * as stylex from "@stylexjs/stylex"; + +import { accentIndigo } from "../../../src/themes/accent/indigo.js"; +import { focusScope } from "../../../src/themes/focus.js"; +import { graySlate } from "../../../src/themes/gray/slate.js"; +import { panelTranslucent } from "../../../src/themes/panel.js"; +import { radiusMedium } from "../../../src/themes/radius.js"; +import { scaling100 } from "../../../src/themes/scaling.js"; +import * as scopes from "../../../src/themes/scope.js"; +import { theme } from "../../../src/themes/theme.js"; + +import.meta.glob("../../../src/tokens/*.stylex.js", { eager: true }); +import.meta.glob("../../../src/themes/accent/*.js", { eager: true }); + +const styles = stylex.create({ body: { margin: 0 } }); + +const applied = [ + styles.body, + ...Object.values(scopes), + focusScope, + accentIndigo, + graySlate, + radiusMedium, + scaling100, + panelTranslucent, + theme.root, + theme.background, +]; + +document.body.className = stylex.props(applied).className ?? ""; diff --git a/packages/reflex-components-ui/js/tests/harness/size/baseline.js b/packages/reflex-components-ui/js/tests/harness/size/baseline.js new file mode 100644 index 00000000000..d421c5cb24b --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/size/baseline.js @@ -0,0 +1,11 @@ +// What a page pays for StyleX before it has a token or a theme. + +import * as stylex from "@stylexjs/stylex"; + +const styles = stylex.create({ body: { margin: 0 } }); + +// A list the compiler cannot see through, so that every entry has the runtime +// of StyleX and they differ by their styles alone. +const applied = [styles.body]; + +document.body.className = stylex.props(applied).className ?? ""; diff --git a/packages/reflex-components-ui/js/tests/harness/size/theme.js b/packages/reflex-components-ui/js/tests/harness/size/theme.js new file mode 100644 index 00000000000..70ff5503154 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/size/theme.js @@ -0,0 +1,32 @@ +// One whole theme, as the root of an app has it: every token, the scope, one +// accent and one gray in both appearances, a radius, a scaling and a panel. + +import * as stylex from "@stylexjs/stylex"; + +import { accentIndigo } from "../../../src/themes/accent/indigo.js"; +import { focusScope } from "../../../src/themes/focus.js"; +import { graySlate } from "../../../src/themes/gray/slate.js"; +import { panelTranslucent } from "../../../src/themes/panel.js"; +import { radiusMedium } from "../../../src/themes/radius.js"; +import { scaling100 } from "../../../src/themes/scaling.js"; +import * as scopes from "../../../src/themes/scope.js"; +import { theme } from "../../../src/themes/theme.js"; + +import.meta.glob("../../../src/tokens/*.stylex.js", { eager: true }); + +const styles = stylex.create({ body: { margin: 0 } }); + +const applied = [ + styles.body, + ...Object.values(scopes), + focusScope, + accentIndigo, + graySlate, + radiusMedium, + scaling100, + panelTranslucent, + theme.root, + theme.background, +]; + +document.body.className = stylex.props(applied).className ?? ""; diff --git a/packages/reflex-components-ui/js/tests/harness/size/tokens.js b/packages/reflex-components-ui/js/tests/harness/size/tokens.js new file mode 100644 index 00000000000..3910b5b97ad --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/size/tokens.js @@ -0,0 +1,14 @@ +// The baseline and every token, with no color scale but the black one that the +// shadows and the overlay are made of. + +import * as stylex from "@stylexjs/stylex"; + +import.meta.glob("../../../src/tokens/*.stylex.js", { eager: true }); + +const styles = stylex.create({ body: { margin: 0 } }); + +// A list the compiler cannot see through, so that every entry has the runtime +// of StyleX and they differ by their styles alone. +const applied = [styles.body]; + +document.body.className = stylex.props(applied).className ?? ""; diff --git a/packages/reflex-components-ui/js/tests/harness/sweep.js b/packages/reflex-components-ui/js/tests/harness/sweep.js new file mode 100644 index 00000000000..6d4a5121feb --- /dev/null +++ b/packages/reflex-components-ui/js/tests/harness/sweep.js @@ -0,0 +1,27 @@ +// The whole token sweep, `npm run sweep`: every custom property Radix Themes +// defines, in every combination of accent, gray, appearance, radius and +// scaling, read under the StyleX modules and under @radix-ui/themes, on an sRGB +// screen and on a display-P3 one. `npm test` runs part of it. + +import { openHarness } from "./browser.js"; +import { fullSweep } from "./configs.js"; + +const start = Date.now(); +const harness = await openHarness(); +const configs = fullSweep(); +let failed = false; +for (const gamut of /** @type {const} */ (["srgb", "p3"])) { + const { differences, distinct } = await harness.compare(configs, gamut); + console.log( + `${gamut}: ${configs.length} themes x ${harness.names.length} custom properties, ${distinct} distinct results, ${differences.length} differences`, + ); + for (const { config, label, ours, radix } of differences.slice(0, 50)) { + console.log( + ` ${label} in ${JSON.stringify(config)}\n ours: ${ours}\n radix: ${radix}`, + ); + } + failed ||= differences.length > 0; +} +await harness.close(); +console.log(`${((Date.now() - start) / 1000).toFixed(1)}s`); +process.exit(failed ? 1 : 0); diff --git a/packages/reflex-components-ui/js/tests/radix-tokens.test.js b/packages/reflex-components-ui/js/tests/radix-tokens.test.js new file mode 100644 index 00000000000..c3ec296d3ef --- /dev/null +++ b/packages/reflex-components-ui/js/tests/radix-tokens.test.js @@ -0,0 +1,211 @@ +// @vitest-environment node +import { readdir, readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; + +import { expect, test } from "vitest"; + +import { + lightDark, + mergeShadows, + parseTokens, + radixTokens, +} from "../scripts/radix-tokens.js"; + +const FIXTURE = fileURLToPath( + new URL("./fixtures/radix-tokens/", import.meta.url), +); + +const OPTIONS = { + version: "0.0.0", + defaults: { + radius: "medium", + scaling: "100%", + panelBackground: "translucent", + accentColor: "red", + grayColor: "auto", + }, + matchingGray: (/** @type {string} */ accent) => + accent === "red" ? "slate" : "gray", +}; + +/** + * The files below a directory. + * + * @param {string} directory The directory. + * @returns {Promise>} Their content, by their path + * relative to the directory. + */ +async function filesBelow(directory) { + const entries = await readdir(directory, { + recursive: true, + withFileTypes: true, + }); + /** @type {Record} */ + const files = {}; + for (const entry of entries) { + if (!entry.isFile()) continue; + const path = `${entry.parentPath}/${entry.name}`; + files[path.slice(directory.length)] = await readFile(path, "utf8"); + } + return files; +} + +/** + * The message of the error a function throws. postcss adds the node it was + * walking to an error, so the error itself is not compared. + * + * @param {() => unknown} run The function. + * @returns {string | null} The message, or null when it does not throw. + */ +function thrown(run) { + try { + run(); + } catch (error) { + return /** @type {Error} */ (error).message; + } + return null; +} + +test("a stylesheet becomes the modules of its colors, tokens and themes", async () => { + const css = await readFile(`${FIXTURE}tokens.css`, "utf8"); + const generated = Object.fromEntries( + await Promise.all( + radixTokens(css, OPTIONS).map(async ({ path, render }) => [ + path, + await render(), + ]), + ), + ); + expect(generated).toEqual(await filesBelow(`${FIXTURE}expected/`)); +}); + +test("a color that is the same in both appearances stays as it is", () => { + expect(lightDark("#0090ff", "#0090ff")).toBe("#0090ff"); +}); + +test("a color that differs is chosen by the color scheme", () => { + expect(lightDark("white", "var(--gray-1)")).toBe( + "light-dark(white, var(--gray-1))", + ); +}); + +test("shadows with the same layers choose their colors", () => { + expect( + mergeShadows( + "0 0 0 1px color-mix(in oklab, var(--gray-a3), var(--gray-3) 25%), 0 8px 40px var(--black-a1)", + "0 0 0 1px color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 8px 40px var(--black-a1)", + ), + ).toBe( + "0 0 0 1px light-dark(color-mix(in oklab, var(--gray-a3), var(--gray-3) 25%), color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%)), 0 8px 40px var(--black-a1)", + ); +}); + +test("a shadow layer of one appearance is transparent in the other, and both keep their order", () => { + expect( + mergeShadows( + "inset 0 0 0 1px var(--gray-a5), inset 0 1.5px 2px 0 var(--gray-a2), inset 0 1.5px 2px 0 var(--black-a2)", + "inset 0 -1px 1px 0 var(--gray-a3), inset 0 0 0 1px var(--gray-a3), inset 0 3px 4px 0 var(--black-a5), inset 0 0 0 1px var(--gray-a4)", + ), + ).toBe( + [ + "inset 0 -1px 1px 0 light-dark(transparent, var(--gray-a3))", + "inset 0 0 0 1px light-dark(var(--gray-a5), var(--gray-a3))", + "inset 0 1.5px 2px 0 light-dark(var(--gray-a2), transparent)", + "inset 0 1.5px 2px 0 light-dark(var(--black-a2), transparent)", + "inset 0 3px 4px 0 light-dark(transparent, var(--black-a5))", + "inset 0 0 0 1px light-dark(transparent, var(--gray-a4))", + ].join(", "), + ); +}); + +test("identical shadows are left alone", () => { + expect(mergeShadows("0 0 0 1px red", "0 0 0 1px red")).toBe("0 0 0 1px red"); +}); + +test("a rule is read into the appearance and the gamut it applies to", () => { + const { tokens, themes, element } = parseTokens(` + :root, .light, .light-theme { --red-9: #e5484d; } + .dark, .dark-theme { --red-9: #e5484e; } + @supports (color: color(display-p3 1 1 1)) { + @media (color-gamut: p3) { + .dark, .dark-theme { --red-9: color(display-p3 0.83 0.329 0.324); } + } + } + :root { --red-contrast: white; } + [data-accent-color='red'] { --accent-9: var(--red-9); } + .radix-themes:where([data-scaling='90%']) { --scaling: 0.9; } + .radix-themes { --space-1: calc(4px + * var(--scaling)); -webkit-text-size-adjust: none; text-size-adjust: none; } + .radix-themes ::selection { background-color: var(--focus-a5); } + `); + expect(Object.fromEntries(tokens)).toEqual({ + "--red-9": { + light: "#e5484d", + dark: "#e5484e", + p3Dark: "color(display-p3 0.83 0.329 0.324)", + }, + "--red-contrast": { light: "white", dark: "white" }, + "--space-1": { + light: "calc(4px * var(--scaling))", + dark: "calc(4px * var(--scaling))", + }, + }); + expect( + Object.fromEntries( + Object.entries(themes).map(([attribute, values]) => [ + attribute, + Object.fromEntries( + [...values].map(([name, vars]) => [name, Object.fromEntries(vars)]), + ), + ]), + ), + ).toEqual({ + "accent-color": { red: { "--accent-9": "var(--red-9)" } }, + scaling: { "90%": { "--scaling": "0.9" } }, + }); + expect(element).toEqual({ root: [["text-size-adjust", "none"]] }); +}); + +// A selector or a condition the generator has not seen is a change in how +// Radix builds its tokens, which it cannot translate by guessing. +test("an unknown selector is an error", () => { + expect(thrown(() => parseTokens(".rt-Button { --accent-9: red; }"))).toBe( + "Unknown selector: .rt-Button", + ); +}); + +test("an unknown condition is an error", () => { + expect( + thrown(() => + parseTokens("@media (min-width: 520px) { :root { --space-1: 4px; } }"), + ), + ).toBe("Unknown condition on :root: @media (min-width: 520px)"); +}); + +test("a custom property on the selection rule is an error", () => { + expect( + thrown(() => parseTokens(".radix-themes ::selection { --focus-1: red; }")), + ).toBe("--focus-1 is set by .radix-themes ::selection"); +}); + +test("a token with one appearance is an error", async () => { + const css = await readFile(`${FIXTURE}tokens.css`, "utf8"); + expect( + thrown(() => + radixTokens(`${css}.dark, .dark-theme { --amber-9: #ffc53d; }`, OPTIONS), + ), + ).toBe("--amber-9 has no value in one appearance."); +}); + +test("a token that is in no group and in no scale is an error", async () => { + const css = await readFile(`${FIXTURE}tokens.css`, "utf8"); + expect( + thrown(() => radixTokens(`${css}:root { --container-1: 448px; }`, OPTIONS)), + ).toBe("--container-1 is in no group and in no color scale."); +}); + +test("a stylesheet without one of the theme attributes is an error", () => { + expect( + thrown(() => radixTokens(":root { --red-9: #e5484d; }", OPTIONS)), + ).toBe("Radix has no rule for data-accent-color."); +}); diff --git a/packages/reflex-components-ui/js/tests/size.test.js b/packages/reflex-components-ui/js/tests/size.test.js new file mode 100644 index 00000000000..a3b2d8e2487 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/size.test.js @@ -0,0 +1,71 @@ +// @vitest-environment node +// +// What the tokens and a theme cost a page, built the way an app builds them. + +import { mkdtemp, readdir, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { gzipSync } from "node:zlib"; + +import { afterAll, beforeAll, expect, test } from "vitest"; + +import { buildHarness } from "./harness/build.js"; + +const KB = 1024; + +/** @type {string} */ +let dist; + +/** @type {Record} */ +const built = {}; + +beforeAll(async () => { + dist = await mkdtemp(join(tmpdir(), "reflex-ui-size-")); + // One build for each entry: StyleX writes one stylesheet for a build. + for (const entry of ["baseline", "tokens", "theme", "accents"]) { + const assets = join(dist, entry, "assets"); + await buildHarness([`size/${entry}.js`], join(dist, entry)); + const files = await readdir(assets); + const [css, js] = await Promise.all( + [".css", ".js"].map((extension) => + readFile( + join( + assets, + /** @type {string} */ ( + files.find((file) => file.endsWith(extension)) + ), + ), + ), + ), + ); + built[entry] = { css: gzipSync(css).length, js: js.toString() }; + } +}, 120_000); + +afterAll(async () => { + await rm(dist, { recursive: true }); +}); + +test("a whole theme, with one accent and one gray, is under 6 KB of gzipped CSS", () => { + expect(built.theme.css - built.baseline.css).toBeLessThanOrEqual(6 * KB); +}); + +test("every accent at once, as an accent bound to state needs, is under 28 KB", () => { + expect(built.accents.css - built.baseline.css).toBeLessThanOrEqual(28 * KB); +}); + +test("the tokens alone are under 2.5 KB of gzipped CSS", () => { + expect(built.tokens.css - built.baseline.css).toBeLessThanOrEqual(2.5 * KB); +}); + +test("the tokens add no javascript", () => { + expect(built.tokens.js).toBe(built.baseline.js); +}); + +test("a theme adds its class names to the javascript and nothing else", () => { + // Each theme is an object of the two class names StyleX compiled it to. + const themes = built.theme.js.match(/\{\w+:`\w+ \w+`,\$\$css:!0\}/g); + expect(themes?.length).toBe(11); + // An accent that is imported and not applied is not in the bundle. + expect(built.accents.js).toBe(built.theme.js); +}); diff --git a/packages/reflex-components-ui/js/tests/themes.test.js b/packages/reflex-components-ui/js/tests/themes.test.js new file mode 100644 index 00000000000..cc3ac91eadb --- /dev/null +++ b/packages/reflex-components-ui/js/tests/themes.test.js @@ -0,0 +1,312 @@ +// @vitest-environment node +// +// The tokens and themes in a browser: a page built with the StyleX modules next +// to one built with @radix-ui/themes, in headless Chromium. `npm run sweep` +// compares the whole product of the theme props the same way. + +import { afterAll, beforeAll, beforeEach, expect, test } from "vitest"; + +import { openHarness } from "./harness/browser.js"; +import { APPEARANCES, DEFAULT_THEME, fastSweep } from "./harness/configs.js"; +import { EXCEPTIONS } from "./harness/exceptions.js"; + +/** @typedef {import("./harness/page.js").Config} Config */ + +const GAMUTS = /** @type {const} */ (["srgb", "p3"]); + +/** @type {Awaited>} */ +let harness; + +beforeAll(async () => { + harness = await openHarness(); +}, 120_000); + +beforeEach(async () => { + await harness.setGamut("srgb"); +}); + +afterAll(async () => { + await harness.close(); +}); + +/** + * Compare pages under both modules and Radix, on both kinds of screen. + * + * @param {Config[]} configs The pages. + * @returns {Promise} Every value + * the two disagree on. + */ +async function differences(configs) { + const found = []; + for (const gamut of GAMUTS) { + found.push(...(await harness.compare(configs, gamut)).differences); + } + return found; +} + +/** + * The declared value of custom properties on the root theme element and on a + * theme nested in it. + * + * @param {Config} config The page to show. + * @param {string[]} names The custom properties. + * @returns {Promise<{ root: Record, nested: Record }>} + * The values, before `light-dark()` is resolved. + */ +async function declared(config, names) { + await harness.read(harness.ours, config); + return harness.ours.evaluate((properties) => { + const root = /** @type {Element} */ (document.body.firstElementChild); + const [rootStyle, nestedStyle] = [root, root.firstElementChild].map( + (element) => getComputedStyle(/** @type {Element} */ (element)), + ); + /** @type {(style: CSSStyleDeclaration) => Record} */ + const values = (style) => + Object.fromEntries( + properties.map((name) => [name, style.getPropertyValue(name)]), + ); + return { root: values(rootStyle), nested: values(nestedStyle) }; + }, names); +} + +test("the sweep reads every custom property of the Radix token stylesheet", () => { + expect(harness.names.length).toBe(1068); + expect( + EXCEPTIONS.map(({ pattern }) => + harness.names.filter((name) => pattern.test(name)), + ), + ).toEqual([ + [ + "--code-font-weight", + "--strong-font-style", + "--em-font-weight", + "--quote-font-weight", + ], + [ + "--shadow-1", + "--shadow-2", + "--shadow-3", + "--shadow-4", + "--shadow-5", + "--shadow-6", + ], + ]); +}); + +test.each( + GAMUTS, +)("every custom property has the value Radix gives it, for each value of each theme prop (%s)", async (gamut) => { + const result = await harness.compare(fastSweep(), gamut); + expect(result).toEqual({ differences: [], distinct: 396 }); +}, 60_000); + +test("the class of html decides the appearance of every scale", async () => { + const [light, dark] = await Promise.all( + APPEARANCES.map(async (appearance) => + harness.read(harness.ours, { appearance, theme: DEFAULT_THEME }), + ), + ); + const scales = harness.names.flatMap((name) => { + const scale = /^--([a-z]+)-a1$/.exec(name)?.[1]; + return scale ? [scale] : []; + }); + const steps = [...Array(12).keys()].flatMap((step) => [ + `${step + 1}`, + `a${step + 1}`, + ]); + const flipped = scales.filter((scale) => + steps.some((step) => { + const name = `--${scale}-${step}`; + return name in light && light[name] !== dark[name]; + }), + ); + expect(scales.length).toBe(35); + // The two overlay scales are the same in both appearances. + expect(flipped).toEqual( + scales.filter((scale) => scale !== "black" && scale !== "white"), + ); +}); + +test("a nested theme overrides accent, gray, radius and scaling for its subtree only", async () => { + /** @type {Config} */ + const config = { + appearance: "light", + theme: DEFAULT_THEME, + nested: { + accentColor: "red", + grayColor: "sand", + radius: "full", + scaling: "110%", + hasBackground: false, + }, + }; + expect( + await declared(config, [ + "--accent-9", + "--gray-9", + "--radius-factor", + "--radius-full", + "--scaling", + "--space-4", + "--radius-4", + "--font-size-3", + ]), + ).toEqual({ + root: { + "--accent-9": "#3e63dd", + "--gray-9": "light-dark(#8b8d98,#696e77)", + "--radius-factor": "1", + "--radius-full": "0px", + "--scaling": "1", + "--space-4": "calc(16px * 1)", + "--radius-4": "calc(8px * 1 * 1)", + "--font-size-3": "calc(16px * 1)", + }, + nested: { + "--accent-9": "#e5484d", + "--gray-9": "light-dark(#8d8d86,#6f6d66)", + "--radius-factor": "1.5", + "--radius-full": "9999px", + "--scaling": "1.1", + "--space-4": "calc(16px * 1.1)", + "--radius-4": "calc(8px * 1.1 * 1.5)", + "--font-size-3": "calc(16px * 1.1)", + }, + }); + expect(await differences([config])).toEqual([]); +}); + +// A nested Radix `Theme` inherits the props it is not given from the theme +// around it. Here a nested theme is the classes of what it sets, and the rest +// is inherited by the cascade. +test.each( + /** @type {[string, Partial, import("./harness/page.js").ThemeProps][]} */ ([ + ["a scaling", {}, { scaling: "90%" }], + ["a radius", {}, { radius: "none" }], + ["an accent", {}, { accentColor: "crimson" }], + ["the gray accent", {}, { accentColor: "gray" }], + ["a gray", {}, { grayColor: "olive" }], + [ + "a gray under a solid panel", + { panelBackground: "solid" }, + { grayColor: "olive" }, + ], + ["a panel", {}, { panelBackground: "solid" }], + ["a background", {}, { hasBackground: true }], + ["the other appearance", {}, { appearance: "dark", hasBackground: true }], + ["the light appearance", {}, { appearance: "light", hasBackground: true }], + [ + "an appearance and an accent, under a gray accent", + { accentColor: "gray" }, + { appearance: "dark", accentColor: "jade", hasBackground: false }, + ], + ]), +)("a nested theme that only sets %s matches Radix, in the page and in the top layer", async (_, theme, nested) => { + const configs = APPEARANCES.flatMap((appearance) => + [false, true].map((popover) => ({ + appearance, + theme: { ...DEFAULT_THEME, ...theme }, + nested, + popover, + })), + ); + expect(await differences(configs)).toEqual([]); +}); + +test("a dark theme inside a light page is one property on its element", async () => { + /** @type {Config} */ + const config = { + appearance: "light", + theme: DEFAULT_THEME, + nested: { appearance: "dark", hasBackground: true }, + }; + const light = await harness.read(harness.ours, { + appearance: "light", + theme: DEFAULT_THEME, + }); + const dark = await harness.read(harness.ours, { + appearance: "dark", + theme: DEFAULT_THEME, + }); + const nested = await harness.read(harness.ours, config); + expect(nested).toEqual(dark); + expect(nested).not.toEqual(light); + expect( + await harness.ours.evaluate(() => { + const root = /** @type {Element} */ (document.body.firstElementChild); + return [document.documentElement, root, root.firstElementChild].map( + (element) => + getComputedStyle(/** @type {Element} */ (element)).colorScheme, + ); + }), + ).toEqual(["light", "light", "dark"]); +}); + +test("a native popover declared in a nested theme has that theme's values", async () => { + /** @type {Config} */ + const config = { + appearance: "light", + theme: DEFAULT_THEME, + nested: { + appearance: "dark", + accentColor: "red", + grayColor: "sand", + radius: "full", + scaling: "110%", + panelBackground: "solid", + hasBackground: true, + }, + }; + const inPage = await harness.read(harness.ours, config); + const inPopover = await harness.read(harness.ours, { + ...config, + popover: true, + }); + expect( + await harness.ours.evaluate(() => { + const popover = /** @type {Element} */ ( + document.querySelector("[popover]") + ); + return [ + popover.matches(":popover-open"), + popover.children.length, + getComputedStyle(popover).colorScheme, + ]; + }), + ).toEqual([true, 1068, "dark"]); + expect(inPopover).toEqual(inPage); + expect({ + accent: inPopover["--accent-9"], + gray: inPopover["--gray-12"], + radius: inPopover["--radius-4"], + space: inPopover["--space-4"], + panel: inPopover["--color-panel"], + }).toEqual({ + accent: "rgb(229, 72, 77)", + gray: "rgb(238, 238, 236)", + radius: "13.2px", + space: "17.6px", + panel: "rgb(25, 25, 24)", + }); +}); + +// The one thing a nested Radix `Theme` does that the cascade cannot: it knows +// that the accent it inherits is the gray, and follows a gray of its own. Here +// the nested theme has to name the gray accent again. +test("a nested gray under an inherited gray accent leaves the accent as it was", async () => { + /** @type {Config} */ + const config = { + appearance: "light", + theme: { ...DEFAULT_THEME, accentColor: "gray" }, + nested: { grayColor: "olive" }, + }; + const { differences: stale } = await harness.compare([config], "srgb"); + expect([ + ...new Set(stale.map(({ label }) => label.replace(/-[a-z]*\d*$/, ""))), + ]).toEqual(["--focus", "--accent"]); + expect( + await differences([ + { ...config, nested: { grayColor: "olive", accentColor: "gray" } }, + ]), + ).toEqual([]); +}); diff --git a/packages/reflex-components-ui/js/tsconfig.node.json b/packages/reflex-components-ui/js/tsconfig.node.json index bc7af158c18..0434d7a4dc7 100644 --- a/packages/reflex-components-ui/js/tsconfig.node.json +++ b/packages/reflex-components-ui/js/tsconfig.node.json @@ -3,7 +3,9 @@ // generators, the tests and this package's own configuration. "extends": "./tsconfig.json", "compilerOptions": { - "types": ["node"] + // `vite/client` is for the pages the live tests build, which use + // `import.meta.glob`. + "types": ["node", "vite/client"] }, "include": ["src/*.js", "scripts", "tests", "*.js"], "exclude": [] diff --git a/packages/reflex-components-ui/news/+tokens-themes.feature.md b/packages/reflex-components-ui/news/+tokens-themes.feature.md new file mode 100644 index 00000000000..41f58227984 --- /dev/null +++ b/packages/reflex-components-ui/news/+tokens-themes.feature.md @@ -0,0 +1 @@ +Add the design tokens, color scales and themes `rx.ui` components are styled with, as StyleX modules generated from Radix Themes. Every custom property keeps its Radix name and value (`--space-4`, `--radius-3`, `--accent-9`), so `rx.color("accent", 9)` and existing CSS resolve the same under both, and an app's stylesheet only carries the scales and themes it imports. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/_radix_tokens.py b/packages/reflex-components-ui/src/reflex_components_ui/_radix_tokens.py new file mode 100644 index 00000000000..644ab3c4a11 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/_radix_tokens.py @@ -0,0 +1,1411 @@ +"""The StyleX modules generated from @radix-ui/themes, and what they define. + +Generated by js/scripts/generate.js. Do not edit. +""" + +RADIX_THEMES_VERSION: str = "3.3.0" + +VAR_GROUPS: dict[str, tuple[str, tuple[str, ...]]] = { + "amber": ( + "colors/amber.stylex.js", + ( + "--amber-1", + "--amber-2", + "--amber-3", + "--amber-4", + "--amber-5", + "--amber-6", + "--amber-7", + "--amber-8", + "--amber-9", + "--amber-10", + "--amber-11", + "--amber-12", + "--amber-a1", + "--amber-a2", + "--amber-a3", + "--amber-a4", + "--amber-a5", + "--amber-a6", + "--amber-a7", + "--amber-a8", + "--amber-a9", + "--amber-a10", + "--amber-a11", + "--amber-a12", + "--amber-surface", + "--amber-indicator", + "--amber-track", + "--amber-contrast", + ), + ), + "black": ( + "colors/black.stylex.js", + ( + "--black-a1", + "--black-a2", + "--black-a3", + "--black-a4", + "--black-a5", + "--black-a6", + "--black-a7", + "--black-a8", + "--black-a9", + "--black-a10", + "--black-a11", + "--black-a12", + ), + ), + "blue": ( + "colors/blue.stylex.js", + ( + "--blue-1", + "--blue-2", + "--blue-3", + "--blue-4", + "--blue-5", + "--blue-6", + "--blue-7", + "--blue-8", + "--blue-9", + "--blue-10", + "--blue-11", + "--blue-12", + "--blue-a1", + "--blue-a2", + "--blue-a3", + "--blue-a4", + "--blue-a5", + "--blue-a6", + "--blue-a7", + "--blue-a8", + "--blue-a9", + "--blue-a10", + "--blue-a11", + "--blue-a12", + "--blue-surface", + "--blue-indicator", + "--blue-track", + "--blue-contrast", + ), + ), + "bronze": ( + "colors/bronze.stylex.js", + ( + "--bronze-1", + "--bronze-2", + "--bronze-3", + "--bronze-4", + "--bronze-5", + "--bronze-6", + "--bronze-7", + "--bronze-8", + "--bronze-9", + "--bronze-10", + "--bronze-11", + "--bronze-12", + "--bronze-a1", + "--bronze-a2", + "--bronze-a3", + "--bronze-a4", + "--bronze-a5", + "--bronze-a6", + "--bronze-a7", + "--bronze-a8", + "--bronze-a9", + "--bronze-a10", + "--bronze-a11", + "--bronze-a12", + "--bronze-surface", + "--bronze-indicator", + "--bronze-track", + "--bronze-contrast", + ), + ), + "brown": ( + "colors/brown.stylex.js", + ( + "--brown-1", + "--brown-2", + "--brown-3", + "--brown-4", + "--brown-5", + "--brown-6", + "--brown-7", + "--brown-8", + "--brown-9", + "--brown-10", + "--brown-11", + "--brown-12", + "--brown-a1", + "--brown-a2", + "--brown-a3", + "--brown-a4", + "--brown-a5", + "--brown-a6", + "--brown-a7", + "--brown-a8", + "--brown-a9", + "--brown-a10", + "--brown-a11", + "--brown-a12", + "--brown-surface", + "--brown-indicator", + "--brown-track", + "--brown-contrast", + ), + ), + "crimson": ( + "colors/crimson.stylex.js", + ( + "--crimson-1", + "--crimson-2", + "--crimson-3", + "--crimson-4", + "--crimson-5", + "--crimson-6", + "--crimson-7", + "--crimson-8", + "--crimson-9", + "--crimson-10", + "--crimson-11", + "--crimson-12", + "--crimson-a1", + "--crimson-a2", + "--crimson-a3", + "--crimson-a4", + "--crimson-a5", + "--crimson-a6", + "--crimson-a7", + "--crimson-a8", + "--crimson-a9", + "--crimson-a10", + "--crimson-a11", + "--crimson-a12", + "--crimson-surface", + "--crimson-indicator", + "--crimson-track", + "--crimson-contrast", + ), + ), + "cyan": ( + "colors/cyan.stylex.js", + ( + "--cyan-1", + "--cyan-2", + "--cyan-3", + "--cyan-4", + "--cyan-5", + "--cyan-6", + "--cyan-7", + "--cyan-8", + "--cyan-9", + "--cyan-10", + "--cyan-11", + "--cyan-12", + "--cyan-a1", + "--cyan-a2", + "--cyan-a3", + "--cyan-a4", + "--cyan-a5", + "--cyan-a6", + "--cyan-a7", + "--cyan-a8", + "--cyan-a9", + "--cyan-a10", + "--cyan-a11", + "--cyan-a12", + "--cyan-surface", + "--cyan-indicator", + "--cyan-track", + "--cyan-contrast", + ), + ), + "gold": ( + "colors/gold.stylex.js", + ( + "--gold-1", + "--gold-2", + "--gold-3", + "--gold-4", + "--gold-5", + "--gold-6", + "--gold-7", + "--gold-8", + "--gold-9", + "--gold-10", + "--gold-11", + "--gold-12", + "--gold-a1", + "--gold-a2", + "--gold-a3", + "--gold-a4", + "--gold-a5", + "--gold-a6", + "--gold-a7", + "--gold-a8", + "--gold-a9", + "--gold-a10", + "--gold-a11", + "--gold-a12", + "--gold-surface", + "--gold-indicator", + "--gold-track", + "--gold-contrast", + ), + ), + "grass": ( + "colors/grass.stylex.js", + ( + "--grass-1", + "--grass-2", + "--grass-3", + "--grass-4", + "--grass-5", + "--grass-6", + "--grass-7", + "--grass-8", + "--grass-9", + "--grass-10", + "--grass-11", + "--grass-12", + "--grass-a1", + "--grass-a2", + "--grass-a3", + "--grass-a4", + "--grass-a5", + "--grass-a6", + "--grass-a7", + "--grass-a8", + "--grass-a9", + "--grass-a10", + "--grass-a11", + "--grass-a12", + "--grass-surface", + "--grass-indicator", + "--grass-track", + "--grass-contrast", + ), + ), + "green": ( + "colors/green.stylex.js", + ( + "--green-1", + "--green-2", + "--green-3", + "--green-4", + "--green-5", + "--green-6", + "--green-7", + "--green-8", + "--green-9", + "--green-10", + "--green-11", + "--green-12", + "--green-a1", + "--green-a2", + "--green-a3", + "--green-a4", + "--green-a5", + "--green-a6", + "--green-a7", + "--green-a8", + "--green-a9", + "--green-a10", + "--green-a11", + "--green-a12", + "--green-surface", + "--green-indicator", + "--green-track", + "--green-contrast", + ), + ), + "indigo": ( + "colors/indigo.stylex.js", + ( + "--indigo-1", + "--indigo-2", + "--indigo-3", + "--indigo-4", + "--indigo-5", + "--indigo-6", + "--indigo-7", + "--indigo-8", + "--indigo-9", + "--indigo-10", + "--indigo-11", + "--indigo-12", + "--indigo-a1", + "--indigo-a2", + "--indigo-a3", + "--indigo-a4", + "--indigo-a5", + "--indigo-a6", + "--indigo-a7", + "--indigo-a8", + "--indigo-a9", + "--indigo-a10", + "--indigo-a11", + "--indigo-a12", + "--indigo-surface", + "--indigo-indicator", + "--indigo-track", + "--indigo-contrast", + ), + ), + "iris": ( + "colors/iris.stylex.js", + ( + "--iris-1", + "--iris-2", + "--iris-3", + "--iris-4", + "--iris-5", + "--iris-6", + "--iris-7", + "--iris-8", + "--iris-9", + "--iris-10", + "--iris-11", + "--iris-12", + "--iris-a1", + "--iris-a2", + "--iris-a3", + "--iris-a4", + "--iris-a5", + "--iris-a6", + "--iris-a7", + "--iris-a8", + "--iris-a9", + "--iris-a10", + "--iris-a11", + "--iris-a12", + "--iris-surface", + "--iris-indicator", + "--iris-track", + "--iris-contrast", + ), + ), + "jade": ( + "colors/jade.stylex.js", + ( + "--jade-1", + "--jade-2", + "--jade-3", + "--jade-4", + "--jade-5", + "--jade-6", + "--jade-7", + "--jade-8", + "--jade-9", + "--jade-10", + "--jade-11", + "--jade-12", + "--jade-a1", + "--jade-a2", + "--jade-a3", + "--jade-a4", + "--jade-a5", + "--jade-a6", + "--jade-a7", + "--jade-a8", + "--jade-a9", + "--jade-a10", + "--jade-a11", + "--jade-a12", + "--jade-surface", + "--jade-indicator", + "--jade-track", + "--jade-contrast", + ), + ), + "lime": ( + "colors/lime.stylex.js", + ( + "--lime-1", + "--lime-2", + "--lime-3", + "--lime-4", + "--lime-5", + "--lime-6", + "--lime-7", + "--lime-8", + "--lime-9", + "--lime-10", + "--lime-11", + "--lime-12", + "--lime-a1", + "--lime-a2", + "--lime-a3", + "--lime-a4", + "--lime-a5", + "--lime-a6", + "--lime-a7", + "--lime-a8", + "--lime-a9", + "--lime-a10", + "--lime-a11", + "--lime-a12", + "--lime-surface", + "--lime-indicator", + "--lime-track", + "--lime-contrast", + ), + ), + "mauve": ( + "colors/mauve.stylex.js", + ( + "--mauve-1", + "--mauve-2", + "--mauve-3", + "--mauve-4", + "--mauve-5", + "--mauve-6", + "--mauve-7", + "--mauve-8", + "--mauve-9", + "--mauve-10", + "--mauve-11", + "--mauve-12", + "--mauve-a1", + "--mauve-a2", + "--mauve-a3", + "--mauve-a4", + "--mauve-a5", + "--mauve-a6", + "--mauve-a7", + "--mauve-a8", + "--mauve-a9", + "--mauve-a10", + "--mauve-a11", + "--mauve-a12", + "--mauve-surface", + "--mauve-indicator", + "--mauve-track", + "--mauve-contrast", + ), + ), + "mint": ( + "colors/mint.stylex.js", + ( + "--mint-1", + "--mint-2", + "--mint-3", + "--mint-4", + "--mint-5", + "--mint-6", + "--mint-7", + "--mint-8", + "--mint-9", + "--mint-10", + "--mint-11", + "--mint-12", + "--mint-a1", + "--mint-a2", + "--mint-a3", + "--mint-a4", + "--mint-a5", + "--mint-a6", + "--mint-a7", + "--mint-a8", + "--mint-a9", + "--mint-a10", + "--mint-a11", + "--mint-a12", + "--mint-surface", + "--mint-indicator", + "--mint-track", + "--mint-contrast", + ), + ), + "olive": ( + "colors/olive.stylex.js", + ( + "--olive-1", + "--olive-2", + "--olive-3", + "--olive-4", + "--olive-5", + "--olive-6", + "--olive-7", + "--olive-8", + "--olive-9", + "--olive-10", + "--olive-11", + "--olive-12", + "--olive-a1", + "--olive-a2", + "--olive-a3", + "--olive-a4", + "--olive-a5", + "--olive-a6", + "--olive-a7", + "--olive-a8", + "--olive-a9", + "--olive-a10", + "--olive-a11", + "--olive-a12", + "--olive-surface", + "--olive-indicator", + "--olive-track", + "--olive-contrast", + ), + ), + "orange": ( + "colors/orange.stylex.js", + ( + "--orange-1", + "--orange-2", + "--orange-3", + "--orange-4", + "--orange-5", + "--orange-6", + "--orange-7", + "--orange-8", + "--orange-9", + "--orange-10", + "--orange-11", + "--orange-12", + "--orange-a1", + "--orange-a2", + "--orange-a3", + "--orange-a4", + "--orange-a5", + "--orange-a6", + "--orange-a7", + "--orange-a8", + "--orange-a9", + "--orange-a10", + "--orange-a11", + "--orange-a12", + "--orange-surface", + "--orange-indicator", + "--orange-track", + "--orange-contrast", + ), + ), + "pink": ( + "colors/pink.stylex.js", + ( + "--pink-1", + "--pink-2", + "--pink-3", + "--pink-4", + "--pink-5", + "--pink-6", + "--pink-7", + "--pink-8", + "--pink-9", + "--pink-10", + "--pink-11", + "--pink-12", + "--pink-a1", + "--pink-a2", + "--pink-a3", + "--pink-a4", + "--pink-a5", + "--pink-a6", + "--pink-a7", + "--pink-a8", + "--pink-a9", + "--pink-a10", + "--pink-a11", + "--pink-a12", + "--pink-surface", + "--pink-indicator", + "--pink-track", + "--pink-contrast", + ), + ), + "plum": ( + "colors/plum.stylex.js", + ( + "--plum-1", + "--plum-2", + "--plum-3", + "--plum-4", + "--plum-5", + "--plum-6", + "--plum-7", + "--plum-8", + "--plum-9", + "--plum-10", + "--plum-11", + "--plum-12", + "--plum-a1", + "--plum-a2", + "--plum-a3", + "--plum-a4", + "--plum-a5", + "--plum-a6", + "--plum-a7", + "--plum-a8", + "--plum-a9", + "--plum-a10", + "--plum-a11", + "--plum-a12", + "--plum-surface", + "--plum-indicator", + "--plum-track", + "--plum-contrast", + ), + ), + "purple": ( + "colors/purple.stylex.js", + ( + "--purple-1", + "--purple-2", + "--purple-3", + "--purple-4", + "--purple-5", + "--purple-6", + "--purple-7", + "--purple-8", + "--purple-9", + "--purple-10", + "--purple-11", + "--purple-12", + "--purple-a1", + "--purple-a2", + "--purple-a3", + "--purple-a4", + "--purple-a5", + "--purple-a6", + "--purple-a7", + "--purple-a8", + "--purple-a9", + "--purple-a10", + "--purple-a11", + "--purple-a12", + "--purple-surface", + "--purple-indicator", + "--purple-track", + "--purple-contrast", + ), + ), + "red": ( + "colors/red.stylex.js", + ( + "--red-1", + "--red-2", + "--red-3", + "--red-4", + "--red-5", + "--red-6", + "--red-7", + "--red-8", + "--red-9", + "--red-10", + "--red-11", + "--red-12", + "--red-a1", + "--red-a2", + "--red-a3", + "--red-a4", + "--red-a5", + "--red-a6", + "--red-a7", + "--red-a8", + "--red-a9", + "--red-a10", + "--red-a11", + "--red-a12", + "--red-surface", + "--red-indicator", + "--red-track", + "--red-contrast", + ), + ), + "ruby": ( + "colors/ruby.stylex.js", + ( + "--ruby-1", + "--ruby-2", + "--ruby-3", + "--ruby-4", + "--ruby-5", + "--ruby-6", + "--ruby-7", + "--ruby-8", + "--ruby-9", + "--ruby-10", + "--ruby-11", + "--ruby-12", + "--ruby-a1", + "--ruby-a2", + "--ruby-a3", + "--ruby-a4", + "--ruby-a5", + "--ruby-a6", + "--ruby-a7", + "--ruby-a8", + "--ruby-a9", + "--ruby-a10", + "--ruby-a11", + "--ruby-a12", + "--ruby-surface", + "--ruby-indicator", + "--ruby-track", + "--ruby-contrast", + ), + ), + "sage": ( + "colors/sage.stylex.js", + ( + "--sage-1", + "--sage-2", + "--sage-3", + "--sage-4", + "--sage-5", + "--sage-6", + "--sage-7", + "--sage-8", + "--sage-9", + "--sage-10", + "--sage-11", + "--sage-12", + "--sage-a1", + "--sage-a2", + "--sage-a3", + "--sage-a4", + "--sage-a5", + "--sage-a6", + "--sage-a7", + "--sage-a8", + "--sage-a9", + "--sage-a10", + "--sage-a11", + "--sage-a12", + "--sage-surface", + "--sage-indicator", + "--sage-track", + "--sage-contrast", + ), + ), + "sand": ( + "colors/sand.stylex.js", + ( + "--sand-1", + "--sand-2", + "--sand-3", + "--sand-4", + "--sand-5", + "--sand-6", + "--sand-7", + "--sand-8", + "--sand-9", + "--sand-10", + "--sand-11", + "--sand-12", + "--sand-a1", + "--sand-a2", + "--sand-a3", + "--sand-a4", + "--sand-a5", + "--sand-a6", + "--sand-a7", + "--sand-a8", + "--sand-a9", + "--sand-a10", + "--sand-a11", + "--sand-a12", + "--sand-surface", + "--sand-indicator", + "--sand-track", + "--sand-contrast", + ), + ), + "sky": ( + "colors/sky.stylex.js", + ( + "--sky-1", + "--sky-2", + "--sky-3", + "--sky-4", + "--sky-5", + "--sky-6", + "--sky-7", + "--sky-8", + "--sky-9", + "--sky-10", + "--sky-11", + "--sky-12", + "--sky-a1", + "--sky-a2", + "--sky-a3", + "--sky-a4", + "--sky-a5", + "--sky-a6", + "--sky-a7", + "--sky-a8", + "--sky-a9", + "--sky-a10", + "--sky-a11", + "--sky-a12", + "--sky-surface", + "--sky-indicator", + "--sky-track", + "--sky-contrast", + ), + ), + "slate": ( + "colors/slate.stylex.js", + ( + "--slate-1", + "--slate-2", + "--slate-3", + "--slate-4", + "--slate-5", + "--slate-6", + "--slate-7", + "--slate-8", + "--slate-9", + "--slate-10", + "--slate-11", + "--slate-12", + "--slate-a1", + "--slate-a2", + "--slate-a3", + "--slate-a4", + "--slate-a5", + "--slate-a6", + "--slate-a7", + "--slate-a8", + "--slate-a9", + "--slate-a10", + "--slate-a11", + "--slate-a12", + "--slate-surface", + "--slate-indicator", + "--slate-track", + "--slate-contrast", + ), + ), + "teal": ( + "colors/teal.stylex.js", + ( + "--teal-1", + "--teal-2", + "--teal-3", + "--teal-4", + "--teal-5", + "--teal-6", + "--teal-7", + "--teal-8", + "--teal-9", + "--teal-10", + "--teal-11", + "--teal-12", + "--teal-a1", + "--teal-a2", + "--teal-a3", + "--teal-a4", + "--teal-a5", + "--teal-a6", + "--teal-a7", + "--teal-a8", + "--teal-a9", + "--teal-a10", + "--teal-a11", + "--teal-a12", + "--teal-surface", + "--teal-indicator", + "--teal-track", + "--teal-contrast", + ), + ), + "tomato": ( + "colors/tomato.stylex.js", + ( + "--tomato-1", + "--tomato-2", + "--tomato-3", + "--tomato-4", + "--tomato-5", + "--tomato-6", + "--tomato-7", + "--tomato-8", + "--tomato-9", + "--tomato-10", + "--tomato-11", + "--tomato-12", + "--tomato-a1", + "--tomato-a2", + "--tomato-a3", + "--tomato-a4", + "--tomato-a5", + "--tomato-a6", + "--tomato-a7", + "--tomato-a8", + "--tomato-a9", + "--tomato-a10", + "--tomato-a11", + "--tomato-a12", + "--tomato-surface", + "--tomato-indicator", + "--tomato-track", + "--tomato-contrast", + ), + ), + "violet": ( + "colors/violet.stylex.js", + ( + "--violet-1", + "--violet-2", + "--violet-3", + "--violet-4", + "--violet-5", + "--violet-6", + "--violet-7", + "--violet-8", + "--violet-9", + "--violet-10", + "--violet-11", + "--violet-12", + "--violet-a1", + "--violet-a2", + "--violet-a3", + "--violet-a4", + "--violet-a5", + "--violet-a6", + "--violet-a7", + "--violet-a8", + "--violet-a9", + "--violet-a10", + "--violet-a11", + "--violet-a12", + "--violet-surface", + "--violet-indicator", + "--violet-track", + "--violet-contrast", + ), + ), + "white": ( + "colors/white.stylex.js", + ( + "--white-a1", + "--white-a2", + "--white-a3", + "--white-a4", + "--white-a5", + "--white-a6", + "--white-a7", + "--white-a8", + "--white-a9", + "--white-a10", + "--white-a11", + "--white-a12", + ), + ), + "yellow": ( + "colors/yellow.stylex.js", + ( + "--yellow-1", + "--yellow-2", + "--yellow-3", + "--yellow-4", + "--yellow-5", + "--yellow-6", + "--yellow-7", + "--yellow-8", + "--yellow-9", + "--yellow-10", + "--yellow-11", + "--yellow-12", + "--yellow-a1", + "--yellow-a2", + "--yellow-a3", + "--yellow-a4", + "--yellow-a5", + "--yellow-a6", + "--yellow-a7", + "--yellow-a8", + "--yellow-a9", + "--yellow-a10", + "--yellow-a11", + "--yellow-a12", + "--yellow-surface", + "--yellow-indicator", + "--yellow-track", + "--yellow-contrast", + ), + ), + "space": ( + "tokens/space.stylex.js", + ( + "--space-1", + "--space-2", + "--space-3", + "--space-4", + "--space-5", + "--space-6", + "--space-7", + "--space-8", + "--space-9", + ), + ), + "scaling": ( + "tokens/scaling.stylex.js", + ("--scaling",), + ), + "radiusFactor": ( + "tokens/radius.stylex.js", + ( + "--radius-factor", + "--radius-full", + "--radius-thumb", + ), + ), + "radius": ( + "tokens/radius.stylex.js", + ( + "--radius-1", + "--radius-2", + "--radius-3", + "--radius-4", + "--radius-5", + "--radius-6", + ), + ), + "shadow": ( + "tokens/shadow.stylex.js", + ( + "--shadow-1", + "--shadow-2", + "--shadow-3", + "--shadow-4", + "--shadow-5", + "--shadow-6", + ), + ), + "cursor": ( + "tokens/cursor.stylex.js", + ( + "--cursor-button", + "--cursor-checkbox", + "--cursor-disabled", + "--cursor-link", + "--cursor-menu-item", + "--cursor-radio", + "--cursor-slider-thumb", + "--cursor-slider-thumb-active", + "--cursor-switch", + ), + ), + "panel": ( + "tokens/panel.stylex.js", + ("--backdrop-filter-panel", "--panel-solid"), + ), + "color": ( + "tokens/color.stylex.js", + ( + "--color-background", + "--color-overlay", + "--color-panel-solid", + "--color-panel-translucent", + "--color-surface", + "--color-transparent", + "--color-panel-if-solid", + "--color-panel", + ), + ), + "accent": ( + "tokens/accent.stylex.js", + ( + "--accent-1", + "--accent-2", + "--accent-3", + "--accent-4", + "--accent-5", + "--accent-6", + "--accent-7", + "--accent-8", + "--accent-9", + "--accent-10", + "--accent-11", + "--accent-12", + "--accent-a1", + "--accent-a2", + "--accent-a3", + "--accent-a4", + "--accent-a5", + "--accent-a6", + "--accent-a7", + "--accent-a8", + "--accent-a9", + "--accent-a10", + "--accent-a11", + "--accent-a12", + "--accent-contrast", + "--accent-surface", + "--accent-indicator", + "--accent-track", + ), + ), + "focus": ( + "tokens/focus.stylex.js", + ( + "--focus-1", + "--focus-2", + "--focus-3", + "--focus-4", + "--focus-5", + "--focus-6", + "--focus-7", + "--focus-8", + "--focus-9", + "--focus-10", + "--focus-11", + "--focus-12", + "--focus-a1", + "--focus-a2", + "--focus-a3", + "--focus-a4", + "--focus-a5", + "--focus-a6", + "--focus-a7", + "--focus-a8", + "--focus-a9", + "--focus-a10", + "--focus-a11", + "--focus-a12", + ), + ), + "gray": ( + "tokens/gray.stylex.js", + ( + "--gray-1", + "--gray-2", + "--gray-3", + "--gray-4", + "--gray-5", + "--gray-6", + "--gray-7", + "--gray-8", + "--gray-9", + "--gray-10", + "--gray-11", + "--gray-12", + "--gray-a1", + "--gray-a2", + "--gray-a3", + "--gray-a4", + "--gray-a5", + "--gray-a6", + "--gray-a7", + "--gray-a8", + "--gray-a9", + "--gray-a10", + "--gray-a11", + "--gray-a12", + "--gray-surface", + "--gray-indicator", + "--gray-track", + "--gray-contrast", + ), + ), + "typography": ( + "tokens/typography.stylex.js", + ( + "--font-size-1", + "--font-size-2", + "--font-size-3", + "--font-size-4", + "--font-size-5", + "--font-size-6", + "--font-size-7", + "--font-size-8", + "--font-size-9", + "--font-weight-light", + "--font-weight-regular", + "--font-weight-medium", + "--font-weight-bold", + "--line-height-1", + "--line-height-2", + "--line-height-3", + "--line-height-4", + "--line-height-5", + "--line-height-6", + "--line-height-7", + "--line-height-8", + "--line-height-9", + "--letter-spacing-1", + "--letter-spacing-2", + "--letter-spacing-3", + "--letter-spacing-4", + "--letter-spacing-5", + "--letter-spacing-6", + "--letter-spacing-7", + "--letter-spacing-8", + "--letter-spacing-9", + "--default-font-family", + "--default-font-size", + "--default-font-style", + "--default-font-weight", + "--default-line-height", + "--default-letter-spacing", + "--default-leading-trim-start", + "--default-leading-trim-end", + "--heading-font-family", + "--heading-font-size-adjust", + "--heading-font-style", + "--heading-leading-trim-start", + "--heading-leading-trim-end", + "--heading-letter-spacing", + "--heading-line-height-1", + "--heading-line-height-2", + "--heading-line-height-3", + "--heading-line-height-4", + "--heading-line-height-5", + "--heading-line-height-6", + "--heading-line-height-7", + "--heading-line-height-8", + "--heading-line-height-9", + "--code-font-family", + "--code-font-size-adjust", + "--code-font-style", + "--code-font-weight", + "--code-letter-spacing", + "--code-padding-top", + "--code-padding-bottom", + "--code-padding-left", + "--code-padding-right", + "--strong-font-family", + "--strong-font-size-adjust", + "--strong-font-style", + "--strong-font-weight", + "--strong-letter-spacing", + "--em-font-family", + "--em-font-size-adjust", + "--em-font-style", + "--em-font-weight", + "--em-letter-spacing", + "--quote-font-family", + "--quote-font-size-adjust", + "--quote-font-style", + "--quote-font-weight", + "--quote-letter-spacing", + "--tab-active-letter-spacing", + "--tab-active-word-spacing", + "--tab-inactive-letter-spacing", + "--tab-inactive-word-spacing", + ), + ), +} + +ACCENT_THEMES: dict[str, tuple[str, str]] = { + "amber": ("themes/accent/amber.js", "accentAmber"), + "blue": ("themes/accent/blue.js", "accentBlue"), + "bronze": ("themes/accent/bronze.js", "accentBronze"), + "brown": ("themes/accent/brown.js", "accentBrown"), + "crimson": ("themes/accent/crimson.js", "accentCrimson"), + "cyan": ("themes/accent/cyan.js", "accentCyan"), + "gold": ("themes/accent/gold.js", "accentGold"), + "grass": ("themes/accent/grass.js", "accentGrass"), + "gray": ("themes/accent/gray.js", "accentGray"), + "green": ("themes/accent/green.js", "accentGreen"), + "indigo": ("themes/accent/indigo.js", "accentIndigo"), + "iris": ("themes/accent/iris.js", "accentIris"), + "jade": ("themes/accent/jade.js", "accentJade"), + "lime": ("themes/accent/lime.js", "accentLime"), + "mint": ("themes/accent/mint.js", "accentMint"), + "orange": ("themes/accent/orange.js", "accentOrange"), + "pink": ("themes/accent/pink.js", "accentPink"), + "plum": ("themes/accent/plum.js", "accentPlum"), + "purple": ("themes/accent/purple.js", "accentPurple"), + "red": ("themes/accent/red.js", "accentRed"), + "ruby": ("themes/accent/ruby.js", "accentRuby"), + "sky": ("themes/accent/sky.js", "accentSky"), + "teal": ("themes/accent/teal.js", "accentTeal"), + "tomato": ("themes/accent/tomato.js", "accentTomato"), + "violet": ("themes/accent/violet.js", "accentViolet"), + "yellow": ("themes/accent/yellow.js", "accentYellow"), +} + +GRAY_THEMES: dict[str, tuple[str, str]] = { + "gray": ("themes/gray/gray.js", "grayGray"), + "mauve": ("themes/gray/mauve.js", "grayMauve"), + "olive": ("themes/gray/olive.js", "grayOlive"), + "sage": ("themes/gray/sage.js", "graySage"), + "sand": ("themes/gray/sand.js", "graySand"), + "slate": ("themes/gray/slate.js", "graySlate"), +} + +RADIUS_THEMES: dict[str, tuple[str, str]] = { + "full": ("themes/radius.js", "radiusFull"), + "large": ("themes/radius.js", "radiusLarge"), + "medium": ("themes/radius.js", "radiusMedium"), + "none": ("themes/radius.js", "radiusNone"), + "small": ("themes/radius.js", "radiusSmall"), +} + +SCALING_THEMES: dict[str, tuple[str, str]] = { + "100%": ("themes/scaling.js", "scaling100"), + "105%": ("themes/scaling.js", "scaling105"), + "110%": ("themes/scaling.js", "scaling110"), + "90%": ("themes/scaling.js", "scaling90"), + "95%": ("themes/scaling.js", "scaling95"), +} + +PANEL_BACKGROUND_THEMES: dict[str, tuple[str, str]] = { + "solid": ("themes/panel.js", "panelSolid"), + "translucent": ("themes/panel.js", "panelTranslucent"), +} + +SCOPE_THEMES: tuple[tuple[str, str], ...] = ( + ("themes/scope.js", "spaceScope"), + ("themes/scope.js", "radiusScope"), + ("themes/scope.js", "typographyScope"), + ("themes/scope.js", "shadowScope"), + ("themes/scope.js", "colorScope"), +) + +FOCUS_THEME: tuple[str, str] = ("themes/focus.js", "focusScope") + +THEME_STYLES: tuple[str, str, tuple[str, ...]] = ( + "themes/theme.js", + "theme", + ( + "light", + "dark", + "background", + "root", + ), +) + +MATCHING_GRAY: dict[str, str] = { + "amber": "sand", + "blue": "slate", + "bronze": "sand", + "brown": "sand", + "crimson": "mauve", + "cyan": "slate", + "gold": "sand", + "grass": "olive", + "gray": "gray", + "green": "sage", + "indigo": "slate", + "iris": "slate", + "jade": "sage", + "lime": "olive", + "mint": "sage", + "orange": "sand", + "pink": "mauve", + "plum": "mauve", + "purple": "mauve", + "red": "mauve", + "ruby": "mauve", + "sky": "slate", + "teal": "sage", + "tomato": "mauve", + "violet": "mauve", + "yellow": "sand", +} + +DEFAULTS: dict[str, str] = { + "accent_color": "indigo", + "gray_color": "auto", + "radius": "medium", + "scaling": "100%", + "panel_background": "translucent", +} diff --git a/pyproject.toml b/pyproject.toml index bec46ac01e7..bd5e070b807 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -318,6 +318,7 @@ preview = true "packages/reflex-build-sdk/scripts/*.py" = ["INP001", "T201"] "packages/reflex-base/hatch_build.py" = ["INP001"] "packages/reflex-components-ui/hatch_build.py" = ["INP001"] +"packages/reflex-components-ui/js/tests/fixtures/*" = ["INP001"] "scripts/changed_paths.py" = ["T201"] "scripts/check_min_deps.py" = ["T201"] "scripts/check_outdated_deps.py" = ["T201"] @@ -336,7 +337,7 @@ markers = [ [tool.codespell] skip = "*.html, examples, *.pyi, */nba.csv, */olympic-winners.json, packages/reflex-build-sdk/openapi.json, uv.lock, */bun.lock, */package-lock.json, node_modules" -ignore-words-list = "te, TreeE, selectin" +ignore-words-list = "te, TreeE, selectin, afterAll" [tool.coverage.run] diff --git a/tests/units/reflex_components_ui/test__radix_tokens.py b/tests/units/reflex_components_ui/test__radix_tokens.py new file mode 100644 index 00000000000..264e1d3f471 --- /dev/null +++ b/tests/units/reflex_components_ui/test__radix_tokens.py @@ -0,0 +1,209 @@ +"""Tests for the generated list of the StyleX modules of reflex-components-ui. + +That the list is what its generator produces is checked by the javascript +package (``npm run generate:check``). These tests check that it describes the +javascript the package ships. +""" + +import re + +from reflex_components_radix.plugin import RADIX_THEMES_PACKAGE +from reflex_components_ui import _radix_tokens as tokens +from reflex_components_ui.constants import JS_SRC + +GRAYS = ("gray", "mauve", "olive", "sage", "sand", "slate") + +ACCENTS = ( + "amber", + "blue", + "bronze", + "brown", + "crimson", + "cyan", + "gold", + "grass", + "gray", + "green", + "indigo", + "iris", + "jade", + "lime", + "mint", + "orange", + "pink", + "plum", + "purple", + "red", + "ruby", + "sky", + "teal", + "tomato", + "violet", + "yellow", +) + +SCALE_STEPS = ( + *(str(step) for step in range(1, 13)), + *(f"a{step}" for step in range(1, 13)), + "contrast", + "surface", + "indicator", + "track", +) + + +def _exports(module: str) -> list[str]: + """Read the names a generated javascript module exports. + + Args: + module: The module, relative to the javascript source. + + Returns: + The exported names, in the order the module defines them. + """ + return re.findall( + r"^export const (\w+) = ", (JS_SRC / module).read_text(), re.MULTILINE + ) + + +def test_generated_from_the_radix_themes_reflex_installs(): + """The version in the list is the one the Radix components install.""" + assert f"@radix-ui/themes@{tokens.RADIX_THEMES_VERSION}" == RADIX_THEMES_PACKAGE + + +def test_var_groups_are_the_exports_of_their_modules(): + """Every group is exported by the module it names, and no export is left out.""" + by_module: dict[str, list[str]] = {} + for name, (module, _) in tokens.VAR_GROUPS.items(): + by_module.setdefault(module, []).append(name) + generated = sorted( + path.relative_to(JS_SRC).as_posix() + for directory in ("colors", "tokens") + for path in (JS_SRC / directory).iterdir() + ) + assert sorted(by_module) == generated + assert {module: _exports(module) for module in by_module} == by_module + + +def test_color_scales_have_the_radix_steps(): + """A scale has twelve steps, twelve alpha steps and four functional colors.""" + scales = { + name: variables + for name, (module, variables) in tokens.VAR_GROUPS.items() + if module.startswith("colors/") + } + colors = sorted({*ACCENTS, *GRAYS} - {"gray"}) + assert sorted(scales) == sorted([*colors, "black", "white"]) + for name in colors: + assert sorted(scales[name]) == sorted( + f"--{name}-{step}" for step in SCALE_STEPS + ) + for name in ("black", "white"): + assert scales[name] == tuple(f"--{name}-a{step}" for step in range(1, 13)) + + +def test_themed_groups_keep_the_radix_names(): + """The variables a theme sets are the ones Radix components read.""" + assert sorted(tokens.VAR_GROUPS["accent"][1]) == sorted( + f"--accent-{step}" for step in SCALE_STEPS + ) + assert sorted(tokens.VAR_GROUPS["gray"][1]) == sorted( + f"--gray-{step}" for step in SCALE_STEPS + ) + assert tokens.VAR_GROUPS["scaling"] == ("tokens/scaling.stylex.js", ("--scaling",)) + assert tokens.VAR_GROUPS["radiusFactor"] == ( + "tokens/radius.stylex.js", + ("--radius-factor", "--radius-full", "--radius-thumb"), + ) + assert tokens.VAR_GROUPS["space"] == ( + "tokens/space.stylex.js", + tuple(f"--space-{step}" for step in range(1, 10)), + ) + + +def test_a_variable_belongs_to_one_group(): + """A custom property can be looked up without knowing its group.""" + names = [name for _, variables in tokens.VAR_GROUPS.values() for name in variables] + assert len(names) == len(set(names)) == 1070 + + +def test_themes_are_the_exports_of_their_modules(): + """Every value of every theme prop has a theme, in the module the list names.""" + assert { + name: (f"themes/accent/{name}.js", f"accent{name.capitalize()}") + for name in ACCENTS + } == tokens.ACCENT_THEMES + assert { + name: (f"themes/gray/{name}.js", f"gray{name.capitalize()}") for name in GRAYS + } == tokens.GRAY_THEMES + assert { + name: ("themes/radius.js", f"radius{name.capitalize()}") + for name in ("full", "large", "medium", "none", "small") + } == tokens.RADIUS_THEMES + assert { + f"{percent}%": ("themes/scaling.js", f"scaling{percent}") + for percent in (100, 105, 110, 90, 95) + } == tokens.SCALING_THEMES + assert tokens.PANEL_BACKGROUND_THEMES == { + "solid": ("themes/panel.js", "panelSolid"), + "translucent": ("themes/panel.js", "panelTranslucent"), + } + assert tokens.SCOPE_THEMES == ( + ("themes/scope.js", "spaceScope"), + ("themes/scope.js", "radiusScope"), + ("themes/scope.js", "typographyScope"), + ("themes/scope.js", "shadowScope"), + ("themes/scope.js", "colorScope"), + ) + assert tokens.FOCUS_THEME == ("themes/focus.js", "focusScope") + assert tokens.THEME_STYLES == ( + "themes/theme.js", + "theme", + ("light", "dark", "background", "root"), + ) + by_module: dict[str, list[str]] = {} + for module, name in ( + *tokens.ACCENT_THEMES.values(), + *tokens.GRAY_THEMES.values(), + *tokens.RADIUS_THEMES.values(), + *tokens.SCALING_THEMES.values(), + *tokens.PANEL_BACKGROUND_THEMES.values(), + *tokens.SCOPE_THEMES, + tokens.FOCUS_THEME, + tokens.THEME_STYLES[:2], + ): + by_module.setdefault(module, []).append(name) + generated = sorted( + path.relative_to(JS_SRC).as_posix() + for path in (JS_SRC / "themes").rglob("*.js") + ) + assert sorted(by_module) == generated + assert {module: _exports(module) for module in by_module} == by_module + + +def test_defaults_are_the_props_of_a_radix_theme(): + """A theme that is given nothing is the default Radix theme.""" + assert tokens.DEFAULTS == { + "accent_color": "indigo", + "gray_color": "auto", + "radius": "medium", + "scaling": "100%", + "panel_background": "translucent", + } + + +def test_every_accent_has_a_matching_gray(): + """The gray that ``auto`` stands for is a gray theme.""" + assert tuple(tokens.MATCHING_GRAY) == ACCENTS + assert set(tokens.MATCHING_GRAY.values()) == set(GRAYS) + assert { + accent: tokens.MATCHING_GRAY[accent] + for accent in ("gray", "indigo", "tomato", "jade", "grass", "amber") + } == { + "gray": "gray", + "indigo": "slate", + "tomato": "mauve", + "jade": "sage", + "grass": "olive", + "amber": "sand", + } diff --git a/tests/units/reflex_components_ui/test_js_package.py b/tests/units/reflex_components_ui/test_js_package.py index 73afb438602..26fcd6c5b83 100644 --- a/tests/units/reflex_components_ui/test_js_package.py +++ b/tests/units/reflex_components_ui/test_js_package.py @@ -3,6 +3,9 @@ import json from pathlib import Path +from reflex_base import constants +from reflex_components_radix.plugin import RADIX_THEMES_PACKAGE + JS_PACKAGE = Path(__file__).parents[3] / "packages/reflex-components-ui/js" # StyleX is 0.x and has broken its output between patch releases, so every @@ -41,3 +44,27 @@ def test_lockfile_installs_stylex_at_the_pinned_version(): "@stylexjs/stylex": STYLEX_VERSION, "@stylexjs/unplugin": STYLEX_VERSION, } + + +def test_radix_themes_is_the_version_reflex_installs(): + """The tokens are generated from the Radix Themes an app gets. + + A page that mixes Radix components with these ones shows one palette only + while both define the same values, so the generator reads the stylesheet of + the version the Radix components install, and no other. + """ + name, _, version = RADIX_THEMES_PACKAGE.rpartition("@") + manifest = json.loads((JS_PACKAGE / "package.json").read_text()) + lock = json.loads((JS_PACKAGE / "package-lock.json").read_text()) + assert name == "@radix-ui/themes" + assert manifest["devDependencies"][name] == version + assert lock["packages"][f"node_modules/{name}"]["version"] == version + + +def test_vite_is_the_version_reflex_installs(): + """The live tests build their pages with the Vite an app is built with.""" + version = constants.PackageJson.DEV_DEPENDENCIES["vite"] + manifest = json.loads((JS_PACKAGE / "package.json").read_text()) + lock = json.loads((JS_PACKAGE / "package-lock.json").read_text()) + assert manifest["devDependencies"]["vite"] == version + assert lock["packages"]["node_modules/vite"]["version"] == version From 035c744263e7bdb9b36e98296774a582a0ca18ff Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 10:55:24 +0000 Subject: [PATCH 13/26] Build the rx.ui test pages with the layer prefix an app uses Claude-Session: https://claude.ai/code/session_014AwvTMTA184ecs3JHWuggN --- packages/reflex-components-ui/js/tests/harness/build.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/reflex-components-ui/js/tests/harness/build.js b/packages/reflex-components-ui/js/tests/harness/build.js index b89e8063c63..e9d99a12a25 100644 --- a/packages/reflex-components-ui/js/tests/harness/build.js +++ b/packages/reflex-components-ui/js/tests/harness/build.js @@ -11,7 +11,7 @@ const ROOT = fileURLToPath(new URL("./", import.meta.url)); // The options Reflex gives StyleX in an app. export const STYLEX_OPTIONS = { - useCSSLayers: true, + useCSSLayers: { prefix: "reflex-ui" }, styleResolution: /** @type {const} */ ("application-order"), lightningcssOptions: { minify: true, exclude: Features.LightDark }, }; From 7ba9da5c3e79777e5956f4e67cb44dd5683aa45f Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:09:47 +0000 Subject: [PATCH 14/26] Apply the rx.ui theme at the root, add rx.ui.theme and rx.ui.tokens (work in progress) Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- .../src/reflex_components_ui/__init__.py | 4 +- .../src/reflex_components_ui/layout/theme.py | 211 +++++++ .../src/reflex_components_ui/plugin.py | 26 +- .../src/reflex_components_ui/style/lower.py | 43 +- .../src/reflex_components_ui/styles/theme.py | 13 + .../src/reflex_components_ui/themes.py | 505 ++++++++++++++++ .../src/reflex_components_ui/tokens.py | 551 ++++++++++++++++++ .../reflex_components_ui/style/test_lower.py | 107 ++-- .../reflex_components_ui/style/test_merge.py | 92 +-- .../units/reflex_components_ui/test_plugin.py | 9 +- 10 files changed, 1444 insertions(+), 117 deletions(-) create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/themes.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/tokens.py diff --git a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py index 6733918892b..667ad352074 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -4,10 +4,12 @@ from reflex_base.utils import lazy_loader -_SUBMODULES: set[str] = set() +_SUBMODULES: set[str] = {"tokens"} _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { "layout.box": ["box"], + "layout.theme": ["theme"], + "themes": ["Theme"], } __getattr__, __dir__, __all__ = lazy_loader.attach( diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py new file mode 100644 index 00000000000..7a0a33444ef --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py @@ -0,0 +1,211 @@ +"""A theme: an element whose subtree has an accent, a gray, a radius and so on.""" + +from __future__ import annotations + +from typing import Any, ClassVar + +from reflex_base.components.component import Component, field +from reflex_base.components.dynamic import is_rendering_dynamic_component +from reflex_base.components.tags import CommonTag +from reflex_base.plugins import get_plugin +from reflex_base.utils.exceptions import ConfigError +from reflex_base.utils.imports import ImportDict +from reflex_base.vars.base import Var +from reflex_base.vars.sequence import LiteralStringVar + +from reflex_components_ui.base import ( + MISSING_PLUGIN_ERROR, + ComponentStyles, + UIComponent, +) +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style.emit import props_call +from reflex_components_ui.styles.theme import APP_THEME +from reflex_components_ui.themes import ( + LiteralAccentColor, + LiteralAppearance, + LiteralGrayColor, + LiteralPanelBackground, + LiteralRadius, + LiteralScaling, + ThemeError, + ThemeStyles, + app_theme_styles, + theme_styles, +) + + +class ThemeElement(UIComponent): + """A block whose content follows a theme of its own. + + An option that is left out is inherited from the theme around the element. + """ + + tag = "div" + + accent_color: LiteralAccentColor | Var[LiteralAccentColor] | None = field( + default=None, + is_javascript_property=False, + doc="The color of the components that stand out.", + ) + + gray_color: LiteralGrayColor | Var[LiteralGrayColor] | None = field( + default=None, + is_javascript_property=False, + doc='The gray of text, borders and surfaces. "auto" is the gray that matches the accent color.', + ) + + radius: LiteralRadius | Var[LiteralRadius] | None = field( + default=None, + is_javascript_property=False, + doc='How round corners are: "none" | "small" | "medium" | "large" | "full".', + ) + + scaling: LiteralScaling | Var[LiteralScaling] | None = field( + default=None, + is_javascript_property=False, + doc='The size of everything: "90%" | "95%" | "100%" | "105%" | "110%".', + ) + + appearance: LiteralAppearance | Var[LiteralAppearance] | None = field( + default=None, + is_javascript_property=False, + doc='"light" or "dark" to keep one whatever the color mode, "inherit" to follow it.', + ) + + panel_background: ( + LiteralPanelBackground | Var[LiteralPanelBackground] | None + ) = field( + default=None, + is_javascript_property=False, + doc='Whether panels such as cards are see-through: "solid" | "translucent".', + ) + + has_background: bool | Var[bool] | None = field( + default=None, + is_javascript_property=False, + doc="Whether the element paints the background of the theme. Defaults to True when it sets an appearance.", + ) + + @classmethod + def _display_name(cls) -> str: + """Get the name an app refers to the component by. + + Returns: + ``rx.ui.theme``. + """ + return "rx.ui.theme" + + def _theme_styles(self) -> ThemeStyles: + """Work out the StyleX themes of the element. + + Returns: + What the element needs to carry its theme. + + Raises: + ConfigError: If the plugin that compiles the styles is not configured. + ThemeError: If the element is rendered from state. + """ + plugin = get_plugin(UIPlugin) + if plugin is None: + raise ConfigError(MISSING_PLUGIN_ERROR) + if is_rendering_dynamic_component(): + msg = ( + f"{self._display_name()}: a theme rendered from state cannot be " + "applied: its code is evaluated in the browser and never " + "reaches the StyleX compiler. Render the theme in a page, and " + "what comes from state inside it." + ) + raise ThemeError(msg) + return self._resolve_theme_styles(plugin) + + def _resolve_theme_styles(self, plugin: UIPlugin) -> ThemeStyles: + """Work out the StyleX themes of the options of the element. + + Args: + plugin: The configured plugin. + + Returns: + What the element needs to carry its theme. + """ + return theme_styles( + self._display_name(), + accent_color=self.accent_color, + gray_color=self.gray_color, + radius=self.radius, + scaling=self.scaling, + appearance=self.appearance, + panel_background=self.panel_background, + has_background=self.has_background, + app_theme=plugin.theme, + ) + + def add_imports(self) -> list[ImportDict]: + """Import StyleX and the StyleX themes of the element. + + Returns: + The imports. + """ + return [super().add_imports(), self._theme_styles().import_dict()] + + def add_custom_code(self) -> list[str]: + """Declare what the element's style and its themes refer to. + + Returns: + The declaration of the style, then the maps an option bound to + state is looked up in. + """ + return [*super().add_custom_code(), *self._theme_styles().declarations] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the element with its themes and its style. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with one ``stylex.props`` spread. + """ + tag = Component._render(self, props) + theme = self._theme_styles() + style = self._stylex() + refs = theme.refs if style is None else (*theme.refs, style.ref) + own = tag.props.get("className") + if own is None or isinstance(own, LiteralStringVar): + names = theme.class_name + if own is not None and own._var_value: + names = f"{names} {own._var_value}" if names else own._var_value + return tag.remove_props("className").set( + special_props=[ + *tag.special_props, + Var(props_call(refs, names), _var_data=theme.var_data), + ] + ) + return tag.add_props( + class_name=Var( + # Parenthesized: the expression may be a conditional. + f'({own!s}) + " " + {props_call(refs, theme.class_name)}.className', + _var_type=str, + _var_data=own._get_all_var_data(), + )._replace(merge_var_data=theme.var_data) + ) + + +class AppTheme(ThemeElement): + """The element around an app, which carries the theme of the plugin.""" + + styles: ClassVar[ComponentStyles] = APP_THEME + + def _resolve_theme_styles(self, plugin: UIPlugin) -> ThemeStyles: + """Work out the StyleX themes of the theme of the app. + + Args: + plugin: The configured plugin. + + Returns: + What the element needs: every option of the theme is set. + """ + return app_theme_styles(plugin.theme) + + +theme = ThemeElement.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/plugin.py b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py index af36a153004..9a8ad1fa0b5 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/plugin.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py @@ -5,9 +5,10 @@ import dataclasses from collections.abc import Sequence from pathlib import Path +from typing import Any from reflex_base.constants import Dirs, Ext, PageNames -from reflex_base.plugins import Plugin, VitePluginEntry +from reflex_base.plugins import PageContext, Plugin, VitePluginEntry from reflex_components_ui.constants import ( JS_SRC, @@ -15,10 +16,16 @@ STYLEX_VERSION, WEB_DIR, ) +from reflex_components_ui.themes import Theme # Declares the cascade layers, so it comes before any stylesheet that names one. BASE_STYLESHEET_IMPORT = f"@import url('../{WEB_DIR}/base.css');" +# Where the element that carries the theme of the app goes among the elements +# around every page: inside the theme of Radix Themes, which is at 20, so that +# a page with components of both follows this one. +APP_THEME_WRAP = (15, "ReflexUITheme") + # The cascade layer the styles of the components are compiled into. CSS_LAYER = "reflex-ui" @@ -57,11 +64,6 @@ def add_base_stylesheet(content: str) -> str: return "\n".join(lines) -@dataclasses.dataclass -class Theme: - """The look of the rx.ui components across an app. It has no options yet.""" - - @dataclasses.dataclass class UIPlugin(Plugin): """Compile the styles of the rx.ui components into the app's stylesheet. @@ -125,3 +127,15 @@ def pre_compile(self, **context) -> None: str(Path(Dirs.STYLES) / (PageNames.STYLESHEET_ROOT + Ext.CSS)), add_base_stylesheet, ) + + def compile_page(self, page_ctx: PageContext, /, **kwargs: Any) -> None: + """Wrap the app in the element that carries its theme. + + Args: + page_ctx: The page being compiled. + **kwargs: The context for the plugin. + """ + # The component imports this module for the plugin it needs. + from reflex_components_ui.layout.theme import AppTheme + + page_ctx.app_wrap_components[APP_THEME_WRAP] = AppTheme.create() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py b/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py index f9340efa21a..2fca5764c3a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py @@ -32,12 +32,14 @@ from reflex_base.breakpoints import Breakpoints, breakpoint_names, breakpoints_values from reflex_base.constants.base import REFLEX_VAR_OPENING_TAG -from reflex_base.constants.colors import COLORS, Color +from reflex_base.constants.colors import Color from reflex_base.style import media_query from reflex_base.utils import format from reflex_base.utils.exceptions import ReflexError from reflex_base.vars.base import LiteralVar, Var +from reflex_components_ui._radix_tokens import VAR_GROUPS +from reflex_components_ui.constants import WEB_DIR from reflex_components_ui.style._css_props import ( CSS_PROPS, PSEUDO_CLASSES, @@ -68,14 +70,29 @@ class StyleError(ReflexError, ValueError): # The module whose import emits the CSS of a custom property, by the first word -# of the property's name: ``var(--ruby-9)`` needs the ruby scale. The accent -# scale is an alias the theme defines, so it has no module of its own. +# of the property's name: ``var(--ruby-9)`` needs the ruby scale, and +# ``var(--font-size-2)`` the typography tokens. VAR_MODULES: dict[str, str] = { - scale: f"$/reflex-ui/colors/{scale}.stylex.js" - for scale in sorted(COLORS - {"accent"}) + name[2:].partition("-")[0]: f"$/{WEB_DIR}/{module}" + for module, names in VAR_GROUPS.values() + for name in names } -_VAR_NAME = re.compile(r"var\(--([a-z]+)-") +# The custom properties that hold one value, which a shorthand can give to a +# longhand. A shadow and a font family are lists, and the panel properties +# are empty or invalid by design. +_MULTIPLE_VALUES = re.compile( + r"--shadow-|--panel-solid$|--backdrop-filter-panel$|--color-panel-if-solid$" + r"|-font-family$" +) +_SINGLE_VALUE_VARS: frozenset[str] = frozenset([ + f"var({name})" + for _, names in VAR_GROUPS.values() + for name in names + if not _MULTIPLE_VALUES.search(name) +]) + +_VAR_NAME = re.compile(r"var\(--([a-z]+)[-),]") _IDENTIFIER = re.compile(r"-?[A-Za-z_][\w-]*") _PARENTHESISED = re.compile(r"\([^()]*\)") _COMBINATOR = re.compile(r"[\s>+~,&]") @@ -413,12 +430,18 @@ def _split(value: str) -> list[str] | None: Returns: The values, or None when the value cannot be split safely: a custom - property may hold several values, and a slash or a comma separates - groups of them. + property may hold several values unless it is a design token known to + hold one, and a slash or a comma separates groups of them. """ - if "var(" in value or "/" in value or "," in value or "!" in value: + if "/" in value or "," in value or "!" in value: return None - return _tokens(value) + tokens = _tokens(value) + if "var(" in value: + single = _SINGLE_VALUE_VARS + for token in tokens: + if "var(" in token and token not in single: + return None + return tokens def _cannot_split(name: str, key: str, value: Any, instead: str) -> StyleError: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py new file mode 100644 index 00000000000..2c232938470 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py @@ -0,0 +1,13 @@ +"""The look of the element that carries the theme of an app.""" + +from reflex_components_ui.base import ComponentStyles + +# What Radix Themes gives its root theme: the background covers the page, and +# the content stacks under what is rendered beside it, such as a toast. +APP_THEME: ComponentStyles = { + "base": { + "position": "relative", + "zIndex": 0, + "minHeight": "100vh", + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/themes.py b/packages/reflex-components-ui/src/reflex_components_ui/themes.py new file mode 100644 index 00000000000..474119b9b7d --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/themes.py @@ -0,0 +1,505 @@ +"""The options of a theme, and the StyleX themes each of them applies. + +A theme element is a plain element that carries the class of a StyleX theme +for each option it sets. The themes are generated modules of the javascript +package, listed in ``_radix_tokens``: an element imports the ones it names, +and the build emits the CSS of nothing else. +""" + +from __future__ import annotations + +import dataclasses +import json +from collections.abc import Mapping +from typing import Any, Literal, get_args + +from reflex_base.utils.exceptions import ReflexError +from reflex_base.utils.imports import ImportDict, ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData + +from reflex_components_ui import _radix_tokens +from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.style.lower import _suggest + +LiteralAccentColor = Literal[ + "tomato", + "red", + "ruby", + "crimson", + "pink", + "plum", + "purple", + "violet", + "iris", + "indigo", + "blue", + "cyan", + "teal", + "jade", + "green", + "grass", + "brown", + "orange", + "sky", + "mint", + "lime", + "yellow", + "amber", + "gold", + "bronze", + "gray", +] +LiteralGrayColor = Literal["auto", "gray", "mauve", "slate", "sage", "olive", "sand"] +LiteralRadius = Literal["none", "small", "medium", "large", "full"] +LiteralScaling = Literal["90%", "95%", "100%", "105%", "110%"] +LiteralAppearance = Literal["inherit", "light", "dark"] +LiteralPanelBackground = Literal["solid", "translucent"] + +# The values of each option, in the order an error message lists them. +OPTIONS: dict[str, tuple[str, ...]] = { + "accent_color": get_args(LiteralAccentColor), + "gray_color": get_args(LiteralGrayColor), + "radius": get_args(LiteralRadius), + "scaling": get_args(LiteralScaling), + "appearance": get_args(LiteralAppearance), + "panel_background": get_args(LiteralPanelBackground), +} + +# The name the styles of a theme element are imported under: `theme` is what +# an app with Radix Themes imports its own theme as. +_THEME_STYLES = "reflexUITheme" + +# The module-level maps an option bound to state is looked up in. +_ACCENT_MAP = "reflexUIAccents" +_GRAY_MAP = "reflexUIGrays" +_MATCHING_GRAY_MAP = "reflexUIMatchingGrays" +_RADIUS_MAP = "reflexUIRadii" +_SCALING_MAP = "reflexUIScalings" +_PANEL_MAP = "reflexUIPanels" + + +class ThemeError(ReflexError, ValueError): + """A theme option that cannot be applied.""" + + +def _check(name: str, option: str, value: object) -> None: + """Fail on a value an option does not take. + + Args: + name: What the option was given to, which starts the error message. + option: The option. + value: Its value. + + Raises: + ThemeError: If the value is not one of the option's. + """ + values = OPTIONS[option] + if value.__class__ is str and value in values: + return + if isinstance(value, Var): + msg = ( + f"{name}: {option} is bound to state, but the theme of an app is " + "compiled ahead of time. Give it one of its values, or bind the " + "option of an rx.ui.theme(...) around the page." + ) + raise ThemeError(msg) + shown = f'"{value}"' if isinstance(value, str) else repr(value) + suggestion = _suggest(value, values) if isinstance(value, str) else "" + choices = ", ".join([f'"{choice}"' for choice in values]) + msg = f"{name}: unknown {option} {shown}.{suggestion} The values are {choices}." + raise ThemeError(msg) + + +def _check_flag(name: str, option: str, value: object) -> None: + """Fail on a value that is not a boolean. + + Args: + name: What the option was given to, which starts the error message. + option: The option. + value: Its value. + + Raises: + ThemeError: If the value is not True or False. + """ + if value.__class__ is not bool: + msg = f"{name}: {option} must be True or False, not {value!r}." + raise ThemeError(msg) + + +@dataclasses.dataclass(frozen=True) +class Theme: + """The look of the rx.ui components across an app. + + Attributes: + accent_color: The color of the components that stand out. + gray_color: The gray of text, borders and surfaces. ``"auto"`` is the + gray that matches the accent color. + radius: How round corners are. + scaling: The size of everything, relative to the default. + appearance: ``"light"`` or ``"dark"`` to keep one whatever the color + mode of the app, ``"inherit"`` to follow it. + panel_background: Whether panels such as cards are see-through. + has_background: Whether the theme paints the background of the page. + """ + + accent_color: LiteralAccentColor = "blue" + gray_color: LiteralGrayColor = "auto" + radius: LiteralRadius = "medium" + scaling: LiteralScaling = "100%" + appearance: LiteralAppearance = "inherit" + panel_background: LiteralPanelBackground = "translucent" + has_background: bool = True + + def __post_init__(self): + """Check every option, so that a mistake stops the app where it is made. + + Raises: + ThemeError: If an option has a value it does not take. + """ + for option in OPTIONS: + _check("rx.ui.Theme", option, getattr(self, option)) + _check_flag("rx.ui.Theme", "has_background", self.has_background) + + +@dataclasses.dataclass(frozen=True, slots=True) +class ThemeStyles: + """What an element needs to carry a theme. + + Attributes: + refs: The arguments of ``stylex.props``, the last one winning. + imports: The module, the export and the local name of each StyleX + theme the arguments name. + declarations: The module-level statements the arguments rely on. + class_name: The class names the element carries beside the compiled + ones. + var_data: The state the arguments read. + """ + + refs: tuple[str, ...] + imports: tuple[tuple[str, str, str | None], ...] + declarations: tuple[str, ...] = () + class_name: str | None = None + var_data: VarData | None = None + + def import_dict(self) -> ImportDict: + """Get the imports in the form a component returns them. + + Returns: + The exports to import from each module of the javascript package. + """ + modules: dict[str, list[ImportVar]] = {} + for module, export, alias in self.imports: + modules.setdefault(f"$/{WEB_DIR}/{module}", []).append( + ImportVar(tag=export, alias=alias) + ) + return dict(modules) + + +class _Builder: + """Collects the themes of one element. + + Attributes: + name: What the options were given to, which starts an error message. + refs: The arguments of ``stylex.props`` so far. + imports: The StyleX themes the arguments name. + declarations: The module-level statements the arguments rely on. + var_data: The state the arguments read. + """ + + __slots__ = ("declarations", "imports", "name", "refs", "var_data") + + def __init__(self, name: str): + """Start with nothing. + + Args: + name: What the options were given to. + """ + self.name = name + self.refs: list[str] = [] + self.imports: set[tuple[str, str, str | None]] = set() + self.declarations: list[str] = [] + self.var_data: list[VarData | None] = [] + + def add(self, theme: tuple[str, str], alias: str | None = None) -> str: + """Import a StyleX theme. + + Args: + theme: The module and the export. + alias: The local name, when it is not the export. + + Returns: + The local name. + """ + self.imports.add((*theme, alias)) + return alias or theme[1] + + def bound(self, value: Var) -> str: + """Read an option from state. + + Args: + value: The Var the option is bound to. + + Returns: + The expression of its value. + """ + self.var_data.append(value._get_all_var_data()) + return str(value) + + def lookup( + self, map_name: str, themes: Mapping[str, tuple[str, str]], value: Var + ) -> str: + """Choose among every theme of an option where the page runs. + + Args: + map_name: The name of the module-level map of the themes. + themes: The theme of each value: every one of them is imported. + value: The Var that holds the value. + + Returns: + The expression of the chosen theme. + """ + entries = ", ".join([ + f"{json.dumps(key)}: {self.add(theme)}" for key, theme in themes.items() + ]) + self.declarations.append(f"const {map_name} = {{ {entries} }};") + return f"{map_name}[{self.bound(value)}]" + + def pick( + self, + option: str, + value: Any, + themes: Mapping[str, tuple[str, str]], + map_name: str, + ) -> None: + """Apply the theme of one option. + + Args: + option: The option. + value: Its value: None when it is inherited, or a Var. + themes: The theme of each value. + map_name: The name of the map a Var is looked up in. + """ + if value is None: + return + if isinstance(value, Var): + self.refs.append(self.lookup(map_name, themes, value)) + else: + _check(self.name, option, value) + self.refs.append(self.add(themes[value])) + + def finish(self, class_name: str | None = None) -> ThemeStyles: + """Wrap up what was collected. + + Args: + class_name: The class names the element also carries. + + Returns: + What the element needs. + """ + return ThemeStyles( + refs=tuple(self.refs), + imports=tuple(sorted(self.imports, key=lambda item: item[:2])), + declarations=tuple(self.declarations), + class_name=class_name, + var_data=VarData.merge(*self.var_data), + ) + + +def _literal(value: Any) -> Any: + """Read a Var that holds a constant as the constant. + + Args: + value: The value of an option. + + Returns: + The constant, or the value as given. + """ + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + return value._var_value + return value + + +def theme_styles( + name: str, + *, + accent_color: Any = None, + gray_color: Any = None, + radius: Any = None, + scaling: Any = None, + appearance: Any = None, + panel_background: Any = None, + has_background: Any = None, + app_theme: Theme | None = None, +) -> ThemeStyles: + """Work out the StyleX themes of a theme element. + + An option that is None is inherited: the element sets nothing for it. + A literal option imports the one theme it names. An option bound to state + imports every theme it could name and chooses among them where the page + runs. + + The cascade does not tell an element what it inherits, so two things are + resolved against the theme of the app, which is what a theme inherits + unless another one stands between them: + + - An accent color without a gray color takes the gray that matches it when + the gray of the app is ``"auto"``, as ``gray_color="auto"`` does. + - A gray color without an accent color names the gray accent again when + the accent of the app is gray: that accent is the gray of the element + it was declared on. + + Args: + name: What the options were given to, which starts an error message. + accent_color: The accent color. + gray_color: The gray color. + radius: The radius. + scaling: The scaling. + appearance: The appearance. + panel_background: The panel background. + has_background: Whether the element paints the background of the + theme. None paints it when the element sets an appearance. + app_theme: The theme of the app. + + Returns: + What the element needs to carry the theme. + + Raises: + ThemeError: If an option has a value it does not take. + """ + tokens = _radix_tokens + builder = _Builder(name) + accent_color = _literal(accent_color) + gray_color = _literal(gray_color) + appearance = _literal(appearance) + has_background = _literal(has_background) + + for scope in tokens.SCOPE_THEMES: + builder.refs.append(builder.add(scope)) + builder.refs.append(builder.add(tokens.FOCUS_THEME)) + + if gray_color is None: + if accent_color is not None and app_theme and app_theme.gray_color == "auto": + gray_color = "auto" + elif not isinstance(gray_color, Var): + _check(name, "gray_color", gray_color) + if accent_color is None: + if gray_color is not None and app_theme and app_theme.accent_color == "gray": + accent_color = "gray" + elif not isinstance(accent_color, Var): + _check(name, "accent_color", accent_color) + + builder.pick("accent_color", accent_color, tokens.ACCENT_THEMES, _ACCENT_MAP) + if gray_color.__class__ is str and gray_color == "auto": + matching = tokens.MATCHING_GRAY + if isinstance(accent_color, Var): + builder.refs.append( + builder.lookup( + _MATCHING_GRAY_MAP, + { + accent: tokens.GRAY_THEMES[gray] + for accent, gray in matching.items() + }, + accent_color, + ) + ) + else: + if accent_color is None: + if app_theme is None: + msg = ( + f'{name}: gray_color "auto" is the gray that matches an ' + "accent color. Give accent_color too, or name the gray." + ) + raise ThemeError(msg) + accent_color = app_theme.accent_color + builder.refs.append(builder.add(tokens.GRAY_THEMES[matching[accent_color]])) + else: + builder.pick("gray_color", gray_color, tokens.GRAY_THEMES, _GRAY_MAP) + builder.pick("radius", radius, tokens.RADIUS_THEMES, _RADIUS_MAP) + builder.pick("scaling", scaling, tokens.SCALING_THEMES, _SCALING_MAP) + builder.pick( + "panel_background", + panel_background, + tokens.PANEL_BACKGROUND_THEMES, + _PANEL_MAP, + ) + + module, export, _ = tokens.THEME_STYLES + styles = builder.add((module, export), _THEME_STYLES) + builder.refs.append(f"{styles}.root") + class_name = None + bound_appearance = None + if isinstance(appearance, Var): + bound_appearance = builder.bound(appearance) + elif appearance is not None: + _check(name, "appearance", appearance) + if appearance != "inherit": + # Radix Themes and Tailwind select on the class: a component of + # either inside this element follows the appearance too. + class_name = appearance + if isinstance(has_background, Var): + builder.refs.append(f"({builder.bound(has_background)}) && {styles}.background") + elif has_background is None: + if bound_appearance is not None: + builder.refs.append( + f'({bound_appearance}) !== "inherit" && {styles}.background' + ) + elif class_name is not None: + builder.refs.append(f"{styles}.background") + else: + _check_flag(name, "has_background", has_background) + if has_background: + builder.refs.append(f"{styles}.background") + if bound_appearance is not None: + builder.refs.extend(( + f"{styles}[{bound_appearance}]", + f'({bound_appearance}) !== "inherit" && ' + f"{{ $$css: true, appearance: {bound_appearance} }}", + )) + elif class_name is not None: + builder.refs.append(f"{styles}.{class_name}") + return builder.finish(class_name) + + +def app_theme_styles(theme: Theme) -> ThemeStyles: + """Work out the StyleX themes of the element that wraps an app. + + Args: + theme: The theme of the app. + + Returns: + What the element needs: every option is set, so that nothing depends + on what is around the app. + """ + return theme_styles("rx.ui.Theme", **dataclasses.asdict(theme)) + + +def color_scheme_styles(name: str, color_scheme: Any) -> ThemeStyles: + """Work out the StyleX themes of a component with a color of its own. + + Args: + name: The display name of the component, which starts an error message. + color_scheme: The accent color of the component, or a Var holding it. + + Returns: + What the element needs: the accent, and the focus colors that follow + it. A gray component keeps the focus colors of the theme, as it does + in Radix Themes. + + Raises: + ThemeError: If the color is not an accent color. + """ + tokens = _radix_tokens + builder = _Builder(name) + color_scheme = _literal(color_scheme) + if isinstance(color_scheme, Var): + builder.refs.append( + builder.lookup(_ACCENT_MAP, tokens.ACCENT_THEMES, color_scheme) + ) + focus = builder.add(tokens.FOCUS_THEME) + builder.refs.append(f'({builder.bound(color_scheme)}) !== "gray" && {focus}') + else: + _check(name, "color_scheme", color_scheme) + builder.refs.append(builder.add(tokens.ACCENT_THEMES[color_scheme])) + if color_scheme != "gray": + builder.refs.append(builder.add(tokens.FOCUS_THEME)) + return builder.finish() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/tokens.py b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py new file mode 100644 index 00000000000..c68b4c4f5e0 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py @@ -0,0 +1,551 @@ +"""The design tokens of the rx.ui components, as values of a style. + +A token is the CSS ``var()`` of a custom property, as a plain string, so it +goes wherever a CSS value does: the ``style`` of any component, the style +table of an rx.ui component, or inside a larger value such as +``f"calc({tokens.space[4]} * 2)"``. + + rx.ui.tokens.space[4] "var(--space-4)" + rx.ui.tokens.accent[9] "var(--accent-9)" + rx.ui.tokens.accent.a[3] "var(--accent-a3)" + rx.ui.tokens.accent.contrast "var(--accent-contrast)" + rx.ui.tokens.font_weight.bold "var(--font-weight-bold)" + +The names and the values are the ones of Radix Themes. A step that does not +exist and a name that is misspelt are errors to a type checker, and raise a +``TokenError`` that lists what exists. +""" + +from __future__ import annotations + +from typing import Literal, NoReturn + +from reflex_base.utils.exceptions import ReflexError + +from reflex_components_ui.style.lower import _suggest + +Step6 = Literal[1, 2, 3, 4, 5, 6] +Step9 = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9] +Step12 = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + +LiteralColorScale = Literal[ + "tomato", + "red", + "ruby", + "crimson", + "pink", + "plum", + "purple", + "violet", + "iris", + "indigo", + "blue", + "cyan", + "teal", + "jade", + "green", + "grass", + "brown", + "orange", + "sky", + "mint", + "lime", + "yellow", + "amber", + "gold", + "bronze", + "mauve", + "slate", + "sage", + "olive", + "sand", +] + + +class TokenError(ReflexError, AttributeError, LookupError): + """A design token that does not exist.""" + + +class _Tokens: + """A group of tokens: named ones as attributes, and steps by number. + + Attributes: + _path: How an app refers to the group, which starts an error message. + _steps: The token of each step, the first one being step 1. + """ + + _path: str + _steps: tuple[str, ...] + + def __init__(self, path: str, prefix: str, steps: int = 0, infix: str = ""): + """Name the steps of the group. + + Args: + path: How an app refers to the group. + prefix: What the custom properties of the group start with. + steps: How many steps the group has. + infix: What comes between the prefix and the number of a step. + """ + self._path = path + self._steps = tuple([ + f"var(--{prefix}-{infix}{step})" for step in range(1, steps + 1) + ]) + + def _step(self, step: int) -> str: + """Get the token of a step. + + Args: + step: The number of the step. + + Returns: + The token. + + Raises: + TokenError: If the group has no such step. + """ + # A bool is an int, and a negative number would count from the end. + if step.__class__ is int and 0 < step <= len(self._steps): + return self._steps[step - 1] + if self._steps: + msg = ( + f"{self._path} has no step {step!r}. Its steps are 1 to " + f"{len(self._steps)}." + ) + else: + msg = f"{self._path} has no steps. Its tokens are {self._names()}." + raise TokenError(msg) + + def _names(self) -> str: + """List the named tokens of the group. + + Returns: + Their names, for an error message. + """ + return ", ".join(sorted([name for name in vars(self) if name[0] != "_"])) + + def __getitem__(self, step: int) -> str: + """Get the token of a step. + + Args: + step: The number of the step. + + Returns: + The token. + """ + return self._step(step) + + def __getattr__(self, name: str) -> NoReturn: + """Fail on a token the group does not have. + + Args: + name: The name that was asked for. + + Raises: + AttributeError: For a private name, which python and the standard + library probe and no token has. + TokenError: For any other name: python only gets here for a + missing one. + """ + if name[:1] == "_": + raise AttributeError(name) + msg = f'{self._path} has no token "{name}".{_suggest(name, vars(self))}' + if names := self._names(): + msg += f" Its tokens are {names}" + if self._steps: + msg += f", and the steps [1] to [{len(self._steps)}]" + msg += "." + else: + msg += f" Its tokens are the steps [1] to [{len(self._steps)}]." + raise TokenError(msg) + + +class _Steps6(_Tokens): + """Tokens of a scale of six steps.""" + + def __getitem__(self, step: Step6) -> str: + """Get the token of a step. + + Args: + step: The number of the step, from 1 to 6. + + Returns: + The token. + """ + return self._step(step) + + +class _Steps9(_Tokens): + """Tokens of a scale of nine steps.""" + + def __getitem__(self, step: Step9) -> str: + """Get the token of a step. + + Args: + step: The number of the step, from 1 to 9. + + Returns: + The token. + """ + return self._step(step) + + +class _Steps12(_Tokens): + """Tokens of a scale of twelve steps.""" + + def __getitem__(self, step: Step12) -> str: + """Get the token of a step. + + Args: + step: The number of the step, from 1 to 12. + + Returns: + The token. + """ + return self._step(step) + + +class _Radius(_Steps6): + """The radius scale, and what the radius of a theme sets. + + Attributes: + factor: What the radius of the theme multiplies every step by. + full: The radius of a pill, when the radius of the theme is full. + thumb: The radius of the thumb of a switch or a slider. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.radius", "radius", 6) + self.factor = "var(--radius-factor)" + self.full = "var(--radius-full)" + self.thumb = "var(--radius-thumb)" + + +class _FontWeight(_Tokens): + """The font weights. + + Attributes: + light: The light weight. + regular: The weight of body text. + medium: The weight of labels and buttons. + bold: The weight of headings. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.font_weight", "font-weight") + self.light = "var(--font-weight-light)" + self.regular = "var(--font-weight-regular)" + self.medium = "var(--font-weight-medium)" + self.bold = "var(--font-weight-bold)" + + +class _Alpha(_Steps12): + """The translucent steps of a color scale.""" + + +class _AlphaScale(_Tokens): + """A scale that only has translucent steps: black and white. + + Attributes: + a: The translucent steps. + """ + + def __init__(self, name: str): + """Name the tokens. + + Args: + name: The name of the scale. + """ + path = f"rx.ui.tokens.{name}" + super().__init__(path, name) + self.a = _Alpha(f"{path}.a", name, 12, "a") + + +class _Focus(_Steps12): + """The colors of a focus ring, which follow the accent. + + Attributes: + a: The translucent steps. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.focus", "focus", 12) + self.a = _Alpha("rx.ui.tokens.focus.a", "focus", 12, "a") + + +class _Scale(_Steps12): + """A color scale: twelve steps, from a background to high-contrast text. + + Attributes: + a: The translucent steps. + contrast: The color of text on step 9. + surface: The background of a translucent surface. + indicator: The color of an indicator, such as a checked checkbox. + track: The color of a track, such as the filled part of a slider. + """ + + def __init__(self, path: str, name: str): + """Name the tokens. + + Args: + path: How an app refers to the scale. + name: The name of the scale. + """ + super().__init__(path, name, 12) + self.a = _Alpha(f"{path}.a", name, 12, "a") + self.contrast = f"var(--{name}-contrast)" + self.surface = f"var(--{name}-surface)" + self.indicator = f"var(--{name}-indicator)" + self.track = f"var(--{name}-track)" + + +class _Color(_Tokens): + """The colors with a role of their own. + + Attributes: + background: The background of the page. + overlay: The backdrop of a dialog. + panel: The background of a panel, as the theme sets it. + panel_solid: The background of an opaque panel. + panel_translucent: The background of a see-through panel. + panel_if_solid: The opaque background when the theme sets it, and + nothing otherwise. + surface: The background of a form control. + transparent: A color that paints nothing. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.color", "color") + self.background = "var(--color-background)" + self.overlay = "var(--color-overlay)" + self.panel = "var(--color-panel)" + self.panel_solid = "var(--color-panel-solid)" + self.panel_translucent = "var(--color-panel-translucent)" + self.panel_if_solid = "var(--color-panel-if-solid)" + self.surface = "var(--color-surface)" + self.transparent = "var(--color-transparent)" + + +class _Cursor(_Tokens): + """The cursor over each kind of control. + + Attributes: + button: Over a button. + checkbox: Over a checkbox. + disabled: Over a disabled control. + link: Over a link. + menu_item: Over an item of a menu. + radio: Over a radio button. + slider_thumb: Over the thumb of a slider. + slider_thumb_active: Over the thumb of a slider while it is dragged. + switch: Over a switch. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.cursor", "cursor") + self.button = "var(--cursor-button)" + self.checkbox = "var(--cursor-checkbox)" + self.disabled = "var(--cursor-disabled)" + self.link = "var(--cursor-link)" + self.menu_item = "var(--cursor-menu-item)" + self.radio = "var(--cursor-radio)" + self.slider_thumb = "var(--cursor-slider-thumb)" + self.slider_thumb_active = "var(--cursor-slider-thumb-active)" + self.switch = "var(--cursor-switch)" + + +class _Panel(_Tokens): + """What the panel background of a theme sets. + + Attributes: + backdrop_filter: The backdrop filter of a panel. + solid: Empty when panels are opaque, and invalid otherwise: a value + that starts with it only applies to an opaque panel. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.panel", "panel") + self.backdrop_filter = "var(--backdrop-filter-panel)" + self.solid = "var(--panel-solid)" + + +class _Default(_Tokens): + """The typography of body text. + + Attributes: + font_family: The font family. + font_size: The font size. + font_style: The font style. + font_weight: The font weight. + line_height: The line height. + letter_spacing: The letter spacing. + leading_trim_start: The space to take off above the first line. + leading_trim_end: The space to take off below the last line. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.default", "default") + self.font_family = "var(--default-font-family)" + self.font_size = "var(--default-font-size)" + self.font_style = "var(--default-font-style)" + self.font_weight = "var(--default-font-weight)" + self.line_height = "var(--default-line-height)" + self.letter_spacing = "var(--default-letter-spacing)" + self.leading_trim_start = "var(--default-leading-trim-start)" + self.leading_trim_end = "var(--default-leading-trim-end)" + + +class _Heading(_Tokens): + """The typography of headings. + + Attributes: + font_family: The font family. + font_size_adjust: What the font size is multiplied by. + font_style: The font style. + letter_spacing: The letter spacing, added to the one of the size. + leading_trim_start: The space to take off above the first line. + leading_trim_end: The space to take off below the last line. + line_height: The line height of each font size. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.heading", "heading") + self.font_family = "var(--heading-font-family)" + self.font_size_adjust = "var(--heading-font-size-adjust)" + self.font_style = "var(--heading-font-style)" + self.letter_spacing = "var(--heading-letter-spacing)" + self.leading_trim_start = "var(--heading-leading-trim-start)" + self.leading_trim_end = "var(--heading-leading-trim-end)" + self.line_height = _Steps9( + "rx.ui.tokens.heading.line_height", "heading-line-height", 9 + ) + + +class _Inline(_Tokens): + """The typography of an inline element: strong, em or quote. + + Attributes: + font_family: The font family. + font_size_adjust: What the font size is multiplied by. + font_style: The font style. + font_weight: The font weight. + letter_spacing: The letter spacing, added to the one of the size. + """ + + def __init__(self, name: str): + """Name the tokens. + + Args: + name: The element. + """ + super().__init__(f"rx.ui.tokens.{name}", name) + self.font_family = f"var(--{name}-font-family)" + self.font_size_adjust = f"var(--{name}-font-size-adjust)" + self.font_style = f"var(--{name}-font-style)" + self.font_weight = f"var(--{name}-font-weight)" + self.letter_spacing = f"var(--{name}-letter-spacing)" + + +class _Code(_Inline): + """The typography of code. + + Attributes: + padding_top: The padding above inline code. + padding_bottom: The padding below inline code. + padding_left: The padding before inline code. + padding_right: The padding after inline code. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("code") + self.padding_top = "var(--code-padding-top)" + self.padding_bottom = "var(--code-padding-bottom)" + self.padding_left = "var(--code-padding-left)" + self.padding_right = "var(--code-padding-right)" + + +class _Tab(_Tokens): + """The spacing that keeps a tab the same width when it becomes bold. + + Attributes: + active_letter_spacing: The letter spacing of the selected tab. + active_word_spacing: The word spacing of the selected tab. + inactive_letter_spacing: The letter spacing of the other tabs. + inactive_word_spacing: The word spacing of the other tabs. + """ + + def __init__(self): + """Name the tokens.""" + super().__init__("rx.ui.tokens.tab", "tab") + self.active_letter_spacing = "var(--tab-active-letter-spacing)" + self.active_word_spacing = "var(--tab-active-word-spacing)" + self.inactive_letter_spacing = "var(--tab-inactive-letter-spacing)" + self.inactive_word_spacing = "var(--tab-inactive-word-spacing)" + + +# The scale every size is multiplied by. +scaling = "var(--scaling)" + +space = _Steps9("rx.ui.tokens.space", "space", 9) +radius = _Radius() +shadow = _Steps6("rx.ui.tokens.shadow", "shadow", 6) + +font_size = _Steps9("rx.ui.tokens.font_size", "font-size", 9) +line_height = _Steps9("rx.ui.tokens.line_height", "line-height", 9) +letter_spacing = _Steps9("rx.ui.tokens.letter_spacing", "letter-spacing", 9) +font_weight = _FontWeight() +default = _Default() +heading = _Heading() +code = _Code() +strong = _Inline("strong") +em = _Inline("em") +quote = _Inline("quote") +tab = _Tab() + +# The accent and the gray of the theme the element is in. +accent = _Scale("rx.ui.tokens.accent", "accent") +gray = _Scale("rx.ui.tokens.gray", "gray") +focus = _Focus() +black = _AlphaScale("black") +white = _AlphaScale("white") +color = _Color() +panel = _Panel() +cursor = _Cursor() + +_SCALES: dict[str, _Scale] = {} + + +def scale(name: LiteralColorScale) -> _Scale: + """Get a color scale by its name, whatever the theme. + + Args: + name: The name of the scale, such as ``"ruby"``. + + Returns: + The tokens of the scale. + + Raises: + TokenError: If there is no such scale. + """ + found = _SCALES.get(name) + if found is None: + scales = LiteralColorScale.__args__ + if name not in scales: + shown = f'"{name}"' if isinstance(name, str) else repr(name) + suggestion = _suggest(name, scales) if isinstance(name, str) else "" + msg = ( + f"rx.ui.tokens.scale: unknown color scale {shown}.{suggestion} " + f"The scales are {', '.join(sorted(scales))}. The accent and the " + "gray of the theme are rx.ui.tokens.accent and rx.ui.tokens.gray." + ) + raise TokenError(msg) + found = _SCALES[name] = _Scale(f'rx.ui.tokens.scale("{name}")', name) + return found diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index ec03014faa6..1b39bfd65ed 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -7,6 +7,7 @@ from reflex_base.constants.colors import Color from reflex_base.vars.base import LiteralVar, Var from reflex_components_ui.style import _css_props +from reflex_components_ui._radix_tokens import VAR_GROUPS from reflex_components_ui.style.lower import ( _BORDERS, _EXPANSIONS, @@ -27,7 +28,9 @@ import reflex as rx RUBY = "$/reflex-ui/colors/ruby.stylex.js" -GRAY = "$/reflex-ui/colors/gray.stylex.js" +GRAY = "$/reflex-ui/tokens/gray.stylex.js" +ACCENT = "$/reflex-ui/tokens/accent.stylex.js" +SPACE = "$/reflex-ui/tokens/space.stylex.js" XS = "@media screen and (min-width: 30em)" SM = "@media screen and (min-width: 48em)" MD = "@media screen and (min-width: 62em)" @@ -202,7 +205,7 @@ def test_whole_dict_var_becomes_the_inline_style(): "paddingBottom": "var(--space-2)", "paddingLeft": "var(--space-2)", }, - (), + (SPACE,), StyleState.style, ) @@ -404,11 +407,11 @@ def test_responsive_values_follow_the_configured_breakpoints(): {"color": "var(--gray-11)"}, (GRAY,), ), - ({"color": rx.color("accent", 9)}, {"color": "var(--accent-9)"}, ()), + ({"color": rx.color("accent", 9)}, {"color": "var(--accent-9)"}, (ACCENT,)), ( {"outline": f"1px solid {rx.color('ruby', 6)}", "color": "var(--gray-a11)"}, {"outline": "1px solid var(--ruby-6)", "color": "var(--gray-a11)"}, - (GRAY, RUBY), + (RUBY, GRAY), ), ( { @@ -423,7 +426,7 @@ def test_responsive_values_follow_the_configured_breakpoints(): ":hover": {"default": "var(--ruby-9)", XS: "var(--ruby-10)"}, } }, - (GRAY, RUBY), + (RUBY, GRAY), ), ( {"border_color": rx.color("ruby", 6)}, @@ -438,7 +441,7 @@ def test_responsive_values_follow_the_configured_breakpoints(): ( {"color": "var(--my-color)", "width": "var(--space-4)"}, {"color": "var(--my-color)", "width": "var(--space-4)"}, - (), + (SPACE,), ), ( {"color": rx.color(SCALE, 9)}, @@ -462,50 +465,30 @@ def test_colors_and_tokens( assert lowered.imports == imports -def test_var_modules_name_a_module_per_color_scale(): - """Every Radix scale has a module, and a token can register its own.""" +def test_var_modules_name_the_module_of_every_custom_property(): + """Each custom property Radix defines is found by the first word of its name.""" assert VAR_MODULES["ruby"] == RUBY - assert sorted(VAR_MODULES) == [ - "amber", - "black", - "blue", - "bronze", - "brown", - "crimson", - "cyan", - "gold", - "grass", - "gray", - "green", - "indigo", - "iris", - "jade", - "lime", - "mauve", - "mint", - "olive", - "orange", - "pink", - "plum", - "purple", - "red", - "ruby", - "sage", - "sand", - "sky", - "slate", - "teal", - "tomato", - "violet", - "white", - "yellow", - ] - VAR_MODULES["space"] = "$/reflex-ui/tokens/space.stylex.js" - try: - lowered = lower("rx.ui.card", {"width": "calc(2 * var(--space-4))"}) - finally: - del VAR_MODULES["space"] - assert lowered.imports == ("$/reflex-ui/tokens/space.stylex.js",) + assert VAR_MODULES["gray"] == GRAY + for module, names in VAR_GROUPS.values(): + for name in names: + word = name.removeprefix("--").partition("-")[0] + assert VAR_MODULES[word] == f"$/reflex-ui/{module}", name + assert sorted(set(VAR_MODULES.values())) == sorted({ + f"$/reflex-ui/{module}" for module, _ in VAR_GROUPS.values() + }) + assert lower( + "rx.ui.card", + { + "width": "calc(2 * var(--space-4))", + "flex_grow": "var(--scaling)", + "font_size": "var(--font-size-2, 14px)", + "color": "var(--mine-1)", + }, + ).imports == ( + "$/reflex-ui/tokens/scaling.stylex.js", + "$/reflex-ui/tokens/space.stylex.js", + "$/reflex-ui/tokens/typography.stylex.js", + ) def _sides(prefix: str, suffix: str, *values: Any) -> dict[str, Any]: @@ -906,7 +889,10 @@ def test_layout_props(layout: dict[str, Any], expected: dict[str, Any]): layout: The layout props. expected: The lowered properties. """ - assert lower("rx.ui.flex", None, layout) == Lowered(expected) + lowered = lower("rx.ui.flex", None, layout) + assert lowered.style == expected + # Only a step of the space scale needs a module. + assert lowered.imports == ((SPACE,) if "var(--space-" in repr(expected) else ()) def test_layout_props_are_merged_under_the_style(): @@ -915,15 +901,18 @@ def test_layout_props_are_merged_under_the_style(): "rx.ui.flex", {"padding_top": "1px", "_hover": {"row_gap": "0"}, "margin": WIDTH}, {"p": "2", "gap": "3", "mt": "1"}, - ) == Lowered({ - "paddingTop": "1px", - "paddingRight": "var(--space-2)", - "paddingBottom": "var(--space-2)", - "paddingLeft": "var(--space-2)", - "rowGap": {"default": "var(--space-3)", ":hover": "0"}, - "columnGap": "var(--space-3)", - "margin": WIDTH, - }) + ) == Lowered( + { + "paddingTop": "1px", + "paddingRight": "var(--space-2)", + "paddingBottom": "var(--space-2)", + "paddingLeft": "var(--space-2)", + "rowGap": {"default": "var(--space-3)", ":hover": "0"}, + "columnGap": "var(--space-3)", + "margin": WIDTH, + }, + (SPACE,), + ) assert ( frozenset({ "p", diff --git a/tests/units/reflex_components_ui/style/test_merge.py b/tests/units/reflex_components_ui/style/test_merge.py index 2a5cdad8429..0838af762a8 100644 --- a/tests/units/reflex_components_ui/style/test_merge.py +++ b/tests/units/reflex_components_ui/style/test_merge.py @@ -1,5 +1,6 @@ """Tests for merging the style table of a component with a user's style.""" +import re from typing import Any import pytest @@ -16,6 +17,11 @@ import reflex as rx RUBY = "$/reflex-ui/colors/ruby.stylex.js" +SPACE = "$/reflex-ui/tokens/space.stylex.js" +ACCENT = "$/reflex-ui/tokens/accent.stylex.js" +GRAY = "$/reflex-ui/tokens/gray.stylex.js" +# The module of each token the expected styles of these tests name. +TOKEN_MODULES = {"ruby": RUBY, "space": SPACE, "accent": ACCENT, "gray": GRAY} XS = "@media screen and (min-width: 30em)" @@ -77,6 +83,24 @@ class MergeState(rx.State): "marginTop": "1px", "outlineWidth": "1px", } + + +def _lowered(style: dict[str, Any], inline: Any = None) -> Lowered: + """Build the lowered style a test expects, with the modules its values need. + + Args: + style: The lowered properties. + inline: A Var holding a whole dict of styles. + + Returns: + The lowered style, importing the module of every token it names. + """ + found = set(re.findall(r"var\(--([a-z]+)-", repr(style))) + return Lowered( + style, tuple(sorted([TOKEN_MODULES[word] for word in found])), inline + ) + + SOLID_BACKGROUND = {"default": "var(--accent-9)", ":hover": "var(--accent-10)"} DOT = Merged(Lowered({"top": 0})) LABEL = Merged(Lowered({"flexGrow": 1})) @@ -201,9 +225,7 @@ def test_merge_order(props: Any, style: Any, expected: dict[str, Any], parts: An parts: The merged styles of its inner elements. """ merged = merge("rx.ui.button", BUTTON, props, style) - imports = (RUBY,) if expected.get("backgroundColor") == "var(--ruby-3)" else () - assert merged == Merged(Lowered(expected, imports), (), parts) - assert merged.style.imports == imports + assert merged == Merged(_lowered(expected), (), parts) assert merged.dynamic == () assert list(merged.parts) == ["icon", "label"] @@ -217,7 +239,7 @@ def test_layout_props_merge_between_the_table_and_the_style(): {"margin_left": "auto"}, {"m": "2", "gap": "1"}, ) == Merged( - Lowered({ + _lowered({ "display": "inline-flex", "color": "black", "marginTop": "var(--space-2)", @@ -238,7 +260,7 @@ def test_whole_dict_var_style_is_carried_with_the_table_styles(): """A Var holding the user style leaves the table styles compiled.""" merged = merge("rx.ui.button", BUTTON, {"size": "1"}, MergeState.style) assert merged == Merged( - Lowered({**BASE, "height": "var(--space-5)"}, (), MergeState.style), + _lowered({**BASE, "height": "var(--space-5)"}, MergeState.style), (), SMALL_PARTS, ) @@ -278,7 +300,7 @@ def test_state_bound_variant_returns_every_value_unresolved(): {"color": "pink", "_hover": {"background_color": "red"}}, ) assert merged == Merged( - Lowered({ + _lowered({ **BASE, "color": "pink", "height": "var(--space-6)", @@ -289,23 +311,20 @@ def test_state_bound_variant_returns_every_value_unresolved(): ("variant",), (VARIANT,), { - ("solid",): Lowered({ + ("solid",): _lowered({ "backgroundColor": { "default": "var(--accent-9)", ":hover": "red", }, "fontWeight": "700", }), - ("soft",): Lowered( - { - "backgroundColor": { - "default": "var(--ruby-3)", - ":hover": "red", - } - }, - (RUBY,), - ), - ("ghost",): Lowered({"outline": "none", "outlineWidth": None}), + ("soft",): _lowered({ + "backgroundColor": { + "default": "var(--ruby-3)", + ":hover": "red", + } + }), + ("ghost",): _lowered({"outline": "none", "outlineWidth": None}), }, ), ), @@ -325,14 +344,14 @@ def test_independent_state_bound_props_are_separate_alternatives(): assert merge( "rx.ui.button", BUTTON, {"variant": "soft", "size": SIZE, "loading": LOADING} ) == Merged( - Lowered({**BASE, "backgroundColor": "var(--ruby-3)"}, (RUBY,)), + _lowered({**BASE, "backgroundColor": "var(--ruby-3)"}), ( Alternatives( ("size",), (SIZE,), { - ("1",): Lowered({"height": "var(--space-5)"}), - ("2",): Lowered({ + ("1",): _lowered({"height": "var(--space-5)"}), + ("2",): _lowered({ "height": "var(--space-6)", "color": {"default": "black", ":hover": "gray"}, }), @@ -341,15 +360,15 @@ def test_independent_state_bound_props_are_separate_alternatives(): Alternatives( ("loading",), (LOADING,), - {("true",): Lowered({"opacity": 0.5, "cursor": "wait"})}, + {("true",): _lowered({"opacity": 0.5, "cursor": "wait"})}, ), ), { "icon": Merged( - Lowered({"width": "1em"}), + _lowered({"width": "1em"}), ( Alternatives( - ("size",), (SIZE,), {("2",): Lowered({"width": "2em"})} + ("size",), (SIZE,), {("2",): _lowered({"width": "2em"})} ), ), {"dot": DOT}, @@ -362,7 +381,7 @@ def test_independent_state_bound_props_are_separate_alternatives(): def test_state_bound_props_that_depend_on_each_other_are_one_alternative(): """Props that share a property or a compound style are picked together.""" solid = {"backgroundColor": SOLID_BACKGROUND} - soft = Lowered({"backgroundColor": "var(--ruby-3)"}, (RUBY,)) + soft = _lowered({"backgroundColor": "var(--ruby-3)"}) ghost = {"outline": "none", "outlineWidth": None} assert merge( "rx.ui.button", BUTTON, {"variant": VARIANT, "size": SIZE} @@ -371,30 +390,25 @@ def test_state_bound_props_that_depend_on_each_other_are_one_alternative(): ("variant", "size"), (VARIANT, SIZE), { - ("solid", "1"): Lowered({ + ("solid", "1"): _lowered({ **solid, "color": "white", "height": "var(--space-5)", }), - ("solid", "2"): Lowered({ + ("solid", "2"): _lowered({ **solid, "color": {"default": "white", ":hover": "gray"}, "height": "var(--space-6)", "fontWeight": "700", }), - ("soft", "1"): Lowered( - {**soft.style, "height": "var(--space-5)"}, (RUBY,) - ), - ("soft", "2"): Lowered( - { - **soft.style, - "height": "var(--space-6)", - "color": {"default": "black", ":hover": "gray"}, - }, - (RUBY,), - ), - ("ghost", "1"): Lowered({**ghost, "height": "var(--space-5)"}), - ("ghost", "2"): Lowered({ + ("soft", "1"): _lowered({**soft.style, "height": "var(--space-5)"}), + ("soft", "2"): _lowered({ + **soft.style, + "height": "var(--space-6)", + "color": {"default": "black", ":hover": "gray"}, + }), + ("ghost", "1"): _lowered({**ghost, "height": "var(--space-5)"}), + ("ghost", "2"): _lowered({ **ghost, "height": "var(--space-6)", "color": {"default": "black", ":hover": "gray"}, diff --git a/tests/units/reflex_components_ui/test_plugin.py b/tests/units/reflex_components_ui/test_plugin.py index f7565a436e8..5abdf50cf76 100644 --- a/tests/units/reflex_components_ui/test_plugin.py +++ b/tests/units/reflex_components_ui/test_plugin.py @@ -7,7 +7,8 @@ import pytest from reflex_base.plugins import VitePluginEntry from reflex_components_ui.constants import JS_SRC -from reflex_components_ui.plugin import Theme, UIPlugin, add_base_stylesheet +from reflex_components_ui.plugin import UIPlugin, add_base_stylesheet +from reflex_components_ui.themes import Theme def test_plugin_installs_the_style_compiler_for_the_build_only(): @@ -89,4 +90,8 @@ def test_base_stylesheet_is_imported_ahead_of_every_other_stylesheet(): def test_plugin_has_a_theme(): assert UIPlugin().theme == Theme() - assert repr(UIPlugin()) == "UIPlugin(theme=Theme())" + assert repr(UIPlugin()) == ( + "UIPlugin(theme=Theme(accent_color='blue', gray_color='auto', " + "radius='medium', scaling='100%', appearance='inherit', " + "panel_background='translucent', has_background=True))" + ) From c38fb26dee2d077c6bb3b2402f7aab117f7420cf Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:17:12 +0000 Subject: [PATCH 15/26] Test the rx.ui themes and tokens, and subscribe a bound theme to its state Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- packages/reflex-components-ui/js/src/base.css | 176 ++++- .../js/tests/base-css.test.js | 26 + .../src/reflex_components_ui/layout/theme.py | 51 +- .../src/reflex_components_ui/styles/theme.py | 5 +- .../src/reflex_components_ui/themes.py | 24 +- .../src/reflex_components_ui/tokens.py | 27 +- tests/units/reflex_components_ui/conftest.py | 9 +- .../reflex_components_ui/layout/test_theme.py | 373 +++++++++++ .../reflex_components_ui/style/test_lower.py | 101 +++ .../units/reflex_components_ui/test_themes.py | 632 ++++++++++++++++++ .../units/reflex_components_ui/test_tokens.py | 223 ++++++ 11 files changed, 1611 insertions(+), 36 deletions(-) create mode 100644 packages/reflex-components-ui/js/tests/base-css.test.js create mode 100644 tests/units/reflex_components_ui/layout/test_theme.py create mode 100644 tests/units/reflex_components_ui/test_themes.py create mode 100644 tests/units/reflex_components_ui/test_tokens.py diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index 3d6a5d39f1d..275f2bce3ee 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -10,7 +10,11 @@ */ @layer __reflex_base, theme, base, reflex-ui, components, utilities; -/* Reflex's color mode provider sets one of these classes on the root element. */ +/* + * Reflex's color mode provider sets one of these classes on the root element. + * Without either, as in a page read with JavaScript off, the color scheme is + * `normal`, under which `light-dark()` is the light color. + */ html.light { color-scheme: light; } @@ -18,3 +22,173 @@ html.light { html.dark { color-scheme: dark; } + +/* + * What Radix Themes styles through a selector that a class on the element + * cannot express. A theme element carries the class `reflex-ui-theme`. + */ +@layer reflex-ui.base { + .reflex-ui-theme ::selection { + background-color: var(--focus-a5); + } +} + +/* + * The system fonts Radix Themes adjusts the metrics of, which the font + * families of the typography tokens name. Copied from the `tokens.css` of + * @radix-ui/themes: `tests/base-css.test.js` fails when they differ. + */ +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 300; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI Semilight'), local('Segoe UI'); +} +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 300; + font-style: italic; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI Semilight Italic'), local('Segoe UI Italic'); +} +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 400; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI'); +} +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 400; + font-style: italic; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI Italic'); +} +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 500; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI Semibold'), local('Segoe UI'); +} +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 500; + font-style: italic; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI Semibold Italic'), local('Segoe UI Italic'); +} +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 700; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI Bold'); +} +@font-face { + font-family: 'Segoe UI (Custom)'; + font-weight: 700; + font-style: italic; + size-adjust: 103%; + descent-override: 35%; + ascent-override: 105%; + src: local('Segoe UI Bold Italic'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 300; + descent-override: 35%; + src: local('Open Sans Light'), local('Open Sans Regular'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 300; + font-style: italic; + descent-override: 35%; + src: local('Open Sans Light Italic'), local('Open Sans Italic'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 400; + descent-override: 35%; + src: local('Open Sans Regular'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 400; + font-style: italic; + descent-override: 35%; + src: local('Open Sans Italic'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 500; + descent-override: 35%; + src: local('Open Sans Medium'), local('Open Sans Regular'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 500; + font-style: italic; + descent-override: 35%; + src: local('Open Sans Medium Italic'), local('Open Sans Italic'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 700; + descent-override: 35%; + src: local('Open Sans Bold'); +} +@font-face { + font-family: 'Open Sans (Custom)'; + font-weight: 700; + font-style: italic; + descent-override: 35%; + src: local('Open Sans Bold Italic'); +} +@font-face { + font-family: 'Consolas (Custom)'; + font-weight: 400; + size-adjust: 110%; + ascent-override: 85%; + descent-override: 22%; + src: local('Consolas'); +} +@font-face { + font-family: 'Consolas (Custom)'; + font-weight: 400; + font-style: italic; + size-adjust: 110%; + ascent-override: 85%; + descent-override: 22%; + src: local('Consolas Italic'); +} +@font-face { + font-family: 'Consolas (Custom)'; + font-weight: 700; + size-adjust: 110%; + ascent-override: 85%; + descent-override: 22%; + src: local('Consolas Bold'); +} +@font-face { + font-family: 'Consolas (Custom)'; + font-weight: 700; + font-style: italic; + size-adjust: 110%; + ascent-override: 85%; + descent-override: 22%; + src: local('Consolas Bold Italic'); +} diff --git a/packages/reflex-components-ui/js/tests/base-css.test.js b/packages/reflex-components-ui/js/tests/base-css.test.js new file mode 100644 index 00000000000..a066442d81a --- /dev/null +++ b/packages/reflex-components-ui/js/tests/base-css.test.js @@ -0,0 +1,26 @@ +// @vitest-environment node +import { readFile } from "node:fs/promises"; +import { createRequire } from "node:module"; + +import { expect, test } from "vitest"; + +const FONT_FACE = /@font-face \{[^}]*\}/g; + +/** + * The `@font-face` rules of a stylesheet. + * + * @param {string | URL} path The stylesheet. + * @returns {Promise} The rules, as they are written. + */ +async function fontFaces(path) { + return (await readFile(path, "utf8")).match(FONT_FACE) ?? []; +} + +test("base.css has the font faces of the Radix Themes tokens", async () => { + const require = createRequire(import.meta.url); + const radix = await fontFaces(require.resolve("@radix-ui/themes/tokens.css")); + expect(radix.length).toBe(20); + expect(await fontFaces(new URL("../src/base.css", import.meta.url))).toEqual( + radix, + ); +}); diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py index 7a0a33444ef..2181856a65a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Iterator from typing import Any, ClassVar from reflex_base.components.component import Component, field @@ -22,6 +23,7 @@ from reflex_components_ui.style.emit import props_call from reflex_components_ui.styles.theme import APP_THEME from reflex_components_ui.themes import ( + OPTIONS, LiteralAccentColor, LiteralAppearance, LiteralGrayColor, @@ -35,6 +37,10 @@ ) +# The fields of the element that are options of its theme. +_OPTIONS = (*OPTIONS, "has_background") + + class ThemeElement(UIComponent): """A block whose content follows a theme of its own. @@ -96,6 +102,28 @@ def _display_name(cls) -> str: """ return "rx.ui.theme" + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in this component. + + Args: + include_children: Whether to include Vars from children. + ignore_ids: The ids to ignore. + + Yields: + The Vars of every component, then the options bound to state: they + are no props of the element, so nothing else reports the state + they read. + """ + yield from super()._get_vars( + include_children=include_children, ignore_ids=ignore_ids + ) + for option in _OPTIONS: + value = getattr(self, option) + if isinstance(value, Var): + yield value + def _theme_styles(self) -> ThemeStyles: """Work out the StyleX themes of the element. @@ -103,12 +131,9 @@ def _theme_styles(self) -> ThemeStyles: What the element needs to carry its theme. Raises: - ConfigError: If the plugin that compiles the styles is not configured. ThemeError: If the element is rendered from state. + ConfigError: If the plugin that compiles the styles is not configured. """ - plugin = get_plugin(UIPlugin) - if plugin is None: - raise ConfigError(MISSING_PLUGIN_ERROR) if is_rendering_dynamic_component(): msg = ( f"{self._display_name()}: a theme rendered from state cannot be " @@ -117,6 +142,9 @@ def _theme_styles(self) -> ThemeStyles: "what comes from state inside it." ) raise ThemeError(msg) + plugin = get_plugin(UIPlugin) + if plugin is None: + raise ConfigError(MISSING_PLUGIN_ERROR) return self._resolve_theme_styles(plugin) def _resolve_theme_styles(self, plugin: UIPlugin) -> ThemeStyles: @@ -140,22 +168,21 @@ def _resolve_theme_styles(self, plugin: UIPlugin) -> ThemeStyles: app_theme=plugin.theme, ) - def add_imports(self) -> list[ImportDict]: - """Import StyleX and the StyleX themes of the element. + def add_imports(self) -> ImportDict: + """Import the StyleX themes of the element. Returns: - The imports. + The imports, beside the ones every rx.ui component has. """ - return [super().add_imports(), self._theme_styles().import_dict()] + return self._theme_styles().import_dict() def add_custom_code(self) -> list[str]: - """Declare what the element's style and its themes refer to. + """Declare the maps an option bound to state is looked up in. Returns: - The declaration of the style, then the maps an option bound to - state is looked up in. + The declarations, beside the one of the element's own style. """ - return [*super().add_custom_code(), *self._theme_styles().declarations] + return list(self._theme_styles().declarations) def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the element with its themes and its style. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py index 2c232938470..ecf23e1d85b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py @@ -8,6 +8,9 @@ "base": { "position": "relative", "zIndex": 0, - "minHeight": "100vh", + "minHeight": { + "default": "100vh", + "@supports (min-height: 100dvh)": "100dvh", + }, }, } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/themes.py b/packages/reflex-components-ui/src/reflex_components_ui/themes.py index 474119b9b7d..7afe73349df 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/themes.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/themes.py @@ -65,6 +65,9 @@ "panel_background": get_args(LiteralPanelBackground), } +# The class of every theme element, which the base stylesheet selects on. +THEME_CLASS = "reflex-ui-theme" + # The name the styles of a theme element are imported under: `theme` is what # an app with Radix Themes imports its own theme as. _THEME_STYLES = "reflexUITheme" @@ -82,18 +85,19 @@ class ThemeError(ReflexError, ValueError): """A theme option that cannot be applied.""" -def _check(name: str, option: str, value: object) -> None: +def _check(name: str, option: str, value: object, accepts: str | None = None) -> None: """Fail on a value an option does not take. Args: name: What the option was given to, which starts the error message. option: The option. value: Its value. + accepts: The option whose values it takes, when it is another one. Raises: ThemeError: If the value is not one of the option's. """ - values = OPTIONS[option] + values = OPTIONS[accepts or option] if value.__class__ is str and value in values: return if isinstance(value, Var): @@ -171,7 +175,7 @@ class ThemeStyles: theme the arguments name. declarations: The module-level statements the arguments rely on. class_name: The class names the element carries beside the compiled - ones. + ones, if any. var_data: The state the arguments read. """ @@ -426,7 +430,8 @@ def theme_styles( module, export, _ = tokens.THEME_STYLES styles = builder.add((module, export), _THEME_STYLES) builder.refs.append(f"{styles}.root") - class_name = None + class_name = THEME_CLASS + explicit = False bound_appearance = None if isinstance(appearance, Var): bound_appearance = builder.bound(appearance) @@ -435,7 +440,8 @@ def theme_styles( if appearance != "inherit": # Radix Themes and Tailwind select on the class: a component of # either inside this element follows the appearance too. - class_name = appearance + class_name = f"{THEME_CLASS} {appearance}" + explicit = True if isinstance(has_background, Var): builder.refs.append(f"({builder.bound(has_background)}) && {styles}.background") elif has_background is None: @@ -443,7 +449,7 @@ def theme_styles( builder.refs.append( f'({bound_appearance}) !== "inherit" && {styles}.background' ) - elif class_name is not None: + elif explicit: builder.refs.append(f"{styles}.background") else: _check_flag(name, "has_background", has_background) @@ -455,8 +461,8 @@ def theme_styles( f'({bound_appearance}) !== "inherit" && ' f"{{ $$css: true, appearance: {bound_appearance} }}", )) - elif class_name is not None: - builder.refs.append(f"{styles}.{class_name}") + elif explicit: + builder.refs.append(f"{styles}.{appearance}") return builder.finish(class_name) @@ -498,7 +504,7 @@ def color_scheme_styles(name: str, color_scheme: Any) -> ThemeStyles: focus = builder.add(tokens.FOCUS_THEME) builder.refs.append(f'({builder.bound(color_scheme)}) !== "gray" && {focus}') else: - _check(name, "color_scheme", color_scheme) + _check(name, "color_scheme", color_scheme, "accent_color") builder.refs.append(builder.add(tokens.ACCENT_THEMES[color_scheme])) if color_scheme != "gray": builder.refs.append(builder.add(tokens.FOCUS_THEME)) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/tokens.py b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py index c68b4c4f5e0..7996b670396 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/tokens.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py @@ -112,16 +112,19 @@ def _step(self, step: int) -> str: f"{len(self._steps)}." ) else: - msg = f"{self._path} has no steps. Its tokens are {self._names()}." + msg = ( + f"{self._path} has no steps. Its tokens are " + f"{', '.join(self._names())}." + ) raise TokenError(msg) - def _names(self) -> str: + def _names(self) -> list[str]: """List the named tokens of the group. Returns: - Their names, for an error message. + Their names, sorted. """ - return ", ".join(sorted([name for name in vars(self) if name[0] != "_"])) + return sorted([name for name in vars(self) if name[0] != "_"]) def __getitem__(self, step: int) -> str: """Get the token of a step. @@ -148,9 +151,10 @@ def __getattr__(self, name: str) -> NoReturn: """ if name[:1] == "_": raise AttributeError(name) - msg = f'{self._path} has no token "{name}".{_suggest(name, vars(self))}' - if names := self._names(): - msg += f" Its tokens are {names}" + names = self._names() + msg = f'{self._path} has no token "{name}".{_suggest(name, names)}' + if names: + msg += f" Its tokens are {', '.join(names)}" if self._steps: msg += f", and the steps [1] to [{len(self._steps)}]" msg += "." @@ -538,13 +542,18 @@ def scale(name: LiteralColorScale) -> _Scale: found = _SCALES.get(name) if found is None: scales = LiteralColorScale.__args__ + if name == "accent" or name == "gray": + msg = ( + f'rx.ui.tokens.scale: "{name}" is not a color scale of its own, ' + f"but the {name} of the theme: use rx.ui.tokens.{name}." + ) + raise TokenError(msg) if name not in scales: shown = f'"{name}"' if isinstance(name, str) else repr(name) suggestion = _suggest(name, scales) if isinstance(name, str) else "" msg = ( f"rx.ui.tokens.scale: unknown color scale {shown}.{suggestion} " - f"The scales are {', '.join(sorted(scales))}. The accent and the " - "gray of the theme are rx.ui.tokens.accent and rx.ui.tokens.gray." + f"The scales are {', '.join(sorted(scales))}." ) raise TokenError(msg) found = _SCALES[name] = _Scale(f'rx.ui.tokens.scale("{name}")', name) diff --git a/tests/units/reflex_components_ui/conftest.py b/tests/units/reflex_components_ui/conftest.py index c935bc00426..bc2afb183b2 100644 --- a/tests/units/reflex_components_ui/conftest.py +++ b/tests/units/reflex_components_ui/conftest.py @@ -7,7 +7,7 @@ import pytest from reflex_base.components.component import Component from reflex_base.config import get_config -from reflex_base.plugins import CompileContext, CompilerHooks +from reflex_base.plugins import CompileContext, CompilerHooks, Plugin from reflex_components_ui.plugin import UIPlugin from reflex.compiler.plugins import default_page_plugins @@ -47,14 +47,15 @@ def compile_page(preserve_memo_registries: None) -> Callable[..., CompileContext preserve_memo_registries: Restores the memos a compile registers. Returns: - A function from a page to its compile context: the source of the page + A function from a page, and the plugins of the app to run beside the + ones of every compile, to its compile context: the source of the page is ``compiled_pages["/"].output_code``. """ - def compile_page(page: Callable[[], Component]) -> CompileContext: + def compile_page(page: Callable[[], Component], *plugins: Plugin) -> CompileContext: ctx = CompileContext( pages=[_Page(route="/", component=page)], - hooks=CompilerHooks(plugins=default_page_plugins()), + hooks=CompilerHooks(plugins=(*default_page_plugins(), *plugins)), ) with ctx: ctx.compile() diff --git a/tests/units/reflex_components_ui/layout/test_theme.py b/tests/units/reflex_components_ui/layout/test_theme.py new file mode 100644 index 00000000000..8382c359fb9 --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_theme.py @@ -0,0 +1,373 @@ +"""Tests for reflex_components_ui.layout.theme.""" + +from collections.abc import Callable + +import pytest +from pytest_mock import MockerFixture +from reflex_base.config import get_config +from reflex_base.plugins import CompileContext +from reflex_base.utils.exceptions import ConfigError +from reflex_base.utils.serializers import serialize +from reflex_components_core.base.app_wrap import AppWrap +from reflex_components_ui.layout.theme import AppTheme, ThemeElement +from reflex_components_ui.plugin import APP_THEME_WRAP, UIPlugin +from reflex_components_ui.themes import Theme, ThemeError + +import reflex as rx +from reflex.compiler import compiler + +APP_ROOT = """ +import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" +import {focusScope} from "$/reflex-ui/themes/focus.js" +import {graySlate} from "$/reflex-ui/themes/gray/slate.js" +import {panelTranslucent} from "$/reflex-ui/themes/panel.js" +import {radiusLarge} from "$/reflex-ui/themes/radius.js" +import {scaling100} from "$/reflex-ui/themes/scaling.js" +import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" +import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" +import * as stylex from "@stylexjs/stylex" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + +import { defaultColorMode } from "$/utils/context"; +import { ThemeProvider } from '$/utils/react-theme'; +import { Layout as AppLayout } from './_document'; +import { Outlet } from 'react-router'; + + + +const sx_c1c0436182 = stylex.create({ s: {"position": "relative", "zIndex": 0, "minHeight": {"default": "100vh", "@supports (min-height: 100dvh)": "100dvh"}} }); + +function ReflexProviders({children}) { + useEffect(() => { + // Make contexts and state objects available globally for dynamic eval'd components + window.__reflex = { + + }; + }, []); + + return jsx(ThemeProvider, {defaultTheme: defaultColorMode, attribute: "class"}, + jsx(AppWrap, {}, children) + ); +} + + +function AppWrap({children}) { + +return (jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentIndigo, graySlate, radiusLarge, scaling100, panelTranslucent, reflexUITheme.root, reflexUITheme.background, sx_c1c0436182.s, { $$css: true, className: "reflex-ui-theme" })},jsx(Fragment,{},children))) +} + +export function Layout({children}) { + return jsx(AppLayout, {}, jsx(ReflexProviders, {}, children)); +} + +// Used by entry.client.js when mount_target is configured: skips the document +// shell (which renders react-router's // and requires a +// framework router context) but keeps the runtime providers. +export function EmbedLayout({children}) { + return jsx(ReflexProviders, {}, children); +} + +export default function App() { + return jsx(Outlet, {}); +} + +""" + +NESTED_PAGE = """import * as stylex from "@stylexjs/stylex" +import {accentRed} from "$/reflex-ui/themes/accent/red.js" +import {focusScope} from "$/reflex-ui/themes/focus.js" +import {grayMauve} from "$/reflex-ui/themes/gray/mauve.js" +import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" +import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" +import {useRegisteredRef} from "$/utils/state" +import {radiusFull} from "$/reflex-ui/themes/radius.js" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + + + +const sx_e0e666cdfc = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "color": "var(--accent-9)"} }); +const sx_ffb9e340d1 = stylex.create({ s: {"padding": "4px"} }); + +function Component() { +const ref_dark = useRegisteredRef("ref_dark"); + + return ( + jsx(Fragment,{},jsx("main",{},jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentRed, grayMauve, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},jsx("div",{...stylex.props(sx_e0e666cdfc.s)},"red")),jsx("div",{id:"dark",ref:ref_dark,...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, radiusFull, reflexUITheme.root, reflexUITheme.background, reflexUITheme.dark, sx_ffb9e340d1.s, { $$css: true, className: "reflex-ui-theme dark p-8" })},"dark"),jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},"plain")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + ) +} +Component.displayName = "Component(/)"; + +export default Component; +""" + +BOUND_PAGE = """import {Themeelement_div_0c153819fc2a864827f9e11f201c2218} from "$/utils/components/Themeelement_div_0c153819fc2a864827f9e11f201c2218" +import {Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf} from "$/utils/components/Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + + + + + +function Component() { + + + return ( + jsx(Fragment,{},jsx("main",{},jsx(Themeelement_div_0c153819fc2a864827f9e11f201c2218,{},"accent"),jsx(Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf,{},"names")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + ) +} +Component.displayName = "Component(/)"; + +export default Component; +""" + +BOUND_ACCENT_THEME = """ +import {isTrue,mergeSlotProps} from "$/utils/state" +import {useStateContext} from "$/utils/context-registry" +import {accentAmber} from "$/reflex-ui/themes/accent/amber.js" +import {accentBlue} from "$/reflex-ui/themes/accent/blue.js" +import {accentBronze} from "$/reflex-ui/themes/accent/bronze.js" +import {accentBrown} from "$/reflex-ui/themes/accent/brown.js" +import {accentCrimson} from "$/reflex-ui/themes/accent/crimson.js" +import {accentCyan} from "$/reflex-ui/themes/accent/cyan.js" +import {accentGold} from "$/reflex-ui/themes/accent/gold.js" +import {accentGrass} from "$/reflex-ui/themes/accent/grass.js" +import {accentGray} from "$/reflex-ui/themes/accent/gray.js" +import {accentGreen} from "$/reflex-ui/themes/accent/green.js" +import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" +import {accentIris} from "$/reflex-ui/themes/accent/iris.js" +import {accentJade} from "$/reflex-ui/themes/accent/jade.js" +import {accentLime} from "$/reflex-ui/themes/accent/lime.js" +import {accentMint} from "$/reflex-ui/themes/accent/mint.js" +import {accentOrange} from "$/reflex-ui/themes/accent/orange.js" +import {accentPink} from "$/reflex-ui/themes/accent/pink.js" +import {accentPlum} from "$/reflex-ui/themes/accent/plum.js" +import {accentPurple} from "$/reflex-ui/themes/accent/purple.js" +import {accentRed} from "$/reflex-ui/themes/accent/red.js" +import {accentRuby} from "$/reflex-ui/themes/accent/ruby.js" +import {accentSky} from "$/reflex-ui/themes/accent/sky.js" +import {accentTeal} from "$/reflex-ui/themes/accent/teal.js" +import {accentTomato} from "$/reflex-ui/themes/accent/tomato.js" +import {accentViolet} from "$/reflex-ui/themes/accent/violet.js" +import {accentYellow} from "$/reflex-ui/themes/accent/yellow.js" +import {focusScope} from "$/reflex-ui/themes/focus.js" +import {grayGray} from "$/reflex-ui/themes/gray/gray.js" +import {grayMauve} from "$/reflex-ui/themes/gray/mauve.js" +import {grayOlive} from "$/reflex-ui/themes/gray/olive.js" +import {graySage} from "$/reflex-ui/themes/gray/sage.js" +import {graySand} from "$/reflex-ui/themes/gray/sand.js" +import {graySlate} from "$/reflex-ui/themes/gray/slate.js" +import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" +import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" +import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" +import {Fragment,memo,useEffect} from "react" + + + +const reflexUIAccents = { "amber": accentAmber, "blue": accentBlue, "bronze": accentBronze, "brown": accentBrown, "crimson": accentCrimson, "cyan": accentCyan, "gold": accentGold, "grass": accentGrass, "gray": accentGray, "green": accentGreen, "indigo": accentIndigo, "iris": accentIris, "jade": accentJade, "lime": accentLime, "mint": accentMint, "orange": accentOrange, "pink": accentPink, "plum": accentPlum, "purple": accentPurple, "red": accentRed, "ruby": accentRuby, "sky": accentSky, "teal": accentTeal, "tomato": accentTomato, "violet": accentViolet, "yellow": accentYellow }; +const reflexUIMatchingGrays = { "amber": graySand, "blue": graySlate, "bronze": graySand, "brown": graySand, "crimson": grayMauve, "cyan": graySlate, "gold": graySand, "grass": grayOlive, "gray": grayGray, "green": graySage, "indigo": graySlate, "iris": graySlate, "jade": graySage, "lime": grayOlive, "mint": graySage, "orange": graySand, "pink": grayMauve, "plum": grayMauve, "purple": grayMauve, "red": grayMauve, "ruby": grayMauve, "sky": graySlate, "teal": graySage, "tomato": grayMauve, "violet": grayMauve, "yellow": graySand }; + + +export const Themeelement_div_0c153819fc2a864827f9e11f201c2218 = /*#__PURE__*/ (() => { +const Themeelement_div_0c153819fc2a864827f9e11f201c2218 = memo(({children, ...rest}) => { + const reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state = useStateContext("reflex___state____state.tests___units___reflex_components_ui___layout___test_theme____theme_state", ["accent_rx_state_"]) + return( + jsx("div",{...mergeSlotProps(rest, ({ ...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], reflexUIMatchingGrays[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" }) }))},children) + ) +}); +Themeelement_div_0c153819fc2a864827f9e11f201c2218.displayName = "ThemeElement"; +return Themeelement_div_0c153819fc2a864827f9e11f201c2218; +})(); +""" + +BOUND_NAMES_THEME = """ +import {isTrue,mergeSlotProps} from "$/utils/state" +import {useStateContext} from "$/utils/context-registry" +import {accentAmber} from "$/reflex-ui/themes/accent/amber.js" +import {accentBlue} from "$/reflex-ui/themes/accent/blue.js" +import {accentBronze} from "$/reflex-ui/themes/accent/bronze.js" +import {accentBrown} from "$/reflex-ui/themes/accent/brown.js" +import {accentCrimson} from "$/reflex-ui/themes/accent/crimson.js" +import {accentCyan} from "$/reflex-ui/themes/accent/cyan.js" +import {accentGold} from "$/reflex-ui/themes/accent/gold.js" +import {accentGrass} from "$/reflex-ui/themes/accent/grass.js" +import {accentGray} from "$/reflex-ui/themes/accent/gray.js" +import {accentGreen} from "$/reflex-ui/themes/accent/green.js" +import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" +import {accentIris} from "$/reflex-ui/themes/accent/iris.js" +import {accentJade} from "$/reflex-ui/themes/accent/jade.js" +import {accentLime} from "$/reflex-ui/themes/accent/lime.js" +import {accentMint} from "$/reflex-ui/themes/accent/mint.js" +import {accentOrange} from "$/reflex-ui/themes/accent/orange.js" +import {accentPink} from "$/reflex-ui/themes/accent/pink.js" +import {accentPlum} from "$/reflex-ui/themes/accent/plum.js" +import {accentPurple} from "$/reflex-ui/themes/accent/purple.js" +import {accentRed} from "$/reflex-ui/themes/accent/red.js" +import {accentRuby} from "$/reflex-ui/themes/accent/ruby.js" +import {accentSky} from "$/reflex-ui/themes/accent/sky.js" +import {accentTeal} from "$/reflex-ui/themes/accent/teal.js" +import {accentTomato} from "$/reflex-ui/themes/accent/tomato.js" +import {accentViolet} from "$/reflex-ui/themes/accent/violet.js" +import {accentYellow} from "$/reflex-ui/themes/accent/yellow.js" +import {focusScope} from "$/reflex-ui/themes/focus.js" +import {graySand} from "$/reflex-ui/themes/gray/sand.js" +import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" +import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" +import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" +import {Fragment,memo,useEffect} from "react" + + + +const reflexUIAccents = { "amber": accentAmber, "blue": accentBlue, "bronze": accentBronze, "brown": accentBrown, "crimson": accentCrimson, "cyan": accentCyan, "gold": accentGold, "grass": accentGrass, "gray": accentGray, "green": accentGreen, "indigo": accentIndigo, "iris": accentIris, "jade": accentJade, "lime": accentLime, "mint": accentMint, "orange": accentOrange, "pink": accentPink, "plum": accentPlum, "purple": accentPurple, "red": accentRed, "ruby": accentRuby, "sky": accentSky, "teal": accentTeal, "tomato": accentTomato, "violet": accentViolet, "yellow": accentYellow }; + + +export const Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf = /*#__PURE__*/ (() => { +const Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf = memo(({children, ...rest}) => { + const reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state = useStateContext("reflex___state____state.tests___units___reflex_components_ui___layout___test_theme____theme_state", ["names_rx_state_", "accent_rx_state_"]) + return( + jsx("div",{...mergeSlotProps(rest, ({ className:(reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.names_rx_state_) + " " + stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], graySand, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" }).className }))},children) + ) +}); +Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf.displayName = "ThemeElement"; +return Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf; +})(); +""" + + +class ThemeState(rx.State): + """State whose fields are bound to a theme.""" + + accent: str = "red" + names: str = "wide" + + +@pytest.fixture +def indigo_plugin(monkeypatch: pytest.MonkeyPatch) -> UIPlugin: + """Configure the plugin with a theme, as an app does in its rxconfig.py. + + Args: + monkeypatch: The pytest fixture that undoes the change. + + Returns: + The configured plugin. + """ + plugin = UIPlugin(theme=Theme(accent_color="indigo", radius="large")) + monkeypatch.setattr(get_config(), "plugins", [plugin]) + return plugin + + +def test_app_root_source(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture): + """The element around the app names one accent, one gray and the options.""" + # The libraries a dynamic component may load are no part of the theme. + mocker.patch( + "reflex.compiler.compiler._split_window_libraries", return_value=([], []) + ) + app = rx.App(enable_state=False) + plugin = UIPlugin(theme=Theme(accent_color="indigo", radius="large")) + monkeypatch.setattr(get_config(), "plugins", [plugin]) + root = app._app_root({ + (0, "AppWrap"): AppWrap.create(), + APP_THEME_WRAP: AppTheme.create(), + }) + assert compiler._compile_app(root, dynamic_components=False) == APP_ROOT + + +def test_plugin_wraps_every_app_in_its_theme( + indigo_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + """A page asks for the wrap, inside the one of Radix Themes.""" + wraps = compile_page(lambda: rx.el.main("hello"), indigo_plugin).app_wrap_components + assert list(wraps) == [(15, "ReflexUITheme")] + assert type(wraps[15, "ReflexUITheme"]) is AppTheme + assert APP_THEME_WRAP == (15, "ReflexUITheme") + + +def test_nested_theme_page_source( + indigo_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + """A literal option imports one module, and the element stays a div.""" + + def page(): + return rx.el.main( + rx.ui.theme( + rx.ui.box("red", style={"color": rx.ui.tokens.accent[9]}), + accent_color="red", + ), + rx.ui.theme( + "dark", + appearance="dark", + radius="full", + class_name="p-8", + style={"padding": "4px"}, + id="dark", + ), + rx.ui.theme("plain"), + ) + + assert compile_page(page).compiled_pages["/"].output_code == NESTED_PAGE + + +def test_theme_bound_to_state_imports_every_accent( + indigo_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + """The element moves to a module of its own, which chooses among them.""" + + def page(): + return rx.el.main( + rx.ui.theme("accent", accent_color=ThemeState.accent), + rx.ui.theme( + "names", + accent_color=ThemeState.accent, + gray_color="sand", + class_name=ThemeState.names, + ), + ) + + ctx = compile_page(page) + assert ctx.compiled_pages["/"].output_code == BOUND_PAGE + files, _ = compiler.compile_memo_components(ctx.auto_memo_components.values()) + sources = [code for path, code in files if "Themeelement_div_" in path] + assert sources == [BOUND_ACCENT_THEME, BOUND_NAMES_THEME] + + +def test_theme_is_a_name_of_the_ui_namespace(): + assert rx.ui.theme == ThemeElement.create + assert rx.ui.Theme is Theme + assert {"theme", "Theme"} <= set(dir(rx.ui)) + assert ThemeElement._display_name() == "rx.ui.theme" + + +def test_theme_needs_the_plugin(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(get_config(), "plugins", []) + with pytest.raises(ConfigError) as error: + rx.ui.theme("hello", accent_color="red").render() + assert str(error.value) == ( + "rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins." + ) + + +def test_theme_refuses_a_value_an_option_does_not_take(indigo_plugin: UIPlugin): + with pytest.raises(ThemeError) as error: + rx.ui.theme("hello", accent_color="indgo").render() # pyright: ignore [reportArgumentType] + assert str(error.value) == ( + 'rx.ui.theme: unknown accent_color "indgo". Did you mean "indigo"? The ' + 'values are "tomato", "red", "ruby", "crimson", "pink", "plum", ' + '"purple", "violet", "iris", "indigo", "blue", "cyan", "teal", "jade", ' + '"green", "grass", "brown", "orange", "sky", "mint", "lime", "yellow", ' + '"amber", "gold", "bronze", "gray".' + ) + + +def test_theme_held_in_state_cannot_be_applied(): + """Its code never reaches the StyleX compiler, which has the class names.""" + with pytest.raises(ThemeError) as error: + serialize(rx.ui.theme("hello", accent_color="red")) + assert str(error.value) == ( + "rx.ui.theme: a theme rendered from state cannot be applied: its code " + "is evaluated in the browser and never reaches the StyleX compiler. " + "Render the theme in a page, and what comes from state inside it." + ) diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index 1b39bfd65ed..f730db8f440 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -7,6 +7,7 @@ from reflex_base.constants.colors import Color from reflex_base.vars.base import LiteralVar, Var from reflex_components_ui.style import _css_props +from reflex_components_ui import tokens from reflex_components_ui._radix_tokens import VAR_GROUPS from reflex_components_ui.style.lower import ( _BORDERS, @@ -1348,3 +1349,103 @@ def test_var_values_are_vars(): value = lower("rx.ui.card", {"width": WIDTH}).style["width"] assert isinstance(value, Var) assert value.equals(WIDTH) + + +@pytest.mark.parametrize( + ("style", "expected", "imports"), + [ + ( + {"padding": tokens.space[3]}, + _sides("padding", "", *["var(--space-3)"] * 4), + (SPACE,), + ), + ( + {"padding": f"{tokens.space[2]} {tokens.space[4]}"}, + _sides( + "padding", + "", + "var(--space-2)", + "var(--space-4)", + "var(--space-2)", + "var(--space-4)", + ), + (SPACE,), + ), + ( + {"margin": f"0 auto {tokens.space[1]}"}, + _sides("margin", "", "0", "auto", "var(--space-1)", "auto"), + (SPACE,), + ), + ( + {"gap": f"{tokens.space[1]} {tokens.space[2]}"}, + {"rowGap": "var(--space-1)", "columnGap": "var(--space-2)"}, + (SPACE,), + ), + ( + {"border_radius": tokens.radius[3]}, + { + "borderTopLeftRadius": "var(--radius-3)", + "borderTopRightRadius": "var(--radius-3)", + "borderBottomRightRadius": "var(--radius-3)", + "borderBottomLeftRadius": "var(--radius-3)", + }, + ("$/reflex-ui/tokens/radius.stylex.js",), + ), + ( + {"border_color": tokens.gray.a[6]}, + _sides("border", "Color", *["var(--gray-a6)"] * 4), + (GRAY,), + ), + ( + {"border": f"1px solid {tokens.accent[7]}"}, + _border(ALL_SIDES, "1px", "solid", "var(--accent-7)"), + (ACCENT,), + ), + ( + {"background": tokens.color.panel}, + {"backgroundColor": "var(--color-panel)", "backgroundImage": "none"}, + ("$/reflex-ui/tokens/color.stylex.js",), + ), + # A shadow is a list of layers and a font family a list of fonts: a + # shorthand that holds one is kept whole, as with any other property. + ( + {"padding": tokens.shadow[1]}, + {"padding": "var(--shadow-1)"}, + ("$/reflex-ui/tokens/shadow.stylex.js",), + ), + ( + {"margin": f"{tokens.space[1]} {tokens.default.font_family}"}, + {"margin": "var(--space-1) var(--default-font-family)"}, + (SPACE, "$/reflex-ui/tokens/typography.stylex.js"), + ), + ( + {"padding": f"{tokens.space[1]} var(--mine)"}, + {"padding": "var(--space-1) var(--mine)"}, + (SPACE,), + ), + ( + {"padding": f"calc({tokens.space[1]} * 2) {tokens.space[2]}"}, + {"padding": "calc(var(--space-1) * 2) var(--space-2)"}, + (SPACE,), + ), + ( + {"font_size": tokens.font_size[2], "box_shadow": tokens.shadow[3]}, + {"fontSize": "var(--font-size-2)", "boxShadow": "var(--shadow-3)"}, + ( + "$/reflex-ui/tokens/shadow.stylex.js", + "$/reflex-ui/tokens/typography.stylex.js", + ), + ), + ], +) +def test_design_tokens(style: Any, expected: dict[str, Any], imports: tuple[str, ...]): + """A token is its custom property: a shorthand gives one to each longhand. + + Args: + style: The style as written. + expected: The lowered properties. + imports: The modules the style needs. + """ + lowered = lower("rx.ui.card", style) + assert lowered == Lowered(expected, imports) + assert lowered.imports == imports diff --git a/tests/units/reflex_components_ui/test_themes.py b/tests/units/reflex_components_ui/test_themes.py new file mode 100644 index 00000000000..d9a7b96bd68 --- /dev/null +++ b/tests/units/reflex_components_ui/test_themes.py @@ -0,0 +1,632 @@ +"""Tests for reflex_components_ui.themes.""" + +import dataclasses +from typing import Any, get_args + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar +from reflex_components_ui import _radix_tokens, themes +from reflex_components_ui.themes import ( + Theme, + ThemeError, + ThemeStyles, + app_theme_styles, + color_scheme_styles, + theme_styles, +) + +import reflex as rx + +SCOPES = ("spaceScope", "radiusScope", "typographyScope", "shadowScope", "colorScope") +SCOPE_IMPORTS = ( + ("themes/scope.js", "colorScope", None), + ("themes/scope.js", "radiusScope", None), + ("themes/scope.js", "shadowScope", None), + ("themes/scope.js", "spaceScope", None), + ("themes/scope.js", "typographyScope", None), +) +FOCUS_IMPORT = ("themes/focus.js", "focusScope", None) +STYLES_IMPORT = ("themes/theme.js", "theme", "reflexUITheme") + +ACCENT_VALUES = ( + '"tomato", "red", "ruby", "crimson", "pink", "plum", "purple", "violet", ' + '"iris", "indigo", "blue", "cyan", "teal", "jade", "green", "grass", ' + '"brown", "orange", "sky", "mint", "lime", "yellow", "amber", "gold", ' + '"bronze", "gray"' +) + +ACCENT_MAP = ( + "const reflexUIAccents = { " + + ", ".join( + f'"{name}": accent{name.capitalize()}' + for name in sorted(_radix_tokens.ACCENT_THEMES) + ) + + " };" +) +ACCENT_IMPORTS = tuple( + (f"themes/accent/{name}.js", f"accent{name.capitalize()}", None) + for name in sorted(_radix_tokens.ACCENT_THEMES) +) +GRAY_IMPORTS = tuple( + (f"themes/gray/{name}.js", f"gray{name.capitalize()}", None) + for name in sorted(_radix_tokens.GRAY_THEMES) +) + + +class ThemeState(rx.State): + """State whose fields are bound to theme options.""" + + accent: str = "red" + gray: str = "sand" + radius: str = "full" + scaling: str = "90%" + panel: str = "solid" + appearance: str = "dark" + background: bool = True + + +def test_literal_types_are_the_generated_themes(): + """A type checker accepts exactly the values a StyleX theme exists for.""" + assert sorted(get_args(themes.LiteralAccentColor)) == sorted( + _radix_tokens.ACCENT_THEMES + ) + assert sorted(get_args(themes.LiteralGrayColor)) == sorted([ + "auto", + *_radix_tokens.GRAY_THEMES, + ]) + assert sorted(get_args(themes.LiteralRadius)) == sorted(_radix_tokens.RADIUS_THEMES) + assert sorted(get_args(themes.LiteralScaling)) == sorted( + _radix_tokens.SCALING_THEMES + ) + assert sorted(get_args(themes.LiteralPanelBackground)) == sorted( + _radix_tokens.PANEL_BACKGROUND_THEMES + ) + module, export, styles = _radix_tokens.THEME_STYLES + assert (module, export) == STYLES_IMPORT[:2] + assert sorted(styles) == sorted([ + "root", + "background", + *(set(get_args(themes.LiteralAppearance)) - {"inherit"}), + ]) + assert themes.OPTIONS == { + "accent_color": get_args(themes.LiteralAccentColor), + "gray_color": get_args(themes.LiteralGrayColor), + "radius": get_args(themes.LiteralRadius), + "scaling": get_args(themes.LiteralScaling), + "appearance": ("inherit", "light", "dark"), + "panel_background": get_args(themes.LiteralPanelBackground), + } + + +def test_theme_defaults_are_the_ones_of_radix_but_for_the_accent(): + """Reflex has always made blue the accent, where Radix Themes has indigo.""" + assert dataclasses.asdict(Theme()) == { + **_radix_tokens.DEFAULTS, + "accent_color": "blue", + "appearance": "inherit", + "has_background": True, + } + assert _radix_tokens.DEFAULTS["accent_color"] == "indigo" + + +def test_theme_is_a_frozen_value(): + theme = Theme(accent_color="indigo", radius="large") + assert theme == Theme(radius="large", accent_color="indigo") + assert hash(theme) == hash(Theme(radius="large", accent_color="indigo")) + with pytest.raises(dataclasses.FrozenInstanceError): + theme.radius = "small" # pyright: ignore [reportAttributeAccessIssue] + + +@pytest.mark.parametrize( + ("options", "message"), + [ + ( + {"accent_color": "indgo"}, + 'rx.ui.Theme: unknown accent_color "indgo". Did you mean "indigo"? ' + f"The values are {ACCENT_VALUES}.", + ), + ( + {"accent_color": "mauve"}, + f'rx.ui.Theme: unknown accent_color "mauve". The values are {ACCENT_VALUES}.', + ), + ( + {"gray_color": "slat"}, + 'rx.ui.Theme: unknown gray_color "slat". Did you mean "slate"? The ' + 'values are "auto", "gray", "mauve", "slate", "sage", "olive", "sand".', + ), + ( + {"radius": "big"}, + 'rx.ui.Theme: unknown radius "big". The values are "none", "small", ' + '"medium", "large", "full".', + ), + ( + {"scaling": 100}, + "rx.ui.Theme: unknown scaling 100. The values are " + '"90%", "95%", "100%", "105%", "110%".', + ), + ( + {"scaling": "100"}, + 'rx.ui.Theme: unknown scaling "100". Did you mean "100%"? The values ' + 'are "90%", "95%", "100%", "105%", "110%".', + ), + ( + {"appearance": "system"}, + 'rx.ui.Theme: unknown appearance "system". The values are ' + '"inherit", "light", "dark".', + ), + ( + {"panel_background": None}, + "rx.ui.Theme: unknown panel_background None. The values are " + '"solid", "translucent".', + ), + ( + {"has_background": "yes"}, + "rx.ui.Theme: has_background must be True or False, not 'yes'.", + ), + ( + {"accent_color": ThemeState.accent}, + "rx.ui.Theme: accent_color is bound to state, but the theme of an " + "app is compiled ahead of time. Give it one of its values, or bind " + "the option of an rx.ui.theme(...) around the page.", + ), + ], +) +def test_theme_refuses_a_value_an_option_does_not_take( + options: dict[str, Any], message: str +): + """A mistake in rxconfig.py stops the app there, and says what to write. + + Args: + options: The options of the theme. + message: The whole error message. + """ + with pytest.raises(ThemeError) as error: + Theme(**options) + assert str(error.value) == message + + +def test_app_theme_sets_every_option(): + """The element around an app depends on nothing outside it.""" + assert app_theme_styles( + Theme(accent_color="indigo", radius="large") + ) == ThemeStyles( + refs=( + *SCOPES, + "focusScope", + "accentIndigo", + "graySlate", + "radiusLarge", + "scaling100", + "panelTranslucent", + "reflexUITheme.root", + "reflexUITheme.background", + ), + imports=( + ("themes/accent/indigo.js", "accentIndigo", None), + FOCUS_IMPORT, + ("themes/gray/slate.js", "graySlate", None), + ("themes/panel.js", "panelTranslucent", None), + ("themes/radius.js", "radiusLarge", None), + ("themes/scaling.js", "scaling100", None), + *SCOPE_IMPORTS, + STYLES_IMPORT, + ), + class_name="reflex-ui-theme", + ) + assert app_theme_styles( + Theme( + accent_color="gray", + gray_color="olive", + radius="none", + scaling="110%", + appearance="dark", + panel_background="solid", + has_background=False, + ) + ) == ThemeStyles( + refs=( + *SCOPES, + "focusScope", + "accentGray", + "grayOlive", + "radiusNone", + "scaling110", + "panelSolid", + "reflexUITheme.root", + "reflexUITheme.dark", + ), + imports=( + ("themes/accent/gray.js", "accentGray", None), + FOCUS_IMPORT, + ("themes/gray/olive.js", "grayOlive", None), + ("themes/panel.js", "panelSolid", None), + ("themes/radius.js", "radiusNone", None), + ("themes/scaling.js", "scaling110", None), + *SCOPE_IMPORTS, + STYLES_IMPORT, + ), + class_name="reflex-ui-theme dark", + ) + + +def test_every_accent_has_the_gray_that_matches_it(): + """``auto`` is resolved when the app is compiled.""" + for accent, gray in _radix_tokens.MATCHING_GRAY.items(): + styles = app_theme_styles(Theme(accent_color=accent)) # pyright: ignore [reportArgumentType] + assert styles.refs[6:8] == ( + f"accent{accent.capitalize()}", + f"gray{gray.capitalize()}", + ) + assert styles.imports[:3] == ( + (f"themes/accent/{accent}.js", f"accent{accent.capitalize()}", None), + FOCUS_IMPORT, + (f"themes/gray/{gray}.js", f"gray{gray.capitalize()}", None), + ) + + +def _nested( + refs: tuple[str, ...], + imports: tuple[tuple[str, str, str | None], ...], + class_name: str = "reflex-ui-theme", +) -> ThemeStyles: + """Build what a nested theme is expected to need. + + Args: + refs: The arguments after the scopes, the focus and before the root style. + imports: The imports beside the ones every theme element has. + class_name: The class names of the element. + + Returns: + The expected styles. + """ + after = tuple(ref for ref in refs if ref.startswith("reflexUITheme")) + before = refs[: len(refs) - len(after)] + return ThemeStyles( + refs=(*SCOPES, "focusScope", *before, "reflexUITheme.root", *after), + imports=tuple(sorted([*imports, FOCUS_IMPORT, *SCOPE_IMPORTS, STYLES_IMPORT])), + class_name=class_name, + ) + + +RED = ("themes/accent/red.js", "accentRed", None) +MAUVE = ("themes/gray/mauve.js", "grayMauve", None) +OLIVE = ("themes/gray/olive.js", "grayOlive", None) +GRAY_ACCENT = ("themes/accent/gray.js", "accentGray", None) + + +@pytest.mark.parametrize( + ("options", "app_theme", "expected"), + [ + # Nothing set: the element only declares again what reads the theme. + ({}, Theme(), _nested((), ())), + # Under the automatic gray of the app, the gray follows the accent. + ( + {"accent_color": "red"}, + Theme(), + _nested(("accentRed", "grayMauve"), (RED, MAUVE)), + ), + ( + {"accent_color": "red"}, + Theme(gray_color="sand"), + _nested(("accentRed",), (RED,)), + ), + ( + {"accent_color": "red", "gray_color": "olive"}, + Theme(), + _nested(("accentRed", "grayOlive"), (RED, OLIVE)), + ), + ( + {"accent_color": "red", "gray_color": "auto"}, + Theme(gray_color="sand"), + _nested(("accentRed", "grayMauve"), (RED, MAUVE)), + ), + # A gray alone, and the gray that matches the accent of the app. + ({"gray_color": "olive"}, Theme(), _nested(("grayOlive",), (OLIVE,))), + ( + {"gray_color": "auto"}, + Theme(accent_color="red"), + _nested(("grayMauve",), (MAUVE,)), + ), + # Under the gray accent, the accent is named again to follow the gray. + ( + {"gray_color": "olive"}, + Theme(accent_color="gray"), + _nested(("accentGray", "grayOlive"), (GRAY_ACCENT, OLIVE)), + ), + ( + {"radius": "full", "scaling": "90%", "panel_background": "solid"}, + Theme(), + _nested( + ("radiusFull", "scaling90", "panelSolid"), + ( + ("themes/radius.js", "radiusFull", None), + ("themes/scaling.js", "scaling90", None), + ("themes/panel.js", "panelSolid", None), + ), + ), + ), + # An appearance paints the background unless it is told not to. + ( + {"appearance": "dark"}, + Theme(), + _nested( + ("reflexUITheme.background", "reflexUITheme.dark"), + (), + "reflex-ui-theme dark", + ), + ), + ( + {"appearance": "light", "has_background": False}, + Theme(), + _nested(("reflexUITheme.light",), (), "reflex-ui-theme light"), + ), + ({"appearance": "inherit"}, Theme(), _nested((), ())), + ( + {"has_background": True}, + Theme(), + _nested(("reflexUITheme.background",), ()), + ), + # A Var that holds a constant is the constant. + ( + { + "accent_color": LiteralVar.create("red"), + "appearance": LiteralVar.create("dark"), + "has_background": LiteralVar.create(False), + }, + Theme(), + _nested( + ("accentRed", "grayMauve", "reflexUITheme.dark"), + (RED, MAUVE), + "reflex-ui-theme dark", + ), + ), + ], +) +def test_nested_theme_sets_what_it_is_given( + options: dict[str, Any], app_theme: Theme, expected: ThemeStyles +): + """A literal option imports the one StyleX theme it names. + + Args: + options: The options of the nested theme. + app_theme: The theme of the app. + expected: What the element needs. + """ + assert theme_styles("rx.ui.theme", **options, app_theme=app_theme) == expected + + +def test_accent_bound_to_state_imports_every_accent(): + """The page chooses among all of them, and the gray that matches each.""" + accent = str(ThemeState.accent) + styles = theme_styles( + "rx.ui.theme", accent_color=ThemeState.accent, app_theme=Theme() + ) + assert styles.refs == ( + *SCOPES, + "focusScope", + f"reflexUIAccents[{accent}]", + f"reflexUIMatchingGrays[{accent}]", + "reflexUITheme.root", + ) + assert styles.imports == tuple( + sorted([ + *ACCENT_IMPORTS, + *GRAY_IMPORTS, + FOCUS_IMPORT, + *SCOPE_IMPORTS, + STYLES_IMPORT, + ]) + ) + assert styles.declarations == ( + ACCENT_MAP, + "const reflexUIMatchingGrays = { " + + ", ".join( + f'"{name}": gray{gray.capitalize()}' + for name, gray in sorted(_radix_tokens.MATCHING_GRAY.items()) + ) + + " };", + ) + assert styles.class_name == "reflex-ui-theme" + assert styles.var_data == ThemeState.accent._get_all_var_data() + + # With a gray of its own, only the accents are imported. + styles = theme_styles( + "rx.ui.theme", + accent_color=ThemeState.accent, + gray_color="sand", + app_theme=Theme(), + ) + assert styles.refs == ( + *SCOPES, + "focusScope", + f"reflexUIAccents[{accent}]", + "graySand", + "reflexUITheme.root", + ) + assert styles.imports == tuple( + sorted([ + *ACCENT_IMPORTS, + ("themes/gray/sand.js", "graySand", None), + FOCUS_IMPORT, + *SCOPE_IMPORTS, + STYLES_IMPORT, + ]) + ) + assert styles.declarations == (ACCENT_MAP,) + + +def test_every_option_can_be_bound_to_state(): + state = ThemeState + styles = theme_styles( + "rx.ui.theme", + gray_color=state.gray, + radius=state.radius, + scaling=state.scaling, + panel_background=state.panel, + appearance=state.appearance, + has_background=state.background, + app_theme=Theme(), + ) + appearance = str(state.appearance) + assert styles.refs == ( + *SCOPES, + "focusScope", + f"reflexUIGrays[{state.gray!s}]", + f"reflexUIRadii[{state.radius!s}]", + f"reflexUIScalings[{state.scaling!s}]", + f"reflexUIPanels[{state.panel!s}]", + "reflexUITheme.root", + f"({state.background!s}) && reflexUITheme.background", + f"reflexUITheme[{appearance}]", + f'({appearance}) !== "inherit" && {{ $$css: true, appearance: {appearance} }}', + ) + assert styles.declarations == ( + 'const reflexUIGrays = { "gray": grayGray, "mauve": grayMauve, ' + '"olive": grayOlive, "sage": graySage, "sand": graySand, ' + '"slate": graySlate };', + 'const reflexUIRadii = { "full": radiusFull, "large": radiusLarge, ' + '"medium": radiusMedium, "none": radiusNone, "small": radiusSmall };', + 'const reflexUIScalings = { "100%": scaling100, "105%": scaling105, ' + '"110%": scaling110, "90%": scaling90, "95%": scaling95 };', + 'const reflexUIPanels = { "solid": panelSolid, ' + '"translucent": panelTranslucent };', + ) + assert styles.imports == tuple( + sorted([ + *GRAY_IMPORTS, + FOCUS_IMPORT, + *( + ("themes/panel.js", name, None) + for name in ("panelSolid", "panelTranslucent") + ), + *( + ("themes/radius.js", f"radius{name}", None) + for name in ("Full", "Large", "Medium", "None", "Small") + ), + *( + ("themes/scaling.js", f"scaling{name}", None) + for name in ("100", "105", "110", "90", "95") + ), + *SCOPE_IMPORTS, + STYLES_IMPORT, + ]) + ) + assert styles.var_data == rx.vars.VarData.merge( + state.gray._get_all_var_data(), + state.radius._get_all_var_data(), + state.scaling._get_all_var_data(), + state.panel._get_all_var_data(), + state.appearance._get_all_var_data(), + state.background._get_all_var_data(), + ) + + # An appearance bound to state paints the background when it is one. + styles = theme_styles("rx.ui.theme", appearance=state.appearance, app_theme=Theme()) + assert styles.refs == ( + *SCOPES, + "focusScope", + "reflexUITheme.root", + f'({appearance}) !== "inherit" && reflexUITheme.background', + f"reflexUITheme[{appearance}]", + f'({appearance}) !== "inherit" && {{ $$css: true, appearance: {appearance} }}', + ) + + +@pytest.mark.parametrize( + ("options", "app_theme", "message"), + [ + ( + {"accent_color": "rubby"}, + Theme(), + 'rx.ui.theme: unknown accent_color "rubby". Did you mean "ruby"? ' + f"The values are {ACCENT_VALUES}.", + ), + ( + {"gray_color": "blue"}, + Theme(), + 'rx.ui.theme: unknown gray_color "blue". The values are "auto", ' + '"gray", "mauve", "slate", "sage", "olive", "sand".', + ), + ( + {"radius": "round"}, + Theme(), + 'rx.ui.theme: unknown radius "round". The values are "none", ' + '"small", "medium", "large", "full".', + ), + ( + {"appearance": "night"}, + Theme(), + 'rx.ui.theme: unknown appearance "night". Did you mean "light"? The values are ' + '"inherit", "light", "dark".', + ), + ( + {"has_background": 1}, + Theme(), + "rx.ui.theme: has_background must be True or False, not 1.", + ), + ( + {"gray_color": "auto"}, + None, + 'rx.ui.theme: gray_color "auto" is the gray that matches an accent ' + "color. Give accent_color too, or name the gray.", + ), + ], +) +def test_nested_theme_refuses_a_value_an_option_does_not_take( + options: dict[str, Any], app_theme: Theme | None, message: str +): + """The error names the component and lists what the option takes. + + Args: + options: The options of the nested theme. + app_theme: The theme of the app. + message: The whole error message. + """ + with pytest.raises(ThemeError) as error: + theme_styles("rx.ui.theme", **options, app_theme=app_theme) + assert str(error.value) == message + + +def test_color_scheme_is_an_accent_on_one_element(): + """A component with a color imports its accent, and the focus that follows.""" + assert color_scheme_styles("rx.ui.button", "red") == ThemeStyles( + refs=("accentRed", "focusScope"), imports=(RED, FOCUS_IMPORT) + ) + assert color_scheme_styles("rx.ui.button", LiteralVar.create("red")) == ThemeStyles( + refs=("accentRed", "focusScope"), imports=(RED, FOCUS_IMPORT) + ) + # A gray component keeps the focus colors of the theme, as in Radix Themes. + assert color_scheme_styles("rx.ui.button", "gray") == ThemeStyles( + refs=("accentGray",), imports=(GRAY_ACCENT,) + ) + accent = str(ThemeState.accent) + assert color_scheme_styles("rx.ui.button", ThemeState.accent) == ThemeStyles( + refs=(f"reflexUIAccents[{accent}]", f'({accent}) !== "gray" && focusScope'), + imports=(*ACCENT_IMPORTS, FOCUS_IMPORT), + declarations=(ACCENT_MAP,), + var_data=ThemeState.accent._get_all_var_data(), + ) + with pytest.raises(ThemeError) as error: + color_scheme_styles("rx.ui.button", "slate") + assert str(error.value) == ( + f'rx.ui.button: unknown color_scheme "slate". The values are {ACCENT_VALUES}.' + ) + + +def test_import_dict_names_the_modules_as_an_app_imports_them(): + assert color_scheme_styles("rx.ui.button", "red").import_dict() == { + "$/reflex-ui/themes/accent/red.js": [ImportVar(tag="accentRed")], + "$/reflex-ui/themes/focus.js": [ImportVar(tag="focusScope")], + } + assert theme_styles("rx.ui.theme", app_theme=Theme()).import_dict() == { + "$/reflex-ui/themes/focus.js": [ImportVar(tag="focusScope")], + "$/reflex-ui/themes/scope.js": [ + ImportVar(tag="colorScope"), + ImportVar(tag="radiusScope"), + ImportVar(tag="shadowScope"), + ImportVar(tag="spaceScope"), + ImportVar(tag="typographyScope"), + ], + "$/reflex-ui/themes/theme.js": [ImportVar(tag="theme", alias="reflexUITheme")], + } diff --git a/tests/units/reflex_components_ui/test_tokens.py b/tests/units/reflex_components_ui/test_tokens.py new file mode 100644 index 00000000000..cf3089beb8e --- /dev/null +++ b/tests/units/reflex_components_ui/test_tokens.py @@ -0,0 +1,223 @@ +"""Tests for reflex_components_ui.tokens.""" + +import copy +from collections.abc import Callable +from typing import Any, get_args + +import pytest +from reflex_components_ui import tokens +from reflex_components_ui._radix_tokens import VAR_GROUPS +from reflex_components_ui.style.lower import Lowered, lower +from reflex_components_ui.tokens import TokenError + +import reflex as rx + +SCALES = get_args(tokens.LiteralColorScale) + +SCALE_NAMES = ( + "amber, blue, bronze, brown, crimson, cyan, gold, grass, green, indigo, " + "iris, jade, lime, mauve, mint, olive, orange, pink, plum, purple, red, " + "ruby, sage, sand, sky, slate, teal, tomato, violet, yellow" +) + + +def _all(group: Any) -> list[str]: + """List every token of a group, and of the groups inside it. + + Args: + group: A token, or a group of tokens. + + Returns: + The tokens. + """ + if isinstance(group, str): + return [group] + found = list(group._steps) + for name, value in vars(group).items(): + if name[0] != "_": + found.extend(_all(value)) + return found + + +def _every_token() -> list[str]: + """List every token an app can name. + + Returns: + The tokens of the module, then the ones of each color scale. + """ + found = [] + for name, value in vars(tokens).items(): + if name[0] != "_" and isinstance(value, (str, tokens._Tokens)): + found.extend(_all(value)) + for name in SCALES: + found.extend(_all(tokens.scale(name))) + return found + + +def test_tokens_are_the_custom_properties_of_radix_themes(): + """An app can name every custom property the modules define, and no other.""" + defined = [f"var({name})" for _, names in VAR_GROUPS.values() for name in names] + assert len(defined) == 1070 + found = _every_token() + assert sorted(found) == sorted(defined) + + +def test_color_scales_are_the_generated_ones(): + """The accent and the gray of the theme aside, a scale is a color module.""" + assert sorted(SCALES) == sorted( + name + for name, (module, names) in VAR_GROUPS.items() + if module.startswith("colors/") and len(names) == 28 + ) + + +def test_a_token_is_a_plain_string(): + """The examples of the documentation, and the type every style takes.""" + assert tokens.space[4] == "var(--space-4)" + assert tokens.radius[3] == "var(--radius-3)" + assert tokens.radius.full == "var(--radius-full)" + assert tokens.shadow[3] == "var(--shadow-3)" + assert tokens.accent[9] == "var(--accent-9)" + assert tokens.accent.a[3] == "var(--accent-a3)" + assert tokens.accent.contrast == "var(--accent-contrast)" + assert tokens.gray[11] == "var(--gray-11)" + assert tokens.focus.a[5] == "var(--focus-a5)" + assert tokens.font_size[2] == "var(--font-size-2)" + assert tokens.line_height[2] == "var(--line-height-2)" + assert tokens.letter_spacing[2] == "var(--letter-spacing-2)" + assert tokens.font_weight.bold == "var(--font-weight-bold)" + assert tokens.heading.line_height[9] == "var(--heading-line-height-9)" + assert tokens.default.font_family == "var(--default-font-family)" + assert tokens.code.padding_top == "var(--code-padding-top)" + assert tokens.color.panel_solid == "var(--color-panel-solid)" + assert tokens.cursor.slider_thumb_active == "var(--cursor-slider-thumb-active)" + assert tokens.panel.backdrop_filter == "var(--backdrop-filter-panel)" + assert tokens.black.a[12] == "var(--black-a12)" + assert tokens.scaling == "var(--scaling)" + assert tokens.scale("ruby")[9] == f"{rx.color('ruby', 9)}" + assert tokens.scale("ruby").a[3] == f"{rx.color('ruby', 3, True)}" + assert tokens.scale("ruby").track == "var(--ruby-track)" + assert tokens.scale("ruby") is tokens.scale("ruby") + assert {type(token) for token in _every_token()} == {str} + assert f"calc({tokens.space[4]} * 2)" == "calc(var(--space-4) * 2)" + + +def test_every_token_lowers_to_itself_and_imports_its_module(): + """A style names the module that defines each token it uses.""" + count = 0 + for module, names in VAR_GROUPS.values(): + for name in names: + token = f"var({name})" + assert lower("rx.ui.box", {"--probe": token}) == Lowered( + {"--probe": token}, (f"$/reflex-ui/{module}",) + ), name + count += 1 + assert count == len(_every_token()) + + +@pytest.mark.parametrize( + ("get", "message"), + [ + ( + lambda: tokens.space[10], # pyright: ignore [reportArgumentType] + "rx.ui.tokens.space has no step 10. Its steps are 1 to 9.", + ), + ( + lambda: tokens.space[0], # pyright: ignore [reportArgumentType] + "rx.ui.tokens.space has no step 0. Its steps are 1 to 9.", + ), + ( + lambda: tokens.space[-1], # pyright: ignore [reportArgumentType] + "rx.ui.tokens.space has no step -1. Its steps are 1 to 9.", + ), + ( + lambda: tokens.space["4"], # pyright: ignore [reportArgumentType] + "rx.ui.tokens.space has no step '4'. Its steps are 1 to 9.", + ), + ( + lambda: tokens.space[True], + "rx.ui.tokens.space has no step True. Its steps are 1 to 9.", + ), + ( + lambda: tokens.radius[7], # pyright: ignore [reportArgumentType] + "rx.ui.tokens.radius has no step 7. Its steps are 1 to 6.", + ), + ( + lambda: tokens.accent.a[13], # pyright: ignore [reportArgumentType] + "rx.ui.tokens.accent.a has no step 13. Its steps are 1 to 12.", + ), + ( + lambda: tokens.scale("ruby").a[0], # pyright: ignore [reportArgumentType] + 'rx.ui.tokens.scale("ruby").a has no step 0. Its steps are 1 to 12.', + ), + ( + lambda: tokens.font_weight[1], + "rx.ui.tokens.font_weight has no steps. Its tokens are bold, light, " + "medium, regular.", + ), + ( + lambda: tokens.black[3], + "rx.ui.tokens.black has no steps. Its tokens are a.", + ), + ( + lambda: tokens.accent.contrst, # pyright: ignore [reportAttributeAccessIssue] + 'rx.ui.tokens.accent has no token "contrst". Did you mean ' + '"contrast"? Its tokens are a, contrast, indicator, surface, track, ' + "and the steps [1] to [12].", + ), + ( + lambda: tokens.space.four, # pyright: ignore [reportAttributeAccessIssue] + 'rx.ui.tokens.space has no token "four". Its tokens are the steps ' + "[1] to [9].", + ), + ( + lambda: tokens.font_weight.semibold, # pyright: ignore [reportAttributeAccessIssue] + 'rx.ui.tokens.font_weight has no token "semibold". Did you mean "bold"? Its tokens are ' + "bold, light, medium, regular.", + ), + ( + lambda: tokens.focus.contrast, # pyright: ignore [reportAttributeAccessIssue] + 'rx.ui.tokens.focus has no token "contrast". Its tokens are a, and ' + "the steps [1] to [12].", + ), + ( + lambda: tokens.scale("rubby"), # pyright: ignore [reportArgumentType] + 'rx.ui.tokens.scale: unknown color scale "rubby". Did you mean ' + f'"ruby"? The scales are {SCALE_NAMES}.', + ), + ( + lambda: tokens.scale("gray"), # pyright: ignore [reportArgumentType] + 'rx.ui.tokens.scale: "gray" is not a color scale of its own, but ' + "the gray of the theme: use rx.ui.tokens.gray.", + ), + ( + lambda: tokens.scale(9), # pyright: ignore [reportArgumentType] + f"rx.ui.tokens.scale: unknown color scale 9. The scales are {SCALE_NAMES}.", + ), + ], +) +def test_a_token_that_does_not_exist_says_what_does( + get: Callable[[], str], message: str +): + """The same mistakes a type checker reports, where the app runs. + + Args: + get: Asks for the token. + message: The whole error message. + """ + with pytest.raises(TokenError) as error: + get() + assert str(error.value) == message + + +def test_token_error_is_what_python_expects_of_a_missing_name(): + """``hasattr`` and ``getattr`` with a default work, and so does copying.""" + assert not hasattr(tokens.accent, "contrst") + assert getattr(tokens.accent, "contrst", None) is None + assert issubclass(TokenError, (AttributeError, LookupError)) + assert copy.deepcopy(tokens.accent).a[3] == "var(--accent-a3)" + + +def test_tokens_are_a_name_of_the_ui_namespace(): + assert rx.ui.tokens is tokens + assert "tokens" in dir(rx.ui) From 795856c21909ec5af50895b1c066f6ee6830c053 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:21:09 +0000 Subject: [PATCH 16/26] Add the rx.ui parity harness and behaviour contract One command, scripts/ui_parity.py, checks an rx.ui component against the Radix component it replaces. A production app generated from the declarations in packages/reflex-components-ui/parity renders each component's matrix in both systems; the runner compares pixels (the pixelmatch method, anti-aliasing ignored), computed styles and the accessibility tree per cell, and runs each step of a behaviour contract against both systems in whichever engines are asked for. A matrix says which dimensions cross and which are swept, the cells at rest of a page load are read from one screenshot, and hover, focus and active are driven through the pointer and the keyboard. Intended differences live in parity/allowlist.toml with a reason, per component and per engine where needed; an entry nothing matches fails. tests/units/reflex_components_ui/test_api_parity.py compares props, types and event triggers with the same file. The integration workflow gains ui-parity (Chromium, report uploaded, 15 minute budget) and ui-contracts (Chromium, Firefox, WebKit), both behind the gate. box is the first component: zero differing pixels. Claude-Session: https://claude.ai/code/session_014AwvTQ75r2sBu4cRnbDwHn --- .github/workflows/integration_tests.yml | 80 +- AGENTS.md | 1 + packages/reflex-components-ui/README.md | 162 +++ .../news/+parity-harness.misc.md | 1 + .../reflex-components-ui/parity/.gitignore | 11 + .../parity/allowlist.toml | 48 + .../reflex-components-ui/parity/rxconfig.py | 10 + .../parity/ui_parity/__init__.py | 5 + .../parity/ui_parity/allowlist.py | 276 +++++ .../parity/ui_parity/api.py | 151 +++ .../parity/ui_parity/app.py | 174 ++++ .../parity/ui_parity/components/__init__.py | 35 + .../parity/ui_parity/components/box.py | 68 ++ .../parity/ui_parity/contract.py | 357 +++++++ .../parity/ui_parity/diff.py | 226 +++++ .../parity/ui_parity/look.py | 943 ++++++++++++++++++ .../parity/ui_parity/matrix.py | 310 ++++++ .../parity/ui_parity/report.py | 179 ++++ .../parity/ui_parity/systems.py | 42 + .../parity/ui_parity/ui_parity.py | 5 + pyproject.toml | 7 + scripts/ui_parity.py | 103 ++ .../tests_playwright/test_ui_parity.py | 336 +++++++ .../reflex_components_ui/parity/__init__.py | 0 .../parity/test_allowlist.py | 221 ++++ .../parity/test_contract.py | 96 ++ .../reflex_components_ui/parity/test_diff.py | 130 +++ .../reflex_components_ui/parity/test_look.py | 207 ++++ .../parity/test_matrix.py | 95 ++ .../parity/test_report.py | 145 +++ .../reflex_components_ui/test_api_parity.py | 172 ++++ tests/units/test_ui_parity_script.py | 50 + 32 files changed, 4645 insertions(+), 1 deletion(-) create mode 100644 packages/reflex-components-ui/news/+parity-harness.misc.md create mode 100644 packages/reflex-components-ui/parity/.gitignore create mode 100644 packages/reflex-components-ui/parity/allowlist.toml create mode 100644 packages/reflex-components-ui/parity/rxconfig.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/__init__.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/allowlist.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/api.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/app.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/__init__.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/box.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/contract.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/diff.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/look.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/matrix.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/report.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/systems.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/ui_parity.py create mode 100644 scripts/ui_parity.py create mode 100644 tests/integration/tests_playwright/test_ui_parity.py create mode 100644 tests/units/reflex_components_ui/parity/__init__.py create mode 100644 tests/units/reflex_components_ui/parity/test_allowlist.py create mode 100644 tests/units/reflex_components_ui/parity/test_contract.py create mode 100644 tests/units/reflex_components_ui/parity/test_diff.py create mode 100644 tests/units/reflex_components_ui/parity/test_look.py create mode 100644 tests/units/reflex_components_ui/parity/test_matrix.py create mode 100644 tests/units/reflex_components_ui/parity/test_report.py create mode 100644 tests/units/reflex_components_ui/test_api_parity.py create mode 100644 tests/units/test_ui_parity_script.py diff --git a/.github/workflows/integration_tests.yml b/.github/workflows/integration_tests.yml index 23ddd7ef686..9a7daf90057 100644 --- a/.github/workflows/integration_tests.yml +++ b/.github/workflows/integration_tests.yml @@ -349,7 +349,83 @@ jobs: - name: Run Playwright integration tests env: REFLEX_REDIS_URL: ${{ matrix.state_manager == 'redis' && 'redis://localhost:6379' || '' }} - run: uv run pytest tests/integration/tests_playwright --reruns 3 -rs -v --maxfail=5 --splits 2 --group ${{ matrix.split_index }} + # The rx.ui parity harness has jobs of its own below: it compares + # pixels, which a rerun must not paper over. + run: uv run pytest tests/integration/tests_playwright --ignore=tests/integration/tests_playwright/test_ui_parity.py --reruns 3 -rs -v --maxfail=5 --splits 2 --group ${{ matrix.split_index }} + + # The look of every rx.ui component against the Radix one it replaces: + # pixels, computed styles and accessibility tree, cell by cell. + ui-parity: + needs: changes + if: needs.changes.outputs.run == 'true' + timeout-minutes: 30 + runs-on: ubuntu-22.04 + env: + UI_PARITY_REPORT: ui-parity-report + # The build and every matrix together, in seconds: the run fails above. + UI_PARITY_BUDGET_SECONDS: "900" + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-tags: true + fetch-depth: 0 + persist-credentials: false + - uses: ./.github/actions/setup_build_env + with: + python-version: "3.14" + run-uv-sync: true + - name: Install Playwright Chromium + run: uv run playwright install chromium --only-shell + - name: Compare every matrix with Radix Themes + run: uv run pytest tests/integration/tests_playwright/test_ui_parity.py -k "not test_contract" -rs -v + - name: Report the run time + if: always() + run: | + if [ -f "$UI_PARITY_REPORT/timings.json" ]; then + { + echo '### rx.ui parity run time' + echo '```json' + cat "$UI_PARITY_REPORT/timings.json" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + fi + - name: Upload the report + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ui-parity-report + path: ui-parity-report + if-no-files-found: warn + + # The behaviour contract of every rx.ui component, and of the Radix one it + # replaces, in each browser engine. + ui-contracts: + needs: changes + if: needs.changes.outputs.run == 'true' + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + engine: [chromium, firefox, webkit] + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-tags: true + fetch-depth: 0 + persist-credentials: false + - uses: ./.github/actions/setup_build_env + with: + python-version: "3.14" + run-uv-sync: true + - name: Install Playwright ${{ matrix.engine }} + env: + ENGINE: ${{ matrix.engine }} + run: uv run playwright install --with-deps "$ENGINE" + - name: Run every contract in ${{ matrix.engine }} + env: + ENGINE: ${{ matrix.engine }} + run: uv run pytest tests/integration/tests_playwright/test_ui_parity.py --browser "$ENGINE" -k test_contract -rs -v bun-only-startup: needs: changes @@ -413,6 +489,8 @@ jobs: reflex-docs-macos, app-harness, app-harness-playwright, + ui-parity, + ui-contracts, bun-only-startup, ] if: always() diff --git a/AGENTS.md b/AGENTS.md index 81af9d2ab5e..2dbd53f2dca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,7 @@ uv run python scripts/make_pyi.py # regenerate .p uv run pre-commit run --all-files # all pre-commit hooks npm --prefix packages/reflex-frontend ci && npm --prefix packages/reflex-frontend run check # frontend package: lint, type-check (JSDoc) and unit tests npm --prefix packages/reflex-components-ui/js ci && npm --prefix packages/reflex-components-ui/js run check # rx.ui javascript: lint, type-check (JSDoc), generated files and unit tests +uv run python scripts/ui_parity.py [component] # rx.ui parity harness: look and behaviour against the Radix components, in Chromium (--all-engines adds Firefox and WebKit) ``` ## Layout diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index ca9a800ead3..54cafc74946 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -35,6 +35,9 @@ js/ the javascript package, with its own tooling vite-plugin-stylex.js the StyleX Vite plugin, fitted to the Reflex build tests/ vitest scripts/generate.js writes and checks the generated files +parity/ the parity harness: is a component the Radix one? Not shipped + ui_parity/components/ the matrix and the contract of each component + allowlist.toml every intended difference from Radix, with its reason hatch_build.py embeds js/src in the wheel ``` @@ -103,6 +106,165 @@ element to that app for a new component rather than a new app. nothing emitted), `run generate:check` and `test` (vitest), which also run on their own. +## The parity harness + +`rx.button(...)` becomes `rx.ui.button(...)` with the same arguments, the same +look and the same behaviour. `parity/` checks that by machine: + +``` +uv run python scripts/ui_parity.py box # one component, in Chromium +uv run python scripts/ui_parity.py # every component, in Chromium +uv run python scripts/ui_parity.py --all-engines # and in Firefox and WebKit +uv run python scripts/ui_parity.py differences # the intended differences, as markdown +uv run pytest tests/units/reflex_components_ui # the API parity test, and the harness's own tests +``` + +Other arguments go to pytest (`-x`, `-k`), and `--engine firefox` picks one +engine. The browsers come from `uv run playwright install chromium firefox webkit`. +The command builds one production app from the declarations in +`parity/ui_parity/components/` and runs +`tests/integration/tests_playwright/test_ui_parity.py` against it: + +- **Look** (`test_matrix`). A page per component renders every element of its + matrix twice, the Radix component beside the rx.ui one, each in a frame of a + fixed size. Per cell the harness compares the pixels (anti-aliasing ignored), + the computed style on a list of properties, and the accessibility tree. +- **Behaviour** (`test_contract`). Each step of a component's contract runs on a + page of its own, against the Radix component and against the rx.ui one, in + each engine asked for. +- **API** (`tests/units/reflex_components_ui/test_api_parity.py`). The props, + their types and literal values, and the event triggers of every name in + `rx.ui` are those of the same name in `rx`. + +A failure names what differed, by how much, and where to look: + +``` +box [chromium] cell base@hover: + - 712 of 10304 pixels differ (6.91%, 0.00% allowed) + - padding-top: rx '0px', rx.ui '3px' + images: .../parity/report/chromium/box/base@hover.{reference,candidate,diff}.png +box [rx.ui, webkit] step "Space toggles" failed: AssertionError: ... +``` + +The run writes a report to `parity/report/` (or `--report DIR`): `index.html` +shows the reference, the candidate and the diff of every cell with its numbers, +grouped by component, `results.json` holds the same numbers and `timings.json` +the run time. The directory is self-contained: zip it or publish it for review. +CI uploads it as the `ui-parity-report` artifact of the `ui-parity` job. + +To look at the pages by hand, `cd packages/reflex-components-ui/parity` and +`uv run reflex run`: `/parity/` and `/contract//`. + +### Adding a component + +A component wave adds, beside the wrapper and its style table, one module: +`parity/ui_parity/components/.py`. It is found by its place; nothing +registers it. + +1. Declare the matrix. Dimensions are props, or `appearance`, `state` and + `viewport`, which the runner provides. `cross` takes every combination, + `sweep` varies one dimension at a time from `base`, and `groups` adds + further small cross products. Cross what interacts (variant with size), and + sweep the rest (32 colors, radius, contrast): a full product does not fit + the run-time budget. + + ```python + MATRIX = Matrix( + component="button", + render=lambda namespace, props: namespace.button("Save", **props), + base={"variant": "solid", "size": "2"}, + cross={"variant": ["solid", "soft", "outline"], "size": ["1", "2", "3"]}, + sweep={ + "color_scheme": ["tomato", "indigo", "gray"], + "high_contrast": [True], + "disabled": [True], + "size": {"responsive": {"initial": "1", "md": "3"}}, + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE, ACTIVE], + "viewport": [520], + }, + groups=[{"variant": ["soft", "outline"], "state": [HOVER], "appearance": [DARK]}], + ) + ``` + + A cell is named after what differs from the base: `size-1_variant-soft`, + `base@dark@hover`. `target` and `parts` name the elements whose computed + style is read when it is not the first element, `stage` sizes the frame, + `crop="stage"` compares the whole frame for what is drawn outside the + element, and `states` adds a driver for a state the runner does not know, + such as `open`. + +2. Declare the contract: what `render` shows, then one step per requirement. + A step runs on the server's HTML (`SERVER`), on the page with scripts off + (`NO_JAVASCRIPT`) or on the hydrated page (the default), and is a plain + function that drives `run.page` and asserts. Every contract already has the + step "hydrates with no warnings". + + ```python + CONTRACT = Contract( + component="switch", + render=lambda namespace: namespace.switch(id="switch"), + ) + + + @CONTRACT.step("Space toggles") + def _space(run: Run) -> None: + switch = run.page.locator("#switch") + switch.focus() + run.page.keyboard.press("Space") + assert switch.get_attribute("aria-checked") == "true" + ``` + +3. Run `uv run python scripts/ui_parity.py ` and open + `parity/report/index.html`. Fix every difference, or, when it is intended, + list it in `parity/allowlist.toml` with a reason written for a user: under + `[[api]]`, `[[contract]]` (per system, per engine where needed) or + `[[look]]`. A listed difference passes; an entry nothing matches any more + fails, so the file stays the complete list, and the migration guide is + generated from it. + +4. Run `--all-engines` before the wave is reviewed, and add the wave's run + time to the table below. + +### What keeps a pixel from flaking + +Both systems are on one page, in frames on the pixel grid, and are cropped by +the same rectangle relative to their frame. The device scale factor and the +viewport are fixed, the page is hydrated and its fonts loaded before it is +read, transitions and animations are off, and the "Built with Reflex" badge is +not rendered. Hover, focus and active are driven through the pointer and the +keyboard, never by a class, and the run stops if an element does not match +`:hover`, `:focus-visible` or `:active` when it should. The CI jobs do not +rerun a failure. + +A pixel differs when its color is off by more than `threshold` (0.01 of the +distance from black to white, about two steps of a channel: the browser +dithers by position) and it is not on an anti-aliased edge; a cell fails above +`tolerance` (0.5% of its pixels). A matrix may tighten both, as the box does. + +### Run time + +The build and every matrix together must take under 15 minutes +(`UI_PARITY_BUDGET_SECONDS`), or `test_run_time_is_within_budget` fails. The +cells at rest of a page load are read from one screenshot and one script +call; an interactive cell is driven on its own. Measured in Chromium on the +development container, with boxes: + +| cells at rest | interactive cells | page loads | build | matrix | +| --- | --- | --- | --- | --- | +| 100 | 0 | 1 | 6 s | 1.1 s | +| 1000 | 0 | 1 | 14 s | 15.6 s | +| 100 | 100 | 1 | 6 s | 14.5 s | +| 1000 | 300 | 1 | 18 s | 58.5 s | + +So a cell at rest costs 11 to 16 ms (growing with the length of the page), an +interactive cell about 0.14 s, and a page load (one per viewport and +appearance) about 0.3 s. Keep interactive states to a sweep or a small group. + +| wave | components | cells | Chromium, build + matrices | +| --- | --- | --- | --- | +| harness | box | 8 | 5 s + 1.1 s | + ## Rules the tooling enforces - **No React components in `js/src`.** Markup comes from the Python wrappers. diff --git a/packages/reflex-components-ui/news/+parity-harness.misc.md b/packages/reflex-components-ui/news/+parity-harness.misc.md new file mode 100644 index 00000000000..5e5fc87e5fe --- /dev/null +++ b/packages/reflex-components-ui/news/+parity-harness.misc.md @@ -0,0 +1 @@ +Add the parity harness that checks each `rx.ui` component against the Radix component it replaces: pixels, computed styles, accessibility tree, behaviour in three browser engines, and Python API. diff --git a/packages/reflex-components-ui/parity/.gitignore b/packages/reflex-components-ui/parity/.gitignore new file mode 100644 index 00000000000..60126784409 --- /dev/null +++ b/packages/reflex-components-ui/parity/.gitignore @@ -0,0 +1,11 @@ +# What a run of the harness leaves here. +report/ +# What `reflex run` leaves here, as it would add the lines itself. +.states +.web +reflex.lock/ +assets/ +*.db +__pycache__/ +assets/external/ +*.py[cod] diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml new file mode 100644 index 00000000000..52973e69389 --- /dev/null +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -0,0 +1,48 @@ +# The intended differences between rx.ui and the Radix components it replaces. +# +# Every check of the parity harness reads this file. A difference listed here +# passes; an entry that no longer matches a difference fails, so the file stays +# the complete list, and the migration guide is generated from it +# (`uv run python scripts/ui_parity.py differences`). Every entry needs a `reason` +# written for a user of the components. +# +# [[api]] a prop or an event trigger differs (tests/units/reflex_components_ui/test_api_parity.py) +# component the name in both namespaces: "box" is rx.box and rx.ui.box +# kind "prop" (one system lacks it), "type" (it takes other values) or "event" +# names the props or event triggers +# +# [[contract]] a step of a behaviour contract does not pass +# component +# step the name of the step, as the contract declares it +# system "rx.ui" (the default) or "rx": the system that does not pass +# engines ["chromium", "firefox", "webkit"]; every engine when left out +# +# [[look]] pixels, computed style or accessibility tree differ +# component +# check "pixels", "style" or "a11y" +# cells a shell pattern over the cell id; every cell when left out +# properties the computed properties that differ, for "style" +# engines as above + +[[api]] +component = "box" +kind = "prop" +names = [ + "access_key", + "auto_capitalize", + "content_editable", + "context_menu", + "dir", + "draggable", + "enter_key_hint", + "hidden", + "input_mode", + "item_prop", + "lang", + "role", + "slot", + "spell_check", + "tab_index", + "title", +] +reason = "rx.ui.box does not take the global HTML attributes as props yet. Pass them through custom_attrs until it does." diff --git a/packages/reflex-components-ui/parity/rxconfig.py b/packages/reflex-components-ui/parity/rxconfig.py new file mode 100644 index 00000000000..6903e2ea65b --- /dev/null +++ b/packages/reflex-components-ui/parity/rxconfig.py @@ -0,0 +1,10 @@ +"""The harness app as a project, to look at its pages by hand.""" + +import reflex as rx + +config = rx.Config( + app_name="ui_parity", + plugins=[rx.plugins.UIPlugin(), rx.plugins.TailwindV4Plugin()], + # The badge floats over the page, and over whatever cell lies under it. + show_built_with_reflex=False, +) diff --git a/packages/reflex-components-ui/parity/ui_parity/__init__.py b/packages/reflex-components-ui/parity/ui_parity/__init__.py new file mode 100644 index 00000000000..cfa3cddfd8f --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/__init__.py @@ -0,0 +1,5 @@ +"""The parity harness of rx.ui: is a component the Radix one it replaces? + +Not shipped: the package lives beside the wheel's source and is put on the +import path by pytest and by ``scripts/ui_parity.py``. +""" diff --git a/packages/reflex-components-ui/parity/ui_parity/allowlist.py b/packages/reflex-components-ui/parity/ui_parity/allowlist.py new file mode 100644 index 00000000000..2d2e1588542 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/allowlist.py @@ -0,0 +1,276 @@ +"""The intended differences between rx.ui and the Radix components. + +Every check of the harness reads ``allowlist.toml``: a difference listed there, +with its reason, passes, and an entry no difference matches any more fails, so +the file stays the complete list. The migration guide is generated from it. +""" + +from __future__ import annotations + +import dataclasses +import fnmatch +import tomllib +from pathlib import Path +from typing import Any + +from ui_parity.systems import CANDIDATE, SYSTEMS + +ALLOWLIST = Path(__file__).parents[1] / "allowlist.toml" + +API_KINDS = ("prop", "type", "event") +LOOK_CHECKS = ("pixels", "style", "a11y") + + +class AllowlistError(ValueError): + """An entry of the allowlist is not one the harness understands.""" + + +@dataclasses.dataclass(frozen=True) +class ApiEntry: + """Props or event triggers that differ on purpose. + + Attributes: + component: The component. + kind: What differs: whether a ``prop`` exists, the ``type`` of one, or + whether an ``event`` trigger exists. + names: The props or event triggers. + reason: Why, for a reader of the migration guide. + """ + + component: str + kind: str + names: tuple[str, ...] + reason: str + + +@dataclasses.dataclass(frozen=True) +class ContractEntry: + """A step of a behaviour contract one system does not pass, on purpose. + + Attributes: + component: The component. + step: The name of the step. + system: The system that does not pass it. + engines: The browser engines it does not pass in: all when empty. + reason: Why, for a reader of the migration guide. + """ + + component: str + step: str + system: str + engines: tuple[str, ...] + reason: str + + def covers(self, component: str, step: str, system: str, engine: str) -> bool: + """Check whether the entry is about one run of a step. + + Args: + component: The component the step belongs to. + step: The name of the step. + system: The name of the system it ran against. + engine: The browser engine it ran in. + + Returns: + Whether the step is expected to fail there. + """ + return ( + self.component == component + and self.step == step + and self.system == system + and (not self.engines or engine in self.engines) + ) + + +@dataclasses.dataclass(frozen=True) +class LookEntry: + """A visible difference from the Radix component, on purpose. + + Attributes: + component: The component. + check: What differs: the ``pixels``, the computed ``style`` or the + ``a11y`` tree. + cells: The cells it differs in, as a shell pattern over the cell id. + properties: The computed properties that differ, for ``style``. + engines: The browser engines it differs in: all when empty. + reason: Why, for a reader of the migration guide. + """ + + component: str + check: str + cells: str + properties: tuple[str, ...] + engines: tuple[str, ...] + reason: str + + def covers(self, component: str, check: str, cell: str, engine: str) -> bool: + """Check whether the entry is about one check of a cell. + + Args: + component: The component of the cell. + check: The check that found a difference. + cell: The id of the cell. + engine: The browser engine it was rendered in. + + Returns: + Whether a difference is expected there. + """ + return ( + self.component == component + and self.check == check + and (not self.engines or engine in self.engines) + and fnmatch.fnmatchcase(cell, self.cells) + ) + + +@dataclasses.dataclass(frozen=True) +class Allowlist: + """Every intended difference. + + Attributes: + api: Differences of props and event triggers. + contract: Differences of behaviour. + look: Differences of pixels, computed style and accessibility tree. + """ + + api: tuple[ApiEntry, ...] = () + contract: tuple[ContractEntry, ...] = () + look: tuple[LookEntry, ...] = () + + +def _entry(table: str, raw: dict[str, Any], defaults: dict[str, Any]) -> dict[str, Any]: + """Validate the keys of one entry. + + Args: + table: The table the entry is in. + raw: The entry as the file has it. + defaults: The keys an entry may leave out, and their values. A key + without a default is required. + + Returns: + The entry with its defaults, lists as tuples. + + Raises: + AllowlistError: If a key is unknown or missing, or the reason is empty. + """ + required = {"component", "reason", *defaults} + if unknown := sorted(set(raw) - required): + msg = f"[[{table}]] entry {raw} has unknown keys: {unknown}." + raise AllowlistError(msg) + entry = {**defaults, **raw} + if missing := sorted(key for key in required if entry.get(key) is None): + msg = f"[[{table}]] entry {raw} is missing: {missing}." + raise AllowlistError(msg) + if not entry["reason"].strip(): + msg = f"[[{table}]] entry {raw} needs a reason." + raise AllowlistError(msg) + return { + key: tuple(value) if isinstance(value, list) else value + for key, value in entry.items() + } + + +def _one_of(table: str, key: str, value: str, choices: tuple[str, ...]) -> None: + """Reject a value outside the ones a key takes. + + Args: + table: The table the entry is in. + key: The key. + value: Its value. + choices: The values the key takes. + + Raises: + AllowlistError: If the value is not one of them. + """ + if value not in choices: + msg = f'[[{table}]] {key} = "{value}" is not one of {list(choices)}.' + raise AllowlistError(msg) + + +def parse(document: dict[str, Any]) -> Allowlist: + """Read an allowlist from its parsed TOML. + + Args: + document: The tables of the file. + + Returns: + The entries. + + Raises: + AllowlistError: If a table or an entry is not understood. + """ + if unknown := sorted(set(document) - {"api", "contract", "look"}): + msg = f"Unknown allowlist tables: {unknown}." + raise AllowlistError(msg) + api = [] + for raw in document.get("api", []): + entry = ApiEntry(**_entry("api", raw, {"kind": None, "names": None})) + _one_of("api", "kind", entry.kind, API_KINDS) + api.append(entry) + contract = [] + systems = tuple(system.name for system in SYSTEMS) + for raw in document.get("contract", []): + entry = ContractEntry( + **_entry( + "contract", + raw, + {"step": None, "system": CANDIDATE.name, "engines": ()}, + ) + ) + _one_of("contract", "system", entry.system, systems) + contract.append(entry) + look = [] + for raw in document.get("look", []): + entry = LookEntry( + **_entry( + "look", + raw, + {"check": None, "cells": "*", "properties": (), "engines": ()}, + ) + ) + _one_of("look", "check", entry.check, LOOK_CHECKS) + look.append(entry) + return Allowlist(api=tuple(api), contract=tuple(contract), look=tuple(look)) + + +def load(path: Path = ALLOWLIST) -> Allowlist: + """Read an allowlist file. + + Args: + path: The TOML file. + + Returns: + The entries. + """ + return parse(tomllib.loads(path.read_text(encoding="utf-8"))) + + +def differences_markdown(allowlist: Allowlist) -> str: + """Write the intended differences as a document section. + + Args: + allowlist: The entries. + + Returns: + A markdown list per component, in name order: what differs and why. + """ + lines: dict[str, list[str]] = {} + for entry in allowlist.api: + names = ", ".join(f"`{name}`" for name in entry.names) + lines.setdefault(entry.component, []).append( + f"- {entry.kind} {names}: {entry.reason}" + ) + for entry in allowlist.contract: + engines = f" in {', '.join(entry.engines)}" if entry.engines else "" + lines.setdefault(entry.component, []).append( + f'- behaviour, `{entry.system}`{engines}, "{entry.step}": {entry.reason}' + ) + for entry in allowlist.look: + engines = f" in {', '.join(entry.engines)}" if entry.engines else "" + what = ", ".join(f"`{name}`" for name in entry.properties) or entry.cells + lines.setdefault(entry.component, []).append( + f"- {entry.check}{engines}, {what}: {entry.reason}" + ) + return "\n\n".join( + "\n".join([f"### {component}", "", *lines[component]]) + for component in sorted(lines) + ) diff --git a/packages/reflex-components-ui/parity/ui_parity/api.py b/packages/reflex-components-ui/parity/ui_parity/api.py new file mode 100644 index 00000000000..25a0b5a37fa --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/api.py @@ -0,0 +1,151 @@ +"""Compare the Python API of an rx.ui component with its Radix counterpart. + +``rx.button(...)`` becomes ``rx.ui.button(...)`` with the same arguments, so +the props, the values their literals take and the event triggers must match. +""" + +from __future__ import annotations + +import dataclasses +import types +import typing +from typing import Any + +from reflex_base.components.component import Component + +from ui_parity.allowlist import Allowlist, ApiEntry + + +@dataclasses.dataclass(frozen=True) +class ApiDifference: + """One way the API of a component differs between the two systems. + + Attributes: + component: The component. + kind: ``prop`` or ``event`` when only one system has the name, + ``type`` when the prop takes different values. + name: The prop or the event trigger. + reference: The type of the prop or the presence of the name on the + Radix component, None when it lacks it. + candidate: The same on the rx.ui component. + """ + + component: str + kind: str + name: str + reference: str | None + candidate: str | None + + +def component_class(factory: Any) -> type[Component]: + """Find the component class behind a name of a namespace. + + Args: + factory: What ``rx.`` or ``rx.ui.`` is: a ``create`` + method, or a namespace that is called to create its root. + + Returns: + The class whose ``create`` the name calls. + """ + create = factory if isinstance(factory, types.MethodType) else factory.__call__ + return typing.cast("type[Component]", create.__self__) + + +def type_shape(annotation: Any) -> str: + """Describe a prop's type by what it accepts, not by where it is defined. + + Two systems each define their own literals and containers, so classes are + named without their module, and the values of a literal and the members of + a union are sorted. + + Args: + annotation: The annotation of the prop. + + Returns: + The description. + """ + origin = typing.get_origin(annotation) + args = typing.get_args(annotation) + if origin is typing.Literal: + return f"Literal[{', '.join(sorted(repr(arg) for arg in args))}]" + if origin in (typing.Union, types.UnionType): + return " | ".join(sorted({type_shape(arg) for arg in args})) + if origin is not None: + return f"{origin.__name__}[{', '.join(type_shape(arg) for arg in args)}]" + if annotation is None or annotation is type(None): + return "None" + return getattr(annotation, "__name__", repr(annotation)) + + +def diff_api( + component: str, reference: type[Component], candidate: type[Component] +) -> list[ApiDifference]: + """Compare the props and event triggers of two component classes. + + Args: + component: The name of the component. + reference: The Radix component. + candidate: The rx.ui component. + + Returns: + The differences, in order of kind and name. + """ + events = [set(cls.get_event_triggers()) for cls in (reference, candidate)] + differences = [ + ApiDifference( + component=component, + kind="event", + name=name, + reference="trigger" if name in events[0] else None, + candidate="trigger" if name in events[1] else None, + ) + for name in events[0] ^ events[1] + ] + ours, theirs = reference.get_fields(), candidate.get_fields() + # A trigger declared as a field is an event, not a prop. + props = {*reference.get_props(), *candidate.get_props()} - events[0] - events[1] + for name in props: + shapes = [ + type_shape(fields[name].annotated_type) if name in fields else None + for fields in (ours, theirs) + ] + if shapes[0] != shapes[1]: + differences.append( + ApiDifference( + component=component, + kind="prop" if None in shapes else "type", + name=name, + reference=shapes[0], + candidate=shapes[1], + ) + ) + return sorted(differences, key=lambda item: (item.kind, item.name)) + + +def unexplained( + differences: list[ApiDifference], allowlist: Allowlist +) -> tuple[list[ApiDifference], list[tuple[ApiEntry, str]]]: + """Hold the differences of the API to the allowlist. + + Args: + differences: Every difference found, of any component. + allowlist: The intended differences. + + Returns: + The differences the allowlist does not list, and the names it lists + that are not differences any more, each with its entry. + """ + listed = { + (entry.component, entry.kind, name): entry + for entry in allowlist.api + for name in entry.names + } + found = {(item.component, item.kind, item.name) for item in differences} + return ( + [ + item + for item in differences + if (item.component, item.kind, item.name) not in listed + ], + [(entry, key[2]) for key, entry in listed.items() if key not in found], + ) diff --git a/packages/reflex-components-ui/parity/ui_parity/app.py b/packages/reflex-components-ui/parity/ui_parity/app.py new file mode 100644 index 00000000000..cfbdf37e84a --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/app.py @@ -0,0 +1,174 @@ +"""The app the harness drives, generated from the declarations. + +A parity page shows every element of one component's matrix twice, the Radix +component beside the rx.ui one, each in a frame of a fixed size. A contract +page shows one component of one system and nothing else, so the keyboard meets +only what the contract declared. +""" + +from __future__ import annotations + +from typing import Any + +import reflex as rx +from ui_parity.components import CONTRACTS, MATRICES +from ui_parity.contract import Contract +from ui_parity.matrix import Matrix +from ui_parity.systems import SYSTEMS, System + +# The space between two frames and around the page, in CSS pixels. Whole +# pixels keep every frame on the pixel grid. +GAP = 8 +# The space between a frame and its element, where an outline is drawn. +PADDING = 16 + + +def parity_route(component: str) -> str: + """Get the route of a component's parity page. + + Args: + component: The name of the component. + + Returns: + The route. + """ + return f"/parity/{component}" + + +def contract_route(component: str, system: System) -> str: + """Get the route of a component's contract page for one system. + + Args: + component: The name of the component. + system: The system the page renders the component of. + + Returns: + The route. + """ + return f"/contract/{component}/{system.slug}" + + +def stage_label(system: System, props_id: str) -> str: + """Name a frame in the accessibility tree. + + Args: + system: The system of the frame's element. + props_id: The props id of the element. + + Returns: + The accessible name of the frame. + """ + return f"{system.role}:{props_id}" + + +def _stage(matrix: Matrix, system: System, props_id: str, props: Any) -> rx.Component: + """Render one element of a matrix in its frame. + + Args: + matrix: The matrix. + system: The system to create the element from. + props_id: The props id of the element. + props: The props of the element. + + Returns: + The frame. + """ + width, height = matrix.stage + return rx.el.div( + matrix.create(system.namespace, props), + # A group with a name splits the page's accessibility tree by frame. + role="group", + custom_attrs={ + "aria-label": stage_label(system, props_id), + "data-parity-stage": props_id, + "data-parity-system": system.role, + }, + style={ + "width": f"{width}px", + "height": f"{height}px", + "padding": f"{PADDING}px", + "box_sizing": "border-box", + "overflow": "hidden", + "position": "relative", + }, + ) + + +def parity_page(matrix: Matrix) -> rx.Component: + """Render the parity page of a component. + + Args: + matrix: The matrix of the component. + + Returns: + The page: for each element, the reference frame then the candidate's. + """ + return rx.el.main( + *( + _stage(matrix, system, props_id, props) + for props_id, props in matrix.rendered().items() + for system in SYSTEMS + ), + style={ + "display": "grid", + "grid_template_columns": f"repeat(auto-fill, {matrix.stage[0]}px)", + "gap": f"{GAP}px", + "padding": f"{GAP}px", + }, + ) + + +def contract_page(contract: Contract, system: System) -> rx.Component: + """Render the contract page of a component for one system. + + Args: + contract: The contract of the component. + system: The system to create the component from. + + Returns: + The page. + """ + return rx.el.main( + contract.render(system.namespace), + custom_attrs={"data-contract-root": system.name}, + style={"padding": f"{PADDING}px"}, + ) + + +def _index() -> rx.Component: + """Render the list of every page, for a person browsing the app. + + Returns: + The page. + """ + routes = [ + *(parity_route(component) for component in MATRICES), + *( + contract_route(component, system) + for component in CONTRACTS + for system in SYSTEMS + ), + ] + return rx.el.main( + rx.el.ul(*(rx.el.li(rx.el.a(route, href=route)) for route in routes)), + style={"padding": f"{PADDING}px"}, + ) + + +def create_app() -> rx.App: + """Build the app from every declared matrix and contract. + + Returns: + The app. + """ + app = rx.App() + app.add_page(_index, route="/") + for component, matrix in MATRICES.items(): + app.add_page(parity_page(matrix), route=parity_route(component)) + for component, contract in CONTRACTS.items(): + for system in SYSTEMS: + app.add_page( + contract_page(contract, system), + route=contract_route(component, system), + ) + return app diff --git a/packages/reflex-components-ui/parity/ui_parity/components/__init__.py b/packages/reflex-components-ui/parity/ui_parity/components/__init__.py new file mode 100644 index 00000000000..947b822612d --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/__init__.py @@ -0,0 +1,35 @@ +"""What the harness checks, one module per component. + +A module declares ``MATRIX``, the cells whose look is compared, and +``CONTRACT``, the behaviour both systems must show. Either may be absent. +""" + +from __future__ import annotations + +import importlib +import pkgutil + +from ui_parity.contract import Contract +from ui_parity.matrix import Matrix + + +def _declared(attribute: str) -> dict: + """Collect one declaration from every component module. + + Args: + attribute: The name the modules declare it under. + + Returns: + The declarations by component name, in name order. + """ + found = {} + for info in sorted(pkgutil.iter_modules(__path__), key=lambda info: info.name): + module = importlib.import_module(f"{__name__}.{info.name}") + declared = getattr(module, attribute, None) + if declared is not None: + found[declared.component] = declared + return found + + +MATRICES: dict[str, Matrix] = _declared("MATRIX") +CONTRACTS: dict[str, Contract] = _declared("CONTRACT") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/box.py b/packages/reflex-components-ui/parity/ui_parity/components/box.py new file mode 100644 index 00000000000..ad430a81b0b --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/box.py @@ -0,0 +1,68 @@ +"""The box: a div with no look of its own.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, Matrix + + +def _box(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a box with a line of text. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The box. + """ + return namespace.box("The quick brown fox", **props) + + +MATRIX = Matrix( + component="box", + render=_box, + sweep={ + "style": { + "padding": {"padding": "12px"}, + "border": {"border": "1px solid currentColor", "borderRadius": "6px"}, + }, + # A div takes the keyboard's focus only when asked to. + "custom_attrs": {"focusable": {"tabIndex": 0}}, + "appearance": [DARK], + "state": [HOVER], + "viewport": [520], + }, + groups=[ + {"custom_attrs": {"focusable": {"tabIndex": 0}}, "state": [FOCUS_VISIBLE]}, + ], + # Two divs of one stylesheet: nothing may differ, not even by a shade. + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="box", + render=lambda namespace: namespace.box("content", id="box"), +) + + +@CONTRACT.step("is a div in the server render", on=SERVER) +def _server_render(run: Run) -> None: + box = run.server.element("box") + assert (box.tag, box.text) == ("div", "content") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + box = run.page.locator("#box") + assert box.is_visible() + assert box.inner_text() == "content" + + +@CONTRACT.step("keeps its content after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + assert run.page.locator("#box").inner_text() == "content" diff --git a/packages/reflex-components-ui/parity/ui_parity/contract.py b/packages/reflex-components-ui/parity/ui_parity/contract.py new file mode 100644 index 00000000000..322a3cfa754 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/contract.py @@ -0,0 +1,357 @@ +"""The behaviour contract of a component, and how a step of it runs. + +A contract is declared once and runs against the Radix component and the rx.ui +one, in every browser engine. A step runs on a page of its own, so one failure +never causes the next, and a failure names the component, the system, the +engine and the step. +""" + +from __future__ import annotations + +import dataclasses +import urllib.request +from collections.abc import Callable +from html.parser import HTMLParser +from typing import Any + +from playwright.sync_api import Browser, ConsoleMessage, Page + +from ui_parity.allowlist import Allowlist +from ui_parity.systems import System + +# What a step runs on: the HTML the server sent, the page with scripts off, +# or the page once React has hydrated it. +SERVER = "server" +NO_JAVASCRIPT = "no-javascript" +HYDRATED = "hydrated" + +# The step every contract has without declaring it. +HYDRATION_STEP = "hydrates with no warnings" + +VIEWPORT = {"width": 1280, "height": 720} + +# Resolves once React has attached to the server-rendered root of the page. +_HYDRATED_SCRIPT = """() => { + const root = document.querySelector("[data-contract-root]"); + return root !== null + && Object.keys(root).some((key) => key.startsWith("__reactFiber")); +}""" + +# Elements that have no end tag, so they never hold another. +_VOID = frozenset({ + "area", + "base", + "br", + "col", + "embed", + "hr", + "img", + "input", + "link", + "meta", + "source", + "track", + "wbr", +}) + + +class ContractError(AssertionError): + """A step of a contract did not go as the contract and allowlist say.""" + + +@dataclasses.dataclass +class ServerElement: + """An element of the HTML the server sent. + + Attributes: + tag: The name of the element. + attributes: Its attributes. + text: The text of the element and of everything inside it. + """ + + tag: str + attributes: dict[str, str | None] + text: str = "" + + +class _ElementFinder(HTMLParser): + """Find the element with an id, and collect its text.""" + + def __init__(self, element_id: str): + """Start a search. + + Args: + element_id: The id of the element to find. + """ + super().__init__() + self.element_id = element_id + self.found: ServerElement | None = None + # How many elements are open inside the found one, itself included. + self.depth = 0 + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]): + """Enter an element. + + Args: + tag: The name of the element. + attrs: Its attributes. + """ + if self.depth: + self.depth += tag not in _VOID + elif self.found is None and dict(attrs).get("id") == self.element_id: + self.found = ServerElement(tag=tag, attributes=dict(attrs)) + self.depth = int(tag not in _VOID) + + def handle_endtag(self, tag: str): + """Leave an element. + + Args: + tag: The name of the element. + """ + if self.depth and tag not in _VOID: + self.depth -= 1 + + def handle_data(self, data: str): + """Read text. + + Args: + data: The text. + """ + if self.depth and self.found is not None: + self.found.text += data + + +@dataclasses.dataclass(frozen=True) +class ServerHtml: + """The document the server sent for a page, before any script ran. + + Attributes: + text: The HTML. + """ + + text: str + + def element(self, element_id: str) -> ServerElement: + """Find an element by its id. + + Args: + element_id: The id of the element. + + Returns: + The element. + + Raises: + AssertionError: If the server did not render the element. + """ + finder = _ElementFinder(element_id) + finder.feed(self.text) + if finder.found is None: + msg = f'the server HTML has no element with id "{element_id}"' + raise AssertionError(msg) + return finder.found + + +@dataclasses.dataclass +class Run: + """What a step works with. + + Attributes: + component: The component under contract. + system: The system the component is of. + engine: The browser engine of the page. + server: The HTML the server sent for the page. + problems: What the browser reported while the page loaded and the + step ran: console warnings and errors, and uncaught exceptions. + _page: The page, or None for a step that runs on the server HTML. + """ + + component: str + system: System + engine: str + server: ServerHtml + problems: list[str] = dataclasses.field(default_factory=list) + _page: Page | None = None + + @property + def page(self) -> Page: + """The page the step drives. + + Returns: + The page, showing the component. + + Raises: + RuntimeError: If the step runs on the server HTML, where no page + is open. + """ + if self._page is None: + msg = f"A step on {SERVER!r} has no page: read run.server instead." + raise RuntimeError(msg) + return self._page + + +@dataclasses.dataclass(frozen=True) +class Step: + """One requirement of a contract. + + Attributes: + name: What the component must do, as a failure reports it. + check: Drives the page and asserts. + on: What the step runs on: SERVER, NO_JAVASCRIPT or HYDRATED. + """ + + name: str + check: Callable[[Run], None] + on: str = HYDRATED + + +def _no_problems(run: Run) -> None: + """Assert that hydrating the page reported nothing. + + Args: + run: The run, on a hydrated page. + """ + assert run.problems == [] + + +@dataclasses.dataclass +class Contract: + """The behaviour both systems' component must show. + + Attributes: + component: The name both namespaces know the component by. + render: Create what the contract page shows from a namespace, ``rx`` + or ``rx.ui``. + steps: The requirements, in the order declared. + """ + + component: str + render: Callable[[Any], Any] + steps: list[Step] = dataclasses.field( + default_factory=lambda: [Step(HYDRATION_STEP, _no_problems)] + ) + + def step( + self, name: str, on: str = HYDRATED + ) -> Callable[[Callable[[Run], None]], Callable[[Run], None]]: + """Declare a step. + + Args: + name: What the component must do. + on: What the step runs on: SERVER, NO_JAVASCRIPT or HYDRATED. + + Returns: + A decorator that adds the function as the step's check. + + Raises: + ValueError: If the contract already has a step of that name, or + the step runs on something unknown. + """ + if on not in (SERVER, NO_JAVASCRIPT, HYDRATED): + msg = f"{self.component}: a step cannot run on {on!r}." + raise ValueError(msg) + if any(step.name == name for step in self.steps): + msg = f'{self.component}: two steps are named "{name}".' + raise ValueError(msg) + + def declare(check: Callable[[Run], None]) -> Callable[[Run], None]: + self.steps.append(Step(name=name, check=check, on=on)) + return check + + return declare + + +def _record(problems: list[str], message: ConsoleMessage) -> None: + """Keep a console message that reports a problem. + + Args: + problems: Where the problems of the page are collected. + message: The message. + """ + if message.type in ("warning", "error"): + problems.append(f"console {message.type}: {message.text}") + + +def _check( + browser: Browser, url: str, contract: Contract, system: System, step: Step +) -> None: + """Run the check of a step on a page of its own. + + Args: + browser: The browser to open the page in. + url: The address of the contract page. + contract: The contract the step belongs to. + system: The system the page renders the component of. + step: The step. + """ + with urllib.request.urlopen(url) as response: + server = ServerHtml(response.read().decode()) + run = Run( + component=contract.component, + system=system, + engine=browser.browser_type.name, + server=server, + ) + if step.on == SERVER: + step.check(run) + return + context = browser.new_context( + viewport=VIEWPORT, # pyright: ignore[reportArgumentType] + java_script_enabled=step.on == HYDRATED, + ) + try: + page = run._page = context.new_page() + page.on("console", lambda message: _record(run.problems, message)) + page.on("pageerror", lambda error: run.problems.append(f"error: {error}")) + page.goto(url) + if step.on == HYDRATED: + page.wait_for_function(_HYDRATED_SCRIPT) + step.check(run) + finally: + context.close() + + +def run_step( + browser: Browser, + url: str, + contract: Contract, + system: System, + step: Step, + allowlist: Allowlist, +) -> None: + """Run one step against one system, and hold it to the allowlist. + + Args: + browser: The browser to run in. + url: The address of the contract page of the system. + contract: The contract the step belongs to. + system: The system under contract. + step: The step. + allowlist: The intended differences. + + Raises: + ContractError: If the step fails, or passes although the allowlist + says the system does not pass it. + """ + engine = browser.browser_type.name + where = f'{contract.component} [{system.name}, {engine}] step "{step.name}"' + allowed = next( + ( + entry + for entry in allowlist.contract + if entry.covers(contract.component, step.name, system.name, engine) + ), + None, + ) + try: + _check(browser, url, contract, system, step) + except Exception as error: + if allowed is not None: + return + msg = f"{where} failed: {type(error).__name__}: {error}" + raise ContractError(msg) from error + if allowed is not None: + msg = ( + f"{where} passes, but allowlist.toml says it does not " + f'("{allowed.reason}"). Remove the entry.' + ) + raise ContractError(msg) diff --git a/packages/reflex-components-ui/parity/ui_parity/diff.py b/packages/reflex-components-ui/parity/ui_parity/diff.py new file mode 100644 index 00000000000..8f288a8f55b --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/diff.py @@ -0,0 +1,226 @@ +"""Compare two screenshots, a pixel at a time, ignoring anti-aliasing. + +The method is pixelmatch's: a perceptual color distance in YIQ space, and a +pixel that differs is set aside when it sits on an anti-aliased edge of either +image, since two renderings of one shape disagree there by nature. +""" + +from __future__ import annotations + +import dataclasses + +import numpy as np +from PIL import Image + +# The largest YIQ distance of two colors: black against white. +MAX_DELTA = 35215.0 + +# How a diff image paints a differing pixel, an anti-aliased one, and one of a +# region only one of the images covers. +DIFFERENT = (255, 0, 0) +ANTIALIASED = (255, 200, 0) + +# The compared images are drawn this faint under the marks. +FADE = 0.1 + + +@dataclasses.dataclass(frozen=True) +class ImageDiff: + """What differs between two images. + + Attributes: + width: The width of the compared area, the wider of the two images. + height: The height of the compared area, the taller of the two. + differing: The pixels that differ, anti-aliased ones left out. + antialiased: The differing pixels set aside as anti-aliasing. + image: The reference, faded, with the differing pixels marked. + """ + + width: int + height: int + differing: int + antialiased: int + image: Image.Image + + @property + def ratio(self) -> float: + """The share of the compared area that differs. + + Returns: + The differing pixels over all pixels, from 0 to 1. + """ + return self.differing / (self.width * self.height) + + +def _rgb(image: Image.Image) -> np.ndarray: + """Read an image as opaque colors, blended with white where transparent. + + Args: + image: The image. + + Returns: + The colors as floats, in an array of height by width by 3. + """ + rgba = np.asarray(image.convert("RGBA"), dtype=np.float64) + alpha = rgba[..., 3:] / 255.0 + return 255.0 + (rgba[..., :3] - 255.0) * alpha + + +def _yiq(rgb: np.ndarray) -> np.ndarray: + """Convert colors to YIQ, where distance follows what an eye sees. + + Args: + rgb: The colors, in an array whose last axis is red, green and blue. + + Returns: + The same array with luma, in-phase and quadrature on the last axis. + """ + red, green, blue = rgb[..., 0], rgb[..., 1], rgb[..., 2] + return np.stack( + [ + red * 0.29889531 + green * 0.58662247 + blue * 0.11448223, + red * 0.59597799 - green * 0.27417610 - blue * 0.32180189, + red * 0.21147017 - green * 0.52261711 + blue * 0.31114694, + ], + axis=-1, + ) + + +def _has_many_siblings(luma: np.ndarray, x: int, y: int) -> bool: + """Check whether a pixel is part of a flat area. + + Args: + luma: The brightness of an image. + x: The column of the pixel. + y: The row of the pixel. + + Returns: + Whether more than two of the pixels around it have its brightness, + counting the image's border as one. + """ + height, width = luma.shape + top, bottom = max(y - 1, 0), min(y + 1, height - 1) + left, right = max(x - 1, 0), min(x + 1, width - 1) + on_border = x in (left, right) or y in (top, bottom) + window = luma[top : bottom + 1, left : right + 1] + same = int(np.count_nonzero(window == luma[y, x])) - 1 + return same + on_border > 2 + + +def _is_antialiased(luma: np.ndarray, other: np.ndarray, x: int, y: int) -> bool: + """Check whether a pixel sits on an anti-aliased edge. + + It does when its neighbors hold at most two of its brightness, one clearly + darker and one clearly brighter, and the darkest or the brightest of them + belongs to a flat area in both images. + + Args: + luma: The brightness of the image the pixel is read from. + other: The brightness of the image it is compared with. + x: The column of the pixel. + y: The row of the pixel. + + Returns: + Whether the pixel is anti-aliasing. + """ + height, width = luma.shape + top, bottom = max(y - 1, 0), min(y + 1, height - 1) + left, right = max(x - 1, 0), min(x + 1, width - 1) + equal = int(x in (left, right) or y in (top, bottom)) + darkest = brightest = 0.0 + darkest_at = brightest_at = (x, y) + for row in range(top, bottom + 1): + for column in range(left, right + 1): + if row == y and column == x: + continue + delta = luma[row, column] - luma[y, x] + if delta == 0: + equal += 1 + if equal > 2: + return False + elif delta < darkest: + darkest, darkest_at = delta, (column, row) + elif delta > brightest: + brightest, brightest_at = delta, (column, row) + if darkest == 0 or brightest == 0: + return False + return ( + _has_many_siblings(luma, *darkest_at) and _has_many_siblings(other, *darkest_at) + ) or ( + _has_many_siblings(luma, *brightest_at) + and _has_many_siblings(other, *brightest_at) + ) + + +def diff_images( + reference: Image.Image, + candidate: Image.Image, + threshold: float = 0.01, + include_antialiasing: bool = False, +) -> ImageDiff: + """Compare two images. + + Images of different sizes are compared from their top left corner, and + every pixel only one of them covers differs. + + Args: + reference: The image the candidate should look like. + candidate: The image under test. + threshold: How far a pixel's color may be off before it differs, from + 0 (any difference) to 1 (black against white). + include_antialiasing: Whether an anti-aliased pixel counts as + differing. + + Returns: + The count of differing pixels and an image marking them. + """ + width = max(reference.width, candidate.width) + height = max(reference.height, candidate.height) + shared_width = min(reference.width, candidate.width) + shared_height = min(reference.height, candidate.height) + + first = _yiq(_rgb(reference)) + second = _yiq(_rgb(candidate)) + delta = first[:shared_height, :shared_width] - second[:shared_height, :shared_width] + distance = ( + 0.5053 * delta[..., 0] ** 2 + + 0.299 * delta[..., 1] ** 2 + + 0.1957 * delta[..., 2] ** 2 + ) + + # Faded brightness of the reference, on white where it has no pixel. + canvas = np.full((height, width, 3), 255.0) + faded = 255.0 + (first[..., 0] - 255.0) * FADE + canvas[: reference.height, : reference.width] = faded[..., None] + + different = np.ones((height, width), dtype=bool) + different[:shared_height, :shared_width] = distance > MAX_DELTA * threshold**2 + antialiased = 0 + if not include_antialiasing: + first_luma, second_luma = first[..., 0], second[..., 0] + for y, x in zip( + *np.nonzero(different[:shared_height, :shared_width]), strict=True + ): + # Only where both images have neighbors to read. + if _is_antialiased( + first_luma[:shared_height, :shared_width], + second_luma[:shared_height, :shared_width], + int(x), + int(y), + ) or _is_antialiased( + second_luma[:shared_height, :shared_width], + first_luma[:shared_height, :shared_width], + int(x), + int(y), + ): + different[y, x] = False + canvas[y, x] = ANTIALIASED + antialiased += 1 + canvas[different] = DIFFERENT + return ImageDiff( + width=width, + height=height, + differing=int(np.count_nonzero(different)), + antialiased=antialiased, + image=Image.fromarray(canvas.round().astype(np.uint8), "RGB"), + ) diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py new file mode 100644 index 00000000000..46a9ce8bc06 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -0,0 +1,943 @@ +"""Compare the look of a component's matrix between the two systems. + +Each pass loads the parity page once under one viewport and color scheme. The +cells at rest are read from a single screenshot and a single script call; a +cell in an interactive state is driven through the pointer or the keyboard, one +element at a time. Both systems are cropped by the same rectangle relative to +their frame, so two equal renderings give equal images. +""" + +from __future__ import annotations + +import dataclasses +import io +import re +import time +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any + +from PIL import Image +from playwright.sync_api import Browser, Locator, Page + +from ui_parity.allowlist import Allowlist, LookEntry +from ui_parity.diff import diff_images +from ui_parity.matrix import ACTIVE, FOCUS_VISIBLE, HOVER, REST, Cell, Matrix, Selector +from ui_parity.systems import CANDIDATE, REFERENCE, SYSTEMS, System + +# The height of the viewport, which no cell depends on: screenshots are of the +# whole page. +VIEWPORT_HEIGHT = 800 + +# The space left above a frame the page is scrolled to, in CSS pixels. +GAP = 8 + +# The tallest screenshot taken at once, in CSS pixels. Browsers cap the size of +# a capture, so a long page is read in bands. +BAND = 8000 + +# Nothing may still be moving when a pixel or a computed value is read. +FREEZE_CSS = """ +*, *::before, *::after { + transition: none !important; + animation-duration: 0s !important; + animation-delay: 0s !important; + animation-iteration-count: 1 !important; + scroll-behavior: auto !important; +} +""" + +# Resolves once the page is hydrated, in the color scheme asked for, with its +# fonts loaded. +_READY_SCRIPT = """async (appearance) => { + const stage = document.querySelector("[data-parity-stage]"); + if ( + stage === null + || !Object.keys(stage).some((key) => key.startsWith("__reactFiber")) + || !document.documentElement.classList.contains(appearance) + ) { + return false; + } + await document.fonts.ready; + return document.fonts.status === "loaded"; +}""" + +# Reads the geometry and the computed style of the frames: all of them, or the +# one of a system and props id. +_READ_SCRIPT = """({properties, targets, parts, only, matches}) => { + const read = (element) => { + const style = getComputedStyle(element); + return Object.fromEntries( + properties.map((name) => [name, style.getPropertyValue(name)]), + ); + }; + const box = (element) => { + const rect = element.getBoundingClientRect(); + return [ + rect.left + window.scrollX, + rect.top + window.scrollY, + rect.width, + rect.height, + ]; + }; + const selector = only === null + ? "[data-parity-stage]" + : `[data-parity-stage="${only.id}"][data-parity-system="${only.system}"]`; + return Array.from(document.querySelectorAll(selector), (stage) => { + const system = stage.dataset.paritySystem; + const target = targets[system] === null + ? stage.firstElementChild + : stage.querySelector(targets[system]); + const styles = {}; + const missing = []; + if (target === null) { + missing.push("target"); + } else { + styles[""] = read(target); + } + for (const [name, selectors] of Object.entries(parts)) { + const part = stage.querySelector(selectors[system]); + if (part === null) { + missing.push(name); + } else { + styles[name] = read(part); + } + } + return { + id: stage.dataset.parityStage, + system, + stage: box(stage), + target: target === null ? null : box(target), + styles, + missing, + matched: matches === null || (target !== null && target.matches(matches)), + view: [window.scrollX, window.scrollY, window.innerWidth, window.innerHeight], + }; + }); +}""" + +# A frame in an ARIA snapshot: its name, then its text when it holds only text. +# Scrolls a frame to the top of the viewport, and reports where the page ended +# up. +_SCROLL_SCRIPT = """(top) => { + window.scrollTo(0, top); + return [window.scrollX, window.scrollY]; +}""" + +_GROUP = re.compile(r'( *)- group "(reference|candidate):([^"]*)"(?:: (.+)|:)?') + + +class CaptureError(RuntimeError): + """The page could not be put in the condition a cell asks for.""" + + +Point = tuple[float, float] +# Left, top, width and height, in CSS pixels. +Clip = tuple[float, float, float, float] + + +@dataclasses.dataclass(frozen=True) +class State: + """How an element is put in an interactive state, and taken out of it. + + A driver is called with the page, the element, and the middle of the + element in the viewport, which the page is scrolled to show. + + Attributes: + enter: Drives the page so the element is in the state. + leave: Undoes it. Without one the page is loaded again. + matches: A selector the element must match once in the state, which + fails the run rather than comparing two elements at rest. + """ + + enter: Callable[[Page, Locator, Point], None] + leave: Callable[[Page, Locator, Point], None] | None = None + matches: str | None = None + + +def _hover(page: Page, target: Locator, point: Point) -> None: + """Put the pointer on an element. + + Args: + page: The page. + target: The element. + point: The middle of the element. + """ + page.mouse.move(*point) + + +def _unhover(page: Page, target: Locator, point: Point) -> None: + """Move the pointer off every frame. + + Args: + page: The page. + target: The element that was hovered. + point: The middle of the element. + """ + page.mouse.move(0, 0) + + +def _focus(page: Page, target: Locator, point: Point) -> None: + """Focus an element as the keyboard does. + + Args: + page: The page. + target: The element. + point: The middle of the element. + """ + # A key press makes the keyboard the page's input, so the focus that + # follows shows its ring. + page.keyboard.press("Tab") + target.focus() + + +def _blur(page: Page, target: Locator, point: Point) -> None: + """Take the focus off an element. + + Args: + page: The page. + target: The element that was focused. + point: The middle of the element. + """ + target.blur() + + +def _press(page: Page, target: Locator, point: Point) -> None: + """Hold the pointer down on an element. + + Args: + page: The page. + target: The element. + point: The middle of the element. + """ + page.mouse.move(*point) + page.mouse.down() + + +def _release(page: Page, target: Locator, point: Point) -> None: + """Release the pointer away from an element, so it is never clicked. + + Args: + page: The page. + target: The element that was pressed. + point: The middle of the element. + """ + page.mouse.move(0, 0) + page.mouse.up() + # Dragging off the element selected its text. + page.evaluate("() => getSelection().removeAllRanges()") + + +# The states the runner drives. +STATES: Mapping[str, State] = { + HOVER: State(enter=_hover, leave=_unhover, matches=":hover"), + FOCUS_VISIBLE: State(enter=_focus, leave=_blur, matches=":focus-visible"), + ACTIVE: State(enter=_press, leave=_release, matches=":active"), +} + + +@dataclasses.dataclass(frozen=True) +class StyleDifference: + """A computed property the two systems disagree on. + + Attributes: + part: The inner element it was read from, or the empty string for the + element itself. + property: The CSS property. + reference: Its computed value on the Radix component. + candidate: Its computed value on the rx.ui component. + """ + + part: str + property: str + reference: str | None + candidate: str | None + + +@dataclasses.dataclass +class CellResult: + """How one cell compared. + + Attributes: + cell: The id of the cell. + width: The width of the compared images, in device pixels. + height: The height of the compared images, in device pixels. + differing: The pixels that differ, anti-aliasing left out. + antialiased: The differing pixels set aside as anti-aliasing. + tolerance: The share of the pixels that may differ. + styles: The computed properties that differ. + a11y: The accessibility tree of the reference and of the candidate + when they differ, or None. + allowed: The reasons of the allowlist entries that excused a + difference of the cell. + images: The files of the reference, the candidate and the diff, + relative to the report. + pixels_allowed: Whether the allowlist excuses the pixels. + """ + + cell: str + width: int + height: int + differing: int + antialiased: int + tolerance: float + styles: list[StyleDifference] + a11y: tuple[str, str] | None + allowed: list[str] + images: dict[str, str] + pixels_allowed: bool = False + + @property + def ratio(self) -> float: + """The share of the cell's pixels that differ. + + Returns: + The differing pixels over all pixels, from 0 to 1. + """ + return self.differing / (self.width * self.height) + + @property + def problems(self) -> list[str]: + """Describe what fails the cell. + + Returns: + A line for the pixels, one per computed property and one for the + accessibility tree, or nothing when the cell passes. + """ + problems = [] + if self.ratio > self.tolerance and not self.pixels_allowed: + problems.append( + f"{self.differing} of {self.width * self.height} pixels differ " + f"({self.ratio:.2%}, {self.tolerance:.2%} allowed)" + ) + problems.extend( + f"{difference.part + ' ' if difference.part else ''}" + f"{difference.property}: rx {difference.reference!r}, " + f"rx.ui {difference.candidate!r}" + for difference in self.styles + ) + if self.a11y is not None: + problems.append( + f"accessibility tree: rx {self.a11y[0]!r}, rx.ui {self.a11y[1]!r}" + ) + return problems + + +@dataclasses.dataclass +class MatrixResult: + """How the matrix of a component compared in one engine. + + Attributes: + component: The component. + engine: The browser engine. + cells: The result of each cell, in the order of the matrix. + seconds: How long the run took. + passes: How many times the page was loaded. + stale: Allowlist entries of the component no difference matched. + """ + + component: str + engine: str + cells: list[CellResult] + seconds: float + passes: int + stale: list[LookEntry] + + def failures(self, report: Path) -> list[str]: + """Describe everything that fails the matrix. + + Args: + report: The directory the images were written to. + + Returns: + For each failing cell: the cell, each difference with its size, + and where its images are. Then each stale allowlist entry. + """ + failures = [] + for result in self.cells: + if problems := result.problems: + # The three images differ by their last name but one. + images = report / result.images["diff"].replace( + ".diff.", ".{reference,candidate,diff}." + ) + failures.append( + f"{self.component} [{self.engine}] cell {result.cell}:\n" + + "".join(f" - {problem}\n" for problem in problems) + + f" images: {images}" + ) + failures.extend( + f"{self.component} [{self.engine}]: nothing differs as the " + f"allowlist.toml entry says ({entry.check}, cells {entry.cells!r}: " + f'"{entry.reason}"). Remove the entry.' + for entry in self.stale + ) + return failures + + +def _per_system(selector: Selector | None) -> dict[str, str | None]: + """Spread a selector over the systems. + + Args: + selector: One selector for both systems, one for each, or None. + + Returns: + The selector of each system, by role. + """ + if selector is None or isinstance(selector, str): + return {REFERENCE.role: selector, CANDIDATE.role: selector} + return {REFERENCE.role: selector[0], CANDIDATE.role: selector[1]} + + +def split_a11y(snapshot: str) -> dict[tuple[str, str], str]: + """Split the accessibility tree of a parity page by frame. + + Args: + snapshot: The ARIA snapshot of the page, where each frame is a group + named after its system and props id. + + Returns: + The tree inside each frame, by system role and props id. + """ + trees: dict[tuple[str, str], list[str]] = {} + current: list[str] | None = None + # What every line inside the current frame starts with. + inside = "" + for line in snapshot.splitlines(): + if match := _GROUP.fullmatch(line): + current = trees.setdefault((match[2], match[3]), []) + inside = match[1] + " " + if match[4] is not None: + current.append(match[4]) + elif current is not None and line.startswith(inside): + current.append(line.removeprefix(inside)) + else: + current = None + return {key: "\n".join(lines) for key, lines in trees.items()} + + +def _crop( + matrix: Matrix, reference: dict[str, Any], candidate: dict[str, Any] +) -> tuple[int, int, int, int]: + """Choose the rectangle of a frame that is compared. + + Args: + matrix: The matrix. + reference: What the page reported of the reference frame. + candidate: What the page reported of the candidate frame. + + Returns: + Left, top, right and bottom, in CSS pixels from the frame's corner: + the same for both systems. + """ + width, height = matrix.stage + if matrix.crop == "stage": + return (0, 0, width, height) + left, top, right, bottom = width, height, 0, 0 + for frame in (reference, candidate): + x, y, w, h = ( + frame["target"][0] - frame["stage"][0], + frame["target"][1] - frame["stage"][1], + frame["target"][2], + frame["target"][3], + ) + left, top = min(left, x), min(top, y) + right, bottom = max(right, x + w), max(bottom, y + h) + return ( + max(int(left) - matrix.margin, 0), + max(int(top) - matrix.margin, 0), + min(-int(-right // 1) + matrix.margin, width), + min(-int(-bottom // 1) + matrix.margin, height), + ) + + +def _style_differences( + reference: dict[str, dict[str, str]], candidate: dict[str, dict[str, str]] +) -> list[StyleDifference]: + """Compare the computed styles of two frames. + + Args: + reference: The computed properties of the reference, by part. + candidate: The computed properties of the candidate, by part. + + Returns: + The properties that differ, a missing part as a property of its own. + """ + differences = [] + for part in sorted({*reference, *candidate}): + ours, theirs = reference.get(part), candidate.get(part) + if ours is None or theirs is None: + differences.append( + StyleDifference( + part=part, + property="(element)", + reference=None if ours is None else "present", + candidate=None if theirs is None else "present", + ) + ) + continue + differences.extend( + StyleDifference(part, name, value, theirs[name]) + for name, value in ours.items() + if theirs[name] != value + ) + return differences + + +class _Pass: + """One load of a parity page, under one viewport and color scheme.""" + + def __init__( + self, + browser: Browser, + url: str, + matrix: Matrix, + viewport: int, + appearance: str, + scale: int, + prepare: Callable[[Page], None] | None, + ): + """Open the page. + + Args: + browser: The browser. + url: The address of the parity page. + matrix: The matrix of the page. + viewport: The width of the page, in CSS pixels. + appearance: The color scheme of the page. + scale: The device pixels per CSS pixel. + prepare: Called with the page once it is ready, before it is read. + """ + self.url = url + self.matrix = matrix + self.appearance = appearance + self.scale = scale + self.prepare = prepare + self.context = browser.new_context( + viewport={"width": viewport, "height": VIEWPORT_HEIGHT}, + device_scale_factor=scale, + color_scheme=appearance, # pyright: ignore[reportArgumentType] + reduced_motion="reduce", + ) + self.page = self.context.new_page() + self.load() + + def load(self) -> None: + """Load the page and wait until it is still.""" + self.page.goto(self.url) + self.page.wait_for_function(_READY_SCRIPT, arg=self.appearance) + self.page.add_style_tag(content=FREEZE_CSS) + if self.prepare is not None: + self.prepare(self.page) + + def read( + self, only: tuple[str, System] | None = None, matches: str | None = None + ) -> list[dict[str, Any]]: + """Read the geometry and computed style of the frames. + + Args: + only: The props id and system of the one frame to read, or None + for every frame. + matches: A selector to test each frame's element against. + + Returns: + What the page reported of each frame. + + Raises: + CaptureError: If a frame lacks the element the matrix names. + """ + frames = self.page.evaluate( + _READ_SCRIPT, + { + "properties": self.matrix.properties, + "targets": _per_system(self.matrix.target), + "parts": { + name: _per_system(selector) + for name, selector in self.matrix.parts.items() + }, + "only": None + if only is None + else {"id": only[0], "system": only[1].role}, + "matches": matches, + }, + ) + for frame in frames: + if "target" in frame["missing"]: + msg = ( + f"{self.matrix.component}: the {frame['system']} frame of " + f"{frame['id']} has no element to compare." + ) + raise CaptureError(msg) + return frames + + def shoot( + self, clip: tuple[float, float, float, float], full_page: bool = True + ) -> Image.Image: + """Take a screenshot of a rectangle of the page. + + Args: + clip: Left, top, width and height, in CSS pixels. + full_page: Whether the rectangle is given from the corner of the + document, wherever the page is scrolled to, rather than from + the corner of the viewport. Slower the longer the page is. + + Returns: + The image, in device pixels. + """ + return Image.open( + io.BytesIO( + self.page.screenshot( + full_page=full_page, + clip={ + "x": clip[0], + "y": clip[1], + "width": clip[2], + "height": clip[3], + }, + animations="disabled", + caret="hide", + scale="device", + ) + ) + ).convert("RGB") + + def shoot_page(self) -> Callable[[tuple[float, float, float, float]], Image.Image]: + """Take a screenshot of the whole page, in bands. + + Returns: + A function cutting a rectangle, given in CSS pixels of the + document, out of the screenshot. + """ + width, height = self.page.evaluate( + "() => [document.documentElement.scrollWidth," + " document.documentElement.scrollHeight]" + ) + bands = [ + (top, self.shoot((0, top, width, min(BAND, height - top)))) + for top in range(0, height, BAND) + ] + scale = self.scale + + def cut(clip: tuple[float, float, float, float]) -> Image.Image: + x, y, w, h = clip + top, band = bands[int(y // BAND)] + if y + h > top + BAND: + # The rectangle straddles two bands: read it on its own. + return self.shoot(clip) + return band.crop(( + round(x * scale), + round((y - top) * scale), + round((x + w) * scale), + round((y - top + h) * scale), + )) + + return cut + + def target(self, props_id: str, system: System) -> Locator: + """Locate the element of a frame. + + Args: + props_id: The props id of the frame. + system: The system of the frame. + + Returns: + The element the matrix compares. + """ + stage = self.page.locator( + f'[data-parity-stage="{props_id}"][data-parity-system="{system.role}"]' + ) + selector = _per_system(self.matrix.target)[system.role] + return stage.locator("xpath=./*[1]" if selector is None else selector).first + + def close(self) -> None: + """Close the page.""" + self.context.close() + + +class _Excuses: + """The allowlist entries of one matrix run, and which of them were needed.""" + + def __init__(self, allowlist: Allowlist, component: str, engine: str): + """Select the entries of a component in an engine. + + Args: + allowlist: The intended differences. + component: The component of the matrix. + engine: The browser engine of the run. + """ + self.component = component + self.engine = engine + self.entries = [ + entry + for entry in allowlist.look + if entry.component == component + and (not entry.engines or engine in entry.engines) + ] + self.used: set[int] = set() + + def reasons(self, check: str, cell: str, name: str | None = None) -> list[str]: + """Find why a difference of a cell is intended, if it is. + + Args: + check: The check that found the difference. + cell: The id of the cell. + name: The computed property that differs, for a style. + + Returns: + The reason of each entry that lists the difference. + """ + reasons = [] + for index, entry in enumerate(self.entries): + if entry.covers(self.component, check, cell, self.engine) and ( + name is None or name in entry.properties + ): + self.used.add(index) + reasons.append(entry.reason) + return reasons + + def stale(self) -> list[LookEntry]: + """List the entries that excused nothing. + + Returns: + The entries no difference of the run matched. + """ + return [ + entry for index, entry in enumerate(self.entries) if index not in self.used + ] + + +def _compare( + matrix: Matrix, + cell: Cell, + images: dict[str, Image.Image], + styles: dict[str, dict[str, dict[str, str]]], + a11y: tuple[str, str] | None, + report: Path, + directory: Path, + excuses: _Excuses, +) -> CellResult: + """Compare what was read of a cell in both systems, and save its images. + + Args: + matrix: The matrix of the cell. + cell: The cell. + images: The screenshot of each system, by role. + styles: The computed properties of each system, by role then part. + a11y: The accessibility trees when they differ, or None. + report: The directory of the report. + directory: Where the images go, relative to the report. + excuses: The intended differences of the run. + + Returns: + The result of the cell. + """ + diff = diff_images( + images[REFERENCE.role], images[CANDIDATE.role], threshold=matrix.threshold + ) + files = { + kind: (directory / f"{cell.id}.{kind}.png").as_posix() + for kind in (REFERENCE.role, CANDIDATE.role, "diff") + } + for kind, image in (*images.items(), ("diff", diff.image)): + image.save(report / files[kind]) + allowed: dict[str, None] = {} + remaining = [] + for difference in _style_differences( + styles[REFERENCE.role], styles[CANDIDATE.role] + ): + if reasons := excuses.reasons("style", cell.id, difference.property): + allowed.update(dict.fromkeys(reasons)) + else: + remaining.append(difference) + pixel_reasons = ( + excuses.reasons("pixels", cell.id) if diff.ratio > matrix.tolerance else [] + ) + allowed.update(dict.fromkeys(pixel_reasons)) + if a11y is not None and (a11y_reasons := excuses.reasons("a11y", cell.id)): + allowed.update(dict.fromkeys(a11y_reasons)) + a11y = None + return CellResult( + cell=cell.id, + width=diff.width, + height=diff.height, + differing=diff.differing, + antialiased=diff.antialiased, + tolerance=matrix.tolerance, + styles=remaining, + a11y=a11y, + allowed=list(allowed), + images=files, + pixels_allowed=bool(pixel_reasons), + ) + + +def _drive( + current: _Pass, + cell: Cell, + state: State, + frames: dict[tuple[str, str], dict[str, Any]], + clips: dict[str, Clip], +) -> tuple[dict[str, Image.Image], dict[str, dict[str, dict[str, str]]]]: + """Put the element of each system in a state, and read it there. + + Args: + current: The loaded page. + cell: The cell, whose state is not rest. + state: The driver of the state. + frames: What the page reported of each frame at rest, by props id and + role. + clips: The rectangle of the document to capture for each system, by + role. + + Returns: + The screenshot and the computed properties of each system, by role. + + Raises: + CaptureError: If an element does not enter the state. + """ + images, styles = {}, {} + for system in SYSTEMS: + frame = frames[cell.props_id, system.role] + # Scrolled to before it is driven, so the page is still afterwards and + # the screenshot is of the viewport: far faster than of a long page. + scroll_x, scroll_y = current.page.evaluate( + _SCROLL_SCRIPT, frame["stage"][1] - GAP + ) + x, y, width, height = frame["target"] + point = (x + width / 2 - scroll_x, y + height / 2 - scroll_y) + target = current.target(cell.props_id, system) + state.enter(current.page, target, point) + (driven,) = current.read((cell.props_id, system), state.matches) + if not driven["matched"]: + msg = ( + f"{current.matrix.component} cell {cell.id}: the {system.name} " + f"element did not enter {cell.state} (it does not match " + f"{state.matches})." + ) + raise CaptureError(msg) + styles[system.role] = driven["styles"] + left, top, clip_width, clip_height = clips[system.role] + # Read again: driving the element may have scrolled the page. + scroll_x, scroll_y, view_width, view_height = driven["view"] + left, top = left - scroll_x, top - scroll_y + if ( + left >= 0 + and top >= 0 + and left + clip_width <= view_width + and top + clip_height <= view_height + ): + images[system.role] = current.shoot( + (left, top, clip_width, clip_height), full_page=False + ) + else: + images[system.role] = current.shoot(clips[system.role]) + if state.leave is None: + current.load() + else: + state.leave(current.page, target, point) + return images, styles + + +def run_matrix( + browser: Browser, + url: str, + matrix: Matrix, + report: Path, + allowlist: Allowlist, + scale: int = 1, + prepare: Callable[[Page], None] | None = None, +) -> MatrixResult: + """Compare every cell of a matrix and write its images. + + Args: + browser: The browser to render in. + url: The address of the component's parity page. + matrix: The matrix. + report: The directory of the report. The images go to a directory + named after the engine and the component. + allowlist: The intended differences. + scale: The device pixels per CSS pixel. + prepare: Called with each loaded page before it is read, to change + what is compared. + + Returns: + The result of each cell. + + Raises: + CaptureError: If a cell names a state nothing drives, or an element + does not enter its state. + """ + started = time.perf_counter() + engine = browser.browser_type.name + directory = Path(engine) / matrix.component + (report / directory).mkdir(parents=True, exist_ok=True) + states = {**STATES, **matrix.states} + excuses = _Excuses(allowlist, matrix.component, engine) + all_cells = matrix.cells() + + passes: dict[tuple[int, str], list[Cell]] = {} + for cell in all_cells: + if cell.state != REST and cell.state not in states: + msg = f'{matrix.component}: no driver for the state "{cell.state}".' + raise CaptureError(msg) + passes.setdefault((cell.viewport, cell.appearance), []).append(cell) + + results: dict[str, CellResult] = {} + # Read once, and compared at the first cell at rest of each element: the + # tree depends on neither the viewport nor the scheme. + trees: dict[tuple[str, str], str] | None = None + described: set[str] = set() + for (viewport, appearance), cells in passes.items(): + current = _Pass(browser, url, matrix, viewport, appearance, scale, prepare) + try: + frames = {(frame["id"], frame["system"]): frame for frame in current.read()} + if trees is None: + trees = split_a11y(current.page.locator("main").aria_snapshot()) + cut = current.shoot_page() + for cell in cells: + left, top, right, bottom = _crop( + matrix, + frames[cell.props_id, REFERENCE.role], + frames[cell.props_id, CANDIDATE.role], + ) + clips: dict[str, Clip] = { + system.role: ( + frames[cell.props_id, system.role]["stage"][0] + left, + frames[cell.props_id, system.role]["stage"][1] + top, + right - left, + bottom - top, + ) + for system in SYSTEMS + } + a11y = None + if cell.state != REST: + images, styles = _drive( + current, cell, states[cell.state], frames, clips + ) + else: + images = {role: cut(clip) for role, clip in clips.items()} + styles = { + system.role: frames[cell.props_id, system.role]["styles"] + for system in SYSTEMS + } + pair = ( + trees.get((REFERENCE.role, cell.props_id), ""), + trees.get((CANDIDATE.role, cell.props_id), ""), + ) + if cell.props_id not in described and pair[0] != pair[1]: + a11y = pair + described.add(cell.props_id) + results[cell.id] = _compare( + matrix, cell, images, styles, a11y, report, directory, excuses + ) + finally: + current.close() + + return MatrixResult( + component=matrix.component, + engine=engine, + # In the order of the matrix, whichever pass rendered a cell. + cells=[results[cell.id] for cell in all_cells], + seconds=time.perf_counter() - started, + passes=len(passes), + stale=excuses.stale(), + ) diff --git a/packages/reflex-components-ui/parity/ui_parity/matrix.py b/packages/reflex-components-ui/parity/ui_parity/matrix.py new file mode 100644 index 00000000000..ef7f0c2d3a0 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/matrix.py @@ -0,0 +1,310 @@ +"""The declaration of a component's parity matrix, and its cells. + +A full cross product of what the components vary by (variant, size, 32 colors, +contrast, radius, appearance, state, viewport) is far too large to render, so a +matrix says which dimensions cross and which are swept one at a time from a +base cell. +""" + +from __future__ import annotations + +import dataclasses +import itertools +import re +from collections.abc import Callable, Mapping, Sequence +from typing import Any + +# Dimensions the runner provides rather than the component: they are not props. +APPEARANCE = "appearance" +STATE = "state" +VIEWPORT = "viewport" +ENVIRONMENT = (APPEARANCE, STATE, VIEWPORT) + +LIGHT = "light" +DARK = "dark" +REST = "rest" +# States driven through the browser: the pointer and the keyboard. +HOVER = "hover" +FOCUS_VISIBLE = "focus-visible" +ACTIVE = "active" + +# The width of the page unless a matrix sweeps the viewport. +DEFAULT_VIEWPORT = 1280 + +ENVIRONMENT_BASE: Mapping[str, Any] = { + APPEARANCE: LIGHT, + STATE: REST, + VIEWPORT: DEFAULT_VIEWPORT, +} + +# What the computed-style diff reads unless a matrix says otherwise: the +# longhands a component's look is made of. +DEFAULT_PROPERTIES: tuple[str, ...] = ( + "display", + "position", + "box-sizing", + "width", + "height", + "min-width", + "min-height", + "max-width", + "max-height", + "margin-top", + "margin-right", + "margin-bottom", + "margin-left", + "padding-top", + "padding-right", + "padding-bottom", + "padding-left", + "border-top-width", + "border-right-width", + "border-bottom-width", + "border-left-width", + "border-top-style", + "border-right-style", + "border-bottom-style", + "border-left-style", + "border-top-color", + "border-right-color", + "border-bottom-color", + "border-left-color", + "border-top-left-radius", + "border-top-right-radius", + "border-bottom-right-radius", + "border-bottom-left-radius", + "background-color", + "background-image", + "box-shadow", + "color", + "opacity", + "font-family", + "font-size", + "font-weight", + "font-style", + "line-height", + "letter-spacing", + "text-align", + "text-decoration-line", + "text-transform", + "white-space", + "vertical-align", + "flex-direction", + "flex-wrap", + "flex-grow", + "flex-shrink", + "flex-basis", + "align-items", + "justify-content", + "row-gap", + "column-gap", + "overflow-x", + "overflow-y", + "outline-style", + "outline-width", + "outline-color", + "outline-offset", + "cursor", + "pointer-events", + "user-select", + "transform", + "filter", + "visibility", +) + +_UNSAFE = re.compile(r"[^a-z0-9]+") + + +def label(value: object) -> str: + """Name a dimension value in a cell id. + + Args: + value: The value of a dimension. + + Returns: + The value in lowercase, anything but letters and digits as a dash. + """ + return _UNSAFE.sub("-", str(value).lower()).strip("-") + + +@dataclasses.dataclass(frozen=True) +class Cell: + """One point of a matrix: a set of props under one environment. + + Attributes: + props_id: The props that differ from the base cell, or ``base``. Cells + that share it share one rendered element. + props: The props the component is created with. + appearance: The color scheme of the page. + state: The interactive state the element is put in. + viewport: The width of the page, in CSS pixels. + """ + + props_id: str + props: Mapping[str, Any] + appearance: str + state: str + viewport: int + + @property + def id(self) -> str: + """Name the cell within its component. + + Returns: + The props id, then each environment value that is not the default. + """ + parts = [self.props_id] + if self.appearance != LIGHT: + parts.append(self.appearance) + if self.state != REST: + parts.append(self.state) + if self.viewport != DEFAULT_VIEWPORT: + parts.append(str(self.viewport)) + return "@".join(parts) + + +Selector = str | tuple[str, str] + + +@dataclasses.dataclass(frozen=True) +class Matrix: + """The cells of a component whose look is compared between the two systems. + + A dimension is a prop name, or one of ``appearance``, ``state`` and + ``viewport``, which the runner provides. Its values are a sequence, or a + mapping from a label to a value that has no short name of its own, such as + a responsive value. + + Attributes: + component: The name both namespaces know the component by: ``rx.box`` + and ``rx.ui.box`` are ``box``. + render: Create the component from a namespace (``rx`` or ``rx.ui``) and + the props of a cell. The default calls the component with the + props. + base: The value of each dimension in the base cell, and props every + cell is created with. + cross: Dimensions whose every combination is a cell. + sweep: Dimensions varied one at a time, the others at their base. + groups: Further cross products, each over its own dimensions. + stage: The width and height, in CSS pixels, of the fixed frame a cell + is rendered in. + margin: How far beyond the element a screenshot reaches, for outlines + and shadows. + crop: ``element`` compares the element and its margin, ``stage`` the + whole frame, for what is drawn outside the element, such as a + popup. + target: The CSS selector, below the frame, of the element whose + computed style is read: one string, or one per system. The default + is the first element of the frame. + parts: Inner elements whose computed style is compared too, by name. + properties: The computed properties compared. + threshold: How far a pixel's color may be off, from 0 to 1, before the + pixel counts as differing. + tolerance: The fraction of a cell's pixels that may differ. + states: Drivers of states the runner does not know, such as ``open``. + """ + + component: str + render: Callable[[Any, Mapping[str, Any]], Any] | None = None + base: Mapping[str, Any] = dataclasses.field(default_factory=dict) + cross: Mapping[str, Sequence[Any] | Mapping[str, Any]] = dataclasses.field( + default_factory=dict + ) + sweep: Mapping[str, Sequence[Any] | Mapping[str, Any]] = dataclasses.field( + default_factory=dict + ) + groups: Sequence[Mapping[str, Sequence[Any] | Mapping[str, Any]]] = () + stage: tuple[int, int] = (240, 120) + margin: int = 8 + crop: str = "element" + target: Selector | None = None + parts: Mapping[str, Selector] = dataclasses.field(default_factory=dict) + properties: tuple[str, ...] = DEFAULT_PROPERTIES + threshold: float = 0.01 + tolerance: float = 0.005 + states: Mapping[str, Any] = dataclasses.field(default_factory=dict) + + def create(self, namespace: Any, props: Mapping[str, Any]) -> Any: + """Create the component of one system for a cell. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The component. + """ + if self.render is not None: + return self.render(namespace, props) + return getattr(namespace, self.component)(**props) + + def cells(self) -> list[Cell]: + """Expand the declaration. + + Returns: + The base cell, then the cells of ``cross``, ``sweep`` and + ``groups`` in the order declared, each combination once. + """ + base_labels = { + **{name: label(value) for name, value in ENVIRONMENT_BASE.items()}, + **{name: label(value) for name, value in self.base.items()}, + } + base_values = {**ENVIRONMENT_BASE, **self.base} + groups = [ + {}, + self.cross, + *({name: values} for name, values in self.sweep.items()), + *self.groups, + ] + cells: dict[str, Cell] = {} + for group in groups: + dimensions = [ + [ + (name, value_label, value) + for value_label, value in ( + values.items() + if isinstance(values, Mapping) + else ((label(value), value) for value in values) + ) + ] + for name, values in group.items() + ] + for combination in itertools.product(*dimensions): + values = dict(base_values) + changed: dict[str, str] = {} + for name, value_label, value in combination: + values[name] = value + if base_labels.get(name) != value_label: + changed[name] = value_label + props_id = ( + "_".join( + f"{label(name)}-{changed[name]}" + for name in sorted(changed) + if name not in ENVIRONMENT + ) + or "base" + ) + cell = Cell( + props_id=props_id, + props={ + name: value + for name, value in values.items() + if name not in ENVIRONMENT + }, + appearance=values[APPEARANCE], + state=values[STATE], + viewport=values[VIEWPORT], + ) + cells.setdefault(cell.id, cell) + return list(cells.values()) + + def rendered(self) -> dict[str, Mapping[str, Any]]: + """Get the elements a page of the matrix renders. + + Returns: + The props of each distinct element, by props id. + """ + rendered: dict[str, Mapping[str, Any]] = {} + for cell in self.cells(): + rendered.setdefault(cell.props_id, cell.props) + return rendered diff --git a/packages/reflex-components-ui/parity/ui_parity/report.py b/packages/reflex-components-ui/parity/ui_parity/report.py new file mode 100644 index 00000000000..e7e8d961649 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/report.py @@ -0,0 +1,179 @@ +"""The browsable report of a parity run. + +A directory that can be zipped or published as it is: ``index.html``, the +numbers as ``results.json``, and the reference, candidate and diff image of +every cell under ``//``. +""" + +from __future__ import annotations + +import dataclasses +import html +import json +import operator +from pathlib import Path +from typing import Any + +from ui_parity.look import MatrixResult + +RESULTS = "results.json" +INDEX = "index.html" + +_STYLE = """ +:root { color-scheme: light dark; font: 14px/1.4 system-ui, sans-serif; } +body { margin: 24px; } +h1 { font-size: 20px; } +h2 { font-size: 16px; margin-top: 32px; } +table { border-collapse: collapse; width: 100%; } +th, td { border-bottom: 1px solid #8884; padding: 6px 8px; text-align: left; vertical-align: top; } +td.number { font-variant-numeric: tabular-nums; white-space: nowrap; } +tr.fail td:first-child { box-shadow: inset 3px 0 #d33; } +tr.pass td:first-child { box-shadow: inset 3px 0 #2a2; } +img { image-rendering: pixelated; background: #fff; outline: 1px solid #8884; max-width: 100%; } +pre { margin: 0; white-space: pre-wrap; } +body.failures tr.pass { display: none; } +""" + + +def _row(result: dict[str, Any]) -> str: + """Render the table row of a cell. + + Args: + result: The cell's entry of the results. + + Returns: + The row. + """ + notes = [ + *(html.escape(problem) for problem in result["problems"]), + *(f"allowed: {html.escape(reason)}" for reason in result["allowed"]), + ] + images = "".join( + f'' + f'' + for kind in ("reference", "candidate", "diff") + ) + status = "fail" if result["problems"] else "pass" + return ( + f'{html.escape(result["cell"])}' + f'{result["differing"]} / ' + f"{result['width'] * result['height']}
{result['ratio']:.2%}
" + f"{result['antialiased']} anti-aliased" + f"{images}
{chr(10).join(notes)}
" + ) + + +def _section(matrix: dict[str, Any]) -> str: + """Render the section of a component in one engine. + + Args: + matrix: The matrix's entry of the results. + + Returns: + The heading, the numbers and the table of cells. + """ + failed = sum(1 for cell in matrix["cells"] if cell["problems"]) + rows = "".join(_row(cell) for cell in matrix["cells"]) + stale = "".join(f"

{html.escape(line)}

" for line in matrix["stale"]) + return ( + f'

' + f"{html.escape(matrix['component'])} · {html.escape(matrix['engine'])}

" + f"

{len(matrix['cells'])} cells, {failed} failing, " + f"{matrix['passes']} page loads, {matrix['seconds']:.1f} s

{stale}" + "" + "" + f"{rows}
cellpixelsrx (Radix)rx.uidiffdifferences
" + ) + + +def render(results: list[dict[str, Any]]) -> str: + """Render the report. + + Args: + results: The entry of each matrix that ran. + + Returns: + The HTML document. + """ + cells = sum(len(matrix["cells"]) for matrix in results) + failed = sum( + 1 for matrix in results for cell in matrix["cells"] if cell["problems"] + ) + seconds = sum(matrix["seconds"] for matrix in results) + sections = "".join(_section(matrix) for matrix in results) + return ( + '' + f"rx.ui parity" + "

rx.ui parity with Radix Themes

" + f"

{len(results)} matrices, {cells} cells, {failed} failing, " + f"{seconds:.1f} s

" + '" + f"{sections}" + ) + + +def entry(result: MatrixResult) -> dict[str, Any]: + """Reduce the result of a matrix to what the report keeps. + + Args: + result: The result. + + Returns: + The numbers of the matrix and of each cell, as JSON holds them. + """ + return { + "component": result.component, + "engine": result.engine, + "seconds": round(result.seconds, 3), + "passes": result.passes, + "stale": [ + f"stale allowlist entry: {item.check}, cells {item.cells}: {item.reason}" + for item in result.stale + ], + "cells": [ + { + "cell": cell.cell, + "width": cell.width, + "height": cell.height, + "differing": cell.differing, + "antialiased": cell.antialiased, + "ratio": cell.ratio, + "tolerance": cell.tolerance, + "styles": [ + dataclasses.asdict(difference) for difference in cell.styles + ], + "a11y": cell.a11y, + "allowed": cell.allowed, + "problems": cell.problems, + "images": cell.images, + } + for cell in result.cells + ], + } + + +def write(report: Path, result: MatrixResult) -> Path: + """Add the result of a matrix to a report. + + Args: + report: The directory of the report. + result: The result, whose images are already there. + + Returns: + The page of the report. + """ + path = report / RESULTS + results = json.loads(path.read_text()) if path.exists() else [] + results = [ + matrix + for matrix in results + if (matrix["engine"], matrix["component"]) != (result.engine, result.component) + ] + results.append(entry(result)) + results.sort(key=operator.itemgetter("component", "engine")) + path.write_text(json.dumps(results, indent=2) + "\n") + index = report / INDEX + index.write_text(render(results), encoding="utf-8") + return index diff --git a/packages/reflex-components-ui/parity/ui_parity/systems.py b/packages/reflex-components-ui/parity/ui_parity/systems.py new file mode 100644 index 00000000000..c96c57a95ef --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/systems.py @@ -0,0 +1,42 @@ +"""The two component systems the harness compares.""" + +from __future__ import annotations + +import dataclasses +import importlib +from types import ModuleType + + +@dataclasses.dataclass(frozen=True) +class System: + """A namespace of components. + + Attributes: + name: The name an app refers to it by. + role: What it is to a comparison: the reference or the candidate. + slug: Its name in a route. + module: The module the namespace is. + """ + + name: str + role: str + slug: str + module: str + + @property + def namespace(self) -> ModuleType: + """The namespace components are created from. + + Returns: + ``rx`` or ``rx.ui``. + """ + return importlib.import_module(self.module) + + +# Radix Themes, which a component must look and behave like. +REFERENCE = System(name="rx", role="reference", slug="rx", module="reflex") +# The compiled components. +CANDIDATE = System( + name="rx.ui", role="candidate", slug="ui", module="reflex_components_ui" +) +SYSTEMS = (REFERENCE, CANDIDATE) diff --git a/packages/reflex-components-ui/parity/ui_parity/ui_parity.py b/packages/reflex-components-ui/parity/ui_parity/ui_parity.py new file mode 100644 index 00000000000..18a10ddd18d --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/ui_parity.py @@ -0,0 +1,5 @@ +"""The app, for ``reflex run`` in the directory above.""" + +from ui_parity.app import create_app + +app = create_app() diff --git a/pyproject.toml b/pyproject.toml index bec46ac01e7..48d9d44df91 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -191,6 +191,8 @@ extraPaths = [ "packages/reflex-recharts/src", "packages/reflex-sonner/src", "packages/reflex-components-ui/src", + # The parity harness is read from the repository rather than installed. + "packages/reflex-components-ui/parity", "packages/reflex-components-internal/src", "packages/reflex-otel/src", "packages/reflex-build-sdk/src", @@ -319,6 +321,9 @@ preview = true "packages/reflex-base/hatch_build.py" = ["INP001"] "packages/reflex-components-ui/hatch_build.py" = ["INP001"] "scripts/changed_paths.py" = ["T201"] +"scripts/ui_parity.py" = ["T201"] +# A Reflex project of its own, beside the package it runs. +"packages/reflex-components-ui/parity/rxconfig.py" = ["INP001"] "scripts/check_min_deps.py" = ["T201"] "scripts/check_outdated_deps.py" = ["T201"] "scripts/hash_examples.py" = ["T201"] @@ -330,6 +335,8 @@ preview = true filterwarnings = "ignore:fields may not start with an underscore:RuntimeWarning" asyncio_default_fixture_loop_scope = "function" asyncio_mode = "auto" +# The rx.ui parity harness, which no wheel ships. +pythonpath = ["packages/reflex-components-ui/parity"] markers = [ "performance: scheduled wall-time, service, memory, lifecycle, or browser benchmark", ] diff --git a/scripts/ui_parity.py b/scripts/ui_parity.py new file mode 100644 index 00000000000..c8b33e24963 --- /dev/null +++ b/scripts/ui_parity.py @@ -0,0 +1,103 @@ +"""Run the rx.ui parity harness: one command for the look and the behaviour. + + uv run python scripts/ui_parity.py box one component, in Chromium + uv run python scripts/ui_parity.py every component, in Chromium + uv run python scripts/ui_parity.py --all-engines and in Firefox and WebKit + uv run python scripts/ui_parity.py differences the intended differences, as markdown + +The checks are the tests of tests/integration/tests_playwright/test_ui_parity.py; +this builds the pytest command for them. +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).parents[1] +PARITY = REPO_ROOT / "packages" / "reflex-components-ui" / "parity" +TESTS = "tests/integration/tests_playwright/test_ui_parity.py" +ENGINES = ("chromium", "firefox", "webkit") +DIFFERENCES = "differences" + + +def pytest_command( + components: list[str], engines: list[str], extra: list[str] +) -> list[str]: + """Build the pytest command of a run. + + Args: + components: The components to check: every one when empty. + engines: The browser engines to run in. + extra: Arguments passed on to pytest. + + Returns: + The command. + """ + command = [sys.executable, "-m", "pytest", TESTS, "-rs"] + for engine in engines: + command += ["--browser", engine] + if components: + # A test id holds its component after the engine: "chromium-box]" for + # a matrix, "chromium-box-rx.ui-..." for a step. The run time is + # recorded whatever ran. + selected = [f"-{name}] or -{name}-" for name in components] + command += ["-k", " or ".join([*selected, "test_run_time"])] + return command + extra + + +def main(argv: list[str] | None = None) -> int: + """Run the harness, or print the intended differences. + + Args: + argv: The command line, without the program name. + + Returns: + The exit code: that of pytest. + """ + parser = argparse.ArgumentParser(description=(__doc__ or "").partition("\n")[0]) + parser.add_argument( + "components", + nargs="*", + help=f'components to check (default: all), or "{DIFFERENCES}"', + ) + parser.add_argument( + "--engine", + action="append", + choices=ENGINES, + help="a browser engine to run in; may be repeated (default: chromium)", + ) + parser.add_argument( + "--all-engines", action="store_true", help="run in every browser engine" + ) + parser.add_argument( + "--report", + type=Path, + help=f"where the report goes (default: {PARITY / 'report'})", + ) + args, extra = parser.parse_known_args(argv) + if args.components == [DIFFERENCES]: + sys.path.insert(0, str(PARITY)) + from ui_parity import allowlist + + print(allowlist.differences_markdown(allowlist.load())) + return 0 + env = dict(os.environ) + if args.report is not None: + env["UI_PARITY_REPORT"] = str(args.report.resolve()) + engines: list[str] = ( + list(ENGINES) if args.all_engines else args.engine or [ENGINES[0]] + ) + return subprocess.run( + pytest_command(args.components, engines, extra), + cwd=REPO_ROOT, + env=env, + check=False, + ).returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/integration/tests_playwright/test_ui_parity.py b/tests/integration/tests_playwright/test_ui_parity.py new file mode 100644 index 00000000000..4b04cfad1de --- /dev/null +++ b/tests/integration/tests_playwright/test_ui_parity.py @@ -0,0 +1,336 @@ +"""The rx.ui parity harness: the look and the behaviour of every component. + +One production build of the generated app serves every test. A matrix test +compares the pixels, computed styles and accessibility tree of a component with +its Radix counterpart, and a contract test runs one step of a behaviour +contract against one of the two systems. Both run in whichever engines +``--browser`` names; ``scripts/ui_parity.py`` builds the command. +""" + +import json +import os +import time +from collections.abc import Generator +from pathlib import Path + +import pytest +from playwright.sync_api import Browser, Page + +from reflex.testing import AppHarness, AppHarnessProd + +# The steps of a contract are plain asserts: have them explain themselves. +pytest.register_assert_rewrite("ui_parity") + +from ui_parity import allowlist, report # noqa: E402 +from ui_parity.app import contract_route, parity_route # noqa: E402 +from ui_parity.components import CONTRACTS, MATRICES # noqa: E402 +from ui_parity.contract import HYDRATED, ContractError, Step, run_step # noqa: E402 +from ui_parity.look import StyleDifference, run_matrix # noqa: E402 +from ui_parity.systems import CANDIDATE, REFERENCE, SYSTEMS # noqa: E402 + +# Where the report of a run goes, unless UI_PARITY_REPORT names a directory. +DEFAULT_REPORT = Path(allowlist.ALLOWLIST).parent / "report" +# How long the build and every matrix may take together, in seconds. +BUDGET = float(os.environ.get("UI_PARITY_BUDGET_SECONDS", "900")) +TIMINGS = "timings.json" + +# What the runs of this module took: the build, then each matrix by engine and +# component. +_seconds: dict[str, float] = {} + + +def UIParityApp(): + """The generated app: a page per matrix and two per contract.""" + from ui_parity.app import create_app + + import reflex as rx + + app = create_app() # noqa: F841 + + config = rx.config.get_config() + config.plugins = [rx.plugins.UIPlugin(), rx.plugins.TailwindV4Plugin()] + # The badge floats over the page, and over whatever cell lies under it. + config.show_built_with_reflex = False + + +@pytest.fixture(scope="module") +def parity_app( + tmp_path_factory: pytest.TempPathFactory, +) -> Generator[AppHarness, None, None]: + """Build the generated app for production and serve it. + + Args: + tmp_path_factory: pytest fixture for creating temporary directories. + + Yields: + The running harness. + """ + started = time.perf_counter() + with AppHarnessProd.create( + root=tmp_path_factory.mktemp("ui_parity_app"), + app_name="ui_parity_app", + app_source=UIParityApp, + ) as harness: + assert harness.frontend_url is not None, "app is not running" + _seconds["build"] = time.perf_counter() - started + yield harness + + +@pytest.fixture(scope="module") +def report_dir() -> Path: + """Start a report: forget the results of the run before. + + The images stay, and are replaced as their cells run again: the directory + is one a developer named, and may hold more than the report. + + Returns: + The directory the report is written to. + """ + directory = Path(os.environ.get("UI_PARITY_REPORT", DEFAULT_REPORT)).resolve() + directory.mkdir(parents=True, exist_ok=True) + for name in (report.RESULTS, report.INDEX, TIMINGS): + (directory / name).unlink(missing_ok=True) + return directory + + +def _url(harness: AppHarness, route: str) -> str: + """Get the address of a page of the app. + + Args: + harness: The running harness. + route: The route of the page. + + Returns: + The address a production build serves the page at. + """ + assert harness.frontend_url is not None + return harness.frontend_url.rstrip("/") + route + "/" + + +@pytest.mark.parametrize("component", MATRICES) +def test_matrix( + parity_app: AppHarness, browser: Browser, report_dir: Path, component: str +): + """Every cell of a component looks like the Radix component.""" + result = run_matrix( + browser, + _url(parity_app, parity_route(component)), + MATRICES[component], + report_dir, + allowlist.load(), + scale=int(os.environ.get("UI_PARITY_SCALE", "1")), + ) + index = report.write(report_dir, result) + _seconds[f"{result.engine}/{component}"] = result.seconds + failures = result.failures(report_dir) + assert not failures, "\n".join([*failures, f"report: {index}"]) + + +def _pad_candidate(page: Page) -> None: + """Give every rx.ui element of a parity page a padding of its own. + + Args: + page: The loaded page. + """ + page.add_style_tag( + content='[data-parity-system="candidate"] > * { padding: 3px !important }' + ) + + +def test_changed_padding_fails_the_matrix( + parity_app: AppHarness, browser: Browser, tmp_path: Path +): + """A box padded differently from the Radix one fails, with the numbers.""" + result = run_matrix( + browser, + _url(parity_app, parity_route("box")), + MATRICES["box"], + tmp_path, + allowlist.Allowlist(), + prepare=_pad_candidate, + ) + base = result.cells[0] + assert base.cell == "base" + assert base.styles == [ + StyleDifference("", "height", "24px", "30px"), + *( + StyleDifference("", f"padding-{side}", "0px", "3px") + for side in ("top", "right", "bottom", "left") + ), + ] + assert base.a11y is None + # The text moved by three pixels each way: its old and its new place differ. + assert base.differing > 0 + assert base.ratio > base.tolerance + assert base.problems[0] == ( + f"{base.differing} of {base.width * base.height} pixels differ " + f"({base.ratio:.2%}, 0.00% allowed)" + ) + # Every cell fails, each naming itself and its three images. + failures = result.failures(tmp_path) + assert [failure.splitlines()[0] for failure in failures] == [ + f"box [{result.engine}] cell {cell.cell}:" for cell in result.cells + ] + directory = tmp_path / result.engine / "box" + assert failures[0].splitlines()[-1] == ( + f" images: {directory}/base.{{reference,candidate,diff}}.png" + ) + assert sorted(path.name for path in directory.iterdir()) == sorted( + f"{cell.cell}.{kind}.png" + for cell in result.cells + for kind in ("reference", "candidate", "diff") + ) + + +def _name_candidate(page: Page) -> None: + """Give every rx.ui element of a parity page a role the Radix one lacks. + + Args: + page: The loaded page. + """ + page.evaluate( + """() => { + for (const element of document.querySelectorAll( + '[data-parity-system="candidate"] > *', + )) { + element.setAttribute("role", "note"); + } + }""" + ) + + +def test_changed_role_fails_the_matrix( + parity_app: AppHarness, browser: Browser, tmp_path: Path +): + """A box the accessibility tree describes differently fails, once per element.""" + result = run_matrix( + browser, + _url(parity_app, parity_route("box")), + MATRICES["box"], + tmp_path, + allowlist.Allowlist(), + prepare=_name_candidate, + ) + trees = ("The quick brown fox", "- note: The quick brown fox") + assert {cell.cell: cell.a11y for cell in result.cells} == { + "base": trees, + "style-padding": trees, + "style-border": trees, + "custom-attrs-focusable": trees, + # The same elements as above, in another environment. + "base@dark": None, + "base@hover": None, + "base@520": None, + "custom-attrs-focusable@focus-visible": None, + } + assert result.cells[0].problems == [ + ( + "accessibility tree: rx 'The quick brown fox', " + "rx.ui '- note: The quick brown fox'" + ) + ] + + +CONTRACT_STEPS = [ + pytest.param(component, system, step, id=f"{component}-{system.name}-{step.name}") + for component, contract in CONTRACTS.items() + for system in SYSTEMS + for step in contract.steps +] + + +@pytest.mark.parametrize(("component", "system", "step"), CONTRACT_STEPS) +def test_contract(parity_app: AppHarness, browser: Browser, component, system, step): + """A step of a component's contract passes, or is listed as a difference.""" + run_step( + browser, + _url(parity_app, contract_route(component, system)), + CONTRACTS[component], + system, + step, + allowlist.load(), + ) + + +def _fail(run) -> None: + """Fail a step: the box is not what the step says it is. + + Args: + run: The run of the step. + """ + assert run.page.locator("#box").inner_text() == "something else" + + +def test_contract_failure_names_what_failed(parity_app: AppHarness, browser: Browser): + """A failing step names the component, the system, the engine and itself.""" + engine = browser.browser_type.name + contract = CONTRACTS["box"] + url = _url(parity_app, contract_route("box", CANDIDATE)) + step = Step("says something else", _fail, on=HYDRATED) + with pytest.raises(ContractError) as failure: + run_step(browser, url, contract, CANDIDATE, step, allowlist.Allowlist()) + assert str(failure.value) == ( + f'box [rx.ui, {engine}] step "says something else" failed: ' + "AssertionError: assert 'content' == 'something else'\n" + " \n - something else\n + content" + ) + + # Listed as a difference of rx.ui in this engine, the failure passes, and + # the same step of the Radix component is not excused by it. + entry = allowlist.ContractEntry( + component="box", + step="says something else", + system=CANDIDATE.name, + engines=(engine,), + reason="The box says what it was given.", + ) + listed = allowlist.Allowlist(contract=(entry,)) + run_step(browser, url, contract, CANDIDATE, step, listed) + with pytest.raises(ContractError): + run_step( + browser, + _url(parity_app, contract_route("box", REFERENCE)), + contract, + REFERENCE, + step, + listed, + ) + + # A listed difference that is none any more fails until it is removed. + stale = allowlist.Allowlist( + contract=( + allowlist.ContractEntry( + component="box", + step=contract.steps[0].name, + system=CANDIDATE.name, + engines=(), + reason="It used to warn.", + ), + ) + ) + with pytest.raises(ContractError) as failure: + run_step(browser, url, contract, CANDIDATE, contract.steps[0], stale) + assert str(failure.value) == ( + f'box [rx.ui, {engine}] step "hydrates with no warnings" passes, but ' + 'allowlist.toml says it does not ("It used to warn."). Remove the entry.' + ) + + +def test_run_time_is_within_budget(report_dir: Path): + """The build and the matrices of the run fit the budget, and are recorded.""" + total = sum(_seconds.values()) + (report_dir / TIMINGS).write_text( + json.dumps( + { + "budget": BUDGET, + "total": round(total, 3), + "seconds": {name: round(value, 3) for name, value in _seconds.items()}, + }, + indent=2, + ) + + "\n" + ) + assert total <= BUDGET, ( + f"The parity run took {total:.0f} s, over its budget of {BUDGET:.0f} s: " + f"{_seconds}. Cross fewer dimensions and sweep the rest." + ) diff --git a/tests/units/reflex_components_ui/parity/__init__.py b/tests/units/reflex_components_ui/parity/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_components_ui/parity/test_allowlist.py b/tests/units/reflex_components_ui/parity/test_allowlist.py new file mode 100644 index 00000000000..40520d3d614 --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_allowlist.py @@ -0,0 +1,221 @@ +"""Tests for the allowlist of the parity harness.""" + +import pytest +import reflex_components_ui +from ui_parity import allowlist +from ui_parity.allowlist import ( + Allowlist, + AllowlistError, + ApiEntry, + ContractEntry, + LookEntry, +) + +# The accepted differences the first component waves bring, in the file's form. +DOCUMENT = { + "api": [ + { + "component": "select", + "kind": "prop", + "names": ["position"], + "reason": "Select has no item-aligned positioning.", + } + ], + "contract": [ + { + "component": "dialog", + "step": "Tab stays inside the dialog", + "reason": "A native modal dialog lets Tab reach the browser's own UI.", + }, + { + "component": "switch", + "step": "Enter toggles", + "system": "rx.ui", + "engines": ["firefox", "webkit"], + "reason": "A switch toggles on Space but not Enter.", + }, + ], + "look": [ + { + "component": "tooltip", + "check": "pixels", + "cells": "*@open", + "reason": "Tooltips have no arrow.", + }, + { + "component": "select", + "check": "style", + "properties": ["top", "left"], + "engines": ["webkit"], + "reason": "Select has no item-aligned positioning.", + }, + ], +} + +ENTRIES = Allowlist( + api=( + ApiEntry( + component="select", + kind="prop", + names=("position",), + reason="Select has no item-aligned positioning.", + ), + ), + contract=( + ContractEntry( + component="dialog", + step="Tab stays inside the dialog", + system="rx.ui", + engines=(), + reason="A native modal dialog lets Tab reach the browser's own UI.", + ), + ContractEntry( + component="switch", + step="Enter toggles", + system="rx.ui", + engines=("firefox", "webkit"), + reason="A switch toggles on Space but not Enter.", + ), + ), + look=( + LookEntry( + component="tooltip", + check="pixels", + cells="*@open", + properties=(), + engines=(), + reason="Tooltips have no arrow.", + ), + LookEntry( + component="select", + check="style", + cells="*", + properties=("top", "left"), + engines=("webkit",), + reason="Select has no item-aligned positioning.", + ), + ), +) + + +def test_parse_reads_every_table_with_its_defaults(): + assert allowlist.parse(DOCUMENT) == ENTRIES + assert allowlist.parse({}) == Allowlist() + + +@pytest.mark.parametrize( + ("document", "message"), + [ + ({"pixels": []}, "Unknown allowlist tables: ['pixels']."), + ( + {"api": [{"component": "box", "kind": "prop", "names": ["a"]}]}, + ( + "[[api]] entry {'component': 'box', 'kind': 'prop', 'names': ['a']} " + "is missing: ['reason']." + ), + ), + ( + {"contract": [{"component": "box", "step": "s", "reason": " "}]}, + ( + "[[contract]] entry {'component': 'box', 'step': 's', 'reason': ' '} " + "needs a reason." + ), + ), + ( + { + "look": [ + {"component": "box", "check": "pixels", "cell": "*", "reason": "r"} + ] + }, + ( + "[[look]] entry {'component': 'box', 'check': 'pixels', 'cell': '*', " + "'reason': 'r'} has unknown keys: ['cell']." + ), + ), + ( + { + "api": [ + {"component": "box", "kind": "props", "names": [], "reason": "r"} + ] + }, + "[[api]] kind = \"props\" is not one of ['prop', 'type', 'event'].", + ), + ( + { + "contract": [ + {"component": "b", "step": "s", "system": "ui", "reason": "r"} + ] + }, + "[[contract]] system = \"ui\" is not one of ['rx', 'rx.ui'].", + ), + ( + {"look": [{"component": "box", "check": "color", "reason": "r"}]}, + "[[look]] check = \"color\" is not one of ['pixels', 'style', 'a11y'].", + ), + ], +) +def test_parse_rejects_what_it_does_not_understand(document: dict, message: str): + with pytest.raises(AllowlistError) as error: + allowlist.parse(document) + assert str(error.value) == message + + +def test_contract_entry_covers_its_system_and_engines(): + everywhere, some = ENTRIES.contract + step = "Tab stays inside the dialog" + assert [ + everywhere.covers("dialog", step, system, engine) + for system in ("rx.ui", "rx") + for engine in ("chromium", "webkit") + ] == [True, True, False, False] + assert everywhere.covers("dialog", "Escape closes", "rx.ui", "chromium") is False + assert everywhere.covers("select", step, "rx.ui", "chromium") is False + assert [ + some.covers("switch", "Enter toggles", "rx.ui", engine) + for engine in ("chromium", "firefox", "webkit") + ] == [False, True, True] + + +def test_look_entry_covers_its_check_cells_and_engines(): + arrow, position = ENTRIES.look + assert [ + arrow.covers("tooltip", check, cell, "firefox") + for check in ("pixels", "style") + for cell in ("base@open", "side-top@dark@open", "base") + ] == [True, True, False, False, False, False] + assert [ + position.covers("select", "style", "base", engine) + for engine in ("chromium", "webkit") + ] == [False, True] + + +def test_differences_markdown_lists_every_entry_by_component(): + assert allowlist.differences_markdown(ENTRIES) == ( + "### dialog\n" + "\n" + '- behaviour, `rx.ui`, "Tab stays inside the dialog": A native modal ' + "dialog lets Tab reach the browser's own UI.\n" + "\n" + "### select\n" + "\n" + "- prop `position`: Select has no item-aligned positioning.\n" + "- style in webkit, `top`, `left`: Select has no item-aligned positioning.\n" + "\n" + "### switch\n" + "\n" + '- behaviour, `rx.ui` in firefox, webkit, "Enter toggles": A switch ' + "toggles on Space but not Enter.\n" + "\n" + "### tooltip\n" + "\n" + "- pixels, *@open: Tooltips have no arrow." + ) + + +def test_committed_allowlist_names_only_rx_ui_components(): + components = set(reflex_components_ui.__all__) + entries = allowlist.load() + listed = { + entry.component for entry in (*entries.api, *entries.contract, *entries.look) + } + assert sorted(listed - components) == [] diff --git a/tests/units/reflex_components_ui/parity/test_contract.py b/tests/units/reflex_components_ui/parity/test_contract.py new file mode 100644 index 00000000000..56c6a8f66c1 --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_contract.py @@ -0,0 +1,96 @@ +"""Tests for the contract declaration that need no browser.""" + +import pytest +from ui_parity.contract import ( + HYDRATED, + HYDRATION_STEP, + NO_JAVASCRIPT, + SERVER, + Contract, + Run, + ServerElement, + ServerHtml, +) +from ui_parity.systems import CANDIDATE + +DOCUMENT = ServerHtml( + '
before' + 'in
side
after
' + '

outside

' +) + + +def test_server_html_finds_an_element_and_its_text(): + assert DOCUMENT.element("a") == ServerElement( + tag="div", attributes={"id": "a", "class": "x y"}, text="beforeinside after" + ) + assert DOCUMENT.element("inner") == ServerElement( + tag="span", attributes={"id": "inner"}, text="inside" + ) + # An element that cannot hold text does not take what follows it. + assert DOCUMENT.element("field") == ServerElement( + tag="input", attributes={"id": "field", "disabled": None, "value": "v"} + ) + + +def test_server_html_fails_for_an_element_the_server_did_not_render(): + with pytest.raises(AssertionError) as error: + DOCUMENT.element("missing") + assert str(error.value) == 'the server HTML has no element with id "missing"' + + +def test_contract_starts_with_the_hydration_step_and_keeps_declared_order(): + contract = Contract(component="switch", render=lambda namespace: None) + + @contract.step("is a checkbox in the server render", on=SERVER) + def server(run: Run) -> None: ... + + @contract.step("is checked with JavaScript disabled", on=NO_JAVASCRIPT) + def without_javascript(run: Run) -> None: ... + + @contract.step("Space toggles") + def space(run: Run) -> None: ... + + assert [(step.name, step.on) for step in contract.steps] == [ + (HYDRATION_STEP, HYDRATED), + ("is a checkbox in the server render", SERVER), + ("is checked with JavaScript disabled", NO_JAVASCRIPT), + ("Space toggles", HYDRATED), + ] + assert [step.check for step in contract.steps[1:]] == [ + server, + without_javascript, + space, + ] + # Each contract has steps of its own. + assert len(Contract(component="box", render=lambda namespace: None).steps) == 1 + + +def test_contract_rejects_a_duplicate_step_and_an_unknown_page(): + contract = Contract(component="switch", render=lambda namespace: None) + with pytest.raises(ValueError) as error: + contract.step(HYDRATION_STEP) + assert str(error.value) == ( + 'switch: two steps are named "hydrates with no warnings".' + ) + with pytest.raises(ValueError) as error: + contract.step("works offline", on="offline") + assert str(error.value) == "switch: a step cannot run on 'offline'." + + +def test_hydration_step_fails_on_what_the_browser_reported(): + (step,) = Contract(component="box", render=lambda namespace: None).steps + run = Run(component="box", system=CANDIDATE, engine="chromium", server=DOCUMENT) + step.check(run) + run.problems.append("console error: Minified React error #418") + with pytest.raises(AssertionError): + step.check(run) + + +def test_server_step_has_no_page(): + run = Run(component="box", system=CANDIDATE, engine="chromium", server=DOCUMENT) + with pytest.raises(RuntimeError) as error: + run.page + assert str(error.value) == ( + "A step on 'server' has no page: read run.server instead." + ) diff --git a/tests/units/reflex_components_ui/parity/test_diff.py b/tests/units/reflex_components_ui/parity/test_diff.py new file mode 100644 index 00000000000..1f7d940f3ee --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_diff.py @@ -0,0 +1,130 @@ +"""Tests for the image diff of the parity harness.""" + +from collections.abc import Callable + +import numpy as np +import pytest +from PIL import Image +from ui_parity.diff import ANTIALIASED, DIFFERENT, ImageDiff, diff_images + +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) +GRAY = (128, 128, 128) +# How the diff image draws black: the reference faded to a tenth. +FADED_BLACK = (230, 230, 230) + +Color = tuple[int, int, int] + + +def fixture(width: int, height: int, color: Callable[[int, int], Color]) -> Image.Image: + """Draw a fixture image. + + Args: + width: The width of the image. + height: The height of the image. + color: The color of the pixel at a column and a row. + + Returns: + The image. + """ + image = Image.new("RGB", (width, height)) + image.putdata([color(x, y) for y in range(height) for x in range(width)]) + return image + + +def pixels(image: Image.Image) -> list[Color]: + """Read the colors of an image. + + Args: + image: The image. + + Returns: + The color of each pixel, row by row. + """ + return [tuple(color) for row in np.asarray(image).tolist() for color in row] + + +def square(left: int) -> Image.Image: + """Draw a black square of 4 pixels on a white image of 10. + + Args: + left: The first column of the square. + + Returns: + The image. + """ + return fixture( + 10, + 10, + lambda x, y: BLACK if left <= x < left + 4 and 2 <= y < 6 else WHITE, + ) + + +def numbers(diff: ImageDiff) -> tuple[int, int, int, int]: + """Get the counts of a diff. + + Args: + diff: The diff. + + Returns: + The width, the height, the differing and the anti-aliased pixels. + """ + return (diff.width, diff.height, diff.differing, diff.antialiased) + + +def test_equal_images_do_not_differ(): + diff = diff_images(square(2), square(2), threshold=0) + assert numbers(diff) == (10, 10, 0, 0) + assert diff.ratio == 0 + # The reference, faded, and no mark. + assert pixels(diff.image) == [ + FADED_BLACK if 2 <= x < 6 and 2 <= y < 6 else WHITE + for y in range(10) + for x in range(10) + ] + + +def test_moved_shape_differs_where_it_left_and_where_it_arrived(): + diff = diff_images(square(2), square(3)) + assert numbers(diff) == (10, 10, 8, 0) + assert diff.ratio == pytest.approx(0.08) + assert pixels(diff.image) == [ + DIFFERENT + if x in (2, 6) and 2 <= y < 6 + else FADED_BLACK + if 2 <= x < 6 and 2 <= y < 6 + else WHITE + for y in range(10) + for x in range(10) + ] + + +def test_antialiased_edge_is_set_aside(): + hard = fixture(7, 7, lambda x, y: BLACK if x < 3 else WHITE) + soft = fixture(7, 7, lambda x, y: BLACK if x < 3 else GRAY if x == 3 else WHITE) + diff = diff_images(hard, soft) + assert numbers(diff) == (7, 7, 0, 7) + assert pixels(diff.image) == [ + FADED_BLACK if x < 3 else ANTIALIASED if x == 3 else WHITE + for y in range(7) + for x in range(7) + ] + # The same pixels count when anti-aliasing is not ignored. + assert numbers(diff_images(hard, soft, include_antialiasing=True)) == (7, 7, 7, 0) + + +def test_threshold_is_the_color_distance_that_counts(): + gray = Image.new("RGB", (4, 4), (100, 100, 100)) + near = Image.new("RGB", (4, 4), (102, 102, 102)) + far = Image.new("RGB", (4, 4), (103, 103, 103)) + assert numbers(diff_images(gray, near, threshold=0)) == (4, 4, 16, 0) + assert numbers(diff_images(gray, near, threshold=0.01)) == (4, 4, 0, 0) + assert numbers(diff_images(gray, far, threshold=0.01)) == (4, 4, 16, 0) + + +def test_images_of_different_sizes_differ_where_only_one_reaches(): + diff = diff_images(Image.new("RGB", (4, 4), WHITE), Image.new("RGB", (6, 5), WHITE)) + assert numbers(diff) == (6, 5, 14, 0) + assert pixels(diff.image) == [ + WHITE if x < 4 and y < 4 else DIFFERENT for y in range(5) for x in range(6) + ] diff --git a/tests/units/reflex_components_ui/parity/test_look.py b/tests/units/reflex_components_ui/parity/test_look.py new file mode 100644 index 00000000000..14d8c2b9f5d --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_look.py @@ -0,0 +1,207 @@ +"""Tests for the comparison of a matrix that need no browser.""" + +from pathlib import Path + +import pytest +from ui_parity.allowlist import Allowlist, LookEntry +from ui_parity.look import ( + CellResult, + MatrixResult, + StyleDifference, + _crop, + _Excuses, + _style_differences, + split_a11y, +) +from ui_parity.matrix import Matrix + + +def test_split_a11y_gives_each_frame_its_tree(): + snapshot = ( + "- main:\n" + ' - group "reference:base":\n' + ' - button "Save"\n' + ' - group "candidate:base":\n' + ' - button "Save":\n' + " - img\n" + ' - group "reference:size-1"\n' + ' - group "candidate:size-1": text\n' + " - paragraph: between\n" + " - text: not of a frame\n" + ' - group "candidate:base@x":\n' + " - text: after\n" + "- contentinfo" + ) + assert split_a11y(snapshot) == { + ("reference", "base"): '- button "Save"', + ("candidate", "base"): '- button "Save":\n - img', + ("reference", "size-1"): "", + ("candidate", "size-1"): "text", + ("candidate", "base@x"): "- text: after", + } + + +def frame(stage: list[float], target: list[float]) -> dict: + """Describe a frame as the page reports it. + + Args: + stage: The left, top, width and height of the frame. + target: The same of its element. + + Returns: + The frame. + """ + return {"stage": stage, "target": target} + + +def test_crop_is_the_union_of_both_elements_and_a_margin_within_the_frame(): + matrix = Matrix(component="button", stage=(240, 120), margin=8) + reference = frame([8, 8, 240, 120], [24, 24, 80.5, 32]) + candidate = frame([256, 8, 240, 120], [272, 24, 84, 30.25]) + # Each element starts 16 pixels into its frame; the wider and the taller + # one set the far edges, rounded out to whole pixels. + assert _crop(matrix, reference, candidate) == (8, 8, 108, 56) + # An element that fills its frame is cropped by the frame. + full = frame([8, 8, 240, 120], [8, 8, 240, 120]) + assert _crop(matrix, full, full) == (0, 0, 240, 120) + whole = Matrix(component="tooltip", stage=(300, 200), crop="stage") + assert _crop(whole, reference, candidate) == (0, 0, 300, 200) + + +def test_style_differences_name_the_part_and_both_values(): + reference = { + "": {"color": "rgb(0, 0, 0)", "height": "32px"}, + "thumb": {"width": "16px"}, + "arrow": {"width": "8px"}, + } + candidate = { + "": {"color": "rgb(0, 0, 0)", "height": "30px"}, + "thumb": {"width": "14px"}, + } + assert _style_differences(reference, candidate) == [ + StyleDifference("", "height", "32px", "30px"), + StyleDifference("arrow", "(element)", "present", None), + StyleDifference("thumb", "width", "16px", "14px"), + ] + assert _style_differences(reference, reference) == [] + + +def result(cell: str, differing: int, **differences) -> CellResult: + """Build the result of a cell of 100 by 50 pixels. + + Args: + cell: The id of the cell. + differing: The pixels that differ. + differences: The other fields of the result. + + Returns: + The result. + """ + fields = { + "styles": [], + "a11y": None, + "allowed": [], + "images": { + kind: f"chromium/button/{cell}.{kind}.png" + for kind in ("reference", "candidate", "diff") + }, + **differences, + } + return CellResult( + cell=cell, + width=100, + height=50, + differing=differing, + antialiased=0, + tolerance=0.005, + **fields, + ) + + +def test_problems_say_which_check_failed_and_by_how_much(): + assert result("base", 25).problems == [] + assert result("base", 26).ratio == pytest.approx(0.0052) + assert result("base", 26).problems == [ + "26 of 5000 pixels differ (0.52%, 0.50% allowed)" + ] + assert result("base", 26, pixels_allowed=True).problems == [] + assert result( + "base", + 0, + styles=[ + StyleDifference("", "height", "32px", "30px"), + StyleDifference("thumb", "width", "16px", None), + ], + a11y=('- button "Save"', "- text: Save"), + ).problems == [ + "height: rx '32px', rx.ui '30px'", + "thumb width: rx '16px', rx.ui None", + "accessibility tree: rx '- button \"Save\"', rx.ui '- text: Save'", + ] + + +def test_failures_name_the_cell_and_where_its_images_are(): + stale = LookEntry( + component="button", + check="pixels", + cells="*@hover", + properties=(), + engines=(), + reason="The hover is lighter.", + ) + matrix = MatrixResult( + component="button", + engine="chromium", + cells=[ + result("base", 0), + result( + "size-1@hover", + 400, + styles=[StyleDifference("", "height", "32px", "30px")], + ), + ], + seconds=1.5, + passes=1, + stale=[stale], + ) + assert matrix.failures(Path("/report")) == [ + ( + "button [chromium] cell size-1@hover:\n" + " - 400 of 5000 pixels differ (8.00%, 0.50% allowed)\n" + " - height: rx '32px', rx.ui '30px'\n" + " images: /report/chromium/button/size-1@hover.{reference,candidate,diff}.png" + ), + ( + "button [chromium]: nothing differs as the allowlist.toml entry says " + "(pixels, cells '*@hover': \"The hover is lighter.\"). Remove the entry." + ), + ] + + +def test_excuses_match_by_check_cell_and_property_and_report_the_unused(): + def entry(check: str, **fields) -> LookEntry: + return LookEntry(**{ + "component": "select", + "check": check, + "cells": "*", + "properties": (), + "engines": (), + "reason": check, + **fields, + }) + + position = entry("style", properties=("top",), reason="position") + arrow = entry("pixels", cells="*@open", reason="arrow") + webkit = entry("a11y", engines=("webkit",), reason="webkit") + other = entry("pixels", component="tooltip", reason="other") + unused = entry("a11y", reason="unused") + excuses = _Excuses( + Allowlist(look=(position, arrow, webkit, other, unused)), "select", "chromium" + ) + assert excuses.entries == [position, arrow, unused] + assert excuses.reasons("style", "base", "top") == ["position"] + assert excuses.reasons("style", "base", "left") == [] + assert excuses.reasons("pixels", "base") == [] + assert excuses.stale() == [arrow, unused] + assert excuses.reasons("pixels", "base@open") == ["arrow"] + assert excuses.stale() == [unused] diff --git a/tests/units/reflex_components_ui/parity/test_matrix.py b/tests/units/reflex_components_ui/parity/test_matrix.py new file mode 100644 index 00000000000..62eee7c46fd --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_matrix.py @@ -0,0 +1,95 @@ +"""Tests for the matrix declaration of the parity harness.""" + +from types import SimpleNamespace + +from ui_parity.matrix import Cell, Matrix, label + + +def test_label_names_a_value_in_a_cell_id(): + assert [label(value) for value in ("solid", True, 3, "Focus Visible!")] == [ + "solid", + "true", + "3", + "focus-visible", + ] + + +def test_cells_cross_some_dimensions_and_sweep_the_rest(): + matrix = Matrix( + component="button", + base={"variant": "solid", "size": "2", "children": "Save"}, + cross={"variant": ["solid", "soft"], "size": ["1", "2"]}, + sweep={ + "color_scheme": ["tomato", "indigo"], + "size": {"responsive": {"initial": "1", "md": "3"}}, + "appearance": ["dark"], + "state": ["hover"], + "viewport": [520], + }, + groups=[{"variant": ["soft"], "state": ["hover", "active"]}], + ) + cells = matrix.cells() + assert [cell.id for cell in cells] == [ + "base", + "size-1", + "size-1_variant-soft", + "variant-soft", + "color-scheme-tomato", + "color-scheme-indigo", + "size-responsive", + "base@dark", + "base@hover", + "base@520", + "variant-soft@hover", + "variant-soft@active", + ] + assert cells[2] == Cell( + props_id="size-1_variant-soft", + props={"variant": "soft", "size": "1", "children": "Save"}, + appearance="light", + state="rest", + viewport=1280, + ) + assert cells[6].props == { + "variant": "solid", + "size": {"initial": "1", "md": "3"}, + "children": "Save", + } + assert cells[-1] == Cell( + props_id="variant-soft", + props={"variant": "soft", "size": "2", "children": "Save"}, + appearance="light", + state="active", + viewport=1280, + ) + # A page renders an element once, however many environments read it. + assert list(matrix.rendered()) == [ + "base", + "size-1", + "size-1_variant-soft", + "variant-soft", + "color-scheme-tomato", + "color-scheme-indigo", + "size-responsive", + ] + assert matrix.rendered()["variant-soft"] == { + "variant": "soft", + "size": "2", + "children": "Save", + } + + +def test_create_calls_the_component_of_the_namespace_unless_told_how(): + namespace = SimpleNamespace(button=lambda **props: ("button", props)) + assert Matrix(component="button").create(namespace, {"size": "1"}) == ( + "button", + {"size": "1"}, + ) + rendered = Matrix( + component="button", + render=lambda namespace, props: namespace.button(text="Save", **props), + ) + assert rendered.create(namespace, {"size": "1"}) == ( + "button", + {"text": "Save", "size": "1"}, + ) diff --git a/tests/units/reflex_components_ui/parity/test_report.py b/tests/units/reflex_components_ui/parity/test_report.py new file mode 100644 index 00000000000..d6de0487e87 --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_report.py @@ -0,0 +1,145 @@ +"""Tests for the report of a parity run.""" + +import json +from pathlib import Path + +from ui_parity import report +from ui_parity.look import CellResult, MatrixResult, StyleDifference + + +def matrix(component: str, engine: str, differing: int) -> MatrixResult: + """Build the result of a matrix of one cell. + + Args: + component: The component. + engine: The browser engine. + differing: The pixels of the cell that differ. + + Returns: + The result. + """ + return MatrixResult( + component=component, + engine=engine, + cells=[ + CellResult( + cell="size-1@hover", + width=100, + height=50, + differing=differing, + antialiased=3, + tolerance=0.005, + styles=[StyleDifference("", "height", "32px", "30px")] + if differing + else [], + a11y=None, + allowed=["Tooltips have arrow."], + images={ + kind: f"{engine}/{component}/size-1@hover.{kind}.png" + for kind in ("reference", "candidate", "diff") + }, + ) + ], + seconds=1.5, + passes=1, + stale=[], + ) + + +ENTRY = { + "component": "button", + "engine": "chromium", + "seconds": 1.5, + "passes": 1, + "stale": [], + "cells": [ + { + "cell": "size-1@hover", + "width": 100, + "height": 50, + "differing": 400, + "antialiased": 3, + "ratio": 0.08, + "tolerance": 0.005, + "styles": [ + { + "part": "", + "property": "height", + "reference": "32px", + "candidate": "30px", + } + ], + "a11y": None, + "allowed": ["Tooltips have arrow."], + "problems": [ + "400 of 5000 pixels differ (8.00%, 0.50% allowed)", + "height: rx '32px', rx.ui '30px'", + ], + "images": { + "reference": "chromium/button/size-1@hover.reference.png", + "candidate": "chromium/button/size-1@hover.candidate.png", + "diff": "chromium/button/size-1@hover.diff.png", + }, + } + ], +} + + +def image(kind: str) -> str: + """Get the table cell the report shows an image of the entry in. + + Args: + kind: Which image: the reference, the candidate or the diff. + + Returns: + The HTML of the cell. + """ + path = f"chromium/button/size-1@hover.{kind}.png" + return ( + f'{kind}' + ) + + +PAGE = ( + '' + f"rx.ui parity" + "

rx.ui parity with Radix Themes

" + "

1 matrices, 1 cells, 1 failing, 1.5 s

" + '" + '

button · chromium

' + "

1 cells, 1 failing, 1 page loads, 1.5 s

" + "" + "" + '' + '' + f"{image('reference')}{image('candidate')}{image('diff')}" + "" + "
cellpixelsrx (Radix)rx.uidiffdifferences
size-1@hover400 / 5000
8.00%
3 anti-aliased
400 of 5000 pixels differ (8.00%, 0.50% allowed)\n"
+    "height: rx '32px', rx.ui '30px'\n"
+    "allowed: Tooltips have <no> arrow.
" +) + + +def test_entry_keeps_the_numbers_of_every_cell(): + assert report.entry(matrix("button", "chromium", 400)) == ENTRY + + +def test_render_shows_each_cell_with_its_images_and_differences(): + assert report.render([ENTRY]) == PAGE + + +def test_write_adds_a_matrix_and_replaces_its_earlier_run(tmp_path: Path): + index = report.write(tmp_path, matrix("button", "webkit", 0)) + assert index == tmp_path / "index.html" + report.write(tmp_path, matrix("button", "chromium", 0)) + report.write(tmp_path, matrix("box", "webkit", 0)) + report.write(tmp_path, matrix("button", "chromium", 400)) + results = json.loads((tmp_path / "results.json").read_text()) + assert [(entry["component"], entry["engine"]) for entry in results] == [ + ("box", "webkit"), + ("button", "chromium"), + ("button", "webkit"), + ] + assert results[1] == ENTRY + assert index.read_text(encoding="utf-8") == report.render(results) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py new file mode 100644 index 00000000000..d534e574b42 --- /dev/null +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -0,0 +1,172 @@ +"""The Python API of every rx.ui component is the Radix component's. + +``rx.button(...)`` becomes ``rx.ui.button(...)`` with the same arguments. An +intended difference is an ``[[api]]`` entry of the parity allowlist, with the +reason the migration guide gives for it. +""" + +from typing import Any, Literal + +import reflex_components_ui +from reflex_base.components.component import Component +from reflex_base.event import EventHandler, no_args_event_spec +from reflex_base.vars.base import Var +from reflex_components_ui.base import UIComponent +from reflex_components_ui.layout.box import Box +from ui_parity import allowlist +from ui_parity.allowlist import Allowlist, ApiEntry +from ui_parity.api import ( + ApiDifference, + component_class, + diff_api, + type_shape, + unexplained, +) + +import reflex as rx + +COMPONENTS = sorted(reflex_components_ui.__all__) + + +def differences(component: str) -> list[ApiDifference]: + """Compare a component of rx.ui with the one of the same name in rx. + + Args: + component: The name of the component. + + Returns: + The differences of their APIs. + """ + return diff_api( + component, + component_class(getattr(rx, component)), + component_class(getattr(reflex_components_ui, component)), + ) + + +def test_every_component_has_the_api_of_its_radix_counterpart(): + found = [item for name in COMPONENTS for item in differences(name)] + unlisted, stale = unexplained(found, allowlist.load()) + assert unlisted == [], ( + "rx.ui differs from rx: match the Radix component, or list the " + "difference under [[api]] in allowlist.toml with its reason." + ) + assert stale == [], "These [[api]] names are differences no more: remove them." + + +def wrapper(without: str | None = None) -> type[Component]: + """Fork the Radix box as a wave does: a wrapper with the same props. + + Args: + without: A prop to leave out of the wrapper. + + Returns: + The wrapper. + """ + reference = component_class(rx.box) + fields = reference.get_fields() + return type( + "Box", + (UIComponent,), + { + "__annotations__": { + name: fields[name].annotated_type + for name in reference.get_props() + if name != without + }, + "__module__": __name__, + }, + ) + + +def test_box_wrapper_with_every_prop_has_no_difference(): + assert diff_api("box", component_class(rx.box), wrapper()) == [] + + +def test_removing_a_prop_from_the_wrapper_is_a_difference(): + found = diff_api("box", component_class(rx.box), wrapper(without="title")) + assert found == [ + ApiDifference( + component="box", + kind="prop", + name="title", + reference="Var[str]", + candidate=None, + ) + ] + # The parity test fails on it: nothing lists the difference. + assert unexplained(found, Allowlist()) == (found, []) + + +def test_box_differs_only_by_the_props_the_allowlist_gives_a_reason_for(): + found = differences("box") + (entry,) = (item for item in allowlist.load().api if item.component == "box") + assert entry.kind == "prop" + assert [(item.kind, item.name, item.candidate) for item in found] == [ + ("prop", name, None) for name in entry.names + ] + + +class Reference(Component): + """A component as Radix has it.""" + + size: Var[Literal["1", "2", "3"]] + variant: Var[Literal["solid", "soft"]] + loading: Var[bool] + on_open_change: EventHandler[no_args_event_spec] + + +class Candidate(Component): + """Its fork: a size less, a renamed prop, another trigger.""" + + size: Var[Literal["2", "1"]] + variant: Var[Literal["soft", "solid"]] + busy: Var[bool] + on_toggle: EventHandler[no_args_event_spec] + + +def test_diff_api_finds_props_types_and_event_triggers(): + assert diff_api("thing", Reference, Candidate) == [ + ApiDifference("thing", "event", "on_open_change", "trigger", None), + ApiDifference("thing", "event", "on_toggle", None, "trigger"), + ApiDifference("thing", "prop", "busy", None, "Var[bool]"), + ApiDifference("thing", "prop", "loading", "Var[bool]", None), + ApiDifference( + "thing", + "type", + "size", + "Var[Literal['1', '2', '3']]", + "Var[Literal['1', '2']]", + ), + ] + + +def test_unexplained_separates_the_unlisted_from_the_stale(): + found = diff_api("thing", Reference, Candidate) + listed = ApiEntry( + component="thing", + kind="prop", + names=("busy", "loading", "color"), + reason="Renamed.", + ) + other = ApiEntry( + component="other", kind="event", names=("on_toggle",), reason="Another." + ) + assert unexplained(found, Allowlist(api=(listed, other))) == ( + [found[0], found[1], found[4]], + [(listed, "color"), (other, "on_toggle")], + ) + + +def test_type_shape_ignores_where_a_type_is_defined_and_its_order(): + responsive: Any = Var[Literal["2", "1"] | dict[str, Literal["1", "2"]]] + assert type_shape(responsive) == ( + "Var[Literal['1', '2'] | dict[str, Literal['1', '2']]]" + ) + assert type_shape(Var[int | None]) == "Var[None | int]" + assert type_shape(Box) == "Box" + + +def test_component_class_reads_a_factory_and_a_namespace(): + assert component_class(rx.ui.box) is Box + assert component_class(rx.select).__name__ == "HighLevelSelect" diff --git a/tests/units/test_ui_parity_script.py b/tests/units/test_ui_parity_script.py new file mode 100644 index 00000000000..3abece77137 --- /dev/null +++ b/tests/units/test_ui_parity_script.py @@ -0,0 +1,50 @@ +"""Tests for scripts/ui_parity.py, the one command of the rx.ui parity harness.""" + +import sys + +import pytest +from ui_parity import allowlist + +from scripts import ui_parity + +TESTS = "tests/integration/tests_playwright/test_ui_parity.py" + + +def test_pytest_command_runs_everything_in_one_engine_by_default(): + assert ui_parity.pytest_command([], ["chromium"], []) == [ + sys.executable, + "-m", + "pytest", + TESTS, + "-rs", + "--browser", + "chromium", + ] + + +def test_pytest_command_selects_components_and_engines(): + assert ui_parity.pytest_command( + ["box", "button"], ["chromium", "firefox", "webkit"], ["-x"] + ) == [ + sys.executable, + "-m", + "pytest", + TESTS, + "-rs", + "--browser", + "chromium", + "--browser", + "firefox", + "--browser", + "webkit", + "-k", + "-box] or -box- or -button] or -button- or test_run_time", + "-x", + ] + + +def test_differences_prints_the_allowlist(capsys: pytest.CaptureFixture[str]): + assert ui_parity.main(["differences"]) == 0 + assert capsys.readouterr().out == ( + allowlist.differences_markdown(allowlist.load()) + "\n" + ) From bc1f0831578478ff95244c4ec569ee355fe4b7cd Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:26:56 +0000 Subject: [PATCH 17/26] Carry the class of an appearance on a boxless element, and sweep the tokens live Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- .../src/reflex_components_ui/layout/theme.py | 50 +- .../src/reflex_components_ui/plugin.py | 17 +- .../src/reflex_components_ui/styles/theme.py | 9 +- .../src/reflex_components_ui/themes.py | 76 ++- .../tests_playwright/test_ui_components.py | 553 +++++++++++++++++- 5 files changed, 642 insertions(+), 63 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py index 2181856a65a..6c64095b25c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py @@ -21,7 +21,7 @@ ) from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style.emit import props_call -from reflex_components_ui.styles.theme import APP_THEME +from reflex_components_ui.styles.theme import APP_THEME, APPEARANCE from reflex_components_ui.themes import ( OPTIONS, LiteralAccentColor, @@ -33,10 +33,36 @@ ThemeError, ThemeStyles, app_theme_styles, + literal_option, theme_styles, ) +class Appearance(UIComponent): + """What carries the class of an appearance around a theme element. + + Radix Themes and Tailwind select on the classes ``light`` and ``dark``, so + their components inside a theme follow its appearance through them. The + class cannot be on the theme element: the stylesheet of Radix Themes sets + its plain gray scale on an element with either class, over the gray of the + theme. This element has no box, so the theme element is laid out as a + child of what is around both. + """ + + tag = "div" + + styles: ClassVar[ComponentStyles] = APPEARANCE + + @classmethod + def _display_name(cls) -> str: + """Get the name an app refers to the component by. + + Returns: + ``rx.ui.theme``, which is what an app wrote. + """ + return "rx.ui.theme" + + # The fields of the element that are options of its theme. _OPTIONS = (*OPTIONS, "has_background") @@ -93,6 +119,28 @@ class ThemeElement(UIComponent): doc="Whether the element paints the background of the theme. Defaults to True when it sets an appearance.", ) + @classmethod + def create(cls, *children, **props) -> Component: + """Create a theme around the children. + + Args: + *children: The children of the theme. + **props: The options of the theme and the props of its element. + + Returns: + The theme element, inside the element that carries the class of + its appearance when it has one of its own. + """ + element = super().create(*children, **props) + appearance = literal_option(element.appearance) + if appearance is None or ( + appearance.__class__ is str and appearance == "inherit" + ): + return element + # Bound to state, the class is `inherit` when the appearance is: no + # stylesheet selects on it. + return Appearance.create(element, class_name=appearance) + @classmethod def _display_name(cls) -> str: """Get the name an app refers to the component by. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/plugin.py b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py index 9a8ad1fa0b5..8fe898aeebb 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/plugin.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py @@ -26,6 +26,10 @@ # a page with components of both follows this one. APP_THEME_WRAP = (15, "ReflexUITheme") +# The element around it that carries the class of the appearance of the theme, +# when it has one of its own. +APP_APPEARANCE_WRAP = (16, "ReflexUIAppearance") + # The cascade layer the styles of the components are compiled into. CSS_LAYER = "reflex-ui" @@ -129,13 +133,18 @@ def pre_compile(self, **context) -> None: ) def compile_page(self, page_ctx: PageContext, /, **kwargs: Any) -> None: - """Wrap the app in the element that carries its theme. + """Wrap the app in the elements that carry its theme. Args: page_ctx: The page being compiled. **kwargs: The context for the plugin. """ # The component imports this module for the plugin it needs. - from reflex_components_ui.layout.theme import AppTheme - - page_ctx.app_wrap_components[APP_THEME_WRAP] = AppTheme.create() + from reflex_components_ui.layout.theme import Appearance, AppTheme + + wraps = page_ctx.app_wrap_components + wraps[APP_THEME_WRAP] = AppTheme.create() + if self.theme.appearance != "inherit": + wraps[APP_APPEARANCE_WRAP] = Appearance.create( + class_name=self.theme.appearance + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py index ecf23e1d85b..1af8f8cc0a9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py @@ -1,4 +1,4 @@ -"""The look of the element that carries the theme of an app.""" +"""The look of the elements of a theme, beside what the theme itself sets.""" from reflex_components_ui.base import ComponentStyles @@ -14,3 +14,10 @@ }, }, } + +# The element that carries the class of an appearance has no box of its own. +APPEARANCE: ComponentStyles = { + "base": { + "display": "contents", + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/themes.py b/packages/reflex-components-ui/src/reflex_components_ui/themes.py index 7afe73349df..f4bc6be8fe2 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/themes.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/themes.py @@ -309,7 +309,7 @@ def finish(self, class_name: str | None = None) -> ThemeStyles: ) -def _literal(value: Any) -> Any: +def literal_option(value: Any) -> Any: """Read a Var that holds a constant as the constant. Args: @@ -342,12 +342,13 @@ def theme_styles( imports every theme it could name and chooses among them where the page runs. - The cascade does not tell an element what it inherits, so two things are - resolved against the theme of the app, which is what a theme inherits - unless another one stands between them: + An accent color without a gray color keeps the gray around the element, + as in Radix Themes. The cascade does not tell an element what it inherits, + so two things are resolved against the theme of the app, which is what a + theme inherits unless another one stands between them: - - An accent color without a gray color takes the gray that matches it when - the gray of the app is ``"auto"``, as ``gray_color="auto"`` does. + - ``gray_color="auto"`` without an accent color is the gray that matches + the accent of the app. - A gray color without an accent color names the gray accent again when the accent of the app is gray: that accent is the gray of the element it was declared on. @@ -372,19 +373,16 @@ def theme_styles( """ tokens = _radix_tokens builder = _Builder(name) - accent_color = _literal(accent_color) - gray_color = _literal(gray_color) - appearance = _literal(appearance) - has_background = _literal(has_background) + accent_color = literal_option(accent_color) + gray_color = literal_option(gray_color) + appearance = literal_option(appearance) + has_background = literal_option(has_background) for scope in tokens.SCOPE_THEMES: builder.refs.append(builder.add(scope)) builder.refs.append(builder.add(tokens.FOCUS_THEME)) - if gray_color is None: - if accent_color is not None and app_theme and app_theme.gray_color == "auto": - gray_color = "auto" - elif not isinstance(gray_color, Var): + if gray_color is not None and not isinstance(gray_color, Var): _check(name, "gray_color", gray_color) if accent_color is None: if gray_color is not None and app_theme and app_theme.accent_color == "gray": @@ -430,40 +428,32 @@ def theme_styles( module, export, _ = tokens.THEME_STYLES styles = builder.add((module, export), _THEME_STYLES) builder.refs.append(f"{styles}.root") - class_name = THEME_CLASS - explicit = False - bound_appearance = None + background = f"{styles}.background" if isinstance(appearance, Var): - bound_appearance = builder.bound(appearance) - elif appearance is not None: - _check(name, "appearance", appearance) - if appearance != "inherit": - # Radix Themes and Tailwind select on the class: a component of - # either inside this element follows the appearance too. - class_name = f"{THEME_CLASS} {appearance}" - explicit = True + bound = builder.bound(appearance) + own_appearance = f'({bound}) !== "inherit"' + appearance_ref = f"{styles}[{bound}]" + else: + if appearance is not None: + _check(name, "appearance", appearance) + own_appearance = appearance is not None and appearance != "inherit" + appearance_ref = f"{styles}.{appearance}" if own_appearance else None if isinstance(has_background, Var): - builder.refs.append(f"({builder.bound(has_background)}) && {styles}.background") + builder.refs.append(f"({builder.bound(has_background)}) && {background}") elif has_background is None: - if bound_appearance is not None: - builder.refs.append( - f'({bound_appearance}) !== "inherit" && {styles}.background' - ) - elif explicit: - builder.refs.append(f"{styles}.background") + # As in Radix Themes, a theme with an appearance of its own paints its + # background unless it is told not to. + if own_appearance.__class__ is str: + builder.refs.append(f"{own_appearance} && {background}") + elif own_appearance: + builder.refs.append(background) else: _check_flag(name, "has_background", has_background) if has_background: - builder.refs.append(f"{styles}.background") - if bound_appearance is not None: - builder.refs.extend(( - f"{styles}[{bound_appearance}]", - f'({bound_appearance}) !== "inherit" && ' - f"{{ $$css: true, appearance: {bound_appearance} }}", - )) - elif explicit: - builder.refs.append(f"{styles}.{appearance}") - return builder.finish(class_name) + builder.refs.append(background) + if appearance_ref is not None: + builder.refs.append(appearance_ref) + return builder.finish(THEME_CLASS) def app_theme_styles(theme: Theme) -> ThemeStyles: @@ -496,7 +486,7 @@ def color_scheme_styles(name: str, color_scheme: Any) -> ThemeStyles: """ tokens = _radix_tokens builder = _Builder(name) - color_scheme = _literal(color_scheme) + color_scheme = literal_option(color_scheme) if isinstance(color_scheme, Var): builder.refs.append( builder.lookup(_ACCENT_MAP, tokens.ACCENT_THEMES, color_scheme) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index dd8fb820918..a566a018c74 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -1,17 +1,25 @@ """The rx.ui components in a real app, in dev and prod. One app is shared by every test of the components: add a page or an element to -``UIComponentsApp`` rather than a new app. +``UIComponentsApp`` rather than a new app. It is built twice, on its own and +beside Radix Themes: the stylesheet of Radix Themes is unlayered and defines +every color scale on the root element, so only the app without it shows what +the rx.ui stylesheet does alone. """ +import functools import hashlib +import json import re import shutil from collections.abc import Generator from pathlib import Path +from typing import Any import pytest -from playwright.sync_api import Browser, Page, expect +from playwright.sync_api import Browser, Page, Route, expect +from reflex_components_ui import _radix_tokens +from reflex_components_ui.constants import JS_SRC from reflex.testing import AppHarness, AppHarnessProd, chdir from reflex.utils import build @@ -35,12 +43,32 @@ CHANGED_STYLE = '"padding": "7px"' -def UIComponentsApp(): - """An app with a page for each thing the rx.ui tests look at.""" +# The colors the theme pages are read through, as Radix Themes defines them. +INDIGO_11 = {"light": "rgb(58, 91, 199)", "dark": "rgb(158, 177, 255)"} +RED_11 = {"light": "rgb(206, 44, 49)", "dark": "rgb(255, 149, 146)"} +SLATE_2 = {"light": "rgb(249, 249, 251)", "dark": "rgb(24, 25, 27)"} + +# The scripts of the token sweep of the javascript package, which read every +# custom property through a property of its type and hold the exceptions. +SWEEP_HARNESS = JS_SRC.parent / "tests" / "harness" +SWEEP_SCRIPTS = "/__reflex_ui_sweep__/" + + +def UIComponentsApp(radix: bool = False): + """An app with a page for each thing the rx.ui tests look at. + + Args: + radix: Whether the app also has Radix Themes and its components. + """ + import json from pathlib import Path + from reflex_components_ui import _radix_tokens + import reflex as rx + tokens = rx.ui.tokens + def index(): return rx.el.main( rx.ui.box("plain", id="plain"), @@ -59,6 +87,118 @@ def index(): def literal(): return rx.ui.box("literal", id="literal", style={"padding": "6px"}) + def probe(name: str): + # Each style reads a token through a property that takes its value. + return rx.ui.box( + name, + id=name, + style={ + "color": tokens.accent[11], + "background_color": tokens.gray[2], + "border_top_left_radius": tokens.radius[3], + "padding_top": tokens.space[4], + "font_size": tokens.font_size[2], + }, + ) + + def theme(): + return rx.el.main( + probe("root-probe"), + rx.ui.theme( + probe("nested-probe"), + rx.el.div( + probe("popover-probe"), + id="popover", + custom_attrs={"popover": "auto"}, + ), + accent_color="red", + radius="full", + scaling="110%", + appearance="dark", + id="nested", + ), + probe("after-probe"), + rx.el.button("toggle", id="toggle", on_click=rx.toggle_color_mode), + ) + + # The themes the sweep compares with Radix Themes: every accent with the + # gray that matches it and every gray, in both appearances, then every + # radius, scaling and panel background. Each sets every option, as a + # nested theme of Radix Themes inherits from the Radix theme of the app + # and one of rx.ui from the rx.ui one. A gray is given an appearance + # because Radix Themes has no rule for the plain gray: without the class + # of an appearance, its nested theme keeps the gray around it. + defaults = { + "accent_color": "indigo", + "gray_color": "auto", + "radius": "medium", + "scaling": "100%", + "panel_background": "translucent", + } + variations = [ + {"accent_color": accent, "appearance": appearance} + for accent in _radix_tokens.ACCENT_THEMES + for appearance in ("light", "dark") + ] + variations += [ + {"gray_color": gray, "appearance": appearance} + for gray in _radix_tokens.GRAY_THEMES + for appearance in ("light", "dark") + ] + variations += [{"radius": radius} for radius in _radix_tokens.RADIUS_THEMES] + variations += [{"scaling": scaling} for scaling in _radix_tokens.SCALING_THEMES] + variations += [ + {"panel_background": panel} for panel in _radix_tokens.PANEL_BACKGROUND_THEMES + ] + configs = [{**defaults, **variation} for variation in variations] + + def sweep(): + themes = [] + for index, config in enumerate(configs): + label = {"data-sweep": json.dumps(config)} + themes.append(rx.ui.theme(id=f"ui-{index}", custom_attrs=label, **config)) + if radix: + # Reflex keeps the appearance of an `rx.theme` for the color + # mode of the app. Radix Themes selects on the class, and gives + # a theme with an appearance its background. + options = {k: v for k, v in config.items() if k != "appearance"} + if "appearance" in config: + options.update(class_name=config["appearance"], has_background=True) + themes.append( + rx.theme(id=f"radix-{index}", custom_attrs=label, **options) + ) + return rx.el.main(*themes) + + def buttons(): + return rx.fragment( + rx.button("accent"), + rx.button("green", color_scheme="green", variant="soft"), + ) + + def mixed(): + return rx.el.main( + rx.button("radix", id="radix-button"), + probe("ui-box"), + # Beside Radix Themes a theme with an appearance names its gray: + # the Radix stylesheet sets the plain gray wherever the class of + # an appearance is. + rx.ui.theme( + buttons(), + accent_color="red", + gray_color="slate", + appearance="dark", + id="ui-dark", + ), + rx.theme( + buttons(), + accent_color="red", + gray_color="slate", + class_name="dark", + has_background=True, + id="radix-dark", + ), + ) + assets = Path.cwd() / "assets" assets.mkdir(exist_ok=True) (assets / "unlayered.css").write_text(".unlayered { padding: 2px }") @@ -66,34 +206,78 @@ def literal(): app = rx.App(stylesheets=["unlayered.css"], enable_state=False) app.add_page(index) app.add_page(literal, route="/literal") + app.add_page(theme, route="/theme") + app.add_page(sweep, route="/sweep") + if radix: + app.add_page(mixed, route="/mixed") config = rx.config.get_config() - config.plugins = [rx.plugins.UIPlugin(), rx.plugins.TailwindV4Plugin()] + config.plugins = [ + rx.plugins.UIPlugin(theme=rx.ui.Theme(accent_color="indigo", radius="large")), + rx.plugins.TailwindV4Plugin(), + ] + if radix: + # Its own theme is blue: the theme of rx.ui is the one a page follows. + config.plugins.append(rx.plugins.RadixThemesPlugin()) -@pytest.fixture(scope="module") -def ui_app( - app_harness_env: type[AppHarness], tmp_path_factory: pytest.TempPathFactory +def _run( + app_harness_env: type[AppHarness], + tmp_path_factory: pytest.TempPathFactory, + radix: bool, ) -> Generator[AppHarness, None, None]: """Run the shared app in dev or prod. Args: app_harness_env: AppHarness (dev) or AppHarnessProd (prod). tmp_path_factory: pytest fixture for creating temporary directories. + radix: Whether the app also has Radix Themes. Yields: The running harness. """ - name = f"ui_components_{app_harness_env.__name__.lower()}" + name = f"ui_{'mixed' if radix else 'components'}_{app_harness_env.__name__.lower()}" with app_harness_env.create( root=tmp_path_factory.mktemp(name), app_name=name, - app_source=UIComponentsApp, + app_source=functools.partial(UIComponentsApp, radix=radix), ) as harness: assert harness.app_instance is not None, "app is not running" yield harness +@pytest.fixture(scope="module") +def ui_app( + app_harness_env: type[AppHarness], tmp_path_factory: pytest.TempPathFactory +) -> Generator[AppHarness, None, None]: + """Run the shared app in dev or prod. + + Args: + app_harness_env: AppHarness (dev) or AppHarnessProd (prod). + tmp_path_factory: pytest fixture for creating temporary directories. + + Yields: + The running harness. + """ + yield from _run(app_harness_env, tmp_path_factory, radix=False) + + +@pytest.fixture(scope="module") +def mixed_app( + app_harness_env: type[AppHarness], tmp_path_factory: pytest.TempPathFactory +) -> Generator[AppHarness, None, None]: + """Run the shared app beside Radix Themes, in dev or prod. + + Args: + app_harness_env: AppHarness (dev) or AppHarnessProd (prod). + tmp_path_factory: pytest fixture for creating temporary directories. + + Yields: + The running harness. + """ + yield from _run(app_harness_env, tmp_path_factory, radix=True) + + @pytest.fixture def prod_app(ui_app: AppHarness) -> AppHarness: """Skip a test of the production build when the app runs in dev. @@ -202,10 +386,8 @@ def test_literal_page_folds_to_class_names(prod_app: AppHarness, page: Page): assert re.findall(r"className:`([^`]*)`", scripts[literal_chunks[0]]) == [ class_name ] - # No script holds a call into StyleX or a style object it reads at runtime. - assert [ - name for name, code in scripts.items() if re.search(r"stylex|\$\$css", code) - ] == [] + # The chunk holds no call into StyleX and no style object read at runtime. + assert re.findall(r"stylex|\$\$css", scripts[literal_chunks[0]]) == [] def _digests(files: dict[str, bytes]) -> dict[str, str]: @@ -285,3 +467,346 @@ def named(digests: dict[str, str]) -> dict[str, str]: ] # The same styles build the same files: a name is a function of content. assert restored == before + + +# What each probe of the theme page reads, and through which token. +PROBE_PROPERTIES = ( + "color", + "background-color", + "border-top-left-radius", + "padding-top", + "font-size", +) + +# The probes under the theme of the app, indigo and large, in each color mode. +APP_PROBE = { + mode: { + "color": INDIGO_11[mode], + "background-color": SLATE_2[mode], + "border-top-left-radius": "9px", + "padding-top": "16px", + "font-size": "14px", + } + for mode in ("light", "dark") +} + +# The probes under the nested theme: red, full, 110% and always dark. +NESTED_PROBE = { + "color": RED_11["dark"], + # The gray is the one around the theme, as an accent does not set it. + "background-color": SLATE_2["dark"], + "border-top-left-radius": "9.9px", + "padding-top": "17.6px", + "font-size": "15.4px", +} + + +def _probes(page: Page) -> dict[str, dict[str, str]]: + """Read the probes of the theme page. + + Args: + page: A page showing the theme page of the app. + + Returns: + The properties in PROBE_PROPERTIES as the browser computed them, by + probe id. + """ + return page.evaluate( + """(properties) => Object.fromEntries( + [...document.querySelectorAll('[id$="-probe"]')].map((probe) => { + const style = getComputedStyle(probe); + return [ + probe.id, + Object.fromEntries( + properties.map((name) => [name, style.getPropertyValue(name)]), + ), + ]; + }), + )""", + list(PROBE_PROPERTIES), + ) + + +def _goto_theme_page(harness: AppHarness, page: Page) -> None: + """Show the theme page, styled. + + Args: + harness: The running harness. + page: The page to navigate. + """ + assert harness.frontend_url is not None + page.goto(harness.frontend_url.rstrip("/") + "/theme/") + # In dev the styles of a page arrive once its module was compiled. + expect(page.locator("#nested-probe")).to_have_css("font-size", "15.4px") + + +def test_nested_theme_overrides_its_subtree_only(ui_app: AppHarness, page: Page): + """The theme of the plugin is around the page, and a nested one inside it.""" + _goto_theme_page(ui_app, page) + page.locator("#popover").evaluate("(popover) => popover.showPopover()") + assert _probes(page) == { + "root-probe": APP_PROBE["light"], + "nested-probe": NESTED_PROBE, + # The browser renders a popover in the top layer, outside the theme + # element: it inherits from where it is declared all the same. + "popover-probe": NESTED_PROBE, + "after-probe": APP_PROBE["light"], + } + themes = page.evaluate( + """() => [...document.querySelectorAll(".reflex-ui-theme")].map((theme) => { + const style = getComputedStyle(theme); + const parent = theme.parentElement; + return [ + theme.id, + style.colorScheme, + style.backgroundColor, + style.minHeight, + parent.classList.contains("dark"), + getComputedStyle(parent).display, + ]; + })""" + ) + viewport = page.viewport_size + assert viewport is not None + assert themes == [ + # The background of a light theme is white, and of a dark one its + # darkest gray: slate here. Only the theme of the app fills the page. + ["", "light", "rgb(255, 255, 255)", f"{viewport['height']}px", False, "block"], + # The class of an appearance is on an element without a box. + ["nested", "dark", "rgb(17, 17, 19)", "0px", True, "contents"], + ] + + +def test_color_mode_toggle_flips_the_palette(ui_app: AppHarness, page: Page): + """A color is one value for both modes, chosen by the class of the page.""" + _goto_theme_page(ui_app, page) + html = page.locator("html") + expect(html).to_have_class("light") + assert _probes(page)["root-probe"] == APP_PROBE["light"] + page.locator("#toggle").click() + expect(html).to_have_class("dark") + assert _probes(page) == { + "root-probe": APP_PROBE["dark"], + # A theme with an appearance of its own keeps it. + "nested-probe": NESTED_PROBE, + "popover-probe": NESTED_PROBE, + "after-probe": APP_PROBE["dark"], + } + page.locator("#toggle").click() + expect(html).to_have_class("light") + assert _probes(page)["root-probe"] == APP_PROBE["light"] + + +def test_prerendered_theme_page_is_themed_without_javascript( + prod_app: AppHarness, browser: Browser +): + """The theme is class names in the document, and needs no script.""" + assert prod_app.frontend_url is not None + context = browser.new_context(java_script_enabled=False) + try: + page = context.new_page() + page.goto(prod_app.frontend_url.rstrip("/") + "/theme/") + # Nothing has set the class of a color mode: the page is light. + assert page.locator("html").get_attribute("class") is None + assert _probes(page) == { + "root-probe": APP_PROBE["light"], + "nested-probe": NESTED_PROBE, + "popover-probe": NESTED_PROBE, + "after-probe": APP_PROBE["light"], + } + finally: + context.close() + + +# The themes of the sweep page, as the app builds them. +SWEEP_DEFAULTS = { + "accent_color": "indigo", + "gray_color": "auto", + "radius": "medium", + "scaling": "100%", + "panel_background": "translucent", +} +SWEEP_CONFIGS: list[dict[str, str]] = [ + {**SWEEP_DEFAULTS, **variation} + for variation in ( + *( + {"accent_color": accent, "appearance": appearance} + for accent in _radix_tokens.ACCENT_THEMES + for appearance in ("light", "dark") + ), + *( + {"gray_color": gray, "appearance": appearance} + for gray in _radix_tokens.GRAY_THEMES + for appearance in ("light", "dark") + ), + *({"radius": radius} for radius in _radix_tokens.RADIUS_THEMES), + *({"scaling": scaling} for scaling in _radix_tokens.SCALING_THEMES), + *( + {"panel_background": panel} + for panel in _radix_tokens.PANEL_BACKGROUND_THEMES + ), + ) +] + +# Every custom property Radix Themes defines: the modules add two of their +# own, through which a theme switches the background of its panels. +SWEEP_NAMES = [ + name + for _, names in _radix_tokens.VAR_GROUPS.values() + for name in names + if name not in ("--panel-solid", "--color-panel-if-solid") +] + +# The custom properties of the modules the sweep page does not import. +NOT_ON_THE_PAGE = ("--cursor-", "--white-") + +READ_SWEEP = """async ([scripts, names, prefix]) => { + const { labels, mount, read } = await import(scripts + "probe.js"); + const container = document.createElement("div"); + const probes = mount(container, names); + const themes = [...document.querySelectorAll(`[data-sweep][id^="${prefix}-"]`)]; + return { + labels: labels(names), + themes: themes.map((theme) => { + theme.append(container); + return [theme.id, theme.dataset.sweep, read(probes, theme)]; + }), + }; +}""" + + +def _serve_sweep_script(route: Route) -> None: + """Answer a request for a script of the token sweep with the file. + + Args: + route: The intercepted request. + """ + name = route.request.url.rsplit("/", 1)[1] + route.fulfill(path=SWEEP_HARNESS / name, content_type="text/javascript") + + +def _read_sweep(harness: AppHarness, page: Page, prefix: str) -> dict[str, Any]: + """Read every custom property under every theme of the sweep page. + + Args: + harness: The running harness. + page: The page to navigate. + prefix: What the ids of the themes to read start with: ``ui`` for the + ones of rx.ui, ``radix`` for the ones of Radix Themes. + + Returns: + The names of the values, and the id, the options and the values of + each theme. + """ + assert harness.frontend_url is not None + page.route(f"**{SWEEP_SCRIPTS}*", _serve_sweep_script) + page.goto(harness.frontend_url.rstrip("/") + "/sweep/") + # In dev the styles of a page arrive once its module was compiled. + expect(page.locator("#ui-0")).to_have_css("overflow-wrap", "break-word") + return page.evaluate(READ_SWEEP, [SWEEP_SCRIPTS, SWEEP_NAMES, prefix]) + + +def _sweep_differences( + reference: dict[str, Any], ours: dict[str, Any] +) -> list[tuple[str, str, str, str]]: + """List where two readings of the sweep page differ. + + Args: + reference: The reading under the themes of Radix Themes. + ours: A reading under the themes of rx.ui. + + Returns: + The options, the name of the value, the value under Radix Themes and + the value under rx.ui, for each difference. + """ + return [ + (config, label, expected, value) + for (_, config, expected_values), (_, _, values) in zip( + reference["themes"], ours["themes"], strict=True + ) + for label, expected, value in zip( + reference["labels"], expected_values, values, strict=True + ) + if expected != value + ] + + +def test_tokens_resolve_as_under_radix_themes( + ui_app: AppHarness, mixed_app: AppHarness, page: Page +): + """Every custom property has the value Radix Themes gives it. + + The same themes are read under ``rx.theme`` and under ``rx.ui.theme`` on + one page, and under ``rx.ui.theme`` in the app without Radix Themes. What + may differ is listed with its reason in the exceptions of the javascript + package, which the script that reads the values applies. + """ + radix = _read_sweep(mixed_app, page, "radix") + mixed = _read_sweep(mixed_app, page, "ui") + alone = _read_sweep(ui_app, page, "ui") + + configs = [json.dumps(config) for config in SWEEP_CONFIGS] + assert len(configs) == 76 + for reading, prefix in ((radix, "radix"), (mixed, "ui"), (alone, "ui")): + assert [theme[:2] for theme in reading["themes"]] == [ + [f"{prefix}-{index}", config] for index, config in enumerate(configs) + ] + assert len(radix["labels"]) == 1068 + 11 + # A value neither side defines would compare equal: Radix defines them all. + assert [ + (config, label, value) + for _, config, values in radix["themes"] + for label, value in zip(radix["labels"], values, strict=True) + if value.startswith("INVALID") + ] == [] + assert _sweep_differences(radix, mixed) == [] + # On its own, an app only has the custom properties of the modules it + # imports: nothing on the page uses a cursor or a white. + assert [ + difference + for difference in _sweep_differences(radix, alone) + if not difference[1].startswith(NOT_ON_THE_PAGE) + ] == [] + assert sorted({ + label + for _, _, values in alone["themes"] + for label, value in zip(alone["labels"], values, strict=True) + if value.startswith("INVALID") + }) == sorted(name for name in SWEEP_NAMES if name.startswith(NOT_ON_THE_PAGE)) + + +def test_radix_components_follow_the_rx_ui_theme(mixed_app: AppHarness, page: Page): + """On a page with both, a Radix button and an rx.ui box show one palette.""" + assert mixed_app.frontend_url is not None + page.goto(mixed_app.frontend_url.rstrip("/") + "/mixed/") + expect(page.locator("#ui-box")).to_have_css("color", INDIGO_11["light"]) + accents = page.evaluate( + """() => ["radix-button", "ui-box"].map((id) => + getComputedStyle(document.getElementById(id)).getPropertyValue("--accent-9"), + )""" + ) + # Indigo, the accent of the rx.ui theme, and not the blue of the Radix one. + assert accents == ["#3e63dd", "#3e63dd"] + expect(page.locator("#radix-button")).to_have_css( + "background-color", "rgb(62, 99, 221)" + ) + + # A nested rx.ui theme is to the Radix components inside it what a nested + # Radix theme is: its accent, and the dark scale of a color of their own. + def read(theme: str) -> list[list[str]]: + return page.locator(f"#{theme}").evaluate( + """(theme) => [theme, ...theme.querySelectorAll("button")].map((element) => { + const style = getComputedStyle(element); + return [style.backgroundColor, style.color]; + })""" + ) + + in_ui_theme = read("ui-dark") + assert in_ui_theme == [ + # The theme itself, its red button and its soft green button: slate 1 + # and 12, red 9, then green a3 and a11, all of the dark scales. + ["rgb(17, 17, 19)", "rgb(237, 238, 240)"], + ["rgb(229, 72, 77)", "rgb(255, 255, 255)"], + ["rgba(34, 255, 153, 0.118)", "rgba(70, 254, 165, 0.83)"], + ] + assert in_ui_theme == read("radix-dark") From 1fae9d28a770edd499386b1124cadba7a3c5d080 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:33:45 +0000 Subject: [PATCH 18/26] Document themes and tokens, regenerate the stubs, and type the tests Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- packages/reflex-components-ui/README.md | 154 ++++++++++++++- .../reflex-components-ui/js/src/README.md | 5 +- .../news/+theme-python.feature.md | 1 + .../src/reflex_components_ui/layout/theme.py | 22 +-- .../src/reflex_components_ui/themes.py | 3 +- .../src/reflex_components_ui/tokens.py | 3 +- pyi_hashes.json | 3 +- .../tests_playwright/test_ui_components.py | 9 +- .../reflex_components_ui/layout/test_theme.py | 109 ++++++++--- .../reflex_components_ui/style/test_lower.py | 2 +- .../units/reflex_components_ui/test_themes.py | 179 ++++++++++-------- .../units/reflex_components_ui/test_tokens.py | 46 +++-- 12 files changed, 393 insertions(+), 143 deletions(-) create mode 100644 packages/reflex-components-ui/news/+theme-python.feature.md diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 99894b4a733..0a67793f3e7 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -24,11 +24,13 @@ rx.plugins.UIPlugin() in rxconfig.py plugins.` ``` src/reflex_components_ui/ the python package: the rx.ui namespace - plugin.py UIPlugin: the build wiring of an app + plugin.py UIPlugin: the build wiring of an app, and its theme base.py UIComponent: a plain element and its StyleX source + themes.py Theme: the options of a theme and the StyleX themes they apply + tokens.py rx.ui.tokens: the design tokens as style values style/emit.py a lowered style to a stylex.create declaration styles/ the look of each component, one table per module - layout/ the components + layout/ the components, rx.ui.theme among them _radix_tokens.py generated: the modules below and what they define js/ the javascript package, with its own tooling src/ what ships: copied into an app at .web/reflex-ui/ @@ -83,6 +85,14 @@ declared in the same module as the element, with literal arguments, so: element's `style`), then Tailwind's `components` and `utilities`. Unlayered CSS, such as an app's stylesheet, Emotion and Radix Themes, beats all of them. +It also holds what Radix Themes styles through a selector that a class on an +element cannot express: the selection color inside a theme, in the layer +`reflex-ui.base` so that a component's own style beats it, and the +`@font-face` rules of the system fonts whose metrics Radix adjusts, which +`js/tests/base-css.test.js` keeps equal to the ones of `@radix-ui/themes`. +`-webkit-text-size-adjust` is not there: the build adds the prefixed property +beside the one `themes/theme.js` sets. + Until the style package lands (`style/lower.py`, `style/merge.py`), a `style` takes flat properties with literal values, and `_lower_literal_styles` in `base.py` stands in for it. @@ -137,6 +147,140 @@ styles, layout props, then the user's style. A style that sets a property only under a condition, as a `_hover` block does, keeps the earlier value everywhere else; one that sets it outright replaces the earlier conditions too. +## Themes and tokens + +The plugin takes the theme of the app. Every option has the values and, the +accent aside, the default of the `Theme` of Radix Themes: + +```python +# rxconfig.py +config = rx.Config( + app_name="shop", + plugins=[ + rx.plugins.UIPlugin(theme=rx.ui.Theme(accent_color="indigo", radius="large")) + ], +) +``` + +| Option | Values | Default | +| --- | --- | --- | +| `accent_color` | the 26 accents, `"gray"` among them | `"blue"`, as `rx.theme` has in Reflex (Radix Themes has `"indigo"`) | +| `gray_color` | `"auto"`, `"gray"`, `"mauve"`, `"slate"`, `"sage"`, `"olive"`, `"sand"` | `"auto"`: the gray that matches the accent | +| `radius` | `"none"`, `"small"`, `"medium"`, `"large"`, `"full"` | `"medium"` | +| `scaling` | `"90%"`, `"95%"`, `"100%"`, `"105%"`, `"110%"` | `"100%"` | +| `appearance` | `"inherit"`, `"light"`, `"dark"` | `"inherit"`: the color mode of the app | +| `panel_background` | `"solid"`, `"translucent"` | `"translucent"` | +| `has_background` | `True`, `False` | `True` | + +A value an option does not take stops the app where `rxconfig.py` is loaded: +`rx.ui.Theme: unknown accent_color "indgo". Did you mean "indigo"? The values +are "tomato", "red", ...`. The types are `Literal`s, so a type checker says the +same. + +The plugin wraps every page in one element that carries the theme, inside the +`Theme` of Radix Themes when the app has both, so a page with components of +both follows this one. It is a `div` with the class of a StyleX theme for each +option, and the only thing imported for an accent is the module of that accent: + +```js +import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" +import {focusScope} from "$/reflex-ui/themes/focus.js" +import {graySlate} from "$/reflex-ui/themes/gray/slate.js" +... +jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentIndigo, graySlate, radiusLarge, scaling100, panelTranslucent, reflexUITheme.root, reflexUITheme.background, sx_c1c0436182.s, { $$css: true, className: "reflex-ui-theme" })}, ...) +``` + +A theme imported from another module is not folded into a string: the call +stays, and with it the 1.2 kB of the StyleX runtime, in the chunk every page +already loads. + +`rx.ui.theme(...)` is the same element around part of a page. It takes the +same options, each one optional: what it leaves out is inherited. + +```python +rx.ui.theme(card(), accent_color="red", radius="full") +rx.ui.theme(sidebar(), appearance="dark") +rx.ui.theme(preview(), accent_color=Settings.accent) +``` + +- An accent keeps the gray around it. `gray_color="auto"` with an accent is + the gray that matches it. +- The cascade does not tell an element what it inherits, so where that matters + a nested theme takes the theme of the app to be what is around it: + `gray_color="auto"` without an accent matches the accent of the app, and a + gray without an accent names the gray accent again when the app has it. + Inside another nested theme, give both options. +- A theme with an appearance paints its background, unless + `has_background=False`. The classes `light` and `dark`, which Tailwind and + Radix Themes select on, go on an element around it that has no box + (`display: contents`), so their components inside follow the appearance. + Beside Radix Themes, give such a theme its `gray_color` too: the Radix + stylesheet sets its plain gray wherever one of the two classes is. +- An option bound to state imports every theme it could name and chooses among + them in the browser. For the accent that is all 26 scales: about 21 kB of + gzipped CSS and 0.5 kB of gzipped javascript more than a literal accent, + where the theme of the app, one accent and one gray, is 4.6 kB of gzipped + CSS. The theme of the app is compiled ahead of time and takes literals only. +- The appearance of the theme of the app pins the page to it. It does not + change the color mode the app starts in, which `default_color_mode` sets. +- A theme held in state is a compile error: its code never reaches StyleX. + +`rx.ui.tokens` names every design token. A token is the `var()` of a custom +property, as a plain `str`, so it goes wherever a CSS value does, in the +`style` of any component and in a style table: + +```python +tokens = rx.ui.tokens + +tokens.space[4] # "var(--space-4)", steps 1 to 9 +tokens.radius[3] # steps 1 to 6, and .full, .thumb, .factor +tokens.shadow[3] # steps 1 to 6 +tokens.font_size[2] # steps 1 to 9, as line_height and letter_spacing +tokens.font_weight.bold # light, regular, medium, bold +tokens.accent[9] # steps 1 to 12 of the accent of the theme +tokens.accent.a[3] # its translucent steps +tokens.accent.contrast # and .surface, .indicator, .track +tokens.gray[11] # the gray of the theme, like the accent +tokens.focus[8] # the focus ring, and tokens.focus.a +tokens.color.panel # background, overlay, surface, panel_solid, ... +tokens.cursor.button # checkbox, disabled, link, menu_item, radio, ... +tokens.scale("ruby")[9] # a scale by name, whatever the theme +tokens.black.a[6] # and tokens.white.a +tokens.default.font_family # and heading, code, strong, em, quote, tab +tokens.scaling # "var(--scaling)" +``` + +A step or a name that does not exist is an error to a type checker, and a +`TokenError` that says what exists: `rx.ui.tokens.space has no step 10. Its +steps are 1 to 9.` + +`lower` reads a token like any other string. It names the module that defines +the custom property in `Lowered.imports` (`VAR_MODULES`, which is built from +the generated list), and a shorthand gives a token that holds one value to its +longhands, as it does with `rx.color(...)`: `{"padding": f"{tokens.space[2]} +{tokens.space[4]}"}` becomes four paddings. A shadow and a font family are +lists, and keep the shorthand whole. + +For a component: + +- Write the style table with tokens, never with the color of a named scale: + `"background_color": tokens.accent[9]`, `"color": tokens.accent.contrast`, + `"border_radius": tokens.radius[2]`, `"height": tokens.space[6]`. +- `color_scheme` is an accent on the element itself. + `themes.color_scheme_styles(name, value)` returns what the element needs: + the arguments to add to its `stylex.props` call (`accentRed` and + `focusScope`; `accentGray` alone for gray), the imports + (`import_dict()`), and for a value bound to state the map of all 26 accents + to declare in the module. The tokens of the table then resolve against the + accent of the element. +- The space, radius, typography, shadow and `--color-*` tokens, the accent, the + gray and the focus colors are defined wherever a theme is, which in an app is + everywhere. A cursor, a black or a white, and a scale named with + `tokens.scale` or `rx.color` are defined by the module `Lowered.imports` + names, once the element that uses them imports it. +- A color is one `light-dark()` value: `getPropertyValue("--accent-9")` in the + browser returns the pair, and a computed `color` the one in use. + ## Working on it From the repository root: @@ -176,7 +320,7 @@ their own. generator produces. - A lint rule in `js/src` cannot be switched off with a comment. -## Tokens and themes +## The modules behind the tokens and themes Every design token is a CSS custom property with the name and the value [Radix Themes](https://www.radix-ui.com/themes) gives it, so that a page can @@ -203,8 +347,8 @@ adds its CSS to an app only when something imports it. - `themes/theme.js` holds the styles of a theme element itself: `root`, `background`, and `light` and `dark`, which set `color-scheme`. -An appearance is the `color-scheme` of an element. The stylesheet every page -loads has to set it for `html.light` and `html.dark`, as +An appearance is the `color-scheme` of an element. `base.css` sets it for +`html.light` and `html.dark`, the classes of the color mode of an app, as `js/tests/harness/base.css` does for the tests; a nested appearance is `theme.light` or `theme.dark` on its element. Nothing else changes between the two, and nothing here depends on being at the root: a popover or a dialog in diff --git a/packages/reflex-components-ui/js/src/README.md b/packages/reflex-components-ui/js/src/README.md index 0da55a10df3..af2fc6ae59c 100644 --- a/packages/reflex-components-ui/js/src/README.md +++ b/packages/reflex-components-ui/js/src/README.md @@ -6,7 +6,10 @@ copies this directory into an app's `.web/reflex-ui/` from the is overwritten. - `base.css` is imported first by the app's stylesheet: it orders the cascade - layers and switches the color scheme. + layers, switches the color scheme, and holds the selection color of a theme + and the font faces the typography tokens name. +- `colors/`, `tokens/` and `themes/` are the design tokens and the themes, as + StyleX modules: a module adds its CSS when a page imports it. - `vite-plugin-stylex.js` is the plugin `vite.config.js` loads to compile the styles. diff --git a/packages/reflex-components-ui/news/+theme-python.feature.md b/packages/reflex-components-ui/news/+theme-python.feature.md new file mode 100644 index 00000000000..4ddb27ece4a --- /dev/null +++ b/packages/reflex-components-ui/news/+theme-python.feature.md @@ -0,0 +1 @@ +`rx.plugins.UIPlugin(theme=rx.ui.Theme(accent_color="indigo", radius="large"))` themes the whole app, `rx.ui.theme(...)` themes part of a page with the same options, and `rx.ui.tokens` names the design tokens as style values, such as `rx.ui.tokens.space[4]` and `rx.ui.tokens.accent.contrast`. The tokens have the values of Radix Themes. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py index 6c64095b25c..47d65df7be7 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py @@ -14,11 +14,7 @@ from reflex_base.vars.base import Var from reflex_base.vars.sequence import LiteralStringVar -from reflex_components_ui.base import ( - MISSING_PLUGIN_ERROR, - ComponentStyles, - UIComponent, -) +from reflex_components_ui.base import MISSING_PLUGIN_ERROR, ComponentStyles, UIComponent from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style.emit import props_call from reflex_components_ui.styles.theme import APP_THEME, APPEARANCE @@ -75,45 +71,43 @@ class ThemeElement(UIComponent): tag = "div" - accent_color: LiteralAccentColor | Var[LiteralAccentColor] | None = field( + accent_color: Var[LiteralAccentColor] | None = field( default=None, is_javascript_property=False, doc="The color of the components that stand out.", ) - gray_color: LiteralGrayColor | Var[LiteralGrayColor] | None = field( + gray_color: Var[LiteralGrayColor] | None = field( default=None, is_javascript_property=False, doc='The gray of text, borders and surfaces. "auto" is the gray that matches the accent color.', ) - radius: LiteralRadius | Var[LiteralRadius] | None = field( + radius: Var[LiteralRadius] | None = field( default=None, is_javascript_property=False, doc='How round corners are: "none" | "small" | "medium" | "large" | "full".', ) - scaling: LiteralScaling | Var[LiteralScaling] | None = field( + scaling: Var[LiteralScaling] | None = field( default=None, is_javascript_property=False, doc='The size of everything: "90%" | "95%" | "100%" | "105%" | "110%".', ) - appearance: LiteralAppearance | Var[LiteralAppearance] | None = field( + appearance: Var[LiteralAppearance] | None = field( default=None, is_javascript_property=False, doc='"light" or "dark" to keep one whatever the color mode, "inherit" to follow it.', ) - panel_background: ( - LiteralPanelBackground | Var[LiteralPanelBackground] | None - ) = field( + panel_background: Var[LiteralPanelBackground] | None = field( default=None, is_javascript_property=False, doc='Whether panels such as cards are see-through: "solid" | "translucent".', ) - has_background: bool | Var[bool] | None = field( + has_background: Var[bool] | None = field( default=None, is_javascript_property=False, doc="Whether the element paints the background of the theme. Defaults to True when it sets an appearance.", diff --git a/packages/reflex-components-ui/src/reflex_components_ui/themes.py b/packages/reflex-components-ui/src/reflex_components_ui/themes.py index f4bc6be8fe2..86021dafb42 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/themes.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/themes.py @@ -10,6 +10,7 @@ import dataclasses import json +import operator from collections.abc import Mapping from typing import Any, Literal, get_args @@ -302,7 +303,7 @@ def finish(self, class_name: str | None = None) -> ThemeStyles: """ return ThemeStyles( refs=tuple(self.refs), - imports=tuple(sorted(self.imports, key=lambda item: item[:2])), + imports=tuple(sorted(self.imports, key=operator.itemgetter(0, 1))), declarations=tuple(self.declarations), class_name=class_name, var_data=VarData.merge(*self.var_data), diff --git a/packages/reflex-components-ui/src/reflex_components_ui/tokens.py b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py index 7996b670396..02ac53bb8a5 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/tokens.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py @@ -113,8 +113,7 @@ def _step(self, step: int) -> str: ) else: msg = ( - f"{self._path} has no steps. Its tokens are " - f"{', '.join(self._names())}." + f"{self._path} has no steps. Its tokens are {', '.join(self._names())}." ) raise TokenError(msg) diff --git a/pyi_hashes.json b/pyi_hashes.json index b435fb7bb5a..8b9d391371b 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,9 +118,10 @@ "packages/reflex-components-recharts/src/reflex_components_recharts/polar.pyi": "adc4db1a3ca7cd292b099ec4d97a4346", "packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "f2a9cf6db58d169289fbc76de6813300", "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "87566e8afc48f0df46be8ca188bac2fb", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "0fb77ee40f719777c68b2de2efdf799b", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "d47c2b7331062c2d3b4588b19b2d530f", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "3a25570b63274a1490fa96a524a241fd", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "55e59f481df8cb08185a820f84e0a10d", + "packages/reflex-components-ui/src/reflex_components_ui/layout/theme.pyi": "e72b55b9f183676ea1476712ad97b712", "reflex/__init__.pyi": "540ab90bd8a7a89647f0bdd0a2fa3590", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index a566a018c74..9ed13c38041 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -62,6 +62,7 @@ def UIComponentsApp(radix: bool = False): """ import json from pathlib import Path + from typing import Any from reflex_components_ui import _radix_tokens @@ -150,7 +151,9 @@ def theme(): variations += [ {"panel_background": panel} for panel in _radix_tokens.PANEL_BACKGROUND_THEMES ] - configs = [{**defaults, **variation} for variation in variations] + configs: list[dict[str, Any]] = [ + {**defaults, **variation} for variation in variations + ] def sweep(): themes = [] @@ -161,7 +164,9 @@ def sweep(): # Reflex keeps the appearance of an `rx.theme` for the color # mode of the app. Radix Themes selects on the class, and gives # a theme with an appearance its background. - options = {k: v for k, v in config.items() if k != "appearance"} + options: dict[str, Any] = { + k: v for k, v in config.items() if k != "appearance" + } if "appearance" in config: options.update(class_name=config["appearance"], has_background=True) themes.append( diff --git a/tests/units/reflex_components_ui/layout/test_theme.py b/tests/units/reflex_components_ui/layout/test_theme.py index 8382c359fb9..1bcee2399bf 100644 --- a/tests/units/reflex_components_ui/layout/test_theme.py +++ b/tests/units/reflex_components_ui/layout/test_theme.py @@ -4,19 +4,21 @@ import pytest from pytest_mock import MockerFixture +from reflex_base.components.component import Component from reflex_base.config import get_config from reflex_base.plugins import CompileContext from reflex_base.utils.exceptions import ConfigError from reflex_base.utils.serializers import serialize from reflex_components_core.base.app_wrap import AppWrap -from reflex_components_ui.layout.theme import AppTheme, ThemeElement +from reflex_components_ui.layout.theme import Appearance, AppTheme, ThemeElement from reflex_components_ui.plugin import APP_THEME_WRAP, UIPlugin from reflex_components_ui.themes import Theme, ThemeError import reflex as rx from reflex.compiler import compiler -APP_ROOT = """ +APP_ROOT = ( + """ import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" import {focusScope} from "$/reflex-ui/themes/focus.js" import {graySlate} from "$/reflex-ui/themes/gray/slate.js" @@ -42,8 +44,10 @@ useEffect(() => { // Make contexts and state objects available globally for dynamic eval'd components window.__reflex = { - - }; +""" + # The template indents the libraries of the app, of which there are none. + " \n" + """ }; }, []); return jsx(ThemeProvider, {defaultTheme: defaultColorMode, attribute: "class"}, @@ -73,11 +77,11 @@ } """ +) NESTED_PAGE = """import * as stylex from "@stylexjs/stylex" import {accentRed} from "$/reflex-ui/themes/accent/red.js" import {focusScope} from "$/reflex-ui/themes/focus.js" -import {grayMauve} from "$/reflex-ui/themes/gray/mauve.js" import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" import {useRegisteredRef} from "$/utils/state" @@ -89,12 +93,13 @@ const sx_e0e666cdfc = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "color": "var(--accent-9)"} }); const sx_ffb9e340d1 = stylex.create({ s: {"padding": "4px"} }); +const sx_71b84cd269 = stylex.create({ s: {"display": "contents"} }); function Component() { const ref_dark = useRegisteredRef("ref_dark"); return ( - jsx(Fragment,{},jsx("main",{},jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentRed, grayMauve, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},jsx("div",{...stylex.props(sx_e0e666cdfc.s)},"red")),jsx("div",{id:"dark",ref:ref_dark,...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, radiusFull, reflexUITheme.root, reflexUITheme.background, reflexUITheme.dark, sx_ffb9e340d1.s, { $$css: true, className: "reflex-ui-theme dark p-8" })},"dark"),jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},"plain")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + jsx(Fragment,{},jsx("main",{},jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentRed, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},jsx("div",{...stylex.props(sx_e0e666cdfc.s)},"red")),jsx("div",{...stylex.props(sx_71b84cd269.s, { $$css: true, className: "dark" })},jsx("div",{id:"dark",ref:ref_dark,...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, radiusFull, reflexUITheme.root, reflexUITheme.background, reflexUITheme.dark, sx_ffb9e340d1.s, { $$css: true, className: "reflex-ui-theme p-8" })},"dark")),jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},"plain")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) ) } Component.displayName = "Component(/)"; @@ -102,7 +107,7 @@ export default Component; """ -BOUND_PAGE = """import {Themeelement_div_0c153819fc2a864827f9e11f201c2218} from "$/utils/components/Themeelement_div_0c153819fc2a864827f9e11f201c2218" +BOUND_PAGE = """import {Themeelement_div_f7d2b7c33308674eb3685852f6be4c25} from "$/utils/components/Themeelement_div_f7d2b7c33308674eb3685852f6be4c25" import {Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf} from "$/utils/components/Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf" import {Fragment,useEffect} from "react" import {jsx} from "@emotion/react" @@ -115,7 +120,7 @@ return ( - jsx(Fragment,{},jsx("main",{},jsx(Themeelement_div_0c153819fc2a864827f9e11f201c2218,{},"accent"),jsx(Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf,{},"names")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + jsx(Fragment,{},jsx("main",{},jsx(Themeelement_div_f7d2b7c33308674eb3685852f6be4c25,{},"accent"),jsx(Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf,{},"names")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) ) } Component.displayName = "Component(/)"; @@ -153,12 +158,6 @@ import {accentViolet} from "$/reflex-ui/themes/accent/violet.js" import {accentYellow} from "$/reflex-ui/themes/accent/yellow.js" import {focusScope} from "$/reflex-ui/themes/focus.js" -import {grayGray} from "$/reflex-ui/themes/gray/gray.js" -import {grayMauve} from "$/reflex-ui/themes/gray/mauve.js" -import {grayOlive} from "$/reflex-ui/themes/gray/olive.js" -import {graySage} from "$/reflex-ui/themes/gray/sage.js" -import {graySand} from "$/reflex-ui/themes/gray/sand.js" -import {graySlate} from "$/reflex-ui/themes/gray/slate.js" import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" import * as stylex from "@stylexjs/stylex" @@ -168,18 +167,17 @@ const reflexUIAccents = { "amber": accentAmber, "blue": accentBlue, "bronze": accentBronze, "brown": accentBrown, "crimson": accentCrimson, "cyan": accentCyan, "gold": accentGold, "grass": accentGrass, "gray": accentGray, "green": accentGreen, "indigo": accentIndigo, "iris": accentIris, "jade": accentJade, "lime": accentLime, "mint": accentMint, "orange": accentOrange, "pink": accentPink, "plum": accentPlum, "purple": accentPurple, "red": accentRed, "ruby": accentRuby, "sky": accentSky, "teal": accentTeal, "tomato": accentTomato, "violet": accentViolet, "yellow": accentYellow }; -const reflexUIMatchingGrays = { "amber": graySand, "blue": graySlate, "bronze": graySand, "brown": graySand, "crimson": grayMauve, "cyan": graySlate, "gold": graySand, "grass": grayOlive, "gray": grayGray, "green": graySage, "indigo": graySlate, "iris": graySlate, "jade": graySage, "lime": grayOlive, "mint": graySage, "orange": graySand, "pink": grayMauve, "plum": grayMauve, "purple": grayMauve, "red": grayMauve, "ruby": grayMauve, "sky": graySlate, "teal": graySage, "tomato": grayMauve, "violet": grayMauve, "yellow": graySand }; -export const Themeelement_div_0c153819fc2a864827f9e11f201c2218 = /*#__PURE__*/ (() => { -const Themeelement_div_0c153819fc2a864827f9e11f201c2218 = memo(({children, ...rest}) => { +export const Themeelement_div_f7d2b7c33308674eb3685852f6be4c25 = /*#__PURE__*/ (() => { +const Themeelement_div_f7d2b7c33308674eb3685852f6be4c25 = memo(({children, ...rest}) => { const reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state = useStateContext("reflex___state____state.tests___units___reflex_components_ui___layout___test_theme____theme_state", ["accent_rx_state_"]) return( - jsx("div",{...mergeSlotProps(rest, ({ ...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], reflexUIMatchingGrays[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" }) }))},children) + jsx("div",{...mergeSlotProps(rest, ({ ...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" }) }))},children) ) }); -Themeelement_div_0c153819fc2a864827f9e11f201c2218.displayName = "ThemeElement"; -return Themeelement_div_0c153819fc2a864827f9e11f201c2218; +Themeelement_div_f7d2b7c33308674eb3685852f6be4c25.displayName = "ThemeElement"; +return Themeelement_div_f7d2b7c33308674eb3685852f6be4c25; })(); """ @@ -243,6 +241,7 @@ class ThemeState(rx.State): accent: str = "red" names: str = "wide" + appearance: str = "dark" @pytest.fixture @@ -276,6 +275,68 @@ def test_app_root_source(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) assert compiler._compile_app(root, dynamic_components=False) == APP_ROOT +def test_plugin_wraps_an_app_with_an_appearance_in_its_class( + monkeypatch: pytest.MonkeyPatch, compile_page: Callable[..., CompileContext] +): + """The class of the appearance is on an element around the theme element.""" + plugin = UIPlugin(theme=Theme(appearance="dark")) + monkeypatch.setattr(get_config(), "plugins", [plugin]) + wraps = compile_page(lambda: rx.el.main("hello"), plugin).app_wrap_components + assert {key: type(wrap) for key, wrap in wraps.items()} == { + (15, "ReflexUITheme"): AppTheme, + (16, "ReflexUIAppearance"): Appearance, + } + assert wraps[16, "ReflexUIAppearance"].render() == { + "name": '"div"', + "props": [ + '...stylex.props(sx_71b84cd269.s, { $$css: true, className: "dark" })' + ], + "children": [], + } + assert wraps[15, "ReflexUITheme"].render() == { + "name": '"div"', + "props": [ + ( + "...stylex.props(spaceScope, radiusScope, typographyScope, " + "shadowScope, colorScope, focusScope, accentBlue, graySlate, " + "radiusMedium, scaling100, panelTranslucent, reflexUITheme.root, " + "reflexUITheme.background, reflexUITheme.dark, sx_c1c0436182.s, " + '{ $$css: true, className: "reflex-ui-theme" })' + ) + ], + "children": [], + } + + +def test_theme_with_an_appearance_is_inside_the_element_of_its_class( + indigo_plugin: UIPlugin, +): + """Only a theme with an appearance of its own has the element around it.""" + assert type(rx.ui.theme("hello")) is ThemeElement + assert type(rx.ui.theme("hello", appearance="inherit")) is ThemeElement + dark: Component = rx.ui.theme("hello", appearance="dark", id="dark") + assert [type(dark), *map(type, dark.children)] == [Appearance, ThemeElement] + bound: Component = rx.ui.theme( + "hello", + appearance=ThemeState.appearance, # pyright: ignore [reportArgumentType] + ) + assert bound.render()["props"] == [ + ( + f'className:({ThemeState.appearance!s}) + " " + ' + "stylex.props(sx_71b84cd269.s).className" + ) + ] + assert bound.children[0].render()["props"] == [ + ( + "...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, " + "colorScope, focusScope, reflexUITheme.root, " + f'({ThemeState.appearance!s}) !== "inherit" && reflexUITheme.background, ' + f"reflexUITheme[{ThemeState.appearance!s}], " + '{ $$css: true, className: "reflex-ui-theme" })' + ) + ] + + def test_plugin_wraps_every_app_in_its_theme( indigo_plugin: UIPlugin, compile_page: Callable[..., CompileContext] ): @@ -318,10 +379,13 @@ def test_theme_bound_to_state_imports_every_accent( def page(): return rx.el.main( - rx.ui.theme("accent", accent_color=ThemeState.accent), + rx.ui.theme( + "accent", + accent_color=ThemeState.accent, # pyright: ignore [reportArgumentType] + ), rx.ui.theme( "names", - accent_color=ThemeState.accent, + accent_color=ThemeState.accent, # pyright: ignore [reportArgumentType] gray_color="sand", class_name=ThemeState.names, ), @@ -338,7 +402,6 @@ def test_theme_is_a_name_of_the_ui_namespace(): assert rx.ui.theme == ThemeElement.create assert rx.ui.Theme is Theme assert {"theme", "Theme"} <= set(dir(rx.ui)) - assert ThemeElement._display_name() == "rx.ui.theme" def test_theme_needs_the_plugin(monkeypatch: pytest.MonkeyPatch): diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index f730db8f440..380e82758f0 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -6,9 +6,9 @@ from reflex_base.breakpoints import breakpoints_values, set_breakpoints from reflex_base.constants.colors import Color from reflex_base.vars.base import LiteralVar, Var -from reflex_components_ui.style import _css_props from reflex_components_ui import tokens from reflex_components_ui._radix_tokens import VAR_GROUPS +from reflex_components_ui.style import _css_props from reflex_components_ui.style.lower import ( _BORDERS, _EXPANSIONS, diff --git a/tests/units/reflex_components_ui/test_themes.py b/tests/units/reflex_components_ui/test_themes.py index d9a7b96bd68..1cb8e78778a 100644 --- a/tests/units/reflex_components_ui/test_themes.py +++ b/tests/units/reflex_components_ui/test_themes.py @@ -57,13 +57,13 @@ class ThemeState(rx.State): """State whose fields are bound to theme options.""" - accent: str = "red" - gray: str = "sand" - radius: str = "full" - scaling: str = "90%" - panel: str = "solid" - appearance: str = "dark" - background: bool = True + accent: rx.Field[str] = rx.field("red") + gray: rx.Field[str] = rx.field("sand") + radius: rx.Field[str] = rx.field("full") + scaling: rx.Field[str] = rx.field("90%") + panel: rx.Field[str] = rx.field("solid") + appearance: rx.Field[str] = rx.field("dark") + background: rx.Field[bool] = rx.field(True) def test_literal_types_are_the_generated_themes(): @@ -89,14 +89,14 @@ def test_literal_types_are_the_generated_themes(): "background", *(set(get_args(themes.LiteralAppearance)) - {"inherit"}), ]) - assert themes.OPTIONS == { + assert { "accent_color": get_args(themes.LiteralAccentColor), "gray_color": get_args(themes.LiteralGrayColor), "radius": get_args(themes.LiteralRadius), "scaling": get_args(themes.LiteralScaling), "appearance": ("inherit", "light", "dark"), "panel_background": get_args(themes.LiteralPanelBackground), - } + } == themes.OPTIONS def test_theme_defaults_are_the_ones_of_radix_but_for_the_accent(): @@ -123,8 +123,10 @@ def test_theme_is_a_frozen_value(): [ ( {"accent_color": "indgo"}, - 'rx.ui.Theme: unknown accent_color "indgo". Did you mean "indigo"? ' - f"The values are {ACCENT_VALUES}.", + ( + 'rx.ui.Theme: unknown accent_color "indgo". Did you mean "indigo"? ' + f"The values are {ACCENT_VALUES}." + ), ), ( {"accent_color": "mauve"}, @@ -132,33 +134,45 @@ def test_theme_is_a_frozen_value(): ), ( {"gray_color": "slat"}, - 'rx.ui.Theme: unknown gray_color "slat". Did you mean "slate"? The ' - 'values are "auto", "gray", "mauve", "slate", "sage", "olive", "sand".', + ( + 'rx.ui.Theme: unknown gray_color "slat". Did you mean "slate"? The ' + 'values are "auto", "gray", "mauve", "slate", "sage", "olive", "sand".' + ), ), ( {"radius": "big"}, - 'rx.ui.Theme: unknown radius "big". The values are "none", "small", ' - '"medium", "large", "full".', + ( + 'rx.ui.Theme: unknown radius "big". The values are "none", "small", ' + '"medium", "large", "full".' + ), ), ( {"scaling": 100}, - "rx.ui.Theme: unknown scaling 100. The values are " - '"90%", "95%", "100%", "105%", "110%".', + ( + "rx.ui.Theme: unknown scaling 100. The values are " + '"90%", "95%", "100%", "105%", "110%".' + ), ), ( {"scaling": "100"}, - 'rx.ui.Theme: unknown scaling "100". Did you mean "100%"? The values ' - 'are "90%", "95%", "100%", "105%", "110%".', + ( + 'rx.ui.Theme: unknown scaling "100". Did you mean "100%"? The values ' + 'are "90%", "95%", "100%", "105%", "110%".' + ), ), ( {"appearance": "system"}, - 'rx.ui.Theme: unknown appearance "system". The values are ' - '"inherit", "light", "dark".', + ( + 'rx.ui.Theme: unknown appearance "system". The values are ' + '"inherit", "light", "dark".' + ), ), ( {"panel_background": None}, - "rx.ui.Theme: unknown panel_background None. The values are " - '"solid", "translucent".', + ( + "rx.ui.Theme: unknown panel_background None. The values are " + '"solid", "translucent".' + ), ), ( {"has_background": "yes"}, @@ -166,9 +180,11 @@ def test_theme_is_a_frozen_value(): ), ( {"accent_color": ThemeState.accent}, - "rx.ui.Theme: accent_color is bound to state, but the theme of an " - "app is compiled ahead of time. Give it one of its values, or bind " - "the option of an rx.ui.theme(...) around the page.", + ( + "rx.ui.Theme: accent_color is bound to state, but the theme of an " + "app is compiled ahead of time. Give it one of its values, or bind " + "the option of an rx.ui.theme(...) around the page." + ), ), ], ) @@ -246,7 +262,7 @@ def test_app_theme_sets_every_option(): *SCOPE_IMPORTS, STYLES_IMPORT, ), - class_name="reflex-ui-theme dark", + class_name="reflex-ui-theme", ) @@ -266,16 +282,13 @@ def test_every_accent_has_the_gray_that_matches_it(): def _nested( - refs: tuple[str, ...], - imports: tuple[tuple[str, str, str | None], ...], - class_name: str = "reflex-ui-theme", + refs: tuple[str, ...], imports: tuple[tuple[str, str, str | None], ...] ) -> ThemeStyles: """Build what a nested theme is expected to need. Args: refs: The arguments after the scopes, the focus and before the root style. imports: The imports beside the ones every theme element has. - class_name: The class names of the element. Returns: The expected styles. @@ -285,7 +298,7 @@ def _nested( return ThemeStyles( refs=(*SCOPES, "focusScope", *before, "reflexUITheme.root", *after), imports=tuple(sorted([*imports, FOCUS_IMPORT, *SCOPE_IMPORTS, STYLES_IMPORT])), - class_name=class_name, + class_name="reflex-ui-theme", ) @@ -300,17 +313,8 @@ def _nested( [ # Nothing set: the element only declares again what reads the theme. ({}, Theme(), _nested((), ())), - # Under the automatic gray of the app, the gray follows the accent. - ( - {"accent_color": "red"}, - Theme(), - _nested(("accentRed", "grayMauve"), (RED, MAUVE)), - ), - ( - {"accent_color": "red"}, - Theme(gray_color="sand"), - _nested(("accentRed",), (RED,)), - ), + # An accent keeps the gray around the element, as in Radix Themes. + ({"accent_color": "red"}, Theme(), _nested(("accentRed",), (RED,))), ( {"accent_color": "red", "gray_color": "olive"}, Theme(), @@ -350,16 +354,12 @@ def _nested( ( {"appearance": "dark"}, Theme(), - _nested( - ("reflexUITheme.background", "reflexUITheme.dark"), - (), - "reflex-ui-theme dark", - ), + _nested(("reflexUITheme.background", "reflexUITheme.dark"), ()), ), ( {"appearance": "light", "has_background": False}, Theme(), - _nested(("reflexUITheme.light",), (), "reflex-ui-theme light"), + _nested(("reflexUITheme.light",), ()), ), ({"appearance": "inherit"}, Theme(), _nested((), ())), ( @@ -375,11 +375,7 @@ def _nested( "has_background": LiteralVar.create(False), }, Theme(), - _nested( - ("accentRed", "grayMauve", "reflexUITheme.dark"), - (RED, MAUVE), - "reflex-ui-theme dark", - ), + _nested(("accentRed", "reflexUITheme.dark"), (RED,)), ), ], ) @@ -400,7 +396,10 @@ def test_accent_bound_to_state_imports_every_accent(): """The page chooses among all of them, and the gray that matches each.""" accent = str(ThemeState.accent) styles = theme_styles( - "rx.ui.theme", accent_color=ThemeState.accent, app_theme=Theme() + "rx.ui.theme", + accent_color=ThemeState.accent, + gray_color="auto", + app_theme=Theme(), ) assert styles.refs == ( *SCOPES, @@ -430,7 +429,17 @@ def test_accent_bound_to_state_imports_every_accent(): assert styles.class_name == "reflex-ui-theme" assert styles.var_data == ThemeState.accent._get_all_var_data() - # With a gray of its own, only the accents are imported. + # With a gray of its own, or the one around it, only the accents are. + inherited = theme_styles( + "rx.ui.theme", accent_color=ThemeState.accent, app_theme=Theme() + ) + assert inherited.refs == ( + *SCOPES, + "focusScope", + f"reflexUIAccents[{accent}]", + "reflexUITheme.root", + ) + assert inherited.declarations == (ACCENT_MAP,) styles = theme_styles( "rx.ui.theme", accent_color=ThemeState.accent, @@ -479,18 +488,25 @@ def test_every_option_can_be_bound_to_state(): "reflexUITheme.root", f"({state.background!s}) && reflexUITheme.background", f"reflexUITheme[{appearance}]", - f'({appearance}) !== "inherit" && {{ $$css: true, appearance: {appearance} }}', ) assert styles.declarations == ( - 'const reflexUIGrays = { "gray": grayGray, "mauve": grayMauve, ' - '"olive": grayOlive, "sage": graySage, "sand": graySand, ' - '"slate": graySlate };', - 'const reflexUIRadii = { "full": radiusFull, "large": radiusLarge, ' - '"medium": radiusMedium, "none": radiusNone, "small": radiusSmall };', - 'const reflexUIScalings = { "100%": scaling100, "105%": scaling105, ' - '"110%": scaling110, "90%": scaling90, "95%": scaling95 };', - 'const reflexUIPanels = { "solid": panelSolid, ' - '"translucent": panelTranslucent };', + ( + 'const reflexUIGrays = { "gray": grayGray, "mauve": grayMauve, ' + '"olive": grayOlive, "sage": graySage, "sand": graySand, ' + '"slate": graySlate };' + ), + ( + 'const reflexUIRadii = { "full": radiusFull, "large": radiusLarge, ' + '"medium": radiusMedium, "none": radiusNone, "small": radiusSmall };' + ), + ( + 'const reflexUIScalings = { "100%": scaling100, "105%": scaling105, ' + '"110%": scaling110, "90%": scaling90, "95%": scaling95 };' + ), + ( + 'const reflexUIPanels = { "solid": panelSolid, ' + '"translucent": panelTranslucent };' + ), ) assert styles.imports == tuple( sorted([ @@ -529,7 +545,6 @@ def test_every_option_can_be_bound_to_state(): "reflexUITheme.root", f'({appearance}) !== "inherit" && reflexUITheme.background', f"reflexUITheme[{appearance}]", - f'({appearance}) !== "inherit" && {{ $$css: true, appearance: {appearance} }}', ) @@ -539,26 +554,34 @@ def test_every_option_can_be_bound_to_state(): ( {"accent_color": "rubby"}, Theme(), - 'rx.ui.theme: unknown accent_color "rubby". Did you mean "ruby"? ' - f"The values are {ACCENT_VALUES}.", + ( + 'rx.ui.theme: unknown accent_color "rubby". Did you mean "ruby"? ' + f"The values are {ACCENT_VALUES}." + ), ), ( {"gray_color": "blue"}, Theme(), - 'rx.ui.theme: unknown gray_color "blue". The values are "auto", ' - '"gray", "mauve", "slate", "sage", "olive", "sand".', + ( + 'rx.ui.theme: unknown gray_color "blue". The values are "auto", ' + '"gray", "mauve", "slate", "sage", "olive", "sand".' + ), ), ( {"radius": "round"}, Theme(), - 'rx.ui.theme: unknown radius "round". The values are "none", ' - '"small", "medium", "large", "full".', + ( + 'rx.ui.theme: unknown radius "round". The values are "none", ' + '"small", "medium", "large", "full".' + ), ), ( {"appearance": "night"}, Theme(), - 'rx.ui.theme: unknown appearance "night". Did you mean "light"? The values are ' - '"inherit", "light", "dark".', + ( + 'rx.ui.theme: unknown appearance "night". Did you mean "light"? The values are ' + '"inherit", "light", "dark".' + ), ), ( {"has_background": 1}, @@ -568,8 +591,10 @@ def test_every_option_can_be_bound_to_state(): ( {"gray_color": "auto"}, None, - 'rx.ui.theme: gray_color "auto" is the gray that matches an accent ' - "color. Give accent_color too, or name the gray.", + ( + 'rx.ui.theme: gray_color "auto" is the gray that matches an accent ' + "color. Give accent_color too, or name the gray." + ), ), ], ) diff --git a/tests/units/reflex_components_ui/test_tokens.py b/tests/units/reflex_components_ui/test_tokens.py index cf3089beb8e..7692e6dd639 100644 --- a/tests/units/reflex_components_ui/test_tokens.py +++ b/tests/units/reflex_components_ui/test_tokens.py @@ -135,7 +135,7 @@ def test_every_token_lowers_to_itself_and_imports_its_module(): "rx.ui.tokens.space has no step '4'. Its steps are 1 to 9.", ), ( - lambda: tokens.space[True], + lambda: tokens.space[True], # pyright: ignore [reportArgumentType] "rx.ui.tokens.space has no step True. Its steps are 1 to 9.", ), ( @@ -152,8 +152,10 @@ def test_every_token_lowers_to_itself_and_imports_its_module(): ), ( lambda: tokens.font_weight[1], - "rx.ui.tokens.font_weight has no steps. Its tokens are bold, light, " - "medium, regular.", + ( + "rx.ui.tokens.font_weight has no steps. Its tokens are bold, light, " + "medium, regular." + ), ), ( lambda: tokens.black[3], @@ -161,34 +163,46 @@ def test_every_token_lowers_to_itself_and_imports_its_module(): ), ( lambda: tokens.accent.contrst, # pyright: ignore [reportAttributeAccessIssue] - 'rx.ui.tokens.accent has no token "contrst". Did you mean ' - '"contrast"? Its tokens are a, contrast, indicator, surface, track, ' - "and the steps [1] to [12].", + ( + 'rx.ui.tokens.accent has no token "contrst". Did you mean ' + '"contrast"? Its tokens are a, contrast, indicator, surface, track, ' + "and the steps [1] to [12]." + ), ), ( lambda: tokens.space.four, # pyright: ignore [reportAttributeAccessIssue] - 'rx.ui.tokens.space has no token "four". Its tokens are the steps ' - "[1] to [9].", + ( + 'rx.ui.tokens.space has no token "four". Its tokens are the steps ' + "[1] to [9]." + ), ), ( lambda: tokens.font_weight.semibold, # pyright: ignore [reportAttributeAccessIssue] - 'rx.ui.tokens.font_weight has no token "semibold". Did you mean "bold"? Its tokens are ' - "bold, light, medium, regular.", + ( + 'rx.ui.tokens.font_weight has no token "semibold". Did you mean "bold"? Its tokens are ' + "bold, light, medium, regular." + ), ), ( lambda: tokens.focus.contrast, # pyright: ignore [reportAttributeAccessIssue] - 'rx.ui.tokens.focus has no token "contrast". Its tokens are a, and ' - "the steps [1] to [12].", + ( + 'rx.ui.tokens.focus has no token "contrast". Its tokens are a, and ' + "the steps [1] to [12]." + ), ), ( lambda: tokens.scale("rubby"), # pyright: ignore [reportArgumentType] - 'rx.ui.tokens.scale: unknown color scale "rubby". Did you mean ' - f'"ruby"? The scales are {SCALE_NAMES}.', + ( + 'rx.ui.tokens.scale: unknown color scale "rubby". Did you mean ' + f'"ruby"? The scales are {SCALE_NAMES}.' + ), ), ( lambda: tokens.scale("gray"), # pyright: ignore [reportArgumentType] - 'rx.ui.tokens.scale: "gray" is not a color scale of its own, but ' - "the gray of the theme: use rx.ui.tokens.gray.", + ( + 'rx.ui.tokens.scale: "gray" is not a color scale of its own, but ' + "the gray of the theme: use rx.ui.tokens.gray." + ), ), ( lambda: tokens.scale(9), # pyright: ignore [reportArgumentType] From b9963725a099f80d3da1cb01cef9098f558116f1 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:46:03 +0000 Subject: [PATCH 19/26] Read the appearance from the props, and settle the type checks of the package Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- .../src/reflex_components_ui/layout/theme.py | 5 +++-- tests/units/reflex_components_ui/test_tokens.py | 8 ++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py index 47d65df7be7..5da2fb1f7f0 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py @@ -126,7 +126,7 @@ def create(cls, *children, **props) -> Component: its appearance when it has one of its own. """ element = super().create(*children, **props) - appearance = literal_option(element.appearance) + appearance = literal_option(props.get("appearance")) if appearance is None or ( appearance.__class__ is str and appearance == "inherit" ): @@ -237,7 +237,8 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """ tag = Component._render(self, props) theme = self._theme_styles() - style = self._stylex() + # The generated stub of the base class leaves its private methods out. + style = self._stylex() # pyright: ignore [reportAttributeAccessIssue] refs = theme.refs if style is None else (*theme.refs, style.ref) own = tag.props.get("className") if own is None or isinstance(own, LiteralStringVar): diff --git a/tests/units/reflex_components_ui/test_tokens.py b/tests/units/reflex_components_ui/test_tokens.py index 7692e6dd639..5138ed8967b 100644 --- a/tests/units/reflex_components_ui/test_tokens.py +++ b/tests/units/reflex_components_ui/test_tokens.py @@ -162,9 +162,9 @@ def test_every_token_lowers_to_itself_and_imports_its_module(): "rx.ui.tokens.black has no steps. Its tokens are a.", ), ( - lambda: tokens.accent.contrst, # pyright: ignore [reportAttributeAccessIssue] + lambda: tokens.accent.contrasst, # pyright: ignore [reportAttributeAccessIssue] ( - 'rx.ui.tokens.accent has no token "contrst". Did you mean ' + 'rx.ui.tokens.accent has no token "contrasst". Did you mean ' '"contrast"? Its tokens are a, contrast, indicator, surface, track, ' "and the steps [1] to [12]." ), @@ -226,8 +226,8 @@ def test_a_token_that_does_not_exist_says_what_does( def test_token_error_is_what_python_expects_of_a_missing_name(): """``hasattr`` and ``getattr`` with a default work, and so does copying.""" - assert not hasattr(tokens.accent, "contrst") - assert getattr(tokens.accent, "contrst", None) is None + assert not hasattr(tokens.accent, "contrasst") + assert getattr(tokens.accent, "contrasst", None) is None assert issubclass(TokenError, (AttributeError, LookupError)) assert copy.deepcopy(tokens.accent).a[3] == "var(--accent-a3)" From aaa0b276fa335b4eca7d9ddfa8e609bc9cd94c01 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:47:45 +0000 Subject: [PATCH 20/26] Compile rx.ui styles: merge in Python, emit one StyleX declaration Join the lowering and merging of the style package with the emitter into the style compiler of the rx.ui components. A component's style table, its layout props and the element's style are merged once in Python. Each distinct result is declared once per module, followed by a constant that StyleX folds into its class names, so no shape needs the StyleX runtime: - a literal is an atomic class in the constant; - a value bound to state is `var(--vN)` in the declaration and a custom property in the element's inline style; - a variant prop bound to state gets one style per value, folded into a table of class names that the element indexes; - a whole style from state is the inline style. UIComponent splits keyword arguments into props, event triggers, attributes, layout props and CSS properties, raises a StyleError where the component is created, binds `Part` children to the parts of the table, applies the styles of the app, and falls back to an inline style in a component held in state. The stub generator takes a per-class annotation for a prop (`_pyi_overwrite_types`, `_pyi_imports`), which types `style` of every rx.ui component as CSS. The Vite plugin hands StyleX only the statements that declare styles and compiles a module once per build: React Router transformed a route module seven times, each a whole pass of Babel. Claude-Session: https://claude.ai/code/session_014AwvTNpEJAmVnKpLAWUGN1 --- .../news/+pyi-overwrite-types.misc.md | 1 + .../src/reflex_base/utils/pyi_generator.py | 38 +- packages/reflex-components-ui/README.md | 148 +++- .../js/src/vite-plugin-stylex.js | 110 ++- .../js/tests/vite-plugin-stylex.test.js | 176 ++++- .../news/+style-compiler.feature.md | 8 + .../src/reflex_components_ui/base.py | 459 +++++++++--- .../src/reflex_components_ui/layout/box.py | 3 +- .../src/reflex_components_ui/style/emit.py | 512 +++++++++++--- .../src/reflex_components_ui/style/lower.py | 8 +- .../src/reflex_components_ui/style/merge.py | 25 +- .../src/reflex_components_ui/styles/box.py | 4 +- pyi_hashes.json | 4 +- .../tests_playwright/test_ui_components.py | 294 +++++++- .../pyi_generator/dataset/overwrite_types.py | 54 ++ .../pyi_generator/golden/overwrite_types.pyi | 272 ++++++++ tests/units/reflex_components_ui/conftest.py | 52 ++ .../reflex_components_ui/layout/test_box.py | 164 ++++- .../style/fixtures/component_errors.py.txt | 13 + .../style/fixtures/component_valid.py.txt | 32 + .../style/test_css_props.py | 59 +- .../reflex_components_ui/style/test_emit.py | 602 +++++++++++++--- .../reflex_components_ui/style/test_merge.py | 26 + tests/units/reflex_components_ui/test_base.py | 655 +++++++++++++++--- 24 files changed, 3205 insertions(+), 514 deletions(-) create mode 100644 packages/reflex-base/news/+pyi-overwrite-types.misc.md create mode 100644 packages/reflex-components-ui/news/+style-compiler.feature.md create mode 100644 tests/units/reflex_base/utils/pyi_generator/dataset/overwrite_types.py create mode 100644 tests/units/reflex_base/utils/pyi_generator/golden/overwrite_types.pyi create mode 100644 tests/units/reflex_components_ui/style/fixtures/component_errors.py.txt create mode 100644 tests/units/reflex_components_ui/style/fixtures/component_valid.py.txt diff --git a/packages/reflex-base/news/+pyi-overwrite-types.misc.md b/packages/reflex-base/news/+pyi-overwrite-types.misc.md new file mode 100644 index 00000000000..fc0d4d5fcee --- /dev/null +++ b/packages/reflex-base/news/+pyi-overwrite-types.misc.md @@ -0,0 +1 @@ +A component class can set `_pyi_overwrite_types` and `_pyi_imports` to give a prop a narrower annotation in its generated `.pyi` stub. diff --git a/packages/reflex-base/src/reflex_base/utils/pyi_generator.py b/packages/reflex-base/src/reflex_base/utils/pyi_generator.py index 0c761cbae05..9cb51fe725b 100644 --- a/packages/reflex-base/src/reflex_base/utils/pyi_generator.py +++ b/packages/reflex-base/src/reflex_base/utils/pyi_generator.py @@ -502,19 +502,27 @@ def _get_class_event_triggers(target_class: type) -> frozenset[str]: def _generate_imports( typing_imports: Iterable[str], + extra_imports: Mapping[str, Iterable[str]] | None = None, ) -> list[ast.ImportFrom | ast.Import]: """Generate the import statements for the stub file. Args: typing_imports: The typing imports to include. + extra_imports: The names the classes of the module ask for, by module, + for the types they overwrite. Returns: The list of import statements. """ return [ *[ - ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values]) # pyright: ignore [reportCallIssue] - for name, values in DEFAULT_IMPORTS.items() + ast.ImportFrom( + module=name, names=[ast.alias(name=val) for val in sorted(values)] + ) # pyright: ignore [reportCallIssue] + for name, values in ( + *DEFAULT_IMPORTS.items(), + *sorted((extra_imports or {}).items()), + ) ], ast.Import([ast.alias("reflex")]), ] @@ -598,6 +606,22 @@ def _extract_func_kwargs_as_ast_nodes( return kwargs +def _class_overwrite_types(clz: type) -> dict[str, str]: + """Get the annotations a class gives its props in place of the declared ones. + + A component class sets ``_pyi_overwrite_types`` to a dict from the name of + a prop to its annotation in the stub, and ``_pyi_imports`` to the names + those annotations need, by module. Both are inherited. + + Args: + clz: The class a ``create`` stub is generated for. + + Returns: + The annotation of each overwritten prop. + """ + return getattr(clz, "_pyi_overwrite_types", {}) + + def _extract_class_props_as_ast_nodes( func: Callable, clzs: list[type], @@ -618,6 +642,8 @@ def _extract_class_props_as_ast_nodes( """ spec = _get_full_argspec(func) func_kwonlyargs = set(spec.kwonlyargs) + # The class the stub is for may type a prop more narrowly than its parents. + overwrite_types = {**OVERWRITE_TYPES, **_class_overwrite_types(clzs[0])} all_props: set[str] = set() kwargs = deque() for target_class in reversed(clzs): @@ -657,7 +683,7 @@ def _extract_class_props_as_ast_nodes( ast.arg( arg=name, annotation=ast.Name( - id=OVERWRITE_TYPES.get( + id=overwrite_types.get( name, _get_type_hint( value, @@ -1214,7 +1240,11 @@ def visit_Import( ] if not self.inserted_imports: self.inserted_imports = True - default_imports = _generate_imports(self.typing_imports) + extra_imports: dict[str, set[str]] = {} + for clz in self.classes.values(): + for module, names in getattr(clz, "_pyi_imports", {}).items(): + extra_imports.setdefault(module, set()).update(names) + default_imports = _generate_imports(self.typing_imports, extra_imports) return [*default_imports, *([node] if node.names else ())] if not node.names: return [] diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 01cde2eb4d2..bb5a78ff30b 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -26,7 +26,8 @@ rx.plugins.UIPlugin() in rxconfig.py plugins.` src/reflex_components_ui/ the python package: the rx.ui namespace plugin.py UIPlugin: the build wiring of an app base.py UIComponent: a plain element and its StyleX source - style/emit.py a lowered style to a stylex.create declaration + style/lower.py, merge.py the styles a user writes to the ones StyleX compiles + style/emit.py merged styles to the statements of a module styles/ the look of each component, one table per module layout/ the components js/ the javascript package, with its own tooling @@ -46,40 +47,141 @@ news fragment goes in `news/`. ## How a component reaches the browser -`rx.ui.box("hello", style={"padding": "4px"})` compiles to a `div`, with its -style declared in the module that renders it: +`rx.ui.box("hello", style={"top": "4px"})` compiles to a `div`, with its style +declared in the module that renders it: ```js import * as stylex from "@stylexjs/stylex" -const sx_f49d6b3475 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "padding": "4px"} }); +const sx_3debd41bb2 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "top": "4px"} }); +const sx_3debd41bb2_c = stylex.props(sx_3debd41bb2.s).className; -jsx("div",{...stylex.props(sx_f49d6b3475.s)},"hello") +jsx("div",{className:sx_3debd41bb2_c},"hello") ``` -StyleX then folds the call into `className: "x9f619 x1lliihq xfawy5m"` and -appends the three rules to the app's stylesheet. It only does so for a style -declared in the same module as the element, with literal arguments, so: +StyleX folds the second statement into the string `"x9f619 x1lliihq xndqk7f"` +and appends the three rules to the app's stylesheet. It only does so for a +call it can evaluate while compiling, on a style declared in the same module, +so everything the compiler emits has that shape and **no page ships the StyleX +runtime**: + +| You write | It becomes | +| --- | --- | +| A literal value | An atomic class in the module's constant | +| A state `Var` value | `var(--v0)` in the declaration, and `style={{"--v0": state.width ?? "initial"}}` on the element | +| A `_hover` or `:focus-visible` block | A condition on each property inside | +| A responsive list or `rx.breakpoints(...)` | Media-query conditions on the app's breakpoints | +| `rx.color("ruby", 9)` or a token | `var(--ruby-9)`, and `import "$/reflex-ui/colors/ruby.stylex.js"` in the module | +| Layout props (`gap`, `p`, `m`, `columns`, `direction`) | Styles, lowered like any other | +| `variant=State.kind` | One style per value of that prop, folded into a table of class names the element indexes: `sx_…_c + " " + (sx_…_0[state.kind] ?? sx_…_0d)` | +| `style=State.style_dict` | The inline `style` of the element; conditions are not available | +| `margin="0 auto"` | Its longhands | +| `"& > div": {...}`, `paddng="1em"` | A `StyleError` where the component is created | + +What follows from it: - A component is a subclass of `UIComponent` with a `styles` table. It imports - nothing: `add_custom_code` emits the declaration, which the compiler places - in whichever module renders the element (a page, or the module of a memo). + nothing: `add_custom_code` emits the declaration and `add_imports` the token + modules, which the compiler places in whichever module renders the element + (a page, an auto-memoized element, an `rx.memo` component). - A declaration is named after its content, so equal styles on many elements - are declared once per module. -- A literal `class_name` is folded into the same string. One bound to state is - joined to it at runtime. + are declared once per module and the elements share one string. +- A value bound to state is a custom property, so the declaration stays + literal. A number is given `px` unless the property takes bare numbers, as + StyleX does for a literal. The browser recomputes the style of each element + whose custom property changes: a thousand rows bound to one value that + changes cost more than they do with Emotion, which swaps one class. Rows + bound to a value of their own cost less. +- A prop bound to state gets, for each of its values, the whole value of the + properties it changes, so a value replaces the others instead of overriding + them. Props that a compound style combines, or that set the same property, + are indexed together: `table[kind]?.[size]`. A value the table does not list + gets the style of the element without the prop. +- The element's own `class_name` is joined to the constant: `"p-8 " + sx_…_c`. - A component held in state is evaluated in the browser and never reaches - StyleX: its styles fall back to an inline `style`, and a conditional style - there is a compile error. + StyleX: its literal styles fall back to an inline `style`, and anything + conditional or bound to state there is a `StyleError` that says to render + the component in a page. `base.css` declares the cascade order once: the resets (Reflex, Tailwind's `theme` and `base`), then `reflex-ui` (a component's styles merged with the element's `style`), then Tailwind's `components` and `utilities`. Unlayered CSS, such as an app's stylesheet, Emotion and Radix Themes, beats all of them. -Until the style package lands (`style/lower.py`, `style/merge.py`), a `style` -takes flat properties with literal values, and `_lower_literal_styles` in -`base.py` stands in for it. +`vite-plugin-stylex.js` hands StyleX only the statements above, not the module +around them, and compiles a module once per build although React Router +transforms it several times. A module that uses StyleX in any other way is +compiled whole. + +## Writing a component + +```python +BUTTON: ComponentStyles = { + "base": {"display": "inline-flex", "border_radius": "var(--radius-2)"}, + "variants": { + "variant": {"solid": {"color": "white"}, "soft": {"opacity": 0.8}}, + "size": {"1": {"height": "var(--space-5)"}, "2": {"height": "var(--space-6)"}}, + }, + "compound": [ + {"props": {"variant": "solid", "size": "2"}, "style": {"font_weight": 700}} + ], + "parts": { + "icon": { + "base": {"width": "1em"}, + "variants": {"size": {"2": {"width": "1.25em"}}}, + } + }, +} + + +class Button(UIComponent): + """A button.""" + + tag = "button" + + styles: ClassVar[ComponentStyles] = BUTTON + + # Which look the button has. + variant: Var[Literal["solid", "soft"]] = field(default=LiteralVar.create("solid")) + + # How large the button is. + size: Var[Literal["1", "2"]] + + # The space between the children. + gap: Var[Responsive[Literal["1", "2", "3"]]] + + # Whether the button can be pressed. + disabled: Var[bool] + + @classmethod + def create(cls, *children, **props) -> Component: + return super().create(Part.create(part="icon", tag="span"), *children, **props) +``` + +- **Props** are fields, as on any component, and reach the element as + attributes. A keyword argument that is not a field, an event trigger, or a + `data_*` or `aria_*` attribute is a CSS property, and an unknown one is an + error: `rx.ui.button: unknown CSS property "paddng". Did you mean "padding"?` +- **Variants**: a field named in `variants` or in the `props` of a `compound` + style selects styles and is not rendered as an attribute. Its default is the + default of the field. Bound to state, it is indexed in the browser. +- **Layout props**: a field named after one of `LAYOUT_PROPS` (`p`, `m`, `gap`, + `columns`, `direction`…) is lowered to styles before the element's own, and + is not rendered either. Declare only those the component should take: on a + component without a `columns` field, `columns` is the CSS property. +- **Parts**: an inner element is a `Part` named after an entry of `parts`, + created as a child of the component or of another part. It reads the props + of the component, takes no styles of its own, and is a `StyleError` anywhere + else. Subclass `Part` for an inner element with fields of its own. +- **Order**: base, variants, compound styles, layout props, the styles of the + app for the component (`rx.App(style={Button: {...}})`), then the element's + `style` with its CSS keyword arguments written over it key by key, as in any + Reflex component. +- The stubs type `style` as `Sequence[StyleProps] | StyleProps | + Var[Mapping[str, Any]] | Breakpoints` through `UIComponent._pyi_overwrite_types`, + so a misspelt property or keyword in a `style` is a type error. Keyword + arguments stay open, as `data_*` and `aria_*` come through them: a misspelt + one is caught by the compile. ## Styles @@ -103,6 +205,9 @@ the style objects StyleX compiles. Nothing in it depends on a component. of the element with every prop known at compile time resolved, `dynamic` alternatives for the props bound to state, and the `Merged` of each part. The table is lowered once and kept by identity, so it is a module constant. +- `emit(merged)` returns an `Emitted`: the statements the module declares, the + constant and the lookups that give the element its class names, the custom + properties of its inline style, and the modules to import. Both results are hashable and equal when they compile to the same declarations. Errors are `StyleError`s that start with the display name passed @@ -130,6 +235,13 @@ Styles merge by property and the last one wins: base, variants, compound styles, layout props, then the user's style. A style that sets a property only under a condition, as a `_hover` block does, keeps the earlier value everywhere else; one that sets it outright replaces the earlier conditions too. +`style` may be a list of styles, each merged over the ones before it. + +StyleX silently drops `border`, `border_top` and its siblings, `background` +and `animation`, which is why the first two are always split and the third is +refused. A split needs the value while compiling, so `background=State.color` +is an error that says to bind `background_color`, and a `background` with more +than a color or an image is one that names its longhands. ## Working on it diff --git a/packages/reflex-components-ui/js/src/vite-plugin-stylex.js b/packages/reflex-components-ui/js/src/vite-plugin-stylex.js index 2e0688c07f0..57a0ddb90d6 100644 --- a/packages/reflex-components-ui/js/src/vite-plugin-stylex.js +++ b/packages/reflex-components-ui/js/src/vite-plugin-stylex.js @@ -12,6 +12,13 @@ // stylesheet that is gone. // - React Router renders the document itself, so nothing loads the module // through which StyleX delivers the styles while developing. +// - React Router builds a route module several times, for the client, for the +// server and for reading its exports, and StyleX compiles it with Babel +// each time. A build compiles each module once and reuses the result. +// - StyleX compiles a module by parsing and printing all of it with Babel, +// which costs more than the rest of the build spends on a page. The Reflex +// compiler writes the styles of a module as statements of their own, so +// only those are handed to StyleX, and the page around them is left as it is. import { basename } from "node:path"; @@ -32,9 +39,12 @@ const CLIENT_ENTRY = /\/app\/entry\.client\.[jt]sx?$/; * @property {"serve" | "build"} [apply] * @property {(this: any, outputOptions: unknown, bundle: Bundle) => void} [generateBundle] * @property {(chunk: { moduleIds: string[] }) => string | void} [augmentChunkHash] - * @property {(code: string, id: string) => string | null} [transform] + * @property {(this: any, code: string, id: string) => any} [transform] * @property {() => string} [__stylexCollectCss] Internal to the unplugin: the * stylesheet of every style compiled so far. + * @property {() => { rulesById: Map }} [__stylexGetSharedStore] + * Internal to the unplugin: the styles of every module compiled so far, which + * every plugin of the process collects from. */ /** @@ -84,6 +94,99 @@ function keepRecordedAssets(plugin) { }; } +// The import and the statements the Reflex compiler writes for the styles of a +// module (`reflex_components_ui.style.emit`): each on a line of its own, named +// after its content. +const STYLEX_IMPORT = 'import * as stylex from "@stylexjs/stylex"'; +const DECLARATION = /^const sx_[0-9a-f]{10}\w* = .*;$/gm; + +/** + * Hand StyleX the styles of a module without the module around them. + * + * @param {VitePlugin} plugin A plugin of the StyleX unplugin. + * @returns {VitePlugin} The plugin, its `transform` compiling the statements + * that declare styles and leaving the rest of the module untouched. A + * module that uses StyleX anywhere else is compiled whole. + */ +function compileDeclarations(plugin) { + const transform = plugin.transform; + if (typeof transform !== "function") return plugin; + return { + ...plugin, + async transform(code, id) { + const declarations = code.match(DECLARATION); + const rest = declarations + ? code.replace(STYLEX_IMPORT, "").replace(DECLARATION, "") + : code; + if (!declarations || /\bstylex\b/.test(rest)) + return transform.call(this, code, id); + const result = await transform.call( + this, + `${STYLEX_IMPORT};\n${declarations.join("\n")}`, + id, + ); + const [first, ...compiled] = String(result?.code).split("\n"); + // Not the module that was handed over: compile the whole one instead. + if (first !== `${STYLEX_IMPORT};`) return transform.call(this, code, id); + let placed = false; + return { + code: code.replace(DECLARATION, () => { + if (placed) return ""; + placed = true; + return compiled.join("\n"); + }), + map: null, + }; + }, + }; +} + +// What StyleX made of each module of this process: the compiled module and +// the styles found in it, by the file and its source. Every plugin of a build +// shares it, as React Router creates more than one. +/** @type {Map>} */ +const compiled = new Map(); + +/** + * Compile a module once in a build, however often it is transformed. + * + * @param {VitePlugin} plugin A plugin of the StyleX unplugin. + * @returns {VitePlugin} The plugin, its `transform` reusing earlier results. + */ +function compileOnce(plugin) { + const transform = plugin.transform; + const store = plugin.__stylexGetSharedStore; + if (typeof transform !== "function" || typeof store !== "function") + return plugin; + return { + ...plugin, + transform(code, id) { + // A development server compiles a module again when it changes, and + // the unplugin skips a module that does not mention StyleX. + if (this?.meta?.watchMode || !code.includes("stylex")) + return transform.call(this, code, id); + const key = `${id.split("?")[0]}\0${code}`; + const earlier = compiled.get(key); + if (earlier) { + return earlier.then(({ result, rules }) => { + // The styles are collected under the name of each module. + const { rulesById } = store(); + if (rules) rulesById.set(id, rules); + else rulesById.delete(id); + return result; + }); + } + const first = Promise.resolve(transform.call(this, code, id)).then( + (result) => ({ result, rules: store().rulesById.get(id) }), + ); + compiled.set(key, first); + // A failed compile is reported by each transform, not remembered. + first.catch(() => compiled.delete(key)); + return first.then(({ result }) => result); + }, + }; +} + /** * Compile the StyleX styles of a Reflex app into one of its stylesheets. * @@ -110,7 +213,10 @@ export default function stylex(stylesheet, options) { ); } return [ - ...plugins.map(keepRecordedAssets), + ...plugins + .map(keepRecordedAssets) + .map(compileDeclarations) + .map(compileOnce), { name: "reflex-ui:stylex-hash", apply: "build", diff --git a/packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js b/packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js index ab017011427..bea171cdef4 100644 --- a/packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js +++ b/packages/reflex-components-ui/js/tests/vite-plugin-stylex.test.js @@ -16,21 +16,106 @@ const OPTIONS = { }; // A page module as the Reflex compiler emits it: one declaration per distinct -// style, and a literal `class_name` carried inside the `stylex.props` call. +// style, each followed by the constant that holds its class names, which an +// element joins with its own. const PAGE = `import * as stylex from "@stylexjs/stylex" import {jsx} from "@emotion/react" const sx_b26ac4fb71 = stylex.create({ s: {"boxSizing": "border-box", "display": "block"} }); +const sx_b26ac4fb71_c = stylex.props(sx_b26ac4fb71.s).className; const sx_f49d6b3475 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "padding": "4px"} }); +const sx_f49d6b3475_c = stylex.props(sx_f49d6b3475.s).className; export default function Component() { - return jsx("main",{},jsx("div",{...stylex.props(sx_b26ac4fb71.s)},"hello"),jsx("div",{...stylex.props(sx_f49d6b3475.s, { $$css: true, className: "p-8" })},"padded")) + return jsx("main",{},jsx("div",{className:sx_b26ac4fb71_c},"hello"),jsx("div",{className:"p-8" + " " + sx_f49d6b3475_c},"padded")) +} +`; + +// What the build makes of it: the declarations become strings, there is no +// call into StyleX, and the rest of the module is as it was written. +const COMPILED_PAGE = `import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" + +const sx_b26ac4fb71_c = { + className: "x9f619 x1lliihq" +}.className; +const sx_f49d6b3475_c = { + className: "x9f619 x1lliihq xfawy5m" +}.className; + + + + +export default function Component() { + return jsx("main",{},jsx("div",{className:sx_b26ac4fb71_c},"hello"),jsx("div",{className:"p-8" + " " + sx_f49d6b3475_c},"padded")) +} +`; + +// A module whose bound prop indexes the class names of its values. +const VARIANT = `import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" + +const sx_0123456789 = stylex.create({ s: {"padding": "4px", "width": "var(--v0)"}, a0_0: {"color": "white"}, a0_1: {"color": "black", "opacity": 0.5}, a0: {"color": "black"} }); +const sx_0123456789_c = stylex.props(sx_0123456789.s).className; +const sx_0123456789_0 = { __proto__: null, "solid": stylex.props(sx_0123456789.a0_0).className, "soft": stylex.props(sx_0123456789.a0_1).className }; +const sx_0123456789_0d = stylex.props(sx_0123456789.a0).className; + +export default function Component({kind, width}) { + return jsx("div",{className:sx_0123456789_c + " " + (sx_0123456789_0[kind] ?? sx_0123456789_0d),style:({ "--v0": (width) ?? "initial" })},"hello") +} +`; + +const COMPILED_VARIANT = `import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" + +const sx_0123456789_c = { + className: "xfawy5m xw9a5fd" +}.className; +const sx_0123456789_0 = { + __proto__: null, + "solid": { + className: "x1awj2ng" + }.className, + "soft": { + className: "x1mqxbix xbyyjgo" + }.className +}; +const sx_0123456789_0d = { + className: "x1mqxbix" +}.className; + + + + +export default function Component({kind, width}) { + return jsx("div",{className:sx_0123456789_c + " " + (sx_0123456789_0[kind] ?? sx_0123456789_0d),style:({ "--v0": (width) ?? "initial" })},"hello") +} +`; + +// A module that calls StyleX outside the statements of the Reflex compiler. +const HANDWRITTEN = `import * as stylex from "@stylexjs/stylex" +import {jsx} from "@emotion/react" + +const sx_b26ac4fb71 = stylex.create({ s: {"boxSizing": "border-box", "display": "block"} }); +const sx_b26ac4fb71_c = stylex.props(sx_b26ac4fb71.s).className; +const own = stylex.create({ root: {"padding": "4px"} }); + +export default function Component() { + return jsx("main",{...stylex.props(own.root)},jsx("div",{className:sx_b26ac4fb71_c},"hello")) } `; const COMPILED_CSS = "@layer reflex-ui.priority1{.xfawy5m{padding:4px}}@layer reflex-ui.priority2{.x9f619{box-sizing:border-box}.x1lliihq{display:block}}"; +// The chunk that links the stylesheet the styles are appended to. +const ROOT = { + moduleIds: [ + "/app/.web/app/root.jsx", + `/app/.web/styles/${STYLESHEET}.css?url`, + ], +}; + beforeEach(() => { // The unplugin keeps the styles of every build of the process. delete (/** @type {any} */ (globalThis).__stylex_unplugin_store); @@ -72,21 +157,87 @@ test("a page folds to class name strings and leaves no call into StyleX", async const plugins = stylex(STYLESHEET, OPTIONS); expect( await transform(plugins, PAGE, "/app/.web/app/routes/_index.jsx"), + ).toBe(COMPILED_PAGE); +}); + +test("a prop and a value bound to state fold to a table of class names and a custom property", async () => { + const plugins = stylex(STYLESHEET, OPTIONS); + expect( + await transform(plugins, VARIANT, "/app/.web/app/routes/_index.jsx"), + ).toBe(COMPILED_VARIANT); +}); + +test("a module that uses StyleX elsewhere is compiled whole", async () => { + const plugins = stylex(STYLESHEET, OPTIONS); + expect( + await transform(plugins, HANDWRITTEN, "/app/.web/app/own.jsx"), ).toBe(`import * as stylex from "@stylexjs/stylex"; import { jsx } from "@emotion/react"; +const sx_b26ac4fb71_c = { + className: "x9f619 x1lliihq" +}.className; export default function Component() { - return jsx("main", {}, jsx("div", { - ...{ - className: "x9f619 x1lliihq" - } - }, "hello"), jsx("div", { + return jsx("main", { ...{ - className: "x9f619 x1lliihq xfawy5m p-8" + className: "xfawy5m" } - }, "padded")); + }, jsx("div", { + className: sx_b26ac4fb71_c + }, "hello")); }`); }); +test("a build compiles a module once, for every plugin and every name it has", async () => { + const source = PAGE.replace('"padding": "4px"', '"padding": "9px"'); + const css = COMPILED_CSS.replace( + ".xfawy5m{padding:4px}", + ".xskserf{padding:9px}", + ); + // React Router builds with two sets of plugins, and names a route twice. + const first = stylex(STYLESHEET, OPTIONS); + const second = stylex(STYLESHEET, OPTIONS); + const route = "/app/.web/app/routes/once.jsx"; + /** + * @param {ReturnType} plugins + * @param {string} code + * @param {string} id + * @param {object} [context] What Vite binds the hook to. + * @returns {Promise<{ code: string }>} What the hook returns. + */ + const compile = (plugins, code, id, context = {}) => + withHook(plugins, "transform", "@stylexjs/unplugin").transform.call( + context, + code, + id, + ); + + const [client, child, server] = await Promise.all([ + compile(first, source, `${route}?__react-router-build-client-route`), + compile(second, source, route), + compile(first, source, route), + ]); + expect(client.code).toBe(COMPILED_PAGE.replace("xfawy5m", "xskserf")); + // One result: the module went through Babel once. + expect(child).toBe(client); + expect(server).toBe(client); + // The styles are collected under each name, as a compile leaves them. + const store = /** @type {any} */ (globalThis).__stylex_unplugin_store; + expect([...store.rulesById.keys()]).toEqual([ + `${route}?__react-router-build-client-route`, + route, + ]); + expect(withHook(second, "augmentChunkHash").augmentChunkHash(ROOT)).toBe(css); + + // Another source of the same file is another compile, and so is every + // transform of a development server, where a module is compiled as it changes. + const changed = await compile(first, PAGE, route); + expect(changed.code).toBe(COMPILED_PAGE); + const watching = { meta: { watchMode: true } }; + const served = await compile(first, PAGE, route, watching); + expect(served).not.toBe(changed); + expect(served.code).toBe(COMPILED_PAGE); +}); + test("the styles are appended to the stylesheet, and the chunk that links it follows the rename", async () => { const plugins = stylex(STYLESHEET, OPTIONS); await transform(plugins, PAGE, "/app/.web/app/routes/_index.jsx"); @@ -155,12 +306,7 @@ test("the chunk that links the stylesheet is named after the compiled styles", a const plugins = stylex(STYLESHEET, OPTIONS); const plugin = withHook(plugins, "augmentChunkHash"); expect(plugin.apply).toBe("build"); - const root = { - moduleIds: [ - "/app/.web/app/root.jsx", - `/app/.web/styles/${STYLESHEET}.css?url`, - ], - }; + const root = ROOT; const page = { moduleIds: [ "/app/.web/app/routes/_index.jsx", diff --git a/packages/reflex-components-ui/news/+style-compiler.feature.md b/packages/reflex-components-ui/news/+style-compiler.feature.md new file mode 100644 index 00000000000..237bb9fae2a --- /dev/null +++ b/packages/reflex-components-ui/news/+style-compiler.feature.md @@ -0,0 +1,8 @@ +`rx.ui` components take every kind of style: values bound to state, `_hover` and other condition blocks, responsive lists and `rx.breakpoints`, `rx.color`, shorthands, keyword arguments, and a whole style dict from state. A component's variant props can be bound to state too. All of it compiles to class names, so no page ships a styling runtime. `style` is typed in the stubs, and a misspelt property is an error that names the fix: + +```python +rx.ui.box("hello", width=State.width, _hover={"color": rx.color("ruby", 9)}) +rx.ui.box( + paddng="1em" +) # rx.ui.box: unknown CSS property "paddng". Did you mean "padding"? +``` diff --git a/packages/reflex-components-ui/src/reflex_components_ui/base.py b/packages/reflex-components-ui/src/reflex_components_ui/base.py index 8e8623927ea..1766718059c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -2,100 +2,106 @@ from __future__ import annotations -from collections.abc import Mapping -from typing import Any, ClassVar, TypedDict +import functools +import json +from collections.abc import Iterator, Mapping, Sequence +from typing import Any, ClassVar -from reflex_base.components.component import Component +from reflex_base import breakpoints +from reflex_base.components.component import BaseComponent, Component from reflex_base.components.dynamic import is_rendering_dynamic_component from reflex_base.components.tags import CommonTag +from reflex_base.constants.compiler import SPECIAL_ATTRS from reflex_base.plugins import get_plugin +from reflex_base.style import media_query from reflex_base.utils import format from reflex_base.utils.exceptions import ConfigError from reflex_base.utils.imports import ImportDict, ImportVar from reflex_base.vars.base import Var -from reflex_base.vars.number import LiteralNumberVar from reflex_base.vars.sequence import LiteralStringVar from reflex_components_ui.plugin import UIPlugin -from reflex_components_ui.style.emit import ( - LoweredStyle, - StyleXStyle, - UnsupportedStyleError, - emit, - inline, - props_call, +from reflex_components_ui.style import ( + LAYOUT_PROPS, + ComponentStyles, + Merged, + StyleError, + merge, ) +from reflex_components_ui.style.emit import Emitted, emit, inline +from reflex_components_ui.style.lower import suggest MISSING_PLUGIN_ERROR = ( "rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins." ) -# The styles of an element. The generated TypedDict of step 8a replaces it. -StyleProps = Mapping[str, Any] +# What starts a keyword argument that is never a style: an event trigger, or +# an attribute that is passed to the element as it is. +_NOT_A_STYLE = ("on_", *SPECIAL_ATTRS) -class CompoundStyle(TypedDict): - """Styles for a combination of props. +def _consulted(styles: Mapping[str, Any]) -> dict[str, None]: + """Find the props a style table reads. - Attributes: - when: The value each prop must have, by prop name. - style: The styles applied when every prop matches. + Args: + styles: The style table of a component, or of one of its parts. + + Returns: + The names of the props, as the keys of a dict to keep their order. """ + props: dict[str, None] = dict.fromkeys(styles.get("variants", ())) + for compound in styles.get("compound", ()): + props.update(dict.fromkeys(compound["props"])) + for part in styles.get("parts", {}).values(): + props.update(_consulted(part)) + return props - when: dict[str, Any] - style: StyleProps +def _responsive(style: breakpoints.Breakpoints) -> dict[str, Any]: + """Read a whole style given per breakpoint as blocks under media queries. -class ComponentStyles(TypedDict, total=False): - """The look of a component. + Args: + style: The styles of each breakpoint. - Attributes: - base: The styles of every instance. - variants: The styles of a prop value: prop name, then prop value. - compound: The styles of a combination of props. - parts: The look of inner elements, such as a switch thumb, by name. + Returns: + One style: what applies everywhere, then a block per breakpoint. """ - - base: StyleProps - variants: dict[str, dict[str, StyleProps]] - compound: list[CompoundStyle] - parts: dict[str, ComponentStyles] + names = breakpoints.breakpoint_names + blocks: dict[str, Any] = {} + for breakpoint, block in style.items(): + if breakpoint == "initial": + blocks = {**block, **blocks} + else: + width = ( + breakpoints.breakpoints_values[names.index(breakpoint)] + if breakpoint in names + else breakpoint + ) + blocks[media_query(width)] = block + return blocks -def _lower_literal_styles(component: UIComponent) -> LoweredStyle: - """Merge the base styles of a component with its literal ``style``. +def _combine(styles: list[Mapping[str, Any]]) -> Mapping[str, Any]: + """Write the styles of an element over each other, in the order given. - A stand-in: the ``lower`` and ``merge`` of the style package replace it, - and bring variants, nested blocks, responsive values and shorthands. + A key replaces the same key, as it does in the ``style`` of any Reflex + component, and moves to the end: what is written last wins over a + shorthand or a longhand written before it. Args: - component: The component to style. + styles: The styles as written, at least one. Returns: - The lowered style of the component's element, the user's style last. - - Raises: - UnsupportedStyleError: If the component or its style needs what only - the real lowering provides. + One style holding them all. """ - name = component._display_name() - styles = component.styles - if "variants" in styles or "compound" in styles: - msg = f"{name}: variant and compound styles are not compiled yet." - raise UnsupportedStyleError(msg) - lowered = dict(styles.get("base", {})) - for prop, value in component.style.items(): - if isinstance(value, (LiteralStringVar, LiteralNumberVar)): - value = value._var_value - elif not isinstance(value, Var): - msg = ( - f'{name}: the style "{prop}" is a nested block or a list, which ' - "rx.ui components cannot compile yet. Use flat properties with " - "literal values." - ) - raise UnsupportedStyleError(msg) - lowered[prop] = value - return lowered + if len(styles) == 1: + return styles[0] + combined = dict(styles[0]) + for style in styles[1:]: + for key, value in style.items(): + combined.pop(key, None) + combined[key] = value + return combined class UIComponent(Component): @@ -103,6 +109,11 @@ class UIComponent(Component): No library is imported: the element's styles are declared in the module that renders it, where the StyleX compiler folds them into class names. + + A subclass declares its props as fields. A prop its style table reads + selects a variant, and a prop named after a layout prop, such as ``gap``, + is lowered to styles: neither reaches the element as an attribute. Any + other keyword argument is a CSS property. """ tag = "div" @@ -112,7 +123,19 @@ class UIComponent(Component): # The component's own look. styles: ClassVar[ComponentStyles] = {} + # How the stubs type the style: the properties and keywords of CSS. + _pyi_overwrite_types: ClassVar[dict[str, str]] = { + "style": ( + "Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] " + "| Breakpoints | None" + ), + } + _pyi_imports: ClassVar[dict[str, list[str]]] = { + "reflex_components_ui.style": ["StyleProps"], + } + @classmethod + @functools.cache def _display_name(cls) -> str: """Get the name an app refers to the component by. @@ -121,33 +144,168 @@ def _display_name(cls) -> str: """ return f"rx.ui.{format.to_snake_case(cls.__name__)}" - def _stylex(self) -> StyleXStyle | None: - """Get the StyleX source of the element's style. + @classmethod + @functools.cache + def _style_props(cls) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Get the props that are read as styles rather than rendered. Returns: - The declaration of the style, or None when the element has none. + The fields that are layout props, and the props the style table + selects variants by. + """ + fields = cls.get_fields() + return ( + tuple(sorted(LAYOUT_PROPS.intersection(fields))), + tuple(_consulted(cls.styles)), + ) + + def _post_init(self, *args, **kwargs): + """Initialize the component, taking its styles out of its props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. Raises: - ConfigError: If the plugin that compiles the styles is not configured. + StyleError: If the style is not a dict of styles, a list of them or + a Var, or cannot be compiled. """ - if get_plugin(UIPlugin) is None: - raise ConfigError(MISSING_PLUGIN_ERROR) - return emit(_lower_literal_styles(self), self._display_name()) + fields = self.get_fields() + triggers = self.get_event_triggers() + layout_props, _ = self._style_props() + written: list[Mapping[str, Any]] = [] + inline = None + style = kwargs.pop("style", None) + if style is not None: + for item in style if isinstance(style, (list, tuple)) else (style,): + if isinstance(item, Var): + inline = item + elif isinstance(item, breakpoints.Breakpoints): + written.append(_responsive(item)) + elif isinstance(item, Mapping): + written.append(item) + else: + msg = ( + f"{self._display_name()}: style must be a dict of styles, " + f"a list of them or a Var, not {type(item).__name__}." + ) + raise StyleError(msg) + # Keyword arguments that are not props are CSS properties. + css = [ + key + for key in kwargs + if key not in fields + and key not in triggers + and not key.startswith(_NOT_A_STYLE) + ] + if css: + written.append({key: kwargs.pop(key) for key in css}) + self._styles: list[Any] = [_combine(written)] if written else [] + if inline is not None: + self._styles.append(inline) + self._layout = ( + {prop: kwargs.pop(prop) for prop in layout_props if prop in kwargs} + if layout_props + else None + ) + super()._post_init(*args, **kwargs) + self._merge_styles() + + def _merge_styles(self) -> None: + """Merge the style table with the styles of this element. + + The styles apply in this order: the table, the layout props, the + styles of the app for the component, then the element's own. + """ + cls = type(self) + name = cls._display_name() + _, variants = cls._style_props() + styles = self._styles + if self.style: + styles = [self.style, *styles] + merged = self._merged = merge( + name, + cls.styles, + {prop: getattr(self, prop, None) for prop in variants} + if variants + else None, + styles or None, + self._layout, + ) + self._emitted_styles = None + if merged.parts: + _bind_parts(self.children, merged.parts, name) + + def _add_style_recursive(self, style: Any, theme: Component | None = None): + """Add the styles of the app to the component and its children. + + Args: + style: A dict from component to styling. + theme: The theme to apply. + + Returns: + The component with the additional style. + """ + result = super()._add_style_recursive(style, theme) + if self.style: + self._merge_styles() + return result + + def _emit(self) -> Emitted: + """Get the StyleX source of the element's styles. + + Returns: + What the module that renders the element declares for it. + """ + emitted = self._emitted_styles + if emitted is None: + emitted = self._emitted_styles = emit(self._element_styles()) + return emitted + + def _element_styles(self) -> Merged: + """Get the merged styles of the element. + + Returns: + The style table merged with the styles of this element. + """ + return self._merged + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in this component, those of its styles included. + + Args: + include_children: Whether to include Vars from children. + ignore_ids: The ids to ignore. + + Yields: + Each var referenced by the component. + """ + yield from super()._get_vars(include_children, ignore_ids) + yield from self._emit().vars def add_imports(self) -> ImportDict: - """Import StyleX, which the build compiles away. + """Import StyleX, which the build compiles away, and the CSS of tokens. Returns: - The import, or nothing for code that never reaches the build. + The imports, or nothing for code that never reaches the build. """ if is_rendering_dynamic_component(): return {} - # The plugin installs it as a development dependency. - return { - "@stylexjs/stylex": ImportVar( + emitted = self._emit() + imports: ImportDict = {} + if emitted.declaration is not None: + # The plugin installs it as a development dependency. + imports["@stylexjs/stylex"] = ImportVar( tag="*", alias="stylex", is_default=True, install=False ) - } + if emitted.imports: + # Imported for the CSS that defines the custom properties. + imports[""] = [ + ImportVar(tag=module, install=False) for module in emitted.imports + ] + return imports def add_custom_code(self) -> list[str]: """Declare the element's style in the module that renders it. @@ -155,11 +313,16 @@ def add_custom_code(self) -> list[str]: Returns: The ``stylex.create`` declaration, or nothing for code that never reaches the build. + + Raises: + ConfigError: If the plugin that compiles the styles is not configured. """ if is_rendering_dynamic_component(): return [] - style = self._stylex() - return [] if style is None else [style.declaration] + if get_plugin(UIPlugin) is None: + raise ConfigError(MISSING_PLUGIN_ERROR) + declaration = self._emit().declaration + return [] if declaration is None else [declaration] def _get_style(self) -> dict: """Get the props that carry the style: none, as ``_render`` adds them. @@ -169,6 +332,15 @@ def _get_style(self) -> dict: """ return {} + def _exclude_props(self) -> list[str]: + """Keep the props that are read as styles off the element. + + Returns: + The layout props and the props that select a variant. + """ + layout_props, variants = self._style_props() + return [*layout_props, *variants] + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the element with its style. @@ -176,46 +348,133 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: props: The props to render (if None, then use get_props). Returns: - The tag, with a ``stylex.props`` spread, or with an inline style in - code that never reaches the build. + The tag, with the class names of its style, or with an inline + style in code that never reaches the build. + + Raises: + ConfigError: If the plugin that compiles the styles is not configured. """ tag = super()._render(props) if is_rendering_dynamic_component(): - style = inline(_lower_literal_styles(self), self._display_name()) + style = inline(self._element_styles(), self._display_name()) return tag.add_props(style=style) if style else tag - style = self._stylex() - if style is None: - return tag - return _add_stylex_props(tag, style.ref) + if get_plugin(UIPlugin) is None: + raise ConfigError(MISSING_PLUGIN_ERROR) + return _add_styles(tag, self._emit()) + + +class Part(UIComponent): + """An inner element of a component, styled by a part of its style table. + + A component creates it as one of its children, or as a child of another + part, and names the part: ``Part.create(part="thumb", tag="span")``. + """ + + def _post_init(self, *args, **kwargs): + """Initialize the part, which takes its styles from its component. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + + Raises: + StyleError: If the part is given styles of its own. + """ + self._part: str = kwargs.pop("part") + super()._post_init(*args, **kwargs) + if self._styles or self._layout: + msg = ( + f'{self._display_name()}: the part "{self._part}" takes its ' + "styles from the style table of its component. Style it there." + ) + raise StyleError(msg) + + def _merge_styles(self) -> None: + """Wait for the component the part belongs to, which has its styles.""" + self._merged = getattr(self, "_merged", None) + self._emitted_styles = None + + def _element_styles(self) -> Merged: + """Get the styles the component of the part has for it. + + Returns: + The merged styles of the part. + + Raises: + StyleError: If no component has claimed the part. + """ + if self._merged is None: + msg = ( + f'{self._display_name()}: the part "{self._part}" is not in a ' + "component whose style table has it. Create it as a child of " + "its component, or of another part of it." + ) + raise StyleError(msg) + return self._merged -def _add_stylex_props(tag: CommonTag, ref: str) -> CommonTag: - """Give a tag the class names of a style, beside its own. +def _bind_parts( + children: Sequence[BaseComponent], parts: Mapping[str, Merged], name: str +) -> None: + """Give the parts among the children of a component their styles. + + Args: + children: The children of the component, or of one of its parts. + parts: The merged styles of each part of the component. + name: The display name of the component, for error messages. + + Raises: + StyleError: If the style table has no such part. + """ + for child in children: + if isinstance(child, Part) and child._merged is None: + merged = parts.get(child._part) + if merged is None: + msg = ( + f'{name}: its style table has no part "{child._part}".' + f"{suggest(child._part, parts)}" + ) + raise StyleError(msg) + child._merged = merged + _bind_parts(child.children, parts, name) + + +def _add_styles(tag: CommonTag, emitted: Emitted) -> CommonTag: + """Give a tag the class names and custom properties of its styles. Args: tag: The rendered element. - ref: The expression naming the style. + emitted: The StyleX source of its styles. Returns: - The tag with a ``stylex.props`` spread, or with one ``className`` - expression when its own class names come from state. + The tag with one ``className`` expression: the constants of its + styles, beside the class names it has of its own. """ + if emitted.variables: + entries = list(emitted.variables) + if emitted.inline is not None: + entries.append(f"...{emitted.inline!s}") + tag = tag.add_props(style=Var(f"({{ {', '.join(entries)} }})")) + elif emitted.inline is not None: + tag = tag.add_props(style=emitted.inline) + if emitted.classes is None and not emitted.lookups: + return tag + names = [] + literal = "" + var_data = None class_name = tag.props.get("className") - if class_name is None: - return tag.set(special_props=[*tag.special_props, Var(props_call((ref,)))]) if isinstance(class_name, LiteralStringVar): - # A spread would replace the attribute, so both fold into one string. - return tag.remove_props("className").set( - special_props=[ - *tag.special_props, - Var(props_call((ref,), class_name._var_value)), - ] - ) + if class_name._var_value: + literal = f"{json.dumps(class_name._var_value + ' ')} + " + elif class_name is not None: + # Parenthesized: the expression may be a conditional. + names.append(f"({class_name!s})") + var_data = class_name._get_all_var_data() + if emitted.classes is not None: + names.append(emitted.classes) + names.extend(emitted.lookups) return tag.add_props( class_name=Var( - # Parenthesized: the expression may be a conditional. - f'({class_name!s}) + " " + {props_call((ref,))}.className', - _var_type=str, - _var_data=class_name._get_all_var_data(), + literal + ' + " " + '.join(names), _var_type=str, _var_data=var_data ) ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/box.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/box.py index d3cf17be3a1..b5367828e41 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/box.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/box.py @@ -4,7 +4,8 @@ from typing import ClassVar -from reflex_components_ui.base import ComponentStyles, UIComponent +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.box import BOX diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/emit.py b/packages/reflex-components-ui/src/reflex_components_ui/style/emit.py index 378fdc00f90..0bc89d15b23 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/style/emit.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/emit.py @@ -1,14 +1,21 @@ -"""Turn a lowered style into the StyleX source the compiler places in a module. - -A lowered style is a StyleX style object: a mapping from a camelCase CSS -property to a literal, or to a condition map such as -``{"default": "red", ":hover": "blue"}``. +"""Turn the merged styles of an element into the StyleX source of its module. StyleX folds ``stylex.props(...)`` into a ``className`` string only when the -style is declared in the module that renders the element, so every distinct -style becomes a declaration of its own, named after its content. The compiler -deduplicates custom code by its text: elements that share a style share one -declaration, in whichever module each of them is rendered. +style is declared in the module that makes the call and the call has nothing +in it that is known at runtime. Everything here is shaped to keep it that way, +so that no element needs the StyleX runtime: + +- Every distinct style becomes a declaration of its own, named after its + content, followed by a constant that holds its folded class names. The + compiler deduplicates custom code by its text: elements that share a style + share one declaration and one string, in whichever module renders them. +- A value bound to state is declared as ``var(--vN)`` and the element sets + that custom property in its inline ``style``, so the declaration stays + literal. +- A variant prop bound to state gets one style per value, each holding the + whole value of the properties the prop changes. They are folded into a + table of class names at module level, which the element indexes with the + value of the prop. """ from __future__ import annotations @@ -16,154 +23,439 @@ import dataclasses import hashlib import json -from collections.abc import Mapping -from typing import TypeAlias, cast +from typing import Any -from reflex_base.utils.exceptions import ReflexError +from reflex_base.utils.types import safe_issubclass from reflex_base.vars.base import Var -# A literal, or the value of a property under each condition. -LoweredValue: TypeAlias = "str | int | float | Mapping[str, LoweredValue]" -# What `lower` produces and StyleX compiles: camelCase property to value. -LoweredStyle: TypeAlias = Mapping[str, LoweredValue] +from reflex_components_ui.style.lower import StyleError +from reflex_components_ui.style.merge import Alternatives, Merged -# The key under which a declaration holds its style. +# The key under which a declaration holds the style every instance has. _KEY = "s" - -class UnsupportedStyleError(ReflexError, TypeError): - """Raised when an rx.ui component has a style that cannot be compiled.""" +# Stands for the name of a declaration until its content gives it one. JSON +# escapes the character, so no style can hold it. +_NAME = "\0" + +# The properties whose numbers are not lengths, as StyleX lists them: it +# appends "px" to a literal number of any other property, and so does the +# value of a custom property that stands for one. +UNITLESS: frozenset[str] = frozenset(( + "WebkitLineClamp", + "animationIterationCount", + "aspectRatio", + "borderImageOutset", + "borderImageSlice", + "borderImageWidth", + "columnCount", + "counterReset", + "counterSet", + "fillOpacity", + "flex", + "flexGrow", + "flexOrder", + "flexShrink", + "floodOpacity", + "fontSizeAdjust", + "fontWeight", + "gridArea", + "gridColumn", + "gridColumnEnd", + "gridColumnStart", + "gridRow", + "gridRowEnd", + "gridRowStart", + "hyphenateLimitChars", + "lineClamp", + "lineHeight", + "maskBorderOutset", + "maskBorderSlice", + "maskBorderWidth", + "mathDepth", + "opacity", + "order", + "orphans", + "rotate", + "scale", + "shapeImageThreshold", + "stopOpacity", + "strokeDasharray", + "strokeDashoffset", + "strokeMiterlimit", + "strokeOpacity", + "strokeWidth", + "tabSize", + "widows", + "zIndex", + "zoom", +)) + +_NOT_RENDERED_IN_PAGE = ( + "which a component rendered from state cannot apply: its code is evaluated " + "in the browser and never reaches the StyleX compiler." +) +_RENDER_IN_PAGE = "render the component in a page and show it with rx.cond." @dataclasses.dataclass(frozen=True, slots=True) -class StyleXStyle: - """The StyleX source of one style. +class Emitted: + """The StyleX source of the styles of one element. Attributes: - declaration: The module-level ``stylex.create`` statement. - ref: The expression naming the style, an argument of ``stylex.props``. + declaration: The module-level statements that declare the styles and + fold them into class names, or None when the element has none. + classes: The constant holding the class names of the style every + instance has, or None when there is none. + lookups: Expressions that each give the class names one group of + state-bound props selects. + variables: The custom properties the element sets in its inline + style, as the entries of an object literal. + inline: A Var holding a whole dict of styles, spread into the inline + style after the custom properties. + imports: The modules to import for their CSS, sorted. + vars: Every Var the expressions above read, for the hooks and imports + they bring. """ - declaration: str - ref: str + declaration: str | None = None + classes: str | None = None + lookups: tuple[str, ...] = () + variables: tuple[str, ...] = () + inline: Var | None = None + imports: tuple[str, ...] = () + vars: tuple[Var, ...] = () + + +_NOTHING = Emitted() +# The name of every literal declaration emitted so far, by its source. +_NAMES: dict[str, str] = {} -def _check_value( - value: object, prop: str, component: str, conditions: tuple[str, ...] -) -> None: - """Fail on a value StyleX cannot compile to a class. + +def _name(source: str) -> str: + """Name a declaration after its source. + + Named after the source rather than the styles: two declarations of one + name in a module would not parse. Args: - value: The value of the property, or of one of its conditions. - prop: The style property the value belongs to. - component: The name of the component, for the error message. - conditions: The conditions the value is nested under. + source: What the declaration holds. - Raises: - UnsupportedStyleError: If the value is bound to state or is not a - literal or a condition map. + Returns: + The name, the same for the same source. """ - if isinstance(value, Mapping): - for condition, nested in value.items(): - _check_value(nested, prop, component, (*conditions, condition)) - return - # A bool is an int to isinstance, and no CSS value. - if isinstance(value, (str, int, float)) and not isinstance(value, bool): - return - where = f'"{prop}"' + "".join(f' under "{c}"' for c in conditions) - if isinstance(value, Var): - msg = ( - f"{component}: the style {where} is bound to state, which rx.ui " - "components cannot compile yet. Give it a literal value, or set it " - "from state with a class_name." - ) - else: - msg = ( - f"{component}: the style {where} is {value!r}, a " - f"{type(value).__name__}. Use a string or a number, or a mapping " - 'from condition to value such as {"default": "red", ":hover": "blue"}.' - ) - raise UnsupportedStyleError(msg) + name = _NAMES.get(source) + if name is None: + name = _NAMES[source] = "sx_" + hashlib.sha256(source.encode()).hexdigest()[:10] + return name -def emit(style: LoweredStyle, component: str) -> StyleXStyle | None: - """Emit the StyleX declaration of a lowered style. +class _Variables: + """The custom properties that carry the state-bound values of an element. + + Attributes: + names: The ``var(...)`` reference of each value, by the Var and + whether its numbers are lengths. + entries: The entries of the inline style that set them. + vars: The Vars the entries read. + """ + + __slots__ = ("entries", "names", "vars") + + def __init__(self): + """Start with no custom property.""" + self.names: dict[tuple[Any, bool], str] = {} + self.entries: list[str] = [] + self.vars: list[Var] = [] + + def reference(self, var: Var, prop: str) -> str: + """Give a state-bound value a custom property. + + Args: + var: The value. + prop: The camelCase property it is the value of. + + Returns: + The literal that stands for the value in the declaration. + """ + lengths = prop not in UNITLESS and not prop.startswith("--") + var_type = var._var_type + if safe_issubclass(var_type, str): + lengths = False + key = (var._hash_key(), lengths) + reference = self.names.get(key) + if reference is None: + name = f"--v{len(self.names)}" + reference = self.names[key] = f"var({name})" + # Parenthesized: the expression may be a conditional. + expression = f"({var!s})" + if lengths and (var_type is int or var_type is float): + expression = f'{expression} + "px"' + else: + if lengths: + expression = ( + f'((v) => typeof v === "number" ? v + "px" : v){expression}' + ) + # An unset value must not pick up the property of an ancestor. + expression = f'{expression} ?? "initial"' + self.entries.append(f'"{name}": {expression}') + self.vars.append(var) + return reference + + def literal(self, value: Any, prop: str) -> Any: + """Replace the Vars of a lowered value with their custom properties. + + Args: + value: The lowered value of a property. + prop: The camelCase property. + + Returns: + The value as StyleX compiles it. + """ + cls = value.__class__ + if cls is str or cls is int or cls is float or value is None: + return value + if cls is dict: + return { + condition: self.literal(item, prop) for condition, item in value.items() + } + return self.reference(value, prop) + + +def _lookup(table: dict[str, Any], depth: int) -> str: + """Write the table that the values of a group of props index. Args: - style: The lowered style of one element. - component: The name of the component, for error messages. + table: The class names of each value of the first prop, or the table + of the props after it. + depth: How many props are left to index by. Returns: - The declaration and the expression that refers to it, or None when the - style is empty. + An object literal without a prototype, so that only its own keys are + found. + """ + entries = ", ".join([ + f"{json.dumps(value)}: {item if depth == 1 else _lookup(item, depth - 1)}" + for value, item in table.items() + ]) + return f"{{ __proto__: null, {entries} }}" - Raises: - UnsupportedStyleError: If a value is bound to state or is not a literal. + +def _classes(key: str) -> str: + """Write the expression StyleX folds into the class names of a style. + + Args: + key: The key of the style in its declaration. + + Returns: + The expression, which is a string once the module is compiled. """ - if not style: - return None - for prop, value in style.items(): - _check_value(value, prop, component, ()) - source = json.dumps(style, ensure_ascii=False) - # Named after the source rather than the mapping: two declarations of one - # name in a module would not parse. - name = "sx_" + hashlib.sha256(source.encode()).hexdigest()[:10] - return StyleXStyle( - declaration=f"const {name} = stylex.create({{ {_KEY}: {source} }});", - ref=f"{name}.{_KEY}", - ) + return f"stylex.props({_NAME}.{key}).className" + + +def _alternatives( + alternatives: Alternatives, + index: int, + static: dict[str, Any], + variables: _Variables, + styles: dict[str, Any], + tables: list[str], +) -> str: + """Declare the styles of a group of state-bound props. + + Each value gets the whole value of every property the group changes, so + that its class names replace those of the other values rather than + override them. The properties are taken out of the style every instance + has. + + Args: + alternatives: The styles the values of the props select. + index: The position of the group among those of the element. + static: The style of the element without the props, changed in place. + variables: The custom properties of the element. + styles: The styles of the declaration, added to in place. + tables: The statements that follow the declaration, added to in place. + + Returns: + The expression that gives the class names of the current values. + """ + shared = { + prop: static.pop(prop) + for change in alternatives.values.values() + for prop in change.style + if prop in static + } + table: dict[str, Any] = {} + for position, (combination, change) in enumerate(alternatives.values.items()): + style = dict(shared) + for prop, value in change.style.items(): + if value is None: + style.pop(prop, None) + else: + style[prop] = variables.literal(value, prop) + if style: + key = f"a{index}_{position}" + styles[key] = style + classes = _classes(key) + else: + classes = '""' + node = table + for value in combination[:-1]: + node = node.setdefault(value, {}) + node[combination[-1]] = classes + name = f"{_NAME}_{index}" + tables.append(f"const {name} = {_lookup(table, len(alternatives.props))};") + if shared: + key = f"a{index}" + styles[key] = shared + fallback = f"{name}d" + tables.append(f"const {fallback} = {_classes(key)};") + else: + fallback = '""' + indexed = "?.".join([f"[{var!s}]" for var in alternatives.vars]) + return f"({name}{indexed} ?? {fallback})" + + +def _emit(merged: Merged) -> Emitted: + """Emit styles that hold a value or a prop bound to state. + + Args: + merged: The merged styles of one element. + Returns: + The declaration, with the expressions and Vars the element needs. + """ + lowered = merged.style + variables = _Variables() + static = { + prop: variables.literal(value, prop) for prop, value in lowered.style.items() + } + styles: dict[str, Any] = {} + tables: list[str] = [] + imports = set(lowered.imports) + vars: list[Var] = [] + lookups = [] + for index, alternatives in enumerate(merged.dynamic): + lookups.append( + _alternatives(alternatives, index, static, variables, styles, tables) + ) + vars.extend(alternatives.vars) + for change in alternatives.values.values(): + imports.update(change.imports) + if static: + styles = {_KEY: static, **styles} + tables.insert(0, f"const {_NAME}_c = {_classes(_KEY)};") + declaration = classes = None + if styles: + entries = ", ".join([ + f"{key}: {json.dumps(style, ensure_ascii=False)}" + for key, style in styles.items() + ]) + template = "\n".join([ + f"const {_NAME} = stylex.create({{ {entries} }});", + *tables, + ]) + name = _name(template) + declaration = template.replace(_NAME, name) + lookups = [lookup.replace(_NAME, name) for lookup in lookups] + if static: + classes = f"{name}_c" + if lowered.inline is not None: + vars.append(lowered.inline) + return Emitted( + declaration, + classes, + tuple(lookups), + tuple(variables.entries), + lowered.inline, + tuple(sorted(imports)), + (*variables.vars, *vars), + ) -def props_call(refs: tuple[str, ...], class_name: str | None = None) -> str: - """Build the ``stylex.props`` call that an element spreads into its props. - A class name given here is folded into the same ``className`` string as the - styles, so the element keeps a single static attribute. +def emit(merged: Merged) -> Emitted: + """Emit the StyleX source of the merged styles of one element. Args: - refs: The styles to apply, the last one winning a conflict. - class_name: Literal class names the element also carries. + merged: The merged styles of the element. Those of its parts are + emitted on their own, for the elements that render them. Returns: - The JavaScript expression. + What the module that renders the element declares, and what the + element reads from it. """ - args = list(refs) - if class_name: - # A compiled style is a map of class names marked with `$$css`; this - # one carries the element's own classes through the fold. - args.append(f"{{ $$css: true, className: {json.dumps(class_name)} }}") - return f"stylex.props({', '.join(args)})" + lowered = merged.style + if merged.dynamic or lowered.inline is not None: + return _emit(merged) + style = lowered.style + if not style: + return _NOTHING + try: + source = json.dumps(style, ensure_ascii=False) + except TypeError: + # A value is a Var. + return _emit(merged) + name = _name(source) + return Emitted( + f"const {name} = stylex.create({{ {_KEY}: {source} }});\n" + f"const {name}_c = stylex.props({name}.{_KEY}).className;", + f"{name}_c", + imports=lowered.imports, + ) -def inline(style: LoweredStyle, component: str) -> dict[str, str | int | float]: - """Check that a lowered style can be an inline ``style`` attribute. +def inline(merged: Merged, component: str) -> dict[str, str | int | float]: + """Turn the merged styles of an element into an inline ``style``. The fallback for code that is evaluated in the browser and never reaches - the StyleX compiler. An inline style has no conditions. + the StyleX compiler. An inline style has no conditions, and nothing bound + to state is compiled for it. Args: - style: The lowered style of one element. + merged: The merged styles of the element. component: The name of the component, for error messages. Returns: The style, every value a literal. Raises: - UnsupportedStyleError: If a value has conditions, is bound to state or - is not a literal. + StyleError: If a value has conditions, or a value, a prop or the + whole style is bound to state. """ - result: dict[str, str | int | float] = {} - for prop, value in style.items(): - if isinstance(value, Mapping): - conditions = ", ".join(f'"{c}"' for c in value) + lowered = merged.style + if merged.dynamic: + props = ", ".join([ + f'"{prop}"' + for alternatives in merged.dynamic + for prop in alternatives.props + ]) + msg = ( + f"{component}: the props {props} select a style and are bound to " + f"state, {_NOT_RENDERED_IN_PAGE} Give them literal values there, or " + f"{_RENDER_IN_PAGE}" + ) + raise StyleError(msg) + if lowered.inline is not None: + msg = ( + f"{component}: the style is a Var, {_NOT_RENDERED_IN_PAGE} Use a " + f"dict of literal values there, or {_RENDER_IN_PAGE}" + ) + raise StyleError(msg) + for prop, value in lowered.style.items(): + if value.__class__ is dict: + conditions = ", ".join([f'"{condition}"' for condition in value]) + msg = ( + f'{component}: the style "{prop}" has conditions ({conditions}), ' + f"{_NOT_RENDERED_IN_PAGE} Use an unconditional value there, or " + f"{_RENDER_IN_PAGE}" + ) + raise StyleError(msg) + if isinstance(value, Var): msg = ( - f'{component}: the style "{prop}" has conditions ' - f"({conditions}), which a component rendered from state cannot " - "apply: its code is evaluated in the browser and never reaches " - "the StyleX compiler. Use an unconditional value there, or " - "render the component in a page and show it with rx.cond." + f'{component}: the style "{prop}" is bound to state, ' + f"{_NOT_RENDERED_IN_PAGE} Use a literal value there, or " + f"{_RENDER_IN_PAGE}" ) - raise UnsupportedStyleError(msg) - _check_value(value, prop, component, ()) - result[prop] = cast("str | int | float", value) - return result + raise StyleError(msg) + return lowered.style diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py b/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py index f9340efa21a..1aee449902d 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/lower.py @@ -269,7 +269,7 @@ def _ends(prefix: str) -> tuple[str, str]: } -def _suggest(key: str, candidates: Any) -> str: +def suggest(key: str, candidates: Any) -> str: """Word the suggestion that ends an error about a misspelt key. Args: @@ -309,7 +309,7 @@ def _condition(name: str, key: str) -> str | None: for pseudo in sorted(PSEUDO_CLASSES | PSEUDO_ELEMENTS) if not pseudo.startswith("-") ] - msg = f'{name}: unknown pseudo-class "{key}".{_suggest(key, known)}' + msg = f'{name}: unknown pseudo-class "{key}".{suggest(key, known)}' raise StyleError(msg) elif first == "@": if key.startswith(_AT_RULES): @@ -370,7 +370,7 @@ def _resolve(name: str, key: Any) -> _Entry: ) msg = ( f'{name}: unknown CSS property "{key}".' - f"{_suggest(key.replace('-', '_'), candidates)}" + f"{suggest(key.replace('-', '_'), candidates)}" ) raise StyleError(msg) entry = (None, condition, None, None) @@ -1018,7 +1018,7 @@ def lower_layer( except KeyError: msg = ( f'{name}: unknown layout prop "{prop}".' - f"{_suggest(prop, sorted(_LAYOUT))}" + f"{suggest(prop, sorted(_LAYOUT))}" ) raise StyleError(msg) from None if read is not None: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/style/merge.py b/packages/reflex-components-ui/src/reflex_components_ui/style/merge.py index 7804d61eb30..c004635f6fa 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/style/merge.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/merge.py @@ -9,7 +9,7 @@ from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from itertools import product from typing import TYPE_CHECKING, Any, TypedDict @@ -506,7 +506,7 @@ def _merge( name: str, table: _Table, props: Mapping[str, Any], - style: Mapping[str, Any] | Var | None, + style: Mapping[str, Any] | Var | Sequence[Mapping[str, Any] | Var] | None, layout: Mapping[str, Any] | None, ) -> Merged: """Merge a lowered style table with the style of one element. @@ -515,7 +515,8 @@ def _merge( name: The display name of the component, for error messages. table: The lowered style table. props: The props of the element. - style: The style the user wrote. + style: The style the user wrote, or several of them in the order + they apply. layout: The layout props of the element. Returns: @@ -558,8 +559,15 @@ def _merge( inline = None if isinstance(style, Var): inline = style + elif isinstance(style, Mapping): + if style: + layers.append(lower_layer(name, style)) elif style: - layers.append(lower_layer(name, style)) + for item in style: + if isinstance(item, Var): + inline = item + elif item: + layers.append(lower_layer(name, item)) if bound is None: merged_props = dict(table.resolve(keys)) @@ -574,7 +582,11 @@ def merge( name: str, styles: ComponentStyles | Mapping[str, Any], props: Mapping[str, Any] | None = None, - style: StyleProps | Mapping[str, Any] | Var | None = None, + style: StyleProps + | Mapping[str, Any] + | Var + | Sequence[StyleProps | Mapping[str, Any] | Var] + | None = None, layout: Mapping[str, Any] | None = None, ) -> Merged: """Merge the style table of a component with the style of one element. @@ -591,7 +603,8 @@ def merge( or, for a prop bound to state, a Var. Props the table does not read are ignored. style: The style the user wrote, or a Var holding a whole dict of - styles, which becomes the inline style of the element. + styles, which becomes the inline style of the element. A list or + tuple of them is merged in order, each over the ones before it. layout: The layout props of the element, such as ``p`` and ``gap``, which are merged after the table and before ``style``. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/box.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/box.py index 089accd2542..071b3b4d5a5 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/box.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/box.py @@ -1,10 +1,10 @@ """The look of the box.""" -from reflex_components_ui.base import ComponentStyles +from reflex_components_ui.style import ComponentStyles BOX: ComponentStyles = { "base": { - "boxSizing": "border-box", + "box_sizing": "border-box", "display": "block", }, } diff --git a/pyi_hashes.json b/pyi_hashes.json index ab363937714..462fe5cb2f3 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -119,8 +119,8 @@ "packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "f2a9cf6db58d169289fbc76de6813300", "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "b195e3845260389ced026d2f5c4adb93", "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "0fb77ee40f719777c68b2de2efdf799b", - "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "3a25570b63274a1490fa96a524a241fd", - "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "55e59f481df8cb08185a820f84e0a10d", + "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "6ed32f40aa1d3ac1a21aa000f836dd3d", + "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "fc1116971a8f022d5b67dcbe81275acb", "reflex/__init__.pyi": "540ab90bd8a7a89647f0bdd0a2fa3590", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index dd8fb820918..1efb35a6652 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -31,16 +31,139 @@ # A style of the literal page as it is compiled, and what the caching test # changes it to. -LITERAL_STYLE = '"padding": "6px"' -CHANGED_STYLE = '"padding": "7px"' +LITERAL_STYLE = '"paddingTop": "6px"' +CHANGED_STYLE = '"paddingTop": "7px"' + +# The elements of the styled page below the first breakpoint, before any event. +STYLED = { + # A width bound to state. + "var": {"width": "100px"}, + "hover": {"color": "rgb(0, 0, 0)"}, + "responsive": {"margin-top": "2px"}, + # A variant bound to state: the base, and what its value changes. + "tone": { + "color": "rgb(0, 0, 255)", + "background-color": "rgb(0, 128, 0)", + "padding": "1px", + }, + # The same variant with a value known at compile time. + "loud": { + "color": "rgb(255, 255, 255)", + "background-color": "rgb(255, 0, 0)", + "padding": "1px", + }, +} + +# What differs from STYLED at and above the first breakpoint. +STYLED_WIDE = {**STYLED, "responsive": {"margin-top": "6px"}} + +# What differs from STYLED once the state has changed. +STYLED_CHANGED = { + **STYLED, + "var": {"width": "200px"}, + "tone": { + "color": "rgb(255, 255, 255)", + "background-color": "rgb(255, 0, 0)", + "padding": "1px", + }, +} + +# The declarations of the styled page: one for each distinct style, with the +# constant that holds its class names. The hundred rows share the last. +STYLED_PAGE_DECLARATIONS = [ + ( + 'const sx_e5e3dab07a = stylex.create({ s: {"boxSizing": "border-box", ' + '"display": "block", "color": {"default": "rgb(0, 0, 0)", ":hover": ' + '"rgb(255, 0, 0)"}} });' + ), + "const sx_e5e3dab07a_c = stylex.props(sx_e5e3dab07a.s).className;", + ( + 'const sx_4c7f040d01 = stylex.create({ s: {"boxSizing": "border-box", ' + '"display": "block", "marginTop": {"default": "2px", "@media screen and ' + '(min-width: 30em)": "6px"}} });' + ), + "const sx_4c7f040d01_c = stylex.props(sx_4c7f040d01.s).className;", + ( + 'const sx_9cbecd042a = stylex.create({ s: {"color": "rgb(255, 255, 255)", ' + '"paddingTop": "1px", "paddingRight": "1px", "paddingBottom": "1px", ' + '"paddingLeft": "1px", "backgroundColor": "rgb(255, 0, 0)"} });' + ), + "const sx_9cbecd042a_c = stylex.props(sx_9cbecd042a.s).className;", + ( + 'const sx_e9f4c4c063 = stylex.create({ s: {"boxSizing": "border-box", ' + '"display": "block", "paddingTop": "3px", "paddingRight": "3px", ' + '"paddingBottom": "3px", "paddingLeft": "3px", "opacity": {":hover": 0.5}} });' + ), + "const sx_e9f4c4c063_c = stylex.props(sx_e9f4c4c063.s).className;", +] + +# The declarations of its elements that read state, which the compiler moves +# into a module of their own: a custom property for the width, and the class +# names of each value of the variant. +STYLED_MEMO_DECLARATIONS = [ + ( + 'const sx_723c142d42 = stylex.create({ s: {"boxSizing": "border-box", ' + '"display": "block", "width": "var(--v0)"} });' + ), + "const sx_723c142d42_c = stylex.props(sx_723c142d42.s).className;", + ( + 'const sx_5f1012736b = stylex.create({ s: {"paddingTop": "1px", ' + '"paddingRight": "1px", "paddingBottom": "1px", "paddingLeft": "1px"}, a0_0: ' + '{"color": "rgb(0, 0, 255)", "backgroundColor": "rgb(0, 128, 0)"}, a0_1: ' + '{"color": "rgb(255, 255, 255)", "backgroundColor": "rgb(255, 0, 0)"}, a0: ' + '{"color": "rgb(0, 0, 255)"} });' + ), + "const sx_5f1012736b_c = stylex.props(sx_5f1012736b.s).className;", + ( + "const sx_5f1012736b_0 = { __proto__: null, " + '"calm": stylex.props(sx_5f1012736b.a0_0).className, ' + '"loud": stylex.props(sx_5f1012736b.a0_1).className };' + ), + "const sx_5f1012736b_0d = stylex.props(sx_5f1012736b.a0).className;", +] def UIComponentsApp(): """An app with a page for each thing the rx.ui tests look at.""" from pathlib import Path + from typing import ClassVar, Literal + + from reflex_components_ui.base import UIComponent + from reflex_components_ui.style import ComponentStyles import reflex as rx + class StyleState(rx.State): + """What the styles of the styled page are bound to.""" + + width: rx.Field[str] = rx.field("100px") + tone: rx.Field[str] = rx.field("calm") + + @rx.event + def change(self): + """Change every value a style is bound to.""" + self.width = "200px" + self.tone = "loud" + + class Tone(UIComponent): + """An element whose look a prop selects.""" + + styles: ClassVar[ComponentStyles] = { + "base": {"color": "rgb(0, 0, 255)", "padding": "1px"}, + "variants": { + "tone": { + "calm": {"background_color": "rgb(0, 128, 0)"}, + "loud": { + "background_color": "rgb(255, 0, 0)", + "color": "rgb(255, 255, 255)", + }, + }, + }, + } + + # Which look the element has. + tone: rx.Var[Literal["calm", "loud"]] + def index(): return rx.el.main( rx.ui.box("plain", id="plain"), @@ -59,13 +182,36 @@ def index(): def literal(): return rx.ui.box("literal", id="literal", style={"padding": "6px"}) + def styled(): + return rx.el.main( + rx.ui.box("var", id="var", width=StyleState.width), + rx.ui.box( + "hover", + id="hover", + style={"color": "rgb(0, 0, 0)", "_hover": {"color": "rgb(255, 0, 0)"}}, + ), + rx.ui.box("responsive", id="responsive", margin_top=["2px", "6px"]), + Tone.create("tone", id="tone", tone=StyleState.tone), + Tone.create("loud", id="loud", tone="loud"), + rx.el.button("change", id="change", on_click=StyleState.change), + *[ + rx.ui.box( + f"row {index}", + class_name="row", + style={"padding": "3px", "_hover": {"opacity": 0.5}}, + ) + for index in range(100) + ], + ) + assets = Path.cwd() / "assets" assets.mkdir(exist_ok=True) (assets / "unlayered.css").write_text(".unlayered { padding: 2px }") - app = rx.App(stylesheets=["unlayered.css"], enable_state=False) + app = rx.App(stylesheets=["unlayered.css"]) app.add_page(index) app.add_page(literal, route="/literal") + app.add_page(styled, route="/styled") config = rx.config.get_config() config.plugins = [rx.plugins.UIPlugin(), rx.plugins.TailwindV4Plugin()] @@ -109,18 +255,21 @@ def prod_app(ui_app: AppHarness) -> AppHarness: return ui_app -def _computed_styles(page: Page) -> dict[str, dict[str, str]]: - """Read the computed style of every box of the index page. +def _computed_styles( + page: Page, elements: dict[str, dict[str, str]] +) -> dict[str, dict[str, str]]: + """Read the computed style of elements of the page. Args: - page: A page showing the index of the app. + page: A page of the app. + elements: The properties to read, as the keys of a dict, by element id. Returns: - The properties in BOX_STYLES as the browser computed them, by box id. + The properties as the browser computed them, by element id. """ return page.evaluate( - """(boxes) => Object.fromEntries( - Object.entries(boxes).map(([id, properties]) => { + """(elements) => Object.fromEntries( + Object.entries(elements).map(([id, properties]) => { const style = getComputedStyle(document.getElementById(id)); return [ id, @@ -133,7 +282,7 @@ def _computed_styles(page: Page) -> dict[str, dict[str, str]]: ]; }), )""", - BOX_STYLES, + elements, ) @@ -143,7 +292,7 @@ def test_box_is_styled_in_cascade_order(ui_app: AppHarness, page: Page): page.goto(ui_app.frontend_url) # In dev the styles of a page arrive once its module was compiled. expect(page.locator("#styled")).to_have_css("padding", "4px") - assert _computed_styles(page) == BOX_STYLES + assert _computed_styles(page, BOX_STYLES) == BOX_STYLES assert page.locator("#plain").evaluate("(box) => box.tagName") == "DIV" @@ -157,7 +306,7 @@ def test_first_paint_is_styled_without_javascript( page = context.new_page() page.goto(prod_app.frontend_url) # Evaluating in the page still works: only its own scripts are off. - assert _computed_styles(page) == BOX_STYLES + assert _computed_styles(page, BOX_STYLES) == BOX_STYLES finally: context.close() @@ -180,6 +329,90 @@ def _client_files(harness: AppHarness) -> dict[str, bytes]: } +def _styled_url(harness: AppHarness) -> str: + """Get the address of the styled page. + + Args: + harness: The running harness. + + Returns: + The address. + """ + assert harness.frontend_url is not None + return harness.frontend_url.rstrip("/") + "/styled/" + + +def test_styles_follow_the_viewport_the_state_and_the_pointer( + ui_app: AppHarness, page: Page +): + """Every kind of style applies where and when it should.""" + page.set_viewport_size({"width": 400, "height": 600}) + page.goto(_styled_url(ui_app)) + # In dev the styles of a page arrive once its module was compiled. + expect(page.locator("#tone")).to_have_css("padding", "1px") + assert _computed_styles(page, STYLED) == STYLED + + page.set_viewport_size({"width": 1280, "height": 600}) + expect(page.locator("#responsive")).to_have_css("margin-top", "6px") + assert _computed_styles(page, STYLED) == STYLED_WIDE + + page.set_viewport_size({"width": 400, "height": 600}) + page.locator("#hover").hover() + expect(page.locator("#hover")).to_have_css("color", "rgb(255, 0, 0)") + + # The value bound to state is a custom property of the element. + variable = "(box) => box.style.getPropertyValue('--v0')" + assert page.locator("#var").evaluate(variable) == "100px" + page.locator("#change").click() + expect(page.locator("#var")).to_have_css("width", "200px") + assert _computed_styles(page, STYLED) == STYLED_CHANGED + assert page.locator("#var").evaluate(variable) == "200px" + + +def test_equal_styles_share_one_declaration(ui_app: AppHarness, page: Page): + """A hundred rows with one style declare it once and carry the same classes.""" + web = ui_app.app_path / ".web" + + def declarations(path: Path) -> list[str]: + return re.findall(r"^const sx_\w+ = .*$", path.read_text(), re.MULTILINE) + + (route,) = (web / "app" / "routes").glob("*styled*.jsx") + assert declarations(route) == STYLED_PAGE_DECLARATIONS + name = ui_app.app_name + assert declarations(web / "app_components" / name / f"{name}.jsx") == ( + STYLED_MEMO_DECLARATIONS + ) + + page.goto(_styled_url(ui_app)) + rows = page.locator(".row") + expect(rows).to_have_count(100) + class_names = set(rows.evaluate_all("(rows) => rows.map((row) => row.className)")) + assert len(class_names) == 1 + (class_name,) = class_names + # Its own class, then display, box-sizing, the four sides of the padding and + # the opacity. While developing, StyleX names the declaration ahead of them. + assert re.fullmatch(r"row (\w+__sx_e9f4c4c063\.s )?x\w+( x\w+){6}", class_name), ( + class_name + ) + expect(rows.first).to_have_css("padding", "3px") + + +def _scripts(harness: AppHarness) -> dict[str, str]: + """Read the scripts the production build serves to the browser. + + Args: + harness: A harness running a production build. + + Returns: + The source of every script, by path. + """ + return { + name: content.decode() + for name, content in _client_files(harness).items() + if name.endswith(".js") + } + + def test_literal_page_folds_to_class_names(prod_app: AppHarness, page: Page): """StyleX leaves a class name string in the page, and none of itself.""" assert prod_app.frontend_url is not None @@ -188,24 +421,43 @@ def test_literal_page_folds_to_class_names(prod_app: AppHarness, page: Page): expect(box).to_have_css("padding", "6px") class_name = box.get_attribute("class") assert class_name is not None - # Three atomic classes: display, box-sizing and padding. - assert re.fullmatch(r"x\w+ x\w+ x\w+", class_name), class_name + # Six atomic classes: display, box-sizing and the four sides of the padding. + assert re.fullmatch(r"x\w+( x\w+){5}", class_name), class_name - scripts = { - name: content.decode() - for name, content in _client_files(prod_app).items() - if name.endswith(".js") - } + scripts = _scripts(prod_app) literal_chunks = [name for name in scripts if name.startswith("assets/_literal_")] assert len(literal_chunks) == 1, sorted(scripts) - # Every class name the chunk of the page sets is the folded string. + # The chunk of the page holds the folded string once, and nothing else + # that names a class. assert re.findall(r"className:`([^`]*)`", scripts[literal_chunks[0]]) == [ class_name ] - # No script holds a call into StyleX or a style object it reads at runtime. + + +def test_no_page_ships_the_stylex_runtime(prod_app: AppHarness): + """Styles bound to state are compiled away too. + + A value bound to state is a custom property, and a variant bound to state + indexes a table of folded class names, so no script holds a call into + StyleX or a style object it reads at runtime: neither the literal page nor + the styled one, whose chunk holds the table. + """ + scripts = _scripts(prod_app) assert [ name for name, code in scripts.items() if re.search(r"stylex|\$\$css", code) ] == [] + styled_chunks = [name for name in scripts if name.startswith("assets/_styled_")] + assert len(styled_chunks) == 1, sorted(scripts) + # The table of the variant, in the chunk that renders the element: the + # class names of each value. + (table,) = re.findall( + r"\{__proto__:null,calm:.*?,loud:.*?\}[^}]*\}", scripts[styled_chunks[0]] + ) + assert re.fullmatch( + r"\{__proto__:null,calm:\{className:`x\w+ x\w+`\}\.className," + r"loud:\{className:`x\w+ x\w+`\}\.className\}", + table, + ), table def _digests(files: dict[str, bytes]) -> dict[str, str]: diff --git a/tests/units/reflex_base/utils/pyi_generator/dataset/overwrite_types.py b/tests/units/reflex_base/utils/pyi_generator/dataset/overwrite_types.py new file mode 100644 index 00000000000..cbb5eabe538 --- /dev/null +++ b/tests/units/reflex_base/utils/pyi_generator/dataset/overwrite_types.py @@ -0,0 +1,54 @@ +"""Components that type a prop of their parents more narrowly in the stub. + +This module tests: +- `_pyi_overwrite_types`: the annotation a class gives a prop in its stub +- `_pyi_imports`: the names those annotations need, imported into the stub +- Both are inherited by subclasses, which may overwrite them again +- A class without them keeps the annotation every component has +""" + +from typing import ClassVar + +from reflex_base.components.component import Component +from reflex_base.vars.base import Var + + +class TypedStyleComponent(Component): + """A component whose style is typed more narrowly than a mapping.""" + + _pyi_overwrite_types: ClassVar[dict[str, str]] = { + "style": "OrderedDict[str, str] | None", + } + _pyi_imports: ClassVar[dict[str, list[str]]] = { + "collections": ["OrderedDict"], + } + + # The title displayed on the component. + title: Var[str] + + +class InheritingComponent(TypedStyleComponent): + """A component that inherits the annotation of its parent.""" + + # The count to display. + count: Var[int] + + +class RetypedComponent(TypedStyleComponent): + """A component that overwrites one of its own props as well.""" + + _pyi_overwrite_types: ClassVar[dict[str, str]] = { + **TypedStyleComponent._pyi_overwrite_types, + "title": "Decimal | None", + } + _pyi_imports: ClassVar[dict[str, list[str]]] = { + **TypedStyleComponent._pyi_imports, + "decimal": ["Decimal"], + } + + +class PlainComponent(Component): + """A component that keeps the annotation every component has.""" + + # The label of the component. + label: Var[str] diff --git a/tests/units/reflex_base/utils/pyi_generator/golden/overwrite_types.pyi b/tests/units/reflex_base/utils/pyi_generator/golden/overwrite_types.pyi new file mode 100644 index 00000000000..414f4ee4d2f --- /dev/null +++ b/tests/units/reflex_base/utils/pyi_generator/golden/overwrite_types.pyi @@ -0,0 +1,272 @@ +"""Stub file for """ + +# ------------------- DO NOT EDIT ---------------------- +# This file was generated by `reflex/utils/pyi_generator.py`! +# ------------------------------------------------------ +from collections import OrderedDict +from collections.abc import Mapping, Sequence +from decimal import Decimal +from typing import Any + +from reflex_base.components.component import Component +from reflex_base.event import EventType, PointerEventInfo +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Breakpoints + +class TypedStyleComponent(Component): + @classmethod + def create( + cls, + *children, + title: Var[str] | str | None = None, + style: OrderedDict[str, str] | None = None, + key: Any | None = None, + id: Any | None = None, + ref: Var | None = None, + class_name: Any | None = None, + custom_attrs: dict[str, Any | Var] | None = None, + on_blur: EventType[()] | None = None, + on_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_context_menu: EventType[()] | EventType[PointerEventInfo] | None = None, + on_double_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_focus: EventType[()] | None = None, + on_mount: EventType[()] | None = None, + on_mouse_down: EventType[()] | None = None, + on_mouse_enter: EventType[()] | None = None, + on_mouse_leave: EventType[()] | None = None, + on_mouse_move: EventType[()] | None = None, + on_mouse_out: EventType[()] | None = None, + on_mouse_over: EventType[()] | None = None, + on_mouse_up: EventType[()] | None = None, + on_scroll: EventType[()] | None = None, + on_scroll_end: EventType[()] | None = None, + on_unmount: EventType[()] | None = None, + **props, + ) -> TypedStyleComponent: + """Create the component. + + Args: + *children: The children of the component. + title: The title displayed on the component. + style: The style of the component. + key: A unique key for the component. + id: The id for the component. + ref: The Var to pass as the ref to the component. + class_name: The class name for the component. + custom_attrs: Attributes passed directly to the component. + on_focus: Fired when the element (or some element inside of it) receives focus. For example, it is called when the user clicks on a text input. + on_blur: Fired when focus has left the element (or left some element inside of it). For example, it is called when the user clicks outside of a focused text input. + on_click: Fired when the user clicks on an element. For example, it's called when the user clicks on a button. + on_context_menu: Fired when the user right-clicks on an element. + on_double_click: Fired when the user double-clicks on an element. + on_mouse_down: Fired when the user presses a mouse button on an element. + on_mouse_enter: Fired when the mouse pointer enters the element. + on_mouse_leave: Fired when the mouse pointer leaves the element. + on_mouse_move: Fired when the mouse pointer moves over the element. + on_mouse_out: Fired when the mouse pointer moves out of the element. + on_mouse_over: Fired when the mouse pointer moves onto the element. + on_mouse_up: Fired when the user releases a mouse button on an element. + on_scroll: Fired when the user scrolls the element. + on_scroll_end: Fired when scrolling ends on the element. + on_mount: Fired when the component is mounted to the page. + on_unmount: Fired when the component is removed from the page. Only called during navigation, not on page refresh. + **props: The props of the component. + + Returns: + The component. + """ + +class InheritingComponent(TypedStyleComponent): + @classmethod + def create( + cls, + *children, + count: Var[int] | int | None = None, + title: Var[str] | str | None = None, + style: OrderedDict[str, str] | None = None, + key: Any | None = None, + id: Any | None = None, + ref: Var | None = None, + class_name: Any | None = None, + custom_attrs: dict[str, Any | Var] | None = None, + on_blur: EventType[()] | None = None, + on_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_context_menu: EventType[()] | EventType[PointerEventInfo] | None = None, + on_double_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_focus: EventType[()] | None = None, + on_mount: EventType[()] | None = None, + on_mouse_down: EventType[()] | None = None, + on_mouse_enter: EventType[()] | None = None, + on_mouse_leave: EventType[()] | None = None, + on_mouse_move: EventType[()] | None = None, + on_mouse_out: EventType[()] | None = None, + on_mouse_over: EventType[()] | None = None, + on_mouse_up: EventType[()] | None = None, + on_scroll: EventType[()] | None = None, + on_scroll_end: EventType[()] | None = None, + on_unmount: EventType[()] | None = None, + **props, + ) -> InheritingComponent: + """Create the component. + + Args: + *children: The children of the component. + count: The count to display. + title: The title displayed on the component. + style: The style of the component. + key: A unique key for the component. + id: The id for the component. + ref: The Var to pass as the ref to the component. + class_name: The class name for the component. + custom_attrs: Attributes passed directly to the component. + on_focus: Fired when the element (or some element inside of it) receives focus. For example, it is called when the user clicks on a text input. + on_blur: Fired when focus has left the element (or left some element inside of it). For example, it is called when the user clicks outside of a focused text input. + on_click: Fired when the user clicks on an element. For example, it's called when the user clicks on a button. + on_context_menu: Fired when the user right-clicks on an element. + on_double_click: Fired when the user double-clicks on an element. + on_mouse_down: Fired when the user presses a mouse button on an element. + on_mouse_enter: Fired when the mouse pointer enters the element. + on_mouse_leave: Fired when the mouse pointer leaves the element. + on_mouse_move: Fired when the mouse pointer moves over the element. + on_mouse_out: Fired when the mouse pointer moves out of the element. + on_mouse_over: Fired when the mouse pointer moves onto the element. + on_mouse_up: Fired when the user releases a mouse button on an element. + on_scroll: Fired when the user scrolls the element. + on_scroll_end: Fired when scrolling ends on the element. + on_mount: Fired when the component is mounted to the page. + on_unmount: Fired when the component is removed from the page. Only called during navigation, not on page refresh. + **props: The props of the component. + + Returns: + The component. + """ + +class RetypedComponent(TypedStyleComponent): + @classmethod + def create( + cls, + *children, + title: Decimal | None = None, + style: OrderedDict[str, str] | None = None, + key: Any | None = None, + id: Any | None = None, + ref: Var | None = None, + class_name: Any | None = None, + custom_attrs: dict[str, Any | Var] | None = None, + on_blur: EventType[()] | None = None, + on_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_context_menu: EventType[()] | EventType[PointerEventInfo] | None = None, + on_double_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_focus: EventType[()] | None = None, + on_mount: EventType[()] | None = None, + on_mouse_down: EventType[()] | None = None, + on_mouse_enter: EventType[()] | None = None, + on_mouse_leave: EventType[()] | None = None, + on_mouse_move: EventType[()] | None = None, + on_mouse_out: EventType[()] | None = None, + on_mouse_over: EventType[()] | None = None, + on_mouse_up: EventType[()] | None = None, + on_scroll: EventType[()] | None = None, + on_scroll_end: EventType[()] | None = None, + on_unmount: EventType[()] | None = None, + **props, + ) -> RetypedComponent: + """Create the component. + + Args: + *children: The children of the component. + title: The title displayed on the component. + style: The style of the component. + key: A unique key for the component. + id: The id for the component. + ref: The Var to pass as the ref to the component. + class_name: The class name for the component. + custom_attrs: Attributes passed directly to the component. + on_focus: Fired when the element (or some element inside of it) receives focus. For example, it is called when the user clicks on a text input. + on_blur: Fired when focus has left the element (or left some element inside of it). For example, it is called when the user clicks outside of a focused text input. + on_click: Fired when the user clicks on an element. For example, it's called when the user clicks on a button. + on_context_menu: Fired when the user right-clicks on an element. + on_double_click: Fired when the user double-clicks on an element. + on_mouse_down: Fired when the user presses a mouse button on an element. + on_mouse_enter: Fired when the mouse pointer enters the element. + on_mouse_leave: Fired when the mouse pointer leaves the element. + on_mouse_move: Fired when the mouse pointer moves over the element. + on_mouse_out: Fired when the mouse pointer moves out of the element. + on_mouse_over: Fired when the mouse pointer moves onto the element. + on_mouse_up: Fired when the user releases a mouse button on an element. + on_scroll: Fired when the user scrolls the element. + on_scroll_end: Fired when scrolling ends on the element. + on_mount: Fired when the component is mounted to the page. + on_unmount: Fired when the component is removed from the page. Only called during navigation, not on page refresh. + **props: The props of the component. + + Returns: + The component. + """ + +class PlainComponent(Component): + @classmethod + def create( + cls, + *children, + label: Var[str] | str | None = None, + style: Sequence[Mapping[str, Any]] + | Mapping[str, Any] + | Var[Mapping[str, Any]] + | Breakpoints + | None = None, + key: Any | None = None, + id: Any | None = None, + ref: Var | None = None, + class_name: Any | None = None, + custom_attrs: dict[str, Any | Var] | None = None, + on_blur: EventType[()] | None = None, + on_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_context_menu: EventType[()] | EventType[PointerEventInfo] | None = None, + on_double_click: EventType[()] | EventType[PointerEventInfo] | None = None, + on_focus: EventType[()] | None = None, + on_mount: EventType[()] | None = None, + on_mouse_down: EventType[()] | None = None, + on_mouse_enter: EventType[()] | None = None, + on_mouse_leave: EventType[()] | None = None, + on_mouse_move: EventType[()] | None = None, + on_mouse_out: EventType[()] | None = None, + on_mouse_over: EventType[()] | None = None, + on_mouse_up: EventType[()] | None = None, + on_scroll: EventType[()] | None = None, + on_scroll_end: EventType[()] | None = None, + on_unmount: EventType[()] | None = None, + **props, + ) -> PlainComponent: + """Create the component. + + Args: + *children: The children of the component. + label: The label of the component. + style: The style of the component. + key: A unique key for the component. + id: The id for the component. + ref: The Var to pass as the ref to the component. + class_name: The class name for the component. + custom_attrs: Attributes passed directly to the component. + on_focus: Fired when the element (or some element inside of it) receives focus. For example, it is called when the user clicks on a text input. + on_blur: Fired when focus has left the element (or left some element inside of it). For example, it is called when the user clicks outside of a focused text input. + on_click: Fired when the user clicks on an element. For example, it's called when the user clicks on a button. + on_context_menu: Fired when the user right-clicks on an element. + on_double_click: Fired when the user double-clicks on an element. + on_mouse_down: Fired when the user presses a mouse button on an element. + on_mouse_enter: Fired when the mouse pointer enters the element. + on_mouse_leave: Fired when the mouse pointer leaves the element. + on_mouse_move: Fired when the mouse pointer moves over the element. + on_mouse_out: Fired when the mouse pointer moves out of the element. + on_mouse_over: Fired when the mouse pointer moves onto the element. + on_mouse_up: Fired when the user releases a mouse button on an element. + on_scroll: Fired when the user scrolls the element. + on_scroll_end: Fired when scrolling ends on the element. + on_mount: Fired when the component is mounted to the page. + on_unmount: Fired when the component is removed from the page. Only called during navigation, not on page refresh. + **props: The props of the component. + + Returns: + The component. + """ diff --git a/tests/units/reflex_components_ui/conftest.py b/tests/units/reflex_components_ui/conftest.py index c935bc00426..f0b2965a839 100644 --- a/tests/units/reflex_components_ui/conftest.py +++ b/tests/units/reflex_components_ui/conftest.py @@ -1,7 +1,12 @@ """Fixtures for the tests of reflex-components-ui.""" import dataclasses +import json +import shutil +import subprocess +import sys from collections.abc import Callable +from pathlib import Path from typing import Any import pytest @@ -12,6 +17,9 @@ from reflex.compiler.plugins import default_page_plugins +# Code for a type checker, kept as text so that no other tool checks it. +FIXTURES = Path(__file__).parent / "style" / "fixtures" + @dataclasses.dataclass(slots=True) class _Page: @@ -61,3 +69,47 @@ def compile_page(page: Callable[[], Component]) -> CompileContext: return ctx return compile_page + + +@pytest.fixture +def pyright(tmp_path: Path) -> Callable[[str], list[tuple[int, str, str]]]: + """Run pyright over a fixture, outside the configuration of the repository. + + Args: + tmp_path: A directory to copy the fixture to. + + Returns: + A function from the name of a fixture, without its extension, to the + line, rule and whole message of every diagnostic. + """ + + def pyright(fixture: str) -> list[tuple[int, str, str]]: + target = tmp_path / f"{fixture}.py" + shutil.copy(FIXTURES / f"{fixture}.py.txt", target) + result = subprocess.run( + [ + sys.executable, + "-m", + "pyright", + "--outputjson", + "--pythonpath", + sys.executable, + str(target), + ], + capture_output=True, + text=True, + cwd=tmp_path, + check=False, + ) + diagnostics = json.loads(result.stdout)["generalDiagnostics"] + assert {diagnostic["file"] for diagnostic in diagnostics} <= {str(target)} + return [ + ( + diagnostic["range"]["start"]["line"] + 1, + diagnostic["rule"], + diagnostic["message"], + ) + for diagnostic in diagnostics + ] + + return pyright diff --git a/tests/units/reflex_components_ui/layout/test_box.py b/tests/units/reflex_components_ui/layout/test_box.py index c2b5dfe7c55..37d166e69f2 100644 --- a/tests/units/reflex_components_ui/layout/test_box.py +++ b/tests/units/reflex_components_ui/layout/test_box.py @@ -1,8 +1,13 @@ """Tests for reflex_components_ui.layout.box.""" +import ast from collections.abc import Callable +from pathlib import Path +import pytest from reflex_base.plugins import CompileContext +from reflex_base.utils.pyi_generator import PyiGenerator +from reflex_components_ui.layout import box as box_module from reflex_components_ui.layout.box import Box from reflex_components_ui.plugin import UIPlugin @@ -15,13 +20,15 @@ const sx_b26ac4fb71 = stylex.create({ s: {"boxSizing": "border-box", "display": "block"} }); -const sx_f49d6b3475 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "padding": "4px"} }); +const sx_b26ac4fb71_c = stylex.props(sx_b26ac4fb71.s).className; +const sx_30d00d85a0 = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "paddingTop": "4px", "paddingRight": "4px", "paddingBottom": "4px", "paddingLeft": "4px"} }); +const sx_30d00d85a0_c = stylex.props(sx_30d00d85a0.s).className; function Component() { return ( - jsx(Fragment,{},jsx("main",{},jsx("div",{...stylex.props(sx_b26ac4fb71.s)},"hello"),jsx("div",{...stylex.props(sx_b26ac4fb71.s)},"again"),jsx("div",{...stylex.props(sx_f49d6b3475.s, { $$css: true, className: "p-8" })},"padded")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + jsx(Fragment,{},jsx("main",{},jsx("div",{className:sx_b26ac4fb71_c},"hello"),jsx("div",{className:sx_b26ac4fb71_c},"again"),jsx("div",{className:"p-8 " + sx_30d00d85a0_c},"padded")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) ) } Component.displayName = "Component(/)"; @@ -48,3 +55,156 @@ def page(): def test_box_is_a_name_of_the_ui_namespace(): assert rx.ui.box == Box.create assert "box" in dir(rx.ui) + + +@pytest.fixture(scope="module") +def box_stub() -> ast.Module: + """Generate the stub of the box, where a build writes it. + + Returns: + The stub, parsed. + """ + source = Path(box_module.__file__) + PyiGenerator().scan_all([source]) + return ast.parse(source.with_suffix(".pyi").read_text()) + + +def test_stub_types_the_style_as_css(box_stub: ast.Module): + """The stub of every rx.ui component types its style, and imports the type.""" + (box,) = [node for node in box_stub.body if isinstance(node, ast.ClassDef)] + (create,) = [node for node in box.body if isinstance(node, ast.FunctionDef)] + annotations = { + argument.arg: ast.unparse(argument.annotation) + for argument in create.args.kwonlyargs + if argument.annotation is not None + } + assert annotations["style"] == ( + "Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | Breakpoints " + "| None" + ) + # Keyword arguments stay open: data_* and aria_* come through them. + assert create.args.kwarg is not None + assert create.args.kwarg.arg == "props" + assert [ + ast.unparse(node) + for node in box_stub.body + if isinstance(node, ast.ImportFrom) + and node.module == "reflex_components_ui.style" + ] == ["from reflex_components_ui.style import ComponentStyles, StyleProps"] + + +def test_valid_styles_of_a_component_type_check( + box_stub: ast.Module, pyright: Callable[[str], list[tuple[int, str, str]]] +): + assert pyright("component_valid") == [] + + +def test_invalid_styles_of_a_component_are_type_errors( + box_stub: ast.Module, pyright: Callable[[str], list[tuple[int, str, str]]] +): + assert pyright("component_errors") == COMPONENT_ERRORS + + +# What pyright says of each call of the fixture: its line, rule and message. +COMPONENT_ERRORS: list[tuple[int, str, str]] = [ + ( + 5, + "reportArgumentType", + ( + 'Argument of type "dict[str, str]" cannot be assigned to parameter "style" of type ' + '"Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | Breakpoints[Unknown, ' + 'Unknown] | None" in function "create"\n' + '\xa0\xa0Type "dict[str, str]" is not assignable to type "Sequence[StyleProps] | ' + 'StyleProps | Var[Mapping[str, Any]] | Breakpoints[Unknown, Unknown] | None"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Sequence[StyleProps]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "StyleProps"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Var[Mapping[str, Any]]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Breakpoints[Unknown, ' + 'Unknown]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "None"' + ), + ), + ( + 7, + "reportArgumentType", + ( + 'Argument of type "dict[str, str]" cannot be assigned to parameter "style" of type ' + '"Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | Breakpoints[Unknown, ' + 'Unknown] | None" in function "create"\n' + '\xa0\xa0Type "dict[str, str]" is not assignable to type "Sequence[StyleProps] | ' + 'StyleProps | Var[Mapping[str, Any]] | Breakpoints[Unknown, Unknown] | None"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Sequence[StyleProps]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "StyleProps"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Var[Mapping[str, Any]]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Breakpoints[Unknown, ' + 'Unknown]"\n' + '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "None"' + ), + ), + ( + 9, + "reportArgumentType", + ( + 'Argument of type "dict[str, dict[str, str]]" cannot be assigned to parameter ' + '"style" of type "Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | ' + 'Breakpoints[Unknown, Unknown] | None" in function "create"\n' + '\xa0\xa0Type "dict[str, dict[str, str]]" is not assignable to type ' + '"Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | Breakpoints[Unknown, ' + 'Unknown] | None"\n' + '\xa0\xa0\xa0\xa0"dict[str, dict[str, str]]" is not assignable to ' + '"Sequence[StyleProps]"\n' + '\xa0\xa0\xa0\xa0"dict[str, dict[str, str]]" is not assignable to "StyleProps"\n' + '\xa0\xa0\xa0\xa0"dict[str, dict[str, str]]" is not assignable to "Var[Mapping[str, ' + 'Any]]"\n' + '\xa0\xa0\xa0\xa0"dict[str, dict[str, str]]" is not assignable to ' + '"Breakpoints[Unknown, Unknown]"\n' + '\xa0\xa0\xa0\xa0"dict[str, dict[str, str]]" is not assignable to "None"' + ), + ), + ( + 11, + "reportArgumentType", + ( + 'Argument of type "list[StyleProps | dict[str, str]]" cannot be assigned to ' + 'parameter "style" of type "Sequence[StyleProps] | StyleProps | Var[Mapping[str, ' + 'Any]] | Breakpoints[Unknown, Unknown] | None" in function "create"\n' + '\xa0\xa0Type "Literal[\'flx\']" is not assignable to type "_Value[_Display | ' + '_StrVar]"\n' + '\xa0\xa0\xa0\xa0"Literal[\'flx\']" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0"Literal[\'flx\']" is not assignable to "Sequence[_Display | ' + '_StrVar]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' + 'not a subtype of "_Display | _StrVar"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Display | ' + '_StrVar"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "Var[str]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type ' + "\"Literal['-webkit-box']\"\n" + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type ' + "\"Literal['block']\"" + ), + ), + ( + 13, + "reportArgumentType", + ( + "Argument of type \"Literal['padding: 1em']\" cannot be assigned to parameter " + '"style" of type "Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | ' + 'Breakpoints[Unknown, Unknown] | None" in function "create"\n' + "\xa0\xa0Type \"Literal['padding: 1em']\" is not assignable to type " + '"Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | Breakpoints[Unknown, ' + 'Unknown] | None"\n' + "\xa0\xa0\xa0\xa0\"Literal['padding: 1em']\" is not assignable to " + '"Sequence[StyleProps]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' + 'not a subtype of "StyleProps"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "StyleProps"\n' + '\xa0\xa0\xa0\xa0"Literal[\'padding: 1em\']" is not assignable to "StyleProps"\n' + '\xa0\xa0\xa0\xa0"Literal[\'padding: 1em\']" is not assignable to "Var[Mapping[str, ' + 'Any]]"\n' + "\xa0\xa0\xa0\xa0\"Literal['padding: 1em']\" is not assignable to " + '"Breakpoints[Unknown, Unknown]"\n' + '\xa0\xa0\xa0\xa0"Literal[\'padding: 1em\']" is not assignable to "None"' + ), + ), +] diff --git a/tests/units/reflex_components_ui/style/fixtures/component_errors.py.txt b/tests/units/reflex_components_ui/style/fixtures/component_errors.py.txt new file mode 100644 index 00000000000..a759ce7050b --- /dev/null +++ b/tests/units/reflex_components_ui/style/fixtures/component_errors.py.txt @@ -0,0 +1,13 @@ +"""Styles of a component that must not type-check: every call below is an error.""" + +from reflex_components_ui.layout.box import box + +box(style={"paddng": "1em"}) + +box(style={"display": "flx"}) + +box(style={"_hover": {"colr": "red"}}) + +box(style=[{"padding": "1em"}, {"display": "flx"}]) + +box(style="padding: 1em") diff --git a/tests/units/reflex_components_ui/style/fixtures/component_valid.py.txt b/tests/units/reflex_components_ui/style/fixtures/component_valid.py.txt new file mode 100644 index 00000000000..055c90350e8 --- /dev/null +++ b/tests/units/reflex_components_ui/style/fixtures/component_valid.py.txt @@ -0,0 +1,32 @@ +"""Styles of a component as users write them: none of the calls is an error.""" + +import reflex as rx +from reflex_components_ui.layout.box import box + + +class State(rx.State): + """State the styles are bound to.""" + + width: rx.Field[str] = rx.field("1em") + styles: rx.Field[dict[str, str]] = rx.field(default_factory=dict) + + +box(style={"padding": "1em"}) + +box(style={"display": "flex", "width": State.width, "margin_top": 2}) + +box(style={"_hover": {"color": "red"}, ":focus-visible": {"outline_width": "2px"}}) + +box(style={"width": ["100%", "50%"], "color": rx.color("ruby", 9)}) + +box(style={"padding": rx.breakpoints(initial="1em", md="2em")}) + +box(style=[{"padding": "1em"}, {"display": "flex"}]) + +box(style=State.styles) + +box(style=rx.breakpoints(initial={"padding": "1em"}, md={"padding": "2em"})) + +# Keyword arguments stay open, as data_* and aria_* come through them: a +# misspelt property there is an error of the compile, not of the type checker. +box(padding="1em", data_state="open", aria_label="Box", paddng="1em") diff --git a/tests/units/reflex_components_ui/style/test_css_props.py b/tests/units/reflex_components_ui/style/test_css_props.py index fc983a9c8ea..d8ba4df090f 100644 --- a/tests/units/reflex_components_ui/style/test_css_props.py +++ b/tests/units/reflex_components_ui/style/test_css_props.py @@ -1,66 +1,21 @@ """Tests for what a type checker makes of the generated style types.""" -import json -import shutil -import subprocess -import sys -from pathlib import Path +from collections.abc import Callable -FIXTURES = Path(__file__).parent / "fixtures" +Diagnostics = list[tuple[int, str, str]] -def _pyright(tmp_path: Path, fixture: str) -> list[tuple[int, str, str]]: - """Run pyright over a fixture, outside the configuration of the repository. - - The fixtures are kept as text so that no other tool checks them. - - Args: - tmp_path: A directory to copy the fixture to. - fixture: The name of the fixture, without its extension. - - Returns: - The line, rule and whole message of every diagnostic. - """ - target = tmp_path / f"{fixture}.py" - shutil.copy(FIXTURES / f"{fixture}.py.txt", target) - result = subprocess.run( - [ - sys.executable, - "-m", - "pyright", - "--outputjson", - "--pythonpath", - sys.executable, - str(target), - ], - capture_output=True, - text=True, - cwd=tmp_path, - check=False, - ) - diagnostics = json.loads(result.stdout)["generalDiagnostics"] - assert {diagnostic["file"] for diagnostic in diagnostics} <= {str(target)} - return [ - ( - diagnostic["range"]["start"]["line"] + 1, - diagnostic["rule"], - diagnostic["message"], - ) - for diagnostic in diagnostics - ] - - -def test_valid_styles_type_check(tmp_path: Path): +def test_valid_styles_type_check(pyright: Callable[[str], Diagnostics]): """What Reflex users write today, and a style table, raise nothing.""" - assert _pyright(tmp_path, "style_valid") == [] + assert pyright("style_valid") == [] -def test_invalid_styles_are_type_errors(tmp_path: Path): +def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): """A misspelt property, keyword or table key is caught before compiling.""" - assert _pyright(tmp_path, "style_errors") == EXPECTED_ERRORS + assert pyright("style_errors") == EXPECTED_ERRORS -EXPECTED_ERRORS: list[tuple[int, str, str]] = [ +EXPECTED_ERRORS: Diagnostics = [ ( 6, "reportAssignmentType", diff --git a/tests/units/reflex_components_ui/style/test_emit.py b/tests/units/reflex_components_ui/style/test_emit.py index f38b4b975d1..543cf12b1de 100644 --- a/tests/units/reflex_components_ui/style/test_emit.py +++ b/tests/units/reflex_components_ui/style/test_emit.py @@ -1,119 +1,527 @@ """Tests for reflex_components_ui.style.emit.""" +from typing import Any + import pytest from reflex_base.vars.base import Var -from reflex_components_ui.style.emit import ( - StyleXStyle, - UnsupportedStyleError, - emit, - inline, - props_call, -) +from reflex_components_ui.style import ComponentStyles, StyleError, merge +from reflex_components_ui.style.emit import Emitted, emit, inline + +import reflex as rx + +RUBY = "$/reflex-ui/colors/ruby.stylex.js" +JADE = "$/reflex-ui/colors/jade.stylex.js" + + +class EmitState(rx.State): + """State the styles and the props are bound to.""" + + width: rx.Field[str] = rx.field("320px") + count: rx.Field[int] = rx.field(2) + kind: rx.Field[str] = rx.field("solid") + size: rx.Field[str] = rx.field("1") + styles: rx.Field[dict[str, str]] = rx.field(default_factory=dict) -def test_emit_declares_a_style_named_after_its_content(): - """Literals and condition maps are written as StyleX takes them.""" - style = { +S = EmitState + +# What the expected source names each Var by. +VARS = { + "": S.width, + "": S.count, + "": S.kind, + "": S.size, + "": S.styles, + "": Var.create(f"calc({S.width} * 2)"), + "": Var("props.raw"), + "": Var("props.tone", _var_type=str), +} + +CARD: ComponentStyles = { + "base": { "padding": "var(--space-3)", - "lineHeight": 1.5, - "zIndex": 2, - "color": { - "default": "red", - ":hover": {"default": "blue", "@media (min-width: 768px)": "green"}, + "border_radius": "var(--radius-4)", + "box_shadow": "var(--shadow-2)", + }, +} + +# Typed loosely: a variant unsets a property with None, which a user's style +# does not take. +BUTTON: dict[str, Any] = { + "base": {"color": "black", "padding_top": "4px"}, + "variants": { + "kind": { + "solid": {"color": "white", "background_color": rx.color("ruby", 9)}, + "soft": {"opacity": 0.5, "padding_top": None}, }, - } - assert emit(style, "rx.ui.box") == StyleXStyle( - declaration=( - 'const sx_163452d900 = stylex.create({ s: {"padding": "var(--space-3)", ' - '"lineHeight": 1.5, "zIndex": 2, "color": {"default": "red", ":hover": ' - '{"default": "blue", "@media (min-width: 768px)": "green"}}} });' - ), - ref="sx_163452d900.s", - ) + "size": {"1": {"height": "1em"}, "2": {"height": "2em"}}, + "tone": {"warm": {"outline_color": "red"}}, + }, + "compound": [ + {"props": {"kind": "solid", "size": "2"}, "style": {"font_weight": 700}}, + ], +} +# A variant whose style holds a value bound to state. +SIZED: ComponentStyles = { + "variants": {"kind": {"a": {"width": S.width}, "b": {"width": "1px"}}}, +} -def test_emit_is_deterministic_and_tells_styles_apart(): - """Equal styles share a declaration; different ones never share a name.""" - assert emit({"padding": "4px"}, "rx.ui.box") == emit( - {"padding": "4px"}, "rx.ui.flex" +NO_STYLES: ComponentStyles = {} + + +def js(source: str) -> str: + """Write the expression of each Var into expected source. + + Args: + source: Source that names Vars as in ``VARS``. + + Returns: + The source as it is emitted. + """ + for name, var in VARS.items(): + source = source.replace(name, str(var)) + return source + + +def emitted( + declaration: str | None = None, + classes: str | None = None, + lookups: tuple[str, ...] = (), + variables: tuple[str, ...] = (), + inline: str | None = None, + imports: tuple[str, ...] = (), + vars: tuple[str, ...] = (), +) -> tuple[Any, ...]: + """Describe an expected result, with every Var named as in ``VARS``. + + Args: + declaration: The module-level statements. + classes: The constant holding the class names every instance has. + lookups: The expressions that give the class names of bound props. + variables: The entries of the inline style. + inline: The Var spread into the inline style. + imports: The modules imported for their CSS. + vars: The Vars the element reads. + + Returns: + What ``comparable`` makes of the result. + """ + return ( + declaration, + classes, + tuple([js(lookup) for lookup in lookups]), + tuple([js(variable) for variable in variables]), + None if inline is None else js(inline), + imports, + tuple([js(var) for var in vars]), ) - names = { - style.ref - for source in ({"padding": "4px"}, {"padding": "5px"}, {"padding": 4}) - if (style := emit(source, "rx.ui.box")) is not None - } - assert len(names) == 3 -def test_emit_has_nothing_to_declare_for_an_empty_style(): - assert emit({}, "rx.ui.box") is None +def comparable(result: Emitted) -> tuple[Any, ...]: + """Reduce a result to values that compare: a Var does not. + Args: + result: What ``emit`` returned. -@pytest.mark.parametrize( - ("style", "message"), - [ - ( - {"color": Var("state.color")}, - ( - 'rx.ui.box: the style "color" is bound to state, which rx.ui components ' - "cannot compile yet. Give it a literal value, or set it from state with " - "a class_name." + Returns: + Its fields, each Var replaced by its expression. + """ + return ( + result.declaration, + result.classes, + result.lookups, + result.variables, + None if result.inline is None else str(result.inline), + result.imports, + tuple([str(var) for var in result.vars]), + ) + + +# The style table, the props, the style and the layout props of an element, +# and what is emitted for it. One group for each kind of input. +CASES: dict[str, tuple[dict[str, Any], tuple[Any, ...]]] = { + "nothing": ({"styles": NO_STYLES}, emitted()), + "literal": ( + { + "styles": CARD, + "style": {"width": "320px", "z_index": 2, "line_height": 1.5}, + }, + emitted( + declaration=( + 'const sx_e4b79af79d = stylex.create({ s: {"padding": ' + '"var(--space-3)", "borderRadius": "var(--radius-4)", "boxShadow": ' + '"var(--shadow-2)", "width": "320px", "zIndex": 2, "lineHeight": ' + "1.5} });\n" + "const sx_e4b79af79d_c = stylex.props(sx_e4b79af79d.s).className;" ), + classes="sx_e4b79af79d_c", ), - ( - {"color": {"default": "red", ":hover": Var("state.color")}}, - ( - 'rx.ui.box: the style "color" under ":hover" is bound to state, which ' - "rx.ui components cannot compile yet. Give it a literal value, or set it " - "from state with a class_name." + ), + # The card of the plan: its width bound to state, and a hover shadow. + "var": ( + { + "styles": CARD, + "style": { + "width": S.width, + "_hover": {"box_shadow": "var(--shadow-3)"}, + }, + }, + emitted( + declaration=( + 'const sx_62330ed6a3 = stylex.create({ s: {"padding": ' + '"var(--space-3)", "borderRadius": "var(--radius-4)", "boxShadow": ' + '{"default": "var(--shadow-2)", ":hover": "var(--shadow-3)"}, ' + '"width": "var(--v0)"} });\n' + "const sx_62330ed6a3_c = stylex.props(sx_62330ed6a3.s).className;" ), + classes="sx_62330ed6a3_c", + variables=('"--v0": () ?? "initial"',), + vars=("",), ), - ( - {"width": ["100%", "50%"]}, - ( - "rx.ui.box: the style \"width\" is ['100%', '50%'], a list. Use a string " - "or a number, or a mapping from condition to value such as " - '{"default": "red", ":hover": "blue"}.' + ), + # A number is a length except where CSS takes a bare number, and one Var + # is one custom property wherever it reads the same. + "var_number": ( + { + "styles": NO_STYLES, + "style": { + "width": S.count, + "opacity": S.count, + "height": S.count, + "margin_top": f"calc({S.width} * 2)", + "_hover": {"width": S.count}, + }, + }, + emitted( + declaration=( + 'const sx_545699866d = stylex.create({ s: {"width": {"default": ' + '"var(--v0)", ":hover": "var(--v0)"}, "opacity": "var(--v1)", ' + '"height": "var(--v0)", "marginTop": "var(--v2)"} });\n' + "const sx_545699866d_c = stylex.props(sx_545699866d.s).className;" + ), + classes="sx_545699866d_c", + variables=( + '"--v0": () + "px"', + '"--v1": () ?? "initial"', + '"--v2": (("calc("++" * 2)")) ?? "initial"', + ), + vars=( + "", + "", + '("calc("++" * 2)")', ), ), - ( - {"display": True}, - ( - 'rx.ui.box: the style "display" is True, a bool. Use a string or a ' - "number, or a mapping from condition to value such as " - '{"default": "red", ":hover": "blue"}.' + ), + "var_untyped": ( + { + "styles": NO_STYLES, + "style": {"width": VARS[""], "z_index": VARS[""]}, + }, + emitted( + declaration=( + 'const sx_bea9985a2e = stylex.create({ s: {"width": "var(--v0)", ' + '"zIndex": "var(--v1)"} });\n' + "const sx_bea9985a2e_c = stylex.props(sx_bea9985a2e.s).className;" + ), + classes="sx_bea9985a2e_c", + variables=( + ( + '"--v0": ((v) => typeof v === "number" ? v + "px" : v)() ?? ' + '"initial"' + ), + '"--v1": () ?? "initial"', + ), + vars=( + "", + "", ), ), - ], -) -def test_emit_rejects_what_stylex_cannot_compile(style: dict, message: str): - with pytest.raises(UnsupportedStyleError) as raised: - emit(style, "rx.ui.box") - assert str(raised.value) == message + ), + "hover": ( + { + "styles": NO_STYLES, + "style": { + "color": "red", + "_hover": {"color": "blue"}, + ":focus-visible": {"outline_width": "2px"}, + }, + }, + emitted( + declaration=( + 'const sx_20caa62f24 = stylex.create({ s: {"color": {"default": ' + '"red", ":hover": "blue"}, "outlineWidth": {":focus-visible": ' + '"2px"}} });\n' + "const sx_20caa62f24_c = stylex.props(sx_20caa62f24.s).className;" + ), + classes="sx_20caa62f24_c", + ), + ), + "responsive": ( + { + "styles": NO_STYLES, + "style": { + "width": ["100%", "50%"], + "color": rx.breakpoints(initial="red", md="blue"), + }, + }, + emitted( + declaration=( + 'const sx_efb6e842bc = stylex.create({ s: {"width": {"default": ' + '"100%", "@media screen and (min-width: 30em)": "50%"}, "color": ' + '{"default": "red", "@media screen and (min-width: 62em)": "blue"}} ' + "});\n" + "const sx_efb6e842bc_c = stylex.props(sx_efb6e842bc.s).className;" + ), + classes="sx_efb6e842bc_c", + ), + ), + "color": ( + { + "styles": NO_STYLES, + "style": { + "color": rx.color("ruby", 9), + "_hover": {"background_color": rx.color("jade", 3)}, + }, + }, + emitted( + declaration=( + 'const sx_fe91e1112f = stylex.create({ s: {"color": "var(--ruby-9)", ' + '"backgroundColor": {":hover": "var(--jade-3)"}} });\n' + "const sx_fe91e1112f_c = stylex.props(sx_fe91e1112f.s).className;" + ), + classes="sx_fe91e1112f_c", + imports=( + JADE, + RUBY, + ), + ), + ), + "layout": ( + { + "styles": NO_STYLES, + "layout": { + "gap": "3", + "p": ["1", "2"], + "m": "-2", + "columns": "3", + "direction": "column", + }, + }, + emitted( + declaration=( + 'const sx_dae5511f98 = stylex.create({ s: {"rowGap": ' + '"var(--space-3)", "columnGap": "var(--space-3)", "paddingTop": ' + '{"default": "var(--space-1)", "@media screen and (min-width: ' + '30em)": "var(--space-2)"}, "paddingRight": {"default": ' + '"var(--space-1)", "@media screen and (min-width: 30em)": ' + '"var(--space-2)"}, "paddingBottom": {"default": "var(--space-1)", ' + '"@media screen and (min-width: 30em)": "var(--space-2)"}, ' + '"paddingLeft": {"default": "var(--space-1)", "@media screen and ' + '(min-width: 30em)": "var(--space-2)"}, "marginTop": "calc(-1 * ' + 'var(--space-2))", "marginRight": "calc(-1 * var(--space-2))", ' + '"marginBottom": "calc(-1 * var(--space-2))", "marginLeft": "calc(-1 ' + '* var(--space-2))", "gridTemplateColumns": "repeat(3, minmax(0, ' + '1fr))", "flexDirection": "column"} });\n' + "const sx_dae5511f98_c = stylex.props(sx_dae5511f98.s).className;" + ), + classes="sx_dae5511f98_c", + ), + ), + "shorthand": ( + {"styles": NO_STYLES, "style": {"margin": "0 auto"}}, + emitted( + declaration=( + 'const sx_9cc5d777ce = stylex.create({ s: {"marginTop": "0", ' + '"marginRight": "auto", "marginBottom": "0", "marginLeft": "auto"} ' + "});\n" + "const sx_9cc5d777ce_c = stylex.props(sx_9cc5d777ce.s).className;" + ), + classes="sx_9cc5d777ce_c", + ), + ), + # Props known at compile time select their styles there. + "variant_literal": ( + {"styles": BUTTON, "props": {"kind": "solid", "size": "2"}}, + emitted( + declaration=( + 'const sx_6f8a31de05 = stylex.create({ s: {"color": "white", ' + '"paddingTop": "4px", "backgroundColor": "var(--ruby-9)", "height": ' + '"2em", "fontWeight": 700} });\n' + "const sx_6f8a31de05_c = stylex.props(sx_6f8a31de05.s).className;" + ), + classes="sx_6f8a31de05_c", + imports=(RUBY,), + ), + ), + # One bound prop: a style for each of its values, holding the whole value + # of what it changes, and the style of a value that is none of them. + "variant_bound": ( + { + "styles": BUTTON, + "props": {"kind": S.kind, "size": "2"}, + "style": {"margin_top": "1px"}, + }, + emitted( + declaration=( + 'const sx_097e4917a8 = stylex.create({ s: {"height": "2em", ' + '"marginTop": "1px"}, a0_0: {"color": "white", "paddingTop": "4px", ' + '"backgroundColor": "var(--ruby-9)", "fontWeight": 700}, a0_1: ' + '{"color": "black", "opacity": 0.5}, a0: {"color": "black", ' + '"paddingTop": "4px"} });\n' + "const sx_097e4917a8_c = stylex.props(sx_097e4917a8.s).className;\n" + 'const sx_097e4917a8_0 = { __proto__: null, "solid": ' + 'stylex.props(sx_097e4917a8.a0_0).className, "soft": ' + "stylex.props(sx_097e4917a8.a0_1).className };\n" + "const sx_097e4917a8_0d = stylex.props(sx_097e4917a8.a0).className;" + ), + classes="sx_097e4917a8_c", + lookups=("(sx_097e4917a8_0[] ?? sx_097e4917a8_0d)",), + imports=(RUBY,), + vars=("",), + ), + ), + # A bound prop that changes nothing the element has without it. + "variant_bound_adds": ( + {"styles": BUTTON, "props": {"kind": "soft", "tone": VARS[""]}}, + emitted( + declaration=( + 'const sx_4dbc04f090 = stylex.create({ s: {"color": "black", ' + '"opacity": 0.5}, a0_0: {"outlineColor": "red"} });\n' + "const sx_4dbc04f090_c = stylex.props(sx_4dbc04f090.s).className;\n" + 'const sx_4dbc04f090_0 = { __proto__: null, "warm": ' + "stylex.props(sx_4dbc04f090.a0_0).className };" + ), + classes="sx_4dbc04f090_c", + lookups=('(sx_4dbc04f090_0[] ?? "")',), + vars=("",), + ), + ), + # Two bound props that a compound style combines are indexed together. + "variant_bound_grouped": ( + {"styles": BUTTON, "props": {"kind": S.kind, "size": S.size}}, + emitted( + declaration=( + 'const sx_954f5c8b18 = stylex.create({ a0_0: {"color": "white", ' + '"paddingTop": "4px", "backgroundColor": "var(--ruby-9)", "height": ' + '"1em"}, a0_1: {"color": "white", "paddingTop": "4px", ' + '"backgroundColor": "var(--ruby-9)", "height": "2em", "fontWeight": ' + '700}, a0_2: {"color": "black", "opacity": 0.5, "height": "1em"}, ' + 'a0_3: {"color": "black", "opacity": 0.5, "height": "2em"}, a0: ' + '{"color": "black", "paddingTop": "4px"} });\n' + 'const sx_954f5c8b18_0 = { __proto__: null, "solid": { __proto__: ' + 'null, "1": stylex.props(sx_954f5c8b18.a0_0).className, "2": ' + 'stylex.props(sx_954f5c8b18.a0_1).className }, "soft": { __proto__: ' + 'null, "1": stylex.props(sx_954f5c8b18.a0_2).className, "2": ' + "stylex.props(sx_954f5c8b18.a0_3).className } };\n" + "const sx_954f5c8b18_0d = stylex.props(sx_954f5c8b18.a0).className;" + ), + lookups=("(sx_954f5c8b18_0[]?.[] ?? sx_954f5c8b18_0d)",), + imports=(RUBY,), + vars=( + "", + "", + ), + ), + ), + "variant_bound_with_var_value": ( + {"styles": SIZED, "props": {"kind": S.kind}}, + emitted( + declaration=( + 'const sx_7cb0d9b7b2 = stylex.create({ a0_0: {"width": "var(--v0)"}, ' + 'a0_1: {"width": "1px"} });\n' + 'const sx_7cb0d9b7b2_0 = { __proto__: null, "a": ' + 'stylex.props(sx_7cb0d9b7b2.a0_0).className, "b": ' + "stylex.props(sx_7cb0d9b7b2.a0_1).className };" + ), + lookups=('(sx_7cb0d9b7b2_0[] ?? "")',), + variables=('"--v0": () ?? "initial"',), + vars=( + "", + "", + ), + ), + ), + "whole_var": ( + {"styles": CARD, "style": S.styles}, + emitted( + declaration=( + 'const sx_884e514c9c = stylex.create({ s: {"padding": ' + '"var(--space-3)", "borderRadius": "var(--radius-4)", "boxShadow": ' + '"var(--shadow-2)"} });\n' + "const sx_884e514c9c_c = stylex.props(sx_884e514c9c.s).className;" + ), + classes="sx_884e514c9c_c", + inline="", + vars=("",), + ), + ), + "whole_var_alone": ( + {"styles": NO_STYLES, "style": S.styles}, + emitted( + inline="", + vars=("",), + ), + ), + "whole_var_after_styles": ( + {"styles": NO_STYLES, "style": [{"width": S.width}, S.styles]}, + emitted( + declaration=( + 'const sx_67b044120d = stylex.create({ s: {"width": "var(--v0)"} });\n' + "const sx_67b044120d_c = stylex.props(sx_67b044120d.s).className;" + ), + classes="sx_67b044120d_c", + variables=('"--v0": () ?? "initial"',), + inline="", + vars=( + "", + "", + ), + ), + ), +} + + +@pytest.mark.parametrize("case", CASES) +def test_emit_writes_the_source_of_each_kind_of_style(case: str): + arguments, expected = CASES[case] + assert comparable(emit(merge("rx.ui.card", **arguments))) == expected + +def test_emit_names_a_declaration_after_its_content(): + """Equal styles share a declaration; different ones never share a name.""" + + def classes(style: dict[str, Any], name: str = "rx.ui.box") -> str | None: + return emit(merge(name, NO_STYLES, style=style)).classes -def test_props_call_applies_styles_in_order_with_literal_class_names(): - assert props_call(("sx_a.s",)) == "stylex.props(sx_a.s)" - assert props_call(("sx_a.s", "sx_b.s")) == "stylex.props(sx_a.s, sx_b.s)" - assert props_call(("sx_a.s",), 'p-8 "quoted"') == ( - 'stylex.props(sx_a.s, { $$css: true, className: "p-8 \\"quoted\\"" })' + top = {"top": "4px"} + assert classes(top) == classes(top, "rx.ui.flex") == "sx_d0020eea95_c" + assert len({classes(top), classes({"top": "5px"}), classes({"top": 4})}) == 3 + # The declaration of a bound prop does not depend on the Var it is bound to. + assert ( + emit(merge("rx.ui.button", BUTTON, {"tone": S.kind})).declaration + == emit(merge("rx.ui.button", BUTTON, {"tone": S.size})).declaration ) - assert props_call(("sx_a.s",), "") == "stylex.props(sx_a.s)" def test_inline_keeps_literals(): - assert inline({"padding": "4px", "zIndex": 2, "opacity": 0.5}, "rx.ui.box") == { - "padding": "4px", + style = {"top": "4px", "z_index": 2, "opacity": 0.5} + assert inline(merge("rx.ui.box", CARD, style=style), "rx.ui.box") == { + "padding": "var(--space-3)", + "borderRadius": "var(--radius-4)", + "boxShadow": "var(--shadow-2)", + "top": "4px", "zIndex": 2, "opacity": 0.5, } + assert inline(merge("rx.ui.box", NO_STYLES), "rx.ui.box") == {} @pytest.mark.parametrize( - ("style", "message"), + ("arguments", "message"), [ ( - {"color": {"default": "red", ":hover": "blue"}}, + {"styles": NO_STYLES, "style": {"color": "red", "_hover": {"color": "x"}}}, ( 'rx.ui.box: the style "color" has conditions ("default", ":hover"), ' "which a component rendered from state cannot apply: its code is " @@ -123,16 +531,38 @@ def test_inline_keeps_literals(): ), ), ( - {"color": Var("state.color")}, + {"styles": NO_STYLES, "style": {"color": S.width}}, + ( + 'rx.ui.box: the style "color" is bound to state, which a component ' + "rendered from state cannot apply: its code is evaluated in the browser " + "and never reaches the StyleX compiler. Use a literal value there, or " + "render the component in a page and show it with rx.cond." + ), + ), + ( + {"styles": NO_STYLES, "style": S.styles}, + ( + "rx.ui.box: the style is a Var, which a component rendered from state " + "cannot apply: its code is evaluated in the browser and never reaches " + "the StyleX compiler. Use a dict of literal values there, or render the " + "component in a page and show it with rx.cond." + ), + ), + ( + {"styles": BUTTON, "props": {"kind": S.kind, "size": S.size}}, ( - 'rx.ui.box: the style "color" is bound to state, which rx.ui components ' - "cannot compile yet. Give it a literal value, or set it from state with " - "a class_name." + 'rx.ui.box: the props "kind", "size" select a style and are bound to ' + "state, which a component rendered from state cannot apply: its code is " + "evaluated in the browser and never reaches the StyleX compiler. Give " + "them literal values there, or render the component in a page and show " + "it with rx.cond." ), ), ], ) -def test_inline_rejects_what_an_inline_style_cannot_hold(style: dict, message: str): - with pytest.raises(UnsupportedStyleError) as raised: - inline(style, "rx.ui.box") +def test_inline_rejects_what_an_inline_style_cannot_hold( + arguments: dict[str, Any], message: str +): + with pytest.raises(StyleError) as raised: + inline(merge("rx.ui.box", **arguments), "rx.ui.box") assert str(raised.value) == message diff --git a/tests/units/reflex_components_ui/style/test_merge.py b/tests/units/reflex_components_ui/style/test_merge.py index 2a5cdad8429..edc30d3e0a3 100644 --- a/tests/units/reflex_components_ui/style/test_merge.py +++ b/tests/units/reflex_components_ui/style/test_merge.py @@ -506,3 +506,29 @@ def test_errors(table: Any, style: Any, message: str): with pytest.raises(StyleError) as error: merge("rx.ui.card", table, None, style) assert str(error.value) == message + + +def test_several_styles_are_merged_in_order(): + """Each style is a layer over the ones before it, and a Var is the inline one.""" + merged = merge( + "rx.ui.button", + {"base": {"color": "black", "padding_top": "1px"}}, + style=[ + {"color": "green", "_hover": {"color": "red"}}, + {}, + MergeState.style, + {"padding": "2px", "_hover": {"opacity": 0.5}}, + ], + ) + assert merged.style.style == { + "color": {"default": "green", ":hover": "red"}, + "paddingTop": "2px", + "paddingRight": "2px", + "paddingBottom": "2px", + "paddingLeft": "2px", + "opacity": {":hover": 0.5}, + } + assert merged.style.inline is MergeState.style + assert merge("rx.ui.button", {"base": {"color": "black"}}, style=[]) == merge( + "rx.ui.button", {"base": {"color": "black"}} + ) diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py index 5e0cd2dee7a..06dd461f927 100644 --- a/tests/units/reflex_components_ui/test_base.py +++ b/tests/units/reflex_components_ui/test_base.py @@ -1,23 +1,51 @@ """Tests for reflex_components_ui.base.""" from collections.abc import Callable -from typing import ClassVar +from typing import Any, ClassVar, Literal import pytest +from reflex_base.components.component import Component +from reflex_base.components.memo import MEMOS from reflex_base.config import get_config from reflex_base.plugins import CompileContext from reflex_base.utils.exceptions import ConfigError from reflex_base.utils.serializers import serialize from reflex_base.vars.base import Var -from reflex_components_ui.base import ComponentStyles, UIComponent +from reflex_components_ui.base import Part, UIComponent from reflex_components_ui.plugin import UIPlugin -from reflex_components_ui.style.emit import UnsupportedStyleError +from reflex_components_ui.style import ComponentStyles, StyleError import reflex as rx from reflex.compiler import compiler +# A page whose elements use the tokens of two modules, two of them equally. +PAGE = """import * as stylex from "@stylexjs/stylex" +import "$/reflex-ui/colors/jade.stylex.js" +import "$/reflex-ui/colors/ruby.stylex.js" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + + + +const sx_7e30cd30d8 = stylex.create({ s: {"color": "var(--ruby-9)", "top": "8px"} }); +const sx_7e30cd30d8_c = stylex.props(sx_7e30cd30d8.s).className; +const sx_f17eb59c2d = stylex.create({ s: {"backgroundColor": "var(--jade-3)"} }); +const sx_f17eb59c2d_c = stylex.props(sx_f17eb59c2d.s).className; + +function Component() { + + + return ( + jsx(Fragment,{},jsx("main",{},jsx("section",{className:sx_7e30cd30d8_c},"ruby"),jsx("section",{className:sx_7e30cd30d8_c},"again"),jsx("div",{className:sx_f17eb59c2d_c},"jade")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + ) +} +Component.displayName = "Component(/)"; + +export default Component; +""" + # A page whose only element was moved into a module of its own. -MEMO_PAGE = """import {Card_section_b8f6e6fad3a0fd8c010369e2de15b082} from "$/utils/components/Card_section_b8f6e6fad3a0fd8c010369e2de15b082" +MEMO_PAGE = """import {Button_button_f1bbe1600e526de2c75f843fcd30a1d1} from "$/utils/components/Button_button_f1bbe1600e526de2c75f843fcd30a1d1" import {Fragment,useEffect} from "react" import {jsx} from "@emotion/react" @@ -29,7 +57,7 @@ return ( - jsx(Fragment,{},jsx(Card_section_b8f6e6fad3a0fd8c010369e2de15b082,{},"hello"),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + jsx(Fragment,{},jsx(Button_button_f1bbe1600e526de2c75f843fcd30a1d1,{},"hello"),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) ) } Component.displayName = "Component(/)"; @@ -37,31 +65,64 @@ export default Component; """ -# The module that renders the element, with the declaration of its style. +# The module that renders the element: its declaration, the table of its +# bound prop, the import of the tokens it uses and the state its styles read. MEMO_MODULE = """ -import {ReflexEvent,applyEventActions,isTrue,mergeSlotProps} from "$/utils/state" -import {addEvents} from "$/utils/context" -import {Fragment,memo,useCallback,useEffect} from "react" +import {isTrue,mergeSlotProps} from "$/utils/state" +import {useStateContext} from "$/utils/context-registry" import * as stylex from "@stylexjs/stylex" +import "$/reflex-ui/colors/ruby.stylex.js" import {jsx} from "@emotion/react" +import {Fragment,memo,useEffect} from "react" -const sx_b5d18f9eca = stylex.create({ s: {"color": {"default": "red", ":hover": "blue"}, "padding": "8px"} }); +const sx_a860bb1ca1 = stylex.create({ s: {"width": "var(--v0)", "borderTopColor": "var(--ruby-9)"}, a0_0: {"color": "white", "backgroundColor": "black"}, a0_1: {"color": "black", "opacity": 0.5}, a0: {"color": "black"} }); +const sx_a860bb1ca1_c = stylex.props(sx_a860bb1ca1.s).className; +const sx_a860bb1ca1_0 = { __proto__: null, "solid": stylex.props(sx_a860bb1ca1.a0_0).className, "soft": stylex.props(sx_a860bb1ca1.a0_1).className }; +const sx_a860bb1ca1_0d = stylex.props(sx_a860bb1ca1.a0).className; -export const Card_section_b8f6e6fad3a0fd8c010369e2de15b082 = /*#__PURE__*/ (() => { -const Card_section_b8f6e6fad3a0fd8c010369e2de15b082 = memo(({children, ...rest}) => { - const on_click_d7389fe0b34b5da3b1e38e11566dcc81 = useCallback(((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___test_base____base_test_state.noop", ({ }), ({ })))], [_e], ({ })))), []) +export const Button_button_f1bbe1600e526de2c75f843fcd30a1d1 = /*#__PURE__*/ (() => { +const Button_button_f1bbe1600e526de2c75f843fcd30a1d1 = memo(({children, ...rest}) => { + const reflex___state____state__tests___units___reflex_components_ui___test_base____base_test_state = useStateContext("reflex___state____state.tests___units___reflex_components_ui___test_base____base_test_state", ["kind_rx_state_", "color_rx_state_"]) return( - jsx("section",{...mergeSlotProps(rest, ({ onClick:on_click_d7389fe0b34b5da3b1e38e11566dcc81, ...stylex.props(sx_b5d18f9eca.s) }))},children) + jsx("button",{...mergeSlotProps(rest, ({ className:sx_a860bb1ca1_c + " " + (sx_a860bb1ca1_0[reflex___state____state__tests___units___reflex_components_ui___test_base____base_test_state.kind_rx_state_] ?? sx_a860bb1ca1_0d), style:({ "--v0": (reflex___state____state__tests___units___reflex_components_ui___test_base____base_test_state.color_rx_state_) ?? "initial" }) }))},children) ) }); -Card_section_b8f6e6fad3a0fd8c010369e2de15b082.displayName = "Card"; -return Card_section_b8f6e6fad3a0fd8c010369e2de15b082; +Button_button_f1bbe1600e526de2c75f843fcd30a1d1.displayName = "Button"; +return Button_button_f1bbe1600e526de2c75f843fcd30a1d1; })(); """ +# The module of an rx.memo component, which is named after where it is defined. +RX_MEMO_MODULE = """ +import {isTrue} from "$/utils/state" +import * as stylex from "@stylexjs/stylex" +import "$/reflex-ui/colors/ruby.stylex.js" +import {jsx} from "@emotion/react" +import {Fragment,memo,useEffect} from "react" + + + +const sx_7e30cd30d8 = stylex.create({ s: {"color": "var(--ruby-9)", "top": "8px"} }); +const sx_7e30cd30d8_c = stylex.props(sx_7e30cd30d8.s).className; + + + + +export const RubyCard_87d7d58e = /*#__PURE__*/ (() => { +const RubyCard_87d7d58e = memo(({}) => { + + return( + jsx("section",{className:sx_7e30cd30d8_c},"ruby") + ) +}); +RubyCard_87d7d58e.displayName = "RubyCard"; +return RubyCard_87d7d58e; +})(); +""".replace("", " ") + # What the browser evaluates for a component held in state. DYNAMIC_MODULE = ( "//__reflex_evaluate:[]\n" @@ -74,7 +135,10 @@ "export default function MySSRComponent () {\n" " \n" " return (\n" - ' (jsx("div", ({className:"p-8",style:({ ["padding"] : "4px", ["zIndex"] : 2 })}), "hello"))\n' + ' (jsx("button", ({className:"p-8",style:({ ["color"] : "black", ' + '["opacity"] : 0.5, ["paddingTop"] : "4px", ["paddingRight"] : "4px", ' + '["paddingBottom"] : "4px", ["paddingLeft"] : "4px", ["zIndex"] : 2 })}), ' + '"hello"))\n' " )\n" "}" ) @@ -90,29 +154,103 @@ class Card(UIComponent): tag = "section" styles: ClassVar[ComponentStyles] = { - "base": {"color": {"default": "red", ":hover": "blue"}, "padding": "8px"}, + "base": {"color": {"default": "red", ":hover": "blue"}, "top": "8px"}, } -class Variants(UIComponent): - """An element whose look depends on a prop.""" +class Button(UIComponent): + """An element with variants, a layout prop and an attribute.""" + + tag = "button" styles: ClassVar[ComponentStyles] = { - "variants": {"size": {"1": {"padding": "4px"}}} + "base": {"color": "black"}, + "variants": { + "kind": { + "solid": {"color": "white", "background_color": "black"}, + "soft": {"opacity": 0.5}, + }, + "size": {"1": {"height": "1em"}, "2": {"height": "2em"}}, + }, + "compound": [ + {"props": {"kind": "solid", "size": "2"}, "style": {"font_weight": 700}}, + ], } + # Which look the button has. + kind: Var[Literal["solid", "soft"]] + + # How tall the button is. + size: Var[Literal["1", "2"]] + + # The space between the children. + gap: Var[str] + + # The tooltip of the element. + title: Var[str] + + +class Switch(UIComponent): + """An element with an inner element that the same props style.""" + + tag = "button" + + styles: ClassVar[ComponentStyles] = { + "base": {"width": "2em"}, + "parts": { + "track": {"base": {"display": "block"}}, + "thumb": { + "base": {"width": "1em"}, + "variants": {"size": {"2": {"width": "2em"}}}, + }, + }, + } + + # How large the switch is. + size: Var[Literal["1", "2"]] + + @classmethod + def create(cls, *children, **props) -> Component: + """Create the switch around its track and thumb. + + Args: + *children: The children of the component. + **props: The props of the component. + + Returns: + The component. + """ + return super().create( + Part.create( + Part.create(part="thumb", tag="span"), part="track", tag="span" + ), + *children, + **props, + ) + class BaseTestState(rx.State): - """State the styles and class names are bound to.""" + """State the styles, the props and the class names are bound to.""" - color: str = "red" - names: str = "p-8" + color: rx.Field[str] = rx.field("red") + names: rx.Field[str] = rx.field("p-8") + kind: rx.Field[str] = rx.field("solid") + size: rx.Field[str] = rx.field("1") + styles: rx.Field[dict[str, str]] = rx.field(default_factory=dict) @rx.event def noop(self): """Do nothing.""" +S = BaseTestState + +# Styles a type checker refuses, typed loosely to reach the compiler. +MISSPELT: Any = {"paddng": "1em"} +NESTED: Any = {"& > div": {"color": "red"}} +NOT_A_STYLE: Any = ["color: red"] + + def test_rendering_without_the_plugin_says_how_to_configure_it( monkeypatch: pytest.MonkeyPatch, compile_page: Callable[..., CompileContext] ): @@ -139,96 +277,403 @@ def test_element_without_styles_is_a_plain_element(ui_plugin: UIPlugin): "children": [{"contents": '"hello"'}], } assert component._get_all_custom_code() == {} + assert component._get_all_imports() == {} def test_style_is_spread_from_a_declaration_and_never_a_css_prop(ui_plugin: UIPlugin): """The user's style is merged over the component's, by property.""" - component = Card.create("hello", style={"padding": "4px", "margin_top": 2}) + component = Card.create("hello", style={"top": "4px", "margin_top": 2}) assert component._get_all_custom_code() == { - 'const sx_5579d75d4f = stylex.create({ s: {"color": {"default": "red", ' - '":hover": "blue"}, "padding": "4px", "marginTop": 2} });': None + 'const sx_14c89d843a = stylex.create({ s: {"color": {"default": "red", ' + '":hover": "blue"}, "top": "4px", "marginTop": 2} });\n' + "const sx_14c89d843a_c = stylex.props(sx_14c89d843a.s).className;": None } assert component.render() == { "name": '"section"', - "props": ["...stylex.props(sx_5579d75d4f.s)"], + "props": ["className:sx_14c89d843a_c"], "children": [{"contents": '"hello"'}], } assert component._get_style() == {} -def test_literal_class_names_fold_into_the_spread(ui_plugin: UIPlugin): - """A spread would replace a className prop, so there is only the spread.""" - component = Card.create(class_name=["p-8", "m-2"], custom_attrs={"role": "note"}) - assert component.render()["props"] == [ - 'role:"note"', - '...stylex.props(sx_b5d18f9eca.s, { $$css: true, className: "p-8 m-2" })', - ] - +def test_keyword_arguments_are_props_events_attributes_or_styles(ui_plugin: UIPlugin): + """Only what is none of the first three is read as a CSS property. -def test_class_names_from_state_are_joined_with_the_folded_ones(ui_plugin: UIPlugin): - component = Card.create(class_name=BaseTestState.names) + A prop the style table reads and a layout prop are styles too: neither is + an attribute of the element. + """ + component = Button.create( + "save", + kind="solid", + size="2", + gap="3", + title="Save", + id="save", + data_state="on", + aria_label="Save", + on_click=S.noop, + margin_top="1px", + style={"margin_top": "2px", "top": 0}, + ) + assert component._get_all_custom_code() == { + 'const sx_1027767e47 = stylex.create({ s: {"color": "white", ' + '"backgroundColor": "black", "height": "2em", "fontWeight": 700, "rowGap": ' + '"var(--space-3)", "columnGap": "var(--space-3)", "top": 0, "marginTop": ' + '"1px"} });\n' + "const sx_1027767e47_c = stylex.props(sx_1027767e47.s).className;": None + } assert component.render()["props"] == [ + '"aria-label":"Save"', + "className:sx_1027767e47_c", + '"data-state":"on"', + 'id:"save"', ( - f'className:({BaseTestState.names!s}) + " " + ' - "stylex.props(sx_b5d18f9eca.s).className" - ) + 'onClick:((_e) => (addEvents([(ReflexEvent("reflex___state____state.' + 'tests___units___reflex_components_ui___test_base____base_test_state.noop", ' + "({ }), ({ })))], [_e], ({ }))))" + ), + "ref:ref_save", + 'title:"Save"', ] + assert list(component.event_triggers) == ["on_click"] + assert component.style == {} @pytest.mark.parametrize( ("create", "message"), [ ( - lambda: Card.create(style={"color": BaseTestState.color}), + lambda: Card.create(paddng="1em"), + 'rx.ui.card: unknown CSS property "paddng". Did you mean "padding"?', + ), + ( + lambda: Card.create(style=MISSPELT), + 'rx.ui.card: unknown CSS property "paddng". Did you mean "padding"?', + ), + ( + lambda: Card.create(style=NESTED), ( - 'rx.ui.card: the style "color" is bound to state, which rx.ui ' - "components cannot compile yet. Give it a literal value, or set it " - "from state with a class_name." + 'rx.ui.card: style key "& > div" is a nested selector, which rx.ui ' + "styles do not support. Style the child component directly, or keep " + "rx.card for this element." ), ), ( - lambda: Card.create(style={"_hover": {"color": "blue"}}), + # A layout prop of another component is not one of this one. + lambda: Card.create(spacing="3"), + 'rx.ui.card: unknown CSS property "spacing". Did you mean "padding"?', + ), + ( + lambda: Card.create(style=NOT_A_STYLE), ( - 'rx.ui.card: the style "_hover" is a nested block or a list, which ' - "rx.ui components cannot compile yet. Use flat properties with literal " - "values." + "rx.ui.card: style must be a dict of styles, a list of them or a " + "Var, not str." ), ), ( - lambda: Card.create(style={"width": ["100%", "50%"]}), + lambda: Button.create(gap=S.color), ( - 'rx.ui.card: the style "width" is a nested block or a list, which ' - "rx.ui components cannot compile yet. Use flat properties with literal " - "values." + 'rx.ui.button: layout prop "gap" is bound to state, but its values ' + 'are read at compile time. Bind the "gap" style instead, which takes ' + "any CSS value." ), ), ( - lambda: Variants.create(), - "rx.ui.variants: variant and compound styles are not compiled yet.", + lambda: Card.create(background=S.color), + ( + 'rx.ui.card: style "background" is bound to state, but rx.ui styles ' + "split this shorthand into longhands at compile time. Bind " + "background_color, background_image and its other longhands instead." + ), ), ], ) -def test_style_that_cannot_be_compiled_yet_is_an_error( - ui_plugin: UIPlugin, create: Callable[[], UIComponent], message: str +def test_style_that_cannot_be_compiled_is_an_error_where_it_is_written( + create: Callable[[], UIComponent], message: str ): - component = create() - with pytest.raises(UnsupportedStyleError) as raised: - component.render() + with pytest.raises(StyleError) as raised: + create() assert str(raised.value) == message - with pytest.raises(UnsupportedStyleError) as raised: - component._get_all_custom_code() + + +def test_unknown_event_trigger_is_not_mistaken_for_a_style(): + with pytest.raises(ValueError) as raised: + Plain.create(on_paddng=S.noop) + assert str(raised.value) == ( + "The Plain does not take in an `on_paddng` event trigger. Valid triggers " + "for Plain: ['on_blur', 'on_click', 'on_context_menu', 'on_double_click', " + "'on_focus', 'on_mount', 'on_mouse_down', 'on_mouse_enter', " + "'on_mouse_leave', 'on_mouse_move', 'on_mouse_out', 'on_mouse_over', " + "'on_mouse_up', 'on_scroll', 'on_scroll_end', 'on_unmount']. If Plain is a " + "third party component make sure to add `on_paddng` to the component's " + "event triggers. visit " + "https://reflex.dev/docs/wrapping-react/guide/#event-triggers for more info." + ) + + +def test_styles_in_a_list_and_keywords_are_written_over_each_other( + ui_plugin: UIPlugin, +): + """A key replaces the same key, as in the style of any Reflex component. + + What is written last wins over a shorthand or a longhand written before + it, and a keyword argument is written after the ``style``. + """ + component = Plain.create( + style=[ + {"padding_top": "1px", "_hover": {"color": "red"}}, + {"padding": "2px", "_hover": {"opacity": 0.5}}, + {"padding_top": "3px"}, + ], + color="blue", + ) + assert component._get_all_custom_code() == { + 'const sx_1799fc9438 = stylex.create({ s: {"paddingTop": "3px", ' + '"paddingRight": "2px", "paddingBottom": "2px", "paddingLeft": "2px", ' + '"opacity": {":hover": 0.5}, "color": "blue"} });\n' + "const sx_1799fc9438_c = stylex.props(sx_1799fc9438.s).className;": None + } + + +def test_style_per_breakpoint_becomes_blocks_under_media_queries(ui_plugin: UIPlugin): + named = Plain.create( + style=rx.breakpoints(initial={"color": "red", "top": 0}, sm={"color": "blue"}) + ) + assert named._get_all_custom_code() == { + 'const sx_10c4c20799 = stylex.create({ s: {"color": {"default": "red", ' + '"@media screen and (min-width: 48em)": "blue"}, "top": 0} });\n' + "const sx_10c4c20799_c = stylex.props(sx_10c4c20799.s).className;": None + } + custom = Plain.create(style=rx.breakpoints({"0px": {"top": 0}, "40em": {"top": 1}})) + assert custom._get_all_custom_code() == { + 'const sx_8b8c48b483 = stylex.create({ s: {"top": {"@media screen and ' + '(min-width: 0px)": 0, "@media screen and (min-width: 40em)": 1}} });\n' + "const sx_8b8c48b483_c = stylex.props(sx_8b8c48b483.s).className;": None + } + + +def test_literal_class_names_are_joined_with_those_of_the_style(ui_plugin: UIPlugin): + """The element has one className: its own class names, then the constant.""" + component = Card.create(class_name=["p-8", "m-2"], custom_attrs={"role": "note"}) + assert component.render()["props"] == [ + 'className:"p-8 m-2 " + sx_262fdfab15_c', + 'role:"note"', + ] + + +def test_class_names_from_state_are_joined_with_those_of_the_style(ui_plugin: UIPlugin): + component = Card.create(class_name=S.names) + assert component.render()["props"] == [ + f'className:({S.names!s}) + " " + sx_262fdfab15_c' + ] + + +def test_value_bound_to_state_is_a_custom_property_of_the_element(ui_plugin: UIPlugin): + component = Card.create(width=S.color, class_name="p-8", style=S.styles) + assert component._get_all_custom_code() == { + 'const sx_bf234bb6b2 = stylex.create({ s: {"color": {"default": "red", ' + '":hover": "blue"}, "top": "8px", "width": "var(--v0)"} });\n' + "const sx_bf234bb6b2_c = stylex.props(sx_bf234bb6b2.s).className;": None + } + assert component.render()["props"] == [ + 'className:"p-8 " + sx_bf234bb6b2_c', + f'style:({{ "--v0": ({S.color!s}) ?? "initial", ...{S.styles!s} }})', + ] + # The Vars bring the hooks that read the state into the module. + assert [str(var) for var in component._get_vars()] == [ + str(S.color), + str(S.styles), + ] + + +def test_whole_style_from_state_is_the_inline_style(ui_plugin: UIPlugin): + component = Plain.create(style=S.styles) + assert component._get_all_custom_code() == {} + assert component.render()["props"] == [f"style:{S.styles!s}"] + + +# The styles of each value of the button's kind, and of a value that is none. +KIND_DECLARATION = ( + 'const sx_749372103b = stylex.create({ a0_0: {"color": "white", ' + '"backgroundColor": "black"}, a0_1: {"color": "black", "opacity": 0.5}, a0: ' + '{"color": "black"} });\n' + 'const sx_749372103b_0 = { __proto__: null, "solid": ' + 'stylex.props(sx_749372103b.a0_0).className, "soft": ' + "stylex.props(sx_749372103b.a0_1).className };\n" + "const sx_749372103b_0d = stylex.props(sx_749372103b.a0).className;" +) +KIND_LOOKUP = "(sx_749372103b_0[] ?? sx_749372103b_0d)" + + +@pytest.mark.parametrize( + ("props", "declaration", "rendered"), + [ + ({"kind": S.kind}, KIND_DECLARATION, [f"className:{KIND_LOOKUP}"]), + ( + {"kind": S.kind, "class_name": "p-8"}, + KIND_DECLARATION, + [f'className:"p-8 " + {KIND_LOOKUP}'], + ), + ( + {"kind": S.kind, "class_name": S.names}, + KIND_DECLARATION, + [f'className:() + " " + {KIND_LOOKUP}'], + ), + ( + # Props that a compound style combines are indexed together. + {"kind": S.kind, "size": S.size}, + ( + 'const sx_5874f5ad04 = stylex.create({ a0_0: {"color": "white", ' + '"backgroundColor": "black", "height": "1em"}, a0_1: {"color": ' + '"white", "backgroundColor": "black", "height": "2em", "fontWeight": ' + '700}, a0_2: {"color": "black", "opacity": 0.5, "height": "1em"}, ' + 'a0_3: {"color": "black", "opacity": 0.5, "height": "2em"}, a0: ' + '{"color": "black"} });\n' + 'const sx_5874f5ad04_0 = { __proto__: null, "solid": { __proto__: ' + 'null, "1": stylex.props(sx_5874f5ad04.a0_0).className, "2": ' + 'stylex.props(sx_5874f5ad04.a0_1).className }, "soft": { __proto__: ' + 'null, "1": stylex.props(sx_5874f5ad04.a0_2).className, "2": ' + "stylex.props(sx_5874f5ad04.a0_3).className } };\n" + "const sx_5874f5ad04_0d = stylex.props(sx_5874f5ad04.a0).className;" + ), + ["className:(sx_5874f5ad04_0[]?.[] ?? sx_5874f5ad04_0d)"], + ), + ], +) +def test_prop_bound_to_state_indexes_the_class_names_of_its_values( + ui_plugin: UIPlugin, props: dict[str, Any], declaration: str, rendered: list[str] +): + component = Button.create(**props) + assert component._get_all_custom_code() == {declaration: None} + assert component.render()["props"] == [ + prop + .replace("", str(S.kind)) + .replace("", str(S.size)) + .replace("", str(S.names)) + for prop in rendered + ] + + +def test_parts_are_styled_by_the_table_of_their_component(ui_plugin: UIPlugin): + """A part reads the props of its component, bound to state or not.""" + width = ( + 'const sx_95ab4202b0 = stylex.create({ s: {"width": "2em"} });\n' + "const sx_95ab4202b0_c = stylex.props(sx_95ab4202b0.s).className;" + ) + block = ( + 'const sx_1cb1fb1245 = stylex.create({ s: {"display": "block"} });\n' + "const sx_1cb1fb1245_c = stylex.props(sx_1cb1fb1245.s).className;" + ) + component = Switch.create("on", size="2") + # The switch and its thumb have the same style, and share its declaration. + assert component._get_all_custom_code() == {width: None, block: None} + assert component.render() == { + "name": '"button"', + "props": ["className:sx_95ab4202b0_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_1cb1fb1245_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_95ab4202b0_c"], + "children": [], + } + ], + }, + {"contents": '"on"'}, + ], + } + bound = Switch.create(size=S.size) + assert bound._get_all_custom_code() == { + width: None, + block: None, + ( + 'const sx_bd2235d0fb = stylex.create({ a0_0: {"width": "2em"}, a0: ' + '{"width": "1em"} });\n' + 'const sx_bd2235d0fb_0 = { __proto__: null, "2": ' + "stylex.props(sx_bd2235d0fb.a0_0).className };\n" + "const sx_bd2235d0fb_0d = stylex.props(sx_bd2235d0fb.a0).className;" + ): None, + } + thumb = bound.render()["children"][0]["children"][0] + assert thumb == { + "name": '"span"', + "props": [f"className:(sx_bd2235d0fb_0[{S.size!s}] ?? sx_bd2235d0fb_0d)"], + "children": [], + } + # The size is a style of the switch and its thumb, not an attribute. + assert bound.render()["props"] == ["className:sx_95ab4202b0_c"] + + +def test_part_outside_its_component_says_where_it_belongs(ui_plugin: UIPlugin): + with pytest.raises(StyleError) as raised: + Switch.create(Part.create(part="thum")) + assert str(raised.value) == ( + 'rx.ui.switch: its style table has no part "thum". Did you mean "thumb"?' + ) + with pytest.raises(StyleError) as raised: + Part.create(part="thumb", color="red") + assert str(raised.value) == ( + 'rx.ui.part: the part "thumb" takes its styles from the style table of its ' + "component. Style it there." + ) + stray = Plain.create(Part.create(part="thumb")) + message = ( + 'rx.ui.part: the part "thumb" is not in a component whose style table has ' + "it. Create it as a child of its component, or of another part of it." + ) + with pytest.raises(StyleError) as raised: + stray.render() assert str(raised.value) == message + # The same holds where the component is evaluated in the browser. + with pytest.raises(StyleError) as raised: + serialize(stray) + assert str(raised.value) == message + + +def test_styles_of_the_app_apply_before_those_of_the_element(ui_plugin: UIPlugin): + component = Card.create(top="1px") + component._add_style_recursive({ + Card: rx.Style({"top": "2px", "color": "green", "_hover": {"left": 0}}) + }) + assert component._get_all_custom_code() == { + 'const sx_802fe7deea = stylex.create({ s: {"color": "green", "top": "1px", ' + '"left": {":hover": 0}} });\n' + "const sx_802fe7deea_c = stylex.props(sx_802fe7deea.s).className;": None + } -def test_declaration_follows_the_element_into_a_memo_module( +def test_page_declares_styles_and_imports_the_modules_of_their_tokens( + ui_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + def page(): + return rx.el.main( + Card.create("ruby", color=rx.color("ruby", 9)), + Card.create("again", color=rx.color("ruby", 9)), + Plain.create("jade", background_color=rx.color("jade", 3)), + ) + + assert compile_page(page).compiled_pages["/"].output_code == PAGE + + +def test_declaration_and_imports_follow_the_element_into_a_memo_module( ui_plugin: UIPlugin, compile_page: Callable[..., CompileContext] ): """StyleX only folds a style declared in the module that renders it. - An event handler makes the compiler move the element into a module of its - own: the declaration and the import go there, and leave the page. + A value bound to state makes the compiler move the element into a module + of its own: the declaration and the imports go there, and leave the page. """ - ctx = compile_page(lambda: Card.create("hello", on_click=BaseTestState.noop)) + ctx = compile_page( + lambda: Button.create( + "hello", + kind=S.kind, + width=S.color, + border_top_color=rx.color("ruby", 9), + ) + ) assert ctx.compiled_pages["/"].output_code == MEMO_PAGE ((_, memo_module),) = compiler.compile_memo_components( tuple(ctx.auto_memo_components.values()) @@ -236,32 +681,64 @@ def test_declaration_follows_the_element_into_a_memo_module( assert memo_module == MEMO_MODULE +def test_declaration_and_imports_follow_the_element_into_an_rx_memo_module( + ui_plugin: UIPlugin, preserve_memo_registries: None +): + @rx.memo + def ruby_card() -> rx.Component: + return Card.create("ruby", color=rx.color("ruby", 9)) + + ((_, memo_module),) = compiler.compile_memo_components(( + next(memo for memo in MEMOS.values() if memo.python_name == "ruby_card"), + ))[0] + assert memo_module == RX_MEMO_MODULE + + def test_dynamic_component_falls_back_to_an_inline_style(): """Code evaluated in the browser has no build, no plugin and no StyleX.""" - component = Plain.create( - "hello", style={"padding": "4px", "z_index": 2}, class_name="p-8" + component = Button.create( + "hello", kind="soft", style={"padding": "4px", "z_index": 2}, class_name="p-8" ) assert serialize(component) == DYNAMIC_MODULE -def test_dynamic_component_cannot_have_a_conditional_style(): - with pytest.raises(UnsupportedStyleError) as raised: - serialize(Card.create("hello")) - assert str(raised.value) == ( - 'rx.ui.card: the style "color" has conditions ("default", ":hover"), which ' - "a component rendered from state cannot apply: its code is evaluated in " - "the browser and never reaches the StyleX compiler. Use an unconditional " - "value there, or render the component in a page and show it with rx.cond." - ) - - -def test_var_style_values_reach_the_error_of_the_emitter(ui_plugin: UIPlugin): - """A state-bound value is not mistaken for a literal on its way down.""" - component = Card.create(style={"color": Var("state.color", _var_type=str)}) - with pytest.raises(UnsupportedStyleError) as raised: - component.render() - assert str(raised.value) == ( - 'rx.ui.card: the style "color" is bound to state, which rx.ui components ' - "cannot compile yet. Give it a literal value, or set it from state with a " - "class_name." - ) +@pytest.mark.parametrize( + ("create", "message"), + [ + ( + lambda: Card.create("hello"), + ( + 'rx.ui.card: the style "color" has conditions ("default", ":hover"), ' + "which a component rendered from state cannot apply: its code is " + "evaluated in the browser and never reaches the StyleX compiler. Use an " + "unconditional value there, or render the component in a page and show " + "it with rx.cond." + ), + ), + ( + lambda: Plain.create(width=S.color), + ( + 'rx.ui.plain: the style "width" is bound to state, which a component ' + "rendered from state cannot apply: its code is evaluated in the browser " + "and never reaches the StyleX compiler. Use a literal value there, or " + "render the component in a page and show it with rx.cond." + ), + ), + ( + lambda: Button.create(kind=S.kind), + ( + 'rx.ui.button: the props "kind" select a style and are bound to ' + "state, which a component rendered from state cannot apply: its code is " + "evaluated in the browser and never reaches the StyleX compiler. Give " + "them literal values there, or render the component in a page and show " + "it with rx.cond." + ), + ), + ], +) +def test_dynamic_component_cannot_have_a_style_that_needs_the_compiler( + create: Callable[[], UIComponent], message: str +): + with pytest.raises(StyleError) as raised: + serialize(create()) + assert str(raised.value) == message From 4fa651ef533bfa9314ed8a62d517cf17bedef329 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:51:18 +0000 Subject: [PATCH 21/26] Refuse a Radix theme in UIPlugin, and test selection and a state-bound theme live Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- .../src/reflex_components_ui/plugin.py | 17 +++- .../src/reflex_components_ui/tokens.py | 4 +- .../tests_playwright/test_ui_components.py | 78 ++++++++++++++++++- .../units/reflex_components_ui/test_plugin.py | 22 +++++- 4 files changed, 116 insertions(+), 5 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/plugin.py b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py index 8fe898aeebb..a63ecd2fdc6 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/plugin.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/plugin.py @@ -16,7 +16,7 @@ STYLEX_VERSION, WEB_DIR, ) -from reflex_components_ui.themes import Theme +from reflex_components_ui.themes import Theme, ThemeError # Declares the cascade layers, so it comes before any stylesheet that names one. BASE_STYLESHEET_IMPORT = f"@import url('../{WEB_DIR}/base.css');" @@ -78,6 +78,21 @@ class UIPlugin(Plugin): theme: Theme = dataclasses.field(default_factory=Theme) + def __post_init__(self): + """Check that the theme is one of rx.ui. + + Raises: + ThemeError: If the theme is something else, such as the theme + component of Radix Themes. + """ + if not isinstance(self.theme, Theme): + msg = ( + "rx.plugins.UIPlugin: theme must be an rx.ui.Theme(...), not " + f"{type(self.theme).__name__}. The theme of Radix Themes, " + "rx.theme(...), goes to rx.plugins.RadixThemesPlugin." + ) + raise ThemeError(msg) + def get_frontend_development_dependencies(self, **context) -> list[str]: """Get the packages that compile the styles. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/tokens.py b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py index 02ac53bb8a5..a65a1176ba8 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/tokens.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/tokens.py @@ -18,7 +18,7 @@ from __future__ import annotations -from typing import Literal, NoReturn +from typing import Literal, NoReturn, get_args from reflex_base.utils.exceptions import ReflexError @@ -540,7 +540,7 @@ def scale(name: LiteralColorScale) -> _Scale: """ found = _SCALES.get(name) if found is None: - scales = LiteralColorScale.__args__ + scales = get_args(LiteralColorScale) if name == "accent" or name == "gray": msg = ( f'rx.ui.tokens.scale: "{name}" is not a color scale of its own, ' diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 9ed13c38041..0476481abe1 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -204,17 +204,43 @@ def mixed(): ), ) + if radix: + + class ThemeState(rx.State): + accent: str = "red" + appearance: str = "inherit" + + @rx.event + def change(self): + self.accent = "green" + self.appearance = "dark" + + def bound(): + return rx.el.main( + rx.ui.theme( + probe("bound-probe"), + accent_color=ThemeState.accent, + gray_color="slate", + appearance=ThemeState.appearance, + id="bound", + ), + rx.el.button("change", id="change", on_click=ThemeState.change), + ) + assets = Path.cwd() / "assets" assets.mkdir(exist_ok=True) (assets / "unlayered.css").write_text(".unlayered { padding: 2px }") - app = rx.App(stylesheets=["unlayered.css"], enable_state=False) + # Only the app beside Radix Themes has state: the other one shows what a + # page costs without it. + app = rx.App(stylesheets=["unlayered.css"], enable_state=radix) app.add_page(index) app.add_page(literal, route="/literal") app.add_page(theme, route="/theme") app.add_page(sweep, route="/sweep") if radix: app.add_page(mixed, route="/mixed") + app.add_page(bound, route="/bound") config = rx.config.get_config() config.plugins = [ @@ -571,6 +597,23 @@ def test_nested_theme_overrides_its_subtree_only(ui_app: AppHarness, page: Page) ]; })""" ) + # Text selected inside a theme has the color of its focus ring. + selection = page.evaluate( + """() => ["root-probe", "nested-probe"].map((id) => { + const probe = document.getElementById(id); + const reference = probe.appendChild(document.createElement("i")); + reference.style.color = "var(--focus-a5)"; + return [ + getComputedStyle(probe, "::selection").backgroundColor, + getComputedStyle(reference).color, + ]; + })""" + ) + # Indigo a5 of the light scale, and red a5 of the dark one. + assert selection == [ + ["rgba(0, 68, 255, 0.176)", "rgba(0, 68, 255, 0.176)"], + ["rgba(255, 32, 71, 0.337)", "rgba(255, 32, 71, 0.337)"], + ] viewport = page.viewport_size assert viewport is not None assert themes == [ @@ -815,3 +858,36 @@ def read(theme: str) -> list[list[str]]: ["rgba(34, 255, 153, 0.118)", "rgba(70, 254, 165, 0.83)"], ] assert in_ui_theme == read("radix-dark") + + +def test_theme_bound_to_state_follows_it(mixed_app: AppHarness, page: Page): + """Every accent is on the page, and the browser applies the one in state.""" + assert mixed_app.frontend_url is not None + page.goto(mixed_app.frontend_url.rstrip("/") + "/bound/") + probe = page.locator("#bound-probe") + expect(probe).to_have_css("color", RED_11["light"]) + + def read() -> list[str]: + return page.locator("#bound").evaluate( + """(theme) => [ + getComputedStyle(theme.querySelector("#bound-probe")).backgroundColor, + getComputedStyle(theme).colorScheme, + getComputedStyle(theme).backgroundColor, + [...theme.parentElement.classList].filter((name) => + ["inherit", "light", "dark"].includes(name), + ).join(" "), + getComputedStyle(theme.parentElement).display, + ]""" + ) + + # The appearance of the page, and no background of its own. + assert read() == [ + SLATE_2["light"], + "light", + "rgba(0, 0, 0, 0)", + "inherit", + "contents", + ] + page.locator("#change").click() + expect(probe).to_have_css("color", "rgb(61, 214, 140)") + assert read() == [SLATE_2["dark"], "dark", "rgb(17, 17, 19)", "dark", "contents"] diff --git a/tests/units/reflex_components_ui/test_plugin.py b/tests/units/reflex_components_ui/test_plugin.py index 5abdf50cf76..721fb782ce2 100644 --- a/tests/units/reflex_components_ui/test_plugin.py +++ b/tests/units/reflex_components_ui/test_plugin.py @@ -8,7 +8,9 @@ from reflex_base.plugins import VitePluginEntry from reflex_components_ui.constants import JS_SRC from reflex_components_ui.plugin import UIPlugin, add_base_stylesheet -from reflex_components_ui.themes import Theme +from reflex_components_ui.themes import Theme, ThemeError + +import reflex as rx def test_plugin_installs_the_style_compiler_for_the_build_only(): @@ -95,3 +97,21 @@ def test_plugin_has_a_theme(): "radius='medium', scaling='100%', appearance='inherit', " "panel_background='translucent', has_background=True))" ) + + +def test_plugin_refuses_a_theme_of_radix_themes(): + """The two themes are easy to take for each other in rxconfig.py.""" + with pytest.raises(ThemeError) as error: + UIPlugin(theme=rx.theme(accent_color="indigo")) # pyright: ignore [reportArgumentType] + assert str(error.value) == ( + "rx.plugins.UIPlugin: theme must be an rx.ui.Theme(...), not Theme. The " + "theme of Radix Themes, rx.theme(...), goes to " + "rx.plugins.RadixThemesPlugin." + ) + with pytest.raises(ThemeError) as error: + UIPlugin(theme={"accent_color": "indigo"}) # pyright: ignore [reportArgumentType] + assert str(error.value) == ( + "rx.plugins.UIPlugin: theme must be an rx.ui.Theme(...), not dict. The " + "theme of Radix Themes, rx.theme(...), goes to " + "rx.plugins.RadixThemesPlugin." + ) From 5127fc7404b434b36b9d95a836da718f9dbbd58d Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 11:55:14 +0000 Subject: [PATCH 22/26] Type the state-bound page of the shared test app Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- .../tests_playwright/test_ui_components.py | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 0476481abe1..2b7980ef34c 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -204,7 +204,19 @@ def mixed(): ), ) + assets = Path.cwd() / "assets" + assets.mkdir(exist_ok=True) + (assets / "unlayered.css").write_text(".unlayered { padding: 2px }") + + # Only the app beside Radix Themes has state: the other one shows what a + # page costs without it. + app = rx.App(stylesheets=["unlayered.css"], enable_state=radix) + app.add_page(index) + app.add_page(literal, route="/literal") + app.add_page(theme, route="/theme") + app.add_page(sweep, route="/sweep") if radix: + app.add_page(mixed, route="/mixed") class ThemeState(rx.State): accent: str = "red" @@ -219,27 +231,14 @@ def bound(): return rx.el.main( rx.ui.theme( probe("bound-probe"), - accent_color=ThemeState.accent, + accent_color=ThemeState.accent, # pyright: ignore [reportArgumentType] gray_color="slate", - appearance=ThemeState.appearance, + appearance=ThemeState.appearance, # pyright: ignore [reportArgumentType] id="bound", ), rx.el.button("change", id="change", on_click=ThemeState.change), ) - assets = Path.cwd() / "assets" - assets.mkdir(exist_ok=True) - (assets / "unlayered.css").write_text(".unlayered { padding: 2px }") - - # Only the app beside Radix Themes has state: the other one shows what a - # page costs without it. - app = rx.App(stylesheets=["unlayered.css"], enable_state=radix) - app.add_page(index) - app.add_page(literal, route="/literal") - app.add_page(theme, route="/theme") - app.add_page(sweep, route="/sweep") - if radix: - app.add_page(mixed, route="/mixed") app.add_page(bound, route="/bound") config = rx.config.get_config() From b6ccd8692996225ebb0db391fa9ef9aff9a31f00 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 12:01:06 +0000 Subject: [PATCH 23/26] Wait for the hydration commit before the parity harness reads a page A fiber key on a frame is set while React still renders the hydration, before Emotion moves its prerendered style tags and before any effect runs, so the look runner could measure a style tag as the Radix box and the contract runner could drive a page whose hooks were not attached. Every page of the harness app now ends in a marker whose effect flags the document, both runners wait for the flag, and a frame's element is its first child that renders. Claude-Session: https://claude.ai/code/session_014AwvTQ75r2sBu4cRnbDwHn --- packages/reflex-components-ui/README.md | 5 +- .../parity/ui_parity/app.py | 3 + .../parity/ui_parity/contract.py | 10 +--- .../parity/ui_parity/hydration.py | 46 +++++++++++++++ .../parity/ui_parity/look.py | 30 +++++----- .../parity/ui_parity/matrix.py | 2 +- .../tests_playwright/test_ui_parity.py | 59 ++++++++++++++++++- 7 files changed, 129 insertions(+), 26 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/hydration.py diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 692c741d015..9d508485d4c 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -399,8 +399,9 @@ registers it. Both systems are on one page, in frames on the pixel grid, and are cropped by the same rectangle relative to their frame. The device scale factor and the -viewport are fixed, the page is hydrated and its fonts loaded before it is -read, transitions and animations are off, and the "Built with Reflex" badge is +viewport are fixed, the page is hydrated (an effect of the first render has +run, so the root committed) and its fonts loaded before it is read, a style +or script tag beside a component is never taken for it, transitions and animations are off, and the "Built with Reflex" badge is not rendered. Hover, focus and active are driven through the pointer and the keyboard, never by a class, and the run stops if an element does not match `:hover`, `:focus-visible` or `:active` when it should. The CI jobs do not diff --git a/packages/reflex-components-ui/parity/ui_parity/app.py b/packages/reflex-components-ui/parity/ui_parity/app.py index cfbdf37e84a..ed81eabacba 100644 --- a/packages/reflex-components-ui/parity/ui_parity/app.py +++ b/packages/reflex-components-ui/parity/ui_parity/app.py @@ -13,6 +13,7 @@ import reflex as rx from ui_parity.components import CONTRACTS, MATRICES from ui_parity.contract import Contract +from ui_parity.hydration import HydrationMarker from ui_parity.matrix import Matrix from ui_parity.systems import SYSTEMS, System @@ -109,6 +110,7 @@ def parity_page(matrix: Matrix) -> rx.Component: for props_id, props in matrix.rendered().items() for system in SYSTEMS ), + HydrationMarker.create(), style={ "display": "grid", "grid_template_columns": f"repeat(auto-fill, {matrix.stage[0]}px)", @@ -130,6 +132,7 @@ def contract_page(contract: Contract, system: System) -> rx.Component: """ return rx.el.main( contract.render(system.namespace), + HydrationMarker.create(), custom_attrs={"data-contract-root": system.name}, style={"padding": f"{PADDING}px"}, ) diff --git a/packages/reflex-components-ui/parity/ui_parity/contract.py b/packages/reflex-components-ui/parity/ui_parity/contract.py index 322a3cfa754..c904e9ac91c 100644 --- a/packages/reflex-components-ui/parity/ui_parity/contract.py +++ b/packages/reflex-components-ui/parity/ui_parity/contract.py @@ -17,6 +17,7 @@ from playwright.sync_api import Browser, ConsoleMessage, Page from ui_parity.allowlist import Allowlist +from ui_parity.hydration import IS_HYDRATED from ui_parity.systems import System # What a step runs on: the HTML the server sent, the page with scripts off, @@ -30,13 +31,6 @@ VIEWPORT = {"width": 1280, "height": 720} -# Resolves once React has attached to the server-rendered root of the page. -_HYDRATED_SCRIPT = """() => { - const root = document.querySelector("[data-contract-root]"); - return root !== null - && Object.keys(root).some((key) => key.startsWith("__reactFiber")); -}""" - # Elements that have no end tag, so they never hold another. _VOID = frozenset({ "area", @@ -304,7 +298,7 @@ def _check( page.on("pageerror", lambda error: run.problems.append(f"error: {error}")) page.goto(url) if step.on == HYDRATED: - page.wait_for_function(_HYDRATED_SCRIPT) + page.wait_for_function(IS_HYDRATED) step.check(run) finally: context.close() diff --git a/packages/reflex-components-ui/parity/ui_parity/hydration.py b/packages/reflex-components-ui/parity/ui_parity/hydration.py new file mode 100644 index 00000000000..9e6723d27ac --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/hydration.py @@ -0,0 +1,46 @@ +"""How a runner knows a page of the harness app is hydrated. + +React gives a server-rendered element its fiber while it still renders, before +anything is committed: Emotion has not moved its style tags yet, and no effect +has attached a behaviour. An effect of the first render runs only once the +root has committed, so every page ends in a marker whose effect flags the +document, and the runners wait for the flag. +""" + +from __future__ import annotations + +from reflex_base.components.component import Component +from reflex_base.utils.imports import ImportDict + +# The attribute of the document element the marker sets. +ATTRIBUTE = "data-parity-hydrated" + +# A JavaScript expression that is true once the page is hydrated. +IS_HYDRATED = f'document.documentElement.hasAttribute("{ATTRIBUTE}")' + +# Elements that render nothing, which a library may put beside a component. +NOT_RENDERED = ("style", "script", "link", "template") + + +class HydrationMarker(Component): + """Flag the document once the page it is on has hydrated.""" + + tag = "Fragment" + library = "react" + + def add_imports(self) -> ImportDict: + """Import the hook the marker runs. + + Returns: + The import. + """ + return {"react": "useEffect"} + + def add_hooks(self) -> list[str]: + """Set the flag in an effect, which runs after the root commits. + + Returns: + The hook. + """ + flag = f'document.documentElement.setAttribute("{ATTRIBUTE}", "")' + return [f"useEffect(() => {{ {flag}; }}, []);"] diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py index 46a9ce8bc06..3c2b3f09eb3 100644 --- a/packages/reflex-components-ui/parity/ui_parity/look.py +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -22,6 +22,7 @@ from ui_parity.allowlist import Allowlist, LookEntry from ui_parity.diff import diff_images +from ui_parity.hydration import IS_HYDRATED, NOT_RENDERED from ui_parity.matrix import ACTIVE, FOCUS_VISIBLE, HOVER, REST, Cell, Matrix, Selector from ui_parity.systems import CANDIDATE, REFERENCE, SYSTEMS, System @@ -49,22 +50,24 @@ # Resolves once the page is hydrated, in the color scheme asked for, with its # fonts loaded. -_READY_SCRIPT = """async (appearance) => { - const stage = document.querySelector("[data-parity-stage]"); +READY_SCRIPT = f"""async (appearance) => {{ if ( - stage === null - || !Object.keys(stage).some((key) => key.startsWith("__reactFiber")) + !{IS_HYDRATED} || !document.documentElement.classList.contains(appearance) - ) { + ) {{ return false; - } + }} await document.fonts.ready; return document.fonts.status === "loaded"; -}""" +}}""" + +# The first element of a frame that renders: not a style tag a library left +# beside the component. +_FIRST_RENDERED = ":scope > " + "".join(f":not({tag})" for tag in NOT_RENDERED) # Reads the geometry and the computed style of the frames: all of them, or the # one of a system and props id. -_READ_SCRIPT = """({properties, targets, parts, only, matches}) => { +READ_SCRIPT = """({properties, targets, parts, only, matches, first}) => { const read = (element) => { const style = getComputedStyle(element); return Object.fromEntries( @@ -85,9 +88,7 @@ : `[data-parity-stage="${only.id}"][data-parity-system="${only.system}"]`; return Array.from(document.querySelectorAll(selector), (stage) => { const system = stage.dataset.paritySystem; - const target = targets[system] === null - ? stage.firstElementChild - : stage.querySelector(targets[system]); + const target = stage.querySelector(targets[system] ?? first); const styles = {}; const missing = []; if (target === null) { @@ -524,7 +525,7 @@ def __init__( def load(self) -> None: """Load the page and wait until it is still.""" self.page.goto(self.url) - self.page.wait_for_function(_READY_SCRIPT, arg=self.appearance) + self.page.wait_for_function(READY_SCRIPT, arg=self.appearance) self.page.add_style_tag(content=FREEZE_CSS) if self.prepare is not None: self.prepare(self.page) @@ -546,7 +547,7 @@ def read( CaptureError: If a frame lacks the element the matrix names. """ frames = self.page.evaluate( - _READ_SCRIPT, + READ_SCRIPT, { "properties": self.matrix.properties, "targets": _per_system(self.matrix.target), @@ -558,6 +559,7 @@ def read( if only is None else {"id": only[0], "system": only[1].role}, "matches": matches, + "first": _FIRST_RENDERED, }, ) for frame in frames: @@ -646,7 +648,7 @@ def target(self, props_id: str, system: System) -> Locator: f'[data-parity-stage="{props_id}"][data-parity-system="{system.role}"]' ) selector = _per_system(self.matrix.target)[system.role] - return stage.locator("xpath=./*[1]" if selector is None else selector).first + return stage.locator(_FIRST_RENDERED if selector is None else selector).first def close(self) -> None: """Close the page.""" diff --git a/packages/reflex-components-ui/parity/ui_parity/matrix.py b/packages/reflex-components-ui/parity/ui_parity/matrix.py index ef7f0c2d3a0..4765d8a8cf7 100644 --- a/packages/reflex-components-ui/parity/ui_parity/matrix.py +++ b/packages/reflex-components-ui/parity/ui_parity/matrix.py @@ -195,7 +195,7 @@ class Matrix: popup. target: The CSS selector, below the frame, of the element whose computed style is read: one string, or one per system. The default - is the first element of the frame. + is the first element of the frame that renders. parts: Inner elements whose computed style is compared too, by name. properties: The computed properties compared. threshold: How far a pixel's color may be off, from 0 to 1, before the diff --git a/tests/integration/tests_playwright/test_ui_parity.py b/tests/integration/tests_playwright/test_ui_parity.py index 4b04cfad1de..1b21f17f91b 100644 --- a/tests/integration/tests_playwright/test_ui_parity.py +++ b/tests/integration/tests_playwright/test_ui_parity.py @@ -25,7 +25,13 @@ from ui_parity.app import contract_route, parity_route # noqa: E402 from ui_parity.components import CONTRACTS, MATRICES # noqa: E402 from ui_parity.contract import HYDRATED, ContractError, Step, run_step # noqa: E402 -from ui_parity.look import StyleDifference, run_matrix # noqa: E402 +from ui_parity.hydration import ATTRIBUTE # noqa: E402 +from ui_parity.look import ( # noqa: E402 + READ_SCRIPT, + READY_SCRIPT, + StyleDifference, + run_matrix, +) from ui_parity.systems import CANDIDATE, REFERENCE, SYSTEMS # noqa: E402 # Where the report of a run goes, unless UI_PARITY_REPORT names a directory. @@ -231,6 +237,57 @@ def test_changed_role_fails_the_matrix( ] +# A reference frame as React leaves it while it still renders the hydration: +# the frame has its fiber, and the style tag Emotion prerendered beside the +# Radix box has not moved to the head yet. +RENDERING = """ + + +
+ +
box
+
+ + + +""" + + +def test_page_is_read_only_once_hydration_committed(page: Page): + """A fiber on a frame is not hydration, and a style tag is not the component.""" + page.set_content(RENDERING) + assert page.evaluate(READY_SCRIPT, "light") is False + # What the read would measure all the same: the box, never the style tag. + request = { + "properties": ["display", "padding-top"], + "targets": {"reference": None, "candidate": None}, + "parts": {}, + "only": None, + "matches": None, + "first": ":scope > :not(style):not(script):not(link):not(template)", + } + assert page.evaluate(READ_SCRIPT, request) == [ + { + "id": "style-padding", + "system": "reference", + "stage": [0, 0, 1280, 44], + # The content box and its padding of 12 pixels a side. + "target": [0, 0, 64, 44], + "styles": {"": {"display": "block", "padding-top": "12px"}}, + "missing": [], + "matched": True, + "view": [0, 0, 1280, 720], + } + ] + # An effect of the first render runs after the commit, and flags the page. + page.evaluate(f'() => document.documentElement.setAttribute("{ATTRIBUTE}", "")') + assert page.evaluate(READY_SCRIPT, "light") is True + # In the wrong color scheme the page is still not the one to read. + assert page.evaluate(READY_SCRIPT, "dark") is False + + CONTRACT_STEPS = [ pytest.param(component, system, step, id=f"{component}-{system.name}-{step.name}") for component, contract in CONTRACTS.items() From 3b54a6f3034db0f609357d036b149161b3940636 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 12:05:46 +0000 Subject: [PATCH 24/26] Wire color_scheme into UIComponent, and adapt the theme tests to the style compiler Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- .../src/reflex_components_ui/base.py | 10 +- .../src/reflex_components_ui/layout/theme.py | 21 +- .../reflex_components_ui/layout/test_theme.py | 98 ++--- .../reflex_components_ui/style/test_emit.py | 94 +++-- .../reflex_components_ui/style/test_lower.py | 4 +- .../reflex_components_ui/test_api_parity.py | 9 +- tests/units/reflex_components_ui/test_base.py | 155 ++++++++ .../units/reflex_components_ui/test_themes.py | 344 +++++++++++------- 8 files changed, 507 insertions(+), 228 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/base.py b/packages/reflex-components-ui/src/reflex_components_ui/base.py index 68922b2e343..07382cf9149 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -211,16 +211,16 @@ def _post_init(self, *args, **kwargs): if layout_props else None ) - super()._post_init(*args, **kwargs) - self._merge_styles() - color_scheme = ( - getattr(self, "color_scheme", None) if "color_scheme" in fields else None - ) + # Before the props are checked against their types: the error of an + # unknown color lists the accent colors and suggests the closest. + color_scheme = kwargs.get("color_scheme") if "color_scheme" in fields else None self._accent = ( None if color_scheme is None else color_scheme_styles(self._display_name(), color_scheme) ) + super()._post_init(*args, **kwargs) + self._merge_styles() def _merge_styles(self) -> None: """Merge the style table with the styles of this element. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py index 0c581d15795..af22c01660e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py @@ -72,44 +72,37 @@ class ThemeElement(UIComponent): tag = "div" - accent_color: Var[LiteralAccentColor] | None = field( - default=None, + accent_color: Var[LiteralAccentColor] = field( is_javascript_property=False, doc="The color of the components that stand out.", ) - gray_color: Var[LiteralGrayColor] | None = field( - default=None, + gray_color: Var[LiteralGrayColor] = field( is_javascript_property=False, doc='The gray of text, borders and surfaces. "auto" is the gray that matches the accent color.', ) - radius: Var[LiteralRadius] | None = field( - default=None, + radius: Var[LiteralRadius] = field( is_javascript_property=False, doc='How round corners are: "none" | "small" | "medium" | "large" | "full".', ) - scaling: Var[LiteralScaling] | None = field( - default=None, + scaling: Var[LiteralScaling] = field( is_javascript_property=False, doc='The size of everything: "90%" | "95%" | "100%" | "105%" | "110%".', ) - appearance: Var[LiteralAppearance] | None = field( - default=None, + appearance: Var[LiteralAppearance] = field( is_javascript_property=False, doc='"light" or "dark" to keep one whatever the color mode, "inherit" to follow it.', ) - panel_background: Var[LiteralPanelBackground] | None = field( - default=None, + panel_background: Var[LiteralPanelBackground] = field( is_javascript_property=False, doc='Whether panels such as cards are see-through: "solid" | "translucent".', ) - has_background: Var[bool] | None = field( - default=None, + has_background: Var[bool] = field( is_javascript_property=False, doc="Whether the element paints the background of the theme. Defaults to True when it sets an appearance.", ) diff --git a/tests/units/reflex_components_ui/layout/test_theme.py b/tests/units/reflex_components_ui/layout/test_theme.py index 1bcee2399bf..0c9750342fd 100644 --- a/tests/units/reflex_components_ui/layout/test_theme.py +++ b/tests/units/reflex_components_ui/layout/test_theme.py @@ -19,6 +19,7 @@ APP_ROOT = ( """ +import {className as reflexUIClassName} from "$/reflex-ui/class-name.js" import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" import {focusScope} from "$/reflex-ui/themes/focus.js" import {graySlate} from "$/reflex-ui/themes/gray/slate.js" @@ -39,6 +40,9 @@ const sx_c1c0436182 = stylex.create({ s: {"position": "relative", "zIndex": 0, "minHeight": {"default": "100vh", "@supports (min-height: 100dvh)": "100dvh"}} }); +const sx_c1c0436182_c = stylex.props(sx_c1c0436182.s).className; +const sx_c1c0436182_o = sx_c1c0436182.s; +const reflexUIClasses_48dbd5f3d5 = "reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentIndigo, graySlate, radiusLarge, scaling100, panelTranslucent, reflexUITheme.root, reflexUITheme.background, sx_c1c0436182_o); function ReflexProviders({children}) { useEffect(() => { @@ -58,7 +62,7 @@ function AppWrap({children}) { -return (jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentIndigo, graySlate, radiusLarge, scaling100, panelTranslucent, reflexUITheme.root, reflexUITheme.background, sx_c1c0436182.s, { $$css: true, className: "reflex-ui-theme" })},jsx(Fragment,{},children))) +return (jsx("div",{className:reflexUIClasses_48dbd5f3d5},jsx(Fragment,{},children))) } export function Layout({children}) { @@ -80,6 +84,8 @@ ) NESTED_PAGE = """import * as stylex from "@stylexjs/stylex" +import "$/reflex-ui/tokens/accent.stylex.js" +import {className as reflexUIClassName} from "$/reflex-ui/class-name.js" import {accentRed} from "$/reflex-ui/themes/accent/red.js" import {focusScope} from "$/reflex-ui/themes/focus.js" import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" @@ -92,14 +98,21 @@ const sx_e0e666cdfc = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "color": "var(--accent-9)"} }); -const sx_ffb9e340d1 = stylex.create({ s: {"padding": "4px"} }); +const sx_e0e666cdfc_c = stylex.props(sx_e0e666cdfc.s).className; +const reflexUIClasses_22039616de = "reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentRed, reflexUITheme.root); +const sx_2ccd5239f0 = stylex.create({ s: {"paddingTop": "4px", "paddingRight": "4px", "paddingBottom": "4px", "paddingLeft": "4px"} }); +const sx_2ccd5239f0_c = stylex.props(sx_2ccd5239f0.s).className; +const sx_2ccd5239f0_o = sx_2ccd5239f0.s; +const reflexUIClasses_fd8fdcb49a = "reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, radiusFull, reflexUITheme.root, reflexUITheme.background, reflexUITheme.dark, sx_2ccd5239f0_o); const sx_71b84cd269 = stylex.create({ s: {"display": "contents"} }); +const sx_71b84cd269_c = stylex.props(sx_71b84cd269.s).className; +const reflexUIClasses_7830a5bcf7 = "reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUITheme.root); function Component() { const ref_dark = useRegisteredRef("ref_dark"); return ( - jsx(Fragment,{},jsx("main",{},jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentRed, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},jsx("div",{...stylex.props(sx_e0e666cdfc.s)},"red")),jsx("div",{...stylex.props(sx_71b84cd269.s, { $$css: true, className: "dark" })},jsx("div",{id:"dark",ref:ref_dark,...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, radiusFull, reflexUITheme.root, reflexUITheme.background, reflexUITheme.dark, sx_ffb9e340d1.s, { $$css: true, className: "reflex-ui-theme p-8" })},"dark")),jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" })},"plain")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + jsx(Fragment,{},jsx("main",{},jsx("div",{className:reflexUIClasses_22039616de},jsx("div",{className:sx_e0e666cdfc_c},"red")),jsx("div",{className:"dark " + sx_71b84cd269_c},jsx("div",{className:"p-8 " + reflexUIClasses_fd8fdcb49a,id:"dark",ref:ref_dark},"dark")),jsx("div",{className:reflexUIClasses_7830a5bcf7},"plain")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) ) } Component.displayName = "Component(/)"; @@ -107,8 +120,8 @@ export default Component; """ -BOUND_PAGE = """import {Themeelement_div_f7d2b7c33308674eb3685852f6be4c25} from "$/utils/components/Themeelement_div_f7d2b7c33308674eb3685852f6be4c25" -import {Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf} from "$/utils/components/Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf" +BOUND_PAGE = """import {Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5} from "$/utils/components/Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5" +import {Themeelement_div_110e113e071e5dc30028d2a466586629} from "$/utils/components/Themeelement_div_110e113e071e5dc30028d2a466586629" import {Fragment,useEffect} from "react" import {jsx} from "@emotion/react" @@ -120,7 +133,7 @@ return ( - jsx(Fragment,{},jsx("main",{},jsx(Themeelement_div_f7d2b7c33308674eb3685852f6be4c25,{},"accent"),jsx(Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf,{},"names")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + jsx(Fragment,{},jsx("main",{},jsx(Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5,{},"accent"),jsx(Themeelement_div_110e113e071e5dc30028d2a466586629,{},"names")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) ) } Component.displayName = "Component(/)"; @@ -131,6 +144,7 @@ BOUND_ACCENT_THEME = """ import {isTrue,mergeSlotProps} from "$/utils/state" import {useStateContext} from "$/utils/context-registry" +import {className as reflexUIClassName} from "$/reflex-ui/class-name.js" import {accentAmber} from "$/reflex-ui/themes/accent/amber.js" import {accentBlue} from "$/reflex-ui/themes/accent/blue.js" import {accentBronze} from "$/reflex-ui/themes/accent/bronze.js" @@ -160,30 +174,30 @@ import {focusScope} from "$/reflex-ui/themes/focus.js" import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" -import * as stylex from "@stylexjs/stylex" import {jsx} from "@emotion/react" import {Fragment,memo,useEffect} from "react" -const reflexUIAccents = { "amber": accentAmber, "blue": accentBlue, "bronze": accentBronze, "brown": accentBrown, "crimson": accentCrimson, "cyan": accentCyan, "gold": accentGold, "grass": accentGrass, "gray": accentGray, "green": accentGreen, "indigo": accentIndigo, "iris": accentIris, "jade": accentJade, "lime": accentLime, "mint": accentMint, "orange": accentOrange, "pink": accentPink, "plum": accentPlum, "purple": accentPurple, "red": accentRed, "ruby": accentRuby, "sky": accentSky, "teal": accentTeal, "tomato": accentTomato, "violet": accentViolet, "yellow": accentYellow }; +const reflexUIAccents = { __proto__: null, "amber": accentAmber, "blue": accentBlue, "bronze": accentBronze, "brown": accentBrown, "crimson": accentCrimson, "cyan": accentCyan, "gold": accentGold, "grass": accentGrass, "gray": accentGray, "green": accentGreen, "indigo": accentIndigo, "iris": accentIris, "jade": accentJade, "lime": accentLime, "mint": accentMint, "orange": accentOrange, "pink": accentPink, "plum": accentPlum, "purple": accentPurple, "red": accentRed, "ruby": accentRuby, "sky": accentSky, "teal": accentTeal, "tomato": accentTomato, "violet": accentViolet, "yellow": accentYellow }; -export const Themeelement_div_f7d2b7c33308674eb3685852f6be4c25 = /*#__PURE__*/ (() => { -const Themeelement_div_f7d2b7c33308674eb3685852f6be4c25 = memo(({children, ...rest}) => { +export const Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5 = /*#__PURE__*/ (() => { +const Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5 = memo(({children, ...rest}) => { const reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state = useStateContext("reflex___state____state.tests___units___reflex_components_ui___layout___test_theme____theme_state", ["accent_rx_state_"]) return( - jsx("div",{...mergeSlotProps(rest, ({ ...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" }) }))},children) + jsx("div",{...mergeSlotProps(rest, ({ className:"reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], reflexUITheme.root) }))},children) ) }); -Themeelement_div_f7d2b7c33308674eb3685852f6be4c25.displayName = "ThemeElement"; -return Themeelement_div_f7d2b7c33308674eb3685852f6be4c25; +Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5.displayName = "ThemeElement"; +return Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5; })(); """ BOUND_NAMES_THEME = """ import {isTrue,mergeSlotProps} from "$/utils/state" import {useStateContext} from "$/utils/context-registry" +import {className as reflexUIClassName} from "$/reflex-ui/class-name.js" import {accentAmber} from "$/reflex-ui/themes/accent/amber.js" import {accentBlue} from "$/reflex-ui/themes/accent/blue.js" import {accentBronze} from "$/reflex-ui/themes/accent/bronze.js" @@ -214,24 +228,23 @@ import {graySand} from "$/reflex-ui/themes/gray/sand.js" import {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" -import * as stylex from "@stylexjs/stylex" import {jsx} from "@emotion/react" import {Fragment,memo,useEffect} from "react" -const reflexUIAccents = { "amber": accentAmber, "blue": accentBlue, "bronze": accentBronze, "brown": accentBrown, "crimson": accentCrimson, "cyan": accentCyan, "gold": accentGold, "grass": accentGrass, "gray": accentGray, "green": accentGreen, "indigo": accentIndigo, "iris": accentIris, "jade": accentJade, "lime": accentLime, "mint": accentMint, "orange": accentOrange, "pink": accentPink, "plum": accentPlum, "purple": accentPurple, "red": accentRed, "ruby": accentRuby, "sky": accentSky, "teal": accentTeal, "tomato": accentTomato, "violet": accentViolet, "yellow": accentYellow }; +const reflexUIAccents = { __proto__: null, "amber": accentAmber, "blue": accentBlue, "bronze": accentBronze, "brown": accentBrown, "crimson": accentCrimson, "cyan": accentCyan, "gold": accentGold, "grass": accentGrass, "gray": accentGray, "green": accentGreen, "indigo": accentIndigo, "iris": accentIris, "jade": accentJade, "lime": accentLime, "mint": accentMint, "orange": accentOrange, "pink": accentPink, "plum": accentPlum, "purple": accentPurple, "red": accentRed, "ruby": accentRuby, "sky": accentSky, "teal": accentTeal, "tomato": accentTomato, "violet": accentViolet, "yellow": accentYellow }; -export const Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf = /*#__PURE__*/ (() => { -const Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf = memo(({children, ...rest}) => { +export const Themeelement_div_110e113e071e5dc30028d2a466586629 = /*#__PURE__*/ (() => { +const Themeelement_div_110e113e071e5dc30028d2a466586629 = memo(({children, ...rest}) => { const reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state = useStateContext("reflex___state____state.tests___units___reflex_components_ui___layout___test_theme____theme_state", ["names_rx_state_", "accent_rx_state_"]) return( - jsx("div",{...mergeSlotProps(rest, ({ className:(reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.names_rx_state_) + " " + stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], graySand, reflexUITheme.root, { $$css: true, className: "reflex-ui-theme" }).className }))},children) + jsx("div",{...mergeSlotProps(rest, ({ className:(reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.names_rx_state_) + " " + "reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, reflexUIAccents[reflex___state____state__tests___units___reflex_components_ui___layout___test_theme____theme_state.accent_rx_state_], graySand, reflexUITheme.root) }))},children) ) }); -Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf.displayName = "ThemeElement"; -return Themeelement_div_7ff1171060456d23f7870cfa8fe2dfcf; +Themeelement_div_110e113e071e5dc30028d2a466586629.displayName = "ThemeElement"; +return Themeelement_div_110e113e071e5dc30028d2a466586629; })(); """ @@ -288,24 +301,27 @@ def test_plugin_wraps_an_app_with_an_appearance_in_its_class( } assert wraps[16, "ReflexUIAppearance"].render() == { "name": '"div"', - "props": [ - '...stylex.props(sx_71b84cd269.s, { $$css: true, className: "dark" })' - ], + "props": ['className:"dark " + sx_71b84cd269_c'], "children": [], } - assert wraps[15, "ReflexUITheme"].render() == { + theme = wraps[15, "ReflexUITheme"] + assert theme.render() == { "name": '"div"', - "props": [ - ( - "...stylex.props(spaceScope, radiusScope, typographyScope, " - "shadowScope, colorScope, focusScope, accentBlue, graySlate, " - "radiusMedium, scaling100, panelTranslucent, reflexUITheme.root, " - "reflexUITheme.background, reflexUITheme.dark, sx_c1c0436182.s, " - '{ $$css: true, className: "reflex-ui-theme" })' - ) - ], + "props": ["className:reflexUIClasses_ac4861b877"], "children": [], } + assert theme._get_all_custom_code() == { + 'const sx_c1c0436182 = stylex.create({ s: {"position": "relative", ' + '"zIndex": 0, "minHeight": {"default": "100vh", "@supports ' + '(min-height: 100dvh)": "100dvh"}} });\n' + "const sx_c1c0436182_c = stylex.props(sx_c1c0436182.s).className;": None, + "const sx_c1c0436182_o = sx_c1c0436182.s;": None, + 'const reflexUIClasses_ac4861b877 = "reflex-ui-theme " + ' + "reflexUIClassName(spaceScope, radiusScope, typographyScope, " + "shadowScope, colorScope, focusScope, accentBlue, graySlate, " + "radiusMedium, scaling100, panelTranslucent, reflexUITheme.root, " + "reflexUITheme.background, reflexUITheme.dark, sx_c1c0436182_o);": None, + } def test_theme_with_an_appearance_is_inside_the_element_of_its_class( @@ -321,19 +337,13 @@ def test_theme_with_an_appearance_is_inside_the_element_of_its_class( appearance=ThemeState.appearance, # pyright: ignore [reportArgumentType] ) assert bound.render()["props"] == [ - ( - f'className:({ThemeState.appearance!s}) + " " + ' - "stylex.props(sx_71b84cd269.s).className" - ) + f'className:({ThemeState.appearance!s}) + " " + sx_71b84cd269_c' ] assert bound.children[0].render()["props"] == [ - ( - "...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, " - "colorScope, focusScope, reflexUITheme.root, " - f'({ThemeState.appearance!s}) !== "inherit" && reflexUITheme.background, ' - f"reflexUITheme[{ThemeState.appearance!s}], " - '{ $$css: true, className: "reflex-ui-theme" })' - ) + 'className:"reflex-ui-theme " + reflexUIClassName(spaceScope, ' + "radiusScope, typographyScope, shadowScope, colorScope, focusScope, " + f'reflexUITheme.root, ({ThemeState.appearance!s}) !== "inherit" && ' + f"reflexUITheme.background, reflexUITheme[{ThemeState.appearance!s}])" ] diff --git a/tests/units/reflex_components_ui/style/test_emit.py b/tests/units/reflex_components_ui/style/test_emit.py index 543cf12b1de..7cc5e638a7a 100644 --- a/tests/units/reflex_components_ui/style/test_emit.py +++ b/tests/units/reflex_components_ui/style/test_emit.py @@ -149,13 +149,24 @@ def comparable(result: Emitted) -> tuple[Any, ...]: }, emitted( declaration=( - 'const sx_e4b79af79d = stylex.create({ s: {"padding": ' - '"var(--space-3)", "borderRadius": "var(--radius-4)", "boxShadow": ' - '"var(--shadow-2)", "width": "320px", "zIndex": 2, "lineHeight": ' - "1.5} });\n" - "const sx_e4b79af79d_c = stylex.props(sx_e4b79af79d.s).className;" + 'const sx_283e421a96 = stylex.create({ s: {"paddingTop": ' + '"var(--space-3)", "paddingRight": "var(--space-3)", ' + '"paddingBottom": "var(--space-3)", "paddingLeft": ' + '"var(--space-3)", "borderTopLeftRadius": "var(--radius-4)", ' + '"borderTopRightRadius": "var(--radius-4)", ' + '"borderBottomRightRadius": "var(--radius-4)", ' + '"borderBottomLeftRadius": "var(--radius-4)", "boxShadow": ' + '"var(--shadow-2)", "width": "320px", "zIndex": 2, ' + '"lineHeight": 1.5} });\n' + "const sx_283e421a96_c = " + "stylex.props(sx_283e421a96.s).className;" + ), + classes="sx_283e421a96_c", + imports=( + "$/reflex-ui/tokens/radius.stylex.js", + "$/reflex-ui/tokens/shadow.stylex.js", + "$/reflex-ui/tokens/space.stylex.js", ), - classes="sx_e4b79af79d_c", ), ), # The card of the plan: its width bound to state, and a hover shadow. @@ -169,13 +180,24 @@ def comparable(result: Emitted) -> tuple[Any, ...]: }, emitted( declaration=( - 'const sx_62330ed6a3 = stylex.create({ s: {"padding": ' - '"var(--space-3)", "borderRadius": "var(--radius-4)", "boxShadow": ' + 'const sx_75ce444dca = stylex.create({ s: {"paddingTop": ' + '"var(--space-3)", "paddingRight": "var(--space-3)", ' + '"paddingBottom": "var(--space-3)", "paddingLeft": ' + '"var(--space-3)", "borderTopLeftRadius": "var(--radius-4)", ' + '"borderTopRightRadius": "var(--radius-4)", ' + '"borderBottomRightRadius": "var(--radius-4)", ' + '"borderBottomLeftRadius": "var(--radius-4)", "boxShadow": ' '{"default": "var(--shadow-2)", ":hover": "var(--shadow-3)"}, ' '"width": "var(--v0)"} });\n' - "const sx_62330ed6a3_c = stylex.props(sx_62330ed6a3.s).className;" + "const sx_75ce444dca_c = " + "stylex.props(sx_75ce444dca.s).className;" + ), + classes="sx_75ce444dca_c", + imports=( + "$/reflex-ui/tokens/radius.stylex.js", + "$/reflex-ui/tokens/shadow.stylex.js", + "$/reflex-ui/tokens/space.stylex.js", ), - classes="sx_62330ed6a3_c", variables=('"--v0": () ?? "initial"',), vars=("",), ), @@ -311,21 +333,24 @@ def comparable(result: Emitted) -> tuple[Any, ...]: emitted( declaration=( 'const sx_dae5511f98 = stylex.create({ s: {"rowGap": ' - '"var(--space-3)", "columnGap": "var(--space-3)", "paddingTop": ' - '{"default": "var(--space-1)", "@media screen and (min-width: ' + '"var(--space-3)", "columnGap": "var(--space-3)", "paddingTop":' + ' {"default": "var(--space-1)", "@media screen and (min-width: ' '30em)": "var(--space-2)"}, "paddingRight": {"default": ' '"var(--space-1)", "@media screen and (min-width: 30em)": ' - '"var(--space-2)"}, "paddingBottom": {"default": "var(--space-1)", ' - '"@media screen and (min-width: 30em)": "var(--space-2)"}, ' - '"paddingLeft": {"default": "var(--space-1)", "@media screen and ' - '(min-width: 30em)": "var(--space-2)"}, "marginTop": "calc(-1 * ' - 'var(--space-2))", "marginRight": "calc(-1 * var(--space-2))", ' - '"marginBottom": "calc(-1 * var(--space-2))", "marginLeft": "calc(-1 ' - '* var(--space-2))", "gridTemplateColumns": "repeat(3, minmax(0, ' + '"var(--space-2)"}, "paddingBottom": {"default": ' + '"var(--space-1)", "@media screen and (min-width: 30em)": ' + '"var(--space-2)"}, "paddingLeft": {"default": ' + '"var(--space-1)", "@media screen and (min-width: 30em)": ' + '"var(--space-2)"}, "marginTop": "calc(-1 * var(--space-2))", ' + '"marginRight": "calc(-1 * var(--space-2))", "marginBottom": ' + '"calc(-1 * var(--space-2))", "marginLeft": "calc(-1 * ' + 'var(--space-2))", "gridTemplateColumns": "repeat(3, minmax(0, ' '1fr))", "flexDirection": "column"} });\n' - "const sx_dae5511f98_c = stylex.props(sx_dae5511f98.s).className;" + "const sx_dae5511f98_c = " + "stylex.props(sx_dae5511f98.s).className;" ), classes="sx_dae5511f98_c", + imports=("$/reflex-ui/tokens/space.stylex.js",), ), ), "shorthand": ( @@ -446,12 +471,23 @@ def comparable(result: Emitted) -> tuple[Any, ...]: {"styles": CARD, "style": S.styles}, emitted( declaration=( - 'const sx_884e514c9c = stylex.create({ s: {"padding": ' - '"var(--space-3)", "borderRadius": "var(--radius-4)", "boxShadow": ' + 'const sx_1026d57c33 = stylex.create({ s: {"paddingTop": ' + '"var(--space-3)", "paddingRight": "var(--space-3)", ' + '"paddingBottom": "var(--space-3)", "paddingLeft": ' + '"var(--space-3)", "borderTopLeftRadius": "var(--radius-4)", ' + '"borderTopRightRadius": "var(--radius-4)", ' + '"borderBottomRightRadius": "var(--radius-4)", ' + '"borderBottomLeftRadius": "var(--radius-4)", "boxShadow": ' '"var(--shadow-2)"} });\n' - "const sx_884e514c9c_c = stylex.props(sx_884e514c9c.s).className;" + "const sx_1026d57c33_c = " + "stylex.props(sx_1026d57c33.s).className;" + ), + classes="sx_1026d57c33_c", + imports=( + "$/reflex-ui/tokens/radius.stylex.js", + "$/reflex-ui/tokens/shadow.stylex.js", + "$/reflex-ui/tokens/space.stylex.js", ), - classes="sx_884e514c9c_c", inline="", vars=("",), ), @@ -507,8 +543,14 @@ def classes(style: dict[str, Any], name: str = "rx.ui.box") -> str | None: def test_inline_keeps_literals(): style = {"top": "4px", "z_index": 2, "opacity": 0.5} assert inline(merge("rx.ui.box", CARD, style=style), "rx.ui.box") == { - "padding": "var(--space-3)", - "borderRadius": "var(--radius-4)", + "paddingTop": "var(--space-3)", + "paddingRight": "var(--space-3)", + "paddingBottom": "var(--space-3)", + "paddingLeft": "var(--space-3)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", "boxShadow": "var(--shadow-2)", "top": "4px", "zIndex": 2, diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index db78a1454fa..eb57dbd5e67 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -470,11 +470,11 @@ def test_var_modules_name_the_module_of_every_custom_property(): """Each custom property Radix defines is found by its whole name.""" assert VAR_MODULES["--ruby-9"] == RUBY assert VAR_MODULES["--gray-9"] == GRAY - assert VAR_MODULES == { + assert { name: f"$/reflex-ui/{module}" for module, names in VAR_GROUPS.values() for name in names - } + } == VAR_MODULES assert len(VAR_MODULES) == 1070 assert lower( "rx.ui.card", diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index d534e574b42..a1c36ace775 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -5,6 +5,7 @@ reason the migration guide gives for it. """ +import types from typing import Any, Literal import reflex_components_ui @@ -25,7 +26,13 @@ import reflex as rx -COMPONENTS = sorted(reflex_components_ui.__all__) +# The names of the namespace that create a component: a theme of the plugin +# and the design tokens are no components. +COMPONENTS = sorted( + name + for name in reflex_components_ui.__all__ + if isinstance(getattr(reflex_components_ui, name), types.MethodType) +) def differences(component: str) -> list[ApiDifference]: diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py index 06dd461f927..edc2d71d744 100644 --- a/tests/units/reflex_components_ui/test_base.py +++ b/tests/units/reflex_components_ui/test_base.py @@ -13,7 +13,9 @@ from reflex_base.vars.base import Var from reflex_components_ui.base import Part, UIComponent from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, StyleError +from reflex_components_ui.themes import LiteralAccentColor, ThemeError import reflex as rx from reflex.compiler import compiler @@ -742,3 +744,156 @@ def test_dynamic_component_cannot_have_a_style_that_needs_the_compiler( with pytest.raises(StyleError) as raised: serialize(create()) assert str(raised.value) == message + + +class Chip(UIComponent): + """An element with a color of its own.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = { + "base": {"background_color": tokens.accent[9], "color": tokens.accent.contrast}, + } + + # The accent color of the element. + color_scheme: Var[LiteralAccentColor] + + +CHIP_PAGE = """import * as stylex from "@stylexjs/stylex" +import "$/reflex-ui/tokens/accent.stylex.js" +import {className as reflexUIClassName} from "$/reflex-ui/class-name.js" +import {accentRed} from "$/reflex-ui/themes/accent/red.js" +import {focusScope} from "$/reflex-ui/themes/focus.js" +import {useRegisteredRef} from "$/utils/state" +import {accentGray} from "$/reflex-ui/themes/accent/gray.js" +import {Chip_span_a1f191971c1d0b090104807deb864e69} from "$/utils/components/Chip_span_a1f191971c1d0b090104807deb864e69" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + + + +const sx_8f99169642 = stylex.create({ s: {"backgroundColor": "var(--accent-9)", "color": "var(--accent-contrast)"} }); +const sx_8f99169642_c = stylex.props(sx_8f99169642.s).className; +const reflexUIClasses_01ac7ed29f = reflexUIClassName(accentRed, focusScope); +const reflexUIClasses_fe8edd03f8 = reflexUIClassName(accentGray); + +function Component() { +const ref_gray = useRegisteredRef("ref_gray"); + + return ( + jsx(Fragment,{},jsx("main",{},jsx("span",{className:sx_8f99169642_c},"theme"),jsx("span",{className:"p-8 " + sx_8f99169642_c + " " + reflexUIClasses_01ac7ed29f},"red"),jsx("span",{className:sx_8f99169642_c + " " + reflexUIClasses_01ac7ed29f},"red again"),jsx("span",{className:sx_8f99169642_c + " " + reflexUIClasses_fe8edd03f8,id:"gray",ref:ref_gray},"gray"),jsx(Chip_span_a1f191971c1d0b090104807deb864e69,{},"bound")),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + ) +} +Component.displayName = "Component(/)"; + +export default Component; +""" + +BOUND_CHIP = """ +import {isTrue,mergeSlotProps} from "$/utils/state" +import {useStateContext} from "$/utils/context-registry" +import * as stylex from "@stylexjs/stylex" +import "$/reflex-ui/tokens/accent.stylex.js" +import {className as reflexUIClassName} from "$/reflex-ui/class-name.js" +import {accentAmber} from "$/reflex-ui/themes/accent/amber.js" +import {accentBlue} from "$/reflex-ui/themes/accent/blue.js" +import {accentBronze} from "$/reflex-ui/themes/accent/bronze.js" +import {accentBrown} from "$/reflex-ui/themes/accent/brown.js" +import {accentCrimson} from "$/reflex-ui/themes/accent/crimson.js" +import {accentCyan} from "$/reflex-ui/themes/accent/cyan.js" +import {accentGold} from "$/reflex-ui/themes/accent/gold.js" +import {accentGrass} from "$/reflex-ui/themes/accent/grass.js" +import {accentGray} from "$/reflex-ui/themes/accent/gray.js" +import {accentGreen} from "$/reflex-ui/themes/accent/green.js" +import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" +import {accentIris} from "$/reflex-ui/themes/accent/iris.js" +import {accentJade} from "$/reflex-ui/themes/accent/jade.js" +import {accentLime} from "$/reflex-ui/themes/accent/lime.js" +import {accentMint} from "$/reflex-ui/themes/accent/mint.js" +import {accentOrange} from "$/reflex-ui/themes/accent/orange.js" +import {accentPink} from "$/reflex-ui/themes/accent/pink.js" +import {accentPlum} from "$/reflex-ui/themes/accent/plum.js" +import {accentPurple} from "$/reflex-ui/themes/accent/purple.js" +import {accentRed} from "$/reflex-ui/themes/accent/red.js" +import {accentRuby} from "$/reflex-ui/themes/accent/ruby.js" +import {accentSky} from "$/reflex-ui/themes/accent/sky.js" +import {accentTeal} from "$/reflex-ui/themes/accent/teal.js" +import {accentTomato} from "$/reflex-ui/themes/accent/tomato.js" +import {accentViolet} from "$/reflex-ui/themes/accent/violet.js" +import {accentYellow} from "$/reflex-ui/themes/accent/yellow.js" +import {focusScope} from "$/reflex-ui/themes/focus.js" +import {jsx} from "@emotion/react" +import {Fragment,memo,useEffect} from "react" + + + +const sx_8f99169642 = stylex.create({ s: {"backgroundColor": "var(--accent-9)", "color": "var(--accent-contrast)"} }); +const sx_8f99169642_c = stylex.props(sx_8f99169642.s).className; +const reflexUIColorSchemes = { __proto__: null, "amber": reflexUIClassName(accentAmber, focusScope), "blue": reflexUIClassName(accentBlue, focusScope), "bronze": reflexUIClassName(accentBronze, focusScope), "brown": reflexUIClassName(accentBrown, focusScope), "crimson": reflexUIClassName(accentCrimson, focusScope), "cyan": reflexUIClassName(accentCyan, focusScope), "gold": reflexUIClassName(accentGold, focusScope), "grass": reflexUIClassName(accentGrass, focusScope), "gray": reflexUIClassName(accentGray), "green": reflexUIClassName(accentGreen, focusScope), "indigo": reflexUIClassName(accentIndigo, focusScope), "iris": reflexUIClassName(accentIris, focusScope), "jade": reflexUIClassName(accentJade, focusScope), "lime": reflexUIClassName(accentLime, focusScope), "mint": reflexUIClassName(accentMint, focusScope), "orange": reflexUIClassName(accentOrange, focusScope), "pink": reflexUIClassName(accentPink, focusScope), "plum": reflexUIClassName(accentPlum, focusScope), "purple": reflexUIClassName(accentPurple, focusScope), "red": reflexUIClassName(accentRed, focusScope), "ruby": reflexUIClassName(accentRuby, focusScope), "sky": reflexUIClassName(accentSky, focusScope), "teal": reflexUIClassName(accentTeal, focusScope), "tomato": reflexUIClassName(accentTomato, focusScope), "violet": reflexUIClassName(accentViolet, focusScope), "yellow": reflexUIClassName(accentYellow, focusScope) }; + + +export const Chip_span_a1f191971c1d0b090104807deb864e69 = /*#__PURE__*/ (() => { +const Chip_span_a1f191971c1d0b090104807deb864e69 = memo(({children, ...rest}) => { + const reflex___state____state__tests___units___reflex_components_ui___test_base____base_test_state = useStateContext("reflex___state____state.tests___units___reflex_components_ui___test_base____base_test_state", ["color_rx_state_"]) + return( + jsx("span",{...mergeSlotProps(rest, ({ className:sx_8f99169642_c + " " + reflexUIColorSchemes[reflex___state____state__tests___units___reflex_components_ui___test_base____base_test_state.color_rx_state_] }))},children) + ) +}); +Chip_span_a1f191971c1d0b090104807deb864e69.displayName = "Chip"; +return Chip_span_a1f191971c1d0b090104807deb864e69; +})(); +""" + + +def test_color_scheme_is_the_accent_of_the_element( + ui_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + """A literal color imports its accent; one bound to state imports them all.""" + + def page(): + return rx.el.main( + Chip.create("theme"), + Chip.create("red", color_scheme="red", class_name="p-8"), + Chip.create("red again", color_scheme="red"), + Chip.create("gray", color_scheme="gray", id="gray"), + Chip.create("bound", color_scheme=S.color), # pyright: ignore [reportArgumentType] + ) + + ctx = compile_page(page) + assert ctx.compiled_pages["/"].output_code == CHIP_PAGE + files, _ = compiler.compile_memo_components(ctx.auto_memo_components.values()) + assert [code for path, code in files if "Chip_span_" in path] == [BOUND_CHIP] + + +def test_color_scheme_must_be_an_accent_color(): + with pytest.raises(ThemeError) as raised: + Chip.create("hello", color_scheme="slate") # pyright: ignore [reportArgumentType] + assert str(raised.value) == ( + 'rx.ui.chip: unknown color_scheme "slate". The values are "tomato", ' + '"red", "ruby", "crimson", "pink", "plum", "purple", "violet", "iris", ' + '"indigo", "blue", "cyan", "teal", "jade", "green", "grass", "brown", ' + '"orange", "sky", "mint", "lime", "yellow", "amber", "gold", "bronze", ' + '"gray".' + ) + + +def test_color_scheme_is_a_css_property_of_a_component_without_the_prop( + ui_plugin: UIPlugin, +): + """Only a component that declares the prop reads it as an accent.""" + component = Plain.create("hello", color_scheme="dark") + assert component._get_all_custom_code() == { + 'const sx_b7c693ea0b = stylex.create({ s: {"colorScheme": "dark"} });\n' + "const sx_b7c693ea0b_c = stylex.props(sx_b7c693ea0b.s).className;": None + } + + +def test_dynamic_component_cannot_have_a_color_scheme(): + with pytest.raises(StyleError) as raised: + serialize(Chip.create("hello", color_scheme="red")) + assert str(raised.value) == ( + "rx.ui.chip: color_scheme cannot be applied to a component rendered " + "from state: its code is evaluated in the browser and never reaches " + "the StyleX compiler. Render the component in a page and show it with " + "rx.cond." + ) diff --git a/tests/units/reflex_components_ui/test_themes.py b/tests/units/reflex_components_ui/test_themes.py index 1cb8e78778a..a86a31b1f3b 100644 --- a/tests/units/reflex_components_ui/test_themes.py +++ b/tests/units/reflex_components_ui/test_themes.py @@ -1,6 +1,7 @@ """Tests for reflex_components_ui.themes.""" import dataclasses +import hashlib from typing import Any, get_args import pytest @@ -36,14 +37,6 @@ '"bronze", "gray"' ) -ACCENT_MAP = ( - "const reflexUIAccents = { " - + ", ".join( - f'"{name}": accent{name.capitalize()}' - for name in sorted(_radix_tokens.ACCENT_THEMES) - ) - + " };" -) ACCENT_IMPORTS = tuple( (f"themes/accent/{name}.js", f"accent{name.capitalize()}", None) for name in sorted(_radix_tokens.ACCENT_THEMES) @@ -202,23 +195,51 @@ def test_theme_refuses_a_value_an_option_does_not_take( assert str(error.value) == message +HELPER_IMPORT = ("class-name.js", "className", "reflexUIClassName") + + +def _theme( + refs: tuple[str, ...], + imports: tuple[tuple[str, str, str | None], ...], +) -> ThemeStyles: + """Build what a theme element with literal options is expected to need. + + Args: + refs: The compiled styles after the scopes and the focus. + imports: The imports beside the ones every theme element has. + + Returns: + The expected styles: the class names are joined once, in a constant + named after the call that joins them. + """ + call = ( + '"reflex-ui-theme " + reflexUIClassName(' + + ", ".join((*SCOPES, "focusScope", *refs)) + + ")" + ) + name = "reflexUIClasses_" + hashlib.sha256(call.encode()).hexdigest()[:10] + return ThemeStyles( + classes=name, + imports=tuple( + sorted([ + *imports, + HELPER_IMPORT, + FOCUS_IMPORT, + *SCOPE_IMPORTS, + STYLES_IMPORT, + ]) + ), + declarations=(f"const {name} = {call};",), + ) + + def test_app_theme_sets_every_option(): """The element around an app depends on nothing outside it.""" - assert app_theme_styles( - Theme(accent_color="indigo", radius="large") - ) == ThemeStyles( - refs=( - *SCOPES, - "focusScope", - "accentIndigo", - "graySlate", - "radiusLarge", - "scaling100", - "panelTranslucent", - "reflexUITheme.root", - "reflexUITheme.background", - ), + styles = app_theme_styles(Theme(accent_color="indigo", radius="large")) + assert styles == ThemeStyles( + classes="reflexUIClasses_35e01a8868", imports=( + HELPER_IMPORT, ("themes/accent/indigo.js", "accentIndigo", None), FOCUS_IMPORT, ("themes/gray/slate.js", "graySlate", None), @@ -228,7 +249,15 @@ def test_app_theme_sets_every_option(): *SCOPE_IMPORTS, STYLES_IMPORT, ), - class_name="reflex-ui-theme", + declarations=( + ( + 'const reflexUIClasses_35e01a8868 = "reflex-ui-theme " + ' + "reflexUIClassName(spaceScope, radiusScope, typographyScope, " + "shadowScope, colorScope, focusScope, accentIndigo, graySlate, " + "radiusLarge, scaling100, panelTranslucent, reflexUITheme.root, " + "reflexUITheme.background);" + ), + ), ) assert app_theme_styles( Theme( @@ -239,11 +268,10 @@ def test_app_theme_sets_every_option(): appearance="dark", panel_background="solid", has_background=False, - ) - ) == ThemeStyles( - refs=( - *SCOPES, - "focusScope", + ), + "sx_0123456789_o", + ) == _theme( + ( "accentGray", "grayOlive", "radiusNone", @@ -251,18 +279,16 @@ def test_app_theme_sets_every_option(): "panelSolid", "reflexUITheme.root", "reflexUITheme.dark", + # The style of the element itself is last: it wins a property. + "sx_0123456789_o", ), - imports=( + ( ("themes/accent/gray.js", "accentGray", None), - FOCUS_IMPORT, ("themes/gray/olive.js", "grayOlive", None), ("themes/panel.js", "panelSolid", None), ("themes/radius.js", "radiusNone", None), ("themes/scaling.js", "scaling110", None), - *SCOPE_IMPORTS, - STYLES_IMPORT, ), - class_name="reflex-ui-theme", ) @@ -270,14 +296,23 @@ def test_every_accent_has_the_gray_that_matches_it(): """``auto`` is resolved when the app is compiled.""" for accent, gray in _radix_tokens.MATCHING_GRAY.items(): styles = app_theme_styles(Theme(accent_color=accent)) # pyright: ignore [reportArgumentType] - assert styles.refs[6:8] == ( - f"accent{accent.capitalize()}", - f"gray{gray.capitalize()}", - ) - assert styles.imports[:3] == ( - (f"themes/accent/{accent}.js", f"accent{accent.capitalize()}", None), - FOCUS_IMPORT, - (f"themes/gray/{gray}.js", f"gray{gray.capitalize()}", None), + assert styles == _theme( + ( + f"accent{accent.capitalize()}", + f"gray{gray.capitalize()}", + "radiusMedium", + "scaling100", + "panelTranslucent", + "reflexUITheme.root", + "reflexUITheme.background", + ), + ( + (f"themes/accent/{accent}.js", f"accent{accent.capitalize()}", None), + (f"themes/gray/{gray}.js", f"gray{gray.capitalize()}", None), + ("themes/panel.js", "panelTranslucent", None), + ("themes/radius.js", "radiusMedium", None), + ("themes/scaling.js", "scaling100", None), + ), ) @@ -287,7 +322,8 @@ def _nested( """Build what a nested theme is expected to need. Args: - refs: The arguments after the scopes, the focus and before the root style. + refs: The compiled styles of its options, then the ones of the + element after its root style. imports: The imports beside the ones every theme element has. Returns: @@ -295,11 +331,7 @@ def _nested( """ after = tuple(ref for ref in refs if ref.startswith("reflexUITheme")) before = refs[: len(refs) - len(after)] - return ThemeStyles( - refs=(*SCOPES, "focusScope", *before, "reflexUITheme.root", *after), - imports=tuple(sorted([*imports, FOCUS_IMPORT, *SCOPE_IMPORTS, STYLES_IMPORT])), - class_name="reflex-ui-theme", - ) + return _theme((*before, "reflexUITheme.root", *after), imports) RED = ("themes/accent/red.js", "accentRed", None) @@ -392,77 +424,86 @@ def test_nested_theme_sets_what_it_is_given( assert theme_styles("rx.ui.theme", **options, app_theme=app_theme) == expected +def _map(name: str, entries: dict[str, str]) -> str: + """Write the map an option bound to state is looked up in. + + Args: + name: The name of the map. + entries: The compiled style of each value. + + Returns: + The expected declaration. + """ + body = ", ".join(f'"{key}": {value}' for key, value in entries.items()) + return f"const {name} = {{ __proto__: null, {body} }};" + + +ACCENT_MAP = _map( + "reflexUIAccents", + { + name: f"accent{name.capitalize()}" + for name in sorted(_radix_tokens.ACCENT_THEMES) + }, +) + + def test_accent_bound_to_state_imports_every_accent(): - """The page chooses among all of them, and the gray that matches each.""" + """The page chooses among all of them when it renders.""" accent = str(ThemeState.accent) styles = theme_styles( - "rx.ui.theme", - accent_color=ThemeState.accent, - gray_color="auto", - app_theme=Theme(), + "rx.ui.theme", accent_color=ThemeState.accent, app_theme=Theme() ) - assert styles.refs == ( - *SCOPES, - "focusScope", - f"reflexUIAccents[{accent}]", - f"reflexUIMatchingGrays[{accent}]", - "reflexUITheme.root", + assert styles.classes == ( + '"reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, ' + "typographyScope, shadowScope, colorScope, focusScope, " + f"reflexUIAccents[{accent}], reflexUITheme.root)" ) assert styles.imports == tuple( sorted([ + HELPER_IMPORT, *ACCENT_IMPORTS, - *GRAY_IMPORTS, FOCUS_IMPORT, *SCOPE_IMPORTS, STYLES_IMPORT, ]) ) - assert styles.declarations == ( - ACCENT_MAP, - "const reflexUIMatchingGrays = { " - + ", ".join( - f'"{name}": gray{gray.capitalize()}' - for name, gray in sorted(_radix_tokens.MATCHING_GRAY.items()) - ) - + " };", - ) - assert styles.class_name == "reflex-ui-theme" - assert styles.var_data == ThemeState.accent._get_all_var_data() + assert styles.declarations == (ACCENT_MAP,) + assert [var.equals(ThemeState.accent) for var in styles.vars] == [True] - # With a gray of its own, or the one around it, only the accents are. - inherited = theme_styles( - "rx.ui.theme", accent_color=ThemeState.accent, app_theme=Theme() - ) - assert inherited.refs == ( - *SCOPES, - "focusScope", - f"reflexUIAccents[{accent}]", - "reflexUITheme.root", - ) - assert inherited.declarations == (ACCENT_MAP,) + # The gray that matches each accent is chosen the same way. styles = theme_styles( "rx.ui.theme", accent_color=ThemeState.accent, - gray_color="sand", + gray_color="auto", app_theme=Theme(), + style="sx_0123456789_o", ) - assert styles.refs == ( - *SCOPES, - "focusScope", - f"reflexUIAccents[{accent}]", - "graySand", - "reflexUITheme.root", + assert styles.classes == ( + '"reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, ' + "typographyScope, shadowScope, colorScope, focusScope, " + f"reflexUIAccents[{accent}], reflexUIMatchingGrays[{accent}], " + "reflexUITheme.root, sx_0123456789_o)" ) assert styles.imports == tuple( sorted([ + HELPER_IMPORT, *ACCENT_IMPORTS, - ("themes/gray/sand.js", "graySand", None), + *GRAY_IMPORTS, FOCUS_IMPORT, *SCOPE_IMPORTS, STYLES_IMPORT, ]) ) - assert styles.declarations == (ACCENT_MAP,) + assert styles.declarations == ( + ACCENT_MAP, + _map( + "reflexUIMatchingGrays", + { + name: f"gray{gray.capitalize()}" + for name, gray in sorted(_radix_tokens.MATCHING_GRAY.items()) + }, + ), + ) def test_every_option_can_be_bound_to_state(): @@ -478,38 +519,40 @@ def test_every_option_can_be_bound_to_state(): app_theme=Theme(), ) appearance = str(state.appearance) - assert styles.refs == ( - *SCOPES, - "focusScope", - f"reflexUIGrays[{state.gray!s}]", - f"reflexUIRadii[{state.radius!s}]", - f"reflexUIScalings[{state.scaling!s}]", - f"reflexUIPanels[{state.panel!s}]", - "reflexUITheme.root", - f"({state.background!s}) && reflexUITheme.background", - f"reflexUITheme[{appearance}]", + assert styles.classes == ( + '"reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, ' + "typographyScope, shadowScope, colorScope, focusScope, " + f"reflexUIGrays[{state.gray!s}], reflexUIRadii[{state.radius!s}], " + f"reflexUIScalings[{state.scaling!s}], reflexUIPanels[{state.panel!s}], " + f"reflexUITheme.root, ({state.background!s}) && reflexUITheme.background, " + f"reflexUITheme[{appearance}])" ) assert styles.declarations == ( - ( - 'const reflexUIGrays = { "gray": grayGray, "mauve": grayMauve, ' - '"olive": grayOlive, "sage": graySage, "sand": graySand, ' - '"slate": graySlate };' + _map( + "reflexUIGrays", + { + name: f"gray{name.capitalize()}" + for name in sorted(_radix_tokens.GRAY_THEMES) + }, ), ( - 'const reflexUIRadii = { "full": radiusFull, "large": radiusLarge, ' - '"medium": radiusMedium, "none": radiusNone, "small": radiusSmall };' + 'const reflexUIRadii = { __proto__: null, "full": radiusFull, ' + '"large": radiusLarge, "medium": radiusMedium, "none": radiusNone, ' + '"small": radiusSmall };' ), ( - 'const reflexUIScalings = { "100%": scaling100, "105%": scaling105, ' - '"110%": scaling110, "90%": scaling90, "95%": scaling95 };' + 'const reflexUIScalings = { __proto__: null, "100%": scaling100, ' + '"105%": scaling105, "110%": scaling110, "90%": scaling90, ' + '"95%": scaling95 };' ), ( - 'const reflexUIPanels = { "solid": panelSolid, ' + 'const reflexUIPanels = { __proto__: null, "solid": panelSolid, ' '"translucent": panelTranslucent };' ), ) assert styles.imports == tuple( sorted([ + HELPER_IMPORT, *GRAY_IMPORTS, FOCUS_IMPORT, *( @@ -528,23 +571,22 @@ def test_every_option_can_be_bound_to_state(): STYLES_IMPORT, ]) ) - assert styles.var_data == rx.vars.VarData.merge( - state.gray._get_all_var_data(), - state.radius._get_all_var_data(), - state.scaling._get_all_var_data(), - state.panel._get_all_var_data(), - state.appearance._get_all_var_data(), - state.background._get_all_var_data(), - ) + assert [str(var) for var in styles.vars] == [ + str(state.gray), + str(state.radius), + str(state.scaling), + str(state.panel), + appearance, + str(state.background), + ] # An appearance bound to state paints the background when it is one. styles = theme_styles("rx.ui.theme", appearance=state.appearance, app_theme=Theme()) - assert styles.refs == ( - *SCOPES, - "focusScope", - "reflexUITheme.root", - f'({appearance}) !== "inherit" && reflexUITheme.background', - f"reflexUITheme[{appearance}]", + assert styles.classes == ( + '"reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, ' + "typographyScope, shadowScope, colorScope, focusScope, " + f'reflexUITheme.root, ({appearance}) !== "inherit" && ' + f"reflexUITheme.background, reflexUITheme[{appearance}])" ) @@ -615,22 +657,25 @@ def test_nested_theme_refuses_a_value_an_option_does_not_take( def test_color_scheme_is_an_accent_on_one_element(): """A component with a color imports its accent, and the focus that follows.""" - assert color_scheme_styles("rx.ui.button", "red") == ThemeStyles( - refs=("accentRed", "focusScope"), imports=(RED, FOCUS_IMPORT) - ) - assert color_scheme_styles("rx.ui.button", LiteralVar.create("red")) == ThemeStyles( - refs=("accentRed", "focusScope"), imports=(RED, FOCUS_IMPORT) + red = ThemeStyles( + classes="reflexUIClasses_01ac7ed29f", + imports=(HELPER_IMPORT, RED, FOCUS_IMPORT), + declarations=( + ( + "const reflexUIClasses_01ac7ed29f = " + "reflexUIClassName(accentRed, focusScope);" + ), + ), ) + assert color_scheme_styles("rx.ui.button", "red") == red + assert color_scheme_styles("rx.ui.button", LiteralVar.create("red")) == red # A gray component keeps the focus colors of the theme, as in Radix Themes. assert color_scheme_styles("rx.ui.button", "gray") == ThemeStyles( - refs=("accentGray",), imports=(GRAY_ACCENT,) - ) - accent = str(ThemeState.accent) - assert color_scheme_styles("rx.ui.button", ThemeState.accent) == ThemeStyles( - refs=(f"reflexUIAccents[{accent}]", f'({accent}) !== "gray" && focusScope'), - imports=(*ACCENT_IMPORTS, FOCUS_IMPORT), - declarations=(ACCENT_MAP,), - var_data=ThemeState.accent._get_all_var_data(), + classes="reflexUIClasses_fe8edd03f8", + imports=(HELPER_IMPORT, GRAY_ACCENT), + declarations=( + "const reflexUIClasses_fe8edd03f8 = reflexUIClassName(accentGray);", + ), ) with pytest.raises(ThemeError) as error: color_scheme_styles("rx.ui.button", "slate") @@ -639,12 +684,39 @@ def test_color_scheme_is_an_accent_on_one_element(): ) +def test_color_scheme_bound_to_state_indexes_a_table_of_class_names(): + """Every accent is imported, and joined with its focus when the module loads.""" + styles = color_scheme_styles("rx.ui.button", ThemeState.accent) + assert styles.classes == f"reflexUIColorSchemes[{ThemeState.accent!s}]" + assert styles.imports == tuple( + sorted([HELPER_IMPORT, *ACCENT_IMPORTS, FOCUS_IMPORT]) + ) + assert styles.declarations == ( + _map( + "reflexUIColorSchemes", + { + name: "reflexUIClassName(accentGray)" + if name == "gray" + else f"reflexUIClassName(accent{name.capitalize()}, focusScope)" + for name in sorted(_radix_tokens.ACCENT_THEMES) + }, + ), + ) + assert [var.equals(ThemeState.accent) for var in styles.vars] == [True] + + def test_import_dict_names_the_modules_as_an_app_imports_them(): assert color_scheme_styles("rx.ui.button", "red").import_dict() == { + "$/reflex-ui/class-name.js": [ + ImportVar(tag="className", alias="reflexUIClassName") + ], "$/reflex-ui/themes/accent/red.js": [ImportVar(tag="accentRed")], "$/reflex-ui/themes/focus.js": [ImportVar(tag="focusScope")], } assert theme_styles("rx.ui.theme", app_theme=Theme()).import_dict() == { + "$/reflex-ui/class-name.js": [ + ImportVar(tag="className", alias="reflexUIClassName") + ], "$/reflex-ui/themes/focus.js": [ImportVar(tag="focusScope")], "$/reflex-ui/themes/scope.js": [ ImportVar(tag="colorScope"), From aab5b831a51fc237ea3e50b54250d358f9c3449e Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 12:09:34 +0000 Subject: [PATCH 25/26] Test color_scheme and the whole token sweep live on the merged base Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- .../tests_playwright/test_ui_components.py | 94 ++++++++++++++----- .../reflex_components_ui/layout/test_theme.py | 10 +- tests/units/reflex_components_ui/test_base.py | 2 +- 3 files changed, 75 insertions(+), 31 deletions(-) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 5197c381bec..3bf0a9746fe 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -191,6 +191,19 @@ class Tone(UIComponent): # Which look the element has. tone: rx.Var[Literal["calm", "loud"]] + class Chip(UIComponent): + """An element with a color of its own.""" + + styles: ClassVar[ComponentStyles] = { + "base": { + "background_color": tokens.accent[9], + "outline_color": tokens.focus[8], + }, + } + + # The accent color of the element. + color_scheme: rx.Var[str] + def index(): return rx.el.main( rx.ui.box("plain", id="plain"), @@ -240,6 +253,9 @@ def theme(): id="nested", ), probe("after-probe"), + Chip.create("theme", id="chip-theme"), + Chip.create("red", id="chip-red", color_scheme="red"), + Chip.create("gray", id="chip-gray", color_scheme="gray"), rx.el.button("toggle", id="toggle", on_click=rx.toggle_color_mode), ) @@ -293,7 +309,9 @@ def sweep(): themes.append( rx.theme(id=f"radix-{index}", custom_attrs=label, **options) ) - return rx.el.main(*themes) + # The tokens no theme defines are on a page through what uses them. + uses = rx.ui.box(cursor=tokens.cursor.button, color=tokens.white.a[1]) + return rx.el.main(*themes, uses) def buttons(): return rx.fragment( @@ -378,6 +396,7 @@ def bound(): appearance=ThemeState.appearance, # pyright: ignore [reportArgumentType] id="bound", ), + Chip.create("bound", id="chip-bound", color_scheme=ThemeState.accent), rx.el.button("change", id="change", on_click=ThemeState.change), ) @@ -649,20 +668,33 @@ def test_no_page_ships_the_stylex_runtime(prod_app: AppHarness): A value bound to state is a custom property, and a variant bound to state indexes a table of folded class names, so no script holds a call into - StyleX or a style object it reads at runtime: neither the literal page nor - the styled one, whose chunk holds the table. + StyleX: neither the literal page nor the styled one, whose element holds + the table. """ scripts = _scripts(prod_app) + # No script holds the StyleX runtime, whose name minifying leaves alone. + assert [ + name for name, code in scripts.items() if re.search(r"stylex|styleq", code) + ] == [] + # A compiled style is only kept where a theme reads it: a theme is + # declared in a module of its own, so its classes are joined when the + # page loads. The pages without a theme of their own hold none. assert [ - name for name, code in scripts.items() if re.search(r"stylex|\$\$css", code) + name + for name, code in scripts.items() + if name.startswith(("assets/_literal_", "assets/_styled_", "assets/_index")) + and "$$css" in code ] == [] - styled_chunks = [name for name in scripts if name.startswith("assets/_styled_")] - assert len(styled_chunks) == 1, sorted(scripts) # The table of the variant, in the chunk that renders the element: the - # class names of each value. - (table,) = re.findall( - r"\{__proto__:null,calm:.*?,loud:.*?\}[^}]*\}", scripts[styled_chunks[0]] - ) + # class names of each value. The element is in the module of the + # components the app keeps apart from their pages, which two pages load. + tables = [ + (name.split("-")[0], table) + for name, code in scripts.items() + for table in re.findall(r"\{__proto__:null,calm:.*?,loud:.*?\}[^}]*\}", code) + ] + ((chunk, table),) = tables + assert chunk == f"assets/{prod_app.app_name}" assert re.fullmatch( r"\{__proto__:null,calm:\{className:`x\w+ x\w+`\}\.className," r"loud:\{className:`x\w+ x\w+`\}\.className\}", @@ -954,9 +986,6 @@ def test_prerendered_theme_page_is_themed_without_javascript( if name not in ("--panel-solid", "--color-panel-if-solid") ] -# The custom properties of the modules the sweep page does not import. -NOT_ON_THE_PAGE = ("--cursor-", "--white-") - READ_SWEEP = """async ([scripts, names, prefix]) => { const { labels, mount, read } = await import(scripts + "probe.js"); const container = document.createElement("div"); @@ -1057,19 +1086,7 @@ def test_tokens_resolve_as_under_radix_themes( if value.startswith("INVALID") ] == [] assert _sweep_differences(radix, mixed) == [] - # On its own, an app only has the custom properties of the modules it - # imports: nothing on the page uses a cursor or a white. - assert [ - difference - for difference in _sweep_differences(radix, alone) - if not difference[1].startswith(NOT_ON_THE_PAGE) - ] == [] - assert sorted({ - label - for _, _, values in alone["themes"] - for label, value in zip(alone["labels"], values, strict=True) - if value.startswith("INVALID") - }) == sorted(name for name in SWEEP_NAMES if name.startswith(NOT_ON_THE_PAGE)) + assert _sweep_differences(radix, alone) == [] def test_radix_components_follow_the_rx_ui_theme(mixed_app: AppHarness, page: Page): @@ -1137,6 +1154,31 @@ def read() -> list[str]: "inherit", "contents", ] + # A component with a color bound to the same state: red 9. + chip = page.locator("#chip-bound") + expect(chip).to_have_css("background-color", "rgb(229, 72, 77)") page.locator("#change").click() expect(probe).to_have_css("color", "rgb(61, 214, 140)") + # Green 9, and step 8 of the focus ring that follows it. + expect(chip).to_have_css("background-color", "rgb(48, 164, 108)") + expect(chip).to_have_css("outline-color", "rgb(91, 185, 139)") assert read() == [SLATE_2["dark"], "dark", "rgb(17, 17, 19)", "dark", "contents"] + + +def test_color_scheme_is_the_accent_of_one_element(ui_app: AppHarness, page: Page): + """A component with a color follows it, and the focus ring with it.""" + _goto_theme_page(ui_app, page) + # Step 9 of the accent, then step 8 of the focus ring. The theme is + # indigo, and its gray is slate: a gray component keeps the indigo focus. + assert page.evaluate( + """() => Object.fromEntries( + [...document.querySelectorAll('[id^="chip-"]')].map((chip) => { + const style = getComputedStyle(chip); + return [chip.id, [style.backgroundColor, style.outlineColor]]; + }), + )""" + ) == { + "chip-theme": ["rgb(62, 99, 221)", "rgb(141, 164, 239)"], + "chip-red": ["rgb(229, 72, 77)", "rgb(235, 142, 144)"], + "chip-gray": ["rgb(139, 141, 152)", "rgb(141, 164, 239)"], + } diff --git a/tests/units/reflex_components_ui/layout/test_theme.py b/tests/units/reflex_components_ui/layout/test_theme.py index 0c9750342fd..0d3aca90681 100644 --- a/tests/units/reflex_components_ui/layout/test_theme.py +++ b/tests/units/reflex_components_ui/layout/test_theme.py @@ -340,10 +340,12 @@ def test_theme_with_an_appearance_is_inside_the_element_of_its_class( f'className:({ThemeState.appearance!s}) + " " + sx_71b84cd269_c' ] assert bound.children[0].render()["props"] == [ - 'className:"reflex-ui-theme " + reflexUIClassName(spaceScope, ' - "radiusScope, typographyScope, shadowScope, colorScope, focusScope, " - f'reflexUITheme.root, ({ThemeState.appearance!s}) !== "inherit" && ' - f"reflexUITheme.background, reflexUITheme[{ThemeState.appearance!s}])" + ( + 'className:"reflex-ui-theme " + reflexUIClassName(spaceScope, ' + "radiusScope, typographyScope, shadowScope, colorScope, focusScope, " + f'reflexUITheme.root, ({ThemeState.appearance!s}) !== "inherit" && ' + f"reflexUITheme.background, reflexUITheme[{ThemeState.appearance!s}])" + ) ] diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py index edc2d71d744..2ca3bfa9639 100644 --- a/tests/units/reflex_components_ui/test_base.py +++ b/tests/units/reflex_components_ui/test_base.py @@ -11,9 +11,9 @@ from reflex_base.utils.exceptions import ConfigError from reflex_base.utils.serializers import serialize from reflex_base.vars.base import Var +from reflex_components_ui import tokens from reflex_components_ui.base import Part, UIComponent from reflex_components_ui.plugin import UIPlugin -from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, StyleError from reflex_components_ui.themes import LiteralAccentColor, ThemeError From 9bf05cc5bb2d8fad68918cf7d4aa32a545401363 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 12:20:18 +0000 Subject: [PATCH 26/26] Document the theme classes without the StyleX runtime, and settle the checks Claude-Session: https://claude.ai/code/session_014AwvTPtxM37ThmoUybK9Fe --- packages/reflex-components-ui/README.md | 50 +++++++++++++------ .../reflex-components-ui/js/src/README.md | 2 + .../js/tests/class-name.test.js | 8 +-- .../news/+theme-python.feature.md | 2 +- .../src/reflex_components_ui/layout/theme.py | 19 +++++-- .../src/reflex_components_ui/styles/theme.py | 4 +- 6 files changed, 59 insertions(+), 26 deletions(-) diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 4c9155c495f..7bbfac922c6 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -36,6 +36,7 @@ src/reflex_components_ui/ the python package: the rx.ui namespace js/ the javascript package, with its own tooling src/ what ships: copied into an app at .web/reflex-ui/ base.css the cascade layer order and the color scheme switch + class-name.js joins the class names of compiled styles: a theme's vite-plugin-stylex.js the StyleX Vite plugin, fitted to the Reflex build colors/ generated: one module for each Radix color scale tokens/ generated: space, radius, typography, shadow, ... @@ -298,16 +299,28 @@ both follows this one. It is a `div` with the class of a StyleX theme for each option, and the only thing imported for an accent is the module of that accent: ```js +import {className as reflexUIClassName} from "$/reflex-ui/class-name.js" import {accentIndigo} from "$/reflex-ui/themes/accent/indigo.js" import {focusScope} from "$/reflex-ui/themes/focus.js" import {graySlate} from "$/reflex-ui/themes/gray/slate.js" ... -jsx("div",{...stylex.props(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentIndigo, graySlate, radiusLarge, scaling100, panelTranslucent, reflexUITheme.root, reflexUITheme.background, sx_c1c0436182.s, { $$css: true, className: "reflex-ui-theme" })}, ...) +const sx_c1c0436182 = stylex.create({ s: {"position": "relative", "zIndex": 0, "minHeight": {...}} }); +const sx_c1c0436182_c = stylex.props(sx_c1c0436182.s).className; +const sx_c1c0436182_o = sx_c1c0436182.s; +const reflexUIClasses_48dbd5f3d5 = "reflex-ui-theme " + reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, colorScope, focusScope, accentIndigo, graySlate, radiusLarge, scaling100, panelTranslucent, reflexUITheme.root, reflexUITheme.background, sx_c1c0436182_o); + +jsx("div",{className:reflexUIClasses_48dbd5f3d5}, ...) ``` -A theme imported from another module is not folded into a string: the call -stays, and with it the 1.2 kB of the StyleX runtime, in the chunk every page -already loads. +StyleX folds `stylex.props(...)` into a string only when every argument is +declared in the module that makes the call, and a theme is declared in a +module of its own. So the classes of a theme are joined when the module +loads, by `class-name.js`: what `stylex.props(...).className` does, a later +style winning a property, without the rest of the StyleX runtime, which no +page ships. The theme of the app adds 0.6 kB of gzipped javascript to the +chunk every page already loads, and no chunk. The element's own style is last, +through `sx_..._o`, the style before it is folded: it wins where a theme +element sets the same property, such as the text color. `rx.ui.theme(...)` is the same element around part of a page. It takes the same options, each one optional: what it leaves out is inherited. @@ -370,8 +383,10 @@ A step or a name that does not exist is an error to a type checker, and a steps are 1 to 9.` `lower` reads a token like any other string. It names the module that defines -the custom property in `Lowered.imports` (`VAR_MODULES`, which is built from -the generated list), and a shorthand gives a token that holds one value to its +the custom property in `Lowered.imports`: `VAR_MODULES` has the module of each +of the 1,070 custom properties by its whole name, built from the generated +list, and a `var()` of any other custom property, such as one an app defines, +is left alone and imports nothing. A shorthand gives a token that holds one value to its longhands, as it does with `rx.color(...)`: `{"padding": f"{tokens.space[2]} {tokens.space[4]}"}` becomes four paddings. A shadow and a font family are lists, and keep the shorthand whole. @@ -381,18 +396,21 @@ For a component: - Write the style table with tokens, never with the color of a named scale: `"background_color": tokens.accent[9]`, `"color": tokens.accent.contrast`, `"border_radius": tokens.radius[2]`, `"height": tokens.space[6]`. -- `color_scheme` is an accent on the element itself. - `themes.color_scheme_styles(name, value)` returns what the element needs: - the arguments to add to its `stylex.props` call (`accentRed` and - `focusScope`; `accentGray` alone for gray), the imports - (`import_dict()`), and for a value bound to state the map of all 26 accents - to declare in the module. The tokens of the table then resolve against the - accent of the element. +- `color_scheme` is an accent on the element itself. Declare the field, + `color_scheme: Var[LiteralAccentColor]` from `reflex_components_ui.themes`, + and `UIComponent` does the rest: the tokens of the table resolve against + the accent of the element. A literal color imports its accent and + `focusScope` and joins their classes in a constant; `"gray"` imports + `accentGray` alone, and keeps the focus colors of the theme; a color bound + to state imports all 26 and indexes a table of their class names, built + when the module loads. On a component without the field, `color_scheme` is + the CSS property. `themes.color_scheme_styles(name, value)` is what + `UIComponent` calls. - The space, radius, typography, shadow and `--color-*` tokens, the accent, the gray and the focus colors are defined wherever a theme is, which in an app is - everywhere. A cursor, a black or a white, and a scale named with - `tokens.scale` or `rx.color` are defined by the module `Lowered.imports` - names, once the element that uses them imports it. + everywhere. A cursor, a white, and a scale named with `tokens.scale` or + `rx.color` are defined by the module `Lowered.imports` names, which the + module that renders the element imports. - A color is one `light-dark()` value: `getPropertyValue("--accent-9")` in the browser returns the pair, and a computed `color` the one in use. diff --git a/packages/reflex-components-ui/js/src/README.md b/packages/reflex-components-ui/js/src/README.md index af2fc6ae59c..00144678adf 100644 --- a/packages/reflex-components-ui/js/src/README.md +++ b/packages/reflex-components-ui/js/src/README.md @@ -8,6 +8,8 @@ is overwritten. - `base.css` is imported first by the app's stylesheet: it orders the cascade layers, switches the color scheme, and holds the selection color of a theme and the font faces the typography tokens name. +- `class-name.js` joins the class names of compiled styles where StyleX + cannot fold them into a string: on an element that carries a theme. - `colors/`, `tokens/` and `themes/` are the design tokens and the themes, as StyleX modules: a module adds its CSS when a page imports it. - `vite-plugin-stylex.js` is the plugin `vite.config.js` loads to compile the diff --git a/packages/reflex-components-ui/js/tests/class-name.test.js b/packages/reflex-components-ui/js/tests/class-name.test.js index e7bcd55af44..8f4e622e664 100644 --- a/packages/reflex-components-ui/js/tests/class-name.test.js +++ b/packages/reflex-components-ui/js/tests/class-name.test.js @@ -27,8 +27,10 @@ test("the classes are the ones the StyleX runtime gives", () => { const cases = [[red], [red, blue], [blue, red], [red, false, unset]]; for (const styles of cases) { const expected = stylex.props(...styles).className ?? ""; - expect(className(...styles).split(" ").sort()).toEqual( - expected.split(" ").filter(Boolean).sort(), - ); + expect( + className(...styles) + .split(" ") + .sort(), + ).toEqual(expected.split(" ").filter(Boolean).sort()); } }); diff --git a/packages/reflex-components-ui/news/+theme-python.feature.md b/packages/reflex-components-ui/news/+theme-python.feature.md index 4ddb27ece4a..28d25e62028 100644 --- a/packages/reflex-components-ui/news/+theme-python.feature.md +++ b/packages/reflex-components-ui/news/+theme-python.feature.md @@ -1 +1 @@ -`rx.plugins.UIPlugin(theme=rx.ui.Theme(accent_color="indigo", radius="large"))` themes the whole app, `rx.ui.theme(...)` themes part of a page with the same options, and `rx.ui.tokens` names the design tokens as style values, such as `rx.ui.tokens.space[4]` and `rx.ui.tokens.accent.contrast`. The tokens have the values of Radix Themes. +`rx.plugins.UIPlugin(theme=rx.ui.Theme(accent_color="indigo", radius="large"))` themes the whole app, `rx.ui.theme(...)` themes part of a page with the same options, and `rx.ui.tokens` names the design tokens as style values, such as `rx.ui.tokens.space[4]` and `rx.ui.tokens.accent.contrast`. The tokens have the values of Radix Themes. A component with a `color_scheme` prop takes that accent for itself. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py index af22c01660e..5c6dd169bc9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/theme.py @@ -17,7 +17,7 @@ from reflex_components_ui.base import MISSING_PLUGIN_ERROR, UIComponent, add_styles from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.style.emit import style_object +from reflex_components_ui.style.emit import Emitted, style_object from reflex_components_ui.styles.theme import APP_THEME, APPEARANCE from reflex_components_ui.themes import ( OPTIONS, @@ -160,6 +160,15 @@ def _get_vars( if isinstance(value, Var): yield value + def _own_styles(self) -> Emitted: + """Get the StyleX source of the element's own styles. + + Returns: + What the module that renders the element declares for them. + """ + # The generated stub of the base class leaves its private methods out. + return self._emit() # pyright: ignore [reportAttributeAccessIssue] + def _theme_styles(self) -> ThemeStyles: """Work out the StyleX themes of the element. @@ -181,7 +190,7 @@ def _theme_styles(self) -> ThemeStyles: plugin = get_plugin(UIPlugin) if plugin is None: raise ConfigError(MISSING_PLUGIN_ERROR) - style = style_object(self._emit()) + style = style_object(self._own_styles()) if style is None: return self._resolve_theme_styles(plugin, None) statement, name = style @@ -226,7 +235,7 @@ def add_custom_code(self) -> list[str]: The declaration of the element's own style, which the others name, then the ones of its theme. """ - declaration = self._emit().declaration + declaration = self._own_styles().declaration declarations = self._theme_styles().declarations return [*declarations] if declaration is None else [declaration, *declarations] @@ -242,7 +251,9 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """ tag = Component._render(self, props) theme = self._theme_styles() - return add_styles(tag, dataclasses.replace(self._emit(), classes=theme.classes)) + return add_styles( + tag, dataclasses.replace(self._own_styles(), classes=theme.classes) + ) class AppTheme(ThemeElement): diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py index 0f42619c1b6..62344a323f6 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/theme.py @@ -7,8 +7,8 @@ APP_THEME: ComponentStyles = { "base": { "position": "relative", - "zIndex": 0, - "minHeight": { + "z_index": 0, + "min_height": { "default": "100vh", "@supports (min-height: 100dvh)": "100dvh", },