From 0dfe9995cd18fdcbfe61c135dd21a357528068ab Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 03:58:56 +0000 Subject: [PATCH 001/204] 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 002/204] 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 006/204] 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 007/204] 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 008/204] 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 009/204] 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 010/204] 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 011/204] 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 012/204] 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 013/204] 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 014/204] 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 015/204] 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 016/204] 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 017/204] 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 018/204] 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 019/204] 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 020/204] 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 021/204] 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 022/204] 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 023/204] 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 0fd5c2711eb4330b6d0398fe1c9199ba243ded57 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 12:05:31 +0000 Subject: [PATCH 024/204] WIP: import Emotion's jsx only in modules that render a css prop Claude-Session: https://claude.ai/code/session_014AwvTP2WjJKEVdjMR1jQ6p --- .../src/reflex_base/compiler/templates.py | 3 +- .../src/reflex_base/components/component.py | 37 +++++- .../src/reflex_base/components/dynamic.py | 10 +- .../src/reflex_base/components/memo.py | 3 +- .../src/reflex_base/constants/compiler.py | 9 ++ .../reflex-base/src/reflex_base/registry.py | 16 +++ .../base/error_boundary.py | 100 ++++++++--------- .../base/static_style.py | 26 +++++ .../src/reflex_components_core/core/banner.py | 42 +++---- .../src/reflex_components_core/core/sticky.py | 106 +++++++----------- .../datadisplay/logo.py | 7 +- reflex/compiler/compiler.py | 18 ++- reflex/compiler/utils.py | 25 ++++- 13 files changed, 245 insertions(+), 157 deletions(-) create mode 100644 packages/reflex-components-core/src/reflex_components_core/base/static_style.py diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 52447e4928c..1f58f518702 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -488,7 +488,6 @@ def context_template( return rf"""import {"React, " if disable_react_owner_stacks else ""}{{ useContext, useMemo, useState, createElement, useEffect }} from "react" {state_imports_str} import {{ ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext, registerApp, eventLoop }} from "$/utils/context-registry" -import {{ jsx }} from "@emotion/react"; {disable_owner_stacks_str} export {{ ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext }}; export const initialState = {initial_state_json} @@ -553,7 +552,7 @@ def context_template( }} load(); }}, []); - return Component ? jsx(Component, props, children) : null; + return Component ? createElement(Component, props, children) : null; }} ClientSideComponent.displayName = name ? `ClientSide(${{name}})` : "ClientSide"; return ClientSideComponent; diff --git a/packages/reflex-base/src/reflex_base/components/component.py b/packages/reflex-base/src/reflex_base/components/component.py index b9005fdd3bf..5241a96388f 100644 --- a/packages/reflex-base/src/reflex_base/components/component.py +++ b/packages/reflex-base/src/reflex_base/components/component.py @@ -329,6 +329,7 @@ def _finalize_fields( _COMPILE_CACHE_ATTRS = ( "_memo_analysis_key", "_cached_render_result", + "_cached_tag", "_vars_cache", "_imports_cache", "_hooks_internal_cache", @@ -1489,6 +1490,31 @@ def _get_style(self) -> dict: else {} ) + def _get_tag(self) -> CommonTag: + """Get the tag the component renders, built once per compile. + + Returns: + The tag ``_render`` returns. + """ + try: + return self._cached_tag + except AttributeError: + pass + tag = self._cached_tag = self._render() + return tag + + def _renders_css_prop(self) -> bool: + """Whether the element this component renders has a ``css`` prop. + + Only Emotion's ``jsx`` applies one, so the module the component is + compiled into imports it. The tag is what decides: it holds the style + of the component and whatever a subclass adds in ``_render``. + + Returns: + True if the rendered tag has a ``css`` prop. + """ + return "css" in self._get_tag().props + def render(self) -> dict: """Render the component. @@ -1499,7 +1525,7 @@ def render(self) -> dict: return self._cached_render_result except AttributeError: pass - tag = self._render() + tag = self._get_tag() children = [child.render() for child in self.children] rendered_dict = tag.render(children) self._replace_prop_names(rendered_dict) @@ -1891,6 +1917,9 @@ def _get_imports(self) -> ParsedImportDict: # Get static imports required for event processing. event_imports = Imports.EVENTS if self.event_triggers else {} + # Only Emotion's element factory applies a ``css`` prop. + jsx_imports = Imports.EMOTION_JSX if self._renders_css_prop() else {} + # Collect imports from Vars used directly by this component. var_imports = [ dict(var_data.imports) @@ -1914,6 +1943,7 @@ def _get_imports(self) -> ParsedImportDict: self._get_hooks_imports(), imports_, event_imports, + jsx_imports, *var_imports, *added_import_dicts, ) @@ -2451,9 +2481,10 @@ def _cached_get_all_var_data(self) -> VarData | None: return VarData.merge( self._var_data, VarData( + # The component asks for Emotion's ``jsx`` itself, through its + # own imports, when it renders a ``css`` prop. imports={ - "@emotion/react": ["jsx"], - "react": ["Fragment"], + "react": [*Imports.REACT_JSX["react"], "Fragment"], }, ), VarData( diff --git a/packages/reflex-base/src/reflex_base/components/dynamic.py b/packages/reflex-base/src/reflex_base/components/dynamic.py index d6e22830038..64779538a51 100644 --- a/packages/reflex-base/src/reflex_base/components/dynamic.py +++ b/packages/reflex-base/src/reflex_base/components/dynamic.py @@ -6,7 +6,11 @@ from typing import TYPE_CHECKING, Any, Union from reflex_base import constants -from reflex_base.registry import RegistrationContext, _default_bundled_libraries +from reflex_base.registry import ( + RegistrationContext, + _default_bundled_libraries, + _eager_bundled_libraries, +) from reflex_base.utils import console, imports from reflex_base.utils.exceptions import DynamicComponentMissingLibraryError from reflex_base.utils.format import format_library_name @@ -302,9 +306,9 @@ def generate_component_code(component: Component) -> str: module_code_lines.insert(0, "const React = window.__reflex.react;") # evalReactComponent loads these optional libraries before the import; - # the default libraries are always in window.__reflex. + # the other default libraries are always in window.__reflex. optional_libraries = sorted( - bundled_library_paths.difference(_default_bundled_libraries()) + bundled_library_paths.difference(_eager_bundled_libraries()) ) function_line = next( diff --git a/packages/reflex-base/src/reflex_base/components/memo.py b/packages/reflex-base/src/reflex_base/components/memo.py index fdfb151db80..3d564b2007d 100644 --- a/packages/reflex-base/src/reflex_base/components/memo.py +++ b/packages/reflex-base/src/reflex_base/components/memo.py @@ -39,6 +39,7 @@ get_memoization_strategy, ) from reflex_base.constants.compiler import ( + Imports, MemoizationDisposition, MemoizationMode, SpecialAttributes, @@ -853,7 +854,7 @@ def _component_import_var(name: str, source_module: str | None = None) -> Var: _var_data=VarData( imports={ library: [ImportVar(tag=symbol)], - "@emotion/react": [ImportVar(tag="jsx")], + **Imports.REACT_JSX, } ), ) diff --git a/packages/reflex-base/src/reflex_base/constants/compiler.py b/packages/reflex-base/src/reflex_base/constants/compiler.py index 48a21df1ed2..a3dd05da6ff 100644 --- a/packages/reflex-base/src/reflex_base/constants/compiler.py +++ b/packages/reflex-base/src/reflex_base/constants/compiler.py @@ -177,6 +177,15 @@ class Imports(SimpleNamespace): f"$/{Dirs.CONTEXTS_PATH}": [ImportVar(tag="EventLoopContext")], } + # Emotion's element factory, the only one that applies a ``css`` prop. A + # component whose element has one asks for it, and the module it is + # compiled into then imports ``jsx`` from here. + EMOTION_JSX = {"@emotion/react": [ImportVar(tag="jsx")]} + + # React's element factory under the name generated code calls. It is what + # ``jsx`` is in a module where nothing asked for Emotion's. + REACT_JSX = {"react": [ImportVar(tag="createElement", alias="jsx")]} + class Hooks(SimpleNamespace): """Common sets of hook declarations.""" diff --git a/packages/reflex-base/src/reflex_base/registry.py b/packages/reflex-base/src/reflex_base/registry.py index 05fb5c694da..45c3877cf35 100644 --- a/packages/reflex-base/src/reflex_base/registry.py +++ b/packages/reflex-base/src/reflex_base/registry.py @@ -37,6 +37,22 @@ def _default_bundled_libraries() -> list[str]: ] +def _eager_bundled_libraries() -> list[str]: + """Return the default libraries every dynamic component can rely on. + + Emotion is left out: only a dynamic component that renders a ``css`` prop + calls it, so it is loaded when one is evaluated. + + Returns: + The default libraries an app loads before any dynamic component. + """ + return [ + library + for library in _default_bundled_libraries() + if library != "@emotion/react" + ] + + @dataclasses.dataclass(frozen=True, kw_only=True, slots=True) class RegisteredEventHandler: """A registered event handler, which includes the handler and its full name.""" diff --git a/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py b/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py index 18650dee4c9..ee99c3bda11 100644 --- a/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py +++ b/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py @@ -8,6 +8,7 @@ from reflex_base.vars.function import ArgsFunctionOperation from reflex_base.vars.object import ObjectVar +from reflex_components_core.base.static_style import static_style from reflex_components_core.datadisplay.logo import svg_logo from reflex_components_core.el import a, button, div, h2, hr, p, pre, svg @@ -30,6 +31,38 @@ def on_error_spec( ) +# The look of the default fallback. Plain rules, not ``css`` props: the +# boundary wraps every app, and an app should not need Emotion to draw it. +_FALLBACK_CSS = ( + ".rx-error-boundary{height:100%;width:100%;position:absolute;" + "background-color:#fff;color:#000;display:flex;align-items:center;" + "justify-content:center}" + ".rx-error-boundary-content{display:flex;flex-direction:column;gap:0.5rem;" + "max-width:min(80ch, 90vw);border-radius:0.25rem;padding:1rem}" + ".rx-error-boundary-heading{opacity:0.5;display:flex;gap:4vmin;" + "align-items:center}" + ".rx-error-boundary-title{font-size:5vmin;font-weight:bold}" + ".rx-error-boundary-hint{opacity:0.75;margin-block:1rem}" + ".rx-error-boundary-details{width:100%;" + "background:color-mix(in srgb, currentColor 5%, transparent);" + "max-height:15rem;overflow:auto;border-radius:0.4rem}" + ".rx-error-boundary-details-body{padding:0.5rem}" + ".rx-error-boundary-trace{word-break:break-word;white-space:pre-wrap}" + ".rx-error-boundary-copy{padding:0.35rem 1.35rem;margin-block:0.5rem;" + "margin-inline-start:auto;" + "background:color-mix(in srgb, currentColor 15%, transparent);" + "border-radius:0.4rem;width:fit-content}" + ".rx-error-boundary-copy:hover" + "{background:color-mix(in srgb, currentColor 25%, transparent)}" + ".rx-error-boundary-copy:active" + "{background:color-mix(in srgb, currentColor 35%, transparent)}" + ".rx-error-boundary-rule{border-color:currentColor;opacity:0.25}" + ".rx-error-boundary-credit{display:flex;align-items:baseline;" + "justify-content:center;font-family:monospace;" + "--default-font-family:monospace;gap:0.5rem}" + ".rx-error-boundary-logo{fill:currentColor}" +) + _ERROR_DISPLAY: str = r"""event_args.error.name + ': ' + event_args.error.message + '\n' + event_args.error.stack""" @@ -67,6 +100,7 @@ def create(cls, *children, **props): ("event_args",), Var.create( div( + static_style("rx-error-boundary", _FALLBACK_CSS), div( div( svg( @@ -88,81 +122,43 @@ def create(cls, *children, **props): ), h2( "An error occurred while rendering this page.", - font_size="5vmin", - font_weight="bold", + class_name="rx-error-boundary-title", ), - opacity="0.5", - display="flex", - gap="4vmin", - align_items="center", + class_name="rx-error-boundary-heading", ), p( "This is an error with the application itself. Refreshing the page might help.", - opacity="0.75", - margin_block="1rem", + class_name="rx-error-boundary-hint", ), div( div( pre( Var(_js_expr=_ERROR_DISPLAY), - word_break="break-word", - white_space="pre-wrap", + class_name="rx-error-boundary-trace", ), - padding="0.5rem", + class_name="rx-error-boundary-details-body", ), - width="100%", - background="color-mix(in srgb, currentColor 5%, transparent)", - max_height="15rem", - overflow="auto", - border_radius="0.4rem", + class_name="rx-error-boundary-details", ), button( "Copy", on_click=set_clipboard(Var(_js_expr=_ERROR_DISPLAY)), - padding="0.35rem 1.35rem", - margin_block="0.5rem", - margin_inline_start="auto", - background="color-mix(in srgb, currentColor 15%, transparent)", - border_radius="0.4rem", - width="fit-content", - _hover={ - "background": "color-mix(in srgb, currentColor 25%, transparent)" - }, - _active={ - "background": "color-mix(in srgb, currentColor 35%, transparent)" - }, - ), - hr( - border_color="currentColor", - opacity="0.25", + class_name="rx-error-boundary-copy", ), + hr(class_name="rx-error-boundary-rule"), a( div( "Built with ", - svg_logo("currentColor"), - display="flex", - align_items="baseline", - justify_content="center", - font_family="monospace", - gap="0.5rem", + svg_logo( + None, class_name="rx-error-boundary-logo" + ), + class_name="rx-error-boundary-credit", ), href="https://reflex.dev", ), - display="flex", - flex_direction="column", - gap="0.5rem", - max_width="min(80ch, 90vw)", - border_radius="0.25rem", - padding="1rem", + class_name="rx-error-boundary-content", ), - height="100%", - width="100%", - position="absolute", - background_color="#fff", - color="#000", - display="flex", - align_items="center", - justify_content="center", + class_name="rx-error-boundary", ) ), _var_type=Component, diff --git a/packages/reflex-components-core/src/reflex_components_core/base/static_style.py b/packages/reflex-components-core/src/reflex_components_core/base/static_style.py new file mode 100644 index 00000000000..17ed85fded8 --- /dev/null +++ b/packages/reflex-components-core/src/reflex_components_core/base/static_style.py @@ -0,0 +1,26 @@ +"""The stylesheet of a part of Reflex's own interface.""" + +from reflex_base.components.component import Component + +from reflex_components_core.el.elements.metadata import StyleEl + + +def static_style(name: str, css: str) -> Component: + """Create a stylesheet that needs no styling library in the page. + + The connection indicator, the badge and the error boundary are part of + every app, so they are styled with class names and plain CSS rather than + a ``css`` prop, which only Emotion applies. React keeps one copy of the + stylesheet per name at the start of the document head, wherever and + however often it is rendered: its rules stay unlayered single class + selectors, as Emotion's were, and a ``css`` prop added to one of the + elements still overrides them. + + Args: + name: What tells the stylesheet from any other in the document. + css: The rules. + + Returns: + The style element. + """ + return StyleEl.create(css, custom_attrs={"href": name, "precedence": "reflex"}) 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 13ccf0cf27e..db01bb1105d 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 @@ -20,6 +20,7 @@ from reflex_components_core import el from reflex_components_core.base.fragment import Fragment +from reflex_components_core.base.static_style import static_style from reflex_components_core.core.cond import cond from reflex_components_core.el.elements.typography import Div @@ -267,6 +268,16 @@ def create(cls, comp: Component | None = None) -> Component: ) +# The look of the connection indicator. Plain rules, not ``css`` props: every +# app with state renders it, and an app should not need Emotion to draw it. +_PULSER_CSS = ( + "@keyframes rx-connection-pulse{from{opacity:0}to{opacity:1}}" + ".rx-connection-pulser{position:fixed;width:100vw;height:0}" + ".rx-connection-pulse{color:crimson;z-index:9999;position:fixed;bottom:33px;" + "right:33px;animation:rx-connection-pulse 1s infinite}" +) + + class WifiOffPulse(Icon): """A wifi_off icon with an animated opacity pulse.""" @@ -276,34 +287,24 @@ def create(cls, *children, **props) -> Icon: Args: *children: The children of the component. - **props: The properties of the component. + **props: The properties of the component. A style prop overrides + the look the icon has by default. Returns: The icon component with default props applied. """ - pulse_var = Var(r"keyframes({ from: { opacity: 0 }, to: { opacity: 1 } })").to( - str - ) + class_name = props.pop("class_name", None) return super().create( "wifi_off", - color=props.pop("color", "crimson"), size=props.pop("size", 32), - z_index=props.pop("z_index", 9999), - position=props.pop("position", "fixed"), - bottom=props.pop("bottom", "33px"), - right=props.pop("right", "33px"), - animation=LiteralVar.create(f"{pulse_var} 1s infinite"), + class_name=( + "rx-connection-pulse" + if class_name is None + else ["rx-connection-pulse", class_name] + ), **props, ) - def add_imports(self) -> dict[str, str | ImportVar | list[str | ImportVar]]: - """Add imports for the WifiOffPulse component. - - Returns: - The import dict. - """ - return {"@emotion/react": [ImportVar(tag="keyframes")]} - class ConnectionPulser(Div): """A connection pulser component.""" @@ -319,14 +320,13 @@ def create(cls, **props) -> Component: The connection pulser component. """ return super().create( + static_style("rx-connection-pulser", _PULSER_CSS), cond( has_connection_errors, WifiOffPulse.create(**props), ), title=f"Connection Error: {connection_error}", - position="fixed", - width="100vw", - height="0", + class_name="rx-connection-pulser", ) diff --git a/packages/reflex-components-core/src/reflex_components_core/core/sticky.py b/packages/reflex-components-core/src/reflex_components_core/core/sticky.py index 1e41773302b..77eb51948dd 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/sticky.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/sticky.py @@ -4,13 +4,36 @@ from reflex_base.components.component import ComponentNamespace from reflex_base.environment import environment -from reflex_base.style import Style +from reflex_components_core.base.static_style import static_style from reflex_components_core.core.colors import color -from reflex_components_core.core.cond import color_mode_cond -from reflex_components_core.core.responsive import desktop_only from reflex_components_core.el.elements.inline import A, Span from reflex_components_core.el.elements.media import Path, Rect, Svg +from reflex_components_core.el.elements.typography import Div + +# The look of the badge. Plain rules, not ``css`` props: the badge is added to +# apps that may otherwise not need Emotion. The colors follow the color mode +# through the class the theme provider keeps on the document element. +_BADGE_CSS = ( + ".rx-sticky-badge{position:fixed;bottom:1rem;right:1rem;display:flex;" + "flex-direction:row;gap:0.375rem;align-items:center;width:auto;" + "border-radius:0.5rem;color:#E5E7EB;border:1px solid #27282B;" + "background-color:#151618;padding:0.375rem;" + "transition:background-color 0.2s ease-in-out;" + "box-shadow:0 1px 2px 0 rgba(0, 0, 0, 0.05);z-index:9998;cursor:pointer;" + "text-align:center}" + ".dark .rx-sticky-badge{color:#27282B;border:1px solid #E5E7EB;" + "background-color:#FCFCFD}" + ".rx-sticky-logo{fill:white}" + ".rx-sticky-logo-square{fill:#6E56CF}" + ".rx-sticky-logo-letter{fill:white}" + "@media screen and (min-width: 0){.rx-sticky-desktop-only{display:none}}" + "@media screen and (min-width: 62em){.rx-sticky-desktop-only{display:block}}" + f".rx-sticky-label{{color:{color('slate', 1)};font-weight:600;" + "font-family:'Instrument Sans', sans-serif;" + "--default-font-family:'Instrument Sans', sans-serif;font-size:0.875rem;" + "line-height:1rem;letter-spacing:-0.00656rem}" +) class StickyLogo(Svg): @@ -24,25 +47,21 @@ def create(cls): The simple Reflex logo SVG. """ return super().create( - Rect.create(width="16", height="16", rx="2", fill="#6E56CF"), - Path.create(d="M10 9V13H12V9H10Z", fill="white"), - Path.create(d="M4 3V13H6V9H10V7H6V5H10V7H12V3H4Z", fill="white"), + Rect.create( + width="16", height="16", rx="2", class_name="rx-sticky-logo-square" + ), + Path.create(d="M10 9V13H12V9H10Z", class_name="rx-sticky-logo-letter"), + Path.create( + d="M4 3V13H6V9H10V7H6V5H10V7H12V3H4Z", + class_name="rx-sticky-logo-letter", + ), width="16", height="16", - viewBox="0 0 16 16", + view_box="0 0 16 16", xmlns="http://www.w3.org/2000/svg", + class_name="rx-sticky-logo", ) - def add_style(self): - """Add the style to the component. - - Returns: - The style of the component. - """ - return Style({ - "fill": "white", - }) - class StickyLabel(Span): """A label that displays the Reflex sticky.""" @@ -54,22 +73,7 @@ def create(cls): Returns: The sticky label. """ - return super().create("Built with Reflex") - - def add_style(self): - """Add the style to the component. - - Returns: - The style of the component. - """ - return Style({ - "color": color("slate", 1), - "font_weight": "600", - "font_family": "'Instrument Sans', sans-serif", - "font_size": "0.875rem", - "line_height": "1rem", - "letter_spacing": "-0.00656rem", - }) + return super().create("Built with Reflex", class_name="rx-sticky-label") def _badge_href() -> str: @@ -95,43 +99,13 @@ def create(cls): The sticky badge. """ return super().create( + static_style("rx-sticky-badge", _BADGE_CSS), StickyLogo.create(), - desktop_only(StickyLabel.create()), + Div.create(StickyLabel.create(), class_name="rx-sticky-desktop-only"), href=_badge_href(), aria_label="Built with Reflex", target="_blank", - width="auto", - padding="0.375rem", - align="center", - text_align="center", - ) - - def add_style(self): - """Add the style to the component. - - Returns: - The style of the component. - """ - return Style( - { - "position": "fixed", - "bottom": "1rem", - "right": "1rem", - "display": "flex", - "flex-direction": "row", - "gap": "0.375rem", - "align-items": "center", - "width": "auto", - "border-radius": "0.5rem", - "color": color_mode_cond("#E5E7EB", "#27282B"), - "border": color_mode_cond("1px solid #27282B", "1px solid #E5E7EB"), - "background-color": color_mode_cond("#151618", "#FCFCFD"), - "padding": "0.375rem", - "transition": "background-color 0.2s ease-in-out", - "box-shadow": "0 1px 2px 0 rgba(0, 0, 0, 0.05)", - "z-index": "9998", - "cursor": "pointer", - }, + class_name="rx-sticky-badge", ) diff --git a/packages/reflex-components-core/src/reflex_components_core/datadisplay/logo.py b/packages/reflex-components-core/src/reflex_components_core/datadisplay/logo.py index 2c007f6c101..c031464494f 100644 --- a/packages/reflex-components-core/src/reflex_components_core/datadisplay/logo.py +++ b/packages/reflex-components-core/src/reflex_components_core/datadisplay/logo.py @@ -8,11 +8,11 @@ SVG_COLOR = color_mode_cond("#110F1F", "white") -def svg_logo(color: str | Var[str] = SVG_COLOR, **props): +def svg_logo(color: str | Var[str] | None = SVG_COLOR, **props): """A Reflex logo SVG. Args: - color: The color of the logo. + color: The color of the logo, or None to leave it to a stylesheet. props: Extra props to pass to the svg component. Returns: @@ -31,6 +31,8 @@ def logo_path(d: str): "M47.04 4.8799V0.399902H49.28V4.8799H47.04ZM53.76 4.8799V0.399902H56V4.8799H53.76ZM49.28 7.1199V4.8799H53.76V7.1199H49.28ZM47.04 11.5999V7.1199H49.28V11.5999H47.04ZM53.76 11.5999V7.1199H56V11.5999H53.76Z", ] + if color is not None: + props["fill"] = color return el.svg( *[logo_path(d) for d in paths], el.title("Reflex"), @@ -38,7 +40,6 @@ def logo_path(d: str): role="img", width=props.pop("width", "56"), height=props.pop("height", "12"), - fill=color, xmlns="http://www.w3.org/2000/svg", **props, ) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 6f8824e57b2..0b599ef9ee2 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -31,12 +31,12 @@ reset_memo_component_classes, ) from reflex_base.config import get_config -from reflex_base.constants.compiler import PageNames, ResetStylesheet +from reflex_base.constants.compiler import Imports, 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.registry import RegistrationContext, _eager_bundled_libraries from reflex_base.utils import log, memo_paths from reflex_base.utils.exceptions import ReflexError from reflex_base.utils.format import to_title_case @@ -83,9 +83,17 @@ def _set_progress_total( def _apply_common_imports( imports: dict[str, list[ImportVar]], ): - imports.setdefault("@emotion/react", []).append(ImportVar("jsx")) + """Add the imports every generated module relies on. + + ``jsx`` is React's ``createElement`` here. A component of the module that + renders a ``css`` prop asks for Emotion's instead, and + ``utils.compile_imports`` then keeps that one. + + Args: + imports: The import dictionary of the module, updated in place. + """ imports.setdefault("react", []).extend( - [ImportVar("Fragment"), ImportVar("useEffect")], + [*Imports.REACT_JSX["react"], ImportVar("Fragment"), ImportVar("useEffect")], ) @@ -194,7 +202,7 @@ def _split_window_libraries( window_libraries = _get_window_libraries() if not get_config().frontend_lazy_bundled_libraries: return window_libraries, [] - core_libraries = set(_default_bundled_libraries()) + core_libraries = set(_eager_bundled_libraries()) explicit_libraries = ( RegistrationContext.ensure_context()._explicit_bundled_libraries ) diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index e0b490938b3..267a5f183c6 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -31,6 +31,7 @@ MemoFunctionDefinition, MemoParamKind, ) +from reflex_base.constants.compiler import Imports from reflex_base.constants.state import FIELD_MARKER from reflex_base.registry import RegistrationContext from reflex_base.style import Style @@ -132,6 +133,27 @@ class _ImportDict(TypedDict): rest: list[str] +(_EMOTION_JSX,) = Imports.EMOTION_JSX["@emotion/react"] +(_REACT_JSX,) = Imports.REACT_JSX["react"] + + +def _resolve_jsx_import(import_dict: ParsedImportDict) -> None: + """Settle which element factory a module calls ``jsx``. + + Every module is given React's ``createElement`` under that name. Emotion's + is requested by whatever renders a ``css`` prop in the module, and wins: + it is the only one that applies the prop, and it behaves as React's does + for an element without one. + + Args: + import_dict: The collapsed imports of one module, updated in place. + """ + if _EMOTION_JSX in import_dict.get("@emotion/react", ()) and _REACT_JSX in ( + react_imports := import_dict.get("react", ()) + ): + react_imports.remove(_REACT_JSX) + + def compile_imports(import_dict: ParsedImportDict) -> list[_ImportDict]: """Compile an import dict. @@ -145,6 +167,7 @@ def compile_imports(import_dict: ParsedImportDict) -> list[_ImportDict]: ValueError: If an import in the dict is invalid. """ collapsed_import_dict: ParsedImportDict = imports.collapse_imports(import_dict) + _resolve_jsx_import(collapsed_import_dict) validate_imports(collapsed_import_dict) import_dicts: list[_ImportDict] = [] for lib, fields in collapsed_import_dict.items(): @@ -654,7 +677,7 @@ def compile_experimental_component_memo( lib: fields for lib, fields in all_imports.items() if lib != self_module } - imports.setdefault("@emotion/react", []).append(ImportVar("jsx")) + imports.setdefault("react", []).extend(Imports.REACT_JSX["react"]) # The wrapper import (``memo`` from React by default) rides on the wrapper # var itself, so a custom wrapper brings its own imports and ``None`` From 3b54a6f3034db0f609357d036b149161b3940636 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 12:05:46 +0000 Subject: [PATCH 025/204] 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 026/204] 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 027/204] 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", }, From fc2450c97afac2456d4481d073b8b8666f5f4408 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 12:36:27 +0000 Subject: [PATCH 028/204] WIP: update exact-output tests for the jsx import rule Claude-Session: https://claude.ai/code/session_014AwvTP2WjJKEVdjMR1jQ6p --- .../src/reflex_components_core/base/bare.py | 9 +++++++ .../base/error_boundary.py | 4 +-- .../src/reflex_components_core/core/cond.py | 9 +++++++ .../reflex_components_core/core/foreach.py | 9 +++++++ .../src/reflex_components_core/core/match.py | 9 +++++++ reflex/compiler/compiler.py | 3 ++- tests/units/compiler/test_compiler.py | 25 ++++++++++--------- .../compiler/test_context_js_template.py | 4 --- .../test_dynamic_components_codegen.py | 4 +-- tests/units/components/core/test_banner.py | 4 +++ .../reflex_components_ui/layout/test_box.py | 3 +-- tests/units/reflex_components_ui/test_base.py | 15 ++++------- tests/units/test_app.py | 8 ++---- 13 files changed, 66 insertions(+), 40 deletions(-) diff --git a/packages/reflex-components-core/src/reflex_components_core/base/bare.py b/packages/reflex-components-core/src/reflex_components_core/base/bare.py index 058952c124a..74a22e5f1dc 100644 --- a/packages/reflex-components-core/src/reflex_components_core/base/bare.py +++ b/packages/reflex-components-core/src/reflex_components_core/base/bare.py @@ -180,6 +180,15 @@ def _get_all_refs(self) -> dict[str, None]: refs |= component._get_all_refs() return refs + def _renders_css_prop(self) -> bool: + """Whether the component renders an element with a ``css`` prop. + + Returns: + False: a bare value renders no element of its own, and its children + answer for theirs. + """ + return False + def _render(self) -> CommonTag: contents = ( Var.create(self.contents) diff --git a/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py b/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py index ee99c3bda11..23d234bdd32 100644 --- a/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py +++ b/packages/reflex-components-core/src/reflex_components_core/base/error_boundary.py @@ -149,9 +149,7 @@ def create(cls, *children, **props): a( div( "Built with ", - svg_logo( - None, class_name="rx-error-boundary-logo" - ), + svg_logo(None, class_name="rx-error-boundary-logo"), class_name="rx-error-boundary-credit", ), href="https://reflex.dev", diff --git a/packages/reflex-components-core/src/reflex_components_core/core/cond.py b/packages/reflex-components-core/src/reflex_components_core/core/cond.py index 9b8540e2556..687751e8080 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/cond.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/cond.py @@ -83,6 +83,15 @@ def create( ) ) + def _renders_css_prop(self) -> bool: + """Whether the component renders an element with a ``css`` prop. + + Returns: + False: a condition renders no element of its own, and its children + answer for theirs. + """ + return False + def _render(self) -> CommonTag: true_child, false_child = self._get_cond_children() return CondTag( diff --git a/packages/reflex-components-core/src/reflex_components_core/core/foreach.py b/packages/reflex-components-core/src/reflex_components_core/core/foreach.py index da8f4986955..99a6e833a06 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/foreach.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/foreach.py @@ -140,6 +140,15 @@ def create( ).with_traceback(e.__traceback__) from None return component + def _renders_css_prop(self) -> bool: + """Whether the component renders an element with a ``css`` prop. + + Returns: + False: a loop renders no element of its own, and its children + answer for theirs. + """ + return False + def _render(self) -> IterTag: props = {} diff --git a/packages/reflex-components-core/src/reflex_components_core/core/match.py b/packages/reflex-components-core/src/reflex_components_core/core/match.py index 94005b6e9bc..368ca12ee10 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/match.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/match.py @@ -293,6 +293,15 @@ def _create_match_cond_var_or_component( ), ) + def _renders_css_prop(self) -> bool: + """Whether the component renders an element with a ``css`` prop. + + Returns: + False: a match renders no element of its own, and its children + answer for theirs. + """ + return False + def _render(self) -> CommonTag: # Reconstruct match_cases and default from self.children, which may have # been updated by the compiler walker to include memoized wrappers. diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 0b599ef9ee2..e818c37351c 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -190,7 +190,8 @@ def _split_window_libraries( A deferred library costs a chunk of its whole namespace, so one the compiler registered is only kept when the app renders a dynamic component. A library - the app registered itself is always kept. + the app registered itself is always kept. Emotion is deferred like any + other: a dynamic component loads it when it renders a ``css`` prop. Args: dynamic_components: Whether the app renders a dynamic component. diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 323413db3a0..4f38aaf7a31 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -771,15 +771,13 @@ def test_compile_app_root_includes_radix_window_library_when_bundled(mocker): _APP_ROOT_HEAD = """ -import {jsx} from "@emotion/react" -import {Fragment,useEffect} from "react" +import {Fragment,createElement as jsx,useEffect} from "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"; @@ -825,7 +823,6 @@ def test_compile_app_root_includes_radix_window_library_when_bundled(mocker): // Make contexts and state objects available globally for dynamic eval'd components window.__reflex = { "react": React, - "@emotion/react": emotion_react, "$/utils/context": utils_context, "$/utils/context-registry": utils_context_registry, "$/utils/state": utils_state, @@ -851,7 +848,6 @@ def _app_root_with_loaders(*loaders: str) -> str: if (typeof window !== "undefined") { window.__reflex = { ...window.__reflex, "react": React, - "@emotion/react": emotion_react, "$/utils/context": utils_context, "$/utils/context-registry": utils_context_registry, "$/utils/state": utils_state, @@ -885,8 +881,13 @@ def _app_root_with_loaders(*loaders: str) -> str: ) +_EMOTION_LOADER = '"@emotion/react": () => import("$/utils/dynamic_libraries/emotion_react").then((module) => module.default),' _RADIX_LOADER = '"@radix-ui/themes": () => import("$/utils/dynamic_libraries/radix_ui_themes").then((module) => module.default),' _D3_LOADER = '"d3-format": () => import("$/utils/dynamic_libraries/d3_format").then((module) => module.default),' +_EMOTION_MODULE = ( + "emotion_react.js", + 'import * as library from "@emotion/react";\nexport default library;\n', +) _RADIX_MODULE = ( "radix_ui_themes.js", 'import * as library from "@radix-ui/themes";\nexport default library;\n', @@ -903,8 +904,8 @@ def _app_root_with_loaders(*loaders: str) -> str: pytest.param( (), True, - _app_root_with_loaders(_RADIX_LOADER), - [_RADIX_MODULE], + _app_root_with_loaders(_EMOTION_LOADER, _RADIX_LOADER), + [_EMOTION_MODULE, _RADIX_MODULE], id="dynamic_components", ), pytest.param( @@ -913,8 +914,8 @@ def _app_root_with_loaders(*loaders: str) -> str: pytest.param( ("d3-format@3.1.0",), True, - _app_root_with_loaders(_RADIX_LOADER, _D3_LOADER), - [_RADIX_MODULE, _D3_MODULE], + _app_root_with_loaders(_EMOTION_LOADER, _RADIX_LOADER, _D3_LOADER), + [_EMOTION_MODULE, _RADIX_MODULE, _D3_MODULE], id="dynamic_components_and_app_library", ), pytest.param( @@ -936,7 +937,8 @@ def test_compile_app_root_loads_optional_libraries_on_demand( """Keep optional library namespaces out of root.jsx, in modules of their own. A library the compiler registered is only loadable when the app renders a - dynamic component, a library the app registered is always loadable. + dynamic component, a library the app registered is always loadable. Emotion + is one of the former: only a dynamic component with a ``css`` prop calls it. Args: app_libraries: The libraries the app registers with bundle_library. @@ -1182,8 +1184,7 @@ def test_compile_document_root_prod( == 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" +import {{Fragment,createElement as jsx,useEffect}} from "react" export function Layout({{children}}) {{ return ( diff --git a/tests/units/compiler/test_context_js_template.py b/tests/units/compiler/test_context_js_template.py index 56dddd8536d..fcb050fce2b 100644 --- a/tests/units/compiler/test_context_js_template.py +++ b/tests/units/compiler/test_context_js_template.py @@ -67,7 +67,6 @@ export const registerApp = () => {}; export const eventLoop = {}; """, - "@emotion/react": "export const jsx = () => null;\n", } # Renders ``StateProvider`` around a leaf and resolves its fixed-depth wrapper. @@ -142,7 +141,6 @@ def test_stateful_context_imports_the_backend_connection() -> None: '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";', ] @@ -153,7 +151,6 @@ def test_stateless_context_does_not_import_the_backend_connection() -> 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";', ] assert "utils/socket" not in rendered @@ -305,7 +302,6 @@ def test_client_state_store_notifies_only_substate_subscribers(tmp_path: Path): ("$/utils/state", state_stub), ("$/utils/socket", _SOCKET_STUB), ("$/utils/context-registry", registry_source), - ("@emotion/react", "export const jsx = () => null;\n"), ): stub = tmp_path / ( "registry.mjs" diff --git a/tests/units/compiler/test_dynamic_components_codegen.py b/tests/units/compiler/test_dynamic_components_codegen.py index 618d8e2c1da..a903235fb73 100644 --- a/tests/units/compiler/test_dynamic_components_codegen.py +++ b/tests/units/compiler/test_dynamic_components_codegen.py @@ -468,7 +468,7 @@ def test_dynamic_component_codegen_wires_event_handlers() -> None: assert isinstance(code, str) assert code.startswith("//__reflex_evaluate") - assert "const {Fragment,useEffect}" in code + assert "const {Fragment,createElement: jsx,useEffect}" in code # ``addEvents`` is now a module-level callable in ``$/utils/context``; # no more ``useContext(EventLoopContext)`` hoist needed for dispatch. assert "const {addEvents} = window.__reflex['$/utils/context']" in code @@ -536,7 +536,7 @@ def counter_ui(self) -> rx.Component: assert "RadixThemesText" in code assert 'justify:"center"' in code assert 'gap:"5"' in code - assert "const {Fragment,useEffect}" in code + assert "const {Fragment,createElement: jsx,useEffect}" in code assert "const {addEvents} = window.__reflex['$/utils/context']" in code assert ( "const {ReflexEvent,applyEventActions,pyOr} = window.__reflex['$/utils/state']" diff --git a/tests/units/components/core/test_banner.py b/tests/units/components/core/test_banner.py index d11c1bf8049..0f898491619 100644 --- a/tests/units/components/core/test_banner.py +++ b/tests/units/components/core/test_banner.py @@ -22,8 +22,10 @@ def test_websocket_target_url(): def test_connection_banner(): banner = ConnectionBanner.create() imports = banner._get_all_imports(collapse=True) + # Its elements are styled through ``css`` props, which need Emotion. assert sorted(imports) == sorted(( "react", + "@emotion/react", "$/utils/context", "$/utils/state", "$/env.json", @@ -37,8 +39,10 @@ def test_connection_banner(): def test_connection_modal(): modal = ConnectionModal.create() imports = modal._get_all_imports(collapse=True) + # Its elements are styled through ``css`` props, which need Emotion. assert sorted(imports) == sorted(( "react", + "@emotion/react", "$/utils/context", "$/utils/state", "$/env.json", diff --git a/tests/units/reflex_components_ui/layout/test_box.py b/tests/units/reflex_components_ui/layout/test_box.py index 37d166e69f2..1af36d02150 100644 --- a/tests/units/reflex_components_ui/layout/test_box.py +++ b/tests/units/reflex_components_ui/layout/test_box.py @@ -14,8 +14,7 @@ import reflex as rx BOX_PAGE = """import * as stylex from "@stylexjs/stylex" -import {Fragment,useEffect} from "react" -import {jsx} from "@emotion/react" +import {Fragment,createElement as jsx,useEffect} from "react" diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py index 06dd461f927..8519220ada5 100644 --- a/tests/units/reflex_components_ui/test_base.py +++ b/tests/units/reflex_components_ui/test_base.py @@ -22,8 +22,7 @@ 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" +import {Fragment,createElement as jsx,useEffect} from "react" @@ -46,8 +45,7 @@ # A page whose only element was moved into a module of its own. MEMO_PAGE = """import {Button_button_f1bbe1600e526de2c75f843fcd30a1d1} from "$/utils/components/Button_button_f1bbe1600e526de2c75f843fcd30a1d1" -import {Fragment,useEffect} from "react" -import {jsx} from "@emotion/react" +import {Fragment,createElement as jsx,useEffect} from "react" @@ -72,8 +70,7 @@ 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" +import {Fragment,createElement as jsx,memo,useEffect} from "react" @@ -100,8 +97,7 @@ 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" +import {Fragment,createElement as jsx,memo,useEffect} from "react" @@ -128,8 +124,7 @@ "//__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 {Fragment,createElement: jsx,useEffect} = window.__reflex['react']\n" "const {pyOr} = window.__reflex['$/utils/state']\n" "\n" "export default function MySSRComponent () {\n" diff --git a/tests/units/test_app.py b/tests/units/test_app.py index f2fed9c4e15..382c2dd832c 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -3367,13 +3367,11 @@ def test_event_provider_app_wrap_order(mocker: MockerFixture) -> None: # 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";', @@ -3407,7 +3405,7 @@ def test_stateless_app_imports_no_backend_connection(mocker: MockerFixture) -> N 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 {Fragment,StrictMode,createElement as jsx,useEffect} from "react"', 'import {EventLoopProvider,StateProvider} from "$/utils/context"', ( "import {Errorboundary_errorboundary_} " @@ -3427,7 +3425,6 @@ def test_stateless_app_imports_no_backend_connection(mocker: MockerFixture) -> N "EventLoopContext, StateStoreContext, registerApp, eventLoop } " 'from "$/utils/context-registry"' ), - 'import { jsx } from "@emotion/react";', ] toast_page = rx.el.button("Notify", on_click=rx.toast("Hello")) @@ -3463,7 +3460,7 @@ def increment(self): app = App(theme=None) app_wrap_imports = [ - 'import {Fragment,StrictMode,useEffect} from "react"', + 'import {Fragment,StrictMode,createElement as jsx,useEffect} from "react"', 'import {EventLoopProvider,StateProvider} from "$/utils/context"', ( "import {Errorboundary_errorboundary_} " @@ -3491,7 +3488,6 @@ def increment(self): "EventLoopContext, StateStoreContext, registerApp, eventLoop } " 'from "$/utils/context-registry"' ), - 'import { jsx } from "@emotion/react";', ] app.toaster = rx.toast.provider() From 5a894f9da09917cc45b4de8a8d29b0d1e3432968 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 15:53:34 +0000 Subject: [PATCH 029/204] WIP: safety net for css keys, unit tests for the jsx import rule and the chrome Claude-Session: https://claude.ai/code/session_014AwvTP2WjJKEVdjMR1jQ6p --- .../src/reflex_base/compiler/templates.py | 97 +++++- tests/units/compiler/test_compiler.py | 313 ++++++++++++++++++ tests/units/components/core/test_banner.py | 87 +++++ tests/units/conftest.py | 43 ++- .../reflex_base/compiler/test_templates.py | 66 ++++ .../reflex_base/components/test_dynamic.py | 36 ++ .../base/test_error_boundary.py | 73 ++++ .../core/test_sticky.py | 92 +++++ tests/units/reflex_components_ui/conftest.py | 41 --- 9 files changed, 793 insertions(+), 55 deletions(-) create mode 100644 tests/units/reflex_components_core/base/test_error_boundary.py diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 1f58f518702..89167c63acc 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, Literal from reflex_base import constants +from reflex_base.constants.compiler import Imports from reflex_base.utils import memo_paths from reflex_base.utils.format import json_dumps from reflex_base.vars.base import VarData @@ -68,6 +69,44 @@ def _merge_state_hooks( return {first_hooks.get(hook, hook): data for hook, data in merged.items()} +# A ``css`` key of an object, as a prop is written and as code written by +# hand may spell it. +_CSS_KEY = re.compile(r"""(? list[_ImportDict]: + """Make ``jsx`` Emotion's in the imports of a module where it is React's. + + Args: + imports: The imports of the module. + + Returns: + The imports, unchanged for a module that does not import React's + ``createElement`` as ``jsx``. + """ + if not any( + module["lib"] == "react" and _REACT_JSX in module["rest"] for module in imports + ): + return imports + emotion: _ImportDict = {"lib": "@emotion/react", "default": "", "rest": []} + swapped: list[_ImportDict] = [] + for module in imports: + if module["lib"] == "react": + module = { + **module, + "rest": [name for name in module["rest"] if name != _REACT_JSX], + } + elif module["lib"] == "@emotion/react": + emotion = module + continue + swapped.append(module) + swapped.append({**emotion, "rest": [*emotion["rest"], _EMOTION_JSX]}) + return swapped + + class _RenderUtils: @staticmethod def render(component: Mapping[str, Any] | str) -> str: @@ -139,6 +178,27 @@ def get_import(module: _ImportDict) -> str: return f'import {{{rest_imports_str}}} from "{module["lib"]}"' return f'import "{module["lib"]}"' + @staticmethod + def get_imports(imports: list[_ImportDict], *code: str) -> str: + """Render the imports of a module, settling what it calls ``jsx``. + + Components ask for Emotion's ``jsx`` through their imports when they + render a ``css`` prop. Code that reaches the module without its imports + cannot, so a ``css`` key anywhere in the module asks for it too: Emotion + behaves as React does for an element without the prop, while React + would drop the style of an element with it. + + Args: + imports: The imports of the module. + *code: The rest of the module. + + Returns: + The import statements, one per line. + """ + if any(map(_CSS_KEY.search, code)): + imports = _with_emotion_jsx(imports) + return "\n".join([_RenderUtils.get_import(module) for module in imports]) + def rxconfig_template(app_name: str): """Template for the Reflex config file. @@ -171,12 +231,12 @@ def document_root_template(*, imports: list[_ImportDict], document: dict[str, An Returns: Rendered document root code as string. """ - imports_rendered = "\n".join([_RenderUtils.get_import(mod) for mod in imports]) - return f"""{imports_rendered} + rendered = _RenderUtils.render(document) + return f"""{_RenderUtils.get_imports(imports, rendered)} export function Layout({{children}}) {{ return ( - {_RenderUtils.render(document)} + {rendered} ) }}""" @@ -207,7 +267,6 @@ def app_root_template( Returns: Rendered App root component as string. """ - imports_str = "\n".join([_RenderUtils.get_import(mod) for mod in imports]) dynamic_imports_str = "\n".join(dynamic_imports) hydrate_fallback_str = "" @@ -272,6 +331,12 @@ def app_root_template( }} """ + hooks_str = _render_hooks(hooks) + rendered = _RenderUtils.render(render) + imports_str = _RenderUtils.get_imports( + imports, custom_code_str, hooks_str, rendered + ) + return f""" {imports_str} {dynamic_imports_str} @@ -294,8 +359,8 @@ def app_root_template( function AppWrap({{children}}) {{ -{_render_hooks(hooks)} -return ({_RenderUtils.render(render)}) +{hooks_str} +return ({rendered}) }} export function Layout({{children}}) {{ @@ -715,11 +780,14 @@ def page_template( Returns: Rendered React page component as string. """ - imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports]) custom_code_str = "\n".join(custom_codes) dynamic_imports_str = "\n".join(dynamic_imports) hooks_str = _render_hooks(hooks) + rendered = _RenderUtils.render(render) + imports_str = _RenderUtils.get_imports( + imports, custom_code_str, hooks_str, rendered + ) display_name_str = ( f"Component.displayName = {json.dumps(f'Component({route})')};\n" if route @@ -740,7 +808,7 @@ def page_template( {hooks_str} return ( - {_RenderUtils.render(render)} + {rendered} ) }} {display_name_str} @@ -1197,7 +1265,6 @@ def memo_components_template( Returns: Rendered custom component code as string. """ - imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports]) dynamic_imports_str = "\n".join(dynamic_imports) custom_code_str = "\n".join(custom_codes) @@ -1209,6 +1276,10 @@ def memo_components_template( f"\nexport const {function['name']} = {function['function']};\n" ) + imports_str = _RenderUtils.get_imports( + imports, custom_code_str, functions_code, components_code + ) + return f""" {imports_str} @@ -1238,11 +1309,11 @@ def memo_single_component_template( Returns: The rendered standalone memo module code. """ - imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports]) dynamic_imports_str = "\n".join(dynamic_imports) custom_code_str = "\n".join(custom_codes) component_code = _render_memo_component(component) + imports_str = _RenderUtils.get_imports(imports, custom_code_str, component_code) return f""" {imports_str} @@ -1267,11 +1338,11 @@ def memo_single_function_template( Returns: The rendered standalone function memo module code. """ - imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports]) + function_code = f"export const {function['name']} = {function['function']};" return f""" -{imports_str} +{_RenderUtils.get_imports(imports, function_code)} -export const {function["name"]} = {function["function"]}; +{function_code} """ diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 4f38aaf7a31..37e5bc5871f 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -3010,3 +3010,316 @@ def notify(self): return rx.toast("From a substate") assert _toast_wrap(rx.App()) == "toaster" + + +# What a module with no ``css`` prop calls ``jsx``, and what one with a ``css`` +# prop does: only Emotion applies the prop. +REACT_JSX = 'import {Fragment,createElement as jsx,useEffect} from "react"' +EMOTION_JSX = [ + 'import {jsx} from "@emotion/react"', + 'import {Fragment,useEffect} from "react"', +] +REACT_JSX_MEMO = 'import {Fragment,createElement as jsx,memo,useEffect} from "react"' +EMOTION_JSX_MEMO = [ + 'import {jsx} from "@emotion/react"', + 'import {Fragment,memo,useEffect} from "react"', +] + +_MEMO_NAME_HASH = re.compile(r"_[0-9a-f]{32}|_[0-9a-f]{8}\b") + + +def _module_imports(code: str) -> list[str]: + """Get the import statements of a generated module. + + Args: + code: The source of the module. + + Returns: + Its import statements in order, with the hashes that name memos + replaced by a placeholder. + """ + return [ + _MEMO_NAME_HASH.sub("_", line) + for line in code.splitlines() + if line.startswith("import ") + ] + + +class JsxImportState(BaseState): + """What the pages of the ``jsx`` import tests are bound to.""" + + color: str = "red" + items: list[str] = ["a"] + on: bool = True + + +class ThirdPartyPlain(Component): + """A component of another package, with no style of its own.""" + + library = "third-party" + tag = "Plain" + + fallback: Var[Component] + + +class ThirdPartyThemed(ThirdPartyPlain): + """A component of another package that adds a ``css`` prop as it renders.""" + + tag = "Themed" + + def _render(self, props: dict[str, Any] | None = None): + return super()._render(props).add_props(css=Var(_js_expr="theme")) + + +THIRD_PARTY_PLAIN = 'import {Plain} from "third-party"' + +_RED = {"color": "red"} + + +@pytest.mark.parametrize( + ("page", "style", "expected"), + [ + pytest.param(lambda: rx.el.div("x"), None, [REACT_JSX], id="no_style"), + pytest.param(lambda: rx.el.div("x", style=_RED), None, EMOTION_JSX, id="style"), + pytest.param( + lambda: rx.box("x", color="red"), + None, + ['import {Box as RadixThemesBox} from "@radix-ui/themes"', *EMOTION_JSX], + id="style_keyword", + ), + pytest.param( + lambda: rx.el.div("x"), {rx.el.div: _RED}, EMOTION_JSX, id="app_style" + ), + pytest.param( + lambda: rx.el.div("x"), + {rx.el.span: _RED}, + [REACT_JSX], + id="app_style_of_another_component", + ), + pytest.param( + lambda: ThirdPartyPlain.create(), + None, + [THIRD_PARTY_PLAIN, REACT_JSX], + id="third_party", + ), + pytest.param( + lambda: ThirdPartyThemed.create(), + None, + ['import {Themed} from "third-party"', *EMOTION_JSX], + id="third_party_css_added_in_render", + ), + pytest.param( + lambda: ThirdPartyPlain.create(custom_attrs={"css": _RED}), + None, + [THIRD_PARTY_PLAIN, *EMOTION_JSX], + id="css_as_custom_attribute", + ), + pytest.param( + lambda: ThirdPartyPlain.create(fallback=rx.el.span("a", style=_RED)), + None, + [ + 'import {jsx} from "@emotion/react"', + THIRD_PARTY_PLAIN, + 'import {Fragment,useEffect} from "react"', + 'import {pyOr} from "$/utils/state"', + ], + id="style_in_a_component_prop", + ), + pytest.param( + lambda: ThirdPartyPlain.create(fallback=rx.el.span("a")), + None, + [THIRD_PARTY_PLAIN, REACT_JSX, 'import {pyOr} from "$/utils/state"'], + id="component_prop", + ), + pytest.param( + # A component that reaches the page as code carries no imports. + lambda: ThirdPartyPlain.create( + custom_attrs={"render": Var(f"() => {rx.el.i('a', style=_RED)!s}")} + ), + None, + [ + THIRD_PARTY_PLAIN, + 'import {Fragment,useEffect} from "react"', + 'import {jsx} from "@emotion/react"', + ], + id="style_in_code_without_imports", + ), + ], +) +def test_page_imports_emotion_only_for_a_css_prop( + page, style, expected: list[str], compile_page +): + """A page calls React's ``createElement`` unless something in it has a ``css`` prop.""" + code = compile_page(page, style).compiled_pages["/"].output_code + assert _module_imports(code) == expected + + +@pytest.mark.parametrize( + ("page", "expected_page", "expected_memo"), + [ + pytest.param( + # The branches of a condition stay in the page. + lambda: rx.el.div( + rx.cond(JsxImportState.on, rx.el.span("a", style=_RED), rx.el.span("b")) + ), + [ + *EMOTION_JSX, + 'import {Cond_comp_} from "$/utils/components/Cond_comp_"', + ], + [ + 'import {isTrue} from "$/utils/state"', + 'import {useStateContext} from "$/utils/context-registry"', + REACT_JSX_MEMO, + ], + id="cond_with_style", + ), + pytest.param( + lambda: rx.el.div( + rx.cond(JsxImportState.on, rx.el.span("a"), rx.el.span("b")) + ), + [ + REACT_JSX, + 'import {Cond_comp_} from "$/utils/components/Cond_comp_"', + ], + [ + 'import {isTrue} from "$/utils/state"', + 'import {useStateContext} from "$/utils/context-registry"', + REACT_JSX_MEMO, + ], + id="cond", + ), + pytest.param( + # The body of a loop moves into the module of the loop. + lambda: rx.el.div( + rx.foreach(JsxImportState.items, lambda i: rx.el.span(i, style=_RED)) + ), + [ + 'import {Foreach_comp_} from "$/utils/components/Foreach_comp_"', + REACT_JSX, + ], + [ + 'import {isTrue} from "$/utils/state"', + 'import {useStateContext} from "$/utils/context-registry"', + *EMOTION_JSX_MEMO, + ], + id="foreach_with_style", + ), + pytest.param( + lambda: rx.el.div( + rx.foreach(JsxImportState.items, lambda i: rx.el.span(i)) + ), + [ + 'import {Foreach_comp_} from "$/utils/components/Foreach_comp_"', + REACT_JSX, + ], + [ + 'import {isTrue} from "$/utils/state"', + 'import {useStateContext} from "$/utils/context-registry"', + REACT_JSX_MEMO, + ], + id="foreach", + ), + pytest.param( + # An element bound to state moves into a module of its own, and + # takes Emotion with it: the page it leaves no longer needs it. + lambda: rx.el.div( + rx.el.span("a", style={"color": JsxImportState.color}), rx.el.p("p") + ), + [ + 'import {Span_span_} from "$/utils/components/Span_span_"', + REACT_JSX, + ], + [ + 'import {isTrue,mergeSlotProps} from "$/utils/state"', + 'import {jsx} from "@emotion/react"', + 'import {useStateContext} from "$/utils/context-registry"', + 'import {Fragment,memo,useEffect} from "react"', + ], + id="style_bound_to_state", + ), + ], +) +def test_auto_memo_module_imports_emotion_only_for_a_css_prop( + page, expected_page: list[str], expected_memo: list[str], compile_page +): + """The rule is applied to each generated module on its own.""" + ctx = compile_page(page) + assert _module_imports(ctx.compiled_pages["/"].output_code) == expected_page + ((_, memo_module),) = compiler.compile_memo_components( + tuple(ctx.auto_memo_components.values()) + )[0] + assert _module_imports(memo_module) == expected_memo + + +def test_rx_memo_module_imports_emotion_only_for_a_css_prop( + compile_page, preserve_memo_registries: None +): + """A memo with a ``css`` prop imports Emotion: the page that calls it does not.""" + + @rx.memo + def jsx_styled_memo() -> rx.Component: + return rx.el.div("m", style=_RED) + + @rx.memo + def jsx_plain_memo() -> rx.Component: + return rx.el.div("m") + + def memo_imports(name: str) -> list[str]: + ((_, code),) = compiler.compile_memo_components(( + next(memo for memo in MEMOS.values() if memo.python_name == name), + ))[0] + return _module_imports(code) + + assert memo_imports("jsx_styled_memo") == [ + 'import {isTrue} from "$/utils/state"', + *EMOTION_JSX_MEMO, + ] + assert memo_imports("jsx_plain_memo") == [ + 'import {isTrue} from "$/utils/state"', + REACT_JSX_MEMO, + ] + page = compile_page(lambda: rx.el.div(jsx_styled_memo(), jsx_plain_memo())) + assert _module_imports(page.compiled_pages["/"].output_code) == [ + ( + "import {JsxPlainMemo_,JsxStyledMemo_} " + 'from "$/app_components/tests/units/compiler/test_compiler"' + ), + REACT_JSX, + ] + + +@pytest.mark.parametrize( + ("component", "expected"), + [ + pytest.param( + lambda: rx.el.div("x"), + [ + { + "lib": "react", + "default": "", + "rest": ["Fragment", "createElement as jsx", "useEffect"], + } + ], + id="no_style", + ), + pytest.param( + lambda: rx.el.div("x", style=_RED), + [ + {"lib": "@emotion/react", "default": "", "rest": ["jsx"]}, + {"lib": "react", "default": "", "rest": ["Fragment", "useEffect"]}, + ], + id="style", + ), + ], +) +def test_module_built_from_the_imports_of_a_component_follows_the_rule( + component, expected: list[dict[str, Any]] +): + """A plugin that writes a module of its own gets the right ``jsx`` too. + + It collects the imports of the components it renders and adds the common + ones, as the compiler does for a page. + """ + imports = component()._get_all_imports() + compiler._apply_common_imports(imports) + assert utils.compile_imports(imports) == expected diff --git a/tests/units/components/core/test_banner.py b/tests/units/components/core/test_banner.py index 0f898491619..d45d759bd4e 100644 --- a/tests/units/components/core/test_banner.py +++ b/tests/units/components/core/test_banner.py @@ -5,6 +5,7 @@ ConnectionPulser, ConnectionToaster, WebsocketTargetURL, + WifiOffPulse, ) from reflex_components_radix.themes.typography.text import Text @@ -81,3 +82,89 @@ def test_connection_toaster_does_not_ask_for_the_toaster(): "const toast = refs['__toast'];", ] assert collect_subtree_app_wraps(toaster) == {} + + +PULSER_CSS = ( + "@keyframes rx-connection-pulse{from{opacity:0}to{opacity:1}}" + ".rx-connection-pulser{position:fixed;width:100vw;height:0}" + ".rx-connection-pulse{color:crimson;z-index:9999;position:fixed;bottom:33px;" + "right:33px;animation:rx-connection-pulse 1s infinite}" +) + + +def test_connection_pulser_is_styled_without_a_css_prop(): + """The indicator every app with state renders does not need Emotion.""" + pulser = ConnectionPulser.create() + assert sorted(pulser._get_all_imports(collapse=True)) == [ + "$/utils/context", + "$/utils/state", + "lucide-react@1.26.0", + "react", + ] + assert pulser.render() == { + "name": '"div"', + "props": [ + 'className:"rx-connection-pulser"', + ( + 'title:("Connection Error: "+((connectErrors.length > 0) ? ' + "connectErrors[connectErrors.length - 1].message : ''))" + ), + ], + "children": [ + { + "name": '"style"', + "props": [ + 'href:"rx-connection-pulser"', + 'precedence:"reflex"', + "suppressHydrationWarning:true", + ], + "children": [{"contents": f'"{PULSER_CSS}"'}], + }, + { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": "(connectErrors.length > 0)", + "true_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": "LucideWifiOff", + "props": [ + 'className:"rx-connection-pulse"', + "size:32", + ], + "children": [], + } + ], + }, + "false_value": { + "name": "Fragment", + "props": [], + "children": [], + }, + } + ], + }, + ], + } + + +def test_wifi_off_pulse_style_props_override_its_stylesheet(): + """A style given to the icon is a ``css`` prop over the class it keeps.""" + icon = WifiOffPulse.create(color="red", class_name="mine") + assert sorted(icon._get_all_imports(collapse=True)) == [ + "@emotion/react", + "lucide-react@1.26.0", + ] + assert icon.render() == { + "name": "LucideWifiOff", + "props": [ + 'className:"rx-connection-pulse mine"', + 'css:({ ["color"] : "red" })', + "size:32", + ], + "children": [], + } diff --git a/tests/units/conftest.py b/tests/units/conftest.py index 2e88acca651..f1d9f219cab 100644 --- a/tests/units/conftest.py +++ b/tests/units/conftest.py @@ -8,7 +8,7 @@ import sys import traceback import uuid -from collections.abc import AsyncGenerator, Generator, Mapping +from collections.abc import AsyncGenerator, Callable, Generator, Mapping from pathlib import Path from types import ModuleType from typing import Any @@ -23,14 +23,17 @@ from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter from reflex_base import otel +from reflex_base.components.component import Component, ComponentStyle from reflex_base.components.memo import MEMOS from reflex_base.event import Event, EventSpec from reflex_base.event.context import EventContext from reflex_base.event.processor import BaseStateEventProcessor, EventProcessor +from reflex_base.plugins import CompileContext, CompilerHooks from reflex_base.registry import RegistrationContext from reflex_base.utils import log from reflex.app import App +from reflex.compiler.plugins import default_page_plugins from reflex.istate.manager import StateManager from reflex.istate.manager.disk import StateManagerDisk from reflex.istate.manager.memory import StateManagerMemory @@ -715,3 +718,41 @@ def open_like_windows( return path_open(self, mode, buffering, encoding, errors, newline) monkeypatch.setattr(Path, "open", open_like_windows) + + +@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 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, and the app style it is compiled with, + to its compile context: the source of the page is + ``compiled_pages["/"].output_code``. + """ + + def compile_page( + page: Callable[[], Component], style: ComponentStyle | None = None + ) -> CompileContext: + ctx = CompileContext( + pages=[_Page(route="/", component=page)], + hooks=CompilerHooks(plugins=default_page_plugins(style=style)), + ) + with ctx: + ctx.compile() + return ctx + + return compile_page diff --git a/tests/units/reflex_base/compiler/test_templates.py b/tests/units/reflex_base/compiler/test_templates.py index a0a4a0f3594..4cabc7c7e1a 100644 --- a/tests/units/reflex_base/compiler/test_templates.py +++ b/tests/units/reflex_base/compiler/test_templates.py @@ -1,8 +1,10 @@ """Tests for reflex_base.compiler.templates.""" +import pytest from reflex_base.compiler.templates import ( _merge_state_hooks, _render_hooks, + _RenderUtils, vite_config_template, ) from reflex_base.constants.state import FIELD_MARKER @@ -189,3 +191,67 @@ def test_vite_config_template_two_vite_plugins(): after_imports='import reactCompiler from "./vite-plugin-react-compiler.js";\n', react_compiler=True, ) + + +REACT_IMPORTS: list = [ + {"lib": "react", "default": "", "rest": ["Fragment", "createElement as jsx"]}, +] + + +@pytest.mark.parametrize( + ("imports", "code", "expected"), + [ + pytest.param( + REACT_IMPORTS, + 'jsx("div",{className:"css",style:{"--css":1}},"scss")', + 'import {Fragment,createElement as jsx} from "react"', + id="no_css_key", + ), + pytest.param( + # Text that reads like the key is taken for one: Emotion renders + # the element as React would. + REACT_IMPORTS, + 'jsx("p",{},"css: the language of style")', + 'import {Fragment} from "react"\nimport {jsx} from "@emotion/react"', + id="css_key_in_text", + ), + pytest.param( + REACT_IMPORTS, + 'jsx("div",{css:({ ["color"] : "red" })},)', + 'import {Fragment} from "react"\nimport {jsx} from "@emotion/react"', + id="css_prop", + ), + pytest.param( + REACT_IMPORTS, + 'const props = {"css": style};', + 'import {Fragment} from "react"\nimport {jsx} from "@emotion/react"', + id="quoted_css_key", + ), + pytest.param( + REACT_IMPORTS, + 'const props = {["css"] : style};', + 'import {Fragment} from "react"\nimport {jsx} from "@emotion/react"', + id="computed_css_key", + ), + pytest.param( + [ + *REACT_IMPORTS, + {"lib": "@emotion/react", "default": "", "rest": ["keyframes"]}, + ], + "jsx(Icon,{css:style},)", + 'import {Fragment} from "react"\nimport {jsx,keyframes} from "@emotion/react"', + id="css_prop_beside_another_emotion_import", + ), + pytest.param( + [{"lib": "react", "default": "", "rest": ["memo"]}], + "const style = {css: 1};", + 'import {memo} from "react"', + id="module_without_jsx", + ), + ], +) +def test_css_key_in_a_module_makes_its_jsx_emotion( + imports: list, code: str, expected: str +): + """Code that carries no imports still gets the ``jsx`` that applies ``css``.""" + assert _RenderUtils.get_imports(imports, "", code) == expected diff --git a/tests/units/reflex_base/components/test_dynamic.py b/tests/units/reflex_base/components/test_dynamic.py index 3dca98c4a40..f294bbdc110 100644 --- a/tests/units/reflex_base/components/test_dynamic.py +++ b/tests/units/reflex_base/components/test_dynamic.py @@ -10,7 +10,9 @@ from reflex_base.registry import RegistrationContext, _default_bundled_libraries from reflex_base.utils.exceptions import DynamicComponentMissingLibraryError from reflex_base.utils.imports import ImportVar, ParsedImportDict +from reflex_base.utils.serializers import serialize +import reflex as rx from reflex.components import dynamic as reflex_dynamic @@ -188,3 +190,37 @@ def add_custom_code(self) -> list[str]: seen.clear() Probe.create()._get_all_custom_code() assert seen == [False] + + +def _dynamic_module_head(component: Component) -> list[str]: + """Get what a dynamic component loads before it renders. + + Args: + component: The component to serialize. + + Returns: + The lines of its module up to the component function. + """ + lines = serialize(component).splitlines() + return [ + line + for line in lines[: lines.index("export default function MySSRComponent () {")] + if line + ] + + +def test_dynamic_component_loads_emotion_only_for_a_css_prop(): + """Emotion is one of the libraries a dynamic component loads on demand.""" + assert _dynamic_module_head(rx.el.div("x")) == [ + "//__reflex_evaluate:[]", + "const React = window.__reflex.react;", + "const {Fragment,createElement: jsx,useEffect} = window.__reflex['react']", + "const {pyOr} = window.__reflex['$/utils/state']", + ] + assert _dynamic_module_head(rx.el.div("x", style={"color": "red"})) == [ + '//__reflex_evaluate:["@emotion/react"]', + "const React = window.__reflex.react;", + "const {Fragment,useEffect} = window.__reflex['react']", + "const {jsx} = window.__reflex['@emotion/react']", + "const {pyOr} = window.__reflex['$/utils/state']", + ] diff --git a/tests/units/reflex_components_core/base/test_error_boundary.py b/tests/units/reflex_components_core/base/test_error_boundary.py new file mode 100644 index 00000000000..cd9da556675 --- /dev/null +++ b/tests/units/reflex_components_core/base/test_error_boundary.py @@ -0,0 +1,73 @@ +"""Tests for the error boundary that wraps every app.""" + +from reflex_components_core.base.error_boundary import ErrorBoundary + +import reflex as rx + +# What the boundary renders in place of a page that failed to render. +FALLBACK = ( + '((event_args) => (jsx("div", ({className:"rx-error-boundary"}), (jsx("style", ' + '({href:"rx-error-boundary",precedence:"reflex",suppressHydrationWarning:true}), ' + '".rx-error-boundary{height:100%;width:100%;position:absolute;background-color:#fff;color:#000;display:flex;align-items:center;justify-content:center}.rx-error-boundary-content{display:flex;flex-direction:column;gap:0.5rem;max-width:min(80ch, ' + "90vw);border-radius:0.25rem;padding:1rem}.rx-error-boundary-heading{opacity:0.5;display:flex;gap:4vmin;align-items:center}.rx-error-boundary-title{font-size:5vmin;font-weight:bold}.rx-error-boundary-hint{opacity:0.75;margin-block:1rem}.rx-error-boundary-details{width:100%;background:color-mix(in " + "srgb, currentColor 5%, " + "transparent);max-height:15rem;overflow:auto;border-radius:0.4rem}.rx-error-boundary-details-body{padding:0.5rem}.rx-error-boundary-trace{word-break:break-word;white-space:pre-wrap}.rx-error-boundary-copy{padding:0.35rem " + "1.35rem;margin-block:0.5rem;margin-inline-start:auto;background:color-mix(in " + "srgb, currentColor 15%, " + "transparent);border-radius:0.4rem;width:fit-content}.rx-error-boundary-copy:hover{background:color-mix(in " + "srgb, currentColor 25%, " + "transparent)}.rx-error-boundary-copy:active{background:color-mix(in srgb, " + "currentColor 35%, " + 'transparent)}.rx-error-boundary-rule{border-color:currentColor;opacity:0.25}.rx-error-boundary-credit{display:flex;align-items:baseline;justify-content:center;font-family:monospace;--default-font-family:monospace;gap:0.5rem}.rx-error-boundary-logo{fill:currentColor}")), ' + '(jsx("div", ({className:"rx-error-boundary-content"}), (jsx("div", ' + '({className:"rx-error-boundary-heading"}), (jsx("svg", ({className:"lucide ' + "lucide-frown-icon " + 'lucide-frown",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 ' + '0 24 24",width:"25vmin",xmlns:"http://www.w3.org/2000/svg"}), (jsx("circle", ' + '({cx:"12",cy:"12",r:"10"}))), (jsx("path", ({d:"M16 16s-1.5-2-4-2-4 2-4 2"}))), ' + '(jsx("line", ({x1:"9",x2:"9.01",y1:"9",y2:"9"}))), (jsx("line", ' + '({x1:"15",x2:"15.01",y1:"9",y2:"9"}))))), (jsx("h2", ' + '({className:"rx-error-boundary-title"}), "An error occurred while rendering this ' + 'page.")))), (jsx("p", ({className:"rx-error-boundary-hint"}), "This is an error ' + 'with the application itself. Refreshing the page might help.")), (jsx("div", ' + '({className:"rx-error-boundary-details"}), (jsx("div", ' + '({className:"rx-error-boundary-details-body"}), (jsx("pre", ' + "({className:\"rx-error-boundary-trace\"}), event_args.error.name + ': ' + " + "event_args.error.message + '\\n' + event_args.error.stack)))))), " + '(jsx("button", ({className:"rx-error-boundary-copy",onClick:((_e) => ' + '(addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => ' + '(navigator?.["clipboard"]?.["writeText"](event_args.error.name + \': \' + ' + "event_args.error.message + '\\n' + event_args.error.stack))), [\"callback\"] : " + 'null }), ({ })))], [_e], ({ }))))}), "Copy")), (jsx("hr", ' + '({className:"rx-error-boundary-rule"}))), (jsx(ReactRouterLink, ' + '({to:"https://reflex.dev"}), (jsx("div", ' + '({className:"rx-error-boundary-credit"}), "Built with ", (jsx("svg", ' + '({"aria-label":"Reflex",className:"rx-error-boundary-logo",height:"12",role:"img",width:"56",xmlns:"http://www.w3.org/2000/svg"}), ' + '(jsx("path", ({d:"M0 ' + "11.5999V0.399902H8.96V4.8799H6.72V2.6399H2.24V4.8799H6.72V7.1199H2.24V11.5999H0ZM6.72 " + '11.5999V7.1199H8.96V11.5999H6.72Z"}))), (jsx("path", ({d:"M11.2 ' + '11.5999V0.399902H17.92V2.6399H13.44V4.8799H17.92V7.1199H13.44V9.3599H17.92V11.5999H11.2Z"}))), ' + '(jsx("path", ({d:"M20.16 ' + '11.5999V0.399902H26.88V2.6399H22.4V4.8799H26.88V7.1199H22.4V11.5999H20.16Z"}))), ' + '(jsx("path", ({d:"M29.12 ' + '11.5999V0.399902H31.36V9.3599H35.84V11.5999H29.12Z"}))), (jsx("path", ' + '({d:"M38.08 ' + '11.5999V0.399902H44.8V2.6399H40.32V4.8799H44.8V7.1199H40.32V9.3599H44.8V11.5999H38.08Z"}))), ' + '(jsx("path", ({d:"M47.04 4.8799V0.399902H49.28V4.8799H47.04ZM53.76 ' + "4.8799V0.399902H56V4.8799H53.76ZM49.28 7.1199V4.8799H53.76V7.1199H49.28ZM47.04 " + '11.5999V7.1199H49.28V11.5999H47.04ZM53.76 11.5999V7.1199H56V11.5999H53.76Z"}))), ' + '(jsx("title", ({}), "Reflex")))))))))))))' +) + + +def test_default_fallback_is_styled_without_a_css_prop(): + """The boundary wraps every app: its fallback does not need Emotion.""" + boundary = ErrorBoundary.create(rx.el.div("page")) + assert sorted(boundary._get_all_imports(collapse=True)) == [ + "$/utils/context", + "$/utils/state", + "react", + "react-error-boundary@6.1.6", + "react-router", + ] + assert str(boundary.fallback_render) == FALLBACK diff --git a/tests/units/reflex_components_core/core/test_sticky.py b/tests/units/reflex_components_core/core/test_sticky.py index 8bca734feb5..180cade282b 100644 --- a/tests/units/reflex_components_core/core/test_sticky.py +++ b/tests/units/reflex_components_core/core/test_sticky.py @@ -42,3 +42,95 @@ def test_badge_href_empty_referrer(monkeypatch: pytest.MonkeyPatch): def test_badge_has_accessible_name_when_visual_label_is_hidden(): """Mobile readers can identify the logo-only link.""" assert '"aria-label":"Built with Reflex"' in StickyBadge.create().render()["props"] + + +BADGE_CSS = ( + ".rx-sticky-badge{position:fixed;bottom:1rem;right:1rem;display:flex;flex-direction:row;gap:0.375rem;align-items:center;width:auto;border-radius:0.5rem;color:#E5E7EB;border:1px " + "solid " + "#27282B;background-color:#151618;padding:0.375rem;transition:background-color " + "0.2s ease-in-out;box-shadow:0 1px 2px 0 rgba(0, 0, 0, " + "0.05);z-index:9998;cursor:pointer;text-align:center}.dark " + ".rx-sticky-badge{color:#27282B;border:1px solid " + "#E5E7EB;background-color:#FCFCFD}.rx-sticky-logo{fill:white}.rx-sticky-logo-square{fill:#6E56CF}.rx-sticky-logo-letter{fill:white}@media " + "screen and (min-width: 0){.rx-sticky-desktop-only{display:none}}@media " + "screen and (min-width: " + "62em){.rx-sticky-desktop-only{display:block}}.rx-sticky-label{color:var(--slate-1);font-weight:600;font-family:'Instrument " + "Sans', sans-serif;--default-font-family:'Instrument Sans', " + "sans-serif;font-size:0.875rem;line-height:1rem;letter-spacing:-0.00656rem}" +) + + +def test_badge_is_styled_without_a_css_prop(monkeypatch: pytest.MonkeyPatch): + """The badge is plain elements and a stylesheet: it does not need Emotion.""" + monkeypatch.delenv("REFLEX_REFERRER_PARAM", raising=False) + badge = StickyBadge.create() + assert badge._get_all_imports(collapse=True) == {} + assert badge.render() == { + "name": '"a"', + "props": [ + '"aria-label":"Built with Reflex"', + 'className:"rx-sticky-badge"', + 'href:"https://reflex.dev"', + 'target:"_blank"', + ], + "children": [ + { + "name": '"style"', + "props": [ + 'href:"rx-sticky-badge"', + 'precedence:"reflex"', + "suppressHydrationWarning:true", + ], + "children": [{"contents": f'"{BADGE_CSS}"'}], + }, + { + "name": '"svg"', + "props": [ + 'className:"rx-sticky-logo"', + 'height:"16"', + 'viewBox:"0 0 16 16"', + 'width:"16"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"rect"', + "props": [ + 'className:"rx-sticky-logo-square"', + 'height:"16"', + 'rx:"2"', + 'width:"16"', + ], + "children": [], + }, + { + "name": '"path"', + "props": [ + 'className:"rx-sticky-logo-letter"', + 'd:"M10 9V13H12V9H10Z"', + ], + "children": [], + }, + { + "name": '"path"', + "props": [ + 'className:"rx-sticky-logo-letter"', + 'd:"M4 3V13H6V9H10V7H6V5H10V7H12V3H4Z"', + ], + "children": [], + }, + ], + }, + { + "name": '"div"', + "props": ['className:"rx-sticky-desktop-only"'], + "children": [ + { + "name": '"span"', + "props": ['className:"rx-sticky-label"'], + "children": [{"contents": '"Built with Reflex"'}], + } + ], + }, + ], + } diff --git a/tests/units/reflex_components_ui/conftest.py b/tests/units/reflex_components_ui/conftest.py index f0b2965a839..0f35828eaa8 100644 --- a/tests/units/reflex_components_ui/conftest.py +++ b/tests/units/reflex_components_ui/conftest.py @@ -1,37 +1,20 @@ """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 -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 - # 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: - 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. @@ -47,30 +30,6 @@ def ui_plugin(monkeypatch: pytest.MonkeyPatch) -> UIPlugin: 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 - - @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. From 340238aa47c5d1fbd6a73c239dcf481c4ddb0d3a Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 15:54:40 +0000 Subject: [PATCH 030/204] Give rx.ui components element props, Radix breakpoints for props, responsive variants, as_ and as_child; add flex and text Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- .../parity/allowlist.toml | 23 -- .../parity/ui_parity/components/flex.py | 93 ++++++ .../parity/ui_parity/components/text.py | 113 +++++++ packages/reflex-components-ui/pyproject.toml | 14 +- .../src/reflex_components_ui/__init__.py | 2 + .../src/reflex_components_ui/base.py | 279 ++++++++++++++++-- .../components/__init__.py | 1 + .../src/reflex_components_ui/layout/box.py | 6 +- .../src/reflex_components_ui/layout/flex.py | 53 ++++ .../src/reflex_components_ui/props.py | 10 + .../reflex_components_ui/style/__init__.py | 2 + .../src/reflex_components_ui/style/lower.py | 93 +++++- .../src/reflex_components_ui/style/merge.py | 121 +++++++- .../src/reflex_components_ui/styles/flex.py | 11 + .../src/reflex_components_ui/styles/text.py | 64 ++++ .../reflex_components_ui/styles/typography.py | 74 +++++ .../typography/__init__.py | 1 + .../reflex_components_ui/typography/base.py | 10 + .../reflex_components_ui/typography/text.py | 87 ++++++ .../reflex_components_ui/style/test_emit.py | 18 +- .../reflex_components_ui/style/test_lower.py | 21 +- .../reflex_components_ui/test_api_parity.py | 10 +- uv.lock | 8 +- 23 files changed, 1024 insertions(+), 90 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/flex.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/text.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/__init__.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/flex.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/props.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/flex.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/text.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/typography/__init__.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/typography/base.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/typography/text.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 52973e69389..f027fe91b86 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -23,26 +23,3 @@ # 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/ui_parity/components/flex.py b/packages/reflex-components-ui/parity/ui_parity/components/flex.py new file mode 100644 index 00000000000..79aba4062bf --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/flex.py @@ -0,0 +1,93 @@ +"""The flex container: direction, alignment, wrapping and gaps.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + + +def _flex(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a flex container whose children do not fit on one line. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The container. + """ + return namespace.flex( + *( + rx.el.div( + word, + style={"border": "1px solid currentColor", "padding": "2px 6px"}, + ) + for word in ("The", "quick", "brown", "fox", "jumps", "over", "lazy") + ), + **props, + ) + + +MATRIX = Matrix( + component="flex", + render=_flex, + cross={ + "direction": ["row", "column", "row-reverse", "column-reverse"], + "wrap": ["nowrap", "wrap", "wrap-reverse"], + }, + sweep={ + "align": ["start", "center", "end", "baseline", "stretch"], + "justify": ["start", "center", "end", "between"], + "spacing": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], + "style": {"sized": {"height": "80px", "padding": "4px"}}, + "appearance": [DARK], + }, + groups=[ + {"wrap": ["wrap"], "spacing": ["2", "5"], "justify": ["between", "end"]}, + {"style": {"sized": {"height": "80px"}}, "align": ["center", "end"]}, + { + "direction": { + "responsive": rx.breakpoints(initial="column", sm="row", lg="column") + }, + "spacing": {"responsive": rx.breakpoints(initial="1", xs="4", md="2")}, + "viewport": [400, 600, 800, 1100, 1280], + }, + ], + stage=(240, 160), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="flex", + render=lambda namespace: namespace.flex( + namespace.box("one"), namespace.box("two"), id="flex", spacing="2" + ), +) + + +@CONTRACT.step("is a div in the server render", on=SERVER) +def _server_render(run: Run) -> None: + flex = run.server.element("flex") + assert (flex.tag, flex.text) == ("div", "onetwo") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + flex = run.page.locator("#flex") + assert flex.is_visible() + assert flex.evaluate("element => getComputedStyle(element).display") == "flex" + + +@CONTRACT.step("lays its children out in a row after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + boxes = run.page.locator("#flex > div") + first, second = boxes.nth(0).bounding_box(), boxes.nth(1).bounding_box() + assert first is not None + assert second is not None + assert first["y"] == second["y"] + assert second["x"] > first["x"] diff --git a/packages/reflex-components-ui/parity/ui_parity/components/text.py b/packages/reflex-components-ui/parity/ui_parity/components/text.py new file mode 100644 index 00000000000..0916d745c79 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/text.py @@ -0,0 +1,113 @@ +"""Text: sizes, weights, alignment, trim, color and the element it renders.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + +PARAGRAPH = ( + "The quick brown fox jumps over the lazy dog, then naps in the warm " + "afternoon sun." +) + + +def _text(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a paragraph that wraps over several lines. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell, ``nested`` naming what is inside. + + Returns: + The text. + """ + props = dict(props) + nested = props.pop("nested", None) + if nested == "text": + return namespace.text( + "The quick ", + namespace.text("brown fox", as_="span", weight="bold"), + " jumps over the lazy dog.", + **props, + ) + if nested == "high-contrast": + return namespace.text( + "The quick ", + namespace.text("brown fox", as_="span", high_contrast=True), + " jumps over the lazy dog.", + **props, + ) + return namespace.text(PARAGRAPH, **props) + + +MATRIX = Matrix( + component="text", + render=_text, + cross={ + "size": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + "weight": ["light", "regular", "medium", "bold"], + }, + sweep={ + "align": ["left", "center", "right"], + "trim": ["normal", "start", "end", "both"], + "as_": ["p", "label", "div", "span", "b", "i", "u", "abbr", "cite", "del", + "em", "ins", "kbd", "mark", "s", "samp", "sub", "sup"], + "color_scheme": ["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"], + "high_contrast": [True], + "nested": ["text", "high-contrast"], + "size": { + "responsive": rx.breakpoints(initial="1", sm="5", lg="3"), + }, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"color_scheme": ["ruby", "gray"], "high_contrast": [True], + "appearance": ["light", DARK]}, + {"color_scheme": ["ruby"], "nested": ["text", "high-contrast"]}, + {"trim": ["both", "start"], "size": ["2", "6"]}, + {"size": {"responsive": rx.breakpoints(initial="1", sm="5", lg="3")}, + "trim": {"responsive": rx.breakpoints(initial="both", md="normal")}, + "viewport": [520, 800, 1100, 1280]}, + ], + stage=(260, 200), +) + +CONTRACT = Contract( + component="text", + render=lambda namespace: namespace.box( + namespace.text("paragraph", id="text"), + namespace.text( + "label", as_="label", id="label", custom_attrs={"htmlFor": "field"} + ), + rx.el.input(id="field"), + ), +) + + +@CONTRACT.step("is a paragraph in the server render", on=SERVER) +def _server_render(run: Run) -> None: + text = run.server.element("text") + assert (text.tag, text.text) == ("p", "paragraph") + assert run.server.element("label").tag == "label" + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + text = run.page.locator("#text") + assert text.is_visible() + assert text.inner_text() == "paragraph" + + +@CONTRACT.step("as a label, a click moves the focus to its field", on=HYDRATED) +def _label(run: Run) -> None: + run.page.locator("#label").click() + assert run.page.evaluate("document.activeElement.id") == "field" diff --git a/packages/reflex-components-ui/pyproject.toml b/packages/reflex-components-ui/pyproject.toml index 716454490bf..8bbd0c38648 100644 --- a/packages/reflex-components-ui/pyproject.toml +++ b/packages/reflex-components-ui/pyproject.toml @@ -15,7 +15,11 @@ classifiers = [ "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", ] -dependencies = ["reflex-base >= 0.11.1.dev0"] +dependencies = [ + "reflex-base >= 0.11.1.dev0", + "reflex-components-core >= 0.11.1.dev0", + "reflex-components-lucide >= 1.1.0", +] [tool.hatch.version] source = "uv-dynamic-versioning" @@ -35,7 +39,13 @@ artifacts = ["/src/**/*.pyi"] include = ["/src", "/js/src", "/hatch_build.py"] [tool.hatch.build.hooks.reflex-pyi] -dependencies = ["ruff", "reflex-base"] +dependencies = [ + "ruff", + "reflex-base", + "reflex-components-core", + "reflex-components-lucide", + "reflex-components-sonner", +] # Embeds js/src, the javascript the components are compiled against, which the # plugin copies into a project's web directory. 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 667ad352074..cb2baae12af 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -8,6 +8,8 @@ _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { "layout.box": ["box"], + "layout.flex": ["flex"], + "typography.text": ["text"], "layout.theme": ["theme"], "themes": ["Theme"], } 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 07382cf9149..5cb26d04406 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -5,8 +5,10 @@ import dataclasses import functools import json +import types +import typing from collections.abc import Iterator, Mapping, Sequence -from typing import Any, ClassVar +from typing import Any, ClassVar, Literal from reflex_base import breakpoints from reflex_base.components.component import BaseComponent, Component @@ -18,7 +20,7 @@ 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.base import LiteralVar, Var, VarData from reflex_base.vars.sequence import LiteralStringVar from reflex_components_ui.plugin import UIPlugin @@ -30,7 +32,8 @@ merge, ) from reflex_components_ui.style.emit import Emitted, emit, inline -from reflex_components_ui.style.lower import suggest +from reflex_components_ui.style.lower import EMPTY, suggest +from reflex_components_ui.style.merge import over from reflex_components_ui.themes import color_scheme_styles MISSING_PLUGIN_ERROR = ( @@ -59,6 +62,75 @@ def _consulted(styles: Mapping[str, Any]) -> dict[str, None]: return props +def _choices(annotation: Any) -> tuple[str, ...] | None: + """Find the values a prop takes when its type is a literal of strings. + + Args: + annotation: The type of the prop, such as ``Var[Responsive[Literal[...]]]``. + + Returns: + The values, or None when the prop takes anything else too. + """ + origin = typing.get_origin(annotation) + args = typing.get_args(annotation) + if origin is Literal: + return args if all(arg.__class__ is str for arg in args) else None + if origin is Var: + return _choices(args[0]) + if origin in (typing.Union, types.UnionType): + # A value per breakpoint is a dict of the same values. + found = None + for arg in args: + if typing.get_origin(arg) is breakpoints.Breakpoints: + continue + choices = _choices(arg) + if choices is None: + return None + found = choices if found is None else (*found, *choices) + return found + return None + + +def _literal(value: Any) -> Any: + """Read a prop that has to be known while compiling. + + Args: + value: The value of the prop. + + Returns: + The value a literal Var holds, or the value as given. + """ + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + return value._var_value + return value + + +def _join_class_names(first: Any, second: Any) -> Any: + """Join the class names of two elements that render as one. + + Args: + first: The class names of one, or None. + second: The class names of the other, or None. + + Returns: + Both, separated by a space. + """ + if first is None: + return second + if second is None: + return first + first, second = LiteralVar.create(first), LiteralVar.create(second) + if isinstance(first, LiteralStringVar) and isinstance(second, LiteralStringVar): + return LiteralVar.create(f"{first._var_value} {second._var_value}".strip()) + return Var( + f'({first!s}) + " " + ({second!s})', + _var_type=str, + _var_data=VarData.merge( + first._get_all_var_data(), second._get_all_var_data() + ), + ) + + def _responsive(style: breakpoints.Breakpoints) -> dict[str, Any]: """Read a whole style given per breakpoint as blocks under media queries. @@ -116,6 +188,12 @@ class UIComponent(Component): 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. + + A subclass that renders one HTML element lists the element class of + ``reflex_components_core.el`` after this one, which gives it the + attributes of its tag as props. Two fields change the element itself: + ``as_`` names the tag, and ``as_child`` renders the only child in place of + the element, with the styles and attributes of both. """ tag = "div" @@ -125,6 +203,10 @@ class UIComponent(Component): # The component's own look. styles: ClassVar[ComponentStyles] = {} + # The tags the `as_` prop renders. Any other value renders the tag of the + # component, as Radix Themes falls back to its default. + _as_tags: ClassVar[frozenset[str]] = frozenset() + # How the stubs type the style: the properties and keywords of CSS. _pyi_overwrite_types: ClassVar[dict[str, str]] = { "style": ( @@ -155,11 +237,52 @@ def _style_props(cls) -> tuple[tuple[str, ...], tuple[str, ...]]: The fields that are layout props, and the props the style table selects variants by. """ + variants = _consulted(cls.styles) + # A prop the style table reads is a variant whatever its name: the + # `align` of text is not the `align` of a flex container. + layout_props = LAYOUT_PROPS.intersection(cls.get_fields()).difference(variants) + return tuple(sorted(layout_props)), tuple(variants) + + @classmethod + @functools.cache + def _literal_props(cls) -> dict[str, tuple[str, ...]]: + """Get the props read as styles, or as the tag, that take listed values. + + Returns: + The values of each such prop. The accent color is not one: its + error is the one of a theme. + """ + layout_props, variants = cls._style_props() fields = cls.get_fields() - return ( - tuple(sorted(LAYOUT_PROPS.intersection(fields))), - tuple(_consulted(cls.styles)), - ) + literals = {} + for prop in (*layout_props, *variants, "as_"): + if prop in fields and prop != "color_scheme": + choices = _choices(fields[prop].annotated_type) + if choices is not None: + literals[prop] = choices + return literals + + def _check_literals(self, kwargs: Mapping[str, Any]) -> None: + """Fail on a value a prop does not take, naming the ones it does. + + Args: + kwargs: The keyword arguments the component is created with. + + Raises: + StyleError: If a prop is given a string it does not take. + """ + literals = self._literal_props() + for prop in literals.keys() & kwargs.keys(): + value = _literal(kwargs[prop]) + choices = literals[prop] + for item in value.values() if isinstance(value, Mapping) else (value,): + if item.__class__ is str and item not in choices: + values = ", ".join([f'"{choice}"' for choice in choices]) + msg = ( + f'{self._display_name()}: unknown {prop} "{item}".' + f"{suggest(item, choices)} The values are {values}." + ) + raise StyleError(msg) def _post_init(self, *args, **kwargs): """Initialize the component, taking its styles out of its props. @@ -170,12 +293,15 @@ def _post_init(self, *args, **kwargs): Raises: StyleError: If the style is not a dict of styles, a list of them or - a Var, or cannot be compiled. + a Var, or cannot be compiled, if a prop is given a value it + does not take, or if ``as_child`` has no single element to + render. ThemeError: If the ``color_scheme`` is not an accent color. """ fields = self.get_fields() triggers = self.get_event_triggers() layout_props, _ = self._style_props() + self._check_literals(kwargs) written: list[Mapping[str, Any]] = [] inline = None style = kwargs.pop("style", None) @@ -219,9 +345,67 @@ def _post_init(self, *args, **kwargs): if color_scheme is None else color_scheme_styles(self._display_name(), color_scheme) ) + self._under: Merged | None = None super()._post_init(*args, **kwargs) + self._as: Var | None = None + if "as_" in fields: + self._set_tag() + self._slot: Component | None = None + if "as_child" in fields: + self._set_slot() self._merge_styles() + def _set_tag(self) -> None: + """Render the element the ``as_`` prop names.""" + as_ = _literal(getattr(self, "as_", None)) + if isinstance(as_, Var): + # The tag is then an expression, evaluated in the browser. + self._as = as_ + elif as_ in self._as_tags: + self.tag = as_ + + def _set_slot(self) -> None: + """Find the child an element with ``as_child`` is rendered as. + + Raises: + StyleError: If ``as_child`` is bound to state, or the component + does not have exactly one child that renders an element. + """ + as_child = _literal(getattr(self, "as_child", None)) + if not as_child: + return + name = self._display_name() + if isinstance(as_child, Var): + msg = ( + f"{name}: as_child is bound to state, but the element is " + "chosen at compile time. Give it True or False, and choose " + "between two components with rx.cond." + ) + raise StyleError(msg) + children = self.children + if ( + len(children) != 1 + or not isinstance(children[0], Component) + or type(children[0]).render is not Component.render + ): + msg = ( + f"{name}: as_child renders the only child in place of the " + f"element, so it needs exactly one child that is an element, " + f"not {_describe(children)}." + ) + raise StyleError(msg) + self._slot = children[0] + + def _get_tag_name(self) -> str: + """Get the JS expression of the element's tag. + + Returns: + The tag, or the expression an ``as_`` bound to state holds. + """ + if self._as is not None: + return str(self._as) + return super()._get_tag_name() + def _merge_styles(self) -> None: """Merge the style table with the styles of this element. @@ -234,18 +418,24 @@ def _merge_styles(self) -> None: styles = self._styles if self.style: styles = [self.style, *styles] + props = None + if variants: + props = {prop: getattr(self, prop, None) for prop in variants} + if self._accent is not None and "color_scheme" in props: + # A style table reads whether the element has an accent of + # its own, not which one: the tokens resolve against it. + props["color_scheme"] = "true" 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, + name, cls.styles, props, styles or None, self._layout ) self._emitted_styles = None if merged.parts: _bind_parts(self.children, merged.parts, name) + slot = self._slot + if isinstance(slot, UIComponent): + # The child renders the styles of both, its own over these. + slot._under = merged + slot._emitted_styles = None def _add_style_recursive(self, style: Any, theme: Component | None = None): """Add the styles of the app to the component and its children. @@ -277,9 +467,14 @@ def _element_styles(self) -> Merged: """Get the merged styles of the element. Returns: - The style table merged with the styles of this element. + The style table merged with the styles of this element, over the + styles of a parent that renders as this element. Nothing for an + element that an rx.ui child of its own renders in its place. """ - return self._merged + if isinstance(self._slot, UIComponent): + return _NO_STYLES + under = self._under + return self._merged if under is None else over(under, self._merged) def _get_vars( self, include_children: bool = False, ignore_ids: set[int] | None = None @@ -359,7 +554,7 @@ def _exclude_props(self) -> list[str]: an element. """ layout_props, variants = self._style_props() - return [*layout_props, *variants, "color_scheme"] + return [*layout_props, *variants, "color_scheme", "as", "as_child"] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the element with its style. @@ -375,6 +570,22 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: ConfigError: If the plugin that compiles the styles is not configured. """ tag = super()._render(props) + slot = self._slot + if slot is not None: + # The child is the element: its props win, its class names and + # the ones of this component stand together. + child = slot._render() + own_props, child_props = tag.props, child.props + tag = child.set( + props={ + **own_props, + **child_props, + "className": _join_class_names( + own_props.get("className"), child_props.get("className") + ), + }, + special_props=[*tag.special_props, *child.special_props], + ) accent = self._accent if is_rendering_dynamic_component(): if accent is not None: @@ -399,6 +610,38 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: return add_styles(tag, emitted) + def render(self) -> dict: + """Render the component, or the child that stands in its place. + + Returns: + The dictionary for template of the component. + """ + slot = self._slot + if slot is None: + return super().render() + rendered = self._render().render([child.render() for child in slot.children]) + slot._replace_prop_names(rendered) + return rendered + + +def _describe(children: Sequence[BaseComponent]) -> str: + """Say what the children of a component are, for an error message. + + Args: + children: The children. + + Returns: + Their number, or the kind of the only one. + """ + if len(children) == 1: + return f"a {type(children[0]).__name__}" + return "none" if not children else f"{len(children)} children" + + +# What an element that renders nothing of its own declares. +_NO_STYLES = Merged(EMPTY) + + class Part(UIComponent): """An inner element of a component, styled by a part of its style table. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/components/__init__.py new file mode 100644 index 00000000000..78a49a649b2 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/__init__.py @@ -0,0 +1 @@ +"""The rx.ui components that are neither layout nor typography.""" 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 b5367828e41..a196ea729a9 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,13 +4,15 @@ from typing import ClassVar +from reflex_components_core.el import elements + from reflex_components_ui.base import UIComponent from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.box import BOX -class Box(UIComponent): - """A block element with no look of its own.""" +class Box(UIComponent, elements.Div): + """A fundamental layout building block, based on `div` element.""" tag = "div" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/flex.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/flex.py new file mode 100644 index 00000000000..f2992a12edc --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/flex.py @@ -0,0 +1,53 @@ +"""A flex container.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.props import LiteralAlign, LiteralJustify, LiteralSpacing +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.flex import FLEX + +LiteralFlexDirection = Literal["row", "column", "row-reverse", "column-reverse"] +LiteralFlexWrap = Literal["nowrap", "wrap", "wrap-reverse"] + + +class Flex(UIComponent, elements.Div): + """Component for creating flex layouts.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = FLEX + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + direction: Var[Responsive[LiteralFlexDirection]] = field( + doc='How child items are laid out: "row" | "column" | "row-reverse" | "column-reverse"' + ) + + align: Var[Responsive[LiteralAlign]] = field( + doc='Alignment of children along the main axis: "start" | "center" | "end" | "baseline" | "stretch"' + ) + + justify: Var[Responsive[LiteralJustify]] = field( + doc='Alignment of children along the cross axis: "start" | "center" | "end" | "between"' + ) + + wrap: Var[Responsive[LiteralFlexWrap]] = field( + doc='Whether children should wrap when they reach the end of their container: "nowrap" | "wrap" | "wrap-reverse"' + ) + + spacing: Var[Responsive[LiteralSpacing]] = field( + doc='Gap between children: "0" - "9"' + ) + + +flex = Flex.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/props.py b/packages/reflex-components-ui/src/reflex_components_ui/props.py new file mode 100644 index 00000000000..5bbad7fcd26 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/props.py @@ -0,0 +1,10 @@ +"""The values of the props many rx.ui components share.""" + +from __future__ import annotations + +from typing import Literal + +LiteralAlign = Literal["start", "center", "end", "baseline", "stretch"] +LiteralJustify = Literal["start", "center", "end", "between"] +LiteralSpacing = Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] +LiteralVariant = Literal["classic", "solid", "soft", "surface", "outline", "ghost"] 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 index ebd7f21f19c..211cb64b9b0 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py @@ -16,6 +16,7 @@ CompoundStyle, Merged, merge, + over, ) __all__ = [ @@ -30,4 +31,5 @@ "StyleProps", "lower", "merge", + "over", ] 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 41ffb54bbbe..cdb367f1e48 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 @@ -907,6 +907,18 @@ def _space(value: Any) -> Any: return value +def _as_written(value: Any) -> Any: + """Read a value of a layout prop that takes the keywords of CSS. + + Args: + value: The value. + + Returns: + The value as given. + """ + return value + + def _tracks(value: Any) -> Any: """Read a number of grid tracks. @@ -935,9 +947,48 @@ def _keywords(names: dict[str, str]) -> Callable[[Any], Any]: _ALIGN = {"start": "flex-start", "end": "flex-end"} +# The breakpoints of a prop, which are those of Radix Themes whatever the +# breakpoints of the app: a responsive prop of an rx component is resolved by +# the Radix stylesheet. A responsive value in a style follows the app instead. +PROP_BREAKPOINTS: dict[str, str] = { + "xs": "@media (min-width: 520px)", + "sm": "@media (min-width: 768px)", + "md": "@media (min-width: 1024px)", + "lg": "@media (min-width: 1280px)", + "xl": "@media (min-width: 1640px)", +} +_PROP_MEDIA = ("default", *PROP_BREAKPOINTS.values()) + + +def prop_breakpoint(name: str, prop: str, breakpoint: Any) -> str: + """Read a key of a responsive prop as the condition its value applies under. + + Args: + name: The display name of the component, for error messages. + prop: The prop. + breakpoint: The key: ``initial`` or the name of a breakpoint. + + Returns: + ``default``, or the media query of the breakpoint. + + Raises: + StyleError: If the key is not a breakpoint of Radix Themes. + """ + if breakpoint == "initial": + return "default" + try: + return PROP_BREAKPOINTS[breakpoint] + except (KeyError, TypeError): + msg = ( + f'{name}: prop "{prop}" is given a value under "{breakpoint}", ' + 'which is not a breakpoint. Use "initial", "xs", "sm", "md", "lg" ' + 'or "xl", or set a style, which takes any media query.' + ) + raise StyleError(msg) from None + # 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]] = { +# how its values are read. +_LAYOUT: dict[str, tuple[str, tuple[str, ...], Callable[[Any], Any]]] = { "p": ("padding", _sides("padding"), _space), "px": ("padding_x", ("paddingLeft", "paddingRight"), _space), "py": ("padding_y", ("paddingTop", "paddingBottom"), _space), @@ -956,10 +1007,12 @@ def _keywords(names: dict[str, str]) -> Callable[[Any], Any]: "spacing": ("gap", ("rowGap", "columnGap"), _space), "gap_x": ("column_gap", ("columnGap",), _space), "gap_y": ("row_gap", ("rowGap",), _space), + "spacing_x": ("column_gap", ("columnGap",), _space), + "spacing_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), + "direction": ("flex_direction", ("flexDirection",), _as_written), + "wrap": ("flex_wrap", ("flexWrap",), _as_written), "align": ("align_items", ("alignItems",), _keywords(_ALIGN)), "justify": ( "justify_content", @@ -983,34 +1036,47 @@ def _read_layout(name: str, prop: str, value: Any, read: Callable[[Any], Any]) - 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. + value: Its value: one, a list of them or a dict of them by breakpoint. read: How one value is read. Returns: - The same shape, holding CSS values. + A CSS value, or a dict of them by the media query of each breakpoint. Raises: - StyleError: If a value is bound to state. + StyleError: If a value that has to be read is bound to state, or a + value is given under a key that is not a breakpoint. """ 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 { + prop_breakpoint(name, prop, 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 len(value) > len(_PROP_MEDIA): + msg = ( + f'{name}: layout prop "{prop}" has {len(value)} responsive ' + f"values, but there are only {len(_PROP_MEDIA)} breakpoints." + ) + raise StyleError(msg) + return { + media: _read_layout(name, prop, item, read) + for media, item in zip(_PROP_MEDIA, value, strict=False) + if item is not None + } 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) + if read is _as_written: + return value 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 + return read(value) def lower_layer( @@ -1046,8 +1112,7 @@ def lower_layer( f"{suggest(prop, sorted(_LAYOUT))}" ) raise StyleError(msg) from None - if read is not None: - value = _read_layout(name, prop, value, read) + value = _read_layout(name, prop, value, read) _value(name, key, (key, targets, None, None), value, (), out, replaced) if style: _block(name, style, (), out, replaced) 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 c004635f6fa..63d67f2a565 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 @@ -17,6 +17,7 @@ from reflex_base.vars.base import LiteralVar, Var from reflex_components_ui.style.lower import ( + PROP_BREAKPOINTS, Layer, Lowered, LoweredValue, @@ -25,6 +26,7 @@ finish, freeze, lower_layer, + prop_breakpoint, ) if TYPE_CHECKING: @@ -355,7 +357,8 @@ def _variant_key(value: Any) -> Any: 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. + The key, the Var itself for a prop that is bound to state, or the + mapping of a prop that is given a value per breakpoint. """ if value is True: return "true" @@ -366,9 +369,76 @@ def _variant_key(value: Any) -> Any: literal = value._var_value return literal if literal.__class__ is str else _variant_key(literal) return value + if isinstance(value, Mapping): + return value return str(value) +def _responsive_layer( + name: str, + table: _Table, + keys: tuple[str | None, ...], + responsive: dict[int, Mapping[str, Any]], +) -> Layer: + """Lower the values a prop is given at the breakpoints after the first. + + The breakpoints are those of Radix Themes and apply mobile first: a value + holds from its breakpoint up, until another one replaces it. At each + breakpoint the styles of the table are resolved for the values the props + then have, compound styles included, and what changes from the breakpoint + before goes under its media query. + + Args: + name: The display name of the component, for error messages. + table: The lowered style table. + keys: The value of each consulted prop before the first breakpoint. + responsive: The value per breakpoint of each responsive prop, by its + position in ``keys``. + + Returns: + The properties that change, each under the media queries it changes at. + + Raises: + StyleError: If a value is given under a key that is not a breakpoint, + or is bound to state. + """ + at: dict[str, list[tuple[int, str]]] = {} + for position, values in responsive.items(): + prop = table.consulted[position] + for breakpoint, value in values.items(): + if value.__class__ is not str: + value = _variant_key(value) + if value.__class__ is not str: + msg = ( + f'{name}: prop "{prop}" is given a value under ' + f'"{breakpoint}" that is not known at compile time. ' + "Give each breakpoint one of the values of the prop." + ) + raise StyleError(msg) + query = prop_breakpoint(name, prop, breakpoint) + if query != "default": + at.setdefault(query, []).append((position, value)) + out: dict[str, LoweredValue] = {} + current = list(keys) + before = table.resolve(keys) + for query in PROP_BREAKPOINTS.values(): + changes = at.get(query) + if changes is None: + continue + for position, value in changes: + current[position] = value + after = table.resolve(tuple(current)) + for prop, value in after.items(): + if prop not in before or freeze(before[prop]) != freeze(value): + conditions = out.get(prop) + if conditions is None: + out[prop] = {query: value} + else: + conditions[query] = value + before = after + return out, () + + def _difference( static: dict[str, LoweredValue], full: dict[str, LoweredValue] ) -> dict[str, LoweredValue]: @@ -524,19 +594,28 @@ def _merge( """ chosen = [] bound = None + responsive = 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 + if isinstance(value, Var): + if bound is None: + bound = {} + bound[len(chosen)] = value + value = None + else: + if responsive is None: + responsive = {} + responsive[len(chosen)] = value + value = value.get("initial") + if value.__class__ is not str and value is not None: + value = _variant_key(value) chosen.append(value) keys = tuple(chosen) - if bound is None: + if bound is None and responsive is None: merged = table.merged.get(keys) if merged is None: merged = table.merged[keys] = Merged( @@ -555,7 +634,13 @@ def _merge( part: _merge(name, inner, props, None, None) for part, inner in table.parts } - layers = [lower_layer(name, None, layout)] if layout else [] + layers = ( + [] + if responsive is None + else [_responsive_layer(name, table, keys, responsive)] + ) + if layout: + layers.append(lower_layer(name, None, layout)) inline = None if isinstance(style, Var): inline = style @@ -578,6 +663,28 @@ def _merge( return Merged(finish(merged_props, inline), dynamic, parts) +def over(under: Merged, top: Merged) -> Merged: + """Lay the styles of one element over those of another. + + For two components that render as one element: a parent with + ``as_child`` and its child. + + Args: + under: The styles that are overridden. + top: The styles that win where both set a property. + + Returns: + The styles of the one element. + """ + props = dict(under.style.style) + apply_layer(props, (top.style.style, ())) + return Merged( + finish(props, top.style.inline or under.style.inline), + (*under.dynamic, *top.dynamic), + {**under.parts, **top.parts} if under.parts else top.parts, + ) + + def merge( name: str, styles: ComponentStyles | Mapping[str, Any], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/flex.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/flex.py new file mode 100644 index 00000000000..f686a3b994b --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/flex.py @@ -0,0 +1,11 @@ +"""The look of the flex container.""" + +from reflex_components_ui.style import ComponentStyles + +FLEX: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "display": "flex", + "justify_content": "flex-start", + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py new file mode 100644 index 00000000000..dd60d56a5eb --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py @@ -0,0 +1,64 @@ +"""The look of text.""" + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.typography import ( + ACCENT_SCOPE, + ACCENT_SCOPE_HIGH_CONTRAST, + ACCENT_TEXT, + ALIGN, + WEIGHT, + trim, +) + +# The line height and the letter spacing are custom properties, so that text +# and code inside the element follow its size. +SIZE: dict[str, Any] = { + str(step): { + "font_size": tokens.font_size[step], + "--line-height": tokens.line_height[step], + "--letter-spacing": tokens.letter_spacing[step], + } + for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) +} + +TEXT: ComponentStyles = { + "base": { + "margin": "0", + "line_height": f"var(--line-height, {tokens.default.line_height})", + "letter_spacing": "var(--letter-spacing, inherit)", + }, + "variants": { + "size": SIZE, + "weight": WEIGHT, + "align": ALIGN, + "trim": trim( + f"var(--leading-trim-start, {tokens.default.leading_trim_start})", + f"var(--leading-trim-end, {tokens.default.leading_trim_end})", + ), + "color_scheme": {"true": {**ACCENT_SCOPE, "color": tokens.accent.a[11]}}, + # Inside an element with a color; no declaration otherwise. + "high_contrast": {"true": {"color": f"var({ACCENT_TEXT})"}}, + "as_": { + "label": { + "@media (pointer: coarse)": { + "WebkitTapHighlightColor": "transparent", + "_active": { + "outline_width": "0.75em", + "outline_style": "solid", + "outline_color": tokens.gray.a[4], + "outline_offset": "-0.6em", + }, + }, + }, + }, + }, + "compound": [ + { + "props": {"color_scheme": "true", "high_contrast": "true"}, + "style": {**ACCENT_SCOPE_HIGH_CONTRAST, "color": tokens.accent[12]}, + }, + ], +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py new file mode 100644 index 00000000000..7e029a6cc46 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py @@ -0,0 +1,74 @@ +"""The styles the typography components share.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import StyleProps + +# What an element with a color of its own tells the text inside it, as Radix +# Themes does through `[data-accent-color]` ancestor selectors: a class on an +# element cannot select by ancestor, so the ancestor hands down the values. +# High-contrast text without a color takes the first, a link without a color +# the other two. +ACCENT_TEXT = "--rx-accent-text" +ACCENT_LINK = "--rx-accent-link" +ACCENT_LINK_LINE = "--rx-accent-link-line" + +# The styles of `color_scheme`, for the "true" value of its variant. +ACCENT_SCOPE: dict[str, Any] = { + ACCENT_TEXT: tokens.accent[12], + ACCENT_LINK: tokens.accent[12], + ACCENT_LINK_LINE: "underline", +} + +# The same for an element that is high contrast too: links inside keep their +# own color. For a compound style of `color_scheme` and `high_contrast`. +ACCENT_SCOPE_HIGH_CONTRAST: dict[str, Any] = { + ACCENT_LINK: None, + ACCENT_LINK_LINE: None, +} + +WEIGHT: dict[str, StyleProps] = { + "light": {"font_weight": tokens.font_weight.light}, + "regular": {"font_weight": tokens.font_weight.regular}, + "medium": {"font_weight": tokens.font_weight.medium}, + "bold": {"font_weight": tokens.font_weight.bold}, +} + +ALIGN: dict[str, StyleProps] = { + "left": {"text_align": "left"}, + "center": {"text_align": "center"}, + "right": {"text_align": "right"}, +} + + +def trim(start: str, end: str) -> dict[str, StyleProps]: + """Make the variants of the trim prop: the leading above and below a text. + + Args: + start: What to take off above the first line. + end: What to take off below the last line. + + Returns: + The styles of each value of the prop. + """ + half_leading = f"var(--line-height, calc(1em * {tokens.default.line_height})) / 2" + none: Any = {"content": "none"} + before: Any = { + "content": "''", + "display": "table", + "margin_bottom": f"calc({start} - {half_leading})", + } + after: Any = { + "content": "''", + "display": "table", + "margin_top": f"calc({end} - {half_leading})", + } + return { + "normal": {"_before": none, "_after": none}, + "start": {"_before": before, "_after": none}, + "end": {"_before": none, "_after": after}, + "both": {"_before": before, "_after": after}, + } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/__init__.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/__init__.py new file mode 100644 index 00000000000..73aab55050a --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/__init__.py @@ -0,0 +1 @@ +"""The rx.ui components that set text.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/base.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/base.py new file mode 100644 index 00000000000..470bd6c21f8 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/base.py @@ -0,0 +1,10 @@ +"""The values of the props the typography components share.""" + +from __future__ import annotations + +from typing import Literal + +LiteralTextWeight = Literal["light", "regular", "medium", "bold"] +LiteralTextAlign = Literal["left", "center", "right"] +LiteralTextSize = Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"] +LiteralTextTrim = Literal["normal", "start", "end", "both"] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py new file mode 100644 index 00000000000..1a336c042df --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py @@ -0,0 +1,87 @@ +"""Text, and the inline elements that mark it up.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.markdown_component_map import MarkdownComponentMap +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.text import TEXT +from reflex_components_ui.themes import LiteralAccentColor +from reflex_components_ui.typography.base import ( + LiteralTextAlign, + LiteralTextSize, + LiteralTextTrim, + LiteralTextWeight, +) + +LiteralType = Literal[ + "p", + "label", + "div", + "span", + "b", + "i", + "u", + "abbr", + "cite", + "del", + "em", + "ins", + "kbd", + "mark", + "s", + "samp", + "sub", + "sup", +] + + +class Text(UIComponent, elements.Span, MarkdownComponentMap): + """A foundational text primitive based on the element.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = TEXT + + _as_tags: ClassVar[frozenset[str]] = frozenset(("span", "div", "label", "p")) + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + as_: Var[LiteralType] = field( + default=Var.create("p"), + doc="Change the default rendered element into a semantically appropriate alternative (cannot be used with asChild)", + ) + + size: Var[Responsive[LiteralTextSize]] = field(doc='Text size: "1" - "9"') + + weight: Var[Responsive[LiteralTextWeight]] = field( + doc='Thickness of text: "light" | "regular" | "medium" | "bold"' + ) + + align: Var[Responsive[LiteralTextAlign]] = field( + doc='Alignment of text in element: "left" | "center" | "right"' + ) + + trim: Var[Responsive[LiteralTextTrim]] = field( + doc='Removes the leading trim space: "normal" | "start" | "end" | "both"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Overrides the accent color inherited from the Theme." + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the text with higher contrast color" + ) + + +text = Text.create diff --git a/tests/units/reflex_components_ui/style/test_emit.py b/tests/units/reflex_components_ui/style/test_emit.py index 7cc5e638a7a..e10b0cab5f8 100644 --- a/tests/units/reflex_components_ui/style/test_emit.py +++ b/tests/units/reflex_components_ui/style/test_emit.py @@ -332,24 +332,24 @@ def comparable(result: Emitted) -> tuple[Any, ...]: }, emitted( declaration=( - 'const sx_dae5511f98 = stylex.create({ s: {"rowGap": ' + 'const sx_7ed480858f = 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)": ' + ' {"default": "var(--space-1)", "@media (min-width: ' + '520px)": "var(--space-2)"}, "paddingRight": {"default": ' + '"var(--space-1)", "@media (min-width: 520px)": ' '"var(--space-2)"}, "paddingBottom": {"default": ' - '"var(--space-1)", "@media screen and (min-width: 30em)": ' + '"var(--space-1)", "@media (min-width: 520px)": ' '"var(--space-2)"}, "paddingLeft": {"default": ' - '"var(--space-1)", "@media screen and (min-width: 30em)": ' + '"var(--space-1)", "@media (min-width: 520px)": ' '"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_7ed480858f_c = " + "stylex.props(sx_7ed480858f.s).className;" ), - classes="sx_dae5511f98_c", + classes="sx_7ed480858f_c", imports=("$/reflex-ui/tokens/space.stylex.js",), ), ), diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index eb57dbd5e67..768dd619dc3 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -37,6 +37,11 @@ MD = "@media screen and (min-width: 62em)" LG = "@media screen and (min-width: 80em)" XL = "@media screen and (min-width: 96em)" +# A responsive prop is on the breakpoints of Radix Themes instead. +PROP_XS = "@media (min-width: 520px)" +PROP_SM = "@media (min-width: 768px)" +PROP_MD = "@media (min-width: 1024px)" +PROP_LG = "@media (min-width: 1280px)" class StyleState(rx.State): @@ -830,8 +835,8 @@ def test_shorthands_stylex_does_not_compile( ( {"gap": ["1", "2"]}, { - "rowGap": {"default": "var(--space-1)", XS: "var(--space-2)"}, - "columnGap": {"default": "var(--space-1)", XS: "var(--space-2)"}, + "rowGap": {"default": "var(--space-1)", PROP_XS: "var(--space-2)"}, + "columnGap": {"default": "var(--space-1)", PROP_XS: "var(--space-2)"}, }, ), ( @@ -839,7 +844,7 @@ def test_shorthands_stylex_does_not_compile( _sides( "padding", "", - *[{"default": "var(--space-1)", MD: "var(--space-4)"}] * 4, + *[{"default": "var(--space-1)", PROP_MD: "var(--space-4)"}] * 4, ), ), ( @@ -854,7 +859,7 @@ def test_shorthands_stylex_does_not_compile( { "gridTemplateColumns": { "default": "repeat(1, minmax(0, 1fr))", - SM: "repeat(2, 10em)", + PROP_SM: "repeat(2, 10em)", } }, ), @@ -869,7 +874,7 @@ def test_shorthands_stylex_does_not_compile( ( {"direction": ["column", "row"], "align": "start", "justify": "between"}, { - "flexDirection": {"default": "column", XS: "row"}, + "flexDirection": {"default": "column", PROP_XS: "row"}, "alignItems": "flex-start", "justifyContent": "space-between", }, @@ -877,8 +882,8 @@ def test_shorthands_stylex_does_not_compile( ( {"align": ["end", "center"], "justify": {"initial": "end", "lg": "start"}}, { - "alignItems": {"default": "flex-end", XS: "center"}, - "justifyContent": {"default": "flex-end", LG: "flex-start"}, + "alignItems": {"default": "flex-end", PROP_XS: "center"}, + "justifyContent": {"default": "flex-end", PROP_LG: "flex-start"}, }, ), ({"direction": SCALE}, {"flexDirection": SCALE}), @@ -939,6 +944,8 @@ def test_layout_props_are_merged_under_the_style(): "spacing", "gap_x", "gap_y", + "spacing_x", + "spacing_y", "columns", "rows", "direction", diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index a1c36ace775..ea3847fce9a 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -105,13 +105,9 @@ def test_removing_a_prop_from_the_wrapper_is_a_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 - ] +def test_box_has_the_props_of_the_radix_box_and_nothing_is_allowlisted(): + assert differences("box") == [] + assert allowlist.load().api == () class Reference(Component): diff --git a/uv.lock b/uv.lock index 761d37b0549..c42ffc10950 100644 --- a/uv.lock +++ b/uv.lock @@ -4514,10 +4514,16 @@ name = "reflex-components-ui" source = { editable = "packages/reflex-components-ui" } dependencies = [ { name = "reflex-base" }, + { name = "reflex-components-core" }, + { name = "reflex-components-lucide" }, ] [package.metadata] -requires-dist = [{ name = "reflex-base", editable = "packages/reflex-base" }] +requires-dist = [ + { name = "reflex-base", editable = "packages/reflex-base" }, + { name = "reflex-components-core", editable = "packages/reflex-components-core" }, + { name = "reflex-components-lucide", editable = "packages/reflex-components-lucide" }, +] [[package]] name = "reflex-docgen" From e1665c821442edb276375ad06792ca987cd73ffd Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:01:38 +0000 Subject: [PATCH 031/204] Add the layout and typography components of rx.ui, with their style tables Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- .../src/reflex_components_ui/__init__.py | 16 +- .../src/reflex_components_ui/base.py | 6 +- .../components/aspect_ratio.py | 75 +++++++ .../reflex_components_ui/components/inset.py | 49 +++++ .../components/separator.py | 70 +++++++ .../src/reflex_components_ui/layout/center.py | 26 +++ .../reflex_components_ui/layout/container.py | 69 ++++++ .../src/reflex_components_ui/layout/grid.py | 60 ++++++ .../src/reflex_components_ui/layout/list.py | 196 ++++++++++++++++++ .../reflex_components_ui/layout/section.py | 32 +++ .../src/reflex_components_ui/layout/spacer.py | 26 +++ .../src/reflex_components_ui/layout/stack.py | 69 ++++++ .../src/reflex_components_ui/style/merge.py | 19 +- .../styles/aspect_ratio.py | 22 ++ .../reflex_components_ui/styles/blockquote.py | 28 +++ .../src/reflex_components_ui/styles/code.py | 154 ++++++++++++++ .../reflex_components_ui/styles/container.py | 29 +++ .../src/reflex_components_ui/styles/grid.py | 14 ++ .../reflex_components_ui/styles/heading.py | 48 +++++ .../src/reflex_components_ui/styles/inset.py | 102 +++++++++ .../src/reflex_components_ui/styles/link.py | 124 +++++++++++ .../src/reflex_components_ui/styles/list.py | 9 + .../reflex_components_ui/styles/section.py | 18 ++ .../reflex_components_ui/styles/separator.py | 29 +++ .../src/reflex_components_ui/styles/text.py | 80 ++++--- .../reflex_components_ui/styles/typography.py | 97 ++++++--- .../typography/blockquote.py | 41 ++++ .../reflex_components_ui/typography/code.py | 63 ++++++ .../typography/heading.py | 72 +++++++ .../reflex_components_ui/typography/link.py | 117 +++++++++++ .../reflex_components_ui/typography/text.py | 46 +++- .../reflex_components_ui/style/test_merge.py | 2 +- 32 files changed, 1740 insertions(+), 68 deletions(-) create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/inset.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/separator.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/center.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/container.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/grid.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/list.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/section.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/spacer.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/layout/stack.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/aspect_ratio.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/blockquote.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/code.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/container.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/grid.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/link.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/list.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/section.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/typography/blockquote.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/typography/code.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/typography/heading.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/typography/link.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 cb2baae12af..5efaffea7f6 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -7,11 +7,25 @@ _SUBMODULES: set[str] = {"tokens"} _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { + "components.aspect_ratio": ["aspect_ratio"], + "components.inset": ["inset"], + "components.separator": ["divider", "separator"], "layout.box": ["box"], + "layout.center": ["center"], + "layout.container": ["container"], "layout.flex": ["flex"], - "typography.text": ["text"], + "layout.grid": ["grid"], + "layout.list": [("list_ns", "list"), "list_item", "ordered_list", "unordered_list"], + "layout.section": ["section"], + "layout.spacer": ["spacer"], + "layout.stack": ["hstack", "stack", "vstack"], "layout.theme": ["theme"], "themes": ["Theme"], + "typography.blockquote": ["blockquote"], + "typography.code": ["code"], + "typography.heading": ["heading"], + "typography.link": ["link"], + "typography.text": ["text"], } __getattr__, __dir__, __all__ = lazy_loader.attach( 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 5cb26d04406..89ce627b39a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -386,7 +386,8 @@ def _set_slot(self) -> None: if ( len(children) != 1 or not isinstance(children[0], Component) - or type(children[0]).render is not Component.render + or type(children[0]).render + not in (Component.render, UIComponent.render) ): msg = ( f"{name}: as_child renders the only child in place of the " @@ -619,6 +620,9 @@ def render(self) -> dict: slot = self._slot if slot is None: return super().render() + # The child may itself render as its own child. + while isinstance(slot, UIComponent) and slot._slot is not None: + slot = slot._slot rendered = self._render().render([child.render() for child in slot.children]) slot._replace_prop_names(rendered) return rendered diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py b/packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py new file mode 100644 index 00000000000..c47154e8e1f --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py @@ -0,0 +1,75 @@ +"""A box that keeps the ratio of its width to its height.""" + +from __future__ import annotations + +from typing import ClassVar + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import LiteralVar, Var + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.aspect_ratio import ASPECT_RATIO, ASPECT_RATIO_FRAME + + +class AspectRatioFrame(UIComponent): + """The element around the content, whose height follows its width.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = ASPECT_RATIO_FRAME + + @classmethod + def _display_name(cls) -> str: + """Get the name an app refers to the component by. + + Returns: + The name of the component the frame belongs to. + """ + return "rx.ui.aspect_ratio" + + +class AspectRatio(UIComponent): + """Displays content with a desired ratio.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = ASPECT_RATIO + + ratio: Var[float | int] = field( + doc="The ratio of the width to the height of the element" + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create the content of the box, inside the frame that sizes it. + + Args: + *children: The children of the component. + **props: The props of the component, which go to the content. + + Returns: + The frame. + """ + ratio = LiteralVar.create(props.get("ratio", 1)) + padding = ( + f"{100 / ratio._var_value}%" + if isinstance(ratio, LiteralVar) + else (100 / ratio).to(str) + "%" + ) + return AspectRatioFrame.create( + super().create(*children, **props), + style={"padding_bottom": padding}, + custom_attrs={"data-radix-aspect-ratio-wrapper": ""}, + ) + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the ratio. + """ + return [*super()._exclude_props(), "ratio"] + + +aspect_ratio = AspectRatio.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/inset.py b/packages/reflex-components-ui/src/reflex_components_ui/components/inset.py new file mode 100644 index 00000000000..7d7230e42da --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/inset.py @@ -0,0 +1,49 @@ +"""An inset: content that reaches the edges of its container.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.inset import INSET + +LiteralButtonSize = Literal["1", "2", "3", "4"] + + +class Inset(UIComponent, elements.Div): + """Applies a negative margin to allow content to bleed into the surrounding container.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = INSET + + side: Var[Responsive[Literal["x", "y", "top", "bottom", "right", "left"]]] = field( + doc="The side" + ) + + clip: Var[Responsive[Literal["border-box", "padding-box"]]] = field( + doc='How to clip the element\'s content: "border-box" | "padding-box"' + ) + + p: Var[Responsive[int | str]] = field(doc="Padding") + + px: Var[Responsive[int | str]] = field(doc="Padding on the x axis") + + py: Var[Responsive[int | str]] = field(doc="Padding on the y axis") + + pt: Var[Responsive[int | str]] = field(doc="Padding on the top") + + pr: Var[Responsive[int | str]] = field(doc="Padding on the right") + + pb: Var[Responsive[int | str]] = field(doc="Padding on the bottom") + + pl: Var[Responsive[int | str]] = field(doc="Padding on the left") + + +inset = Inset.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/separator.py b/packages/reflex-components-ui/src/reflex_components_ui/components/separator.py new file mode 100644 index 00000000000..350aa31e24e --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/separator.py @@ -0,0 +1,70 @@ +"""A separator: a line between two things.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.components.tags import CommonTag +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.separator import SEPARATOR +from reflex_components_ui.themes import LiteralAccentColor + +LiteralSeparatorSize = Literal["1", "2", "3", "4"] + + +class Separator(UIComponent): + """Visually or semantically separates content.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = SEPARATOR + + size: Var[Responsive[LiteralSeparatorSize]] = field( + default=LiteralVar.create("4"), + doc='The size of the separator: "1" | "2" | "3" | "4"', + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="The color of the separator") + + orientation: Var[Responsive[Literal["horizontal", "vertical"]]] = field( + doc="The orientation of the separator." + ) + + decorative: Var[bool] = field( + doc="When true, signifies that it is purely visual, carries no semantic meaning, and ensures it is not present in the accessibility tree." + ) + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the one read as the role. + """ + return [*super()._exclude_props(), "decorative"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the line, with the role of a separator unless it is decorative. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. + """ + tag = super()._render(props) + decorative = self.decorative + if decorative is None: + return tag + if isinstance(decorative, LiteralVar): + return tag if decorative._var_value else tag.add_props(role="separator") + role = Var(f'({decorative!s} ? undefined : "separator")') + return tag.add_props(role=role._replace(merge_var_data=decorative._get_all_var_data())) + + +# Alias to divider. +divider = separator = Separator.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/center.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/center.py new file mode 100644 index 00000000000..5c2d4de2a30 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/center.py @@ -0,0 +1,26 @@ +"""A flex container that centers its content.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui.layout.flex import Flex + + +class Center(Flex): + """A center component.""" + + def add_style(self) -> dict[str, Any] | None: + """Add style that center the content. + + Returns: + The style of the component. + """ + return { + "display": "flex", + "align_items": "center", + "justify_content": "center", + } + + +center = Center.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/container.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/container.py new file mode 100644 index 00000000000..17f8b18ba9c --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/container.py @@ -0,0 +1,69 @@ +"""A container that bounds the width of a page.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.style import ComponentStyles, StyleError +from reflex_components_ui.styles.container import CONTAINER + +LiteralContainerSize = Literal["1", "2", "3", "4"] + + +class Container(UIComponent, elements.Div): + """Constrains the maximum width of page content.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = CONTAINER + + size: Var[Responsive[LiteralContainerSize]] = field( + default=LiteralVar.create("3"), + doc='The size of the container: "1" - "4" (default "3")', + ) + + @classmethod + def create( + cls, + *children, + padding: str = "16px", + stack_children_full_width: bool = False, + **props, + ) -> Component: + """Create the container component. + + Args: + *children: The children components. + padding: The padding of the container. + stack_children_full_width: If True, any vstack/hstack children will have 100% width. + **props: The properties of the container. + + Returns: + The container component. + + Raises: + StyleError: If ``stack_children_full_width`` is set: it styles the + stacks inside the container through nested selectors. + """ + if stack_children_full_width: + msg = ( + f"{cls._display_name()}: stack_children_full_width styles the " + "stacks inside the container through nested selectors, which " + 'rx.ui styles do not support. Give those stacks width="100%", ' + "or keep rx.container for this element." + ) + raise StyleError(msg) + return super().create( + Part.create(*children, part="inner", tag="div"), + padding=padding, + **props, + ) + + +container = Container.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/grid.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/grid.py new file mode 100644 index 00000000000..7b81851eced --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/grid.py @@ -0,0 +1,60 @@ +"""A grid container.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.props import LiteralAlign, LiteralJustify, LiteralSpacing +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.grid import GRID + +LiteralGridFlow = Literal["row", "column", "dense", "row-dense", "column-dense"] + + +class Grid(UIComponent, elements.Div): + """Component for creating grid layouts.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = GRID + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + columns: Var[Responsive[str]] = field(doc="Number of columns") + + rows: Var[Responsive[str]] = field(doc="Number of rows") + + flow: Var[Responsive[LiteralGridFlow]] = field( + doc='How the grid items are laid out: "row" | "column" | "dense" | "row-dense" | "column-dense"' + ) + + align: Var[Responsive[LiteralAlign]] = field( + doc='Alignment of children along the main axis: "start" | "center" | "end" | "baseline" | "stretch"' + ) + + justify: Var[Responsive[LiteralJustify]] = field( + doc='Alignment of children along the cross axis: "start" | "center" | "end" | "between"' + ) + + spacing: Var[Responsive[LiteralSpacing]] = field( + doc='Gap between children: "0" - "9"' + ) + + spacing_x: Var[Responsive[LiteralSpacing]] = field( + doc='Gap between children horizontal: "0" - "9"' + ) + + spacing_y: Var[Responsive[LiteralSpacing]] = field( + doc='Gap between children vertical: "0" - "9"' + ) + + +grid = Grid.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/list.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/list.py new file mode 100644 index 00000000000..84263638075 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/list.py @@ -0,0 +1,196 @@ +"""List components.""" + +from __future__ import annotations + +from collections.abc import Iterable, MutableSequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.vars.base import Var +from reflex_components_core.core.foreach import Foreach +from reflex_components_core.core.markdown_component_map import MarkdownComponentMap +from reflex_components_core.el.elements.base import BaseHTML +from reflex_components_core.el.elements.typography import Li, Ol, Ul +from reflex_components_lucide.icon import Icon + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.list import LIST, MARKER_INDENT +from reflex_components_ui.typography.text import Text + +LiteralListStyleTypeUnordered = Literal[ + "none", + "disc", + "circle", + "square", +] + +LiteralListStyleTypeOrdered = Literal[ + "none", + "decimal", + "decimal-leading-zero", + "lower-roman", + "upper-roman", + "lower-greek", + "lower-latin", + "upper-latin", + "armenian", + "georgian", + "lower-alpha", + "upper-alpha", + "hiragana", + "katakana", +] + + +class BaseList(UIComponent, BaseHTML, MarkdownComponentMap): + """Base class for ordered and unordered lists.""" + + tag = "ul" + + styles: ClassVar[ComponentStyles] = LIST + + list_style_type: Var[ + LiteralListStyleTypeUnordered | LiteralListStyleTypeOrdered + ] = field( + default=Var.create("none"), doc='The style of the list. Default to "none".' + ) + + items: Var[Iterable] = field( + default=Var.create([]), doc="A list of items to add to the list." + ) + + @classmethod + def create( + cls, + *children, + **props, + ) -> Component: + """Create a list component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The list component. + """ + items = props.pop("items", None) + list_style_type = props.pop("list_style_type", "none") + + if not children and items is not None: + if isinstance(items, Var): + children = [Foreach.create(items, ListItem.create)] + else: + children = [ListItem.create(item) for item in items] + # The marker wins over a list_style_type in the style of the element. + marker: dict[str, Any] = {"list_style_type": list_style_type} + style = props.get("style") + if style is None: + props["style"] = marker + elif isinstance(style, (list, tuple)): + props["style"] = [*style, marker] + else: + props["style"] = [style, marker] + return super().create(*children, **props) + + def _exclude_props(self) -> MutableSequence[str]: + return [*super()._exclude_props(), "items", "list_style_type"] + + +class UnorderedList(BaseList, Ul): + """Display an unordered list.""" + + tag = "ul" + + @classmethod + def create( + cls, + *children, + **props, + ) -> Component: + """Create an unordered list component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The list component. + """ + items = props.pop("items", None) + list_style_type = props.pop("list_style_type", "disc") + + props["margin_left"] = props.get("margin_left", MARKER_INDENT) + return super().create( + *children, items=items, list_style_type=list_style_type, **props + ) + + +class OrderedList(BaseList, Ol): + """Display an ordered list.""" + + tag = "ol" + + @classmethod + def create( + cls, + *children, + **props, + ) -> Component: + """Create an ordered list component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The list component. + """ + items = props.pop("items", None) + list_style_type = props.pop("list_style_type", "decimal") + + props["margin_left"] = props.get("margin_left", MARKER_INDENT) + return super().create( + *children, items=items, list_style_type=list_style_type, **props + ) + + +class ListItem(UIComponent, Li, MarkdownComponentMap): + """Display an item of an ordered or unordered list.""" + + tag = "li" + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a list item component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The list item component. + """ + for child in children: + if isinstance(child, Text): + # Text inside an item is a run of it, not a paragraph. + child.tag = "span" + elif isinstance(child, Icon) and "display" not in child.style: + child.style["display"] = "inline" + return super().create(*children, **props) + + +class List(ComponentNamespace): + """List components.""" + + item = staticmethod(ListItem.create) + ordered = staticmethod(OrderedList.create) + unordered = staticmethod(UnorderedList.create) + __call__ = staticmethod(BaseList.create) + + +list_ns = List() +list_item = list_ns.item +ordered_list = list_ns.ordered +unordered_list = list_ns.unordered diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/section.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/section.py new file mode 100644 index 00000000000..ad1a72cdc40 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/section.py @@ -0,0 +1,32 @@ +"""A section of a page.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.section import SECTION + +LiteralSectionSize = Literal["1", "2", "3"] + + +class Section(UIComponent, elements.Section): + """Denotes a section of page content.""" + + tag = "section" + + styles: ClassVar[ComponentStyles] = SECTION + + size: Var[Responsive[LiteralSectionSize]] = field( + default=LiteralVar.create("2"), + doc='The size of the section: "1" - "3" (default "2")', + ) + + +section = Section.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/spacer.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/spacer.py new file mode 100644 index 00000000000..0a320265ae5 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/spacer.py @@ -0,0 +1,26 @@ +"""A flex item that takes up the space between its siblings.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui.layout.flex import Flex + + +class Spacer(Flex): + """A spacer component.""" + + def add_style(self) -> dict[str, Any] | None: + """Add style to the component. + + Returns: + The style of the component. + """ + return { + "flex": 1, + "justify_self": "stretch", + "align_self": "stretch", + } + + +spacer = Spacer.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/stack.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/stack.py new file mode 100644 index 00000000000..6c9477251f9 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/stack.py @@ -0,0 +1,69 @@ +"""Stacks: flex containers with a gap between their children.""" + +from __future__ import annotations + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.layout.flex import Flex, LiteralFlexDirection +from reflex_components_ui.props import LiteralAlign, LiteralSpacing + + +class Stack(Flex): + """A stack component.""" + + spacing: Var[Responsive[LiteralSpacing]] = field( + default=Var.create("3"), doc="The spacing between each stack item." + ) + + align: Var[Responsive[LiteralAlign]] = field( + default=Var.create("start"), doc="The alignment of the stack items." + ) + + @classmethod + def create( + cls, + *children, + **props, + ) -> Component: + """Create a new instance of the component. + + Args: + *children: The children of the stack. + **props: The properties of the stack. + + Returns: + The stack component. + """ + # The class name an app's stylesheet finds a stack by. + given_class_name = props.pop("class_name", []) + if not isinstance(given_class_name, list): + given_class_name = [given_class_name] + props["class_name"] = ["rx-Stack", *given_class_name] + + return super().create( + *children, + **props, + ) + + +class VStack(Stack): + """A vertical stack component.""" + + direction: Var[Responsive[LiteralFlexDirection]] = field( + default=Var.create("column"), doc="The direction of the stack." + ) + + +class HStack(Stack): + """A horizontal stack component.""" + + direction: Var[Responsive[LiteralFlexDirection]] = field( + default=Var.create("row"), doc="The direction of the stack." + ) + + +stack = Stack.create +hstack = HStack.create +vstack = VStack.create 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 63d67f2a565..0a700550eed 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 @@ -44,16 +44,19 @@ 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. + as strings: ``"true"`` and ``"false"`` for a boolean prop. ``defaults`` + gives the value a prop selects styles by when the element leaves it out, + for a default the component has in its look alone, not in its API. """ base: StyleProps variants: dict[str, dict[str, StyleProps]] + defaults: dict[str, str] compound: list[CompoundStyle] parts: dict[str, ComponentStyles] -_TABLE_KEYS = frozenset(("base", "variants", "compound", "parts")) +_TABLE_KEYS = frozenset(("base", "variants", "defaults", "compound", "parts")) _NO_PROPS: Mapping[str, Any] = {} @@ -224,6 +227,7 @@ class _Table: 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. + defaults: The value each consulted prop has when it is not set. base: The lowered base style. variants: For each variant, the position of its prop in ``consulted`` and the lowered style of each value. @@ -239,6 +243,7 @@ class _Table: "breakpoints", "compound", "consulted", + "defaults", "merged", "parts", "resolved", @@ -260,8 +265,7 @@ def __init__(self, name: str, source: Mapping[str, Any]): 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".' +XX ) raise StyleError(msg) self.source = source @@ -280,6 +284,10 @@ def __init__(self, name: str, source: Mapping[str, Any]): positions.update(dict.fromkeys(part.consulted, 0)) positions = {prop: position for position, prop in enumerate(positions)} self.consulted = tuple(positions) + defaults = source.get("defaults", _NO_PROPS) + self.defaults: tuple[str | None, ...] = tuple([ + defaults.get(prop) for prop in positions + ]) self.variants: tuple[tuple[int, dict[str | None, Layer]], ...] = tuple([ ( positions[prop], @@ -595,6 +603,7 @@ def _merge( chosen = [] bound = None responsive = None + defaults = table.defaults for prop in table.consulted: value = props.get(prop) if value.__class__ is not str and value is not None: @@ -612,6 +621,8 @@ def _merge( value = value.get("initial") if value.__class__ is not str and value is not None: value = _variant_key(value) + if value is None: + value = defaults[len(chosen)] chosen.append(value) keys = tuple(chosen) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/aspect_ratio.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/aspect_ratio.py new file mode 100644 index 00000000000..27118121d7e --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/aspect_ratio.py @@ -0,0 +1,22 @@ +"""The look of a box that keeps the ratio of its width to its height.""" + +from reflex_components_ui.style import ComponentStyles + +# The frame takes its height from a padding in proportion to its width, which +# the component sets: the content fills it. +ASPECT_RATIO_FRAME: ComponentStyles = { + "base": { + "position": "relative", + "width": "100%", + }, +} + +ASPECT_RATIO: ComponentStyles = { + "base": { + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/blockquote.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/blockquote.py new file mode 100644 index 00000000000..b76e2ae82a7 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/blockquote.py @@ -0,0 +1,28 @@ +"""The look of a block quotation: text with a rule beside it.""" + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.text import TEXT_BASE +from reflex_components_ui.styles.typography import ( + COLOR, + COLOR_HIGH_CONTRAST, + SIZE, + WEIGHT, +) + +BLOCKQUOTE: ComponentStyles = { + "base": { + **TEXT_BASE, + "box_sizing": "border-box", + "border_left_width": f"max({tokens.space[1]}, 0.25em)", + "border_left_style": "solid", + "border_left_color": tokens.accent.a[6], + "padding_left": f"min({tokens.space[5]}, max({tokens.space[3]}, 0.5em))", + }, + "variants": { + "size": SIZE, + "weight": WEIGHT, + **COLOR, + }, + "compound": [COLOR_HIGH_CONTRAST], +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py new file mode 100644 index 00000000000..7b235f47817 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py @@ -0,0 +1,154 @@ +"""The look of inline code.""" + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.typography import ( + ACCENT_SCOPE, + ACCENT_SCOPE_HIGH_CONTRAST, + ACCENT_TEXT, + LINK_CODE_OUTLINE, + LINK_CODE_SOFT, + LINK_CODE_SOLID, + WEIGHT, +) + +# What the font size is multiplied by: a variant with a background is a +# little smaller than the text around it. +_ADJUST = "--code-variant-font-size-adjust" + +SIZE: dict[str, Any] = { + str(step): { + "font_size": f"calc({tokens.font_size[step]} * var({_ADJUST}))", + "line_height": tokens.line_height[step], + "--letter-spacing": tokens.letter_spacing[step], + } + for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) +} + + +def _hover(inside_link: str, otherwise: str) -> dict[str, Any]: + """Make the background of code under the pointer. + + Args: + inside_link: The custom property a link around the code sets. + otherwise: The background of the code at rest. + + Returns: + The background: it only changes inside a link. + """ + return { + "default": otherwise, + "@media (hover: hover)": {":hover": f"var({inside_link}, {otherwise})"}, + } + + +_OUTLINE = "inset 0 0 0 max(1px, 0.033em)" + +_SOFT: Any = { + "background_color": _hover(LINK_CODE_SOFT, tokens.accent.a[3]), + "color": tokens.accent.a[11], +} + +CODE: ComponentStyles = { + "base": { + _ADJUST: f"calc({tokens.code.font_size_adjust} * 0.95)", + "font_family": tokens.code.font_family, + "font_size": f"calc(var({_ADJUST}) * 1em)", + "font_style": tokens.code.font_style, + "font_weight": tokens.code.font_weight, + "line_height": "1.25", + "letter_spacing": ( + f"calc({tokens.code.letter_spacing} + " + f"var(--letter-spacing, {tokens.default.letter_spacing}))" + ), + "border_radius": f"calc((0.5px + 0.2em) * {tokens.radius.factor})", + "box_sizing": "border-box", + "padding_top": tokens.code.padding_top, + "padding_left": tokens.code.padding_left, + "padding_bottom": tokens.code.padding_bottom, + "padding_right": tokens.code.padding_right, + # Not stretched by a flex or grid container. + "height": "fit-content", + }, + "variants": { + "size": SIZE, + "weight": WEIGHT, + "variant": { + "ghost": {_ADJUST: tokens.code.font_size_adjust, "padding": "0"}, + "solid": { + "background_color": _hover(LINK_CODE_SOLID, tokens.accent.a[9]), + "color": tokens.accent.contrast, + "_selection": { + "background_color": tokens.accent[7], + "color": tokens.accent[12], + }, + }, + "soft": _SOFT, + "outline": { + "box_shadow": f"{_OUTLINE} {tokens.accent.a[8]}", + "color": tokens.accent.a[11], + "background_color": { + "@media (hover: hover)": { + ":hover": f"var({LINK_CODE_OUTLINE}, transparent)" + }, + }, + }, + # Radix Themes has neither for code, and falls back to soft. + "classic": _SOFT, + "surface": _SOFT, + }, + "color_scheme": {"true": ACCENT_SCOPE}, + }, + "defaults": {"variant": "soft"}, + "compound": [ + { + "props": {"color_scheme": "true", "high_contrast": "true"}, + "style": ACCENT_SCOPE_HIGH_CONTRAST, + }, + { + "props": {"variant": "ghost", "color_scheme": "true"}, + "style": {"color": tokens.accent.a[11]}, + }, + { + "props": {"variant": "ghost", "high_contrast": "true"}, + "style": {"color": f"var({ACCENT_TEXT})"}, + }, + { + "props": { + "variant": "ghost", + "color_scheme": "true", + "high_contrast": "true", + }, + "style": {"color": tokens.accent[12]}, + }, + { + "props": {"variant": "solid", "high_contrast": "true"}, + "style": { + "background_color": tokens.accent[12], + "color": tokens.accent[1], + "_selection": { + "background_color": tokens.accent.a[11], + "color": tokens.accent[1], + }, + }, + }, + *( + { + "props": {"variant": variant, "high_contrast": "true"}, + "style": {"color": tokens.accent[12]}, + } + for variant in ("soft", "classic", "surface") + ), + { + "props": {"variant": "outline", "high_contrast": "true"}, + "style": { + "box_shadow": ( + f"{_OUTLINE} {tokens.accent.a[7]}, {_OUTLINE} {tokens.gray.a[11]}" + ), + "color": tokens.accent[12], + }, + }, + ], +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/container.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/container.py new file mode 100644 index 00000000000..cbd8c6ffb3a --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/container.py @@ -0,0 +1,29 @@ +"""The look of the container that bounds the width of a page.""" + +from reflex_components_ui.style import ComponentStyles + +CONTAINER: ComponentStyles = { + "base": { + "display": "flex", + "box_sizing": "border-box", + "flex_direction": "column", + "align_items": "center", + "flex_shrink": "0", + "flex_grow": "1", + }, + "parts": { + "inner": { + "base": {"width": "100%"}, + # The widths Radix Themes declares beside its container: they are + # not design tokens, and no theme changes them. + "variants": { + "size": { + "1": {"max_width": "448px"}, + "2": {"max_width": "688px"}, + "3": {"max_width": "880px"}, + "4": {"max_width": "1136px"}, + }, + }, + }, + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/grid.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/grid.py new file mode 100644 index 00000000000..bac60d8b521 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/grid.py @@ -0,0 +1,14 @@ +"""The look of the grid container.""" + +from reflex_components_ui.style import ComponentStyles + +GRID: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "display": "grid", + "align_items": "stretch", + "justify_content": "flex-start", + "grid_template_columns": "minmax(0, 1fr)", + "grid_template_rows": "none", + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py new file mode 100644 index 00000000000..67bd2eb4cca --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py @@ -0,0 +1,48 @@ +"""The look of a heading.""" + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.typography import ( + ALIGN, + COLOR, + COLOR_HIGH_CONTRAST, + TRIM, + WEIGHT, +) + +# The line height is a custom property, which text inside the heading follows. +SIZE: dict[str, Any] = { + str(step): { + "font_size": ( + f"calc({tokens.font_size[step]} * {tokens.heading.font_size_adjust})" + ), + "--line-height": tokens.heading.line_height[step], + "letter_spacing": ( + f"calc({tokens.letter_spacing[step]} + {tokens.heading.letter_spacing})" + ), + } + for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) +} + +HEADING: ComponentStyles = { + "base": { + "--leading-trim-start": tokens.heading.leading_trim_start, + "--leading-trim-end": tokens.heading.leading_trim_end, + "font_family": tokens.heading.font_family, + "font_style": tokens.heading.font_style, + "font_weight": tokens.font_weight.bold, + "line_height": "var(--line-height)", + "margin": "0", + }, + "variants": { + "size": SIZE, + "weight": WEIGHT, + "align": ALIGN, + "trim": TRIM, + **COLOR, + }, + "defaults": {"size": "6"}, + "compound": [COLOR_HIGH_CONTRAST], +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py new file mode 100644 index 00000000000..5bc74866a03 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py @@ -0,0 +1,102 @@ +"""The look of an inset: content that reaches the edges of its container.""" + +from typing import Any + +from reflex_components_ui.style import ComponentStyles + +# The container, a card for one, says how far its edges are through the +# `--inset-padding-*`, `--inset-border-width` and `--inset-border-radius` +# custom properties, as it does for Radix Themes. +_SIDES = ("top", "right", "bottom", "left") +_RADIUS = "var(--inset-border-radius-calc)" + + +def _side(*sides: str, corners: str = "") -> dict[str, Any]: + """Make the margins and the corners of an inset that reaches some sides. + + Args: + *sides: The sides the inset reaches. + corners: The side whose two corners follow the container, ``all`` for + every corner, or nothing for square corners. + + Returns: + A negative margin on each of those sides, and the radius of each + corner. + """ + style: dict[str, Any] = { + f"margin_{side}": ( + f"calc(0px - var(--inset-padding-{side}-calc))" if side in sides else "0px" + ) + for side in _SIDES + } + for vertical in ("top", "bottom"): + for horizontal in ("left", "right"): + style[f"border_{vertical}_{horizontal}_radius"] = ( + _RADIUS if corners in ("all", vertical, horizontal) else "0px" + ) + return style + + +def _clip(border: bool) -> dict[str, Any]: + """Make the edges an inset reaches to: of the border, or inside it. + + Args: + border: Whether the border of the container is covered too. + + Returns: + The distances the margins and the corners are worked out from. + """ + width = "var(--inset-border-width, 0px)" + radius = "var(--inset-border-radius, 0px)" + style = { + "--inset-border-radius-calc": radius if border else f"calc({radius} - {width})", + } + for side in _SIDES: + padding = f"var(--inset-padding-{side}, 0px)" + style[f"--inset-padding-{side}-calc"] = ( + f"calc({padding} + {width})" if border else padding + ) + return style + + +INSET: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "overflow": "hidden", + }, + "variants": { + "clip": { + "border-box": _clip(border=False), + "padding-box": _clip(border=True), + }, + "side": { + "top": _side("left", "top", "right", corners="top"), + "bottom": _side("left", "bottom", "right", corners="bottom"), + "left": _side("top", "left", "bottom", corners="left"), + "right": _side("top", "right", "bottom", corners="right"), + "x": _side("left", "right"), + "y": _side("top", "bottom"), + "all": _side(*_SIDES, corners="all"), + }, + # The padding props take two values: none, or the padding of the + # container, which the inset then has itself. + **{ + prop: { + "0": {f"padding_{side}": "0" for side in sides}, + "current": { + f"padding_{side}": f"var(--inset-padding-{side})" for side in sides + }, + } + for prop, sides in ( + ("p", _SIDES), + ("px", ("left", "right")), + ("py", ("top", "bottom")), + ("pt", ("top",)), + ("pr", ("right",)), + ("pb", ("bottom",)), + ("pl", ("left",)), + ) + }, + }, + "defaults": {"clip": "border-box", "side": "all"}, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py new file mode 100644 index 00000000000..30815ed533e --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py @@ -0,0 +1,124 @@ +"""The look of a link.""" + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.text import TEXT_BASE +from reflex_components_ui.styles.typography import ( + ACCENT_LINK, + ACCENT_LINK_LINE, + ACCENT_LINK_LINE_COLOR, + ACCENT_SCOPE, + LINK_CODE_OUTLINE, + LINK_CODE_SOFT, + LINK_CODE_SOLID, + SIZE, + TRIM, + WEIGHT, + underline_color, +) + +# A line is hard to see under code with a background, when that is all the +# link holds. +_ONLY_CODE = ':has(code[data-variant]:not([data-variant="ghost"]):only-child)' + + +def _line_color(color: str) -> dict[str, str]: + """Make the color of the line under a link. + + Args: + color: The color. + + Returns: + The color, unless the line is hidden. + """ + return {"default": color, _ONLY_CODE: "transparent"} + + +def _line(rest: str, hover: str) -> dict[str, Any]: + """Make the line of a link: never under the ring of the keyboard's focus. + + Args: + rest: The line at rest. + hover: The line under the pointer. + + Returns: + The line in each state. + """ + return { + "default": rest, + ":focus-visible": "none", + "@media (hover: hover)": {":hover": hover, ":focus-visible": "none"}, + } + + +LINK: ComponentStyles = { + "base": { + **TEXT_BASE, + # Without a color of its own, inside an element that has one. + "color": f"var({ACCENT_LINK}, {tokens.accent.a[11]})", + "WebkitTapHighlightColor": "transparent", + ":any-link": {"cursor": tokens.cursor.link}, + "[data-disabled]": {"cursor": tokens.cursor.disabled}, + "text_decoration_style": "solid", + "text_decoration_thickness": "min(2px, max(1px, 0.05em))", + "text_underline_offset": "calc(0.025em + 2px)", + "text_decoration_color": _line_color(underline_color(5)), + ":focus-visible": { + "border_radius": f"calc(0.07em * {tokens.radius.factor})", + "outline_color": tokens.focus[8], + "outline_width": "2px", + "outline_style": "solid", + "outline_offset": "2px", + }, + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": { + "outline_width": "0.75em", + "outline_style": "solid", + "outline_color": tokens.accent.a[4], + "outline_offset": "-0.6em", + }, + }, + LINK_CODE_SOLID: tokens.accent[10], + LINK_CODE_SOFT: tokens.accent.a[4], + LINK_CODE_OUTLINE: tokens.accent.a[2], + }, + "variants": { + "size": SIZE, + "weight": WEIGHT, + "trim": TRIM, + "underline": { + "auto": { + "text_decoration_line": _line( + f"var({ACCENT_LINK_LINE}, none)", "underline" + ), + "text_decoration_color": _line_color( + f"var({ACCENT_LINK_LINE_COLOR}, {underline_color(5)})" + ), + }, + "hover": {"text_decoration_line": _line("none", "underline")}, + "always": {"text_decoration_line": _line("underline", "underline")}, + "none": {"text_decoration_line": "none"}, + }, + "color_scheme": {"true": {**ACCENT_SCOPE, "color": tokens.accent.a[11]}}, + "high_contrast": {"true": {"color": tokens.accent[12]}}, + }, + "defaults": {"underline": "auto"}, + "compound": [ + { + "props": {"underline": "auto", "color_scheme": "true"}, + "style": { + "text_decoration_line": _line("none", "underline"), + "text_decoration_color": _line_color(underline_color(5)), + }, + }, + { + "props": {"underline": "auto", "high_contrast": "true"}, + "style": { + "text_decoration_line": _line("underline", "underline"), + "text_decoration_color": _line_color(underline_color(6)), + }, + }, + ], +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/list.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/list.py new file mode 100644 index 00000000000..159445f9bdb --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/list.py @@ -0,0 +1,9 @@ +"""The look of lists: the browser's, with the marker the list asks for.""" + +from reflex_components_ui.style import ComponentStyles + +LIST: ComponentStyles = {} + +# What an ordered or unordered list is given when it is created: room for the +# markers. A list of neither kind has none to show. +MARKER_INDENT = "1.5rem" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/section.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/section.py new file mode 100644 index 00000000000..67995bbdb2d --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/section.py @@ -0,0 +1,18 @@ +"""The look of a section of a page.""" + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles + +SECTION: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "flex_shrink": "0", + }, + "variants": { + "size": { + "1": {"padding_top": tokens.space[5], "padding_bottom": tokens.space[5]}, + "2": {"padding_top": tokens.space[7], "padding_bottom": tokens.space[7]}, + "3": {"padding_top": tokens.space[9], "padding_bottom": tokens.space[9]}, + }, + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py new file mode 100644 index 00000000000..72632bf9cca --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py @@ -0,0 +1,29 @@ +"""The look of a separator: a line between two things.""" + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles + +# The length of the line, which both orientations read. +_SIZE = "--separator-size" + +SEPARATOR: ComponentStyles = { + "base": { + "display": "block", + # Gray unless the separator has a color of its own. + "background_color": tokens.gray.a[6], + }, + "variants": { + "orientation": { + "horizontal": {"width": f"var({_SIZE})", "height": "1px"}, + "vertical": {"width": "1px", "height": f"var({_SIZE})"}, + }, + "size": { + "1": {_SIZE: tokens.space[4]}, + "2": {_SIZE: tokens.space[6]}, + "3": {_SIZE: tokens.space[9]}, + "4": {_SIZE: "100%"}, + }, + "color_scheme": {"true": {"background_color": tokens.accent.a[6]}}, + }, + "defaults": {"orientation": "horizontal"}, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py index dd60d56a5eb..6c7aeedcf0b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py @@ -1,46 +1,33 @@ -"""The look of text.""" +"""The look of text, and of the inline elements that mark it up.""" from typing import Any from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.typography import ( - ACCENT_SCOPE, - ACCENT_SCOPE_HIGH_CONTRAST, - ACCENT_TEXT, ALIGN, + COLOR, + COLOR_HIGH_CONTRAST, + SIZE, + TRIM, WEIGHT, - trim, ) -# The line height and the letter spacing are custom properties, so that text -# and code inside the element follow its size. -SIZE: dict[str, Any] = { - str(step): { - "font_size": tokens.font_size[step], - "--line-height": tokens.line_height[step], - "--letter-spacing": tokens.letter_spacing[step], - } - for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) +# What every element that is text has, a link and a quotation among them. +TEXT_BASE: dict[str, Any] = { + "margin": "0", + "line_height": f"var(--line-height, {tokens.default.line_height})", + "letter_spacing": "var(--letter-spacing, inherit)", } TEXT: ComponentStyles = { - "base": { - "margin": "0", - "line_height": f"var(--line-height, {tokens.default.line_height})", - "letter_spacing": "var(--letter-spacing, inherit)", - }, + "base": TEXT_BASE, "variants": { "size": SIZE, "weight": WEIGHT, "align": ALIGN, - "trim": trim( - f"var(--leading-trim-start, {tokens.default.leading_trim_start})", - f"var(--leading-trim-end, {tokens.default.leading_trim_end})", - ), - "color_scheme": {"true": {**ACCENT_SCOPE, "color": tokens.accent.a[11]}}, - # Inside an element with a color; no declaration otherwise. - "high_contrast": {"true": {"color": f"var({ACCENT_TEXT})"}}, + "trim": TRIM, + **COLOR, "as_": { "label": { "@media (pointer: coarse)": { @@ -55,10 +42,41 @@ }, }, }, - "compound": [ - { - "props": {"color_scheme": "true", "high_contrast": "true"}, - "style": {**ACCENT_SCOPE_HIGH_CONTRAST, "color": tokens.accent[12]}, + "compound": [COLOR_HIGH_CONTRAST], +} + + +def _inline(element: Any, **style: Any) -> ComponentStyles: + """Make the look of an inline element from its typography tokens. + + Args: + element: The tokens of the element. + **style: What the element has beside its font. + + Returns: + The style table. + """ + return { + "base": { + "font_family": element.font_family, + "font_size": f"calc({element.font_size_adjust} * 1em)", + "font_style": element.font_style, + "font_weight": element.font_weight, + "letter_spacing": ( + f"calc({element.letter_spacing} + " + f"var(--letter-spacing, {tokens.default.letter_spacing}))" + ), + **style, }, - ], + } + + +_BOXED: dict[str, Any] = { + "box_sizing": "border-box", + "line_height": "1.25", + "color": "inherit", } + +EM: ComponentStyles = _inline(tokens.em, **_BOXED) +STRONG: ComponentStyles = _inline(tokens.strong) +QUOTE: ComponentStyles = _inline(tokens.quote, **_BOXED) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py index 7e029a6cc46..86ef78770af 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py @@ -11,16 +11,37 @@ # Themes does through `[data-accent-color]` ancestor selectors: a class on an # element cannot select by ancestor, so the ancestor hands down the values. # High-contrast text without a color takes the first, a link without a color -# the other two. +# the others. ACCENT_TEXT = "--rx-accent-text" ACCENT_LINK = "--rx-accent-link" ACCENT_LINK_LINE = "--rx-accent-link-line" +ACCENT_LINK_LINE_COLOR = "--rx-accent-link-line-color" + +# The same from a link to the code inside it: what the code shows under the +# pointer, by its variant. +LINK_CODE_SOLID = "--rx-link-code-solid" +LINK_CODE_SOFT = "--rx-link-code-soft" +LINK_CODE_OUTLINE = "--rx-link-code-outline" + + +def underline_color(step: int) -> str: + """Mix the color of the line under a link, which keeps bright colors legible. + + Args: + step: The translucent step of the accent. + + Returns: + The color. + """ + return f"color-mix(in oklab, {tokens.accent.a[step]}, {tokens.gray.a[6]})" + # The styles of `color_scheme`, for the "true" value of its variant. ACCENT_SCOPE: dict[str, Any] = { ACCENT_TEXT: tokens.accent[12], ACCENT_LINK: tokens.accent[12], ACCENT_LINK_LINE: "underline", + ACCENT_LINK_LINE_COLOR: underline_color(6), } # The same for an element that is high contrast too: links inside keep their @@ -28,6 +49,7 @@ ACCENT_SCOPE_HIGH_CONTRAST: dict[str, Any] = { ACCENT_LINK: None, ACCENT_LINK_LINE: None, + ACCENT_LINK_LINE_COLOR: None, } WEIGHT: dict[str, StyleProps] = { @@ -44,31 +66,52 @@ } -def trim(start: str, end: str) -> dict[str, StyleProps]: - """Make the variants of the trim prop: the leading above and below a text. +# The line height and the letter spacing of a size are custom properties, so +# that text and code inside the element follow them. +SIZE: dict[str, Any] = { + str(step): { + "font_size": tokens.font_size[step], + "--line-height": tokens.line_height[step], + "--letter-spacing": tokens.letter_spacing[step], + } + for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) +} - Args: - start: What to take off above the first line. - end: What to take off below the last line. +# Half of the leading is taken off by a pseudo-element with a negative margin. +# A heading sets the two custom properties to the trim of its own font. +_HALF_LEADING = f"var(--line-height, calc(1em * {tokens.default.line_height})) / 2" +_NO_TRIM: Any = {"content": "none"} +_TRIM_START: Any = { + "content": "''", + "display": "table", + "margin_bottom": ( + f"calc(var(--leading-trim-start, {tokens.default.leading_trim_start})" + f" - {_HALF_LEADING})" + ), +} +_TRIM_END: Any = { + "content": "''", + "display": "table", + "margin_top": ( + f"calc(var(--leading-trim-end, {tokens.default.leading_trim_end})" + f" - {_HALF_LEADING})" + ), +} +TRIM: dict[str, StyleProps] = { + "normal": {"_before": _NO_TRIM, "_after": _NO_TRIM}, + "start": {"_before": _TRIM_START, "_after": _NO_TRIM}, + "end": {"_before": _NO_TRIM, "_after": _TRIM_END}, + "both": {"_before": _TRIM_START, "_after": _TRIM_END}, +} - Returns: - The styles of each value of the prop. - """ - half_leading = f"var(--line-height, calc(1em * {tokens.default.line_height})) / 2" - none: Any = {"content": "none"} - before: Any = { - "content": "''", - "display": "table", - "margin_bottom": f"calc({start} - {half_leading})", - } - after: Any = { - "content": "''", - "display": "table", - "margin_top": f"calc({end} - {half_leading})", - } - return { - "normal": {"_before": none, "_after": none}, - "start": {"_before": before, "_after": none}, - "end": {"_before": none, "_after": after}, - "both": {"_before": before, "_after": after}, - } +# The color of text with a color of its own, for the variants of +# `color_scheme` and `high_contrast` and their compound style. +COLOR: dict[str, dict[str, Any]] = { + "color_scheme": {"true": {**ACCENT_SCOPE, "color": tokens.accent.a[11]}}, + # Inside an element with a color; no declaration anywhere else. + "high_contrast": {"true": {"color": f"var({ACCENT_TEXT})"}}, +} +COLOR_HIGH_CONTRAST: Any = { + "props": {"color_scheme": "true", "high_contrast": "true"}, + "style": {**ACCENT_SCOPE_HIGH_CONTRAST, "color": tokens.accent[12]}, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/blockquote.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/blockquote.py new file mode 100644 index 00000000000..882f3c683e6 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/blockquote.py @@ -0,0 +1,41 @@ +"""A block quotation.""" + +from __future__ import annotations + +from typing import ClassVar + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.blockquote import BLOCKQUOTE +from reflex_components_ui.themes import LiteralAccentColor +from reflex_components_ui.typography.base import LiteralTextSize, LiteralTextWeight + + +class Blockquote(UIComponent, elements.Blockquote): + """A block level extended quotation.""" + + tag = "blockquote" + + styles: ClassVar[ComponentStyles] = BLOCKQUOTE + + size: Var[Responsive[LiteralTextSize]] = field(doc='Text size: "1" - "9"') + + weight: Var[Responsive[LiteralTextWeight]] = field( + doc='Thickness of text: "light" | "regular" | "medium" | "bold"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Overrides the accent color inherited from the Theme." + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the text with higher contrast color" + ) + + +blockquote = Blockquote.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/code.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/code.py new file mode 100644 index 00000000000..d90bfdbe9db --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/code.py @@ -0,0 +1,63 @@ +"""Inline code.""" + +from __future__ import annotations + +from typing import Any, ClassVar + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.markdown_component_map import MarkdownComponentMap +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.props import LiteralVariant +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.code import CODE +from reflex_components_ui.themes import LiteralAccentColor +from reflex_components_ui.typography.base import LiteralTextSize, LiteralTextWeight + + +class Code(UIComponent, elements.Code, MarkdownComponentMap): + """A block level extended quotation.""" + + tag = "code" + + styles: ClassVar[ComponentStyles] = CODE + + variant: Var[LiteralVariant] = field( + doc='The visual variant to apply: "solid" | "soft" | "outline" | "ghost"' + ) + + size: Var[Responsive[LiteralTextSize]] = field(doc='Text size: "1" - "9"') + + weight: Var[Responsive[LiteralTextWeight]] = field( + doc='Thickness of text: "light" | "regular" | "medium" | "bold"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Overrides the accent color inherited from the Theme." + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the text with higher contrast color" + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create inline code. + + Args: + *children: The children of the component. + **props: The props of the component. + + Returns: + The code, which tells a link around it which variant it is: a + link hides its underline under code that has a background. + """ + custom_attrs: dict[str, Any] = props.setdefault("custom_attrs", {}) + custom_attrs.setdefault("data-variant", props.get("variant", "soft")) + return super().create(*children, **props) + + +code = Code.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/heading.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/heading.py new file mode 100644 index 00000000000..e7a07acd3b9 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/heading.py @@ -0,0 +1,72 @@ +"""A heading.""" + +from __future__ import annotations + +from typing import ClassVar + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.markdown_component_map import MarkdownComponentMap +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.heading import HEADING +from reflex_components_ui.themes import LiteralAccentColor +from reflex_components_ui.typography.base import ( + LiteralTextAlign, + LiteralTextSize, + LiteralTextTrim, + LiteralTextWeight, +) + + +class Heading(UIComponent, elements.H1, MarkdownComponentMap): + """A foundational text primitive based on the element.""" + + tag = "h1" + + styles: ClassVar[ComponentStyles] = HEADING + + _as_tags: ClassVar[frozenset[str]] = frozenset(( + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + )) + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + as_: Var[str] = field( + doc="Change the default rendered element into a semantically appropriate alternative (cannot be used with asChild)" + ) + + size: Var[Responsive[LiteralTextSize]] = field(doc='Text size: "1" - "9"') + + weight: Var[Responsive[LiteralTextWeight]] = field( + doc='Thickness of text: "light" | "regular" | "medium" | "bold"' + ) + + align: Var[Responsive[LiteralTextAlign]] = field( + doc='Alignment of text in element: "left" | "center" | "right"' + ) + + trim: Var[Responsive[LiteralTextTrim]] = field( + doc='Removes the leading trim space: "normal" | "start" | "end" | "both"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Overrides the accent color inherited from the Theme." + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the text with higher contrast color" + ) + + +heading = Heading.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/link.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/link.py new file mode 100644 index 00000000000..32eb41795dd --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/link.py @@ -0,0 +1,117 @@ +"""A link, which navigates within the app without loading a page.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import Component, MemoizationLeaf, field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.cond import cond +from reflex_components_core.core.markdown_component_map import MarkdownComponentMap +from reflex_components_core.el.elements.inline import A +from reflex_components_core.react_router.dom import ReactRouterLink + +from reflex_components_ui import tokens +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.link import LINK +from reflex_components_ui.themes import LiteralAccentColor +from reflex_components_ui.typography.base import ( + LiteralTextSize, + LiteralTextTrim, + LiteralTextWeight, +) + +LiteralLinkUnderline = Literal["auto", "hover", "always", "none"] + +_KNOWN_REACT_ROUTER_LINK_PROPS = frozenset(ReactRouterLink.get_props()) + + +class Link(UIComponent, A, MemoizationLeaf, MarkdownComponentMap): + """A semantic element for navigation between pages.""" + + tag = "a" + + styles: ClassVar[ComponentStyles] = LINK + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + size: Var[Responsive[LiteralTextSize]] = field(doc='Text size: "1" - "9"') + + weight: Var[Responsive[LiteralTextWeight]] = field( + doc='Thickness of text: "light" | "regular" | "medium" | "bold"' + ) + + trim: Var[Responsive[LiteralTextTrim]] = field( + doc='Removes the leading trim space: "normal" | "start" | "end" | "both"' + ) + + underline: Var[LiteralLinkUnderline] = field( + doc='Sets the visibility of the underline affordance: "auto" | "hover" | "always" | "none"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Overrides the accent color inherited from the Theme." + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the text with higher contrast color" + ) + + is_external: Var[bool] = field(doc="If True, the link will open in a new tab") + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a Link component. + + Args: + *children: The children of the component. + **props: The props of the component. + + Returns: + Component: The link component + + Raises: + ValueError: in case of missing children + """ + props.setdefault("_hover", {"color": tokens.accent[8]}) + href = props.get("href") + + is_external = props.pop("is_external", None) + + if is_external is not None: + props["target"] = cond(is_external, "_blank", "") + + if href is not None: + if not len(children): + msg = "Link without a child will not display" + raise ValueError(msg) + + if "as_child" not in props: + # Extract props for the ReactRouterLink, the rest go to the Link/A element. + react_router_link_props = {} + for prop in props.copy(): + if prop in _KNOWN_REACT_ROUTER_LINK_PROPS: + react_router_link_props[prop] = props.pop(prop) + + react_router_link_props["to"] = react_router_link_props.pop( + "href", href + ) + + # Without `as_child`, the link of the router is the element: + # an internal navigation does not load the page again. + return super().create( + ReactRouterLink.create(*children, **react_router_link_props), + as_child=True, + **props, + ) + else: + props["href"] = "#" + + return super().create(*children, **props) + + +link = Link.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py index 1a336c042df..b6d1b16aec2 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py @@ -4,7 +4,7 @@ from typing import ClassVar, Literal -from reflex_base.components.component import field +from reflex_base.components.component import ComponentNamespace, field from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.core.markdown_component_map import MarkdownComponentMap @@ -12,7 +12,7 @@ from reflex_components_ui.base import UIComponent from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.text import TEXT +from reflex_components_ui.styles.text import EM, QUOTE, STRONG, TEXT from reflex_components_ui.themes import LiteralAccentColor from reflex_components_ui.typography.base import ( LiteralTextAlign, @@ -84,4 +84,44 @@ class Text(UIComponent, elements.Span, MarkdownComponentMap): ) -text = Text.create +class Span(Text): + """A variant of text rendering as element.""" + + as_: Var[LiteralType] = Var.create("span") + + +class Em(UIComponent, elements.Em): + """Marks text to stress emphasis.""" + + tag = "em" + + styles: ClassVar[ComponentStyles] = EM + + +class Quote(UIComponent, elements.Q): + """A short inline quotation.""" + + tag = "q" + + styles: ClassVar[ComponentStyles] = QUOTE + + +class Strong(UIComponent, elements.Strong): + """Marks text to signify strong importance.""" + + tag = "strong" + + styles: ClassVar[ComponentStyles] = STRONG + + +class TextNamespace(ComponentNamespace): + """Text and the inline elements that mark it up.""" + + __call__ = staticmethod(Text.create) + em = staticmethod(Em.create) + quote = staticmethod(Quote.create) + strong = staticmethod(Strong.create) + span = staticmethod(Span.create) + + +text = TextNamespace() diff --git a/tests/units/reflex_components_ui/style/test_merge.py b/tests/units/reflex_components_ui/style/test_merge.py index a445b37964a..431d7cb7b44 100644 --- a/tests/units/reflex_components_ui/style/test_merge.py +++ b/tests/units/reflex_components_ui/style/test_merge.py @@ -480,7 +480,7 @@ def test_table_is_lowered_again_when_the_breakpoints_change(): None, ( 'rx.ui.card: unknown key "variant" in a style table. Use "base", ' - '"variants", "compound" or "parts".' + '"variants", "defaults", "compound" or "parts".' ), ), ( From ec449719e85fe445ca58cde74832e5c2b9639674 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:08:33 +0000 Subject: [PATCH 032/204] WIP: news, stubs, integration test, type fixes Claude-Session: https://claude.ai/code/session_014AwvTP2WjJKEVdjMR1jQ6p --- news/+emotion-free-pages.performance.md | 1 + .../news/+emotion-free-pages.performance.md | 1 + .../src/reflex_base/compiler/templates.py | 34 ++++++++++++------- .../+chrome-without-emotion.performance.md | 1 + pyi_hashes.json | 6 ++-- reflex/compiler/utils.py | 7 ++-- .../tests_playwright/test_ui_components.py | 25 ++++++++++++++ .../reflex_base/components/test_dynamic.py | 4 ++- .../base/test_error_boundary.py | 3 +- 9 files changed, 62 insertions(+), 20 deletions(-) create mode 100644 news/+emotion-free-pages.performance.md create mode 100644 packages/reflex-base/news/+emotion-free-pages.performance.md create mode 100644 packages/reflex-components-core/news/+chrome-without-emotion.performance.md diff --git a/news/+emotion-free-pages.performance.md b/news/+emotion-free-pages.performance.md new file mode 100644 index 00000000000..51bb56887ff --- /dev/null +++ b/news/+emotion-free-pages.performance.md @@ -0,0 +1 @@ +Pages, memoized components and the app root import Emotion only when one of their components renders a `css` prop (a `style` on `rx.el.*`, `rx.box` and other Emotion-backed components, or an app-level `style`); every other generated module calls React's `createElement`. An app with no such style, such as one built from `rx.ui`, no longer ships Emotion: about 8 kB less gzipped JavaScript. Dynamic components load Emotion on demand when they need it. diff --git a/packages/reflex-base/news/+emotion-free-pages.performance.md b/packages/reflex-base/news/+emotion-free-pages.performance.md new file mode 100644 index 00000000000..6f50caea3ac --- /dev/null +++ b/packages/reflex-base/news/+emotion-free-pages.performance.md @@ -0,0 +1 @@ +A component asks for Emotion's `jsx` through its imports only when the element it renders has a `css` prop, and generated modules otherwise import React's `createElement` as `jsx`. Code that generates a module of its own from `Component._get_all_imports()` keeps working unchanged; `Imports.EMOTION_JSX` and `Imports.REACT_JSX` name the two imports. diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 89167c63acc..d0d40032f3d 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -77,7 +77,7 @@ def _merge_state_hooks( (_EMOTION_JSX,) = (var.name for var in Imports.EMOTION_JSX["@emotion/react"]) -def _with_emotion_jsx(imports: list[_ImportDict]) -> list[_ImportDict]: +def _with_emotion_jsx(imports: Iterable[_ImportDict]) -> list[_ImportDict]: """Make ``jsx`` Emotion's in the imports of a module where it is React's. Args: @@ -87,23 +87,31 @@ def _with_emotion_jsx(imports: list[_ImportDict]) -> list[_ImportDict]: The imports, unchanged for a module that does not import React's ``createElement`` as ``jsx``. """ - if not any( - module["lib"] == "react" and _REACT_JSX in module["rest"] for module in imports - ): - return imports - emotion: _ImportDict = {"lib": "@emotion/react", "default": "", "rest": []} swapped: list[_ImportDict] = [] + emotion: int | None = None + is_react_jsx = False for module in imports: - if module["lib"] == "react": - module = { - **module, + if module["lib"] == "react" and _REACT_JSX in module["rest"]: + is_react_jsx = True + module: _ImportDict = { + "lib": "react", + "default": module["default"], "rest": [name for name in module["rest"] if name != _REACT_JSX], } elif module["lib"] == "@emotion/react": - emotion = module - continue + emotion = len(swapped) swapped.append(module) - swapped.append({**emotion, "rest": [*emotion["rest"], _EMOTION_JSX]}) + if not is_react_jsx: + return swapped + if emotion is None: + swapped.append({"lib": "@emotion/react", "default": "", "rest": [_EMOTION_JSX]}) + else: + module = swapped[emotion] + swapped[emotion] = { + "lib": "@emotion/react", + "default": module["default"], + "rest": [*module["rest"], _EMOTION_JSX], + } return swapped @@ -179,7 +187,7 @@ def get_import(module: _ImportDict) -> str: return f'import "{module["lib"]}"' @staticmethod - def get_imports(imports: list[_ImportDict], *code: str) -> str: + def get_imports(imports: Iterable[_ImportDict], *code: str) -> str: """Render the imports of a module, settling what it calls ``jsx``. Components ask for Emotion's ``jsx`` through their imports when they diff --git a/packages/reflex-components-core/news/+chrome-without-emotion.performance.md b/packages/reflex-components-core/news/+chrome-without-emotion.performance.md new file mode 100644 index 00000000000..59d4d696d35 --- /dev/null +++ b/packages/reflex-components-core/news/+chrome-without-emotion.performance.md @@ -0,0 +1 @@ +The connection indicator (`rx.connection_pulser`), the "Built with Reflex" badge and the default error boundary fallback are styled by class names and a small stylesheet rendered with them instead of `css` props, so they no longer pull Emotion into an app. They look the same; style props passed to `rx.connection_pulser` still override the defaults. diff --git a/pyi_hashes.json b/pyi_hashes.json index e7dc52b6829..7c86fcb5dfd 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -6,7 +6,7 @@ "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": "04d20bcfba980db936b2e88974e0b02c", - "packages/reflex-components-core/src/reflex_components_core/base/error_boundary.pyi": "2bec3beeafea96787d10838d73e47bdc", + "packages/reflex-components-core/src/reflex_components_core/base/error_boundary.pyi": "bbb90ef9de18bcef6fb110e1ee6a9877", "packages/reflex-components-core/src/reflex_components_core/base/fragment.pyi": "04de5816bc98f33bbf14370af7f787b3", "packages/reflex-components-core/src/reflex_components_core/base/link.pyi": "d39ded31424a9af8532b9d4eb0ce8abf", "packages/reflex-components-core/src/reflex_components_core/base/meta.pyi": "c0e97a357ac2521c9b1c48b9368513e7", @@ -14,12 +14,12 @@ "packages/reflex-components-core/src/reflex_components_core/base/strict_mode.pyi": "135dd395a27f01be303b3879ece179c1", "packages/reflex-components-core/src/reflex_components_core/core/__init__.pyi": "931b222daf3755f67281b6c4d7155f85", "packages/reflex-components-core/src/reflex_components_core/core/auto_scroll.pyi": "2d83dc211884423496c31d372d3f3734", - "packages/reflex-components-core/src/reflex_components_core/core/banner.pyi": "85ff5f20fc7a59de5544858cfc364cf1", + "packages/reflex-components-core/src/reflex_components_core/core/banner.pyi": "ec83e96514332e998c3923c9dfff9349", "packages/reflex-components-core/src/reflex_components_core/core/clipboard.pyi": "21d51b69ab11279e864f7aca9307462f", "packages/reflex-components-core/src/reflex_components_core/core/debounce.pyi": "86b2bea0aeec5334dbb64b3addae91df", "packages/reflex-components-core/src/reflex_components_core/core/helmet.pyi": "a43533eba05dec1ece2602bd64ca0f01", "packages/reflex-components-core/src/reflex_components_core/core/html.pyi": "bedb5c94e690d50721ddc7bfdfbe8a25", - "packages/reflex-components-core/src/reflex_components_core/core/sticky.pyi": "a910d65f42f620531c959677d22977cb", + "packages/reflex-components-core/src/reflex_components_core/core/sticky.pyi": "d14c16775c159f674975f8989becefb8", "packages/reflex-components-core/src/reflex_components_core/core/upload.pyi": "d903297d188fe6fe56a824127e0db925", "packages/reflex-components-core/src/reflex_components_core/core/window_events.pyi": "3e39f7b3282570da5d2d3ac503d1f278", "packages/reflex-components-core/src/reflex_components_core/datadisplay/__init__.pyi": "fd3cea1f1a221ed3404c28ec4fec7b3c", diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index 267a5f183c6..eda4a18d094 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -148,8 +148,11 @@ def _resolve_jsx_import(import_dict: ParsedImportDict) -> None: Args: import_dict: The collapsed imports of one module, updated in place. """ - if _EMOTION_JSX in import_dict.get("@emotion/react", ()) and _REACT_JSX in ( - react_imports := import_dict.get("react", ()) + react_imports = import_dict.get("react") + if ( + react_imports + and _REACT_JSX in react_imports + and _EMOTION_JSX in import_dict.get("@emotion/react", ()) ): react_imports.remove(_REACT_JSX) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 1efb35a6652..a30ccd0df4d 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -460,6 +460,31 @@ def test_no_page_ships_the_stylex_runtime(prod_app: AppHarness): ), table +def test_no_script_ships_emotion(prod_app: AppHarness, page: Page): + """An app built from rx.ui has no ``css`` prop, so nothing imports Emotion. + + Neither do the parts every app with state gets from Reflex itself: the + connection indicator and the error boundary are styled by a stylesheet + React keeps in the document head. + """ + scripts = _scripts(prod_app) + assert [ + name + for name, code in scripts.items() + if re.search(r"emotion", name + code, re.IGNORECASE) + ] == [] + + page.goto(_styled_url(prod_app)) + expect(page.locator("#var")).to_have_css("width", "100px") + assert page.locator(".rx-connection-pulser").evaluate( + """(pulser) => { + const style = getComputedStyle(pulser); + return [style.position, style.height]; + }""" + ) == ["fixed", "0px"] + assert page.locator("style[data-emotion]").count() == 0 + + def _digests(files: dict[str, bytes]) -> dict[str, str]: """Reduce files to what tells two versions of one apart. diff --git a/tests/units/reflex_base/components/test_dynamic.py b/tests/units/reflex_base/components/test_dynamic.py index f294bbdc110..58b4507283d 100644 --- a/tests/units/reflex_base/components/test_dynamic.py +++ b/tests/units/reflex_base/components/test_dynamic.py @@ -201,7 +201,9 @@ def _dynamic_module_head(component: Component) -> list[str]: Returns: The lines of its module up to the component function. """ - lines = serialize(component).splitlines() + code = serialize(component) + assert isinstance(code, str) + lines = code.splitlines() return [ line for line in lines[: lines.index("export default function MySSRComponent () {")] diff --git a/tests/units/reflex_components_core/base/test_error_boundary.py b/tests/units/reflex_components_core/base/test_error_boundary.py index cd9da556675..245516ea281 100644 --- a/tests/units/reflex_components_core/base/test_error_boundary.py +++ b/tests/units/reflex_components_core/base/test_error_boundary.py @@ -70,4 +70,5 @@ def test_default_fallback_is_styled_without_a_css_prop(): "react-error-boundary@6.1.6", "react-router", ] - assert str(boundary.fallback_render) == FALLBACK + fallback, _on_error = boundary.render()["props"] + assert fallback == f"fallbackRender:{FALLBACK}" From 0cad8c553d17d3fabf278fa5f8168735b1b5eb44 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:10:00 +0000 Subject: [PATCH 033/204] Add the parity matrices and contracts of the layout and typography wave; follow compile-time styles in rx.ui merges Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- .../ui_parity/components/aspect_ratio.py | 91 ++++++++++ .../parity/ui_parity/components/blockquote.py | 77 +++++++++ .../parity/ui_parity/components/center.py | 75 ++++++++ .../parity/ui_parity/components/code.py | 108 ++++++++++++ .../parity/ui_parity/components/container.py | 78 +++++++++ .../parity/ui_parity/components/flex.py | 10 +- .../parity/ui_parity/components/grid.py | 95 ++++++++++ .../parity/ui_parity/components/heading.py | 112 ++++++++++++ .../parity/ui_parity/components/hstack.py | 89 ++++++++++ .../parity/ui_parity/components/inset.py | 125 ++++++++++++++ .../parity/ui_parity/components/link.py | 163 ++++++++++++++++++ .../parity/ui_parity/components/list.py | 131 ++++++++++++++ .../parity/ui_parity/components/section.py | 70 ++++++++ .../parity/ui_parity/components/separator.py | 66 +++++++ .../parity/ui_parity/components/spacer.py | 95 ++++++++++ .../parity/ui_parity/components/stack.py | 89 ++++++++++ .../parity/ui_parity/components/text.py | 23 ++- .../parity/ui_parity/components/vstack.py | 89 ++++++++++ .../parity/ui_parity/samples.py | 63 +++++++ .../src/reflex_components_ui/base.py | 93 +++++++--- .../src/reflex_components_ui/style/merge.py | 3 +- .../src/reflex_components_ui/styles/link.py | 3 + scripts/ui_parity.py | 5 +- tests/units/test_ui_parity_script.py | 2 +- 24 files changed, 1707 insertions(+), 48 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/aspect_ratio.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/blockquote.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/center.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/code.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/container.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/grid.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/heading.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/hstack.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/inset.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/link.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/list.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/section.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/separator.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/spacer.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/stack.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/vstack.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/samples.py diff --git a/packages/reflex-components-ui/parity/ui_parity/components/aspect_ratio.py b/packages/reflex-components-ui/parity/ui_parity/components/aspect_ratio.py new file mode 100644 index 00000000000..1ee349f3354 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/aspect_ratio.py @@ -0,0 +1,91 @@ +"""The aspect ratio: a box whose height follows its width.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + + +def _aspect_ratio(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a box of a ratio whose content fills it. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The box. + """ + return namespace.aspect_ratio( + rx.el.div( + "16:9", + style={ + "width": "100%", + "height": "100%", + "background_color": "rgba(128, 128, 128, 0.4)", + }, + ), + **props, + ) + + +MATRIX = Matrix( + component="aspect_ratio", + render=_aspect_ratio, + sweep={ + "ratio": { + "square": 1, + "wide": 16 / 9, + "classic": 4 / 3, + "tall": 0.75, + "whole": 2, + }, + "style": {"rounded": {"border_radius": "12px", "overflow": "hidden"}}, + "appearance": [DARK], + "viewport": [520], + }, + stage=(232, 320), + target=":scope > div > div", + crop="stage", + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="aspect_ratio", + render=lambda namespace: namespace.box( + namespace.aspect_ratio(namespace.box("content"), ratio=2, id="ratio"), + style={"width": "300px"}, + ), +) + + +@CONTRACT.step("is a div inside the frame that sizes it", on=SERVER) +def _server_render(run: Run) -> None: + ratio = run.server.element("ratio") + assert (ratio.tag, ratio.text) == ("div", "content") + + +@CONTRACT.step("keeps its ratio with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + _keeps_its_ratio(run) + + +@CONTRACT.step("keeps its ratio after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + _keeps_its_ratio(run) + + +def _keeps_its_ratio(run: Run) -> None: + """Check that the box is twice as wide as it is high. + + Args: + run: The run of the step. + """ + box = run.page.locator("#ratio").bounding_box() + assert box is not None + assert (box["width"], box["height"]) == (300, 150) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/blockquote.py b/packages/reflex-components-ui/parity/ui_parity/components/blockquote.py new file mode 100644 index 00000000000..4ab3cdae415 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/blockquote.py @@ -0,0 +1,77 @@ +"""The block quotation: text with a rule beside it.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import ACCENTS, PARAGRAPH + + +def _blockquote(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a quotation that wraps over several lines. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The quotation. + """ + return namespace.blockquote(PARAGRAPH, **props) + + +MATRIX = Matrix( + component="blockquote", + render=_blockquote, + cross={ + "size": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + "weight": ["light", "regular", "medium", "bold"], + }, + sweep={ + "color_scheme": ACCENTS, + "high_contrast": [True], + "size": {"responsive": rx.breakpoints(initial="1", sm="5", lg="3")}, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "color_scheme": ["ruby", "gray"], + "high_contrast": [True], + "appearance": ["light", DARK], + }, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="5", lg="3")}, + "viewport": [520, 800, 1280], + }, + ], + stage=(300, 260), +) + +CONTRACT = Contract( + component="blockquote", + render=lambda namespace: namespace.blockquote( + "Stay hungry", id="quote", cite="https://example.com/speech" + ), +) + + +@CONTRACT.step("is a blockquote with its source in the server render", on=SERVER) +def _server_render(run: Run) -> None: + quote = run.server.element("quote") + assert (quote.tag, quote.text) == ("blockquote", "Stay hungry") + assert quote.attributes["cite"] == "https://example.com/speech" + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#quote").inner_text() == "Stay hungry" + + +@CONTRACT.step("has the role of a blockquote after hydration", on=HYDRATED) +def _role(run: Run) -> None: + assert run.page.get_by_role("blockquote").get_attribute("id") == "quote" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/center.py b/packages/reflex-components-ui/parity/ui_parity/components/center.py new file mode 100644 index 00000000000..d0d5b8b6d38 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/center.py @@ -0,0 +1,75 @@ +"""The center: a flex container with its content in the middle.""" + +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, Matrix +from ui_parity.samples import tiles + + +def _center(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a center taller than its content. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The center. + """ + return namespace.center(*tiles(("quick", "brown", "fox")), **props) + + +MATRIX = Matrix( + component="center", + render=_center, + base={"style": {"height": "100px"}}, + sweep={ + "direction": ["row", "column"], + "spacing": ["2", "5"], + # Centering wins over both, as it does in rx. + "align": ["start", "end"], + "justify": ["start", "between"], + "wrap": ["wrap"], + "appearance": [DARK], + "viewport": [520], + }, + stage=(240, 140), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="center", + render=lambda namespace: namespace.center( + namespace.box("content", id="content"), + id="center", + style={"height": "200px"}, + ), +) + + +@CONTRACT.step("is a div in the server render", on=SERVER) +def _server_render(run: Run) -> None: + center = run.server.element("center") + assert (center.tag, center.text) == ("div", "content") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#content").is_visible() + + +@CONTRACT.step("holds its content in the middle after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + center = run.page.locator("#center").bounding_box() + content = run.page.locator("#content").bounding_box() + assert center is not None + assert content is not None + for start, length in (("x", "width"), ("y", "height")): + before = content[start] - center[start] + after = center[start] + center[length] - content[start] - content[length] + assert abs(before - after) <= 1 diff --git a/packages/reflex-components-ui/parity/ui_parity/components/code.py b/packages/reflex-components-ui/parity/ui_parity/components/code.py new file mode 100644 index 00000000000..06e179fca45 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/code.py @@ -0,0 +1,108 @@ +"""Inline code: variants, sizes, color, and code inside text and links.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, HOVER, Matrix +from ui_parity.samples import ACCENTS + + +def _code(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create inline code, alone or inside something that changes its look. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``inside`` names what is around the + code, at the size ``around`` gives. + + Returns: + The code, or what is around it. + """ + props = dict(props) + inside = props.pop("inside", None) + around = props.pop("around", "3") + code = namespace.code("uv run reflex", **props) + if inside == "text": + return namespace.text("Run ", code, " to start the app.", size=around) + if inside == "heading": + return namespace.heading("Run ", code, " first", size=around) + if inside == "link": + return namespace.text( + "See ", namespace.link(code, href="/docs"), " for more.", size=around + ) + return code + + +MATRIX = Matrix( + component="code", + render=_code, + cross={ + "variant": ["soft", "solid", "outline", "ghost"], + "size": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + }, + sweep={ + # Radix Themes has neither for code: both look like soft. + "variant": ["classic", "surface"], + "weight": ["light", "regular", "medium", "bold"], + "color_scheme": ACCENTS, + "high_contrast": [True], + "inside": ["text", "heading", "link"], + "size": {"responsive": rx.breakpoints(initial="1", sm="6", lg="3")}, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "variant": ["soft", "solid", "outline", "ghost"], + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + "appearance": ["light", DARK], + }, + { + "variant": ["soft", "solid", "outline", "ghost"], + "high_contrast": [True], + }, + { + "variant": ["soft", "solid", "outline", "ghost"], + "inside": ["text", "heading", "link"], + "around": ["2", "6"], + }, + { + "variant": ["soft", "solid", "outline", "ghost"], + "inside": [None, "link"], + "state": [HOVER], + }, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="6", lg="3")}, + "viewport": [520, 800, 1280], + }, + ], + stage=(300, 120), + target="code", + crop="stage", +) + +CONTRACT = Contract( + component="code", + render=lambda namespace: namespace.code("uv sync", id="code"), +) + + +@CONTRACT.step("is a code element in the server render", on=SERVER) +def _server_render(run: Run) -> None: + code = run.server.element("code") + assert (code.tag, code.text) == ("code", "uv sync") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#code").inner_text() == "uv sync" + + +@CONTRACT.step("has the role of code after hydration", on=HYDRATED) +def _role(run: Run) -> None: + assert run.page.get_by_role("code").get_attribute("id") == "code" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/container.py b/packages/reflex-components-ui/parity/ui_parity/components/container.py new file mode 100644 index 00000000000..81ab66eb105 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/container.py @@ -0,0 +1,78 @@ +"""The container: the width it bounds its content to.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import PARAGRAPH + + +def _container(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a container whose content shows the width it is given. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The container. + """ + return namespace.container( + rx.el.div(PARAGRAPH, style={"border": "1px solid currentColor"}), + **props, + ) + + +MATRIX = Matrix( + component="container", + render=_container, + sweep={ + "size": ["1", "2", "3", "4"], + "padding": ["0px", "32px"], + "style": {"background": {"background_color": "rgba(128, 128, 128, 0.2)"}}, + "appearance": [DARK], + }, + groups=[ + { + "size": {"responsive": rx.breakpoints(initial="1", sm="2", lg="4")}, + "viewport": [520, 800, 1280], + }, + ], + # Wider than the widest container. + stage=(1232, 96), + parts={"inner": ":scope > div > div"}, + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="container", + render=lambda namespace: namespace.container( + namespace.box("content", id="content"), id="container", size="1" + ), +) + + +@CONTRACT.step("wraps its content in a div in the server render", on=SERVER) +def _server_render(run: Run) -> None: + container = run.server.element("container") + assert (container.tag, container.text) == ("div", "content") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#content").is_visible() + + +@CONTRACT.step("bounds and centers its content after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + container = run.page.locator("#container").bounding_box() + inner = run.page.locator("#container > div").bounding_box() + assert container is not None + assert inner is not None + assert inner["width"] == 448 + assert inner["x"] - container["x"] == (container["width"] - 448) / 2 diff --git a/packages/reflex-components-ui/parity/ui_parity/components/flex.py b/packages/reflex-components-ui/parity/ui_parity/components/flex.py index 79aba4062bf..0cad4571e4b 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/flex.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/flex.py @@ -8,6 +8,7 @@ import reflex as rx from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import tiles def _flex(namespace: Any, props: Mapping[str, Any]) -> Any: @@ -21,14 +22,7 @@ def _flex(namespace: Any, props: Mapping[str, Any]) -> Any: The container. """ return namespace.flex( - *( - rx.el.div( - word, - style={"border": "1px solid currentColor", "padding": "2px 6px"}, - ) - for word in ("The", "quick", "brown", "fox", "jumps", "over", "lazy") - ), - **props, +*tiles(), **props ) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/grid.py b/packages/reflex-components-ui/parity/ui_parity/components/grid.py new file mode 100644 index 00000000000..8cc28298174 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/grid.py @@ -0,0 +1,95 @@ +"""The grid container: tracks, flow, alignment and gaps.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import tiles + + +def _grid(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a grid of more children than one row holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The grid. + """ + return namespace.grid(*tiles(), **props) + + +MATRIX = Matrix( + component="grid", + render=_grid, + cross={ + "columns": ["1", "2", "3", "4"], + "spacing": ["0", "2", "5"], + }, + sweep={ + "columns": {"lengths": "60px 1fr", "repeat": "repeat(3, 40px)"}, + "rows": ["2", "3", "repeat(4, 20px)"], + "flow": ["row", "column", "dense", "row-dense", "column-dense"], + "align": ["start", "center", "end", "baseline", "stretch"], + "justify": ["start", "center", "end", "between"], + "spacing": ["1", "3", "4", "6", "7", "8", "9"], + "spacing_x": ["1", "4", "9"], + "spacing_y": ["1", "4", "9"], + "style": {"sized": {"height": "140px", "padding": "4px"}}, + "appearance": [DARK], + }, + groups=[ + {"rows": ["3"], "flow": ["column", "column-dense"], "spacing": ["2"]}, + {"columns": ["3"], "spacing_x": ["4"], "spacing_y": ["1"]}, + { + "columns": {"sized": "repeat(3, 40px)"}, + "justify": ["center", "end", "between"], + }, + { + "columns": { + "responsive": rx.breakpoints(initial="1", xs="2", md="4", lg="3") + }, + "spacing": {"responsive": rx.breakpoints(initial="1", sm="4")}, + "viewport": [400, 600, 800, 1100, 1280], + }, + ], + stage=(260, 180), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="grid", + render=lambda namespace: namespace.grid( + namespace.box("one"), namespace.box("two"), id="grid", columns="2" + ), +) + + +@CONTRACT.step("is a div in the server render", on=SERVER) +def _server_render(run: Run) -> None: + grid = run.server.element("grid") + assert (grid.tag, grid.text) == ("div", "onetwo") + + +@CONTRACT.step("is a grid with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + grid = run.page.locator("#grid") + assert grid.is_visible() + assert grid.evaluate("element => getComputedStyle(element).display") == "grid" + + +@CONTRACT.step("lays its children out in two columns after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + boxes = run.page.locator("#grid > div") + first, second = boxes.nth(0).bounding_box(), boxes.nth(1).bounding_box() + assert first is not None + assert second is not None + assert first["y"] == second["y"] + assert first["width"] == second["width"] + assert second["x"] == first["x"] + first["width"] diff --git a/packages/reflex-components-ui/parity/ui_parity/components/heading.py b/packages/reflex-components-ui/parity/ui_parity/components/heading.py new file mode 100644 index 00000000000..ca1c7ff69df --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/heading.py @@ -0,0 +1,112 @@ +"""The heading: sizes, weights, alignment, trim, color and its level.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import ACCENTS + +TITLE = "The quick brown fox jumps over the lazy dog" + + +def _heading(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a heading that wraps over several lines. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell, ``nested`` naming what is inside. + + Returns: + The heading. + """ + props = dict(props) + nested = props.pop("nested", None) + if nested == "text": + return namespace.heading( + "The quick ", + namespace.text("brown fox", as_="span", weight="regular"), + " jumps over the lazy dog", + **props, + ) + if nested == "code": + return namespace.heading( + "The quick ", namespace.code("brown fox"), " jumps over", **props + ) + if nested == "high-contrast": + return namespace.heading( + "The quick ", + namespace.text("brown fox", as_="span", high_contrast=True), + " jumps over the lazy dog", + **props, + ) + return namespace.heading(TITLE, **props) + + +RESPONSIVE = rx.breakpoints(initial="2", sm="8", lg="4") + +MATRIX = Matrix( + component="heading", + render=_heading, + cross={ + "size": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + "weight": ["light", "regular", "medium", "bold"], + }, + sweep={ + "align": ["left", "center", "right"], + "trim": ["normal", "start", "end", "both"], + "as_": ["h1", "h2", "h3", "h4", "h5", "h6", "div"], + "color_scheme": ACCENTS, + "high_contrast": [True], + "nested": ["text", "code", "high-contrast"], + "size": {"responsive": RESPONSIVE}, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "color_scheme": ["ruby", "gray"], + "high_contrast": [True], + "appearance": ["light", DARK], + }, + {"color_scheme": ["ruby"], "nested": ["text", "code", "high-contrast"]}, + {"trim": ["both", "start", "end"], "size": ["2", "4", "8"]}, + {"nested": ["text", "code"], "size": ["2", "8"]}, + { + "size": {"responsive": RESPONSIVE}, + "trim": {"responsive": rx.breakpoints(initial="both", md="normal")}, + "align": {"responsive": rx.breakpoints(initial="center", sm="right")}, + "viewport": [520, 800, 1100, 1280], + }, + ], + stage=(300, 240), +) + +CONTRACT = Contract( + component="heading", + render=lambda namespace: namespace.box( + namespace.heading("Title", id="title"), + namespace.heading("Subtitle", as_="h2", id="subtitle"), + ), +) + + +@CONTRACT.step("is a heading of its level in the server render", on=SERVER) +def _server_render(run: Run) -> None: + title = run.server.element("title") + assert (title.tag, title.text) == ("h1", "Title") + assert run.server.element("subtitle").tag == "h2" + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#title").inner_text() == "Title" + + +@CONTRACT.step("has the role of a heading and its level", on=HYDRATED) +def _roles(run: Run) -> None: + assert run.page.get_by_role("heading", level=1).get_attribute("id") == "title" + assert run.page.get_by_role("heading", level=2).get_attribute("id") == "subtitle" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/hstack.py b/packages/reflex-components-ui/parity/ui_parity/components/hstack.py new file mode 100644 index 00000000000..49819361a86 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/hstack.py @@ -0,0 +1,89 @@ +"""The horizontal stack: a row with a gap between its children.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import tiles + + +def _hstack(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a stack of more children than one line holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The stack. + """ + return namespace.hstack(*tiles(), **props) + + +MATRIX = Matrix( + component="hstack", + render=_hstack, + sweep={ + "spacing": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], + "align": ["start", "center", "end", "baseline", "stretch"], + "justify": ["start", "center", "end", "between"], + "direction": ["row", "column", "row-reverse", "column-reverse"], + "wrap": ["nowrap", "wrap", "wrap-reverse"], + "class_name": ["mine"], + "style": {"sized": {"height": "120px", "width": "100%"}}, + "appearance": [DARK], + }, + groups=[ + {"wrap": ["wrap"], "spacing": ["1", "4"], "align": ["center", "end"]}, + { + "style": {"sized": {"height": "120px", "width": "100%"}}, + "justify": ["center", "between"], + "align": ["center", "stretch"], + }, + { + "direction": { + "responsive": rx.breakpoints(initial="column", sm="row", lg="column") + }, + "spacing": {"responsive": rx.breakpoints(initial="1", xs="5", md="2")}, + "align": {"responsive": rx.breakpoints(initial="end", md="center")}, + "viewport": [400, 600, 800, 1100, 1280], + }, + ], + stage=(240, 200), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="hstack", + render=lambda namespace: namespace.hstack( + namespace.box("one"), namespace.box("two"), id="stack" + ), +) + + +@CONTRACT.step("is a div with the class of a stack in the server render", on=SERVER) +def _server_render(run: Run) -> None: + stack = run.server.element("stack") + assert (stack.tag, stack.text) == ("div", "onetwo") + assert "rx-Stack" in (stack.attributes["class"] or "").split() + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#stack").is_visible() + + +@CONTRACT.step("lays its children out in a row, a gap apart", on=HYDRATED) +def _hydrated(run: Run) -> None: + boxes = run.page.locator("#stack > div") + first, second = boxes.nth(0).bounding_box(), boxes.nth(1).bounding_box() + assert first is not None + assert second is not None + # The default spacing is the third step of the space scale: 12px. + assert second["y"] == first["y"] + assert second["x"] == first["x"] + first["width"] + 12 diff --git a/packages/reflex-components-ui/parity/ui_parity/components/inset.py b/packages/reflex-components-ui/parity/ui_parity/components/inset.py new file mode 100644 index 00000000000..a9a3987482c --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/inset.py @@ -0,0 +1,125 @@ +"""The inset: content that reaches the edges of the card around it.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + + +def _inset(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create an inset inside a card, which says how far its edges are. + + The card is the Radix one for both systems: it sets the custom properties + an inset reads, and rx.ui has no card yet. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell, ``card`` holding those of the card. + + Returns: + The card. + """ + props = dict(props) + card = props.pop("card", {}) + return rx.card( + namespace.inset( + rx.el.div( + "The quick brown fox", + style={"background_color": "rgba(128, 128, 128, 0.4)"}, + ), + custom_attrs={"data-inset": ""}, + **props, + ), + rx.el.div("jumps over the lazy dog"), + **card, + ) + + +SIDES = ["x", "y", "top", "bottom", "right", "left"] + +MATRIX = Matrix( + component="inset", + render=_inset, + cross={ + "side": SIDES, + "clip": ["border-box", "padding-box"], + }, + sweep={ + "clip": ["border-box", "padding-box"], + "p": ["current", "0"], + "px": ["current", "0"], + "py": ["current", "0"], + "pt": ["current", "0"], + "pr": ["current", "0"], + "pb": ["current", "0"], + "pl": ["current", "0"], + "card": { + "size-1": {"size": "1"}, + "size-3": {"size": "3"}, + "classic": {"variant": "classic"}, + "ghost": {"variant": "ghost"}, + }, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"side": ["top", "x"], "p": ["current"], "clip": ["padding-box"]}, + { + "side": {"responsive": rx.breakpoints(initial="top", sm="x", lg="bottom")}, + "clip": { + "responsive": rx.breakpoints(initial="padding-box", md="border-box") + }, + "p": {"responsive": rx.breakpoints(initial="current", sm="0")}, + "viewport": [520, 800, 1100, 1280], + }, + ], + stage=(260, 140), + target="[data-inset]", + crop="stage", +) + +CONTRACT = Contract( + component="inset", + render=lambda namespace: rx.card( + namespace.inset(namespace.box("content"), id="inset", side="top"), + id="card", + ), +) + + +@CONTRACT.step("is a div in the server render", on=SERVER) +def _server_render(run: Run) -> None: + inset = run.server.element("inset") + assert (inset.tag, inset.text) == ("div", "content") + + +@CONTRACT.step("reaches the edges of the card with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + _reaches_the_edges(run) + + +@CONTRACT.step("reaches the edges of the card after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + _reaches_the_edges(run) + + +def _reaches_the_edges(run: Run) -> None: + """Check that the inset covers the padding of the card on three sides. + + Args: + run: The run of the step. + """ + card = run.page.locator("#card").bounding_box() + inset = run.page.locator("#inset").bounding_box() + assert card is not None + assert inset is not None + # All but the border of the card, which is one pixel. + assert (inset["x"], inset["y"], inset["width"]) == ( + card["x"] + 1, + card["y"] + 1, + card["width"] - 2, + ) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/link.py b/packages/reflex-components-ui/parity/ui_parity/components/link.py new file mode 100644 index 00000000000..89b901b513b --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/link.py @@ -0,0 +1,163 @@ +"""The link: its look in each state, and navigation without a page load.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, Matrix +from ui_parity.samples import ACCENTS + + +def _link(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a link, alone or inside text that changes its look. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``inside`` names the text around the + link, and ``holds`` what the link holds beside words. + + Returns: + The link, or the text around it. + """ + props = dict(props) + inside = props.pop("inside", None) + holds = props.pop("holds", None) + props.setdefault("href", "/docs") + if holds == "code": + link = namespace.link(namespace.code("rx.link"), **props) + elif holds == "code-and-words": + link = namespace.link("the ", namespace.code("rx.link"), " docs", **props) + else: + link = namespace.link("the quick brown fox", **props) + if inside == "text": + return namespace.text("See ", link, " for more.", size="5") + if inside == "colored": + return namespace.text("See ", link, " for more.", color_scheme="ruby") + if inside == "high-contrast": + return namespace.text( + "See ", link, " for more.", color_scheme="ruby", high_contrast=True + ) + return link + + +STATES = ["rest", HOVER, FOCUS_VISIBLE] + +MATRIX = Matrix( + component="link", + render=_link, + cross={ + "underline": ["auto", "hover", "always", "none"], + "state": STATES, + }, + sweep={ + "size": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + "weight": ["light", "regular", "medium", "bold"], + "trim": ["normal", "start", "end", "both"], + "color_scheme": ACCENTS, + "high_contrast": [True], + "inside": ["text", "colored", "high-contrast"], + "holds": ["code", "code-and-words"], + "is_external": [True], + "href": {"none": None, "external": "https://reflex.dev"}, + "size": {"responsive": rx.breakpoints(initial="1", sm="6", lg="3")}, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"high_contrast": [True], "state": STATES, "appearance": ["light", DARK]}, + { + "color_scheme": ["ruby", "gray"], + "high_contrast": [False, True], + "state": STATES, + }, + {"inside": ["text", "colored", "high-contrast"], "state": STATES}, + { + "inside": ["colored"], + "underline": ["hover", "always", "none"], + }, + {"inside": ["colored"], "color_scheme": ["blue"], "state": STATES}, + {"holds": ["code", "code-and-words"], "state": STATES}, + {"underline": ["always"], "appearance": [DARK], "state": STATES}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="6", lg="3")}, + "viewport": [520, 800, 1280], + }, + ], + stage=(300, 120), + target="a", + crop="stage", + properties=( + *Matrix.__dataclass_fields__["properties"].default, + "text-decoration-style", + "text-decoration-color", + "text-decoration-thickness", + "text-underline-offset", + ), +) + +CONTRACT = Contract( + component="link", + render=lambda namespace: namespace.box( + namespace.link("Parity pages", href="/", id="internal"), + namespace.link("Reflex", href="https://reflex.dev", id="external"), + namespace.link("New tab", href="/", is_external=True, id="new-tab"), + namespace.link("Nowhere", id="nowhere"), + ), +) + + +@CONTRACT.step("is an anchor with its address in the server render", on=SERVER) +def _server_render(run: Run) -> None: + internal = run.server.element("internal") + assert (internal.tag, internal.text) == ("a", "Parity pages") + assert internal.attributes["href"] == "/" + external = run.server.element("external") + assert (external.tag, external.attributes["href"]) == ("a", "https://reflex.dev") + assert run.server.element("new-tab").attributes["target"] == "_blank" + assert run.server.element("nowhere").attributes["href"] == "#" + + +@CONTRACT.step("is a plain link with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + link = run.page.locator("#internal") + assert link.is_visible() + link.click() + run.page.wait_for_url(lambda url: url.rstrip("/").count("/") == 2) + + +@CONTRACT.step("has the role and the name of a link", on=HYDRATED) +def _role(run: Run) -> None: + link = run.page.get_by_role("link", name="Parity pages") + assert link.get_attribute("id") == "internal" + + +@CONTRACT.step("Tab moves the focus through the links in order", on=HYDRATED) +def _tab(run: Run) -> None: + focused = [] + for _ in range(4): + run.page.keyboard.press("Tab") + focused.append(run.page.evaluate("document.activeElement.id")) + assert focused == ["internal", "external", "new-tab", "nowhere"] + assert run.page.locator("#nowhere").evaluate( + "element => element.matches(':focus-visible')" + ) + + +@CONTRACT.step("a click navigates without loading the page again", on=HYDRATED) +def _client_side_navigation(run: Run) -> None: + run.page.evaluate("window.loadedOnce = true") + run.page.locator("#internal").click() + run.page.wait_for_url(lambda url: url.rstrip("/").count("/") == 2) + assert run.page.evaluate("window.loadedOnce") is True + + +@CONTRACT.step("Enter follows the focused link without a page load", on=HYDRATED) +def _enter(run: Run) -> None: + run.page.evaluate("window.loadedOnce = true") + run.page.locator("#internal").focus() + run.page.keyboard.press("Enter") + run.page.wait_for_url(lambda url: url.rstrip("/").count("/") == 2) + assert run.page.evaluate("window.loadedOnce") is True diff --git a/packages/reflex-components-ui/parity/ui_parity/components/list.py b/packages/reflex-components-ui/parity/ui_parity/components/list.py new file mode 100644 index 00000000000..ca2c27c382d --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/list.py @@ -0,0 +1,131 @@ +"""Lists: ordered, unordered and plain, their markers and their items.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + +ITEMS = ["The quick brown fox", "jumps over", "the lazy dog"] + + +def _list(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a list of one kind, from items or from children. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``kind`` names the helper that creates + the list, and ``children`` what its items hold. + + Returns: + The list. + """ + props = dict(props) + kind = props.pop("kind", "unordered") + children = props.pop("children", "items") + create = namespace.list if kind == "plain" else getattr(namespace.list, kind) + if children == "items": + return create(items=ITEMS, **props) + if children == "rich": + return create( + namespace.list.item( + rx.icon("circle_check", size=14), namespace.text("Tested", size="2") + ), + namespace.list.item( + namespace.text("Read ", weight="bold"), + namespace.link("the docs", href="/docs"), + ), + namespace.list.item("Run ", namespace.code("uv sync")), + **props, + ) + return create( + namespace.list.item( + "Fruits", namespace.list.unordered(items=["Apples", "Pears"]) + ), + namespace.list.item("Vegetables", namespace.list.ordered(items=["Leeks"])), + **props, + ) + + +MATRIX = Matrix( + component="list", + render=_list, + cross={ + "kind": ["unordered", "ordered", "plain"], + "children": ["items", "rich", "nested"], + }, + sweep={ + "list_style_type": ["none", "disc", "circle", "square"], + "style": {"spaced": {"padding_left": "8px", "color": "gray"}}, + "margin_left": ["0px", "3rem"], + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "kind": ["ordered"], + "list_style_type": [ + "none", + "decimal", + "decimal-leading-zero", + "lower-roman", + "upper-roman", + "lower-greek", + "lower-latin", + "upper-latin", + "armenian", + "georgian", + "lower-alpha", + "upper-alpha", + "hiragana", + "katakana", + ], + }, + {"kind": ["plain"], "list_style_type": ["disc", "decimal"]}, + ], + stage=(260, 200), + parts={"item": "li"}, + properties=( + *Matrix.__dataclass_fields__["properties"].default, + "list-style-type", + "list-style-position", + ), +) + +CONTRACT = Contract( + component="list", + render=lambda namespace: namespace.box( + namespace.list.unordered(items=["one", "two"], id="unordered"), + namespace.list.ordered( + namespace.list.item("first", id="first"), namespace.list.item("second"), + id="ordered", + ), + ), +) + + +@CONTRACT.step("is a list of items in the server render", on=SERVER) +def _server_render(run: Run) -> None: + unordered = run.server.element("unordered") + assert (unordered.tag, unordered.text) == ("ul", "onetwo") + assert run.server.element("ordered").tag == "ol" + first = run.server.element("first") + assert (first.tag, first.text) == ("li", "first") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#unordered").inner_text() == "one\ntwo" + + +@CONTRACT.step("has the roles of lists and their items", on=HYDRATED) +def _roles(run: Run) -> None: + lists = run.page.get_by_role("list") + assert [lists.nth(index).get_attribute("id") for index in range(2)] == [ + "unordered", + "ordered", + ] + assert run.page.get_by_role("listitem").count() == 4 diff --git a/packages/reflex-components-ui/parity/ui_parity/components/section.py b/packages/reflex-components-ui/parity/ui_parity/components/section.py new file mode 100644 index 00000000000..2098341d840 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/section.py @@ -0,0 +1,70 @@ +"""The section: the space above and below its content.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + + +def _section(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a section whose content shows the space around it. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The section. + """ + return namespace.section( + rx.el.div("The quick brown fox", style={"border": "1px solid currentColor"}), + **props, + ) + + +MATRIX = Matrix( + component="section", + render=_section, + sweep={ + "size": ["1", "2", "3"], + "style": {"background": {"background_color": "rgba(128, 128, 128, 0.2)"}}, + "appearance": [DARK], + }, + groups=[ + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1280], + }, + ], + stage=(240, 200), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="section", + render=lambda namespace: namespace.section( + "content", id="section", custom_attrs={"aria-label": "Pricing"} + ), +) + + +@CONTRACT.step("is a section in the server render", on=SERVER) +def _server_render(run: Run) -> None: + section = run.server.element("section") + assert (section.tag, section.text) == ("section", "content") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#section").is_visible() + + +@CONTRACT.step("is a region with its label after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + region = run.page.get_by_role("region", name="Pricing") + assert region.get_attribute("id") == "section" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/separator.py b/packages/reflex-components-ui/parity/ui_parity/components/separator.py new file mode 100644 index 00000000000..0776e64a442 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/separator.py @@ -0,0 +1,66 @@ +"""The separator: a line of a size, an orientation and a color.""" + +from __future__ import annotations + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import ACCENTS + +MATRIX = Matrix( + component="separator", + cross={ + "size": ["1", "2", "3", "4"], + "orientation": ["horizontal", "vertical"], + }, + sweep={ + "color_scheme": ACCENTS, + "decorative": [True, False], + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"color_scheme": ["ruby", "gray"], "appearance": [DARK]}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "orientation": { + "responsive": rx.breakpoints(initial="vertical", md="horizontal") + }, + "viewport": [520, 800, 1100, 1280], + }, + ], + stage=(200, 120), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="separator", + render=lambda namespace: namespace.box( + namespace.separator(id="decorative"), + namespace.separator(decorative=False, id="semantic"), + ), +) + + +@CONTRACT.step("is a span, with a role when it is not decorative", on=SERVER) +def _server_render(run: Run) -> None: + decorative = run.server.element("decorative") + assert (decorative.tag, decorative.text) == ("span", "") + assert "role" not in decorative.attributes + assert run.server.element("semantic").attributes["role"] == "separator" + + +@CONTRACT.step("is a line across its container with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + box = run.page.locator("#decorative").bounding_box() + assert box is not None + assert box["height"] == 1 + assert box["width"] > 100 + + +@CONTRACT.step("only the semantic one is in the accessibility tree", on=HYDRATED) +def _roles(run: Run) -> None: + separators = run.page.get_by_role("separator") + assert separators.count() == 1 + assert separators.get_attribute("id") == "semantic" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/spacer.py b/packages/reflex-components-ui/parity/ui_parity/components/spacer.py new file mode 100644 index 00000000000..b8fdf28f7f0 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/spacer.py @@ -0,0 +1,95 @@ +"""The spacer: the room between the children of a flex container.""" + +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, Matrix +from ui_parity.samples import tiles + + +def _spacer(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a flex container with a spacer between its children. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell: ``direction`` is the container's, the + rest are the spacer's. + + Returns: + The container. + """ + props = dict(props) + direction = props.pop("direction", "row") + first, second = tiles(("quick", "fox")) + return namespace.flex( + first, + namespace.spacer(custom_attrs={"data-spacer": ""}, **props), + second, + direction=direction, + style={"height": "100px"}, + ) + + +MATRIX = Matrix( + component="spacer", + render=_spacer, + sweep={ + "direction": ["row", "column", "row-reverse"], + "style": { + "outlined": {"border": "1px dashed currentColor"}, + "bounded": {"max_width": "40px"}, + }, + "appearance": [DARK], + "viewport": [520], + }, + stage=(240, 140), + target="[data-spacer]", + crop="stage", + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="spacer", + render=lambda namespace: namespace.flex( + namespace.box("left", id="left"), + namespace.spacer(id="spacer"), + namespace.box("right", id="right"), + id="row", + ), +) + + +@CONTRACT.step("is an empty div in the server render", on=SERVER) +def _server_render(run: Run) -> None: + spacer = run.server.element("spacer") + assert (spacer.tag, spacer.text) == ("div", "") + + +@CONTRACT.step("pushes its siblings apart with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + _pushes_apart(run) + + +@CONTRACT.step("pushes its siblings apart after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + _pushes_apart(run) + + +def _pushes_apart(run: Run) -> None: + """Check that the siblings of the spacer are at the ends of the row. + + Args: + run: The run of the step. + """ + row = run.page.locator("#row").bounding_box() + left = run.page.locator("#left").bounding_box() + right = run.page.locator("#right").bounding_box() + assert row is not None + assert left is not None + assert right is not None + assert left["x"] == row["x"] + assert right["x"] + right["width"] == row["x"] + row["width"] diff --git a/packages/reflex-components-ui/parity/ui_parity/components/stack.py b/packages/reflex-components-ui/parity/ui_parity/components/stack.py new file mode 100644 index 00000000000..44a020a44f8 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/stack.py @@ -0,0 +1,89 @@ +"""The stack: a flex container with a gap, in a row unless told otherwise.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import tiles + + +def _stack(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a stack of more children than one line holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The stack. + """ + return namespace.stack(*tiles(), **props) + + +MATRIX = Matrix( + component="stack", + render=_stack, + sweep={ + "spacing": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], + "align": ["start", "center", "end", "baseline", "stretch"], + "justify": ["start", "center", "end", "between"], + "direction": ["row", "column", "row-reverse", "column-reverse"], + "wrap": ["nowrap", "wrap", "wrap-reverse"], + "class_name": ["mine"], + "style": {"sized": {"height": "120px", "width": "100%"}}, + "appearance": [DARK], + }, + groups=[ + {"wrap": ["wrap"], "spacing": ["1", "4"], "align": ["center", "end"]}, + { + "style": {"sized": {"height": "120px", "width": "100%"}}, + "justify": ["center", "between"], + "align": ["center", "stretch"], + }, + { + "direction": { + "responsive": rx.breakpoints(initial="column", sm="row", lg="column") + }, + "spacing": {"responsive": rx.breakpoints(initial="1", xs="5", md="2")}, + "align": {"responsive": rx.breakpoints(initial="end", md="center")}, + "viewport": [400, 600, 800, 1100, 1280], + }, + ], + stage=(240, 200), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="stack", + render=lambda namespace: namespace.stack( + namespace.box("one"), namespace.box("two"), id="stack" + ), +) + + +@CONTRACT.step("is a div with the class of a stack in the server render", on=SERVER) +def _server_render(run: Run) -> None: + stack = run.server.element("stack") + assert (stack.tag, stack.text) == ("div", "onetwo") + assert "rx-Stack" in (stack.attributes["class"] or "").split() + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#stack").is_visible() + + +@CONTRACT.step("lays its children out in a row, a gap apart", on=HYDRATED) +def _hydrated(run: Run) -> None: + boxes = run.page.locator("#stack > div") + first, second = boxes.nth(0).bounding_box(), boxes.nth(1).bounding_box() + assert first is not None + assert second is not None + # The default spacing is the third step of the space scale: 12px. + assert second["y"] == first["y"] + assert second["x"] == first["x"] + first["width"] + 12 diff --git a/packages/reflex-components-ui/parity/ui_parity/components/text.py b/packages/reflex-components-ui/parity/ui_parity/components/text.py index 0916d745c79..07587e4a261 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/text.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/text.py @@ -8,12 +8,7 @@ import reflex as rx from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import DARK, Matrix - -PARAGRAPH = ( - "The quick brown fox jumps over the lazy dog, then naps in the warm " - "afternoon sun." -) - +from ui_parity.samples import ACCENTS, PARAGRAPH def _text(namespace: Any, props: Mapping[str, Any]) -> Any: """Create a paragraph that wraps over several lines. @@ -41,6 +36,13 @@ def _text(namespace: Any, props: Mapping[str, Any]) -> Any: " jumps over the lazy dog.", **props, ) + if nested in ("em", "strong", "quote", "span"): + return namespace.text( + "The quick ", + getattr(namespace.text, nested)("brown fox jumps"), + " over the lazy dog, then naps in the sun.", + **props, + ) return namespace.text(PARAGRAPH, **props) @@ -56,13 +58,9 @@ def _text(namespace: Any, props: Mapping[str, Any]) -> Any: "trim": ["normal", "start", "end", "both"], "as_": ["p", "label", "div", "span", "b", "i", "u", "abbr", "cite", "del", "em", "ins", "kbd", "mark", "s", "samp", "sub", "sup"], - "color_scheme": ["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"], + "color_scheme": ACCENTS, "high_contrast": [True], - "nested": ["text", "high-contrast"], + "nested": ["text", "high-contrast", "em", "strong", "quote", "span"], "size": { "responsive": rx.breakpoints(initial="1", sm="5", lg="3"), }, @@ -74,6 +72,7 @@ def _text(namespace: Any, props: Mapping[str, Any]) -> Any: "appearance": ["light", DARK]}, {"color_scheme": ["ruby"], "nested": ["text", "high-contrast"]}, {"trim": ["both", "start"], "size": ["2", "6"]}, + {"nested": ["em", "strong", "quote"], "size": ["1", "5", "9"]}, {"size": {"responsive": rx.breakpoints(initial="1", sm="5", lg="3")}, "trim": {"responsive": rx.breakpoints(initial="both", md="normal")}, "viewport": [520, 800, 1100, 1280]}, diff --git a/packages/reflex-components-ui/parity/ui_parity/components/vstack.py b/packages/reflex-components-ui/parity/ui_parity/components/vstack.py new file mode 100644 index 00000000000..0e745657db5 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/vstack.py @@ -0,0 +1,89 @@ +"""The vertical stack: a column with a gap between its children.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import tiles + + +def _vstack(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a stack of more children than one line holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The stack. + """ + return namespace.vstack(*tiles(), **props) + + +MATRIX = Matrix( + component="vstack", + render=_vstack, + sweep={ + "spacing": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], + "align": ["start", "center", "end", "baseline", "stretch"], + "justify": ["start", "center", "end", "between"], + "direction": ["row", "column", "row-reverse", "column-reverse"], + "wrap": ["nowrap", "wrap", "wrap-reverse"], + "class_name": ["mine"], + "style": {"sized": {"height": "120px", "width": "100%"}}, + "appearance": [DARK], + }, + groups=[ + {"wrap": ["wrap"], "spacing": ["1", "4"], "align": ["center", "end"]}, + { + "style": {"sized": {"height": "120px", "width": "100%"}}, + "justify": ["center", "between"], + "align": ["center", "stretch"], + }, + { + "direction": { + "responsive": rx.breakpoints(initial="column", sm="row", lg="column-reverse") + }, + "spacing": {"responsive": rx.breakpoints(initial="1", xs="5", md="2")}, + "align": {"responsive": rx.breakpoints(initial="end", md="center")}, + "viewport": [400, 600, 800, 1100, 1280], + }, + ], + stage=(240, 200), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="vstack", + render=lambda namespace: namespace.vstack( + namespace.box("one"), namespace.box("two"), id="stack" + ), +) + + +@CONTRACT.step("is a div with the class of a stack in the server render", on=SERVER) +def _server_render(run: Run) -> None: + stack = run.server.element("stack") + assert (stack.tag, stack.text) == ("div", "onetwo") + assert "rx-Stack" in (stack.attributes["class"] or "").split() + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#stack").is_visible() + + +@CONTRACT.step("lays its children out in a column, a gap apart", on=HYDRATED) +def _hydrated(run: Run) -> None: + boxes = run.page.locator("#stack > div") + first, second = boxes.nth(0).bounding_box(), boxes.nth(1).bounding_box() + assert first is not None + assert second is not None + # The default spacing is the third step of the space scale: 12px. + assert second["x"] == first["x"] + assert second["y"] == first["y"] + first["height"] + 12 diff --git a/packages/reflex-components-ui/parity/ui_parity/samples.py b/packages/reflex-components-ui/parity/ui_parity/samples.py new file mode 100644 index 00000000000..70b7939643a --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/samples.py @@ -0,0 +1,63 @@ +"""What the matrices of several components render and sweep.""" + +from __future__ import annotations + +from typing import Any + +import reflex as rx + +# Every accent color, for a sweep of `color_scheme`. +ACCENTS: tuple[str, ...] = ( + "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", +) + +# Long enough to wrap over several lines in a frame. +PARAGRAPH = ( + "The quick brown fox jumps over the lazy dog, then naps in the warm " + "afternoon sun." +) + +WORDS = ("The", "quick", "brown", "fox", "jumps", "over", "lazy") + + +def tiles(words: tuple[str, ...] = WORDS) -> list[Any]: + """Create the children of a layout: boxes with an outline, one per word. + + Args: + words: The text of each box. + + Returns: + The boxes, the same elements for both systems. + """ + return [ + rx.el.div( + word, + style={"border": "1px solid currentColor", "padding": "2px 6px"}, + ) + for word in words + ] 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 89ce627b39a..0a673f12e5c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -262,6 +262,22 @@ def _literal_props(cls) -> dict[str, tuple[str, ...]]: literals[prop] = choices return literals + @classmethod + @functools.cache + def _layout_defaults(cls) -> dict[str, Any]: + """Get the layout props an element has without being given them. + + Returns: + The default of each layout prop whose field has one. + """ + layout_props, _ = cls._style_props() + fields = cls.get_fields() + return { + prop: fields[prop].default_value() + for prop in layout_props + if prop in cls._get_defaulted_props() + } + def _check_literals(self, kwargs: Mapping[str, Any]) -> None: """Fail on a value a prop does not take, naming the ones it does. @@ -333,7 +349,10 @@ def _post_init(self, *args, **kwargs): if inline is not None: self._styles.append(inline) self._layout = ( - {prop: kwargs.pop(prop) for prop in layout_props if prop in kwargs} + { + **self._layout_defaults(), + **{prop: kwargs.pop(prop) for prop in layout_props if prop in kwargs}, + } if layout_props else None ) @@ -345,12 +364,14 @@ def _post_init(self, *args, **kwargs): if color_scheme is None else color_scheme_styles(self._display_name(), color_scheme) ) - self._under: Merged | None = None + # Whether a parent with `as_child` renders as this element, and + # whether this element renders as its only child. + self._slotted = False + self._as_child = False super()._post_init(*args, **kwargs) self._as: Var | None = None if "as_" in fields: self._set_tag() - self._slot: Component | None = None if "as_child" in fields: self._set_slot() self._merge_styles() @@ -395,7 +416,22 @@ def _set_slot(self) -> None: f"not {_describe(children)}." ) raise StyleError(msg) - self._slot = children[0] + self._as_child = True + child = children[0] + if isinstance(child, UIComponent): + # This element declares the styles of both, the child's over its + # own: two sets of class names cannot say which one wins. + child._slotted = True + + @property + def _slot(self) -> Component | None: + """Get the child the element is rendered as. + + Returns: + The only child of an element with ``as_child``, as the tree has + it now: a compile works on copies. + """ + return self.children[0] if self._as_child else None # pyright: ignore[reportReturnType] def _get_tag_name(self) -> str: """Get the JS expression of the element's tag. @@ -429,14 +465,11 @@ def _merge_styles(self) -> None: merged = self._merged = merge( name, cls.styles, props, styles or None, self._layout ) - self._emitted_styles = None + # A compile gives a copy of the component its styles of the app and + # of `add_style` by assigning `style`: the merge follows it. + self._merged_for = self.style if merged.parts: _bind_parts(self.children, merged.parts, name) - slot = self._slot - if isinstance(slot, UIComponent): - # The child renders the styles of both, its own over these. - slot._under = merged - slot._emitted_styles = None def _add_style_recursive(self, style: Any, theme: Component | None = None): """Add the styles of the app to the component and its children. @@ -449,7 +482,7 @@ def _add_style_recursive(self, style: Any, theme: Component | None = None): The component with the additional style. """ result = super()._add_style_recursive(style, theme) - if self.style: + if self.style is not self._merged_for: self._merge_styles() return result @@ -459,23 +492,35 @@ def _emit(self) -> Emitted: 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 + merged = self._element_styles() + if merged is not getattr(self, "_emitted_for", None): + self._emitted_for = merged + self._emitted_styles = emit(merged) + return self._emitted_styles def _element_styles(self) -> Merged: - """Get the merged styles of the element. + """Get the styles the element declares. + + Returns: + The styles of the element, or nothing when a parent with + ``as_child`` declares them with its own. + """ + return _NO_STYLES if self._slotted else self._slot_styles() + + def _slot_styles(self) -> Merged: + """Get the merged styles of the element and of what it renders as. Returns: - The style table merged with the styles of this element, over the - styles of a parent that renders as this element. Nothing for an - element that an rx.ui child of its own renders in its place. + The style table merged with the styles of this element, under + the styles of an rx.ui child that is rendered in its place. """ - if isinstance(self._slot, UIComponent): - return _NO_STYLES - under = self._under - return self._merged if under is None else over(under, self._merged) + if self.style is not self._merged_for: + self._merge_styles() + merged = self._merged + slot = self._slot + if isinstance(slot, UIComponent): + merged = over(merged, slot._slot_styles()) + return merged def _get_vars( self, include_children: bool = False, ignore_ids: set[int] | None = None @@ -675,7 +720,7 @@ def _post_init(self, *args, **kwargs): 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 + self._merged_for = self.style def _element_styles(self) -> Merged: """Get the styles the component of the part has for it. 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 0a700550eed..ef8e23298b6 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 @@ -265,7 +265,8 @@ def __init__(self, name: str, source: Mapping[str, Any]): for key in source: if key not in _TABLE_KEYS: msg = ( -XX + f'{name}: unknown key "{key}" in a style table. Use "base", ' + '"variants", "defaults", "compound" or "parts".' ) raise StyleError(msg) self.source = source diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py index 30815ed533e..4946c7a3855 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py @@ -59,6 +59,9 @@ def _line(rest: str, hover: str) -> dict[str, Any]: # Without a color of its own, inside an element that has one. "color": f"var({ACCENT_LINK}, {tokens.accent.a[11]})", "WebkitTapHighlightColor": "transparent", + # Radix Themes unsets everything on an anchor, the border a reset of + # the page gives every element included. + "border_style": "none", ":any-link": {"cursor": tokens.cursor.link}, "[data-disabled]": {"cursor": tokens.cursor.disabled}, "text_decoration_style": "solid", diff --git a/scripts/ui_parity.py b/scripts/ui_parity.py index c8b33e24963..dc9bd32197c 100644 --- a/scripts/ui_parity.py +++ b/scripts/ui_parity.py @@ -43,9 +43,10 @@ def pytest_command( 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. + # recorded whatever ran, and is named first: an expression that starts + # with "-center" would be read as the option "-c". selected = [f"-{name}] or -{name}-" for name in components] - command += ["-k", " or ".join([*selected, "test_run_time"])] + command += ["-k", " or ".join(["test_run_time", *selected])] return command + extra diff --git a/tests/units/test_ui_parity_script.py b/tests/units/test_ui_parity_script.py index 3abece77137..f08da70a42a 100644 --- a/tests/units/test_ui_parity_script.py +++ b/tests/units/test_ui_parity_script.py @@ -38,7 +38,7 @@ def test_pytest_command_selects_components_and_engines(): "--browser", "webkit", "-k", - "-box] or -box- or -button] or -button- or test_run_time", + "test_run_time or -box] or -box- or -button] or -button-", "-x", ] From 12230ac1fed4a642820aabb670849042e2c65973 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:12:53 +0000 Subject: [PATCH 034/204] WIP: keep the cached tag per kind of code, rx.ui elements never ask for Emotion Claude-Session: https://claude.ai/code/session_014AwvTP2WjJKEVdjMR1jQ6p --- .../src/reflex_base/components/component.py | 20 ++++++++++----- .../src/reflex_components_ui/base.py | 9 +++++++ tests/units/components/test_component.py | 25 +++++++++++++++++++ tests/units/reflex_components_ui/test_base.py | 18 +++++++++++++ 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/packages/reflex-base/src/reflex_base/components/component.py b/packages/reflex-base/src/reflex_base/components/component.py index 5241a96388f..a2eeda86795 100644 --- a/packages/reflex-base/src/reflex_base/components/component.py +++ b/packages/reflex-base/src/reflex_base/components/component.py @@ -21,7 +21,10 @@ from reflex_base import constants from reflex_base.breakpoints import Breakpoints -from reflex_base.components.dynamic import load_dynamic_serializer +from reflex_base.components.dynamic import ( + is_rendering_dynamic_component, + load_dynamic_serializer, +) from reflex_base.components.field import BaseField, FieldBasedMeta from reflex_base.components.tags import CommonTag, Tag from reflex_base.constants import Dirs, EventTriggers, Imports, MemoizationMode @@ -1493,14 +1496,19 @@ def _get_style(self) -> dict: def _get_tag(self) -> CommonTag: """Get the tag the component renders, built once per compile. + A component may render differently as a dynamic component, and one + held in state has its imports collected before it is serialized as + one: the tag is kept for the kind of code it was built for. + Returns: The tag ``_render`` returns. """ - try: - return self._cached_tag - except AttributeError: - pass - tag = self._cached_tag = self._render() + dynamic = is_rendering_dynamic_component() + cached = self.__dict__.get("_cached_tag") + if cached is not None and cached[0] is dynamic: + return cached[1] + tag = self._render() + self._cached_tag = (dynamic, tag) return tag def _renders_css_prop(self) -> bool: 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 1766718059c..771757c7cf7 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -332,6 +332,15 @@ def _get_style(self) -> dict: """ return {} + def _renders_css_prop(self) -> bool: + """Whether the element has a ``css`` prop. + + Returns: + False, without rendering the element to find out: its imports are + also collected where it cannot be rendered. + """ + return False + def _exclude_props(self) -> list[str]: """Keep the props that are read as styles off the element. diff --git a/tests/units/components/test_component.py b/tests/units/components/test_component.py index 99b612c3da1..e7310f4a159 100644 --- a/tests/units/components/test_component.py +++ b/tests/units/components/test_component.py @@ -9,6 +9,10 @@ import pytest from reflex_base.compiler.templates import _render_hooks from reflex_base.components.component import Component, field +from reflex_base.components.dynamic import ( + _RENDERING_DYNAMIC_COMPONENT, + is_rendering_dynamic_component, +) from reflex_base.components.tags import CommonTag, Tag from reflex_base.constants import EventTriggers from reflex_base.constants.state import FIELD_MARKER @@ -2676,3 +2680,24 @@ def test_ref_hook_registers_through_state_helper(): hook_imports = component._get_hooks_imports() assert list(hook_imports["$/utils/state"]) == [ImportVar(tag="useRegisteredRef")] assert "react" not in hook_imports + + +def test_tag_is_rebuilt_for_a_dynamic_component(): + """Imports collected for a page do not fix how a dynamic component renders.""" + + class ContextualComponent(Component): + tag = "Contextual" + library = "contextual" + + def _render(self, props: dict[str, Any] | None = None): + tag = super()._render(props) + return tag.add_props(dynamic=is_rendering_dynamic_component()) + + component = ContextualComponent.create() + assert component._get_all_imports() == {"contextual": [ImportVar(tag="Contextual")]} + assert component._get_tag() is component._get_tag() + token = _RENDERING_DYNAMIC_COMPONENT.set(True) + try: + assert component.render()["props"] == ["dynamic:true"] + finally: + _RENDERING_DYNAMIC_COMPONENT.reset(token) diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py index 8519220ada5..16a54984260 100644 --- a/tests/units/reflex_components_ui/test_base.py +++ b/tests/units/reflex_components_ui/test_base.py @@ -5,6 +5,7 @@ import pytest from reflex_base.components.component import Component +from reflex_base.components.dynamic import _RENDERING_DYNAMIC_COMPONENT from reflex_base.components.memo import MEMOS from reflex_base.config import get_config from reflex_base.plugins import CompileContext @@ -737,3 +738,20 @@ 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 + + +def test_element_never_asks_for_emotion(mocker): + """An rx.ui element has no ``css`` prop, and is not rendered to find out. + + Its imports are also read where it cannot be rendered: for a component + held in state, before it is serialized as a dynamic component. + """ + component = Button.create("hello", kind="soft", style={"padding": "4px"}) + render = mocker.spy(Button, "_render") + token = _RENDERING_DYNAMIC_COMPONENT.set(True) + try: + imports = component._get_all_imports() + finally: + _RENDERING_DYNAMIC_COMPONENT.reset(token) + assert imports == {} + assert render.call_count == 0 From d269a61461db55f784ed95c44516e6bb5bb32a19 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:13:08 +0000 Subject: [PATCH 035/204] Hold the typography matrices to zero differing pixels Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- .../parity/ui_parity/components/blockquote.py | 2 ++ .../reflex-components-ui/parity/ui_parity/components/code.py | 2 ++ .../parity/ui_parity/components/heading.py | 2 ++ .../reflex-components-ui/parity/ui_parity/components/inset.py | 3 +++ .../reflex-components-ui/parity/ui_parity/components/link.py | 2 ++ .../reflex-components-ui/parity/ui_parity/components/list.py | 2 ++ .../reflex-components-ui/parity/ui_parity/components/text.py | 2 ++ 7 files changed, 15 insertions(+) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/blockquote.py b/packages/reflex-components-ui/parity/ui_parity/components/blockquote.py index 4ab3cdae415..6b17acb9749 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/blockquote.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/blockquote.py @@ -50,6 +50,8 @@ def _blockquote(namespace: Any, props: Mapping[str, Any]) -> Any: }, ], stage=(300, 260), + threshold=0, + tolerance=0, ) CONTRACT = Contract( diff --git a/packages/reflex-components-ui/parity/ui_parity/components/code.py b/packages/reflex-components-ui/parity/ui_parity/components/code.py index 06e179fca45..3cfc15456c4 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/code.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/code.py @@ -84,6 +84,8 @@ def _code(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(300, 120), target="code", crop="stage", + threshold=0, + tolerance=0, ) CONTRACT = Contract( diff --git a/packages/reflex-components-ui/parity/ui_parity/components/heading.py b/packages/reflex-components-ui/parity/ui_parity/components/heading.py index ca1c7ff69df..d81fd51b372 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/heading.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/heading.py @@ -83,6 +83,8 @@ def _heading(namespace: Any, props: Mapping[str, Any]) -> Any: }, ], stage=(300, 240), + threshold=0, + tolerance=0, ) CONTRACT = Contract( diff --git a/packages/reflex-components-ui/parity/ui_parity/components/inset.py b/packages/reflex-components-ui/parity/ui_parity/components/inset.py index a9a3987482c..6e956103bc2 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/inset.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/inset.py @@ -80,6 +80,9 @@ def _inset(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(260, 140), target="[data-inset]", crop="stage", + # Not held to zero, as the other layouts are: the card around the inset + # is the same Radix card in both frames, and the browser dithers its + # rounded corners and its shadow by position. ) CONTRACT = Contract( diff --git a/packages/reflex-components-ui/parity/ui_parity/components/link.py b/packages/reflex-components-ui/parity/ui_parity/components/link.py index 89b901b513b..aef7aa1208e 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/link.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/link.py @@ -96,6 +96,8 @@ def _link(namespace: Any, props: Mapping[str, Any]) -> Any: "text-decoration-thickness", "text-underline-offset", ), + threshold=0, + tolerance=0, ) CONTRACT = Contract( diff --git a/packages/reflex-components-ui/parity/ui_parity/components/list.py b/packages/reflex-components-ui/parity/ui_parity/components/list.py index ca2c27c382d..4ee89cea47e 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/list.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/list.py @@ -93,6 +93,8 @@ def _list(namespace: Any, props: Mapping[str, Any]) -> Any: "list-style-type", "list-style-position", ), + threshold=0, + tolerance=0, ) CONTRACT = Contract( diff --git a/packages/reflex-components-ui/parity/ui_parity/components/text.py b/packages/reflex-components-ui/parity/ui_parity/components/text.py index 07587e4a261..e7e20678515 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/text.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/text.py @@ -78,6 +78,8 @@ def _text(namespace: Any, props: Mapping[str, Any]) -> Any: "viewport": [520, 800, 1100, 1280]}, ], stage=(260, 200), + threshold=0, + tolerance=0, ) CONTRACT = Contract( From 521d08b62df68ee58ffeb6ca649cd77b099d5ccd Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:21:16 +0000 Subject: [PATCH 036/204] Ship Emotion only in modules that render a css prop A component asks for Emotion's jsx through its imports when its rendered tag has a css prop; every generated module otherwise imports React's createElement as jsx. A css key anywhere in a module's code asks for Emotion too, for code that reaches it without imports. Dynamic components load Emotion on demand. The connection indicator, the badge and the error boundary fallback are styled by class names and a hoisted stylesheet. Claude-Session: https://claude.ai/code/session_014AwvTP2WjJKEVdjMR1jQ6p --- .../news/+no-emotion.performance.md | 1 + .../tests_playwright/test_scripts_after_first_paint.py | 10 ++++++++++ 2 files changed, 11 insertions(+) create mode 100644 packages/reflex-components-ui/news/+no-emotion.performance.md diff --git a/packages/reflex-components-ui/news/+no-emotion.performance.md b/packages/reflex-components-ui/news/+no-emotion.performance.md new file mode 100644 index 00000000000..aa8aadd8314 --- /dev/null +++ b/packages/reflex-components-ui/news/+no-emotion.performance.md @@ -0,0 +1 @@ +An app built only from `rx.ui` components no longer ships Emotion: their pages import React's `createElement` instead of Emotion's `jsx`, about 8 kB less gzipped JavaScript. diff --git a/tests/integration/tests_playwright/test_scripts_after_first_paint.py b/tests/integration/tests_playwright/test_scripts_after_first_paint.py index b31796b7b72..eb1324373f5 100644 --- a/tests/integration/tests_playwright/test_scripts_after_first_paint.py +++ b/tests/integration/tests_playwright/test_scripts_after_first_paint.py @@ -6,6 +6,8 @@ import pytest from playwright.sync_api import Page, expect +from reflex_components_core.core.banner import _PULSER_CSS +from reflex_components_core.core.sticky import _BADGE_CSS import reflex.constants as constants import reflex.utils.prerequisites as prerequisites @@ -108,9 +110,17 @@ def test_prerendered_head_preloads_no_script(scripts_app: AppHarness): preload_color_theme("system").render()["children"][0]["contents"] ) stylesheet = "/assets/__reflex_global_styles-HASH.css" + # The rules of the connection indicator and the badge, which React hoists + # from where they are rendered into one element ahead of the stylesheet. + own_styles = ( + '" + ) assert re.sub(r"-[\w-]{8}\.css", "-HASH.css", head) == ( '' '' + f"{own_styles}" f'' "Index" '' From ae31b448fa47b29e4cd2ed303668d433a3bdc6b9 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:24:02 +0000 Subject: [PATCH 037/204] Test the layout and typography wave: components, responsive props, as_ and as_child; add text.kbd Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- .../parity/allowlist.toml | 6 + .../parity/ui_parity/components/container.py | 4 +- .../parity/ui_parity/components/flex.py | 4 +- .../parity/ui_parity/components/inset.py | 4 +- .../parity/ui_parity/components/kbd.py | 71 ++++ .../parity/ui_parity/components/link.py | 6 +- .../parity/ui_parity/components/list.py | 3 +- .../parity/ui_parity/components/separator.py | 4 +- .../parity/ui_parity/components/text.py | 49 ++- .../parity/ui_parity/components/vstack.py | 4 +- .../parity/ui_parity/samples.py | 3 +- .../src/reflex_components_ui/base.py | 14 +- .../components/separator.py | 4 +- .../src/reflex_components_ui/style/lower.py | 1 + .../src/reflex_components_ui/style/merge.py | 33 +- .../src/reflex_components_ui/styles/text.py | 58 +++ .../reflex_components_ui/typography/text.py | 13 +- pyi_hashes.json | 22 +- .../components/__init__.py | 0 .../components/test_aspect_ratio.py | 64 ++++ .../components/test_inset.py | 82 ++++ .../components/test_separator.py | 89 +++++ tests/units/reflex_components_ui/conftest.py | 37 ++ .../layout/test_center.py | 48 +++ .../layout/test_container.py | 79 ++++ .../reflex_components_ui/layout/test_flex.py | 85 +++++ .../reflex_components_ui/layout/test_grid.py | 68 ++++ .../reflex_components_ui/layout/test_list.py | 101 +++++ .../layout/test_section.py | 56 +++ .../layout/test_spacer.py | 33 ++ .../reflex_components_ui/layout/test_stack.py | 78 ++++ .../parity/test_allowlist.py | 8 + .../reflex_components_ui/style/test_lower.py | 45 +++ .../reflex_components_ui/style/test_merge.py | 200 ++++++++++ .../reflex_components_ui/test_api_parity.py | 112 +++++- tests/units/reflex_components_ui/test_base.py | 286 ++++++++++++++ .../typography/__init__.py | 0 .../typography/test_blockquote.py | 78 ++++ .../typography/test_code.py | 229 ++++++++++++ .../typography/test_heading.py | 127 +++++++ .../typography/test_link.py | 353 ++++++++++++++++++ .../typography/test_text.py | 308 +++++++++++++++ 42 files changed, 2815 insertions(+), 54 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/kbd.py create mode 100644 tests/units/reflex_components_ui/components/__init__.py create mode 100644 tests/units/reflex_components_ui/components/test_aspect_ratio.py create mode 100644 tests/units/reflex_components_ui/components/test_inset.py create mode 100644 tests/units/reflex_components_ui/components/test_separator.py create mode 100644 tests/units/reflex_components_ui/layout/test_center.py create mode 100644 tests/units/reflex_components_ui/layout/test_container.py create mode 100644 tests/units/reflex_components_ui/layout/test_flex.py create mode 100644 tests/units/reflex_components_ui/layout/test_grid.py create mode 100644 tests/units/reflex_components_ui/layout/test_list.py create mode 100644 tests/units/reflex_components_ui/layout/test_section.py create mode 100644 tests/units/reflex_components_ui/layout/test_spacer.py create mode 100644 tests/units/reflex_components_ui/layout/test_stack.py create mode 100644 tests/units/reflex_components_ui/typography/__init__.py create mode 100644 tests/units/reflex_components_ui/typography/test_blockquote.py create mode 100644 tests/units/reflex_components_ui/typography/test_code.py create mode 100644 tests/units/reflex_components_ui/typography/test_heading.py create mode 100644 tests/units/reflex_components_ui/typography/test_link.py create mode 100644 tests/units/reflex_components_ui/typography/test_text.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index f027fe91b86..94865a66a63 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -23,3 +23,9 @@ # cells a shell pattern over the cell id; every cell when left out # properties the computed properties that differ, for "style" # engines as above + +[[look]] +component = "kbd" +check = "style" +properties = ["box-shadow"] +reason = "The shadow of rx.ui.text.kbd lists the layers of the light and the dark appearance, and the ones of the other appearance are transparent, so one value serves both. It paints the same." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/container.py b/packages/reflex-components-ui/parity/ui_parity/components/container.py index 81ab66eb105..40f0471b395 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/container.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/container.py @@ -75,4 +75,6 @@ def _hydrated(run: Run) -> None: assert container is not None assert inner is not None assert inner["width"] == 448 - assert inner["x"] - container["x"] == (container["width"] - 448) / 2 + before = inner["x"] - container["x"] + after = container["x"] + container["width"] - inner["x"] - inner["width"] + assert abs(before - after) <= 1 diff --git a/packages/reflex-components-ui/parity/ui_parity/components/flex.py b/packages/reflex-components-ui/parity/ui_parity/components/flex.py index 0cad4571e4b..09062cab57e 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/flex.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/flex.py @@ -21,9 +21,7 @@ def _flex(namespace: Any, props: Mapping[str, Any]) -> Any: Returns: The container. """ - return namespace.flex( -*tiles(), **props - ) + return namespace.flex(*tiles(), **props) MATRIX = Matrix( diff --git a/packages/reflex-components-ui/parity/ui_parity/components/inset.py b/packages/reflex-components-ui/parity/ui_parity/components/inset.py index 6e956103bc2..e3f9318c53b 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/inset.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/inset.py @@ -100,7 +100,9 @@ def _server_render(run: Run) -> None: assert (inset.tag, inset.text) == ("div", "content") -@CONTRACT.step("reaches the edges of the card with JavaScript disabled", on=NO_JAVASCRIPT) +@CONTRACT.step( + "reaches the edges of the card with JavaScript disabled", on=NO_JAVASCRIPT +) def _without_javascript(run: Run) -> None: _reaches_the_edges(run) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/kbd.py b/packages/reflex-components-ui/parity/ui_parity/components/kbd.py new file mode 100644 index 00000000000..06be866b7ab --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/kbd.py @@ -0,0 +1,71 @@ +"""The key of a keyboard, which text names: ``text.kbd`` in both namespaces.""" + +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, Matrix + + +def _kbd(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a key, alone or inside text of a size. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell, ``around`` giving the size of the text + the key is in. + + Returns: + The key, or the text around it. + """ + props = dict(props) + around = props.pop("around", None) + key = namespace.text.kbd("Shift + Tab", **props) + if around is None: + return key + return namespace.text("Press ", key, " to go back.", size=around) + + +MATRIX = Matrix( + component="kbd", + render=_kbd, + cross={ + "size": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + "appearance": ["light", DARK], + }, + sweep={ + "around": ["1", "3", "6", "9"], + "viewport": [520], + }, + groups=[ + {"around": ["2", "5"], "appearance": [DARK]}, + ], + stage=(360, 120), + target="kbd", + crop="stage", + # Not held to zero: the shadow lists the layers of both appearances, and + # the edge of a layer a fraction of a pixel wide is rounded another way. +) + +CONTRACT = Contract( + component="kbd", + render=lambda namespace: namespace.text.kbd("Esc", id="key"), +) + + +@CONTRACT.step("is a kbd element in the server render", on=SERVER) +def _server_render(run: Run) -> None: + key = run.server.element("key") + assert (key.tag, key.text) == ("kbd", "Esc") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#key").inner_text() == "Esc" + + +@CONTRACT.step("keeps its text after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + assert run.page.locator("#key").inner_text() == "Esc" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/link.py b/packages/reflex-components-ui/parity/ui_parity/components/link.py index aef7aa1208e..09b722d8b33 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/link.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/link.py @@ -53,7 +53,10 @@ def _link(namespace: Any, props: Mapping[str, Any]) -> Any: "state": STATES, }, sweep={ - "size": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + "size": { + **{size: size for size in "123456789"}, + "responsive": rx.breakpoints(initial="1", sm="6", lg="3"), + }, "weight": ["light", "regular", "medium", "bold"], "trim": ["normal", "start", "end", "both"], "color_scheme": ACCENTS, @@ -62,7 +65,6 @@ def _link(namespace: Any, props: Mapping[str, Any]) -> Any: "holds": ["code", "code-and-words"], "is_external": [True], "href": {"none": None, "external": "https://reflex.dev"}, - "size": {"responsive": rx.breakpoints(initial="1", sm="6", lg="3")}, "appearance": [DARK], "viewport": [520], }, diff --git a/packages/reflex-components-ui/parity/ui_parity/components/list.py b/packages/reflex-components-ui/parity/ui_parity/components/list.py index 4ee89cea47e..7315791eb5a 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/list.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/list.py @@ -102,7 +102,8 @@ def _list(namespace: Any, props: Mapping[str, Any]) -> Any: render=lambda namespace: namespace.box( namespace.list.unordered(items=["one", "two"], id="unordered"), namespace.list.ordered( - namespace.list.item("first", id="first"), namespace.list.item("second"), + namespace.list.item("first", id="first"), + namespace.list.item("second"), id="ordered", ), ), diff --git a/packages/reflex-components-ui/parity/ui_parity/components/separator.py b/packages/reflex-components-ui/parity/ui_parity/components/separator.py index 0776e64a442..5308b770eab 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/separator.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/separator.py @@ -51,7 +51,9 @@ def _server_render(run: Run) -> None: assert run.server.element("semantic").attributes["role"] == "separator" -@CONTRACT.step("is a line across its container with JavaScript disabled", on=NO_JAVASCRIPT) +@CONTRACT.step( + "is a line across its container with JavaScript disabled", on=NO_JAVASCRIPT +) def _without_javascript(run: Run) -> None: box = run.page.locator("#decorative").bounding_box() assert box is not None diff --git a/packages/reflex-components-ui/parity/ui_parity/components/text.py b/packages/reflex-components-ui/parity/ui_parity/components/text.py index e7e20678515..6d39b7722ef 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/text.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/text.py @@ -10,6 +10,7 @@ from ui_parity.matrix import DARK, Matrix from ui_parity.samples import ACCENTS, PARAGRAPH + def _text(namespace: Any, props: Mapping[str, Any]) -> Any: """Create a paragraph that wraps over several lines. @@ -43,6 +44,13 @@ def _text(namespace: Any, props: Mapping[str, Any]) -> Any: " over the lazy dog, then naps in the sun.", **props, ) + if nested == "kbd": + return namespace.text( + "Press ", + namespace.text.kbd("Shift + Tab"), + " to go back to the field before.", + **props, + ) return namespace.text(PARAGRAPH, **props) @@ -56,11 +64,29 @@ def _text(namespace: Any, props: Mapping[str, Any]) -> Any: sweep={ "align": ["left", "center", "right"], "trim": ["normal", "start", "end", "both"], - "as_": ["p", "label", "div", "span", "b", "i", "u", "abbr", "cite", "del", - "em", "ins", "kbd", "mark", "s", "samp", "sub", "sup"], + "as_": [ + "p", + "label", + "div", + "span", + "b", + "i", + "u", + "abbr", + "cite", + "del", + "em", + "ins", + "kbd", + "mark", + "s", + "samp", + "sub", + "sup", + ], "color_scheme": ACCENTS, "high_contrast": [True], - "nested": ["text", "high-contrast", "em", "strong", "quote", "span"], + "nested": ["text", "high-contrast", "em", "strong", "quote", "span", "kbd"], "size": { "responsive": rx.breakpoints(initial="1", sm="5", lg="3"), }, @@ -68,14 +94,19 @@ def _text(namespace: Any, props: Mapping[str, Any]) -> Any: "viewport": [520], }, groups=[ - {"color_scheme": ["ruby", "gray"], "high_contrast": [True], - "appearance": ["light", DARK]}, + { + "color_scheme": ["ruby", "gray"], + "high_contrast": [True], + "appearance": ["light", DARK], + }, {"color_scheme": ["ruby"], "nested": ["text", "high-contrast"]}, {"trim": ["both", "start"], "size": ["2", "6"]}, - {"nested": ["em", "strong", "quote"], "size": ["1", "5", "9"]}, - {"size": {"responsive": rx.breakpoints(initial="1", sm="5", lg="3")}, - "trim": {"responsive": rx.breakpoints(initial="both", md="normal")}, - "viewport": [520, 800, 1100, 1280]}, + {"nested": ["em", "strong", "quote", "kbd"], "size": ["1", "5", "9"]}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="5", lg="3")}, + "trim": {"responsive": rx.breakpoints(initial="both", md="normal")}, + "viewport": [520, 800, 1100, 1280], + }, ], stage=(260, 200), threshold=0, diff --git a/packages/reflex-components-ui/parity/ui_parity/components/vstack.py b/packages/reflex-components-ui/parity/ui_parity/components/vstack.py index 0e745657db5..746fa63dcbc 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/vstack.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/vstack.py @@ -46,7 +46,9 @@ def _vstack(namespace: Any, props: Mapping[str, Any]) -> Any: }, { "direction": { - "responsive": rx.breakpoints(initial="column", sm="row", lg="column-reverse") + "responsive": rx.breakpoints( + initial="column", sm="row", lg="column-reverse" + ) }, "spacing": {"responsive": rx.breakpoints(initial="1", xs="5", md="2")}, "align": {"responsive": rx.breakpoints(initial="end", md="center")}, diff --git a/packages/reflex-components-ui/parity/ui_parity/samples.py b/packages/reflex-components-ui/parity/ui_parity/samples.py index 70b7939643a..88e8609c50c 100644 --- a/packages/reflex-components-ui/parity/ui_parity/samples.py +++ b/packages/reflex-components-ui/parity/ui_parity/samples.py @@ -38,8 +38,7 @@ # Long enough to wrap over several lines in a frame. PARAGRAPH = ( - "The quick brown fox jumps over the lazy dog, then naps in the warm " - "afternoon sun." + "The quick brown fox jumps over the lazy dog, then naps in the warm afternoon sun." ) WORDS = ("The", "quick", "brown", "fox", "jumps", "over", "lazy") 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 0a673f12e5c..5f904c7047b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -125,9 +125,7 @@ def _join_class_names(first: Any, second: Any) -> Any: return Var( f'({first!s}) + " " + ({second!s})', _var_type=str, - _var_data=VarData.merge( - first._get_all_var_data(), second._get_all_var_data() - ), + _var_data=VarData.merge(first._get_all_var_data(), second._get_all_var_data()), ) @@ -393,8 +391,6 @@ def _set_slot(self) -> None: does not have exactly one child that renders an element. """ as_child = _literal(getattr(self, "as_child", None)) - if not as_child: - return name = self._display_name() if isinstance(as_child, Var): msg = ( @@ -403,12 +399,13 @@ def _set_slot(self) -> None: "between two components with rx.cond." ) raise StyleError(msg) + if not as_child: + return children = self.children if ( len(children) != 1 or not isinstance(children[0], Component) - or type(children[0]).render - not in (Component.render, UIComponent.render) + or type(children[0]).render not in (Component.render, UIComponent.render) ): msg = ( f"{name}: as_child renders the only child in place of the " @@ -425,7 +422,7 @@ def _set_slot(self) -> None: @property def _slot(self) -> Component | None: - """Get the child the element is rendered as. + """The child the element is rendered as. Returns: The only child of an element with ``as_child``, as the tree has @@ -655,7 +652,6 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: ) return add_styles(tag, emitted) - def render(self) -> dict: """Render the component, or the child that stands in its place. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/separator.py b/packages/reflex-components-ui/src/reflex_components_ui/components/separator.py index 350aa31e24e..d8a6bc1f372 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/separator.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/separator.py @@ -63,7 +63,9 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: if isinstance(decorative, LiteralVar): return tag if decorative._var_value else tag.add_props(role="separator") role = Var(f'({decorative!s} ? undefined : "separator")') - return tag.add_props(role=role._replace(merge_var_data=decorative._get_all_var_data())) + return tag.add_props( + role=role._replace(merge_var_data=decorative._get_all_var_data()) + ) # Alias to divider. 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 cdb367f1e48..b5367903203 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 @@ -986,6 +986,7 @@ def prop_breakpoint(name: str, prop: str, breakpoint: Any) -> str: ) raise StyleError(msg) from None + # The layout props: the style each one stands for, the longhands it sets, and # how its values are read. _LAYOUT: dict[str, tuple[str, tuple[str, ...], Callable[[Any], Any]]] = { 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 ef8e23298b6..94168078df6 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 @@ -395,7 +395,8 @@ def _responsive_layer( holds from its breakpoint up, until another one replaces it. At each breakpoint the styles of the table are resolved for the values the props then have, compound styles included, and what changes from the breakpoint - before goes under its media query. + before goes under its media query. From there up the element looks as it + would with those values alone. Args: name: The display name of the component, for error messages. @@ -428,6 +429,21 @@ def _responsive_layer( if query != "default": at.setdefault(query, []).append((position, value)) out: dict[str, LoweredValue] = {} + + def put(prop: str, query: str, value: LoweredValue) -> None: + """Give a property its value from a breakpoint up. + + Args: + prop: The property. + query: The media query of the breakpoint. + value: The value. + """ + conditions = out.get(prop) + if conditions is None: + out[prop] = {query: value} + else: + conditions[query] = value + current = list(keys) before = table.resolve(keys) for query in PROP_BREAKPOINTS.values(): @@ -439,11 +455,12 @@ def _responsive_layer( after = table.resolve(tuple(current)) for prop, value in after.items(): if prop not in before or freeze(before[prop]) != freeze(value): - conditions = out.get(prop) - if conditions is None: - out[prop] = {query: value} - else: - conditions[query] = value + put(prop, query, value) + for prop in before: + if prop not in after: + # What the values of this breakpoint do not set is what it is + # without the styles of the component. + put(prop, query, "revert-layer") before = after return out, () @@ -647,9 +664,7 @@ def _merge( } layers = ( - [] - if responsive is None - else [_responsive_layer(name, table, keys, responsive)] + [] if responsive is None else [_responsive_layer(name, table, keys, responsive)] ) if layout: layers.append(lower_layer(name, None, layout)) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py index 6c7aeedcf0b..c675fcf531f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py @@ -80,3 +80,61 @@ def _inline(element: Any, **style: Any) -> ComponentStyles: EM: ComponentStyles = _inline(tokens.em, **_BOXED) STRONG: ComponentStyles = _inline(tokens.strong) QUOTE: ComponentStyles = _inline(tokens.quote, **_BOXED) + +# The layers of the shadow of a key in both appearances: where one appearance +# has a layer of another size, the layer is transparent in the other. +_NONE = "transparent" +_KEY_SHADOW = ", ".join([ + f"{layer} light-dark({light}, {dark})" + for layer, light, dark in ( + ("inset 0 -0.05em 0.5em", tokens.gray.a[2], tokens.gray.a[3]), + ("inset 0 0.05em", tokens.white.a[12], tokens.gray.a[11]), + ("inset 0 0.25em 0.5em", tokens.gray.a[2], tokens.gray.a[2]), + ("inset 0 -0.05em", tokens.gray.a[6], _NONE), + ("inset 0 -0.1em", _NONE, tokens.black.a[11]), + ("0 0 0 0.05em", tokens.gray.a[5], _NONE), + ("0 0 0 0.075em", _NONE, tokens.gray.a[7]), + ("0 0.08em 0.17em", tokens.gray.a[7], tokens.black.a[12]), + ) +]) + +KBD: ComponentStyles = { + "base": { + "display": "inline-flex", + "align_items": "center", + "justify_content": "center", + "flex_shrink": "0", + "font_family": tokens.default.font_family, + "font_weight": "normal", + "vertical_align": "text-top", + "white_space": "nowrap", + "user_select": "none", + "position": "relative", + "top": "-0.03em", + "font_size": "0.75em", + "min_width": "1.75em", + "line_height": "1.7em", + "box_sizing": "border-box", + "padding_left": "0.5em", + "padding_right": "0.5em", + "padding_bottom": "0.05em", + "word_spacing": "-0.1em", + "border_radius": f"calc({tokens.radius.factor} * 0.35em)", + "letter_spacing": f"var(--letter-spacing, {tokens.default.letter_spacing})", + # Not stretched by a flex or grid container. + "height": "fit-content", + "color": tokens.gray[12], + # The classic variant, the one a key has. + "background_color": tokens.gray[1], + "box_shadow": _KEY_SHADOW, + }, + "variants": { + "size": { + str(step): { + "font_size": f"calc({tokens.font_size[step]} * 0.8)", + "--letter-spacing": tokens.letter_spacing[step], + } + for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) + }, + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py index b6d1b16aec2..bd906c334f0 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/text.py @@ -12,7 +12,7 @@ from reflex_components_ui.base import UIComponent from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.text import EM, QUOTE, STRONG, TEXT +from reflex_components_ui.styles.text import EM, KBD, QUOTE, STRONG, TEXT from reflex_components_ui.themes import LiteralAccentColor from reflex_components_ui.typography.base import ( LiteralTextAlign, @@ -98,6 +98,16 @@ class Em(UIComponent, elements.Em): styles: ClassVar[ComponentStyles] = EM +class Kbd(UIComponent, elements.Kbd): + """Represents keyboard input or a hotkey.""" + + tag = "kbd" + + styles: ClassVar[ComponentStyles] = KBD + + size: Var[LiteralTextSize] = field(doc='Text size: "1" - "9"') + + class Quote(UIComponent, elements.Q): """A short inline quotation.""" @@ -119,6 +129,7 @@ class TextNamespace(ComponentNamespace): __call__ = staticmethod(Text.create) em = staticmethod(Em.create) + kbd = staticmethod(Kbd.create) quote = staticmethod(Quote.create) strong = staticmethod(Strong.create) span = staticmethod(Span.create) diff --git a/pyi_hashes.json b/pyi_hashes.json index 1a475e4aae8..43de49f2237 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,10 +118,26 @@ "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": "d47c2b7331062c2d3b4588b19b2d530f", - "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "43a46ffcfbd608e124e7c9f9b971910d", - "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "fc1116971a8f022d5b67dcbe81275acb", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "04594af03ce14a1150a8c1f88a2594d7", + "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "d4866ed281752f69eef9ad719980dd8c", + "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", + "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", + "packages/reflex-components-ui/src/reflex_components_ui/components/separator.pyi": "bd32f08f7c0ff2cb6733f964ea843440", + "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", + "packages/reflex-components-ui/src/reflex_components_ui/layout/center.pyi": "a38424cf14313b5358c9ad198a7880f9", + "packages/reflex-components-ui/src/reflex_components_ui/layout/container.pyi": "ecfbd513a1a12bbfc11a6d30e91987c6", + "packages/reflex-components-ui/src/reflex_components_ui/layout/flex.pyi": "5e2dd1d1058ef41f13f9b90d45401eeb", + "packages/reflex-components-ui/src/reflex_components_ui/layout/grid.pyi": "1560afd6c556e30645708e3d91f11537", + "packages/reflex-components-ui/src/reflex_components_ui/layout/list.pyi": "c1fe75a4cf8bffae77876de74d1adb84", + "packages/reflex-components-ui/src/reflex_components_ui/layout/section.pyi": "4379b64a103fc35a7f44039aed5e149b", + "packages/reflex-components-ui/src/reflex_components_ui/layout/spacer.pyi": "b90c86986ab38b2c750cadbc1b5982cb", + "packages/reflex-components-ui/src/reflex_components_ui/layout/stack.pyi": "f89a0438e8802d5df80b63b4aae1d78f", "packages/reflex-components-ui/src/reflex_components_ui/layout/theme.pyi": "b220429b137abe449810ba9f03d044ec", + "packages/reflex-components-ui/src/reflex_components_ui/typography/blockquote.pyi": "a24a93bece60027eaf534509555a35e3", + "packages/reflex-components-ui/src/reflex_components_ui/typography/code.pyi": "f5f00376a95e1a9b1e222a90082ed39e", + "packages/reflex-components-ui/src/reflex_components_ui/typography/heading.pyi": "0b84a08b532c0a0aea6a3e9ec65601a1", + "packages/reflex-components-ui/src/reflex_components_ui/typography/link.pyi": "65a5792e27dcd5827d9b7f0981690160", + "packages/reflex-components-ui/src/reflex_components_ui/typography/text.pyi": "038aecaeeb3f1c935a0697b787966e01", "reflex/__init__.pyi": "540ab90bd8a7a89647f0bdd0a2fa3590", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" diff --git a/tests/units/reflex_components_ui/components/__init__.py b/tests/units/reflex_components_ui/components/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_components_ui/components/test_aspect_ratio.py b/tests/units/reflex_components_ui/components/test_aspect_ratio.py new file mode 100644 index 00000000000..f47a1b78d6e --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_aspect_ratio.py @@ -0,0 +1,64 @@ +"""Tests for reflex_components_ui.components.aspect_ratio.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_aspect_ratio_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An aspect ratio is a frame as high as it is wide, with the content filling it.""" + component = rx.ui.aspect_ratio("a") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_7e9d0745eb_c", '"data-radix-aspect-ratio-wrapper":""'], + "children": [ + { + "name": '"div"', + "props": ["className:sx_f0e83cb220_c"], + "children": [{"contents": '"a"'}], + } + ], + } + assert declared_styles(component) == [ + {"position": "relative", "width": "100%", "paddingBottom": "100.0%"}, + {"position": "absolute", "top": "0", "right": "0", "bottom": "0", "left": "0"}, + ] + + +def test_aspect_ratio_ratio( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The ratio sets the height of the frame, and the props go to the content.""" + component = rx.ui.aspect_ratio( + "a", ratio=16 / 9, id="video", style={"border_radius": "4px"} + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_29d4184c5f_c", '"data-radix-aspect-ratio-wrapper":""'], + "children": [ + { + "name": '"div"', + "props": ["className:sx_75437de2d8_c", 'id:"video"', "ref:ref_video"], + "children": [{"contents": '"a"'}], + } + ], + } + assert declared_styles(component) == [ + {"position": "relative", "width": "100%", "paddingBottom": "56.25%"}, + { + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "borderTopLeftRadius": "4px", + "borderTopRightRadius": "4px", + "borderBottomRightRadius": "4px", + "borderBottomLeftRadius": "4px", + }, + ] diff --git a/tests/units/reflex_components_ui/components/test_inset.py b/tests/units/reflex_components_ui/components/test_inset.py new file mode 100644 index 00000000000..c1cc4a00a14 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_inset.py @@ -0,0 +1,82 @@ +"""Tests for reflex_components_ui.components.inset.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_inset_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An inset reaches every edge of its container.""" + component = rx.ui.inset("a") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_c190e59d1d_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "overflowX": "hidden", + "overflowY": "hidden", + "--inset-border-radius-calc": "calc(var(--inset-border-radius, 0px) - " + "var(--inset-border-width, 0px))", + "--inset-padding-top-calc": "var(--inset-padding-top, 0px)", + "--inset-padding-right-calc": "var(--inset-padding-right, 0px)", + "--inset-padding-bottom-calc": "var(--inset-padding-bottom, 0px)", + "--inset-padding-left-calc": "var(--inset-padding-left, 0px)", + "marginTop": "calc(0px - var(--inset-padding-top-calc))", + "marginRight": "calc(0px - var(--inset-padding-right-calc))", + "marginBottom": "calc(0px - var(--inset-padding-bottom-calc))", + "marginLeft": "calc(0px - var(--inset-padding-left-calc))", + "borderTopLeftRadius": "var(--inset-border-radius-calc)", + "borderTopRightRadius": "var(--inset-border-radius-calc)", + "borderBottomLeftRadius": "var(--inset-border-radius-calc)", + "borderBottomRightRadius": "var(--inset-border-radius-calc)", + } + ] + + +def test_inset_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A side, the border, and the padding of the container.""" + component = rx.ui.inset( + "a", side="top", clip="padding-box", pb="current", px="0", id="cover" + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_5dd6cd8662_c", 'id:"cover"', "ref:ref_cover"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "overflowX": "hidden", + "overflowY": "hidden", + "--inset-border-radius-calc": "var(--inset-border-radius, 0px)", + "--inset-padding-top-calc": "calc(var(--inset-padding-top, 0px) + " + "var(--inset-border-width, 0px))", + "--inset-padding-right-calc": "calc(var(--inset-padding-right, 0px) + " + "var(--inset-border-width, 0px))", + "--inset-padding-bottom-calc": "calc(var(--inset-padding-bottom, 0px) + " + "var(--inset-border-width, 0px))", + "--inset-padding-left-calc": "calc(var(--inset-padding-left, 0px) + " + "var(--inset-border-width, 0px))", + "marginTop": "calc(0px - var(--inset-padding-top-calc))", + "marginRight": "calc(0px - var(--inset-padding-right-calc))", + "marginBottom": "0px", + "marginLeft": "calc(0px - var(--inset-padding-left-calc))", + "borderTopLeftRadius": "var(--inset-border-radius-calc)", + "borderTopRightRadius": "var(--inset-border-radius-calc)", + "borderBottomLeftRadius": "0px", + "borderBottomRightRadius": "0px", + "paddingLeft": "0", + "paddingRight": "0", + "paddingBottom": "var(--inset-padding-bottom)", + } + ] diff --git a/tests/units/reflex_components_ui/components/test_separator.py b/tests/units/reflex_components_ui/components/test_separator.py new file mode 100644 index 00000000000..05b42221b4c --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_separator.py @@ -0,0 +1,89 @@ +"""Tests for reflex_components_ui.components.separator.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_separator_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A separator is a gray line across its container.""" + component = rx.ui.separator() + assert component.render() == { + "name": '"span"', + "props": ["className:sx_9af5fbf21f_c"], + "children": [], + } + assert declared_styles(component) == [ + { + "display": "block", + "backgroundColor": "var(--gray-a6)", + "width": "var(--separator-size)", + "height": "1px", + "--separator-size": "100%", + } + ] + + +def test_separator_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Its length follows its size in either orientation, and it has a role unless decorative.""" + component = rx.ui.separator( + size="2", orientation="vertical", color_scheme="ruby", decorative=False + ) + assert component.render() == { + "name": '"span"', + "props": [ + 'className:sx_672d983ef5_c + " " + reflexUIClasses_e201574881', + 'role:"separator"', + ], + "children": [], + } + assert declared_styles(component) == [ + { + "display": "block", + "backgroundColor": "var(--accent-a6)", + "width": "1px", + "height": "var(--separator-size)", + "--separator-size": "var(--space-6)", + } + ] + + +def test_separator_responsive( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Both props can change at a breakpoint.""" + component = rx.ui.divider( + size=rx.breakpoints(initial="1", md="4"), + orientation=rx.breakpoints(initial="vertical", md="horizontal"), + decorative=True, + ) + assert component.render() == { + "name": '"span"', + "props": ["className:sx_3029cc93ff_c"], + "children": [], + } + assert declared_styles(component) == [ + { + "display": "block", + "backgroundColor": "var(--gray-a6)", + "width": { + "default": "1px", + "@media (min-width: 1024px)": "var(--separator-size)", + }, + "height": { + "default": "var(--separator-size)", + "@media (min-width: 1024px)": "1px", + }, + "--separator-size": { + "default": "var(--space-4)", + "@media (min-width: 1024px)": "100%", + }, + } + ] diff --git a/tests/units/reflex_components_ui/conftest.py b/tests/units/reflex_components_ui/conftest.py index bb0d1d6972a..33c2c9daedc 100644 --- a/tests/units/reflex_components_ui/conftest.py +++ b/tests/units/reflex_components_ui/conftest.py @@ -114,3 +114,40 @@ def pyright(fixture: str) -> list[tuple[int, str, str]]: ] return pyright + + +@pytest.fixture +def compiled() -> Callable[[Component], Component]: + """Give a component the styles a compile adds to it. + + Returns: + A function from a component to itself, with the styles of its + ``add_style``. + """ + + def compiled(component: Component) -> Component: + component._add_style_recursive({}) + return component + + return compiled + + +@pytest.fixture +def declared_styles() -> Callable[[Any], list[dict[str, Any]]]: + """Collect the style each rx.ui element of a tree declares. + + Returns: + A function from the root of a tree to the lowered style of each of + its rx.ui elements, parents before children. + """ + + def declared_styles(component: Any) -> list[dict[str, Any]]: + found = [] + element_styles = getattr(component, "_element_styles", None) + if element_styles is not None: + found.append(element_styles().style.style) + for child in getattr(component, "children", ()): + found.extend(declared_styles(child)) + return found + + return declared_styles diff --git a/tests/units/reflex_components_ui/layout/test_center.py b/tests/units/reflex_components_ui/layout/test_center.py new file mode 100644 index 00000000000..def34df9e3e --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_center.py @@ -0,0 +1,48 @@ +"""Tests for reflex_components_ui.layout.center.""" + +from collections.abc import Callable +from typing import Any + +from reflex_base.components.component import Component +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_center_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A center is a flex container, before the compile adds its style.""" + component = rx.ui.center("a") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_78b49527aa_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + {"boxSizing": "border-box", "display": "flex", "justifyContent": "flex-start"} + ] + + +def test_center_compiled( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """The compile centers the content, over the props of the element.""" + component = compiled(rx.ui.center("a", align="start", spacing="2")) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_58f475335d_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "center", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + } + ] diff --git a/tests/units/reflex_components_ui/layout/test_container.py b/tests/units/reflex_components_ui/layout/test_container.py new file mode 100644 index 00000000000..be02ef494a6 --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_container.py @@ -0,0 +1,79 @@ +"""Tests for reflex_components_ui.layout.container.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_container_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A container centers an inner div of its default width, with padding.""" + component = rx.ui.container("a") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_4d7dc9707b_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_5cfb91b5e6_c"], + "children": [{"contents": '"a"'}], + } + ], + } + assert declared_styles(component) == [ + { + "display": "flex", + "boxSizing": "border-box", + "flexDirection": "column", + "alignItems": "center", + "flexShrink": "0", + "flexGrow": "1", + "paddingTop": "16px", + "paddingRight": "16px", + "paddingBottom": "16px", + "paddingLeft": "16px", + }, + {"width": "100%", "maxWidth": "880px"}, + ] + + +def test_container_sizes( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The size bounds the inner div, and the padding is the element's.""" + component = rx.ui.container( + "a", size=rx.breakpoints(initial="1", md="4"), padding="0px", id="page" + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_5ce2c30d05_c", 'id:"page"', "ref:ref_page"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_974d132e83_c"], + "children": [{"contents": '"a"'}], + } + ], + } + assert declared_styles(component) == [ + { + "display": "flex", + "boxSizing": "border-box", + "flexDirection": "column", + "alignItems": "center", + "flexShrink": "0", + "flexGrow": "1", + "paddingTop": "0px", + "paddingRight": "0px", + "paddingBottom": "0px", + "paddingLeft": "0px", + }, + { + "width": "100%", + "maxWidth": {"default": "448px", "@media (min-width: 1024px)": "1136px"}, + }, + ] diff --git a/tests/units/reflex_components_ui/layout/test_flex.py b/tests/units/reflex_components_ui/layout/test_flex.py new file mode 100644 index 00000000000..3b4ba47ee12 --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_flex.py @@ -0,0 +1,85 @@ +"""Tests for reflex_components_ui.layout.flex.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_flex_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A flex container is a div that lays its children out in a row.""" + component = rx.ui.flex("a", "b") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_78b49527aa_c"], + "children": [{"contents": '"a"'}, {"contents": '"b"'}], + } + assert declared_styles(component) == [ + {"boxSizing": "border-box", "display": "flex", "justifyContent": "flex-start"} + ] + + +def test_flex_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Its props are styles, on the breakpoints of Radix Themes.""" + component = rx.ui.flex( + "a", + direction=rx.breakpoints(initial="column", md="row"), + align="center", + justify="between", + wrap="wrap", + spacing="3", + id="row", + title="A row", + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_a66dcbf62c_c", + 'id:"row"', + "ref:ref_row", + 'title:"A row"', + ], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "space-between", + "alignItems": "center", + "flexDirection": {"default": "column", "@media (min-width: 1024px)": "row"}, + "rowGap": "var(--space-3)", + "columnGap": "var(--space-3)", + "flexWrap": "wrap", + } + ] + + +def test_flex_style_over_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The style of the element wins over its props.""" + component = rx.ui.flex( + "a", spacing="3", gap="1px", direction="column", style={"flex_direction": "row"} + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_1126f0dad7_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "flex-start", + "flexDirection": "row", + "rowGap": "1px", + "columnGap": "1px", + } + ] diff --git a/tests/units/reflex_components_ui/layout/test_grid.py b/tests/units/reflex_components_ui/layout/test_grid.py new file mode 100644 index 00000000000..e5bd9aa81ad --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_grid.py @@ -0,0 +1,68 @@ +"""Tests for reflex_components_ui.layout.grid.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_grid_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A grid is a div with one column until it is told otherwise.""" + component = rx.ui.grid("a", "b") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_c885f4149b_c"], + "children": [{"contents": '"a"'}, {"contents": '"b"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "stretch", + "justifyContent": "flex-start", + "gridTemplateColumns": "minmax(0, 1fr)", + "gridTemplateRows": "none", + } + ] + + +def test_grid_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Counts become tracks of equal size, anything else is CSS.""" + component = rx.ui.grid( + "a", + columns=rx.breakpoints(initial="1", sm="3"), + rows="repeat(2, 64px)", + flow="row-dense", + align="end", + justify="center", + spacing="2", + spacing_x="4", + spacing_y="1", + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_7fdc4cc3b1_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "flex-end", + "justifyContent": "center", + "gridTemplateColumns": { + "default": "repeat(1, minmax(0, 1fr))", + "@media (min-width: 768px)": "repeat(3, minmax(0, 1fr))", + }, + "gridTemplateRows": "repeat(2, 64px)", + "gridAutoFlow": "row dense", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-4)", + } + ] diff --git a/tests/units/reflex_components_ui/layout/test_list.py b/tests/units/reflex_components_ui/layout/test_list.py new file mode 100644 index 00000000000..05670ebadfa --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_list.py @@ -0,0 +1,101 @@ +"""Tests for reflex_components_ui.layout.list.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_list_unordered( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An unordered list is a ul of items with discs and room for them.""" + component = rx.ui.list.unordered(items=["a", "b"]) + assert component.render() == { + "name": '"ul"', + "props": ["className:sx_9d24074fc7_c"], + "children": [ + {"name": '"li"', "props": [], "children": [{"contents": '"a"'}]}, + {"name": '"li"', "props": [], "children": [{"contents": '"b"'}]}, + ], + } + assert declared_styles(component) == [ + {"listStyleType": "disc", "marginLeft": "1.5rem"}, + {}, + {}, + ] + + +def test_list_ordered( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An ordered list is an ol with numbers, or the marker it is given.""" + component = rx.ui.list.ordered( + rx.ui.list.item("a", id="first"), list_style_type="upper-roman", margin_left="0" + ) + assert component.render() == { + "name": '"ol"', + "props": ["className:sx_c4dab3f068_c"], + "children": [ + { + "name": '"li"', + "props": ['id:"first"', "ref:ref_first"], + "children": [{"contents": '"a"'}], + } + ], + } + assert declared_styles(component) == [ + {"listStyleType": "upper-roman", "marginLeft": "0"}, + {}, + ] + + +def test_list_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A plain list has no marker and no indent, and its marker wins over the style.""" + component = rx.ui.list( + rx.ui.list.item("a"), style={"list_style_type": "disc", "color": "red"} + ) + assert component.render() == { + "name": '"ul"', + "props": ["className:sx_98c5add4ad_c"], + "children": [{"name": '"li"', "props": [], "children": [{"contents": '"a"'}]}], + } + assert declared_styles(component) == [{"color": "red", "listStyleType": "none"}, {}] + + +def test_list_item( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Text inside an item is a span, and an icon is inline.""" + component = rx.ui.list.item(rx.icon("check"), rx.ui.text("done")) + assert component.render() == { + "name": '"li"', + "props": [], + "children": [ + { + "name": "LucideCheck", + "props": ['css:({ ["display"] : "inline" })'], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_af8fa2456e_c"], + "children": [{"contents": '"done"'}], + }, + ], + } + assert declared_styles(component) == [ + {}, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + }, + ] diff --git a/tests/units/reflex_components_ui/layout/test_section.py b/tests/units/reflex_components_ui/layout/test_section.py new file mode 100644 index 00000000000..05c5295e67f --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_section.py @@ -0,0 +1,56 @@ +"""Tests for reflex_components_ui.layout.section.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_section_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A section has the space of its default size above and below.""" + component = rx.ui.section("a") + assert component.render() == { + "name": '"section"', + "props": ["className:sx_e51f3ff1bc_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "flexShrink": "0", + "paddingTop": "var(--space-7)", + "paddingBottom": "var(--space-7)", + } + ] + + +def test_section_sizes( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Each size is a step of the space scale, per breakpoint.""" + component = rx.ui.section( + "a", size=rx.breakpoints(initial="1", lg="3"), id="pricing" + ) + assert component.render() == { + "name": '"section"', + "props": ["className:sx_ec9b9c5834_c", 'id:"pricing"', "ref:ref_pricing"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "flexShrink": "0", + "paddingTop": { + "default": "var(--space-5)", + "@media (min-width: 1280px)": "var(--space-9)", + }, + "paddingBottom": { + "default": "var(--space-5)", + "@media (min-width: 1280px)": "var(--space-9)", + }, + } + ] diff --git a/tests/units/reflex_components_ui/layout/test_spacer.py b/tests/units/reflex_components_ui/layout/test_spacer.py new file mode 100644 index 00000000000..313e76a2dfb --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_spacer.py @@ -0,0 +1,33 @@ +"""Tests for reflex_components_ui.layout.spacer.""" + +from collections.abc import Callable +from typing import Any + +from reflex_base.components.component import Component +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_spacer_compiled( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """A spacer grows to take the room its siblings leave.""" + component = compiled(rx.ui.spacer()) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_a2aca5400f_c"], + "children": [], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "flex-start", + "flex": 1, + "justifySelf": "stretch", + "alignSelf": "stretch", + } + ] diff --git a/tests/units/reflex_components_ui/layout/test_stack.py b/tests/units/reflex_components_ui/layout/test_stack.py new file mode 100644 index 00000000000..ce402e34dfc --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_stack.py @@ -0,0 +1,78 @@ +"""Tests for reflex_components_ui.layout.stack.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_stack_stack( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A stack has a gap and aligns its children at the start.""" + component = rx.ui.stack("a", "b") + assert component.render() == { + "name": '"div"', + "props": ['className:"rx-Stack " + sx_e8554125f7_c'], + "children": [{"contents": '"a"'}, {"contents": '"b"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "flex-start", + "alignItems": "flex-start", + "rowGap": "var(--space-3)", + "columnGap": "var(--space-3)", + } + ] + + +def test_stack_hstack( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A horizontal stack is a row, whatever the class names it is given.""" + component = rx.ui.hstack("a", class_name="toolbar", spacing="1") + assert component.render() == { + "name": '"div"', + "props": ['className:"rx-Stack toolbar " + sx_ddd1ab0711_c'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "flex-start", + "alignItems": "flex-start", + "flexDirection": "row", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + } + ] + + +def test_stack_vstack( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A vertical stack is a column.""" + component = rx.ui.vstack( + "a", align="center", direction=rx.breakpoints(initial="column", sm="row") + ) + assert component.render() == { + "name": '"div"', + "props": ['className:"rx-Stack " + sx_f669e55d47_c'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "flex-start", + "alignItems": "center", + "flexDirection": {"default": "column", "@media (min-width: 768px)": "row"}, + "rowGap": "var(--space-3)", + "columnGap": "var(--space-3)", + } + ] diff --git a/tests/units/reflex_components_ui/parity/test_allowlist.py b/tests/units/reflex_components_ui/parity/test_allowlist.py index 40520d3d614..429f16377e5 100644 --- a/tests/units/reflex_components_ui/parity/test_allowlist.py +++ b/tests/units/reflex_components_ui/parity/test_allowlist.py @@ -2,6 +2,7 @@ import pytest import reflex_components_ui +from reflex_base.components.component import ComponentNamespace from ui_parity import allowlist from ui_parity.allowlist import ( Allowlist, @@ -214,6 +215,13 @@ def test_differences_markdown_lists_every_entry_by_component(): def test_committed_allowlist_names_only_rx_ui_components(): components = set(reflex_components_ui.__all__) + # A member of a namespace is listed by its own name: "kbd" is text.kbd. + for name in reflex_components_ui.__all__: + value = getattr(reflex_components_ui, name) + if isinstance(value, ComponentNamespace): + components.update( + member for member in dir(value) if not member.startswith("_") + ) entries = allowlist.load() listed = { entry.component for entry in (*entries.api, *entries.contract, *entries.look) diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index 768dd619dc3..dce347f045d 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -1461,3 +1461,48 @@ def test_design_tokens(style: Any, expected: dict[str, Any], imports: tuple[str, lowered = lower("rx.ui.card", style) assert lowered == Lowered(expected, imports) assert lowered.imports == imports + + +@pytest.mark.parametrize( + ("layout", "message"), + [ + ( + {"p": {"tablet": "1"}}, + ( + 'rx.ui.flex: prop "p" is given a value under "tablet", which is not a ' + 'breakpoint. Use "initial", "xs", "sm", "md", "lg" or "xl", or set a ' + "style, which takes any media query." + ), + ), + ( + {"gap": ["1"] * 7}, + ( + 'rx.ui.flex: layout prop "gap" has 7 responsive values, but there are ' + "only 6 breakpoints." + ), + ), + ], +) +def test_layout_prop_breakpoint_errors(layout: dict[str, Any], message: str): + with pytest.raises(StyleError) as error: + lower("rx.ui.flex", None, layout) + assert str(error.value) == message + + +def test_layout_props_keep_the_breakpoints_of_radix_whatever_the_app_has(): + """A prop is resolved as Radix Themes resolves it; a style follows the app.""" + original = tuple(breakpoints_values) + set_breakpoints(("10px", "20px", "30px", "40px", "50px")) + try: + lowered = lower( + "rx.ui.flex", + {"width": rx.breakpoints(sm="2px")}, + {"spacing_x": rx.breakpoints(sm="2"), "spacing_y": ["1", "3"]}, + ) + finally: + set_breakpoints(original) # pyright: ignore [reportArgumentType] + assert lowered.style == { + "columnGap": {PROP_SM: "var(--space-2)"}, + "rowGap": {"default": "var(--space-1)", PROP_XS: "var(--space-3)"}, + "width": {"@media screen and (min-width: 20px)": "2px"}, + } diff --git a/tests/units/reflex_components_ui/style/test_merge.py b/tests/units/reflex_components_ui/style/test_merge.py index 431d7cb7b44..51878eef2b1 100644 --- a/tests/units/reflex_components_ui/style/test_merge.py +++ b/tests/units/reflex_components_ui/style/test_merge.py @@ -12,6 +12,7 @@ ComponentStyles, Merged, merge, + over, ) import reflex as rx @@ -546,3 +547,202 @@ def test_several_styles_are_merged_in_order(): assert merge("rx.ui.button", {"base": {"color": "black"}}, style=[]) == merge( "rx.ui.button", {"base": {"color": "black"}} ) + + +# A table whose props can each be given a value per breakpoint. +RESPONSIVE_TABLE: Any = { + "base": {"display": "block", "color": "black"}, + "variants": { + "size": { + "1": {"height": "1px", "color": "red"}, + "2": {"height": "2px"}, + "3": {"height": "3px", "_hover": {"color": "blue"}}, + }, + "tone": {"true": {"opacity": "0.5"}}, + }, + "defaults": {"size": "2"}, + "compound": [{"props": {"size": "3", "tone": "true"}, "style": {"width": "9px"}}], + "parts": { + "icon": { + "variants": {"size": {"1": {"width": "1em"}, "3": {"width": "3em"}}}, + }, + }, +} +PROP_XS = "@media (min-width: 520px)" +PROP_SM = "@media (min-width: 768px)" +PROP_MD = "@media (min-width: 1024px)" +PROP_LG = "@media (min-width: 1280px)" +PROP_XL = "@media (min-width: 1640px)" +HOVERED = {"default": "black", ":hover": "blue"} + + +@pytest.mark.parametrize( + ("props", "expected", "icon"), + [ + # A prop that is left out selects the default of the table. + (None, {"display": "block", "color": "black", "height": "2px"}, {}), + ( + {"size": "1"}, + {"display": "block", "color": "red", "height": "1px"}, + {"width": "1em"}, + ), + # Each property changes at the breakpoint its value changes at. + ( + {"size": rx.breakpoints(initial="1", md="3")}, + { + "display": "block", + "color": {"default": "red", PROP_MD: HOVERED}, + "height": {"default": "1px", PROP_MD: "3px"}, + }, + {"width": {"default": "1em", PROP_MD: "3em"}}, + ), + # Without a first value the default holds until the first breakpoint, + # and a compound style applies from where every prop has its value. + ( + {"size": rx.breakpoints(sm="1", lg="3"), "tone": True}, + { + "display": "block", + "color": {"default": "black", PROP_SM: "red", PROP_LG: HOVERED}, + "height": {"default": "2px", PROP_SM: "1px", PROP_LG: "3px"}, + "opacity": "0.5", + "width": {PROP_LG: "9px"}, + }, + {"width": {PROP_SM: "1em", PROP_LG: "3em"}}, + ), + # What the values of a breakpoint no longer set is given back. + ( + { + "size": rx.breakpoints(initial="3", xs="1", xl="3"), + "tone": rx.breakpoints(initial=True, sm=False), + }, + { + "display": "block", + "color": {**HOVERED, PROP_XS: "red", PROP_XL: HOVERED}, + "height": {"default": "3px", PROP_XS: "1px", PROP_XL: "3px"}, + "opacity": {"default": "0.5", PROP_SM: "revert-layer"}, + "width": {"default": "9px", PROP_XS: "revert-layer"}, + }, + {"width": {"default": "3em", PROP_XS: "1em", PROP_XL: "3em"}}, + ), + # A value that does not change at a breakpoint adds no condition. + ( + {"size": {"initial": "1", "md": "1"}}, + {"display": "block", "color": "red", "height": "1px"}, + {"width": "1em"}, + ), + # As a component holds it: a literal Var. + ( + {"size": LiteralVar.create(rx.breakpoints(initial="1", md="3"))}, + { + "display": "block", + "color": {"default": "red", PROP_MD: HOVERED}, + "height": {"default": "1px", PROP_MD: "3px"}, + }, + {"width": {"default": "1em", PROP_MD: "3em"}}, + ), + ], +) +def test_prop_per_breakpoint_resolves_each_property_mobile_first( + props: Any, expected: dict[str, Any], icon: dict[str, Any] +): + """A responsive prop is resolved on the breakpoints of Radix Themes. + + Args: + props: The props of the element. + expected: The lowered properties of the element. + icon: The lowered properties of its part. + """ + merged = merge("rx.ui.card", RESPONSIVE_TABLE, props) + assert merged.style.style == expected + assert merged.parts["icon"].style.style == icon + assert merged.dynamic == () + + +def test_prop_per_breakpoint_merges_under_the_layout_props_and_the_style(): + merged = merge( + "rx.ui.card", + RESPONSIVE_TABLE, + {"size": rx.breakpoints(initial="1", md="3")}, + {"height": "5px", "_hover": {"color": "green"}}, + {"p": rx.breakpoints(md="2")}, + ) + padding = {PROP_MD: "var(--space-2)"} + assert merged.style.style == { + "display": "block", + "color": {"default": "red", PROP_MD: HOVERED, ":hover": "green"}, + "height": "5px", + "paddingTop": padding, + "paddingRight": padding, + "paddingBottom": padding, + "paddingLeft": padding, + } + + +def test_default_of_the_table_is_what_a_state_bound_prop_falls_back_to(): + """A value the table does not list gets the style of the default.""" + merged = merge("rx.ui.card", RESPONSIVE_TABLE, {"size": SIZE}) + assert merged.style.style == { + "display": "block", + "color": "black", + "height": "2px", + } + (alternatives,) = merged.dynamic + assert alternatives.props == ("size",) + assert {combo: style.style for combo, style in alternatives.values.items()} == { + ("1",): {"color": "red", "height": "1px"}, + ("3",): {"height": "3px", "color": HOVERED}, + } + + +@pytest.mark.parametrize( + ("props", "message"), + [ + ( + {"size": rx.breakpoints(custom={"640px": "1"})}, + ( + 'rx.ui.card: prop "size" is given a value under "640px", which is not ' + 'a breakpoint. Use "initial", "xs", "sm", "md", "lg" or "xl", or set a ' + "style, which takes any media query." + ), + ), + ( + {"size": {"initial": "1", "md": SIZE}}, + ( + 'rx.ui.card: prop "size" is given a value under "md" that is not ' + "known at compile time. Give each breakpoint one of the values of the " + "prop." + ), + ), + ], +) +def test_prop_per_breakpoint_errors(props: Any, message: str): + with pytest.raises(StyleError) as error: + merge("rx.ui.card", RESPONSIVE_TABLE, props) + assert str(error.value) == message + + +def test_over_lays_the_styles_of_a_child_on_those_of_its_parent(): + """For as_child: the child wins by property, and keeps what it only adds to.""" + parent = merge( + "rx.ui.flex", + {"base": {"color": "red", "top": "1px", "_hover": {"color": "blue"}}}, + {}, + # A whole style bound to state is carried along. + SIZE, + ) + child = merge( + "rx.ui.link", + { + "base": {"top": "2px", "left": "0", "_hover": {"color": "green"}}, + "parts": {"icon": {"base": {"width": "1em"}}}, + }, + ) + merged = over(parent, child) + assert merged.style.style == { + "color": {"default": "red", ":hover": "green"}, + "top": "2px", + "left": "0", + } + assert merged.style.inline is SIZE + assert merged.dynamic == () + assert merged.parts == {"icon": Merged(Lowered({"width": "1em"}))} diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index ea3847fce9a..db2f1101a12 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -5,11 +5,13 @@ reason the migration guide gives for it. """ +import functools import types from typing import Any, Literal +import pytest import reflex_components_ui -from reflex_base.components.component import Component +from reflex_base.components.component import Component, ComponentNamespace from reflex_base.event import EventHandler, no_args_event_spec from reflex_base.vars.base import Var from reflex_components_ui.base import UIComponent @@ -26,13 +28,59 @@ import reflex as rx -# 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 members(namespace: ComponentNamespace) -> list[str]: + """List the components a namespace creates beside the one it is called for. + + Args: + namespace: A namespace of components, such as ``rx.text``. + + Returns: + The names of its members, sorted. + """ + return sorted( + name + for name in dir(namespace) + if not name.startswith("_") + and isinstance(getattr(namespace, name), types.MethodType) + ) + + +def component_names() -> list[str]: + """List the names of rx.ui that create a component. + + A theme of the plugin and the design tokens are no components. A + namespace is its own name, then each of its members: ``text``, + ``text.em``. + + Returns: + The names, sorted. + """ + names = [] + for name in reflex_components_ui.__all__: + value = getattr(reflex_components_ui, name) + if isinstance(value, types.MethodType): + names.append(name) + elif isinstance(value, ComponentNamespace): + names.append(name) + names.extend(f"{name}.{member}" for member in members(value)) + return sorted(names) + + +COMPONENTS = component_names() + + +def resolve(namespace: Any, component: str) -> Any: + """Find a component by its name in a namespace. + + Args: + namespace: ``rx`` or ``rx.ui``. + component: The name, dotted for a member of a namespace. + + Returns: + What creates the component. + """ + return functools.reduce(getattr, component.split("."), namespace) def differences(component: str) -> list[ApiDifference]: @@ -46,8 +94,52 @@ def differences(component: str) -> list[ApiDifference]: """ return diff_api( component, - component_class(getattr(rx, component)), - component_class(getattr(reflex_components_ui, component)), + component_class(resolve(rx, component)), + component_class(resolve(reflex_components_ui, component)), + ) + + +def test_the_wave_of_layout_and_typography_is_in_the_namespace(): + assert COMPONENTS == [ + "aspect_ratio", + "blockquote", + "box", + "center", + "code", + "container", + "divider", + "flex", + "grid", + "heading", + "hstack", + "inset", + "link", + "list", + "list.item", + "list.ordered", + "list.unordered", + "list_item", + "ordered_list", + "section", + "separator", + "spacer", + "stack", + "text", + "text.em", + "text.kbd", + "text.quote", + "text.span", + "text.strong", + "theme", + "unordered_list", + "vstack", + ] + + +@pytest.mark.parametrize("namespace", ["list", "text"]) +def test_namespace_has_the_members_of_its_radix_counterpart(namespace: str): + assert members(getattr(reflex_components_ui, namespace)) == members( + getattr(rx, namespace) ) diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py index 2ca3bfa9639..7418275dbb1 100644 --- a/tests/units/reflex_components_ui/test_base.py +++ b/tests/units/reflex_components_ui/test_base.py @@ -11,6 +11,7 @@ from reflex_base.utils.exceptions import ConfigError from reflex_base.utils.serializers import serialize from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive from reflex_components_ui import tokens from reflex_components_ui.base import Part, UIComponent from reflex_components_ui.plugin import UIPlugin @@ -19,6 +20,7 @@ import reflex as rx from reflex.compiler import compiler +from reflex.compiler.plugins.builtin import ApplyStylePlugin # A page whose elements use the tokens of two modules, two of them equally. PAGE = """import * as stylex from "@stylexjs/stylex" @@ -897,3 +899,287 @@ def test_dynamic_component_cannot_have_a_color_scheme(): "the StyleX compiler. Render the component in a page and show it with " "rx.cond." ) + + +class Tag(UIComponent, rx.el.elements.Span): + """A component with every kind of prop that changes its element.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = { + "base": {"display": "inline-flex"}, + "variants": { + "size": {"1": {"height": "1em"}, "2": {"height": "2em"}}, + # A variant wins the name over the layout prop `align`. + "align": {"left": {"text_align": "left"}}, + }, + } + + _as_tags: ClassVar[frozenset[str]] = frozenset(("span", "label")) + + as_child: Var[bool] + + as_: Var[Literal["span", "label", "kbd"]] + + size: Var[Responsive[Literal["1", "2"]]] + + align: Var[Literal["left"]] + + spacing: Var[Literal["1", "2", "3"]] = Var.create("2") + + +TAG_STYLE = { + "display": "inline-flex", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", +} + + +def test_element_class_gives_a_component_the_attributes_of_its_tag( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The element's props are attributes, never styles.""" + component = Tag.create("new", title="New", tab_index=0, hidden=True) + assert component.render() == { + "name": '"span"', + "props": [ + "className:sx_b2180e046d_c", + "hidden:true", + "tabIndex:0", + 'title:"New"', + ], + "children": [{"contents": '"new"'}], + } + assert declared_styles(component)[0] == TAG_STYLE + + +def test_default_of_a_layout_prop_applies_until_the_element_sets_it( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + assert declared_styles(Tag.create(spacing="1"))[0] == { + "display": "inline-flex", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + } + + +def test_prop_a_table_reads_is_a_variant_whatever_its_name( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + assert declared_styles(Tag.create(align="left"))[0] == { + **TAG_STYLE, + "textAlign": "left", + } + + +@pytest.mark.parametrize( + ("props", "message"), + [ + ( + {"size": "12"}, + 'rx.ui.tag: unknown size "12". Did you mean "2"? The values are "1", "2".', + ), + ( + {"size": rx.breakpoints(initial="1", md="large")}, + 'rx.ui.tag: unknown size "large". The values are "1", "2".', + ), + ( + {"spacing": "5"}, + 'rx.ui.tag: unknown spacing "5". The values are "1", "2", "3".', + ), + ( + {"as_": "labl"}, + ( + 'rx.ui.tag: unknown as_ "labl". Did you mean "label"? The values ' + 'are "span", "label", "kbd".' + ), + ), + ], +) +def test_value_a_prop_does_not_take_names_the_component_and_the_values( + props: dict[str, Any], message: str +): + with pytest.raises(StyleError) as error: + Tag.create(**props) + assert str(error.value) == message + + +@pytest.mark.parametrize( + ("as_", "tag"), + [ + (None, '"span"'), + ("label", '"label"'), + # A tag Radix Themes does not render falls back to the component's. + ("kbd", '"span"'), + # Bound to state, the tag is an expression. + (Var("kind", _var_type=str), "kind"), + ], +) +def test_as_names_the_tag_of_the_element(ui_plugin: UIPlugin, as_: Any, tag: str): + component = Tag.create("new", as_=as_) + assert component.render() == { + "name": tag, + "props": ["className:sx_b2180e046d_c"], + "children": [{"contents": '"new"'}], + } + + +def test_as_child_renders_the_child_with_the_props_and_styles_of_both( + ui_plugin: UIPlugin, +): + """The props of the child win; the class names of both stand together.""" + component = Tag.create( + rx.el.a("docs", href="/docs", title="Docs", class_name="mine"), + as_child=True, + title="A tag", + id="tag", + class_name="yours", + size="1", + ) + assert component.render() == { + "name": "ReactRouterLink", + "props": [ + 'className:"yours mine " + sx_df8e5c49fb_c', + 'id:"tag"', + "ref:ref_tag", + 'title:"Docs"', + 'to:"/docs"', + ], + "children": [{"contents": '"docs"'}], + } + + +def test_as_child_merges_the_styles_of_an_rx_ui_child_over_its_own( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """One declaration holds the styles of both, the child's winning.""" + child = Plain.create("inner", color="red", display="grid") + component = Tag.create(child, as_child=True, size="2", spacing="1") + assert declared_styles(component)[0] == { + "display": "grid", + "height": "2em", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + "color": "red", + } + # The child declares nothing of its own. + assert declared_styles(child)[0] == {} + assert child.add_custom_code() == [] + assert component.render() == { + "name": '"div"', + "props": ["className:sx_e7a15007dc_c"], + "children": [{"contents": '"inner"'}], + } + + +def test_as_child_reaches_through_a_child_that_has_it_too( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + component = Tag.create( + Tag.create(rx.el.a("docs", href="/docs"), as_child=True, size="1"), + as_child=True, + size="2", + id="outer", + ) + assert declared_styles(component)[0] == {**TAG_STYLE, "height": "1em"} + assert component.render() == { + "name": "ReactRouterLink", + "props": [ + "className:sx_df8e5c49fb_c", + 'id:"outer"', + "ref:ref_outer", + 'to:"/docs"', + ], + "children": [{"contents": '"docs"'}], + } + + +@pytest.mark.parametrize( + ("children", "as_child", "message"), + [ + ( + (), + True, + ( + "rx.ui.tag: as_child renders the only child in place of the element, " + "so it needs exactly one child that is an element, not none." + ), + ), + ( + ("one", "two"), + True, + ( + "rx.ui.tag: as_child renders the only child in place of the element, " + "so it needs exactly one child that is an element, not 2 children." + ), + ), + ( + ("text",), + True, + ( + "rx.ui.tag: as_child renders the only child in place of the element, " + "so it needs exactly one child that is an element, not a Bare." + ), + ), + ( + ("text",), + Var("open", _var_type=bool), + ( + "rx.ui.tag: as_child is bound to state, but the element is chosen at " + "compile time. Give it True or False, and choose between two " + "components with rx.cond." + ), + ), + ], +) +def test_as_child_needs_one_element_known_at_compile_time( + children: tuple[Any, ...], as_child: Any, message: str +): + with pytest.raises(StyleError) as error: + Tag.create(*children, as_child=as_child) + assert str(error.value) == message + + +class Centered(Tag): + """A component whose class adds a style when an app is compiled.""" + + def add_style(self) -> dict[str, Any] | None: + """Add the style of the class. + + Returns: + The style. + """ + return {"justify_content": "center", "display": "flex"} + + +CENTERED_PAGE = """import * as stylex from "@stylexjs/stylex" +import "$/reflex-ui/tokens/space.stylex.js" +import {Fragment,useEffect} from "react" +import {jsx} from "@emotion/react" + + + +const sx_95585a7173 = stylex.create({ s: {"display": "flex", "rowGap": "var(--space-2)", "columnGap": "var(--space-2)", "justifyContent": "center", "color": "red"} }); +const sx_95585a7173_c = stylex.props(sx_95585a7173.s).className; + +function Component() { + + + return ( + jsx(Fragment,{},jsx("span",{className:sx_95585a7173_c},"new"),jsx("title",{}," | Index"),jsx("meta",{content:"",property:"og:image"},)) + ) +} +Component.displayName = "Component(/)"; + +export default Component; +""" + + +def test_compile_merges_the_styles_it_gives_a_copy_of_the_component( + ui_plugin: UIPlugin, compile_page: Callable[..., CompileContext] +): + """The style of ``add_style`` reaches the declaration of a compiled page.""" + page = compile_page( + lambda: Centered.create("new", color="red"), ApplyStylePlugin(style={}) + ) + assert page.compiled_pages["/"].output_code == CENTERED_PAGE diff --git a/tests/units/reflex_components_ui/typography/__init__.py b/tests/units/reflex_components_ui/typography/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_components_ui/typography/test_blockquote.py b/tests/units/reflex_components_ui/typography/test_blockquote.py new file mode 100644 index 00000000000..3fb03b34c11 --- /dev/null +++ b/tests/units/reflex_components_ui/typography/test_blockquote.py @@ -0,0 +1,78 @@ +"""Tests for reflex_components_ui.typography.blockquote.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_blockquote_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A block quotation is text with a rule in the accent beside it.""" + component = rx.ui.blockquote("a") + assert component.render() == { + "name": '"blockquote"', + "props": ["className:sx_2166c3832e_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "boxSizing": "border-box", + "borderLeftWidth": "max(var(--space-1), 0.25em)", + "borderLeftStyle": "solid", + "borderLeftColor": "var(--accent-a6)", + "paddingLeft": "min(var(--space-5), max(var(--space-3), 0.5em))", + } + ] + + +def test_blockquote_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """It has the size, weight and color of text.""" + component = rx.ui.blockquote( + "a", + size="4", + weight="light", + color_scheme="plum", + high_contrast=True, + cite="https://example.com", + ) + assert component.render() == { + "name": '"blockquote"', + "props": [ + 'cite:"https://example.com"', + 'className:sx_a40e05b616_c + " " + reflexUIClasses_3c6adfa0ad', + ], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "boxSizing": "border-box", + "borderLeftWidth": "max(var(--space-1), 0.25em)", + "borderLeftStyle": "solid", + "borderLeftColor": "var(--accent-a6)", + "paddingLeft": "min(var(--space-5), max(var(--space-3), 0.5em))", + "fontSize": "var(--font-size-4)", + "--line-height": "var(--line-height-4)", + "--letter-spacing": "var(--letter-spacing-4)", + "fontWeight": "var(--font-weight-light)", + "--rx-accent-text": "var(--accent-12)", + "color": "var(--accent-12)", + } + ] diff --git a/tests/units/reflex_components_ui/typography/test_code.py b/tests/units/reflex_components_ui/typography/test_code.py new file mode 100644 index 00000000000..a593feb24cb --- /dev/null +++ b/tests/units/reflex_components_ui/typography/test_code.py @@ -0,0 +1,229 @@ +"""Tests for reflex_components_ui.typography.code.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_code_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Code is soft unless told otherwise, and says so to a link around it.""" + component = rx.ui.code("a") + assert component.render() == { + "name": '"code"', + "props": ["className:sx_1e9979b5c2_c", '"data-variant":"soft"'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "--code-variant-font-size-adjust": "calc(var(--code-font-size-adjust) * 0.95)", + "fontFamily": "var(--code-font-family)", + "fontSize": "calc(var(--code-variant-font-size-adjust) * 1em)", + "fontStyle": "var(--code-font-style)", + "fontWeight": "var(--code-font-weight)", + "lineHeight": "1.25", + "letterSpacing": "calc(var(--code-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "borderRadius": "calc((0.5px + 0.2em) * var(--radius-factor))", + "boxSizing": "border-box", + "paddingTop": "var(--code-padding-top)", + "paddingLeft": "var(--code-padding-left)", + "paddingBottom": "var(--code-padding-bottom)", + "paddingRight": "var(--code-padding-right)", + "height": "fit-content", + "backgroundColor": { + "default": "var(--accent-a3)", + "@media (hover: hover)": { + ":hover": "var(--rx-link-code-soft, var(--accent-a3))" + }, + }, + "color": "var(--accent-a11)", + } + ] + + +def test_code_ghost( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Ghost code has no box, and a color only when it is given one.""" + component = rx.ui.box( + rx.ui.code("a", variant="ghost"), + rx.ui.code("b", variant="ghost", color_scheme="ruby", high_contrast=True), + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_b26ac4fb71_c"], + "children": [ + { + "name": '"code"', + "props": ["className:sx_35379f6a4b_c", '"data-variant":"ghost"'], + "children": [{"contents": '"a"'}], + }, + { + "name": '"code"', + "props": [ + 'className:sx_83425e1e1d_c + " " + reflexUIClasses_e201574881', + '"data-variant":"ghost"', + ], + "children": [{"contents": '"b"'}], + }, + ], + } + assert declared_styles(component) == [ + {"boxSizing": "border-box", "display": "block"}, + { + "--code-variant-font-size-adjust": "var(--code-font-size-adjust)", + "fontFamily": "var(--code-font-family)", + "fontSize": "calc(var(--code-variant-font-size-adjust) * 1em)", + "fontStyle": "var(--code-font-style)", + "fontWeight": "var(--code-font-weight)", + "lineHeight": "1.25", + "letterSpacing": "calc(var(--code-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "borderRadius": "calc((0.5px + 0.2em) * var(--radius-factor))", + "boxSizing": "border-box", + "paddingTop": "0", + "paddingLeft": "0", + "paddingBottom": "0", + "paddingRight": "0", + "height": "fit-content", + }, + { + "--code-variant-font-size-adjust": "var(--code-font-size-adjust)", + "fontFamily": "var(--code-font-family)", + "fontSize": "calc(var(--code-variant-font-size-adjust) * 1em)", + "fontStyle": "var(--code-font-style)", + "fontWeight": "var(--code-font-weight)", + "lineHeight": "1.25", + "letterSpacing": "calc(var(--code-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "borderRadius": "calc((0.5px + 0.2em) * var(--radius-factor))", + "boxSizing": "border-box", + "paddingTop": "0", + "paddingLeft": "0", + "paddingBottom": "0", + "paddingRight": "0", + "height": "fit-content", + "--rx-accent-text": "var(--accent-12)", + "color": "var(--accent-12)", + }, + ] + + +def test_code_solid( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Solid code in high contrast, at a size.""" + component = rx.ui.code( + "a", variant="solid", high_contrast=True, size="2", weight="bold" + ) + assert component.render() == { + "name": '"code"', + "props": ["className:sx_d6bd7d723a_c", '"data-variant":"solid"'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "--code-variant-font-size-adjust": "calc(var(--code-font-size-adjust) * 0.95)", + "fontFamily": "var(--code-font-family)", + "fontSize": "calc(var(--font-size-2) * var(--code-variant-font-size-adjust))", + "fontStyle": "var(--code-font-style)", + "fontWeight": "var(--font-weight-bold)", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "calc(var(--code-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "borderRadius": "calc((0.5px + 0.2em) * var(--radius-factor))", + "boxSizing": "border-box", + "paddingTop": "var(--code-padding-top)", + "paddingLeft": "var(--code-padding-left)", + "paddingBottom": "var(--code-padding-bottom)", + "paddingRight": "var(--code-padding-right)", + "height": "fit-content", + "--letter-spacing": "var(--letter-spacing-2)", + "backgroundColor": { + "default": "var(--accent-12)", + "::selection": "var(--accent-a11)", + }, + "color": {"default": "var(--accent-1)", "::selection": "var(--accent-1)"}, + } + ] + + +def test_code_outline( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Outlined code, and a variant Radix Themes does not have for code.""" + component = rx.ui.box( + rx.ui.code("a", variant="outline"), rx.ui.code("b", variant="surface") + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_b26ac4fb71_c"], + "children": [ + { + "name": '"code"', + "props": ["className:sx_f9cadf6492_c", '"data-variant":"outline"'], + "children": [{"contents": '"a"'}], + }, + { + "name": '"code"', + "props": ["className:sx_1e9979b5c2_c", '"data-variant":"surface"'], + "children": [{"contents": '"b"'}], + }, + ], + } + assert declared_styles(component) == [ + {"boxSizing": "border-box", "display": "block"}, + { + "--code-variant-font-size-adjust": "calc(var(--code-font-size-adjust) * 0.95)", + "fontFamily": "var(--code-font-family)", + "fontSize": "calc(var(--code-variant-font-size-adjust) * 1em)", + "fontStyle": "var(--code-font-style)", + "fontWeight": "var(--code-font-weight)", + "lineHeight": "1.25", + "letterSpacing": "calc(var(--code-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "borderRadius": "calc((0.5px + 0.2em) * var(--radius-factor))", + "boxSizing": "border-box", + "paddingTop": "var(--code-padding-top)", + "paddingLeft": "var(--code-padding-left)", + "paddingBottom": "var(--code-padding-bottom)", + "paddingRight": "var(--code-padding-right)", + "height": "fit-content", + "boxShadow": "inset 0 0 0 max(1px, 0.033em) var(--accent-a8)", + "color": "var(--accent-a11)", + "backgroundColor": { + "@media (hover: hover)": { + ":hover": "var(--rx-link-code-outline, transparent)" + } + }, + }, + { + "--code-variant-font-size-adjust": "calc(var(--code-font-size-adjust) * 0.95)", + "fontFamily": "var(--code-font-family)", + "fontSize": "calc(var(--code-variant-font-size-adjust) * 1em)", + "fontStyle": "var(--code-font-style)", + "fontWeight": "var(--code-font-weight)", + "lineHeight": "1.25", + "letterSpacing": "calc(var(--code-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "borderRadius": "calc((0.5px + 0.2em) * var(--radius-factor))", + "boxSizing": "border-box", + "paddingTop": "var(--code-padding-top)", + "paddingLeft": "var(--code-padding-left)", + "paddingBottom": "var(--code-padding-bottom)", + "paddingRight": "var(--code-padding-right)", + "height": "fit-content", + "backgroundColor": { + "default": "var(--accent-a3)", + "@media (hover: hover)": { + ":hover": "var(--rx-link-code-soft, var(--accent-a3))" + }, + }, + "color": "var(--accent-a11)", + }, + ] diff --git a/tests/units/reflex_components_ui/typography/test_heading.py b/tests/units/reflex_components_ui/typography/test_heading.py new file mode 100644 index 00000000000..170855931c6 --- /dev/null +++ b/tests/units/reflex_components_ui/typography/test_heading.py @@ -0,0 +1,127 @@ +"""Tests for reflex_components_ui.typography.heading.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_heading_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A heading is an h1 of the sixth size.""" + component = rx.ui.heading("a") + assert component.render() == { + "name": '"h1"', + "props": ["className:sx_3cd9045b38_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "--leading-trim-start": "var(--heading-leading-trim-start)", + "--leading-trim-end": "var(--heading-leading-trim-end)", + "fontFamily": "var(--heading-font-family)", + "fontStyle": "var(--heading-font-style)", + "fontWeight": "var(--font-weight-bold)", + "lineHeight": "var(--line-height)", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "fontSize": "calc(var(--font-size-6) * var(--heading-font-size-adjust))", + "--line-height": "var(--heading-line-height-6)", + "letterSpacing": "calc(var(--letter-spacing-6) + var(--heading-letter-spacing))", + } + ] + + +def test_heading_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Its level is the tag, and its props are styles.""" + component = rx.ui.heading( + "a", + as_="h3", + size="8", + weight="medium", + align="right", + trim="start", + color_scheme="gray", + high_contrast=True, + ) + assert component.render() == { + "name": '"h3"', + "props": ['className:sx_c91e482fa5_c + " " + reflexUIClasses_fe8edd03f8'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "--leading-trim-start": "var(--heading-leading-trim-start)", + "--leading-trim-end": "var(--heading-leading-trim-end)", + "fontFamily": "var(--heading-font-family)", + "fontStyle": "var(--heading-font-style)", + "fontWeight": "var(--font-weight-medium)", + "lineHeight": "var(--line-height)", + "marginTop": "0", + "marginRight": "0", + "marginBottom": { + "default": "0", + "::before": "calc(var(--leading-trim-start, " + "var(--default-leading-trim-start)) - " + "var(--line-height, calc(1em * " + "var(--default-line-height))) / 2)", + }, + "marginLeft": "0", + "fontSize": "calc(var(--font-size-8) * var(--heading-font-size-adjust))", + "--line-height": "var(--heading-line-height-8)", + "letterSpacing": "calc(var(--letter-spacing-8) + var(--heading-letter-spacing))", + "textAlign": "right", + "content": {"::before": "''", "::after": "none"}, + "display": {"::before": "table"}, + "--rx-accent-text": "var(--accent-12)", + "color": "var(--accent-12)", + } + ] + + +def test_heading_fallback_tag( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A tag that is not a heading renders an h1.""" + component = rx.ui.heading("a", as_="div", size=rx.breakpoints(sm="9")) + assert component.render() == { + "name": '"h1"', + "props": ["className:sx_64062b0d12_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "--leading-trim-start": "var(--heading-leading-trim-start)", + "--leading-trim-end": "var(--heading-leading-trim-end)", + "fontFamily": "var(--heading-font-family)", + "fontStyle": "var(--heading-font-style)", + "fontWeight": "var(--font-weight-bold)", + "lineHeight": "var(--line-height)", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "fontSize": { + "default": "calc(var(--font-size-6) * var(--heading-font-size-adjust))", + "@media (min-width: 768px)": "calc(var(--font-size-9) * " + "var(--heading-font-size-adjust))", + }, + "--line-height": { + "default": "var(--heading-line-height-6)", + "@media (min-width: 768px)": "var(--heading-line-height-9)", + }, + "letterSpacing": { + "default": "calc(var(--letter-spacing-6) + " + "var(--heading-letter-spacing))", + "@media (min-width: 768px)": "calc(var(--letter-spacing-9) + " + "var(--heading-letter-spacing))", + }, + } + ] diff --git a/tests/units/reflex_components_ui/typography/test_link.py b/tests/units/reflex_components_ui/typography/test_link.py new file mode 100644 index 00000000000..6ecb2fde4ec --- /dev/null +++ b/tests/units/reflex_components_ui/typography/test_link.py @@ -0,0 +1,353 @@ +"""Tests for reflex_components_ui.typography.link.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_link_internal( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A link with an address is the link of the router, with the styles of the link.""" + component = rx.ui.link("a", href="/docs") + assert component.render() == { + "name": "ReactRouterLink", + "props": ["className:sx_10205cfca6_c", 'to:"/docs"'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "color": { + "default": "var(--rx-accent-link, var(--accent-a11))", + ":hover": "var(--accent-8)", + }, + "WebkitTapHighlightColor": "transparent", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": { + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "textDecorationStyle": "solid", + "textDecorationThickness": "min(2px, max(1px, 0.05em))", + "textUnderlineOffset": "calc(0.025em + 2px)", + "textDecorationColor": { + "default": "var(--rx-accent-link-line-color, color-mix(in " + "oklab, var(--accent-a5), var(--gray-a6)))", + ':has(code[data-variant]:not([data-variant="ghost"]):only-child)': "transparent", + }, + "borderRadius": {":focus-visible": "calc(0.07em * var(--radius-factor))"}, + "outlineColor": { + ":focus-visible": "var(--focus-8)", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "var(--accent-a4)" + }, + }, + "outlineWidth": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "0.75em" + }, + }, + "outlineStyle": { + ":focus-visible": "solid", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "solid" + }, + }, + "outlineOffset": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "-0.6em" + }, + }, + "--rx-link-code-solid": "var(--accent-10)", + "--rx-link-code-soft": "var(--accent-a4)", + "--rx-link-code-outline": "var(--accent-a2)", + "textDecorationLine": { + "default": "var(--rx-accent-link-line, none)", + ":focus-visible": "none", + "@media (hover: hover)": { + ":hover": "underline", + ":focus-visible": "none", + }, + }, + } + ] + + +def test_link_no_href( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Without an address it is an anchor that goes nowhere.""" + component = rx.ui.link( + "a", underline="always", size="2", weight="medium", trim="both" + ) + assert component.render() == { + "name": '"a"', + "props": ["className:sx_3534c54b5a_c", 'href:"#"'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": { + "default": "0", + "::after": "calc(var(--leading-trim-end, " + "var(--default-leading-trim-end)) - var(--line-height, " + "calc(1em * var(--default-line-height))) / 2)", + }, + "marginRight": "0", + "marginBottom": { + "default": "0", + "::before": "calc(var(--leading-trim-start, " + "var(--default-leading-trim-start)) - " + "var(--line-height, calc(1em * " + "var(--default-line-height))) / 2)", + }, + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "color": { + "default": "var(--rx-accent-link, var(--accent-a11))", + ":hover": "var(--accent-8)", + }, + "WebkitTapHighlightColor": "transparent", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": { + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "textDecorationStyle": "solid", + "textDecorationThickness": "min(2px, max(1px, 0.05em))", + "textUnderlineOffset": "calc(0.025em + 2px)", + "textDecorationColor": { + "default": "color-mix(in oklab, var(--accent-a5), var(--gray-a6))", + ':has(code[data-variant]:not([data-variant="ghost"]):only-child)': "transparent", + }, + "borderRadius": {":focus-visible": "calc(0.07em * var(--radius-factor))"}, + "outlineColor": { + ":focus-visible": "var(--focus-8)", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "var(--accent-a4)" + }, + }, + "outlineWidth": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "0.75em" + }, + }, + "outlineStyle": { + ":focus-visible": "solid", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "solid" + }, + }, + "outlineOffset": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "-0.6em" + }, + }, + "--rx-link-code-solid": "var(--accent-10)", + "--rx-link-code-soft": "var(--accent-a4)", + "--rx-link-code-outline": "var(--accent-a2)", + "fontSize": "var(--font-size-2)", + "--line-height": "var(--line-height-2)", + "--letter-spacing": "var(--letter-spacing-2)", + "fontWeight": "var(--font-weight-medium)", + "content": {"::before": "''", "::after": "''"}, + "display": {"::before": "table", "::after": "table"}, + "textDecorationLine": { + "default": "underline", + ":focus-visible": "none", + "@media (hover: hover)": { + ":hover": "underline", + ":focus-visible": "none", + }, + }, + } + ] + + +def test_link_external( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The props of the router go to its link, the others to the element.""" + component = rx.ui.link( + "a", + href="https://reflex.dev", + is_external=True, + reload_document=True, + id="home", + color_scheme="ruby", + high_contrast=True, + underline="hover", + ) + assert component.render() == { + "name": "ReactRouterLink", + "props": [ + 'className:sx_fb32bcfecb_c + " " + reflexUIClasses_e201574881', + 'id:"home"', + "ref:ref_home", + "reloadDocument:true", + 'target:(true ? "_blank" : "")', + 'to:"https://reflex.dev"', + ], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "color": {"default": "var(--accent-12)", ":hover": "var(--accent-8)"}, + "WebkitTapHighlightColor": "transparent", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": { + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "textDecorationStyle": "solid", + "textDecorationThickness": "min(2px, max(1px, 0.05em))", + "textUnderlineOffset": "calc(0.025em + 2px)", + "textDecorationColor": { + "default": "color-mix(in oklab, var(--accent-a5), var(--gray-a6))", + ':has(code[data-variant]:not([data-variant="ghost"]):only-child)': "transparent", + }, + "borderRadius": {":focus-visible": "calc(0.07em * var(--radius-factor))"}, + "outlineColor": { + ":focus-visible": "var(--focus-8)", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "var(--accent-a4)" + }, + }, + "outlineWidth": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "0.75em" + }, + }, + "outlineStyle": { + ":focus-visible": "solid", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "solid" + }, + }, + "outlineOffset": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "-0.6em" + }, + }, + "--rx-link-code-solid": "var(--accent-10)", + "--rx-link-code-soft": "var(--accent-a4)", + "--rx-link-code-outline": "var(--accent-a2)", + "textDecorationLine": { + "default": "none", + ":focus-visible": "none", + "@media (hover: hover)": { + ":hover": "underline", + ":focus-visible": "none", + }, + }, + "--rx-accent-text": "var(--accent-12)", + "--rx-accent-link": "var(--accent-12)", + "--rx-accent-link-line": "underline", + "--rx-accent-link-line-color": "color-mix(in oklab, var(--accent-a6), " + "var(--gray-a6))", + } + ] + + +def test_link_as_child( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """With as_child the only child is the element.""" + component = rx.ui.link( + rx.el.button("a"), as_child=True, underline="none", _hover={"color": "red"} + ) + assert component.render() == { + "name": '"button"', + "props": ["className:sx_27b53d9e29_c", 'href:"#"'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "color": { + "default": "var(--rx-accent-link, var(--accent-a11))", + ":hover": "red", + }, + "WebkitTapHighlightColor": "transparent", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": { + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "textDecorationStyle": "solid", + "textDecorationThickness": "min(2px, max(1px, 0.05em))", + "textUnderlineOffset": "calc(0.025em + 2px)", + "textDecorationColor": { + "default": "color-mix(in oklab, var(--accent-a5), var(--gray-a6))", + ':has(code[data-variant]:not([data-variant="ghost"]):only-child)': "transparent", + }, + "borderRadius": {":focus-visible": "calc(0.07em * var(--radius-factor))"}, + "outlineColor": { + ":focus-visible": "var(--focus-8)", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "var(--accent-a4)" + }, + }, + "outlineWidth": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "0.75em" + }, + }, + "outlineStyle": { + ":focus-visible": "solid", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "solid" + }, + }, + "outlineOffset": { + ":focus-visible": "2px", + "@media (pointer: coarse)": { + ":active:not(:focus-visible, [data-state='open'])": "-0.6em" + }, + }, + "--rx-link-code-solid": "var(--accent-10)", + "--rx-link-code-soft": "var(--accent-a4)", + "--rx-link-code-outline": "var(--accent-a2)", + "textDecorationLine": "none", + } + ] diff --git a/tests/units/reflex_components_ui/typography/test_text.py b/tests/units/reflex_components_ui/typography/test_text.py new file mode 100644 index 00000000000..4de85e0c13b --- /dev/null +++ b/tests/units/reflex_components_ui/typography/test_text.py @@ -0,0 +1,308 @@ +"""Tests for reflex_components_ui.typography.text.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_text_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Text is a paragraph that follows the size of what is around it.""" + component = rx.ui.text("a") + assert component.render() == { + "name": '"p"', + "props": ["className:sx_af8fa2456e_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + } + ] + + +def test_text_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Its props are styles, and the tag is one of four.""" + component = rx.ui.text( + "a", + as_="label", + size="3", + weight="bold", + align="center", + trim="both", + id="name", + ) + assert component.render() == { + "name": '"label"', + "props": ["className:sx_82cd5676a1_c", 'id:"name"', "ref:ref_name"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": { + "default": "0", + "::after": "calc(var(--leading-trim-end, " + "var(--default-leading-trim-end)) - var(--line-height, " + "calc(1em * var(--default-line-height))) / 2)", + }, + "marginRight": "0", + "marginBottom": { + "default": "0", + "::before": "calc(var(--leading-trim-start, " + "var(--default-leading-trim-start)) - " + "var(--line-height, calc(1em * " + "var(--default-line-height))) / 2)", + }, + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-3)", + "--line-height": "var(--line-height-3)", + "--letter-spacing": "var(--letter-spacing-3)", + "fontWeight": "var(--font-weight-bold)", + "textAlign": "center", + "content": {"::before": "''", "::after": "''"}, + "display": {"::before": "table", "::after": "table"}, + "WebkitTapHighlightColor": {"@media (pointer: coarse)": "transparent"}, + "outlineWidth": {"@media (pointer: coarse)": {":active": "0.75em"}}, + "outlineStyle": {"@media (pointer: coarse)": {":active": "solid"}}, + "outlineColor": {"@media (pointer: coarse)": {":active": "var(--gray-a4)"}}, + "outlineOffset": {"@media (pointer: coarse)": {":active": "-0.6em"}}, + } + ] + + +def test_text_fallback_tag( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A tag Radix Themes does not take renders its default, a span.""" + component = rx.ui.text("a", as_="kbd") + assert component.render() == { + "name": '"span"', + "props": ["className:sx_af8fa2456e_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + } + ] + + +def test_text_color( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A color is the accent of the element, and what the text inside reads.""" + component = rx.ui.text("a", color_scheme="ruby") + assert component.render() == { + "name": '"p"', + "props": ['className:sx_4385ba4ca3_c + " " + reflexUIClasses_e201574881'], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "--rx-accent-text": "var(--accent-12)", + "--rx-accent-link": "var(--accent-12)", + "--rx-accent-link-line": "underline", + "--rx-accent-link-line-color": "color-mix(in oklab, var(--accent-a6), " + "var(--gray-a6))", + "color": "var(--accent-a11)", + } + ] + + +def test_text_high_contrast( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """High contrast takes its color from the element or from around it.""" + component = rx.ui.box( + rx.ui.text("a", color_scheme="ruby", high_contrast=True), + rx.ui.text("b", high_contrast=True), + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_b26ac4fb71_c"], + "children": [ + { + "name": '"p"', + "props": [ + ('className:sx_ac0c7abea3_c + " " + reflexUIClasses_e201574881') + ], + "children": [{"contents": '"a"'}], + }, + { + "name": '"p"', + "props": ["className:sx_2bca64ad62_c"], + "children": [{"contents": '"b"'}], + }, + ], + } + assert declared_styles(component) == [ + {"boxSizing": "border-box", "display": "block"}, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "--rx-accent-text": "var(--accent-12)", + "color": "var(--accent-12)", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "color": "var(--rx-accent-text)", + }, + ] + + +def test_text_responsive( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A size per breakpoint changes each property at its breakpoint.""" + component = rx.ui.text("a", size=rx.breakpoints(initial="1", sm="3", xl="1")) + assert component.render() == { + "name": '"p"', + "props": ["className:sx_85993688dd_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": { + "default": "var(--font-size-1)", + "@media (min-width: 768px)": "var(--font-size-3)", + "@media (min-width: 1640px)": "var(--font-size-1)", + }, + "--line-height": { + "default": "var(--line-height-1)", + "@media (min-width: 768px)": "var(--line-height-3)", + "@media (min-width: 1640px)": "var(--line-height-1)", + }, + "--letter-spacing": { + "default": "var(--letter-spacing-1)", + "@media (min-width: 768px)": "var(--letter-spacing-3)", + "@media (min-width: 1640px)": "var(--letter-spacing-1)", + }, + } + ] + + +def test_text_span( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A span is text that renders a span.""" + component = rx.ui.text.span("a", size="1") + assert component.render() == { + "name": '"span"', + "props": ["className:sx_6220d7656d_c"], + "children": [{"contents": '"a"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-1)", + "--line-height": "var(--line-height-1)", + "--letter-spacing": "var(--letter-spacing-1)", + } + ] + + +def test_text_inline( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Em, strong and quote take their font from the tokens.""" + component = rx.ui.box( + rx.ui.text.em("a"), rx.ui.text.strong("b"), rx.ui.text.quote("c") + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_b26ac4fb71_c"], + "children": [ + { + "name": '"em"', + "props": ["className:sx_bbfc178e37_c"], + "children": [{"contents": '"a"'}], + }, + { + "name": '"strong"', + "props": ["className:sx_d0df461b7a_c"], + "children": [{"contents": '"b"'}], + }, + { + "name": '"q"', + "props": ["className:sx_fd5e021245_c"], + "children": [{"contents": '"c"'}], + }, + ], + } + assert declared_styles(component) == [ + {"boxSizing": "border-box", "display": "block"}, + { + "fontFamily": "var(--em-font-family)", + "fontSize": "calc(var(--em-font-size-adjust) * 1em)", + "fontStyle": "var(--em-font-style)", + "fontWeight": "var(--em-font-weight)", + "letterSpacing": "calc(var(--em-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "boxSizing": "border-box", + "lineHeight": "1.25", + "color": "inherit", + }, + { + "fontFamily": "var(--strong-font-family)", + "fontSize": "calc(var(--strong-font-size-adjust) * 1em)", + "fontStyle": "var(--strong-font-style)", + "fontWeight": "var(--strong-font-weight)", + "letterSpacing": "calc(var(--strong-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + }, + { + "fontFamily": "var(--quote-font-family)", + "fontSize": "calc(var(--quote-font-size-adjust) * 1em)", + "fontStyle": "var(--quote-font-style)", + "fontWeight": "var(--quote-font-weight)", + "letterSpacing": "calc(var(--quote-letter-spacing) + var(--letter-spacing, " + "var(--default-letter-spacing)))", + "boxSizing": "border-box", + "lineHeight": "1.25", + "color": "inherit", + }, + ] From 9caa657162edd997e767de61298ffbf8d9648fac Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:28:21 +0000 Subject: [PATCH 038/204] Exercise the layout and typography components in the shared integration app Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- .../tests_playwright/test_ui_components.py | 77 ++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 3bf0a9746fe..d2dff44a84c 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -369,8 +369,38 @@ def styled(): assets.mkdir(exist_ok=True) (assets / "unlayered.css").write_text(".unlayered { padding: 2px }") - app = rx.App(stylesheets=["unlayered.css"]) + def wave(): + return rx.el.main( + rx.ui.center( + rx.ui.text("middle", id="middle"), + id="center", + style={"height": "200px"}, + ), + rx.ui.vstack(rx.ui.box("one"), rx.ui.box("two"), id="vstack"), + rx.ui.heading( + "Title", size=rx.breakpoints(initial="2", md="8"), id="heading" + ), + rx.ui.text( + "See ", + rx.ui.link("the styled page", href="/styled", id="link"), + color_scheme="ruby", + id="colored", + ), + rx.ui.flex( + rx.ui.text("slot", size="5", id="slot"), + as_child=True, + direction="column", + ), + rx.ui.separator(id="separator"), + ) + + # The style of the app for a component of the wave, as an app writes it. + app = rx.App( + stylesheets=["unlayered.css"], + style={rx.ui.heading: {"text_transform": "uppercase"}}, + ) app.add_page(index) + app.add_page(wave, route="/wave") app.add_page(literal, route="/literal") app.add_page(styled, route="/styled") app.add_page(theme, route="/theme") @@ -1182,3 +1212,48 @@ def test_color_scheme_is_the_accent_of_one_element(ui_app: AppHarness, page: Pag "chip-red": ["rgb(229, 72, 77)", "rgb(235, 142, 144)"], "chip-gray": ["rgb(139, 141, 152)", "rgb(141, 164, 239)"], } + + +# What the page of the layout and typography components computes to, by id. +WAVE = { + # The style a class adds when an app is compiled. + "center": { + "display": "flex", + "align-items": "center", + "justify-content": "center", + }, + # The defaults of the fields of a stack: its direction and its spacing. + "vstack": {"flex-direction": "column", "row-gap": "12px"}, + # A size per breakpoint, and the style of the app for the component. + "heading": {"font-size": "14px", "text-transform": "uppercase"}, + # A link inside colored text has the color of the text, at full contrast. + "link": {"color": "rgb(100, 23, 43)", "text-decoration-line": "underline"}, + # A flex container rendered as its child, a paragraph. + "slot": {"display": "flex", "flex-direction": "column", "font-size": "20px"}, + "separator": {"display": "block", "height": "1px"}, +} +WAVE_WIDE = {**WAVE, "heading": {"font-size": "35px", "text-transform": "uppercase"}} + + +def test_layout_and_typography_components_are_styled_and_navigate( + ui_app: AppHarness, page: Page +): + """The first wave of components works in a real app, in dev and prod.""" + assert ui_app.frontend_url is not None + page.set_viewport_size({"width": 400, "height": 600}) + page.goto(ui_app.frontend_url.rstrip("/") + "/wave") + expect(page.locator("#center")).to_have_css("display", "flex") + assert _computed_styles(page, WAVE) == WAVE + assert page.locator("#slot").evaluate("element => element.tagName") == "P" + + # A prop follows the breakpoints of Radix Themes: md is 1024px. + page.set_viewport_size({"width": 1280, "height": 600}) + expect(page.locator("#heading")).to_have_css("font-size", "35px") + assert _computed_styles(page, WAVE_WIDE) == WAVE_WIDE + + # The link is the one of the router: the page is not loaded again. + page.evaluate("window.loadedOnce = true") + page.locator("#link").click() + styled = _styled_url(ui_app).rstrip("/") + page.wait_for_url(lambda url: url.rstrip("/") == styled) + assert page.evaluate("window.loadedOnce") is True From b030bf083a5154ae0cbfeeccd9b139d1ab79a7e5 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:40:49 +0000 Subject: [PATCH 039/204] Document the conventions of an rx.ui component, add the news fragment, and settle the types of the style tables Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- packages/reflex-components-ui/README.md | 118 ++++++++++++++++-- .../news/+wave1-layout-typography.feature.md | 9 ++ .../components/aspect_ratio.py | 11 +- .../reflex_components_ui/layout/container.py | 2 +- .../reflex_components_ui/style/__init__.py | 2 + .../src/reflex_components_ui/style/merge.py | 18 +++ .../src/reflex_components_ui/styles/code.py | 21 ++-- .../reflex_components_ui/styles/heading.py | 15 ++- .../src/reflex_components_ui/styles/inset.py | 12 +- .../src/reflex_components_ui/styles/link.py | 10 +- .../reflex_components_ui/styles/separator.py | 10 +- .../src/reflex_components_ui/styles/text.py | 17 +-- .../reflex_components_ui/styles/typography.py | 21 ++-- .../reflex_components_ui/style/test_merge.py | 12 ++ 14 files changed, 213 insertions(+), 65 deletions(-) create mode 100644 packages/reflex-components-ui/news/+wave1-layout-typography.feature.md diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 354b6d51e9b..f19c90334a7 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -31,7 +31,10 @@ src/reflex_components_ui/ the python package: the rx.ui namespace 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, rx.ui.theme among them + layout/ the layout components, rx.ui.theme among them + typography/ text, heading, code, blockquote, link + components/ the other components: separator, inset, aspect_ratio + props.py the values of the props many components share _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/ @@ -82,7 +85,8 @@ runtime**: | 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 | +| A responsive list or `rx.breakpoints(...)` in a style | Media-query conditions on the app's breakpoints | +| A prop per breakpoint: `size=rx.breakpoints(initial="1", md="3")` | Media-query conditions on the breakpoints of Radix Themes: 520, 768, 1024, 1280 and 1640px | | `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)` | @@ -154,7 +158,7 @@ BUTTON: ComponentStyles = { } -class Button(UIComponent): +class Button(UIComponent, elements.Button): """A button.""" tag = "button" @@ -178,17 +182,55 @@ class Button(UIComponent): return super().create(Part.create(part="icon", tag="span"), *children, **props) ``` +- **The element.** A component that renders one HTML element lists its class + of `reflex_components_core.el.elements` after `UIComponent`, as the Radix + wrapper it is forked from does. It gives the component the attributes of + its tag as props (`title`, `tab_index`, `href`...), and nothing else. - **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. + default of the field, or the entry of `defaults` in the table for a default + that Radix Themes has and the Reflex wrapper does not pass, such as the + size of a heading. Bound to state, it is indexed in the browser. A variant + wins its name over a layout prop: the `align` of text is `text-align`. - **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. + `spacing`, `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. +- **A value per breakpoint.** A variant or a layout prop typed `Responsive[...]` + takes `rx.breakpoints(initial="1", md="3")`. The breakpoints are those of + Radix Themes, whatever the breakpoints of the app, and apply mobile first. + At each one the table is resolved again for the values the props then have, + compound styles included, and each property that changes gets a media + query; a property those values no longer set is `revert-layer`. A table + needs nothing for it. +- **A value a prop does not take** is an error where the component is + created, for every variant and layout prop whose type is a `Literal`: + `rx.ui.text: unknown size "12". Did you mean "2"? The values are "1", ...`. +- **`as_`** names the tag. `_as_tags` lists the tags Radix Themes renders for + the component; any other value of the prop renders the default tag, as it + does there. `as_` can be read as a variant (`"as_": {"label": {...}}`). +- **`as_child`** renders the only child in place of the element: the tag, the + props and the children are the child's, its props winning, with the class + names of both. When the child is an rx.ui component the styles of both are + merged into one declaration, the child's winning, since two sets of class + names cannot say which one does. It is read at compile time. +- **`color_scheme`** is read by a table as `"true"` when the element has a + color: `"variants": {"color_scheme": {"true": {...}}}`. The tokens of the + accent resolve against that color, so a table never needs to know which. +- **What Radix Themes selects by ancestor**, a class on an element cannot: a + link inside colored text, high-contrast text inside a colored element, code + inside a link. The ancestor hands the value down in a custom property and + the descendant reads it with a fallback, as `styles/typography.py` does. + Every component with a `color_scheme` spreads `ACCENT_SCOPE` into that + variant. +- **Styles a class adds**: `add_style`, as in any component, applies after the + layout props and before the styles of the app. `rx.ui.center` centers that + way, so that `align` and `justify` lose to it as they do in `rx.center`. - **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 @@ -214,8 +256,9 @@ the style objects StyleX compiles. Nothing in it depends on a component. 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. + and value, `defaults` for the value a prop selects styles by when it is left + out, `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 @@ -246,7 +289,7 @@ What lowering does to each input: | `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)` | +| Layout props (`p`, `m`, `gap`, `columns`, `direction`...) | Styles, with steps of the space scale as `var(--space-N)`, and a value per breakpoint on the breakpoints of Radix Themes | | 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` | @@ -263,6 +306,58 @@ 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. +## Adding a component + +What a wave does for each component, in this order. `flex` (a layout), `text` +(typography) and `separator` (neither) are the ones to copy. + +1. **Read the sources.** The Radix wrapper in + `reflex-components-radix/.../themes/` gives the API: the base classes, the + fields with their types, defaults and docstrings, and what `create` does. + The CSS in `js/node_modules/@radix-ui/themes/src/components/.css` + gives the look, and `.props.tsx` the defaults Radix applies when a + prop is left out and the values it falls back from. +2. **The table**, `styles/.py`: one `ComponentStyles` constant, grouped + as the CSS is (base, sizes, variants), with a one-line comment only where + the Radix rule is not obvious. Values are tokens (`tokens.space[4]`, + `tokens.accent.a[11]`), never a copy of what a token holds. A custom + property Radix sets on the element (`--line-height`) stays one, so that + what is inside the element follows it. `StyleProps` cannot type such a + key, a free condition such as `"@media (pointer: coarse)"`, or a token on a + property typed by its keywords (`font_style`, `cursor`): wrap a style that + holds one in `unchecked(...)`, and the lowering checks it instead. Radix's + default for a prop the wrapper does not default goes in `defaults`. What several tables share is + in `styles/typography.py`. +3. **The wrapper**, `layout/`, `typography/` or `components/.py`: a + class deriving from `UIComponent` and the element class the Radix wrapper + derives from, with `tag`, `styles` and the same fields, copied with their + `field(doc=...)` so that the documentation and the stubs stay complete. + Keep `create` as it is there. A second element is a `Part`. +4. **The name**: an entry of `_SUBMOD_ATTRS` in `__init__.py`, a namespace + (`rx.ui.text`, `rx.ui.list`) under the name `rx` has it. +5. **Unit tests**, `tests/units/reflex_components_ui//test_.py`: + for a few uses, the whole rendered element and the whole style each + element declares (the `declared_styles` fixture). The API parity test + picks the name up by itself, members of a namespace included, and the list + of names in `test_api_parity.py` is extended by hand. +6. **The matrix and the contract**, `parity/ui_parity/components/.py` + (see [The parity harness](#the-parity-harness)): every value of every prop, + crossed where they interact and swept otherwise, the 26 accents as a + sweep, dark, each interactive state the component has, a prop per + breakpoint at the viewports around its breakpoints, and the nestings Radix + styles specially. Hold it to zero (`threshold=0, tolerance=0`) unless + something outside the component dithers, and say what in a comment. +7. **Run** `uv run python scripts/ui_parity.py ` until nothing differs. + An intended difference is an entry of `parity/allowlist.toml` with a + reason a user can read; anything else is a bug. +8. **The stubs**: `uv run python scripts/make_pyi.py`, and commit + `pyi_hashes.json`. +9. **The shared app**: an element on the `/wave` page of + `tests/integration/tests_playwright/test_ui_components.py` for what only a + real app shows, such as a style the compile adds or a navigation. +10. **The record**: the wave's row in the run-time table below, the gzipped + CSS and JavaScript it adds, and a news fragment in `news/`. + ## Themes and tokens The plugin takes the theme of the app. Every option has the values and, the @@ -486,7 +581,7 @@ 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 +### Declaring a matrix and a contract 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 @@ -596,6 +691,7 @@ 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 | +| 1: layout and typography | 19, and `text.kbd` | 1011, 44 of them interactive | 27 s + 61 s | ## Rules the tooling enforces diff --git a/packages/reflex-components-ui/news/+wave1-layout-typography.feature.md b/packages/reflex-components-ui/news/+wave1-layout-typography.feature.md new file mode 100644 index 00000000000..f59ad627efc --- /dev/null +++ b/packages/reflex-components-ui/news/+wave1-layout-typography.feature.md @@ -0,0 +1,9 @@ +Add the layout and typography components to `rx.ui`: `box`, `flex`, `grid`, `container`, `section`, `center`, `spacer`, `stack`, `hstack`, `vstack`, `text` (with `text.span`, `text.em`, `text.strong`, `text.quote` and `text.kbd`), `heading`, `code`, `blockquote`, `link`, `list` (with `list.ordered`, `list.unordered` and `list.item`), `separator`, `inset` and `aspect_ratio`. Each takes the arguments of the component of the same name in `rx` and looks the same; `rx.ui.container` does not take `stack_children_full_width`. + +```python +rx.ui.vstack( + rx.ui.heading("Reports", size=rx.breakpoints(initial="5", md="8")), + rx.ui.text("See ", rx.ui.link("the docs", href="/docs"), color_scheme="ruby"), + spacing="3", +) +``` diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py b/packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py index c47154e8e1f..53544910690 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.py @@ -51,11 +51,14 @@ def create(cls, *children, **props) -> Component: Returns: The frame. """ - ratio = LiteralVar.create(props.get("ratio", 1)) + ratio = props.get("ratio", 1) + if isinstance(ratio, Var): + ratio = ratio._var_value if isinstance(ratio, LiteralVar) else ratio + # Bound to state, the padding is worked out in the browser. padding = ( - f"{100 / ratio._var_value}%" - if isinstance(ratio, LiteralVar) - else (100 / ratio).to(str) + "%" + (100 / ratio.to(float)).to_string() + "%" + if isinstance(ratio, Var) + else f"{100 / ratio}%" ) return AspectRatioFrame.create( super().create(*children, **props), diff --git a/packages/reflex-components-ui/src/reflex_components_ui/layout/container.py b/packages/reflex-components-ui/src/reflex_components_ui/layout/container.py index 17f8b18ba9c..7450b57d4d3 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/layout/container.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/layout/container.py @@ -53,7 +53,7 @@ def create( """ if stack_children_full_width: msg = ( - f"{cls._display_name()}: stack_children_full_width styles the " + "rx.ui.container: stack_children_full_width styles the " "stacks inside the container through nested selectors, which " 'rx.ui styles do not support. Give those stacks width="100%", ' "or keep rx.container for this element." 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 index 211cb64b9b0..39bc69b849e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py @@ -17,6 +17,7 @@ Merged, merge, over, + unchecked, ) __all__ = [ @@ -32,4 +33,5 @@ "lower", "merge", "over", + "unchecked", ] 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 94168078df6..6991bb56f3e 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 @@ -690,6 +690,24 @@ def _merge( return Merged(finish(merged_props, inline), dynamic, parts) +def unchecked(style: Mapping[str, Any]) -> Any: + """Mark the part of a style table that ``StyleProps`` cannot type. + + A custom property and a condition such as ``@media (pointer: coarse)`` + are no keys of a ``TypedDict``, and a design token is a plain string where + a property is typed by its keywords. A style that holds one is wrapped + whole, and is checked when the table is lowered instead: + ``unchecked({"--line-height": "1.5", "margin": "0"})``. + + Args: + style: The style. + + Returns: + The style, as a type checker lets pass. + """ + return style + + def over(under: Merged, top: Merged) -> Merged: """Lay the styles of one element over those of another. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py index 7b235f47817..6e068c53269 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py @@ -3,7 +3,7 @@ from typing import Any from reflex_components_ui import tokens -from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.style import ComponentStyles, StyleProps, unchecked from reflex_components_ui.styles.typography import ( ACCENT_SCOPE, ACCENT_SCOPE_HIGH_CONTRAST, @@ -18,12 +18,12 @@ # little smaller than the text around it. _ADJUST = "--code-variant-font-size-adjust" -SIZE: dict[str, Any] = { - str(step): { +SIZE: dict[str, StyleProps] = { + str(step): unchecked({ "font_size": f"calc({tokens.font_size[step]} * var({_ADJUST}))", "line_height": tokens.line_height[step], "--letter-spacing": tokens.letter_spacing[step], - } + }) for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) } @@ -52,7 +52,7 @@ def _hover(inside_link: str, otherwise: str) -> dict[str, Any]: } CODE: ComponentStyles = { - "base": { + "base": unchecked({ _ADJUST: f"calc({tokens.code.font_size_adjust} * 0.95)", "font_family": tokens.code.font_family, "font_size": f"calc(var({_ADJUST}) * 1em)", @@ -71,12 +71,15 @@ def _hover(inside_link: str, otherwise: str) -> dict[str, Any]: "padding_right": tokens.code.padding_right, # Not stretched by a flex or grid container. "height": "fit-content", - }, + }), "variants": { "size": SIZE, "weight": WEIGHT, "variant": { - "ghost": {_ADJUST: tokens.code.font_size_adjust, "padding": "0"}, + "ghost": unchecked({ + _ADJUST: tokens.code.font_size_adjust, + "padding": "0", + }), "solid": { "background_color": _hover(LINK_CODE_SOLID, tokens.accent.a[9]), "color": tokens.accent.contrast, @@ -99,13 +102,13 @@ def _hover(inside_link: str, otherwise: str) -> dict[str, Any]: "classic": _SOFT, "surface": _SOFT, }, - "color_scheme": {"true": ACCENT_SCOPE}, + "color_scheme": {"true": unchecked(ACCENT_SCOPE)}, }, "defaults": {"variant": "soft"}, "compound": [ { "props": {"color_scheme": "true", "high_contrast": "true"}, - "style": ACCENT_SCOPE_HIGH_CONTRAST, + "style": unchecked(ACCENT_SCOPE_HIGH_CONTRAST), }, { "props": {"variant": "ghost", "color_scheme": "true"}, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py index 67bd2eb4cca..b1b3e512914 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/heading.py @@ -1,9 +1,7 @@ """The look of a heading.""" -from typing import Any - from reflex_components_ui import tokens -from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.style import ComponentStyles, StyleProps, unchecked from reflex_components_ui.styles.typography import ( ALIGN, COLOR, @@ -13,8 +11,8 @@ ) # The line height is a custom property, which text inside the heading follows. -SIZE: dict[str, Any] = { - str(step): { +SIZE: dict[str, StyleProps] = { + str(step): unchecked({ "font_size": ( f"calc({tokens.font_size[step]} * {tokens.heading.font_size_adjust})" ), @@ -22,12 +20,13 @@ "letter_spacing": ( f"calc({tokens.letter_spacing[step]} + {tokens.heading.letter_spacing})" ), - } + }) for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) } HEADING: ComponentStyles = { - "base": { + "base": unchecked({ + # The trim of the font of headings, which the trim prop reads. "--leading-trim-start": tokens.heading.leading_trim_start, "--leading-trim-end": tokens.heading.leading_trim_end, "font_family": tokens.heading.font_family, @@ -35,7 +34,7 @@ "font_weight": tokens.font_weight.bold, "line_height": "var(--line-height)", "margin": "0", - }, + }), "variants": { "size": SIZE, "weight": WEIGHT, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py index 5bc74866a03..8045a33c38e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/inset.py @@ -2,7 +2,7 @@ from typing import Any -from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.style import ComponentStyles, unchecked # The container, a card for one, says how far its edges are through the # `--inset-padding-*`, `--inset-border-width` and `--inset-border-radius` @@ -11,7 +11,7 @@ _RADIUS = "var(--inset-border-radius-calc)" -def _side(*sides: str, corners: str = "") -> dict[str, Any]: +def _side(*sides: str, corners: str = "") -> Any: """Make the margins and the corners of an inset that reaches some sides. Args: @@ -37,7 +37,7 @@ def _side(*sides: str, corners: str = "") -> dict[str, Any]: return style -def _clip(border: bool) -> dict[str, Any]: +def _clip(border: bool) -> Any: """Make the edges an inset reaches to: of the border, or inside it. Args: @@ -82,10 +82,10 @@ def _clip(border: bool) -> dict[str, Any]: # container, which the inset then has itself. **{ prop: { - "0": {f"padding_{side}": "0" for side in sides}, - "current": { + "0": unchecked({f"padding_{side}": "0" for side in sides}), + "current": unchecked({ f"padding_{side}": f"var(--inset-padding-{side})" for side in sides - }, + }), } for prop, sides in ( ("p", _SIDES), diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py index 4946c7a3855..7bb0fe004bf 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py @@ -3,7 +3,7 @@ from typing import Any from reflex_components_ui import tokens -from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.style import ComponentStyles, unchecked from reflex_components_ui.styles.text import TEXT_BASE from reflex_components_ui.styles.typography import ( ACCENT_LINK, @@ -54,7 +54,7 @@ def _line(rest: str, hover: str) -> dict[str, Any]: LINK: ComponentStyles = { - "base": { + "base": unchecked({ **TEXT_BASE, # Without a color of its own, inside an element that has one. "color": f"var({ACCENT_LINK}, {tokens.accent.a[11]})", @@ -86,7 +86,7 @@ def _line(rest: str, hover: str) -> dict[str, Any]: LINK_CODE_SOLID: tokens.accent[10], LINK_CODE_SOFT: tokens.accent.a[4], LINK_CODE_OUTLINE: tokens.accent.a[2], - }, + }), "variants": { "size": SIZE, "weight": WEIGHT, @@ -104,7 +104,9 @@ def _line(rest: str, hover: str) -> dict[str, Any]: "always": {"text_decoration_line": _line("underline", "underline")}, "none": {"text_decoration_line": "none"}, }, - "color_scheme": {"true": {**ACCENT_SCOPE, "color": tokens.accent.a[11]}}, + "color_scheme": { + "true": unchecked({**ACCENT_SCOPE, "color": tokens.accent.a[11]}), + }, "high_contrast": {"true": {"color": tokens.accent[12]}}, }, "defaults": {"underline": "auto"}, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py index 72632bf9cca..0fd42764d0d 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/separator.py @@ -1,7 +1,7 @@ """The look of a separator: a line between two things.""" from reflex_components_ui import tokens -from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.style import ComponentStyles, unchecked # The length of the line, which both orientations read. _SIZE = "--separator-size" @@ -18,10 +18,10 @@ "vertical": {"width": "1px", "height": f"var({_SIZE})"}, }, "size": { - "1": {_SIZE: tokens.space[4]}, - "2": {_SIZE: tokens.space[6]}, - "3": {_SIZE: tokens.space[9]}, - "4": {_SIZE: "100%"}, + "1": unchecked({_SIZE: tokens.space[4]}), + "2": unchecked({_SIZE: tokens.space[6]}), + "3": unchecked({_SIZE: tokens.space[9]}), + "4": unchecked({_SIZE: "100%"}), }, "color_scheme": {"true": {"background_color": tokens.accent.a[6]}}, }, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py index c675fcf531f..8a5d329a8b7 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/text.py @@ -3,7 +3,7 @@ from typing import Any from reflex_components_ui import tokens -from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.style import ComponentStyles, StyleProps, unchecked from reflex_components_ui.styles.typography import ( ALIGN, COLOR, @@ -14,7 +14,7 @@ ) # What every element that is text has, a link and a quotation among them. -TEXT_BASE: dict[str, Any] = { +TEXT_BASE: StyleProps = { "margin": "0", "line_height": f"var(--line-height, {tokens.default.line_height})", "letter_spacing": "var(--letter-spacing, inherit)", @@ -29,7 +29,7 @@ "trim": TRIM, **COLOR, "as_": { - "label": { + "label": unchecked({ "@media (pointer: coarse)": { "WebkitTapHighlightColor": "transparent", "_active": { @@ -39,7 +39,7 @@ "outline_offset": "-0.6em", }, }, - }, + }), }, }, "compound": [COLOR_HIGH_CONTRAST], @@ -57,7 +57,8 @@ def _inline(element: Any, **style: Any) -> ComponentStyles: The style table. """ return { - "base": { + # The font style is a token, where the property is typed by keywords. + "base": unchecked({ "font_family": element.font_family, "font_size": f"calc({element.font_size_adjust} * 1em)", "font_style": element.font_style, @@ -67,7 +68,7 @@ def _inline(element: Any, **style: Any) -> ComponentStyles: f"var(--letter-spacing, {tokens.default.letter_spacing}))" ), **style, - }, + }), } @@ -130,10 +131,10 @@ def _inline(element: Any, **style: Any) -> ComponentStyles: }, "variants": { "size": { - str(step): { + str(step): unchecked({ "font_size": f"calc({tokens.font_size[step]} * 0.8)", "--letter-spacing": tokens.letter_spacing[step], - } + }) for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) }, }, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py index 86ef78770af..0eea1fa3b1a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py @@ -5,7 +5,8 @@ from typing import Any from reflex_components_ui import tokens -from reflex_components_ui.style import StyleProps +from reflex_components_ui.style import CompoundStyle, StyleProps, unchecked +from reflex_components_ui.tokens import Step12 # What an element with a color of its own tells the text inside it, as Radix # Themes does through `[data-accent-color]` ancestor selectors: a class on an @@ -24,7 +25,7 @@ LINK_CODE_OUTLINE = "--rx-link-code-outline" -def underline_color(step: int) -> str: +def underline_color(step: Step12) -> str: """Mix the color of the line under a link, which keeps bright colors legible. Args: @@ -68,12 +69,12 @@ def underline_color(step: int) -> str: # The line height and the letter spacing of a size are custom properties, so # that text and code inside the element follow them. -SIZE: dict[str, Any] = { - str(step): { +SIZE: dict[str, StyleProps] = { + str(step): unchecked({ "font_size": tokens.font_size[step], "--line-height": tokens.line_height[step], "--letter-spacing": tokens.letter_spacing[step], - } + }) for step in (1, 2, 3, 4, 5, 6, 7, 8, 9) } @@ -106,12 +107,14 @@ def underline_color(step: int) -> str: # The color of text with a color of its own, for the variants of # `color_scheme` and `high_contrast` and their compound style. -COLOR: dict[str, dict[str, Any]] = { - "color_scheme": {"true": {**ACCENT_SCOPE, "color": tokens.accent.a[11]}}, +COLOR: dict[str, dict[str, StyleProps]] = { + "color_scheme": { + "true": unchecked({**ACCENT_SCOPE, "color": tokens.accent.a[11]}), + }, # Inside an element with a color; no declaration anywhere else. "high_contrast": {"true": {"color": f"var({ACCENT_TEXT})"}}, } -COLOR_HIGH_CONTRAST: Any = { +COLOR_HIGH_CONTRAST: CompoundStyle = { "props": {"color_scheme": "true", "high_contrast": "true"}, - "style": {**ACCENT_SCOPE_HIGH_CONTRAST, "color": tokens.accent[12]}, + "style": unchecked({**ACCENT_SCOPE_HIGH_CONTRAST, "color": tokens.accent[12]}), } diff --git a/tests/units/reflex_components_ui/style/test_merge.py b/tests/units/reflex_components_ui/style/test_merge.py index 51878eef2b1..1202373ccb9 100644 --- a/tests/units/reflex_components_ui/style/test_merge.py +++ b/tests/units/reflex_components_ui/style/test_merge.py @@ -13,6 +13,7 @@ Merged, merge, over, + unchecked, ) import reflex as rx @@ -746,3 +747,14 @@ def test_over_lays_the_styles_of_a_child_on_those_of_its_parent(): assert merged.style.inline is SIZE assert merged.dynamic == () assert merged.parts == {"icon": Merged(Lowered({"width": "1em"}))} + + +def test_unchecked_passes_a_style_a_type_checker_cannot_read(): + """A style with a custom property is the same style, lowered like any other.""" + style = {"--line-height": "1.5", "margin_top": "0"} + assert unchecked(style) is style + table: ComponentStyles = {"base": unchecked(style)} + assert merge("rx.ui.card", table).style.style == { + "--line-height": "1.5", + "marginTop": "0", + } From bedf0d45d67b86edd9089328584caafe2d30d657 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:49:24 +0000 Subject: [PATCH 040/204] Keep the child of as_child in place when it is bound to state, and tidy the wave after review Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB --- .../src/reflex_components_ui/base.py | 15 +++++++--- .../reflex_components_ui/typography/code.py | 8 +++-- .../tests_playwright/test_ui_components.py | 30 +++++++++++++++---- 3 files changed, 41 insertions(+), 12 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 5f904c7047b..c3854e79cce 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -285,10 +285,10 @@ def _check_literals(self, kwargs: Mapping[str, Any]) -> None: Raises: StyleError: If a prop is given a string it does not take. """ - literals = self._literal_props() - for prop in literals.keys() & kwargs.keys(): + for prop, choices in self._literal_props().items(): + if prop not in kwargs: + continue value = _literal(kwargs[prop]) - choices = literals[prop] for item in value.values() if isinstance(value, Mapping) else (value,): if item.__class__ is str and item not in choices: values = ", ".join([f'"{choice}"' for choice in choices]) @@ -366,6 +366,8 @@ def _post_init(self, *args, **kwargs): # whether this element renders as its only child. self._slotted = False self._as_child = False + # The merged styles the emitted source was made from. + self._emitted_for: Merged | None = None super()._post_init(*args, **kwargs) self._as: Var | None = None if "as_" in fields: @@ -414,6 +416,11 @@ def _set_slot(self) -> None: ) raise StyleError(msg) self._as_child = True + # The child has to stay the child: a compile would otherwise move + # one that is bound to state into a component of its own. + self._memoization_mode = dataclasses.replace( + self._memoization_mode, recursive=False + ) child = children[0] if isinstance(child, UIComponent): # This element declares the styles of both, the child's over its @@ -490,7 +497,7 @@ def _emit(self) -> Emitted: What the module that renders the element declares for it. """ merged = self._element_styles() - if merged is not getattr(self, "_emitted_for", None): + if merged is not self._emitted_for: self._emitted_for = merged self._emitted_styles = emit(merged) return self._emitted_styles diff --git a/packages/reflex-components-ui/src/reflex_components_ui/typography/code.py b/packages/reflex-components-ui/src/reflex_components_ui/typography/code.py index d90bfdbe9db..da2de7e8af3 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/typography/code.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/typography/code.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Any, ClassVar +from typing import ClassVar from reflex_base.components.component import Component, field from reflex_base.vars.base import Var @@ -55,8 +55,10 @@ def create(cls, *children, **props) -> Component: The code, which tells a link around it which variant it is: a link hides its underline under code that has a background. """ - custom_attrs: dict[str, Any] = props.setdefault("custom_attrs", {}) - custom_attrs.setdefault("data-variant", props.get("variant", "soft")) + props["custom_attrs"] = { + "data-variant": props.get("variant", "soft"), + **props.get("custom_attrs", {}), + } return super().create(*children, **props) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index d2dff44a84c..268e5e78271 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -105,6 +105,22 @@ "const sx_e9f4c4c063_c = stylex.props(sx_e9f4c4c063.s).className;", ] +# The one declaration of a flex container rendered as its child, a paragraph +# bound to state: the styles of both, in the module the compiler moves the +# pair into. +WAVE_MEMO_DECLARATIONS = [ + ( + 'const sx_d987dc85ff = stylex.create({ s: {"boxSizing": "border-box", ' + '"display": "flex", "justifyContent": "flex-start", "flexDirection": ' + '"column", "marginTop": "0", "marginRight": "0", "marginBottom": "0", ' + '"marginLeft": "0", "lineHeight": "var(--line-height, var(--default-line-' + 'height))", "letterSpacing": "var(--letter-spacing, inherit)", "fontSize": ' + '"var(--font-size-5)", "--line-height": "var(--line-height-5)", "--letter-' + 'spacing": "var(--letter-spacing-5)"} });' + ), + "const sx_d987dc85ff_c = stylex.props(sx_d987dc85ff.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. @@ -386,8 +402,9 @@ def wave(): color_scheme="ruby", id="colored", ), + # The child is bound to state, and stays the element all the same. rx.ui.flex( - rx.ui.text("slot", size="5", id="slot"), + rx.ui.text(StyleState.tone, size="5", id="slot"), as_child=True, direction="column", ), @@ -638,9 +655,10 @@ def declarations(path: Path) -> list[str]: (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 - ) + assert declarations(web / "app_components" / name / f"{name}.jsx") == [ + *WAVE_MEMO_DECLARATIONS, + *STYLED_MEMO_DECLARATIONS, + ] page.goto(_styled_url(ui_app)) rows = page.locator(".row") @@ -1244,7 +1262,9 @@ def test_layout_and_typography_components_are_styled_and_navigate( page.goto(ui_app.frontend_url.rstrip("/") + "/wave") expect(page.locator("#center")).to_have_css("display", "flex") assert _computed_styles(page, WAVE) == WAVE - assert page.locator("#slot").evaluate("element => element.tagName") == "P" + slot = page.locator("#slot") + assert slot.evaluate("element => element.tagName") == "P" + expect(slot).to_have_text("calm") # A prop follows the breakpoints of Radix Themes: md is 1024px. page.set_viewport_size({"width": 1280, "height": 600}) From a8dac31a589f152bfd6ba0deece242a3db7cb372 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 16:55:46 +0000 Subject: [PATCH 041/204] Restore the imports the rx.ui test fixtures need after the merge Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- tests/units/reflex_components_ui/conftest.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/units/reflex_components_ui/conftest.py b/tests/units/reflex_components_ui/conftest.py index 56ea26b01a4..a7ba988a640 100644 --- a/tests/units/reflex_components_ui/conftest.py +++ b/tests/units/reflex_components_ui/conftest.py @@ -6,8 +6,10 @@ import sys from collections.abc import Callable from pathlib import Path +from typing import Any import pytest +from reflex_base.components.component import Component from reflex_base.config import get_config from reflex_components_ui.plugin import UIPlugin From 24e3d7ae2379d7cc4c39196d1cc4782b70e97e4f Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:09:28 +0000 Subject: [PATCH 042/204] Dispatch an early click only after the page's mount effects The click recorded before hydration was dispatched from the mount effect of Scripts, a leaf: providers above it had not run their own effects yet, and the updates of those that had were not applied. It is now dispatched from the effect of a transition started on mount, which React renders only after every update of a higher priority. A click between hydrateRoot and that point had the same problem without any replay: React hydrates synchronously and runs the handler before the mount effects, so the theme provider restored the stored color mode over the one the click had just set. Such a click is now held back from React at the window and dispatched with the recorded one. Clicks in a form or on a control the browser acts on are left alone, and a ten second limit lets clicks through again if hydration never completes. Claude-Session: https://claude.ai/code/session_014AwvTNacWVsm7SEvVjhfGM --- packages/reflex-frontend/README.md | 9 +- packages/reflex-frontend/src/utils/scripts.js | 85 +++++++++++--- .../reflex-frontend/tests/public_api.test.js | 1 + .../reflex-frontend/tests/scripts.test.js | 105 +++++++++++++++++- .../test_scripts_after_first_paint.py | 53 +++++++++ 5 files changed, 228 insertions(+), 25 deletions(-) diff --git a/packages/reflex-frontend/README.md b/packages/reflex-frontend/README.md index e40f5c71086..59aea0829fb 100644 --- a/packages/reflex-frontend/README.md +++ b/packages/reflex-frontend/README.md @@ -77,9 +77,12 @@ without it appearing in its arguments. What there is, and where it is pinned: 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. + The entry point calls `takeEarlyClick` right before `hydrateRoot`; from then + until the page has settled, that module holds clicks back from React, which + would run a handler before the mount effects of the page. The last click is + dispatched once, from the effect of a transition `Scripts` starts on mount. + An entry point that hydrates without calling it loses a click made before + hydration, 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/utils/scripts.js b/packages/reflex-frontend/src/utils/scripts.js index 3db32d083a4..4de86fe6e41 100644 --- a/packages/reflex-frontend/src/utils/scripts.js +++ b/packages/reflex-frontend/src/utils/scripts.js @@ -2,8 +2,10 @@ import { createElement, Fragment, isValidElement, + startTransition, useContext, useEffect, + useState, } from "react"; import { Scripts as RouterScripts, @@ -62,21 +64,55 @@ observer.observe({type:"paint",buffered:true}); }`; /** - * Elements a click already acted on without javascript, or that are not safe - * to click a second time: a link is being followed, a form control or a - * `
` has changed state. + * How long the click of a page that is being hydrated is held back for at + * most. Hydration settles in milliseconds; the limit is for a page whose + * hydration never completes, which must not swallow clicks for good. + * Exported for the tests. + */ +export const HOLD_CLICK_TIMEOUT_MS = 10000; + +/** + * Where a click acts without javascript, or is not safe to dispatch a second + * time: a link is being followed, a form is submitted, a form control or a + * `
` has changed state. Such a click is left to the browser. */ const ACTS_WITHOUT_SCRIPTS = - "a[href],area[href],input,select,textarea,label,summary,[contenteditable]"; + "a[href],area[href],form,input,select,textarea,label,summary,[contenteditable]"; let earlyClick = null; +let holdTimer; + +/** + * Hold back a click on a page that is being hydrated. + * + * React would hydrate at once and run the handler, before any mount effect + * of the page: a provider that sets itself up in one then overwrites what the + * handler did. The click is kept from React and dispatched again with the one + * recorded before, once the page has settled. + * @param {MouseEvent} event The click, in the capture phase at the window. + */ +const holdClick = (event) => { + earlyClick = null; + if ( + event.target instanceof Element && + !event.target.closest(ACTS_WITHOUT_SCRIPTS) + ) { + earlyClick = event; + event.stopImmediatePropagation(); + } +}; + +const stopHolding = () => { + window.removeEventListener("click", holdClick, true); + clearTimeout(holdTimer); +}; /** - * Stop the inline script recording clicks, and keep the last one it saw. + * Take over the clicks of a prerendered page that is about to be hydrated. * - * 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. + * Called right before `hydrateRoot`. The inline script stops recording, and + * its last click is kept. Until the page has settled, later clicks are held + * back here, so React never sees a click that is dispatched again afterwards. */ export const takeEarlyClick = () => { const early = window.__reflex_early; @@ -84,17 +120,24 @@ export const takeEarlyClick = () => { document.removeEventListener("click", early.record, true); earlyClick = early.click; window.__reflex_early = undefined; + window.addEventListener("click", holdClick, true); + holdTimer = setTimeout(() => { + earlyClick = null; + stopHolding(); + }, HOLD_CLICK_TIMEOUT_MS); }; /** - * Dispatch again the click a prerendered page got before it was hydrated. + * Dispatch again the last click a prerendered page got before it could + * handle one properly, and let clicks through from here on. * - * 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. An entry point that never took the click over - * gets none dispatched: there is no telling whether React handled it. + * Without this a click before hydration 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 it. An entry point that never took the clicks + * over gets none dispatched: there is no telling whether React handled it. */ const replayEarlyClick = () => { + stopHolding(); const click = earlyClick; earlyClick = null; const target = click?.target; @@ -142,14 +185,24 @@ const useRouterScripts = RouterScripts; * (dev mode, the SPA fallback) has nothing to paint before its scripts run, * and gets what react-router renders. * - * A click that comes while a prerendered page cannot handle one yet is - * dispatched again once it is hydrated. + * A click that comes while a prerendered page cannot handle one yet, before + * or during hydration, is dispatched again once the page has settled. * @param {import("react-router").ScriptsProps} props Props for the script tags. * @returns {import("react").ReactNode} The script and link tags. */ export function Scripts(props) { const rendered = useRouterScripts(props); - useEffect(replayEarlyClick, []); + // Effects run child first, and this component is a leaf: on mount, no + // provider above it has run its own yet, and none of the updates those + // schedule has been applied. A transition is rendered only once every + // update of a higher priority has been, which covers the updates of mount + // effects and of the effects those renders trigger in turn. So the click is + // dispatched from the effect of a transition started on mount. + const [settled, setSettled] = useState(false); + useEffect(() => startTransition(() => setSettled(true)), []); + useEffect(() => { + if (settled) replayEarlyClick(); + }, [settled]); const isSpaMode = useContext(FrameworkContext)?.isSpaMode; if (isSpaMode !== false || !rendered) return rendered; const elements = flatten(rendered); diff --git a/packages/reflex-frontend/tests/public_api.test.js b/packages/reflex-frontend/tests/public_api.test.js index 05d524a0013..6893e195c9a 100644 --- a/packages/reflex-frontend/tests/public_api.test.js +++ b/packages/reflex-frontend/tests/public_api.test.js @@ -125,6 +125,7 @@ const PUBLIC_API = { "$/utils/helpers/upload": ["uploadFiles"], "$/utils/scripts": [ "FIRST_PAINT_TIMEOUT_MS", + "HOLD_CLICK_TIMEOUT_MS", "START_AFTER_FIRST_PAINT", "Scripts", "takeEarlyClick", diff --git a/packages/reflex-frontend/tests/scripts.test.js b/packages/reflex-frontend/tests/scripts.test.js index b27b45a9ccc..91025c65ac0 100644 --- a/packages/reflex-frontend/tests/scripts.test.js +++ b/packages/reflex-frontend/tests/scripts.test.js @@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { FIRST_PAINT_TIMEOUT_MS, + HOLD_CLICK_TIMEOUT_MS, START_AFTER_FIRST_PAINT, Scripts, } from "$/utils/scripts"; @@ -304,16 +305,21 @@ describe("START_AFTER_FIRST_PAINT", () => { * 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. + * @param {(scripts: object, react: typeof import("react")) => object} [options.wrap] Builds the page around the scripts element. */ - const hydrate = async ({ take = true } = {}) => { + const hydrate = async ({ + take = true, + wrap = (scripts) => scripts, + } = {}) => { vi.resetModules(); - const { act, createElement } = await import("react"); + const react = await import("react"); + const { act, createElement } = react; const { createRoot } = await import("react-dom/client"); const { createRoutesStub } = await import("react-router"); const { Scripts, takeEarlyClick } = await import("$/utils/scripts"); if (take) takeEarlyClick(); const Stub = createRoutesStub([ - { path: "/", Component: () => createElement(Scripts) }, + { path: "/", Component: () => wrap(createElement(Scripts), react) }, ]); const container = document.body.appendChild( document.createElement("div"), @@ -355,6 +361,40 @@ describe("START_AFTER_FIRST_PAINT", () => { expect(clicks.length).toBe(3); }); + test("is handled after the mount effects of the whole page", async () => { + // A provider that restores its value in a mount effect, as the theme + // provider does from storage, must not overwrite what the click set. + const { target } = addToPage(''); + const page = { set: null, values: [] }; + target.addEventListener("click", () => page.set?.("clicked")); + run(); + click(target); + + const provider = (scripts, { createElement, useEffect, useState }) => + createElement(function Provider() { + const [value, setValue] = useState("default"); + const [restored, setRestored] = useState(false); + page.set = setValue; + page.values.push(value); + useEffect(() => { + setValue("stored"); + setRestored(true); + }, []); + // A second round: an effect that only runs once the first applied. + useEffect(() => { + if (restored) setValue((current) => current + "+restored"); + }, [restored]); + return scripts; + }); + await hydrate({ wrap: provider }); + expect(page.values).toEqual([ + "default", + "stored", + "stored+restored", + "clicked", + ]); + }); + test("only the last one is dispatched again", async () => { const first = addToPage(''); run(); @@ -397,15 +437,68 @@ describe("START_AFTER_FIRST_PAINT", () => { expect(clicks.length).toBe(1); }); - test("is not recorded once the entry point took it over", async () => { + test("during hydration is held back from React and dispatched once", async () => { const { target, clicks } = addToPage(''); run(); const { record } = window.__reflex_early; const removed = vi.spyOn(document, "removeEventListener"); - await hydrate(); + const page = { values: [] }; + // The entry point has taken the clicks over when the page renders. + const clickWhileRendering = (scripts, { createElement, useState }) => + createElement(function Page() { + const [clicked] = useState(() => click(target)); + page.values.push(clicked, clicks.length); + return scripts; + }); + await hydrate({ wrap: clickWhileRendering }); expect(removed.mock.calls).toEqual([["click", record, true]]); + // Dispatching returned true, and no listener of the page ran then. + expect(page.values.slice(0, 2)).toEqual([true, 0]); + expect(clicks.length).toBe(1); + expect(clicks[0].isTrusted).toBe(false); + + // The page handles its own clicks from here on. + click(target); + expect(clicks.length).toBe(2); + vi.advanceTimersByTime(HOLD_CLICK_TIMEOUT_MS); + expect(clicks.length).toBe(2); + }); + + test("during hydration is left to React where the browser acts on it", async () => { + addToPage('
'); + const target = document.getElementById("target"); + const seen = []; + document.addEventListener( + "click", + (event) => { + event.preventDefault(); + seen.push(event); + }, + { once: true }, + ); + run(); + const clickWhileRendering = (scripts, { createElement, useState }) => + createElement(function Page() { + useState(() => click(target)); + return scripts; + }); + await hydrate({ wrap: clickWhileRendering }); + expect(seen.length).toBe(1); + }); + + test("is let through again when hydration never completes", async () => { + const { target, clicks } = addToPage(''); + run(); + vi.resetModules(); + const { takeEarlyClick } = await import("$/utils/scripts"); + takeEarlyClick(); + click(target); + expect(clicks.length).toBe(0); + vi.advanceTimersByTime(HOLD_CLICK_TIMEOUT_MS - 1); + click(target); + expect(clicks.length).toBe(0); + vi.advanceTimersByTime(1); click(target); - await hydrate(); expect(clicks.length).toBe(1); }); diff --git a/tests/integration/tests_playwright/test_scripts_after_first_paint.py b/tests/integration/tests_playwright/test_scripts_after_first_paint.py index eb1324373f5..ba8471b526e 100644 --- a/tests/integration/tests_playwright/test_scripts_after_first_paint.py +++ b/tests/integration/tests_playwright/test_scripts_after_first_paint.py @@ -48,6 +48,7 @@ def counter(heading: rx.Component, *links: rx.Component) -> rx.Component: heading, rx.el.p(CounterState.count, id="count"), rx.el.button("Increment", id="increment", on_click=CounterState.increment), + rx.el.button("Toggle", id="toggle", on_click=rx.toggle_color_mode), *links, ) @@ -185,3 +186,55 @@ def test_input_before_first_paint_starts_scripts(scripts_app: AppHarness, page: expect(page.locator("#count")).to_have_text("1") increment.click() expect(page.locator("#count")).to_have_text("2") + + +def test_click_before_hydration_outlasts_mount_effects( + scripts_app: AppHarness, page: Page +): + """A replayed click is handled after the providers have set themselves up. + + The theme provider restores the color mode in a mount effect, which must + not overwrite the mode the click switched to. + """ + if not isinstance(scripts_app, AppHarnessProd): + pytest.skip("pages are prerendered in prod only") + page.emulate_media(color_scheme="light") + page.add_init_script(NEVER_PAINTED) + page.goto(_frontend_url(scripts_app), wait_until="load") + html = page.locator("html") + expect(html).to_have_class("light") + assert not page.evaluate(HYDRATED) + + page.get_by_role("button", name="Toggle").click() + expect(html).to_have_class("dark") + page.wait_for_function(HYDRATED) + assert page.evaluate("localStorage.getItem('theme')") == "dark" + + +# Clicks the toggle in the first microtask after the entry point hydrates: +# the entry point clears `__reflex_early` right before it calls hydrateRoot. +CLICK_WHILE_HYDRATING = """ +let early; +Object.defineProperty(window, "__reflex_early", { + get: () => early, + set: (value) => { + if (early && !value) { + queueMicrotask(() => document.getElementById("toggle").click()); + } + early = value; + }, +}); +""" + + +def test_click_while_hydrating_outlasts_mount_effects( + scripts_app: AppHarness, page: Page +): + """A click React handles by hydrating first is not undone by mount effects.""" + if not isinstance(scripts_app, AppHarnessProd): + pytest.skip("pages are prerendered in prod only") + page.emulate_media(color_scheme="light") + page.add_init_script(CLICK_WHILE_HYDRATING) + page.goto(_frontend_url(scripts_app)) + page.wait_for_function(HYDRATED) + expect(page.locator("html")).to_have_class("dark") From 18bd167934a9bb511aa2545d632613ef56482531 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:15:06 +0000 Subject: [PATCH 043/204] Add keyframes to rx.ui styles, a radius of its own to a component, and keep the imports of a component held in state apart from a page's Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../src/reflex_base/components/dynamic.py | 24 +++- packages/reflex-components-ui/js/src/base.css | 27 ++++ .../src/reflex_components_ui/base.py | 93 ++++++++++--- .../src/reflex_components_ui/layout/theme.py | 3 + .../reflex_components_ui/style/__init__.py | 4 + .../src/reflex_components_ui/style/emit.py | 43 +++++- .../src/reflex_components_ui/style/lower.py | 126 +++++++++++++++++- .../src/reflex_components_ui/themes.py | 44 ++++++ reflex/compiler/utils.py | 6 +- tests/units/reflex_components_ui/test_base.py | 55 ++++++++ 10 files changed, 393 insertions(+), 32 deletions(-) diff --git a/packages/reflex-base/src/reflex_base/components/dynamic.py b/packages/reflex-base/src/reflex_base/components/dynamic.py index 64779538a51..4209f54e30d 100644 --- a/packages/reflex-base/src/reflex_base/components/dynamic.py +++ b/packages/reflex-base/src/reflex_base/components/dynamic.py @@ -1,8 +1,10 @@ """Components that are dynamically generated on the backend.""" +import contextlib import contextvars import dataclasses import json +from collections.abc import Iterator from typing import TYPE_CHECKING, Any, Union from reflex_base import constants @@ -41,6 +43,23 @@ def is_rendering_dynamic_component() -> bool: return _RENDERING_DYNAMIC_COMPONENT.get() +@contextlib.contextmanager +def rendering_dynamic_component() -> Iterator[None]: + """Generate code that is evaluated in the browser at runtime. + + For what is read from a component on behalf of the code it is serialized + to, such as the libraries that code imports. + + Yields: + Nothing: ``is_rendering_dynamic_component`` is True inside the block. + """ + token = _RENDERING_DYNAMIC_COMPONENT.set(True) + try: + yield + finally: + _RENDERING_DYNAMIC_COMPONENT.reset(token) + + def __getattr__(name: str) -> Any: """Provide the module-level globals that moved onto `RegistrationContext`. @@ -195,11 +214,8 @@ def make_component(component: Component) -> str: Returns: The generated code """ - token = _RENDERING_DYNAMIC_COMPONENT.set(True) - try: + with rendering_dynamic_component(): 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. diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index 27641ea20b1..a827eab45ab 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -27,6 +27,25 @@ html.dark { color-scheme: dark; } +/* + * `light-dark()` only chooses between colors. A value of another kind that + * differs between the appearances, such as a filter or the geometry of a + * shadow, is written `var(--rx-if-light, ) var(--rx-if-dark, )`: + * the property of the current appearance is invalid, so its fallback is used, + * and the other one is empty. The classes are those of the color mode, and of + * the element around a theme with an appearance of its own. + */ +:where(html), +.light { + --rx-if-light: initial; + --rx-if-dark: ; +} + +.dark { + --rx-if-light: ; + --rx-if-dark: initial; +} + /* * What Radix Themes styles through a selector that a class on the element * cannot express. A theme element carries the class `reflex-ui-theme`. @@ -35,6 +54,14 @@ html.dark { .reflex-ui-theme ::selection { background-color: var(--focus-a5); } + + /* + * A button dims the icons inside it: it hands the opacity down, and + * everything else is left as it is. + */ + .reflex-ui-theme svg { + opacity: var(--rx-icon-opacity, revert-layer); + } } /* 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 a4ad5654077..b14597ff5c8 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -19,7 +19,7 @@ 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.utils.imports import ImportDict, ImportVar, ParsedImportDict from reflex_base.vars.base import LiteralVar, Var, VarData from reflex_base.vars.sequence import LiteralStringVar @@ -34,7 +34,7 @@ from reflex_components_ui.style.emit import Emitted, emit, inline from reflex_components_ui.style.lower import EMPTY, suggest from reflex_components_ui.style.merge import over -from reflex_components_ui.themes import color_scheme_styles +from reflex_components_ui.themes import ThemeStyles, color_scheme_styles, radius_styles MISSING_PLUGIN_ERROR = ( "rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins." @@ -205,6 +205,10 @@ class UIComponent(Component): # component, as Radix Themes falls back to its default. _as_tags: ClassVar[frozenset[str]] = frozenset() + # Whether a `radius` field is the radius of the element itself, applied + # as a theme. A theme element has the option for what is inside it. + _own_radius: ClassVar[bool] = True + # How the stubs type the style: the properties and keywords of CSS. _pyi_overwrite_types: ClassVar[dict[str, str]] = { "style": ( @@ -310,7 +314,8 @@ def _post_init(self, *args, **kwargs): a Var, or cannot be compiled, if a prop is given a value it does not take, or if ``as_child`` has no single element to render. - ThemeError: If the ``color_scheme`` is not an accent color. + ThemeError: If the ``color_scheme`` is not an accent color, or the + ``radius`` not one a theme takes. """ fields = self.get_fields() triggers = self.get_event_triggers() @@ -362,6 +367,13 @@ def _post_init(self, *args, **kwargs): if color_scheme is None else color_scheme_styles(self._display_name(), color_scheme) ) + # The same for a radius of its own. + radius = ( + kwargs.get("radius") if self._own_radius and "radius" in fields else None + ) + self._radius = ( + None if radius is None else radius_styles(self._display_name(), radius) + ) # Whether a parent with `as_child` renders as this element, and # whether this element renders as its only child. self._slotted = False @@ -526,6 +538,19 @@ def _slot_styles(self) -> Merged: merged = over(merged, slot._slot_styles()) return merged + @property + def _themes(self) -> tuple[ThemeStyles, ...]: + """The themes the element carries beside its styles. + + Returns: + The themes of its accent color and of its radius, for a + component that is given one. + """ + accent, radius = self._accent, self._radius + if accent is None: + return () if radius is None else (radius,) + return (accent,) if radius is None else (accent, radius) + def _get_vars( self, include_children: bool = False, ignore_ids: set[int] | None = None ) -> Iterator[Var]: @@ -540,10 +565,27 @@ def _get_vars( """ yield from super()._get_vars(include_children, ignore_ids) yield from self._emit().vars - if self._accent is not None: - yield from self._accent.vars + for theme in self._themes: + yield from theme.vars + + def _get_imports(self) -> ParsedImportDict: + """Get the imports of the element, for the kind of code it renders in. - def add_imports(self) -> ImportDict: + A page imports StyleX and the modules of the tokens, and code that is + evaluated in the browser imports neither. A component held in state + is asked for both, so what one kind of code imports is not kept for + the other. + + Returns: + The imports needed by the component. + """ + dynamic = is_rendering_dynamic_component() + if self.__dict__.get("_imports_for") is not dynamic: + self.__dict__.pop("_imports_cache", None) + self._imports_for = dynamic + return super()._get_imports() + + def add_imports(self) -> ImportDict | list[ImportDict]: """Import StyleX, which the build compiles away, and the CSS of tokens. Returns: @@ -563,8 +605,9 @@ def add_imports(self) -> ImportDict: imports[""] = [ ImportVar(tag=module, install=False) for module in emitted.imports ] - if self._accent is not None: - imports.update(self._accent.import_dict()) + themes = self._themes + if themes: + return [imports, *[theme.import_dict() for theme in themes]] return imports def add_custom_code(self) -> list[str]: @@ -583,8 +626,8 @@ def add_custom_code(self) -> list[str]: raise ConfigError(MISSING_PLUGIN_ERROR) declaration = self._emit().declaration code = [] if declaration is None else [declaration] - if self._accent is not None: - code.extend(self._accent.declarations) + for theme in self._themes: + code.extend(theme.declarations) return code def _get_style(self) -> dict: @@ -609,11 +652,18 @@ def _exclude_props(self) -> list[str]: Returns: The layout props, the props that select a variant, and the accent - color of the component: an attribute of that name is nothing to - an element. + color and the radius of the component: an attribute of that name + is nothing to an element. """ layout_props, variants = self._style_props() - return [*layout_props, *variants, "color_scheme", "as", "as_child"] + return [ + *layout_props, + *variants, + "color_scheme", + "radius", + "as", + "as_child", + ] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the element with its style. @@ -645,11 +695,12 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: }, special_props=[*tag.special_props, *child.special_props], ) - accent = self._accent + themes = self._themes if is_rendering_dynamic_component(): - if accent is not None: + if themes: + prop = "color_scheme" if self._accent is not None else "radius" msg = ( - f"{self._display_name()}: color_scheme cannot be applied to " + f"{self._display_name()}: {prop} 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." @@ -660,11 +711,13 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: if get_plugin(UIPlugin) is None: raise ConfigError(MISSING_PLUGIN_ERROR) emitted = self._emit() - if accent is not None: - # The themes of an accent only set custom properties, so their - # class names stand beside the ones of the styles. + if themes: + # The themes of an accent and of a radius only set custom + # properties, so their class names stand beside the ones of the + # styles. emitted = dataclasses.replace( - emitted, lookups=(*emitted.lookups, accent.classes) + emitted, + lookups=(*emitted.lookups, *[theme.classes for theme in themes]), ) return add_styles(tag, emitted) 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 5c6dd169bc9..6675991a1b9 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,6 +72,9 @@ class ThemeElement(UIComponent): tag = "div" + # The radius is an option of the theme, for what is inside the element. + _own_radius: ClassVar[bool] = False + accent_color: Var[LiteralAccentColor] = field( is_javascript_property=False, doc="The color of the components that stand out.", 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 index 39bc69b849e..246d14c1bf9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py @@ -6,8 +6,10 @@ from reflex_components_ui.style.lower import ( LAYOUT_PROPS, VAR_MODULES, + Keyframes, Lowered, StyleError, + keyframes, lower, ) from reflex_components_ui.style.merge import ( @@ -26,10 +28,12 @@ "Alternatives", "ComponentStyles", "CompoundStyle", + "Keyframes", "Lowered", "Merged", "StyleError", "StyleProps", + "keyframes", "lower", "merge", "over", 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 909d817ac50..60efa9b75cd 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 @@ -28,7 +28,7 @@ from reflex_base.utils.types import safe_issubclass from reflex_base.vars.base import Var -from reflex_components_ui.style.lower import StyleError +from reflex_components_ui.style.lower import Keyframes, StyleError from reflex_components_ui.style.merge import Alternatives, Merged # The key under which a declaration holds the style every instance has. @@ -237,7 +237,13 @@ def literal(self, value: Any, prop: str) -> Any: 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: + if ( + cls is str + or cls is int + or cls is float + or value is None + or cls is Keyframes + ): return value if cls is dict: return { @@ -371,11 +377,33 @@ def _emit(merged: Merged) -> Emitted: tables.insert(0, f"const {_NAME}_c = {_classes(_KEY)};") declaration = classes = None if styles: + animations: dict[Keyframes, str] = {} + + def reference(value: Any) -> str: + """Stand in for the keyframes of a style until they have a name. + + Args: + value: What JSON cannot hold: the keyframes of an animation. + + Returns: + A marker that no style can hold, as JSON escapes it. + """ + return animations.setdefault(value, f"\1{len(animations)}\1") + entries = ", ".join([ - f"{key}: {json.dumps(style, ensure_ascii=False)}" + f"{key}: {json.dumps(style, ensure_ascii=False, default=reference)}" for key, style in styles.items() ]) + for position, frames in enumerate(animations): + # StyleX compiles a reference to keyframes of the same module. + entries = entries.replace( + f'"\\u0001{position}\\u0001"', f"{_NAME}_k{position}" + ) template = "\n".join([ + *[ + f"const {_NAME}_k{position} = stylex.keyframes({frames.source});" + for position, frames in enumerate(animations) + ], f"const {_NAME} = stylex.create({{ {entries} }});", *tables, ]) @@ -414,6 +442,8 @@ def emit(merged: Merged) -> Emitted: style = lowered.style if not style: return _NOTHING + if "animationName" in style: + return _emit(merged) try: source = json.dumps(style, ensure_ascii=False) except TypeError: @@ -474,6 +504,13 @@ def inline(merged: Merged, component: str) -> dict[str, str | int | float]: f"{_RENDER_IN_PAGE}" ) raise StyleError(msg) + if value.__class__ is Keyframes: + msg = ( + f'{component}: the style "{prop}" plays keyframes, ' + f"{_NOT_RENDERED_IN_PAGE} Leave the animation out there, or " + f"{_RENDER_IN_PAGE}" + ) + raise StyleError(msg) if isinstance(value, Var): msg = ( f'{component}: the style "{prop}" is bound to state, ' 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 b5367903203..054fa6a2d3f 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 @@ -9,12 +9,14 @@ 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. + condition map and in the alternatives of a state-bound variant; +- a ``Keyframes``, the value of ``animationName`` alone. 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 +them; ``animation``, which cannot be split here, is refused: an animation is +its longhands, with ``keyframes(...)`` as its ``animation_name``. 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. @@ -26,6 +28,7 @@ from __future__ import annotations import difflib +import json import re from collections.abc import Callable, Mapping from typing import TYPE_CHECKING, Any @@ -632,6 +635,110 @@ def _entries() -> tuple[dict[str, _Entry], dict[str, _Entry]]: _SNAKE_KEYS = tuple(_ENTRIES) +class Keyframes: + """The keyframes of an animation, declared with the style that plays them. + + Two of them are equal, and hash the same, when they hold the same + declarations, so one animation is declared once per module however many + styles play it. + + Attributes: + source: The frames as the object ``stylex.keyframes`` takes. + imports: The modules that define the custom properties the frames + use, sorted. + """ + + __slots__ = ("imports", "source") + + def __init__(self, source: str, imports: tuple[str, ...]): + """Hold lowered keyframes. + + Args: + source: The frames as the object ``stylex.keyframes`` takes. + imports: The modules the frames need, sorted. + """ + self.source = source + self.imports = imports + + def __eq__(self, other: object) -> bool: + """Compare with other keyframes. + + Args: + other: What to compare with. + + Returns: + Whether both declare the same animation. + """ + return isinstance(other, Keyframes) and self.source == other.source + + def __hash__(self) -> int: + """Hash consistently with equality. + + Returns: + The hash of the source. + """ + return hash(self.source) + + def __repr__(self) -> str: + """Show what the keyframes hold. + + Returns: + The constructor call that would rebuild them. + """ + return f"Keyframes({self.source!r}, {self.imports!r})" + + +def keyframes(frames: Mapping[str, StyleProps | Mapping[str, Any]]) -> Any: + """Declare the keyframes of an animation, for a style to play. + + The result is the value of ``animation_name``, in a style table or in the + style of an element. StyleX names the animation after its content and + drops the ``animation`` shorthand, so the rest of an animation is its + longhands:: + + { + "animation_name": keyframes({"from": {"opacity": 1}, "to": {"opacity": 0}}), + "animation_duration": "800ms", + "animation_iteration_count": "infinite", + } + + Args: + frames: The styles of each frame, by ``from``, ``to`` or a percentage. + Every value is a literal: a frame has no conditions and nothing + bound to state. + + Returns: + The keyframes. + + Raises: + StyleError: If a frame is not a dict of literal styles. + """ + name = "rx.ui keyframes" + lowered: dict[str, dict[str, Any]] = {} + found: set[str] = set() + for frame, style in frames.items(): + if not isinstance(style, Mapping): + msg = ( + f'{name}: the frame "{frame}" must be a dict of styles, not ' + f"{type(style).__name__}." + ) + raise StyleError(msg) + props, _ = lower_layer(name, style) + for prop, value in props.items(): + cls = value.__class__ + if cls is str: + _modules(value, found) + elif cls is not int and cls is not float: + msg = ( + f'{name}: the style "{prop}" of the frame "{frame}" must be ' + "a literal: a frame takes no condition and nothing bound " + "to state." + ) + raise StyleError(msg) + lowered[frame] = props + return Keyframes(json.dumps(lowered, ensure_ascii=False), tuple(sorted(found))) + + def _put( out: dict[str, LoweredValue], prop: str, path: tuple[str, ...], value: Any ) -> None: @@ -794,6 +901,15 @@ def _value( ) _value(name, key, entry, item, inner, out, replaced) return + elif cls is Keyframes: + if entry[0] != "animationName": + msg = ( + f'{name}: style "{key}" is given keyframes, which are the ' + "value of animation_name." + ) + raise StyleError(msg) + _put(out, "animationName", path, value) + return elif not isinstance(value, Var): msg = ( f'{name}: style "{key}" cannot take a value of type ' @@ -1179,6 +1295,8 @@ def freeze(value: LoweredValue) -> Any: return tuple([(key, freeze(item)) for key, item in value.items()]) if cls is Lowered: return value.key + if cls is Keyframes: + return value return (Var, value._hash_key()) @@ -1198,6 +1316,8 @@ def _modules(value: LoweredValue, found: set[str]) -> None: elif value.__class__ is dict: for item in value.values(): _modules(item, found) + elif value.__class__ is Keyframes: + found.update(value.imports) class Lowered: @@ -1304,7 +1424,7 @@ def finish( if cls is str: if "var(--" in value: _modules(value, found) - elif cls is dict: + elif cls is dict or cls is Keyframes: _modules(value, found) elif value is None: dropped = True 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 e0953c30c85..ca33b05bed4 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/themes.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/themes.py @@ -82,6 +82,7 @@ _SCALING_MAP = "reflexUIScalings" _PANEL_MAP = "reflexUIPanels" _COLOR_SCHEME_MAP = "reflexUIColorSchemes" +_ELEMENT_RADIUS_MAP = "reflexUIElementRadii" # What joins the class names of compiled styles, and its local name. _CLASS_NAME = ("class-name.js", "className") @@ -91,6 +92,12 @@ _CONSTANT = "reflexUIClasses" +# The theme that declares the steps of the radius scale again. +_RADIUS_SCOPE = next( + scope for scope in _radix_tokens.SCOPE_THEMES if scope[1] == "radiusScope" +) + + class ThemeError(ReflexError, ValueError): """A theme option that cannot be applied.""" @@ -550,3 +557,40 @@ def themes(accent: str) -> list[str]: return builder.finish(f"{_COLOR_SCHEME_MAP}[{builder.bound(color_scheme)}]") _check(name, "color_scheme", color_scheme, "accent_color") return builder.finish(builder.call(themes(color_scheme))) + + +def radius_styles(name: str, radius: Any) -> ThemeStyles: + """Work out the StyleX themes of a component with a radius of its own. + + The radius, and the steps of the radius scale, which read it on the + element they are declared on. A radius bound to state imports the five + of them: their class names are joined once, in a table the element + indexes. + + Args: + name: The display name of the component, which starts an error message. + radius: The radius of the component, or a Var holding it. + + Returns: + What the element needs. + + Raises: + ThemeError: If the radius is not one a theme takes. + """ + tokens = _radix_tokens + builder = _Builder(name) + radius = literal_option(radius) + scope = builder.add(_RADIUS_SCOPE) + if isinstance(radius, Var): + entries = ", ".join([ + f"{json.dumps(value)}: {builder.call([scope, builder.add(theme)])}" + for value, theme in tokens.RADIUS_THEMES.items() + ]) + builder.declarations.append( + f"const {_ELEMENT_RADIUS_MAP} = {{ __proto__: null, {entries} }};" + ) + return builder.finish(f"{_ELEMENT_RADIUS_MAP}[{builder.bound(radius)}]") + _check(name, "radius", radius) + return builder.finish( + builder.call([scope, builder.add(tokens.RADIUS_THEMES[radius])]) + ) diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index eda4a18d094..a32d1903c1a 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -24,7 +24,7 @@ scoped_memo_wrapper, ) from reflex_base.components.component import BaseComponent, Component, ComponentStyle -from reflex_base.components.dynamic import _bundle_imports +from reflex_base.components.dynamic import _bundle_imports, rendering_dynamic_component from reflex_base.components.memo import ( DEFAULT_MEMO_WRAPPER, MemoComponentDefinition, @@ -303,7 +303,9 @@ def serialize_initial_value(value: Any) -> Any: The serialized value. """ if isinstance(value, Component): - value_imports = value._get_all_imports() + # The imports of the code the component is serialized to. + with rendering_dynamic_component(): + value_imports = value._get_all_imports() _bundle_imports(value_imports) if component_imports is not None: for library, fields in value_imports.items(): diff --git a/tests/units/reflex_components_ui/test_base.py b/tests/units/reflex_components_ui/test_base.py index 6539608bb75..0ba93448ec7 100644 --- a/tests/units/reflex_components_ui/test_base.py +++ b/tests/units/reflex_components_ui/test_base.py @@ -1,5 +1,6 @@ """Tests for reflex_components_ui.base.""" +import json from collections.abc import Callable from typing import Any, ClassVar, Literal @@ -9,6 +10,7 @@ from reflex_base.components.memo import MEMOS from reflex_base.config import get_config from reflex_base.plugins import CompileContext +from reflex_base.registry import RegistrationContext from reflex_base.utils.exceptions import ConfigError from reflex_base.utils.serializers import serialize from reflex_base.vars.base import Var @@ -21,6 +23,7 @@ import reflex as rx from reflex.compiler import compiler +from reflex.compiler import utils as compiler_utils from reflex.compiler.plugins.builtin import ApplyStylePlugin # A page whose elements use the tokens of two modules, two of them equally. @@ -702,6 +705,58 @@ def test_dynamic_component_falls_back_to_an_inline_style(): assert serialize(component) == DYNAMIC_MODULE +def _soft_button() -> UIComponent: + """Create the button the dynamic module above renders. + + Returns: + The button. + """ + return Button.create( + "hello", kind="soft", style={"padding": "4px", "z_index": 2}, class_name="p-8" + ) + + +def test_dynamic_component_whose_imports_a_page_read_never_imports_stylex(): + """The imports of a page and of code for the browser are kept apart.""" + component = _soft_button() + assert list(component._get_all_imports()) == ["@stylexjs/stylex"] + assert serialize(component) == DYNAMIC_MODULE + assert list(component._get_all_imports()) == ["@stylexjs/stylex"] + + +def test_page_imports_stylex_for_a_component_that_was_serialized_first(): + """Serializing a component for the browser does not empty its page imports.""" + component = _soft_button() + assert serialize(component) == DYNAMIC_MODULE + assert list(component._get_all_imports()) == ["@stylexjs/stylex"] + + +def test_initial_state_reads_the_imports_of_a_dynamic_component( + monkeypatch: pytest.MonkeyPatch, +): + """A component in the initial state hands StyleX to neither npm nor the browser. + + Args: + monkeypatch: The pytest fixture that undoes the change. + """ + component = _soft_button() + monkeypatch.setattr( + compiler_utils, "compile_state", lambda state: {"state": {"held": component}} + ) + libraries = RegistrationContext.ensure_context().bundled_libraries + before = list(libraries) + component_imports: dict[str, Any] = {} + try: + _, initial_state = compiler_utils._compile_initial_state( + rx.State, component_imports=component_imports + ) + assert component_imports == {} + assert libraries == before + finally: + libraries[:] = before + assert initial_state == json.dumps({"state": {"held": DYNAMIC_MODULE}}) + + @pytest.mark.parametrize( ("create", "message"), [ From 325320523b86e14fc1810f3aa90aa15662cb8072 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:27:18 +0000 Subject: [PATCH 044/204] Add rx.ui.button and rx.ui.spinner, and keep the styles of a pseudo-element under a later style Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/ui_parity/components/button.py | 175 ++++++ .../src/reflex_components_ui/__init__.py | 2 + .../src/reflex_components_ui/base.py | 9 + .../reflex_components_ui/components/button.py | 152 +++++ .../components/spinner.py | 109 ++++ .../src/reflex_components_ui/style/emit.py | 2 +- .../src/reflex_components_ui/style/lower.py | 19 +- .../reflex_components_ui/styles/appearance.py | 25 + .../src/reflex_components_ui/styles/button.py | 518 ++++++++++++++++++ .../reflex_components_ui/styles/spinner.py | 95 ++++ .../reflex_components_ui/test_api_parity.py | 4 +- 11 files changed, 1106 insertions(+), 4 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/button.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/button.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/spinner.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/appearance.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/button.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/spinner.py diff --git a/packages/reflex-components-ui/parity/ui_parity/components/button.py b/packages/reflex-components-ui/parity/ui_parity/components/button.py new file mode 100644 index 00000000000..cb3624d2173 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/button.py @@ -0,0 +1,175 @@ +"""The button: every variant, size and state, and what the keyboard does.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS + +VARIANTS = ["classic", "solid", "soft", "surface", "outline", "ghost"] +SIZES = ["1", "2", "3", "4"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] + + +def _button(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a button, with what a cell says it holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` names the children when they + are not words alone. + + Returns: + The button. + """ + props = dict(props) + holds = props.pop("holds", None) + if holds == "icon": + return namespace.button(rx.icon("plus"), "Add", **props) + if holds == "link": + return namespace.button(rx.el.a("Docs", href="#docs"), as_child=True, **props) + return namespace.button("Save", **props) + + +MATRIX = Matrix( + component="button", + render=_button, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "color_scheme": ACCENTS, + "radius": ["none", "small", "medium", "large", "full"], + "high_contrast": [True], + "disabled": [True], + "loading": [True, False], + "holds": ["icon", "link"], + "size": {"responsive": rx.breakpoints(initial="1", sm="4", lg="2")}, + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + {"variant": VARIANTS, "state": STATES, "appearance": [LIGHT, DARK]}, + { + "variant": VARIANTS, + "high_contrast": [True], + "state": STATES, + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "disabled": [True], + "state": ["rest", HOVER], + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "disabled": [True], "high_contrast": [True]}, + {"variant": VARIANTS, "loading": [True], "appearance": [LIGHT, DARK]}, + {"variant": ["solid", "ghost"], "loading": [True], "size": SIZES}, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + {"variant": ["solid", "soft"], "radius": ["none", "full"], "size": SIZES}, + {"variant": VARIANTS, "holds": ["icon"]}, + {"variant": ["solid", "ghost"], "holds": ["link"], "state": STATES}, + {"holds": ["link"], "disabled": [True], "state": ["rest", HOVER]}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="4", lg="2")}, + "variant": ["solid", "ghost"], + "viewport": [520, 800, 1100, 1280], + }, + ], + stage=(200, 100), + parts={"icon": "svg"}, + # Not held to zero. At a threshold of zero 252 of the 290 cells are equal + # pixel for pixel, and the others differ by where they are on the page: + # the gradients of the classic variant are dithered, by one or two steps + # of a channel, and a few pixels on the rounded ring of the focus and on + # the turned leaves of the spinner are anti-aliased otherwise (at most 4 + # pixels of a cell). The same props in another frame are equal. + tolerance=0.002, +) + +CONTRACT = Contract( + component="button", + render=lambda namespace: namespace.box( + namespace.button( + "Save", + id="save", + on_click=rx.call_script("window.saved = (window.saved || 0) + 1"), + ), + namespace.button("Off", id="off", disabled=True), + namespace.button("Busy", id="busy", loading=True), + namespace.button("Last", id="last"), + ), +) + + +@CONTRACT.step("is a button with its text in the server render", on=SERVER) +def _server_render(run: Run) -> None: + save = run.server.element("save") + assert (save.tag, save.text) == ("button", "Save") + off = run.server.element("off") + assert "disabled" in off.attributes + assert off.attributes["data-disabled"] == "true" + busy = run.server.element("busy") + assert "disabled" in busy.attributes + assert busy.attributes["data-disabled"] == "true" + + +@CONTRACT.step( + "is a button that takes the focus with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + save = run.page.locator("#save") + assert save.is_visible() + run.page.keyboard.press("Tab") + assert run.page.evaluate("document.activeElement.id") == "save" + assert run.page.locator("#off").is_disabled() + + +@CONTRACT.step("has the role and the name of a button, loading or not", on=HYDRATED) +def _role(run: Run) -> None: + assert run.page.get_by_role("button", name="Save").get_attribute("id") == "save" + busy = run.page.get_by_role("button", name="Busy", include_hidden=True) + assert busy.get_attribute("id") == "busy" + assert run.page.get_by_role("button", disabled=True).count() == 2 + + +@CONTRACT.step("Tab skips the disabled and the loading button", on=HYDRATED) +def _tab(run: Run) -> None: + focused = [] + for _ in range(2): + run.page.keyboard.press("Tab") + focused.append(run.page.evaluate("document.activeElement.id")) + assert focused == ["save", "last"] + assert run.page.locator("#last").evaluate( + "element => element.matches(':focus-visible')" + ) + run.page.keyboard.press("Shift+Tab") + assert run.page.evaluate("document.activeElement.id") == "save" + + +@CONTRACT.step("Enter, Space and a click press the button", on=HYDRATED) +def _press(run: Run) -> None: + save = run.page.locator("#save") + save.focus() + run.page.keyboard.press("Enter") + run.page.wait_for_function("window.saved === 1") + run.page.keyboard.press("Space") + run.page.wait_for_function("window.saved === 2") + save.click() + run.page.wait_for_function("window.saved === 3") + assert run.page.evaluate("document.activeElement.id") == "save" + + +@CONTRACT.step("a disabled button is not pressed", on=HYDRATED) +def _disabled(run: Run) -> None: + run.page.locator("#off").click(force=True) + run.page.locator("#busy").click(force=True) + run.page.locator("#save").click() + run.page.wait_for_function("window.saved === 1") 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 5efaffea7f6..3175bd3a427 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -8,8 +8,10 @@ _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { "components.aspect_ratio": ["aspect_ratio"], + "components.button": ["button"], "components.inset": ["inset"], "components.separator": ["divider", "separator"], + "components.spinner": ["spinner"], "layout.box": ["box"], "layout.center": ["center"], "layout.container": ["container"], 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 b14597ff5c8..c8cb75b0d48 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -22,6 +22,8 @@ from reflex_base.utils.imports import ImportDict, ImportVar, ParsedImportDict from reflex_base.vars.base import LiteralVar, Var, VarData from reflex_base.vars.sequence import LiteralStringVar +from reflex_components_core.base.fragment import Fragment +from reflex_components_core.core.cond import Cond from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import ( @@ -806,6 +808,10 @@ def _element_styles(self) -> Merged: return self._merged +# What renders no element of its own, between a component and its parts. +_NO_ELEMENT = (Fragment, Cond) + + def _bind_parts( children: Sequence[BaseComponent], parts: Mapping[str, Merged], name: str ) -> None: @@ -830,6 +836,9 @@ def _bind_parts( raise StyleError(msg) child._merged = merged _bind_parts(child.children, parts, name) + elif type(child) in _NO_ELEMENT: + # A part that is only rendered under a condition. + _bind_parts(child.children, parts, name) def add_styles(tag: CommonTag, emitted: Emitted) -> CommonTag: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/button.py b/packages/reflex-components-ui/src/reflex_components_ui/components/button.py new file mode 100644 index 00000000000..8d602e9d972 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/button.py @@ -0,0 +1,152 @@ +"""A button.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.components.tags import CommonTag +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.components.spinner import leaves, while_loading +from reflex_components_ui.props import LiteralVariant +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.button import BUTTON +from reflex_components_ui.themes import LiteralAccentColor, LiteralRadius + +LiteralButtonSize = Literal["1", "2", "3", "4"] + + +def _either(first: Var | None, second: Var | None) -> Var | None: + """Combine two flags, either of which may be left out. + + Args: + first: A flag. + second: Another one. + + Returns: + Whether one of them is set, or None when neither is given. + """ + if first is None or second is None: + return second if first is None else first + if isinstance(first, LiteralVar) and isinstance(second, LiteralVar): + return LiteralVar.create(bool(first._var_value or second._var_value)) + return Var( + f"({first!s} || {second!s})", + _var_type=bool, + _var_data=VarData.merge(first._get_all_var_data(), second._get_all_var_data()), + ) + + +class BaseButton(UIComponent, elements.Button): + """What a button and an icon button share.""" + + tag = "button" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + size: Var[Responsive[LiteralButtonSize]] = field(doc='Button size "1" - "4"') + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + high_contrast: Var[bool] = field( + doc="Whether to render the button with higher contrast color against background" + ) + + radius: Var[LiteralRadius] = field( + doc='Override theme radius for button: "none" | "small" | "medium" | "large" | "full"' + ) + + loading: Var[bool] = field( + doc="If set, show an rx.spinner instead of the component children." + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a button, with a spinner over its children while it loads. + + Args: + *children: The children of the button. + **props: The props of the button. + + Returns: + The button. + """ + loading = props.get("loading") + if loading is not None and not props.get("as_child"): + # As Radix Themes renders it: the children keep their place + # without being shown, and are still read out. + children = while_loading( + loading, + [ + Part.create( + *children, + part="content", + tag="span", + custom_attrs={"aria-hidden": True}, + ), + Part.create(*children, part="label", tag="span"), + Part.create( + Part.create(*leaves(), part="spinner", tag="span"), + part="overlay", + tag="span", + ), + ], + children, + ) + return super().create(*children, **props) + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the one that shows the spinner. + """ + return [*super()._exclude_props(), "loading"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the button, disabled while it loads. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a disabled button says so in ``data-disabled`` too, + which is what its styles select on, so that an element rendered + in its place with ``as_child`` looks disabled as well. + """ + tag = super()._render(props) + disabled = _either(self.disabled, self.loading) + if disabled is None: + return tag + if isinstance(disabled, LiteralVar): + if not disabled._var_value: + return tag + return tag.add_props(disabled=True, **{"data-disabled": True}) + return tag.add_props( + disabled=disabled, + **{ + "data-disabled": Var( + f"({disabled!s} || undefined)", + _var_data=disabled._get_all_var_data(), + ) + }, + ) + + +class Button(BaseButton): + """Trigger an action or event, such as submitting a form or displaying a dialog.""" + + styles: ClassVar[ComponentStyles] = BUTTON + + variant: Var[LiteralVariant] = field( + doc='Variant of button: "solid" | "soft" | "outline" | "ghost"' + ) + + +button = Button.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/spinner.py b/packages/reflex-components-ui/src/reflex_components_ui/components/spinner.py new file mode 100644 index 00000000000..f13efca75d8 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/spinner.py @@ -0,0 +1,109 @@ +"""A spinner: an animated sign that something is loading.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_core.base.fragment import Fragment +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.cond import cond + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.spinner import SPINNER, SPINNER_WRAPPER + +LiteralSpinnerSize = Literal["1", "2", "3"] + +# How many leaves a spinner has. +LEAVES = 8 + + +def leaves() -> list[Component]: + """Create the leaves of a spinner, for the component whose part they are. + + Returns: + The leaves. + """ + return [Part.create(part="leaf", tag="span") for _ in range(LEAVES)] + + +def while_loading(loading: Any, shown: list[Any], otherwise: tuple[Any, ...]) -> Any: + """Choose what a component shows by whether it is loading. + + Args: + loading: The ``loading`` prop: a bool, or a Var holding one. + shown: What is shown while loading. + otherwise: What is shown the rest of the time. + + Returns: + The children of the component. + """ + if isinstance(loading, LiteralVar): + loading = loading._var_value + if isinstance(loading, Var): + return [cond(loading, Fragment.create(*shown), Fragment.create(*otherwise))] + return shown if loading else list(otherwise) + + +class SpinnerWrapper(UIComponent): + """What a spinner with children renders: the spinner over their place.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = SPINNER_WRAPPER + + +class Spinner(UIComponent): + """A spinner component.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = SPINNER + + loading: Var[bool] = field( + doc="If set, show an rx.spinner instead of the component children." + ) + + size: Var[Responsive[LiteralSpinnerSize]] = field(doc="The size of the spinner.") + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the one that chooses what is shown. + """ + return [*super()._exclude_props(), "loading"] + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a spinner, around the children it stands in for if any. + + Args: + *children: What the spinner is shown in place of while loading. + **props: The props of the spinner. + + Returns: + The spinner, the children once they are no longer loading, or + the element that shows the spinner over the place of the children. + """ + loading = props.get("loading", True) + spinner = super().create(*leaves(), **props) + if children: + shown: Any = SpinnerWrapper.create( + Part.create( + *children, + part="content", + tag="span", + custom_attrs={"aria-hidden": True}, + ), + Part.create(spinner, part="overlay", tag="span"), + ) + else: + shown = spinner + (result,) = while_loading(loading, [shown], (Fragment.create(*children),)) + return result + + +spinner = Spinner.create 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 60efa9b75cd..88ab45a5aa5 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 @@ -394,7 +394,7 @@ def reference(value: Any) -> str: f"{key}: {json.dumps(style, ensure_ascii=False, default=reference)}" for key, style in styles.items() ]) - for position, frames in enumerate(animations): + for position in range(len(animations)): # StyleX compiles a reference to keyframes of the same module. entries = entries.replace( f'"\\u0001{position}\\u0001"', f"{_NAME}_k{position}" 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 054fa6a2d3f..b5f7c4628b5 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 @@ -1260,7 +1260,9 @@ def apply_layer(target: dict[str, LoweredValue], layer: Layer) -> None: 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. + does, keeps the earlier value everywhere else. A pseudo-element is another + box: what the earlier style gives it stays, unless the later one sets the + property for that pseudo-element too. Args: target: The properties merged so far. @@ -1270,9 +1272,22 @@ def apply_layer(target: dict[str, LoweredValue], layer: Layer) -> None: for prop in replaced: target.pop(prop, None) for prop, value in props.items(): + old = target.get(prop) 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) + elif old.__class__ is dict: + kept = { + condition: item + for condition, item in old.items() + if condition[:2] == "::" + and (value.__class__ is not dict or condition not in value) + } + if not kept: + target[prop] = value + elif value.__class__ is dict: + target[prop] = {**value, **kept} + else: + target[prop] = {"default": value, **kept} else: target[prop] = value diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/appearance.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/appearance.py new file mode 100644 index 00000000000..cea5cc1dd6d --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/appearance.py @@ -0,0 +1,25 @@ +"""Values that differ between the light and the dark appearance.""" + +from __future__ import annotations + +# Set by the base stylesheet wherever an appearance is: the one of the +# current appearance is invalid, the other one is empty. +IF_LIGHT = "--rx-if-light" +IF_DARK = "--rx-if-dark" + + +def by_appearance(light: str, dark: str) -> str: + """Write a value that is not a color for both appearances. + + ``light-dark()`` only chooses between colors. This chooses between any + two values, such as filters or the layers of a shadow, and the computed + value is the one of the appearance alone. + + Args: + light: The value in the light appearance. + dark: The value in the dark appearance. + + Returns: + The value of a property, or a part of one. + """ + return f"var({IF_LIGHT}, {light}) var({IF_DARK}, {dark})" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py new file mode 100644 index 00000000000..a70e349016d --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py @@ -0,0 +1,518 @@ +"""The look of a button, which an icon button shares.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked +from reflex_components_ui.styles.appearance import by_appearance +from reflex_components_ui.styles.spinner import ( + CENTERED, + HIDDEN_CONTENT, + LEAF, + OPACITY, + SPINNER_BASE, + SPINNER_SIZE, +) +from reflex_components_ui.styles.typography import ACCENT_SCOPE + +accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black + +# What a button tells the icons inside it, which the base stylesheet reads: +# Radix Themes dims every `svg` below a button that is not a ghost. +ICON_OPACITY = "--rx-icon-opacity" + +# What the solid code inside a hovered link is filtered by, when it is high +# contrast: the filter of a high-contrast solid button under the pointer. +SOLID_HIGH_CONTRAST_HOVER_FILTER = by_appearance( + "contrast(0.88) saturate(1.1) brightness(1.1)", + "contrast(0.88) saturate(1.3) brightness(1.18)", +) + +_HEIGHT = "--base-button-height" +_PRESSED_PADDING = "--base-button-classic-active-padding-top" + +# The states. Under the pointer only where there is one, and not while +# pressed: StyleX places a rule inside a media query after the others, and a +# pressed button is not the one under the pointer. A disabled button is +# selected by attribute, which wins over every pseudo-class. +_POINTER = "@media (hover: hover)" +_HOVER = ":hover:not(:active)" +_ACTIVE = ":active:not([data-state='open'])" +_DISABLED = "[data-disabled]" +_FOCUS = ":focus-visible" +_TOUCH = "@media (pointer: coarse)" + + +def _hover(style: dict[str, Any]) -> dict[str, Any]: + """Make the styles of a button under the pointer. + + Args: + style: The styles. + + Returns: + The styles, where a pointer can hover and the button is not pressed. + """ + return {_POINTER: {_HOVER: style}} + + +def _ring(color: str, offset: str) -> dict[str, Any]: + """Make the ring of the keyboard's focus. + + Args: + color: The color of the ring. + offset: How far from the edge of the button it is. + + Returns: + The outline. + """ + return { + "outline_width": "2px", + "outline_style": "solid", + "outline_color": color, + "outline_offset": offset, + } + + +# Instead of the highlight of a tap, which is turned off. +_TAP: dict[str, Any] = { + _TOUCH: { + f"{_ACTIVE[:-1]}, {_DISABLED}, {_FOCUS})": { + "outline_width": "0.5em", + "outline_style": "solid", + "outline_color": accent.a[4], + "outline_offset": "0", + } + } +} + +_DISABLED_FILL: dict[str, Any] = {"color": gray.a[8], "background_color": gray.a[3]} + +_CLASSIC_TOP = by_appearance( + f"inset 0 0 0 1px {gray.a[4]}, inset 0 -2px 1px {gray.a[3]}", + f"inset 0 0 0 1px {white.a[2]}, inset 0 4px 2px -2px {white.a[3]}, " + f"inset 0 1px 1px {white.a[6]}, inset 0 -1px 1px {black.a[6]}", +) +_CLASSIC_BOTTOM = by_appearance( + f"inset 0 4px 2px -2px {white.a[9]}, inset 0 2px 1px -1px {white.a[9]}", + "0 0 transparent", +) +_CLASSIC_DISABLED_SHADOW = by_appearance( + f"inset 0 0 0 1px {gray.a[4]}, inset 0 -2px 1px {gray.a[3]}, " + f"inset 0 4px 2px -2px {white.a[9]}, inset 0 2px 1px -1px {white.a[9]}", + f"inset 0 0 0 1px {gray.a[5]}, inset 0 4px 2px -2px {gray.a[2]}, " + f"inset 0 1px 1px {gray.a[5]}, inset 0 -1px 1px {black.a[3]}, " + f"inset 0 0 0 1px {gray.a[2]}", +) +_CLASSIC_ACTIVE = f":active:not([data-state='open'], {_DISABLED})" + + +def _classic(color: str) -> dict[str, Any]: + """Make the fill of a classic button. + + Args: + color: The color of the button. + + Returns: + The background and the shadows that make it look raised. + """ + return { + "background_color": color, + "background_image": ( + f"linear-gradient(to bottom, transparent 50%, {gray.a[4]}), " + f"linear-gradient(to bottom, transparent 50%, {color} 80%)" + ), + "box_shadow": f"{_CLASSIC_TOP}, inset 0 0 0 1px {color}, {_CLASSIC_BOTTOM}", + } + + +_VARIANTS: dict[str, Any] = { + "classic": { + **_classic(accent[9]), + "color": accent.contrast, + "position": "relative", + "z_index": 0, + # The pseudo-element is the outermost block, with its states inside: + # a style merged over this one keeps what it does not set for it. + "_after": { + "content": "''", + "box_sizing": "border-box", + "position": "absolute", + "border_radius": "inherit", + "pointer_events": "none", + "inset": "0", + "z_index": -1, + "border_width": by_appearance("2px", "1px"), + "border_style": "solid", + "border_color": "transparent", + "background_clip": "content-box", + "background_color": "inherit", + "background_image": ( + f"linear-gradient({black.a[1]}, transparent, {white.a[2]})" + ), + "box_shadow": f"inset 0 2px 3px -1px {white.a[4]}", + **_hover({ + "background_color": accent[10], + "background_image": ( + f"linear-gradient({black.a[2]} -15%, transparent, {white.a[3]})" + ), + }), + _CLASSIC_ACTIVE: { + "box_shadow": "none", + "background_color": "inherit", + "background_image": ( + f"linear-gradient({black.a[2]}, transparent, {white.a[3]})" + ), + }, + _DISABLED: { + "box_shadow": "none", + "background_color": gray.a[2], + "background_image": ( + f"linear-gradient({black.a[1]} -20%, transparent, {white.a[1]})" + ), + }, + }, + **_TAP, + f"{_FOCUS}:not({_DISABLED})": _ring(tokens.focus[8], "2px"), + _CLASSIC_ACTIVE: { + "background_color": accent[9], + "background_image": f"linear-gradient({black.a[1]}, transparent)", + "padding_top": f"var({_PRESSED_PADDING})", + "box_shadow": ( + f"inset 0 4px 2px -2px {gray.a[4]}, inset 0 1px 1px {gray.a[7]}, " + f"inset 0 0 0 1px {gray.a[5]}, inset 0 0 0 1px {accent[9]}, " + f"inset 0 3px 2px {gray.a[3]}, inset 0 0 0 1px {white.a[7]}, " + f"inset 0 -2px 1px {white.a[5]}" + ), + }, + _DISABLED: { + "color": gray.a[8], + "background_color": gray[2], + "background_image": "none", + "box_shadow": _CLASSIC_DISABLED_SHADOW, + "filter": "none", + }, + }, + "solid": { + "background_color": accent[9], + "color": accent.contrast, + **_hover({"background_color": accent[10]}), + _ACTIVE: { + "background_color": accent[10], + "filter": by_appearance( + "brightness(0.92) saturate(1.1)", "brightness(1.08)" + ), + }, + **_TAP, + f"{_FOCUS}:not({_DISABLED})": _ring(tokens.focus[8], "2px"), + _DISABLED: {**_DISABLED_FILL, "filter": "none"}, + }, + "soft": { + "color": accent.a[11], + "background_color": accent.a[3], + _FOCUS: _ring(accent[8], "-1px"), + **_hover({"background_color": accent.a[4]}), + _ACTIVE: {"background_color": accent.a[5]}, + _DISABLED: _DISABLED_FILL, + }, + "ghost": { + "color": accent.a[11], + **_hover({"background_color": accent.a[3]}), + _FOCUS: _ring(tokens.focus[8], "-1px"), + _ACTIVE: {"background_color": accent.a[4]}, + _DISABLED: {"color": gray.a[8], "background_color": "transparent"}, + "box_sizing": "content-box", + # Not stretched by a flex or grid container. + "height": "fit-content", + }, + "outline": { + "box_shadow": f"inset 0 0 0 1px {accent.a[8]}", + "color": accent.a[11], + **_hover({"background_color": accent.a[2]}), + _ACTIVE: {"background_color": accent.a[3]}, + _FOCUS: _ring(tokens.focus[8], "-1px"), + _DISABLED: { + "color": gray.a[8], + "box_shadow": f"inset 0 0 0 1px {gray.a[7]}", + "background_color": "transparent", + }, + }, + "surface": { + "background_color": accent.surface, + "box_shadow": f"inset 0 0 0 1px {accent.a[7]}", + "color": accent.a[11], + **_hover({"box_shadow": f"inset 0 0 0 1px {accent.a[8]}"}), + _ACTIVE: { + "background_color": accent.a[3], + "box_shadow": f"inset 0 0 0 1px {accent.a[8]}", + }, + _FOCUS: _ring(tokens.focus[8], "-1px"), + _DISABLED: { + "color": gray.a[8], + "box_shadow": f"inset 0 0 0 1px {gray.a[6]}", + "background_color": gray.a[2], + }, + }, +} + +_HIGH_CONTRAST: dict[str, Any] = { + "classic": { + **_classic(accent[12]), + "color": gray[1], + "_after": { + "background_image": ( + f"linear-gradient({black.a[3]}, transparent, {white.a[2]})" + ), + **_hover({ + "background_color": accent[12], + "background_image": ( + f"linear-gradient({black.a[5]}, transparent, {white.a[2]})" + ), + }), + _CLASSIC_ACTIVE: { + "background_image": ( + f"linear-gradient({black.a[5]}, transparent, {white.a[3]})" + ), + }, + }, + **_hover({ + "filter": by_appearance( + "contrast(0.88) saturate(1.1) brightness(1.1)", + "contrast(0.88) saturate(1.3) brightness(1.14)", + ), + }), + _CLASSIC_ACTIVE: { + "background_color": accent[12], + "filter": by_appearance( + "contrast(0.82) saturate(1.2) brightness(1.16)", + "brightness(0.95) saturate(1.2)", + ), + # Radix Themes names two custom properties here that nothing + # defines, which leaves the pressed button without a shadow. + "box_shadow": "none", + }, + }, + "solid": { + "background_color": accent[12], + "color": gray[1], + **_hover({ + "background_color": accent[12], + "filter": SOLID_HIGH_CONTRAST_HOVER_FILTER, + }), + _ACTIVE: { + "background_color": accent[12], + "filter": by_appearance( + "contrast(0.82) saturate(1.2) brightness(1.16)", + "brightness(0.95) saturate(1.2)", + ), + }, + }, + "soft": {"color": accent[12]}, + "ghost": {"color": accent[12]}, + "outline": { + "box_shadow": f"inset 0 0 0 1px {accent.a[7]}, inset 0 0 0 1px {gray.a[11]}", + "color": accent[12], + }, + "surface": {"color": accent[12]}, +} + + +def _over(under: dict[str, Any], top: dict[str, Any]) -> dict[str, Any]: + """Lay the rules of one selector over those of another, block by block. + + A compound style replaces the whole value of each property it sets, the + conditions of the variant included, so the style of a high-contrast + button is the one of its variant with the high-contrast rules written + into the same blocks. + + Args: + under: The styles of the variant. + top: The styles that high contrast changes. + + Returns: + The styles of the high-contrast variant. + """ + merged = dict(under) + for key, value in top.items(): + below = merged.get(key) + merged[key] = ( + _over(below, value) + if value.__class__ is dict and below.__class__ is dict + else value + ) + return merged + + +# The size of the spinner of a loading button, by the size of the button. +_SPINNER_SIZE = {"1": "1", "2": "2", "3": "2", "4": "3"} + +_PARTS: dict[str, ComponentStyles] = { + # The children of a loading button keep their place and are not shown. + "content": {"base": HIDDEN_CONTENT}, + # They are read out all the same. + "label": { + "base": { + "position": "absolute", + "border_width": "0", + "width": "1px", + "height": "1px", + "padding": "0", + "margin": "-1px", + "overflow": "hidden", + "clip": "rect(0, 0, 0, 0)", + "white_space": "nowrap", + "word_wrap": "normal", + } + }, + "overlay": {"base": CENTERED}, + "spinner": { + "base": SPINNER_BASE, + "variants": { + "size": { + size: SPINNER_SIZE[spinner] for size, spinner in _SPINNER_SIZE.items() + } + }, + "defaults": {"size": "2"}, + }, + "leaf": {"base": LEAF}, +} + +_RADIUS = {"1": 1, "2": 2, "3": 3, "4": 4} + +# What everything a button does not set is, as Radix Themes unsets it all: +# the look the browser gives a button, and what a reset of the page adds. +_RESET: dict[str, Any] = { + "margin": "0", + "padding": "0", + "border_width": "0", + "border_style": "none", + "background_color": "transparent", + "background_image": "none", + "appearance": "none", + "box_sizing": "border-box", + "font_size": "inherit", + "line_height": "inherit", + "letter_spacing": "inherit", + "font_weight": "normal", + "text_transform": "inherit", + "text_indent": "initial", + "text_shadow": "inherit", + "word_spacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": tokens.cursor.button, + ":any-link": tokens.cursor.link, + _DISABLED: tokens.cursor.disabled, + }, + "outline_style": "none", + "WebkitTapHighlightColor": "transparent", +} + + +def button_styles(icon: bool) -> ComponentStyles: + """Make the style table of a button. + + Args: + icon: Whether the button holds a single icon, and is as wide as it + is tall. + + Returns: + The table. + """ + sizes: dict[str, Any] = {} + compound: list[CompoundStyle] = [] + for size, step in _RADIUS.items(): + sizes[size] = { + _PRESSED_PADDING: "1px" if size == "1" else "2px", + _HEIGHT: tokens.space[step + 4], + "border_radius": f"max({tokens.radius[step]}, {tokens.radius.full})", + } + if icon: + ghost_padding = { + "1": tokens.space[1], + "2": f"calc({tokens.space[1]} * 1.5)", + "3": tokens.space[2], + "4": tokens.space[3], + } + ghost = { + size: {"padding": padding, "margin": f"calc(0px - {padding})"} + for size, padding in ghost_padding.items() + } + solid_size: dict[str, Any] = { + size: {"height": f"var({_HEIGHT})", "width": f"var({_HEIGHT})"} + for size in sizes + } + else: + for size, step in _RADIUS.items(): + sizes[size].update({ + "gap": tokens.space[min(step, 3)], + "font_size": tokens.font_size[step], + "line_height": tokens.line_height[step], + "letter_spacing": tokens.letter_spacing[step], + }) + ghost_paddings = { + "1": (tokens.space[1], tokens.space[2], tokens.space[1]), + "2": (tokens.space[1], tokens.space[2], tokens.space[1]), + "3": (f"calc({tokens.space[1]} * 1.5)", tokens.space[3], tokens.space[2]), + "4": (tokens.space[2], tokens.space[4], tokens.space[2]), + } + ghost = { + size: { + "gap": gap, + "padding": f"{y} {x}", + "margin": f"calc(0px - {y}) calc(0px - {x})", + } + for size, (y, x, gap) in ghost_paddings.items() + } + solid_size = { + size: { + "height": f"var({_HEIGHT})", + "padding_left": tokens.space[step + 1], + "padding_right": tokens.space[step + 1], + "font_weight": tokens.font_weight.medium, + ICON_OPACITY: "0.9", + } + for size, step in _RADIUS.items() + } + for variant in _VARIANTS: + by_size = ghost if variant == "ghost" else solid_size + compound.extend( + {"props": {"variant": variant, "size": size}, "style": unchecked(style)} + for size, style in by_size.items() + ) + for variant, style in _HIGH_CONTRAST.items(): + compound.append({ + "props": {"variant": variant, "high_contrast": "true"}, + "style": unchecked(_over(_VARIANTS[variant], style)), + }) + return { + "base": unchecked({ + **_RESET, + "display": "inline-flex", + "align_items": "center", + "justify_content": "center", + "flex_shrink": 0, + "user_select": "none", + "vertical_align": "top", + "font_family": tokens.default.font_family, + "font_style": "normal", + "text_align": "center", + _DISABLED: {OPACITY: "1"}, + }), + "variants": { + "size": {size: unchecked(style) for size, style in sizes.items()}, + "variant": { + variant: unchecked(style) for variant, style in _VARIANTS.items() + }, + "loading": {"true": {"position": "relative"}}, + "color_scheme": {"true": unchecked(ACCENT_SCOPE)}, + }, + "defaults": {"size": "2", "variant": "solid"}, + "compound": compound, + "parts": _PARTS, + } + + +BUTTON: ComponentStyles = button_styles(icon=False) +ICON_BUTTON: ComponentStyles = button_styles(icon=True) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/spinner.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/spinner.py new file mode 100644 index 00000000000..ac0807a60fb --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/spinner.py @@ -0,0 +1,95 @@ +"""The look of a spinner: eight leaves that fade in turn.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, StyleProps, keyframes, unchecked + +# How long a turn takes, and how see-through the spinner is: an app may set +# either, and a disabled button sets the second for the spinner inside it. +DURATION = "var(--spinner-animation-duration, 800ms)" +OPACITY = "--spinner-opacity" + +_FADE = keyframes({"from": {"opacity": 1}, "to": {"opacity": 0.25}}) + +SPINNER_BASE: StyleProps = unchecked({ + "display": "block", + "position": "relative", + "opacity": f"var({OPACITY}, 0.65)", +}) + +SPINNER_SIZE: dict[str, StyleProps] = { + "1": {"width": tokens.space[3], "height": tokens.space[3]}, + "2": {"width": tokens.space[4], "height": tokens.space[4]}, + "3": { + "width": f"calc(1.25 * {tokens.space[4]})", + "height": f"calc(1.25 * {tokens.space[4]})", + }, +} + +# The leaves are the same element eight times: each one is turned, and +# starts its fade, by its place. +_PLACES = range(1, 9) + +LEAF: Any = unchecked({ + "position": "absolute", + "top": "0", + "left": "calc(50% - 12.5% / 2)", + "width": "12.5%", + "height": "100%", + "animation_name": _FADE, + "animation_duration": DURATION, + "animation_timing_function": "linear", + "animation_iteration_count": "infinite", + "transform": { + f":nth-child({place})": f"rotate({(place - 1) * 45}deg)" for place in _PLACES + }, + "animation_delay": { + f":nth-child({place})": f"calc(-{9 - place} / 8 * {DURATION})" + for place in _PLACES + }, + "_before": { + "content": "''", + "display": "block", + "width": "100%", + "height": "30%", + "border_radius": tokens.radius[1], + "background_color": "currentColor", + }, +}) + +# Around the children a spinner stands in for: they keep their place and are +# not shown, and the spinner is centered over them. +HIDDEN_CONTENT: StyleProps = {"display": "contents", "visibility": "hidden"} +CENTERED: StyleProps = { + "box_sizing": "border-box", + "display": "flex", + "align_items": "center", + "justify_content": "center", + "position": "absolute", + "inset": "0", +} + +SPINNER: ComponentStyles = { + "base": SPINNER_BASE, + "variants": {"size": SPINNER_SIZE}, + "defaults": {"size": "2"}, + "parts": {"leaf": {"base": LEAF}}, +} + +# The element around the children a spinner stands in for. +SPINNER_WRAPPER: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "display": "flex", + "position": "relative", + "align_items": "center", + "justify_content": "center", + }, + "parts": { + "content": {"base": HIDDEN_CONTENT}, + "overlay": {"base": CENTERED}, + }, +} diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index db2f1101a12..26efa40b507 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -99,11 +99,12 @@ def differences(component: str) -> list[ApiDifference]: ) -def test_the_wave_of_layout_and_typography_is_in_the_namespace(): +def test_every_wave_is_in_the_namespace(): assert COMPONENTS == [ "aspect_ratio", "blockquote", "box", + "button", "center", "code", "container", @@ -123,6 +124,7 @@ def test_the_wave_of_layout_and_typography_is_in_the_namespace(): "section", "separator", "spacer", + "spinner", "stack", "text", "text.em", From 272a557159ac38c01bd381e704cdf0015d13be50 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:40:37 +0000 Subject: [PATCH 045/204] Add rx.ui.icon_button, and the matrices and contracts of the spinner and the icon button Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .claude/worktrees/agent-a7203ecf61e793df9 | 1 + .claude/worktrees/agent-a9215a1f258294f74 | 1 + .claude/worktrees/agent-aa1bdca7e4ce77dfb | 1 + .../ui_parity/components/icon_button.py | 122 +++++++++++++++++ .../parity/ui_parity/components/spinner.py | 123 ++++++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/icon_button.py | 78 +++++++++++ .../src/reflex_components_ui/styles/button.py | 30 ++++- .../reflex_components_ui/test_api_parity.py | 1 + 9 files changed, 352 insertions(+), 6 deletions(-) create mode 160000 .claude/worktrees/agent-a7203ecf61e793df9 create mode 160000 .claude/worktrees/agent-a9215a1f258294f74 create mode 160000 .claude/worktrees/agent-aa1bdca7e4ce77dfb create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/icon_button.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/spinner.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.py diff --git a/.claude/worktrees/agent-a7203ecf61e793df9 b/.claude/worktrees/agent-a7203ecf61e793df9 new file mode 160000 index 00000000000..325320523b8 --- /dev/null +++ b/.claude/worktrees/agent-a7203ecf61e793df9 @@ -0,0 +1 @@ +Subproject commit 325320523b86e14fc1810f3aa90aa15662cb8072 diff --git a/.claude/worktrees/agent-a9215a1f258294f74 b/.claude/worktrees/agent-a9215a1f258294f74 new file mode 160000 index 00000000000..eea8298204b --- /dev/null +++ b/.claude/worktrees/agent-a9215a1f258294f74 @@ -0,0 +1 @@ +Subproject commit eea8298204be749dcfa6b80a79e1d5ebf12255d9 diff --git a/.claude/worktrees/agent-aa1bdca7e4ce77dfb b/.claude/worktrees/agent-aa1bdca7e4ce77dfb new file mode 160000 index 00000000000..325320523b8 --- /dev/null +++ b/.claude/worktrees/agent-aa1bdca7e4ce77dfb @@ -0,0 +1 @@ +Subproject commit 325320523b86e14fc1810f3aa90aa15662cb8072 diff --git a/packages/reflex-components-ui/parity/ui_parity/components/icon_button.py b/packages/reflex-components-ui/parity/ui_parity/components/icon_button.py new file mode 100644 index 00000000000..82389c62317 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/icon_button.py @@ -0,0 +1,122 @@ +"""The icon button: a square button around one icon.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS + +VARIANTS = ["classic", "solid", "soft", "surface", "outline", "ghost"] +SIZES = ["1", "2", "3", "4"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +RESPONSIVE = rx.breakpoints(initial="1", sm="4", lg="2") + + +def _icon_button(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create an icon button around a plus, named or passed as an icon. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` says whether the icon is + created by the caller. + + Returns: + The icon button. + """ + props = dict(props) + if props.pop("holds", None) == "icon": + return namespace.icon_button(rx.icon("plus", size=18), **props) + return namespace.icon_button("plus", **props) + + +MATRIX = Matrix( + component="icon_button", + render=_icon_button, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "color_scheme": ACCENTS, + "radius": ["none", "small", "medium", "large", "full"], + "high_contrast": [True], + "disabled": [True], + "loading": [True, False], + "holds": ["icon"], + "size": {"responsive": RESPONSIVE}, + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + {"variant": VARIANTS, "state": STATES, "appearance": [LIGHT, DARK]}, + {"variant": VARIANTS, "high_contrast": [True], "appearance": [LIGHT, DARK]}, + {"variant": VARIANTS, "disabled": [True], "appearance": [LIGHT, DARK]}, + {"variant": ["solid", "ghost"], "loading": [True], "size": SIZES}, + {"variant": ["solid", "soft"], "radius": ["none", "full"], "size": SIZES}, + { + "size": {"responsive": RESPONSIVE}, + "variant": ["solid", "ghost"], + "viewport": [520, 800, 1100, 1280], + }, + ], + stage=(140, 100), + parts={"icon": "svg"}, + # Not held to zero, for what the button is not: the gradients of the + # classic variant are dithered by where they are on the page, and the + # rounded ring of the focus is anti-aliased by it. + tolerance=0.002, +) + +CONTRACT = Contract( + component="icon_button", + render=lambda namespace: namespace.box( + namespace.icon_button( + "plus", + id="add", + custom_attrs={"aria-label": "Add"}, + on_click=rx.call_script("window.added = (window.added || 0) + 1"), + ), + namespace.icon_button( + "trash", id="off", disabled=True, custom_attrs={"aria-label": "Remove"} + ), + ), +) + + +@CONTRACT.step("is a button around an icon in the server render", on=SERVER) +def _server_render(run: Run) -> None: + add = run.server.element("add") + assert (add.tag, add.text, add.attributes["aria-label"]) == ("button", "", "Add") + off = run.server.element("off") + assert "disabled" in off.attributes + assert off.attributes["data-disabled"] == "true" + + +@CONTRACT.step( + "shows its icon and takes the focus with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#add svg").is_visible() + run.page.keyboard.press("Tab") + assert run.page.evaluate("document.activeElement.id") == "add" + + +@CONTRACT.step("has the role of a button and the name it is given", on=HYDRATED) +def _role(run: Run) -> None: + assert run.page.get_by_role("button", name="Add").get_attribute("id") == "add" + assert run.page.get_by_role("button", name="Remove").is_disabled() + + +@CONTRACT.step("Enter, Space and a click press the button", on=HYDRATED) +def _press(run: Run) -> None: + add = run.page.locator("#add") + run.page.keyboard.press("Tab") + assert add.evaluate("element => element.matches(':focus-visible')") + run.page.keyboard.press("Enter") + run.page.wait_for_function("window.added === 1") + run.page.keyboard.press("Space") + run.page.wait_for_function("window.added === 2") + add.click() + run.page.wait_for_function("window.added === 3") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/spinner.py b/packages/reflex-components-ui/parity/ui_parity/components/spinner.py new file mode 100644 index 00000000000..3ea4464c896 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/spinner.py @@ -0,0 +1,123 @@ +"""The spinner: its sizes, what it stands in for, and how it turns.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + +RESPONSIVE = rx.breakpoints(initial="1", sm="3", lg="2") + + +def _spinner(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a spinner, alone, over what it stands in for, or in colored text. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` names the children, and + ``inside`` what is around the spinner. + + Returns: + The spinner, or what is around it. + """ + props = dict(props) + holds = props.pop("holds", None) + inside = props.pop("inside", None) + children = ["Loading the report"] if holds == "words" else [] + if holds == "box": + children = [rx.el.div(style={"width": "80px", "height": "40px"})] + spinner = namespace.spinner(*children, **props) + if inside == "colored": + return rx.el.div(spinner, style={"color": "crimson"}) + return spinner + + +MATRIX = Matrix( + component="spinner", + render=_spinner, + cross={"size": ["1", "2", "3"], "holds": ["none", "words", "box"]}, + sweep={ + "size": {"responsive": RESPONSIVE}, + # Without children a spinner that is not loading renders nothing. + "loading": [True], + "inside": ["colored"], + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + # Around words alone, a spinner that is not loading is no element. + {"holds": ["box"], "loading": [True, False]}, + {"holds": ["none", "words"], "appearance": [DARK]}, + {"size": {"responsive": RESPONSIVE}, "viewport": [520, 800, 1100, 1280]}, + ], + stage=(200, 100), + # Not held to zero: the leaves are turned, and their edges are + # anti-aliased by where the spinner is on the page. + tolerance=0.002, +) + +CONTRACT = Contract( + component="spinner", + render=lambda namespace: namespace.box( + namespace.spinner(id="alone"), + namespace.spinner("Report", id="over", size="3"), + namespace.spinner("Ready", id="done", loading=False), + ), +) + + +@CONTRACT.step("is a span of eight leaves in the server render", on=SERVER) +def _server_render(run: Run) -> None: + alone = run.server.element("alone") + assert (alone.tag, alone.text) == ("span", "") + assert run.server.text.count("Report") == 1 + assert run.server.text.count("Ready") == 1 + + +@CONTRACT.step("shows its leaves with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + box = run.page.locator("#alone").bounding_box() + assert box is not None + assert (box["width"], box["height"]) == (16, 16) + assert run.page.locator("#alone > span").count() == 8 + assert run.page.get_by_text("Ready").is_visible() + + +@CONTRACT.step("hides what it stands in for, which keeps its place", on=HYDRATED) +def _stands_in(run: Run) -> None: + report = run.page.get_by_text("Report") + assert report.evaluate("element => getComputedStyle(element).visibility") == ( + "hidden" + ) + assert report.get_attribute("aria-hidden") == "true" + assert run.page.get_by_text("Ready").is_visible() + + +@CONTRACT.step("each leaf fades in turn, eight to a turn of 800ms", on=HYDRATED) +def _animation(run: Run) -> None: + leaves = run.page.evaluate( + """() => [...document.querySelectorAll("#alone > span")].map((leaf) => { + const [animation] = leaf.getAnimations(); + const timing = animation.effect.getTiming(); + return { + frames: animation.effect.getKeyframes().map( + (frame) => [frame.offset, frame.opacity, frame.easing]), + timing: [timing.duration, Math.round(timing.delay), timing.iterations, + timing.easing, timing.direction, timing.fill], + state: animation.playState, + transform: getComputedStyle(leaf).transform, + }; + })""" + ) + assert [leaf["frames"] for leaf in leaves] == [ + [[0, "1", "linear"], [1, "0.25", "linear"]] + ] * 8 + assert [leaf["timing"] for leaf in leaves] == [ + [800, -100 * (8 - place), float("inf"), "linear", "normal", "none"] + for place in range(8) + ] + assert [leaf["state"] for leaf in leaves] == ["running"] * 8 + assert len({leaf["transform"] for leaf in leaves}) == 8 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 3175bd3a427..e0b5ca8b092 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -9,6 +9,7 @@ _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { "components.aspect_ratio": ["aspect_ratio"], "components.button": ["button"], + "components.icon_button": ["icon_button"], "components.inset": ["inset"], "components.separator": ["divider", "separator"], "components.spinner": ["spinner"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.py b/packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.py new file mode 100644 index 00000000000..b825d3eae25 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.py @@ -0,0 +1,78 @@ +"""An icon button: a button that holds a single icon.""" + +from __future__ import annotations + +from typing import ClassVar + +from reflex_base.components.component import Component, field +from reflex_base.style import Style +from reflex_base.vars.base import Var +from reflex_components_core.core.match import Match +from reflex_components_lucide import Icon + +from reflex_components_ui.components.button import BaseButton +from reflex_components_ui.props import LiteralVariant +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.button import ICON_BUTTON + +RADIX_TO_LUCIDE_SIZE = {"1": 12, "2": 24, "3": 36, "4": 48} + + +class IconButton(BaseButton): + """A button designed specifically for usage with a single icon.""" + + styles: ClassVar[ComponentStyles] = ICON_BUTTON + + variant: Var[LiteralVariant] = field( + doc='Variant of button: "classic" | "solid" | "soft" | "surface" | "outline" | "ghost"' + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a IconButton component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The IconButton component. + + Raises: + ValueError: If no children are passed. + """ + if children: + if isinstance(children[0], str): + children = [ + Icon.create( + children[0], + ) + ] + else: + msg = "IconButton requires a child icon. Pass a string as the first child or a rx.icon." + raise ValueError(msg) + if "size" in props: + if isinstance(props["size"], str): + children[0].size = RADIX_TO_LUCIDE_SIZE[props["size"]] # pyright: ignore[reportAttributeAccessIssue] + else: + size_map_var = Match.create( + props["size"], + *list(RADIX_TO_LUCIDE_SIZE.items()), + 12, + ) + if not isinstance(size_map_var, Var): + msg = f"Match did not return a Var: {size_map_var}" + raise ValueError(msg) + children[0].size = size_map_var # pyright: ignore[reportAttributeAccessIssue] + return super().create(*children, **props) + + def add_style(self): + """Add style to the component. + + Returns: + The style of the component. + """ + return Style({"padding": "6px"}) + + +icon_button = IconButton.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py index a70e349016d..df17d531ea9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py @@ -410,6 +410,28 @@ def _over(under: dict[str, Any], top: dict[str, Any]) -> dict[str, Any]: } +def _ghost_box(y: str, x: str) -> dict[str, str]: + """Make the padding of a ghost button, and the margins that take it back. + + A ghost button sits where its content would without the padding. Each + side is written out: a size whose padding is a calculation would keep + the shorthand whole where the other sizes are split, and a size per + breakpoint would mix the two. + + Args: + y: The padding above and below. + x: The padding on each side. + + Returns: + The paddings and the margins. + """ + style = {} + for side, padding in (("top", y), ("right", x), ("bottom", y), ("left", x)): + style[f"padding_{side}"] = padding + style[f"margin_{side}"] = f"calc(0px - {padding})" + return style + + def button_styles(icon: bool) -> ComponentStyles: """Make the style table of a button. @@ -436,7 +458,7 @@ def button_styles(icon: bool) -> ComponentStyles: "4": tokens.space[3], } ghost = { - size: {"padding": padding, "margin": f"calc(0px - {padding})"} + size: _ghost_box(padding, padding) for size, padding in ghost_padding.items() } solid_size: dict[str, Any] = { @@ -458,11 +480,7 @@ def button_styles(icon: bool) -> ComponentStyles: "4": (tokens.space[2], tokens.space[4], tokens.space[2]), } ghost = { - size: { - "gap": gap, - "padding": f"{y} {x}", - "margin": f"calc(0px - {y}) calc(0px - {x})", - } + size: {"gap": gap, **_ghost_box(y, x)} for size, (y, x, gap) in ghost_paddings.items() } solid_size = { diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 26efa40b507..f28b360e89a 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -113,6 +113,7 @@ def test_every_wave_is_in_the_namespace(): "grid", "heading", "hstack", + "icon_button", "inset", "link", "list", From 0c836a0eff11bffa404c7b416826cf78723a5117 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:40:46 +0000 Subject: [PATCH 046/204] Remove the worktree pointers committed by mistake Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .claude/worktrees/agent-a7203ecf61e793df9 | 1 - .claude/worktrees/agent-a9215a1f258294f74 | 1 - .claude/worktrees/agent-aa1bdca7e4ce77dfb | 1 - 3 files changed, 3 deletions(-) delete mode 160000 .claude/worktrees/agent-a7203ecf61e793df9 delete mode 160000 .claude/worktrees/agent-a9215a1f258294f74 delete mode 160000 .claude/worktrees/agent-aa1bdca7e4ce77dfb diff --git a/.claude/worktrees/agent-a7203ecf61e793df9 b/.claude/worktrees/agent-a7203ecf61e793df9 deleted file mode 160000 index 325320523b8..00000000000 --- a/.claude/worktrees/agent-a7203ecf61e793df9 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 325320523b86e14fc1810f3aa90aa15662cb8072 diff --git a/.claude/worktrees/agent-a9215a1f258294f74 b/.claude/worktrees/agent-a9215a1f258294f74 deleted file mode 160000 index eea8298204b..00000000000 --- a/.claude/worktrees/agent-a9215a1f258294f74 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit eea8298204be749dcfa6b80a79e1d5ebf12255d9 diff --git a/.claude/worktrees/agent-aa1bdca7e4ce77dfb b/.claude/worktrees/agent-aa1bdca7e4ce77dfb deleted file mode 160000 index 325320523b8..00000000000 --- a/.claude/worktrees/agent-aa1bdca7e4ce77dfb +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 325320523b86e14fc1810f3aa90aa15662cb8072 From d02e18ec71d2169ffb46a4d06650bee3fd705642 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:44:01 +0000 Subject: [PATCH 047/204] Filter high-contrast solid code under the pointer inside a link, as Radix Themes does Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/ui_parity/components/code.py | 9 +++++++ .../src/reflex_components_ui/styles/code.py | 7 ++++++ .../src/reflex_components_ui/styles/link.py | 3 +++ .../reflex_components_ui/styles/typography.py | 2 ++ .../typography/test_code.py | 5 +++- .../typography/test_link.py | 24 +++++++++++++++---- 6 files changed, 45 insertions(+), 5 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/code.py b/packages/reflex-components-ui/parity/ui_parity/components/code.py index 3cfc15456c4..b5ee52cedb4 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/code.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/code.py @@ -76,6 +76,15 @@ def _code(namespace: Any, props: Mapping[str, Any]) -> Any: "inside": [None, "link"], "state": [HOVER], }, + # High-contrast solid code is filtered under the pointer inside a + # link, as a high-contrast solid button is. + { + "variant": ["solid"], + "high_contrast": [True], + "inside": [None, "link"], + "state": [HOVER], + "appearance": ["light", DARK], + }, { "size": {"responsive": rx.breakpoints(initial="1", sm="6", lg="3")}, "viewport": [520, 800, 1280], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py index 6e068c53269..5e23449d764 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/code.py @@ -8,6 +8,7 @@ ACCENT_SCOPE, ACCENT_SCOPE_HIGH_CONTRAST, ACCENT_TEXT, + LINK_CODE_FILTER, LINK_CODE_OUTLINE, LINK_CODE_SOFT, LINK_CODE_SOLID, @@ -130,6 +131,12 @@ def _hover(inside_link: str, otherwise: str) -> dict[str, Any]: "props": {"variant": "solid", "high_contrast": "true"}, "style": { "background_color": tokens.accent[12], + # Inside a link, the filter of a high-contrast solid button. + "filter": { + "@media (hover: hover)": { + ":hover": f"var({LINK_CODE_FILTER}, none)" + }, + }, "color": tokens.accent[1], "_selection": { "background_color": tokens.accent.a[11], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py index 7bb0fe004bf..aab07827b8e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/link.py @@ -4,12 +4,14 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.button import SOLID_HIGH_CONTRAST_HOVER_FILTER from reflex_components_ui.styles.text import TEXT_BASE from reflex_components_ui.styles.typography import ( ACCENT_LINK, ACCENT_LINK_LINE, ACCENT_LINK_LINE_COLOR, ACCENT_SCOPE, + LINK_CODE_FILTER, LINK_CODE_OUTLINE, LINK_CODE_SOFT, LINK_CODE_SOLID, @@ -86,6 +88,7 @@ def _line(rest: str, hover: str) -> dict[str, Any]: LINK_CODE_SOLID: tokens.accent[10], LINK_CODE_SOFT: tokens.accent.a[4], LINK_CODE_OUTLINE: tokens.accent.a[2], + LINK_CODE_FILTER: SOLID_HIGH_CONTRAST_HOVER_FILTER, }), "variants": { "size": SIZE, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py index 0eea1fa3b1a..24aa5b42b75 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/typography.py @@ -23,6 +23,8 @@ LINK_CODE_SOLID = "--rx-link-code-solid" LINK_CODE_SOFT = "--rx-link-code-soft" LINK_CODE_OUTLINE = "--rx-link-code-outline" +# And what solid code is filtered by there when it is high contrast. +LINK_CODE_FILTER = "--rx-link-code-filter" def underline_color(step: Step12) -> str: diff --git a/tests/units/reflex_components_ui/typography/test_code.py b/tests/units/reflex_components_ui/typography/test_code.py index a593feb24cb..8e3b54afdcc 100644 --- a/tests/units/reflex_components_ui/typography/test_code.py +++ b/tests/units/reflex_components_ui/typography/test_code.py @@ -123,7 +123,7 @@ def test_code_solid( ) assert component.render() == { "name": '"code"', - "props": ["className:sx_d6bd7d723a_c", '"data-variant":"solid"'], + "props": ["className:sx_16de2ef521_c", '"data-variant":"solid"'], "children": [{"contents": '"a"'}], } assert declared_styles(component) == [ @@ -149,6 +149,9 @@ def test_code_solid( "::selection": "var(--accent-a11)", }, "color": {"default": "var(--accent-1)", "::selection": "var(--accent-1)"}, + "filter": { + "@media (hover: hover)": {":hover": "var(--rx-link-code-filter, none)"} + }, } ] diff --git a/tests/units/reflex_components_ui/typography/test_link.py b/tests/units/reflex_components_ui/typography/test_link.py index 6ecb2fde4ec..cdbcd621bb2 100644 --- a/tests/units/reflex_components_ui/typography/test_link.py +++ b/tests/units/reflex_components_ui/typography/test_link.py @@ -15,7 +15,7 @@ def test_link_internal( component = rx.ui.link("a", href="/docs") assert component.render() == { "name": "ReactRouterLink", - "props": ["className:sx_10205cfca6_c", 'to:"/docs"'], + "props": ["className:sx_b8b1ea03e8_c", 'to:"/docs"'], "children": [{"contents": '"a"'}], } assert declared_styles(component) == [ @@ -75,6 +75,10 @@ def test_link_internal( "--rx-link-code-solid": "var(--accent-10)", "--rx-link-code-soft": "var(--accent-a4)", "--rx-link-code-outline": "var(--accent-a2)", + "--rx-link-code-filter": ( + "var(--rx-if-light, contrast(0.88) saturate(1.1) brightness(1.1)) " + "var(--rx-if-dark, contrast(0.88) saturate(1.3) brightness(1.18))" + ), "textDecorationLine": { "default": "var(--rx-accent-link-line, none)", ":focus-visible": "none", @@ -96,7 +100,7 @@ def test_link_no_href( ) assert component.render() == { "name": '"a"', - "props": ["className:sx_3534c54b5a_c", 'href:"#"'], + "props": ["className:sx_ee879616af_c", 'href:"#"'], "children": [{"contents": '"a"'}], } assert declared_styles(component) == [ @@ -166,6 +170,10 @@ def test_link_no_href( "--rx-link-code-solid": "var(--accent-10)", "--rx-link-code-soft": "var(--accent-a4)", "--rx-link-code-outline": "var(--accent-a2)", + "--rx-link-code-filter": ( + "var(--rx-if-light, contrast(0.88) saturate(1.1) brightness(1.1)) " + "var(--rx-if-dark, contrast(0.88) saturate(1.3) brightness(1.18))" + ), "fontSize": "var(--font-size-2)", "--line-height": "var(--line-height-2)", "--letter-spacing": "var(--letter-spacing-2)", @@ -201,7 +209,7 @@ def test_link_external( assert component.render() == { "name": "ReactRouterLink", "props": [ - 'className:sx_fb32bcfecb_c + " " + reflexUIClasses_e201574881', + 'className:sx_271b4725e7_c + " " + reflexUIClasses_e201574881', 'id:"home"', "ref:ref_home", "reloadDocument:true", @@ -263,6 +271,10 @@ def test_link_external( "--rx-link-code-solid": "var(--accent-10)", "--rx-link-code-soft": "var(--accent-a4)", "--rx-link-code-outline": "var(--accent-a2)", + "--rx-link-code-filter": ( + "var(--rx-if-light, contrast(0.88) saturate(1.1) brightness(1.1)) " + "var(--rx-if-dark, contrast(0.88) saturate(1.3) brightness(1.18))" + ), "textDecorationLine": { "default": "none", ":focus-visible": "none", @@ -289,7 +301,7 @@ def test_link_as_child( ) assert component.render() == { "name": '"button"', - "props": ["className:sx_27b53d9e29_c", 'href:"#"'], + "props": ["className:sx_8321e25311_c", 'href:"#"'], "children": [{"contents": '"a"'}], } assert declared_styles(component) == [ @@ -348,6 +360,10 @@ def test_link_as_child( "--rx-link-code-solid": "var(--accent-10)", "--rx-link-code-soft": "var(--accent-a4)", "--rx-link-code-outline": "var(--accent-a2)", + "--rx-link-code-filter": ( + "var(--rx-if-light, contrast(0.88) saturate(1.1) brightness(1.1)) " + "var(--rx-if-dark, contrast(0.88) saturate(1.3) brightness(1.18))" + ), "textDecorationLine": "none", } ] From 7f36d31ebef08de1436bd847c585d3e7634f623b Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:48:10 +0000 Subject: [PATCH 048/204] Test the button, the icon button, the spinner, keyframes, a radius of its own and the styles of a pseudo-element Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../components/test_button.py | 1103 +++++++++++++++++ .../components/test_icon_button.py | 284 +++++ .../components/test_spinner.py | 359 ++++++ .../reflex_components_ui/style/test_emit.py | 66 +- .../reflex_components_ui/style/test_lower.py | 94 ++ .../reflex_components_ui/style/test_merge.py | 39 + .../units/reflex_components_ui/test_themes.py | 52 + 7 files changed, 1996 insertions(+), 1 deletion(-) create mode 100644 tests/units/reflex_components_ui/components/test_button.py create mode 100644 tests/units/reflex_components_ui/components/test_icon_button.py create mode 100644 tests/units/reflex_components_ui/components/test_spinner.py diff --git a/tests/units/reflex_components_ui/components/test_button.py b/tests/units/reflex_components_ui/components/test_button.py new file mode 100644 index 00000000000..b2a9e2b4e7d --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_button.py @@ -0,0 +1,1103 @@ +"""Tests for reflex_components_ui.components.button.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.components.dynamic import _RENDERING_DYNAMIC_COMPONENT +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import Keyframes, StyleError +from reflex_components_ui.themes import ThemeError + +import reflex as rx + +# What each leaf of a spinner declares. +LEAF: dict[str, Any] = { + "position": "absolute", + "top": "0", + "left": "calc(50% - 12.5% / 2)", + "width": {"default": "12.5%", "::before": "100%"}, + "height": {"default": "100%", "::before": "30%"}, + "animationName": Keyframes('{"from": {"opacity": 1}, "to": {"opacity": 0.25}}', ()), + "animationDuration": "var(--spinner-animation-duration, 800ms)", + "animationTimingFunction": "linear", + "animationIterationCount": "infinite", + "transform": { + ":nth-child(1)": "rotate(0deg)", + ":nth-child(2)": "rotate(45deg)", + ":nth-child(3)": "rotate(90deg)", + ":nth-child(4)": "rotate(135deg)", + ":nth-child(5)": "rotate(180deg)", + ":nth-child(6)": "rotate(225deg)", + ":nth-child(7)": "rotate(270deg)", + ":nth-child(8)": "rotate(315deg)", + }, + "animationDelay": { + ":nth-child(1)": "calc(-8 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(2)": "calc(-7 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(3)": "calc(-6 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(4)": "calc(-5 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(5)": "calc(-4 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(6)": "calc(-3 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(7)": "calc(-2 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(8)": "calc(-1 / 8 * var(--spinner-animation-duration, 800ms))", + }, + "content": {"::before": "''"}, + "display": {"::before": "block"}, + "borderTopLeftRadius": {"::before": "var(--radius-1)"}, + "borderTopRightRadius": {"::before": "var(--radius-1)"}, + "borderBottomRightRadius": {"::before": "var(--radius-1)"}, + "borderBottomLeftRadius": {"::before": "var(--radius-1)"}, + "backgroundColor": {"::before": "currentColor"}, +} + + +class ButtonState(rx.State): + """What a button is bound to.""" + + busy: bool = False + off: bool = False + + +def test_button_plain( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A button is solid, of the second size, and a native button.""" + component = rx.ui.button("Save") + assert component.render() == { + "name": '"button"', + "props": ["className:sx_6fb0976665_c"], + "children": [{"contents": '"Save"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "var(--space-3)", + "paddingBottom": "0", + "paddingLeft": "var(--space-3)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--accent-9)", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + ":active:not([data-state='open'])": "var(--accent-10)", + "[data-disabled]": "var(--gray-a3)", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": "var(--font-size-2)", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "var(--letter-spacing-2)", + "fontWeight": "var(--font-weight-medium)", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + }, + ":focus-visible:not([data-disabled])": "solid", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-6)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "color": { + "default": "var(--accent-contrast)", + "[data-disabled]": "var(--gray-a8)", + }, + "filter": { + ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + "saturate(1.1)) var(--rx-if-dark, " + "brightness(1.08))", + "[data-disabled]": "none", + }, + "outlineWidth": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "outlineColor": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + }, + ":focus-visible:not([data-disabled])": "var(--focus-8)", + }, + "outlineOffset": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + } + ] + + +def test_button_soft_with_a_color_and_a_radius( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A color and a radius are themes on the element, beside its styles.""" + component = rx.ui.button( + "Save", + variant="soft", + size="1", + color_scheme="ruby", + radius="full", + high_contrast=True, + ) + assert component.render() == { + "name": '"button"', + "props": [ + ( + 'className:sx_2d7416ba7b_c + " " + reflexUIClasses_e201574881 + " " + ' + "reflexUIClasses_4c7cd6a7ce" + ) + ], + "children": [{"contents": '"Save"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "var(--space-2)", + "paddingBottom": "0", + "paddingLeft": "var(--space-2)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--accent-a3)", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a4)"}, + ":active:not([data-state='open'])": "var(--accent-a5)", + "[data-disabled]": "var(--gray-a3)", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": "var(--font-size-1)", + "lineHeight": "var(--line-height-1)", + "letterSpacing": "var(--letter-spacing-1)", + "fontWeight": "var(--font-weight-medium)", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "1px", + "--base-button-height": "var(--space-5)", + "borderRadius": "max(var(--radius-1), var(--radius-full))", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + "color": { + "default": "var(--accent-12)", + "[data-disabled]": "var(--gray-a8)", + }, + "outlineWidth": {":focus-visible": "2px"}, + "outlineColor": {":focus-visible": "var(--accent-8)"}, + "outlineOffset": {":focus-visible": "-1px"}, + "--rx-accent-text": "var(--accent-12)", + "--rx-accent-link": "var(--accent-12)", + "--rx-accent-link-line": "underline", + "--rx-accent-link-line-color": "color-mix(in oklab, var(--accent-a6), " + "var(--gray-a6))", + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + } + ] + + +def test_button_ghost( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A ghost button takes back with margins the padding it adds.""" + component = rx.ui.button("Save", variant="ghost", size="3") + assert component.render() == { + "name": '"button"', + "props": ["className:sx_2251570250_c"], + "children": [{"contents": '"Save"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "calc(0px - calc(var(--space-1) * 1.5))", + "marginRight": "calc(0px - var(--space-3))", + "marginBottom": "calc(0px - calc(var(--space-1) * 1.5))", + "marginLeft": "calc(0px - var(--space-3))", + "paddingTop": "calc(var(--space-1) * 1.5)", + "paddingRight": "var(--space-3)", + "paddingBottom": "calc(var(--space-1) * 1.5)", + "paddingLeft": "var(--space-3)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a3)"}, + ":active:not([data-state='open'])": "var(--accent-a4)", + "[data-disabled]": "transparent", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "content-box", + "fontSize": "var(--font-size-3)", + "lineHeight": "var(--line-height-3)", + "letterSpacing": "var(--letter-spacing-3)", + "fontWeight": "normal", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-7)", + "borderRadius": "max(var(--radius-3), var(--radius-full))", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "color": { + "default": "var(--accent-a11)", + "[data-disabled]": "var(--gray-a8)", + }, + "outlineWidth": {":focus-visible": "2px"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-1px"}, + "height": "fit-content", + } + ] + + +def test_button_classic_high_contrast( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The classic variant is drawn by a pseudo-element, with its own states.""" + component = rx.ui.button("Save", variant="classic", high_contrast=True) + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": { + "default": "0", + ":active:not([data-state='open'], [data-disabled])": "var(--base-button-classic-active-padding-top)", + }, + "paddingRight": "var(--space-3)", + "paddingBottom": "0", + "paddingLeft": "var(--space-3)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": {"default": "none", "::after": "solid"}, + "borderRightStyle": {"default": "none", "::after": "solid"}, + "borderBottomStyle": {"default": "none", "::after": "solid"}, + "borderLeftStyle": {"default": "none", "::after": "solid"}, + "backgroundColor": { + "default": "var(--accent-12)", + "::after": { + "default": "inherit", + "@media (hover: hover)": { + ":hover:not(:active)": "var(--accent-12)" + }, + ":active:not([data-state='open'], [data-disabled])": "inherit", + "[data-disabled]": "var(--gray-a2)", + }, + ":active:not([data-state='open'], [data-disabled])": "var(--accent-12)", + "[data-disabled]": "var(--gray-2)", + }, + "backgroundImage": { + "default": "linear-gradient(to bottom, transparent 50%, " + "var(--gray-a4)), linear-gradient(to bottom, " + "transparent 50%, var(--accent-12) 80%)", + "::after": { + "default": "linear-gradient(var(--black-a3), " + "transparent, var(--white-a2))", + "@media (hover: hover)": { + ":hover:not(:active)": "linear-gradient(var(--black-a5), " + "transparent, " + "var(--white-a2))" + }, + ":active:not([data-state='open'], [data-disabled])": "linear-gradient(var(--black-a5), " + "transparent, " + "var(--white-a3))", + "[data-disabled]": "linear-gradient(var(--black-a1) " + "-20%, transparent, " + "var(--white-a1))", + }, + ":active:not([data-state='open'], [data-disabled])": "linear-gradient(var(--black-a1), " + "transparent)", + "[data-disabled]": "none", + }, + "appearance": "none", + "boxSizing": {"default": "border-box", "::after": "border-box"}, + "fontSize": "var(--font-size-2)", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "var(--letter-spacing-2)", + "fontWeight": "var(--font-weight-medium)", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + }, + ":focus-visible:not([data-disabled])": "solid", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-6)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "boxShadow": { + "default": "var(--rx-if-light, inset 0 0 0 1px var(--gray-a4), inset 0 " + "-2px 1px var(--gray-a3)) var(--rx-if-dark, inset 0 0 0 1px " + "var(--white-a2), inset 0 4px 2px -2px var(--white-a3), " + "inset 0 1px 1px var(--white-a6), inset 0 -1px 1px " + "var(--black-a6)), inset 0 0 0 1px var(--accent-12), " + "var(--rx-if-light, inset 0 4px 2px -2px var(--white-a9), " + "inset 0 2px 1px -1px var(--white-a9)) var(--rx-if-dark, 0 " + "0 transparent)", + "::after": { + "default": "inset 0 2px 3px -1px var(--white-a4)", + ":active:not([data-state='open'], [data-disabled])": "none", + "[data-disabled]": "none", + }, + ":active:not([data-state='open'], [data-disabled])": "none", + "[data-disabled]": "var(--rx-if-light, inset 0 0 0 1px var(--gray-a4), " + "inset 0 -2px 1px var(--gray-a3), inset 0 4px 2px " + "-2px var(--white-a9), inset 0 2px 1px -1px " + "var(--white-a9)) var(--rx-if-dark, inset 0 0 0 1px " + "var(--gray-a5), inset 0 4px 2px -2px " + "var(--gray-a2), inset 0 1px 1px var(--gray-a5), " + "inset 0 -1px 1px var(--black-a3), inset 0 0 0 1px " + "var(--gray-a2))", + }, + "color": {"default": "var(--gray-1)", "[data-disabled]": "var(--gray-a8)"}, + "position": {"default": "relative", "::after": "absolute"}, + "zIndex": {"default": 0, "::after": -1}, + "content": {"::after": "''"}, + "borderTopLeftRadius": {"::after": "inherit"}, + "borderTopRightRadius": {"::after": "inherit"}, + "borderBottomRightRadius": {"::after": "inherit"}, + "borderBottomLeftRadius": {"::after": "inherit"}, + "pointerEvents": {"::after": "none"}, + "top": {"::after": "0"}, + "right": {"::after": "0"}, + "bottom": {"::after": "0"}, + "left": {"::after": "0"}, + "borderWidth": { + "::after": "var(--rx-if-light, 2px) var(--rx-if-dark, 1px)" + }, + "borderTopColor": {"::after": "transparent"}, + "borderRightColor": {"::after": "transparent"}, + "borderBottomColor": {"::after": "transparent"}, + "borderLeftColor": {"::after": "transparent"}, + "backgroundClip": {"::after": "content-box"}, + "outlineWidth": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "outlineColor": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + }, + ":focus-visible:not([data-disabled])": "var(--focus-8)", + }, + "outlineOffset": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "filter": { + "[data-disabled]": "none", + ":active:not([data-state='open'], [data-disabled])": "var(--rx-if-light, " + "contrast(0.82) " + "saturate(1.2) " + "brightness(1.16)) " + "var(--rx-if-dark, " + "brightness(0.95) " + "saturate(1.2))", + "@media (hover: hover)": { + ":hover:not(:active)": "var(--rx-if-light, " + "contrast(0.88) " + "saturate(1.1) " + "brightness(1.1)) " + "var(--rx-if-dark, " + "contrast(0.88) " + "saturate(1.3) " + "brightness(1.14))" + }, + }, + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + } + ] + + +def test_button_responsive_size( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A size per breakpoint changes what the size sets, at the breakpoints of Radix Themes.""" + component = rx.ui.button( + "Save", variant="outline", size=rx.breakpoints(initial="1", md="3") + ) + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": { + "default": "var(--space-2)", + "@media (min-width: 1024px)": "var(--space-4)", + }, + "paddingBottom": "0", + "paddingLeft": { + "default": "var(--space-2)", + "@media (min-width: 1024px)": "var(--space-4)", + }, + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a2)"}, + ":active:not([data-state='open'])": "var(--accent-a3)", + "[data-disabled]": "transparent", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": { + "default": "var(--font-size-1)", + "@media (min-width: 1024px)": "var(--font-size-3)", + }, + "lineHeight": { + "default": "var(--line-height-1)", + "@media (min-width: 1024px)": "var(--line-height-3)", + }, + "letterSpacing": { + "default": "var(--letter-spacing-1)", + "@media (min-width: 1024px)": "var(--letter-spacing-3)", + }, + "fontWeight": "var(--font-weight-medium)", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": { + "default": "1px", + "@media (min-width: 1024px)": "2px", + }, + "--base-button-height": { + "default": "var(--space-5)", + "@media (min-width: 1024px)": "var(--space-7)", + }, + "borderRadius": { + "default": "max(var(--radius-1), var(--radius-full))", + "@media (min-width: 1024px)": "max(var(--radius-3), " + "var(--radius-full))", + }, + "rowGap": { + "default": "var(--space-1)", + "@media (min-width: 1024px)": "var(--space-3)", + }, + "columnGap": { + "default": "var(--space-1)", + "@media (min-width: 1024px)": "var(--space-3)", + }, + "boxShadow": { + "default": "inset 0 0 0 1px var(--accent-a8)", + "[data-disabled]": "inset 0 0 0 1px var(--gray-a7)", + }, + "color": { + "default": "var(--accent-a11)", + "[data-disabled]": "var(--gray-a8)", + }, + "outlineWidth": {":focus-visible": "2px"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-1px"}, + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + } + ] + + +def test_button_disabled( + ui_plugin: UIPlugin, +): + """A disabled button says so in data-disabled, which its styles select on.""" + component = rx.ui.button("Save", disabled=True, type="submit") + assert component.render() == { + "name": '"button"', + "props": [ + "className:sx_6fb0976665_c", + '"data-disabled":true', + "disabled:true", + 'type:"submit"', + ], + "children": [{"contents": '"Save"'}], + } + + +def test_button_loading( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A loading button is disabled, and shows a spinner over children that keep their place.""" + component = rx.ui.button("Save", loading=True, size="4") + assert component.render() == { + "name": '"button"', + "props": ["className:sx_e8602a468e_c", '"data-disabled":true', "disabled:true"], + "children": [ + { + "name": '"span"', + "props": ['"aria-hidden":true', "className:sx_33a975bab1_c"], + "children": [{"contents": '"Save"'}], + }, + { + "name": '"span"', + "props": ["className:sx_0daea2e46b_c"], + "children": [{"contents": '"Save"'}], + }, + { + "name": '"span"', + "props": ["className:sx_67bf81be86_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_12ba415941_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + ], + } + ], + }, + ], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "var(--space-5)", + "paddingBottom": "0", + "paddingLeft": "var(--space-5)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--accent-9)", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + ":active:not([data-state='open'])": "var(--accent-10)", + "[data-disabled]": "var(--gray-a3)", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": "var(--font-size-4)", + "lineHeight": "var(--line-height-4)", + "letterSpacing": "var(--letter-spacing-4)", + "fontWeight": "var(--font-weight-medium)", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + }, + ":focus-visible:not([data-disabled])": "solid", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-8)", + "borderRadius": "max(var(--radius-4), var(--radius-full))", + "rowGap": "var(--space-3)", + "columnGap": "var(--space-3)", + "color": { + "default": "var(--accent-contrast)", + "[data-disabled]": "var(--gray-a8)", + }, + "filter": { + ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + "saturate(1.1)) var(--rx-if-dark, " + "brightness(1.08))", + "[data-disabled]": "none", + }, + "outlineWidth": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "outlineColor": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + }, + ":focus-visible:not([data-disabled])": "var(--focus-8)", + }, + "outlineOffset": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "position": "relative", + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + }, + {"display": "contents", "visibility": "hidden"}, + { + "position": "absolute", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "width": "1px", + "height": "1px", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "marginTop": "-1px", + "marginRight": "-1px", + "marginBottom": "-1px", + "marginLeft": "-1px", + "overflowX": "hidden", + "overflowY": "hidden", + "clip": "rect(0, 0, 0, 0)", + "whiteSpace": "nowrap", + "wordWrap": "normal", + }, + { + "boxSizing": "border-box", + "display": "flex", + "alignItems": "center", + "justifyContent": "center", + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + }, + { + "display": "block", + "position": "relative", + "opacity": "var(--spinner-opacity, 0.65)", + "width": "calc(1.25 * var(--space-4))", + "height": "calc(1.25 * var(--space-4))", + }, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + ] + + +def test_button_bound_to_state( + ui_plugin: UIPlugin, +): + """Loading and disabled bound to state choose the children and the attributes in the browser.""" + component = rx.ui.button("Save", loading=ButtonState.busy, disabled=ButtonState.off) + assert component.render() == { + "name": '"button"', + "props": [ + ( + 'className:sx_aec9f4943f_c + " " + ' + "(sx_aec9f4943f_0[reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_] " + '?? "")' + ), + ( + '"data-disabled":((reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.off_rx_state_ ' + "|| " + "reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_) " + "|| undefined)" + ), + ( + "disabled:(reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.off_rx_state_ " + "|| " + "reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_)" + ), + ], + "children": [ + { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": "reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_", + "true_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"span"', + "props": [ + '"aria-hidden":true', + "className:sx_33a975bab1_c", + ], + "children": [{"contents": '"Save"'}], + }, + { + "name": '"span"', + "props": ["className:sx_0daea2e46b_c"], + "children": [{"contents": '"Save"'}], + }, + { + "name": '"span"', + "props": ["className:sx_67bf81be86_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_fe93a2d910_c"], + "children": [ + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + ], + } + ], + }, + ], + }, + "false_value": { + "name": "Fragment", + "props": [], + "children": [{"contents": '"Save"'}], + }, + } + ], + } + ], + } + + +def test_button_as_child( + ui_plugin: UIPlugin, +): + """With as_child the only child is the element, with the styles of the button.""" + component = rx.ui.button( + rx.el.a("Docs", href="/docs"), as_child=True, disabled=True + ) + assert component.render() == { + "name": "ReactRouterLink", + "props": [ + "className:sx_6fb0976665_c", + '"data-disabled":true', + "disabled:true", + 'to:"/docs"', + ], + "children": [{"contents": '"Docs"'}], + } + + +@pytest.mark.parametrize( + ("props", "error", "message"), + [ + ( + {"variant": "sold"}, + StyleError, + ( + 'rx.ui.button: unknown variant "sold". Did you mean "solid"? The values ' + 'are "classic", "solid", "soft", "surface", "outline", "ghost".' + ), + ), + ( + {"size": "5"}, + StyleError, + 'rx.ui.button: unknown size "5". The values are "1", "2", "3", "4".', + ), + ( + {"radius": "round"}, + ThemeError, + ( + 'rx.ui.button: unknown radius "round". The values are "none", "small", ' + '"medium", "large", "full".' + ), + ), + ( + {"color_scheme": "rubi"}, + ThemeError, + ( + 'rx.ui.button: unknown color_scheme "rubi". Did you mean "ruby"? 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_button_rejects_a_value_a_prop_does_not_take( + props: dict[str, str], error: type[Exception], message: str +): + """The error names the component, the prop and the values it takes.""" + with pytest.raises(error) as raised: + rx.ui.button("Save", **props) + assert str(raised.value) == message + + +def test_button_rendered_from_state_cannot_carry_a_radius(ui_plugin: UIPlugin): + """A theme on an element needs the build, as its styles do.""" + token = _RENDERING_DYNAMIC_COMPONENT.set(True) + try: + with pytest.raises(StyleError) as raised: + rx.ui.button("Save", radius="full").render() + finally: + _RENDERING_DYNAMIC_COMPONENT.reset(token) + assert str(raised.value) == ( + "rx.ui.button: radius 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/components/test_icon_button.py b/tests/units/reflex_components_ui/components/test_icon_button.py new file mode 100644 index 00000000000..2a61ba10efb --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_icon_button.py @@ -0,0 +1,284 @@ +"""Tests for reflex_components_ui.components.icon_button.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.components.component import Component +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_icon_button_from_a_name( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """The name of an icon is the icon, and the button is as wide as it is tall.""" + component = compiled(rx.ui.icon_button("plus")) + assert component.render() == { + "name": '"button"', + "props": ["className:sx_9b6dbd2f05_c"], + "children": [{"name": "LucidePlus", "props": [], "children": []}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "6px", + "paddingRight": "6px", + "paddingBottom": "6px", + "paddingLeft": "6px", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--accent-9)", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + ":active:not([data-state='open'])": "var(--accent-10)", + "[data-disabled]": "var(--gray-a3)", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + }, + ":focus-visible:not([data-disabled])": "solid", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-6)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "color": { + "default": "var(--accent-contrast)", + "[data-disabled]": "var(--gray-a8)", + }, + "filter": { + ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + "saturate(1.1)) var(--rx-if-dark, " + "brightness(1.08))", + "[data-disabled]": "none", + }, + "outlineWidth": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "outlineColor": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + }, + ":focus-visible:not([data-disabled])": "var(--focus-8)", + }, + "outlineOffset": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "height": "var(--base-button-height)", + "width": "var(--base-button-height)", + } + ] + + +def test_icon_button_size_sizes_the_icon( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """The size of the button gives the icon its size.""" + component = compiled(rx.ui.icon_button(rx.icon("trash"), size="3", variant="soft")) + assert component.render() == { + "name": '"button"', + "props": ["className:sx_76b6296e23_c"], + "children": [{"name": "LucideTrash", "props": ["size:36"], "children": []}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "6px", + "paddingRight": "6px", + "paddingBottom": "6px", + "paddingLeft": "6px", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--accent-a3)", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a4)"}, + ":active:not([data-state='open'])": "var(--accent-a5)", + "[data-disabled]": "var(--gray-a3)", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-7)", + "borderRadius": "max(var(--radius-3), var(--radius-full))", + "color": { + "default": "var(--accent-a11)", + "[data-disabled]": "var(--gray-a8)", + }, + "outlineWidth": {":focus-visible": "2px"}, + "outlineColor": {":focus-visible": "var(--accent-8)"}, + "outlineOffset": {":focus-visible": "-1px"}, + "height": "var(--base-button-height)", + "width": "var(--base-button-height)", + } + ] + + +def test_icon_button_ghost( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """A ghost icon button has the padding of the wrapper over the one of its size.""" + component = compiled(rx.ui.icon_button("plus", variant="ghost", size="2")) + assert declared_styles(component) == [ + { + "marginTop": "calc(0px - calc(var(--space-1) * 1.5))", + "marginRight": "calc(0px - calc(var(--space-1) * 1.5))", + "marginBottom": "calc(0px - calc(var(--space-1) * 1.5))", + "marginLeft": "calc(0px - calc(var(--space-1) * 1.5))", + "paddingTop": "6px", + "paddingRight": "6px", + "paddingBottom": "6px", + "paddingLeft": "6px", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a3)"}, + ":active:not([data-state='open'])": "var(--accent-a4)", + "[data-disabled]": "transparent", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "content-box", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-6)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "color": { + "default": "var(--accent-a11)", + "[data-disabled]": "var(--gray-a8)", + }, + "outlineWidth": {":focus-visible": "2px"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-1px"}, + "height": "fit-content", + } + ] + + +def test_icon_button_needs_an_icon(): + """Without a child there is nothing to show.""" + with pytest.raises(ValueError, match="IconButton requires a child icon") as raised: + rx.ui.icon_button() + assert str(raised.value) == ( + "IconButton requires a child icon. Pass a string as the first child or a " + "rx.icon." + ) diff --git a/tests/units/reflex_components_ui/components/test_spinner.py b/tests/units/reflex_components_ui/components/test_spinner.py new file mode 100644 index 00000000000..efd0cdbb61a --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_spinner.py @@ -0,0 +1,359 @@ +"""Tests for reflex_components_ui.components.spinner.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import Keyframes + +import reflex as rx + +# What each leaf of a spinner declares. +LEAF: dict[str, Any] = { + "position": "absolute", + "top": "0", + "left": "calc(50% - 12.5% / 2)", + "width": {"default": "12.5%", "::before": "100%"}, + "height": {"default": "100%", "::before": "30%"}, + "animationName": Keyframes('{"from": {"opacity": 1}, "to": {"opacity": 0.25}}', ()), + "animationDuration": "var(--spinner-animation-duration, 800ms)", + "animationTimingFunction": "linear", + "animationIterationCount": "infinite", + "transform": { + ":nth-child(1)": "rotate(0deg)", + ":nth-child(2)": "rotate(45deg)", + ":nth-child(3)": "rotate(90deg)", + ":nth-child(4)": "rotate(135deg)", + ":nth-child(5)": "rotate(180deg)", + ":nth-child(6)": "rotate(225deg)", + ":nth-child(7)": "rotate(270deg)", + ":nth-child(8)": "rotate(315deg)", + }, + "animationDelay": { + ":nth-child(1)": "calc(-8 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(2)": "calc(-7 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(3)": "calc(-6 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(4)": "calc(-5 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(5)": "calc(-4 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(6)": "calc(-3 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(7)": "calc(-2 / 8 * var(--spinner-animation-duration, 800ms))", + ":nth-child(8)": "calc(-1 / 8 * var(--spinner-animation-duration, 800ms))", + }, + "content": {"::before": "''"}, + "display": {"::before": "block"}, + "borderTopLeftRadius": {"::before": "var(--radius-1)"}, + "borderTopRightRadius": {"::before": "var(--radius-1)"}, + "borderBottomRightRadius": {"::before": "var(--radius-1)"}, + "borderBottomLeftRadius": {"::before": "var(--radius-1)"}, + "backgroundColor": {"::before": "currentColor"}, +} + + +class SpinnerState(rx.State): + """What a spinner is bound to.""" + + busy: bool = True + + +def test_spinner_alone( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A spinner is a span of eight leaves, each turned and delayed by its place.""" + component = rx.ui.spinner(id="wait") + assert component.render() == { + "name": '"span"', + "props": ["className:sx_fe93a2d910_c", 'id:"wait"', "ref:ref_wait"], + "children": [ + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + {"name": '"span"', "props": ["className:sx_32f6bd5200_c"], "children": []}, + ], + } + assert declared_styles(component) == [ + { + "display": "block", + "position": "relative", + "opacity": "var(--spinner-opacity, 0.65)", + "width": "var(--space-4)", + "height": "var(--space-4)", + }, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + ] + + +def test_spinner_size( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The size of a spinner may change at a breakpoint.""" + component = rx.ui.spinner(size=rx.breakpoints(initial="1", md="3")) + assert declared_styles(component) == [ + { + "display": "block", + "position": "relative", + "opacity": "var(--spinner-opacity, 0.65)", + "width": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "calc(1.25 * var(--space-4))", + }, + "height": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "calc(1.25 * var(--space-4))", + }, + }, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + ] + + +def test_spinner_over_children( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """Around children, the spinner is centered over their place.""" + component = rx.ui.spinner("Report", size="3") + assert component.render() == { + "name": '"span"', + "props": ["className:sx_826ff773c9_c"], + "children": [ + { + "name": '"span"', + "props": ['"aria-hidden":true', "className:sx_33a975bab1_c"], + "children": [{"contents": '"Report"'}], + }, + { + "name": '"span"', + "props": ["className:sx_67bf81be86_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_12ba415941_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_32f6bd5200_c"], + "children": [], + }, + ], + } + ], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "position": "relative", + "alignItems": "center", + "justifyContent": "center", + }, + {"display": "contents", "visibility": "hidden"}, + { + "boxSizing": "border-box", + "display": "flex", + "alignItems": "center", + "justifyContent": "center", + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + }, + { + "display": "block", + "position": "relative", + "opacity": "var(--spinner-opacity, 0.65)", + "width": "calc(1.25 * var(--space-4))", + "height": "calc(1.25 * var(--space-4))", + }, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + LEAF, + ] + + +def test_spinner_not_loading( + ui_plugin: UIPlugin, +): + """A spinner that is not loading is its children.""" + component = rx.ui.spinner("Report", loading=False) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [{"contents": '"Report"'}], + } + + +def test_spinner_bound_to_state( + ui_plugin: UIPlugin, +): + """Loading bound to state chooses between the spinner and the children in the browser.""" + component = rx.ui.spinner("Report", loading=SpinnerState.busy) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": "reflex___state____state__tests___units___reflex_components_ui___components___test_spinner____spinner_state.busy_rx_state_", + "true_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"span"', + "props": ["className:sx_826ff773c9_c"], + "children": [ + { + "name": '"span"', + "props": [ + '"aria-hidden":true', + "className:sx_33a975bab1_c", + ], + "children": [{"contents": '"Report"'}], + }, + { + "name": '"span"', + "props": ["className:sx_67bf81be86_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_fe93a2d910_c"], + "children": [ + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_32f6bd5200_c" + ], + "children": [], + }, + ], + } + ], + }, + ], + } + ], + }, + "false_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": "Fragment", + "props": [], + "children": [{"contents": '"Report"'}], + } + ], + }, + } + ], + } diff --git a/tests/units/reflex_components_ui/style/test_emit.py b/tests/units/reflex_components_ui/style/test_emit.py index e10b0cab5f8..e6f2b1a4e85 100644 --- a/tests/units/reflex_components_ui/style/test_emit.py +++ b/tests/units/reflex_components_ui/style/test_emit.py @@ -4,7 +4,7 @@ import pytest from reflex_base.vars.base import Var -from reflex_components_ui.style import ComponentStyles, StyleError, merge +from reflex_components_ui.style import ComponentStyles, StyleError, keyframes, merge from reflex_components_ui.style.emit import Emitted, emit, inline import reflex as rx @@ -608,3 +608,67 @@ def test_inline_rejects_what_an_inline_style_cannot_hold( with pytest.raises(StyleError) as raised: inline(merge("rx.ui.box", **arguments), "rx.ui.box") assert str(raised.value) == message + + +FADE = keyframes({"from": {"opacity": 1}, "to": {"opacity": 0.25}}) +SLIDE = keyframes({"to": {"top": "0"}}) + +# A style that plays keyframes, at rest and under a condition, and a variant +# bound to state that plays others. +ANIMATED: ComponentStyles = { + "base": { + "animation_name": {"default": FADE, ":hover": SLIDE}, + "animation_duration": "800ms", + }, + "variants": {"kind": {"slide": {"animation_name": SLIDE}}}, +} + + +def test_emit_declares_keyframes_before_the_style_that_plays_them(): + """Keyframes are statements of the declaration, named after it.""" + assert emit(merge("rx.ui.spinner", ANIMATED)) == Emitted( + declaration=( + "const sx_88a6398628_k0 = stylex.keyframes(" + '{"from": {"opacity": 1}, "to": {"opacity": 0.25}});\n' + 'const sx_88a6398628_k1 = stylex.keyframes({"to": {"top": "0"}});\n' + "const sx_88a6398628 = stylex.create({ s: " + '{"animationName": {"default": sx_88a6398628_k0, ":hover": ' + 'sx_88a6398628_k1}, "animationDuration": "800ms"} });\n' + "const sx_88a6398628_c = stylex.props(sx_88a6398628.s).className;" + ), + classes="sx_88a6398628_c", + ) + + +def test_emit_declares_the_keyframes_of_a_state_bound_variant_once(): + """Each value of the prop plays keyframes the declaration holds once.""" + emitted = emit(merge("rx.ui.spinner", ANIMATED, {"kind": S.kind})) + assert emitted.declaration == ( + "const sx_5a092954ad_k0 = stylex.keyframes(" + '{"to": {"top": "0"}});\n' + "const sx_5a092954ad_k1 = stylex.keyframes(" + '{"from": {"opacity": 1}, "to": {"opacity": 0.25}});\n' + "const sx_5a092954ad = stylex.create({ s: " + '{"animationDuration": "800ms"}, a0_0: {"animationName": ' + 'sx_5a092954ad_k0}, a0: {"animationName": {"default": ' + 'sx_5a092954ad_k1, ":hover": sx_5a092954ad_k0}} });\n' + "const sx_5a092954ad_c = stylex.props(sx_5a092954ad.s).className;\n" + 'const sx_5a092954ad_0 = { __proto__: null, "slide": ' + "stylex.props(sx_5a092954ad.a0_0).className };\n" + "const sx_5a092954ad_0d = stylex.props(sx_5a092954ad.a0).className;" + ) + assert emitted.lookups == (f"(sx_5a092954ad_0[{S.kind!s}] ?? sx_5a092954ad_0d)",) + + +def test_inline_cannot_play_keyframes(): + """Code evaluated in the browser declares no keyframes.""" + with pytest.raises(StyleError) as error: + inline( + merge("rx.ui.spinner", {"base": {"animation_name": FADE}}), "rx.ui.spinner" + ) + assert str(error.value) == ( + 'rx.ui.spinner: the style "animationName" plays keyframes, which a ' + "component rendered from state cannot apply: its code is evaluated in the " + "browser and never reaches the StyleX compiler. Leave the animation out " + "there, or render the component in a page and show it with rx.cond." + ) diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index dce347f045d..6d85f3fa835 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -22,6 +22,7 @@ StyleError, apply_layer, finish, + keyframes, lower, lower_layer, ) @@ -1506,3 +1507,96 @@ def test_layout_props_keep_the_breakpoints_of_radix_whatever_the_app_has(): "rowGap": {"default": "var(--space-1)", PROP_XS: "var(--space-3)"}, "width": {"@media screen and (min-width: 20px)": "2px"}, } + + +FADE = keyframes({ + "from": {"opacity": 1, "background_color": tokens.accent[9]}, + "50%": {"margin_x": "2px"}, + "to": {"opacity": 0.25}, +}) + + +def test_keyframes_lower_each_frame_and_compare_by_content(): + """Frames are lowered like any style, and equal keyframes are one animation.""" + assert FADE.source == ( + '{"from": {"opacity": 1, "backgroundColor": "var(--accent-9)"}, ' + '"50%": {"marginLeft": "2px", "marginRight": "2px"}, ' + '"to": {"opacity": 0.25}}' + ) + assert FADE.imports == ("$/reflex-ui/tokens/accent.stylex.js",) + again = keyframes({ + "from": {"opacity": 1, "background_color": tokens.accent[9]}, + "50%": {"margin_x": "2px"}, + "to": {"opacity": 0.25}, + }) + assert again == FADE + assert hash(again) == hash(FADE) + assert again != keyframes({"from": {"opacity": 1}}) + assert repr(keyframes({"to": {"top": "0"}})) == ( + """Keyframes('{"to": {"top": "0"}}', ())""" + ) + + +def test_keyframes_are_the_value_of_animation_name(): + """The style that plays keyframes imports what their frames use.""" + lowered = lower( + "rx.ui.spinner", + { + "animation_name": { + "default": FADE, + "@media (prefers-reduced-motion: reduce)": "none", + }, + "animation_duration": "800ms", + }, + ) + assert lowered.style == { + "animationName": { + "default": FADE, + "@media (prefers-reduced-motion: reduce)": "none", + }, + "animationDuration": "800ms", + } + assert lowered.imports == ("$/reflex-ui/tokens/accent.stylex.js",) + assert lowered == lower( + "rx.ui.spinner", + { + "animation_duration": "800ms", + "animation_name": { + "default": FADE, + "@media (prefers-reduced-motion: reduce)": "none", + }, + }, + ) + + +@pytest.mark.parametrize( + ("create", "message"), + [ + ( + lambda: lower("rx.ui.spinner", {"transition_property": FADE}), + ( + 'rx.ui.spinner: style "transition_property" is given keyframes, ' + "which are the value of animation_name." + ), + ), + ( + lambda: keyframes({"from": "opacity: 1"}), # pyright: ignore[reportArgumentType] + 'rx.ui keyframes: the frame "from" must be a dict of styles, not str.', + ), + ( + lambda: keyframes({"to": {"opacity": {"default": 1, ":hover": 0}}}), + ( + 'rx.ui keyframes: the style "opacity" of the frame "to" must be a ' + "literal: a frame takes no condition and nothing bound to state." + ), + ), + ( + lambda: keyframes({"to": {"opacty": 1}}), + 'rx.ui keyframes: unknown CSS property "opacty". Did you mean "opacity"?', + ), + ], +) +def test_keyframes_errors(create: Any, message: str): + with pytest.raises(StyleError) as error: + create() + assert str(error.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 1202373ccb9..abead7c0788 100644 --- a/tests/units/reflex_components_ui/style/test_merge.py +++ b/tests/units/reflex_components_ui/style/test_merge.py @@ -758,3 +758,42 @@ def test_unchecked_passes_a_style_a_type_checker_cannot_read(): "--line-height": "1.5", "marginTop": "0", } + + +def test_later_style_keeps_what_an_earlier_one_gives_a_pseudo_element(): + """A pseudo-element is another box: a value for the element leaves it alone.""" + table: ComponentStyles = { + "base": { + "color": "red", + "_hover": {"color": "blue"}, + "_after": {"color": "green", "_hover": {"color": "teal"}, "top": "0"}, + }, + "variants": { + "kind": { + # Outright: the conditions of the element go, its pseudo-element stays. + "plain": {"color": "black"}, + # For the pseudo-element too: it is replaced as a whole. + "both": {"color": "black", "_after": {"color": "white"}}, + # With conditions of its own, and nothing for the pseudo-element. + "states": {"color": {"default": "black", ":active": "gray"}}, + } + }, + } + after = {"default": "green", ":hover": "teal"} + assert merge("rx.ui.card", table, {"kind": "plain"}).style.style == { + "color": {"default": "black", "::after": after}, + "top": {"::after": "0"}, + } + assert merge("rx.ui.card", table, {"kind": "both"}).style.style == { + "color": {"default": "black", "::after": "white"}, + "top": {"::after": "0"}, + } + assert merge("rx.ui.card", table, {"kind": "states"}).style.style == { + "color": {"default": "black", ":active": "gray", "::after": after}, + "top": {"::after": "0"}, + } + # The style of the element is merged the same way. + assert merge("rx.ui.card", table, None, {"color": "navy"}).style.style == { + "color": {"default": "navy", "::after": after}, + "top": {"::after": "0"}, + } diff --git a/tests/units/reflex_components_ui/test_themes.py b/tests/units/reflex_components_ui/test_themes.py index a86a31b1f3b..ec3de524a26 100644 --- a/tests/units/reflex_components_ui/test_themes.py +++ b/tests/units/reflex_components_ui/test_themes.py @@ -14,6 +14,7 @@ ThemeStyles, app_theme_styles, color_scheme_styles, + radius_styles, theme_styles, ) @@ -727,3 +728,54 @@ def test_import_dict_names_the_modules_as_an_app_imports_them(): ], "$/reflex-ui/themes/theme.js": [ImportVar(tag="theme", alias="reflexUITheme")], } + + +def test_radius_styles_of_a_component(): + """A radius on one element is its theme, and the steps that read it.""" + full = ThemeStyles( + classes="reflexUIClasses_4c7cd6a7ce", + imports=( + HELPER_IMPORT, + ("themes/radius.js", "radiusFull", None), + ("themes/scope.js", "radiusScope", None), + ), + declarations=( + ( + "const reflexUIClasses_4c7cd6a7ce = " + "reflexUIClassName(radiusScope, radiusFull);" + ), + ), + ) + assert radius_styles("rx.ui.button", "full") == full + assert radius_styles("rx.ui.button", LiteralVar.create("full")) == full + with pytest.raises(ThemeError) as error: + radius_styles("rx.ui.button", "round") + assert str(error.value) == ( + 'rx.ui.button: unknown radius "round". The values are "none", "small", ' + '"medium", "large", "full".' + ) + + +def test_radius_bound_to_state_indexes_a_table_of_class_names(): + """Every radius is imported, and joined with the steps when the module loads.""" + styles = radius_styles("rx.ui.button", ThemeState.radius) + assert styles.classes == f"reflexUIElementRadii[{ThemeState.radius!s}]" + assert styles.imports == ( + HELPER_IMPORT, + ("themes/radius.js", "radiusFull", None), + ("themes/radius.js", "radiusLarge", None), + ("themes/radius.js", "radiusMedium", None), + ("themes/radius.js", "radiusNone", None), + ("themes/radius.js", "radiusSmall", None), + ("themes/scope.js", "radiusScope", None), + ) + assert styles.declarations == ( + _map( + "reflexUIElementRadii", + { + name: f"reflexUIClassName(radiusScope, radius{name.capitalize()})" + for name in _radix_tokens.RADIUS_THEMES + }, + ), + ) + assert [var.equals(ThemeState.radius) for var in styles.vars] == [True] From 6b1d5ea1b3c63d3dc0e0332e267952fa034cb894 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:48:52 +0000 Subject: [PATCH 049/204] Document the conventions of the display and action wave, and add its news fragments Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- news/+initial-state-dynamic-imports.bugfix.md | 1 + .../news/+rendering-dynamic-component.misc.md | 1 + packages/reflex-components-ui/README.md | 54 +++++++++++++++++-- .../news/+dynamic-component-imports.bugfix.md | 1 + .../news/+keyframes.feature.md | 11 ++++ .../news/+pseudo-element-merge.bugfix.md | 1 + .../news/+wave2-display-actions.feature.md | 9 ++++ 7 files changed, 73 insertions(+), 5 deletions(-) create mode 100644 news/+initial-state-dynamic-imports.bugfix.md create mode 100644 packages/reflex-base/news/+rendering-dynamic-component.misc.md create mode 100644 packages/reflex-components-ui/news/+dynamic-component-imports.bugfix.md create mode 100644 packages/reflex-components-ui/news/+keyframes.feature.md create mode 100644 packages/reflex-components-ui/news/+pseudo-element-merge.bugfix.md create mode 100644 packages/reflex-components-ui/news/+wave2-display-actions.feature.md diff --git a/news/+initial-state-dynamic-imports.bugfix.md b/news/+initial-state-dynamic-imports.bugfix.md new file mode 100644 index 00000000000..a1742317efe --- /dev/null +++ b/news/+initial-state-dynamic-imports.bugfix.md @@ -0,0 +1 @@ +The libraries a component in the initial state hands to the browser are the ones its dynamic code imports, not the ones a page that renders it would: a component that relies on a build step no longer has its build-only imports bundled. diff --git a/packages/reflex-base/news/+rendering-dynamic-component.misc.md b/packages/reflex-base/news/+rendering-dynamic-component.misc.md new file mode 100644 index 00000000000..bf028fdebd1 --- /dev/null +++ b/packages/reflex-base/news/+rendering-dynamic-component.misc.md @@ -0,0 +1 @@ +Add `reflex_base.components.dynamic.rendering_dynamic_component`, a context manager for reading from a component what its code needs when it is evaluated in the browser. diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index f19c90334a7..b1eef1b83fd 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -31,6 +31,7 @@ src/reflex_components_ui/ the python package: the rx.ui namespace 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 + styles/appearance.py by_appearance: a value that is no color, light and dark layout/ the layout components, rx.ui.theme among them typography/ text, heading, code, blockquote, link components/ the other components: separator, inset, aspect_ratio @@ -92,6 +93,7 @@ runtime**: | `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 | +| `animation_name=keyframes({...})` | A `stylex.keyframes` statement beside the declaration, which StyleX folds into the name of the animation | | `"& > div": {...}`, `paddng="1em"` | A `StyleError` where the component is created | What follows from it: @@ -125,10 +127,20 @@ 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`. +element cannot express: the selection color inside a theme and the opacity a +button gives the icons inside it (`--rx-icon-opacity`, read by every `svg` of +a theme and nothing to one outside a button), in the layer `reflex-ui.base` +so that a component's own style beats them, 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`. + +And it says which appearance an element has to what `light-dark()` cannot +choose between. `--rx-if-light` and `--rx-if-dark` are set wherever the +classes `light` and `dark` are (the root, and the element around a theme with +an appearance): the one of the current appearance is invalid and the other is +empty, so `var(--rx-if-light, brightness(0.92)) var(--rx-if-dark, +brightness(1.08))` is the filter of the appearance alone. A table writes it +`by_appearance(light, dark)`, from `styles/appearance.py`. `-webkit-text-size-adjust` is not there: the build adds the prefixed property beside the one `themes/theme.js` sets. @@ -222,12 +234,42 @@ class Button(UIComponent, elements.Button): - **`color_scheme`** is read by a table as `"true"` when the element has a color: `"variants": {"color_scheme": {"true": {...}}}`. The tokens of the accent resolve against that color, so a table never needs to know which. +- **`radius`**, on a component with that field, is the radius of the element + itself, as `data-radius` is in Radix Themes: the theme of that radius and + the steps of the radius scale, applied like the accent of a `color_scheme`. + Declare the field (`Var[LiteralRadius]`) and write the table with + `tokens.radius`. - **What Radix Themes selects by ancestor**, a class on an element cannot: a link inside colored text, high-contrast text inside a colored element, code inside a link. The ancestor hands the value down in a custom property and the descendant reads it with a fallback, as `styles/typography.py` does. Every component with a `color_scheme` spreads `ACCENT_SCOPE` into that variant. +- **What Radix Themes resets on children**: a ghost button or card, and an + inset, take their padding back with negative margins, which Radix computes + through `--margin-*-override` properties that it has to reset on every + child. Here the margins are written on the element itself (`calc(0px - + )`) and nothing is handed down, so there is nothing to reset: + no rx.ui element reads an inherited margin. +- **States**: a rule under `@media (hover: hover)` is placed after the ones + for `:active` and `:focus-visible`, and a rule on an attribute + (`[data-disabled]`) after every pseudo-class, whatever the order of the + table. Where Radix lets a later rule win, make the conditions exclusive + instead: `":hover:not(:active)"`, as `styles/button.py` does. +- **Pseudo-elements** (`_before`, `_after`) are the outermost block, with + their states inside: `"_after": {"@media (hover: hover)": {":hover:not(:active)": + {...}}}`. A style merged later keeps what the earlier one gives a + pseudo-element and replaces everything else of a property it sets, its + conditions included, so a variant that changes the rules of several states + (high contrast) is the table of its variant merged block by block when the + table is built (`_over` in `styles/button.py`), listed as a compound style. +- **A value that differs between the appearances** and is no color, such as a + filter or the layers of a shadow, is `by_appearance(light, dark)`. +- **Animations**: `"animation_name": keyframes({"from": {...}, "to": {...}})` + with the longhands beside it (`animation_duration`...), as StyleX drops the + `animation` shorthand. Equal keyframes are declared once per module. Radix + Themes does not change the spinner, the skeleton or the progress bar for + `prefers-reduced-motion`, so neither do these. - **Styles a class adds**: `add_style`, as in any component, applies after the layout props and before the styles of the app. `rx.ui.center` centers that way, so that `align` and `justify` lose to it as they do in `rx.center`. @@ -292,6 +334,7 @@ What lowering does to each input: | Layout props (`p`, `m`, `gap`, `columns`, `direction`...) | Styles, with steps of the space scale as `var(--space-N)`, and a value per breakpoint on the breakpoints of Radix Themes | | A shorthand bound to state, or holding `var(...)` | Kept whole; it removes its longhands from the styles before it | | `None` | The property is unset | +| `keyframes({...})` as `animation_name` | A `Keyframes`: its frames lowered, compared and hashed by content | | A nested selector, an unknown property, `animation` | `StyleError` | Styles merge by property and the last one wins: base, variants, compound @@ -302,7 +345,8 @@ else; one that sets it outright replaces the earlier conditions too. 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` +refused: an animation is its longhands, and `keyframes(frames)` as its +`animation_name`, in a table or in the `style` of an element. 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. diff --git a/packages/reflex-components-ui/news/+dynamic-component-imports.bugfix.md b/packages/reflex-components-ui/news/+dynamic-component-imports.bugfix.md new file mode 100644 index 00000000000..aabf88635b9 --- /dev/null +++ b/packages/reflex-components-ui/news/+dynamic-component-imports.bugfix.md @@ -0,0 +1 @@ +An `rx.ui` component held in state no longer imports StyleX in the browser: it falls back to an inline style whether or not a page read its imports first. diff --git a/packages/reflex-components-ui/news/+keyframes.feature.md b/packages/reflex-components-ui/news/+keyframes.feature.md new file mode 100644 index 00000000000..8c8515d25ff --- /dev/null +++ b/packages/reflex-components-ui/news/+keyframes.feature.md @@ -0,0 +1,11 @@ +A style can play an animation: `keyframes({...})` from `reflex_components_ui.style` is the value of `animation_name`, in a style table or in the `style` of an element, and compiles to a class name like any other style. + +```python +from reflex_components_ui.style import keyframes + +rx.ui.box( + animation_name=keyframes({"from": {"opacity": 1}, "to": {"opacity": 0.25}}), + animation_duration="800ms", + animation_iteration_count="infinite", +) +``` diff --git a/packages/reflex-components-ui/news/+pseudo-element-merge.bugfix.md b/packages/reflex-components-ui/news/+pseudo-element-merge.bugfix.md new file mode 100644 index 00000000000..6b586d21327 --- /dev/null +++ b/packages/reflex-components-ui/news/+pseudo-element-merge.bugfix.md @@ -0,0 +1 @@ +A style no longer removes what a component gives its `::before` and `::after`: `rx.ui.card(background_color="red")` keeps the surface the card draws in a pseudo-element. diff --git a/packages/reflex-components-ui/news/+wave2-display-actions.feature.md b/packages/reflex-components-ui/news/+wave2-display-actions.feature.md new file mode 100644 index 00000000000..14ab3e1fde3 --- /dev/null +++ b/packages/reflex-components-ui/news/+wave2-display-actions.feature.md @@ -0,0 +1,9 @@ +Add the display and action components to `rx.ui`: `button`, `icon_button`, `badge`, `card`, `callout` (with `callout.root`, `callout.icon` and `callout.text`), `avatar`, `skeleton`, `spinner`, `table` (with its parts), `data_list` (with its parts), `progress` and `scroll_area`. Each takes the arguments of the component of the same name in `rx` and looks the same, in every variant, size, color, radius and state. + +```python +rx.ui.card( + rx.ui.heading("Invoice", size="3"), + rx.ui.badge("Paid", color_scheme="green"), + rx.ui.button("Send", loading=State.sending, on_click=State.send), +) +``` From d7e6d19e05b6399ec08c65318ff26e4ece529c23 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:50:38 +0000 Subject: [PATCH 050/204] Settle the types of the button table and regenerate the stubs Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../src/reflex_components_ui/base.py | 2 +- .../reflex_components_ui/components/button.py | 2 +- .../src/reflex_components_ui/style/lower.py | 2 +- .../src/reflex_components_ui/styles/button.py | 64 ++++++++++++++----- pyi_hashes.json | 7 +- .../components/test_button.py | 2 +- 6 files changed, 56 insertions(+), 23 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 c8cb75b0d48..189da7d2d18 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -583,7 +583,7 @@ def _get_imports(self) -> ParsedImportDict: """ dynamic = is_rendering_dynamic_component() if self.__dict__.get("_imports_for") is not dynamic: - self.__dict__.pop("_imports_cache", None) + self._imports_cache = None self._imports_for = dynamic return super()._get_imports() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/button.py b/packages/reflex-components-ui/src/reflex_components_ui/components/button.py index 8d602e9d972..5f62944c2fb 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/button.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/button.py @@ -121,7 +121,7 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: in its place with ``as_child`` looks disabled as well. """ tag = super()._render(props) - disabled = _either(self.disabled, self.loading) + disabled = _either(getattr(self, "disabled", None), self.loading) if disabled is None: return tag if isinstance(disabled, LiteralVar): 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 b5f7c4628b5..d336702cc7a 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 @@ -1272,7 +1272,7 @@ def apply_layer(target: dict[str, LoweredValue], layer: Layer) -> None: for prop in replaced: target.pop(prop, None) for prop, value in props.items(): - old = target.get(prop) + old: Any = target.get(prop) if value.__class__ is dict and "default" not in value: target[prop] = value if old is None else _overlay(old, value) elif old.__class__ is dict: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py index df17d531ea9..04b8f8fd1ca 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py @@ -335,7 +335,7 @@ def _over(under: dict[str, Any], top: dict[str, Any]) -> dict[str, Any]: """ merged = dict(under) for key, value in top.items(): - below = merged.get(key) + below: Any = merged.get(key) merged[key] = ( _over(below, value) if value.__class__ is dict and below.__class__ is dict @@ -378,7 +378,41 @@ def _over(under: dict[str, Any], top: dict[str, Any]) -> dict[str, Any]: "leaf": {"base": LEAF}, } -_RADIUS = {"1": 1, "2": 2, "3": 3, "4": 4} +# The height, the radius and the padding on each side of each size. +_SIZES: dict[str, tuple[str, str, str]] = { + "1": (tokens.space[5], tokens.radius[1], tokens.space[2]), + "2": (tokens.space[6], tokens.radius[2], tokens.space[3]), + "3": (tokens.space[7], tokens.radius[3], tokens.space[4]), + "4": (tokens.space[8], tokens.radius[4], tokens.space[5]), +} + +# The space between the children of a button of each size, and its text. +_TEXT: dict[str, dict[str, str]] = { + "1": { + "gap": tokens.space[1], + "font_size": tokens.font_size[1], + "line_height": tokens.line_height[1], + "letter_spacing": tokens.letter_spacing[1], + }, + "2": { + "gap": tokens.space[2], + "font_size": tokens.font_size[2], + "line_height": tokens.line_height[2], + "letter_spacing": tokens.letter_spacing[2], + }, + "3": { + "gap": tokens.space[3], + "font_size": tokens.font_size[3], + "line_height": tokens.line_height[3], + "letter_spacing": tokens.letter_spacing[3], + }, + "4": { + "gap": tokens.space[3], + "font_size": tokens.font_size[4], + "line_height": tokens.line_height[4], + "letter_spacing": tokens.letter_spacing[4], + }, +} # What everything a button does not set is, as Radix Themes unsets it all: # the look the browser gives a button, and what a reset of the page adds. @@ -442,14 +476,15 @@ def button_styles(icon: bool) -> ComponentStyles: Returns: The table. """ - sizes: dict[str, Any] = {} compound: list[CompoundStyle] = [] - for size, step in _RADIUS.items(): - sizes[size] = { + sizes: dict[str, Any] = { + size: { _PRESSED_PADDING: "1px" if size == "1" else "2px", - _HEIGHT: tokens.space[step + 4], - "border_radius": f"max({tokens.radius[step]}, {tokens.radius.full})", + _HEIGHT: height, + "border_radius": f"max({radius}, {tokens.radius.full})", } + for size, (height, radius, _) in _SIZES.items() + } if icon: ghost_padding = { "1": tokens.space[1], @@ -466,13 +501,8 @@ def button_styles(icon: bool) -> ComponentStyles: for size in sizes } else: - for size, step in _RADIUS.items(): - sizes[size].update({ - "gap": tokens.space[min(step, 3)], - "font_size": tokens.font_size[step], - "line_height": tokens.line_height[step], - "letter_spacing": tokens.letter_spacing[step], - }) + for size, text in _TEXT.items(): + sizes[size].update(text) ghost_paddings = { "1": (tokens.space[1], tokens.space[2], tokens.space[1]), "2": (tokens.space[1], tokens.space[2], tokens.space[1]), @@ -486,12 +516,12 @@ def button_styles(icon: bool) -> ComponentStyles: solid_size = { size: { "height": f"var({_HEIGHT})", - "padding_left": tokens.space[step + 1], - "padding_right": tokens.space[step + 1], + "padding_left": padding, + "padding_right": padding, "font_weight": tokens.font_weight.medium, ICON_OPACITY: "0.9", } - for size, step in _RADIUS.items() + for size, (_, _, padding) in _SIZES.items() } for variant in _VARIANTS: by_size = ghost if variant == "ghost" else solid_size diff --git a/pyi_hashes.json b/pyi_hashes.json index d403206faa8..d65d9244e92 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,11 +118,14 @@ "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": "04594af03ce14a1150a8c1f88a2594d7", - "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "d4866ed281752f69eef9ad719980dd8c", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "c08242790fe83b60bc78516b695583b6", + "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "b8536b02469bd96e86989749728e34b7", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", + "packages/reflex-components-ui/src/reflex_components_ui/components/button.pyi": "9e3f6fccbe30356fdbbe576471d6222e", + "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", "packages/reflex-components-ui/src/reflex_components_ui/components/separator.pyi": "bd32f08f7c0ff2cb6733f964ea843440", + "packages/reflex-components-ui/src/reflex_components_ui/components/spinner.pyi": "9e62e8634e1425a75302d24fb458e8a8", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", "packages/reflex-components-ui/src/reflex_components_ui/layout/center.pyi": "a38424cf14313b5358c9ad198a7880f9", "packages/reflex-components-ui/src/reflex_components_ui/layout/container.pyi": "ecfbd513a1a12bbfc11a6d30e91987c6", diff --git a/tests/units/reflex_components_ui/components/test_button.py b/tests/units/reflex_components_ui/components/test_button.py index b2a9e2b4e7d..86200379f3f 100644 --- a/tests/units/reflex_components_ui/components/test_button.py +++ b/tests/units/reflex_components_ui/components/test_button.py @@ -1084,7 +1084,7 @@ def test_button_rejects_a_value_a_prop_does_not_take( ): """The error names the component, the prop and the values it takes.""" with pytest.raises(error) as raised: - rx.ui.button("Save", **props) + rx.ui.button("Save", **props) # pyright: ignore[reportArgumentType] assert str(raised.value) == message From d0fb57f152478b15ac67f568671932f7d0a7e16d Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:34:54 +0000 Subject: [PATCH 051/204] Add rx.ui.badge Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/ui_parity/components/badge.py | 126 ++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/badge.py | 42 +++++ .../src/reflex_components_ui/styles/badge.py | 108 ++++++++++++ .../components/test_badge.py | 162 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 6 files changed, 440 insertions(+) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/badge.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/badge.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/badge.py create mode 100644 tests/units/reflex_components_ui/components/test_badge.py diff --git a/packages/reflex-components-ui/parity/ui_parity/components/badge.py b/packages/reflex-components-ui/parity/ui_parity/components/badge.py new file mode 100644 index 00000000000..47fd89f0262 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/badge.py @@ -0,0 +1,126 @@ +"""The badge: every variant, size and color, alone and among other things.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, LIGHT, Matrix +from ui_parity.samples import ACCENTS + +VARIANTS = ["solid", "soft", "surface", "outline"] +SIZES = ["1", "2", "3"] +RADII = ["none", "small", "medium", "large", "full"] +RESPONSIVE = {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")} + + +def _badge(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a badge, with what a cell says it holds or is inside of. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` names the children when they + are not words alone, and ``inside`` what is around the badge. + + Returns: + The badge, or what is around it. + """ + props = dict(props) + holds = props.pop("holds", None) + inside = props.pop("inside", None) + props["custom_attrs"] = {"data-badge": ""} + if holds == "icon": + badge = namespace.badge(rx.icon("check", size=12), "Shipped", **props) + else: + badge = namespace.badge("In progress", **props) + if inside == "flex": + # A badge keeps its height in a row of taller things. + return namespace.flex( + namespace.heading("Order 42", size="6"), + badge, + namespace.text("since Monday", size="2"), + spacing="2", + ) + if inside == "text": + return namespace.text("The order is ", badge, " and leaves soon.", size="3") + return badge + + +MATRIX = Matrix( + component="badge", + render=_badge, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "color_scheme": ACCENTS, + "radius": RADII, + "high_contrast": [True], + "holds": ["icon"], + "inside": ["flex", "text"], + "size": RESPONSIVE, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + {"radius": RADII, "size": SIZES}, + {"variant": VARIANTS, "holds": ["icon"], "size": SIZES}, + {"variant": VARIANTS, "inside": ["flex", "text"]}, + {"size": RESPONSIVE, "viewport": [520, 800, 1100, 1280]}, + ], + stage=(320, 100), + target="[data-badge]", + crop="stage", + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="badge", + render=lambda namespace: namespace.box( + namespace.badge("New", id="badge", title="Added this week"), + namespace.badge( + rx.icon("check", size=12), + "Shipped", + id="shipped", + variant="solid", + color_scheme="green", + ), + ), +) + + +@CONTRACT.step("is a span with its text in the server render", on=SERVER) +def _server_render(run: Run) -> None: + badge = run.server.element("badge") + assert (badge.tag, badge.text) == ("span", "New") + assert badge.attributes["title"] == "Added this week" + shipped = run.server.element("shipped") + assert (shipped.tag, shipped.text) == ("span", "Shipped") + + +@CONTRACT.step("is shown with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#badge").inner_text() == "New" + assert run.page.locator("#shipped").is_visible() + + +@CONTRACT.step("has no role and does not take the focus", on=HYDRATED) +def _role(run: Run) -> None: + badge = run.page.locator("#badge") + assert badge.get_attribute("role") is None + assert badge.evaluate("element => element.tabIndex") == -1 + assert run.page.get_by_text("New", exact=True).get_attribute("id") == "badge" + run.page.keyboard.press("Tab") + assert run.page.evaluate("document.activeElement.tagName") == "BODY" 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 e0b5ca8b092..81151348183 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -8,6 +8,7 @@ _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { "components.aspect_ratio": ["aspect_ratio"], + "components.badge": ["badge"], "components.button": ["button"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/badge.py b/packages/reflex-components-ui/src/reflex_components_ui/components/badge.py new file mode 100644 index 00000000000..d85ee42c508 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/badge.py @@ -0,0 +1,42 @@ +"""A badge: a short label that stands out.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.badge import BADGE +from reflex_components_ui.themes import LiteralAccentColor, LiteralRadius + + +class Badge(UIComponent, elements.Span): + """A stylized badge element.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = BADGE + + variant: Var[Literal["solid", "soft", "surface", "outline"]] = field( + doc="The variant of the badge" + ) + + size: Var[Responsive[Literal["1", "2", "3"]]] = field(doc="The size of the badge") + + color_scheme: Var[LiteralAccentColor] = field(doc="Color theme of the badge") + + high_contrast: Var[bool] = field( + doc="Whether to render the badge with higher contrast color against background" + ) + + radius: Var[LiteralRadius] = field( + doc='Override theme radius for badge: "none" | "small" | "medium" | "large" | "full"' + ) + + +badge = Badge.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/badge.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/badge.py new file mode 100644 index 00000000000..5a5c92fe323 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/badge.py @@ -0,0 +1,108 @@ +"""The look of a badge.""" + +from __future__ import annotations + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.typography import ACCENT_SCOPE + +accent = tokens.accent + +_HALF_SPACE = f"calc({tokens.space[1]} * 0.5)" +_GAP = f"calc({tokens.space[1]} * 1.5)" + +BADGE: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "display": "inline-flex", + "align_items": "center", + "white_space": "nowrap", + "font_family": tokens.default.font_family, + "font_weight": tokens.font_weight.medium, + "font_style": "normal", + "flex_shrink": 0, + # Not stretched by a flex or grid container. + "height": "fit-content", + }, + "variants": { + "size": { + "1": { + "font_size": tokens.font_size[1], + "line_height": tokens.line_height[1], + "letter_spacing": tokens.letter_spacing[1], + "padding": f"{_HALF_SPACE} {_GAP}", + "gap": _GAP, + "border_radius": f"max({tokens.radius[1]}, {tokens.radius.full})", + }, + "2": { + "font_size": tokens.font_size[1], + "line_height": tokens.line_height[1], + "letter_spacing": tokens.letter_spacing[1], + "padding": f"{tokens.space[1]} {tokens.space[2]}", + "gap": _GAP, + "border_radius": f"max({tokens.radius[2]}, {tokens.radius.full})", + }, + "3": { + "font_size": tokens.font_size[2], + "line_height": tokens.line_height[2], + "letter_spacing": tokens.letter_spacing[2], + "padding": f"{tokens.space[1]} calc({tokens.space[2]} * 1.25)", + "gap": tokens.space[2], + "border_radius": f"max({tokens.radius[2]}, {tokens.radius.full})", + }, + }, + "variant": { + "solid": { + "background_color": accent[9], + "color": accent.contrast, + "_selection": { + "background_color": accent[7], + "color": accent[12], + }, + }, + "surface": { + "background_color": accent.surface, + "box_shadow": f"inset 0 0 0 1px {accent.a[6]}", + "color": accent.a[11], + }, + "soft": {"background_color": accent.a[3], "color": accent.a[11]}, + "outline": { + "box_shadow": f"inset 0 0 0 1px {accent.a[8]}", + "color": accent.a[11], + }, + }, + "color_scheme": {"true": unchecked(ACCENT_SCOPE)}, + }, + "defaults": {"size": "1", "variant": "soft"}, + "compound": [ + { + "props": {"variant": "solid", "high_contrast": "true"}, + "style": { + "background_color": accent[12], + "color": accent[1], + "_selection": { + "background_color": accent.a[11], + "color": accent[1], + }, + }, + }, + { + "props": {"variant": "surface", "high_contrast": "true"}, + "style": {"color": accent[12]}, + }, + { + "props": {"variant": "soft", "high_contrast": "true"}, + "style": {"color": accent[12]}, + }, + { + "props": {"variant": "outline", "high_contrast": "true"}, + "style": { + "box_shadow": ( + f"inset 0 0 0 1px {accent.a[7]}, " + f"inset 0 0 0 1px {tokens.gray.a[11]}" + ), + "color": accent[12], + }, + }, + ], +} diff --git a/tests/units/reflex_components_ui/components/test_badge.py b/tests/units/reflex_components_ui/components/test_badge.py new file mode 100644 index 00000000000..b1763ea93c8 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_badge.py @@ -0,0 +1,162 @@ +"""Tests for reflex_components_ui.components.badge.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +def test_badge_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A badge is a small soft span unless told otherwise.""" + component = rx.ui.badge("New") + assert component.render() == { + "name": '"span"', + "props": ["className:sx_a19a58d0f6_c"], + "children": [{"contents": '"New"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "inline-flex", + "alignItems": "center", + "whiteSpace": "nowrap", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-medium)", + "fontStyle": "normal", + "flexShrink": 0, + "height": "fit-content", + "fontSize": "var(--font-size-1)", + "lineHeight": "var(--line-height-1)", + "letterSpacing": "var(--letter-spacing-1)", + "padding": "calc(var(--space-1) * 0.5) calc(var(--space-1) * 1.5)", + "gap": "calc(var(--space-1) * 1.5)", + "borderRadius": "max(var(--radius-1), var(--radius-full))", + "backgroundColor": "var(--accent-a3)", + "color": "var(--accent-a11)", + } + ] + + +def test_badge_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A solid high-contrast badge with a color and a radius of its own.""" + component = rx.ui.badge( + "New", + variant="solid", + size="3", + color_scheme="ruby", + high_contrast=True, + radius="full", + ) + assert component.render() == { + "name": '"span"', + "props": [ + 'className:sx_4faa730ade_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce' + ], + "children": [{"contents": '"New"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "inline-flex", + "alignItems": "center", + "whiteSpace": "nowrap", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-medium)", + "fontStyle": "normal", + "flexShrink": 0, + "height": "fit-content", + "fontSize": "var(--font-size-2)", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "var(--letter-spacing-2)", + "padding": "var(--space-1) calc(var(--space-2) * 1.25)", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "backgroundColor": { + "default": "var(--accent-12)", + "::selection": "var(--accent-a11)", + }, + "color": {"default": "var(--accent-1)", "::selection": "var(--accent-1)"}, + "--rx-accent-text": "var(--accent-12)", + "--rx-accent-link": "var(--accent-12)", + "--rx-accent-link-line": "underline", + "--rx-accent-link-line-color": "color-mix(in oklab, var(--accent-a6), var(--gray-a6))", + } + ] + + +def test_badge_responsive( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The size can change at a breakpoint, under any variant.""" + component = rx.ui.badge( + "New", + variant="outline", + high_contrast=True, + size=rx.breakpoints(initial="1", md="3"), + ) + assert component.render() == { + "name": '"span"', + "props": ["className:sx_01ef3af011_c"], + "children": [{"contents": '"New"'}], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "inline-flex", + "alignItems": "center", + "whiteSpace": "nowrap", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-medium)", + "fontStyle": "normal", + "flexShrink": 0, + "height": "fit-content", + "fontSize": { + "default": "var(--font-size-1)", + "@media (min-width: 1024px)": "var(--font-size-2)", + }, + "lineHeight": { + "default": "var(--line-height-1)", + "@media (min-width: 1024px)": "var(--line-height-2)", + }, + "letterSpacing": { + "default": "var(--letter-spacing-1)", + "@media (min-width: 1024px)": "var(--letter-spacing-2)", + }, + "padding": { + "default": "calc(var(--space-1) * 0.5) calc(var(--space-1) * 1.5)", + "@media (min-width: 1024px)": "var(--space-1) calc(var(--space-2) * 1.25)", + }, + "gap": { + "default": "calc(var(--space-1) * 1.5)", + "@media (min-width: 1024px)": "revert-layer", + }, + "borderRadius": { + "default": "max(var(--radius-1), var(--radius-full))", + "@media (min-width: 1024px)": "max(var(--radius-2), var(--radius-full))", + }, + "boxShadow": "inset 0 0 0 1px var(--accent-a7), inset 0 0 0 1px var(--gray-a11)", + "color": "var(--accent-12)", + "rowGap": {"@media (min-width: 1024px)": "var(--space-2)"}, + "columnGap": {"@media (min-width: 1024px)": "var(--space-2)"}, + } + ] + + +def test_badge_unknown_variant(ui_plugin: UIPlugin): + """A variant a badge does not have is an error that lists the ones it has.""" + wrong: dict[str, Any] = {"variant": "ghost"} + with pytest.raises(StyleError) as error: + rx.ui.badge("New", **wrong) + assert str(error.value) == ( + 'rx.ui.badge: unknown variant "ghost". ' + 'The values are "solid", "soft", "surface", "outline".' + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index f28b360e89a..122d81e41ec 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -102,6 +102,7 @@ def differences(component: str) -> list[ApiDifference]: def test_every_wave_is_in_the_namespace(): assert COMPONENTS == [ "aspect_ratio", + "badge", "blockquote", "box", "button", From 2593eb3c83f8586b38b30d7cf700019868e5b87e Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:47:38 +0000 Subject: [PATCH 052/204] Add rx.ui.data_list, and props that stand for a CSS property The list hands its orientation down to its items, labels and values in custom properties, which they read with a fallback. The width props of a label are styles at the breakpoints of Radix Themes (props.style_props). Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/allowlist.toml | 7 + .../parity/ui_parity/components/data_list.py | 247 +++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/data_list.py | 104 +++++++ .../src/reflex_components_ui/props.py | 50 ++- .../reflex_components_ui/styles/data_list.py | 186 +++++++++++ .../components/test_data_list.py | 292 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 14 +- .../units/reflex_components_ui/test_props.py | 73 +++++ 9 files changed, 969 insertions(+), 5 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/data_list.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/data_list.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/data_list.py create mode 100644 tests/units/reflex_components_ui/components/test_data_list.py create mode 100644 tests/units/reflex_components_ui/test_props.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 94865a66a63..2290fa42372 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -29,3 +29,10 @@ component = "kbd" check = "style" properties = ["box-shadow"] reason = "The shadow of rx.ui.text.kbd lists the layers of the light and the dark appearance, and the ones of the other appearance are transparent, so one value serves both. It paints the same." + +[[look]] +component = "data_list" +check = "style" +cells = "*orientation-responsive*" +properties = ["flex-direction", "align-items", "grid-template-columns", "grid-column-start", "width"] +reason = "When the orientation of rx.data_list changes at a breakpoint, Radix Themes keeps what the orientation before it declared and the new one does not: the direction of a column on the grid of a horizontal list, and the columns and the baseline alignment of a grid on the items of a vertical one, whose labels and values are then as wide as their text. rx.ui.data_list gives each breakpoint the styles of its orientation alone, so a list that turns vertical is the vertical list: labels and values are as wide as the list. Nothing is drawn differently." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/data_list.py b/packages/reflex-components-ui/parity/ui_parity/components/data_list.py new file mode 100644 index 00000000000..ce08e5d1011 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/data_list.py @@ -0,0 +1,247 @@ +"""The data list: labels beside or above their values, in each size and alignment.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import ACCENTS, PARAGRAPH + +ALIGNS = ["start", "center", "end", "baseline", "stretch"] +ORIENTATIONS = ["horizontal", "vertical"] +SIZES = ["1", "2", "3"] +TRIMS = ["normal", "start", "end", "both"] + +# The props of a cell that are those of the label, and of an item. +_LABEL_PROPS = ("color_scheme", "width", "min_width", "max_width") +_ITEM_PROPS = ("align",) + + +def _values(namespace: Any, content: str) -> list[tuple[str, Any]]: + """Make the labels and the values of a list. + + Args: + namespace: ``rx`` or ``rx.ui``. + content: What the values hold: ``plain`` words, ``long`` text that + wraps, ``rich`` components, or ``tall`` values, which show how an + item is aligned. + + Returns: + Each label with its value. + """ + if content == "long": + return [ + ("Description of the animal", PARAGRAPH), + ("Identifier", "u_2J89JSA4GJ_u_2J89JSA4GJ_u_2J89JSA4GJ_u_2J89JSA4GJ"), + ] + if content == "rich": + return [ + ("Status", rx.badge("Authorized", color_scheme="jade", radius="full")), + ("ID", namespace.code("u_2J89JSA4GJ")), + ("Email", namespace.link("fox@example.com", href="#mail")), + ("Name", namespace.text("Quick Brown Fox", weight="bold")), + ] + if content == "tall": + return [ + ( + "Name", + rx.el.div("Fox", style={"height": "40px", "outline": "1px solid"}), + ), + ( + "Den", + rx.el.div("Hill", style={"height": "40px", "outline": "1px solid"}), + ), + ( + "Food", + rx.el.div("Hens", style={"height": "40px", "outline": "1px solid"}), + ), + ] + return [("Name", "Quick Brown Fox"), ("Email", "fox@example.com"), ("Den", "Hill")] + + +def _data_list(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a data list, with the props of a cell on the part they belong to. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``content`` names what the list holds. + + Returns: + The list. + """ + props = dict(props) + content = props.pop("content", "plain") + label = {name: props.pop(name) for name in _LABEL_PROPS if name in props} + item = {name: props.pop(name) for name in _ITEM_PROPS if name in props} + data_list = namespace.data_list + return data_list.root( + *[ + data_list.item( + data_list.label(name, **label), data_list.value(value), **item + ) + for name, value in _values(namespace, content) + ], + **props, + ) + + +MATRIX = Matrix( + component="data_list", + render=_data_list, + cross={"orientation": ORIENTATIONS, "size": SIZES}, + sweep={ + "trim": TRIMS, + "align": ALIGNS, + "content": ["long", "rich", "tall"], + "color_scheme": ACCENTS, + "width": ["60px", "200px"], + "min_width": ["0px", "180px"], + "max_width": ["30px"], + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"orientation": ORIENTATIONS, "trim": TRIMS, "size": ["1", "3"]}, + {"orientation": ORIENTATIONS, "align": ALIGNS, "content": ["tall", "long"]}, + {"orientation": ORIENTATIONS, "content": ["long", "rich", "tall"]}, + {"orientation": ORIENTATIONS, "content": ["rich"], "size": SIZES}, + { + "orientation": ORIENTATIONS, + "min_width": ["0px", "180px"], + "width": ["60px"], + }, + { + "orientation": ORIENTATIONS, + "color_scheme": ["ruby", "gray"], + "appearance": [DARK], + }, + {"content": ["rich"], "appearance": [DARK]}, + { + "orientation": { + "responsive": rx.breakpoints(initial="vertical", sm="horizontal") + }, + "size": {"responsive": rx.breakpoints(initial="1", xs="3", md="2")}, + "trim": {"responsive": rx.breakpoints(initial="both", sm="start")}, + "align": {"responsive": rx.breakpoints(initial="center", md="end")}, + "width": {"responsive": rx.breakpoints(initial="80px", md="160px")}, + "content": ["plain", "tall"], + "viewport": [519, 520, 767, 768, 1023, 1024, 1280], + }, + { + "orientation": { + "responsive-vertical": rx.breakpoints( + initial="horizontal", sm="vertical" + ) + }, + "content": ["plain", "long"], + "viewport": [767, 768], + }, + ], + stage=(380, 260), + parts={ + "item": "dl > div", + "label": "dt", + "value": "dd", + "last item": "dl > div:last-child", + "last label": "dl > div:last-child dt", + "last value": "dl > div:last-child dd", + }, + properties=( + *Matrix.__dataclass_fields__["properties"].default, + "grid-template-columns", + "grid-column-start", + "grid-column-end", + "overflow-wrap", + ), + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="data_list", + render=lambda namespace: namespace.data_list.root( + namespace.data_list.item( + namespace.data_list.label("Name", id="name-label"), + namespace.data_list.value("Quick Brown Fox", id="name-value"), + id="name", + ), + namespace.data_list.item( + namespace.data_list.label("Email", id="email-label"), + namespace.data_list.value( + rx.el.a("fox@example.com", href="#mail", id="mail"), + id="email-value", + ), + ), + id="list", + ), +) + + +@CONTRACT.step( + "is a description list of terms and details in the server render", on=SERVER +) +def _server_render(run: Run) -> None: + root = run.server.element("list") + assert (root.tag, root.text) == ("dl", "NameQuick Brown FoxEmailfox@example.com") + item = run.server.element("name") + assert (item.tag, item.text) == ("div", "NameQuick Brown Fox") + label = run.server.element("name-label") + assert (label.tag, label.text) == ("dt", "Name") + value = run.server.element("name-value") + assert (value.tag, value.text) == ("dd", "Quick Brown Fox") + + +def _laid_out(run: Run) -> None: + """Check that each label is beside its value, and the labels are one column. + + Args: + run: The run of the step. + """ + name, value, email, mail = ( + run.page.locator(f"#{element}").evaluate( + "element => element.getBoundingClientRect().toJSON()" + ) + for element in ("name-label", "name-value", "email-label", "email-value") + ) + # The implicit width of a label, then the gap of the size. + assert (name["x"], name["width"]) == (email["x"], 120) + assert value["x"] == mail["x"] == name["x"] + 120 + 16 + assert email["y"] > name["y"] + + +@CONTRACT.step( + "lays out labels beside values with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#list").inner_text() == ( + "Name\nQuick Brown Fox\nEmail\nfox@example.com" + ) + _laid_out(run) + + +@CONTRACT.step("lays out labels beside values after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + _laid_out(run) + + +@CONTRACT.step("has the roles of terms and their definitions", on=HYDRATED) +def _roles(run: Run) -> None: + terms = run.page.get_by_role("term") + assert [terms.nth(index).get_attribute("id") for index in range(2)] == [ + "name-label", + "email-label", + ] + definitions = run.page.get_by_role("definition") + assert [definitions.nth(index).get_attribute("id") for index in range(2)] == [ + "name-value", + "email-value", + ] + + +@CONTRACT.step("Tab reaches what a value holds", on=HYDRATED) +def _tab(run: Run) -> None: + run.page.keyboard.press("Tab") + assert run.page.evaluate("document.activeElement.id") == "mail" 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 81151348183..f817837518f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -10,6 +10,7 @@ "components.aspect_ratio": ["aspect_ratio"], "components.badge": ["badge"], "components.button": ["button"], + "components.data_list": ["data_list"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], "components.separator": ["divider", "separator"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/data_list.py b/packages/reflex-components-ui/src/reflex_components_ui/components/data_list.py new file mode 100644 index 00000000000..80dbd7aa019 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/data_list.py @@ -0,0 +1,104 @@ +"""A data list: labels and their values.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.props import style_props +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.data_list import ( + DATA_LIST_ITEM, + DATA_LIST_LABEL, + DATA_LIST_ROOT, + DATA_LIST_VALUE, +) +from reflex_components_ui.themes import LiteralAccentColor + + +class DataListRoot(UIComponent): + """Root element for a DataList component.""" + + tag = "dl" + + styles: ClassVar[ComponentStyles] = DATA_LIST_ROOT + + orientation: Var[Responsive[Literal["horizontal", "vertical"]]] = field( + doc='The orientation of the data list item: "horizontal" | "vertical"' + ) + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc='The size of the data list item: "1" | "2" | "3"' + ) + + trim: Var[Responsive[Literal["normal", "start", "end", "both"]]] = field( + doc="Trims the leading whitespace from the start or end of the text." + ) + + +class DataListItem(UIComponent): + """An item in the DataList component.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = DATA_LIST_ITEM + + align: Var[Responsive[Literal["start", "center", "end", "baseline", "stretch"]]] = ( + field(doc="The alignment of the data list item within its container.") + ) + + +class DataListLabel(UIComponent): + """A label in the DataList component.""" + + tag = "dt" + + styles: ClassVar[ComponentStyles] = DATA_LIST_LABEL + + width: Var[Responsive[str]] = field(doc="The width of the component") + + min_width: Var[Responsive[str]] = field(doc="The minimum width of the component") + + max_width: Var[Responsive[str]] = field(doc="The maximum width of the component") + + color_scheme: Var[LiteralAccentColor] = field( + doc="The color scheme for the DataList component." + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a label, as wide as its width props say. + + Args: + *children: The children of the label. + **props: The props of the label. + + Returns: + The label. + """ + style_props("rx.ui.data_list.label", props, ("width", "min_width", "max_width")) + return super().create(*children, **props) + + +class DataListValue(UIComponent): + """A value in the DataList component.""" + + tag = "dd" + + styles: ClassVar[ComponentStyles] = DATA_LIST_VALUE + + +class DataList(ComponentNamespace): + """DataList components namespace.""" + + root = staticmethod(DataListRoot.create) + item = staticmethod(DataListItem.create) + label = staticmethod(DataListLabel.create) + value = staticmethod(DataListValue.create) + + +data_list = DataList() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/props.py b/packages/reflex-components-ui/src/reflex_components_ui/props.py index 5bbad7fcd26..cc59aeee364 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/props.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/props.py @@ -2,9 +2,57 @@ from __future__ import annotations -from typing import Literal +from collections.abc import Mapping +from typing import Any, Literal + +from reflex_base.vars.base import LiteralVar + +from reflex_components_ui.style.lower import PROP_BREAKPOINTS, prop_breakpoint LiteralAlign = Literal["start", "center", "end", "baseline", "stretch"] LiteralJustify = Literal["start", "center", "end", "between"] LiteralSpacing = Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] LiteralVariant = Literal["classic", "solid", "soft", "surface", "outline", "ghost"] + + +def style_props(name: str, props: dict[str, Any], names: tuple[str, ...]) -> None: + """Move the props that stand for a CSS property into the style of an element. + + Radix Themes has such props (``width``, ``min_width``...) beside the ones + that choose among listed values. A value per breakpoint applies at the + breakpoints of Radix Themes, as every prop does, and the ``style`` of the + element wins over them. + + Args: + name: The display name of the component, for error messages. + props: The props a component is created with, changed in place. + names: The props to move: each one is named after its CSS property. + """ + style: dict[str, Any] = {} + for prop in names: + value = props.pop(prop, None) + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + value = value._var_value + if isinstance(value, Mapping): + for breakpoint, item in value.items(): + condition = prop_breakpoint(name, prop, breakpoint) + if condition == "default": + style[prop] = item + else: + style.setdefault(condition, {})[prop] = item + elif value is not None: + style[prop] = value + if not style: + return + # In the order of the breakpoints, whatever the order they are given in. + ordered = {key: item for key, item in style.items() if key in names} + ordered.update( + (media, style[media]) for media in PROP_BREAKPOINTS.values() if media in style + ) + written = props.get("style") + if written is None: + props["style"] = ordered + elif isinstance(written, (list, tuple)): + props["style"] = [ordered, *written] + else: + props["style"] = [ordered, written] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/data_list.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/data_list.py new file mode 100644 index 00000000000..8e3a8a99992 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/data_list.py @@ -0,0 +1,186 @@ +"""The look of a data list: labels beside, or above, their values.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.text import TEXT_BASE +from reflex_components_ui.styles.typography import ACCENT_SCOPE, SIZE + +# What the list tells its items, labels and values, which Radix Themes +# selects below the classes of the list: how an item lays out its label and +# its value, how far a value may reach out of its row, and how narrow a label +# may be. +_ITEM_DISPLAY = "--rx-data-list-item-display" +_ITEM_DIRECTION = "--rx-data-list-item-direction" +_ITEM_COLUMNS = "--rx-data-list-item-columns" +_ITEM_SPAN = "--rx-data-list-item-span" +_ITEM_ALIGN = "--rx-data-list-item-align" +_ITEM_GAP = "--rx-data-list-item-gap" +_VALUE_TRIM = "--rx-data-list-value-trim" +_LABEL_MIN_WIDTH = "--rx-data-list-label-min-width" + +# The margins of the value of an item, as Radix Themes names them. +_VALUE_TOP = "--data-list-value-margin-top" +_VALUE_BOTTOM = "--data-list-value-margin-bottom" + +_GAP = { + "1": tokens.space[3], + "2": tokens.space[4], + "3": f"calc({tokens.space[4]} * 1.25)", +} + +_TRIM = f"var({_VALUE_TRIM}, 0px)" + + +def _value_margins(start: str, end: str, first: str, last: str) -> dict[str, Any]: + """Make the margins of the value of an item. + + Args: + start: The margin above the value. + end: The margin below it. + first: The margin above the value of the first item. + last: The margin below the value of the last item. + + Returns: + The custom properties the value reads its margins from. + """ + return { + _VALUE_TOP: {"default": start, ":first-child": first}, + _VALUE_BOTTOM: {"default": end, ":last-child": last}, + } + + +# A value reaches out of its row where the alignment lets it, and out of the +# list only when it is centered: its two margins are then always equal. +_ALIGN: dict[str, tuple[str, dict[str, Any]]] = { + "baseline": ("baseline", _value_margins(_TRIM, _TRIM, "0px", "0px")), + "start": ("flex-start", _value_margins("0px", _TRIM, "0px", "0px")), + "center": ("center", _value_margins(_TRIM, _TRIM, _TRIM, _TRIM)), + "end": ("flex-end", _value_margins(_TRIM, "0px", "0px", "0px")), + "stretch": ("stretch", _value_margins("0px", "0px", "0px", "0px")), +} + +# Zero-width joiner to establish a baseline: lets what a label or a value +# holds align with the text of the other. +_BASELINE: dict[str, Any] = {"_before": {"content": "'‍'"}} + +_LEADING_TRIM_START = ( + f"calc({tokens.default.leading_trim_start} - var(--line-height) / 2)" +) +_LEADING_TRIM_END = f"calc({tokens.default.leading_trim_end} - var(--line-height) / 2)" + +DATA_LIST_ROOT: ComponentStyles = { + "base": { + **TEXT_BASE, + "overflow_wrap": "anywhere", + "font_family": tokens.default.font_family, + "font_style": "normal", + "text_align": "start", + }, + "variants": { + "size": { + # The longhands: a shorthand is only split when its value is a + # token alone, and each size has to set the same properties. + size: unchecked({**SIZE[size], "row_gap": gap, "column_gap": gap}) + for size, gap in _GAP.items() + }, + "orientation": { + "vertical": unchecked({ + "display": "flex", + "flex_direction": "column", + _ITEM_DISPLAY: "flex", + _ITEM_DIRECTION: "column", + _ITEM_COLUMNS: "none", + _ITEM_SPAN: "auto", + _ITEM_ALIGN: "normal", + _ITEM_GAP: tokens.space[1], + _VALUE_TRIM: "0px", + _LABEL_MIN_WIDTH: "0px", + }), + "horizontal": unchecked({ + "display": "grid", + "grid_template_columns": "auto 1fr", + _ITEM_DISPLAY: "grid", + _ITEM_DIRECTION: "row", + _ITEM_COLUMNS: "subgrid", + _ITEM_SPAN: "span 2", + _ITEM_ALIGN: "baseline", + # None: an item then has the gap of the list, whatever sets it. + _ITEM_GAP: "initial", + _VALUE_TRIM: "-0.25em", + _LABEL_MIN_WIDTH: "120px", + }), + }, + # The margins are those of the first and of the last item. + "trim": { + "normal": unchecked({ + "--leading-trim-start": "initial", + "--leading-trim-end": "initial", + }), + "start": unchecked({ + "--leading-trim-start": _LEADING_TRIM_START, + "--leading-trim-end": "initial", + }), + "end": unchecked({ + "--leading-trim-start": "initial", + "--leading-trim-end": _LEADING_TRIM_END, + }), + "both": unchecked({ + "--leading-trim-start": _LEADING_TRIM_START, + "--leading-trim-end": _LEADING_TRIM_END, + }), + }, + }, + "defaults": {"size": "2", "orientation": "horizontal"}, +} + +DATA_LIST_ITEM: ComponentStyles = { + "base": unchecked({ + "display": f"var({_ITEM_DISPLAY}, block)", + "flex_direction": f"var({_ITEM_DIRECTION}, row)", + "grid_template_columns": f"var({_ITEM_COLUMNS}, none)", + "grid_column_start": f"var({_ITEM_SPAN}, auto)", + "align_items": f"var({_ITEM_ALIGN}, normal)", + "row_gap": f"var({_ITEM_GAP}, inherit)", + "column_gap": f"var({_ITEM_GAP}, inherit)", + "margin_top": {":first-child": "var(--leading-trim-start)"}, + "margin_bottom": {":last-child": "var(--leading-trim-end)"}, + **_ALIGN["baseline"][1], + }), + "variants": { + "align": { + align: unchecked({"align_items": align_items, **margins}) + for align, (align_items, margins) in _ALIGN.items() + }, + }, +} + +DATA_LIST_LABEL: ComponentStyles = { + "base": unchecked({ + "display": "flex", + "color": tokens.gray.a[11], + "min_width": f"var({_LABEL_MIN_WIDTH})", + **_BASELINE, + }), + "variants": { + "color_scheme": { + "true": unchecked({**ACCENT_SCOPE, "color": tokens.accent.a[11]}), + }, + }, +} + +DATA_LIST_VALUE: ComponentStyles = { + "base": unchecked({ + "display": "flex", + "margin_left": "0", + "margin_right": "0", + "margin_top": f"var({_VALUE_TOP}, 0px)", + "margin_bottom": f"var({_VALUE_BOTTOM}, 0px)", + # A value can be truncated. + "min_width": "0px", + **_BASELINE, + }), +} diff --git a/tests/units/reflex_components_ui/components/test_data_list.py b/tests/units/reflex_components_ui/components/test_data_list.py new file mode 100644 index 00000000000..a97932d9bc0 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_data_list.py @@ -0,0 +1,292 @@ +"""Tests for reflex_components_ui.components.data_list.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + +TRIM = "var(--rx-data-list-value-trim, 0px)" + +ROOT_TEXT = { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "overflowWrap": "anywhere", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", +} + +ITEM_LAYOUT = { + "display": "var(--rx-data-list-item-display, block)", + "flexDirection": "var(--rx-data-list-item-direction, row)", + "gridTemplateColumns": "var(--rx-data-list-item-columns, none)", + "gridColumnStart": "var(--rx-data-list-item-span, auto)", +} + +ITEM_SPACE = { + "rowGap": "var(--rx-data-list-item-gap, inherit)", + "columnGap": "var(--rx-data-list-item-gap, inherit)", + "marginTop": {":first-child": "var(--leading-trim-start)"}, + "marginBottom": {":last-child": "var(--leading-trim-end)"}, +} + +VALUE = { + "display": "flex", + "marginLeft": "0", + "marginRight": "0", + "marginTop": "var(--data-list-value-margin-top, 0px)", + "marginBottom": "var(--data-list-value-margin-bottom, 0px)", + "minWidth": "0px", + "content": {"::before": "'‍'"}, +} + + +def test_data_list_plain( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A data list is a grid of two columns, which its items take over.""" + data_list = rx.ui.data_list + component = data_list.root( + data_list.item(data_list.label("Name"), data_list.value("Fox")) + ) + assert component.render() == { + "name": '"dl"', + "props": ["className:sx_b3965b5abf_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_0d6d130655_c"], + "children": [ + { + "name": '"dt"', + "props": ["className:sx_dbeafabcc8_c"], + "children": [{"contents": '"Name"'}], + }, + { + "name": '"dd"', + "props": ["className:sx_01ce835e4e_c"], + "children": [{"contents": '"Fox"'}], + }, + ], + } + ], + } + assert declared_styles(component) == [ + { + **ROOT_TEXT, + "fontSize": "var(--font-size-2)", + "--line-height": "var(--line-height-2)", + "--letter-spacing": "var(--letter-spacing-2)", + "rowGap": "var(--space-4)", + "columnGap": "var(--space-4)", + "display": "grid", + "gridTemplateColumns": "auto 1fr", + "--rx-data-list-item-display": "grid", + "--rx-data-list-item-direction": "row", + "--rx-data-list-item-columns": "subgrid", + "--rx-data-list-item-span": "span 2", + "--rx-data-list-item-align": "baseline", + "--rx-data-list-item-gap": "initial", + "--rx-data-list-value-trim": "-0.25em", + "--rx-data-list-label-min-width": "120px", + }, + { + **ITEM_LAYOUT, + "alignItems": "var(--rx-data-list-item-align, normal)", + **ITEM_SPACE, + "--data-list-value-margin-top": {"default": TRIM, ":first-child": "0px"}, + "--data-list-value-margin-bottom": {"default": TRIM, ":last-child": "0px"}, + }, + { + "display": "flex", + "color": "var(--gray-a11)", + "minWidth": "var(--rx-data-list-label-min-width)", + "content": {"::before": "'‍'"}, + }, + VALUE, + ] + + +def test_data_list_props( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """Each part has its props, and the style of a label wins over its width props.""" + data_list = rx.ui.data_list + component = data_list.root( + data_list.item( + data_list.label( + "Name", + color_scheme="ruby", + width="80px", + min_width=rx.breakpoints(initial="0px", md="120px"), + max_width="50%", + style={"width": "90px"}, + ), + data_list.value("Fox"), + align=rx.breakpoints(initial="center", sm="stretch"), + ), + orientation="vertical", + size="3", + trim="both", + ) + assert component.render() == { + "name": '"dl"', + "props": ["className:sx_2832f8b266_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_b7d48fc98e_c"], + "children": [ + { + "name": '"dt"', + "props": [ + 'className:sx_8bfbd8b1bf_c + " " + reflexUIClasses_e201574881' + ], + "children": [{"contents": '"Name"'}], + }, + { + "name": '"dd"', + "props": ["className:sx_01ce835e4e_c"], + "children": [{"contents": '"Fox"'}], + }, + ], + } + ], + } + assert declared_styles(component) == [ + { + **ROOT_TEXT, + "fontSize": "var(--font-size-3)", + "--line-height": "var(--line-height-3)", + "--letter-spacing": "var(--letter-spacing-3)", + "rowGap": "calc(var(--space-4) * 1.25)", + "columnGap": "calc(var(--space-4) * 1.25)", + "display": "flex", + "flexDirection": "column", + "--rx-data-list-item-display": "flex", + "--rx-data-list-item-direction": "column", + "--rx-data-list-item-columns": "none", + "--rx-data-list-item-span": "auto", + "--rx-data-list-item-align": "normal", + "--rx-data-list-item-gap": "var(--space-1)", + "--rx-data-list-value-trim": "0px", + "--rx-data-list-label-min-width": "0px", + "--leading-trim-start": ( + "calc(var(--default-leading-trim-start) - var(--line-height) / 2)" + ), + "--leading-trim-end": ( + "calc(var(--default-leading-trim-end) - var(--line-height) / 2)" + ), + }, + { + **ITEM_LAYOUT, + "alignItems": {"default": "center", "@media (min-width: 768px)": "stretch"}, + **ITEM_SPACE, + "--data-list-value-margin-top": { + "default": TRIM, + ":first-child": TRIM, + "@media (min-width: 768px)": {"default": "0px", ":first-child": "0px"}, + }, + "--data-list-value-margin-bottom": { + "default": TRIM, + ":last-child": TRIM, + "@media (min-width: 768px)": {"default": "0px", ":last-child": "0px"}, + }, + }, + { + "display": "flex", + "color": "var(--accent-a11)", + "minWidth": {"default": "0px", "@media (min-width: 1024px)": "120px"}, + "content": {"::before": "'‍'"}, + "--rx-accent-text": "var(--accent-12)", + "--rx-accent-link": "var(--accent-12)", + "--rx-accent-link-line": "underline", + "--rx-accent-link-line-color": ( + "color-mix(in oklab, var(--accent-a6), var(--gray-a6))" + ), + "maxWidth": "50%", + "width": "90px", + }, + VALUE, + ] + + +def test_data_list_responsive( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The props of the list change at a breakpoint, and what it tells its parts with them.""" + component = rx.ui.data_list.root( + orientation=rx.breakpoints(initial="vertical", sm="horizontal"), + size=rx.breakpoints(initial="1", lg="3"), + trim=rx.breakpoints(initial="start", xs="normal"), + ) + assert component.render() == { + "name": '"dl"', + "props": ["className:sx_a6a26de24f_c"], + "children": [], + } + wide, large = "@media (min-width: 768px)", "@media (min-width: 1280px)" + assert declared_styles(component) == [ + { + **ROOT_TEXT, + "fontSize": {"default": "var(--font-size-1)", large: "var(--font-size-3)"}, + "--line-height": { + "default": "var(--line-height-1)", + large: "var(--line-height-3)", + }, + "--letter-spacing": { + "default": "var(--letter-spacing-1)", + large: "var(--letter-spacing-3)", + }, + "rowGap": { + "default": "var(--space-3)", + large: "calc(var(--space-4) * 1.25)", + }, + "columnGap": { + "default": "var(--space-3)", + large: "calc(var(--space-4) * 1.25)", + }, + "display": {"default": "flex", wide: "grid"}, + "flexDirection": {"default": "column", wide: "revert-layer"}, + "--rx-data-list-item-display": {"default": "flex", wide: "grid"}, + "--rx-data-list-item-direction": {"default": "column", wide: "row"}, + "--rx-data-list-item-columns": {"default": "none", wide: "subgrid"}, + "--rx-data-list-item-span": {"default": "auto", wide: "span 2"}, + "--rx-data-list-item-align": {"default": "normal", wide: "baseline"}, + "--rx-data-list-item-gap": {"default": "var(--space-1)", wide: "initial"}, + "--rx-data-list-value-trim": {"default": "0px", wide: "-0.25em"}, + "--rx-data-list-label-min-width": {"default": "0px", wide: "120px"}, + "--leading-trim-start": { + "default": ( + "calc(var(--default-leading-trim-start) - var(--line-height) / 2)" + ), + "@media (min-width: 520px)": "initial", + }, + "--leading-trim-end": "initial", + "gridTemplateColumns": {wide: "auto 1fr"}, + } + ] + + +def test_data_list_unknown_values(ui_plugin: UIPlugin): + """A value a prop does not take names the component and the values it takes.""" + with pytest.raises(StyleError) as error: + rx.ui.data_list.root(orientation="diagonal") # pyright: ignore[reportArgumentType] + assert str(error.value) == ( + 'rx.ui.data_list_root: unknown orientation "diagonal". ' + 'The values are "horizontal", "vertical".' + ) + with pytest.raises(StyleError) as error: + rx.ui.data_list.item(align="middle") # pyright: ignore[reportArgumentType] + assert str(error.value) == ( + 'rx.ui.data_list_item: unknown align "middle". ' + 'The values are "start", "center", "end", "baseline", "stretch".' + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 122d81e41ec..89477fb8e8e 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -50,8 +50,8 @@ def component_names() -> list[str]: """List the names of rx.ui that create a component. A theme of the plugin and the design tokens are no components. A - namespace is its own name, then each of its members: ``text``, - ``text.em``. + namespace is its own name when it is called, then each of its members: + ``text``, ``text.em``. Returns: The names, sorted. @@ -62,7 +62,9 @@ def component_names() -> list[str]: if isinstance(value, types.MethodType): names.append(name) elif isinstance(value, ComponentNamespace): - names.append(name) + # A namespace that is not called has members only. + if callable(value): + names.append(name) names.extend(f"{name}.{member}" for member in members(value)) return sorted(names) @@ -109,6 +111,10 @@ def test_every_wave_is_in_the_namespace(): "center", "code", "container", + "data_list.item", + "data_list.label", + "data_list.root", + "data_list.value", "divider", "flex", "grid", @@ -140,7 +146,7 @@ def test_every_wave_is_in_the_namespace(): ] -@pytest.mark.parametrize("namespace", ["list", "text"]) +@pytest.mark.parametrize("namespace", ["data_list", "list", "text"]) def test_namespace_has_the_members_of_its_radix_counterpart(namespace: str): assert members(getattr(reflex_components_ui, namespace)) == members( getattr(rx, namespace) diff --git a/tests/units/reflex_components_ui/test_props.py b/tests/units/reflex_components_ui/test_props.py new file mode 100644 index 00000000000..af3b6b89096 --- /dev/null +++ b/tests/units/reflex_components_ui/test_props.py @@ -0,0 +1,73 @@ +"""Tests for reflex_components_ui.props.""" + +from typing import Any + +import pytest +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_ui.props import style_props +from reflex_components_ui.style import StyleError + +import reflex as rx + +NAMES = ("width", "min_width") + + +def test_style_props_moves_the_props_before_the_style(): + """A prop named after a CSS property is a style the element's own wins over.""" + props: dict[str, Any] = { + "width": "10px", + "min_width": LiteralVar.create("5px"), + "id": "label", + "style": {"width": "20px"}, + } + style_props("rx.ui.thing", props, NAMES) + assert props == { + "id": "label", + "style": [{"width": "10px", "min_width": "5px"}, {"width": "20px"}], + } + props = {"width": "10px", "style": [{"color": "red"}, {"color": "blue"}]} + style_props("rx.ui.thing", props, NAMES) + assert props == {"style": [{"width": "10px"}, {"color": "red"}, {"color": "blue"}]} + + +def test_style_props_reads_a_value_per_breakpoint_of_radix_themes(): + """The breakpoints are those of every prop, in their order.""" + props: dict[str, Any] = { + "width": rx.breakpoints(lg="40px", initial="10px", xs="20px"), + "min_width": rx.breakpoints(xs="5px"), + } + style_props("rx.ui.thing", props, NAMES) + assert props == { + "style": { + "width": "10px", + "@media (min-width: 520px)": {"width": "20px", "min_width": "5px"}, + "@media (min-width: 1280px)": {"width": "40px"}, + } + } + assert list(props["style"]) == [ + "width", + "@media (min-width: 520px)", + "@media (min-width: 1280px)", + ] + + +def test_style_props_keeps_a_value_bound_to_state_and_leaves_the_rest(): + """A Var is a style like any other, and props that are not given add nothing.""" + width = Var("state.width", _var_type=str) + props: dict[str, Any] = {"width": width, "max_width": "1px"} + style_props("rx.ui.thing", props, NAMES) + assert props == {"max_width": "1px", "style": {"width": width}} + props = {"id": "label"} + style_props("rx.ui.thing", props, NAMES) + assert props == {"id": "label"} + + +def test_style_props_rejects_a_key_that_is_no_breakpoint(): + """A value under anything but a breakpoint is an error that names them.""" + with pytest.raises(StyleError) as error: + style_props("rx.ui.thing", {"width": {"huge": "1px"}}, NAMES) + assert str(error.value) == ( + 'rx.ui.thing: prop "width" is given a value under "huge", which is not ' + 'a breakpoint. Use "initial", "xs", "sm", "md", "lg" or "xl", or set a ' + "style, which takes any media query." + ) From d7d64c51cb1ed4482b4e51e2771f5e129608b94b Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 17:48:04 +0000 Subject: [PATCH 053/204] Add rx.ui.progress, and let a style play several animations together A progress bar is a div with the role, the ARIA attributes and the data attributes Radix renders, around an indicator that reads the value from a custom property: a value bound to state moves it without a render of its own. keyframes() takes several sets of frames, which a style plays together as the comma-separated list of animation_name. Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/ui_parity/components/progress.py | 315 +++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/progress.py | 232 +++++++++++ .../src/reflex_components_ui/style/emit.py | 24 +- .../src/reflex_components_ui/style/lower.py | 82 ++-- .../reflex_components_ui/styles/progress.py | 204 ++++++++++ .../components/test_button.py | 4 +- .../components/test_progress.py | 361 ++++++++++++++++++ .../components/test_spinner.py | 4 +- .../reflex_components_ui/style/test_emit.py | 55 ++- .../reflex_components_ui/style/test_lower.py | 112 ++---- .../reflex_components_ui/test_api_parity.py | 1 + 12 files changed, 1278 insertions(+), 117 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/progress.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/progress.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/progress.py create mode 100644 tests/units/reflex_components_ui/components/test_progress.py diff --git a/packages/reflex-components-ui/parity/ui_parity/components/progress.py b/packages/reflex-components-ui/parity/ui_parity/components/progress.py new file mode 100644 index 00000000000..70bdc2d14a4 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/progress.py @@ -0,0 +1,315 @@ +"""The progress bar: every value, variant and size, and a bar without a value.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, LIGHT, Matrix +from ui_parity.samples import ACCENTS + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +RADII = ["none", "small", "medium", "large", "full"] + +# A bar without a value: the prop is left out. +INDETERMINATE = {"indeterminate": None} + +INDICATOR = "[role='progressbar'] > div" + + +def _progress(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a progress bar, without the value of a cell that has none. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The progress bar. + """ + return namespace.progress(**{ + name: value for name, value in props.items() if value is not None + }) + + +MATRIX = Matrix( + component="progress", + render=_progress, + base={"value": 40}, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + # Whole and fractional widths, the ends, and a value over the + # maximum, which is no value: the bar is indeterminate. + "value": { + **INDETERMINATE, + **{str(value): value for value in (0, 1, 25, 33, 50, 75, 99, 100, 150)}, + }, + "max": [40, 60, 250], + "color_scheme": ACCENTS, + "high_contrast": [True], + "radius": RADII, + "fill_color": ["crimson"], + "duration": ["2s"], + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + # The frame an indeterminate bar is frozen on: grown to the whole + # track, under its shine. + { + "value": INDETERMINATE, + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + {"value": INDETERMINATE, "size": SIZES, "radius": ["none", "full"]}, + {"value": INDETERMINATE, "duration": ["2s"], "fill_color": ["crimson"]}, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + { + "variant": VARIANTS, + "fill_color": ["crimson"], + "high_contrast": [False, True], + }, + {"size": SIZES, "radius": RADII}, + {"value": [3, 97], "radius": ["full"], "size": SIZES}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100, 1280], + }, + ], + stage=(200, 48), + parts={"indicator": INDICATOR}, + # The threshold is not held to zero, the tolerance is. At a threshold of + # zero 127 of the 139 cells are equal pixel for pixel. In the others one + # channel is off by one step, by where the frame is on the page: the + # translucent layers of a track (the ring of its shadow over its gray, + # the gradient the soft variant blends in) are rounded one way or the + # other, the same props being equal in another frame and at another + # viewport. + tolerance=0, +) + + +class ProgressState(rx.State): + """How far the bar of the contract is.""" + + done: rx.Field[int] = rx.field(20) + + @rx.event + def advance(self): + """Move the bar on.""" + self.done = 80 + + +CONTRACT = Contract( + component="progress", + render=lambda namespace: namespace.box( + namespace.progress(value=30, id="some"), + namespace.progress(value=5, max=5, id="all"), + namespace.progress(id="waiting"), + namespace.progress(value=ProgressState.done, id="bound"), + rx.el.button("Advance", id="advance", on_click=ProgressState.advance), + width="300px", + ), +) + +# What an indeterminate bar plays, as `getAnimations()` reports it: the +# indicator grows, fades and pulses, and a shine crosses it. +ANIMATIONS = """element => element.getAnimations({subtree: true}).map(animation => { + const {delay, duration, iterations, fill, direction, easing} = + animation.effect.getTiming(); + return { + on: animation.effect.pseudoElement, + timing: {delay, duration, iterations, fill, direction, easing}, + frames: animation.effect.getKeyframes().map( + ({computedOffset, composite, ...frame}) => frame + ), + }; +})""" + +_GROW = [ + {"offset": 0, "easing": "ease", "transform": "scaleX(0.01)"}, + {"offset": 0.2, "easing": "ease", "transform": "scaleX(0.1)"}, + {"offset": 0.3, "easing": "ease", "transform": "scaleX(0.6)"}, + {"offset": 0.4, "easing": "ease", "transform": "scaleX(0.9)"}, + {"offset": 0.5, "easing": "ease", "transform": "scaleX(0.9)"}, + {"offset": 1, "easing": "ease", "transform": "scaleX(1)"}, +] + +# The blue of the theme: its track color, and the step it fades to. +_TRACK = "rgb(0, 144, 255)" +_FADED = "rgb(142, 200, 246)" + +EXPECTED_ANIMATIONS = [ + { + "on": None, + "timing": { + "delay": 0, + "duration": 5000, + "iterations": 1, + "fill": "both", + "direction": "normal", + "easing": "linear", + }, + "frames": _GROW, + }, + { + "on": None, + "timing": { + "delay": 10000, + "duration": 2500, + "iterations": 1, + "fill": "none", + "direction": "normal", + "easing": "linear", + }, + "frames": [ + {"offset": 0, "easing": "ease", "backgroundColor": _TRACK}, + {"offset": 1, "easing": "ease", "backgroundColor": _FADED}, + ], + }, + { + "on": None, + "timing": { + "delay": 12500, + "duration": 5000, + "iterations": float("inf"), + "fill": "none", + "direction": "alternate", + "easing": "linear", + }, + "frames": [ + {"offset": 0, "easing": "ease", "backgroundColor": _FADED}, + {"offset": 1, "easing": "ease", "backgroundColor": _TRACK}, + ], + }, + { + "on": "::after", + "timing": { + "delay": 10000, + "duration": 5000, + "iterations": float("inf"), + "fill": "backwards", + "direction": "normal", + "easing": "linear", + }, + "frames": [ + {"offset": 0, "easing": "ease", "transform": "translate(-100%)"}, + {"offset": 1, "easing": "ease", "transform": "translate(0%)"}, + ], + }, +] + + +# How much of its track the indicator of a bar covers, in thousandths. +COVERED = ( + "(element => Math.round(1000" + " * element.firstElementChild.getBoundingClientRect().width" + " / element.getBoundingClientRect().width))" +) + + +def _covered(run: Run, bar: str) -> int: + """Read how much of its track the indicator of a bar covers. + + Args: + run: The run, on a page. + bar: The id of the bar. + + Returns: + The width of the indicator over the width of the bar, in thousandths. + """ + return run.page.locator(f"#{bar}").evaluate(COVERED) + + +@CONTRACT.step("is a progressbar with its value in the server render", on=SERVER) +def _server_render(run: Run) -> None: + some = run.server.element("some") + assert some.tag == "div" + assert { + name: value + for name, value in some.attributes.items() + if name.startswith(("aria-", "data-", "role")) + } == { + "aria-valuemax": "100", + "aria-valuemin": "0", + "aria-valuenow": "30", + "aria-valuetext": "30%", + "role": "progressbar", + "data-state": "loading", + "data-value": "30", + "data-max": "100", + } + done = run.server.element("all").attributes + assert (done["aria-valuenow"], done["aria-valuemax"], done["data-state"]) == ( + "5", + "5", + "complete", + ) + waiting = run.server.element("waiting").attributes + assert "aria-valuenow" not in waiting + assert waiting["data-state"] == "indeterminate" + assert run.server.element("bound").attributes["aria-valuenow"] == "20" + + +@CONTRACT.step("shows its value with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert _covered(run, "some") == 300 + assert _covered(run, "all") == 1000 + assert _covered(run, "bound") == 200 + assert run.page.get_by_role("progressbar").count() == 4 + + +@CONTRACT.step("has the role and the value of a progressbar", on=HYDRATED) +def _role(run: Run) -> None: + assert run.page.locator("main").aria_snapshot() == ( + "- main:\n" + " - progressbar\n" + " - progressbar\n" + " - progressbar\n" + " - progressbar\n" + ' - button "Advance"' + ) + names = ("aria-valuemin", "aria-valuenow", "aria-valuemax", "aria-valuetext") + assert [ + [run.page.locator(f"#{bar}").get_attribute(name) for name in names] + for bar in ("some", "all", "waiting", "bound") + ] == [ + ["0", "30", "100", "30%"], + ["0", "5", "5", "100%"], + ["0", None, "100", None], + ["0", "20", "100", "20%"], + ] + + +@CONTRACT.step("a bar without a value grows, fades, pulses and shines", on=HYDRATED) +def _animations(run: Run) -> None: + indicator = run.page.locator("#waiting > div") + assert indicator.evaluate(ANIMATIONS) == EXPECTED_ANIMATIONS + assert run.page.locator("#some > div").evaluate(ANIMATIONS) == [] + + +@CONTRACT.step("a value bound to state moves the indicator", on=HYDRATED) +def _bound(run: Run) -> None: + assert _covered(run, "bound") == 200 + run.page.locator("#advance").click() + run.page.wait_for_function( + "document.getElementById('bound').getAttribute('aria-valuenow') === '80'" + ) + bound = run.page.locator("#bound") + assert bound.get_attribute("aria-valuetext") == "80%" + assert bound.get_attribute("data-state") == "loading" + run.page.wait_for_function(f"{COVERED}(document.getElementById('bound')) === 800") 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 f817837518f..deab9c8da0f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -13,6 +13,7 @@ "components.data_list": ["data_list"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], + "components.progress": ["progress"], "components.separator": ["divider", "separator"], "components.spinner": ["spinner"], "layout.box": ["box"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/progress.py b/packages/reflex-components-ui/src/reflex_components_ui/components/progress.py new file mode 100644 index 00000000000..8a591fd3881 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/progress.py @@ -0,0 +1,232 @@ +"""A progress bar: how far something is, or that it is under way.""" + +from __future__ import annotations + +import math +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.progress import DURATION, FILL, MAX, PROGRESS, VALUE +from reflex_components_ui.themes import LiteralAccentColor, LiteralRadius + +# The maximum of a bar that is given none, or one that is not above zero. +DEFAULT_MAX = 100 + + +def _is_number(value: Any) -> bool: + """Tell whether a literal is a number, as JavaScript has them. + + Args: + value: The literal. + + Returns: + Whether it is an int or a float, and not NaN. + """ + return (value.__class__ is int or value.__class__ is float) and not math.isnan( + value + ) + + +def _state(value: Any, maximum: Any) -> dict[str, Any]: + """Describe how far a bar is, the way Radix Themes says it. + + A value that is not a number between zero and the maximum is no value: + the bar is then indeterminate, as it is without one. + + Args: + value: The ``value`` prop: a number, a Var or None. + maximum: The ``max`` prop: a number, a Var or None. + + Returns: + The attributes of the element: ``max``, ``now``, ``text`` and + ``state``, each a literal or a Var, ``now`` and ``text`` None for a + bar that is known to have no value. + """ + if isinstance(maximum, Var): + limit = ( + f'(typeof {maximum!s} === "number" && {maximum!s} > 0 ' + f"? {maximum!s} : {DEFAULT_MAX})" + ) + maximum_data = maximum._get_all_var_data() + else: + if not (_is_number(maximum) and maximum > 0): + maximum = DEFAULT_MAX + limit = str(LiteralVar.create(maximum)) + maximum_data = None + if not isinstance(value, Var): + if not (_is_number(value) and 0 <= value <= maximum): + return { + "max": maximum, + "now": None, + "text": None, + "state": "indeterminate", + } + return { + "max": maximum, + "now": value, + # Rounded as JavaScript rounds: a half goes up. + "text": f"{math.floor(value / maximum * 100 + 0.5)}%", + "state": "complete" if value == maximum else "loading", + } + if value is None: + return { + "max": Var(limit, _var_type=float, _var_data=maximum_data), + "now": None, + "text": None, + "state": "indeterminate", + } + now = str(LiteralVar.create(value)) + valid = f'typeof {now} === "number" && {now} >= 0 && {now} <= {limit}' + data = VarData.merge( + value._get_all_var_data() if isinstance(value, Var) else None, maximum_data + ) + return { + "max": Var(limit, _var_type=float, _var_data=data), + "now": Var(f"({valid} ? {now} : undefined)", _var_data=data), + "text": Var( + f'({valid} ? Math.round({now} / {limit} * 100) + "%" : undefined)', + _var_data=data, + ), + "state": Var( + f'({valid} ? ({now} === {limit} ? "complete" : "loading") ' + ': "indeterminate")', + _var_type=str, + _var_data=data, + ), + } + + +def _known(value: Any) -> Any: + """Read a prop that may be known while compiling. + + Args: + value: The value of the prop. + + Returns: + The value a literal Var holds, or the value as given. + """ + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + return value._var_value + return value + + +def _css_number(value: Any) -> Any: + """Write a number as the value of a custom property. + + Args: + value: A number, or a Var. + + Returns: + The Var, or the number as text: a custom property takes no unit. + """ + return value if isinstance(value, Var) else str(LiteralVar.create(value)) + + +class Progress(UIComponent): + """A progress bar component.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = PROGRESS + + value: Var[int] = field(doc="The value of the progress bar: 0 to max (default 100)") + + max: Var[int] = field(doc="The maximum progress value.") + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc='The size of the progress bar: "1" | "2" | "3"' + ) + + variant: Var[Literal["classic", "surface", "soft"]] = field( + doc='The variant of the progress bar: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="The color theme of the progress bar" + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the progress bar with higher contrast color against background" + ) + + radius: Var[LiteralRadius] = field( + doc='Override theme radius for progress bar: "none" | "small" | "medium" | "large" | "full"' + ) + + duration: Var[str] = field( + doc="The duration of the progress bar animation. Once the duration times out, the progress bar will start an indeterminate animation." + ) + + fill_color: Var[str] = field(doc="The color of the progress bar fill animation.") + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a Progress component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The Progress Component. + """ + props.setdefault("width", "100%") + value = _known(props.get("value")) + maximum = _known(props.get("max")) + state = _state(value, maximum) + # The indicator reads how far it is from custom properties, so a + # value bound to state moves it without a render of its own. + if value is not None: + props[VALUE] = _css_number(value) + elif props.get("duration") is not None: + props[DURATION] = props["duration"] + if maximum is not None: + props[MAX] = _css_number(maximum) + if props.get("fill_color") is not None: + props[FILL] = props["fill_color"] + attrs = { + "aria-valuemax": state["max"], + "aria-valuemin": 0, + "aria-valuenow": state["now"], + "aria-valuetext": state["text"], + "role": "progressbar", + "data-state": state["state"], + "data-value": state["now"], + "data-max": state["max"], + } + props["custom_attrs"] = { + **{ + name: attr + for name, attr in attrs.items() + if attr is not None and name.replace("-", "_") not in props + }, + **props.get("custom_attrs", {}), + } + indicator = Part.create( + part="indicator", + tag="div", + custom_attrs={ + name: attrs[name] + for name in ("data-state", "data-value", "data-max") + if attrs[name] is not None + }, + ) + # Radix Themes renders the indicator alone, whatever the children. + return super().create(indicator, **props) + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the ones the custom properties and + the ARIA attributes of the element are made from. + """ + return [*super()._exclude_props(), "value", "max", "duration", "fill_color"] + + +progress = Progress.create 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 88ab45a5aa5..155b28cae23 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 @@ -377,7 +377,7 @@ def _emit(merged: Merged) -> Emitted: tables.insert(0, f"const {_NAME}_c = {_classes(_KEY)};") declaration = classes = None if styles: - animations: dict[Keyframes, str] = {} + played: dict[Keyframes, str] = {} def reference(value: Any) -> str: """Stand in for the keyframes of a style until they have a name. @@ -388,21 +388,31 @@ def reference(value: Any) -> str: Returns: A marker that no style can hold, as JSON escapes it. """ - return animations.setdefault(value, f"\1{len(animations)}\1") + return played.setdefault(value, f"\1{len(played)}\1") entries = ", ".join([ f"{key}: {json.dumps(style, ensure_ascii=False, default=reference)}" for key, style in styles.items() ]) - for position in range(len(animations)): - # StyleX compiles a reference to keyframes of the same module. + # One declaration for each animation, whichever styles play it. + animations: dict[str, str] = {} + for position, frames in enumerate(played): + names = [ + animations.setdefault(source, f"{_NAME}_k{len(animations)}") + for source in frames.sources + ] + # StyleX compiles a reference to keyframes of the same module, and + # a template that holds nothing else to the list of their names. entries = entries.replace( - f'"\\u0001{position}\\u0001"', f"{_NAME}_k{position}" + f'"\\u0001{position}\\u0001"', + names[0] + if len(names) == 1 + else f"`{', '.join([f'${{{name}}}' for name in names])}`", ) template = "\n".join([ *[ - f"const {_NAME}_k{position} = stylex.keyframes({frames.source});" - for position, frames in enumerate(animations) + f"const {name} = stylex.keyframes({source});" + for source, name in animations.items() ], f"const {_NAME} = stylex.create({{ {entries} }});", *tables, 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 d336702cc7a..4a69f961262 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 @@ -10,7 +10,8 @@ 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; -- a ``Keyframes``, the value of ``animationName`` alone. +- a ``Keyframes``, the value of ``animationName`` alone: the animations a + style plays. 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 @@ -636,28 +637,30 @@ def _entries() -> tuple[dict[str, _Entry], dict[str, _Entry]]: class Keyframes: - """The keyframes of an animation, declared with the style that plays them. + """The keyframes of the animations a style plays, declared with it. Two of them are equal, and hash the same, when they hold the same declarations, so one animation is declared once per module however many styles play it. Attributes: - source: The frames as the object ``stylex.keyframes`` takes. + sources: The frames of each animation, in the order they are played, + as the objects ``stylex.keyframes`` takes. imports: The modules that define the custom properties the frames use, sorted. """ - __slots__ = ("imports", "source") + __slots__ = ("imports", "sources") - def __init__(self, source: str, imports: tuple[str, ...]): + def __init__(self, sources: tuple[str, ...], imports: tuple[str, ...]): """Hold lowered keyframes. Args: - source: The frames as the object ``stylex.keyframes`` takes. + sources: The frames of each animation, as the objects + ``stylex.keyframes`` takes. imports: The modules the frames need, sorted. """ - self.source = source + self.sources = sources self.imports = imports def __eq__(self, other: object) -> bool: @@ -667,17 +670,17 @@ def __eq__(self, other: object) -> bool: other: What to compare with. Returns: - Whether both declare the same animation. + Whether both declare the same animations. """ - return isinstance(other, Keyframes) and self.source == other.source + return isinstance(other, Keyframes) and self.sources == other.sources def __hash__(self) -> int: """Hash consistently with equality. Returns: - The hash of the source. + The hash of the sources. """ - return hash(self.source) + return hash(self.sources) def __repr__(self) -> str: """Show what the keyframes hold. @@ -685,10 +688,13 @@ def __repr__(self) -> str: Returns: The constructor call that would rebuild them. """ - return f"Keyframes({self.source!r}, {self.imports!r})" + return f"Keyframes({self.sources!r}, {self.imports!r})" -def keyframes(frames: Mapping[str, StyleProps | Mapping[str, Any]]) -> Any: +def keyframes( + frames: Mapping[str, StyleProps | Mapping[str, Any]], + *more: Mapping[str, StyleProps | Mapping[str, Any]], +) -> Any: """Declare the keyframes of an animation, for a style to play. The result is the value of ``animation_name``, in a style table or in the @@ -702,10 +708,19 @@ def keyframes(frames: Mapping[str, StyleProps | Mapping[str, Any]]) -> Any: "animation_iteration_count": "infinite", } + Several sets of frames are as many animations played together, which the + longhands then list a value for each of, separated by commas:: + + { + "animation_name": keyframes(grow, fade), + "animation_duration": "5s, 2.5s", + } + Args: frames: The styles of each frame, by ``from``, ``to`` or a percentage. Every value is a literal: a frame has no conditions and nothing bound to state. + *more: The frames of the animations played with the first one. Returns: The keyframes. @@ -714,29 +729,32 @@ def keyframes(frames: Mapping[str, StyleProps | Mapping[str, Any]]) -> Any: StyleError: If a frame is not a dict of literal styles. """ name = "rx.ui keyframes" - lowered: dict[str, dict[str, Any]] = {} + sources = [] found: set[str] = set() - for frame, style in frames.items(): - if not isinstance(style, Mapping): - msg = ( - f'{name}: the frame "{frame}" must be a dict of styles, not ' - f"{type(style).__name__}." - ) - raise StyleError(msg) - props, _ = lower_layer(name, style) - for prop, value in props.items(): - cls = value.__class__ - if cls is str: - _modules(value, found) - elif cls is not int and cls is not float: + for animation in (frames, *more): + lowered: dict[str, dict[str, Any]] = {} + for frame, style in animation.items(): + if not isinstance(style, Mapping): msg = ( - f'{name}: the style "{prop}" of the frame "{frame}" must be ' - "a literal: a frame takes no condition and nothing bound " - "to state." + f'{name}: the frame "{frame}" must be a dict of styles, not ' + f"{type(style).__name__}." ) raise StyleError(msg) - lowered[frame] = props - return Keyframes(json.dumps(lowered, ensure_ascii=False), tuple(sorted(found))) + props, _ = lower_layer(name, style) + for prop, value in props.items(): + cls = value.__class__ + if cls is str: + _modules(value, found) + elif cls is not int and cls is not float: + msg = ( + f'{name}: the style "{prop}" of the frame "{frame}" must be ' + "a literal: a frame takes no condition and nothing bound " + "to state." + ) + raise StyleError(msg) + lowered[frame] = props + sources.append(json.dumps(lowered, ensure_ascii=False)) + return Keyframes(tuple(sources), tuple(sorted(found))) def _put( diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/progress.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/progress.py new file mode 100644 index 00000000000..741c4223880 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/progress.py @@ -0,0 +1,204 @@ +"""The look of a progress bar: a track, and an indicator as wide as the value.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, keyframes, unchecked +from reflex_components_ui.styles.appearance import by_appearance +from reflex_components_ui.styles.typography import ACCENT_SCOPE + +accent, gray, white = tokens.accent, tokens.gray, tokens.white + +# What the element sets and the indicator reads, as with Radix Themes: how far +# the progress is, and how long a bar without a value takes to fill. +VALUE = "--progress-value" +MAX = "--progress-max" +DURATION = "--progress-duration" + +# The color the `fill_color` prop gives the indicator, whatever its variant. +FILL = "--rx-progress-fill" + +_HEIGHT = "--progress-height" + +# A bar whose value is not known, or not one between zero and its maximum. +_INDETERMINATE = "[data-state='indeterminate']" + +_GROW: dict[str, Any] = { + "0%": {"transform": "scaleX(0.01)"}, + "20%": {"transform": "scaleX(0.1)"}, + "30%": {"transform": "scaleX(0.6)"}, + "40%": {"transform": "scaleX(0.9)"}, + "50%": {"transform": "scaleX(0.9)"}, + "100%": {"transform": "scaleX(1)"}, +} + +_SHINE = keyframes({ + "0%": {"transform": "translateX(-100%)"}, + "100%": {"transform": "translateX(0%)"}, +}) + + +def _fill(color: str) -> str: + """Make the color of an indicator, which the ``fill_color`` prop replaces. + + Args: + color: The color of the variant. + + Returns: + The value of the background color. + """ + return f"var({FILL}, {color})" + + +def _waiting(faded: dict[str, Any], back: dict[str, Any]) -> Any: + """Make the animations of an indicator whose value is not known. + + It grows to the whole track, then fades to a color and pulses between + that color and another for as long as it waits. + + Args: + faded: What the indicator fades to once it has grown. + back: What it pulses back to. + + Returns: + The styles that play the three animations. + """ + return { + _INDETERMINATE: { + "animation_name": keyframes( + _GROW, {"100%": faded}, {"0%": faded, "100%": back} + ) + } + } + + +# The shine that crosses an indicator whose value is not known. +_SHINE_COLORS = by_appearance( + f"{white.a[5]}, {white.a[9]}, {white.a[5]}", + f"{white.a[3]}, {white.a[6]}, {white.a[3]}", +) + +_INDICATOR: ComponentStyles = { + "base": unchecked({ + "box_sizing": "border-box", + "display": "block", + "height": "100%", + "width": "100%", + "transform": f"scaleX(calc(var({VALUE}) / var({MAX})))", + "transform_origin": "left center", + "transition_property": "transform", + "transition_duration": "120ms", + _INDETERMINATE: { + "animation_delay": ( + f"0s, calc(var({DURATION}) + 5s), calc(var({DURATION}) + 7.5s)" + ), + "animation_duration": f"var({DURATION}), 2.5s, 5s", + "animation_iteration_count": "1, 1, infinite", + "animation_fill_mode": "both, none, none", + "animation_direction": "normal, normal, alternate", + }, + "_after": { + _INDETERMINATE: { + "box_sizing": "border-box", + "position": "absolute", + "inset": "0", + "content": "''", + "width": "400%", + "animation_name": _SHINE, + "animation_delay": f"calc(var({DURATION}) + 5s)", + "animation_duration": "5s", + "animation_fill_mode": "backwards", + "animation_iteration_count": "infinite", + "background_image": ( + "linear-gradient(to right, transparent 25%, " + f"{_SHINE_COLORS}, transparent 75%)" + ), + }, + }, + }), + "variants": { + "variant": { + "surface": unchecked({ + "background_color": _fill(accent.track), + **_waiting( + {"background_color": accent[7]}, {"background_color": accent.track} + ), + }), + "classic": unchecked({ + "background_color": _fill(accent.track), + **_waiting( + {"background_color": accent[7]}, {"background_color": accent.track} + ), + }), + "soft": unchecked({ + "background_image": (f"linear-gradient({accent.a[5]}, {accent.a[5]})"), + "background_color": _fill(accent[8]), + "_after": {_INDETERMINATE: {"opacity": 0.75}}, + **_waiting( + {"background_color": accent[5]}, {"background_color": accent[7]} + ), + }), + }, + "high_contrast": { + "true": unchecked({ + "background_color": _fill(accent[12]), + "_after": {_INDETERMINATE: {"opacity": 0.75}}, + **_waiting({"opacity": 0.8}, {"opacity": 1}), + }), + }, + }, + "defaults": {"variant": "surface"}, +} + +PROGRESS: ComponentStyles = { + "base": unchecked({ + VALUE: "0", + MAX: "100", + DURATION: "5s", + "box_sizing": "border-box", + "pointer_events": "none", + "position": "relative", + "overflow": "hidden", + "flex_grow": 1, + "height": f"var({_HEIGHT})", + "border_radius": ( + f"max(calc({tokens.radius.factor} * var({_HEIGHT}) / 3), " + f"calc({tokens.radius.factor} * {tokens.radius.thumb}))" + ), + # Over the indicator, for the shadows of a variant. + "_after": { + "box_sizing": "border-box", + "position": "absolute", + "inset": "0", + "content": "''", + "border_radius": "inherit", + }, + }), + "variants": { + "size": { + "1": unchecked({_HEIGHT: tokens.space[1]}), + "2": unchecked({_HEIGHT: f"calc({tokens.space[2]} * 0.75)"}), + "3": unchecked({_HEIGHT: tokens.space[2]}), + }, + "variant": { + "surface": { + "background_color": gray.a[3], + "_after": {"box_shadow": f"inset 0 0 0 1px {gray.a[4]}"}, + }, + "classic": { + "background_color": gray.a[3], + "_after": {"box_shadow": tokens.shadow[1]}, + }, + "soft": { + "background_color": gray.a[4], + # Blended with white, for more contrast in the dark appearance. + "background_image": f"linear-gradient({white.a[1]}, {white.a[1]})", + }, + }, + "color_scheme": {"true": unchecked(ACCENT_SCOPE)}, + }, + "defaults": {"size": "2", "variant": "surface"}, + "parts": {"indicator": _INDICATOR}, +} diff --git a/tests/units/reflex_components_ui/components/test_button.py b/tests/units/reflex_components_ui/components/test_button.py index 86200379f3f..e12fa57f907 100644 --- a/tests/units/reflex_components_ui/components/test_button.py +++ b/tests/units/reflex_components_ui/components/test_button.py @@ -18,7 +18,9 @@ "left": "calc(50% - 12.5% / 2)", "width": {"default": "12.5%", "::before": "100%"}, "height": {"default": "100%", "::before": "30%"}, - "animationName": Keyframes('{"from": {"opacity": 1}, "to": {"opacity": 0.25}}', ()), + "animationName": Keyframes( + ('{"from": {"opacity": 1}, "to": {"opacity": 0.25}}',), () + ), "animationDuration": "var(--spinner-animation-duration, 800ms)", "animationTimingFunction": "linear", "animationIterationCount": "infinite", diff --git a/tests/units/reflex_components_ui/components/test_progress.py b/tests/units/reflex_components_ui/components/test_progress.py new file mode 100644 index 00000000000..f21a7a30b74 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_progress.py @@ -0,0 +1,361 @@ +"""Tests for reflex_components_ui.components.progress.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.vars.base import Var +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError, keyframes + +import reflex as rx + +WAITING = "[data-state='indeterminate']" + +GROW = { + "0%": {"transform": "scaleX(0.01)"}, + "20%": {"transform": "scaleX(0.1)"}, + "30%": {"transform": "scaleX(0.6)"}, + "40%": {"transform": "scaleX(0.9)"}, + "50%": {"transform": "scaleX(0.9)"}, + "100%": {"transform": "scaleX(1)"}, +} +SHINE = keyframes({ + "0%": {"transform": "translateX(-100%)"}, + "100%": {"transform": "translateX(0%)"}, +}) +SHINE_IMAGE = ( + "linear-gradient(to right, transparent 25%, " + "var(--rx-if-light, var(--white-a5), var(--white-a9), var(--white-a5)) " + "var(--rx-if-dark, var(--white-a3), var(--white-a6), var(--white-a3)), " + "transparent 75%)" +) + + +class ProgressState(rx.State): + """State a progress bar is bound to.""" + + done: rx.Field[int] = rx.field(3) + total: rx.Field[int] = rx.field(10) + + +DONE = str(ProgressState.done) +TOTAL = str(ProgressState.total) + + +def track(**changed: Any) -> dict[str, Any]: + """Describe the style a progress bar declares. + + Args: + **changed: The properties that are not those of a plain bar, None for + one a bar does not set. + + Returns: + The whole style of a surface bar of size 2, with the changes. + """ + style = { + "--progress-value": "0", + "--progress-max": "100", + "--progress-duration": "5s", + "boxSizing": {"default": "border-box", "::after": "border-box"}, + "pointerEvents": "none", + "position": {"default": "relative", "::after": "absolute"}, + "overflowX": "hidden", + "overflowY": "hidden", + "flexGrow": 1, + "height": "var(--progress-height)", + "borderRadius": ( + "max(calc(var(--radius-factor) * var(--progress-height) / 3), " + "calc(var(--radius-factor) * var(--radius-thumb)))" + ), + "top": {"::after": "0"}, + "right": {"::after": "0"}, + "bottom": {"::after": "0"}, + "left": {"::after": "0"}, + "content": {"::after": "''"}, + "borderTopLeftRadius": {"::after": "inherit"}, + "borderTopRightRadius": {"::after": "inherit"}, + "borderBottomRightRadius": {"::after": "inherit"}, + "borderBottomLeftRadius": {"::after": "inherit"}, + "--progress-height": "calc(var(--space-2) * 0.75)", + "backgroundColor": "var(--gray-a3)", + "boxShadow": {"::after": "inset 0 0 0 1px var(--gray-a4)"}, + "width": "100%", + **changed, + } + return {prop: value for prop, value in style.items() if value is not None} + + +def indicator( + color: str = "var(--accent-track)", + faded: dict[str, Any] | None = None, + back: dict[str, Any] | None = None, + **changed: Any, +) -> dict[str, Any]: + """Describe the style the indicator of a progress bar declares. + + Args: + color: The color of the variant. + faded: What the indicator fades to while it waits. + back: What it pulses back to. + **changed: The properties that are not those of a surface indicator. + + Returns: + The whole style. + """ + faded = faded or {"background_color": "var(--accent-7)"} + back = back or {"background_color": "var(--accent-track)"} + return { + "boxSizing": {"default": "border-box", "::after": {WAITING: "border-box"}}, + "display": "block", + "height": "100%", + "width": {"default": "100%", "::after": {WAITING: "400%"}}, + "transform": "scaleX(calc(var(--progress-value) / var(--progress-max)))", + "transformOrigin": "left center", + "transitionProperty": "transform", + "transitionDuration": "120ms", + "animationDelay": { + WAITING: ( + "0s, calc(var(--progress-duration) + 5s), " + "calc(var(--progress-duration) + 7.5s)" + ), + "::after": {WAITING: "calc(var(--progress-duration) + 5s)"}, + }, + "animationDuration": { + WAITING: "var(--progress-duration), 2.5s, 5s", + "::after": {WAITING: "5s"}, + }, + "animationIterationCount": { + WAITING: "1, 1, infinite", + "::after": {WAITING: "infinite"}, + }, + "animationFillMode": { + WAITING: "both, none, none", + "::after": {WAITING: "backwards"}, + }, + "animationDirection": {WAITING: "normal, normal, alternate"}, + "position": {"::after": {WAITING: "absolute"}}, + "top": {"::after": {WAITING: "0"}}, + "right": {"::after": {WAITING: "0"}}, + "bottom": {"::after": {WAITING: "0"}}, + "left": {"::after": {WAITING: "0"}}, + "content": {"::after": {WAITING: "''"}}, + "animationName": { + "::after": {WAITING: SHINE}, + WAITING: keyframes(GROW, {"100%": faded}, {"0%": faded, "100%": back}), + }, + "backgroundImage": {"::after": {WAITING: SHINE_IMAGE}}, + "backgroundColor": f"var(--rx-progress-fill, {color})", + **changed, + } + + +def test_progress_with_a_value( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A bar says how far it is to assistive technology and to its indicator.""" + component = rx.ui.progress(value=25) + assert component.render() == { + "name": '"div"', + "props": [ + '"aria-valuemax":100', + '"aria-valuemin":0', + '"aria-valuenow":25', + '"aria-valuetext":"25%"', + "className:sx_3f4f92d33a_c", + '"data-max":100', + '"data-state":"loading"', + '"data-value":25', + 'role:"progressbar"', + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_0fd9549b4f_c", + '"data-max":100', + '"data-state":"loading"', + '"data-value":25', + ], + "children": [], + } + ], + } + assert declared_styles(component) == [ + track(**{"--progress-value": "25"}), + indicator(), + ] + + +def test_progress_without_a_value( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A bar without a value waits for as long as its duration, in the look of its props.""" + component = rx.ui.progress( + variant="soft", + size="3", + high_contrast=True, + color_scheme="ruby", + radius="full", + duration="10s", + fill_color="red", + width="50%", + ) + assert component.render() == { + "name": '"div"', + "props": [ + '"aria-valuemax":100', + '"aria-valuemin":0', + ( + 'className:sx_635f52cf10_c + " " + reflexUIClasses_e201574881 + " " + ' + "reflexUIClasses_4c7cd6a7ce" + ), + '"data-max":100', + '"data-state":"indeterminate"', + 'role:"progressbar"', + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_3ba578a75b_c", + '"data-max":100', + '"data-state":"indeterminate"', + ], + "children": [], + } + ], + } + waiting = indicator( + "var(--accent-12)", + {"opacity": 0.8}, + {"opacity": 1}, + opacity={"::after": {WAITING: 0.75}}, + ) + waiting["backgroundImage"] = { + "default": "linear-gradient(var(--accent-a5), var(--accent-a5))", + "::after": {WAITING: SHINE_IMAGE}, + } + styles = declared_styles(component) + assert styles == [ + track(**{ + "--progress-duration": "10s", + "--progress-height": "var(--space-2)", + "backgroundColor": "var(--gray-a4)", + "backgroundImage": "linear-gradient(var(--white-a1), var(--white-a1))", + "boxShadow": None, + "--rx-accent-text": "var(--accent-12)", + "--rx-accent-link": "var(--accent-12)", + "--rx-accent-link-line": "underline", + "--rx-accent-link-line-color": ( + "color-mix(in oklab, var(--accent-a6), var(--gray-a6))" + ), + "width": "50%", + "--rx-progress-fill": "red", + }), + waiting, + ] + + +def test_progress_bound_to_state( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A value bound to state is a custom property, and is checked in the browser.""" + component = rx.ui.progress(value=ProgressState.done, max=ProgressState.total) + limit = f'(typeof {TOTAL} === "number" && {TOTAL} > 0 ? {TOTAL} : 100)' + valid = f'typeof {DONE} === "number" && {DONE} >= 0 && {DONE} <= {limit}' + now = f"({valid} ? {DONE} : undefined)" + state = ( + f'({valid} ? ({DONE} === {limit} ? "complete" : "loading") : "indeterminate")' + ) + assert component.render() == { + "name": '"div"', + "props": [ + f'"aria-valuemax":{limit}', + '"aria-valuemin":0', + f'"aria-valuenow":{now}', + ( + f'"aria-valuetext":({valid} ? Math.round({DONE} / {limit} * 100) + "%" ' + ": undefined)" + ), + "className:sx_3453e4362e_c", + f'"data-max":{limit}', + f'"data-state":{state}', + f'"data-value":{now}', + 'role:"progressbar"', + f'style:({{ "--v0": ({DONE}) ?? "initial", "--v1": ({TOTAL}) ?? "initial" }})', + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_0fd9549b4f_c", + f'"data-max":{limit}', + f'"data-state":{state}', + f'"data-value":{now}', + ], + "children": [], + } + ], + } + root, inner = declared_styles(component) + assert { + prop: str(value) if isinstance(value, Var) else value + for prop, value in root.items() + } == track(**{"--progress-value": DONE, "--progress-max": TOTAL}) + assert inner == indicator() + + +def test_progress_checks_its_value_as_radix_does( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A value over the maximum is no value, and a maximum of zero is 100.""" + component = rx.ui.progress(value=150, max=0, aria_valuetext="unknown") + assert component.render() == { + "name": '"div"', + "props": [ + '"aria-valuemax":100', + '"aria-valuemin":0', + '"aria-valuetext":"unknown"', + "className:sx_6d82c8dfbb_c", + '"data-max":100', + '"data-state":"indeterminate"', + 'role:"progressbar"', + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_0fd9549b4f_c", + '"data-max":100', + '"data-state":"indeterminate"', + ], + "children": [], + } + ], + } + assert declared_styles(component) == [ + track(**{"--progress-value": "150", "--progress-max": "0"}), + indicator(), + ] + complete = rx.ui.progress(value=8, max=8).render() + assert complete["props"] == [ + '"aria-valuemax":8', + '"aria-valuemin":0', + '"aria-valuenow":8', + '"aria-valuetext":"100%"', + "className:sx_68b5d1fe7c_c", + '"data-max":8', + '"data-state":"complete"', + '"data-value":8', + 'role:"progressbar"', + ] + + +def test_progress_rejects_an_unknown_variant(ui_plugin: UIPlugin): + with pytest.raises(StyleError) as error: + rx.ui.progress(variant="solid") # pyright: ignore[reportArgumentType] + assert str(error.value) == ( + 'rx.ui.progress: unknown variant "solid". The values are "classic", ' + '"surface", "soft".' + ) diff --git a/tests/units/reflex_components_ui/components/test_spinner.py b/tests/units/reflex_components_ui/components/test_spinner.py index efd0cdbb61a..91514df1cc8 100644 --- a/tests/units/reflex_components_ui/components/test_spinner.py +++ b/tests/units/reflex_components_ui/components/test_spinner.py @@ -15,7 +15,9 @@ "left": "calc(50% - 12.5% / 2)", "width": {"default": "12.5%", "::before": "100%"}, "height": {"default": "100%", "::before": "30%"}, - "animationName": Keyframes('{"from": {"opacity": 1}, "to": {"opacity": 0.25}}', ()), + "animationName": Keyframes( + ('{"from": {"opacity": 1}, "to": {"opacity": 0.25}}',), () + ), "animationDuration": "var(--spinner-animation-duration, 800ms)", "animationTimingFunction": "linear", "animationIterationCount": "infinite", diff --git a/tests/units/reflex_components_ui/style/test_emit.py b/tests/units/reflex_components_ui/style/test_emit.py index e6f2b1a4e85..0fea4cf72b1 100644 --- a/tests/units/reflex_components_ui/style/test_emit.py +++ b/tests/units/reflex_components_ui/style/test_emit.py @@ -610,17 +610,17 @@ def test_inline_rejects_what_an_inline_style_cannot_hold( assert str(raised.value) == message -FADE = keyframes({"from": {"opacity": 1}, "to": {"opacity": 0.25}}) -SLIDE = keyframes({"to": {"top": "0"}}) +FADING = keyframes({"from": {"opacity": 1}, "to": {"opacity": 0.25}}) +SLIDING = keyframes({"to": {"top": "0"}}) # A style that plays keyframes, at rest and under a condition, and a variant # bound to state that plays others. ANIMATED: ComponentStyles = { "base": { - "animation_name": {"default": FADE, ":hover": SLIDE}, + "animation_name": {"default": FADING, ":hover": SLIDING}, "animation_duration": "800ms", }, - "variants": {"kind": {"slide": {"animation_name": SLIDE}}}, + "variants": {"kind": {"slide": {"animation_name": SLIDING}}}, } @@ -664,7 +664,8 @@ def test_inline_cannot_play_keyframes(): """Code evaluated in the browser declares no keyframes.""" with pytest.raises(StyleError) as error: inline( - merge("rx.ui.spinner", {"base": {"animation_name": FADE}}), "rx.ui.spinner" + merge("rx.ui.spinner", {"base": {"animation_name": FADING}}), + "rx.ui.spinner", ) assert str(error.value) == ( 'rx.ui.spinner: the style "animationName" plays keyframes, which a ' @@ -672,3 +673,47 @@ def test_inline_cannot_play_keyframes(): "browser and never reaches the StyleX compiler. Leave the animation out " "there, or render the component in a page and show it with rx.cond." ) + + +FADE = {"from": {"opacity": 1}, "to": {"opacity": 0}} +TINT = {"100%": {"background_color": "var(--accent-7)"}} + + +def test_emit_declares_the_keyframes_of_one_animation(): + style = {"animation_name": keyframes(FADE)} + assert emit(merge("rx.ui.box", NO_STYLES, style=style)) == Emitted( + declaration=( + "const sx_4e60b95abf_k0 = stylex.keyframes(" + '{"from": {"opacity": 1}, "to": {"opacity": 0}});\n' + "const sx_4e60b95abf = stylex.create(" + '{ s: {"animationName": sx_4e60b95abf_k0} });\n' + "const sx_4e60b95abf_c = stylex.props(sx_4e60b95abf.s).className;" + ), + classes="sx_4e60b95abf_c", + ) + + +def test_emit_lists_the_animations_played_together_in_a_template(): + """Each animation is declared once, whichever styles play it, in any order.""" + style = { + "animation_name": keyframes(FADE, TINT), + "animation_duration": "1s, 2s", + "_after": {"animation_name": keyframes(TINT)}, + "_hover": {"animation_name": keyframes(TINT, FADE)}, + } + assert emit(merge("rx.ui.box", NO_STYLES, style=style)) == Emitted( + declaration=( + "const sx_a97dd18a1b_k0 = stylex.keyframes(" + '{"from": {"opacity": 1}, "to": {"opacity": 0}});\n' + "const sx_a97dd18a1b_k1 = stylex.keyframes(" + '{"100%": {"backgroundColor": "var(--accent-7)"}});\n' + "const sx_a97dd18a1b = stylex.create({ s: {" + '"animationName": {"default": `${sx_a97dd18a1b_k0}, ${sx_a97dd18a1b_k1}`, ' + '"::after": sx_a97dd18a1b_k1, ' + '":hover": `${sx_a97dd18a1b_k1}, ${sx_a97dd18a1b_k0}`}, ' + '"animationDuration": "1s, 2s"} });\n' + "const sx_a97dd18a1b_c = stylex.props(sx_a97dd18a1b.s).className;" + ), + classes="sx_a97dd18a1b_c", + imports=("$/reflex-ui/tokens/accent.stylex.js",), + ) diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index 6d85f3fa835..a604551a23a 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -1509,94 +1509,64 @@ def test_layout_props_keep_the_breakpoints_of_radix_whatever_the_app_has(): } -FADE = keyframes({ - "from": {"opacity": 1, "background_color": tokens.accent[9]}, - "50%": {"margin_x": "2px"}, - "to": {"opacity": 0.25}, -}) - - -def test_keyframes_lower_each_frame_and_compare_by_content(): - """Frames are lowered like any style, and equal keyframes are one animation.""" - assert FADE.source == ( - '{"from": {"opacity": 1, "backgroundColor": "var(--accent-9)"}, ' - '"50%": {"marginLeft": "2px", "marginRight": "2px"}, ' - '"to": {"opacity": 0.25}}' +FADE = {"from": {"opacity": 1}, "to": {"opacity": 0}} +TINT = {"100%": {"background_color": tokens.accent[7]}} +FADE_SOURCE = '{"from": {"opacity": 1}, "to": {"opacity": 0}}' +TINT_SOURCE = '{"100%": {"backgroundColor": "var(--accent-7)"}}' +ACCENT_MODULE = "$/reflex-ui/tokens/accent.stylex.js" + + +def test_keyframes_hold_the_frames_of_each_animation_they_play(): + """One set of frames is one animation, several are played together.""" + one = keyframes(FADE) + assert (one.sources, one.imports) == ((FADE_SOURCE,), ()) + assert repr(one) == f"Keyframes(({FADE_SOURCE!r},), ())" + several = keyframes(FADE, TINT) + assert (several.sources, several.imports) == ( + (FADE_SOURCE, TINT_SOURCE), + (ACCENT_MODULE,), ) - assert FADE.imports == ("$/reflex-ui/tokens/accent.stylex.js",) - again = keyframes({ - "from": {"opacity": 1, "background_color": tokens.accent[9]}, - "50%": {"margin_x": "2px"}, - "to": {"opacity": 0.25}, - }) - assert again == FADE - assert hash(again) == hash(FADE) - assert again != keyframes({"from": {"opacity": 1}}) - assert repr(keyframes({"to": {"top": "0"}})) == ( - """Keyframes('{"to": {"top": "0"}}', ())""" - ) - - -def test_keyframes_are_the_value_of_animation_name(): - """The style that plays keyframes imports what their frames use.""" + # Equal by what they declare, in the order they play it. + assert several == keyframes(FADE, TINT) + assert hash(several) == hash(keyframes(FADE, TINT)) + assert several != keyframes(TINT, FADE) + assert several != one lowered = lower( - "rx.ui.spinner", - { - "animation_name": { - "default": FADE, - "@media (prefers-reduced-motion: reduce)": "none", - }, - "animation_duration": "800ms", - }, + "rx.ui.box", {"animation_name": several, "animation_duration": "1s, 2s"} ) assert lowered.style == { - "animationName": { - "default": FADE, - "@media (prefers-reduced-motion: reduce)": "none", - }, - "animationDuration": "800ms", + "animationName": several, + "animationDuration": "1s, 2s", } - assert lowered.imports == ("$/reflex-ui/tokens/accent.stylex.js",) - assert lowered == lower( - "rx.ui.spinner", - { - "animation_duration": "800ms", - "animation_name": { - "default": FADE, - "@media (prefers-reduced-motion: reduce)": "none", - }, - }, - ) + assert lowered.imports == (ACCENT_MODULE,) @pytest.mark.parametrize( - ("create", "message"), + ("frames", "message"), [ ( - lambda: lower("rx.ui.spinner", {"transition_property": FADE}), - ( - 'rx.ui.spinner: style "transition_property" is given keyframes, ' - "which are the value of animation_name." - ), - ), - ( - lambda: keyframes({"from": "opacity: 1"}), # pyright: ignore[reportArgumentType] - 'rx.ui keyframes: the frame "from" must be a dict of styles, not str.', + (FADE, {"to": "red"}), + 'rx.ui keyframes: the frame "to" must be a dict of styles, not str.', ), ( - lambda: keyframes({"to": {"opacity": {"default": 1, ":hover": 0}}}), + (FADE, {"to": {"color": {"default": "red", ":hover": "blue"}}}), ( - 'rx.ui keyframes: the style "opacity" of the frame "to" must be a ' + 'rx.ui keyframes: the style "color" of the frame "to" must be a ' "literal: a frame takes no condition and nothing bound to state." ), ), - ( - lambda: keyframes({"to": {"opacty": 1}}), - 'rx.ui keyframes: unknown CSS property "opacty". Did you mean "opacity"?', - ), ], ) -def test_keyframes_errors(create: Any, message: str): +def test_keyframes_check_every_animation(frames: tuple[Any, ...], message: str): with pytest.raises(StyleError) as error: - create() + keyframes(*frames) assert str(error.value) == message + + +def test_keyframes_are_the_value_of_animation_name_alone(): + with pytest.raises(StyleError) as error: + lower("rx.ui.box", {"animation_duration": keyframes(FADE, TINT)}) + assert str(error.value) == ( + 'rx.ui.box: style "animation_duration" is given keyframes, which are ' + "the value of animation_name." + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 89477fb8e8e..ac6847bf5d1 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -129,6 +129,7 @@ def test_every_wave_is_in_the_namespace(): "list.unordered", "list_item", "ordered_list", + "progress", "section", "separator", "spacer", From cd423d4fdfa2cda9d3d4637d7a2f0bb7def15b6d Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 22:40:03 +0000 Subject: [PATCH 054/204] Add rx.ui.card, and render the inset matrix inside it Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/ui_parity/components/card.py | 247 +++++ .../parity/ui_parity/components/inset.py | 37 +- .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/card.py | 37 + .../src/reflex_components_ui/styles/card.py | 333 ++++++ .../components/test_card.py | 974 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 7 files changed, 1615 insertions(+), 15 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/card.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/card.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/card.py create mode 100644 tests/units/reflex_components_ui/components/test_card.py diff --git a/packages/reflex-components-ui/parity/ui_parity/components/card.py b/packages/reflex-components-ui/parity/ui_parity/components/card.py new file mode 100644 index 00000000000..761010bbeba --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/card.py @@ -0,0 +1,247 @@ +"""The card: every variant and size, what it holds, and a card that is a link.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix + +VARIANTS = ["surface", "classic", "ghost"] +SIZES = ["1", "2", "3", "4", "5"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +RESPONSIVE = {"responsive": rx.breakpoints(initial="1", sm="4", lg="2")} + +# A translucent card blurs what is behind it, 64 pixels around: the frames +# beside its own, which are not the same for the two systems. A filter makes +# an element the root of the backdrop of what it holds. +_BACKDROP_ROOT = {"filter": "opacity(1)"} + +# What shows through a translucent card. +_STRIPES = { + "padding": "12px", + "background_image": ( + "repeating-linear-gradient(45deg, #e5484d 0 12px, #ffc53d 12px 24px, " + "#30a46c 24px 36px)" + ), +} + + +def _words(namespace: Any) -> list[Any]: + """Create what every card of the matrix says. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + A heading and a paragraph. + """ + return [ + namespace.heading("Quarterly report", size="3"), + namespace.text( + "Revenue grew by a fifth, and costs stayed flat.", + size="2", + color_scheme="gray", + ), + ] + + +def _card(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a card with real content, as the element a cell says it is. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` names what is inside the + card, ``renders`` the element it is rendered as, ``panel`` the + panel background of a theme around it, and ``over`` what is + behind it. + + Returns: + The card, or what is around it. + """ + props = dict(props) + holds = props.pop("holds", "actions") + renders = props.pop("renders", None) + panel = props.pop("panel", None) + over = props.pop("over", None) + props["custom_attrs"] = {"data-card": ""} + children = _words(namespace) + if holds == "actions" and renders is None: + children.append( + namespace.flex( + namespace.button("Open", size="1"), + namespace.button("Share", size="1", variant="soft"), + spacing="2", + margin_top="8px", + ) + ) + elif holds == "inset": + children.insert( + 0, + namespace.inset( + rx.el.img( + src=( + "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' " + "width='40' height='20'%3E%3Crect width='40' height='20' " + "fill='%233e63dd'/%3E%3Ccircle cx='20' cy='10' r='6' " + "fill='%23ffc53d'/%3E%3C/svg%3E" + ), + alt="A sun in the sky", + style={"display": "block", "width": "100%", "height": "48px"}, + ), + side="top", + pb="current", + ), + ) + elif holds == "card": + children.append(namespace.card(namespace.text("Details", size="1"))) + if renders == "link": + card = namespace.card( + rx.el.a(*children, href="#report"), as_child=True, **props + ) + elif renders == "button": + card = namespace.card(rx.el.button(*children), as_child=True, **props) + elif renders == "label": + card = namespace.card(rx.el.label(*children), as_child=True, **props) + else: + card = namespace.card(*children, **props) + if panel is not None: + card = namespace.theme(card, panel_background=panel) + if over == "stripes": + card = rx.el.div(card, style=_STRIPES) + return rx.el.div(card, style=_BACKDROP_ROOT) + + +MATRIX = Matrix( + component="card", + render=_card, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "holds": ["inset", "card"], + "renders": ["link", "button", "label"], + "panel": ["solid", "translucent"], + "over": ["stripes"], + "size": RESPONSIVE, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"variant": VARIANTS, "appearance": [LIGHT, DARK]}, + # A card that is a link or a button answers to the pointer and the + # keyboard; one that is neither does not. + { + "variant": VARIANTS, + "renders": ["link", "button"], + "state": STATES, + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "renders": ["label"], "state": ["rest", HOVER, ACTIVE]}, + {"variant": VARIANTS, "state": [HOVER, ACTIVE]}, + {"variant": VARIANTS, "holds": ["inset"], "size": ["1", "3", "5"]}, + { + "variant": VARIANTS, + "over": ["stripes"], + "panel": ["solid", "translucent"], + "appearance": [LIGHT, DARK], + }, + { + "size": RESPONSIVE, + "variant": ["surface", "ghost"], + "viewport": [520, 800, 1100, 1280], + }, + ], + stage=(400, 280), + target="[data-card]", + crop="stage", + # No pixel may differ, at the default threshold and not at zero. At a + # threshold of zero 117 of the 125 cells are equal, and in the others 1 + # to 12 pixels on the rounded corners of the border and of the shadow are + # off by one or two steps of a channel, by where the frame is on the + # page: the same props in another frame are equal (the base cell and + # `size-responsive_variant-surface@520`, which is the same card). + tolerance=0, +) + +CONTRACT = Contract( + component="card", + render=lambda namespace: namespace.box( + namespace.card( + namespace.heading("Report", size="3"), + namespace.text("Read by the board."), + id="card", + ), + namespace.card( + rx.el.a(namespace.text("Open the report"), href="#report"), + as_child=True, + id="link", + ), + namespace.card( + rx.el.button( + namespace.text("Archive"), + on_click=rx.call_script("window.archived = (window.archived || 0) + 1"), + ), + as_child=True, + id="button", + ), + ), +) + + +@CONTRACT.step( + "is a div, or the element it is rendered as, in the server render", on=SERVER +) +def _server_render(run: Run) -> None: + card = run.server.element("card") + assert (card.tag, card.text) == ("div", "ReportRead by the board.") + link = run.server.element("link") + assert (link.tag, link.text) == ("a", "Open the report") + assert link.attributes["href"] == f"/contract/card/{run.system.slug}/#report" + button = run.server.element("button") + assert (button.tag, button.text) == ("button", "Archive") + + +@CONTRACT.step( + "a card that is a link navigates with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#card").is_visible() + run.page.keyboard.press("Tab") + assert run.page.evaluate("document.activeElement.id") == "link" + run.page.locator("#link").click() + assert run.page.evaluate("location.hash") == "#report" + + +@CONTRACT.step("has the role of the element it is rendered as", on=HYDRATED) +def _role(run: Run) -> None: + assert run.page.locator("#card").get_attribute("role") is None + link = run.page.get_by_role("link", name="Open the report") + assert link.get_attribute("id") == "link" + button = run.page.get_by_role("button", name="Archive") + assert button.get_attribute("id") == "button" + + +@CONTRACT.step("Tab reaches the link and the button, not the plain card", on=HYDRATED) +def _tab(run: Run) -> None: + focused = [] + for _ in range(2): + run.page.keyboard.press("Tab") + focused.append(run.page.evaluate("document.activeElement.id")) + assert run.page.evaluate("document.activeElement.matches(':focus-visible')") + assert focused == ["link", "button"] + assert run.page.locator("#card").evaluate("element => element.tabIndex") == -1 + + +@CONTRACT.step("Enter follows the link and presses the button", on=HYDRATED) +def _press(run: Run) -> None: + run.page.locator("#link").focus() + run.page.keyboard.press("Enter") + run.page.wait_for_function("location.hash === '#report'") + run.page.locator("#button").focus() + run.page.keyboard.press("Enter") + run.page.wait_for_function("window.archived === 1") + run.page.keyboard.press("Space") + run.page.wait_for_function("window.archived === 2") + run.page.locator("#button").click() + run.page.wait_for_function("window.archived === 3") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/inset.py b/packages/reflex-components-ui/parity/ui_parity/components/inset.py index e3f9318c53b..bdd01715368 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/inset.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/inset.py @@ -9,12 +9,17 @@ from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import DARK, Matrix +# A translucent card blurs what is behind it, 64 pixels around: the frames +# beside its own, which are not the same for the two systems. A filter makes +# an element the root of the backdrop of what it holds. +_BACKDROP_ROOT = {"filter": "opacity(1)"} + def _inset(namespace: Any, props: Mapping[str, Any]) -> Any: """Create an inset inside a card, which says how far its edges are. - The card is the Radix one for both systems: it sets the custom properties - an inset reads, and rx.ui has no card yet. + The card is the one of the same system: it sets the custom properties an + inset reads. Args: namespace: ``rx`` or ``rx.ui``. @@ -25,17 +30,20 @@ def _inset(namespace: Any, props: Mapping[str, Any]) -> Any: """ props = dict(props) card = props.pop("card", {}) - return rx.card( - namespace.inset( - rx.el.div( - "The quick brown fox", - style={"background_color": "rgba(128, 128, 128, 0.4)"}, + return rx.el.div( + namespace.card( + namespace.inset( + rx.el.div( + "The quick brown fox", + style={"background_color": "rgba(128, 128, 128, 0.4)"}, + ), + custom_attrs={"data-inset": ""}, + **props, ), - custom_attrs={"data-inset": ""}, - **props, + rx.el.div("jumps over the lazy dog"), + **card, ), - rx.el.div("jumps over the lazy dog"), - **card, + style=_BACKDROP_ROOT, ) @@ -80,14 +88,13 @@ def _inset(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(260, 140), target="[data-inset]", crop="stage", - # Not held to zero, as the other layouts are: the card around the inset - # is the same Radix card in both frames, and the browser dithers its - # rounded corners and its shadow by position. + threshold=0, + tolerance=0, ) CONTRACT = Contract( component="inset", - render=lambda namespace: rx.card( + render=lambda namespace: namespace.card( namespace.inset(namespace.box("content"), id="inset", side="top"), id="card", ), 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 deab9c8da0f..7a5435edcb8 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -10,6 +10,7 @@ "components.aspect_ratio": ["aspect_ratio"], "components.badge": ["badge"], "components.button": ["button"], + "components.card": ["card"], "components.data_list": ["data_list"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/card.py b/packages/reflex-components-ui/src/reflex_components_ui/components/card.py new file mode 100644 index 00000000000..748e99e9d79 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/card.py @@ -0,0 +1,37 @@ +"""A card: a container that groups related content and actions.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.card import CARD + + +class Card(UIComponent, elements.Div): + """Container that groups related content and actions.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = CARD + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + size: Var[Responsive[Literal["1", "2", "3", "4", "5"],]] = field( + doc='Card size: "1" - "5"' + ) + + variant: Var[Literal["surface", "classic", "ghost"]] = field( + doc='Variant of Card: "surface" | "classic" | "ghost"' + ) + + +card = Card.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py new file mode 100644 index 00000000000..1808bd16ce0 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py @@ -0,0 +1,333 @@ +"""The look of a card.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.appearance import by_appearance +from reflex_components_ui.tokens import Step12 + +gray, black, focus = tokens.gray, tokens.black, tokens.focus + +# What a size and a variant set, and the rest of the card reads. An inset +# inside the card reads how far its edges are from the `--inset-*` ones. +_PADDING = "--card-padding" +_RADIUS = "--card-border-radius" +_BORDER = "--card-border-width" +_BACKGROUND = "--card-background-color" + +# A card rendered as a link, a button or a label answers to the pointer. +_LINK = ":is(:any-link, button, label)" +_POINTER = "@media (hover: hover)" +_TOUCH = "@media (pointer: coarse)" +_OPEN = "[data-state='open']" +_HOVER = f"{_LINK}:hover:not(:active)" +_PRESSED = f":active:not({_OPEN})" +_ACTIVE = f"{_LINK}{_PRESSED}" + + +def _states(hover: dict[str, Any], active: dict[str, Any]) -> dict[str, Any]: + """Make the styles of a card that is a link, in each of its states. + + StyleX places a rule inside a media query after the others, so the card + under the pointer is not the pressed one: no two of the states apply + together, but for an open card under the pointer, which looks the same. + + Args: + hover: The styles under the pointer, and of an open card. + active: The styles of a pressed card. + + Returns: + The styles, by state. + """ + return { + _POINTER: {_HOVER: hover}, + f"{_LINK}{_OPEN}": hover, + _ACTIVE: active, + } + + +def _mix(step: Step12) -> str: + """Mix the color of a border, which stays visible over any background. + + Args: + step: The step of the gray. + + Returns: + The color. + """ + return f"color-mix(in oklab, {gray.a[step]}, {gray[step]} 25%)" + + +Layer = tuple[str, str, str] + +# The spread of a layer on the card, by its spread on the pseudo-element. +_SMALLER = { + "1px": "0", + "0.5px": "0", + "0": "-1px", + "-1px": "-2px", + "-2px": "-3px", + "-4px": "-5px", + "-8px": "-9px", +} + + +def _classic(light: tuple[Layer, ...], dark: tuple[Layer, ...]) -> tuple[str, str]: + """Make the two shadows of a classic card, in both appearances. + + The shadow is on a pseudo-element that is smaller than the card by the + border, and the card itself repeats every layer with a spread one pixel + smaller: what reaches outside the card is not clipped with its content. + + Args: + light: The layers in the light appearance, the border first: each + one as its offsets and blur, its spread and its color. + dark: The same in the dark appearance. + + Returns: + The shadow of the card and the shadow of the pseudo-element. + """ + outer, inner = ( + by_appearance( + *( + ", ".join( + f"{offsets} {spreads.get(spread, spread)} {color}" + for offsets, spread, color in layers + ) + for layers in (light, dark) + ) + ) + for spreads in (_SMALLER, {}) + ) + return outer, inner + + +_NONE = tokens.color.transparent + +_CLASSIC_OUTER, _CLASSIC_INNER = _classic( + ( + ("0 0 0", "1px", _mix(3)), + ("0 0 0", "1px", _NONE), + ("0 0 0", "0.5px", black.a[1]), + ("0 1px 1px", "0", gray.a[2]), + ("0 2px 1px", "-1px", black.a[1]), + ("0 1px 3px", "0", black.a[1]), + ), + ( + ("0 0 0", "1px", _mix(6)), + ("0 0 0", "1px", _NONE), + ("0 0 0", "0.5px", black.a[3]), + ("0 1px 1px", "0", black.a[6]), + ("0 2px 1px", "-1px", black.a[6]), + ("0 1px 3px", "0", black.a[5]), + ), +) +_CLASSIC_HOVER_OUTER, _CLASSIC_HOVER_INNER = _classic( + ( + ("0 0 0", "1px", _mix(4)), + ("0 1px 1px", "1px", black.a[1]), + ("0 2px 1px", "-1px", gray.a[3]), + ("0 2px 3px", "-2px", black.a[1]), + ("0 3px 12px", "-4px", gray.a[3]), + ("0 4px 16px", "-8px", black.a[1]), + ), + ( + ("0 0 0", "1px", _mix(6)), + ("0 0 1px", "1px", gray.a[4]), + ("0 0 1px", "-1px", gray.a[4]), + ("0 0 3px", "-2px", gray.a[3]), + ("0 0 12px", "-2px", gray.a[3]), + ("0 0 16px", "-8px", gray.a[7]), + ), +) +_CLASSIC_ACTIVE_OUTER, _CLASSIC_ACTIVE_INNER = _classic( + ( + ("0 0 0", "1px", _mix(3)), + ("0 0 0", "1px", _NONE), + ("0 0 0", "0.5px", black.a[1]), + ("0 1px 1px", "0", gray.a[4]), + ("0 2px 1px", "-1px", black.a[1]), + ("0 1px 3px", "0", black.a[1]), + ), + ( + ("0 0 0", "1px", _mix(6)), + ("0 0 0", "1px", _NONE), + ("0 0 0", "0.5px", black.a[3]), + ("0 1px 1px", "0", black.a[6]), + ("0 2px 1px", "-1px", black.a[6]), + ("0 1px 3px", "0", black.a[5]), + ), +) + +# Behind the children, and over them: the background and the border. +_LAYER: dict[str, Any] = { + "content": "''", + "box_sizing": "border-box", + "position": "absolute", + "pointer_events": "none", + "transition_property": "inherit", + "transition_duration": "inherit", + "transition_timing_function": "inherit", + "transition_delay": "inherit", + "border_radius": f"calc(var({_RADIUS}) - var({_BORDER}))", + "inset": f"var({_BORDER})", +} + +_PANEL: dict[str, Any] = { + "background_color": f"var({_BACKGROUND})", + "backdrop_filter": tokens.panel.backdrop_filter, +} + +_SIZES = {"1": (3, 4), "2": (4, 4), "3": (5, 5), "4": (6, 5), "5": (8, 6)} + +_INSET_PADDING = f"calc(var({_PADDING}) - var({_BORDER}))" +_GHOST_MARGIN = f"calc(0px - var({_PADDING}))" + +# What everything a card does not set is, when it is rendered as a link or a +# button: Radix Themes unsets all of what the browser gives either. +_RESET: dict[str, Any] = { + "margin": "0", + "border_width": "0", + # A reset of the page gives every element a border style, which is kept + # where Radix Themes keeps it. + "border_style": {":is(a, button)": "none"}, + "background_color": "transparent", + "background_image": "none", + "appearance": "none", + "color": "inherit", + "font_size": "inherit", + # Radix Themes names a font weight that no token defines here, which + # leaves the weight of what is around the card. + "font_weight": "inherit", + "line_height": "inherit", + "letter_spacing": "inherit", + "text_decoration_line": "none", + "text_transform": "inherit", + "text_indent": "initial", + "text_shadow": "inherit", + "word_spacing": "inherit", + "cursor": { + ":where(button):not(:disabled, [data-disabled])": tokens.cursor.button, + ":any-link:not([data-disabled])": tokens.cursor.link, + ":is(:disabled, [data-disabled])": tokens.cursor.disabled, + }, + "outline_style": {"default": "none", ":focus-visible": "solid"}, + "WebkitTapHighlightColor": "transparent", +} + +CARD: ComponentStyles = { + "base": unchecked({ + **_RESET, + "display": "block", + "position": "relative", + "overflow": "hidden", + "border_radius": f"var({_RADIUS})", + "font_family": tokens.default.font_family, + "font_style": "normal", + "text_align": "start", + "padding": f"var({_PADDING})", + "box_sizing": "border-box", + # A stacking context, so that the background stays over what is + # behind the card. + "contain": "paint", + "--inset-border-width": f"var({_BORDER})", + "--inset-border-radius": f"var({_RADIUS})", + "--inset-padding-top": _INSET_PADDING, + "--inset-padding-right": _INSET_PADDING, + "--inset-padding-bottom": _INSET_PADDING, + "--inset-padding-left": _INSET_PADDING, + "_before": { + **_LAYER, + "z_index": -1, + f":focus-visible{_PRESSED}": { + "background_image": f"linear-gradient({focus.a[2]}, {focus.a[2]})", + }, + # Instead of the highlight of a tap, which is turned off. + _TOUCH: { + f"{_LINK}:active:not(:focus-visible, {_OPEN})": { + "background_image": f"linear-gradient({gray.a[4]}, {gray.a[4]})", + }, + }, + }, + "_after": { + **_LAYER, + ":focus-visible": { + "outline_width": "2px", + "outline_style": "solid", + "outline_color": focus[8], + }, + }, + ":focus-visible": { + "outline_width": "2px", + "outline_color": focus[8], + "outline_offset": "-1px", + }, + }), + "variants": { + "size": { + size: unchecked({ + _PADDING: tokens.space[space], + _RADIUS: tokens.radius[radius], + }) + for size, (space, radius) in _SIZES.items() + }, + "variant": { + "surface": unchecked({ + _BORDER: "1px", + _BACKGROUND: tokens.color.panel, + "_before": _PANEL, + "_after": { + "box_shadow": f"0 0 0 1px {_mix(5)}", + **_states( + {"box_shadow": f"0 0 0 1px {_mix(7)}"}, + {"box_shadow": f"0 0 0 1px {_mix(6)}"}, + ), + }, + }), + "classic": unchecked({ + _BORDER: "1px", + _BACKGROUND: tokens.color.panel, + "transition_property": "box-shadow", + "transition_duration": "120ms", + "box_shadow": _CLASSIC_OUTER, + **_states( + { + "transition_duration": "40ms", + "box_shadow": _CLASSIC_HOVER_OUTER, + }, + { + "transition_duration": "40ms", + "box_shadow": _CLASSIC_ACTIVE_OUTER, + }, + ), + "_before": _PANEL, + "_after": { + "box_shadow": _CLASSIC_INNER, + **_states( + {"box_shadow": _CLASSIC_HOVER_INNER}, + {"box_shadow": _CLASSIC_ACTIVE_INNER}, + ), + }, + }), + "ghost": unchecked({ + _BORDER: "0px", + # It reaches as far out as its padding, so that what it + # holds lines up with what is around it. + "margin": _GHOST_MARGIN, + "background_color": { + _POINTER: { + f"{_LINK}:hover:not(:active, :focus-visible)": gray.a[3], + f"{_LINK}:hover:focus-visible": focus.a[2], + }, + f"{_LINK}{_OPEN}:not(:focus-visible)": gray.a[3], + f"{_LINK}:active:not({_OPEN}, :focus-visible)": gray.a[4], + f"{_LINK}:focus-visible:is(:active, {_OPEN})": focus.a[2], + }, + }), + }, + }, + "defaults": {"size": "1", "variant": "surface"}, +} diff --git a/tests/units/reflex_components_ui/components/test_card.py b/tests/units/reflex_components_ui/components/test_card.py new file mode 100644 index 00000000000..74c08d9eacf --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_card.py @@ -0,0 +1,974 @@ +"""Tests for reflex_components_ui.components.card.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +def test_card_plain( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A card is a surface of the first size, drawn by two pseudo-elements.""" + component = rx.ui.card("Invoice") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_8966fad991_c"], + "children": [{"contents": '"Invoice"'}], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": {":is(a, button)": "none"}, + "borderRightStyle": {":is(a, button)": "none"}, + "borderBottomStyle": {":is(a, button)": "none"}, + "borderLeftStyle": {":is(a, button)": "none"}, + "backgroundColor": { + "default": "transparent", + "::before": "var(--card-background-color)", + }, + "backgroundImage": { + "default": "none", + "::before": { + ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + "var(--focus-a2))", + "@media (pointer: coarse)": { + ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + "var(--gray-a4))" + }, + }, + }, + "appearance": "none", + "color": "inherit", + "fontSize": "inherit", + "fontWeight": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "textDecorationLine": "none", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + ":where(button):not(:disabled, [data-disabled])": "var(--cursor-button)", + ":any-link:not([data-disabled])": "var(--cursor-link)", + ":is(:disabled, [data-disabled])": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + ":focus-visible": "solid", + "::after": {":focus-visible": "solid"}, + }, + "WebkitTapHighlightColor": "transparent", + "display": "block", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--card-border-radius)", + "::before": "calc(var(--card-border-radius) - " + "var(--card-border-width))", + "::after": "calc(var(--card-border-radius) - var(--card-border-width))", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "padding": "var(--card-padding)", + "boxSizing": { + "default": "border-box", + "::before": "border-box", + "::after": "border-box", + }, + "contain": "paint", + "--inset-border-width": "var(--card-border-width)", + "--inset-border-radius": "var(--card-border-radius)", + "--inset-padding-top": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-right": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-bottom": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-left": "calc(var(--card-padding) - var(--card-border-width))", + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": {"::before": "inherit", "::after": "inherit"}, + "transitionDuration": {"::before": "inherit", "::after": "inherit"}, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "inset": { + "::before": "var(--card-border-width)", + "::after": "var(--card-border-width)", + }, + "zIndex": {"::before": -1}, + "outlineWidth": { + "::after": {":focus-visible": "2px"}, + ":focus-visible": "2px", + }, + "outlineColor": { + "::after": {":focus-visible": "var(--focus-8)"}, + ":focus-visible": "var(--focus-8)", + }, + "outlineOffset": {":focus-visible": "-1px"}, + "--card-padding": "var(--space-3)", + "--card-border-radius": "var(--radius-4)", + "--card-border-width": "1px", + "--card-background-color": "var(--color-panel)", + "backdropFilter": {"::before": "var(--backdrop-filter-panel)"}, + "boxShadow": { + "::after": { + "default": "0 0 0 1px color-mix(in oklab, var(--gray-a5), " + "var(--gray-5) 25%)", + "@media (hover: hover)": { + ":is(:any-link, button, label):hover:not(:active)": "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a7), " + "var(--gray-7) " + "25%)" + }, + ":is(:any-link, button, label)[data-state='open']": "0 0 0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a7), " + "var(--gray-7) " + "25%)", + ":is(:any-link, button, label):active:not([data-state='open'])": "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%)", + } + }, + } + ] + + +def test_card_classic( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The classic card repeats its shadow on itself, one pixel smaller.""" + component = rx.ui.card("Invoice", variant="classic", size="3") + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": {":is(a, button)": "none"}, + "borderRightStyle": {":is(a, button)": "none"}, + "borderBottomStyle": {":is(a, button)": "none"}, + "borderLeftStyle": {":is(a, button)": "none"}, + "backgroundColor": { + "default": "transparent", + "::before": "var(--card-background-color)", + }, + "backgroundImage": { + "default": "none", + "::before": { + ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + "var(--focus-a2))", + "@media (pointer: coarse)": { + ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + "var(--gray-a4))" + }, + }, + }, + "appearance": "none", + "color": "inherit", + "fontSize": "inherit", + "fontWeight": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "textDecorationLine": "none", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + ":where(button):not(:disabled, [data-disabled])": "var(--cursor-button)", + ":any-link:not([data-disabled])": "var(--cursor-link)", + ":is(:disabled, [data-disabled])": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + ":focus-visible": "solid", + "::after": {":focus-visible": "solid"}, + }, + "WebkitTapHighlightColor": "transparent", + "display": "block", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--card-border-radius)", + "::before": "calc(var(--card-border-radius) - " + "var(--card-border-width))", + "::after": "calc(var(--card-border-radius) - var(--card-border-width))", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "padding": "var(--card-padding)", + "boxSizing": { + "default": "border-box", + "::before": "border-box", + "::after": "border-box", + }, + "contain": "paint", + "--inset-border-width": "var(--card-border-width)", + "--inset-border-radius": "var(--card-border-radius)", + "--inset-padding-top": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-right": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-bottom": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-left": "calc(var(--card-padding) - var(--card-border-width))", + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": { + "default": "box-shadow", + "::before": "inherit", + "::after": "inherit", + }, + "transitionDuration": { + "default": "120ms", + "@media (hover: hover)": { + ":is(:any-link, button, label):hover:not(:active)": "40ms" + }, + ":is(:any-link, button, label)[data-state='open']": "40ms", + ":is(:any-link, button, label):active:not([data-state='open'])": "40ms", + "::before": "inherit", + "::after": "inherit", + }, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "inset": { + "::before": "var(--card-border-width)", + "::after": "var(--card-border-width)", + }, + "zIndex": {"::before": -1}, + "outlineWidth": { + "::after": {":focus-visible": "2px"}, + ":focus-visible": "2px", + }, + "outlineColor": { + "::after": {":focus-visible": "var(--focus-8)"}, + ":focus-visible": "var(--focus-8)", + }, + "outlineOffset": {":focus-visible": "-1px"}, + "--card-padding": "var(--space-5)", + "--card-border-radius": "var(--radius-5)", + "--card-border-width": "1px", + "--card-background-color": "var(--color-panel)", + "boxShadow": { + "default": "var(--rx-if-light, 0 0 0 0 color-mix(in oklab, " + "var(--gray-a3), var(--gray-3) 25%), 0 0 0 0 " + "var(--color-transparent), 0 0 0 0 var(--black-a1), 0 1px " + "1px -1px var(--gray-a2), 0 2px 1px -2px var(--black-a1), 0 " + "1px 3px -1px var(--black-a1)) var(--rx-if-dark, 0 0 0 0 " + "color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 " + "0 0 0 var(--color-transparent), 0 0 0 0 var(--black-a3), 0 " + "1px 1px -1px var(--black-a6), 0 2px 1px -2px " + "var(--black-a6), 0 1px 3px -1px var(--black-a5))", + "@media (hover: hover)": { + ":is(:any-link, button, label):hover:not(:active)": "var(--rx-if-light, " + "0 " + "0 " + "0 " + "0 " + "color-mix(in " + "oklab, " + "var(--gray-a4), " + "var(--gray-4) " + "25%), " + "0 " + "1px " + "1px " + "0 " + "var(--black-a1), " + "0 " + "2px " + "1px " + "-2px " + "var(--gray-a3), " + "0 " + "2px " + "3px " + "-3px " + "var(--black-a1), " + "0 " + "3px " + "12px " + "-5px " + "var(--gray-a3), " + "0 " + "4px " + "16px " + "-9px " + "var(--black-a1)) " + "var(--rx-if-dark, " + "0 " + "0 " + "0 " + "0 " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%), " + "0 " + "0 " + "1px " + "0 " + "var(--gray-a4), " + "0 " + "0 " + "1px " + "-2px " + "var(--gray-a4), " + "0 " + "0 " + "3px " + "-3px " + "var(--gray-a3), " + "0 " + "0 " + "12px " + "-3px " + "var(--gray-a3), " + "0 " + "0 " + "16px " + "-9px " + "var(--gray-a7))" + }, + ":is(:any-link, button, label)[data-state='open']": "var(--rx-if-light, " + "0 0 0 0 " + "color-mix(in " + "oklab, " + "var(--gray-a4), " + "var(--gray-4) " + "25%), 0 1px 1px 0 " + "var(--black-a1), " + "0 2px 1px -2px " + "var(--gray-a3), 0 " + "2px 3px -3px " + "var(--black-a1), " + "0 3px 12px -5px " + "var(--gray-a3), 0 " + "4px 16px -9px " + "var(--black-a1)) " + "var(--rx-if-dark, " + "0 0 0 0 " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%), 0 0 1px 0 " + "var(--gray-a4), 0 " + "0 1px -2px " + "var(--gray-a4), 0 " + "0 3px -3px " + "var(--gray-a3), 0 " + "0 12px -3px " + "var(--gray-a3), 0 " + "0 16px -9px " + "var(--gray-a7))", + ":is(:any-link, button, label):active:not([data-state='open'])": "var(--rx-if-light, " + "0 0 " + "0 0 " + "color-mix(in " + "oklab, " + "var(--gray-a3), " + "var(--gray-3) " + "25%), " + "0 0 " + "0 0 " + "var(--color-transparent), " + "0 0 " + "0 0 " + "var(--black-a1), " + "0 " + "1px " + "1px " + "-1px " + "var(--gray-a4), " + "0 " + "2px " + "1px " + "-2px " + "var(--black-a1), " + "0 " + "1px " + "3px " + "-1px " + "var(--black-a1)) " + "var(--rx-if-dark, " + "0 0 " + "0 0 " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%), " + "0 0 " + "0 0 " + "var(--color-transparent), " + "0 0 " + "0 0 " + "var(--black-a3), " + "0 " + "1px " + "1px " + "-1px " + "var(--black-a6), " + "0 " + "2px " + "1px " + "-2px " + "var(--black-a6), " + "0 " + "1px " + "3px " + "-1px " + "var(--black-a5))", + "::after": { + "default": "var(--rx-if-light, 0 0 0 1px color-mix(in " + "oklab, var(--gray-a3), var(--gray-3) 25%), 0 0 " + "0 1px var(--color-transparent), 0 0 0 0.5px " + "var(--black-a1), 0 1px 1px 0 var(--gray-a2), 0 " + "2px 1px -1px var(--black-a1), 0 1px 3px 0 " + "var(--black-a1)) var(--rx-if-dark, 0 0 0 1px " + "color-mix(in oklab, var(--gray-a6), " + "var(--gray-6) 25%), 0 0 0 1px " + "var(--color-transparent), 0 0 0 0.5px " + "var(--black-a3), 0 1px 1px 0 var(--black-a6), " + "0 2px 1px -1px var(--black-a6), 0 1px 3px 0 " + "var(--black-a5))", + "@media (hover: hover)": { + ":is(:any-link, button, label):hover:not(:active)": "var(--rx-if-light, " + "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a4), " + "var(--gray-4) " + "25%), " + "0 " + "1px " + "1px " + "1px " + "var(--black-a1), " + "0 " + "2px " + "1px " + "-1px " + "var(--gray-a3), " + "0 " + "2px " + "3px " + "-2px " + "var(--black-a1), " + "0 " + "3px " + "12px " + "-4px " + "var(--gray-a3), " + "0 " + "4px " + "16px " + "-8px " + "var(--black-a1)) " + "var(--rx-if-dark, " + "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%), " + "0 " + "0 " + "1px " + "1px " + "var(--gray-a4), " + "0 " + "0 " + "1px " + "-1px " + "var(--gray-a4), " + "0 " + "0 " + "3px " + "-2px " + "var(--gray-a3), " + "0 " + "0 " + "12px " + "-2px " + "var(--gray-a3), " + "0 " + "0 " + "16px " + "-8px " + "var(--gray-a7))" + }, + ":is(:any-link, button, label)[data-state='open']": "var(--rx-if-light, " + "0 0 0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a4), " + "var(--gray-4) " + "25%), " + "0 1px " + "1px " + "1px " + "var(--black-a1), " + "0 2px " + "1px " + "-1px " + "var(--gray-a3), " + "0 2px " + "3px " + "-2px " + "var(--black-a1), " + "0 3px " + "12px " + "-4px " + "var(--gray-a3), " + "0 4px " + "16px " + "-8px " + "var(--black-a1)) " + "var(--rx-if-dark, " + "0 0 0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%), " + "0 0 " + "1px " + "1px " + "var(--gray-a4), " + "0 0 " + "1px " + "-1px " + "var(--gray-a4), " + "0 0 " + "3px " + "-2px " + "var(--gray-a3), " + "0 0 " + "12px " + "-2px " + "var(--gray-a3), " + "0 0 " + "16px " + "-8px " + "var(--gray-a7))", + ":is(:any-link, button, label):active:not([data-state='open'])": "var(--rx-if-light, " + "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a3), " + "var(--gray-3) " + "25%), " + "0 " + "0 " + "0 " + "1px " + "var(--color-transparent), " + "0 " + "0 " + "0 " + "0.5px " + "var(--black-a1), " + "0 " + "1px " + "1px " + "0 " + "var(--gray-a4), " + "0 " + "2px " + "1px " + "-1px " + "var(--black-a1), " + "0 " + "1px " + "3px " + "0 " + "var(--black-a1)) " + "var(--rx-if-dark, " + "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%), " + "0 " + "0 " + "0 " + "1px " + "var(--color-transparent), " + "0 " + "0 " + "0 " + "0.5px " + "var(--black-a3), " + "0 " + "1px " + "1px " + "0 " + "var(--black-a6), " + "0 " + "2px " + "1px " + "-1px " + "var(--black-a6), " + "0 " + "1px " + "3px " + "0 " + "var(--black-a5))", + }, + }, + "backdropFilter": {"::before": "var(--backdrop-filter-panel)"}, + } + ] + + +def test_card_ghost_responsive( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A ghost card takes back its padding, at each size of a breakpoint.""" + component = rx.ui.card( + "Invoice", variant="ghost", size=rx.breakpoints(initial="1", md="4") + ) + assert declared_styles(component) == [ + { + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": {":is(a, button)": "none"}, + "borderRightStyle": {":is(a, button)": "none"}, + "borderBottomStyle": {":is(a, button)": "none"}, + "borderLeftStyle": {":is(a, button)": "none"}, + "backgroundColor": { + "default": "transparent", + "@media (hover: hover)": { + ":is(:any-link, button, label):hover:not(:active, :focus-visible)": "var(--gray-a3)", + ":is(:any-link, button, label):hover:focus-visible": "var(--focus-a2)", + }, + ":is(:any-link, button, label)[data-state='open']:not(:focus-visible)": "var(--gray-a3)", + ":is(:any-link, button, label):active:not([data-state='open'], :focus-visible)": "var(--gray-a4)", + ":is(:any-link, button, label):focus-visible:is(:active, [data-state='open'])": "var(--focus-a2)", + }, + "backgroundImage": { + "default": "none", + "::before": { + ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + "var(--focus-a2))", + "@media (pointer: coarse)": { + ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + "var(--gray-a4))" + }, + }, + }, + "appearance": "none", + "color": "inherit", + "fontSize": "inherit", + "fontWeight": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "textDecorationLine": "none", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + ":where(button):not(:disabled, [data-disabled])": "var(--cursor-button)", + ":any-link:not([data-disabled])": "var(--cursor-link)", + ":is(:disabled, [data-disabled])": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + ":focus-visible": "solid", + "::after": {":focus-visible": "solid"}, + }, + "WebkitTapHighlightColor": "transparent", + "display": "block", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--card-border-radius)", + "::before": "calc(var(--card-border-radius) - " + "var(--card-border-width))", + "::after": "calc(var(--card-border-radius) - var(--card-border-width))", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "padding": "var(--card-padding)", + "boxSizing": { + "default": "border-box", + "::before": "border-box", + "::after": "border-box", + }, + "contain": "paint", + "--inset-border-width": "var(--card-border-width)", + "--inset-border-radius": "var(--card-border-radius)", + "--inset-padding-top": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-right": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-bottom": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-left": "calc(var(--card-padding) - var(--card-border-width))", + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": {"::before": "inherit", "::after": "inherit"}, + "transitionDuration": {"::before": "inherit", "::after": "inherit"}, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "inset": { + "::before": "var(--card-border-width)", + "::after": "var(--card-border-width)", + }, + "zIndex": {"::before": -1}, + "outlineWidth": { + "::after": {":focus-visible": "2px"}, + ":focus-visible": "2px", + }, + "outlineColor": { + "::after": {":focus-visible": "var(--focus-8)"}, + ":focus-visible": "var(--focus-8)", + }, + "outlineOffset": {":focus-visible": "-1px"}, + "--card-padding": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "var(--space-6)", + }, + "--card-border-radius": { + "default": "var(--radius-4)", + "@media (min-width: 1024px)": "var(--radius-5)", + }, + "--card-border-width": "0px", + "margin": "calc(0px - var(--card-padding))", + } + ] + + +def test_card_as_child( + ui_plugin: UIPlugin, +): + """A card rendered as a link is the link, with the styles of the card.""" + component = rx.ui.card(rx.el.a("Invoice", href="/invoice"), as_child=True) + assert component.render() == { + "name": "ReactRouterLink", + "props": ["className:sx_8966fad991_c", 'to:"/invoice"'], + "children": [{"contents": '"Invoice"'}], + } + + +def test_card_keeps_its_surface_under_a_background( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A style of the element leaves the pseudo-elements what the card gives them.""" + component = rx.ui.card("Invoice", background_color="red") + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": {":is(a, button)": "none"}, + "borderRightStyle": {":is(a, button)": "none"}, + "borderBottomStyle": {":is(a, button)": "none"}, + "borderLeftStyle": {":is(a, button)": "none"}, + "backgroundColor": { + "default": "red", + "::before": "var(--card-background-color)", + }, + "backgroundImage": { + "default": "none", + "::before": { + ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + "var(--focus-a2))", + "@media (pointer: coarse)": { + ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + "var(--gray-a4))" + }, + }, + }, + "appearance": "none", + "color": "inherit", + "fontSize": "inherit", + "fontWeight": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "textDecorationLine": "none", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + ":where(button):not(:disabled, [data-disabled])": "var(--cursor-button)", + ":any-link:not([data-disabled])": "var(--cursor-link)", + ":is(:disabled, [data-disabled])": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + ":focus-visible": "solid", + "::after": {":focus-visible": "solid"}, + }, + "WebkitTapHighlightColor": "transparent", + "display": "block", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--card-border-radius)", + "::before": "calc(var(--card-border-radius) - " + "var(--card-border-width))", + "::after": "calc(var(--card-border-radius) - var(--card-border-width))", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "padding": "var(--card-padding)", + "boxSizing": { + "default": "border-box", + "::before": "border-box", + "::after": "border-box", + }, + "contain": "paint", + "--inset-border-width": "var(--card-border-width)", + "--inset-border-radius": "var(--card-border-radius)", + "--inset-padding-top": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-right": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-bottom": "calc(var(--card-padding) - var(--card-border-width))", + "--inset-padding-left": "calc(var(--card-padding) - var(--card-border-width))", + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": {"::before": "inherit", "::after": "inherit"}, + "transitionDuration": {"::before": "inherit", "::after": "inherit"}, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "inset": { + "::before": "var(--card-border-width)", + "::after": "var(--card-border-width)", + }, + "zIndex": {"::before": -1}, + "outlineWidth": { + "::after": {":focus-visible": "2px"}, + ":focus-visible": "2px", + }, + "outlineColor": { + "::after": {":focus-visible": "var(--focus-8)"}, + ":focus-visible": "var(--focus-8)", + }, + "outlineOffset": {":focus-visible": "-1px"}, + "--card-padding": "var(--space-3)", + "--card-border-radius": "var(--radius-4)", + "--card-border-width": "1px", + "--card-background-color": "var(--color-panel)", + "backdropFilter": {"::before": "var(--backdrop-filter-panel)"}, + "boxShadow": { + "::after": { + "default": "0 0 0 1px color-mix(in oklab, var(--gray-a5), " + "var(--gray-5) 25%)", + "@media (hover: hover)": { + ":is(:any-link, button, label):hover:not(:active)": "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a7), " + "var(--gray-7) " + "25%)" + }, + ":is(:any-link, button, label)[data-state='open']": "0 0 0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a7), " + "var(--gray-7) " + "25%)", + ":is(:any-link, button, label):active:not([data-state='open'])": "0 " + "0 " + "0 " + "1px " + "color-mix(in " + "oklab, " + "var(--gray-a6), " + "var(--gray-6) " + "25%)", + } + }, + } + ] + + +def test_card_rejects_a_value_a_prop_does_not_take(): + """The error names the component, the prop and the values it takes.""" + with pytest.raises(StyleError) as raised: + rx.ui.card("Invoice", variant="solid") # pyright: ignore[reportArgumentType] + assert str(raised.value) == ( + 'rx.ui.card: unknown variant "solid". The values are "surface", ' + '"classic", "ghost".' + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index ac6847bf5d1..7e09b4a12b5 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -108,6 +108,7 @@ def test_every_wave_is_in_the_namespace(): "blockquote", "box", "button", + "card", "center", "code", "container", From 797c4a90aacc65515fdcacecd4f80888646c058f Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 22:46:28 +0000 Subject: [PATCH 055/204] Add rx.ui.avatar: an image over its fallback, and the one script that follows its load Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../reflex-components-ui/js/src/README.md | 3 + .../js/src/behaviors/image-status.js | 35 +++ .../js/tests/behaviors/image-status.test.js | 108 ++++++++ .../parity/allowlist.toml | 18 ++ .../parity/ui_parity/components/avatar.py | 122 ++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/avatar.py | 117 ++++++++ .../src/reflex_components_ui/styles/avatar.py | 204 ++++++++++++++ .../components/test_avatar.py | 262 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 10 files changed, 871 insertions(+) create mode 100644 packages/reflex-components-ui/js/src/behaviors/image-status.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/image-status.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/avatar.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py create mode 100644 tests/units/reflex_components_ui/components/test_avatar.py diff --git a/packages/reflex-components-ui/js/src/README.md b/packages/reflex-components-ui/js/src/README.md index 00144678adf..bbb5d499802 100644 --- a/packages/reflex-components-ui/js/src/README.md +++ b/packages/reflex-components-ui/js/src/README.md @@ -12,6 +12,9 @@ is overwritten. 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. +- `behaviors/` holds the little a component needs a script for, each in a + module a page imports only with that component: `image-status.js` tells an + avatar how the load of its image ended. - `vite-plugin-stylex.js` is the plugin `vite.config.js` loads to compile the styles. diff --git a/packages/reflex-components-ui/js/src/behaviors/image-status.js b/packages/reflex-components-ui/js/src/behaviors/image-status.js new file mode 100644 index 00000000000..58bae36d55f --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/image-status.js @@ -0,0 +1,35 @@ +// How the load of an image ended, said on the image and on what stands in +// for it, so that their styles show one of the two. +// +// The server renders both: the image lies over its stand-in, so a page shows +// a loaded image before this runs, and without JavaScript. An image may have +// loaded, or failed, before React attaches: its events are gone by then, and +// the image itself says how it ended. + +/** + * Follow the load of an image: the `ref` of the `img` element. + * + * `data-status` is `loaded` or `error`, on the image and on the element + * before it. Nothing is rendered again. + * + * @param {HTMLImageElement | null} image The image, or null when it leaves. + * @returns {(() => void) | undefined} What stops following it. + */ +export function watchImage(image) { + if (!image) return undefined; + const settle = () => { + const status = image.naturalWidth > 0 ? "loaded" : "error"; + image.dataset.status = status; + const standIn = image.previousElementSibling; + if (standIn instanceof HTMLElement) standIn.dataset.status = status; + }; + // Already over, before or without an event: an image the browser had + // loaded or given up on before hydration, or one without an address. + if (image.complete) settle(); + image.addEventListener("load", settle); + image.addEventListener("error", settle); + return () => { + image.removeEventListener("load", settle); + image.removeEventListener("error", settle); + }; +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/image-status.test.js b/packages/reflex-components-ui/js/tests/behaviors/image-status.test.js new file mode 100644 index 00000000000..918766c7ec5 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/image-status.test.js @@ -0,0 +1,108 @@ +// What an avatar follows the load of its image with: the image and what +// stands in for it are both in the page, and each is told how the load ended. +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { watchImage } from "$/reflex-ui/behaviors/image-status.js"; + +// jsdom loads no image: a test says how the load of each address stands. +/** @type {Record} */ +let images; + +/** @type {HTMLElement} */ +let standIn; +/** @type {HTMLImageElement} */ +let image; + +/** + * Put an avatar in the page: a stand-in, then its image. + * + * @param {string} src The address of the image. + */ +function render(src) { + document.body.innerHTML = `AB`; + standIn = /** @type {HTMLElement} */ (document.querySelector("span > span")); + image = /** @type {HTMLImageElement} */ (document.querySelector("img")); +} + +/** + * Read what the image and its stand-in were told. + * + * @returns {(string | undefined)[]} The status of the stand-in, then of the image. + */ +function statuses() { + return [standIn.dataset.status, image.dataset.status]; +} + +beforeEach(() => { + images = { + "/loading.png": { complete: false, naturalWidth: 0 }, + "/loaded.png": { complete: true, naturalWidth: 32 }, + "/broken.png": { complete: true, naturalWidth: 0 }, + }; + for (const property of /** @type {const} */ (["complete", "naturalWidth"])) { + vi.spyOn(HTMLImageElement.prototype, property, "get").mockImplementation( + /** @this {HTMLImageElement} */ + function () { + return images[this.getAttribute("src") ?? ""]?.[property]; + }, + ); + } +}); + +afterEach(() => { + vi.restoreAllMocks(); + document.body.innerHTML = ""; +}); + +test("an image that loaded before it was followed is loaded at once", () => { + render("/loaded.png"); + watchImage(image); + expect(statuses()).toEqual(["loaded", "loaded"]); +}); + +test("an image that failed before it was followed is an error at once", () => { + render("/broken.png"); + watchImage(image); + expect(statuses()).toEqual(["error", "error"]); +}); + +test("an image that is loading says nothing until its event", () => { + render("/loading.png"); + watchImage(image); + expect(statuses()).toEqual([undefined, undefined]); + images["/loading.png"] = { complete: true, naturalWidth: 32 }; + image.dispatchEvent(new Event("load")); + expect(statuses()).toEqual(["loaded", "loaded"]); +}); + +test("an image that fails while it is followed is an error", () => { + render("/loading.png"); + watchImage(image); + image.dispatchEvent(new Event("error")); + expect(statuses()).toEqual(["error", "error"]); +}); + +test("a new address is followed on the same image", () => { + render("/broken.png"); + watchImage(image); + image.setAttribute("src", "/loaded.png"); + image.dispatchEvent(new Event("load")); + expect(statuses()).toEqual(["loaded", "loaded"]); +}); + +test("an image that left is no longer followed", () => { + render("/loading.png"); + const stop = watchImage(image); + expect(typeof stop).toBe("function"); + stop?.(); + image.dispatchEvent(new Event("error")); + expect(statuses()).toEqual([undefined, undefined]); + expect(watchImage(null)).toBeUndefined(); +}); + +test("an image alone is told, with nothing before it", () => { + document.body.innerHTML = ``; + image = /** @type {HTMLImageElement} */ (document.querySelector("img")); + watchImage(image); + expect(image.dataset.status).toBe("error"); +}); diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 2290fa42372..25c7e2c98ba 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -36,3 +36,21 @@ check = "style" cells = "*orientation-responsive*" properties = ["flex-direction", "align-items", "grid-template-columns", "grid-column-start", "width"] reason = "When the orientation of rx.data_list changes at a breakpoint, Radix Themes keeps what the orientation before it declared and the new one does not: the direction of a column on the grid of a horizontal list, and the columns and the baseline alignment of a grid on the items of a vertical one, whose labels and values are then as wide as their text. rx.ui.data_list gives each breakpoint the styles of its orientation alone, so a list that turns vertical is the vertical list: labels and values are as wide as the list. Nothing is drawn differently." + +[[contract]] +component = "avatar" +step = "the fallback is in the server render" +system = "rx" +reason = "rx.avatar renders its fallback and its image once JavaScript has run: the server sends an empty placeholder. rx.ui.avatar sends both, so the page shows the avatar before it is hydrated." + +[[contract]] +component = "avatar" +step = "shows a loaded image and the fallback without JavaScript" +system = "rx" +reason = "rx.avatar shows neither its image nor its fallback with JavaScript disabled. rx.ui.avatar shows the fallback, and the image over it once it has loaded; only an image that fails needs JavaScript to give way to the fallback." + +[[look]] +component = "avatar" +check = "pixels" +cells = "size-responsive-large@800" +reason = "When the size of rx.avatar grows at a breakpoint from one of the four small sizes to a larger one, Radix Themes keeps the smaller letters the small size has for a fallback of two letters. rx.ui.avatar gives the two letters the size they have in an avatar of the larger size alone." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/avatar.py b/packages/reflex-components-ui/parity/ui_parity/components/avatar.py new file mode 100644 index 00000000000..fad70aa8646 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/avatar.py @@ -0,0 +1,122 @@ +"""The avatar: an image, and the fallback that shows until it loads or when it fails.""" + +from __future__ import annotations + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, LIGHT, Matrix +from ui_parity.samples import ACCENTS + +# A checkerboard of eight pixels a side: nothing is loaded from a network. +IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAJUlEQVR4nGM8YRPFAAMJcnlwNhMDDkC6BKNG1Ak4Z8GjSbSwAwDxyAW3Fur+BAAAAABJRU5ErkJggg==" +# An address that is no image. +BROKEN = "data:image/png;base64,AAAA" + +SIZES = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] +RESPONSIVE = rx.breakpoints(initial="1", sm="4", lg="2") +# From a size with a smaller size for two letters to one without. +RESPONSIVE_LARGE = rx.breakpoints(initial="2", sm="6") + +MATRIX = Matrix( + component="avatar", + base={"fallback": "AB"}, + cross={"size": SIZES, "fallback": ["A", "AB", "ABC"]}, + sweep={ + "variant": ["solid", "soft"], + "color_scheme": ACCENTS, + "radius": ["none", "small", "medium", "large", "full"], + "high_contrast": [True], + "src": {"image": IMAGE, "broken": BROKEN}, + "size": {"responsive": RESPONSIVE}, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "variant": ["solid", "soft"], + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + { + "variant": ["solid", "soft"], + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + {"src": {"image": IMAGE, "broken": BROKEN}, "size": ["1", "5", "9"]}, + { + "src": {"image": IMAGE, "broken": BROKEN}, + "variant": ["solid", "soft"], + "radius": ["none", "full"], + }, + {"radius": ["none", "full"], "size": ["1", "5", "9"]}, + {"size": {"responsive": RESPONSIVE}, "viewport": [520, 800, 1100, 1280]}, + {"size": {"responsive-large": RESPONSIVE_LARGE}, "viewport": [520, 800]}, + ], + stage=(200, 200), + # Not held to zero, for the image alone: at a threshold of zero every + # cell without an image is equal pixel for pixel, and so are most with + # one. The image is a checkerboard of eight pixels scaled up, and where + # its two colors meet the browser interpolates them by where the avatar + # is on the page: 3 of the 13 cells with an image differ there, by at + # most 80 pixels of 30976. +) + +CONTRACT = Contract( + component="avatar", + render=lambda namespace: namespace.box( + rx.el.div(namespace.avatar(src=IMAGE, fallback="AB", alt="Ada"), id="loaded"), + rx.el.div(namespace.avatar(src=BROKEN, fallback="CD", alt="Bo"), id="broken"), + rx.el.div(namespace.avatar(fallback="EF"), id="none"), + ), +) + + +@CONTRACT.step("a loaded image is shown, with its text for the accessibility tree") +def _loaded(run: Run) -> None: + image = run.page.locator("#loaded").get_by_role("img", name="Ada") + image.wait_for() + box = image.bounding_box() + assert box is not None + assert (box["width"], box["height"]) == (40, 40) + assert run.page.locator("#loaded").get_by_text("AB").is_hidden() + + +@CONTRACT.step("the fallback is shown for an image that fails", on=HYDRATED) +def _broken(run: Run) -> None: + fallback = run.page.locator("#broken").get_by_text("CD") + fallback.wait_for() + box = fallback.bounding_box() + assert box is not None + assert (box["width"], box["height"]) == (40, 40) + run.page.wait_for_function( + "!document.querySelector('#broken img')" + " || getComputedStyle(document.querySelector('#broken img')).display === 'none'" + ) + + +@CONTRACT.step("the fallback is shown without an image", on=HYDRATED) +def _none(run: Run) -> None: + assert run.page.locator("#none").get_by_text("EF").is_visible() + assert run.page.locator("#none img").count() == 0 + + +@CONTRACT.step("the fallback is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("none").text == "EF" + assert run.server.element("loaded").text == "AB" + assert run.server.element("broken").text == "CD" + + +@CONTRACT.step( + "shows a loaded image and the fallback without JavaScript", + on=NO_JAVASCRIPT, +) +def _without_javascript(run: Run) -> None: + assert run.page.locator("#none").get_by_text("EF").is_visible() + image = run.page.locator("#loaded img") + assert image.evaluate("image => image.complete && image.naturalWidth") == 8 + box = image.bounding_box() + assert box is not None + assert (box["width"], box["height"]) == (40, 40) + # The image covers the fallback, which is the same box. + assert run.page.locator("#loaded span > span").bounding_box() == box 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 7a5435edcb8..7f840e44510 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -8,6 +8,7 @@ _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { "components.aspect_ratio": ["aspect_ratio"], + "components.avatar": ["avatar"], "components.badge": ["badge"], "components.button": ["button"], "components.card": ["card"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py b/packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py new file mode 100644 index 00000000000..396c51c26e1 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py @@ -0,0 +1,117 @@ +"""An avatar: an image of a user, and what stands in for it.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.avatar import AVATAR +from reflex_components_ui.themes import LiteralAccentColor, LiteralRadius + +LiteralSize = Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"] + +# The ref of the image: it tells the image and the fallback how the load +# ended, which is all the JavaScript of an avatar. +_WATCH_IMAGE = Var( + "watchImage", + _var_data=VarData( + imports={ + f"$/{WEB_DIR}/behaviors/image-status.js": [ImportVar(tag="watchImage")] + } + ), +) + +# The part that holds the fallback, by the number of its letters. +_FALLBACK_PARTS = {1: "fallback_one", 2: "fallback_two"} + + +class AvatarImage(Part, elements.Img): + """The image of an avatar.""" + + tag = "img" + + +class Avatar(UIComponent): + """An image element with a fallback for representing the user.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = AVATAR + + variant: Var[Literal["solid", "soft"]] = field(doc="The variant of the avatar") + + size: Var[Responsive[LiteralSize]] = field(doc='The size of the avatar: "1" - "9"') + + color_scheme: Var[LiteralAccentColor] = field(doc="Color theme of the avatar") + + high_contrast: Var[bool] = field( + doc="Whether to render the avatar with higher contrast color against background" + ) + + radius: Var[LiteralRadius] = field( + doc='Override theme radius for avatar: "none" | "small" | "medium" | "large" | "full"' + ) + + src: Var[str] = field(doc="The src of the avatar image") + + alt: Var[str] = field( + doc='Alternative text for the avatar image. Use "" for a decorative image whose name is already shown next to it.' + ) + + fallback: Var[str] = field(doc="The rendered fallback text") + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes of the element off it. + + Returns: + The props read as styles, and the ones of the image and of the + fallback inside. + """ + return [*super()._exclude_props(), "src", "alt", "fallback"] + + @classmethod + def create(cls, *children, **props) -> Component: + """Create an avatar: the fallback, and the image over it when it has one. + + The fallback shows until the image has loaded, and when it fails. An + avatar without a ``src`` is its fallback alone, and has no JavaScript. + + Args: + *children: The children of the component. + **props: The props of the component. + + Returns: + The avatar. + """ + fallback = props.get("fallback") + letters = fallback + if isinstance(fallback, LiteralVar): + letters = fallback._var_value + # The size of the letters follows their number, which only a literal + # says while compiling: any other fallback has the size around it. + part = _FALLBACK_PARTS.get(len(letters) if isinstance(letters, str) else 0) + parts = [ + Part.create( + *([] if fallback is None else [fallback]), + part=part or "fallback", + tag="span", + ) + ] + src = props.get("src") + if src is not None: + image_props = {"src": src, "custom_attrs": {"ref": _WATCH_IMAGE}} + if "alt" in props: + image_props["alt"] = props["alt"] + parts.append(AvatarImage.create(part="image", **image_props)) + return super().create(*parts, *children, **props) + + +avatar = Avatar.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py new file mode 100644 index 00000000000..01da17ed1c3 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py @@ -0,0 +1,204 @@ +"""The look of an avatar: an image over what stands in for it.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.typography import ACCENT_SCOPE + +accent = tokens.accent + +_SIZE = "--avatar-size" +_ONE_LETTER = "--avatar-fallback-one-letter-font-size" +_TWO_LETTERS = "--avatar-fallback-two-letters-font-size" + +# The side of each size, the sizes of one and of two letters, the radius and +# the letter spacing. The larger sizes have one size of letters. +_SIZES: dict[str, tuple[str, str, str | None, str, str]] = { + "1": ( + tokens.space[5], + tokens.font_size[2], + tokens.font_size[1], + tokens.radius[2], + tokens.letter_spacing[1], + ), + "2": ( + tokens.space[6], + tokens.font_size[3], + tokens.font_size[2], + tokens.radius[2], + tokens.letter_spacing[2], + ), + "3": ( + tokens.space[7], + tokens.font_size[4], + tokens.font_size[3], + tokens.radius[3], + tokens.letter_spacing[3], + ), + "4": ( + tokens.space[8], + tokens.font_size[5], + tokens.font_size[4], + tokens.radius[3], + tokens.letter_spacing[4], + ), + "5": ( + tokens.space[9], + tokens.font_size[6], + None, + tokens.radius[4], + tokens.letter_spacing[6], + ), + "6": ( + "80px", + tokens.font_size[7], + None, + tokens.radius[5], + tokens.letter_spacing[7], + ), + "7": ( + "96px", + tokens.font_size[7], + None, + tokens.radius[5], + tokens.letter_spacing[7], + ), + "8": ( + "128px", + tokens.font_size[8], + None, + tokens.radius[6], + tokens.letter_spacing[8], + ), + "9": ( + "160px", + tokens.font_size[9], + None, + tokens.radius[6], + tokens.letter_spacing[9], + ), +} + + +def _size( + side: str, one: str, two: str | None, radius: str, spacing: str +) -> dict[str, str]: + """Make the styles of one size. + + Args: + side: The width and the height. + one: The font size of a fallback of one letter. + two: The font size of a fallback of two letters, when it is smaller. + radius: The radius of the corners. + spacing: The letter spacing. + + Returns: + The styles. + """ + style = { + _SIZE: side, + _ONE_LETTER: one, + "border_radius": f"max({radius}, {tokens.radius.full})", + "letter_spacing": spacing, + } + if two is not None: + style[_TWO_LETTERS] = two + return style + + +def _fallback(font_size: str | None) -> ComponentStyles: + """Make the table of what stands in for the image. + + Args: + font_size: The size of its letters, when their number says it. + + Returns: + The table. + """ + base: dict[str, Any] = { + "box_sizing": "border-box", + "font_family": tokens.default.font_family, + "font_weight": tokens.font_weight.medium, + "font_style": "normal", + "z_index": 0, + "width": "100%", + "height": "100%", + "display": "flex", + "align_items": "center", + "justify_content": "center", + "line_height": 1, + "border_radius": "inherit", + "text_transform": "uppercase", + # Under the image, which is as large: neither gives way to the other. + "flex_shrink": 0, + # An image that loaded is all there is to see, see-through or not. + "visibility": {"[data-status='loaded']": "hidden"}, + } + if font_size is not None: + base["font_size"] = font_size + return { + "base": unchecked(base), + "variants": { + "variant": { + "solid": { + "background_color": accent[9], + "color": accent.contrast, + }, + "soft": {"background_color": accent.a[3], "color": accent.a[11]}, + }, + }, + "defaults": {"variant": "soft"}, + "compound": [ + { + "props": {"variant": "solid", "high_contrast": "true"}, + "style": {"background_color": accent[12], "color": accent[1]}, + }, + { + "props": {"variant": "soft", "high_contrast": "true"}, + "style": {"color": accent[12]}, + }, + ], + } + + +AVATAR: ComponentStyles = { + "base": unchecked({ + "box_sizing": "border-box", + "display": "inline-flex", + "align_items": "center", + "justify_content": "center", + "vertical_align": "middle", + "user_select": "none", + "width": f"var({_SIZE})", + "height": f"var({_SIZE})", + "flex_shrink": 0, + }), + "variants": { + "size": {size: unchecked(_size(*values)) for size, values in _SIZES.items()}, + "color_scheme": {"true": unchecked(ACCENT_SCOPE)}, + }, + "defaults": {"size": "3"}, + "parts": { + # By the number of letters, which says how large they are. + "fallback": _fallback(None), + "fallback_one": _fallback(f"var({_ONE_LETTER})"), + "fallback_two": _fallback(f"var({_TWO_LETTERS}, var({_ONE_LETTER}))"), + "image": { + "base": unchecked({ + "box_sizing": "border-box", + "display": {"default": "block", "[data-status='error']": "none"}, + "max_width": "100%", + "width": "100%", + "height": "100%", + "object_fit": "cover", + "border_radius": "inherit", + # Over what stands in for it, which comes first. + "flex_shrink": 0, + "margin_left": "-100%", + }), + }, + }, +} diff --git a/tests/units/reflex_components_ui/components/test_avatar.py b/tests/units/reflex_components_ui/components/test_avatar.py new file mode 100644 index 00000000000..e115562052e --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_avatar.py @@ -0,0 +1,262 @@ +"""Tests for reflex_components_ui.components.avatar.""" + +from collections.abc import Callable +from typing import Any + +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +class AvatarState(rx.State): + """What an avatar is bound to.""" + + initials: str = "AB" + + +def test_avatar_fallback_alone( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """Without a src an avatar is its fallback, sized by its two letters.""" + component = rx.ui.avatar(fallback="AB") + assert component.render() == { + "name": '"span"', + "props": ["className:sx_eecdbf58c4_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_d9c345d227_c"], + "children": [{"contents": '"AB"'}], + } + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "middle", + "userSelect": "none", + "width": "var(--avatar-size)", + "height": "var(--avatar-size)", + "flexShrink": 0, + "--avatar-size": "var(--space-7)", + "--avatar-fallback-one-letter-font-size": "var(--font-size-4)", + "borderRadius": "max(var(--radius-3), var(--radius-full))", + "letterSpacing": "var(--letter-spacing-3)", + "--avatar-fallback-two-letters-font-size": "var(--font-size-3)", + }, + { + "boxSizing": "border-box", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-medium)", + "fontStyle": "normal", + "zIndex": 0, + "width": "100%", + "height": "100%", + "display": "flex", + "alignItems": "center", + "justifyContent": "center", + "lineHeight": 1, + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "textTransform": "uppercase", + "flexShrink": 0, + "visibility": {"[data-status='loaded']": "hidden"}, + "fontSize": "var(--avatar-fallback-two-letters-font-size, " + "var(--avatar-fallback-one-letter-font-size))", + "backgroundColor": "var(--accent-a3)", + "color": "var(--accent-a11)", + }, + ] + + +def test_avatar_image_over_the_fallback( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The image lies over the fallback, and its ref says how its load ended.""" + component = rx.ui.avatar( + src="/ada.png", + alt="Ada", + fallback="A", + size="5", + variant="solid", + high_contrast=True, + radius="full", + id="ada", + ) + assert component.render() == { + "name": '"span"', + "props": [ + 'className:sx_119fa60175_c + " " + reflexUIClasses_4c7cd6a7ce', + 'id:"ada"', + "ref:ref_ada", + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_a4a6b79df8_c"], + "children": [{"contents": '"A"'}], + }, + { + "name": '"img"', + "props": [ + 'alt:"Ada"', + "className:sx_b22e24c3d6_c", + "ref:watchImage", + 'src:"/ada.png"', + ], + "children": [], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "middle", + "userSelect": "none", + "width": "var(--avatar-size)", + "height": "var(--avatar-size)", + "flexShrink": 0, + "--avatar-size": "var(--space-9)", + "--avatar-fallback-one-letter-font-size": "var(--font-size-6)", + "borderRadius": "max(var(--radius-4), var(--radius-full))", + "letterSpacing": "var(--letter-spacing-6)", + }, + { + "boxSizing": "border-box", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-medium)", + "fontStyle": "normal", + "zIndex": 0, + "width": "100%", + "height": "100%", + "display": "flex", + "alignItems": "center", + "justifyContent": "center", + "lineHeight": 1, + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "textTransform": "uppercase", + "flexShrink": 0, + "visibility": {"[data-status='loaded']": "hidden"}, + "fontSize": "var(--avatar-fallback-one-letter-font-size)", + "backgroundColor": "var(--accent-12)", + "color": "var(--accent-1)", + }, + { + "boxSizing": "border-box", + "display": {"default": "block", "[data-status='error']": "none"}, + "maxWidth": "100%", + "width": "100%", + "height": "100%", + "objectFit": "cover", + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "flexShrink": 0, + "marginLeft": "-100%", + }, + ] + + +def test_avatar_fallback_bound_to_state( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A fallback bound to state has the size of the text around it.""" + component = rx.ui.avatar( + fallback=AvatarState.initials, size=rx.breakpoints(initial="1", md="4") + ) + assert component.render() == { + "name": '"span"', + "props": ["className:sx_0c15401e7f_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_5204d15c1d_c"], + "children": [ + { + "contents": "reflex___state____state__tests___units___reflex_components_ui___components___test_avatar____avatar_state.initials_rx_state_" + } + ], + } + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "middle", + "userSelect": "none", + "width": "var(--avatar-size)", + "height": "var(--avatar-size)", + "flexShrink": 0, + "--avatar-size": { + "default": "var(--space-5)", + "@media (min-width: 1024px)": "var(--space-8)", + }, + "--avatar-fallback-one-letter-font-size": { + "default": "var(--font-size-2)", + "@media (min-width: 1024px)": "var(--font-size-5)", + }, + "borderRadius": { + "default": "max(var(--radius-2), var(--radius-full))", + "@media (min-width: 1024px)": "max(var(--radius-3), " + "var(--radius-full))", + }, + "letterSpacing": { + "default": "var(--letter-spacing-1)", + "@media (min-width: 1024px)": "var(--letter-spacing-4)", + }, + "--avatar-fallback-two-letters-font-size": { + "default": "var(--font-size-1)", + "@media (min-width: 1024px)": "var(--font-size-4)", + }, + }, + { + "boxSizing": "border-box", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-medium)", + "fontStyle": "normal", + "zIndex": 0, + "width": "100%", + "height": "100%", + "display": "flex", + "alignItems": "center", + "justifyContent": "center", + "lineHeight": 1, + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "textTransform": "uppercase", + "flexShrink": 0, + "visibility": {"[data-status='loaded']": "hidden"}, + "backgroundColor": "var(--accent-a3)", + "color": "var(--accent-a11)", + }, + ] + + +def test_avatar_imports_its_script_only_with_an_image(ui_plugin: UIPlugin): + """The one script of an avatar follows the load of an image.""" + script = "$/reflex-ui/behaviors/image-status.js" + assert script not in rx.ui.avatar(fallback="AB")._get_all_imports() + assert rx.ui.avatar(src="/ada.png", fallback="AB")._get_all_imports()[script] == [ + ImportVar(tag="watchImage") + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 7e09b4a12b5..e501f858bd4 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -104,6 +104,7 @@ def differences(component: str) -> list[ApiDifference]: def test_every_wave_is_in_the_namespace(): assert COMPONENTS == [ "aspect_ratio", + "avatar", "badge", "blockquote", "box", From f2eaeb30730beed1165970c127fcf3c3e7ed0ea8 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 22:49:30 +0000 Subject: [PATCH 056/204] Add rx.ui.callout, with its parts and the form made from a text Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- packages/reflex-components-ui/js/src/base.css | 8 + .../parity/ui_parity/components/callout.py | 134 ++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/callout.py | 124 +++++++++ .../reflex_components_ui/styles/callout.py | 96 +++++++ .../components/test_callout.py | 250 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 6 +- 7 files changed, 618 insertions(+), 1 deletion(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/callout.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/callout.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/callout.py create mode 100644 tests/units/reflex_components_ui/components/test_callout.py diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index a827eab45ab..d94d318888e 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -62,6 +62,14 @@ html.dark { .reflex-ui-theme svg { opacity: var(--rx-icon-opacity, revert-layer); } + + /* + * Everything in a callout but its icon is in the last column, whatever + * the element is: the icon places itself, in the column before. + */ + [data-rx-callout] > * { + grid-column-start: -1; + } } /* diff --git a/packages/reflex-components-ui/parity/ui_parity/components/callout.py b/packages/reflex-components-ui/parity/ui_parity/components/callout.py new file mode 100644 index 00000000000..0975876313d --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/callout.py @@ -0,0 +1,134 @@ +"""The callout: a message with or without an icon, in each variant and size.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, LIGHT, Matrix +from ui_parity.samples import ACCENTS, PARAGRAPH + +VARIANTS = ["soft", "surface", "outline"] +SIZES = ["1", "2", "3"] +RESPONSIVE = rx.breakpoints(initial="1", sm="3", lg="2") + + +def _callout(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a callout, from its text or from its parts. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` names what a callout made of + its parts holds, and ``text`` the text of the other kind. + + Returns: + The callout. + """ + props = dict(props) + holds = props.pop("holds", None) + text = props.pop("text", "Access denied. Ask an admin for it.") + if holds is None: + return namespace.callout(text, **props) + props.pop("icon", None) + children = [ + namespace.callout.icon(rx.icon("info", size=16)), + namespace.callout.text(text), + ] + if holds == "more": + # What is neither the icon nor the text is in the column of the text. + children.append(rx.el.div("Retry in a minute.", style={"font_size": "12px"})) + children.append(namespace.callout.text("And a second paragraph.")) + if holds == "text": + children = children[1:] + return namespace.callout.root(*children, **props) + + +MATRIX = Matrix( + component="callout", + render=_callout, + base={"icon": "info"}, + cross={"variant": VARIANTS, "size": SIZES, "icon": ["info", None]}, + sweep={ + "color_scheme": ACCENTS, + "high_contrast": [True], + "holds": ["parts", "more", "text"], + "text": {"long": PARAGRAPH}, + "size": {"responsive": RESPONSIVE}, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + {"holds": ["more"], "size": SIZES, "variant": VARIANTS}, + {"text": {"long": PARAGRAPH}, "size": SIZES, "icon": ["info", None]}, + {"size": {"responsive": RESPONSIVE}, "viewport": [520, 800, 1100, 1280]}, + ], + stage=(320, 200), + parts={"text": "p"}, + # Not held to zero, for the icon: at a threshold of zero 100 of the 101 + # cells are equal pixel for pixel, and in the base cell at a width of + # 520 the edge of the icon is anti-aliased otherwise (one pixel beyond + # anti-aliasing). The same callout at the other widths is equal. + tolerance=0.002, +) + +CONTRACT = Contract( + component="callout", + render=lambda namespace: namespace.box( + namespace.callout("Saved.", icon="check", id="saved"), + namespace.callout.root( + namespace.callout.icon(rx.icon("info"), id="icon"), + namespace.callout.text("Read this.", id="text"), + id="root", + ), + ), +) + + +@CONTRACT.step( + "is a div around an icon and a paragraph in the server render", on=SERVER +) +def _server_render(run: Run) -> None: + saved = run.server.element("saved") + assert (saved.tag, saved.text) == ("div", "Saved.") + assert run.server.element("icon").tag == "div" + text = run.server.element("text") + assert (text.tag, text.text) == ("p", "Read this.") + + +@CONTRACT.step( + "shows its icon beside its text with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + _icon_is_beside_the_text(run) + + +@CONTRACT.step("shows its icon beside its text after hydration", on=HYDRATED) +def _hydrated(run: Run) -> None: + _icon_is_beside_the_text(run) + assert run.page.get_by_role("paragraph").count() == 2 + + +def _icon_is_beside_the_text(run: Run) -> None: + """Check that the icon is left of the text, on its first line. + + Args: + run: The run of the step. + """ + icon = run.page.locator("#icon").bounding_box() + text = run.page.locator("#text").bounding_box() + assert icon is not None + assert text is not None + assert icon["x"] + icon["width"] < text["x"] + assert (icon["y"], icon["height"]) == (text["y"], text["height"]) 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 7f840e44510..9c8bb282d3a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -11,6 +11,7 @@ "components.avatar": ["avatar"], "components.badge": ["badge"], "components.button": ["button"], + "components.callout": ["callout"], "components.card": ["card"], "components.data_list": ["data_list"], "components.icon_button": ["icon_button"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/callout.py b/packages/reflex-components-ui/src/reflex_components_ui/components/callout.py new file mode 100644 index 00000000000..99b67c2ae96 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/callout.py @@ -0,0 +1,124 @@ +"""A callout: a short message to attract the attention of the user.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import ( + Component, + ComponentNamespace, + ComponentVar, + field, +) +from reflex_base.components.tags import CommonTag +from reflex_base.vars.base import Var +from reflex_components_core.base.fragment import fragment +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements +from reflex_components_lucide.icon import Icon + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.callout import ( + CALLOUT_ICON, + CALLOUT_ROOT, + CALLOUT_TEXT, +) +from reflex_components_ui.themes import LiteralAccentColor + +CalloutVariant = Literal["soft", "surface", "outline"] + + +class CalloutRoot(UIComponent, elements.Div): + """Groups Icon and Text parts of a Callout.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = CALLOUT_ROOT + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + size: Var[Responsive[Literal["1", "2", "3"]]] = field(doc='Size "1" - "3"') + + variant: Var[CalloutVariant] = field( + doc='Variant of button: "soft" | "surface" | "outline"' + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + high_contrast: Var[bool] = field( + doc="Whether to render the button with higher contrast color against background" + ) + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the root, marked for what the base stylesheet says of it. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: whatever is inside but the icon is in the last column, + which a class on the root cannot say of its children. + """ + return super()._render(props).add_props(**{"data-rx-callout": ""}) + + +class CalloutIcon(UIComponent, elements.Div): + """Provides width and height for the icon associated with the callout.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = CALLOUT_ICON + + +class CalloutText(UIComponent, elements.P): + """Renders the callout text. This component is based on the p element.""" + + tag = "p" + + styles: ClassVar[ComponentStyles] = CALLOUT_TEXT + + +class Callout(CalloutRoot): + """A short message to attract user's attention.""" + + text: Var[str] = field(doc="The text of the callout.") + + icon: Var[Component | str] = field( + doc="The icon of the callout: a Lucide icon name or a component." + ) + + @classmethod + def create(cls, text: str | Var[str], **props) -> Component: + """Create a callout component. + + Args: + text: The text of the callout. + **props: The properties of the component. + + Returns: + The callout component. + """ + icon = props.pop("icon", None) + if icon is not None and not isinstance(icon, (Component, ComponentVar)): + icon = Icon.create(tag=icon) + + return CalloutRoot.create( + CalloutIcon.create(icon) if icon is not None else fragment(), + CalloutText.create(text), + **props, + ) + + +class CalloutNamespace(ComponentNamespace): + """Callout components namespace.""" + + root = staticmethod(CalloutRoot.create) + icon = staticmethod(CalloutIcon.create) + text = staticmethod(CalloutText.create) + __call__ = staticmethod(Callout.create) + + +callout = CalloutNamespace() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/callout.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/callout.py new file mode 100644 index 00000000000..9dd2440cdf3 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/callout.py @@ -0,0 +1,96 @@ +"""The look of a callout: a short message with an icon beside it.""" + +from __future__ import annotations + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.text import TEXT_BASE +from reflex_components_ui.styles.typography import ( + ACCENT_SCOPE, + ACCENT_SCOPE_HIGH_CONTRAST, +) + +accent = tokens.accent + +# What the root tells its parts, as the size of a callout is the size of +# its text in Radix Themes: the height of the icon is the height of a line. +_ICON_HEIGHT = "--callout-icon-height" +_FONT_SIZE = "--rx-callout-font-size" +_LINE_HEIGHT = "--rx-callout-line-height" +_LETTER_SPACING = "--rx-callout-letter-spacing" + +# The gaps, the padding and the radius of each size. +_SIZES: dict[str, tuple[str, str, str, str]] = { + "1": (tokens.space[2], tokens.space[2], tokens.space[3], tokens.radius[3]), + "2": (tokens.space[2], tokens.space[3], tokens.space[4], tokens.radius[4]), + "3": (tokens.space[3], tokens.space[4], tokens.space[5], tokens.radius[5]), +} + +# The text of each size: the second size of text, and the third for the last. +_TEXT: dict[str, tuple[str, str, str]] = { + "1": (tokens.font_size[2], tokens.line_height[2], tokens.letter_spacing[2]), + "2": (tokens.font_size[2], tokens.line_height[2], tokens.letter_spacing[2]), + "3": (tokens.font_size[3], tokens.line_height[3], tokens.letter_spacing[3]), +} + +CALLOUT_ROOT: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "display": "grid", + "align_items": "flex-start", + "justify_content": "flex-start", + "text_align": "left", + "color": accent.a[11], + }, + "variants": { + "size": { + size: unchecked({ + "row_gap": row_gap, + "column_gap": column_gap, + "padding": padding, + "border_radius": radius, + _ICON_HEIGHT: _TEXT[size][1], + _FONT_SIZE: _TEXT[size][0], + _LINE_HEIGHT: _TEXT[size][1], + _LETTER_SPACING: _TEXT[size][2], + }) + for size, (row_gap, column_gap, padding, radius) in _SIZES.items() + }, + "variant": { + "soft": {"background_color": accent.a[3]}, + "surface": { + "box_shadow": f"inset 0 0 0 1px {accent.a[6]}", + "background_color": accent.a[2], + }, + "outline": {"box_shadow": f"inset 0 0 0 1px {accent.a[7]}"}, + }, + "color_scheme": {"true": unchecked(ACCENT_SCOPE)}, + "high_contrast": {"true": {"color": accent[12]}}, + }, + "defaults": {"size": "2", "variant": "soft"}, + "compound": [ + { + "props": {"color_scheme": "true", "high_contrast": "true"}, + "style": unchecked(ACCENT_SCOPE_HIGH_CONTRAST), + }, + ], +} + +CALLOUT_ICON: ComponentStyles = { + "base": { + "display": "flex", + "align_items": "center", + "grid_column_start": "-2", + "height": f"var({_ICON_HEIGHT})", + }, +} + +# Text of the size of the callout around it; outside one, of no size. +CALLOUT_TEXT: ComponentStyles = { + "base": unchecked({ + **TEXT_BASE, + "font_size": f"var({_FONT_SIZE})", + "--line-height": f"var({_LINE_HEIGHT})", + "--letter-spacing": f"var({_LETTER_SPACING})", + }), +} diff --git a/tests/units/reflex_components_ui/components/test_callout.py b/tests/units/reflex_components_ui/components/test_callout.py new file mode 100644 index 00000000000..11d91717f4c --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_callout.py @@ -0,0 +1,250 @@ +"""Tests for reflex_components_ui.components.callout.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_callout_from_its_text( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A callout made from its text is a root around an icon and a paragraph.""" + component = rx.ui.callout("Saved.", icon="check") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_91bac2f16e_c", '"data-rx-callout":""'], + "children": [ + { + "name": '"div"', + "props": ["className:sx_c4b3ee3cc5_c"], + "children": [{"name": "LucideCheck", "props": [], "children": []}], + }, + { + "name": '"p"', + "props": ["className:sx_9baccc1576_c"], + "children": [{"contents": '"Saved."'}], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "flex-start", + "justifyContent": "flex-start", + "textAlign": "left", + "color": "var(--accent-a11)", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-3)", + "paddingTop": "var(--space-4)", + "paddingRight": "var(--space-4)", + "paddingBottom": "var(--space-4)", + "paddingLeft": "var(--space-4)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "--callout-icon-height": "var(--line-height-2)", + "--rx-callout-font-size": "var(--font-size-2)", + "--rx-callout-line-height": "var(--line-height-2)", + "--rx-callout-letter-spacing": "var(--letter-spacing-2)", + "backgroundColor": "var(--accent-a3)", + }, + { + "display": "flex", + "alignItems": "center", + "gridColumnStart": "-2", + "height": "var(--callout-icon-height)", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--rx-callout-font-size)", + "--line-height": "var(--rx-callout-line-height)", + "--letter-spacing": "var(--rx-callout-letter-spacing)", + }, + ] + + +def test_callout_without_an_icon( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """Without an icon the text is all the root holds.""" + component = rx.ui.callout( + "Saved.", variant="outline", size="3", color_scheme="green", high_contrast=True + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_f1fef71f3c_c + " " + reflexUIClasses_e970788578', + '"data-rx-callout":""', + ], + "children": [ + {"name": "Fragment", "props": [], "children": []}, + { + "name": '"p"', + "props": ["className:sx_9baccc1576_c"], + "children": [{"contents": '"Saved."'}], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "flex-start", + "justifyContent": "flex-start", + "textAlign": "left", + "color": "var(--accent-12)", + "rowGap": "var(--space-3)", + "columnGap": "var(--space-4)", + "paddingTop": "var(--space-5)", + "paddingRight": "var(--space-5)", + "paddingBottom": "var(--space-5)", + "paddingLeft": "var(--space-5)", + "borderTopLeftRadius": "var(--radius-5)", + "borderTopRightRadius": "var(--radius-5)", + "borderBottomRightRadius": "var(--radius-5)", + "borderBottomLeftRadius": "var(--radius-5)", + "--callout-icon-height": "var(--line-height-3)", + "--rx-callout-font-size": "var(--font-size-3)", + "--rx-callout-line-height": "var(--line-height-3)", + "--rx-callout-letter-spacing": "var(--letter-spacing-3)", + "boxShadow": "inset 0 0 0 1px var(--accent-a7)", + "--rx-accent-text": "var(--accent-12)", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--rx-callout-font-size)", + "--line-height": "var(--rx-callout-line-height)", + "--letter-spacing": "var(--rx-callout-letter-spacing)", + }, + ] + + +def test_callout_parts( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The parts follow the size of the root through what it hands down.""" + component = rx.ui.callout.root( + rx.ui.callout.icon(rx.icon("info")), + rx.ui.callout.text("Read this."), + size=rx.breakpoints(initial="1", md="3"), + variant="surface", + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_06a0a0907d_c", '"data-rx-callout":""'], + "children": [ + { + "name": '"div"', + "props": ["className:sx_c4b3ee3cc5_c"], + "children": [{"name": "LucideInfo", "props": [], "children": []}], + }, + { + "name": '"p"', + "props": ["className:sx_9baccc1576_c"], + "children": [{"contents": '"Read this."'}], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "flex-start", + "justifyContent": "flex-start", + "textAlign": "left", + "color": "var(--accent-a11)", + "rowGap": { + "default": "var(--space-2)", + "@media (min-width: 1024px)": "var(--space-3)", + }, + "columnGap": { + "default": "var(--space-2)", + "@media (min-width: 1024px)": "var(--space-4)", + }, + "paddingTop": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "var(--space-5)", + }, + "paddingRight": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "var(--space-5)", + }, + "paddingBottom": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "var(--space-5)", + }, + "paddingLeft": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "var(--space-5)", + }, + "borderTopLeftRadius": { + "default": "var(--radius-3)", + "@media (min-width: 1024px)": "var(--radius-5)", + }, + "borderTopRightRadius": { + "default": "var(--radius-3)", + "@media (min-width: 1024px)": "var(--radius-5)", + }, + "borderBottomRightRadius": { + "default": "var(--radius-3)", + "@media (min-width: 1024px)": "var(--radius-5)", + }, + "borderBottomLeftRadius": { + "default": "var(--radius-3)", + "@media (min-width: 1024px)": "var(--radius-5)", + }, + "--callout-icon-height": { + "default": "var(--line-height-2)", + "@media (min-width: 1024px)": "var(--line-height-3)", + }, + "--rx-callout-font-size": { + "default": "var(--font-size-2)", + "@media (min-width: 1024px)": "var(--font-size-3)", + }, + "--rx-callout-line-height": { + "default": "var(--line-height-2)", + "@media (min-width: 1024px)": "var(--line-height-3)", + }, + "--rx-callout-letter-spacing": { + "default": "var(--letter-spacing-2)", + "@media (min-width: 1024px)": "var(--letter-spacing-3)", + }, + "boxShadow": "inset 0 0 0 1px var(--accent-a6)", + "backgroundColor": "var(--accent-a2)", + }, + { + "display": "flex", + "alignItems": "center", + "gridColumnStart": "-2", + "height": "var(--callout-icon-height)", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--rx-callout-font-size)", + "--line-height": "var(--rx-callout-line-height)", + "--letter-spacing": "var(--rx-callout-letter-spacing)", + }, + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index e501f858bd4..75381b39f95 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -109,6 +109,10 @@ def test_every_wave_is_in_the_namespace(): "blockquote", "box", "button", + "callout", + "callout.icon", + "callout.root", + "callout.text", "card", "center", "code", @@ -149,7 +153,7 @@ def test_every_wave_is_in_the_namespace(): ] -@pytest.mark.parametrize("namespace", ["data_list", "list", "text"]) +@pytest.mark.parametrize("namespace", ["callout", "data_list", "list", "text"]) def test_namespace_has_the_members_of_its_radix_counterpart(namespace: str): assert members(getattr(reflex_components_ui, namespace)) == members( getattr(rx, namespace) From 3009d7381b42fe86e8e909a188e1381e778cc5e6 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 22:49:41 +0000 Subject: [PATCH 057/204] Tidy the callout declarations Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/ui_parity/components/callout.py | 6 ++++-- .../src/reflex_components_ui/components/callout.py | 6 +----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/callout.py b/packages/reflex-components-ui/parity/ui_parity/components/callout.py index 0975876313d..01ae7443eaf 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/callout.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/callout.py @@ -38,8 +38,10 @@ def _callout(namespace: Any, props: Mapping[str, Any]) -> Any: ] if holds == "more": # What is neither the icon nor the text is in the column of the text. - children.append(rx.el.div("Retry in a minute.", style={"font_size": "12px"})) - children.append(namespace.callout.text("And a second paragraph.")) + children.extend(( + rx.el.div("Retry in a minute.", style={"font_size": "12px"}), + namespace.callout.text("And a second paragraph."), + )) if holds == "text": children = children[1:] return namespace.callout.root(*children, **props) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/callout.py b/packages/reflex-components-ui/src/reflex_components_ui/components/callout.py index 99b67c2ae96..372e42ceec7 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/callout.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/callout.py @@ -19,11 +19,7 @@ from reflex_components_ui.base import UIComponent from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.callout import ( - CALLOUT_ICON, - CALLOUT_ROOT, - CALLOUT_TEXT, -) +from reflex_components_ui.styles.callout import CALLOUT_ICON, CALLOUT_ROOT, CALLOUT_TEXT from reflex_components_ui.themes import LiteralAccentColor CalloutVariant = Literal["soft", "surface", "outline"] From 17acb4a8202e114fc34c6af988d832437d157328 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:00:11 +0000 Subject: [PATCH 058/204] Add rx.ui.skeleton: a span around text, or the element it stands in for Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- packages/reflex-components-ui/js/src/base.css | 8 + .../parity/ui_parity/components/skeleton.py | 169 ++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/skeleton.py | 193 +++++++++ .../reflex_components_ui/styles/skeleton.py | 58 +++ .../components/test_skeleton.py | 381 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 7 files changed, 811 insertions(+) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/skeleton.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/skeleton.py create mode 100644 tests/units/reflex_components_ui/components/test_skeleton.py diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index d94d318888e..aa430939e08 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -70,6 +70,14 @@ html.dark { [data-rx-callout] > * { grid-column-start: -1; } + + /* + * What a skeleton stands in for keeps its place and is not shown, whatever + * the elements inside are. + */ + [data-rx-skeleton] > * { + visibility: hidden !important; + } } /* diff --git a/packages/reflex-components-ui/parity/ui_parity/components/skeleton.py b/packages/reflex-components-ui/parity/ui_parity/components/skeleton.py new file mode 100644 index 00000000000..8fb8d7dab01 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/skeleton.py @@ -0,0 +1,169 @@ +"""The skeleton: a pulsing block with the size of what it stands in for.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, LIGHT, Matrix + +HOLDS = ["text", "words", "button", "soft-button", "avatar", "card", "nothing"] + + +def _skeleton(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a skeleton around what a cell says it holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` names the children. + + Returns: + The skeleton, in a paragraph when it stands in for words of one. + """ + props = dict(props) + holds = props.pop("holds", "text") + if holds == "text": + return namespace.skeleton(namespace.text("Loading the report"), **props) + if holds == "words": + return namespace.text( + "Total: ", namespace.skeleton("1,204 euros", **props), " this month." + ) + if holds == "button": + return namespace.skeleton(namespace.button("Save"), **props) + if holds == "soft-button": + return namespace.skeleton( + namespace.button("Save", variant="classic", size="3"), **props + ) + if holds == "avatar": + return namespace.skeleton(namespace.avatar(fallback="AB", size="5"), **props) + if holds == "card": + return namespace.skeleton( + namespace.card(namespace.text("Invoice"), namespace.button("Pay")), **props + ) + return namespace.skeleton(**props) + + +MATRIX = Matrix( + component="skeleton", + render=_skeleton, + # A skeleton that holds nothing and is not loading renders nothing. + cross={"holds": HOLDS[:-1], "loading": [True, False]}, + sweep={ + "width": { + "fixed": "120px", + "responsive": rx.breakpoints(initial="60px", sm="160px"), + }, + "height": ["40px"], + "min_width": ["150px"], + "max_width": ["40px"], + "min_height": ["60px"], + "max_height": ["8px"], + "holds": ["nothing"], + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"holds": HOLDS, "appearance": [LIGHT, DARK]}, + {"holds": ["nothing", "button"], "width": ["120px"], "height": ["40px"]}, + { + "holds": ["nothing", "text"], + "width": {"responsive": rx.breakpoints(initial="60px", sm="160px")}, + "viewport": [520, 800, 1280], + }, + ], + stage=(260, 120), + # A screenshot is taken with animations off, so the pulse is in no + # image: the color of the skeleton is compared as a computed style, in + # which both systems are on the same frame, and by the contract. + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="skeleton", + render=lambda namespace: namespace.box( + namespace.skeleton(namespace.button("Save", id="save")), + namespace.text("Total: ", namespace.skeleton("1,204", id="words")), + namespace.skeleton(namespace.button("Ready", id="ready"), loading=False), + namespace.button("Last", id="last"), + ), +) + + +@CONTRACT.step("is its child, or a span around text, in the server render", on=SERVER) +def _server_render(run: Run) -> None: + save = run.server.element("save") + assert (save.tag, save.text) == ("button", "Save") + assert save.attributes["aria-hidden"] == "true" + assert save.attributes["tabindex"] == "-1" + words = run.server.element("words") + assert (words.tag, words.text) == ("span", "1,204") + assert run.server.element("ready").text == "Ready" + + +@CONTRACT.step( + "hides what is loading and shows what is not without JavaScript", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + _hides_what_is_loading(run) + + +@CONTRACT.step( + "hides what is loading from the eye, the keyboard and a reader", on=HYDRATED +) +def _hydrated(run: Run) -> None: + _hides_what_is_loading(run) + assert run.page.get_by_role("button").evaluate_all( + "buttons => buttons.map((button) => button.id)" + ) == ["ready", "last"] + focused = [] + for _ in range(2): + run.page.keyboard.press("Tab") + focused.append(run.page.evaluate("document.activeElement.id")) + assert focused == ["ready", "last"] + + +@CONTRACT.step("pulses between two grays, back and forth every second", on=HYDRATED) +def _animation(run: Run) -> None: + animation = run.page.evaluate( + """() => { + const [animation] = document.getElementById("words").getAnimations(); + const timing = animation.effect.getTiming(); + return { + frames: animation.effect.getKeyframes().map( + (frame) => [frame.offset, frame.easing]), + colors: animation.effect.getKeyframes().map( + (frame) => frame.backgroundColor).length, + timing: [timing.duration, timing.delay, timing.iterations, + timing.easing, timing.direction, timing.fill], + state: animation.playState, + }; + }""" + ) + assert animation == { + "frames": [[0, "ease"], [1, "ease"]], + "colors": 2, + "timing": [1000, 0, float("inf"), "linear", "alternate-reverse", "none"], + "state": "running", + } + + +def _hides_what_is_loading(run: Run) -> None: + """Check that a skeleton shows a block where its child is, and no text. + + Args: + run: The run of the step. + """ + styles = run.page.evaluate( + """() => ["save", "words"].map((id) => { + const style = getComputedStyle(document.getElementById(id)); + return [style.color, style.pointerEvents, style.backgroundImage]; + })""" + ) + assert styles == [["rgba(0, 0, 0, 0)", "none", "none"]] * 2 + assert run.page.locator("#ready").is_visible() + box = run.page.locator("#save").bounding_box() + assert box is not None + assert box["height"] == 32 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 9c8bb282d3a..2d3cbf69e2e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -18,6 +18,7 @@ "components.inset": ["inset"], "components.progress": ["progress"], "components.separator": ["divider", "separator"], + "components.skeleton": ["skeleton"], "components.spinner": ["spinner"], "layout.box": ["box"], "layout.center": ["center"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py b/packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py new file mode 100644 index 00000000000..1be07e01e4c --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py @@ -0,0 +1,193 @@ +"""A skeleton: a placeholder with the size of what is loading.""" + +from __future__ import annotations + +import dataclasses +from typing import Any, ClassVar + +from reflex_base.components.component import Component, field +from reflex_base.constants.compiler import MemoizationMode +from reflex_base.vars.base import Var +from reflex_components_core.base.fragment import Fragment +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components.spinner import while_loading +from reflex_components_ui.props import style_props +from reflex_components_ui.style import ComponentStyles, Merged +from reflex_components_ui.styles.skeleton import SKELETON + +# The props that are the CSS property of the same name. +_SIZE_PROPS = ( + "width", + "min_width", + "max_width", + "height", + "min_height", + "max_height", +) + + +class Skeleton(UIComponent): + """Skeleton component.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = SKELETON + + loading: Var[bool] = field( + doc="If set, show an rx.spinner instead of the component children." + ) + + width: Var[Responsive[str]] = field(doc="The width of the skeleton") + + min_width: Var[Responsive[str]] = field(doc="The minimum width of the skeleton") + + max_width: Var[Responsive[str]] = field(doc="The maximum width of the skeleton") + + height: Var[Responsive[str]] = field(doc="The height of the skeleton") + + min_height: Var[Responsive[str]] = field(doc="The minimum height of the skeleton") + + max_height: Var[Responsive[str]] = field(doc="The maximum height of the skeleton") + + _memoization_mode = MemoizationMode(recursive=False) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a skeleton in the place of its children while they load. + + A skeleton around one element is that element, with the look of a + skeleton over its own: it has its size. Around anything else it is a + span. + + Args: + *children: What the skeleton stands in for. + **props: The props of the skeleton. + + Returns: + The skeleton, or the children once they are no longer loading. + """ + loading = props.pop("loading", True) + sized = any(prop in props for prop in _SIZE_PROPS) + style_props("rx.ui.skeleton", props, _SIZE_PROPS) + if sized and _is_element(children): + # The size of the skeleton is over the one of the element it is + # rendered as, which has class names of its own. + style = props["style"] + sizes = style[0] if isinstance(style, list) else style + important = _important(sizes) + props["style"] = ( + [important, *style[1:]] if isinstance(style, list) else important + ) + skeleton = super().create( + *children, + custom_attrs={ + "aria-hidden": True, + "tabIndex": -1, + "inert": True, + "data-rx-skeleton": "", + **props.pop("custom_attrs", {}), + }, + **props, + ) + (shown,) = while_loading(loading, [skeleton], (Fragment.create(*children),)) + return shown + + def _post_init(self, *args, **kwargs): + """Initialize the skeleton, rendered as its child when that is an element. + + The child keeps its own styles and the skeleton adds its own beside + them, most of them important: the child is also what shows once it + is no longer loading. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + children = kwargs.get("children", ()) + # What the style table reads as variants: whether the skeleton is + # around text rather than rendered as an element, and whether it + # rounds its corners. + self._inline = not _is_element(children) + self._rounded = self._inline or not _has_radius(children[0]) + super()._post_init(*args, **kwargs) + if not self._inline: + self._as_child = True + # The child has to stay the child: a compile would otherwise + # move one that is bound to state into a component of its own. + self._memoization_mode = dataclasses.replace( + self._memoization_mode, recursive=False + ) + + def _slot_styles(self) -> Merged: + """Get the styles of the skeleton alone. + + Returns: + The styles the skeleton declares: the element it is rendered as + declares its own, and has the class names of both. + """ + if self.style is not self._merged_for: + self._merge_styles() + return self._merged + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the one that chooses what is shown. + """ + return [*super()._exclude_props(), "loading"] + + +def _important(style: dict[str, Any]) -> dict[str, Any]: + """Make the literal values of a style win over any other class name. + + Args: + style: The style, with blocks under media queries. + + Returns: + The style, each of its strings important. + """ + return { + key: _important(value) + if isinstance(value, dict) + else f"{value} !important" + if value.__class__ is str + else value + for key, value in style.items() + } + + +def _has_radius(child: Any) -> bool: + """Whether an rx.ui element rounds its own corners. + + Args: + child: The element a skeleton is rendered as. + + Returns: + True if the styles of the element set its radius. + """ + if not isinstance(child, UIComponent): + return False + style = child._element_styles().style.style + return "borderRadius" in style or "borderTopLeftRadius" in style + + +def _is_element(children: Any) -> bool: + """Whether a skeleton has one child that renders an element. + + Args: + children: The children of the skeleton. + + Returns: + True if the skeleton is rendered as its child. + """ + return ( + len(children) == 1 + and isinstance(children[0], Component) + and type(children[0]).render in (Component.render, UIComponent.render) + ) + + +skeleton = Skeleton.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/skeleton.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/skeleton.py new file mode 100644 index 00000000000..79fc274faaf --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/skeleton.py @@ -0,0 +1,58 @@ +"""The look of a skeleton: a pulsing block in the place of what is loading.""" + +from __future__ import annotations + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, keyframes, unchecked + +_PULSE = keyframes({ + "from": {"background_color": tokens.gray.a[3]}, + "to": {"background_color": tokens.gray.a[4]}, +}) + +# Most of it is important, as in Radix Themes: a skeleton rendered as its +# child takes the look of the skeleton over the one of the child, wherever +# the styles of the child come from. +SKELETON: ComponentStyles = { + "base": unchecked({ + "animation_name": _PULSE, + "animation_duration": "1000ms !important", + "animation_timing_function": "ease !important", + "animation_delay": "0s !important", + "animation_iteration_count": "infinite !important", + "animation_direction": "alternate-reverse !important", + "animation_fill_mode": "none !important", + "animation_play_state": "running !important", + "background_image": "none !important", + "background_clip": "border-box !important", + "border_style": "none !important", + "border_width": "medium !important", + "border_color": "currentcolor !important", + "box_shadow": "none !important", + "box_decoration_break": "clone !important", + "color": "transparent !important", + "outline_style": "none !important", + "outline_width": "medium !important", + "outline_color": "currentcolor !important", + "pointer_events": "none !important", + "user_select": "none !important", + "cursor": "default !important", + "_before": {"visibility": "hidden !important"}, + "_after": {"visibility": "hidden !important"}, + # Without anything to stand in for, a line of its own. + ":empty": {"display": "block", "height": tokens.space[3]}, + }), + "variants": { + # Unless the element the skeleton is rendered as has corners of its + # own, which it keeps. + "_rounded": {"true": {"border_radius": tokens.radius[1]}}, + # Around text rather than an element. The metrics of Arial give the + # background of a line of text a better height. + "_inline": { + "true": { + "line_height": 0, + "font_family": "Arial, sans-serif !important", + } + }, + }, +} diff --git a/tests/units/reflex_components_ui/components/test_skeleton.py b/tests/units/reflex_components_ui/components/test_skeleton.py new file mode 100644 index 00000000000..231bbbfec9c --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_skeleton.py @@ -0,0 +1,381 @@ +"""Tests for reflex_components_ui.components.skeleton.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import Keyframes + +import reflex as rx + +# What each leaf of a spinner declares. +LEAF: dict[str, Any] = { + "animationName": Keyframes( + ( + '{"from": {"backgroundColor": "var(--gray-a3)"}, "to": {"backgroundColor": "var(--gray-a4)"}}', + ), + ("$/reflex-ui/tokens/gray.stylex.js",), + ), + "animationDuration": "1000ms !important", + "animationTimingFunction": "ease !important", + "animationDelay": "0s !important", + "animationIterationCount": "infinite !important", + "animationDirection": "alternate-reverse !important", + "animationFillMode": "none !important", + "animationPlayState": "running !important", + "backgroundImage": "none !important", + "backgroundClip": "border-box !important", + "borderStyle": "none !important", + "borderWidth": "medium !important", + "borderColor": "currentcolor !important", + "boxShadow": "none !important", + "boxDecorationBreak": "clone !important", + "color": "transparent !important", + "outlineStyle": "none !important", + "outlineWidth": "medium !important", + "outlineColor": "currentcolor !important", + "pointerEvents": "none !important", + "userSelect": "none !important", + "cursor": "default !important", + "visibility": {"::before": "hidden !important", "::after": "hidden !important"}, + "display": {":empty": "block"}, + "height": {":empty": "var(--space-3)"}, + "borderTopLeftRadius": "var(--radius-1)", + "borderTopRightRadius": "var(--radius-1)", + "borderBottomRightRadius": "var(--radius-1)", + "borderBottomLeftRadius": "var(--radius-1)", + "lineHeight": 0, + "fontFamily": "Arial, sans-serif !important", + "width": {"default": "60px", "@media (min-width: 1024px)": "160px"}, +} + + +class SkeletonState(rx.State): + """What a skeleton is bound to.""" + + loading: bool = True + + +def test_skeleton_around_text( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """Around text a skeleton is a span, hidden from the keyboard and from a reader.""" + component = rx.ui.skeleton( + "1,204 euros", width=rx.breakpoints(initial="60px", md="160px") + ) + assert component.render() == { + "name": '"span"', + "props": [ + '"aria-hidden":true', + "className:sx_dc6750d851_c", + '"data-rx-skeleton":""', + "inert:true", + "tabIndex:-1", + ], + "children": [{"contents": '"1,204 euros"'}], + } + assert declared_styles(component) == [LEAF] + + +def test_skeleton_alone( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A skeleton that holds nothing is a line of its own.""" + component = rx.ui.skeleton(height="40px") + assert component.render() == { + "name": '"span"', + "props": [ + '"aria-hidden":true', + "className:sx_77a15491e1_c", + '"data-rx-skeleton":""', + "inert:true", + "tabIndex:-1", + ], + "children": [], + } + assert declared_styles(component) == [LEAF] + + +def test_skeleton_as_its_child( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """Around one element a skeleton is that element, which keeps its styles and its corners.""" + component = rx.ui.skeleton(rx.ui.button("Save", id="save"), width="120px") + assert component.render() == { + "name": '"button"', + "props": [ + '"aria-hidden":true', + 'className:(sx_6fb0976665_c) + " " + sx_596747f37d_c', + '"data-rx-skeleton":""', + 'id:"save"', + "inert:true", + "ref:ref_save", + "tabIndex:-1", + ], + "children": [{"contents": '"Save"'}], + } + assert declared_styles(component) == [ + LEAF, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "var(--space-3)", + "paddingBottom": "0", + "paddingLeft": "var(--space-3)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--accent-9)", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + ":active:not([data-state='open'])": "var(--accent-10)", + "[data-disabled]": "var(--gray-a3)", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": "var(--font-size-2)", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "var(--letter-spacing-2)", + "fontWeight": "var(--font-weight-medium)", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + }, + ":focus-visible:not([data-disabled])": "solid", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-6)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "color": { + "default": "var(--accent-contrast)", + "[data-disabled]": "var(--gray-a8)", + }, + "filter": { + ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + "saturate(1.1)) var(--rx-if-dark, " + "brightness(1.08))", + "[data-disabled]": "none", + }, + "outlineWidth": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "outlineColor": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + }, + ":focus-visible:not([data-disabled])": "var(--focus-8)", + }, + "outlineOffset": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + }, + ] + + +def test_skeleton_not_loading( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A skeleton that is not loading is its children, untouched.""" + component = rx.ui.skeleton(rx.ui.button("Save"), loading=False) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"button"', + "props": ["className:sx_6fb0976665_c"], + "children": [{"contents": '"Save"'}], + } + ], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "var(--space-3)", + "paddingBottom": "0", + "paddingLeft": "var(--space-3)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--accent-9)", + "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + ":active:not([data-state='open'])": "var(--accent-10)", + "[data-disabled]": "var(--gray-a3)", + }, + "backgroundImage": "none", + "appearance": "none", + "boxSizing": "border-box", + "fontSize": "var(--font-size-2)", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "var(--letter-spacing-2)", + "fontWeight": "var(--font-weight-medium)", + "textTransform": "inherit", + "textIndent": "initial", + "textShadow": "inherit", + "wordSpacing": "inherit", + "cursor": { + "default": "inherit", + ":where(button)": "var(--cursor-button)", + ":any-link": "var(--cursor-link)", + "[data-disabled]": "var(--cursor-disabled)", + }, + "outlineStyle": { + "default": "none", + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + }, + ":focus-visible:not([data-disabled])": "solid", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "center", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "--spinner-opacity": {"[data-disabled]": "1"}, + "--base-button-classic-active-padding-top": "2px", + "--base-button-height": "var(--space-6)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "color": { + "default": "var(--accent-contrast)", + "[data-disabled]": "var(--gray-a8)", + }, + "filter": { + ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + "saturate(1.1)) var(--rx-if-dark, " + "brightness(1.08))", + "[data-disabled]": "none", + }, + "outlineWidth": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "outlineColor": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + }, + ":focus-visible:not([data-disabled])": "var(--focus-8)", + }, + "outlineOffset": { + "@media (pointer: coarse)": { + ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + }, + ":focus-visible:not([data-disabled])": "2px", + }, + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + } + ] + + +def test_skeleton_bound_to_state( + ui_plugin: UIPlugin, +): + """Loading bound to state chooses between the skeleton and the child in the browser.""" + component = rx.ui.skeleton(rx.el.div("Report"), loading=SkeletonState.loading) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": "reflex___state____state__tests___units___reflex_components_ui___components___test_skeleton____skeleton_state.loading_rx_state_", + "true_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"div"', + "props": [ + '"aria-hidden":true', + "className:sx_89c14fd899_c", + '"data-rx-skeleton":""', + "inert:true", + "tabIndex:-1", + ], + "children": [{"contents": '"Report"'}], + } + ], + }, + "false_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"div"', + "props": [], + "children": [{"contents": '"Report"'}], + } + ], + } + ], + }, + } + ], + } diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 75381b39f95..7716c35f395 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -138,6 +138,7 @@ def test_every_wave_is_in_the_namespace(): "progress", "section", "separator", + "skeleton", "spacer", "spinner", "stack", From 89eb32103be4d230180d1e69b191b24a848dd560 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:00:43 +0000 Subject: [PATCH 059/204] Compare each skeleton with its own declared style Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../components/test_skeleton.py | 167 +++++++++++++----- 1 file changed, 123 insertions(+), 44 deletions(-) diff --git a/tests/units/reflex_components_ui/components/test_skeleton.py b/tests/units/reflex_components_ui/components/test_skeleton.py index 231bbbfec9c..88219ebeb9b 100644 --- a/tests/units/reflex_components_ui/components/test_skeleton.py +++ b/tests/units/reflex_components_ui/components/test_skeleton.py @@ -8,47 +8,6 @@ import reflex as rx -# What each leaf of a spinner declares. -LEAF: dict[str, Any] = { - "animationName": Keyframes( - ( - '{"from": {"backgroundColor": "var(--gray-a3)"}, "to": {"backgroundColor": "var(--gray-a4)"}}', - ), - ("$/reflex-ui/tokens/gray.stylex.js",), - ), - "animationDuration": "1000ms !important", - "animationTimingFunction": "ease !important", - "animationDelay": "0s !important", - "animationIterationCount": "infinite !important", - "animationDirection": "alternate-reverse !important", - "animationFillMode": "none !important", - "animationPlayState": "running !important", - "backgroundImage": "none !important", - "backgroundClip": "border-box !important", - "borderStyle": "none !important", - "borderWidth": "medium !important", - "borderColor": "currentcolor !important", - "boxShadow": "none !important", - "boxDecorationBreak": "clone !important", - "color": "transparent !important", - "outlineStyle": "none !important", - "outlineWidth": "medium !important", - "outlineColor": "currentcolor !important", - "pointerEvents": "none !important", - "userSelect": "none !important", - "cursor": "default !important", - "visibility": {"::before": "hidden !important", "::after": "hidden !important"}, - "display": {":empty": "block"}, - "height": {":empty": "var(--space-3)"}, - "borderTopLeftRadius": "var(--radius-1)", - "borderTopRightRadius": "var(--radius-1)", - "borderBottomRightRadius": "var(--radius-1)", - "borderBottomLeftRadius": "var(--radius-1)", - "lineHeight": 0, - "fontFamily": "Arial, sans-serif !important", - "width": {"default": "60px", "@media (min-width: 1024px)": "160px"}, -} - class SkeletonState(rx.State): """What a skeleton is bound to.""" @@ -75,7 +34,50 @@ def test_skeleton_around_text( ], "children": [{"contents": '"1,204 euros"'}], } - assert declared_styles(component) == [LEAF] + assert declared_styles(component) == [ + { + "animationName": Keyframes( + ( + '{"from": {"backgroundColor": "var(--gray-a3)"}, "to": {"backgroundColor": "var(--gray-a4)"}}', + ), + ("$/reflex-ui/tokens/gray.stylex.js",), + ), + "animationDuration": "1000ms !important", + "animationTimingFunction": "ease !important", + "animationDelay": "0s !important", + "animationIterationCount": "infinite !important", + "animationDirection": "alternate-reverse !important", + "animationFillMode": "none !important", + "animationPlayState": "running !important", + "backgroundImage": "none !important", + "backgroundClip": "border-box !important", + "borderStyle": "none !important", + "borderWidth": "medium !important", + "borderColor": "currentcolor !important", + "boxShadow": "none !important", + "boxDecorationBreak": "clone !important", + "color": "transparent !important", + "outlineStyle": "none !important", + "outlineWidth": "medium !important", + "outlineColor": "currentcolor !important", + "pointerEvents": "none !important", + "userSelect": "none !important", + "cursor": "default !important", + "visibility": { + "::before": "hidden !important", + "::after": "hidden !important", + }, + "display": {":empty": "block"}, + "height": {":empty": "var(--space-3)"}, + "borderTopLeftRadius": "var(--radius-1)", + "borderTopRightRadius": "var(--radius-1)", + "borderBottomRightRadius": "var(--radius-1)", + "borderBottomLeftRadius": "var(--radius-1)", + "lineHeight": 0, + "fontFamily": "Arial, sans-serif !important", + "width": {"default": "60px", "@media (min-width: 1024px)": "160px"}, + } + ] def test_skeleton_alone( @@ -95,7 +97,49 @@ def test_skeleton_alone( ], "children": [], } - assert declared_styles(component) == [LEAF] + assert declared_styles(component) == [ + { + "animationName": Keyframes( + ( + '{"from": {"backgroundColor": "var(--gray-a3)"}, "to": {"backgroundColor": "var(--gray-a4)"}}', + ), + ("$/reflex-ui/tokens/gray.stylex.js",), + ), + "animationDuration": "1000ms !important", + "animationTimingFunction": "ease !important", + "animationDelay": "0s !important", + "animationIterationCount": "infinite !important", + "animationDirection": "alternate-reverse !important", + "animationFillMode": "none !important", + "animationPlayState": "running !important", + "backgroundImage": "none !important", + "backgroundClip": "border-box !important", + "borderStyle": "none !important", + "borderWidth": "medium !important", + "borderColor": "currentcolor !important", + "boxShadow": "none !important", + "boxDecorationBreak": "clone !important", + "color": "transparent !important", + "outlineStyle": "none !important", + "outlineWidth": "medium !important", + "outlineColor": "currentcolor !important", + "pointerEvents": "none !important", + "userSelect": "none !important", + "cursor": "default !important", + "visibility": { + "::before": "hidden !important", + "::after": "hidden !important", + }, + "display": {":empty": "block"}, + "height": "40px", + "borderTopLeftRadius": "var(--radius-1)", + "borderTopRightRadius": "var(--radius-1)", + "borderBottomRightRadius": "var(--radius-1)", + "borderBottomLeftRadius": "var(--radius-1)", + "lineHeight": 0, + "fontFamily": "Arial, sans-serif !important", + } + ] def test_skeleton_as_its_child( @@ -118,7 +162,42 @@ def test_skeleton_as_its_child( "children": [{"contents": '"Save"'}], } assert declared_styles(component) == [ - LEAF, + { + "animationName": Keyframes( + ( + '{"from": {"backgroundColor": "var(--gray-a3)"}, "to": {"backgroundColor": "var(--gray-a4)"}}', + ), + ("$/reflex-ui/tokens/gray.stylex.js",), + ), + "animationDuration": "1000ms !important", + "animationTimingFunction": "ease !important", + "animationDelay": "0s !important", + "animationIterationCount": "infinite !important", + "animationDirection": "alternate-reverse !important", + "animationFillMode": "none !important", + "animationPlayState": "running !important", + "backgroundImage": "none !important", + "backgroundClip": "border-box !important", + "borderStyle": "none !important", + "borderWidth": "medium !important", + "borderColor": "currentcolor !important", + "boxShadow": "none !important", + "boxDecorationBreak": "clone !important", + "color": "transparent !important", + "outlineStyle": "none !important", + "outlineWidth": "medium !important", + "outlineColor": "currentcolor !important", + "pointerEvents": "none !important", + "userSelect": "none !important", + "cursor": "default !important", + "visibility": { + "::before": "hidden !important", + "::after": "hidden !important", + }, + "display": {":empty": "block"}, + "height": {":empty": "var(--space-3)"}, + "width": "120px !important", + }, { "marginTop": "0", "marginRight": "0", From ea42645276dc0e7e6febfde383c51c2a21f1ba47 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:09:09 +0000 Subject: [PATCH 060/204] Add rx.ui.scroll_area, which scrolls natively Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/allowlist.toml | 24 +++ .../ui_parity/components/scroll_area.py | 162 ++++++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/scroll_area.py | 62 +++++++ .../styles/scroll_area.py | 92 ++++++++++ .../components/test_scroll_area.py | 140 +++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 7 files changed, 482 insertions(+) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py create mode 100644 tests/units/reflex_components_ui/components/test_scroll_area.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 25c7e2c98ba..804aedf109e 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -54,3 +54,27 @@ component = "avatar" check = "pixels" cells = "size-responsive-large@800" reason = "When the size of rx.avatar grows at a breakpoint from one of the four small sizes to a larger one, Radix Themes keeps the smaller letters the small size has for a fallback of two letters. rx.ui.avatar gives the two letters the size they have in an avatar of the larger size alone." + +[[contract]] +component = "scroll_area" +step = "scrolls to its last line with JavaScript disabled" +system = "rx" +reason = "rx.scroll_area scrolls once JavaScript has run: until then its content is clipped. rx.ui.scroll_area scrolls natively, with or without JavaScript." + +[[look]] +component = "scroll_area" +check = "style" +properties = ["overflow-x", "overflow-y"] +reason = "rx.ui.scroll_area is itself the element that scrolls. rx.scroll_area is a clipped box around a viewport that scrolls and the scrollbars it draws." + +[[look]] +component = "scroll_area" +check = "pixels" +cells = "*type-always*" +reason = "rx.ui.scroll_area scrolls natively and has the scrollbars of the browser, thin and in the grays of the theme, where rx.scroll_area draws scrollbars of its own with JavaScript. Their shape and where they show follow the browser and the system: they may take room beside the content or lie over it, and `type` \"hover\" and \"scroll\" and `scroll_hide_delay` are left to them." + +[[look]] +component = "scroll_area" +check = "pixels" +cells = "content-*_type-auto" +reason = "rx.ui.scroll_area scrolls natively and has the scrollbars of the browser, thin and in the grays of the theme, where rx.scroll_area draws scrollbars of its own with JavaScript. Their shape and where they show follow the browser and the system: they may take room beside the content or lie over it, and `type` \"hover\" and \"scroll\" and `scroll_hide_delay` are left to them." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py new file mode 100644 index 00000000000..d6f5421679a --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py @@ -0,0 +1,162 @@ +"""The scroll area: a box that scrolls what does not fit, natively in rx.ui.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix + +# What an area holds, by how it overflows a frame of 208 by 88 pixels. +CONTENT = { + "fits": (120, 40), + "tall": (120, 300), + "wide": (500, 40), + "large": (500, 300), +} + +# The scroller of an area: the area itself in rx.ui, its viewport in Radix. +SCROLLER = """(area) => [area, ...area.querySelectorAll("*")].find((element) => { + const style = getComputedStyle(element); + return /auto|scroll/.test(style.overflowY + style.overflowX); +})""" + + +def _block(width: int, height: int) -> Any: + """Create something to scroll: stripes of a fixed size. + + Args: + width: Its width, in pixels. + height: Its height, in pixels. + + Returns: + The element. + """ + return rx.el.div( + style={ + "width": f"{width}px", + "height": f"{height}px", + "background_image": ( + "repeating-linear-gradient(135deg, rgb(200, 200, 220) 0 10px, " + "rgb(120, 120, 180) 10px 20px)" + ), + }, + ) + + +def _scroll_area(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a scroll area around stripes that fit or overflow. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``content`` names what the area holds. + + Returns: + The scroll area. + """ + props = dict(props) + content = props.pop("content", "fits") + return namespace.scroll_area(_block(*CONTENT[content]), **props) + + +SCROLLBARS = ["vertical", "horizontal", "both"] +TYPES = ["auto", "always", "scroll", "hover"] + +MATRIX = Matrix( + component="scroll_area", + render=_scroll_area, + cross={"scrollbars": SCROLLBARS, "type": TYPES}, + sweep={ + "content": ["tall", "wide", "large"], + "scroll_hide_delay": [100], + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + {"content": ["tall", "wide", "large"], "scrollbars": SCROLLBARS, "type": TYPES}, + {"content": ["large"], "appearance": [DARK]}, + ], + crop="stage", + # Held to zero wherever no scrollbar shows. Where Radix Themes draws its + # own scrollbars, the area of rx.ui has the ones of the browser, which + # the allowlist says: in this browser they lie over the content and show + # while it scrolls, so a cell at rest has none. + threshold=0, + tolerance=0, +) + +CONTRACT = Contract( + component="scroll_area", + render=lambda namespace: rx.el.div( + namespace.scroll_area( + rx.el.p("First line", id="first"), + _block(600, 600), + rx.el.p("Last line", id="last"), + ), + id="area", + style={"width": "200px", "height": "150px"}, + ), +) + + +def _scroll_offsets(run: Run) -> list[int]: + """Read how far the area is scrolled. + + Args: + run: The run of the step. + + Returns: + The offsets of its scroller, from the left and from the top. + """ + return run.page.locator("#area").evaluate( + f"(area) => {{ const scroller = ({SCROLLER})(area);" + " return [Math.round(scroller.scrollLeft), Math.round(scroller.scrollTop)]; }" + ) + + +@CONTRACT.step("holds all its content in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("area").tag == "div" + assert run.server.element("first").text == "First line" + assert run.server.element("last").text == "Last line" + + +@CONTRACT.step("scrolls to its last line with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + run.page.locator("#area").hover() + run.page.mouse.wheel(0, 2000) + run.page.locator("#last").wait_for() + run.page.wait_for_function( + "document.getElementById('last').getBoundingClientRect().bottom" + " <= document.getElementById('area').getBoundingClientRect().bottom + 1" + ) + + +@CONTRACT.step("the wheel scrolls it both ways", on=HYDRATED) +def _wheel(run: Run) -> None: + assert _scroll_offsets(run) == [0, 0] + run.page.locator("#area").hover() + run.page.mouse.wheel(120, 80) + run.page.wait_for_function( + f"(() => {{ const scroller = ({SCROLLER})(document.getElementById('area'));" + " return scroller.scrollLeft === 120 && scroller.scrollTop === 80; })()" + ) + + +@CONTRACT.step("Tab reaches it and the keyboard scrolls it", on=HYDRATED) +def _keyboard(run: Run) -> None: + run.page.keyboard.press("Tab") + assert run.page.locator("#area").evaluate( + f"(area) => ({SCROLLER})(area) === document.activeElement" + ) + run.page.keyboard.press("End") + run.page.wait_for_function( + f"(() => {{ const scroller = ({SCROLLER})(document.getElementById('area'));" + " return scroller.scrollTop > 0; })()" + ) + run.page.keyboard.press("Home") + run.page.wait_for_function( + f"({SCROLLER})(document.getElementById('area')).scrollTop === 0" + ) 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 2d3cbf69e2e..a522be80a71 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -17,6 +17,7 @@ "components.icon_button": ["icon_button"], "components.inset": ["inset"], "components.progress": ["progress"], + "components.scroll_area": ["scroll_area"], "components.separator": ["divider", "separator"], "components.skeleton": ["skeleton"], "components.spinner": ["spinner"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.py b/packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.py new file mode 100644 index 00000000000..4f1f2133d11 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.py @@ -0,0 +1,62 @@ +"""A scroll area: a box that scrolls what does not fit in it.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import Var + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.scroll_area import SCROLL_AREA + + +class ScrollArea(UIComponent): + """Custom styled, cross-browser scrollable area using native functionality.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = SCROLL_AREA + + scrollbars: Var[Literal["vertical", "horizontal", "both"]] = field( + doc="The alignment of the scroll area" + ) + + type: Var[Literal["auto", "always", "scroll", "hover"]] = field( + doc='Describes the nature of scrollbar visibility, similar to how the scrollbar preferences in MacOS control visibility of native scrollbars. "auto" | "always" | "scroll" | "hover"' + ) + + scroll_hide_delay: Var[int] = field( + doc='If type is set to either "scroll" or "hover", this prop determines the length of time, in milliseconds, before the scrollbars are hidden after the user stops interacting with scrollbars.' + ) + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the delay, which the scrollbars of + the browser do not take. + """ + return [*super()._exclude_props(), "type", "scroll_hide_delay"] + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a scroll area around its children. + + The area scrolls natively, with the scrollbars of the browser: no + script runs, and it scrolls with JavaScript disabled. + + Args: + *children: What the area scrolls. + **props: The props of the area. + + Returns: + The scroll area. + """ + return super().create( + Part.create(*children, part="content", tag="div"), **props + ) + + +scroll_area = ScrollArea.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py new file mode 100644 index 00000000000..82b2f5e724b --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py @@ -0,0 +1,92 @@ +"""The look of a scroll area: a box that scrolls what does not fit in it.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked + +gray = tokens.gray + +# Which way the area scrolls, by its scrollbars: each axis as a keyword of +# `overflow`, the first for an area that scrolls when there is too much and +# the second for one whose scrollbars always show. +_AXES: dict[str, tuple[bool, bool]] = { + "vertical": (False, True), + "horizontal": (True, False), + "both": (True, True), +} + + +def _overflow(scrollbars: str, always: bool) -> dict[str, Any]: + """Make the overflow of an area. + + Args: + scrollbars: Which scrollbars the area has. + always: Whether they show when everything fits. + + Returns: + The overflow of each axis: an axis without a scrollbar is clipped. + """ + horizontal, vertical = _AXES[scrollbars] + shown = "scroll" if always else "auto" + style: dict[str, Any] = { + "overflow_x": shown if horizontal else "hidden", + "overflow_y": shown if vertical else "hidden", + } + if horizontal: + # No swipe back or forward in the history at the end of the area. + style["overscroll_behavior_x"] = "contain" + return style + + +_ALWAYS: list[CompoundStyle] = [ + { + "props": {"scrollbars": scrollbars, "type": "always"}, + "style": unchecked(_overflow(scrollbars, always=True)), + } + for scrollbars in _AXES +] + +# The area scrolls natively: the scrollbars are the ones of the browser, thin +# and in the grays Radix Themes draws its own with. +SCROLL_AREA: ComponentStyles = { + "base": unchecked({ + "box_sizing": "border-box", + "display": "flex", + "flex_direction": "column", + "position": "relative", + "width": "100%", + "height": "100%", + "scrollbar_width": "thin", + "scrollbar_color": f"{gray.a[8]} {gray.a[3]}", + ":focus-visible": { + "outline_width": "2px", + "outline_style": "solid", + "outline_color": tokens.focus[8], + "outline_offset": "-2px", + }, + }), + "variants": { + "scrollbars": { + scrollbars: unchecked(_overflow(scrollbars, always=False)) + for scrollbars in _AXES + }, + }, + "defaults": {"scrollbars": "both"}, + "compound": _ALWAYS, + "parts": { + # What is inside is laid out as in any block, as wide as it needs + # and at least as wide as the area. + "content": { + "base": { + "box_sizing": "border-box", + "display": "block", + "width": "fit-content", + "min_width": "100%", + "flex_grow": 1, + } + }, + }, +} diff --git a/tests/units/reflex_components_ui/components/test_scroll_area.py b/tests/units/reflex_components_ui/components/test_scroll_area.py new file mode 100644 index 00000000000..b52a504e374 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_scroll_area.py @@ -0,0 +1,140 @@ +"""Tests for reflex_components_ui.components.scroll_area.""" + +from collections.abc import Callable +from typing import Any + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def test_scroll_area_plain( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A scroll area scrolls both ways, around a block that holds its children.""" + component = rx.ui.scroll_area(rx.el.p("One"), rx.el.p("Two"), id="area") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_d0de57eb68_c", 'id:"area"', "ref:ref_area"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_b06d947c7c_c"], + "children": [ + {"name": '"p"', "props": [], "children": [{"contents": '"One"'}]}, + {"name": '"p"', "props": [], "children": [{"contents": '"Two"'}]}, + ], + } + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "position": "relative", + "width": "100%", + "height": "100%", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) var(--gray-a3)", + "outlineWidth": {":focus-visible": "2px"}, + "outlineStyle": {":focus-visible": "solid"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-2px"}, + "overflowX": "auto", + "overflowY": "auto", + "overscrollBehaviorX": "contain", + }, + { + "boxSizing": "border-box", + "display": "block", + "width": "fit-content", + "minWidth": "100%", + "flexGrow": 1, + }, + ] + + +def test_scroll_area_vertical_always( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """One scrollbar clips the other axis, and always shows it.""" + component = rx.ui.scroll_area( + "Text", + scrollbars="vertical", + type="always", + scroll_hide_delay=100, + height="120px", + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_b6352d4ad5_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_b06d947c7c_c"], + "children": [{"contents": '"Text"'}], + } + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "position": "relative", + "width": "100%", + "height": "120px", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) var(--gray-a3)", + "outlineWidth": {":focus-visible": "2px"}, + "outlineStyle": {":focus-visible": "solid"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-2px"}, + "overflowX": "hidden", + "overflowY": "scroll", + }, + { + "boxSizing": "border-box", + "display": "block", + "width": "fit-content", + "minWidth": "100%", + "flexGrow": 1, + }, + ] + + +def test_scroll_area_horizontal( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A horizontal area keeps a swipe from leaving the page.""" + component = rx.ui.scroll_area("Text", scrollbars="horizontal", type="hover") + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "position": "relative", + "width": "100%", + "height": "100%", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) var(--gray-a3)", + "outlineWidth": {":focus-visible": "2px"}, + "outlineStyle": {":focus-visible": "solid"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-2px"}, + "overflowX": "auto", + "overflowY": "hidden", + "overscrollBehaviorX": "contain", + }, + { + "boxSizing": "border-box", + "display": "block", + "width": "fit-content", + "minWidth": "100%", + "flexGrow": 1, + }, + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 7716c35f395..131ae930729 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -136,6 +136,7 @@ def test_every_wave_is_in_the_namespace(): "list_item", "ordered_list", "progress", + "scroll_area", "section", "separator", "skeleton", From 785e084e4521a3042b210cbe949732827e140b21 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:14:42 +0000 Subject: [PATCH 061/204] Add rx.ui.table, with its parts Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../parity/ui_parity/components/table.py | 223 +++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/table.py | 222 +++++++++++ .../src/reflex_components_ui/styles/table.py | 188 +++++++++ .../components/test_table.py | 377 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 9 +- 6 files changed, 1019 insertions(+), 1 deletion(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/table.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/table.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/table.py create mode 100644 tests/units/reflex_components_ui/components/test_table.py diff --git a/packages/reflex-components-ui/parity/ui_parity/components/table.py b/packages/reflex-components-ui/parity/ui_parity/components/table.py new file mode 100644 index 00000000000..7f4fbea38f8 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/table.py @@ -0,0 +1,223 @@ +"""The table: a header, row headers and cells, in each variant and size.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, LIGHT, Matrix +from ui_parity.samples import PARAGRAPH + +PEOPLE = ( + ("Danilo Sousa", "danilo@example.com", "Developer"), + ("Zahra Ambessa", "zahra@example.com", "Admin"), + ("Jasper Eriksson", "jasper@example.com", "Developer"), +) +RESPONSIVE = rx.breakpoints(initial="1", sm="3", lg="2") + + +def _table(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a table of people, with what a cell says of its rows and cells. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``row`` and ``cell`` hold the props of + every row of the body and of every cell, ``header`` the ones of + the header cells, and ``content`` names what the cells hold. + + Returns: + The table. + """ + props = dict(props) + row = props.pop("row", {}) + cell = props.pop("cell", {}) + header = props.pop("header", {}) + content = props.pop("content", "short") + table = namespace.table + people = PEOPLE + if content == "long": + people = ((PEOPLE[0][0], PARAGRAPH, "Developer"), *PEOPLE[1:]) + if content == "wide": + people = tuple( + (name, f"{email} · {email} · {email}", role) for name, email, role in PEOPLE + ) + return table.root( + table.header( + table.row( + *( + table.column_header_cell(title, **header) + for title in ("Full name", "Email", "Group") + ) + ) + ), + table.body( + *( + table.row( + table.row_header_cell(name, **cell), + table.cell(email, **cell), + table.cell(role, **cell), + **row, + ) + for name, email, role in people + ) + ), + **props, + ) + + +MATRIX = Matrix( + component="table", + render=_table, + cross={"variant": ["ghost", "surface"], "size": ["1", "2", "3"]}, + sweep={ + "size": {"responsive": RESPONSIVE}, + "content": ["long", "wide"], + "row": { + f"align-{align}": {"align": align} + for align in ("start", "center", "end", "baseline") + }, + "cell": { + **{ + f"justify-{justify}": {"justify": justify} + for justify in ("start", "center", "end") + }, + "p-4": {"p": "4"}, + "px-0": {"px": "0"}, + "py-1": {"py": "1"}, + "sides": {"pt": "1", "pr": "2", "pb": "3", "pl": "4"}, + "min-width": {"min_width": "200px"}, + "max-width": {"max_width": "60px"}, + "responsive": { + "p": rx.breakpoints(initial="1", sm="4"), + "min_width": rx.breakpoints(initial="60px", sm="180px"), + }, + }, + "header": { + "justify-end": {"justify": "end"}, + "min-width": {"min_width": "200px"}, + }, + "appearance": [DARK], + "viewport": [520], + }, + groups=[ + { + "variant": ["ghost", "surface"], + "content": ["long", "wide"], + "appearance": [LIGHT, DARK], + }, + { + "row": {"align-center": {"align": "center"}, "align-end": {"align": "end"}}, + "content": ["long"], + "variant": ["ghost", "surface"], + }, + { + "size": {"responsive": RESPONSIVE}, + "variant": ["ghost", "surface"], + "viewport": [520, 800, 1100, 1280], + }, + { + "cell": { + "responsive": { + "p": rx.breakpoints(initial="1", sm="4"), + "min_width": rx.breakpoints(initial="60px", sm="180px"), + } + }, + "viewport": [520, 800], + }, + ], + stage=(480, 300), + crop="stage", + parts={ + "table": "table", + "header": "thead", + "body": "tbody", + "row": "tbody tr", + "last row": "tbody tr:last-child", + "column header": "thead th", + "row header": "tbody th", + "cell": "td", + "last cell": "tbody tr:last-child td", + }, + # No pixel may differ, at the default threshold and not at zero. At a + # threshold of zero the 37 cells of the ghost variant are equal, and the + # 13 of the surface variant differ by one step of a channel in a band of + # the header: its see-through background lies over the see-through panel + # of the table, and the two systems put a different number of boxes + # between them, which the browser blends in another order. + tolerance=0, +) + +CONTRACT = Contract( + component="table", + render=lambda namespace: namespace.table.root( + namespace.table.header( + namespace.table.row( + namespace.table.column_header_cell("Full name", id="name"), + namespace.table.column_header_cell("Group"), + id="head", + ), + id="header", + ), + namespace.table.body( + namespace.table.row( + namespace.table.row_header_cell("Danilo Sousa", id="danilo"), + namespace.table.cell("Developer", id="group"), + ), + id="body", + ), + id="root", + ), +) + + +@CONTRACT.step("is a table of rows and cells in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("root").tag == "div" + assert run.server.element("header").tag == "thead" + assert run.server.element("body").tag == "tbody" + assert (run.server.element("head").tag, run.server.element("head").text) == ( + "tr", + "Full nameGroup", + ) + assert run.server.element("name").tag == "th" + assert run.server.element("danilo").tag == "th" + group = run.server.element("group") + assert (group.tag, group.text) == ("td", "Developer") + + +@CONTRACT.step( + "lays its cells out in columns with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + _columns(run) + + +@CONTRACT.step("has the roles of a table, its headers and its cells", on=HYDRATED) +def _roles(run: Run) -> None: + _columns(run) + page = run.page + assert page.get_by_role("table").count() == 1 + assert page.get_by_role("rowgroup").count() == 2 + assert page.get_by_role("row").count() == 2 + assert page.get_by_role("columnheader").all_inner_texts() == ["Full name", "Group"] + assert page.get_by_role("rowheader").all_inner_texts() == ["Danilo Sousa"] + assert page.get_by_role("cell").all_inner_texts() == ["Developer"] + + +def _columns(run: Run) -> None: + """Check that a cell is under its column header, beside its row header. + + Args: + run: The run of the step. + """ + name = run.page.locator("#name").bounding_box() + danilo = run.page.locator("#danilo").bounding_box() + group = run.page.locator("#group").bounding_box() + assert name is not None + assert danilo is not None + assert group is not None + assert (danilo["x"], danilo["width"]) == (name["x"], name["width"]) + assert danilo["y"] == name["y"] + name["height"] + assert (group["y"], group["x"]) == (danilo["y"], danilo["x"] + danilo["width"]) 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 a522be80a71..d3ba0571080 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -21,6 +21,7 @@ "components.separator": ["divider", "separator"], "components.skeleton": ["skeleton"], "components.spinner": ["spinner"], + "components.table": ["table"], "layout.box": ["box"], "layout.center": ["center"], "layout.container": ["container"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/table.py b/packages/reflex-components-ui/src/reflex_components_ui/components/table.py new file mode 100644 index 00000000000..86d0f87d0ad --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/table.py @@ -0,0 +1,222 @@ +"""A table: rows of cells under a header.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.props import LiteralSpacing, style_props +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.table import ( + TABLE_BODY, + TABLE_CELL, + TABLE_COLUMN_HEADER_CELL, + TABLE_HEADER, + TABLE_ROOT, + TABLE_ROW, + TABLE_ROW_HEADER_CELL, +) + +# The props of a cell that are the CSS property of the same name. +_WIDTH_PROPS = ("min_width", "max_width") + + +class TableRootTable(Part): + """The table inside a table root, which the header and the body go in.""" + + tag = "table" + + +class TableRoot(UIComponent, elements.Table): + """A semantic table for presenting tabular data.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = TABLE_ROOT + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc='The size of the table: "1" | "2" | "3"' + ) + + variant: Var[Literal["surface", "ghost"]] = field(doc="The variant of the table") + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a table, inside a box that scrolls when it is too wide. + + Args: + *children: The header and the body of the table. + **props: The props of the table. + + Returns: + The root: a block around the box that scrolls, around the table. + """ + return super().create( + Part.create( + Part.create( + TableRootTable.create(*children, part="table"), + part="content", + tag="div", + ), + part="scroll", + tag="div", + ), + **props, + ) + + +class TableHeader(UIComponent, elements.Thead): + """The header of the table defines column names and other non-data elements.""" + + tag = "thead" + + styles: ClassVar[ComponentStyles] = TABLE_HEADER + + _invalid_children: ClassVar[list[str]] = ["TableBody"] + + _valid_parents: ClassVar[list[str]] = ["TableRootTable"] + + +class TableRow(UIComponent, elements.Tr): + """A row containing table cells.""" + + tag = "tr" + + styles: ClassVar[ComponentStyles] = TABLE_ROW + + align: Var[Literal["start", "center", "end", "baseline"]] = field( + doc="The alignment of the row" + ) + + _invalid_children: ClassVar[list[str]] = ["TableBody", "TableHeader", "TableRow"] + + +class TableBody(UIComponent, elements.Tbody): + """The body of the table contains the data rows.""" + + tag = "tbody" + + styles: ClassVar[ComponentStyles] = TABLE_BODY + + _invalid_children: ClassVar[list[str]] = [ + "TableHeader", + "TableRowHeaderCell", + "TableColumnHeaderCell", + "TableCell", + ] + + _valid_parents: ClassVar[list[str]] = ["TableRootTable"] + + +class BaseCell(UIComponent): + """What every cell of a table shares.""" + + justify: Var[Literal["start", "center", "end"]] = field( + doc="The justification of the column" + ) + + min_width: Var[Responsive[str]] = field(doc="The minimum width of the cell") + + max_width: Var[Responsive[str]] = field(doc="The maximum width of the cell") + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a cell, its width props as styles. + + Args: + *children: The children of the cell. + **props: The props of the cell. + + Returns: + The cell. + """ + style_props(cls._display_name(), props, _WIDTH_PROPS) + return super().create(*children, **props) + + +class PaddingProps(UIComponent): + """The padding props of a cell, in steps of the space scale.""" + + p: Var[Responsive[LiteralSpacing]] = field(doc='Padding: "0" - "9" # noqa: ERA001') + + px: Var[Responsive[LiteralSpacing]] = field(doc='Padding horizontal: "0" - "9"') + + py: Var[Responsive[LiteralSpacing]] = field(doc='Padding vertical: "0" - "9"') + + pt: Var[Responsive[LiteralSpacing]] = field(doc='Padding top: "0" - "9"') + + pr: Var[Responsive[LiteralSpacing]] = field(doc='Padding right: "0" - "9"') + + pb: Var[Responsive[LiteralSpacing]] = field(doc='Padding bottom: "0" - "9"') + + pl: Var[Responsive[LiteralSpacing]] = field(doc='Padding left: "0" - "9"') + + +class TableColumnHeaderCell(BaseCell, elements.Th): + """A table cell that is semantically treated as a column header.""" + + tag = "th" + + styles: ClassVar[ComponentStyles] = TABLE_COLUMN_HEADER_CELL + + _invalid_children: ClassVar[list[str]] = [ + "TableBody", + "TableHeader", + "TableRow", + "TableCell", + "TableColumnHeaderCell", + "TableRowHeaderCell", + ] + + +class TableCell(BaseCell, PaddingProps, elements.Td): + """A cell containing data.""" + + tag = "td" + + styles: ClassVar[ComponentStyles] = TABLE_CELL + + _invalid_children: ClassVar[list[str]] = [ + "TableBody", + "TableHeader", + "TableRowHeaderCell", + "TableColumnHeaderCell", + "TableCell", + ] + + +class TableRowHeaderCell(BaseCell, PaddingProps, elements.Th): + """A table cell that is semantically treated as a row header.""" + + tag = "th" + + styles: ClassVar[ComponentStyles] = TABLE_ROW_HEADER_CELL + + _invalid_children: ClassVar[list[str]] = [ + "TableBody", + "TableHeader", + "TableRow", + "TableCell", + "TableColumnHeaderCell", + "TableRowHeaderCell", + ] + + +class Table(ComponentNamespace): + """Table components namespace.""" + + root = staticmethod(TableRoot.create) + header = staticmethod(TableHeader.create) + body = staticmethod(TableBody.create) + row = staticmethod(TableRow.create) + cell = staticmethod(TableCell.create) + column_header_cell = staticmethod(TableColumnHeaderCell.create) + row_header_cell = staticmethod(TableRowHeaderCell.create) + + +table = Table() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py new file mode 100644 index 00000000000..ab991a2624c --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py @@ -0,0 +1,188 @@ +"""The look of a table.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.scroll_area import SCROLL_AREA + +gray = tokens.gray + +# What the root sets and the cells read, as in Radix Themes. +_RADIUS = "--table-border-radius" +_CELL_PADDING = "--table-cell-padding" +_CELL_MIN_HEIGHT = "--table-cell-min-height" +_ROW_BACKGROUND = "--table-row-background-color" +_ROW_SHADOW = "--table-row-box-shadow" + +# What Radix Themes selects by ancestor, handed down instead: the background +# of the header of a surface table, and the line under the last row of its +# body, which a surface table does not draw. +_HEADER_BACKGROUND = "--rx-table-header-background" +_BODY_LAST_ROW_SHADOW = "--rx-table-body-last-row-shadow" +_LAST_ROW_SHADOW = "--rx-table-last-row-shadow" + +_LINE = f"inset 0 -1px {gray.a[5]}" + +# The radius, the padding and the least height of a cell, and the text. +_SIZES: dict[str, tuple[str, str, str, str, str]] = { + "1": ( + tokens.radius[3], + tokens.space[2], + f"calc(36px * {tokens.scaling})", + tokens.font_size[2], + tokens.line_height[2], + ), + "2": ( + tokens.radius[4], + tokens.space[3], + f"calc(44px * {tokens.scaling})", + tokens.font_size[2], + tokens.line_height[2], + ), + "3": ( + tokens.radius[4], + f"{tokens.space[3]} {tokens.space[4]}", + tokens.space[8], + tokens.font_size[3], + tokens.line_height[3], + ), +} + +_scroll_parts: Any = SCROLL_AREA["parts"] + +TABLE_ROOT: ComponentStyles = { + "variants": { + "size": { + size: unchecked({ + _RADIUS: radius, + _CELL_PADDING: padding, + _CELL_MIN_HEIGHT: height, + }) + for size, (radius, padding, height, _, _) in _SIZES.items() + }, + "variant": { + "surface": unchecked({ + "box_sizing": "border-box", + "border_width": "1px", + "border_style": "solid", + # Half see-through, to blend with what is behind the table. + "border_color": f"color-mix(in oklab, {gray.a[5]}, {gray[6]})", + "border_radius": f"var({_RADIUS})", + "background_color": tokens.color.panel, + "backdrop_filter": tokens.panel.backdrop_filter, + "background_clip": "padding-box", + "position": "relative", + _HEADER_BACKGROUND: gray.a[2], + _BODY_LAST_ROW_SHADOW: "none", + }), + }, + }, + "defaults": {"size": "2", "variant": "ghost"}, + "parts": { + # The table scrolls sideways when it is wider than its place: the + # box of a scroll area, which scrolls natively. + "scroll": { + "base": { + **SCROLL_AREA["base"], + "overflow_x": "auto", + "overflow_y": "auto", + "overscroll_behavior_x": "contain", + }, + }, + "content": _scroll_parts["content"], + "table": { + "base": unchecked({ + _ROW_BACKGROUND: "transparent", + _ROW_SHADOW: _LINE, + "width": "100%", + "text_align": "left", + "vertical_align": "top", + "border_collapse": "collapse", + "border_radius": f"calc(var({_RADIUS}) - 1px)", + "border_spacing": "0", + "box_sizing": "border-box", + # Lets a height of 100% work inside a cell. + "height": "0", + }), + "variants": { + "size": { + size: {"font_size": font_size, "line_height": line_height} + for size, (_, _, _, font_size, line_height) in _SIZES.items() + }, + "variant": {"surface": {"overflow": "hidden"}}, + }, + "defaults": {"size": "2"}, + }, + }, +} + +TABLE_HEADER: ComponentStyles = { + "base": unchecked({ + "vertical_align": "inherit", + _ROW_BACKGROUND: f"var({_HEADER_BACKGROUND}, transparent)", + }), +} + +TABLE_BODY: ComponentStyles = { + "base": unchecked({ + "vertical_align": "inherit", + _LAST_ROW_SHADOW: f"var({_BODY_LAST_ROW_SHADOW}, {_LINE})", + }), +} + +TABLE_ROW: ComponentStyles = { + "base": unchecked({ + "vertical_align": "inherit", + "color": gray[12], + _ROW_SHADOW: {":last-child": f"var({_LAST_ROW_SHADOW}, {_LINE})"}, + }), + "variants": { + "align": { + "start": {"vertical_align": "top"}, + "center": {"vertical_align": "middle"}, + "end": {"vertical_align": "bottom"}, + "baseline": {"vertical_align": "baseline"}, + }, + }, +} + + +def cell_styles(font_weight: str | None) -> ComponentStyles: + """Make the style table of a cell. + + Args: + font_weight: The weight of a header cell, which the browser would + otherwise choose. + + Returns: + The table. + """ + base: dict[str, Any] = { + "background_color": f"var({_ROW_BACKGROUND})", + "box_shadow": f"var({_ROW_SHADOW})", + "box_sizing": "border-box", + "vertical_align": "inherit", + "padding": f"var({_CELL_PADDING})", + # Works as a least height. + "height": f"var({_CELL_MIN_HEIGHT})", + } + if font_weight is not None: + base["font_weight"] = font_weight + return { + "base": unchecked(base), + "variants": { + "justify": { + "start": {"text_align": "left"}, + "center": {"text_align": "center"}, + "end": {"text_align": "right"}, + }, + }, + } + + +TABLE_CELL: ComponentStyles = cell_styles(None) +TABLE_COLUMN_HEADER_CELL: ComponentStyles = cell_styles("bold") +TABLE_ROW_HEADER_CELL: ComponentStyles = cell_styles("normal") diff --git a/tests/units/reflex_components_ui/components/test_table.py b/tests/units/reflex_components_ui/components/test_table.py new file mode 100644 index 00000000000..bfd81219328 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_table.py @@ -0,0 +1,377 @@ +"""Tests for reflex_components_ui.components.table.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.components.component import Component +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +def people(**props: Any) -> Component: + """Create a table of one person. + + Args: + **props: The props of the root. + + Returns: + The table. + """ + table = rx.ui.table + return table.root( + table.header(table.row(table.column_header_cell("Name", min_width="80px"))), + table.body( + table.row( + table.row_header_cell("Ada", justify="center"), + table.cell( + "Admin", + justify="end", + px="4", + max_width=rx.breakpoints(initial="60px", md="120px"), + ), + align="center", + ) + ), + **props, + ) + + +def test_table_ghost( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A table is a block around a box that scrolls, around the table itself.""" + component = people(id="people") + assert component.render() == { + "name": '"div"', + "props": ["className:sx_bd7098de3f_c", 'id:"people"', "ref:ref_people"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_d0de57eb68_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_b06d947c7c_c"], + "children": [ + { + "name": '"table"', + "props": ["className:sx_9d58645f70_c"], + "children": [ + { + "name": '"thead"', + "props": ["className:sx_280fdd8cb1_c"], + "children": [ + { + "name": '"tr"', + "props": ["className:sx_4dca3cb40d_c"], + "children": [ + { + "name": '"th"', + "props": [ + "className:sx_679f7a88f7_c" + ], + "children": [ + {"contents": '"Name"'} + ], + } + ], + } + ], + }, + { + "name": '"tbody"', + "props": ["className:sx_03514a22c2_c"], + "children": [ + { + "name": '"tr"', + "props": ["className:sx_00a8b9e2b4_c"], + "children": [ + { + "name": '"th"', + "props": [ + "className:sx_6e04c0def9_c" + ], + "children": [ + {"contents": '"Ada"'} + ], + }, + { + "name": '"td"', + "props": [ + "className:sx_dd497830d2_c" + ], + "children": [ + {"contents": '"Admin"'} + ], + }, + ], + } + ], + }, + ], + } + ], + } + ], + } + ], + } + assert declared_styles(component) == [ + { + "--table-border-radius": "var(--radius-4)", + "--table-cell-padding": "var(--space-3)", + "--table-cell-min-height": "calc(44px * var(--scaling))", + }, + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "position": "relative", + "width": "100%", + "height": "100%", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) var(--gray-a3)", + "outlineWidth": {":focus-visible": "2px"}, + "outlineStyle": {":focus-visible": "solid"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-2px"}, + "overflowX": "auto", + "overflowY": "auto", + "overscrollBehaviorX": "contain", + }, + { + "boxSizing": "border-box", + "display": "block", + "width": "fit-content", + "minWidth": "100%", + "flexGrow": 1, + }, + { + "--table-row-background-color": "transparent", + "--table-row-box-shadow": "inset 0 -1px var(--gray-a5)", + "width": "100%", + "textAlign": "left", + "verticalAlign": "top", + "borderCollapse": "collapse", + "borderRadius": "calc(var(--table-border-radius) - 1px)", + "borderSpacing": "0", + "boxSizing": "border-box", + "height": "0", + "fontSize": "var(--font-size-2)", + "lineHeight": "var(--line-height-2)", + }, + { + "verticalAlign": "inherit", + "--table-row-background-color": "var(--rx-table-header-background, transparent)", + }, + { + "verticalAlign": "inherit", + "color": "var(--gray-12)", + "--table-row-box-shadow": { + ":last-child": "var(--rx-table-last-row-shadow, inset 0 " + "-1px var(--gray-a5))" + }, + }, + { + "backgroundColor": "var(--table-row-background-color)", + "boxShadow": "var(--table-row-box-shadow)", + "boxSizing": "border-box", + "verticalAlign": "inherit", + "padding": "var(--table-cell-padding)", + "height": "var(--table-cell-min-height)", + "fontWeight": "bold", + "minWidth": "80px", + }, + { + "verticalAlign": "inherit", + "--rx-table-last-row-shadow": "var(--rx-table-body-last-row-shadow, inset 0 -1px " + "var(--gray-a5))", + }, + { + "verticalAlign": "middle", + "color": "var(--gray-12)", + "--table-row-box-shadow": { + ":last-child": "var(--rx-table-last-row-shadow, inset 0 " + "-1px var(--gray-a5))" + }, + }, + { + "backgroundColor": "var(--table-row-background-color)", + "boxShadow": "var(--table-row-box-shadow)", + "boxSizing": "border-box", + "verticalAlign": "inherit", + "padding": "var(--table-cell-padding)", + "height": "var(--table-cell-min-height)", + "fontWeight": "normal", + "textAlign": "center", + }, + { + "backgroundColor": "var(--table-row-background-color)", + "boxShadow": "var(--table-row-box-shadow)", + "boxSizing": "border-box", + "verticalAlign": "inherit", + "padding": "var(--table-cell-padding)", + "height": "var(--table-cell-min-height)", + "textAlign": "right", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "maxWidth": {"default": "60px", "@media (min-width: 1024px)": "120px"}, + }, + ] + + +def test_table_surface( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A surface table tells its header its background, and its body to drop its last line.""" + component = people(variant="surface", size=rx.breakpoints(initial="1", md="3")) + assert declared_styles(component) == [ + { + "--table-border-radius": { + "default": "var(--radius-3)", + "@media (min-width: 1024px)": "var(--radius-4)", + }, + "--table-cell-padding": { + "default": "var(--space-2)", + "@media (min-width: 1024px)": "var(--space-3) var(--space-4)", + }, + "--table-cell-min-height": { + "default": "calc(36px * var(--scaling))", + "@media (min-width: 1024px)": "var(--space-8)", + }, + "boxSizing": "border-box", + "borderTopWidth": "1px", + "borderRightWidth": "1px", + "borderBottomWidth": "1px", + "borderLeftWidth": "1px", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", + "borderColor": "color-mix(in oklab, var(--gray-a5), var(--gray-6))", + "borderRadius": "var(--table-border-radius)", + "backgroundColor": "var(--color-panel)", + "backdropFilter": "var(--backdrop-filter-panel)", + "backgroundClip": "padding-box", + "position": "relative", + "--rx-table-header-background": "var(--gray-a2)", + "--rx-table-body-last-row-shadow": "none", + }, + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "position": "relative", + "width": "100%", + "height": "100%", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) var(--gray-a3)", + "outlineWidth": {":focus-visible": "2px"}, + "outlineStyle": {":focus-visible": "solid"}, + "outlineColor": {":focus-visible": "var(--focus-8)"}, + "outlineOffset": {":focus-visible": "-2px"}, + "overflowX": "auto", + "overflowY": "auto", + "overscrollBehaviorX": "contain", + }, + { + "boxSizing": "border-box", + "display": "block", + "width": "fit-content", + "minWidth": "100%", + "flexGrow": 1, + }, + { + "--table-row-background-color": "transparent", + "--table-row-box-shadow": "inset 0 -1px var(--gray-a5)", + "width": "100%", + "textAlign": "left", + "verticalAlign": "top", + "borderCollapse": "collapse", + "borderRadius": "calc(var(--table-border-radius) - 1px)", + "borderSpacing": "0", + "boxSizing": "border-box", + "height": "0", + "fontSize": { + "default": "var(--font-size-2)", + "@media (min-width: 1024px)": "var(--font-size-3)", + }, + "lineHeight": { + "default": "var(--line-height-2)", + "@media (min-width: 1024px)": "var(--line-height-3)", + }, + "overflowX": "hidden", + "overflowY": "hidden", + }, + { + "verticalAlign": "inherit", + "--table-row-background-color": "var(--rx-table-header-background, transparent)", + }, + { + "verticalAlign": "inherit", + "color": "var(--gray-12)", + "--table-row-box-shadow": { + ":last-child": "var(--rx-table-last-row-shadow, inset 0 " + "-1px var(--gray-a5))" + }, + }, + { + "backgroundColor": "var(--table-row-background-color)", + "boxShadow": "var(--table-row-box-shadow)", + "boxSizing": "border-box", + "verticalAlign": "inherit", + "padding": "var(--table-cell-padding)", + "height": "var(--table-cell-min-height)", + "fontWeight": "bold", + "minWidth": "80px", + }, + { + "verticalAlign": "inherit", + "--rx-table-last-row-shadow": "var(--rx-table-body-last-row-shadow, inset 0 -1px " + "var(--gray-a5))", + }, + { + "verticalAlign": "middle", + "color": "var(--gray-12)", + "--table-row-box-shadow": { + ":last-child": "var(--rx-table-last-row-shadow, inset 0 " + "-1px var(--gray-a5))" + }, + }, + { + "backgroundColor": "var(--table-row-background-color)", + "boxShadow": "var(--table-row-box-shadow)", + "boxSizing": "border-box", + "verticalAlign": "inherit", + "padding": "var(--table-cell-padding)", + "height": "var(--table-cell-min-height)", + "fontWeight": "normal", + "textAlign": "center", + }, + { + "backgroundColor": "var(--table-row-background-color)", + "boxShadow": "var(--table-row-box-shadow)", + "boxSizing": "border-box", + "verticalAlign": "inherit", + "padding": "var(--table-cell-padding)", + "height": "var(--table-cell-min-height)", + "textAlign": "right", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "maxWidth": {"default": "60px", "@media (min-width: 1024px)": "120px"}, + }, + ] + + +def test_table_header_goes_in_a_table(): + """A header or a body outside a table root is an error where it is placed.""" + with pytest.raises(ValueError, match="TableHeader") as raised: + rx.ui.box(rx.ui.table.header()) + assert str(raised.value) == ( + "The component `TableHeader` can only be a child of the components: " + "`TableRootTable`. Got `Box` instead." + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 131ae930729..f7574178623 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -143,6 +143,13 @@ def test_every_wave_is_in_the_namespace(): "spacer", "spinner", "stack", + "table.body", + "table.cell", + "table.column_header_cell", + "table.header", + "table.root", + "table.row", + "table.row_header_cell", "text", "text.em", "text.kbd", @@ -155,7 +162,7 @@ def test_every_wave_is_in_the_namespace(): ] -@pytest.mark.parametrize("namespace", ["callout", "data_list", "list", "text"]) +@pytest.mark.parametrize("namespace", ["callout", "data_list", "list", "table", "text"]) def test_namespace_has_the_members_of_its_radix_counterpart(namespace: str): assert members(getattr(reflex_components_ui, namespace)) == members( getattr(rx, namespace) From 3372a8b7c850ec88555b9ee5a493b3035aea32cb Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:23:01 +0000 Subject: [PATCH 062/204] Keep the cells whose Radix reference depends on timing out of the scroll area and skeleton matrices Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- packages/reflex-components-ui/parity/allowlist.toml | 6 ------ .../parity/ui_parity/components/scroll_area.py | 9 ++++++++- .../parity/ui_parity/components/skeleton.py | 13 ++++++++----- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 804aedf109e..342b517cfb9 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -72,9 +72,3 @@ component = "scroll_area" check = "pixels" cells = "*type-always*" reason = "rx.ui.scroll_area scrolls natively and has the scrollbars of the browser, thin and in the grays of the theme, where rx.scroll_area draws scrollbars of its own with JavaScript. Their shape and where they show follow the browser and the system: they may take room beside the content or lie over it, and `type` \"hover\" and \"scroll\" and `scroll_hide_delay` are left to them." - -[[look]] -component = "scroll_area" -check = "pixels" -cells = "content-*_type-auto" -reason = "rx.ui.scroll_area scrolls natively and has the scrollbars of the browser, thin and in the grays of the theme, where rx.scroll_area draws scrollbars of its own with JavaScript. Their shape and where they show follow the browser and the system: they may take room beside the content or lie over it, and `type` \"hover\" and \"scroll\" and `scroll_hide_delay` are left to them." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py index d6f5421679a..a779cf4486d 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py @@ -75,7 +75,14 @@ def _scroll_area(namespace: Any, props: Mapping[str, Any]) -> Any: "viewport": [520], }, groups=[ - {"content": ["tall", "wide", "large"], "scrollbars": SCROLLBARS, "type": TYPES}, + # Not `auto` around what overflows: Radix Themes then shows its + # scrollbars once it has measured the content, some time after the + # page is ready, so a screenshot has them or not. + { + "content": ["tall", "wide", "large"], + "scrollbars": SCROLLBARS, + "type": ["always", "scroll", "hover"], + }, {"content": ["large"], "appearance": [DARK]}, ], crop="stage", diff --git a/packages/reflex-components-ui/parity/ui_parity/components/skeleton.py b/packages/reflex-components-ui/parity/ui_parity/components/skeleton.py index 8fb8d7dab01..90da60c2add 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/skeleton.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/skeleton.py @@ -9,7 +9,7 @@ from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import DARK, LIGHT, Matrix -HOLDS = ["text", "words", "button", "soft-button", "avatar", "card", "nothing"] +HOLDS = ["text", "words", "button", "soft-button", "card"] def _skeleton(namespace: Any, props: Mapping[str, Any]) -> Any: @@ -48,8 +48,7 @@ def _skeleton(namespace: Any, props: Mapping[str, Any]) -> Any: MATRIX = Matrix( component="skeleton", render=_skeleton, - # A skeleton that holds nothing and is not loading renders nothing. - cross={"holds": HOLDS[:-1], "loading": [True, False]}, + cross={"holds": HOLDS, "loading": [True, False]}, sweep={ "width": { "fixed": "120px", @@ -60,12 +59,16 @@ def _skeleton(namespace: Any, props: Mapping[str, Any]) -> Any: "max_width": ["40px"], "min_height": ["60px"], "max_height": ["8px"], - "holds": ["nothing"], + # Loading only. A skeleton that holds nothing and is not loading + # renders nothing, and an avatar that is shown is the matrix of the + # avatar: the one of Radix Themes shows its fallback some time after + # the page is ready. + "holds": ["nothing", "avatar"], "appearance": [DARK], "viewport": [520], }, groups=[ - {"holds": HOLDS, "appearance": [LIGHT, DARK]}, + {"holds": [*HOLDS, "nothing", "avatar"], "appearance": [LIGHT, DARK]}, {"holds": ["nothing", "button"], "width": ["120px"], "height": ["40px"]}, { "holds": ["nothing", "text"], From 5594633ea92b3ea604a879d3e19a69a24d77109e Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:25:20 +0000 Subject: [PATCH 063/204] Let a component keep the styles of the child it is rendered as, and settle the types of the wave Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../src/reflex_components_ui/base.py | 7 ++- .../components/skeleton.py | 22 +++---- .../reflex_components_ui/components/table.py | 2 +- .../src/reflex_components_ui/styles/card.py | 15 +++-- .../styles/scroll_area.py | 61 ++++++++++--------- .../src/reflex_components_ui/styles/table.py | 8 +-- pyi_hashes.json | 11 +++- 7 files changed, 71 insertions(+), 55 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 189da7d2d18..2a17d7d144a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -207,6 +207,11 @@ class UIComponent(Component): # component, as Radix Themes falls back to its default. _as_tags: ClassVar[frozenset[str]] = frozenset() + # Whether an rx.ui child rendered in place of the element has its styles + # merged into the ones of the element. Otherwise each declares its own, + # and the child has the class names of both. + _merges_slot: ClassVar[bool] = True + # Whether a `radius` field is the radius of the element itself, applied # as a theme. A theme element has the option for what is inside it. _own_radius: ClassVar[bool] = True @@ -536,7 +541,7 @@ def _slot_styles(self) -> Merged: self._merge_styles() merged = self._merged slot = self._slot - if isinstance(slot, UIComponent): + if self._merges_slot and isinstance(slot, UIComponent): merged = over(merged, slot._slot_styles()) return merged diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py b/packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py index 1be07e01e4c..5f7f9bea8b4 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.py @@ -14,7 +14,7 @@ from reflex_components_ui.base import UIComponent from reflex_components_ui.components.spinner import while_loading from reflex_components_ui.props import style_props -from reflex_components_ui.style import ComponentStyles, Merged +from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.skeleton import SKELETON # The props that are the CSS property of the same name. @@ -53,6 +53,10 @@ class Skeleton(UIComponent): _memoization_mode = MemoizationMode(recursive=False) + # The element a skeleton is rendered as keeps its own styles: it is also + # what shows once it is no longer loading. + _merges_slot: ClassVar[bool] = False + @classmethod def create(cls, *children, **props) -> Component: """Create a skeleton in the place of its children while they load. @@ -120,17 +124,6 @@ def _post_init(self, *args, **kwargs): self._memoization_mode, recursive=False ) - def _slot_styles(self) -> Merged: - """Get the styles of the skeleton alone. - - Returns: - The styles the skeleton declares: the element it is rendered as - declares its own, and has the class names of both. - """ - if self.style is not self._merged_for: - self._merge_styles() - return self._merged - def _exclude_props(self) -> list[str]: """Keep the props that are not attributes off the element. @@ -168,9 +161,10 @@ def _has_radius(child: Any) -> bool: Returns: True if the styles of the element set its radius. """ - if not isinstance(child, UIComponent): + element_styles = getattr(child, "_element_styles", None) + if element_styles is None: return False - style = child._element_styles().style.style + style = element_styles().style.style return "borderRadius" in style or "borderTopLeftRadius" in style diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/table.py b/packages/reflex-components-ui/src/reflex_components_ui/components/table.py index 86d0f87d0ad..5bce0e28377 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/table.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/table.py @@ -135,7 +135,7 @@ def create(cls, *children, **props) -> Component: Returns: The cell. """ - style_props(cls._display_name(), props, _WIDTH_PROPS) + style_props("rx.ui.table cell", props, _WIDTH_PROPS) return super().create(*children, **props) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py index 1808bd16ce0..f5ccca955ca 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py @@ -181,7 +181,14 @@ def _classic(light: tuple[Layer, ...], dark: tuple[Layer, ...]) -> tuple[str, st "backdrop_filter": tokens.panel.backdrop_filter, } -_SIZES = {"1": (3, 4), "2": (4, 4), "3": (5, 5), "4": (6, 5), "5": (8, 6)} +# The padding and the radius of each size. +_SIZES: dict[str, tuple[str, str]] = { + "1": (tokens.space[3], tokens.radius[4]), + "2": (tokens.space[4], tokens.radius[4]), + "3": (tokens.space[5], tokens.radius[5]), + "4": (tokens.space[6], tokens.radius[5]), + "5": (tokens.space[8], tokens.radius[6]), +} _INSET_PADDING = f"calc(var({_PADDING}) - var({_BORDER}))" _GHOST_MARGIN = f"calc(0px - var({_PADDING}))" @@ -269,10 +276,10 @@ def _classic(light: tuple[Layer, ...], dark: tuple[Layer, ...]) -> tuple[str, st "variants": { "size": { size: unchecked({ - _PADDING: tokens.space[space], - _RADIUS: tokens.radius[radius], + _PADDING: padding, + _RADIUS: radius, }) - for size, (space, radius) in _SIZES.items() + for size, (padding, radius) in _SIZES.items() }, "variant": { "surface": unchecked({ diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py index 82b2f5e724b..accd49976ac 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/scroll_area.py @@ -51,23 +51,38 @@ def _overflow(scrollbars: str, always: bool) -> dict[str, Any]: # The area scrolls natively: the scrollbars are the ones of the browser, thin # and in the grays Radix Themes draws its own with. -SCROLL_AREA: ComponentStyles = { - "base": unchecked({ +# The box of an area, without the way it scrolls. +SCROLL_BOX: Any = unchecked({ + "box_sizing": "border-box", + "display": "flex", + "flex_direction": "column", + "position": "relative", + "width": "100%", + "height": "100%", + "scrollbar_width": "thin", + "scrollbar_color": f"{gray.a[8]} {gray.a[3]}", + ":focus-visible": { + "outline_width": "2px", + "outline_style": "solid", + "outline_color": tokens.focus[8], + "outline_offset": "-2px", + }, +}) + +# What is inside is laid out as in any block, as wide as it needs and at +# least as wide as the area. +SCROLL_CONTENT: ComponentStyles = { + "base": { "box_sizing": "border-box", - "display": "flex", - "flex_direction": "column", - "position": "relative", - "width": "100%", - "height": "100%", - "scrollbar_width": "thin", - "scrollbar_color": f"{gray.a[8]} {gray.a[3]}", - ":focus-visible": { - "outline_width": "2px", - "outline_style": "solid", - "outline_color": tokens.focus[8], - "outline_offset": "-2px", - }, - }), + "display": "block", + "width": "fit-content", + "min_width": "100%", + "flex_grow": 1, + } +} + +SCROLL_AREA: ComponentStyles = { + "base": SCROLL_BOX, "variants": { "scrollbars": { scrollbars: unchecked(_overflow(scrollbars, always=False)) @@ -76,17 +91,5 @@ def _overflow(scrollbars: str, always: bool) -> dict[str, Any]: }, "defaults": {"scrollbars": "both"}, "compound": _ALWAYS, - "parts": { - # What is inside is laid out as in any block, as wide as it needs - # and at least as wide as the area. - "content": { - "base": { - "box_sizing": "border-box", - "display": "block", - "width": "fit-content", - "min_width": "100%", - "flex_grow": 1, - } - }, - }, + "parts": {"content": SCROLL_CONTENT}, } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py index ab991a2624c..f7ae02f7f7d 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py @@ -6,7 +6,7 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, unchecked -from reflex_components_ui.styles.scroll_area import SCROLL_AREA +from reflex_components_ui.styles.scroll_area import SCROLL_BOX, SCROLL_CONTENT gray = tokens.gray @@ -51,8 +51,6 @@ ), } -_scroll_parts: Any = SCROLL_AREA["parts"] - TABLE_ROOT: ComponentStyles = { "variants": { "size": { @@ -86,13 +84,13 @@ # box of a scroll area, which scrolls natively. "scroll": { "base": { - **SCROLL_AREA["base"], + **SCROLL_BOX, "overflow_x": "auto", "overflow_y": "auto", "overscroll_behavior_x": "contain", }, }, - "content": _scroll_parts["content"], + "content": SCROLL_CONTENT, "table": { "base": unchecked({ _ROW_BACKGROUND: "transparent", diff --git a/pyi_hashes.json b/pyi_hashes.json index d65d9244e92..f104a46c2dd 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,14 +118,23 @@ "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": "c08242790fe83b60bc78516b695583b6", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "4bb4827db7a53b2225e43ed90fa6f7b3", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "b8536b02469bd96e86989749728e34b7", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", + "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "296a02d4f7a276a0548ec473a6c761a9", + "packages/reflex-components-ui/src/reflex_components_ui/components/badge.pyi": "f54c7d6d2a403389eb7424f7024bb847", "packages/reflex-components-ui/src/reflex_components_ui/components/button.pyi": "9e3f6fccbe30356fdbbe576471d6222e", + "packages/reflex-components-ui/src/reflex_components_ui/components/callout.pyi": "b878e3859317f6cf7e452eaa9683654f", + "packages/reflex-components-ui/src/reflex_components_ui/components/card.pyi": "f3a2ccfa6dc14e579c0d9f0974c32e3e", + "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", + "packages/reflex-components-ui/src/reflex_components_ui/components/progress.pyi": "ba32f562c590556d634f16062120fa34", + "packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.pyi": "2102625de1fc3800ee61b9e161c4ca83", "packages/reflex-components-ui/src/reflex_components_ui/components/separator.pyi": "bd32f08f7c0ff2cb6733f964ea843440", + "packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.pyi": "4bedd989efb5b095b943a04830bbd140", "packages/reflex-components-ui/src/reflex_components_ui/components/spinner.pyi": "9e62e8634e1425a75302d24fb458e8a8", + "packages/reflex-components-ui/src/reflex_components_ui/components/table.pyi": "3d2683d69d98f3cd14da65831e89e5fe", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", "packages/reflex-components-ui/src/reflex_components_ui/layout/center.pyi": "a38424cf14313b5358c9ad198a7880f9", "packages/reflex-components-ui/src/reflex_components_ui/layout/container.pyi": "ecfbd513a1a12bbfc11a6d30e91987c6", From 53f6642bf542d5d8088c6fcaffdcf267b14c4f5d Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:26:31 +0000 Subject: [PATCH 064/204] Type the scrolling box of a table Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../src/reflex_components_ui/styles/table.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py index f7ae02f7f7d..49e52ff5189 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/table.py @@ -83,12 +83,12 @@ # The table scrolls sideways when it is wider than its place: the # box of a scroll area, which scrolls natively. "scroll": { - "base": { + "base": unchecked({ **SCROLL_BOX, "overflow_x": "auto", "overflow_y": "auto", "overscroll_behavior_x": "contain", - }, + }), }, "content": SCROLL_CONTENT, "table": { From 4e3425fbeb9cd59479bd55863b0ebd27986c140a Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:30:37 +0000 Subject: [PATCH 065/204] Exercise the display and action components in the shared integration app Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- .../tests_playwright/test_ui_components.py | 224 ++++++++++++++++++ 1 file changed, 224 insertions(+) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index e4d37c1c458..ca019d8b853 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -147,6 +147,102 @@ ] +# The declarations of the buttons of the actions page that read state or +# send an event: the one whose loading is bound to state has a style for +# each value, and the other is a plain solid button. +ACTIONS_MEMO_DECLARATIONS = [ + ( + 'const sx_8d448f3b8d = stylex.create({ s: {"marginTop": "0", "marginRight' + '": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0", "padd' + 'ingRight": "var(--space-3)", "paddingBottom": "0", "paddingLeft": "var(-' + '-space-3)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBotto' + 'mWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderR' + 'ightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "non' + 'e", "backgroundColor": {"default": "var(--accent-9)", "@media (hover: ho' + 'ver)": {":hover:not(:active)": "var(--accent-10)"}, ":active:not([data-s' + 'tate=\'open\'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)"}' + ', "backgroundImage": "none", "appearance": "none", "boxSizing": "border-' + 'box", "fontSize": "var(--font-size-2)", "lineHeight": "var(--line-height' + '-2)", "letterSpacing": "var(--letter-spacing-2)", "fontWeight": "var(--f' + 'ont-weight-medium)", "textTransform": "inherit", "textIndent": "initial"' + ', "textShadow": "inherit", "wordSpacing": "inherit", "cursor": {"default' + '": "inherit", ":where(button)": "var(--cursor-button)", ":any-link": "va' + 'r(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)"}, "outlin' + 'eStyle": {"default": "none", "@media (pointer: coarse)": {":active:not([' + 'data-state=\'open\'], [data-disabled], :focus-visible)": "solid"}, ":focus' + '-visible:not([data-disabled])": "solid"}, "WebkitTapHighlightColor": "tr' + 'ansparent", "display": "inline-flex", "alignItems": "center", "justifyCo' + 'ntent": "center", "flexShrink": 0, "userSelect": "none", "verticalAlign"' + ': "top", "fontFamily": "var(--default-font-family)", "fontStyle": "norma' + 'l", "textAlign": "center", "--spinner-opacity": {"[data-disabled]": "1"}' + ', "--base-button-classic-active-padding-top": "2px", "--base-button-heig' + 'ht": "var(--space-6)", "borderRadius": "max(var(--radius-2), var(--radiu' + 's-full))", "rowGap": "var(--space-2)", "columnGap": "var(--space-2)", "c' + 'olor": {"default": "var(--accent-contrast)", "[data-disabled]": "var(--g' + 'ray-a8)"}, "filter": {":active:not([data-state=\'open\'])": "var(--rx-if-l' + "ight, brightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08)" + ')", "[data-disabled]": "none"}, "outlineWidth": {"@media (pointer: coars' + "e)\": {\":active:not([data-state='open'], [data-disabled], :focus-visible)" + '": "0.5em"}, ":focus-visible:not([data-disabled])": "2px"}, "outlineColo' + 'r": {"@media (pointer: coarse)": {":active:not([data-state=\'open\'], [dat' + 'a-disabled], :focus-visible)": "var(--accent-a4)"}, ":focus-visible:not(' + '[data-disabled])": "var(--focus-8)"}, "outlineOffset": {"@media (pointer' + ": coarse)\": {\":active:not([data-state='open'], [data-disabled], :focus-v" + 'isible)": "0"}, ":focus-visible:not([data-disabled])": "2px"}, "--rx-acc' + 'ent-text": "var(--accent-12)", "--rx-accent-link": "var(--accent-12)", "' + '--rx-accent-link-line": "underline", "--rx-accent-link-line-color": "col' + 'or-mix(in oklab, var(--accent-a6), var(--gray-a6))", "height": "var(--ba' + 'se-button-height)", "--rx-icon-opacity": "0.9"}, a0_0: {"position": "rel' + 'ative"} });' + ), + "const sx_8d448f3b8d_c = stylex.props(sx_8d448f3b8d.s).className;", + ( + 'const sx_8d448f3b8d_0 = { __proto__: null, "true": stylex.props(sx_8d448' + "f3b8d.a0_0).className };" + ), + ( + 'const sx_6fb0976665 = stylex.create({ s: {"marginTop": "0", "marginRight' + '": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0", "padd' + 'ingRight": "var(--space-3)", "paddingBottom": "0", "paddingLeft": "var(-' + '-space-3)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBotto' + 'mWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderR' + 'ightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "non' + 'e", "backgroundColor": {"default": "var(--accent-9)", "@media (hover: ho' + 'ver)": {":hover:not(:active)": "var(--accent-10)"}, ":active:not([data-s' + 'tate=\'open\'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)"}' + ', "backgroundImage": "none", "appearance": "none", "boxSizing": "border-' + 'box", "fontSize": "var(--font-size-2)", "lineHeight": "var(--line-height' + '-2)", "letterSpacing": "var(--letter-spacing-2)", "fontWeight": "var(--f' + 'ont-weight-medium)", "textTransform": "inherit", "textIndent": "initial"' + ', "textShadow": "inherit", "wordSpacing": "inherit", "cursor": {"default' + '": "inherit", ":where(button)": "var(--cursor-button)", ":any-link": "va' + 'r(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)"}, "outlin' + 'eStyle": {"default": "none", "@media (pointer: coarse)": {":active:not([' + 'data-state=\'open\'], [data-disabled], :focus-visible)": "solid"}, ":focus' + '-visible:not([data-disabled])": "solid"}, "WebkitTapHighlightColor": "tr' + 'ansparent", "display": "inline-flex", "alignItems": "center", "justifyCo' + 'ntent": "center", "flexShrink": 0, "userSelect": "none", "verticalAlign"' + ': "top", "fontFamily": "var(--default-font-family)", "fontStyle": "norma' + 'l", "textAlign": "center", "--spinner-opacity": {"[data-disabled]": "1"}' + ', "--base-button-classic-active-padding-top": "2px", "--base-button-heig' + 'ht": "var(--space-6)", "borderRadius": "max(var(--radius-2), var(--radiu' + 's-full))", "rowGap": "var(--space-2)", "columnGap": "var(--space-2)", "c' + 'olor": {"default": "var(--accent-contrast)", "[data-disabled]": "var(--g' + 'ray-a8)"}, "filter": {":active:not([data-state=\'open\'])": "var(--rx-if-l' + "ight, brightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08)" + ')", "[data-disabled]": "none"}, "outlineWidth": {"@media (pointer: coars' + "e)\": {\":active:not([data-state='open'], [data-disabled], :focus-visible)" + '": "0.5em"}, ":focus-visible:not([data-disabled])": "2px"}, "outlineColo' + 'r": {"@media (pointer: coarse)": {":active:not([data-state=\'open\'], [dat' + 'a-disabled], :focus-visible)": "var(--accent-a4)"}, ":focus-visible:not(' + '[data-disabled])": "var(--focus-8)"}, "outlineOffset": {"@media (pointer' + ": coarse)\": {\":active:not([data-state='open'], [data-disabled], :focus-v" + 'isible)": "0"}, ":focus-visible:not([data-disabled])": "2px"}, "height":' + ' "var(--base-button-height)", "--rx-icon-opacity": "0.9"} });' + ), + "const sx_6fb0976665_c = stylex.props(sx_6fb0976665.s).className;", +] + # 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)"} @@ -411,6 +507,72 @@ def wave(): rx.ui.separator(id="separator"), ) + class ActionState(rx.State): + """What the display and action components are bound to.""" + + busy: rx.Field[bool] = rx.field(False) + + @rx.event + def start(self): + """Start loading.""" + self.busy = True + + @rx.event + def finish(self): + """Stop loading.""" + self.busy = False + + def actions(): + table = rx.ui.table + return rx.el.main( + # Loading bound to state, a color and a radius of its own. + rx.ui.button( + "Save", + id="save", + loading=ActionState.busy, + on_click=ActionState.start, + color_scheme="red", + radius="full", + ), + rx.ui.button("Done", id="done", on_click=ActionState.finish), + # The style a class adds when an app is compiled. + rx.ui.icon_button(rx.el.span("+"), id="add", variant="ghost", size="1"), + rx.ui.spinner(id="spinner"), + rx.ui.skeleton("1,204 euros", id="skeleton"), + # What differs between the appearances and is no color. + rx.ui.button("Light", variant="classic", id="classic-light"), + rx.ui.theme( + rx.ui.button("Dark", variant="classic", id="classic-dark"), + appearance="dark", + ), + rx.ui.card( + rx.ui.inset(rx.el.div("edge", id="edge"), side="top", id="inset"), + rx.ui.badge("Paid", color_scheme="green", id="badge"), + rx.ui.callout("Saved.", id="callout"), + rx.ui.progress(value=40, id="progress"), + id="card", + size="2", + ), + rx.ui.avatar(fallback="AB", id="initials"), + rx.el.div(rx.ui.avatar(src="/missing.png", fallback="CD"), id="broken"), + rx.ui.box( + rx.ui.scroll_area(rx.ui.box(height="400px"), id="area"), + height="100px", + ), + table.root( + table.header(table.row(table.column_header_cell("Name", id="th"))), + table.body(table.row(table.cell("Ada", id="td"))), + variant="surface", + id="table", + ), + rx.ui.data_list.root( + rx.ui.data_list.item( + rx.ui.data_list.label("Name", id="dt"), + rx.ui.data_list.value("Ada", id="dd"), + ), + ), + ) + # The style of the app for a component of the wave, as an app writes it. app = rx.App( stylesheets=["unlayered.css"], @@ -418,6 +580,7 @@ def wave(): ) app.add_page(index) app.add_page(wave, route="/wave") + app.add_page(actions, route="/actions") app.add_page(literal, route="/literal") app.add_page(styled, route="/styled") app.add_page(theme, route="/theme") @@ -657,6 +820,7 @@ def declarations(path: Path) -> list[str]: name = ui_app.app_name assert declarations(web / "app_components" / name / f"{name}.jsx") == [ *WAVE_MEMO_DECLARATIONS, + *ACTIONS_MEMO_DECLARATIONS, *STYLED_MEMO_DECLARATIONS, ] @@ -1302,3 +1466,63 @@ def test_layout_and_typography_components_are_styled_and_navigate( styled = _styled_url(ui_app).rstrip("/") page.wait_for_url(lambda url: url.rstrip("/") == styled) assert page.evaluate("window.loadedOnce") is True + + +# What the page of the display and action components computes to, by id. +ACTIONS = { + # The accent and the radius of one element: red 9, and a full radius. + "save": { + "background-color": "rgb(229, 72, 77)", + "border-top-left-radius": "9999px", + }, + # The padding of the class, over the one of its size, and the margins + # that take the padding of a ghost button back. + "add": {"padding-top": "6px", "margin-top": "-4px"}, + "card": {"padding-top": "16px", "position": "relative"}, + # An inset reaches the border of the rx.ui card around it, one pixel wide. + "inset": {"margin-top": "-15px", "margin-left": "-15px"}, + "badge": {"color": "rgba(0, 113, 63, 0.87)"}, + "initials": {"width": "40px", "height": "40px"}, + "area": {"overflow-y": "auto", "scrollbar-width": "thin"}, + # What a surface table hands down to its header and to its last row. + "th": {"background-color": "rgba(0, 0, 85, 0.024)", "font-weight": "700"}, + "td": {"box-shadow": "none"}, + "dt": {"color": "rgba(0, 7, 20, 0.624)"}, +} + + +def test_display_and_action_components_work_in_an_app(ui_app: AppHarness, page: Page): + """The second wave of components works in a real app, in dev and prod.""" + assert ui_app.frontend_url is not None + page.goto(ui_app.frontend_url.rstrip("/") + "/actions") + save = page.locator("#save") + expect(save).to_have_css("background-color", "rgb(229, 72, 77)") + assert _computed_styles(page, ACTIONS) == ACTIONS + + # A light and a dark classic button differ by more than their colors. + assert page.evaluate( + """() => ["classic-light", "classic-dark"].map((id) => + getComputedStyle(document.getElementById(id), "::after").borderTopWidth)""" + ) == ["2px", "1px"] + + # The keyframes of a style are compiled, and play. + assert page.evaluate( + """() => ["#spinner > span", "#skeleton"].map((selector) => { + const [animation] = document.querySelector(selector).getAnimations(); + return [animation.playState, animation.effect.getTiming().duration]; + })""" + ) == [["running", 800], ["running", 1000]] + + # The one script of the wave: a broken image gives way to its fallback. + expect(page.locator("#broken img")).to_have_css("display", "none") + expect(page.locator("#broken").get_by_text("CD")).to_be_visible() + + # Loading follows the state: the button is disabled under a spinner. + assert save.is_enabled() + save.click() + expect(save).to_be_disabled() + expect(save).to_have_attribute("data-disabled", "true") + expect(save.locator("span > span > span")).to_have_count(8) + page.locator("#done").click() + expect(save).to_be_enabled() + expect(save).to_have_text("Save") From 4593d4f36732ea85894ae764030c9dd0dc0f1559 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 27 Nov 2026 23:40:01 +0000 Subject: [PATCH 066/204] Record what the display and action wave adds and settles Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR --- packages/reflex-components-ui/README.md | 75 +++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index b1eef1b83fd..7cb652f32f9 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -42,6 +42,7 @@ js/ the javascript package, with its own tooling 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 + behaviors/ the little a component needs a script for colors/ generated: one module for each Radix color scale tokens/ generated: space, radius, typography, shadow, ... themes/ generated: accent/, gray/, radius, scaling, ... @@ -402,6 +403,79 @@ What a wave does for each component, in this order. `flex` (a layout), `text` 10. **The record**: the wave's row in the run-time table below, the gzipped CSS and JavaScript it adds, and a news fragment in `news/`. +What the display and action wave settled, for the waves after it: + +- **Zero is the first target, and the report says what kept a matrix from + it.** Run a matrix at `threshold=0, tolerance=0` first. What is left is a + bug unless the same props are equal in another frame: the browser dithers + a gradient and anti-aliases a rounded ring, a turned shape or a scaled + image by where they are on the page. Then keep the default threshold, say + in a comment how many cells were equal at zero and what the others hold, + and set `tolerance` no higher than what was measured. +- **A reference that settles late is no reference.** Radix Themes shows the + fallback of an avatar and the scrollbars of a scroll area some time after + the page is ready, so a screenshot has them or not. Leave such a cell out + with a comment that says so, and cover the state in the contract, which + waits for it. +- **An animation is compared by the contract.** A screenshot is taken with + animations off, and an animation that never ends is cancelled for it. A + step reads `element.getAnimations()` on both systems and asserts the + keyframes and the timing exactly, as the spinner and the skeleton do. +- **A native element where Radix draws its own.** `rx.ui.scroll_area` is + one element that scrolls natively: `overflow` by the `scrollbars` prop, + `scrollbar-width: thin` and `scrollbar-color` in the grays Radix uses. It + needs no script and scrolls with JavaScript off; what the browser decides + (the shape of a scrollbar, whether it takes room, when it shows) is in the + allowlist with its reason. `rx.ui.progress` is a `div` with the ARIA of a + progress bar rather than a ``: a plain element costs no script + either, and the pseudo-elements a native bar is drawn with differ by + engine, of which only Chromium could be looked at when it was written. +- **A script is the last resort, and is a function, not a component.** + `js/src/behaviors/.js` exports plain functions with JSDoc types and a + vitest file under `js/tests/behaviors/`. A component reaches one through a + `Var` that carries its import, such as the `ref` of the image of an + avatar: no hook, no state, nothing rendered again, and a page without the + component does not load it. Render both states on the server and let the + script say which one holds (`data-status`), so that the page is right + before it runs, and say in the contract what shows with JavaScript off. +- **What a class cannot say of the children of an element** is a rule of + `base.css`, on an attribute the wrapper renders: `[data-rx-callout] > *` + puts everything in a callout in its last column, `[data-rx-skeleton] > *` + hides what a skeleton stands in for. +- **A component rendered as its child** without an `as_child` prop, as a + skeleton around one element, sets `_as_child` itself, and + `_merges_slot = False` when the child has to keep its own styles: each + then declares its own, and the element has the class names of both. What + must win over the child is `!important`, as it is in Radix Themes. +- **A prop that is a CSS property** (`width`, `min_width`...) is moved into + the style with `props.style_props`, at the breakpoints of Radix Themes. +- **A private variant.** A table may read something that is no prop, such as + whether a skeleton is around text: name the variant with an underscore + (`"_inline"`) and set the attribute of that name before the component is + initialized. Mind the names the base class uses (`_radius`, `_accent`). +- **A shorthand that some values keep whole** (`padding: calc(...)`) and + others split does not mix across the values of one prop: StyleX resolves + styles in the order they are written, and a whole shorthand written after + its longhands cancels them. Write each side out, as the ghost button does. + +### What a wave adds to a page + +Gzipped (`gzip -9` of each file under `.web/build/client`), for an app whose +only plugin is `UIPlugin()`, against the same page without the components: + +| page | JavaScript | CSS | files | +| --- | --- | --- | --- | +| one `rx.ui.button` | +405 B | +1,031 B | none | +| a button with a `color_scheme` | +659 B | +2,081 B | one shared chunk of 188 B | +| a button with a `radius` | +621 B | +1,031 B | one shared chunk of 287 B | +| the 12 components of wave 2, one accent | +3,374 B | +5,295 B | Lucide's icon chunk (783 B), as `rx.icon` alone adds | + +The page without components is 146,124 B of JavaScript and 6,109 B of CSS, +4.6 kB of it the theme. The script of an avatar is 231 B of the page's own +chunk. Each further literal `color_scheme` on a page is about 1.05 kB of +CSS, the scale of that color, and some 20 B of JavaScript: a page with six +colors is 5.4 kB of CSS over the one with none, and still one chunk. + ## Themes and tokens The plugin takes the theme of the app. Every option has the values and, the @@ -736,6 +810,7 @@ appearance) about 0.3 s. Keep interactive states to a sweep or a small group. | --- | --- | --- | --- | | harness | box | 8 | 5 s + 1.1 s | | 1: layout and typography | 19, and `text.kbd` | 1011, 44 of them interactive | 27 s + 61 s | +| 2: display and actions | 12 | 1379, 181 of them interactive | 56 s + 178 s for both waves, 115 s of it this one | ## Rules the tooling enforces From 02cb37543c19d6fa0e8b0acdc5f2c74f4e2b3b1e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 00:13:44 +0000 Subject: [PATCH 067/204] Turn the wheel until the scroll area moves in its no-JavaScript contract step A wheel event sent before the browser can hit-test the page scrolls nothing, which failed the step once in a full parity run and never alone. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- .../parity/ui_parity/components/scroll_area.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py index a779cf4486d..87b43d009ec 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py @@ -5,6 +5,8 @@ from collections.abc import Mapping from typing import Any +from playwright.sync_api import TimeoutError as PlaywrightTimeoutError + import reflex as rx from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import DARK, Matrix @@ -132,13 +134,22 @@ def _server_render(run: Run) -> None: @CONTRACT.step("scrolls to its last line with JavaScript disabled", on=NO_JAVASCRIPT) def _without_javascript(run: Run) -> None: + run.page.locator("#last").wait_for(state="attached") run.page.locator("#area").hover() - run.page.mouse.wheel(0, 2000) - run.page.locator("#last").wait_for() - run.page.wait_for_function( + reached = ( "document.getElementById('last').getBoundingClientRect().bottom" " <= document.getElementById('area').getBoundingClientRect().bottom + 1" ) + # A wheel turned before the browser can hit-test the page scrolls nothing, + # so turn it until the area has moved: only the end of the scroll is asserted. + for _ in range(40): + run.page.mouse.wheel(0, 2000) + try: + run.page.wait_for_function(reached, timeout=250) + except PlaywrightTimeoutError: + continue + return + run.page.wait_for_function(reached, timeout=1) @CONTRACT.step("the wheel scrolls it both ways", on=HYDRATED) From 2a6ec7ea92e9b8fb8240e1ad0ce9c9fb808cf122 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 00:34:04 +0000 Subject: [PATCH 068/204] Add rx.ui.checkbox: a native input drawn as the Radix checkbox The first form control of the wave. One input element with its box and check drawn by pseudo-elements, the high-level form with a label, the matrix and the contract against rx.checkbox. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../news/+wave3-form-controls.feature.md | 1 + .../parity/allowlist.toml | 16 + .../parity/ui_parity/components/checkbox.py | 302 +++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/checkbox.py | 145 +++++ .../reflex_components_ui/styles/checkbox.py | 159 +++++ .../reflex_components_ui/styles/control.py | 60 ++ .../components/test_checkbox.py | 593 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 9 files changed, 1278 insertions(+) create mode 100644 packages/reflex-components-ui/news/+wave3-form-controls.feature.md create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/checkbox.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/control.py create mode 100644 tests/units/reflex_components_ui/components/test_checkbox.py diff --git a/packages/reflex-components-ui/news/+wave3-form-controls.feature.md b/packages/reflex-components-ui/news/+wave3-form-controls.feature.md new file mode 100644 index 00000000000..73d401bf5bc --- /dev/null +++ b/packages/reflex-components-ui/news/+wave3-form-controls.feature.md @@ -0,0 +1 @@ +Add the form controls to `rx.ui`, each a drop-in for the component of the same name in `rx`: `rx.ui.checkbox` so far. A control is the native element, drawn as Radix Themes draws its own, so it works before JavaScript loads and without it. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 342b517cfb9..15dcd132c97 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -72,3 +72,19 @@ component = "scroll_area" check = "pixels" cells = "*type-always*" reason = "rx.ui.scroll_area scrolls natively and has the scrollbars of the browser, thin and in the grays of the theme, where rx.scroll_area draws scrollbars of its own with JavaScript. Their shape and where they show follow the browser and the system: they may take room beside the content or lie over it, and `type` \"hover\" and \"scroll\" and `scroll_hide_delay` are left to them." + +[[look]] +component = "checkbox" +check = "a11y" +reason = "A checked rx.checkbox holds its check as an image without a name, which a screen reader may announce inside the checkbox. rx.ui.checkbox is one native input: its check is drawn by its styles and is nothing to the accessibility tree, which has the role, the name and the state of the checkbox alone." + +[[contract]] +component = "checkbox" +step = "is checked by a click with JavaScript disabled" +system = "rx" +reason = "rx.checkbox is a button that JavaScript turns into a checkbox: until it has run, a click does nothing. rx.ui.checkbox is a native input, which is checked by a click on it or on its label with or without JavaScript." + +[[contract]] +component = "checkbox" +step = "Enter on a checkbox does not submit its form" +reason = "rx.ui.checkbox is a native input, and the browser submits a form when Enter is pressed in one of its inputs, a checkbox included. rx.checkbox swallows the key. Space toggles both, and Enter toggles neither." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/checkbox.py b/packages/reflex-components-ui/parity/ui_parity/components/checkbox.py new file mode 100644 index 00000000000..9622780b956 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/checkbox.py @@ -0,0 +1,302 @@ +"""The checkbox: every variant, size and state, and what a native input gives it.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +# The checkbox itself, inside its label: a button of Radix, an input here. +TARGET = ("button", "input") + + +def _checkbox(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a checkbox with its label. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``text`` is the label. + + Returns: + The checkbox. + """ + props = dict(props) + return namespace.checkbox(props.pop("text", "Agree"), **props) + + +MATRIX = Matrix( + component="checkbox", + render=_checkbox, + base={"default_checked": True}, + cross={"variant": VARIANTS, "size": SIZES, "default_checked": [True, False]}, + sweep={ + "color_scheme": ACCENTS, + "high_contrast": [True], + "disabled": [True], + "text": {"none": ""}, + "spacing": ["1", "4"], + "appearance": [DARK], + "state": STATES, + }, + groups=[ + { + "variant": VARIANTS, + "default_checked": [True, False], + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "default_checked": [True, False], + "disabled": [True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "default_checked": [True, False], + "state": STATES, + }, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + ], + stage=(160, 64), + crop="stage", + target=TARGET, + # Not held to zero, for the check alone: Radix Themes draws it as an svg + # element and an input has no children, so here it is the same path as a + # mask, whose edge the browser rasterizes by a step of a channel + # otherwise. At a threshold of zero 96 of the 132 cells are equal, every + # unchecked one among them, and the others differ by at most 28 pixels of + # 10240 on that edge. At the default threshold one cell differs, by 3 + # pixels: the check of the smallest size lies on half a pixel. + tolerance=0.0005, +) + + +class CheckboxState(rx.State): + """What the checkboxes of the contract are bound to.""" + + bound: bool = False + seen: list[bool] = [] + submitted: dict[str, str] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, checked: bool): + """Follow the bound checkbox. + + Args: + checked: Whether it is checked. + """ + self.bound = checked + + @rx.event + def see(self, checked: bool): + """Keep what a change handed over. + + Args: + checked: Whether the checkbox is checked. + """ + self.seen.append(checked) + + @rx.event + def flip(self): + """Change the bound value from outside the checkbox.""" + self.bound = not self.bound + + @rx.event + def submit(self, data: dict[str, str]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +CONTRACT = Contract( + component="checkbox", + render=lambda namespace: namespace.box( + namespace.checkbox("Agree", id="agree", on_change=CheckboxState.see), + namespace.checkbox("Off", id="off", disabled=True), + namespace.checkbox( + "Bound", + id="bound", + checked=CheckboxState.bound, + on_change=CheckboxState.set_bound, + ), + rx.el.button("Flip", id="flip", on_click=CheckboxState.flip), + rx.el.form( + namespace.checkbox("News", id="news", name="news"), + namespace.checkbox("Plan", id="plan", name="plan", value="pro"), + namespace.checkbox("Was", id="was", name="was", default_checked=True), + namespace.checkbox("Terms", id="terms", name="terms", required=True), + rx.el.button("Send", id="send", type="submit"), + on_submit=CheckboxState.submit, + id="form", + ), + rx.el.span(CheckboxState.seen.to_string(), id="seen"), + rx.el.span(CheckboxState.bound.to_string(), id="bound-value"), + rx.el.span(CheckboxState.submitted.to_string(), id="submitted"), + rx.el.span(CheckboxState.submissions.to_string(), id="submissions"), + ), +) + + +def _focused(run: Run) -> str: + """Read which element has the focus. + + Args: + run: The run, on a page. + + Returns: + The id of the element. + """ + return run.page.evaluate("document.activeElement.id") + + +@CONTRACT.step("its label is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert "id" in run.server.element("agree").attributes + assert "disabled" in run.server.element("off").attributes + assert run.server.element("form").text == "NewsPlanWasTermsSend" + + +@CONTRACT.step("is checked by a click with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + assert _focused(run) == "agree" + page.get_by_text("Agree").click() + assert page.locator("#agree").is_checked() + assert page.locator("#was").is_checked() + assert page.locator("#off").is_disabled() + + +@CONTRACT.step("has the role, the name and the state of a checkbox") +def _role(run: Run) -> None: + page = run.page + agree = page.get_by_role("checkbox", name="Agree") + assert agree.get_attribute("id") == "agree" + assert not agree.is_checked() + assert page.get_by_role("checkbox", name="Was", checked=True).count() == 1 + assert page.get_by_role("checkbox", name="Off", disabled=True).count() == 1 + assert page.get_by_role("checkbox").count() == 7 + + +@CONTRACT.step("Tab skips a disabled checkbox") +def _tab(run: Run) -> None: + focused = [] + for _ in range(3): + run.page.keyboard.press("Tab") + focused.append(_focused(run)) + assert focused == ["agree", "bound", "flip"] + run.page.keyboard.press("Shift+Tab") + assert _focused(run) == "bound" + assert run.page.locator("#bound").evaluate( + "element => element.matches(':focus-visible')" + ) + + +@CONTRACT.step("Space and a click on its label toggle it, and say so") +def _toggle(run: Run) -> None: + page = run.page + agree = page.locator("#agree") + agree.focus() + page.keyboard.press("Space") + assert agree.is_checked() + page.keyboard.press("Space") + assert not agree.is_checked() + page.get_by_text("Agree").click() + assert agree.is_checked() + agree.click() + assert not agree.is_checked() + page.wait_for_function( + "document.getElementById('seen').textContent === '[true,false,true,false]'" + ) + + +@CONTRACT.step("Enter does not toggle it") +def _enter(run: Run) -> None: + agree = run.page.locator("#agree") + agree.focus() + run.page.keyboard.press("Enter") + assert not agree.is_checked() + + +@CONTRACT.step("Enter on a checkbox does not submit its form") +def _enter_in_form(run: Run) -> None: + page = run.page + page.locator("#terms").check() + page.locator("#news").focus() + page.keyboard.press("Enter") + page.locator("#flip").click() + page.wait_for_function( + "document.getElementById('bound-value').textContent === 'true'" + ) + assert page.locator("#submissions").text_content() == "0" + + +@CONTRACT.step("a disabled checkbox is not toggled") +def _disabled(run: Run) -> None: + off = run.page.locator("#off") + off.click(force=True) + run.page.get_by_text("Off").click(force=True) + assert not off.is_checked() + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + bound = page.locator("#bound") + bound.click() + page.wait_for_function( + "document.getElementById('bound-value').textContent === 'true'" + ) + assert bound.is_checked() + page.locator("#flip").click() + page.wait_for_function( + "document.getElementById('bound-value').textContent === 'false'" + ) + page.wait_for_function( + "!document.getElementById('bound').matches(':checked, [aria-checked=true]')" + ) + assert not bound.is_checked() + + +@CONTRACT.step("submits its value with a form when it is checked") +def _submit(run: Run) -> None: + page = run.page + page.locator("#plan").check() + page.locator("#terms").check() + page.locator("#send").click() + page.wait_for_function("document.getElementById('submissions').textContent === '1'") + assert page.locator("#submitted").text_content() == ( + '{"plan":true,"was":true,"terms":true,"news":false}' + ) + + +@CONTRACT.step("a required checkbox holds its form back until it is checked") +def _required(run: Run) -> None: + page = run.page + page.locator("#send").click() + # An event that does reach the server comes back after the blocked one. + page.locator("#flip").click() + page.wait_for_function( + "document.getElementById('bound-value').textContent === 'true'" + ) + assert page.locator("#submissions").text_content() == "0" + page.locator("#terms").check() + page.locator("#send").click() + page.wait_for_function("document.getElementById('submissions').textContent === '1'") 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 d3ba0571080..56fb42ca3d8 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -13,6 +13,7 @@ "components.button": ["button"], "components.callout": ["callout"], "components.card": ["card"], + "components.checkbox": ["checkbox"], "components.data_list": ["data_list"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py new file mode 100644 index 00000000000..a8dfce42685 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py @@ -0,0 +1,145 @@ +"""A checkbox: a native input, drawn as Radix Themes draws its own.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, checked_input_event +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.layout.flex import Flex +from reflex_components_ui.props import LiteralSpacing +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.checkbox import CHECKBOX +from reflex_components_ui.themes import LiteralAccentColor +from reflex_components_ui.typography.text import Text + +LiteralCheckboxSize = Literal["1", "2", "3"] +LiteralCheckboxVariant = Literal["classic", "surface", "soft"] + + +class CheckedInput(UIComponent): + """A native input that is checked or not: a checkbox, a switch.""" + + tag = "input" + + # The type of the input. + _type: ClassVar[str] = "checkbox" + + def _set_slot(self) -> None: + """Render the input itself: it has no child to be rendered as.""" + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the input with its type. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. An input whose ``checked`` nothing changes says so, as + React asks of an input it controls. + """ + tag = super()._render(props).add_props(type=self._type) + if ( + getattr(self, "checked", None) is not None + and "on_change" not in self.event_triggers + ): + return tag.add_props(read_only=True) + return tag + + +class Checkbox(CheckedInput): + """Selects a single value, typically for submission in a form.""" + + styles: ClassVar[ComponentStyles] = CHECKBOX + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + size: Var[Responsive[LiteralCheckboxSize]] = field(doc='Checkbox size "1" - "3"') + + variant: Var[LiteralCheckboxVariant] = field( + doc='Variant of checkbox: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for checkbox" + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the checkbox with higher contrast color against background" + ) + + default_checked: Var[bool] = field(doc="Whether the checkbox is checked by default") + + checked: Var[bool] = field(doc="Whether the checkbox is checked") + + disabled: Var[bool] = field(doc="Whether the checkbox is disabled") + + required: Var[bool] = field(doc="Whether the checkbox is required") + + name: Var[str] = field( + doc="The name of the checkbox control when submitting the form." + ) + + value: Var[str] = field( + doc="The value of the checkbox control when submitting the form." + ) + + on_change: EventHandler[checked_input_event] = field( + doc="Fired when the checkbox is checked or unchecked." + ) + + +class HighLevelCheckbox(Checkbox): + """A checkbox component with a label.""" + + text: Var[str] = field(doc="The text label for the checkbox.") + + spacing: Var[LiteralSpacing] = field( + doc="The gap between the checkbox and the label." + ) + + size: Var[LiteralCheckboxSize] = field(doc='The size of the checkbox "1" - "3".') + + @classmethod + def create(cls, text: Var[str] = Var.create(""), **props) -> Component: + """Create a checkbox with a label. + + Args: + text: The text of the label. + **props: Additional properties to apply to the checkbox item. + + Returns: + The checkbox component with a label. + """ + spacing = props.pop("spacing", "2") + size = props.pop("size", "2") + flex_props = {} + if "gap" in props: + flex_props["gap"] = props.pop("gap", None) + + return Text.create( + Flex.create( + Checkbox.create(size=size, **props), + text, + spacing=spacing, + **flex_props, + ), + as_="label", + size=size, + ) + + +class CheckboxNamespace(ComponentNamespace): + """Checkbox components namespace.""" + + __call__ = staticmethod(HighLevelCheckbox.create) + + +checkbox = CheckboxNamespace() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py new file mode 100644 index 00000000000..6e5720f4865 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py @@ -0,0 +1,159 @@ +"""The look of a checkbox: a native input drawn as a box and a check.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.control import DISABLED, FOCUS, FOCUS_RING, RESET, mask + +accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black + +_SIZE = "--checkbox-size" +_INDICATOR = "--checkbox-indicator-size" +_RADIUS = "--checkbox-border-radius" + +# Checked, or neither checked nor unchecked: the box is filled either way. +_ON = ":is(:checked, :indeterminate)" +_ON_ENABLED = f"{_ON}:not({DISABLED})" + +# The icons Radix Themes draws in the box. +_CHECK = mask( + "M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 " + "8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 " + "3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 " + "5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 " + "4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 " + "0.396414 8.53547 0.62293Z" +) +_DIVIDER = mask( + "M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 " + "4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 " + "4.91421 0.75 4.5Z" +) + + +def _look(variant: str, high_contrast: bool) -> dict[str, Any]: + """Make the box and the check of one variant. + + Args: + variant: The variant. + high_contrast: Whether the checkbox is high contrast. + + Returns: + The styles of the two pseudo-elements, for every state of the input. + """ + fill = accent[12] if high_contrast else accent.indicator + check = accent[1] if high_contrast else accent.contrast + if variant == "surface": + box: dict[str, Any] = { + "background_color": { + "default": tokens.color.surface, + _ON_ENABLED: fill, + DISABLED: gray.a[3], + }, + "box_shadow": { + "default": f"inset 0 0 0 1px {gray.a[7]}", + _ON_ENABLED: "none", + DISABLED: f"inset 0 0 0 1px {gray.a[6]}", + }, + } + elif variant == "classic": + box = { + "background_color": { + "default": tokens.color.surface, + _ON_ENABLED: fill, + DISABLED: gray.a[3], + }, + "background_image": { + "default": "none", + _ON_ENABLED: ( + f"linear-gradient(to bottom, {white.a[3]}, transparent, " + f"{black.a[1]})" + ), + }, + "box_shadow": { + "default": f"inset 0 0 0 1px {gray.a[3]}, {tokens.shadow[1]}", + _ON_ENABLED: ( + f"inset 0 0.5px 0.5px {white.a[4]}, " + f"inset 0 -0.5px 0.5px {black.a[4]}" + ), + DISABLED: tokens.shadow[1], + }, + } + else: + box = {"background_color": {"default": accent.a[5], DISABLED: gray.a[3]}} + check = accent[12] if high_contrast else accent.a[11] + return { + "_before": box, + "_after": {"background_color": {"default": check, DISABLED: gray.a[8]}}, + } + + +_VARIANTS = ("classic", "surface", "soft") + +CHECKBOX: ComponentStyles = { + "base": unchecked({ + **RESET, + "position": "relative", + "display": "inline-flex", + "align_items": "center", + "justify_content": "center", + "vertical_align": "top", + "flex_shrink": 0, + "cursor": {"default": tokens.cursor.checkbox, DISABLED: tokens.cursor.disabled}, + # In a line of text it is as high as the line. + "height": f"var(--line-height, var({_SIZE}))", + "_before": { + "content": "''", + "display": "block", + "height": f"var({_SIZE})", + "width": f"var({_SIZE})", + "border_radius": f"var({_RADIUS})", + FOCUS: FOCUS_RING, + }, + # The check, or the line of a checkbox that is neither. + "_after": { + _ON: {"content": "''"}, + "position": "absolute", + "width": f"var({_INDICATOR})", + "height": f"var({_INDICATOR})", + "transform": "translate(-50%, -50%)", + "top": "50%", + "left": "50%", + "pointer_events": "none", + "mask_image": {"default": _CHECK, ":indeterminate": _DIVIDER}, + "mask_size": "100% 100%", + "mask_repeat": "no-repeat", + }, + }), + "variants": { + "size": { + "1": unchecked({ + _SIZE: f"calc({tokens.space[4]} * 0.875)", + _INDICATOR: f"calc(9px * {tokens.scaling})", + _RADIUS: f"calc({tokens.radius[1]} * 0.875)", + }), + "2": unchecked({ + _SIZE: tokens.space[4], + _INDICATOR: f"calc(10px * {tokens.scaling})", + _RADIUS: tokens.radius[1], + }), + "3": unchecked({ + _SIZE: f"calc({tokens.space[4]} * 1.25)", + _INDICATOR: f"calc(12px * {tokens.scaling})", + _RADIUS: f"calc({tokens.radius[1]} * 1.25)", + }), + }, + "variant": {variant: unchecked(_look(variant, False)) for variant in _VARIANTS}, + }, + "defaults": {"size": "2", "variant": "surface"}, + "compound": [ + { + "props": {"variant": variant, "high_contrast": "true"}, + "style": unchecked(_look(variant, True)), + } + for variant in _VARIANTS + ], +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/control.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/control.py new file mode 100644 index 00000000000..416a118b2f1 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/control.py @@ -0,0 +1,60 @@ +"""What the tables of the native form controls share.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens + +DISABLED = ":disabled" +FOCUS = ":focus-visible" + +# What a checkbox, a radio button, a switch or a range is before its table +# draws it: nothing of the look of the platform, as Radix Themes unsets it all. +RESET: dict[str, Any] = { + "appearance": "none", + "margin": "0", + "padding": "0", + "border_width": "0", + "border_style": "none", + "background_color": "transparent", + "background_image": "none", + "box_sizing": "border-box", + "color": "inherit", + "font_size": "inherit", + "line_height": "inherit", + "letter_spacing": "inherit", + "font_weight": "normal", + "font_style": "normal", + "text_indent": "initial", + # The whole outline, as the browser has one of its own for the focus. + "outline_style": "none", + "outline_width": "medium", + "outline_color": "currentcolor", + "outline_offset": "0", + "WebkitTapHighlightColor": "transparent", +} + +# The ring of the keyboard's focus around a control. +FOCUS_RING: dict[str, Any] = { + "outline_width": "2px", + "outline_style": "solid", + "outline_color": tokens.focus[8], + "outline_offset": "2px", +} + + +def mask(path: str) -> str: + """Make the mask that draws an icon of Radix Themes in the current color. + + Args: + path: The path of the icon, on its grid of nine units a side. + + Returns: + The value of ``mask-image``: the icon as an image. + """ + return ( + "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' " + "viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' " + f"d='{path}'/%3E%3C/svg%3E\")" + ) diff --git a/tests/units/reflex_components_ui/components/test_checkbox.py b/tests/units/reflex_components_ui/components/test_checkbox.py new file mode 100644 index 00000000000..76995c05cc9 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_checkbox.py @@ -0,0 +1,593 @@ +"""Tests for reflex_components_ui.components.checkbox.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.components.checkbox import Checkbox +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +class CheckboxState(rx.State): + """What a checkbox is bound to.""" + + agreed: bool = False + + @rx.event + def agree(self, agreed: bool): + """Follow the checkbox. + + Args: + agreed: Whether it is checked. + """ + self.agreed = agreed + + +def test_checkbox_with_its_label( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A checkbox is a native input in a label, with its text beside it.""" + component = rx.ui.checkbox("Agree", id="agree", name="agree") + assert component.render() == { + "name": '"label"', + "props": ["className:sx_d1083f6dbf_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_1362d43b5f_c"], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_eda6ae65a6_c", + 'id:"agree"', + 'name:"agree"', + "ref:ref_agree", + 'type:"checkbox"', + ], + "children": [], + }, + {"contents": '"Agree"'}, + ], + } + ], + } + assert declared_styles(component) == [ + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-2)", + "--line-height": "var(--line-height-2)", + "--letter-spacing": "var(--letter-spacing-2)", + "WebkitTapHighlightColor": {"@media (pointer: coarse)": "transparent"}, + "outlineWidth": {"@media (pointer: coarse)": {":active": "0.75em"}}, + "outlineStyle": {"@media (pointer: coarse)": {":active": "solid"}}, + "outlineColor": {"@media (pointer: coarse)": {":active": "var(--gray-a4)"}}, + "outlineOffset": {"@media (pointer: coarse)": {":active": "-0.6em"}}, + }, + { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "flex-start", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": 'url("data:image/svg+xml,%3Csvg ' + "xmlns='http://www.w3.org/2000/svg' " + "viewBox='0 0 9 9'%3E%3Cpath " + "fill-rule='evenodd' " + "clip-rule='evenodd' d='M8.53547 " + "0.62293C8.88226 0.849446 8.97976 " + "1.3142 8.75325 1.66099L4.5083 " + "8.1599C4.38833 8.34356 4.19397 8.4655 " + "3.9764 8.49358C3.75883 8.52167 3.53987 " + "8.45309 3.3772 8.30591L0.616113 " + "5.80777C0.308959 5.52987 0.285246 " + "5.05559 0.563148 4.74844C0.84105 " + "4.44128 1.31533 4.41757 1.62249 " + "4.69547L3.73256 6.60459L7.49741 " + "0.840706C7.72393 0.493916 8.18868 " + "0.396414 8.53547 " + "0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": 'url("data:image/svg+xml,%3Csvg ' + "xmlns='http://www.w3.org/2000/svg' " + "viewBox='0 0 9 9'%3E%3Cpath " + "fill-rule='evenodd' " + "clip-rule='evenodd' d='M0.75 " + "4.5C0.75 4.08579 1.08579 3.75 " + "1.5 3.75H7.5C7.91421 3.75 8.25 " + "4.08579 8.25 4.5C8.25 4.91421 " + "7.91421 5.25 7.5 " + "5.25H1.5C1.08579 5.25 0.75 " + "4.91421 0.75 " + "4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "var(--space-4)", + "--checkbox-indicator-size": "calc(10px * var(--scaling))", + "--checkbox-border-radius": "var(--radius-1)", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a7)", + ":is(:checked, :indeterminate):not(:disabled)": "none", + ":disabled": "inset 0 0 0 1px var(--gray-a6)", + } + }, + }, + ] + + +def test_checkbox_alone( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """Every prop reaches the input or selects its styles, and a checkbox that nothing changes is read only.""" + component = Checkbox.create( + checked=True, + size=rx.breakpoints(initial="1", md="3"), + variant="soft", + high_contrast=True, + color_scheme="ruby", + disabled=True, + required=True, + value="yes", + as_child=True, + ) + assert component.render() == { + "name": '"input"', + "props": [ + "checked:true", + 'className:sx_cf89508fbc_c + " " + reflexUIClasses_e201574881', + "disabled:true", + "readOnly:true", + "required:true", + 'type:"checkbox"', + 'value:"yes"', + ], + "children": [], + } + assert declared_styles(component) == [ + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--accent-a5)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": 'url("data:image/svg+xml,%3Csvg ' + "xmlns='http://www.w3.org/2000/svg' " + "viewBox='0 0 9 9'%3E%3Cpath " + "fill-rule='evenodd' " + "clip-rule='evenodd' d='M8.53547 " + "0.62293C8.88226 0.849446 8.97976 " + "1.3142 8.75325 1.66099L4.5083 " + "8.1599C4.38833 8.34356 4.19397 8.4655 " + "3.9764 8.49358C3.75883 8.52167 3.53987 " + "8.45309 3.3772 8.30591L0.616113 " + "5.80777C0.308959 5.52987 0.285246 " + "5.05559 0.563148 4.74844C0.84105 " + "4.44128 1.31533 4.41757 1.62249 " + "4.69547L3.73256 6.60459L7.49741 " + "0.840706C7.72393 0.493916 8.18868 " + "0.396414 8.53547 " + "0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": 'url("data:image/svg+xml,%3Csvg ' + "xmlns='http://www.w3.org/2000/svg' " + "viewBox='0 0 9 9'%3E%3Cpath " + "fill-rule='evenodd' " + "clip-rule='evenodd' d='M0.75 " + "4.5C0.75 4.08579 1.08579 3.75 " + "1.5 3.75H7.5C7.91421 3.75 8.25 " + "4.08579 8.25 4.5C8.25 4.91421 " + "7.91421 5.25 7.5 " + "5.25H1.5C1.08579 5.25 0.75 " + "4.91421 0.75 " + "4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": { + "default": "calc(var(--space-4) * 0.875)", + "@media (min-width: 1024px)": "calc(var(--space-4) * 1.25)", + }, + "--checkbox-indicator-size": { + "default": "calc(9px * var(--scaling))", + "@media (min-width: 1024px)": "calc(12px * var(--scaling))", + }, + "--checkbox-border-radius": { + "default": "calc(var(--radius-1) * 0.875)", + "@media (min-width: 1024px)": "calc(var(--radius-1) * 1.25)", + }, + } + ] + + +def test_checkbox_classic( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The classic variant has a gradient and the shadows of a raised box.""" + component = Checkbox.create(variant="classic", default_checked=True) + assert declared_styles(component) == [ + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": { + "default": "none", + "::before": { + "default": "none", + ":is(:checked, :indeterminate):not(:disabled)": "linear-gradient(to " + "bottom, " + "var(--white-a3), " + "transparent, " + "var(--black-a1))", + }, + }, + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": 'url("data:image/svg+xml,%3Csvg ' + "xmlns='http://www.w3.org/2000/svg' " + "viewBox='0 0 9 9'%3E%3Cpath " + "fill-rule='evenodd' " + "clip-rule='evenodd' d='M8.53547 " + "0.62293C8.88226 0.849446 8.97976 " + "1.3142 8.75325 1.66099L4.5083 " + "8.1599C4.38833 8.34356 4.19397 8.4655 " + "3.9764 8.49358C3.75883 8.52167 3.53987 " + "8.45309 3.3772 8.30591L0.616113 " + "5.80777C0.308959 5.52987 0.285246 " + "5.05559 0.563148 4.74844C0.84105 " + "4.44128 1.31533 4.41757 1.62249 " + "4.69547L3.73256 6.60459L7.49741 " + "0.840706C7.72393 0.493916 8.18868 " + "0.396414 8.53547 " + "0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": 'url("data:image/svg+xml,%3Csvg ' + "xmlns='http://www.w3.org/2000/svg' " + "viewBox='0 0 9 9'%3E%3Cpath " + "fill-rule='evenodd' " + "clip-rule='evenodd' d='M0.75 " + "4.5C0.75 4.08579 1.08579 3.75 " + "1.5 3.75H7.5C7.91421 3.75 8.25 " + "4.08579 8.25 4.5C8.25 4.91421 " + "7.91421 5.25 7.5 " + "5.25H1.5C1.08579 5.25 0.75 " + "4.91421 0.75 " + "4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "var(--space-4)", + "--checkbox-indicator-size": "calc(10px * var(--scaling))", + "--checkbox-border-radius": "var(--radius-1)", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a3), var(--shadow-1)", + ":is(:checked, :indeterminate):not(:disabled)": "inset " + "0 " + "0.5px " + "0.5px " + "var(--white-a4), " + "inset " + "0 " + "-0.5px " + "0.5px " + "var(--black-a4)", + ":disabled": "var(--shadow-1)", + } + }, + } + ] + + +def test_checkbox_spacing_and_gap( + ui_plugin: UIPlugin, +): + """The spacing and the gap are the ones of the row of the label.""" + component = rx.ui.checkbox("Agree", spacing="4", gap="1px", size="3") + assert component.render() == { + "name": '"label"', + "props": ["className:sx_3c18f01562_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_6778334529_c"], + "children": [ + { + "name": '"input"', + "props": ["className:sx_216a3adbf2_c", 'type:"checkbox"'], + "children": [], + }, + {"contents": '"Agree"'}, + ], + } + ], + } + + +def test_checkbox_unknown_variant(ui_plugin: UIPlugin): + """A variant a checkbox does not have is an error that lists the ones it has.""" + with pytest.raises(StyleError) as error: + rx.ui.checkbox("Agree", variant="solid") + assert ( + str(error.value) + == 'rx.ui.checkbox: unknown variant "solid". The values are "classic", "surface", "soft".' + ) + + +def test_checkbox_unknown_size(ui_plugin: UIPlugin): + """So is a size.""" + with pytest.raises(StyleError) as error: + rx.ui.checkbox("Agree", size="4") + assert ( + str(error.value) + == 'rx.ui.checkbox: unknown size "4". The values are "1", "2", "3".' + ) + + +def test_checkbox_bound_to_state(ui_plugin: UIPlugin): + """A change hands over whether the input is checked, and the input follows.""" + component = Checkbox.create( + checked=CheckboxState.agreed, on_change=CheckboxState.agree + ) + state = ( + "tests___units___reflex_components_ui___components___test_checkbox" + "____checkbox_state" + ) + assert component.render()["props"] == [ + f"checked:reflex___state____state__{state}.agreed_rx_state_", + "className:sx_eda6ae65a6_c", + ( + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.' + f'{state}.agree", ({{ ["agreed"] : _e?.["target"]?.["checked"] }}), ' + "({ })))], [_e], ({ }))))" + ), + 'type:"checkbox"', + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index f7574178623..59a80998d5e 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -115,6 +115,7 @@ def test_every_wave_is_in_the_namespace(): "callout.text", "card", "center", + "checkbox", "code", "container", "data_list.item", From 7a8920c80b8c1befd88d11b09bb809b031c57f3f Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 00:41:05 +0000 Subject: [PATCH 069/204] Add rx.ui.switch: a native checkbox with the role of a switch Its track and thumb are the pseudo-elements of one input. Enter does not toggle it, as the browser has it, which the allowlist says. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../parity/allowlist.toml | 16 + .../parity/ui_parity/components/switch.py | 300 +++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/switch.py | 90 +++ .../src/reflex_components_ui/styles/switch.py | 287 +++++++++ .../components/test_switch.py | 570 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 7 files changed, 1265 insertions(+) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/switch.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/switch.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py create mode 100644 tests/units/reflex_components_ui/components/test_switch.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 15dcd132c97..10cff6b9e20 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -88,3 +88,19 @@ reason = "rx.checkbox is a button that JavaScript turns into a checkbox: until i component = "checkbox" step = "Enter on a checkbox does not submit its form" reason = "rx.ui.checkbox is a native input, and the browser submits a form when Enter is pressed in one of its inputs, a checkbox included. rx.checkbox swallows the key. Space toggles both, and Enter toggles neither." + +[[contract]] +component = "switch" +step = "is turned on by a click with JavaScript disabled" +system = "rx" +reason = "rx.switch is a button that JavaScript turns into a switch: until it has run, a click does nothing. rx.ui.switch is a native checkbox with the role of a switch, which a click on it or on its label turns on and off with or without JavaScript." + +[[contract]] +component = "switch" +step = "Enter toggles it" +reason = "rx.ui.switch is a native checkbox, which the browser toggles on Space and not on Enter. rx.switch is a button, which both keys press." + +[[contract]] +component = "switch" +step = "Enter on a switch does not submit its form" +reason = "rx.ui.switch is a native input, and the browser submits a form when Enter is pressed in one of its inputs. rx.switch toggles on that key instead." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/switch.py b/packages/reflex-components-ui/parity/ui_parity/components/switch.py new file mode 100644 index 00000000000..1bbc0981c55 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/switch.py @@ -0,0 +1,300 @@ +"""The switch: every variant, size and state, and what a native input gives it.""" + +from __future__ import annotations + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +ON_OFF = [True, False] + +MATRIX = Matrix( + component="switch", + base={"default_checked": True}, + cross={"variant": VARIANTS, "size": SIZES, "default_checked": ON_OFF}, + sweep={ + "color_scheme": ACCENTS, + "radius": ["none", "small", "full"], + "high_contrast": [True], + "disabled": [True], + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "default_checked": ON_OFF, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "default_checked": ON_OFF, + "disabled": [True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "default_checked": ON_OFF, + "high_contrast": [False, True], + "state": STATES, + }, + { + "variant": VARIANTS, + "default_checked": [True], + "state": [ACTIVE], + "high_contrast": [False, True], + "appearance": [DARK], + }, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + {"radius": ["none", "small", "full"], "size": SIZES}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(120, 64), + # Not held to zero. At a threshold of zero 132 of the 164 cells are equal + # pixel for pixel, the base cell among them, and the others differ by + # where they are on the page: the gradient of the track is dithered and + # the blurred shadows of the thumb are rasterized by a step of a channel + # otherwise, on at most 8 pixels of 1408. At the default threshold 5 cells + # differ, by at most 3 pixels of 1836. + tolerance=0.002, +) + + +class SwitchState(rx.State): + """What the switches of the contract are bound to.""" + + bound: bool = False + seen: list[bool] = [] + submitted: dict[str, str] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, checked: bool): + """Follow the bound switch. + + Args: + checked: Whether it is on. + """ + self.bound = checked + + @rx.event + def see(self, checked: bool): + """Keep what a change handed over. + + Args: + checked: Whether the switch is on. + """ + self.seen.append(checked) + + @rx.event + def flip(self): + """Change the bound value from outside the switch.""" + self.bound = not self.bound + + @rx.event + def submit(self, data: dict[str, str]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +CONTRACT = Contract( + component="switch", + render=lambda namespace: namespace.box( + rx.el.label("Wifi", namespace.switch(id="wifi", on_change=SwitchState.see)), + namespace.switch(id="off", disabled=True, aria_label="Off"), + namespace.switch( + id="bound", + aria_label="Bound", + checked=SwitchState.bound, + on_change=SwitchState.set_bound, + ), + rx.el.button("Flip", id="flip", on_click=SwitchState.flip), + rx.el.form( + namespace.switch(id="news", name="news", aria_label="News"), + namespace.switch(id="plan", name="plan", value="pro", aria_label="Plan"), + namespace.switch( + id="was", name="was", default_checked=True, aria_label="Was" + ), + namespace.switch( + id="terms", name="terms", required=True, aria_label="Terms" + ), + rx.el.button("Send", id="send", type="submit"), + on_submit=SwitchState.submit, + id="form", + ), + rx.el.span(SwitchState.seen.to_string(), id="seen"), + rx.el.span(SwitchState.bound.to_string(), id="bound-value"), + rx.el.span(SwitchState.submitted.to_string(), id="submitted"), + rx.el.span(SwitchState.submissions.to_string(), id="submissions"), + ), +) + + +def _focused(run: Run) -> str: + """Read which element has the focus. + + Args: + run: The run, on a page. + + Returns: + The id of the element. + """ + return run.page.evaluate("document.activeElement.id") + + +def _wait_for_text(run: Run, element: str, text: str) -> None: + """Wait until an element holds a text. + + Args: + run: The run, on a page. + element: The id of the element. + text: The whole text. + """ + run.page.wait_for_function( + "([id, text]) => document.getElementById(id).textContent === text", + arg=[element, text], + ) + + +@CONTRACT.step("is a switch in the server render", on=SERVER) +def _server_render(run: Run) -> None: + wifi = run.server.element("wifi").attributes + assert wifi["role"] == "switch" + assert "disabled" in run.server.element("off").attributes + + +@CONTRACT.step("is turned on by a click with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + assert _focused(run) == "wifi" + page.get_by_text("Wifi").click() + assert page.locator("#wifi").is_checked() + assert page.locator("#was").is_checked() + assert page.locator("#off").is_disabled() + + +@CONTRACT.step("has the role, the name and the state of a switch") +def _role(run: Run) -> None: + page = run.page + wifi = page.get_by_role("switch", name="Wifi") + assert wifi.get_attribute("id") == "wifi" + assert not wifi.is_checked() + assert page.get_by_role("switch", name="Was", checked=True).count() == 1 + assert page.get_by_role("switch", name="Off", disabled=True).count() == 1 + assert page.get_by_role("switch").count() == 7 + + +@CONTRACT.step("Tab skips a disabled switch") +def _tab(run: Run) -> None: + focused = [] + for _ in range(3): + run.page.keyboard.press("Tab") + focused.append(_focused(run)) + assert focused == ["wifi", "bound", "flip"] + run.page.keyboard.press("Shift+Tab") + assert _focused(run) == "bound" + assert run.page.locator("#bound").evaluate( + "element => element.matches(':focus-visible')" + ) + + +@CONTRACT.step("Space and a click on it or on its label toggle it, and say so") +def _toggle(run: Run) -> None: + page = run.page + wifi = page.locator("#wifi") + wifi.focus() + page.keyboard.press("Space") + assert wifi.is_checked() + page.keyboard.press("Space") + assert not wifi.is_checked() + page.get_by_text("Wifi").click(position={"x": 4, "y": 4}) + assert wifi.is_checked() + wifi.click() + assert not wifi.is_checked() + _wait_for_text(run, "seen", "[true,false,true,false]") + + +@CONTRACT.step("Enter toggles it") +def _enter(run: Run) -> None: + wifi = run.page.locator("#wifi") + wifi.focus() + run.page.keyboard.press("Enter") + assert wifi.is_checked() + + +@CONTRACT.step("Enter on a switch does not submit its form") +def _enter_in_form(run: Run) -> None: + page = run.page + page.locator("#terms").check() + page.locator("#news").focus() + page.keyboard.press("Enter") + page.locator("#flip").click() + _wait_for_text(run, "bound-value", "true") + assert page.locator("#submissions").text_content() == "0" + + +@CONTRACT.step("a disabled switch is not toggled") +def _disabled(run: Run) -> None: + off = run.page.locator("#off") + off.click(force=True) + assert not off.is_checked() + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + bound = page.locator("#bound") + bound.click() + _wait_for_text(run, "bound-value", "true") + assert bound.is_checked() + page.locator("#flip").click() + _wait_for_text(run, "bound-value", "false") + page.wait_for_function( + "!document.getElementById('bound').matches(':checked, [aria-checked=true]')" + ) + assert not bound.is_checked() + + +@CONTRACT.step("submits with a form whether it is on") +def _submit(run: Run) -> None: + page = run.page + page.locator("#plan").check() + page.locator("#terms").check() + page.locator("#send").click() + _wait_for_text(run, "submissions", "1") + assert page.locator("#submitted").text_content() == ( + '{"plan":true,"was":true,"terms":true,"news":false}' + ) + + +@CONTRACT.step("a required switch holds its form back until it is on") +def _required(run: Run) -> None: + page = run.page + page.locator("#send").click() + # An event that does reach the server comes back after the blocked one. + page.locator("#flip").click() + _wait_for_text(run, "bound-value", "true") + assert page.locator("#submissions").text_content() == "0" + page.locator("#terms").check() + page.locator("#send").click() + _wait_for_text(run, "submissions", "1") 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 56fb42ca3d8..bc1c6a79092 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -22,6 +22,7 @@ "components.separator": ["divider", "separator"], "components.skeleton": ["skeleton"], "components.spinner": ["spinner"], + "components.switch": ["switch"], "components.table": ["table"], "layout.box": ["box"], "layout.center": ["center"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/switch.py b/packages/reflex-components-ui/src/reflex_components_ui/components/switch.py new file mode 100644 index 00000000000..5276d4fc1ba --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/switch.py @@ -0,0 +1,90 @@ +"""A switch: a native checkbox with the role of a switch.""" + +from __future__ import annotations + +import functools +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, checked_input_event +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.components.checkbox import CheckedInput +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.switch import SWITCH +from reflex_components_ui.themes import LiteralAccentColor + +LiteralSwitchSize = Literal["1", "2", "3"] + + +class Switch(CheckedInput): + """A toggle switch alternative to the checkbox.""" + + styles: ClassVar[ComponentStyles] = SWITCH + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + default_checked: Var[bool] = field(doc="Whether the switch is checked by default") + + checked: Var[bool] = field(doc="Whether the switch is checked") + + disabled: Var[bool] = field( + doc="If true, prevent the user from interacting with the switch" + ) + + required: Var[bool] = field( + doc="If true, the user must interact with the switch to submit the form" + ) + + name: Var[str] = field(doc="The name of the switch (when submitting a form)") + + value: Var[str] = field(doc='The value associated with the "on" position') + + size: Var[Responsive[LiteralSwitchSize]] = field(doc='Switch size "1" - "4"') + + variant: Var[Literal["classic", "surface", "soft"]] = field( + doc='Variant of switch: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for switch") + + high_contrast: Var[bool] = field( + doc="Whether to render the switch with higher contrast color against background" + ) + + radius: Var[Literal["none", "small", "full"]] = field( + doc='Override theme radius for switch: "none" | "small" | "full"' + ) + + on_change: EventHandler[checked_input_event] = field( + doc="Fired when the value of the switch changes" + ) + + @classmethod + @functools.cache + def _literal_props(cls) -> dict[str, tuple[str, ...]]: + """Get the props that take listed values. + + Returns: + The values of each such prop, the radius among them: a switch has + fewer than a theme. + """ + return {**super()._literal_props(), "radius": ("none", "small", "full")} + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the input as a switch. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role that says on and off rather than checked. + """ + return super()._render(props).add_props(role="switch") + + +switch = Switch.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py new file mode 100644 index 00000000000..cc48a835f6f --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py @@ -0,0 +1,287 @@ +"""The look of a switch: a native checkbox drawn as a track and a thumb.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.appearance import by_appearance +from reflex_components_ui.styles.control import DISABLED, FOCUS, FOCUS_RING, RESET + +accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black + +_HEIGHT = "--switch-height" +_WIDTH = "--switch-width" +_RADIUS = "--switch-border-radius" +_INSET = "--switch-thumb-inset" +_THUMB = "--switch-thumb-size" +_TRAVEL = "--switch-thumb-translate-x" + +_CHECKED = ":checked" +_CHECKED_ENABLED = f":checked:not({DISABLED})" +_PRESSED = f":active:not({DISABLED})" +_UNCHECKED_PRESSED = f":active:not(:checked, {DISABLED})" +_CHECKED_PRESSED = f":checked:active:not({DISABLED})" + +# A pressed switch that is on, and one that is high contrast too. +_PRESSED_FILTER = by_appearance("brightness(0.92) saturate(1.1)", "brightness(1.08)") +_PRESSED_FILTER_HIGH_CONTRAST = by_appearance( + "contrast(0.82) saturate(1.2) brightness(1.16)", "brightness(1.08)" +) +# What darkens the track of a high contrast switch that is on. +_OVERLAY = f"light-dark({black.a[8]}, transparent)" + +_THUMB_DISABLED = f"0 0 0 1px {gray.a[2]}, 0 1px 3px {black.a[1]}" +_THUMB_CHECKED = ( + f"0 1px 3px {black.a[2]}, 0 2px 4px -1px {black.a[1]}, 0 0 0 1px {black.a[1]}, " + f"0 0 0 1px {accent.a[4]}, -1px 0 1px {black.a[2]}" +) +_THUMB_CHECKED_HIGH_CONTRAST = ( + f"0 1px 3px {black.a[2]}, 0 2px 4px -1px {black.a[1]}, 0 0 0 1px {black.a[2]}, " + f"-1px 0 1px {black.a[2]}" +) + + +def _fade(start: str, end: str = "transparent") -> str: + """Make one layer of a track: a color that gives way where the thumb is. + + Args: + start: The color under the part that is on. + end: The color under the part that is off. + + Returns: + The gradient. + """ + return f"linear-gradient(to right, {start} 40%, {end} 60%)" + + +def _states(rest: Any, checked: Any = None, disabled: Any = None, **more: Any) -> Any: + """Make the value of a property by the state of the input. + + Args: + rest: The value of a switch that is off. + checked: The value of one that is on, when it differs. + disabled: The value of a disabled one, when it differs. + **more: Values under further conditions. + + Returns: + The value, under a condition for each state that has one of its own. + """ + value = {"default": rest} + if checked is not None: + value[_CHECKED_ENABLED] = checked + value.update(more) + if disabled is not None: + value[DISABLED] = disabled + return value + + +def _thumb(rest: str, checked: str) -> dict[str, Any]: + """Make the thumb of a variant. + + Args: + rest: The shadows of the thumb of a switch that is off. + checked: The shadows of one that is on. + + Returns: + The styles of the thumb. + """ + return { + "background_color": _states("white", disabled=gray[2]), + "box_shadow": _states(rest, checked, _THUMB_DISABLED), + } + + +def _look(variant: str, high_contrast: bool) -> dict[str, Any]: + """Make the track and the thumb of one variant. + + Args: + variant: The variant. + high_contrast: Whether the switch is high contrast. + + Returns: + The styles of the two pseudo-elements, for every state of the input. + """ + pressed = {"filter": _states("none", **{_CHECKED_PRESSED: _PRESSED_FILTER})} + if high_contrast: + pressed = { + "filter": _states( + "none", **{_CHECKED_PRESSED: _PRESSED_FILTER_HIGH_CONTRAST} + ) + } + checked = _THUMB_CHECKED_HIGH_CONTRAST if high_contrast else _THUMB_CHECKED + overlay = [_fade(_OVERLAY)] if high_contrast else [] + if variant == "surface": + track: dict[str, Any] = { + "background_color": _states(gray.a[3], **{_PRESSED: gray.a[4]}), + "background_image": _states( + ", ".join([*overlay, _fade(accent.track)]), disabled="none" + ), + "box_shadow": _states( + f"inset 0 0 0 1px {gray.a[5]}", + disabled=f"inset 0 0 0 1px {gray.a[3]}", + ), + **pressed, + } + thumb = _thumb( + f"0 0 1px 1px {black.a[2]}, 0 1px 1px {black.a[1]}, " + f"0 2px 4px -1px {black.a[1]}", + checked, + ) + elif variant == "classic": + track = { + "background_color": _states( + gray.a[4], disabled=gray.a[5], **{_UNCHECKED_PRESSED: gray.a[5]} + ), + "background_image": _states( + ", ".join([*overlay, _fade(accent.track)]), disabled="none" + ), + "box_shadow": ( + _states( + f"inset 0 0 0 1px {gray.a[3]}, inset 0 0 0 1px {black.a[2]}, " + f"inset 0 1.5px 2px 0 {black.a[2]}", + disabled=tokens.shadow[1], + ) + if high_contrast + else _states( + tokens.shadow[1], + f"inset 0 0 0 1px {gray.a[3]}, inset 0 0 0 1px {accent.a[4]}, " + f"inset 0 0 0 1px {black.a[1]}, " + f"inset 0 1.5px 2px 0 {black.a[2]}", + tokens.shadow[1], + ) + ), + "opacity": _states(1, disabled=0.5), + **pressed, + } + thumb = _thumb( + f"0 1px 3px {black.a[3]}, 0 2px 4px -1px {black.a[1]}, " + f"0 0 0 1px {black.a[2]}", + checked, + ) + else: + step = accent.a[6] if high_contrast else accent.a[4] + track = { + "background_color": _states( + gray.a[3], "transparent", gray.a[4], **{_PRESSED: gray.a[4]} + ), + "background_image": _states( + ", ".join([ + *overlay, + _fade(step), + _fade(step), + # Blended with white for more contrast in the dark. + _fade(step, white.a[1]), + _fade(accent.a[3] if high_contrast else gray.a[2], gray.a[3]), + ]), + disabled="none", + ), + } + if high_contrast: + track.update(pressed) + thumb = { + "background_color": _states("white", disabled=gray[2]), + "box_shadow": _states( + f"0 0 0 1px {black.a[1]}, 0 1px 3px {black.a[1]}, " + f"0 1px 3px {black.a[1]}, 0 2px 4px -1px {black.a[1]}", + f"0 0 0 1px {black.a[1]}, 0 1px 3px {black.a[2]}, " + f"0 1px 3px {accent.a[3]}, 0 2px 4px -1px {accent.a[3]}", + _THUMB_DISABLED, + ), + "filter": _states("saturate(0.45)", disabled="none"), + } + return {"_before": track, "_after": thumb} + + +_VARIANTS = ("classic", "surface", "soft") + +SWITCH: ComponentStyles = { + "base": unchecked({ + **RESET, + "position": "relative", + "display": "inline-flex", + "align_items": "center", + "vertical_align": "top", + "flex_shrink": 0, + # In a line of text it is as high as the line. + "height": f"var(--line-height, var({_HEIGHT}))", + _WIDTH: f"calc(var({_HEIGHT}) * 1.75)", + _INSET: "1px", + _THUMB: f"calc(var({_HEIGHT}) - var({_INSET}) * 2)", + _TRAVEL: f"calc(var({_WIDTH}) - var({_HEIGHT}))", + "cursor": {DISABLED: tokens.cursor.disabled}, + "mix_blend_mode": {DISABLED: by_appearance("multiply", "screen")}, + # The track: its gradient is the width of the part that is on, the + # height of the thumb and the width of the part that is off, and + # moves with the thumb. + "_before": { + "content": "''", + "display": "block", + "width": f"var({_WIDTH})", + "height": f"var({_HEIGHT})", + "border_radius": f"var({_RADIUS})", + "transition_property": ( + "background-position, background-color, box-shadow, filter" + ), + "transition_timing_function": "linear, ease-in-out, ease-in-out, ease-in-out", + "transition_duration": { + "default": "120ms, 140ms, 140ms, 140ms", + _CHECKED: "160ms, 140ms, 140ms, 140ms", + ":active": "30ms", + }, + "background_repeat": "no-repeat", + "background_size": f"calc(var({_WIDTH}) * 2 + var({_HEIGHT})) 100%", + "background_position_x": {"default": "100%", _CHECKED: "0%"}, + "background_position_y": "50%", + "cursor": { + "default": tokens.cursor.switch, + DISABLED: tokens.cursor.disabled, + }, + FOCUS: FOCUS_RING, + }, + "_after": { + "content": "''", + "position": "absolute", + "left": f"var({_INSET})", + "width": f"var({_THUMB})", + "height": f"var({_THUMB})", + "border_radius": f"calc(var({_RADIUS}) - var({_INSET}))", + "transition_property": { + "default": "transform, box-shadow", + DISABLED: "none", + }, + "transition_duration": "140ms", + "transition_timing_function": ( + "cubic-bezier(0.45, 0.05, 0.55, 0.95), ease-in-out" + ), + "transform": {_CHECKED: f"translateX(var({_TRAVEL}))"}, + "pointer_events": "none", + }, + }), + "variants": { + "size": { + "1": unchecked({ + _HEIGHT: tokens.space[4], + _RADIUS: f"max({tokens.radius[1]}, {tokens.radius.thumb})", + }), + "2": unchecked({ + _HEIGHT: f"calc({tokens.space[5]} * 5 / 6)", + _RADIUS: f"max({tokens.radius[2]}, {tokens.radius.thumb})", + }), + "3": unchecked({ + _HEIGHT: tokens.space[5], + _RADIUS: f"max({tokens.radius[2]}, {tokens.radius.thumb})", + }), + }, + "variant": {variant: unchecked(_look(variant, False)) for variant in _VARIANTS}, + }, + "defaults": {"size": "2", "variant": "surface"}, + "compound": [ + { + "props": {"variant": variant, "high_contrast": "true"}, + "style": unchecked(_look(variant, True)), + } + for variant in _VARIANTS + ], +} diff --git a/tests/units/reflex_components_ui/components/test_switch.py b/tests/units/reflex_components_ui/components/test_switch.py new file mode 100644 index 00000000000..61132c97946 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_switch.py @@ -0,0 +1,570 @@ +"""Tests for reflex_components_ui.components.switch.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +def test_switch( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A switch is a native checkbox with the role of a switch, its track and thumb drawn by its styles.""" + component = rx.ui.switch(id="wifi", name="wifi", default_checked=True) + assert component.render() == { + "name": '"input"', + "props": [ + "className:sx_14daba69db_c", + "defaultChecked:true", + 'id:"wifi"', + 'name:"wifi"', + "ref:ref_wifi", + 'role:"switch"', + 'type:"checkbox"', + ], + "children": [], + } + assert declared_styles(component) == [ + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--gray-a3)", + ":active:not(:disabled)": "var(--gray-a4)", + }, + "::after": {"default": "white", ":disabled": "var(--gray-2)"}, + }, + "backgroundImage": { + "default": "none", + "::before": { + "default": "linear-gradient(to right, " + "var(--accent-track) 40%, " + "transparent 60%)", + ":disabled": "none", + }, + }, + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "verticalAlign": "top", + "flexShrink": 0, + "height": { + "default": "var(--line-height, var(--switch-height))", + "::before": "var(--switch-height)", + "::after": "var(--switch-thumb-size)", + }, + "--switch-width": "calc(var(--switch-height) * 1.75)", + "--switch-thumb-inset": "1px", + "--switch-thumb-size": "calc(var(--switch-height) - " + "var(--switch-thumb-inset) * 2)", + "--switch-thumb-translate-x": "calc(var(--switch-width) - " + "var(--switch-height))", + "cursor": { + ":disabled": "var(--cursor-disabled)", + "::before": { + "default": "var(--cursor-switch)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "mixBlendMode": { + ":disabled": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" + }, + "content": {"::before": "''", "::after": "''"}, + "width": { + "::before": "var(--switch-width)", + "::after": "var(--switch-thumb-size)", + }, + "borderRadius": { + "::before": "var(--switch-border-radius)", + "::after": "calc(var(--switch-border-radius) - " + "var(--switch-thumb-inset))", + }, + "transitionProperty": { + "::before": "background-position, background-color, box-shadow, filter", + "::after": {"default": "transform, box-shadow", ":disabled": "none"}, + }, + "transitionTimingFunction": { + "::before": "linear, ease-in-out, ease-in-out, ease-in-out", + "::after": "cubic-bezier(0.45, 0.05, 0.55, 0.95), ease-in-out", + }, + "transitionDuration": { + "::before": { + "default": "120ms, 140ms, 140ms, 140ms", + ":checked": "160ms, 140ms, 140ms, 140ms", + ":active": "30ms", + }, + "::after": "140ms", + }, + "backgroundRepeat": {"::before": "no-repeat"}, + "backgroundSize": { + "::before": "calc(var(--switch-width) * 2 + var(--switch-height)) 100%" + }, + "backgroundPositionX": {"::before": {"default": "100%", ":checked": "0%"}}, + "backgroundPositionY": {"::before": "50%"}, + "left": {"::after": "var(--switch-thumb-inset)"}, + "transform": { + "::after": {":checked": "translateX(var(--switch-thumb-translate-x))"} + }, + "pointerEvents": {"::after": "none"}, + "--switch-height": "calc(var(--space-5) * 5 / 6)", + "--switch-border-radius": "max(var(--radius-2), var(--radius-thumb))", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a5)", + ":disabled": "inset 0 0 0 1px var(--gray-a3)", + }, + "::after": { + "default": "0 0 1px 1px var(--black-a2), 0 1px 1px " + "var(--black-a1), 0 2px 4px -1px " + "var(--black-a1)", + ":checked:not(:disabled)": "0 1px 3px " + "var(--black-a2), 0 2px " + "4px -1px " + "var(--black-a1), 0 0 0 " + "1px var(--black-a1), 0 " + "0 0 1px " + "var(--accent-a4), -1px " + "0 1px var(--black-a2)", + ":disabled": "0 0 0 1px var(--gray-a2), 0 1px 3px var(--black-a1)", + }, + }, + "filter": { + "::before": { + "default": "none", + ":checked:active:not(:disabled)": "var(--rx-if-light, " + "brightness(0.92) " + "saturate(1.1)) " + "var(--rx-if-dark, " + "brightness(1.08))", + } + }, + } + ] + + +def test_switch_classic_high_contrast( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """Every prop reaches the input or selects its styles, and a switch that nothing changes is read only.""" + component = rx.ui.switch( + checked=True, + size=rx.breakpoints(initial="1", md="3"), + variant="classic", + high_contrast=True, + color_scheme="ruby", + radius="small", + disabled=True, + required=True, + value="yes", + as_child=True, + ) + assert component.render() == { + "name": '"input"', + "props": [ + "checked:true", + 'className:sx_7350a6aadb_c + " " + reflexUIClasses_e201574881 + " " ' + "+ reflexUIClasses_6d1e87c3d8", + "disabled:true", + "readOnly:true", + "required:true", + 'role:"switch"', + 'type:"checkbox"', + 'value:"yes"', + ], + "children": [], + } + assert declared_styles(component) == [ + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--gray-a4)", + ":active:not(:checked, :disabled)": "var(--gray-a5)", + ":disabled": "var(--gray-a5)", + }, + "::after": {"default": "white", ":disabled": "var(--gray-2)"}, + }, + "backgroundImage": { + "default": "none", + "::before": { + "default": "linear-gradient(to right, " + "light-dark(var(--black-a8), " + "transparent) 40%, transparent " + "60%), linear-gradient(to right, " + "var(--accent-track) 40%, " + "transparent 60%)", + ":disabled": "none", + }, + }, + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "verticalAlign": "top", + "flexShrink": 0, + "height": { + "default": "var(--line-height, var(--switch-height))", + "::before": "var(--switch-height)", + "::after": "var(--switch-thumb-size)", + }, + "--switch-width": "calc(var(--switch-height) * 1.75)", + "--switch-thumb-inset": "1px", + "--switch-thumb-size": "calc(var(--switch-height) - " + "var(--switch-thumb-inset) * 2)", + "--switch-thumb-translate-x": "calc(var(--switch-width) - " + "var(--switch-height))", + "cursor": { + ":disabled": "var(--cursor-disabled)", + "::before": { + "default": "var(--cursor-switch)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "mixBlendMode": { + ":disabled": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" + }, + "content": {"::before": "''", "::after": "''"}, + "width": { + "::before": "var(--switch-width)", + "::after": "var(--switch-thumb-size)", + }, + "borderRadius": { + "::before": "var(--switch-border-radius)", + "::after": "calc(var(--switch-border-radius) - " + "var(--switch-thumb-inset))", + }, + "transitionProperty": { + "::before": "background-position, background-color, box-shadow, filter", + "::after": {"default": "transform, box-shadow", ":disabled": "none"}, + }, + "transitionTimingFunction": { + "::before": "linear, ease-in-out, ease-in-out, ease-in-out", + "::after": "cubic-bezier(0.45, 0.05, 0.55, 0.95), ease-in-out", + }, + "transitionDuration": { + "::before": { + "default": "120ms, 140ms, 140ms, 140ms", + ":checked": "160ms, 140ms, 140ms, 140ms", + ":active": "30ms", + }, + "::after": "140ms", + }, + "backgroundRepeat": {"::before": "no-repeat"}, + "backgroundSize": { + "::before": "calc(var(--switch-width) * 2 + var(--switch-height)) 100%" + }, + "backgroundPositionX": {"::before": {"default": "100%", ":checked": "0%"}}, + "backgroundPositionY": {"::before": "50%"}, + "left": {"::after": "var(--switch-thumb-inset)"}, + "transform": { + "::after": {":checked": "translateX(var(--switch-thumb-translate-x))"} + }, + "pointerEvents": {"::after": "none"}, + "--switch-height": { + "default": "var(--space-4)", + "@media (min-width: 1024px)": "var(--space-5)", + }, + "--switch-border-radius": { + "default": "max(var(--radius-1), var(--radius-thumb))", + "@media (min-width: 1024px)": "max(var(--radius-2), " + "var(--radius-thumb))", + }, + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a3), inset " + "0 0 0 1px var(--black-a2), inset 0 " + "1.5px 2px 0 var(--black-a2)", + ":disabled": "var(--shadow-1)", + }, + "::after": { + "default": "0 1px 3px var(--black-a3), 0 2px 4px " + "-1px var(--black-a1), 0 0 0 1px " + "var(--black-a2)", + ":checked:not(:disabled)": "0 1px 3px " + "var(--black-a2), 0 2px " + "4px -1px " + "var(--black-a1), 0 0 0 " + "1px var(--black-a2), " + "-1px 0 1px " + "var(--black-a2)", + ":disabled": "0 0 0 1px var(--gray-a2), 0 1px 3px var(--black-a1)", + }, + }, + "opacity": {"::before": {"default": 1, ":disabled": 0.5}}, + "filter": { + "::before": { + "default": "none", + ":checked:active:not(:disabled)": "var(--rx-if-light, " + "contrast(0.82) " + "saturate(1.2) " + "brightness(1.16)) " + "var(--rx-if-dark, " + "brightness(1.08))", + } + }, + } + ] + + +def test_switch_soft( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The soft variant layers the gradients of its track and mutes its thumb.""" + component = rx.ui.switch(variant="soft") + assert declared_styles(component) == [ + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--gray-a3)", + ":checked:not(:disabled)": "transparent", + ":active:not(:disabled)": "var(--gray-a4)", + ":disabled": "var(--gray-a4)", + }, + "::after": {"default": "white", ":disabled": "var(--gray-2)"}, + }, + "backgroundImage": { + "default": "none", + "::before": { + "default": "linear-gradient(to right, " + "var(--accent-a4) 40%, " + "transparent 60%), " + "linear-gradient(to right, " + "var(--accent-a4) 40%, " + "transparent 60%), " + "linear-gradient(to right, " + "var(--accent-a4) 40%, " + "var(--white-a1) 60%), " + "linear-gradient(to right, " + "var(--gray-a2) 40%, " + "var(--gray-a3) 60%)", + ":disabled": "none", + }, + }, + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "verticalAlign": "top", + "flexShrink": 0, + "height": { + "default": "var(--line-height, var(--switch-height))", + "::before": "var(--switch-height)", + "::after": "var(--switch-thumb-size)", + }, + "--switch-width": "calc(var(--switch-height) * 1.75)", + "--switch-thumb-inset": "1px", + "--switch-thumb-size": "calc(var(--switch-height) - " + "var(--switch-thumb-inset) * 2)", + "--switch-thumb-translate-x": "calc(var(--switch-width) - " + "var(--switch-height))", + "cursor": { + ":disabled": "var(--cursor-disabled)", + "::before": { + "default": "var(--cursor-switch)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "mixBlendMode": { + ":disabled": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" + }, + "content": {"::before": "''", "::after": "''"}, + "width": { + "::before": "var(--switch-width)", + "::after": "var(--switch-thumb-size)", + }, + "borderRadius": { + "::before": "var(--switch-border-radius)", + "::after": "calc(var(--switch-border-radius) - " + "var(--switch-thumb-inset))", + }, + "transitionProperty": { + "::before": "background-position, background-color, box-shadow, filter", + "::after": {"default": "transform, box-shadow", ":disabled": "none"}, + }, + "transitionTimingFunction": { + "::before": "linear, ease-in-out, ease-in-out, ease-in-out", + "::after": "cubic-bezier(0.45, 0.05, 0.55, 0.95), ease-in-out", + }, + "transitionDuration": { + "::before": { + "default": "120ms, 140ms, 140ms, 140ms", + ":checked": "160ms, 140ms, 140ms, 140ms", + ":active": "30ms", + }, + "::after": "140ms", + }, + "backgroundRepeat": {"::before": "no-repeat"}, + "backgroundSize": { + "::before": "calc(var(--switch-width) * 2 + var(--switch-height)) 100%" + }, + "backgroundPositionX": {"::before": {"default": "100%", ":checked": "0%"}}, + "backgroundPositionY": {"::before": "50%"}, + "left": {"::after": "var(--switch-thumb-inset)"}, + "transform": { + "::after": {":checked": "translateX(var(--switch-thumb-translate-x))"} + }, + "pointerEvents": {"::after": "none"}, + "--switch-height": "calc(var(--space-5) * 5 / 6)", + "--switch-border-radius": "max(var(--radius-2), var(--radius-thumb))", + "boxShadow": { + "::after": { + "default": "0 0 0 1px var(--black-a1), 0 1px 3px " + "var(--black-a1), 0 1px 3px " + "var(--black-a1), 0 2px 4px -1px " + "var(--black-a1)", + ":checked:not(:disabled)": "0 0 0 1px " + "var(--black-a1), 0 1px " + "3px var(--black-a2), 0 " + "1px 3px " + "var(--accent-a3), 0 " + "2px 4px -1px " + "var(--accent-a3)", + ":disabled": "0 0 0 1px var(--gray-a2), 0 1px 3px var(--black-a1)", + } + }, + "filter": {"::after": {"default": "saturate(0.45)", ":disabled": "none"}}, + } + ] + + +def test_switch_unknown_variant(ui_plugin: UIPlugin): + """A variant a switch does not have is an error that lists the ones it has.""" + with pytest.raises(StyleError) as error: + rx.ui.switch(variant="solid") + assert ( + str(error.value) + == 'rx.ui.switch: unknown variant "solid". The values are "classic", "surface", "soft".' + ) + + +def test_switch_unknown_radius(ui_plugin: UIPlugin): + """So is a radius: a switch has three.""" + with pytest.raises(StyleError) as error: + rx.ui.switch(radius="large") + assert ( + str(error.value) + == 'rx.ui.switch: unknown radius "large". The values are "none", "small", "full".' + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 59a80998d5e..f7b727b1291 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -144,6 +144,7 @@ def test_every_wave_is_in_the_namespace(): "spacer", "spinner", "stack", + "switch", "table.body", "table.cell", "table.column_header_cell", From 287cf920c0fc8e244c63ccf1dee996d84e25039f Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 01:05:05 +0000 Subject: [PATCH 070/204] Add rx.ui.radio and rx.ui.radio_group: native radio buttons that share a name A group gives its items their name, their look and their state while compiling, where Radix hands them through a context: the items are found below the root at any depth, through foreach and cond. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../parity/allowlist.toml | 11 + .../parity/ui_parity/components/radio.py | 54 ++ .../ui_parity/components/radio_group.py | 323 +++++++++ .../parity/ui_parity/samples.py | 26 + .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/_group.py | 113 +++ .../components/radio_group.py | 410 +++++++++++ .../src/reflex_components_ui/styles/radio.py | 152 ++++ .../components/test_radio_group.py | 683 ++++++++++++++++++ .../components/test_switch.py | 112 +-- .../reflex_components_ui/test_api_parity.py | 20 +- 11 files changed, 1815 insertions(+), 90 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/radio.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/radio_group.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_group.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py create mode 100644 tests/units/reflex_components_ui/components/test_radio_group.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 10cff6b9e20..1bbfdf549e6 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -104,3 +104,14 @@ reason = "rx.ui.switch is a native checkbox, which the browser toggles on Space component = "switch" step = "Enter on a switch does not submit its form" reason = "rx.ui.switch is a native input, and the browser submits a form when Enter is pressed in one of its inputs. rx.switch toggles on that key instead." + +[[contract]] +component = "radio_group" +step = "checks one item of a group with JavaScript disabled" +system = "rx" +reason = "The items of rx.radio_group are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. The items of rx.ui.radio_group are native radio buttons that share a name, which the browser checks one at a time with or without JavaScript." + +[[contract]] +component = "radio_group" +step = "Enter on a radio button does not submit its form" +reason = "The items of rx.ui.radio_group are native inputs, and the browser submits a form when Enter is pressed in one of its inputs, a radio button included. rx.radio_group swallows the key. Space and the arrow keys check an item in both." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio.py b/packages/reflex-components-ui/parity/ui_parity/components/radio.py new file mode 100644 index 00000000000..3688db504fe --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio.py @@ -0,0 +1,54 @@ +"""The radio namespace: a group built from a root and its items.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, Matrix + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +# The first radio button of the group: a button of Radix, an input here. +TARGET = ("button", "input") + + +def _group(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a radio group from its parts. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the root. + + Returns: + The group: an item with text, a disabled one, and one alone. + """ + return namespace.radio.root( + namespace.radio.item("One", value="1"), + namespace.radio.item("Two", value="2", disabled=True), + namespace.radio.item(value="3"), + **props, + ) + + +MATRIX = Matrix( + component="radio", + render=_group, + base={"default_value": "1"}, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "default_value": ["2", "3"], + "color_scheme": ["ruby", "gray"], + "high_contrast": [True], + "disabled": [True], + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE], + }, + stage=(160, 110), + crop="stage", + target=TARGET, + # Not held to zero, as the matrix of the radio group is not: a circle + # is anti-aliased by where it is on the page. At the default threshold 7 + # of the 19 cells differ, by at most 49 pixels of 17600. + tolerance=0.003, +) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py new file mode 100644 index 00000000000..f311731a076 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py @@ -0,0 +1,323 @@ +"""The radio group: every variant, size and state, and what native inputs give it.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, focused, wait_for_text + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +ITEMS = ["One", "Two", "Three"] +# The first radio button of the group: a button of Radix, an input here. +TARGET = ("button", "input") + + +def _group(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a radio group from a list of items. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. + + Returns: + The group. + """ + return namespace.radio_group(ITEMS, **props) + + +MATRIX = Matrix( + component="radio_group", + render=_group, + base={"default_value": "One"}, + cross={"variant": VARIANTS, "size": SIZES, "default_value": ["One", "Two"]}, + sweep={ + "color_scheme": ACCENTS, + "high_contrast": [True], + "disabled": [True], + "direction": ["row", "column", "row-reverse", "column-reverse"], + "spacing": ["1", "5"], + "appearance": [DARK], + "state": STATES, + }, + groups=[ + { + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "disabled": [True], "appearance": [LIGHT, DARK]}, + {"variant": VARIANTS, "default_value": ["One", "Two"], "state": STATES}, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + ], + stage=(220, 110), + crop="stage", + target=TARGET, + # Not held to zero. A circle is anti-aliased by where it is on the page: + # with the two frames of a cell swapped, each system is equal pixel for + # pixel to the other one in the same place, and differs from itself in + # the other place by the same pixels. At the default threshold 26 of the + # 117 cells differ, by at most 88 pixels of 24200. + tolerance=0.004, +) + + +class RadioGroupState(rx.State): + """What the radio groups of the contract are bound to.""" + + bound: str = "a" + seen: list[str] = [] + submitted: dict[str, str] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, value: str): + """Follow the bound group. + + Args: + value: The value of its checked item. + """ + self.bound = value + + @rx.event + def see(self, value: str): + """Keep what a change handed over. + + Args: + value: The value of the checked item. + """ + self.seen.append(value) + + @rx.event + def pick_last(self): + """Change the bound value from outside the group.""" + self.bound = "c" + + @rx.event + def submit(self, data: dict[str, str]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +CONTRACT = Contract( + component="radio_group", + render=lambda namespace: namespace.box( + rx.el.div( + namespace.radio_group(ITEMS, on_change=RadioGroupState.see), id="pick" + ), + rx.el.div( + namespace.radio_group.root( + namespace.radio_group.item("Red", value="red"), + namespace.radio_group.item("Green", value="green", disabled=True), + namespace.radio_group.item("Blue", value="blue"), + default_value="red", + on_change=RadioGroupState.see, + ), + id="colors", + ), + rx.el.div( + namespace.radio_group( + ["a", "b", "c"], + value=RadioGroupState.bound, + on_change=RadioGroupState.set_bound, + ), + id="bound", + ), + rx.el.button("Last", id="last", on_click=RadioGroupState.pick_last), + rx.el.div(namespace.radio_group(["x", "y"], disabled=True), id="off"), + rx.el.form( + namespace.radio_group(["s", "m", "l"], name="size", default_value="m"), + namespace.radio_group.root( + namespace.radio_group.item("Yes", value="yes"), + namespace.radio_group.item("No", value="no"), + name="answer", + required=True, + ), + rx.el.button("Send", id="send", type="submit"), + on_submit=RadioGroupState.submit, + id="form", + ), + rx.el.span(RadioGroupState.seen.to_string(), id="seen"), + rx.el.span(RadioGroupState.bound, id="bound-value"), + rx.el.span(RadioGroupState.submitted.to_string(), id="submitted"), + rx.el.span(RadioGroupState.submissions.to_string(), id="submissions"), + ), +) + +# The text of the checked radio buttons of a group, by the id of its frame. +CHECKED = ( + "id => [...document.getElementById(id).querySelectorAll('label')]" + ".filter(label => label.querySelector(':checked, [aria-checked=true]'))" + ".map(label => label.textContent)" +) +# How long a key is held, in milliseconds. +HELD = 60 +# The text of the item that has the focus. +FOCUSED_ITEM = "document.activeElement.closest('label')?.textContent" + + +def _wait_for_checked(run: Run, group: str, items: list[str]) -> None: + """Wait until the checked items of a group are the ones expected. + + Args: + run: The run, on a page. + group: The id of the frame of the group. + items: The text of each item that is to be checked. + """ + run.page.wait_for_function( + f"([id, items]) => JSON.stringify(({CHECKED})(id)) === items", + arg=[group, json.dumps(items)], + ) + + +@CONTRACT.step("its items are in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("pick").text == "OneTwoThree" + assert run.server.element("colors").text == "RedGreenBlue" + + +@CONTRACT.step("checks one item of a group with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.locator("#pick").get_by_text("Two").click() + _wait_for_checked(run, "pick", ["Two"]) + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + _wait_for_checked(run, "colors", ["Red"]) + _wait_for_checked(run, "form", ["m"]) + + +@CONTRACT.step("has the roles, the names and the states of a group of radio buttons") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("radiogroup").count() == 6 + pick = page.locator("#pick") + assert pick.get_by_role("radio").count() == 3 + assert not pick.get_by_role("radio", name="One").is_checked() + colors = page.locator("#colors") + assert colors.get_by_role("radio", name="Red", checked=True).count() == 1 + assert colors.get_by_role("radio", name="Green", disabled=True).count() == 1 + assert page.locator("#off").get_by_role("radio", disabled=True).count() == 2 + + +@CONTRACT.step("Tab stops once in each group, on its checked item") +def _tab(run: Run) -> None: + page = run.page + stops = [] + for _ in range(4): + page.keyboard.press("Tab") + stops.append(page.evaluate(FOCUSED_ITEM) or focused(page)) + assert stops == ["One", "Red", "a", "last"] + _wait_for_checked(run, "pick", []) + + +@CONTRACT.step("Shift+Tab into a group with nothing checked stops on its first item") +def _shift_tab(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + page.keyboard.press("Tab") + assert page.evaluate(FOCUSED_ITEM) == "Red" + page.keyboard.press("Shift+Tab") + assert page.evaluate(FOCUSED_ITEM) == "One" + + +@CONTRACT.step("the arrow keys move through a group and check, past a disabled item") +def _arrows(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + visited = [] + for key in ("ArrowDown", "ArrowRight", "ArrowDown", "ArrowUp", "ArrowLeft"): + # Held as long as a finger holds it: Radix checks the item the focus + # moves to only while the key is still down. + page.keyboard.press(key, delay=HELD) + visited.append(page.evaluate(FOCUSED_ITEM)) + _wait_for_checked(run, "pick", [visited[-1]]) + assert visited == ["Two", "Three", "One", "Three", "Two"] + wait_for_text(page, "seen", '["Two","Three","One","Three","Two"]') + page.keyboard.press("Tab") + page.keyboard.press("ArrowDown", delay=HELD) + assert page.evaluate(FOCUSED_ITEM) == "Blue" + _wait_for_checked(run, "colors", ["Blue"]) + page.keyboard.press("ArrowDown", delay=HELD) + _wait_for_checked(run, "colors", ["Red"]) + + +@CONTRACT.step("Space and a click on a label check an item, and say so") +def _check(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + page.keyboard.press("Space") + _wait_for_checked(run, "pick", ["One"]) + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + wait_for_text(page, "seen", '["One","Three"]') + + +@CONTRACT.step("Enter on a radio button does not submit its form") +def _enter_in_form(run: Run) -> None: + page = run.page + page.locator("#form").get_by_text("Yes").click() + page.keyboard.press("Enter") + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + assert page.locator("#submissions").text_content() == "0" + + +@CONTRACT.step("a disabled group and a disabled item are not checked") +def _disabled(run: Run) -> None: + page = run.page + page.locator("#off").get_by_text("x").click(force=True) + _wait_for_checked(run, "off", []) + page.locator("#colors").get_by_text("Green").click(force=True) + _wait_for_checked(run, "colors", ["Red"]) + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + _wait_for_checked(run, "bound", ["a"]) + page.locator("#bound").get_by_text("b").click() + wait_for_text(page, "bound-value", "b") + _wait_for_checked(run, "bound", ["b"]) + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + _wait_for_checked(run, "bound", ["c"]) + + +@CONTRACT.step("submits the value of its checked item with a form") +def _submit(run: Run) -> None: + page = run.page + page.locator("#form").get_by_text("No").click() + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == '{"size":"m","answer":"no"}' + + +@CONTRACT.step("a required group holds its form back until an item is checked") +def _required(run: Run) -> None: + page = run.page + page.locator("#send").click() + # An event that does reach the server comes back after the blocked one. + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + assert page.locator("#submissions").text_content() == "0" + page.locator("#form").get_by_text("Yes").click() + page.locator("#send").click() + wait_for_text(page, "submissions", "1") diff --git a/packages/reflex-components-ui/parity/ui_parity/samples.py b/packages/reflex-components-ui/parity/ui_parity/samples.py index 88e8609c50c..8a75b068d42 100644 --- a/packages/reflex-components-ui/parity/ui_parity/samples.py +++ b/packages/reflex-components-ui/parity/ui_parity/samples.py @@ -60,3 +60,29 @@ def tiles(words: tuple[str, ...] = WORDS) -> list[Any]: ) for word in words ] + + +def focused(page: Any) -> str: + """Read which element of a page has the focus. + + Args: + page: The page. + + Returns: + The id of the element. + """ + return page.evaluate("document.activeElement.id") + + +def wait_for_text(page: Any, element: str, text: str) -> None: + """Wait until an element of a page holds a text. + + Args: + page: The page. + element: The id of the element. + text: Its whole text. + """ + page.wait_for_function( + "([id, text]) => document.getElementById(id).textContent === text", + arg=[element, text], + ) 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 bc1c6a79092..90265db519c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -18,6 +18,7 @@ "components.icon_button": ["icon_button"], "components.inset": ["inset"], "components.progress": ["progress"], + "components.radio_group": ["radio", "radio_group"], "components.scroll_area": ["scroll_area"], "components.separator": ["divider", "separator"], "components.skeleton": ["skeleton"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py new file mode 100644 index 00000000000..457e685d870 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py @@ -0,0 +1,113 @@ +"""What a group of form controls shares: finding its items, and their state.""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterator +from typing import Any, TypeVar + +from reflex_base.components.component import BaseComponent +from reflex_base.vars.base import LiteralVar, Var, VarData + +T = TypeVar("T") + +# Numbers the groups that are given no name of their own. +_names = itertools.count(1) + + +def group_name(name: Var | None, kind: str) -> Var: + """Get the name the inputs of a group share. + + The browser takes radio buttons for one group by their name, so a group + without one is given a name no other group of the app has. + + Args: + name: The name the group was created with, or None. + kind: What the group holds, such as ``radio``. + + Returns: + The name of the inputs. + """ + if name is not None: + return name + return LiteralVar.create(f"rx-{kind}-{next(_names)}") + + +def descendants( + component: BaseComponent, kind: type[T], group: type | tuple[type, ...] +) -> Iterator[T]: + """Find the items of a group below its root, at any depth. + + Args: + component: The root of the group, or what is searched below it. + kind: The class of the items. + group: The class of a root: what is below another one is its own. + + Yields: + Each item, in the order of the tree. + """ + for child in component.children: + if isinstance(child, kind): + yield child + if not isinstance(child, group): + yield from descendants(child, kind, group) + + +def literal(value: Any) -> Any: + """Read a value that is known while compiling. + + Args: + value: A prop of a component. + + Returns: + What a literal Var holds, or the value as given. + """ + if isinstance(value, LiteralVar) and value._get_all_var_data() is None: + return value._var_value + return value + + +def either(first: Var | None, second: Var | None) -> Var | None: + """Combine two flags, either of which may be left out. + + Args: + first: A flag, such as whether a group is disabled. + second: Another one, such as whether one of its items is. + + Returns: + Whether one of them is set, or None when neither is given. + """ + if first is None or second is None: + return second if first is None else first + one, other = literal(first), literal(second) + if not isinstance(one, Var) and not isinstance(other, Var): + return LiteralVar.create(bool(one or other)) + return Var( + f"({first!s} || {second!s})", + _var_type=bool, + _var_data=VarData.merge(first._get_all_var_data(), second._get_all_var_data()), + ) + + +def is_value(selected: Var, value: Var | None) -> Var | bool: + """Say whether an item is the one a group has selected. + + Args: + selected: The value of the group. + value: The value of the item. + + Returns: + Whether they are equal: a bool when both are known while compiling. + """ + if value is None: + return False + one, other = literal(selected), literal(value) + if not isinstance(one, Var) and not isinstance(other, Var): + return one == other + return Var( + f"({selected!s} === {value!s})", + _var_type=bool, + _var_data=VarData.merge( + selected._get_all_var_data(), value._get_all_var_data() + ), + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py b/packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py new file mode 100644 index 00000000000..2d20b017a20 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py @@ -0,0 +1,410 @@ +"""A group of radio buttons: native inputs that share a name.""" + +from __future__ import annotations + +from collections.abc import Iterator, Sequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, input_event +from reflex_base.utils import types +from reflex_base.vars.base import LiteralVar, Var +from reflex_base.vars.sequence import StringVar +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.cond import cond +from reflex_components_core.core.foreach import foreach + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._group import ( + descendants, + either, + group_name, + is_value, + literal, +) +from reflex_components_ui.layout.flex import Flex +from reflex_components_ui.props import LiteralSpacing +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.radio import ( + RADIO, + RADIO_GROUP, + RADIO_GROUP_ITEM, + RADIO_GROUP_ITEM_INNER, +) +from reflex_components_ui.themes import LiteralAccentColor +from reflex_components_ui.typography.text import Text + +LiteralFlexDirection = Literal["row", "column", "row-reverse", "column-reverse"] + + +class RadioGroupItemLabel(Text): + """The label around an item that is given children.""" + + def add_style(self) -> dict[str, Any]: + """Lay the radio button and its text out in a row. + + Returns: + The styles Radix Themes gives the label of an item. + """ + return RADIO_GROUP_ITEM + + +class RadioGroupItemInner(UIComponent): + """The children of an item, beside its radio button.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = RADIO_GROUP_ITEM_INNER + + +class RadioGroupItem(UIComponent): + """An item in the group that can be checked.""" + + tag = "input" + + styles: ClassVar[ComponentStyles] = RADIO + + value: Var[str] = field( + doc="The value of the radio item to check. Should be used in conjunction with on_change." + ) + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the radio item." + ) + + required: Var[bool] = field( + doc="When true, indicates that the user must check the radio item before the owning form can be submitted." + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create an item: a radio button, in a label when it has children. + + Args: + *children: What is shown beside the radio button. + **props: The props of the item. With children, its styles are + those of the label. + + Returns: + The radio button, or the label that holds it. + """ + if not children: + return super().create(**props) + fields = cls.get_fields() + triggers = cls.get_event_triggers() + own = { + key: props.pop(key) + for key in list(props) + if key in fields + or key in triggers + or key.startswith(("on_", "aria_", "data_")) + } + return RadioGroupItemLabel.create( + super().create(**own), + RadioGroupItemInner.create(*children), + as_="label", + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the item, with the look of a group of its own. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as variants, and the attributes the + # group gives its items: both are set by the group around the item. + self._size: Any = None + self._variant: Any = None + self._high_contrast: Any = None + self._group: dict[str, Any] = {} + super()._post_init(*args, **kwargs) + + def _join(self, group: RadioGroupRoot) -> None: + """Take from a group what Radix hands its items through a context. + + Args: + group: The group the item is in. + """ + self._size = group.size + self._variant = group.variant + self._high_contrast = group.high_contrast + attributes: dict[str, Any] = {"name": group._name} + disabled = either(group.disabled, self.disabled) + if disabled is not None: + attributes["disabled"] = disabled + required = either(group.required, self.required) + if required is not None: + attributes["required"] = required + if group.value is not None: + # An input React keeps checked says who changes it: the group. + attributes["checked"] = is_value(group.value, self.value) + attributes["read_only"] = True + elif group.default_value is not None: + checked = is_value(group.default_value, self.value) + if checked is not False: + attributes["default_checked"] = checked + self._group = attributes + self._merge_styles() + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the item, those its group gives it 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) + for value in self._group.values(): + if isinstance(value, Var): + yield value + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the radio button. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the type of the input and what its group gives it. + """ + return super()._render(props).add_props(type="radio", **self._group) + + +class RadioGroupRoot(UIComponent): + """A set of interactive radio buttons where only one can be selected at a time.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = RADIO_GROUP + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + default=LiteralVar.create("2"), + doc='The size of the radio group: "1" | "2" | "3"', + ) + + variant: Var[Literal["classic", "surface", "soft"]] = field( + default=LiteralVar.create("classic"), doc="The variant of the radio group" + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="The color of the radio group") + + high_contrast: Var[bool] = field( + doc="Whether to render the radio group with higher contrast color against background" + ) + + value: Var[str] = field( + doc="The controlled value of the radio item to check. Should be used in conjunction with on_change." + ) + + default_value: Var[str] = field( + doc="The initial value of checked radio item. Should be used in conjunction with on_change." + ) + + disabled: Var[bool] = field(doc="Whether the radio group is disabled") + + name: Var[str] = field( + doc="The name of the group. Submitted with its owning form as part of a name/value pair." + ) + + required: Var[bool] = field(doc="Whether the radio group is required") + + on_change: EventHandler[input_event] = field( + doc="Fired when the value of the radio group changes." + ) + + def _post_init(self, *args, **kwargs): + """Initialize the group, and give its items what they share. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + # The browser takes radio buttons for a group by their name. + self._name = group_name(self.name, "radio") + for label in descendants(self, RadioGroupItemLabel, RadioGroupRoot): + label.size = self.size + label._merge_styles() + for item in descendants(self, RadioGroupItem, RadioGroupRoot): + item._join(self) + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the items off the element. + + Returns: + The props read as styles, and what the group hands its items. + """ + return [ + *super()._exclude_props(), + "size", + "variant", + "high_contrast", + "value", + "default_value", + "disabled", + "name", + "required", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the group. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role of a group of radio buttons and whether + one of them has to be checked. + """ + tag = super()._render(props).add_props(role="radiogroup") + if self.required is not None and literal(self.required) is not False: + tag = tag.add_props(**{"aria-required": self.required}) + return tag + + +class HighLevelRadioGroup(UIComponent): + """High level wrapper for the RadioGroup component.""" + + items: Var[Sequence[str]] = field(doc="The items of the radio group.") + + direction: Var[LiteralFlexDirection] = field( + default=LiteralVar.create("row"), doc="The direction of the radio group." + ) + + spacing: Var[LiteralSpacing] = field( + default=LiteralVar.create("2"), + doc="The gap between the items of the radio group.", + ) + + size: Var[Literal["1", "2", "3"]] = field( + default=LiteralVar.create("2"), doc="The size of the radio group." + ) + + variant: Var[Literal["classic", "surface", "soft"]] = field( + default=LiteralVar.create("classic"), doc="The variant of the radio group" + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="The color of the radio group") + + high_contrast: Var[bool] = field( + doc="Whether to render the radio group with higher contrast color against background" + ) + + value: Var[str] = field( + doc="The controlled value of the radio item to check. Should be used in conjunction with on_change." + ) + + default_value: Var[str] = field( + doc="The initial value of checked radio item. Should be used in conjunction with on_change." + ) + + disabled: Var[bool] = field(doc="Whether the radio group is disabled") + + name: Var[str] = field( + doc="The name of the group. Submitted with its owning form as part of a name/value pair." + ) + + required: Var[bool] = field(doc="Whether the radio group is required") + + @classmethod + def create( + cls, + items: Var[Sequence[str | int | float | list | dict | bool | None]], + **props, + ) -> Component: + """Create a radio group component. + + Args: + items: The items of the radio group. + **props: Additional properties to apply to the accordion item. + + Returns: + The created radio group component. + + Raises: + TypeError: If the type of items is invalid. + """ + direction = props.pop("direction", "row") + spacing = props.pop("spacing", "2") + size = props.pop("size", "2") + variant = props.pop("variant", "classic") + color_scheme = props.pop("color_scheme", None) + default_value = props.pop("default_value", "") + + if not isinstance(items, (list, Var)) or ( + isinstance(items, Var) + and not types.typehint_issubclass(items._var_type, list) + ): + items_type = type(items) if not isinstance(items, Var) else items._var_type + msg = f"The radio group component takes in a list, got {items_type} instead" + raise TypeError(msg) + + default_value = LiteralVar.create(default_value) + + # convert only non-strings to json(JSON.stringify) so quotes are not rendered + # for string literal types. + if isinstance(default_value, str) or ( + isinstance(default_value, Var) and default_value._var_type is str + ): + default_value = LiteralVar.create(default_value) + else: + default_value = LiteralVar.create(default_value).to_string() + + def radio_group_item(value: Var) -> Component: + item_value = cond( + value.js_type() == "string", + value, + value.to_string(), + ).to(StringVar) + + return Text.create( + Flex.create( + RadioGroupItem.create( + value=item_value, + disabled=props.get("disabled", LiteralVar.create(False)), + ), + item_value, + spacing="2", + ), + size=size, + as_="label", + ) + + children = [ + foreach( + items, + radio_group_item, + ) + ] + + return RadioGroupRoot.create( + Flex.create( + *children, + direction=direction, + spacing=spacing, + ), + size=size, + variant=variant, + color_scheme=color_scheme, + default_value=default_value, + **props, + ) + + +class RadioGroup(ComponentNamespace): + """RadioGroup components namespace.""" + + root = staticmethod(RadioGroupRoot.create) + item = staticmethod(RadioGroupItem.create) + __call__ = staticmethod(HighLevelRadioGroup.create) + + +radio = radio_group = RadioGroup() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py new file mode 100644 index 00000000000..0330c682e01 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py @@ -0,0 +1,152 @@ +"""The look of a radio button and of a group of them.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.control import DISABLED, FOCUS, FOCUS_RING, RESET + +accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black + +_SIZE = "--radio-size" + +_CHECKED_ENABLED = f":checked:not({DISABLED})" + + +def _look(variant: str, high_contrast: bool) -> dict[str, Any]: + """Make the circle and the dot of one variant. + + Args: + variant: The variant. + high_contrast: Whether the radio button is high contrast. + + Returns: + The styles of the two pseudo-elements, for every state of the input. + """ + fill = accent[12] if high_contrast else accent.indicator + dot = accent[1] if high_contrast else accent.contrast + if variant == "surface": + circle: dict[str, Any] = { + "background_color": { + "default": tokens.color.surface, + _CHECKED_ENABLED: fill, + DISABLED: gray.a[3], + }, + "box_shadow": { + "default": f"inset 0 0 0 1px {gray.a[7]}", + _CHECKED_ENABLED: "none", + DISABLED: f"inset 0 0 0 1px {gray.a[6]}", + }, + } + elif variant == "classic": + circle = { + "background_color": { + "default": tokens.color.surface, + _CHECKED_ENABLED: fill, + DISABLED: gray.a[3], + }, + "background_image": { + "default": "none", + _CHECKED_ENABLED: ( + f"linear-gradient(to bottom, {white.a[3]}, transparent, " + f"{black.a[3]})" + ), + }, + "box_shadow": { + "default": f"inset 0 0 0 1px {gray[7]}, {tokens.shadow[1]}", + _CHECKED_ENABLED: ( + f"inset 0 0.5px 0.5px {white.a[4]}, " + f"inset 0 -0.5px 0.5px {black.a[4]}" + ), + DISABLED: tokens.shadow[1], + }, + } + else: + circle = { + "background_color": {"default": accent.a[4], DISABLED: gray.a[3]}, + # A gray ring for a gray radio button. + "outline_color": {FOCUS: accent.a[8]}, + } + dot = accent[12] if high_contrast else accent.a[11] + return { + "_before": circle, + "_after": {"background_color": {"default": dot, DISABLED: gray.a[8]}}, + } + + +_VARIANTS = ("classic", "surface", "soft") + +# A radio button. Its group says how it looks, so the variants are not props. +RADIO: ComponentStyles = { + "base": unchecked({ + **RESET, + "position": "relative", + "display": "inline-flex", + "align_items": "center", + "justify_content": "center", + "vertical_align": "top", + "flex_shrink": 0, + "cursor": {"default": tokens.cursor.radio, DISABLED: tokens.cursor.disabled}, + # In a line of text it is as high as the line. + "height": f"var(--line-height, var({_SIZE}))", + "_before": { + "content": "''", + "display": "block", + "height": f"var({_SIZE})", + "width": f"var({_SIZE})", + "border_radius": "100%", + FOCUS: FOCUS_RING, + }, + # The dot: as large as the circle and scaled down, which places it + # on a part of a pixel. + "_after": { + ":checked": {"content": "''"}, + "pointer_events": "none", + "position": "absolute", + "height": f"var({_SIZE})", + "width": f"var({_SIZE})", + "border_radius": "100%", + "transform": "scale(0.4)", + }, + }), + "variants": { + "_size": { + "1": unchecked({_SIZE: f"calc({tokens.space[4]} * 0.875)"}), + "2": unchecked({_SIZE: tokens.space[4]}), + "3": unchecked({_SIZE: f"calc({tokens.space[4]} * 1.25)"}), + }, + "_variant": { + variant: unchecked(_look(variant, False)) for variant in _VARIANTS + }, + }, + "defaults": {"_size": "2", "_variant": "surface"}, + "compound": [ + { + "props": {"_variant": variant, "_high_contrast": "true"}, + "style": unchecked(_look(variant, True)), + } + for variant in _VARIANTS + ], +} + +RADIO_GROUP: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "display": "flex", + "flex_direction": "column", + "gap": tokens.space[1], + }, +} + +# The label Radix Themes puts an item with children in: no wider than its +# text, so that the space beside it does not check the item. +RADIO_GROUP_ITEM: dict[str, Any] = { + "display": "flex", + "gap": "0.5em", + "width": "fit-content", +} + +# What is beside the radio button of such an item: text that may be cut off. +RADIO_GROUP_ITEM_INNER: ComponentStyles = {"base": {"min_width": 0}} diff --git a/tests/units/reflex_components_ui/components/test_radio_group.py b/tests/units/reflex_components_ui/components/test_radio_group.py new file mode 100644 index 00000000000..f5d96d37aba --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_radio_group.py @@ -0,0 +1,683 @@ +"""Tests for reflex_components_ui.components.radio_group.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.components import _group +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +class RadioState(rx.State): + """What a radio group is bound to.""" + + picked: str = "a" + sizes: list[str] = ["s", "m"] + + @rx.event + def pick(self, picked: str): + """Follow the group. + + Args: + picked: The value of the checked item. + """ + self.picked = picked + + +def test_radio_group_from_parts( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The items of a group are native radio buttons with its name, its look and its state; one with children is in a label.""" + component = rx.ui.radio.root( + rx.ui.radio.item("One", value="1", id="one", margin="1px"), + rx.ui.radio.item(value="2", disabled=True), + rx.el.div(rx.ui.radio.item(value="3")), + default_value="2", + name="pick", + size="3", + variant="soft", + high_contrast=True, + color_scheme="ruby", + id="group", + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_a088d40a93_c + " " + reflexUIClasses_e201574881', + 'id:"group"', + "ref:ref_group", + 'role:"radiogroup"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_ab61f35f5f_c"], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_1929c3a89b_c", + 'id:"one"', + 'name:"pick"', + "ref:ref_one", + 'type:"radio"', + 'value:"1"', + ], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_1107ef58c5_c"], + "children": [{"contents": '"One"'}], + }, + ], + }, + { + "name": '"input"', + "props": [ + "className:sx_1929c3a89b_c", + "defaultChecked:true", + "disabled:true", + 'name:"pick"', + 'type:"radio"', + 'value:"2"', + ], + "children": [], + }, + { + "name": '"div"', + "props": [], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_1929c3a89b_c", + 'name:"pick"', + 'type:"radio"', + 'value:"3"', + ], + "children": [], + } + ], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + }, + { + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-3)", + "--line-height": "var(--line-height-3)", + "--letter-spacing": "var(--letter-spacing-3)", + "WebkitTapHighlightColor": {"@media (pointer: coarse)": "transparent"}, + "outlineWidth": {"@media (pointer: coarse)": {":active": "0.75em"}}, + "outlineStyle": {"@media (pointer: coarse)": {":active": "solid"}}, + "outlineColor": {"@media (pointer: coarse)": {":active": "var(--gray-a4)"}}, + "outlineOffset": {"@media (pointer: coarse)": {":active": "-0.6em"}}, + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--accent-a4)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--accent-a8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-radio)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--radio-size))", + "::before": "var(--radio-size)", + "::after": "var(--radio-size)", + }, + "content": {"::before": "''", "::after": {":checked": "''"}}, + "width": {"::before": "var(--radio-size)", "::after": "var(--radio-size)"}, + "borderTopLeftRadius": {"::before": "100%", "::after": "100%"}, + "borderTopRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomLeftRadius": {"::before": "100%", "::after": "100%"}, + "pointerEvents": {"::after": "none"}, + "transform": {"::after": "scale(0.4)"}, + "--radio-size": "calc(var(--space-4) * 1.25)", + }, + {"minWidth": 0}, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--accent-a4)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--accent-a8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-radio)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--radio-size))", + "::before": "var(--radio-size)", + "::after": "var(--radio-size)", + }, + "content": {"::before": "''", "::after": {":checked": "''"}}, + "width": {"::before": "var(--radio-size)", "::after": "var(--radio-size)"}, + "borderTopLeftRadius": {"::before": "100%", "::after": "100%"}, + "borderTopRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomLeftRadius": {"::before": "100%", "::after": "100%"}, + "pointerEvents": {"::after": "none"}, + "transform": {"::after": "scale(0.4)"}, + "--radio-size": "calc(var(--space-4) * 1.25)", + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--accent-a4)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--accent-a8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-radio)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--radio-size))", + "::before": "var(--radio-size)", + "::after": "var(--radio-size)", + }, + "content": {"::before": "''", "::after": {":checked": "''"}}, + "width": {"::before": "var(--radio-size)", "::after": "var(--radio-size)"}, + "borderTopLeftRadius": {"::before": "100%", "::after": "100%"}, + "borderTopRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomLeftRadius": {"::before": "100%", "::after": "100%"}, + "pointerEvents": {"::after": "none"}, + "transform": {"::after": "scale(0.4)"}, + "--radio-size": "calc(var(--space-4) * 1.25)", + }, + ] + + +def test_radio_group_classic( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The classic variant, which a group has unless it is given another.""" + component = rx.ui.radio.root(rx.ui.radio.item(value="1"), name="pick") + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":checked:not(:disabled)": "var(--accent-indicator)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": { + "default": "none", + "::before": { + "default": "none", + ":checked:not(:disabled)": "linear-gradient(to bottom, var(--white-a3), transparent, var(--black-a3))", + }, + }, + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-radio)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--radio-size))", + "::before": "var(--radio-size)", + "::after": "var(--radio-size)", + }, + "content": {"::before": "''", "::after": {":checked": "''"}}, + "width": {"::before": "var(--radio-size)", "::after": "var(--radio-size)"}, + "borderTopLeftRadius": {"::before": "100%", "::after": "100%"}, + "borderTopRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomRightRadius": {"::before": "100%", "::after": "100%"}, + "borderBottomLeftRadius": {"::before": "100%", "::after": "100%"}, + "pointerEvents": {"::after": "none"}, + "transform": {"::after": "scale(0.4)"}, + "--radio-size": "var(--space-4)", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-7), var(--shadow-1)", + ":checked:not(:disabled)": "inset 0 0.5px 0.5px var(--white-a4), inset 0 -0.5px 0.5px var(--black-a4)", + ":disabled": "var(--shadow-1)", + } + }, + }, + ] + + +def test_radio_group_required_and_disabled( + ui_plugin: UIPlugin, +): + """A group that is required or disabled says so on each of its items, and to the accessibility tree.""" + component = rx.ui.radio_group.root( + rx.ui.radio_group.item(value="1"), + rx.ui.radio_group.item(value="2", required=False, disabled=False), + name="pick", + required=True, + disabled=True, + ) + assert component.render() == { + "name": '"div"', + "props": [ + '"aria-required":true', + "className:sx_a088d40a93_c", + 'role:"radiogroup"', + ], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8f60d95144_c", + "disabled:true", + 'name:"pick"', + "required:true", + 'type:"radio"', + 'value:"1"', + ], + "children": [], + }, + { + "name": '"input"', + "props": [ + "className:sx_8f60d95144_c", + "disabled:true", + 'name:"pick"', + "required:true", + 'type:"radio"', + 'value:"2"', + ], + "children": [], + }, + ], + } + + +def test_radio_group_not_a_list(ui_plugin: UIPlugin): + """The items of a group are a list.""" + with pytest.raises(TypeError) as error: + rx.ui.radio("a") + assert ( + str(error.value) + == "The radio group component takes in a list, got instead" + ) + + +def test_radio_group_unknown_variant(ui_plugin: UIPlugin): + """A variant a group does not have is an error that lists the ones it has.""" + with pytest.raises(TypeError) as error: + rx.ui.radio.root(variant="solid") + assert ( + str(error.value) + == "Invalid var passed for prop RadioGroupRoot.variant, expected type typing.Literal['classic', 'surface', 'soft'], got value 'solid' of type ." + ) + + +def test_radio_group_bound_to_state(ui_plugin: UIPlugin): + """A bound group checks the item of its value, and a change hands over the value.""" + component = rx.ui.radio.root( + rx.ui.radio.item(value="a"), + rx.ui.radio.item(value="b"), + value=RadioState.picked, + on_change=RadioState.pick, + name="pick", + ) + state = ( + "tests___units___reflex_components_ui___components___test_radio_group" + "____radio_state" + ) + picked = f"reflex___state____state__{state}.picked_rx_state_" + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_a088d40a93_c", + ( + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.' + f'{state}.pick", ({{ ["picked"] : _e?.["target"]?.["value"] }}), ' + "({ })))], [_e], ({ }))))" + ), + 'role:"radiogroup"', + ], + "children": [ + { + "name": '"input"', + "props": [ + f'checked:({picked} === "{value}")', + "className:sx_8f60d95144_c", + 'name:"pick"', + "readOnly:true", + 'type:"radio"', + f'value:"{value}"', + ], + "children": [], + } + for value in ("a", "b") + ], + } + # The compiler finds the state an item reads through its group. + item = component.children[0] + assert [str(var) for var in item._get_vars()] == [ + '"a"', + '"pick"', + f'({picked} === "a")', + ] + + +def test_radio_group_without_a_name( + ui_plugin: UIPlugin, monkeypatch: pytest.MonkeyPatch +): + """Each group without a name is given one of its own: it is what groups its items.""" + monkeypatch.setattr(_group, "_names", itertools.count(7)) + names = [ + [item.render()["props"][1] for item in group.children] + for group in ( + rx.ui.radio.root(rx.ui.radio.item(value="1"), rx.ui.radio.item(value="2")), + rx.ui.radio.root(rx.ui.radio.item(value="1")), + ) + ] + assert names == [ + ['name:"rx-radio-7"', 'name:"rx-radio-7"'], + ['name:"rx-radio-8"'], + ] + + +def test_radio_group_inside_another(ui_plugin: UIPlugin): + """The items below another group are the ones of that group.""" + inner = rx.ui.radio.root(rx.ui.radio.item(value="1"), name="inner", size="1") + rx.ui.radio.root(rx.ui.radio.item(value="2"), inner, name="outer", size="3") + item = inner.children[0] + assert item._group == {"name": inner.name} + assert item._element_styles().style.style["--radio-size"] == ( + "calc(var(--space-4) * 0.875)" + ) + + +def test_radio_group_from_items(ui_plugin: UIPlugin): + """A list of items is a row of labels, each around a radio button of the group.""" + component = rx.ui.radio( + ["a", "b"], default_value="a", name="pick", direction="column", spacing="4" + ) + rendered = component.render() + items = rendered["children"][0]["children"][0] + items["iterable"] = str(items["iterable"]) + value = ( + '(((typeof(value_rx_state_))?.valueOf?.() === "string"?.valueOf?.()) ? ' + "value_rx_state_ : (JSON.stringify(value_rx_state_)))" + ) + index = "index_cb46f9c6d80243188763ec1eabe9a266" + assert rendered == { + "name": '"div"', + "props": ["className:sx_a088d40a93_c", 'role:"radiogroup"'], + "children": [ + { + "name": '"div"', + "props": ["className:sx_29f00bc870_c"], + "children": [ + { + "name": "", + "props": [], + "children": [ + { + "name": '"label"', + "props": ["className:sx_d1083f6dbf_c", f"key:{index}"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_1362d43b5f_c"], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8f60d95144_c", + f'defaultChecked:("a" === {value})', + "disabled:false", + 'name:"pick"', + 'type:"radio"', + f"value:{value}", + ], + "children": [], + }, + {"contents": value}, + ], + } + ], + } + ], + "iterable": '["a", "b"]', + "arg_var_name": "value_rx_state_", + "index_var_name": index, + "iterable_state": '["a", "b"]', + "arg_name": "value_rx_state_", + "arg_index": index, + } + ], + } + ], + } diff --git a/tests/units/reflex_components_ui/components/test_switch.py b/tests/units/reflex_components_ui/components/test_switch.py index 61132c97946..db66dc79e70 100644 --- a/tests/units/reflex_components_ui/components/test_switch.py +++ b/tests/units/reflex_components_ui/components/test_switch.py @@ -59,9 +59,7 @@ def test_switch( "backgroundImage": { "default": "none", "::before": { - "default": "linear-gradient(to right, " - "var(--accent-track) 40%, " - "transparent 60%)", + "default": "linear-gradient(to right, var(--accent-track) 40%, transparent 60%)", ":disabled": "none", }, }, @@ -99,10 +97,8 @@ def test_switch( }, "--switch-width": "calc(var(--switch-height) * 1.75)", "--switch-thumb-inset": "1px", - "--switch-thumb-size": "calc(var(--switch-height) - " - "var(--switch-thumb-inset) * 2)", - "--switch-thumb-translate-x": "calc(var(--switch-width) - " - "var(--switch-height))", + "--switch-thumb-size": "calc(var(--switch-height) - var(--switch-thumb-inset) * 2)", + "--switch-thumb-translate-x": "calc(var(--switch-width) - var(--switch-height))", "cursor": { ":disabled": "var(--cursor-disabled)", "::before": { @@ -120,8 +116,7 @@ def test_switch( }, "borderRadius": { "::before": "var(--switch-border-radius)", - "::after": "calc(var(--switch-border-radius) - " - "var(--switch-thumb-inset))", + "::after": "calc(var(--switch-border-radius) - var(--switch-thumb-inset))", }, "transitionProperty": { "::before": "background-position, background-color, box-shadow, filter", @@ -158,28 +153,15 @@ def test_switch( ":disabled": "inset 0 0 0 1px var(--gray-a3)", }, "::after": { - "default": "0 0 1px 1px var(--black-a2), 0 1px 1px " - "var(--black-a1), 0 2px 4px -1px " - "var(--black-a1)", - ":checked:not(:disabled)": "0 1px 3px " - "var(--black-a2), 0 2px " - "4px -1px " - "var(--black-a1), 0 0 0 " - "1px var(--black-a1), 0 " - "0 0 1px " - "var(--accent-a4), -1px " - "0 1px var(--black-a2)", + "default": "0 0 1px 1px var(--black-a2), 0 1px 1px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":checked:not(:disabled)": "0 1px 3px var(--black-a2), 0 2px 4px -1px var(--black-a1), 0 0 0 1px var(--black-a1), 0 0 0 1px var(--accent-a4), -1px 0 1px var(--black-a2)", ":disabled": "0 0 0 1px var(--gray-a2), 0 1px 3px var(--black-a1)", }, }, "filter": { "::before": { "default": "none", - ":checked:active:not(:disabled)": "var(--rx-if-light, " - "brightness(0.92) " - "saturate(1.1)) " - "var(--rx-if-dark, " - "brightness(1.08))", + ":checked:active:not(:disabled)": "var(--rx-if-light, brightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08))", } }, } @@ -207,8 +189,7 @@ def test_switch_classic_high_contrast( "name": '"input"', "props": [ "checked:true", - 'className:sx_7350a6aadb_c + " " + reflexUIClasses_e201574881 + " " ' - "+ reflexUIClasses_6d1e87c3d8", + 'className:sx_7350a6aadb_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', "disabled:true", "readOnly:true", "required:true", @@ -249,12 +230,7 @@ def test_switch_classic_high_contrast( "backgroundImage": { "default": "none", "::before": { - "default": "linear-gradient(to right, " - "light-dark(var(--black-a8), " - "transparent) 40%, transparent " - "60%), linear-gradient(to right, " - "var(--accent-track) 40%, " - "transparent 60%)", + "default": "linear-gradient(to right, light-dark(var(--black-a8), transparent) 40%, transparent 60%), linear-gradient(to right, var(--accent-track) 40%, transparent 60%)", ":disabled": "none", }, }, @@ -292,10 +268,8 @@ def test_switch_classic_high_contrast( }, "--switch-width": "calc(var(--switch-height) * 1.75)", "--switch-thumb-inset": "1px", - "--switch-thumb-size": "calc(var(--switch-height) - " - "var(--switch-thumb-inset) * 2)", - "--switch-thumb-translate-x": "calc(var(--switch-width) - " - "var(--switch-height))", + "--switch-thumb-size": "calc(var(--switch-height) - var(--switch-thumb-inset) * 2)", + "--switch-thumb-translate-x": "calc(var(--switch-width) - var(--switch-height))", "cursor": { ":disabled": "var(--cursor-disabled)", "::before": { @@ -313,8 +287,7 @@ def test_switch_classic_high_contrast( }, "borderRadius": { "::before": "var(--switch-border-radius)", - "::after": "calc(var(--switch-border-radius) - " - "var(--switch-thumb-inset))", + "::after": "calc(var(--switch-border-radius) - var(--switch-thumb-inset))", }, "transitionProperty": { "::before": "background-position, background-color, box-shadow, filter", @@ -349,27 +322,16 @@ def test_switch_classic_high_contrast( }, "--switch-border-radius": { "default": "max(var(--radius-1), var(--radius-thumb))", - "@media (min-width: 1024px)": "max(var(--radius-2), " - "var(--radius-thumb))", + "@media (min-width: 1024px)": "max(var(--radius-2), var(--radius-thumb))", }, "boxShadow": { "::before": { - "default": "inset 0 0 0 1px var(--gray-a3), inset " - "0 0 0 1px var(--black-a2), inset 0 " - "1.5px 2px 0 var(--black-a2)", + "default": "inset 0 0 0 1px var(--gray-a3), inset 0 0 0 1px var(--black-a2), inset 0 1.5px 2px 0 var(--black-a2)", ":disabled": "var(--shadow-1)", }, "::after": { - "default": "0 1px 3px var(--black-a3), 0 2px 4px " - "-1px var(--black-a1), 0 0 0 1px " - "var(--black-a2)", - ":checked:not(:disabled)": "0 1px 3px " - "var(--black-a2), 0 2px " - "4px -1px " - "var(--black-a1), 0 0 0 " - "1px var(--black-a2), " - "-1px 0 1px " - "var(--black-a2)", + "default": "0 1px 3px var(--black-a3), 0 2px 4px -1px var(--black-a1), 0 0 0 1px var(--black-a2)", + ":checked:not(:disabled)": "0 1px 3px var(--black-a2), 0 2px 4px -1px var(--black-a1), 0 0 0 1px var(--black-a2), -1px 0 1px var(--black-a2)", ":disabled": "0 0 0 1px var(--gray-a2), 0 1px 3px var(--black-a1)", }, }, @@ -377,12 +339,7 @@ def test_switch_classic_high_contrast( "filter": { "::before": { "default": "none", - ":checked:active:not(:disabled)": "var(--rx-if-light, " - "contrast(0.82) " - "saturate(1.2) " - "brightness(1.16)) " - "var(--rx-if-dark, " - "brightness(1.08))", + ":checked:active:not(:disabled)": "var(--rx-if-light, contrast(0.82) saturate(1.2) brightness(1.16)) var(--rx-if-dark, brightness(1.08))", } }, } @@ -427,18 +384,7 @@ def test_switch_soft( "backgroundImage": { "default": "none", "::before": { - "default": "linear-gradient(to right, " - "var(--accent-a4) 40%, " - "transparent 60%), " - "linear-gradient(to right, " - "var(--accent-a4) 40%, " - "transparent 60%), " - "linear-gradient(to right, " - "var(--accent-a4) 40%, " - "var(--white-a1) 60%), " - "linear-gradient(to right, " - "var(--gray-a2) 40%, " - "var(--gray-a3) 60%)", + "default": "linear-gradient(to right, var(--accent-a4) 40%, transparent 60%), linear-gradient(to right, var(--accent-a4) 40%, transparent 60%), linear-gradient(to right, var(--accent-a4) 40%, var(--white-a1) 60%), linear-gradient(to right, var(--gray-a2) 40%, var(--gray-a3) 60%)", ":disabled": "none", }, }, @@ -476,10 +422,8 @@ def test_switch_soft( }, "--switch-width": "calc(var(--switch-height) * 1.75)", "--switch-thumb-inset": "1px", - "--switch-thumb-size": "calc(var(--switch-height) - " - "var(--switch-thumb-inset) * 2)", - "--switch-thumb-translate-x": "calc(var(--switch-width) - " - "var(--switch-height))", + "--switch-thumb-size": "calc(var(--switch-height) - var(--switch-thumb-inset) * 2)", + "--switch-thumb-translate-x": "calc(var(--switch-width) - var(--switch-height))", "cursor": { ":disabled": "var(--cursor-disabled)", "::before": { @@ -497,8 +441,7 @@ def test_switch_soft( }, "borderRadius": { "::before": "var(--switch-border-radius)", - "::after": "calc(var(--switch-border-radius) - " - "var(--switch-thumb-inset))", + "::after": "calc(var(--switch-border-radius) - var(--switch-thumb-inset))", }, "transitionProperty": { "::before": "background-position, background-color, box-shadow, filter", @@ -531,17 +474,8 @@ def test_switch_soft( "--switch-border-radius": "max(var(--radius-2), var(--radius-thumb))", "boxShadow": { "::after": { - "default": "0 0 0 1px var(--black-a1), 0 1px 3px " - "var(--black-a1), 0 1px 3px " - "var(--black-a1), 0 2px 4px -1px " - "var(--black-a1)", - ":checked:not(:disabled)": "0 0 0 1px " - "var(--black-a1), 0 1px " - "3px var(--black-a2), 0 " - "1px 3px " - "var(--accent-a3), 0 " - "2px 4px -1px " - "var(--accent-a3)", + "default": "0 0 0 1px var(--black-a1), 0 1px 3px var(--black-a1), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":checked:not(:disabled)": "0 0 0 1px var(--black-a1), 0 1px 3px var(--black-a2), 0 1px 3px var(--accent-a3), 0 2px 4px -1px var(--accent-a3)", ":disabled": "0 0 0 1px var(--gray-a2), 0 1px 3px var(--black-a1)", } }, diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index f7b727b1291..34952b0eb44 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -137,6 +137,12 @@ def test_every_wave_is_in_the_namespace(): "list_item", "ordered_list", "progress", + "radio", + "radio.item", + "radio.root", + "radio_group", + "radio_group.item", + "radio_group.root", "scroll_area", "section", "separator", @@ -164,7 +170,19 @@ def test_every_wave_is_in_the_namespace(): ] -@pytest.mark.parametrize("namespace", ["callout", "data_list", "list", "table", "text"]) +@pytest.mark.parametrize( + "namespace", + [ + "callout", + "checkbox", + "data_list", + "list", + "radio", + "radio_group", + "table", + "text", + ], +) def test_namespace_has_the_members_of_its_radix_counterpart(namespace: str): assert members(getattr(reflex_components_ui, namespace)) == members( getattr(rx, namespace) From e06e1285ebc37d8bb3ee00438a7bada438c88e47 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 01:15:14 +0000 Subject: [PATCH 071/204] Add rx.ui.checkbox_group, on the group machinery the radio group shares A root finds its items while compiling and gives them their name, look and state. The values a change hands over are read from the checkboxes. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../parity/allowlist.toml | 32 + .../ui_parity/components/checkbox_group.py | 315 ++++++++ .../ui_parity/components/radio_group.py | 1 + .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/_group.py | 207 ++++- .../components/checkbox_group.py | 174 +++++ .../components/radio_group.py | 160 +--- .../reflex_components_ui/styles/checkbox.py | 148 ++-- .../reflex_components_ui/styles/control.py | 23 + .../src/reflex_components_ui/styles/radio.py | 20 - .../components/test_checkbox.py | 131 +--- .../components/test_checkbox_group.py | 713 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 2 + 13 files changed, 1565 insertions(+), 362 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.py create mode 100644 tests/units/reflex_components_ui/components/test_checkbox_group.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 1bbfdf549e6..3bdf3e4ff99 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -115,3 +115,35 @@ reason = "The items of rx.radio_group are buttons that JavaScript turns into rad component = "radio_group" step = "Enter on a radio button does not submit its form" reason = "The items of rx.ui.radio_group are native inputs, and the browser submits a form when Enter is pressed in one of its inputs, a radio button included. rx.radio_group swallows the key. Space and the arrow keys check an item in both." + +[[look]] +component = "checkbox_group" +check = "a11y" +reason = "A checked item of rx.checkbox_group holds its check as an image without a name. An item of rx.ui.checkbox_group is one native input: its check is drawn by its styles and is nothing to the accessibility tree." + +[[contract]] +component = "checkbox_group" +step = "checks its items with JavaScript disabled" +system = "rx" +reason = "The items of rx.checkbox_group are buttons that JavaScript turns into checkboxes: until it has run, a click does nothing. The items of rx.ui.checkbox_group are native checkboxes, which a click checks with or without JavaScript." + +[[contract]] +component = "checkbox_group" +step = "Tab stops once in each group" +reason = "The items of rx.ui.checkbox_group are native checkboxes, and Tab stops on each of them, as it does on every checkbox of a page. rx.checkbox_group takes one stop for the whole group and moves through it with the arrow keys." + +[[contract]] +component = "checkbox_group" +step = "the arrow keys move through a group" +reason = "The browser does not move between checkboxes with the arrow keys: in rx.ui.checkbox_group Tab and Shift+Tab do, and `orientation`, `loop` and the direction of `dir` for the arrow keys have nothing to say. rx.checkbox_group moves the focus with the arrow keys." + +[[contract]] +component = "checkbox_group" +step = "Tab reaches every checkbox that is not disabled" +system = "rx" +reason = "rx.checkbox_group takes one Tab stop for the whole group. In rx.ui.checkbox_group every checkbox is a stop, as native checkboxes are." + +[[contract]] +component = "checkbox_group" +step = "hands over the checked values in the order they were checked in" +reason = "`on_value_change` of rx.ui.checkbox_group hands over the values of the checked items in the order of the items, whatever the order they were checked in: the group keeps no state of its own and reads its checkboxes. rx.checkbox_group appends each value as it is checked." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py new file mode 100644 index 00000000000..4c8e2c32ed4 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py @@ -0,0 +1,315 @@ +"""The checkbox group: every variant, size and state of its items, and its values.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, focused, wait_for_text + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +# The first checkbox of the group: a button of Radix, an input here. +TARGET = ("button", "input") + + +def _group(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a checkbox group from its parts. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the root. + + Returns: + The group: an item with text, a disabled one, and one alone. + """ + return namespace.checkbox_group.root( + namespace.checkbox_group.item("One", value="1"), + namespace.checkbox_group.item("Two", value="2", disabled=True), + namespace.checkbox_group.item(value="3"), + **props, + ) + + +MATRIX = Matrix( + component="checkbox_group", + render=_group, + base={"default_value": ["1"]}, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "default_value": {"none": [], "all": ["1", "2", "3"]}, + "color_scheme": ACCENTS, + "high_contrast": [True], + "disabled": [True], + "appearance": [DARK], + "state": STATES, + }, + groups=[ + { + "variant": VARIANTS, + "default_value": {"all": ["1", "2", "3"]}, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "disabled": [True], "appearance": [LIGHT, DARK]}, + {"variant": VARIANTS, "state": STATES}, + ], + stage=(160, 110), + crop="stage", + target=TARGET, + # Not held to zero, for the check alone, as the matrix of the checkbox + # is not: it is a mask here and an svg element in Radix Themes. + # At the default threshold 3 of the 74 cells differ, by at most 6 pixels + # of 17600. + tolerance=0.0005, +) + + +class CheckboxGroupState(rx.State): + """What the checkbox groups of the contract are bound to.""" + + bound: list[str] = ["a"] + seen: list[list[str]] = [] + submitted: dict[str, Any] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, values: list[str]): + """Follow the bound group. + + Args: + values: The values of its checked items. + """ + self.bound = values + + @rx.event + def see(self, values: list[str]): + """Keep what a change handed over. + + Args: + values: The values of the checked items. + """ + self.seen.append(values) + + @rx.event + def pick_last(self): + """Change the bound value from outside the group.""" + self.bound = ["c"] + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +def _items(namespace: Any, *values: str) -> list[Any]: + """Create the items of a group, each with its value as its text. + + Args: + namespace: ``rx`` or ``rx.ui``. + *values: The value of each item. + + Returns: + The items. + """ + return [namespace.checkbox_group.item(value, value=value) for value in values] + + +CONTRACT = Contract( + component="checkbox_group", + render=lambda namespace: namespace.box( + rx.el.div( + namespace.checkbox_group.root( + *_items(namespace, "One", "Two", "Three"), + on_value_change=CheckboxGroupState.see, + ), + id="pick", + ), + rx.el.div( + namespace.checkbox_group.root( + namespace.checkbox_group.item("Red", value="red"), + namespace.checkbox_group.item("Green", value="green", disabled=True), + namespace.checkbox_group.item("Blue", value="blue"), + default_value=["red"], + ), + id="colors", + ), + rx.el.div( + namespace.checkbox_group.root( + *_items(namespace, "a", "b", "c"), + value=CheckboxGroupState.bound, + on_value_change=CheckboxGroupState.set_bound, + ), + id="bound", + ), + rx.el.button("Last", id="last", on_click=CheckboxGroupState.pick_last), + rx.el.div( + namespace.checkbox_group.root(*_items(namespace, "x", "y"), disabled=True), + id="off", + ), + rx.el.form( + namespace.checkbox_group.root( + *_items(namespace, "s", "m", "l"), name="size", default_value=["m"] + ), + rx.el.button("Send", id="send", type="submit"), + on_submit=CheckboxGroupState.submit, + id="form", + ), + rx.el.span(CheckboxGroupState.seen.to_string(), id="seen"), + rx.el.span(CheckboxGroupState.bound.to_string(), id="bound-value"), + rx.el.span(CheckboxGroupState.submitted.to_string(), id="submitted"), + rx.el.span(CheckboxGroupState.submissions.to_string(), id="submissions"), + ), +) + +# The text of the checked checkboxes of a group, by the id of its frame. +CHECKED = ( + "id => [...document.getElementById(id).querySelectorAll('label')]" + ".filter(label => label.querySelector(':checked, [aria-checked=true]'))" + ".map(label => label.textContent)" +) +# How long a step that one system is known not to pass waits, in milliseconds. +QUICK = 3000 +# The text of the item that has the focus. +FOCUSED_ITEM = "document.activeElement.closest('label')?.textContent" + + +def _wait_for_checked(run: Run, group: str, items: list[str]) -> None: + """Wait until the checked items of a group are the ones expected. + + Args: + run: The run, on a page. + group: The id of the frame of the group. + items: The text of each item that is to be checked. + """ + run.page.wait_for_function( + f"([id, items]) => ({CHECKED})(id).join() === items", + arg=[group, ",".join(items)], + ) + + +@CONTRACT.step("its items are in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("pick").text == "OneTwoThree" + assert run.server.element("colors").text == "RedGreenBlue" + + +@CONTRACT.step("checks its items with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(QUICK) + page.locator("#pick").get_by_text("Two").click() + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Two", "Three"]) + _wait_for_checked(run, "colors", ["Red"]) + _wait_for_checked(run, "form", ["m"]) + + +@CONTRACT.step("has the roles, the names and the states of a group of checkboxes") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("group").count() == 5 + pick = page.locator("#pick") + assert pick.get_by_role("checkbox").count() == 3 + assert not pick.get_by_role("checkbox", name="One").is_checked() + colors = page.locator("#colors") + assert colors.get_by_role("checkbox", name="Red", checked=True).count() == 1 + assert colors.get_by_role("checkbox", name="Green", disabled=True).count() == 1 + assert page.locator("#off").get_by_role("checkbox", disabled=True).count() == 2 + + +@CONTRACT.step("Tab stops once in each group") +def _tab(run: Run) -> None: + page = run.page + stops = [] + for _ in range(4): + page.keyboard.press("Tab") + stops.append(page.evaluate(FOCUSED_ITEM) or focused(page)) + assert stops == ["One", "Red", "a", "last"] + + +@CONTRACT.step("the arrow keys move through a group") +def _arrows(run: Run) -> None: + page = run.page + page.set_default_timeout(QUICK) + page.keyboard.press("Tab") + for key, item in ( + ("ArrowDown", "Two"), + ("ArrowRight", "Three"), + ("ArrowUp", "Two"), + ): + page.keyboard.press(key, delay=60) + page.wait_for_function(f"{FOCUSED_ITEM} === '{item}'") + _wait_for_checked(run, "pick", []) + + +@CONTRACT.step("Tab reaches every checkbox that is not disabled") +def _tab_each(run: Run) -> None: + page = run.page + stops = [] + for _ in range(6): + page.keyboard.press("Tab") + stops.append(page.evaluate(FOCUSED_ITEM) or focused(page)) + assert stops == ["One", "Two", "Three", "Red", "Blue", "a"] + + +@CONTRACT.step("Space and a click on a label check and uncheck an item, and say so") +def _check(run: Run) -> None: + page = run.page + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + page.keyboard.press("Space") + _wait_for_checked(run, "pick", []) + page.locator("#pick").get_by_text("One").click() + _wait_for_checked(run, "pick", ["One"]) + wait_for_text(page, "seen", '[["Three"],[],["One"]]') + + +@CONTRACT.step("hands over the checked values in the order they were checked in") +def _order(run: Run) -> None: + page = run.page + page.set_default_timeout(QUICK) + page.locator("#pick").get_by_text("Three").click() + page.locator("#pick").get_by_text("One").click() + wait_for_text(page, "seen", '[["Three"],["Three","One"]]') + + +@CONTRACT.step("a disabled group and a disabled item are not checked") +def _disabled(run: Run) -> None: + page = run.page + page.locator("#off").get_by_text("x").click(force=True) + page.locator("#colors").get_by_text("Green").click(force=True) + page.locator("#colors").get_by_text("Blue").click() + _wait_for_checked(run, "colors", ["Red", "Blue"]) + _wait_for_checked(run, "off", []) + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + _wait_for_checked(run, "bound", ["a"]) + page.locator("#bound").get_by_text("b").click() + wait_for_text(page, "bound-value", '["a","b"]') + _wait_for_checked(run, "bound", ["a", "b"]) + page.locator("#last").click() + wait_for_text(page, "bound-value", '["c"]') + _wait_for_checked(run, "bound", ["c"]) + + +@CONTRACT.step("submits with a form") +def _submit(run: Run) -> None: + page = run.page + page.locator("#form").get_by_text("l").click() + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + # A form of Reflex keeps one value of each name: the last one. + assert page.locator("#submitted").text_content() == '{"size":"l"}' diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py index f311731a076..5bfcfd4e947 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py @@ -194,6 +194,7 @@ def _server_render(run: Run) -> None: @CONTRACT.step("checks one item of a group with JavaScript disabled", on=NO_JAVASCRIPT) def _without_javascript(run: Run) -> None: page = run.page + page.set_default_timeout(3000) page.locator("#pick").get_by_text("Two").click() _wait_for_checked(run, "pick", ["Two"]) page.locator("#pick").get_by_text("Three").click() 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 90265db519c..d051b9a0e31 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -14,6 +14,7 @@ "components.callout": ["callout"], "components.card": ["card"], "components.checkbox": ["checkbox"], + "components.checkbox_group": ["checkbox_group"], "components.data_list": ["data_list"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py index 457e685d870..e3ccbe61ecc 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py @@ -4,11 +4,17 @@ import itertools from collections.abc import Iterator -from typing import Any, TypeVar +from typing import Any, ClassVar, TypeVar -from reflex_base.components.component import BaseComponent +from reflex_base.components.component import BaseComponent, Component +from reflex_base.components.tags import CommonTag from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_components_ui.base import UIComponent +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.control import GROUP_ITEM, GROUP_ITEM_INNER +from reflex_components_ui.typography.text import Text + T = TypeVar("T") # Numbers the groups that are given no name of their own. @@ -33,24 +39,182 @@ def group_name(name: Var | None, kind: str) -> Var: return LiteralVar.create(f"rx-{kind}-{next(_names)}") -def descendants( - component: BaseComponent, kind: type[T], group: type | tuple[type, ...] -) -> Iterator[T]: +class GroupRoot(UIComponent): + """The root of a group of inputs, which says how its items look and are. + + Radix hands the items of a group its props through a context. Here the + root finds its items while compiling, below it at any depth, and gives + them what they render: nothing is looked up in the browser. An item that + is not below its root in the tree a page is built from, such as one a + memoized component renders, has the look of a group without props. + """ + + def _post_init(self, *args, **kwargs): + """Initialize the group, and give its items what they share. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + self._bind() + # The size Radix Themes gives a group that is not given one. + size = getattr(self, "size", None) + if size is None: + size = LiteralVar.create("2") + for label in descendants(self, GroupItemLabel): + label.size = size + label._merge_styles() + for item in descendants(self, GroupInput): + item._join(self) + + def _bind(self) -> None: + """Work out what the items of the group are given, before they join.""" + + +def descendants(component: BaseComponent, kind: type[T]) -> Iterator[T]: """Find the items of a group below its root, at any depth. Args: component: The root of the group, or what is searched below it. kind: The class of the items. - group: The class of a root: what is below another one is its own. Yields: - Each item, in the order of the tree. + Each item, in the order of the tree. What is below the root of + another group is the business of that group. """ for child in component.children: if isinstance(child, kind): yield child - if not isinstance(child, group): - yield from descendants(child, kind, group) + if not isinstance(child, GroupRoot): + yield from descendants(child, kind) + + +class GroupItemLabel(Text): + """The label around an item of a group that is given children.""" + + def add_style(self) -> dict[str, Any]: + """Lay the input and its text out in a row. + + Returns: + The styles Radix Themes gives the label of an item. + """ + return GROUP_ITEM + + +class GroupItemInner(UIComponent): + """The children of an item of a group, beside its input.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = GROUP_ITEM_INNER + + +class GroupInput(UIComponent): + """An item of a group: a native input its group gives a look and a state.""" + + tag = "input" + + # The type of the input. + _type: ClassVar[str] + + @classmethod + def create(cls, *children, **props) -> Component: + """Create an item: an input, in a label when it has children. + + Args: + *children: What is shown beside the input. + **props: The props of the item. With children, its styles are + those of the label. + + Returns: + The input, or the label that holds it. + """ + if not children: + return super().create(**props) + fields = cls.get_fields() + own = { + key: props.pop(key) + for key in list(props) + if key in fields or key.startswith(("on_", "aria_", "data_")) + } + return GroupItemLabel.create( + super().create(**own), + GroupItemInner.create(*children), + as_="label", + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the item, with the look of a group without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as variants, and the attributes the + # group gives its items: both are set by the group around the item. + self._size: Any = None + self._variant: Any = None + self._high_contrast: Any = None + self._group: dict[str, Any] = {} + super()._post_init(*args, **kwargs) + + def _join(self, group: Any) -> None: + """Take from a group what Radix hands its items through a context. + + Args: + group: The group the item is in. + """ + self._size = group.size + self._variant = group.variant + self._high_contrast = group.high_contrast + attributes: dict[str, Any] = {"name": group._name} + disabled = either(group.disabled, getattr(self, "disabled", None)) + if disabled is not None: + attributes["disabled"] = disabled + required = either(group.required, getattr(self, "required", None)) + if required is not None: + attributes["required"] = required + value = getattr(self, "value", None) + if group.value is not None: + # An input React keeps checked says who changes it: the group. + attributes["checked"] = group._holds(group.value, value) + attributes["read_only"] = True + elif group.default_value is not None: + checked = group._holds(group.default_value, value) + if checked is not False: + attributes["default_checked"] = checked + self._group = attributes + self._merge_styles() + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the item, those its group gives it 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) + for value in self._group.values(): + if isinstance(value, Var): + yield value + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the input. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the type of the input and what its group gives it. + """ + return super()._render(props).add_props(type=self._type, **self._group) def literal(value: Any) -> Any: @@ -111,3 +275,28 @@ def is_value(selected: Var, value: Var | None) -> Var | bool: selected._get_all_var_data(), value._get_all_var_data() ), ) + + +def has_value(selected: Var, value: Var | None) -> Var | bool: + """Say whether an item is among the ones a group has selected. + + Args: + selected: The values of the group. + value: The value of the item. + + Returns: + Whether the value is one of them: a bool when both are known while + compiling. + """ + if value is None: + return False + several, one = literal(selected), literal(value) + if not isinstance(several, Var) and not isinstance(one, Var): + return one in several + return Var( + f"({selected!s}.includes({value!s}))", + _var_type=bool, + _var_data=VarData.merge( + selected._get_all_var_data(), value._get_all_var_data() + ), + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.py b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.py new file mode 100644 index 00000000000..655c45afcfb --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.py @@ -0,0 +1,174 @@ +"""A group of checkboxes: native inputs that share a name.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, JavascriptInputEvent +from reflex_base.vars.base import Var +from reflex_base.vars.object import ObjectVar +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.components._group import ( + GroupInput, + GroupRoot, + group_name, + has_value, +) +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.checkbox import CHECKBOX_GROUP_ITEM +from reflex_components_ui.styles.control import GROUP +from reflex_components_ui.themes import LiteralAccentColor + + +def checked_values_event( + e: ObjectVar[JavascriptInputEvent], +) -> tuple[Var[list[str]]]: + """Get the values of the checked checkboxes of a group from a change in it. + + Args: + e: The change of one of the checkboxes, as it reaches their group. + + Returns: + The value of each checked checkbox that has the name of the changed + one, in the order of the checkboxes. + """ + return ( + Var( + f"Array.from({e!s}.currentTarget.querySelectorAll(" + '"input[type=checkbox]:checked"))' + f".filter((input) => input.name === {e!s}.target.name)" + ".map((input) => input.value)", + _var_type=list[str], + ), + ) + + +class CheckboxGroupRoot(GroupRoot): + """Root element for a CheckboxGroup component.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = GROUP + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc="Use the size prop to control the checkbox size." + ) + + variant: Var[Literal["classic", "surface", "soft"]] = field( + doc='Variant of button: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + high_contrast: Var[bool] = field( + doc="Uses a higher contrast color for the component." + ) + + default_value: Var[Sequence[str]] = field( + doc="determines which checkboxes, if any, are checked by default." + ) + + value: Var[Sequence[str]] = field( + doc="The controlled value of the checked checkboxes. Should be used in conjunction with on_value_change." + ) + + name: Var[str] = field( + doc="used to assign a name to the entire group of checkboxes" + ) + + disabled: Var[bool] = field(doc="Whether the checkbox group is disabled") + + required: Var[bool] = field( + doc="When true, every checkbox in the group must be checked before the owning form can be submitted." + ) + + orientation: Var[Literal["horizontal", "vertical"]] = field( + doc="The orientation of the component." + ) + + dir: Var[Literal["ltr", "rtl"]] = field( + doc="The reading direction of the checkbox group. If omitted, inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode." + ) + + loop: Var[bool] = field( + doc="When true, keyboard navigation will loop from last item to first, and vice versa." + ) + + on_value_change: EventHandler[checked_values_event] = field( + doc="Fired when the set of checked checkboxes changes." + ) + + _rename_props: ClassVar[dict[str, str]] = {"onValueChange": "onChange"} + + _holds = staticmethod(has_value) + + def _bind(self) -> None: + """Name the group: a change says which checkboxes it is about by it.""" + self._name = group_name(self.name, "checkbox") + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the items off the element. + + Returns: + The props read as styles, what the group hands its items, and + what says how the arrow keys move through a group of Radix: the + checkboxes of this one are reached with Tab, as any checkbox is. + """ + return [ + *super()._exclude_props(), + "size", + "variant", + "high_contrast", + "value", + "default_value", + "disabled", + "name", + "required", + "orientation", + "loop", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the group. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role of a group. + """ + return super()._render(props).add_props(role="group") + + +class CheckboxGroupItem(GroupInput): + """An item in the CheckboxGroup component.""" + + styles: ClassVar[ComponentStyles] = CHECKBOX_GROUP_ITEM + + _type: ClassVar[str] = "checkbox" + + value: Var[str] = field( + doc="specifies the value associated with a particular checkbox option." + ) + + disabled: Var[bool] = field( + doc="Use the native disabled attribute to create a disabled checkbox." + ) + + required: Var[bool] = field( + doc="When true, indicates that the user must check the checkbox item before the owning form can be submitted." + ) + + +class CheckboxGroup(ComponentNamespace): + """CheckboxGroup components namespace.""" + + root = staticmethod(CheckboxGroupRoot.create) + item = staticmethod(CheckboxGroupItem.create) + + +checkbox_group = CheckboxGroup() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py b/packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py index 2d20b017a20..970740e3d1b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import Iterator, Sequence +from collections.abc import Sequence from typing import Any, ClassVar, Literal from reflex_base.components.component import Component, ComponentNamespace, field @@ -17,8 +17,8 @@ from reflex_components_ui.base import UIComponent from reflex_components_ui.components._group import ( - descendants, - either, + GroupInput, + GroupRoot, group_name, is_value, literal, @@ -26,45 +26,21 @@ from reflex_components_ui.layout.flex import Flex from reflex_components_ui.props import LiteralSpacing from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.radio import ( - RADIO, - RADIO_GROUP, - RADIO_GROUP_ITEM, - RADIO_GROUP_ITEM_INNER, -) +from reflex_components_ui.styles.control import GROUP +from reflex_components_ui.styles.radio import RADIO from reflex_components_ui.themes import LiteralAccentColor from reflex_components_ui.typography.text import Text LiteralFlexDirection = Literal["row", "column", "row-reverse", "column-reverse"] -class RadioGroupItemLabel(Text): - """The label around an item that is given children.""" - - def add_style(self) -> dict[str, Any]: - """Lay the radio button and its text out in a row. - - Returns: - The styles Radix Themes gives the label of an item. - """ - return RADIO_GROUP_ITEM - - -class RadioGroupItemInner(UIComponent): - """The children of an item, beside its radio button.""" - - tag = "span" - - styles: ClassVar[ComponentStyles] = RADIO_GROUP_ITEM_INNER - - -class RadioGroupItem(UIComponent): +class RadioGroupItem(GroupInput): """An item in the group that can be checked.""" - tag = "input" - styles: ClassVar[ComponentStyles] = RADIO + _type: ClassVar[str] = "radio" + value: Var[str] = field( doc="The value of the radio item to check. Should be used in conjunction with on_change." ) @@ -77,113 +53,13 @@ class RadioGroupItem(UIComponent): doc="When true, indicates that the user must check the radio item before the owning form can be submitted." ) - @classmethod - def create(cls, *children, **props) -> Component: - """Create an item: a radio button, in a label when it has children. - - Args: - *children: What is shown beside the radio button. - **props: The props of the item. With children, its styles are - those of the label. - - Returns: - The radio button, or the label that holds it. - """ - if not children: - return super().create(**props) - fields = cls.get_fields() - triggers = cls.get_event_triggers() - own = { - key: props.pop(key) - for key in list(props) - if key in fields - or key in triggers - or key.startswith(("on_", "aria_", "data_")) - } - return RadioGroupItemLabel.create( - super().create(**own), - RadioGroupItemInner.create(*children), - as_="label", - **props, - ) - - def _post_init(self, *args, **kwargs): - """Initialize the item, with the look of a group of its own. - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # What the style table reads as variants, and the attributes the - # group gives its items: both are set by the group around the item. - self._size: Any = None - self._variant: Any = None - self._high_contrast: Any = None - self._group: dict[str, Any] = {} - super()._post_init(*args, **kwargs) - - def _join(self, group: RadioGroupRoot) -> None: - """Take from a group what Radix hands its items through a context. - - Args: - group: The group the item is in. - """ - self._size = group.size - self._variant = group.variant - self._high_contrast = group.high_contrast - attributes: dict[str, Any] = {"name": group._name} - disabled = either(group.disabled, self.disabled) - if disabled is not None: - attributes["disabled"] = disabled - required = either(group.required, self.required) - if required is not None: - attributes["required"] = required - if group.value is not None: - # An input React keeps checked says who changes it: the group. - attributes["checked"] = is_value(group.value, self.value) - attributes["read_only"] = True - elif group.default_value is not None: - checked = is_value(group.default_value, self.value) - if checked is not False: - attributes["default_checked"] = checked - self._group = attributes - self._merge_styles() - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the item, those its group gives it 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) - for value in self._group.values(): - if isinstance(value, Var): - yield value - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the radio button. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, with the type of the input and what its group gives it. - """ - return super()._render(props).add_props(type="radio", **self._group) - - -class RadioGroupRoot(UIComponent): +class RadioGroupRoot(GroupRoot): """A set of interactive radio buttons where only one can be selected at a time.""" tag = "div" - styles: ClassVar[ComponentStyles] = RADIO_GROUP + styles: ClassVar[ComponentStyles] = GROUP size: Var[Responsive[Literal["1", "2", "3"]]] = field( default=LiteralVar.create("2"), @@ -220,21 +96,11 @@ class RadioGroupRoot(UIComponent): doc="Fired when the value of the radio group changes." ) - def _post_init(self, *args, **kwargs): - """Initialize the group, and give its items what they share. + _holds = staticmethod(is_value) - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - # The browser takes radio buttons for a group by their name. + def _bind(self) -> None: + """Name the group: the browser takes radio buttons for one by it.""" self._name = group_name(self.name, "radio") - for label in descendants(self, RadioGroupItemLabel, RadioGroupRoot): - label.size = self.size - label._merge_styles() - for item in descendants(self, RadioGroupItem, RadioGroupRoot): - item._join(self) def _exclude_props(self) -> list[str]: """Keep the props that are the ones of the items off the element. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py index 6e5720f4865..72e8d775c07 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py @@ -93,67 +93,89 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: _VARIANTS = ("classic", "surface", "soft") -CHECKBOX: ComponentStyles = { - "base": unchecked({ - **RESET, - "position": "relative", - "display": "inline-flex", - "align_items": "center", - "justify_content": "center", - "vertical_align": "top", - "flex_shrink": 0, - "cursor": {"default": tokens.cursor.checkbox, DISABLED: tokens.cursor.disabled}, - # In a line of text it is as high as the line. - "height": f"var(--line-height, var({_SIZE}))", - "_before": { - "content": "''", - "display": "block", - "height": f"var({_SIZE})", - "width": f"var({_SIZE})", - "border_radius": f"var({_RADIUS})", - FOCUS: FOCUS_RING, - }, - # The check, or the line of a checkbox that is neither. - "_after": { - _ON: {"content": "''"}, - "position": "absolute", - "width": f"var({_INDICATOR})", - "height": f"var({_INDICATOR})", - "transform": "translate(-50%, -50%)", - "top": "50%", - "left": "50%", - "pointer_events": "none", - "mask_image": {"default": _CHECK, ":indeterminate": _DIVIDER}, - "mask_size": "100% 100%", - "mask_repeat": "no-repeat", - }, - }), - "variants": { - "size": { - "1": unchecked({ - _SIZE: f"calc({tokens.space[4]} * 0.875)", - _INDICATOR: f"calc(9px * {tokens.scaling})", - _RADIUS: f"calc({tokens.radius[1]} * 0.875)", - }), - "2": unchecked({ - _SIZE: tokens.space[4], - _INDICATOR: f"calc(10px * {tokens.scaling})", - _RADIUS: tokens.radius[1], - }), - "3": unchecked({ - _SIZE: f"calc({tokens.space[4]} * 1.25)", - _INDICATOR: f"calc(12px * {tokens.scaling})", - _RADIUS: f"calc({tokens.radius[1]} * 1.25)", - }), + +def _table(size: str, variant: str, high_contrast: str) -> ComponentStyles: + """Make the table of a checkbox. + + Args: + size: The name of the prop that says how large it is. + variant: The name of the prop that says which look it has. + high_contrast: The name of the prop that says whether it is high + contrast. + + Returns: + The table. + """ + return { + "base": unchecked({ + **RESET, + "position": "relative", + "display": "inline-flex", + "align_items": "center", + "justify_content": "center", + "vertical_align": "top", + "flex_shrink": 0, + "cursor": { + "default": tokens.cursor.checkbox, + DISABLED: tokens.cursor.disabled, + }, + # In a line of text it is as high as the line. + "height": f"var(--line-height, var({_SIZE}))", + "_before": { + "content": "''", + "display": "block", + "height": f"var({_SIZE})", + "width": f"var({_SIZE})", + "border_radius": f"var({_RADIUS})", + FOCUS: FOCUS_RING, + }, + # The check, or the line of a checkbox that is neither. + "_after": { + _ON: {"content": "''"}, + "position": "absolute", + "width": f"var({_INDICATOR})", + "height": f"var({_INDICATOR})", + "transform": "translate(-50%, -50%)", + "top": "50%", + "left": "50%", + "pointer_events": "none", + "mask_image": {"default": _CHECK, ":indeterminate": _DIVIDER}, + "mask_size": "100% 100%", + "mask_repeat": "no-repeat", + }, + }), + "variants": { + size: { + "1": unchecked({ + _SIZE: f"calc({tokens.space[4]} * 0.875)", + _INDICATOR: f"calc(9px * {tokens.scaling})", + _RADIUS: f"calc({tokens.radius[1]} * 0.875)", + }), + "2": unchecked({ + _SIZE: tokens.space[4], + _INDICATOR: f"calc(10px * {tokens.scaling})", + _RADIUS: tokens.radius[1], + }), + "3": unchecked({ + _SIZE: f"calc({tokens.space[4]} * 1.25)", + _INDICATOR: f"calc(12px * {tokens.scaling})", + _RADIUS: f"calc({tokens.radius[1]} * 1.25)", + }), + }, + variant: {look: unchecked(_look(look, False)) for look in _VARIANTS}, }, - "variant": {variant: unchecked(_look(variant, False)) for variant in _VARIANTS}, - }, - "defaults": {"size": "2", "variant": "surface"}, - "compound": [ - { - "props": {"variant": variant, "high_contrast": "true"}, - "style": unchecked(_look(variant, True)), - } - for variant in _VARIANTS - ], -} + "defaults": {size: "2", variant: "surface"}, + "compound": [ + { + "props": {variant: look, high_contrast: "true"}, + "style": unchecked(_look(look, True)), + } + for look in _VARIANTS + ], + } + + +CHECKBOX: ComponentStyles = _table("size", "variant", "high_contrast") + +# A checkbox of a group, which says how it looks: the variants are not props. +CHECKBOX_GROUP_ITEM: ComponentStyles = _table("_size", "_variant", "_high_contrast") diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/control.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/control.py index 416a118b2f1..aa2e51eec76 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/control.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/control.py @@ -5,6 +5,7 @@ from typing import Any from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles DISABLED = ":disabled" FOCUS = ":focus-visible" @@ -58,3 +59,25 @@ def mask(path: str) -> str: "viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' " f"d='{path}'/%3E%3C/svg%3E\")" ) + + +# A group of checkboxes or of radio buttons: one below the other. +GROUP: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "display": "flex", + "flex_direction": "column", + "gap": tokens.space[1], + }, +} + +# The label Radix Themes puts an item with children in: no wider than its +# text, so that the space beside it does not check the item. +GROUP_ITEM: dict[str, Any] = { + "display": "flex", + "gap": "0.5em", + "width": "fit-content", +} + +# What is beside the input of such an item: text that may be cut off. +GROUP_ITEM_INNER: ComponentStyles = {"base": {"min_width": 0}} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py index 0330c682e01..77c781868f9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py @@ -130,23 +130,3 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: for variant in _VARIANTS ], } - -RADIO_GROUP: ComponentStyles = { - "base": { - "box_sizing": "border-box", - "display": "flex", - "flex_direction": "column", - "gap": tokens.space[1], - }, -} - -# The label Radix Themes puts an item with children in: no wider than its -# text, so that the space beside it does not check the item. -RADIO_GROUP_ITEM: dict[str, Any] = { - "display": "flex", - "gap": "0.5em", - "width": "fit-content", -} - -# What is beside the radio button of such an item: text that may be cut off. -RADIO_GROUP_ITEM_INNER: ComponentStyles = {"base": {"min_width": 0}} diff --git a/tests/units/reflex_components_ui/components/test_checkbox.py b/tests/units/reflex_components_ui/components/test_checkbox.py index 76995c05cc9..2a53ebc4d03 100644 --- a/tests/units/reflex_components_ui/components/test_checkbox.py +++ b/tests/units/reflex_components_ui/components/test_checkbox.py @@ -163,35 +163,8 @@ def test_checkbox_with_its_label( "pointerEvents": {"::after": "none"}, "maskImage": { "::after": { - "default": 'url("data:image/svg+xml,%3Csvg ' - "xmlns='http://www.w3.org/2000/svg' " - "viewBox='0 0 9 9'%3E%3Cpath " - "fill-rule='evenodd' " - "clip-rule='evenodd' d='M8.53547 " - "0.62293C8.88226 0.849446 8.97976 " - "1.3142 8.75325 1.66099L4.5083 " - "8.1599C4.38833 8.34356 4.19397 8.4655 " - "3.9764 8.49358C3.75883 8.52167 3.53987 " - "8.45309 3.3772 8.30591L0.616113 " - "5.80777C0.308959 5.52987 0.285246 " - "5.05559 0.563148 4.74844C0.84105 " - "4.44128 1.31533 4.41757 1.62249 " - "4.69547L3.73256 6.60459L7.49741 " - "0.840706C7.72393 0.493916 8.18868 " - "0.396414 8.53547 " - "0.62293Z'/%3E%3C/svg%3E\")", - ":indeterminate": 'url("data:image/svg+xml,%3Csvg ' - "xmlns='http://www.w3.org/2000/svg' " - "viewBox='0 0 9 9'%3E%3Cpath " - "fill-rule='evenodd' " - "clip-rule='evenodd' d='M0.75 " - "4.5C0.75 4.08579 1.08579 3.75 " - "1.5 3.75H7.5C7.91421 3.75 8.25 " - "4.08579 8.25 4.5C8.25 4.91421 " - "7.91421 5.25 7.5 " - "5.25H1.5C1.08579 5.25 0.75 " - "4.91421 0.75 " - "4.5Z'/%3E%3C/svg%3E\")", + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", } }, "maskSize": {"::after": "100% 100%"}, @@ -322,35 +295,8 @@ def test_checkbox_alone( "pointerEvents": {"::after": "none"}, "maskImage": { "::after": { - "default": 'url("data:image/svg+xml,%3Csvg ' - "xmlns='http://www.w3.org/2000/svg' " - "viewBox='0 0 9 9'%3E%3Cpath " - "fill-rule='evenodd' " - "clip-rule='evenodd' d='M8.53547 " - "0.62293C8.88226 0.849446 8.97976 " - "1.3142 8.75325 1.66099L4.5083 " - "8.1599C4.38833 8.34356 4.19397 8.4655 " - "3.9764 8.49358C3.75883 8.52167 3.53987 " - "8.45309 3.3772 8.30591L0.616113 " - "5.80777C0.308959 5.52987 0.285246 " - "5.05559 0.563148 4.74844C0.84105 " - "4.44128 1.31533 4.41757 1.62249 " - "4.69547L3.73256 6.60459L7.49741 " - "0.840706C7.72393 0.493916 8.18868 " - "0.396414 8.53547 " - "0.62293Z'/%3E%3C/svg%3E\")", - ":indeterminate": 'url("data:image/svg+xml,%3Csvg ' - "xmlns='http://www.w3.org/2000/svg' " - "viewBox='0 0 9 9'%3E%3Cpath " - "fill-rule='evenodd' " - "clip-rule='evenodd' d='M0.75 " - "4.5C0.75 4.08579 1.08579 3.75 " - "1.5 3.75H7.5C7.91421 3.75 8.25 " - "4.08579 8.25 4.5C8.25 4.91421 " - "7.91421 5.25 7.5 " - "5.25H1.5C1.08579 5.25 0.75 " - "4.91421 0.75 " - "4.5Z'/%3E%3C/svg%3E\")", + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", } }, "maskSize": {"::after": "100% 100%"}, @@ -412,11 +358,7 @@ def test_checkbox_classic( "default": "none", "::before": { "default": "none", - ":is(:checked, :indeterminate):not(:disabled)": "linear-gradient(to " - "bottom, " - "var(--white-a3), " - "transparent, " - "var(--black-a1))", + ":is(:checked, :indeterminate):not(:disabled)": "linear-gradient(to bottom, var(--white-a3), transparent, var(--black-a1))", }, }, "boxSizing": "border-box", @@ -471,35 +413,8 @@ def test_checkbox_classic( "pointerEvents": {"::after": "none"}, "maskImage": { "::after": { - "default": 'url("data:image/svg+xml,%3Csvg ' - "xmlns='http://www.w3.org/2000/svg' " - "viewBox='0 0 9 9'%3E%3Cpath " - "fill-rule='evenodd' " - "clip-rule='evenodd' d='M8.53547 " - "0.62293C8.88226 0.849446 8.97976 " - "1.3142 8.75325 1.66099L4.5083 " - "8.1599C4.38833 8.34356 4.19397 8.4655 " - "3.9764 8.49358C3.75883 8.52167 3.53987 " - "8.45309 3.3772 8.30591L0.616113 " - "5.80777C0.308959 5.52987 0.285246 " - "5.05559 0.563148 4.74844C0.84105 " - "4.44128 1.31533 4.41757 1.62249 " - "4.69547L3.73256 6.60459L7.49741 " - "0.840706C7.72393 0.493916 8.18868 " - "0.396414 8.53547 " - "0.62293Z'/%3E%3C/svg%3E\")", - ":indeterminate": 'url("data:image/svg+xml,%3Csvg ' - "xmlns='http://www.w3.org/2000/svg' " - "viewBox='0 0 9 9'%3E%3Cpath " - "fill-rule='evenodd' " - "clip-rule='evenodd' d='M0.75 " - "4.5C0.75 4.08579 1.08579 3.75 " - "1.5 3.75H7.5C7.91421 3.75 8.25 " - "4.08579 8.25 4.5C8.25 4.91421 " - "7.91421 5.25 7.5 " - "5.25H1.5C1.08579 5.25 0.75 " - "4.91421 0.75 " - "4.5Z'/%3E%3C/svg%3E\")", + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", } }, "maskSize": {"::after": "100% 100%"}, @@ -510,16 +425,7 @@ def test_checkbox_classic( "boxShadow": { "::before": { "default": "inset 0 0 0 1px var(--gray-a3), var(--shadow-1)", - ":is(:checked, :indeterminate):not(:disabled)": "inset " - "0 " - "0.5px " - "0.5px " - "var(--white-a4), " - "inset " - "0 " - "-0.5px " - "0.5px " - "var(--black-a4)", + ":is(:checked, :indeterminate):not(:disabled)": "inset 0 0.5px 0.5px var(--white-a4), inset 0 -0.5px 0.5px var(--black-a4)", ":disabled": "var(--shadow-1)", } }, @@ -570,24 +476,3 @@ def test_checkbox_unknown_size(ui_plugin: UIPlugin): str(error.value) == 'rx.ui.checkbox: unknown size "4". The values are "1", "2", "3".' ) - - -def test_checkbox_bound_to_state(ui_plugin: UIPlugin): - """A change hands over whether the input is checked, and the input follows.""" - component = Checkbox.create( - checked=CheckboxState.agreed, on_change=CheckboxState.agree - ) - state = ( - "tests___units___reflex_components_ui___components___test_checkbox" - "____checkbox_state" - ) - assert component.render()["props"] == [ - f"checked:reflex___state____state__{state}.agreed_rx_state_", - "className:sx_eda6ae65a6_c", - ( - 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.' - f'{state}.agree", ({{ ["agreed"] : _e?.["target"]?.["checked"] }}), ' - "({ })))], [_e], ({ }))))" - ), - 'type:"checkbox"', - ] diff --git a/tests/units/reflex_components_ui/components/test_checkbox_group.py b/tests/units/reflex_components_ui/components/test_checkbox_group.py new file mode 100644 index 00000000000..b5317b2a5ed --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_checkbox_group.py @@ -0,0 +1,713 @@ +"""Tests for reflex_components_ui.components.checkbox_group.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +class CheckboxGroupState(rx.State): + """What a checkbox group is bound to.""" + + picked: list[str] = ["a"] + + @rx.event + def pick(self, picked: list[str]): + """Follow the group. + + Args: + picked: The values of the checked items. + """ + self.picked = picked + + +def test_checkbox_group( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The items of a group are native checkboxes with its name, its look and its state; one with children is in a label.""" + component = rx.ui.checkbox_group.root( + rx.ui.checkbox_group.item("One", value="1", id="one", margin="1px"), + rx.ui.checkbox_group.item(value="2", disabled=True), + rx.el.div(rx.ui.checkbox_group.item(value="3")), + default_value=["2", "3"], + name="pick", + size="3", + variant="soft", + high_contrast=True, + color_scheme="ruby", + id="group", + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_a088d40a93_c + " " + reflexUIClasses_e201574881', + 'id:"group"', + "ref:ref_group", + 'role:"group"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_ab61f35f5f_c"], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_0710e9ad14_c", + 'id:"one"', + 'name:"pick"', + "ref:ref_one", + 'type:"checkbox"', + 'value:"1"', + ], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_1107ef58c5_c"], + "children": [{"contents": '"One"'}], + }, + ], + }, + { + "name": '"input"', + "props": [ + "className:sx_0710e9ad14_c", + "defaultChecked:true", + "disabled:true", + 'name:"pick"', + 'type:"checkbox"', + 'value:"2"', + ], + "children": [], + }, + { + "name": '"div"', + "props": [], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_0710e9ad14_c", + "defaultChecked:true", + 'name:"pick"', + 'type:"checkbox"', + 'value:"3"', + ], + "children": [], + } + ], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + }, + { + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-3)", + "--line-height": "var(--line-height-3)", + "--letter-spacing": "var(--letter-spacing-3)", + "WebkitTapHighlightColor": {"@media (pointer: coarse)": "transparent"}, + "outlineWidth": {"@media (pointer: coarse)": {":active": "0.75em"}}, + "outlineStyle": {"@media (pointer: coarse)": {":active": "solid"}}, + "outlineColor": {"@media (pointer: coarse)": {":active": "var(--gray-a4)"}}, + "outlineOffset": {"@media (pointer: coarse)": {":active": "-0.6em"}}, + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--accent-a5)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "calc(var(--space-4) * 1.25)", + "--checkbox-indicator-size": "calc(12px * var(--scaling))", + "--checkbox-border-radius": "calc(var(--radius-1) * 1.25)", + }, + {"minWidth": 0}, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--accent-a5)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "calc(var(--space-4) * 1.25)", + "--checkbox-indicator-size": "calc(12px * var(--scaling))", + "--checkbox-border-radius": "calc(var(--radius-1) * 1.25)", + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--accent-a5)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "calc(var(--space-4) * 1.25)", + "--checkbox-indicator-size": "calc(12px * var(--scaling))", + "--checkbox-border-radius": "calc(var(--radius-1) * 1.25)", + }, + ] + + +def test_checkbox_group_bound_to_state( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A bound group checks the items among its values, and a change hands over the values of the checked ones.""" + component = rx.ui.checkbox_group.root( + rx.ui.checkbox_group.item(value="a"), + rx.ui.checkbox_group.item("B", value="b"), + value=CheckboxGroupState.picked, + on_value_change=CheckboxGroupState.pick, + name="pick", + required=True, + disabled=False, + orientation="horizontal", + loop=True, + dir="rtl", + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_a088d40a93_c", + 'dir:"rtl"', + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_checkbox_group____checkbox_group_state.pick", ({ ["picked"] : Array.from(_e.currentTarget.querySelectorAll("input[type=checkbox]:checked")).filter((input) => input.name === _e.target.name).map((input) => input.value) }), ({ })))], [_e], ({ }))))', + 'role:"group"', + ], + "children": [ + { + "name": '"input"', + "props": [ + 'checked:(reflex___state____state__tests___units___reflex_components_ui___components___test_checkbox_group____checkbox_group_state.picked_rx_state_.includes("a"))', + "className:sx_eda6ae65a6_c", + "disabled:false", + 'name:"pick"', + "readOnly:true", + "required:true", + 'type:"checkbox"', + 'value:"a"', + ], + "children": [], + }, + { + "name": '"label"', + "props": ["className:sx_d1083f6dbf_c"], + "children": [ + { + "name": '"input"', + "props": [ + 'checked:(reflex___state____state__tests___units___reflex_components_ui___components___test_checkbox_group____checkbox_group_state.picked_rx_state_.includes("b"))', + "className:sx_eda6ae65a6_c", + "disabled:false", + 'name:"pick"', + "readOnly:true", + "required:true", + 'type:"checkbox"', + 'value:"b"', + ], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_1107ef58c5_c"], + "children": [{"contents": '"B"'}], + }, + ], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "flex", + "flexDirection": "column", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "var(--space-4)", + "--checkbox-indicator-size": "calc(10px * var(--scaling))", + "--checkbox-border-radius": "var(--radius-1)", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a7)", + ":is(:checked, :indeterminate):not(:disabled)": "none", + ":disabled": "inset 0 0 0 1px var(--gray-a6)", + } + }, + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-2)", + "--line-height": "var(--line-height-2)", + "--letter-spacing": "var(--letter-spacing-2)", + "WebkitTapHighlightColor": {"@media (pointer: coarse)": "transparent"}, + "outlineWidth": {"@media (pointer: coarse)": {":active": "0.75em"}}, + "outlineStyle": {"@media (pointer: coarse)": {":active": "solid"}}, + "outlineColor": {"@media (pointer: coarse)": {":active": "var(--gray-a4)"}}, + "outlineOffset": {"@media (pointer: coarse)": {":active": "-0.6em"}}, + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", + ":disabled": "var(--gray-a3)", + }, + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": { + "default": "none", + "::before": {":focus-visible": "solid"}, + }, + "outlineWidth": { + "default": "medium", + "::before": {":focus-visible": "2px"}, + }, + "outlineColor": { + "default": "currentcolor", + "::before": {":focus-visible": "var(--focus-8)"}, + }, + "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, + "WebkitTapHighlightColor": "transparent", + "position": {"default": "relative", "::after": "absolute"}, + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": { + "default": "var(--cursor-checkbox)", + ":disabled": "var(--cursor-disabled)", + }, + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "var(--space-4)", + "--checkbox-indicator-size": "calc(10px * var(--scaling))", + "--checkbox-border-radius": "var(--radius-1)", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a7)", + ":is(:checked, :indeterminate):not(:disabled)": "none", + ":disabled": "inset 0 0 0 1px var(--gray-a6)", + } + }, + }, + {"minWidth": 0}, + ] + + +def test_checkbox_group_unknown_variant(ui_plugin: UIPlugin): + """A variant a group does not have is an error that lists the ones it has.""" + with pytest.raises(TypeError) as error: + rx.ui.checkbox_group.root(variant="solid") + assert ( + str(error.value) + == "Invalid var passed for prop CheckboxGroupRoot.variant, expected type typing.Literal['classic', 'surface', 'soft'], got value 'solid' of type ." + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 34952b0eb44..55c3155fe7d 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -116,6 +116,8 @@ def test_every_wave_is_in_the_namespace(): "card", "center", "checkbox", + "checkbox_group.item", + "checkbox_group.root", "code", "container", "data_list.item", From 09c465be2af4269dd4c27b823554835edbda0a91 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 01:33:38 +0000 Subject: [PATCH 072/204] Add rx.ui.radio_cards and rx.ui.checkbox_cards: labels around native inputs A card reads its state from the input inside it with :has(), and its group gives both their look while compiling. The harness gains a state driver for the focus of a control inside the element a cell reads. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- packages/reflex-components-ui/js/src/base.css | 11 + .../parity/allowlist.toml | 48 ++ .../ui_parity/components/checkbox_cards.py | 342 ++++++++ .../ui_parity/components/radio_cards.py | 360 ++++++++ .../parity/ui_parity/look.py | 36 + .../src/reflex_components_ui/__init__.py | 2 + .../reflex_components_ui/components/_cards.py | 113 +++ .../reflex_components_ui/components/_group.py | 49 +- .../components/checkbox_cards.py | 161 ++++ .../components/radio_cards.py | 144 ++++ .../src/reflex_components_ui/styles/cards.py | 323 +++++++ .../reflex_components_ui/styles/checkbox.py | 46 +- .../components/test_checkbox_cards.py | 790 ++++++++++++++++++ .../components/test_radio_cards.py | 575 +++++++++++++ .../reflex_components_ui/test_api_parity.py | 4 + 15 files changed, 2979 insertions(+), 25 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_cards.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/cards.py create mode 100644 tests/units/reflex_components_ui/components/test_checkbox_cards.py create mode 100644 tests/units/reflex_components_ui/components/test_radio_cards.py diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index aa430939e08..656f86d9490 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -78,6 +78,17 @@ html.dark { [data-rx-skeleton] > * { visibility: hidden !important; } + + /* + * What a radio card or a checkbox card holds is not dragged out of it, an + * image for one, and an icon keeps its size beside a long text. + */ + [data-rx-cards-item] > * { + pointer-events: none; + } + [data-rx-cards-item] > svg { + flex-shrink: 0; + } } /* diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 3bdf3e4ff99..f440cd962ad 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -147,3 +147,51 @@ reason = "rx.checkbox_group takes one Tab stop for the whole group. In rx.ui.che component = "checkbox_group" step = "hands over the checked values in the order they were checked in" reason = "`on_value_change` of rx.ui.checkbox_group hands over the values of the checked items in the order of the items, whatever the order they were checked in: the group keeps no state of its own and reads its checkboxes. rx.checkbox_group appends each value as it is checked." + +[[look]] +component = "radio_cards" +check = "a11y" +reason = "A card of rx.ui.radio_cards is a label around a native radio button: what the card holds names the radio button, as in rx.radio_cards, and is also text of the page, as the text of any label is. A card of rx.radio_cards is one button that holds its text." + +[[contract]] +component = "radio_cards" +step = "checks one card of a group with JavaScript disabled" +system = "rx" +reason = "The cards of rx.radio_cards are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. A card of rx.ui.radio_cards is a label around a native radio button, which the browser checks with or without JavaScript." + +[[contract]] +component = "radio_cards" +step = "Enter on a card does not submit its form" +reason = "The cards of rx.ui.radio_cards hold native inputs, and the browser submits a form when Enter is pressed in one of its inputs, a radio button included. rx.radio_cards swallows the key. Space and the arrow keys check a card in both." + +[[look]] +component = "checkbox_cards" +check = "a11y" +reason = "The checkbox of a checked card of rx.checkbox_cards holds its check as an image without a name. The checkbox of a card of rx.ui.checkbox_cards is one native input: its check is drawn by its styles and is nothing to the accessibility tree." + +[[contract]] +component = "checkbox_cards" +step = "checks its cards with JavaScript disabled" +system = "rx" +reason = "The checkboxes of rx.checkbox_cards are buttons that JavaScript turns into checkboxes: until it has run, a click does nothing. The checkbox of a card of rx.ui.checkbox_cards is a native input, which a click on the card checks with or without JavaScript." + +[[contract]] +component = "checkbox_cards" +step = "Tab stops once in each group" +reason = "The cards of rx.ui.checkbox_cards hold native checkboxes, and Tab stops on each of them, as it does on every checkbox of a page. rx.checkbox_cards takes one stop for the whole group and moves through it with the arrow keys." + +[[contract]] +component = "checkbox_cards" +step = "the arrow keys move through a group" +reason = "The browser does not move between checkboxes with the arrow keys: in rx.ui.checkbox_cards Tab and Shift+Tab do, and `orientation`, `loop` and the direction of `dir` for the arrow keys have nothing to say. rx.checkbox_cards moves the focus with the arrow keys." + +[[contract]] +component = "checkbox_cards" +step = "Tab reaches every card that is not disabled" +system = "rx" +reason = "rx.checkbox_cards takes one Tab stop for the whole group. In rx.ui.checkbox_cards every card is a stop, as native checkboxes are." + +[[contract]] +component = "checkbox_cards" +step = "hands over the checked values in the order they were checked in" +reason = "`on_value_change` of rx.ui.checkbox_cards hands over the values of the checked cards in the order of the cards, whatever the order they were checked in: the group keeps no state of its own and reads its checkboxes. rx.checkbox_cards appends each value as it is checked." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py new file mode 100644 index 00000000000..97787670a7a --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py @@ -0,0 +1,342 @@ +"""Checkbox cards: every variant, size and state, and what native checkboxes give them.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import FOCUS_WITHIN +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, focused, wait_for_text + +VARIANTS = ["surface", "classic"] +SIZES = ["1", "2", "3"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +# The first card: a label in both systems. +TARGET = "label" +# The checkbox at the end of the first card: a button of Radix, an input here. +CHECKBOX = ("label > button", "label > input") + + +def _cards(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create checkbox cards. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the root. ``holds`` says what the cards hold when + it is not words alone. + + Returns: + The cards: the first one checked unless the cell says otherwise, and + the last one disabled. + """ + props = dict(props) + holds = props.pop("holds", None) + first: list[Any] = ["One"] + if holds == "icon": + first = [rx.icon("star"), "One"] + return namespace.checkbox_cards.root( + namespace.checkbox_cards.item(*first, value="1"), + namespace.checkbox_cards.item("Two", value="2"), + namespace.checkbox_cards.item("Three", value="3", disabled=True), + **props, + ) + + +MATRIX = Matrix( + component="checkbox_cards", + render=_cards, + base={"default_value": ["1"], "columns": "3", "gap": "2"}, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "default_value": {"none": [], "all": ["1", "2", "3"]}, + "color_scheme": ACCENTS, + "high_contrast": [True], + "disabled": [True], + "holds": ["icon"], + "columns": {"default": None, "1": "1"}, + "gap": {"default": None, "5": "5"}, + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "disabled": [True], + "default_value": {"all": ["1", "2", "3"]}, + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "state": STATES, "appearance": [LIGHT, DARK]}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(420, 150), + crop="stage", + target=TARGET, + parts={"checkbox": CHECKBOX}, + # The focus is on the checkbox inside the card. + states={FOCUS_VISIBLE: FOCUS_WITHIN}, + # Not held to zero, as the matrix of the radio cards is not: a card is + # dithered and anti-aliased by where it is on the page, and the check is + # a mask here. At the default threshold 49 of the 79 cells differ, by at + # most 4 pixels of 63000. + tolerance=0.0002, +) + + +class CheckboxCardsState(rx.State): + """What the checkbox cards of the contract are bound to.""" + + bound: list[str] = ["a"] + seen: list[list[str]] = [] + submitted: dict[str, Any] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, values: list[str]): + """Follow the bound group. + + Args: + values: The values of its checked cards. + """ + self.bound = values + + @rx.event + def see(self, values: list[str]): + """Keep what a change handed over. + + Args: + values: The values of the checked cards. + """ + self.seen.append(values) + + @rx.event + def pick_last(self): + """Change the bound value from outside the group.""" + self.bound = ["c"] + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +def _items(namespace: Any, *values: str) -> list[Any]: + """Create the cards of a group, each with its value as its text. + + Args: + namespace: ``rx`` or ``rx.ui``. + *values: The value of each card. + + Returns: + The cards. + """ + return [namespace.checkbox_cards.item(value, value=value) for value in values] + + +CONTRACT = Contract( + component="checkbox_cards", + render=lambda namespace: namespace.box( + rx.el.div( + namespace.checkbox_cards.root( + *_items(namespace, "One", "Two", "Three"), + on_value_change=CheckboxCardsState.see, + ), + id="pick", + ), + rx.el.div( + namespace.checkbox_cards.root( + namespace.checkbox_cards.item("Red", value="red"), + namespace.checkbox_cards.item("Green", value="green", disabled=True), + namespace.checkbox_cards.item("Blue", value="blue"), + default_value=["red"], + ), + id="colors", + ), + rx.el.div( + namespace.checkbox_cards.root( + *_items(namespace, "a", "b", "c"), + value=CheckboxCardsState.bound, + on_value_change=CheckboxCardsState.set_bound, + ), + id="bound", + ), + rx.el.button("Last", id="last", on_click=CheckboxCardsState.pick_last), + rx.el.div( + namespace.checkbox_cards.root(*_items(namespace, "x", "y"), disabled=True), + id="off", + ), + rx.el.form( + namespace.checkbox_cards.root( + *_items(namespace, "s", "m", "l"), name="size", default_value=["m"] + ), + rx.el.button("Send", id="send", type="submit"), + on_submit=CheckboxCardsState.submit, + id="form", + ), + rx.el.span(CheckboxCardsState.seen.to_string(), id="seen"), + rx.el.span(CheckboxCardsState.bound.to_string(), id="bound-value"), + rx.el.span(CheckboxCardsState.submitted.to_string(), id="submitted"), + rx.el.span(CheckboxCardsState.submissions.to_string(), id="submissions"), + ), +) + +# The text of the checked cards of a group, by the id of its frame. +CHECKED = ( + "id => [...document.getElementById(id).querySelectorAll('label')]" + ".filter(label => label.querySelector(':checked, [aria-checked=true]'))" + ".map(label => label.textContent)" +) +# The text of the card that has the focus. +FOCUSED_CARD = "document.activeElement.closest('label')?.textContent" +# How long a step that one system is known not to pass waits, in milliseconds. +QUICK = 3000 + + +def _wait_for_checked(run: Run, group: str, cards: list[str]) -> None: + """Wait until the checked cards of a group are the ones expected. + + Args: + run: The run, on a page. + group: The id of the frame of the group. + cards: The text of each card that is to be checked. + """ + run.page.wait_for_function( + f"([id, cards]) => ({CHECKED})(id).join() === cards", + arg=[group, ",".join(cards)], + ) + + +@CONTRACT.step("its cards are in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("pick").text == "OneTwoThree" + assert run.server.element("colors").text == "RedGreenBlue" + + +@CONTRACT.step("checks its cards with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(QUICK) + page.locator("#pick").get_by_text("Two").click() + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Two", "Three"]) + _wait_for_checked(run, "colors", ["Red"]) + _wait_for_checked(run, "form", ["m"]) + + +@CONTRACT.step("has the roles, the names and the states of a group of checkboxes") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("group").count() == 5 + pick = page.locator("#pick") + assert pick.get_by_role("checkbox").count() == 3 + assert not pick.get_by_role("checkbox", name="One").is_checked() + colors = page.locator("#colors") + assert colors.get_by_role("checkbox", name="Red", checked=True).count() == 1 + assert colors.get_by_role("checkbox", name="Green", disabled=True).count() == 1 + assert page.locator("#off").get_by_role("checkbox", disabled=True).count() == 2 + + +@CONTRACT.step("Tab stops once in each group") +def _tab(run: Run) -> None: + page = run.page + page.set_default_timeout(QUICK) + stops = [] + for _ in range(4): + page.keyboard.press("Tab") + stops.append(page.evaluate(FOCUSED_CARD) or focused(page)) + assert stops == ["One", "Red", "a", "last"] + + +@CONTRACT.step("the arrow keys move through a group") +def _arrows(run: Run) -> None: + page = run.page + page.set_default_timeout(QUICK) + page.keyboard.press("Tab") + for key, card in ( + ("ArrowDown", "Two"), + ("ArrowRight", "Three"), + ("ArrowUp", "Two"), + ): + page.keyboard.press(key, delay=60) + page.wait_for_function(f"{FOCUSED_CARD} === '{card}'") + _wait_for_checked(run, "pick", []) + + +@CONTRACT.step("Tab reaches every card that is not disabled") +def _tab_each(run: Run) -> None: + page = run.page + stops = [] + for _ in range(6): + page.keyboard.press("Tab") + stops.append(page.evaluate(FOCUSED_CARD) or focused(page)) + assert stops == ["One", "Two", "Three", "Red", "Blue", "a"] + + +@CONTRACT.step("Space and a click check and uncheck a card, and say so") +def _check(run: Run) -> None: + page = run.page + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + page.keyboard.press("Space") + _wait_for_checked(run, "pick", []) + page.locator("#pick").get_by_text("One").click() + _wait_for_checked(run, "pick", ["One"]) + wait_for_text(page, "seen", '[["Three"],[],["One"]]') + + +@CONTRACT.step("hands over the checked values in the order they were checked in") +def _order(run: Run) -> None: + page = run.page + page.set_default_timeout(QUICK) + page.locator("#pick").get_by_text("Three").click() + page.locator("#pick").get_by_text("One").click() + wait_for_text(page, "seen", '[["Three"],["Three","One"]]') + + +@CONTRACT.step("a disabled group and a disabled card are not checked") +def _disabled(run: Run) -> None: + page = run.page + page.locator("#off").get_by_text("x").click(force=True) + page.locator("#colors").get_by_text("Green").click(force=True) + page.locator("#colors").get_by_text("Blue").click() + _wait_for_checked(run, "colors", ["Red", "Blue"]) + _wait_for_checked(run, "off", []) + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + _wait_for_checked(run, "bound", ["a"]) + page.locator("#bound").get_by_text("b").click() + wait_for_text(page, "bound-value", '["a","b"]') + _wait_for_checked(run, "bound", ["a", "b"]) + page.locator("#last").click() + wait_for_text(page, "bound-value", '["c"]') + _wait_for_checked(run, "bound", ["c"]) + + +@CONTRACT.step("submits with a form") +def _submit(run: Run) -> None: + page = run.page + page.locator("#form").get_by_text("l").click() + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + # A form of Reflex keeps one value of each name: the last one. + assert page.locator("#submitted").text_content() == '{"size":"l"}' diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py new file mode 100644 index 00000000000..4c3e522e225 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py @@ -0,0 +1,360 @@ +"""Radio cards: every variant, size and state, and what native radio buttons give them.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import FOCUS_WITHIN +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, focused, wait_for_text + +VARIANTS = ["surface", "classic"] +SIZES = ["1", "2", "3"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +# The first card: a button of Radix, a label here. +TARGET = ("button", "label") + + +def _cards(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create radio cards. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the root. ``holds`` says what the cards hold when + it is not words alone. + + Returns: + The cards: the first one checked unless the cell says otherwise, and + the last one disabled. + """ + props = dict(props) + holds = props.pop("holds", None) + first: list[Any] = ["One"] + if holds == "icon": + first = [rx.icon("star"), "One"] + return namespace.radio_cards.root( + namespace.radio_cards.item(*first, value="1"), + namespace.radio_cards.item("Two", value="2"), + namespace.radio_cards.item("Three", value="3", disabled=True), + **props, + ) + + +MATRIX = Matrix( + component="radio_cards", + render=_cards, + base={"default_value": "1", "columns": "3", "gap": "2"}, + cross={"variant": VARIANTS, "size": SIZES, "default_value": ["1", "2"]}, + sweep={ + "color_scheme": ACCENTS, + "high_contrast": [True], + "disabled": [True], + "holds": ["icon"], + "columns": {"default": None, "1": "1"}, + "gap": {"default": None, "5": "5"}, + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "disabled": [True], "appearance": [LIGHT, DARK]}, + { + "variant": VARIANTS, + "default_value": ["1", "2"], + "state": STATES, + "appearance": [LIGHT, DARK], + }, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(360, 150), + crop="stage", + target=TARGET, + # The focus is on the card of Radix and on the input in the card here. + states={FOCUS_VISIBLE: FOCUS_WITHIN}, + # Not held to zero. The translucent fill of a card, its rounded clip and + # the layers of its border are dithered and anti-aliased by where the + # card is on the page: with the two frames of a cell swapped, each system + # is equal pixel for pixel to the other one in the same place. At the + # default threshold 32 of the 99 cells differ, by at most 10 pixels of + # 54000. + tolerance=0.0005, +) + + +class RadioCardsState(rx.State): + """What the radio cards of the contract are bound to.""" + + bound: str = "a" + seen: list[str] = [] + submitted: dict[str, str] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, value: str): + """Follow the bound group. + + Args: + value: The value of its checked card. + """ + self.bound = value + + @rx.event + def see(self, value: str): + """Keep what a change handed over. + + Args: + value: The value of the checked card. + """ + self.seen.append(value) + + @rx.event + def pick_last(self): + """Change the bound value from outside the group.""" + self.bound = "c" + + @rx.event + def submit(self, data: dict[str, str]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +def _items(namespace: Any, *values: str) -> list[Any]: + """Create the cards of a group, each with its value as its text. + + Args: + namespace: ``rx`` or ``rx.ui``. + *values: The value of each card. + + Returns: + The cards. + """ + return [namespace.radio_cards.item(value, value=value) for value in values] + + +CONTRACT = Contract( + component="radio_cards", + render=lambda namespace: namespace.box( + rx.el.div( + namespace.radio_cards.root( + *_items(namespace, "One", "Two", "Three"), + on_value_change=RadioCardsState.see, + ), + id="pick", + ), + rx.el.div( + namespace.radio_cards.root( + namespace.radio_cards.item("Red", value="red"), + namespace.radio_cards.item("Green", value="green", disabled=True), + namespace.radio_cards.item("Blue", value="blue"), + default_value="red", + ), + id="colors", + ), + rx.el.div( + namespace.radio_cards.root( + *_items(namespace, "a", "b", "c"), + value=RadioCardsState.bound, + on_value_change=RadioCardsState.set_bound, + ), + id="bound", + ), + rx.el.button("Last", id="last", on_click=RadioCardsState.pick_last), + rx.el.div( + namespace.radio_cards.root(*_items(namespace, "x", "y"), disabled=True), + id="off", + ), + rx.el.form( + namespace.radio_cards.root( + *_items(namespace, "s", "m", "l"), name="size", default_value="m" + ), + namespace.radio_cards.root( + *_items(namespace, "yes", "no"), name="answer", required=True + ), + rx.el.button("Send", id="send", type="submit"), + on_submit=RadioCardsState.submit, + id="form", + ), + rx.el.span(RadioCardsState.seen.to_string(), id="seen"), + rx.el.span(RadioCardsState.bound, id="bound-value"), + rx.el.span(RadioCardsState.submitted.to_string(), id="submitted"), + rx.el.span(RadioCardsState.submissions.to_string(), id="submissions"), + ), +) + +# A card is a button of Radix and a label around an input here. +CARDS = "button[role=radio], label" +# The text of the checked cards of a group, by the id of its frame. +CHECKED = ( + f"id => [...document.getElementById(id).querySelectorAll('{CARDS}')]" + ".filter(card => card.matches('[aria-checked=true], :has(:checked)'))" + ".map(card => card.textContent)" +) +# The text of the card that has the focus. +FOCUSED_CARD = f"document.activeElement.closest('{CARDS}')?.textContent" +# How long a key is held, in milliseconds. +HELD = 60 + + +def _wait_for_checked(run: Run, group: str, cards: list[str]) -> None: + """Wait until the checked cards of a group are the ones expected. + + Args: + run: The run, on a page. + group: The id of the frame of the group. + cards: The text of each card that is to be checked. + """ + run.page.wait_for_function( + f"([id, cards]) => JSON.stringify(({CHECKED})(id)) === cards", + arg=[group, json.dumps(cards)], + ) + + +@CONTRACT.step("its cards are in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("pick").text == "OneTwoThree" + assert run.server.element("colors").text == "RedGreenBlue" + + +@CONTRACT.step("checks one card of a group with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + page.locator("#pick").get_by_text("Two").click() + _wait_for_checked(run, "pick", ["Two"]) + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + _wait_for_checked(run, "colors", ["Red"]) + + +@CONTRACT.step("has the roles, the names and the states of a group of radio buttons") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("radiogroup").count() == 6 + pick = page.locator("#pick") + assert pick.get_by_role("radio").count() == 3 + assert not pick.get_by_role("radio", name="One").is_checked() + colors = page.locator("#colors") + assert colors.get_by_role("radio", name="Red", checked=True).count() == 1 + assert colors.get_by_role("radio", name="Green", disabled=True).count() == 1 + assert page.locator("#off").get_by_role("radio", disabled=True).count() == 2 + + +@CONTRACT.step("Tab stops once in each group, on its checked card") +def _tab(run: Run) -> None: + page = run.page + stops = [] + for _ in range(4): + page.keyboard.press("Tab") + stops.append(page.evaluate(FOCUSED_CARD) or focused(page)) + assert stops == ["One", "Red", "a", "last"] + _wait_for_checked(run, "pick", []) + + +@CONTRACT.step("the arrow keys move through a group and check, past a disabled card") +def _arrows(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + for key, card in ( + ("ArrowDown", "Two"), + ("ArrowRight", "Three"), + ("ArrowDown", "One"), + ("ArrowUp", "Three"), + ("ArrowLeft", "Two"), + ): + # Held as long as a finger holds it: Radix checks the card the focus + # moves to only while the key is still down. + page.keyboard.press(key, delay=HELD) + page.wait_for_function(f"{FOCUSED_CARD} === '{card}'") + _wait_for_checked(run, "pick", [card]) + wait_for_text(page, "seen", '["Two","Three","One","Three","Two"]') + page.keyboard.press("Tab") + page.keyboard.press("ArrowDown", delay=HELD) + _wait_for_checked(run, "colors", ["Blue"]) + page.keyboard.press("ArrowDown", delay=HELD) + _wait_for_checked(run, "colors", ["Red"]) + + +@CONTRACT.step("Space and a click check a card, and say so") +def _check(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + page.keyboard.press("Space") + _wait_for_checked(run, "pick", ["One"]) + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + page.locator("#pick").get_by_text("Three").click() + _wait_for_checked(run, "pick", ["Three"]) + wait_for_text(page, "seen", '["One","Three"]') + + +@CONTRACT.step("Enter on a card does not submit its form") +def _enter_in_form(run: Run) -> None: + page = run.page + page.locator("#form").get_by_text("yes").click() + page.keyboard.press("Enter") + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + assert page.locator("#submissions").text_content() == "0" + + +@CONTRACT.step("a disabled group and a disabled card are not checked") +def _disabled(run: Run) -> None: + page = run.page + page.locator("#off").get_by_text("x").click(force=True) + page.locator("#colors").get_by_text("Green").click(force=True) + page.locator("#pick").get_by_text("Two").click() + _wait_for_checked(run, "pick", ["Two"]) + _wait_for_checked(run, "off", []) + _wait_for_checked(run, "colors", ["Red"]) + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + _wait_for_checked(run, "bound", ["a"]) + page.locator("#bound").get_by_text("b").click() + wait_for_text(page, "bound-value", "b") + _wait_for_checked(run, "bound", ["b"]) + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + _wait_for_checked(run, "bound", ["c"]) + + +@CONTRACT.step("submits the value of its checked card with a form") +def _submit(run: Run) -> None: + page = run.page + page.locator("#form").get_by_text("no").click() + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == '{"size":"m","answer":"no"}' + + +@CONTRACT.step("a required group holds its form back until a card is checked") +def _required(run: Run) -> None: + page = run.page + page.locator("#send").click() + # An event that does reach the server comes back after the blocked one. + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + assert page.locator("#submissions").text_content() == "0" + page.locator("#form").get_by_text("yes").click() + page.locator("#send").click() + wait_for_text(page, "submissions", "1") diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py index 3c2b3f09eb3..ea6e490f6c5 100644 --- a/packages/reflex-components-ui/parity/ui_parity/look.py +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -203,6 +203,33 @@ def _blur(page: Page, target: Locator, point: Point) -> None: target.blur() +def _focus_within(page: Page, target: Locator, point: Point) -> None: + """Focus an element, or the control inside it, as the keyboard does. + + Args: + page: The page. + target: The element: a control, or what is drawn around one. + point: The middle of the element. + """ + page.keyboard.press("Tab") + target.evaluate( + "element => (element.matches('button, input, select, textarea, [tabindex]')" + " ? element : element.querySelector('input, button, select, textarea'))" + ".focus()" + ) + + +def _blur_within(page: Page, target: Locator, point: Point) -> None: + """Take the focus off whatever has it. + + Args: + page: The page. + target: The element that was focused, or held what was. + point: The middle of the element. + """ + page.evaluate("document.activeElement.blur()") + + def _press(page: Page, target: Locator, point: Point) -> None: """Hold the pointer down on an element. @@ -236,6 +263,15 @@ def _release(page: Page, target: Locator, point: Point) -> None: ACTIVE: State(enter=_press, leave=_release, matches=":active"), } +# The focus of the keyboard on an element whose control is inside it, for a +# matrix to drive `focus-visible` with: Radix draws some controls as one +# button where rx.ui draws a label around a native input. +FOCUS_WITHIN = State( + enter=_focus_within, + leave=_blur_within, + matches=":is(:focus-visible, :has(:focus-visible))", +) + @dataclasses.dataclass(frozen=True) class StyleDifference: 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 d051b9a0e31..06ca1eea216 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -14,11 +14,13 @@ "components.callout": ["callout"], "components.card": ["card"], "components.checkbox": ["checkbox"], + "components.checkbox_cards": ["checkbox_cards"], "components.checkbox_group": ["checkbox_group"], "components.data_list": ["data_list"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], "components.progress": ["progress"], + "components.radio_cards": ["radio_cards"], "components.radio_group": ["radio", "radio_group"], "components.scroll_area": ["scroll_area"], "components.separator": ["divider", "separator"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_cards.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_cards.py new file mode 100644 index 00000000000..6e0deac232c --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_cards.py @@ -0,0 +1,113 @@ +"""What radio cards and checkbox cards share: a grid of labels around inputs.""" + +from __future__ import annotations + +from typing import Any, ClassVar + +from reflex_base.components.component import Component +from reflex_base.components.tags import CommonTag + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._group import GroupInput, GroupMember, GroupRoot + + +class CardsRoot(GroupRoot): + """The root of a grid of cards to choose from.""" + + tag = "div" + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the items off the element. + + Returns: + The props read as styles, what the group hands its items, and + what says how the arrow keys move through a group of Radix: the + browser moves through native inputs. + """ + return [ + *super()._exclude_props(), + "variant", + "high_contrast", + "value", + "default_value", + "disabled", + "name", + "required", + "orientation", + "loop", + ] + + +class CardsItem(GroupMember, UIComponent): + """A card of a group: a label around the input that is its state.""" + + tag = "label" + + # The input of the card, and whether it comes after the children. + _input: ClassVar[type[GroupInput]] + _input_last: ClassVar[bool] = False + + @classmethod + def create(cls, *children, **props) -> Component: + """Create a card: a label that holds its input and the children. + + Args: + *children: What the card shows. + **props: The props of the card. Its styles are those of the + label, and everything else is given to the input. + + Returns: + The label. + """ + fields = cls._input.get_fields() + own = { + key: props.pop(key) + for key in list(props) + if key in fields or key.startswith(("on_", "aria_", "data_")) + } + field = cls._input.create(**own) + if cls._input_last: + return super().create(*children, field, **props) + return super().create(field, *children, **props) + + def _post_init(self, *args, **kwargs): + """Initialize the card, with the look of a group without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as variants: the group sets both. + self._variant: Any = None + self._high_contrast: Any = None + super()._post_init(*args, **kwargs) + + def _join(self, group: Any) -> None: + """Take the look of the card from the group. + + Args: + group: The group the card is in. + """ + self._variant = group.variant + self._high_contrast = group.high_contrast + self._merge_styles() + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the input off the label. + + Returns: + The props read as styles, and the ones of the input. + """ + return [*super()._exclude_props(), "value", "disabled", "required"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the card. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, marked for the rule that keeps the pointer off what a + card holds. + """ + return super()._render(props).add_props(**{"data-rx-cards-item": ""}) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py index e3ccbe61ecc..e04c7d1478e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py @@ -58,15 +58,8 @@ def _post_init(self, *args, **kwargs): """ super()._post_init(*args, **kwargs) self._bind() - # The size Radix Themes gives a group that is not given one. - size = getattr(self, "size", None) - if size is None: - size = LiteralVar.create("2") - for label in descendants(self, GroupItemLabel): - label.size = size - label._merge_styles() - for item in descendants(self, GroupInput): - item._join(self) + for member in descendants(self, GroupMember): + member._join(self) def _bind(self) -> None: """Work out what the items of the group are given, before they join.""" @@ -90,9 +83,30 @@ def descendants(component: BaseComponent, kind: type[T]) -> Iterator[T]: yield from descendants(child, kind) -class GroupItemLabel(Text): +class GroupMember: + """An element below the root of a group that takes something from it.""" + + def _join(self, group: Any) -> None: + """Take from a group what Radix hands down through a context. + + Args: + group: The group the element is in. + """ + + +class GroupItemLabel(GroupMember, Text): """The label around an item of a group that is given children.""" + def _join(self, group: Any) -> None: + """Take the size of the text from the group. + + Args: + group: The group the label is in. + """ + # The size Radix Themes gives a group that is not given one. + self.size = LiteralVar.create("2") if group.size is None else group.size + self._merge_styles() + def add_style(self) -> dict[str, Any]: """Lay the input and its text out in a row. @@ -110,7 +124,7 @@ class GroupItemInner(UIComponent): styles: ClassVar[ComponentStyles] = GROUP_ITEM_INNER -class GroupInput(UIComponent): +class GroupInput(GroupMember, UIComponent): """An item of a group: a native input its group gives a look and a state.""" tag = "input" @@ -167,7 +181,7 @@ def _join(self, group: Any) -> None: group: The group the item is in. """ self._size = group.size - self._variant = group.variant + self._variant = self._variant_of(group) self._high_contrast = group.high_contrast attributes: dict[str, Any] = {"name": group._name} disabled = either(group.disabled, getattr(self, "disabled", None)) @@ -188,6 +202,17 @@ def _join(self, group: Any) -> None: self._group = attributes self._merge_styles() + def _variant_of(self, group: Any) -> Any: + """Get the variant the input has in a group. + + Args: + group: The group the item is in. + + Returns: + The variant of the group. + """ + return group.variant + def _get_vars( self, include_children: bool = False, ignore_ids: set[int] | None = None ) -> Iterator[Var]: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.py b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.py new file mode 100644 index 00000000000..4e1bb7ad66b --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.py @@ -0,0 +1,161 @@ +"""Checkbox cards: a grid of labels, each around a native checkbox.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.components._cards import CardsItem, CardsRoot +from reflex_components_ui.components._group import GroupInput, group_name, has_value +from reflex_components_ui.components.checkbox_group import checked_values_event +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.cards import CHECKBOX_CARDS, CHECKBOX_CARDS_ITEM +from reflex_components_ui.styles.checkbox import ( + CHECKBOX_CARDS_ITEM as CHECKBOX_CARDS_CHECKBOX, +) +from reflex_components_ui.themes import LiteralAccentColor + + +class CheckboxCardsRoot(CardsRoot): + """Root element for a CheckboxCards component.""" + + styles: ClassVar[ComponentStyles] = CHECKBOX_CARDS + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc='The size of the checkbox cards: "1" | "2" | "3"' + ) + + variant: Var[Literal["classic", "surface"]] = field( + doc='Variant of button: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + high_contrast: Var[bool] = field( + doc="Uses a higher contrast color for the component." + ) + + columns: Var[ + Responsive[str | Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]] + ] = field(doc="The number of columns:") + + gap: Var[Responsive[str | Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]] = ( + field(doc="The gap between the checkbox cards:") + ) + + default_value: Var[Sequence[str]] = field( + doc="determines which cards, if any, are checked by default." + ) + + value: Var[Sequence[str]] = field( + doc="The controlled value of the checked cards. Should be used in conjunction with on_value_change." + ) + + name: Var[str] = field( + doc="The name of the group. Submitted with its owning form as part of a name/value pair." + ) + + disabled: Var[bool] = field(doc="Whether the checkbox cards group is disabled") + + required: Var[bool] = field( + doc="When true, every card in the group must be checked before the owning form can be submitted." + ) + + orientation: Var[Literal["horizontal", "vertical"]] = field( + doc="The orientation of the component." + ) + + dir: Var[Literal["ltr", "rtl"]] = field( + doc="The reading direction of the checkbox cards group. If omitted, inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode." + ) + + loop: Var[bool] = field( + doc="When true, keyboard navigation will loop from last item to first, and vice versa." + ) + + on_value_change: EventHandler[checked_values_event] = field( + doc="Fired when the set of checked cards changes." + ) + + _rename_props: ClassVar[dict[str, str]] = {"onValueChange": "onChange"} + + _holds = staticmethod(has_value) + + def _bind(self) -> None: + """Name the group: a change says which checkboxes it is about by it.""" + self._name = group_name(self.name, "checkbox-cards") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the group. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role of a group. + """ + return super()._render(props).add_props(role="group") + + +class CheckboxCardsInput(GroupInput): + """The checkbox of a card, at its end.""" + + styles: ClassVar[ComponentStyles] = CHECKBOX_CARDS_CHECKBOX + + _type: ClassVar[str] = "checkbox" + + value: Var[str] = field(doc="The value given as data when submitted with a name.") + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the checkbox item." + ) + + required: Var[bool] = field( + doc="When true, indicates that the user must check the checkbox item before the owning form can be submitted." + ) + + def _variant_of(self, group: Any) -> str: + """Get the variant of the checkbox: the same in every card. + + Args: + group: The group the card is in. + + Returns: + The variant Radix Themes draws the checkbox of a card in. + """ + return "surface" + + +class CheckboxCardsItem(CardsItem): + """An item in the CheckboxCards component.""" + + styles: ClassVar[ComponentStyles] = CHECKBOX_CARDS_ITEM + + _input: ClassVar[type[GroupInput]] = CheckboxCardsInput + _input_last: ClassVar[bool] = True + + value: Var[str] = field(doc="The value given as data when submitted with a name.") + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the checkbox item." + ) + + required: Var[bool] = field( + doc="When true, indicates that the user must check the checkbox item before the owning form can be submitted." + ) + + +class CheckboxCards(ComponentNamespace): + """CheckboxCards components namespace.""" + + root = staticmethod(CheckboxCardsRoot.create) + item = staticmethod(CheckboxCardsItem.create) + + +checkbox_cards = CheckboxCards() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.py b/packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.py new file mode 100644 index 00000000000..4e36b35a1ab --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.py @@ -0,0 +1,144 @@ +"""Radio cards: a grid of labels, each around a native radio button.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, input_event +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.components._cards import CardsItem, CardsRoot +from reflex_components_ui.components._group import GroupInput, group_name, is_value +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.cards import CARD_INPUT, RADIO_CARDS, RADIO_CARDS_ITEM +from reflex_components_ui.themes import LiteralAccentColor + + +class RadioCardsRoot(CardsRoot): + """Root element for RadioCards component.""" + + styles: ClassVar[ComponentStyles] = RADIO_CARDS + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc='The size of the checkbox cards: "1" | "2" | "3"' + ) + + variant: Var[Literal["classic", "surface"]] = field( + doc='Variant of button: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + high_contrast: Var[bool] = field( + doc="Uses a higher contrast color for the component." + ) + + columns: Var[ + Responsive[str | Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]] + ] = field(doc="The number of columns:") + + gap: Var[Responsive[str | Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]] = ( + field(doc="The gap between the checkbox cards:") + ) + + default_value: Var[str] + + value: Var[str] = field( + doc="The controlled value of the radio item to check. Should be used in conjunction with onValueChange." + ) + + name: Var[str] = field( + doc="The name of the group. Submitted with its owning form as part of a name/value pair." + ) + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with radio items." + ) + + required: Var[bool] = field( + doc="When true, indicates that the user must check a radio item before the owning form can be submitted." + ) + + orientation: Var[Literal["horizontal", "vertical", "undefined"]] = field( + doc="The orientation of the component." + ) + + dir: Var[Literal["ltr", "rtl"]] = field( + doc="The reading direction of the radio group. If omitted, inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode." + ) + + loop: Var[bool] = field( + doc="When true, keyboard navigation will loop from last item to first, and vice versa." + ) + + on_value_change: EventHandler[input_event] = field( + doc="Event handler called when the value changes." + ) + + _rename_props: ClassVar[dict[str, str]] = {"onValueChange": "onChange"} + + _holds = staticmethod(is_value) + + def _bind(self) -> None: + """Name the group: the browser takes radio buttons for one by it.""" + self._name = group_name(self.name, "radio-cards") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the group. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role of a group of radio buttons. + """ + return super()._render(props).add_props(role="radiogroup") + + +class RadioCardsInput(GroupInput): + """The radio button of a card, which is not seen.""" + + styles: ClassVar[ComponentStyles] = CARD_INPUT + + _type: ClassVar[str] = "radio" + + value: Var[str] = field(doc="The value given as data when submitted with a name.") + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the radio item." + ) + + required: Var[bool] = field( + doc="When true, indicates that the user must check the radio item before the owning form can be submitted." + ) + + +class RadioCardsItem(CardsItem): + """Item element for RadioCards component.""" + + styles: ClassVar[ComponentStyles] = RADIO_CARDS_ITEM + + _input: ClassVar[type[GroupInput]] = RadioCardsInput + + value: Var[str] = field(doc="The value given as data when submitted with a name.") + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the radio item." + ) + + required: Var[bool] = field( + doc="When true, indicates that the user must check the radio item before the owning form can be submitted." + ) + + +class RadioCards(ComponentNamespace): + """RadioCards components namespace.""" + + root = staticmethod(RadioCardsRoot.create) + item = staticmethod(RadioCardsItem.create) + + +radio_cards = RadioCards() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/cards.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/cards.py new file mode 100644 index 00000000000..fef1facf0e5 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/cards.py @@ -0,0 +1,323 @@ +"""The look of radio cards and of checkbox cards: a grid of cards to choose from.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.card import ( + _CLASSIC_HOVER_INNER, + _CLASSIC_HOVER_OUTER, + _CLASSIC_INNER, + _CLASSIC_OUTER, + _mix, +) + +accent, gray, focus = tokens.accent, tokens.gray, tokens.focus + +_POINTER = "@media (hover: hover)" +_TOUCH = "@media (pointer: coarse)" + +# What says how a card is, on the label that is the card: the input inside. +CHECKED = ":has(:checked)" +FOCUSED = ":has(:focus-visible)" +DISABLED = ":has(:disabled)" + + +def _root(columns: str, sizes: dict[str, dict[str, str]]) -> ComponentStyles: + """Make the table of a grid of cards. + + Args: + columns: The columns of a grid that is given none. + sizes: What each size hands its cards, by custom property. + + Returns: + The table. + """ + return { + "base": { + "box_sizing": "border-box", + "display": "grid", + "align_items": "stretch", + "justify_content": "flex-start", + "grid_template_columns": columns, + "grid_template_rows": "none", + "gap": tokens.space[4], + "line_height": "var(--line-height)", + "letter_spacing": "var(--letter-spacing)", + "cursor": "default", + }, + "variants": { + "size": { + size: unchecked({ + "font_size": tokens.font_size[step], + "--line-height": tokens.line_height[step], + "--letter-spacing": tokens.letter_spacing[step], + **sizes[size], + }) + for size, step in (("1", 2), ("2", 2), ("3", 3)) + }, + }, + "defaults": {"size": "2"}, + } + + +def _item( + padding: tuple[str, str, str, str], + radius: str, + base: dict[str, Any], + hover: str, + after: dict[str, Any], +) -> ComponentStyles: + """Make the table of a card: a label around the input that is its state. + + Args: + padding: The padding of the card, from the top clockwise. + radius: The radius of its corners. + base: What the kind of card adds to the card itself. + hover: The state of a card under the pointer that answers to it. + after: What the kind of card adds to its border. + + Returns: + The table. + """ + border = "1px" + layer: dict[str, Any] = { + "content": "''", + "position": "absolute", + "pointer_events": "none", + "transition_property": "inherit", + "transition_duration": "inherit", + "transition_timing_function": "inherit", + "transition_delay": "inherit", + "border_radius": f"calc({radius} - {border})", + "inset": border, + } + top, right, bottom, left = padding + return { + "base": unchecked({ + "display": "flex", + "align_items": "center", + "gap": tokens.space[2], + "position": "relative", + "overflow": "hidden", + "border_radius": radius, + "font_family": tokens.default.font_family, + "font_style": "normal", + "text_align": "start", + "padding_top": top, + "padding_right": right, + "padding_bottom": bottom, + "padding_left": left, + "box_sizing": "border-box", + # A stacking context, so that the background stays over what is + # behind the card. + "contain": "paint", + "--inset-border-width": border, + "--inset-border-radius": radius, + "--inset-padding-top": f"calc({top} - {border})", + "--inset-padding-right": f"calc({right} - {border})", + "--inset-padding-bottom": f"calc({bottom} - {border})", + "--inset-padding-left": f"calc({left} - {border})", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": tokens.cursor.button, + DISABLED: tokens.cursor.disabled, + }, + **base, + # Behind the children, and over them: the background and the + # border. + "_before": { + **layer, + "z_index": -1, + "background_color": tokens.color.surface, + **base.get("_before", {}), + }, + "_after": {**layer, **after}, + }), + "variants": { + "_variant": { + "surface": unchecked({ + "_after": { + "box_shadow": { + "default": f"0 0 0 1px {_mix(5)}", + _POINTER: {hover: f"0 0 0 1px {_mix(7)}"}, + }, + }, + }), + "classic": unchecked({ + "transition_property": "box-shadow", + "transition_duration": { + "default": "120ms", + _POINTER: {hover: "40ms"}, + }, + "box_shadow": { + "default": _CLASSIC_OUTER, + _POINTER: {hover: _CLASSIC_HOVER_OUTER}, + }, + "_after": { + "box_shadow": { + "default": _CLASSIC_INNER, + _POINTER: {hover: _CLASSIC_HOVER_INNER}, + }, + }, + }), + }, + }, + "defaults": {"_variant": "surface"}, + } + + +_DISABLED_FILL = f"linear-gradient({gray.a[2]}, {gray.a[2]})" + +_RADIO_X = "var(--radio-cards-item-padding-x)" +_RADIO_Y = "var(--radio-cards-item-padding-y)" + +RADIO_CARDS: ComponentStyles = _root( + "repeat(auto-fit, minmax(160px, 1fr))", + { + "1": { + "--radio-cards-item-padding-x": tokens.space[3], + "--radio-cards-item-padding-y": f"calc({tokens.space[3]} / 1.2)", + "--radio-cards-item-border-radius": tokens.radius[3], + }, + "2": { + "--radio-cards-item-padding-x": tokens.space[4], + "--radio-cards-item-padding-y": f"calc({tokens.space[4]} * 0.875)", + "--radio-cards-item-border-radius": tokens.radius[3], + }, + "3": { + "--radio-cards-item-padding-x": tokens.space[5], + "--radio-cards-item-padding-y": f"calc({tokens.space[5]} / 1.2)", + "--radio-cards-item-border-radius": tokens.radius[4], + }, + }, +) + +# A radio card: the ring of the checked card, and the one of the focus over it. +RADIO_CARDS_ITEM: ComponentStyles = _item( + (_RADIO_Y, _RADIO_X, _RADIO_Y, _RADIO_X), + "var(--radio-cards-item-border-radius)", + { + "justify_content": "center", + "color": {"default": "inherit", DISABLED: gray.a[9]}, + # As the button a card of Radix Themes is has none. + "border_width": "0", + "border_style": "none", + "_before": { + "background_image": { + f"{CHECKED}{FOCUSED}": f"linear-gradient({focus.a[3]}, {focus.a[3]})", + DISABLED: _DISABLED_FILL, + }, + }, + }, + f":hover:not({CHECKED}, {DISABLED})", + { + "outline_offset": "-1px", + "outline_style": {CHECKED: "solid", FOCUSED: "solid"}, + "outline_width": {CHECKED: "2px", FOCUSED: "2px"}, + "outline_color": { + f"{CHECKED}:not({FOCUSED}, {DISABLED})": accent.indicator, + f"{FOCUSED}:not({CHECKED})": focus[8], + f"{CHECKED}{FOCUSED}": focus[10], + DISABLED: gray[8], + }, + }, +) + +RADIO_CARDS_ITEM_HIGH_CONTRAST: dict[str, Any] = { + "_after": { + "outline_color": { + f"{CHECKED}:not({FOCUSED}, {DISABLED})": accent[12], + f"{FOCUSED}:not({CHECKED})": focus[8], + f"{CHECKED}{FOCUSED}": focus[10], + DISABLED: gray[8], + }, + }, +} +RADIO_CARDS_ITEM["compound"] = [ + { + "props": {"_high_contrast": "true"}, + "style": unchecked(RADIO_CARDS_ITEM_HIGH_CONTRAST), + } +] + +# The radio button of a card: there for the keyboard and for forms, not seen. +CARD_INPUT: ComponentStyles = { + "base": { + "appearance": "none", + "position": "absolute", + "inset": "0", + "margin": "0", + "opacity": 0, + "pointer_events": "none", + }, +} + +_CHECKBOX_LEFT = "var(--checkbox-cards-item-padding-left)" +_CHECKBOX_SIZE = "--checkbox-cards-item-checkbox-size" +_FOCUS_RING: dict[str, Any] = { + "outline_width": {FOCUSED: "2px"}, + "outline_style": {FOCUSED: "solid"}, + "outline_color": {FOCUSED: focus[8]}, + "outline_offset": {FOCUSED: "-1px"}, +} + +CHECKBOX_CARDS: ComponentStyles = _root( + "repeat(auto-fit, minmax(200px, 1fr))", + { + "1": { + "--checkbox-cards-item-padding-top": f"calc({tokens.space[3]} / 1.2)", + "--checkbox-cards-item-padding-bottom": f"calc({tokens.space[3]} / 1.2)", + "--checkbox-cards-item-padding-left": tokens.space[3], + "--checkbox-cards-item-border-radius": tokens.radius[3], + _CHECKBOX_SIZE: f"calc({tokens.space[4]} * 0.875)", + }, + "2": { + "--checkbox-cards-item-padding-top": f"calc({tokens.space[4]} * 0.875)", + "--checkbox-cards-item-padding-bottom": ( + f"calc({tokens.space[4]} * 0.875)" + ), + "--checkbox-cards-item-padding-left": tokens.space[4], + "--checkbox-cards-item-border-radius": tokens.radius[3], + _CHECKBOX_SIZE: tokens.space[4], + }, + "3": { + "--checkbox-cards-item-padding-top": f"calc({tokens.space[5]} / 1.2)", + "--checkbox-cards-item-padding-bottom": f"calc({tokens.space[5]} / 1.2)", + "--checkbox-cards-item-padding-left": tokens.space[5], + "--checkbox-cards-item-border-radius": tokens.radius[4], + _CHECKBOX_SIZE: f"calc({tokens.space[4]} * 1.25)", + }, + }, +) + +# A checkbox card: room at its end for the checkbox, and the ring of the focus. +CHECKBOX_CARDS_ITEM: ComponentStyles = _item( + ( + "var(--checkbox-cards-item-padding-top)", + f"calc({_CHECKBOX_LEFT} * 2 + var({_CHECKBOX_SIZE}))", + "var(--checkbox-cards-item-padding-bottom)", + _CHECKBOX_LEFT, + ), + "var(--checkbox-cards-item-border-radius)", + { + "color": {DISABLED: gray.a[9]}, + **_FOCUS_RING, + "_before": { + "background_image": { + # Instead of the highlight of a tap, which is turned off. + _TOUCH: { + f":active:not({FOCUSED}, {DISABLED})": ( + f"linear-gradient({gray.a[4]}, {gray.a[4]})" + ), + }, + DISABLED: _DISABLED_FILL, + }, + }, + }, + f":hover:not({DISABLED})", + # The ring again on the border, which does not take its offset. + {key: value for key, value in _FOCUS_RING.items() if key != "outline_offset"}, +) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py index 72e8d775c07..fb438fa815f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py @@ -11,6 +11,8 @@ accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black _SIZE = "--checkbox-size" +# How far the checkbox of a card is from its end: the padding of the card. +CARD_PADDING = "var(--checkbox-cards-item-padding-left)" _INDICATOR = "--checkbox-indicator-size" _RADIUS = "--checkbox-border-radius" @@ -34,12 +36,13 @@ ) -def _look(variant: str, high_contrast: bool) -> dict[str, Any]: +def _look(variant: str, high_contrast: bool, disabled: str) -> dict[str, Any]: """Make the box and the check of one variant. Args: variant: The variant. high_contrast: Whether the checkbox is high contrast. + disabled: The fill of a disabled checkbox. Returns: The styles of the two pseudo-elements, for every state of the input. @@ -51,7 +54,7 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: "background_color": { "default": tokens.color.surface, _ON_ENABLED: fill, - DISABLED: gray.a[3], + DISABLED: disabled, }, "box_shadow": { "default": f"inset 0 0 0 1px {gray.a[7]}", @@ -64,7 +67,7 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: "background_color": { "default": tokens.color.surface, _ON_ENABLED: fill, - DISABLED: gray.a[3], + DISABLED: disabled, }, "background_image": { "default": "none", @@ -83,7 +86,7 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: }, } else: - box = {"background_color": {"default": accent.a[5], DISABLED: gray.a[3]}} + box = {"background_color": {"default": accent.a[5], DISABLED: disabled}} check = accent[12] if high_contrast else accent.a[11] return { "_before": box, @@ -94,7 +97,9 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: _VARIANTS = ("classic", "surface", "soft") -def _table(size: str, variant: str, high_contrast: str) -> ComponentStyles: +def _table( + size: str, variant: str, high_contrast: str, card: bool = False +) -> ComponentStyles: """Make the table of a checkbox. Args: @@ -102,23 +107,31 @@ def _table(size: str, variant: str, high_contrast: str) -> ComponentStyles: variant: The name of the prop that says which look it has. high_contrast: The name of the prop that says whether it is high contrast. + card: Whether the checkbox is the one of a card, which shows the + focus itself and places the checkbox at its end. Returns: The table. """ + disabled = "transparent" if card else gray.a[3] return { "base": unchecked({ **RESET, - "position": "relative", + "position": "absolute" if card else "relative", + **({"right": CARD_PADDING} if card else {}), "display": "inline-flex", "align_items": "center", "justify_content": "center", "vertical_align": "top", "flex_shrink": 0, - "cursor": { - "default": tokens.cursor.checkbox, - DISABLED: tokens.cursor.disabled, - }, + "cursor": ( + tokens.cursor.checkbox + if card + else { + "default": tokens.cursor.checkbox, + DISABLED: tokens.cursor.disabled, + } + ), # In a line of text it is as high as the line. "height": f"var(--line-height, var({_SIZE}))", "_before": { @@ -127,7 +140,7 @@ def _table(size: str, variant: str, high_contrast: str) -> ComponentStyles: "height": f"var({_SIZE})", "width": f"var({_SIZE})", "border_radius": f"var({_RADIUS})", - FOCUS: FOCUS_RING, + **({} if card else {FOCUS: FOCUS_RING}), }, # The check, or the line of a checkbox that is neither. "_after": { @@ -162,13 +175,15 @@ def _table(size: str, variant: str, high_contrast: str) -> ComponentStyles: _RADIUS: f"calc({tokens.radius[1]} * 1.25)", }), }, - variant: {look: unchecked(_look(look, False)) for look in _VARIANTS}, + variant: { + look: unchecked(_look(look, False, disabled)) for look in _VARIANTS + }, }, "defaults": {size: "2", variant: "surface"}, "compound": [ { "props": {variant: look, high_contrast: "true"}, - "style": unchecked(_look(look, True)), + "style": unchecked(_look(look, True, disabled)), } for look in _VARIANTS ], @@ -179,3 +194,8 @@ def _table(size: str, variant: str, high_contrast: str) -> ComponentStyles: # A checkbox of a group, which says how it looks: the variants are not props. CHECKBOX_GROUP_ITEM: ComponentStyles = _table("_size", "_variant", "_high_contrast") + +# The checkbox of a card, at its end. +CHECKBOX_CARDS_ITEM: ComponentStyles = _table( + "_size", "_variant", "_high_contrast", card=True +) diff --git a/tests/units/reflex_components_ui/components/test_checkbox_cards.py b/tests/units/reflex_components_ui/components/test_checkbox_cards.py new file mode 100644 index 00000000000..db4f1552314 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_checkbox_cards.py @@ -0,0 +1,790 @@ +"""Tests for reflex_components_ui.components.checkbox_cards.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +class CardsState(rx.State): + """What a group of cards is bound to.""" + + picked: list[str] = ["a"] + + @rx.event + def pick(self, picked: list[str]): + """Follow the group. + + Args: + picked: What is checked. + """ + self.picked = picked + + +def test_checkbox_cards( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A card is a label around a native input, which the group gives its name, its look and its state.""" + component = rx.ui.checkbox_cards.root( + rx.ui.checkbox_cards.item("One", value="1", id="one", margin="1px"), + rx.ui.checkbox_cards.item("Two", value="2", disabled=True), + default_value=["1"], + name="pick", + id="group", + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_076463c881_c", + 'id:"group"', + "ref:ref_group", + 'role:"group"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_26403764ed_c", '"data-rx-cards-item":""'], + "children": [ + {"contents": '"One"'}, + { + "name": '"input"', + "props": [ + "className:sx_e9aee32af5_c", + "defaultChecked:true", + 'id:"one"', + 'name:"pick"', + "ref:ref_one", + 'type:"checkbox"', + 'value:"1"', + ], + "children": [], + }, + ], + }, + { + "name": '"label"', + "props": ["className:sx_12056722ee_c", '"data-rx-cards-item":""'], + "children": [ + {"contents": '"Two"'}, + { + "name": '"input"', + "props": [ + "className:sx_e9aee32af5_c", + "disabled:true", + 'name:"pick"', + 'type:"checkbox"', + 'value:"2"', + ], + "children": [], + }, + ], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "stretch", + "justifyContent": "flex-start", + "gridTemplateColumns": "repeat(auto-fit, minmax(200px, 1fr))", + "gridTemplateRows": "none", + "rowGap": "var(--space-4)", + "columnGap": "var(--space-4)", + "lineHeight": "var(--line-height)", + "letterSpacing": "var(--letter-spacing)", + "cursor": "default", + "fontSize": "var(--font-size-2)", + "--line-height": "var(--line-height-2)", + "--letter-spacing": "var(--letter-spacing-2)", + "--checkbox-cards-item-padding-top": "calc(var(--space-4) * 0.875)", + "--checkbox-cards-item-padding-bottom": "calc(var(--space-4) * 0.875)", + "--checkbox-cards-item-padding-left": "var(--space-4)", + "--checkbox-cards-item-border-radius": "var(--radius-3)", + "--checkbox-cards-item-checkbox-size": "var(--space-4)", + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--checkbox-cards-item-border-radius)", + "::before": "calc(var(--checkbox-cards-item-border-radius) - 1px)", + "::after": "calc(var(--checkbox-cards-item-border-radius) - 1px)", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "paddingTop": "var(--checkbox-cards-item-padding-top)", + "paddingRight": "calc(var(--checkbox-cards-item-padding-left) * 2 + var(--checkbox-cards-item-checkbox-size))", + "paddingBottom": "var(--checkbox-cards-item-padding-bottom)", + "paddingLeft": "var(--checkbox-cards-item-padding-left)", + "boxSizing": "border-box", + "contain": "paint", + "--inset-border-width": "1px", + "--inset-border-radius": "var(--checkbox-cards-item-border-radius)", + "--inset-padding-top": "calc(var(--checkbox-cards-item-padding-top) - 1px)", + "--inset-padding-right": "calc(calc(var(--checkbox-cards-item-padding-left) * 2 + var(--checkbox-cards-item-checkbox-size)) - 1px)", + "--inset-padding-bottom": "calc(var(--checkbox-cards-item-padding-bottom) - 1px)", + "--inset-padding-left": "calc(var(--checkbox-cards-item-padding-left) - 1px)", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "var(--cursor-button)", + ":has(:disabled)": "var(--cursor-disabled)", + }, + "color": {":has(:disabled)": "var(--gray-a9)"}, + "outlineWidth": { + ":has(:focus-visible)": "2px", + "::after": {":has(:focus-visible)": "2px"}, + }, + "outlineStyle": { + ":has(:focus-visible)": "solid", + "::after": {":has(:focus-visible)": "solid"}, + }, + "outlineColor": { + ":has(:focus-visible)": "var(--focus-8)", + "::after": {":has(:focus-visible)": "var(--focus-8)"}, + }, + "outlineOffset": {":has(:focus-visible)": "-1px"}, + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": {"::before": "inherit", "::after": "inherit"}, + "transitionDuration": {"::before": "inherit", "::after": "inherit"}, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "top": {"::before": "1px", "::after": "1px"}, + "right": {"::before": "1px", "::after": "1px"}, + "bottom": {"::before": "1px", "::after": "1px"}, + "left": {"::before": "1px", "::after": "1px"}, + "zIndex": {"::before": -1}, + "backgroundColor": {"::before": "var(--color-surface)"}, + "backgroundImage": { + "::before": { + "@media (pointer: coarse)": { + ":active:not(:has(:focus-visible), :has(:disabled))": "linear-gradient(var(--gray-a4), var(--gray-a4))" + }, + ":has(:disabled)": "linear-gradient(var(--gray-a2), var(--gray-a2))", + } + }, + "boxShadow": { + "::after": { + "default": "0 0 0 1px color-mix(in oklab, var(--gray-a5), var(--gray-5) 25%)", + "@media (hover: hover)": { + ":hover:not(:has(:disabled))": "0 0 0 1px color-mix(in oklab, var(--gray-a7), var(--gray-7) 25%)" + }, + } + }, + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", + ":disabled": "transparent", + }, + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "WebkitTapHighlightColor": "transparent", + "position": {"default": "absolute", "::after": "absolute"}, + "right": "var(--checkbox-cards-item-padding-left)", + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": "var(--cursor-checkbox)", + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "var(--space-4)", + "--checkbox-indicator-size": "calc(10px * var(--scaling))", + "--checkbox-border-radius": "var(--radius-1)", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a7)", + ":is(:checked, :indeterminate):not(:disabled)": "none", + ":disabled": "inset 0 0 0 1px var(--gray-a6)", + } + }, + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--checkbox-cards-item-border-radius)", + "::before": "calc(var(--checkbox-cards-item-border-radius) - 1px)", + "::after": "calc(var(--checkbox-cards-item-border-radius) - 1px)", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "paddingTop": "var(--checkbox-cards-item-padding-top)", + "paddingRight": "calc(var(--checkbox-cards-item-padding-left) * 2 + var(--checkbox-cards-item-checkbox-size))", + "paddingBottom": "var(--checkbox-cards-item-padding-bottom)", + "paddingLeft": "var(--checkbox-cards-item-padding-left)", + "boxSizing": "border-box", + "contain": "paint", + "--inset-border-width": "1px", + "--inset-border-radius": "var(--checkbox-cards-item-border-radius)", + "--inset-padding-top": "calc(var(--checkbox-cards-item-padding-top) - 1px)", + "--inset-padding-right": "calc(calc(var(--checkbox-cards-item-padding-left) * 2 + var(--checkbox-cards-item-checkbox-size)) - 1px)", + "--inset-padding-bottom": "calc(var(--checkbox-cards-item-padding-bottom) - 1px)", + "--inset-padding-left": "calc(var(--checkbox-cards-item-padding-left) - 1px)", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "var(--cursor-button)", + ":has(:disabled)": "var(--cursor-disabled)", + }, + "color": {":has(:disabled)": "var(--gray-a9)"}, + "outlineWidth": { + ":has(:focus-visible)": "2px", + "::after": {":has(:focus-visible)": "2px"}, + }, + "outlineStyle": { + ":has(:focus-visible)": "solid", + "::after": {":has(:focus-visible)": "solid"}, + }, + "outlineColor": { + ":has(:focus-visible)": "var(--focus-8)", + "::after": {":has(:focus-visible)": "var(--focus-8)"}, + }, + "outlineOffset": {":has(:focus-visible)": "-1px"}, + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": {"::before": "inherit", "::after": "inherit"}, + "transitionDuration": {"::before": "inherit", "::after": "inherit"}, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "top": {"::before": "1px", "::after": "1px"}, + "right": {"::before": "1px", "::after": "1px"}, + "bottom": {"::before": "1px", "::after": "1px"}, + "left": {"::before": "1px", "::after": "1px"}, + "zIndex": {"::before": -1}, + "backgroundColor": {"::before": "var(--color-surface)"}, + "backgroundImage": { + "::before": { + "@media (pointer: coarse)": { + ":active:not(:has(:focus-visible), :has(:disabled))": "linear-gradient(var(--gray-a4), var(--gray-a4))" + }, + ":has(:disabled)": "linear-gradient(var(--gray-a2), var(--gray-a2))", + } + }, + "boxShadow": { + "::after": { + "default": "0 0 0 1px color-mix(in oklab, var(--gray-a5), var(--gray-5) 25%)", + "@media (hover: hover)": { + ":hover:not(:has(:disabled))": "0 0 0 1px color-mix(in oklab, var(--gray-a7), var(--gray-7) 25%)" + }, + } + }, + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", + ":disabled": "transparent", + }, + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "WebkitTapHighlightColor": "transparent", + "position": {"default": "absolute", "::after": "absolute"}, + "right": "var(--checkbox-cards-item-padding-left)", + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": "var(--cursor-checkbox)", + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": "var(--space-4)", + "--checkbox-indicator-size": "calc(10px * var(--scaling))", + "--checkbox-border-radius": "var(--radius-1)", + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a7)", + ":is(:checked, :indeterminate):not(:disabled)": "none", + ":disabled": "inset 0 0 0 1px var(--gray-a6)", + } + }, + }, + ] + + +def test_checkbox_cards_classic( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The size, the variant and the contrast of a group are the ones of its cards, and its columns and gap the ones of its grid.""" + component = rx.ui.checkbox_cards.root( + rx.ui.checkbox_cards.item("One", value="1"), + name="pick", + size=rx.breakpoints(initial="1", md="3"), + variant="classic", + high_contrast=True, + color_scheme="ruby", + columns="2", + gap="6", + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_33c68550fa_c + " " + reflexUIClasses_e201574881', + 'role:"group"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_ec5835b087_c", '"data-rx-cards-item":""'], + "children": [ + {"contents": '"One"'}, + { + "name": '"input"', + "props": [ + "className:sx_0d82b24940_c", + 'name:"pick"', + 'type:"checkbox"', + 'value:"1"', + ], + "children": [], + }, + ], + } + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "stretch", + "justifyContent": "flex-start", + "gridTemplateColumns": "repeat(2, minmax(0, 1fr))", + "gridTemplateRows": "none", + "rowGap": "var(--space-6)", + "columnGap": "var(--space-6)", + "lineHeight": "var(--line-height)", + "letterSpacing": "var(--letter-spacing)", + "cursor": "default", + "fontSize": { + "default": "var(--font-size-2)", + "@media (min-width: 1024px)": "var(--font-size-3)", + }, + "--line-height": { + "default": "var(--line-height-2)", + "@media (min-width: 1024px)": "var(--line-height-3)", + }, + "--letter-spacing": { + "default": "var(--letter-spacing-2)", + "@media (min-width: 1024px)": "var(--letter-spacing-3)", + }, + "--checkbox-cards-item-padding-top": { + "default": "calc(var(--space-3) / 1.2)", + "@media (min-width: 1024px)": "calc(var(--space-5) / 1.2)", + }, + "--checkbox-cards-item-padding-bottom": { + "default": "calc(var(--space-3) / 1.2)", + "@media (min-width: 1024px)": "calc(var(--space-5) / 1.2)", + }, + "--checkbox-cards-item-padding-left": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "var(--space-5)", + }, + "--checkbox-cards-item-border-radius": { + "default": "var(--radius-3)", + "@media (min-width: 1024px)": "var(--radius-4)", + }, + "--checkbox-cards-item-checkbox-size": { + "default": "calc(var(--space-4) * 0.875)", + "@media (min-width: 1024px)": "calc(var(--space-4) * 1.25)", + }, + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--checkbox-cards-item-border-radius)", + "::before": "calc(var(--checkbox-cards-item-border-radius) - 1px)", + "::after": "calc(var(--checkbox-cards-item-border-radius) - 1px)", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "paddingTop": "var(--checkbox-cards-item-padding-top)", + "paddingRight": "calc(var(--checkbox-cards-item-padding-left) * 2 + var(--checkbox-cards-item-checkbox-size))", + "paddingBottom": "var(--checkbox-cards-item-padding-bottom)", + "paddingLeft": "var(--checkbox-cards-item-padding-left)", + "boxSizing": "border-box", + "contain": "paint", + "--inset-border-width": "1px", + "--inset-border-radius": "var(--checkbox-cards-item-border-radius)", + "--inset-padding-top": "calc(var(--checkbox-cards-item-padding-top) - 1px)", + "--inset-padding-right": "calc(calc(var(--checkbox-cards-item-padding-left) * 2 + var(--checkbox-cards-item-checkbox-size)) - 1px)", + "--inset-padding-bottom": "calc(var(--checkbox-cards-item-padding-bottom) - 1px)", + "--inset-padding-left": "calc(var(--checkbox-cards-item-padding-left) - 1px)", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "var(--cursor-button)", + ":has(:disabled)": "var(--cursor-disabled)", + }, + "color": {":has(:disabled)": "var(--gray-a9)"}, + "outlineWidth": { + ":has(:focus-visible)": "2px", + "::after": {":has(:focus-visible)": "2px"}, + }, + "outlineStyle": { + ":has(:focus-visible)": "solid", + "::after": {":has(:focus-visible)": "solid"}, + }, + "outlineColor": { + ":has(:focus-visible)": "var(--focus-8)", + "::after": {":has(:focus-visible)": "var(--focus-8)"}, + }, + "outlineOffset": {":has(:focus-visible)": "-1px"}, + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": { + "default": "box-shadow", + "::before": "inherit", + "::after": "inherit", + }, + "transitionDuration": { + "default": "120ms", + "@media (hover: hover)": {":hover:not(:has(:disabled))": "40ms"}, + "::before": "inherit", + "::after": "inherit", + }, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "top": {"::before": "1px", "::after": "1px"}, + "right": {"::before": "1px", "::after": "1px"}, + "bottom": {"::before": "1px", "::after": "1px"}, + "left": {"::before": "1px", "::after": "1px"}, + "zIndex": {"::before": -1}, + "backgroundColor": {"::before": "var(--color-surface)"}, + "backgroundImage": { + "::before": { + "@media (pointer: coarse)": { + ":active:not(:has(:focus-visible), :has(:disabled))": "linear-gradient(var(--gray-a4), var(--gray-a4))" + }, + ":has(:disabled)": "linear-gradient(var(--gray-a2), var(--gray-a2))", + } + }, + "boxShadow": { + "default": "var(--rx-if-light, 0 0 0 0 color-mix(in oklab, var(--gray-a3), var(--gray-3) 25%), 0 0 0 0 var(--color-transparent), 0 0 0 0 var(--black-a1), 0 1px 1px -1px var(--gray-a2), 0 2px 1px -2px var(--black-a1), 0 1px 3px -1px var(--black-a1)) var(--rx-if-dark, 0 0 0 0 color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 0 0 var(--color-transparent), 0 0 0 0 var(--black-a3), 0 1px 1px -1px var(--black-a6), 0 2px 1px -2px var(--black-a6), 0 1px 3px -1px var(--black-a5))", + "@media (hover: hover)": { + ":hover:not(:has(:disabled))": "var(--rx-if-light, 0 0 0 0 color-mix(in oklab, var(--gray-a4), var(--gray-4) 25%), 0 1px 1px 0 var(--black-a1), 0 2px 1px -2px var(--gray-a3), 0 2px 3px -3px var(--black-a1), 0 3px 12px -5px var(--gray-a3), 0 4px 16px -9px var(--black-a1)) var(--rx-if-dark, 0 0 0 0 color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 1px 0 var(--gray-a4), 0 0 1px -2px var(--gray-a4), 0 0 3px -3px var(--gray-a3), 0 0 12px -3px var(--gray-a3), 0 0 16px -9px var(--gray-a7))" + }, + "::after": { + "default": "var(--rx-if-light, 0 0 0 1px color-mix(in oklab, var(--gray-a3), var(--gray-3) 25%), 0 0 0 1px var(--color-transparent), 0 0 0 0.5px var(--black-a1), 0 1px 1px 0 var(--gray-a2), 0 2px 1px -1px var(--black-a1), 0 1px 3px 0 var(--black-a1)) var(--rx-if-dark, 0 0 0 1px color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 0 1px var(--color-transparent), 0 0 0 0.5px var(--black-a3), 0 1px 1px 0 var(--black-a6), 0 2px 1px -1px var(--black-a6), 0 1px 3px 0 var(--black-a5))", + "@media (hover: hover)": { + ":hover:not(:has(:disabled))": "var(--rx-if-light, 0 0 0 1px color-mix(in oklab, var(--gray-a4), var(--gray-4) 25%), 0 1px 1px 1px var(--black-a1), 0 2px 1px -1px var(--gray-a3), 0 2px 3px -2px var(--black-a1), 0 3px 12px -4px var(--gray-a3), 0 4px 16px -8px var(--black-a1)) var(--rx-if-dark, 0 0 0 1px color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 1px 1px var(--gray-a4), 0 0 1px -1px var(--gray-a4), 0 0 3px -2px var(--gray-a3), 0 0 12px -2px var(--gray-a3), 0 0 16px -8px var(--gray-a7))" + }, + }, + }, + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::before": { + "default": "var(--color-surface)", + ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-12)", + ":disabled": "transparent", + }, + "::after": { + "default": "var(--accent-1)", + ":disabled": "var(--gray-a8)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": "inherit", + "fontSize": "inherit", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "textIndent": "initial", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "WebkitTapHighlightColor": "transparent", + "position": {"default": "absolute", "::after": "absolute"}, + "right": "var(--checkbox-cards-item-padding-left)", + "display": {"default": "inline-flex", "::before": "block"}, + "alignItems": "center", + "justifyContent": "center", + "verticalAlign": "top", + "flexShrink": 0, + "cursor": "var(--cursor-checkbox)", + "height": { + "default": "var(--line-height, var(--checkbox-size))", + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "content": { + "::before": "''", + "::after": {":is(:checked, :indeterminate)": "''"}, + }, + "width": { + "::before": "var(--checkbox-size)", + "::after": "var(--checkbox-indicator-size)", + }, + "borderRadius": {"::before": "var(--checkbox-border-radius)"}, + "transform": {"::after": "translate(-50%, -50%)"}, + "top": {"::after": "50%"}, + "left": {"::after": "50%"}, + "pointerEvents": {"::after": "none"}, + "maskImage": { + "::after": { + "default": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z'/%3E%3C/svg%3E\")", + ":indeterminate": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0.75 4.5C0.75 4.08579 1.08579 3.75 1.5 3.75H7.5C7.91421 3.75 8.25 4.08579 8.25 4.5C8.25 4.91421 7.91421 5.25 7.5 5.25H1.5C1.08579 5.25 0.75 4.91421 0.75 4.5Z'/%3E%3C/svg%3E\")", + } + }, + "maskSize": {"::after": "100% 100%"}, + "maskRepeat": {"::after": "no-repeat"}, + "--checkbox-size": { + "default": "calc(var(--space-4) * 0.875)", + "@media (min-width: 1024px)": "calc(var(--space-4) * 1.25)", + }, + "--checkbox-indicator-size": { + "default": "calc(9px * var(--scaling))", + "@media (min-width: 1024px)": "calc(12px * var(--scaling))", + }, + "--checkbox-border-radius": { + "default": "calc(var(--radius-1) * 0.875)", + "@media (min-width: 1024px)": "calc(var(--radius-1) * 1.25)", + }, + "boxShadow": { + "::before": { + "default": "inset 0 0 0 1px var(--gray-a7)", + ":is(:checked, :indeterminate):not(:disabled)": "none", + ":disabled": "inset 0 0 0 1px var(--gray-a6)", + } + }, + }, + ] + + +def test_checkbox_cards_bound_to_state( + ui_plugin: UIPlugin, +): + """A bound group checks the cards of its value, and a change hands the value over.""" + component = rx.ui.checkbox_cards.root( + rx.ui.checkbox_cards.item("A", value="a"), + value=CardsState.picked, + on_value_change=CardsState.pick, + name="pick", + required=True, + orientation="horizontal", + loop=True, + dir="rtl", + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_076463c881_c", + 'dir:"rtl"', + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_checkbox_cards____cards_state.pick", ({ ["picked"] : Array.from(_e.currentTarget.querySelectorAll("input[type=checkbox]:checked")).filter((input) => input.name === _e.target.name).map((input) => input.value) }), ({ })))], [_e], ({ }))))', + 'role:"group"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_12056722ee_c", '"data-rx-cards-item":""'], + "children": [ + {"contents": '"A"'}, + { + "name": '"input"', + "props": [ + 'checked:(reflex___state____state__tests___units___reflex_components_ui___components___test_checkbox_cards____cards_state.picked_rx_state_.includes("a"))', + "className:sx_e9aee32af5_c", + 'name:"pick"', + "readOnly:true", + "required:true", + 'type:"checkbox"', + 'value:"a"', + ], + "children": [], + }, + ], + } + ], + } + + +def test_checkbox_cards_unknown_variant(ui_plugin: UIPlugin): + """A variant a group of cards does not have is an error that lists the ones it has.""" + with pytest.raises(TypeError) as error: + rx.ui.checkbox_cards.root(variant="soft") + assert ( + str(error.value) + == "Invalid var passed for prop CheckboxCardsRoot.variant, expected type typing.Literal['classic', 'surface'], got value 'soft' of type ." + ) diff --git a/tests/units/reflex_components_ui/components/test_radio_cards.py b/tests/units/reflex_components_ui/components/test_radio_cards.py new file mode 100644 index 00000000000..79548273d0d --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_radio_cards.py @@ -0,0 +1,575 @@ +"""Tests for reflex_components_ui.components.radio_cards.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +class CardsState(rx.State): + """What a group of cards is bound to.""" + + picked: str = "a" + + @rx.event + def pick(self, picked: str): + """Follow the group. + + Args: + picked: What is checked. + """ + self.picked = picked + + +def test_radio_cards( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A card is a label around a native input, which the group gives its name, its look and its state.""" + component = rx.ui.radio_cards.root( + rx.ui.radio_cards.item("One", value="1", id="one", margin="1px"), + rx.ui.radio_cards.item("Two", value="2", disabled=True), + default_value="1", + name="pick", + id="group", + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_a11baf901a_c", + 'id:"group"', + "ref:ref_group", + 'role:"radiogroup"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_b5ba4311cf_c", '"data-rx-cards-item":""'], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8e51139181_c", + "defaultChecked:true", + 'id:"one"', + 'name:"pick"', + "ref:ref_one", + 'type:"radio"', + 'value:"1"', + ], + "children": [], + }, + {"contents": '"One"'}, + ], + }, + { + "name": '"label"', + "props": ["className:sx_a4bbfb9e0c_c", '"data-rx-cards-item":""'], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8e51139181_c", + "disabled:true", + 'name:"pick"', + 'type:"radio"', + 'value:"2"', + ], + "children": [], + }, + {"contents": '"Two"'}, + ], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "stretch", + "justifyContent": "flex-start", + "gridTemplateColumns": "repeat(auto-fit, minmax(160px, 1fr))", + "gridTemplateRows": "none", + "rowGap": "var(--space-4)", + "columnGap": "var(--space-4)", + "lineHeight": "var(--line-height)", + "letterSpacing": "var(--letter-spacing)", + "cursor": "default", + "fontSize": "var(--font-size-2)", + "--line-height": "var(--line-height-2)", + "--letter-spacing": "var(--letter-spacing-2)", + "--radio-cards-item-padding-x": "var(--space-4)", + "--radio-cards-item-padding-y": "calc(var(--space-4) * 0.875)", + "--radio-cards-item-border-radius": "var(--radius-3)", + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--radio-cards-item-border-radius)", + "::before": "calc(var(--radio-cards-item-border-radius) - 1px)", + "::after": "calc(var(--radio-cards-item-border-radius) - 1px)", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "paddingTop": "var(--radio-cards-item-padding-y)", + "paddingRight": "var(--radio-cards-item-padding-x)", + "paddingBottom": "var(--radio-cards-item-padding-y)", + "paddingLeft": "var(--radio-cards-item-padding-x)", + "boxSizing": "border-box", + "contain": "paint", + "--inset-border-width": "1px", + "--inset-border-radius": "var(--radio-cards-item-border-radius)", + "--inset-padding-top": "calc(var(--radio-cards-item-padding-y) - 1px)", + "--inset-padding-right": "calc(var(--radio-cards-item-padding-x) - 1px)", + "--inset-padding-bottom": "calc(var(--radio-cards-item-padding-y) - 1px)", + "--inset-padding-left": "calc(var(--radio-cards-item-padding-x) - 1px)", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "var(--cursor-button)", + ":has(:disabled)": "var(--cursor-disabled)", + }, + "justifyContent": "center", + "color": {"default": "inherit", ":has(:disabled)": "var(--gray-a9)"}, + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": {"::before": "inherit", "::after": "inherit"}, + "transitionDuration": {"::before": "inherit", "::after": "inherit"}, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "top": {"::before": "1px", "::after": "1px"}, + "right": {"::before": "1px", "::after": "1px"}, + "bottom": {"::before": "1px", "::after": "1px"}, + "left": {"::before": "1px", "::after": "1px"}, + "zIndex": {"::before": -1}, + "backgroundColor": {"::before": "var(--color-surface)"}, + "backgroundImage": { + "::before": { + ":has(:checked):has(:focus-visible)": "linear-gradient(var(--focus-a3), var(--focus-a3))", + ":has(:disabled)": "linear-gradient(var(--gray-a2), var(--gray-a2))", + } + }, + "outlineOffset": {"::after": "-1px"}, + "outlineStyle": { + "::after": {":has(:checked)": "solid", ":has(:focus-visible)": "solid"} + }, + "outlineWidth": { + "::after": {":has(:checked)": "2px", ":has(:focus-visible)": "2px"} + }, + "outlineColor": { + "::after": { + ":has(:checked):not(:has(:focus-visible), :has(:disabled))": "var(--accent-indicator)", + ":has(:focus-visible):not(:has(:checked))": "var(--focus-8)", + ":has(:checked):has(:focus-visible)": "var(--focus-10)", + ":has(:disabled)": "var(--gray-8)", + } + }, + "boxShadow": { + "::after": { + "default": "0 0 0 1px color-mix(in oklab, var(--gray-a5), var(--gray-5) 25%)", + "@media (hover: hover)": { + ":hover:not(:has(:checked), :has(:disabled))": "0 0 0 1px color-mix(in oklab, var(--gray-a7), var(--gray-7) 25%)" + }, + } + }, + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + }, + { + "appearance": "none", + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "opacity": 0, + "pointerEvents": "none", + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--radio-cards-item-border-radius)", + "::before": "calc(var(--radio-cards-item-border-radius) - 1px)", + "::after": "calc(var(--radio-cards-item-border-radius) - 1px)", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "paddingTop": "var(--radio-cards-item-padding-y)", + "paddingRight": "var(--radio-cards-item-padding-x)", + "paddingBottom": "var(--radio-cards-item-padding-y)", + "paddingLeft": "var(--radio-cards-item-padding-x)", + "boxSizing": "border-box", + "contain": "paint", + "--inset-border-width": "1px", + "--inset-border-radius": "var(--radio-cards-item-border-radius)", + "--inset-padding-top": "calc(var(--radio-cards-item-padding-y) - 1px)", + "--inset-padding-right": "calc(var(--radio-cards-item-padding-x) - 1px)", + "--inset-padding-bottom": "calc(var(--radio-cards-item-padding-y) - 1px)", + "--inset-padding-left": "calc(var(--radio-cards-item-padding-x) - 1px)", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "var(--cursor-button)", + ":has(:disabled)": "var(--cursor-disabled)", + }, + "justifyContent": "center", + "color": {"default": "inherit", ":has(:disabled)": "var(--gray-a9)"}, + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": {"::before": "inherit", "::after": "inherit"}, + "transitionDuration": {"::before": "inherit", "::after": "inherit"}, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "top": {"::before": "1px", "::after": "1px"}, + "right": {"::before": "1px", "::after": "1px"}, + "bottom": {"::before": "1px", "::after": "1px"}, + "left": {"::before": "1px", "::after": "1px"}, + "zIndex": {"::before": -1}, + "backgroundColor": {"::before": "var(--color-surface)"}, + "backgroundImage": { + "::before": { + ":has(:checked):has(:focus-visible)": "linear-gradient(var(--focus-a3), var(--focus-a3))", + ":has(:disabled)": "linear-gradient(var(--gray-a2), var(--gray-a2))", + } + }, + "outlineOffset": {"::after": "-1px"}, + "outlineStyle": { + "::after": {":has(:checked)": "solid", ":has(:focus-visible)": "solid"} + }, + "outlineWidth": { + "::after": {":has(:checked)": "2px", ":has(:focus-visible)": "2px"} + }, + "outlineColor": { + "::after": { + ":has(:checked):not(:has(:focus-visible), :has(:disabled))": "var(--accent-indicator)", + ":has(:focus-visible):not(:has(:checked))": "var(--focus-8)", + ":has(:checked):has(:focus-visible)": "var(--focus-10)", + ":has(:disabled)": "var(--gray-8)", + } + }, + "boxShadow": { + "::after": { + "default": "0 0 0 1px color-mix(in oklab, var(--gray-a5), var(--gray-5) 25%)", + "@media (hover: hover)": { + ":hover:not(:has(:checked), :has(:disabled))": "0 0 0 1px color-mix(in oklab, var(--gray-a7), var(--gray-7) 25%)" + }, + } + }, + }, + { + "appearance": "none", + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "opacity": 0, + "pointerEvents": "none", + }, + ] + + +def test_radio_cards_classic( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The size, the variant and the contrast of a group are the ones of its cards, and its columns and gap the ones of its grid.""" + component = rx.ui.radio_cards.root( + rx.ui.radio_cards.item("One", value="1"), + name="pick", + size=rx.breakpoints(initial="1", md="3"), + variant="classic", + high_contrast=True, + color_scheme="ruby", + columns="2", + gap="6", + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_ad19158c20_c + " " + reflexUIClasses_e201574881', + 'role:"radiogroup"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_9366874d90_c", '"data-rx-cards-item":""'], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8e51139181_c", + 'name:"pick"', + 'type:"radio"', + 'value:"1"', + ], + "children": [], + }, + {"contents": '"One"'}, + ], + } + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "grid", + "alignItems": "stretch", + "justifyContent": "flex-start", + "gridTemplateColumns": "repeat(2, minmax(0, 1fr))", + "gridTemplateRows": "none", + "rowGap": "var(--space-6)", + "columnGap": "var(--space-6)", + "lineHeight": "var(--line-height)", + "letterSpacing": "var(--letter-spacing)", + "cursor": "default", + "fontSize": { + "default": "var(--font-size-2)", + "@media (min-width: 1024px)": "var(--font-size-3)", + }, + "--line-height": { + "default": "var(--line-height-2)", + "@media (min-width: 1024px)": "var(--line-height-3)", + }, + "--letter-spacing": { + "default": "var(--letter-spacing-2)", + "@media (min-width: 1024px)": "var(--letter-spacing-3)", + }, + "--radio-cards-item-padding-x": { + "default": "var(--space-3)", + "@media (min-width: 1024px)": "var(--space-5)", + }, + "--radio-cards-item-padding-y": { + "default": "calc(var(--space-3) / 1.2)", + "@media (min-width: 1024px)": "calc(var(--space-5) / 1.2)", + }, + "--radio-cards-item-border-radius": { + "default": "var(--radius-3)", + "@media (min-width: 1024px)": "var(--radius-4)", + }, + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "position": { + "default": "relative", + "::before": "absolute", + "::after": "absolute", + }, + "overflowX": "hidden", + "overflowY": "hidden", + "borderRadius": { + "default": "var(--radio-cards-item-border-radius)", + "::before": "calc(var(--radio-cards-item-border-radius) - 1px)", + "::after": "calc(var(--radio-cards-item-border-radius) - 1px)", + }, + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "start", + "paddingTop": "var(--radio-cards-item-padding-y)", + "paddingRight": "var(--radio-cards-item-padding-x)", + "paddingBottom": "var(--radio-cards-item-padding-y)", + "paddingLeft": "var(--radio-cards-item-padding-x)", + "boxSizing": "border-box", + "contain": "paint", + "--inset-border-width": "1px", + "--inset-border-radius": "var(--radio-cards-item-border-radius)", + "--inset-padding-top": "calc(var(--radio-cards-item-padding-y) - 1px)", + "--inset-padding-right": "calc(var(--radio-cards-item-padding-x) - 1px)", + "--inset-padding-bottom": "calc(var(--radio-cards-item-padding-y) - 1px)", + "--inset-padding-left": "calc(var(--radio-cards-item-padding-x) - 1px)", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "var(--cursor-button)", + ":has(:disabled)": "var(--cursor-disabled)", + }, + "justifyContent": "center", + "color": {"default": "inherit", ":has(:disabled)": "var(--gray-a9)"}, + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "content": {"::before": "''", "::after": "''"}, + "pointerEvents": {"::before": "none", "::after": "none"}, + "transitionProperty": { + "default": "box-shadow", + "::before": "inherit", + "::after": "inherit", + }, + "transitionDuration": { + "default": "120ms", + "@media (hover: hover)": { + ":hover:not(:has(:checked), :has(:disabled))": "40ms" + }, + "::before": "inherit", + "::after": "inherit", + }, + "transitionTimingFunction": {"::before": "inherit", "::after": "inherit"}, + "transitionDelay": {"::before": "inherit", "::after": "inherit"}, + "top": {"::before": "1px", "::after": "1px"}, + "right": {"::before": "1px", "::after": "1px"}, + "bottom": {"::before": "1px", "::after": "1px"}, + "left": {"::before": "1px", "::after": "1px"}, + "zIndex": {"::before": -1}, + "backgroundColor": {"::before": "var(--color-surface)"}, + "backgroundImage": { + "::before": { + ":has(:checked):has(:focus-visible)": "linear-gradient(var(--focus-a3), var(--focus-a3))", + ":has(:disabled)": "linear-gradient(var(--gray-a2), var(--gray-a2))", + } + }, + "outlineOffset": {"::after": "-1px"}, + "outlineStyle": { + "::after": {":has(:checked)": "solid", ":has(:focus-visible)": "solid"} + }, + "outlineWidth": { + "::after": {":has(:checked)": "2px", ":has(:focus-visible)": "2px"} + }, + "outlineColor": { + "::after": { + ":has(:checked):not(:has(:focus-visible), :has(:disabled))": "var(--accent-12)", + ":has(:focus-visible):not(:has(:checked))": "var(--focus-8)", + ":has(:checked):has(:focus-visible)": "var(--focus-10)", + ":has(:disabled)": "var(--gray-8)", + } + }, + "boxShadow": { + "default": "var(--rx-if-light, 0 0 0 0 color-mix(in oklab, var(--gray-a3), var(--gray-3) 25%), 0 0 0 0 var(--color-transparent), 0 0 0 0 var(--black-a1), 0 1px 1px -1px var(--gray-a2), 0 2px 1px -2px var(--black-a1), 0 1px 3px -1px var(--black-a1)) var(--rx-if-dark, 0 0 0 0 color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 0 0 var(--color-transparent), 0 0 0 0 var(--black-a3), 0 1px 1px -1px var(--black-a6), 0 2px 1px -2px var(--black-a6), 0 1px 3px -1px var(--black-a5))", + "@media (hover: hover)": { + ":hover:not(:has(:checked), :has(:disabled))": "var(--rx-if-light, 0 0 0 0 color-mix(in oklab, var(--gray-a4), var(--gray-4) 25%), 0 1px 1px 0 var(--black-a1), 0 2px 1px -2px var(--gray-a3), 0 2px 3px -3px var(--black-a1), 0 3px 12px -5px var(--gray-a3), 0 4px 16px -9px var(--black-a1)) var(--rx-if-dark, 0 0 0 0 color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 1px 0 var(--gray-a4), 0 0 1px -2px var(--gray-a4), 0 0 3px -3px var(--gray-a3), 0 0 12px -3px var(--gray-a3), 0 0 16px -9px var(--gray-a7))" + }, + "::after": { + "default": "var(--rx-if-light, 0 0 0 1px color-mix(in oklab, var(--gray-a3), var(--gray-3) 25%), 0 0 0 1px var(--color-transparent), 0 0 0 0.5px var(--black-a1), 0 1px 1px 0 var(--gray-a2), 0 2px 1px -1px var(--black-a1), 0 1px 3px 0 var(--black-a1)) var(--rx-if-dark, 0 0 0 1px color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 0 1px var(--color-transparent), 0 0 0 0.5px var(--black-a3), 0 1px 1px 0 var(--black-a6), 0 2px 1px -1px var(--black-a6), 0 1px 3px 0 var(--black-a5))", + "@media (hover: hover)": { + ":hover:not(:has(:checked), :has(:disabled))": "var(--rx-if-light, 0 0 0 1px color-mix(in oklab, var(--gray-a4), var(--gray-4) 25%), 0 1px 1px 1px var(--black-a1), 0 2px 1px -1px var(--gray-a3), 0 2px 3px -2px var(--black-a1), 0 3px 12px -4px var(--gray-a3), 0 4px 16px -8px var(--black-a1)) var(--rx-if-dark, 0 0 0 1px color-mix(in oklab, var(--gray-a6), var(--gray-6) 25%), 0 0 1px 1px var(--gray-a4), 0 0 1px -1px var(--gray-a4), 0 0 3px -2px var(--gray-a3), 0 0 12px -2px var(--gray-a3), 0 0 16px -8px var(--gray-a7))" + }, + }, + }, + }, + { + "appearance": "none", + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "opacity": 0, + "pointerEvents": "none", + }, + ] + + +def test_radio_cards_bound_to_state( + ui_plugin: UIPlugin, +): + """A bound group checks the cards of its value, and a change hands the value over.""" + component = rx.ui.radio_cards.root( + rx.ui.radio_cards.item("A", value="a"), + value=CardsState.picked, + on_value_change=CardsState.pick, + name="pick", + required=True, + orientation="horizontal", + loop=True, + dir="rtl", + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_a11baf901a_c", + 'dir:"rtl"', + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_radio_cards____cards_state.pick", ({ ["picked"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))', + 'role:"radiogroup"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_a4bbfb9e0c_c", '"data-rx-cards-item":""'], + "children": [ + { + "name": '"input"', + "props": [ + 'checked:(reflex___state____state__tests___units___reflex_components_ui___components___test_radio_cards____cards_state.picked_rx_state_ === "a")', + "className:sx_8e51139181_c", + 'name:"pick"', + "readOnly:true", + "required:true", + 'type:"radio"', + 'value:"a"', + ], + "children": [], + }, + {"contents": '"A"'}, + ], + } + ], + } + + +def test_radio_cards_unknown_variant(ui_plugin: UIPlugin): + """A variant a group of cards does not have is an error that lists the ones it has.""" + with pytest.raises(TypeError) as error: + rx.ui.radio_cards.root(variant="soft") + assert ( + str(error.value) + == "Invalid var passed for prop RadioCardsRoot.variant, expected type typing.Literal['classic', 'surface'], got value 'soft' of type ." + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 55c3155fe7d..cffb2445383 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -116,6 +116,8 @@ def test_every_wave_is_in_the_namespace(): "card", "center", "checkbox", + "checkbox_cards.item", + "checkbox_cards.root", "checkbox_group.item", "checkbox_group.root", "code", @@ -142,6 +144,8 @@ def test_every_wave_is_in_the_namespace(): "radio", "radio.item", "radio.root", + "radio_cards.item", + "radio_cards.root", "radio_group", "radio_group.item", "radio_group.root", From bae63a8c69ea631c5a64c4dd6be76b287260fbd9 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 01:54:36 +0000 Subject: [PATCH 073/204] Add rx.ui.input, rx.ui.text_field and rx.ui.text_area A box around a native control, whose state the box reads with :has(). A control bound to state keeps the debounce wrapper rx.input has. The one script gives the input the focus from a slot. The lowering writes a whole shorthand that only applies under a condition before its longhands: StyleX took the radius of a pseudo-element to cancel the corners of the element itself. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- packages/reflex-components-ui/js/src/base.css | 32 + .../js/src/behaviors/text-field.js | 33 + .../js/tests/behaviors/text-field.test.js | 89 +++ .../parity/ui_parity/components/text_area.py | 274 ++++++++ .../parity/ui_parity/components/text_field.py | 374 +++++++++++ .../parity/ui_parity/look.py | 16 +- .../src/reflex_components_ui/__init__.py | 2 + .../components/text_area.py | 157 +++++ .../components/text_field.py | 350 ++++++++++ .../src/reflex_components_ui/style/lower.py | 46 ++ .../reflex_components_ui/styles/text_area.py | 228 +++++++ .../reflex_components_ui/styles/text_field.py | 355 ++++++++++ .../components/test_text_area.py | 497 ++++++++++++++ .../components/test_text_field.py | 633 ++++++++++++++++++ .../reflex_components_ui/style/test_lower.py | 42 ++ .../reflex_components_ui/test_api_parity.py | 7 + 16 files changed, 3132 insertions(+), 3 deletions(-) create mode 100644 packages/reflex-components-ui/js/src/behaviors/text-field.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/text-field.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/text_area.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/text_field.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/text_area.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/text_field.py create mode 100644 tests/units/reflex_components_ui/components/test_text_area.py create mode 100644 tests/units/reflex_components_ui/components/test_text_field.py diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index 656f86d9490..147fd1998e1 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -89,6 +89,38 @@ html.dark { [data-rx-cards-item] > svg { flex-shrink: 0; } + + /* The thumb of the scrollbar of a text area, under the pointer. */ + @media (hover: hover) { + [data-rx-text-area-input]:not(:disabled)::-webkit-scrollbar-thumb:hover { + background-color: var(--gray-a9); + } + } + + /* + * The fields and the icon the browser lays a date or a time out as, in a + * text field: a state of one of them is no state of the input, so no + * class on the input can say it. + */ + [data-rx-text-field-input]::-webkit-calendar-picker-indicator:hover { + background-color: var(--gray-a3); + } + [data-rx-text-field-input]::-webkit-calendar-picker-indicator:focus-visible { + outline: 2px solid var(--text-field-focus-color); + } + [data-rx-text-field-input]::-webkit-datetime-edit-ampm-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-day-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-hour-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-millisecond-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-minute-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-month-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-second-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-week-field:focus, + [data-rx-text-field-input]::-webkit-datetime-edit-year-field:focus { + background-color: var(--text-field-selection-color); + color: inherit; + outline: none; + } } /* diff --git a/packages/reflex-components-ui/js/src/behaviors/text-field.js b/packages/reflex-components-ui/js/src/behaviors/text-field.js new file mode 100644 index 00000000000..229f13465f7 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/text-field.js @@ -0,0 +1,33 @@ +// What a pointer on the box of a text field does when it is not on the +// input: on a slot that holds an icon, or on the edge of the box. +// +// Without it the input still takes the focus from a pointer on the input +// itself, from the keyboard and from its label. + +/** + * Give the input of a text field the focus: the `onPointerDown` of its box. + * + * The caret goes to the end of the value from a slot on the right and to + * its start from anywhere else. A button or a link in a slot keeps the + * pointer for itself. + * + * @param {{ target: EventTarget | null, currentTarget: Element }} event The + * pointer going down inside the box. + * @returns {void} + */ +export function focusField(event) { + const target = event.target; + if (!(target instanceof Element) || target.closest("input, button, a")) return; + const input = event.currentTarget.querySelector("input"); + if (!input) return; + const caret = target.closest("[data-side='right']") ? input.value.length : 0; + requestAnimationFrame(() => { + try { + // An input without text, such as a date, has no caret to place. + input.setSelectionRange(caret, caret); + } catch { + // The focus is all it takes then. + } + input.focus(); + }); +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/text-field.test.js b/packages/reflex-components-ui/js/tests/behaviors/text-field.test.js new file mode 100644 index 00000000000..3f28e9ce656 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/text-field.test.js @@ -0,0 +1,89 @@ +// What a pointer on the box of a text field does: the input takes the focus, +// with its caret at the end the pointer is nearest to. +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { focusField } from "$/reflex-ui/behaviors/text-field.js"; + +/** @type {HTMLElement} */ +let box; +/** @type {HTMLInputElement} */ +let input; + +beforeEach(() => { + document.body.innerHTML = ` +
+ +
+ +
x
+
+
`; + box = /** @type {HTMLElement} */ (document.getElementById("box")); + input = /** @type {HTMLInputElement} */ (box.querySelector("input")); + // The focus waits for a frame, as the pointer is still going down. + vi.stubGlobal( + "requestAnimationFrame", + (/** @type {FrameRequestCallback} */ callback) => { + callback(0); + return 0; + }, + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +/** + * Put the pointer down on an element of a box. + * + * @param {string} id The id of the element. + * @param {Element} [currentTarget] The box, when it is not the first one. + * @returns {void} + */ +function pointerDown(id, currentTarget = box) { + focusField({ target: document.getElementById(id), currentTarget }); +} + +test("a pointer on a left slot focuses the input at the start of its text", () => { + pointerDown("icon"); + expect(document.activeElement).toBe(input); + expect([input.selectionStart, input.selectionEnd]).toEqual([0, 0]); +}); + +test("a pointer on a right slot focuses the input at the end of its text", () => { + pointerDown("right"); + expect(document.activeElement).toBe(input); + expect([input.selectionStart, input.selectionEnd]).toEqual([6, 6]); +}); + +test("a pointer on the box itself focuses the input at the start", () => { + pointerDown("box"); + expect(document.activeElement).toBe(input); + expect([input.selectionStart, input.selectionEnd]).toEqual([0, 0]); +}); + +test("a button, a link and the input keep the pointer for themselves", () => { + input.setSelectionRange(3, 3); + for (const id of ["clear", "link"]) { + pointerDown(id); + expect(document.activeElement).toBe(document.body); + } + focusField({ target: input, currentTarget: box }); + expect(document.activeElement).toBe(document.body); + expect(input.selectionStart).toBe(3); +}); + +test("an input without a caret, such as a date, still takes the focus", () => { + input.type = "date"; + pointerDown("right"); + expect(document.activeElement).toBe(input); +}); + +test("a box without an input and a target that is no element do nothing", () => { + const empty = /** @type {HTMLElement} */ (document.getElementById("empty")); + pointerDown("alone", empty); + focusField({ target: null, currentTarget: box }); + focusField({ target: document, currentTarget: box }); + expect(document.activeElement).toBe(document.body); +}); diff --git a/packages/reflex-components-ui/parity/ui_parity/components/text_area.py b/packages/reflex-components-ui/parity/ui_parity/components/text_area.py new file mode 100644 index 00000000000..45915651e26 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/text_area.py @@ -0,0 +1,274 @@ +"""The text area: every variant, size and state, and what it does with text.""" + +from __future__ import annotations + +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import FOCUS_WITHIN +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, PARAGRAPH, focused, wait_for_text + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +RADII = ["none", "small", "medium", "large", "full"] +STATES = ["rest", HOVER, FOCUS_VISIBLE] +RESIZE = ["none", "vertical", "horizontal", "both"] + +MATRIX = Matrix( + component="text_area", + base={"placeholder": "Say something"}, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "color_scheme": ACCENTS, + "radius": RADII, + "disabled": [True], + "read_only": [True], + "default_value": {"hello": "Hello", "long": PARAGRAPH * 4}, + "rows": ["2", "6"], + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "resize": [*RESIZE, rx.breakpoints(initial="none", sm="both")], + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "default_value": ["Hello"], + "disabled": [False, True], + "read_only": [False, True], + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "disabled": [True], "appearance": [LIGHT, DARK]}, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "state": STATES, + "default_value": ["Hello"], + }, + {"variant": VARIANTS, "state": STATES, "appearance": [LIGHT, DARK]}, + {"variant": VARIANTS, "default_value": {"long": PARAGRAPH * 4}}, + {"radius": RADII, "size": SIZES}, + {"resize": RESIZE, "variant": VARIANTS}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(260, 160), + parts={"textarea": "textarea"}, + # The focus is on the textarea inside the box. + states={FOCUS_VISIBLE: FOCUS_WITHIN}, + # Every cell is equal at the default threshold. At a threshold of zero + # 7 of them differ, the disabled and read-only ones: their fill is a + # gradient, which is dithered by a step of a channel by where the text + # area is on the page. + tolerance=0, +) + + +class TextAreaState(rx.State): + """What the text areas of the contract are bound to.""" + + bound: str = "start" + seen: list[str] = [] + submitted: dict[str, Any] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, value: str): + """Follow the bound text area. + + Args: + value: Its text. + """ + self.bound = value + + @rx.event + def see(self, value: str): + """Keep what an event handed over. + + Args: + value: The text of the text area. + """ + self.seen.append(value) + + @rx.event + def reset_bound(self): + """Change the bound value from outside the text area.""" + self.bound = "reset" + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +CONTRACT = Contract( + component="text_area", + render=lambda namespace: namespace.box( + rx.el.label("Notes", html_for="notes"), + namespace.text_area( + id="notes", placeholder="Your notes", on_change=TextAreaState.see, rows="2" + ), + namespace.text_area(id="off", disabled=True, default_value="off"), + namespace.text_area(id="fixed", read_only=True, default_value="fixed"), + namespace.text_area( + id="events", + aria_label="Events", + on_focus=TextAreaState.see, + on_blur=TextAreaState.see, + default_value="e", + ), + namespace.text_area( + id="bound", + aria_label="Bound", + value=TextAreaState.bound, + on_change=TextAreaState.set_bound, + ), + rx.el.button("Reset", id="reset", on_click=TextAreaState.reset_bound), + rx.el.button("Set", id="set", on_click=rx.set_value("notes", "set")), + rx.el.button("Focus", id="focus", on_click=rx.set_focus("notes")), + rx.el.form( + namespace.text_area(id="q", name="q", required=True, max_length=4), + rx.el.button("Send", id="send", type="submit"), + on_submit=TextAreaState.submit, + id="form", + ), + rx.el.span(TextAreaState.seen.to_string(), id="seen"), + rx.el.span(TextAreaState.bound, id="bound-value"), + rx.el.span(TextAreaState.submitted.to_string(), id="submitted"), + rx.el.span(TextAreaState.submissions.to_string(), id="submissions"), + ), +) + + +@CONTRACT.step("is a textarea with its attributes in the server render", on=SERVER) +def _server_render(run: Run) -> None: + notes = run.server.element("notes") + assert (notes.tag, notes.attributes["placeholder"], notes.attributes["rows"]) == ( + "textarea", + "Your notes", + "2", + ) + assert run.server.element("off").text == "off" + assert "disabled" in run.server.element("off").attributes + assert "readonly" in run.server.element("fixed").attributes + assert run.server.element("bound").text == "start" + + +@CONTRACT.step("takes the focus and text with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.get_by_text("Notes", exact=True).click() + assert focused(page) == "notes" + page.keyboard.type("one") + page.keyboard.press("Enter") + page.keyboard.type("two") + assert page.locator("#notes").input_value() == "one\ntwo" + + +@CONTRACT.step("has the role and the name of a text box, and its label") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("textbox", name="Notes").get_attribute("id") == "notes" + assert page.get_by_label("Notes", exact=True).get_attribute("id") == "notes" + assert page.get_by_role("textbox", name="Events").get_attribute("id") == "events" + assert page.get_by_role("textbox", disabled=True).count() == 1 + + +@CONTRACT.step("Tab stops on each text area but a disabled one") +def _tab(run: Run) -> None: + stops = [] + for _ in range(4): + run.page.keyboard.press("Tab") + stops.append(focused(run.page)) + assert stops == ["notes", "fixed", "events", "bound"] + + +@CONTRACT.step("typing changes the text and says so, key by key") +def _type(run: Run) -> None: + page = run.page + page.locator("#notes").focus() + page.keyboard.type("Ada", delay=30) + assert page.locator("#notes").input_value() == "Ada" + wait_for_text(page, "seen", '["A","Ad","Ada"]') + + +@CONTRACT.step("focus and blur hand over the text") +def _focus_blur(run: Run) -> None: + page = run.page + page.locator("#events").focus() + wait_for_text(page, "seen", '["e"]') + page.keyboard.press("Control+End") + page.keyboard.type("x") + page.keyboard.press("Tab") + wait_for_text(page, "seen", '["e","ex"]') + + +@CONTRACT.step( + "a disabled text area takes no text, and a read-only one the focus alone" +) +def _disabled(run: Run) -> None: + page = run.page + assert page.locator("#off").is_disabled() + page.locator("#fixed").focus() + page.keyboard.type("x") + assert page.locator("#fixed").input_value() == "fixed" + assert focused(page) == "fixed" + + +@CONTRACT.step("a text area bound to state keeps what is typed and follows the state") +def _bound(run: Run) -> None: + page = run.page + bound = page.locator("#bound") + assert bound.input_value() == "start" + bound.focus() + page.keyboard.press("Control+End") + page.keyboard.type(" and more", delay=15) + assert bound.input_value() == "start and more" + wait_for_text(page, "bound-value", "start and more") + assert bound.input_value() == "start and more" + page.locator("#reset").click() + wait_for_text(page, "bound-value", "reset") + page.wait_for_function("document.getElementById('bound').value === 'reset'") + + +@CONTRACT.step("rx.set_value and rx.set_focus reach the textarea by its id") +def _refs(run: Run) -> None: + page = run.page + page.locator("#set").click() + page.wait_for_function("document.getElementById('notes').value === 'set'") + page.locator("#focus").click() + page.wait_for_function("document.activeElement.id === 'notes'") + + +@CONTRACT.step("submits its text with a form") +def _submit(run: Run) -> None: + page = run.page + page.locator("#q").focus() + page.keyboard.type("abcdefg") + assert page.locator("#q").input_value() == "abcd" + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == '{"q":"abcd"}' + + +@CONTRACT.step("a required text area holds its form back until it has text") +def _required(run: Run) -> None: + page = run.page + page.locator("#send").click() + # An event that does reach the server comes back after the blocked one. + page.locator("#reset").click() + wait_for_text(page, "bound-value", "reset") + assert page.locator("#submissions").text_content() == "0" + page.locator("#q").fill("ok") + page.locator("#send").click() + wait_for_text(page, "submissions", "1") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/text_field.py b/packages/reflex-components-ui/parity/ui_parity/components/text_field.py new file mode 100644 index 00000000000..b8541fdfc2f --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/text_field.py @@ -0,0 +1,374 @@ +"""The text field: every variant, size and state, its slots, and what it does with text.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import FOCUS_WITHIN +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, focused, wait_for_text + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +RADII = ["none", "small", "medium", "large", "full"] +STATES = ["rest", HOVER, FOCUS_VISIBLE] +HOLDS = ["icon", "end", "both", "two", "button", "color"] + + +def _field(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a text field, with the slots a cell says it holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``holds`` names its slots. + + Returns: + The text field. + """ + props = dict(props) + holds = props.pop("holds", None) + slot = namespace.input.slot + slots: list[Any] = [] + if holds == "icon": + slots = [slot(rx.icon("search", size=16))] + elif holds == "end": + slots = [slot("kg", side="right")] + elif holds == "both": + slots = [ + slot(rx.icon("search", size=16), side="left"), + slot("kg", side="right"), + ] + elif holds == "two": + slots = [slot(rx.icon("search", size=16)), slot("kg")] + elif holds == "button": + slots = [ + slot( + namespace.icon_button(rx.icon("x", size=14), size="1", variant="ghost"), + side="right", + ) + ] + elif holds == "color": + slots = [slot(rx.icon("search", size=16), color_scheme="ruby")] + return namespace.input(*slots, **props) + + +MATRIX = Matrix( + component="text_field", + render=_field, + base={"placeholder": "Search"}, + cross={"variant": VARIANTS, "size": SIZES, "holds": [None, "both"]}, + sweep={ + "color_scheme": ACCENTS, + "radius": RADII, + "disabled": [True], + "read_only": [True], + "default_value": ["Hello"], + "type": ["password", "number", "search", "email", "date", "time"], + "holds": HOLDS, + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "default_value": ["Hello"], + "disabled": [False, True], + "read_only": [False, True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "disabled": [True], + "appearance": [LIGHT, DARK], + }, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "state": STATES, + "default_value": ["Hello"], + }, + {"variant": VARIANTS, "state": STATES, "appearance": [LIGHT, DARK]}, + {"variant": VARIANTS, "holds": HOLDS, "size": ["1", "3"]}, + {"variant": VARIANTS, "holds": ["both"], "disabled": [True]}, + {"radius": RADII, "size": SIZES, "holds": [None, "both"]}, + { + "type": ["password", "date", "time"], + "default_value": {"filled": "2024-05-06"}, + "holds": [None, "icon"], + }, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(260, 80), + parts={"input": "input"}, + # The focus is on the input inside the box. + states={FOCUS_VISIBLE: FOCUS_WITHIN}, + # Not held to zero. At a threshold of zero 199 of the 217 cells are equal + # pixel for pixel, and the others differ by where they are on the page: + # the fill of a disabled or read-only field is a gradient, which is + # dithered by a step of a channel, and the corners of the larger radii + # are anti-aliased otherwise. At the default threshold 2 cells differ, by + # 2 pixels of 11712 on a corner of the full radius. + tolerance=0.0002, +) + + +class TextFieldState(rx.State): + """What the text fields of the contract are bound to.""" + + bound: str = "start" + seen: list[str] = [] + keys: list[str] = [] + submitted: dict[str, Any] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, value: str): + """Follow the bound field. + + Args: + value: Its text. + """ + self.bound = value + + @rx.event + def see(self, value: str): + """Keep what an event handed over. + + Args: + value: The text of the field. + """ + self.seen.append(value) + + @rx.event + def see_key(self, key: str): + """Keep the key an event handed over. + + Args: + key: The key. + """ + self.keys.append(key) + + @rx.event + def reset_bound(self): + """Change the bound value from outside the field.""" + self.bound = "reset" + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +CONTRACT = Contract( + component="text_field", + render=lambda namespace: namespace.box( + rx.el.label("Name", html_for="name"), + namespace.input( + id="name", + placeholder="Your name", + on_change=TextFieldState.see, + on_key_down=TextFieldState.see_key, + ), + namespace.input(id="off", disabled=True, default_value="off"), + namespace.input(id="fixed", read_only=True, default_value="fixed"), + namespace.input( + id="events", + aria_label="Events", + on_focus=TextFieldState.see, + on_blur=TextFieldState.see, + default_value="e", + ), + namespace.input( + id="bound", + aria_label="Bound", + value=TextFieldState.bound, + on_change=TextFieldState.set_bound, + ), + rx.el.button("Reset", id="reset", on_click=TextFieldState.reset_bound), + rx.el.button("Set", id="set", on_click=rx.set_value("name", "set")), + rx.el.button("Focus", id="focus", on_click=rx.set_focus("name")), + rx.el.div( + namespace.input( + namespace.input.slot(rx.icon("search", size=16), id="left-slot"), + namespace.input.slot("kg", side="right", id="right-slot"), + namespace.input.slot( + rx.el.button("Clear", id="clear", type="button"), side="right" + ), + id="slotted", + aria_label="Slotted", + default_value="abcdef", + ), + id="slots", + style={"width": "300px"}, + ), + rx.el.div(namespace.input(id="hidden", type="hidden", name="h"), id="gone"), + rx.el.form( + namespace.input(id="q", name="q", required=True, max_length=4), + namespace.input(id="n", name="n", type="number", default_value="7"), + rx.el.button("Send", id="send", type="submit"), + on_submit=TextFieldState.submit, + id="form", + ), + rx.el.span(TextFieldState.seen.to_string(), id="seen"), + rx.el.span(TextFieldState.keys.to_string(), id="keys"), + rx.el.span(TextFieldState.bound, id="bound-value"), + rx.el.span(TextFieldState.submitted.to_string(), id="submitted"), + rx.el.span(TextFieldState.submissions.to_string(), id="submissions"), + ), +) + + +@CONTRACT.step("is an input with its attributes in the server render", on=SERVER) +def _server_render(run: Run) -> None: + name = run.server.element("name") + assert (name.tag, name.attributes["placeholder"]) == ("input", "Your name") + assert run.server.element("off").attributes["value"] == "off" + assert "disabled" in run.server.element("off").attributes + assert "readonly" in run.server.element("fixed").attributes + assert run.server.element("bound").attributes["value"] == "start" + + +@CONTRACT.step("takes the focus and text with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.get_by_text("Name", exact=True).click() + assert focused(page) == "name" + page.keyboard.type("Ada") + assert page.locator("#name").input_value() == "Ada" + + +@CONTRACT.step("has the role and the name of a text box, and its label") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("textbox", name="Name").get_attribute("id") == "name" + assert page.get_by_label("Name", exact=True).get_attribute("id") == "name" + assert page.get_by_role("textbox", name="Events").get_attribute("id") == "events" + assert page.get_by_role("textbox", disabled=True).count() == 1 + assert page.get_by_role("spinbutton").get_attribute("id") == "n" + + +@CONTRACT.step("Tab stops on each field but a disabled one") +def _tab(run: Run) -> None: + stops = [] + for _ in range(4): + run.page.keyboard.press("Tab") + stops.append(focused(run.page)) + assert stops == ["name", "fixed", "events", "bound"] + + +@CONTRACT.step("typing changes the text and says so, key by key") +def _type(run: Run) -> None: + page = run.page + page.locator("#name").focus() + page.keyboard.type("Ada", delay=30) + assert page.locator("#name").input_value() == "Ada" + wait_for_text(page, "seen", '["A","Ad","Ada"]') + wait_for_text(page, "keys", '["A","d","a"]') + + +@CONTRACT.step("focus and blur hand over the text") +def _focus_blur(run: Run) -> None: + page = run.page + page.locator("#events").focus() + wait_for_text(page, "seen", '["e"]') + page.keyboard.press("End") + page.keyboard.type("x") + page.keyboard.press("Tab") + wait_for_text(page, "seen", '["e","ex"]') + + +@CONTRACT.step("a disabled field takes no text, and a read-only one the focus alone") +def _disabled(run: Run) -> None: + page = run.page + assert page.locator("#off").is_disabled() + page.locator("#fixed").focus() + page.keyboard.type("x") + assert page.locator("#fixed").input_value() == "fixed" + assert focused(page) == "fixed" + + +@CONTRACT.step("a field bound to state keeps what is typed and follows the state") +def _bound(run: Run) -> None: + page = run.page + bound = page.locator("#bound") + assert bound.input_value() == "start" + bound.focus() + page.keyboard.press("End") + page.keyboard.type(" and more", delay=15) + assert bound.input_value() == "start and more" + wait_for_text(page, "bound-value", "start and more") + assert bound.input_value() == "start and more" + page.locator("#reset").click() + wait_for_text(page, "bound-value", "reset") + page.wait_for_function("document.getElementById('bound').value === 'reset'") + + +@CONTRACT.step("rx.set_value and rx.set_focus reach the input by its id") +def _refs(run: Run) -> None: + page = run.page + page.locator("#set").click() + page.wait_for_function("document.getElementById('name').value === 'set'") + page.locator("#focus").click() + page.wait_for_function("document.activeElement.id === 'name'") + + +@CONTRACT.step("a pointer on a slot gives the input the focus, at that end of its text") +def _slots(run: Run) -> None: + page = run.page + caret = "[document.activeElement.id, document.activeElement.selectionStart]" + page.locator("#right-slot").click() + page.wait_for_function(f"{caret}.join() === 'slotted,6'") + page.locator("#name").focus() + page.locator("#left-slot").click() + page.wait_for_function(f"{caret}.join() === 'slotted,0'") + page.locator("#name").focus() + page.locator("#clear").click() + page.wait_for_timeout(100) + assert focused(page) == "clear" + + +@CONTRACT.step("a hidden input leaves no box behind") +def _hidden(run: Run) -> None: + page = run.page + assert page.locator("#gone").bounding_box() == { + **(page.locator("#gone").bounding_box() or {}), + "height": 0, + } + assert page.locator("#hidden").get_attribute("type") == "hidden" + + +@CONTRACT.step("submits its text with a form, as its type has it") +def _submit(run: Run) -> None: + page = run.page + page.locator("#q").focus() + page.keyboard.type("abcdefg") + assert page.locator("#q").input_value() == "abcd" + page.keyboard.press("Enter") + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == '{"q":"abcd","n":"7"}' + + +@CONTRACT.step("a required field holds its form back until it has text") +def _required(run: Run) -> None: + page = run.page + page.locator("#send").click() + # An event that does reach the server comes back after the blocked one. + page.locator("#reset").click() + wait_for_text(page, "bound-value", "reset") + assert page.locator("#submissions").text_content() == "0" + page.locator("#q").fill("ok") + page.locator("#send").click() + wait_for_text(page, "submissions", "1") diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py index ea6e490f6c5..d7dabcefcad 100644 --- a/packages/reflex-components-ui/parity/ui_parity/look.py +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -212,10 +212,20 @@ def _focus_within(page: Page, target: Locator, point: Point) -> None: point: The middle of the element. """ page.keyboard.press("Tab") + # The key may have landed on the control itself and selected its text, + # which a focus alone does not: the caret goes back to the start. target.evaluate( - "element => (element.matches('button, input, select, textarea, [tabindex]')" - " ? element : element.querySelector('input, button, select, textarea'))" - ".focus()" + """element => { + const control = element.matches( + 'button, input, select, textarea, [tabindex]' + ) ? element : element.querySelector('input, button, select, textarea'); + control.focus(); + try { + control.setSelectionRange?.(0, 0); + } catch { + // A control without text has no selection to collapse. + } + }""" ) 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 06ca1eea216..c7b4644a728 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -28,6 +28,8 @@ "components.spinner": ["spinner"], "components.switch": ["switch"], "components.table": ["table"], + "components.text_area": ["text_area"], + "components.text_field": ["input", "text_field"], "layout.box": ["box"], "layout.center": ["center"], "layout.container": ["container"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py b/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py new file mode 100644 index 00000000000..239c7a01470 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py @@ -0,0 +1,157 @@ +"""A text area: a box around a native textarea.""" + +from __future__ import annotations + +import functools +from typing import ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components.text_field import DebouncedControl, control_props +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.text_area import TEXT_AREA, TEXT_AREA_INPUT +from reflex_components_ui.themes import LiteralAccentColor, LiteralRadius + +LiteralTextAreaSize = Literal["1", "2", "3"] +LiteralTextAreaResize = Literal["none", "vertical", "horizontal", "both"] + + +class TextAreaInput(UIComponent, elements.Textarea): + """The textarea of a text area.""" + + tag = "textarea" + + styles: ClassVar[ComponentStyles] = TEXT_AREA_INPUT + + @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 layout props and the variants. The rows of a textarea are + its lines, an attribute, and not the rows of a grid. + """ + layout_props, variants = super()._style_props() + return tuple(prop for prop in layout_props if prop != "rows"), variants + + def _post_init(self, *args, **kwargs): + """Initialize the textarea, with the look its box gives it. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. ``box`` holds the + size and the variant of the box. + """ + # What the style table reads as variants. + self._size, self._variant = kwargs.pop("box") + super()._post_init(*args, **kwargs) + + +class TextArea(UIComponent, elements.Textarea): + """The input part of a TextArea, may be used by itself.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = TEXT_AREA + + size: Var[Responsive[LiteralTextAreaSize]] = field( + doc='The size of the text area: "1" | "2" | "3"' + ) + + variant: Var[Literal["classic", "surface", "soft"]] = field( + doc="The variant of the text area" + ) + + resize: Var[Responsive[LiteralTextAreaResize]] = field( + doc='The resize behavior of the text area: "none" | "vertical" | "horizontal" | "both"' + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="The color of the text area") + + radius: Var[LiteralRadius] = field( + doc='The radius of the text area: "none" | "small" | "medium" | "large" | "full"' + ) + + auto_complete: Var[bool] = field( + doc="Whether the form control should have autocomplete enabled" + ) + + auto_focus: Var[bool] = field( + doc="Automatically focuses the textarea when the page loads" + ) + + default_value: Var[str] = field( + doc="The default value of the textarea when initially rendered" + ) + + dirname: Var[str] = field( + doc="Name part of the textarea to submit in 'dir' and 'name' pair when form is submitted" + ) + + disabled: Var[bool] = field(doc="Disables the textarea") + + form: Var[str] = field(doc="Associates the textarea with a form (by id)") + + max_length: Var[int] = field( + doc="Maximum number of characters allowed in the textarea" + ) + + min_length: Var[int] = field( + doc="Minimum number of characters required in the textarea" + ) + + name: Var[str] = field(doc="Name of the textarea, used when submitting the form") + + placeholder: Var[str] = field(doc="Placeholder text in the textarea") + + read_only: Var[bool] = field(doc="Indicates whether the textarea is read-only") + + required: Var[bool] = field(doc="Indicates that the textarea is required") + + rows: Var[str] = field(doc="Visible number of lines in the text control") + + value: Var[str] = field( + doc="The controlled value of the textarea, read only unless used with on_change" + ) + + wrap: Var[str] = field( + doc="How the text in the textarea is to be wrapped when submitting the form" + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Create an Input component. + + The size, the variant, the resize behavior, the color, the radius + and the styles are the ones of the box, and every other prop is + given to the textarea inside it: its attributes, its ``id`` and its + event triggers. A ``padding`` is the one of the textarea. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The component. + """ + own = control_props(props, elements.Textarea) + padding = props.pop("padding", None) + if padding is not None: + own["style"] = {"padding": padding} + # Marked for the rule of the thumb of its scrollbar. + own.setdefault("custom_attrs", {})["data-rx-text-area-input"] = "" + control: Component = TextAreaInput.create( + *children, box=(props.get("size"), props.get("variant")), **own + ) + if own.get("value") is not None and own.get("on_change") is not None: + # create a debounced input if the user requests full control to avoid typing jank + control = DebouncedControl.create(control) # pyright: ignore[reportArgumentType] + return super().create(control, **props) + + +text_area = TextArea.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py new file mode 100644 index 00000000000..e9b3c6b0d54 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py @@ -0,0 +1,350 @@ +"""A text field: a box around a native input, with slots for icons and buttons.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, input_event, key_event +from reflex_base.utils.imports import ImportVar +from reflex_base.utils.types import is_optional, safe_issubclass, value_inside_optional +from reflex_base.vars.base import Var, VarData +from reflex_base.vars.number import ternary_operation +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.debounce import DebounceInput +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._group import literal +from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.text_field import ( + TEXT_FIELD, + TEXT_FIELD_INPUT, + TEXT_FIELD_SLOT, +) +from reflex_components_ui.themes import LiteralAccentColor, LiteralRadius + +LiteralTextFieldSize = Literal["1", "2", "3"] +LiteralTextFieldVariant = Literal["classic", "surface", "soft"] + +# The `onPointerDown` of a box with slots: a pointer on a slot or on the edge +# of the box gives the input the focus, which is all the JavaScript of a text +# field. +_FOCUS_FIELD = Var( + "focusField", + _var_data=VarData( + imports={f"$/{WEB_DIR}/behaviors/text-field.js": [ImportVar(tag="focusField")]} + ), +) + +# The props of the box of a text field or a text area. Every other one is a +# prop of the control inside it. +_BOX_PROPS = frozenset(( + "size", + "variant", + "resize", + "color_scheme", + "radius", + "class_name", + "style", +)) + + +def control_props(props: dict[str, Any], element: type[Component]) -> dict[str, Any]: + """Take the props of the control out of the props of its box. + + Args: + props: The props a text field or a text area is created with, which + keeps the ones of the box. + element: The element class of the control. + + Returns: + The props of the control: its attributes, its ``id`` and its event + triggers. + """ + fields = element.get_fields() + return { + key: props.pop(key) + for key in list(props) + if key not in _BOX_PROPS + and ( + key in fields + or key.startswith(("on_", "aria_", "data_")) + or key == "custom_attrs" + ) + } + + +class DebouncedControl(DebounceInput): + """An input or a text area that keeps what is typed while state catches up. + + The value of a control bound to state comes back from the state after + each change, later than the next key. This is the wrapper Reflex puts + around every input a state controls, with the class names of the + control's styles. + """ + + @classmethod + def create(cls, control: UIComponent) -> Component: # pyright: ignore[reportIncompatibleMethodOverride] + """Wrap a control that has a value and an ``on_change``. + + Args: + control: The input or the text area. + + Returns: + The control inside the wrapper. + """ + component = super().create(control) + component._control = control # pyright: ignore[reportAttributeAccessIssue] + return component + + def _render(self) -> CommonTag: + """Render the wrapper with the class names of the control's styles. + + Returns: + The tag. + """ + control: UIComponent = self._control # pyright: ignore[reportAttributeAccessIssue] + return ( + super()._render().add_props(class_name=control._render().props["className"]) + ) + + +class TextFieldInput(UIComponent, elements.Input): + """The input of a text field.""" + + tag = "input" + + styles: ClassVar[ComponentStyles] = TEXT_FIELD_INPUT + + def _post_init(self, *args, **kwargs): + """Initialize the input, with the look its box gives it. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. ``box`` holds the + size and the variant of the box. + """ + # What the style table reads as variants. + self._size, self._variant = kwargs.pop("box") + super()._post_init(*args, **kwargs) + + +class TextFieldRoot(UIComponent, elements.Input): + """Captures user input with an optional slot for buttons and icons.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = TEXT_FIELD + + size: Var[Responsive[LiteralTextFieldSize]] = field(doc='Text field size "1" - "3"') + + variant: Var[LiteralTextFieldVariant] = field( + doc='Variant of text field: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for text field" + ) + + radius: Var[LiteralRadius] = field( + doc='Override theme radius for text field: "none" | "small" | "medium" | "large" | "full"' + ) + + auto_complete: Var[str] = field( + doc='The autocomplete hint, e.g. "off", "on" or "email". True and False become "on" and "off".' + ) + + default_value: Var[str] = field( + doc="The value of the input when initially rendered." + ) + + disabled: Var[bool] = field(doc="Disables the input") + + max_length: Var[int] = field( + doc="Specifies the maximum number of characters allowed in the input" + ) + + min_length: Var[int] = field( + doc="Specifies the minimum number of characters required in the input" + ) + + name: Var[str] = field(doc="Name of the input, used when sending form data") + + placeholder: Var[str] = field(doc="Placeholder text in the input") + + read_only: Var[bool] = field(doc="Indicates whether the input is read-only") + + required: Var[bool] = field(doc="Indicates that the input is required") + + type: Var[str] = field(doc="Specifies the type of input") + + value: Var[str | int | float] = field(doc="Value of the input") + + list: Var[str] = field(doc="References a datalist for suggested options") + + on_change: EventHandler[input_event] = field( + doc="Fired when the value of the textarea changes." + ) + + on_focus: EventHandler[input_event] = field( + doc="Fired when the textarea is focused." + ) + + on_blur: EventHandler[input_event] = field( + doc="Fired when the textarea is blurred." + ) + + on_key_down: EventHandler[key_event] = field( + doc="Fired when a key is pressed down." + ) + + on_key_up: EventHandler[key_event] = field(doc="Fired when a key is released.") + + @classmethod + def create(cls, *children, **props) -> Component: + """Create an Input component. + + The size, the variant, the color, the radius and the styles are the + ones of the box, and every other prop is given to the input inside + it: its attributes, its ``id`` and its event triggers. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The component. + """ + # React drops a bool autoComplete, the DOM takes a string + auto_complete = props.get("auto_complete") + if isinstance(auto_complete, bool): + props["auto_complete"] = "on" if auto_complete else "off" + elif isinstance(auto_complete, Var) and safe_issubclass( + value_inside_optional(auto_complete._var_type), bool + ): + props["auto_complete"] = ternary_operation( + auto_complete, Var.create("on"), Var.create("off") + ) + + value = props.get("value") + + # React expects an empty string(instead of null) for controlled inputs. + if value is not None and is_optional( + (value_var := Var.create(value))._var_type + ): + value_var_is_not_none = value_var != Var.create(None) + value_var_is_not_undefined = value_var != Var(_js_expr="undefined") + props["value"] = ternary_operation( + value_var_is_not_none & value_var_is_not_undefined, + value, + Var.create(""), + ) + + own = control_props(props, elements.Input) + # Marked for the rules of the fields of a date, and without the spell + # check of the browser unless it is asked for, as in Radix Themes. + own.setdefault("custom_attrs", {})["data-rx-text-field-input"] = "" + own.setdefault("spell_check", False) + control: Component = TextFieldInput.create( + box=(props.get("size"), props.get("variant")), **own + ) + if own.get("value") is not None and own.get("on_change") is not None: + # create a debounced input if the user requests full control to avoid typing jank + control = DebouncedControl.create(control) # pyright: ignore[reportArgumentType] + if children: + _place_slots(children) + props.setdefault("custom_attrs", {})["onPointerDown"] = _FOCUS_FIELD + return super().create(control, *children, **props) + + +def _place_slots(children: tuple[Any, ...]) -> None: + """Say which side each slot of a text field is on. + + A slot is on the side it names, and one that names none is on the left, + or on the right when a slot before it is not: two slots without a side + are one on each. + + Args: + children: The children of the text field. + """ + left_before = False + for child in children: + if isinstance(child, TextFieldSlot): + side = literal(child.side) + if side is None: + child._set_side("right" if left_before else "left") + left_before = left_before or child._side != "right" + + +class TextFieldSlot(UIComponent): + """Contains icons or buttons associated with an Input.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = TEXT_FIELD_SLOT + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for text field slot" + ) + + side: Var[Literal["left", "right"]] = field( + doc="Which side of the input the slot should be placed on" + ) + + def _post_init(self, *args, **kwargs): + """Initialize the slot, on the side it names. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as a variant: the text field sets the + # side of a slot that names none. + self._side: Any = kwargs.get("side") + super()._post_init(*args, **kwargs) + + def _set_side(self, side: str) -> None: + """Put a slot that names no side on one. + + Args: + side: The side. + """ + self._side = side + self._merge_styles() + + def _exclude_props(self) -> list[str]: + """Keep the side off the element as a prop: it is rendered as data. + + Returns: + The props read as styles, and the side. + """ + return [*super()._exclude_props(), "side"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the slot. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the side the slot is on: the box around it reads + it to leave no room on that side of the input. + """ + return ( + super() + ._render(props) + .add_props(**{"data-side": "left" if self._side is None else self._side}) + ) + + +class TextField(ComponentNamespace): + """TextField components namespace.""" + + slot = staticmethod(TextFieldSlot.create) + __call__ = staticmethod(TextFieldRoot.create) + + +input = text_field = TextField() 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 4a69f961262..95ad2803a3b 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 @@ -1436,6 +1436,51 @@ def __repr__(self) -> str: EMPTY = Lowered({}) +def _before_longhands(props: dict[str, LoweredValue]) -> dict[str, LoweredValue]: + """Write a shorthand that only applies under a condition before its longhands. + + StyleX applies the properties of a style in the order they are written, + and takes a whole shorthand written after its longhands to cancel them, + everywhere. A shorthand kept whole under a condition, such as the padding + of a pseudo-element, says nothing of what the longhands are anywhere + else: written before them, it leaves them be. + + Args: + props: The merged properties. + + Returns: + The properties, in an order StyleX reads as they are meant, and the + same dict when nothing has to move. + """ + moved: dict[str, int] | None = None + order: dict[str, int] | None = None + for prop, value in props.items(): + longhands = _REPLACES.get(prop) + if ( + longhands is None or value.__class__ is not dict or "default" in value # pyright: ignore[reportOperatorIssue] + ): + continue + if order is None: + order = {key: index for index, key in enumerate(props)} + first = min( + (order[key] for key in longhands if key in order), default=order[prop] + ) + if first < order[prop]: + moved = moved or {} + moved[prop] = first + if moved is None or order is None: + return props + # A moved shorthand comes right before the first of its longhands. + return dict( + sorted( + props.items(), + key=lambda item: ( + (moved[item[0]], 0) if item[0] in moved else (order[item[0]], 1) + ), + ) + ) + + def finish( props: dict[str, LoweredValue], inline: Var | None = None, unset: bool = False ) -> Lowered: @@ -1465,6 +1510,7 @@ def finish( props = {prop: value for prop, value in props.items() if value is not None} if not props and inline is None: return EMPTY + props = _before_longhands(props) return Lowered(props, tuple(sorted(found)) if found else (), inline) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/text_area.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/text_area.py new file mode 100644 index 00000000000..fad94a52dda --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/text_area.py @@ -0,0 +1,228 @@ +"""The look of a text area: a box around a native textarea.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.text_field import ( + AUTOFILLED, + DISABLED, + INPUT_RESET, + OFF, +) + +accent, gray, focus = tokens.accent, tokens.gray, tokens.focus + +_BORDER = "--text-area-border-width" +_PADDING_Y = "--text-area-padding-y" +_PADDING_X = "--text-area-padding-x" + +_FOCUSED = ":focus-within" +_FILLED = f"inset 0 0 0 1px {focus.a[5]}, inset 0 0 0 1px {gray.a[5]}" +_DISABLED_FILL = f"linear-gradient({gray.a[2]}, {gray.a[2]})" + + +def _ring(color: str) -> dict[str, Any]: + """Make the color of the ring of a focused text area. + + Args: + color: The color around a text area that takes text. + + Returns: + The color, by whether the text area takes text. + """ + return { + "outline_color": { + f"{_FOCUSED}:not({DISABLED})": color, + f"{_FOCUSED}{DISABLED}": gray[8], + }, + } + + +def _input_size(y: str, x: str, step: int) -> dict[str, Any]: + """Make the styles of the textarea of one size. + + Args: + y: The room above and below the text. + x: The room beside it. + step: The step of the type scale. + + Returns: + The styles. + """ + return { + _PADDING_Y: f"calc({y} - var({_BORDER}))", + _PADDING_X: f"calc({x} - var({_BORDER}))", + "font_size": tokens.font_size[step], + "line_height": tokens.line_height[step], + "letter_spacing": tokens.letter_spacing[step], + } + + +TEXT_AREA: ComponentStyles = { + "base": unchecked({ + "display": "flex", + "flex_direction": "column", + "box_sizing": "border-box", + "font_family": tokens.default.font_family, + "font_weight": tokens.font_weight.regular, + "font_style": "normal", + "text_align": "start", + # What lets the box be resized. + "overflow": "hidden", + "padding": f"var({_BORDER})", + _FOCUSED: { + "outline_width": "2px", + "outline_style": "solid", + "outline_offset": "-1px", + }, + }), + "variants": { + "size": { + "1": {"min_height": tokens.space[8], "border_radius": tokens.radius[2]}, + "2": {"min_height": tokens.space[9], "border_radius": tokens.radius[2]}, + "3": {"min_height": "80px", "border_radius": tokens.radius[3]}, + }, + "variant": { + "surface": unchecked({ + _BORDER: "1px", + "background_clip": "content-box", + "background_color": tokens.color.surface, + "background_image": { + AUTOFILLED: f"linear-gradient({focus.a[2]}, {focus.a[2]})", + DISABLED: _DISABLED_FILL, + }, + "box_shadow": { + "default": f"inset 0 0 0 var({_BORDER}) {gray.a[7]}", + AUTOFILLED: _FILLED, + DISABLED: f"inset 0 0 0 var({_BORDER}) {gray.a[6]}", + }, + "color": gray[12], + **_ring(focus[8]), + }), + "classic": unchecked({ + _BORDER: "1px", + "background_clip": "content-box", + "background_color": tokens.color.surface, + "background_image": { + AUTOFILLED: f"linear-gradient({focus.a[2]}, {focus.a[2]})", + DISABLED: _DISABLED_FILL, + }, + "box_shadow": {"default": tokens.shadow[1], AUTOFILLED: _FILLED}, + "color": gray[12], + **_ring(focus[8]), + }), + "soft": unchecked({ + _BORDER: "0px", + "background_color": {"default": accent.a[3], DISABLED: gray.a[3]}, + "box_shadow": { + AUTOFILLED: ( + f"inset 0 0 0 1px {accent.a[5]}, inset 0 0 0 1px {gray.a[4]}" + ), + }, + "color": accent[12], + # A gray ring for a gray text area. + **_ring(accent[8]), + }), + }, + "resize": { + "none": {"resize": "none"}, + "vertical": {"resize": "vertical"}, + "horizontal": {"resize": "horizontal"}, + "both": {"resize": "both"}, + }, + }, + "defaults": {"size": "2", "variant": "surface"}, +} + +_SCROLLBAR_PART: dict[str, Any] = { + "background_clip": "content-box", + "border_width": tokens.space[1], + "border_style": "solid", + "border_color": "transparent", + "border_radius": tokens.space[3], +} + + +def _placeholder(color: str, opacity: float) -> dict[str, Any]: + """Make the placeholder and the selection of the textarea of a variant. + + Args: + color: The color of the placeholder. + opacity: How much of it shows in a textarea that takes text. + + Returns: + The styles. + """ + return { + "_placeholder": { + "user_select": "none", + "color": color, + "opacity": {"default": opacity, OFF: 0.5}, + }, + } + + +# The textarea. Its box says how it looks, so the variants are not props. +TEXT_AREA_INPUT: ComponentStyles = { + "base": unchecked({ + **INPUT_RESET, + "border_radius": "inherit", + "resize": "none", + "display": "block", + "width": "100%", + "flex_grow": 1, + "text_align": "start", + "text_indent": "initial", + "padding": f"var({_PADDING_Y}) var({_PADDING_X})", + # An arrow over the scrollbar, and over a text area that takes no + # text and has none. + "cursor": { + "default": "auto", + f"{OFF}:not(:placeholder-shown)": "text", + f"{OFF}:placeholder-shown": tokens.cursor.disabled, + }, + "color": {"default": "inherit", OFF: gray.a[11]}, + "WebkitTextFillColor": {OFF: gray.a[11], ":autofill": gray[12]}, + "background_clip": {":autofill": "text"}, + "::-webkit-scrollbar": { + "width": tokens.space[3], + "height": tokens.space[3], + }, + "::-webkit-scrollbar-track": { + **_SCROLLBAR_PART, + "background_color": gray.a[3], + }, + "::-webkit-scrollbar-thumb": { + **_SCROLLBAR_PART, + "background_color": gray.a[8], + }, + }), + "variants": { + "_size": { + "1": unchecked(_input_size(tokens.space[1], f"{tokens.space[1]} * 1.5", 1)), + "2": unchecked(_input_size(f"{tokens.space[1]} * 1.5", tokens.space[2], 2)), + "3": unchecked(_input_size(tokens.space[2], tokens.space[3], 3)), + }, + "_variant": { + "surface": unchecked({ + **_placeholder(gray.a[10], 1), + "_selection": {"background_color": {OFF: gray.a[5]}}, + }), + "classic": unchecked({ + **_placeholder(gray.a[10], 1), + "_selection": {"background_color": {OFF: gray.a[5]}}, + }), + "soft": unchecked({ + **_placeholder(accent[12], 0.65), + # A gray selection in a gray text area. + "_selection": { + "background_color": {"default": accent.a[5], OFF: gray.a[5]}, + }, + }), + }, + }, + "defaults": {"_size": "2", "_variant": "surface"}, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/text_field.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/text_field.py new file mode 100644 index 00000000000..97acf529418 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/text_field.py @@ -0,0 +1,355 @@ +"""The look of a text field: a box around a native input and its slots.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked + +accent, gray, focus = tokens.accent, tokens.gray, tokens.focus + +_HEIGHT = "--text-field-height" +_PADDING = "--text-field-padding" +_RADIUS = "--text-field-border-radius" +_BORDER = "--text-field-border-width" +_ICON = "--text-field-native-icon-size" +SELECTION = "--text-field-selection-color" +FOCUS_COLOR = "--text-field-focus-color" + +# What the box hands the input and the slots inside it, which a class on +# either cannot ask of the other: the room the input leaves on a side +# without a slot, and how the slots look. +_INDENT = "--rx-text-field-indent" +_PADDING_LEFT = "--rx-text-field-padding-left" +_PADDING_RIGHT = "--rx-text-field-padding-right" +_RADIUS_LEFT = "--rx-text-field-radius-left" +_RADIUS_RIGHT = "--rx-text-field-radius-right" +_SLOT_GAP = "--rx-text-field-slot-gap" +_SLOT_PADDING = "--rx-text-field-slot-padding" +_SLOT_COLOR = "--rx-text-field-slot-color" +_SLOT_CURSOR = "--rx-text-field-slot-cursor" + +_INPUT = "> :is(input, textarea)" +# The state of the box is the one of the input inside it. +FOCUSED = f":has({_INPUT}:focus)" +OFF = ":is(:disabled, :read-only)" +DISABLED = f":has({_INPUT}{OFF})" +AUTOFILLED = f":has({_INPUT}:autofill:not({OFF}))" +_LEFT_SLOT = ":has(> [data-side='left'])" +_RIGHT_SLOT = ":has(> [data-side='right'])" + +# The inputs the browser lays out as several fields. +_DATES = ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])" + +_INNER_RADIUS = f"calc(var({_RADIUS}) - var({_BORDER}))" + + +def _size( + height: str, padding: str, radius: str, icon: str, step: int, slot: str +) -> dict[str, Any]: + """Make the styles of one size. + + Args: + height: The height of the box. + padding: The room between the box and the text. + radius: The radius of the corners. + icon: The side of the icon the browser gives a date. + step: The step of the type scale. + slot: The gap and the padding of a slot. + + Returns: + The styles. + """ + return { + _HEIGHT: height, + _PADDING: f"calc({padding} - var({_BORDER}))", + _RADIUS: f"max({radius}, {tokens.radius.full})", + _ICON: icon, + "font_size": tokens.font_size[step], + "letter_spacing": tokens.letter_spacing[step], + _SLOT_GAP: slot, + _SLOT_PADDING: tokens.space[step], + } + + +def _variant( + border: str, + rest: dict[str, Any], + disabled: dict[str, Any], + autofilled: str, + soft: bool = False, +) -> dict[str, Any]: + """Make the styles of one variant. + + Args: + border: The width of the border. + rest: The fill and the border of the box. + disabled: What a disabled or read-only input changes of them. + autofilled: The border of a box the browser filled in. + soft: Whether the box takes its colors from the accent. + + Returns: + The styles, by the state of the input. + """ + style: dict[str, Any] = { + SELECTION: { + "default": accent.a[5] if soft else focus.a[5], + DISABLED: gray.a[5], + }, + FOCUS_COLOR: { + "default": accent[8] if soft else focus[8], + DISABLED: gray[8], + }, + _BORDER: border, + "color": accent[12] if soft else gray[12], + _SLOT_COLOR: accent[12] if soft else gray.a[11], + } + for key, value in rest.items(): + style[key] = {"default": value} + for key, value in disabled.items(): + style.setdefault(key, {})[DISABLED] = value + style.setdefault("box_shadow", {})[AUTOFILLED] = autofilled + if not soft: + style["background_clip"] = "content-box" + style.setdefault("background_image", {})[AUTOFILLED] = ( + f"linear-gradient({focus.a[2]}, {focus.a[2]})" + ) + return style + + +_FILLED = f"inset 0 0 0 1px {focus.a[5]}, inset 0 0 0 1px {gray.a[5]}" +_DISABLED_FILL = f"linear-gradient({gray.a[2]}, {gray.a[2]})" + +# The fill and the border of each variant, which a text area shares. +VARIANTS: dict[str, Any] = { + "surface": unchecked( + _variant( + "1px", + { + "background_color": tokens.color.surface, + "box_shadow": f"inset 0 0 0 var({_BORDER}) {gray.a[7]}", + }, + { + "background_image": _DISABLED_FILL, + "box_shadow": f"inset 0 0 0 var({_BORDER}) {gray.a[6]}", + }, + _FILLED, + ) + ), + "classic": unchecked( + _variant( + "1px", + {"background_color": tokens.color.surface, "box_shadow": tokens.shadow[1]}, + {"background_image": _DISABLED_FILL}, + _FILLED, + ) + ), + "soft": unchecked( + _variant( + "0px", + {"background_color": accent.a[3]}, + {"background_color": gray.a[3]}, + f"inset 0 0 0 1px {accent.a[5]}, inset 0 0 0 1px {gray.a[4]}", + soft=True, + ) + ), +} + +TEXT_FIELD: ComponentStyles = { + "base": unchecked({ + "display": { + "default": "flex", + # A hidden input leaves no empty box behind. + ":has(> input:is([hidden], [type='hidden' i]))": "none", + }, + "align_items": "stretch", + "font_family": tokens.default.font_family, + "font_weight": tokens.font_weight.regular, + "font_style": "normal", + "text_align": "start", + "box_sizing": "border-box", + "height": f"var({_HEIGHT})", + "padding": f"var({_BORDER})", + "border_radius": f"var({_RADIUS})", + FOCUSED: { + "outline_width": "2px", + "outline_style": "solid", + "outline_color": f"var({FOCUS_COLOR})", + "outline_offset": "-1px", + }, + "_selection": {"background_color": f"var({SELECTION})"}, + _INDENT: {"default": f"var({_PADDING})", _LEFT_SLOT: "0"}, + _PADDING_LEFT: {"default": f"var({_PADDING})", _LEFT_SLOT: "0"}, + _PADDING_RIGHT: {"default": f"var({_PADDING})", _RIGHT_SLOT: "0"}, + _RADIUS_LEFT: {"default": _INNER_RADIUS, _LEFT_SLOT: "0"}, + _RADIUS_RIGHT: {"default": _INNER_RADIUS, _RIGHT_SLOT: "0"}, + _SLOT_CURSOR: { + "default": "text", + f":has({_INPUT}{OFF}:placeholder-shown)": tokens.cursor.disabled, + }, + }), + "variants": { + "size": { + "1": unchecked( + _size( + tokens.space[5], + f"{tokens.space[1]} * 1.5", + tokens.radius[2], + tokens.space[3], + 1, + tokens.space[2], + ) + ), + "2": unchecked( + _size( + tokens.space[6], + tokens.space[2], + tokens.radius[2], + tokens.space[4], + 2, + tokens.space[2], + ) + ), + "3": unchecked( + _size( + tokens.space[7], + tokens.space[3], + tokens.radius[3], + tokens.space[4], + 3, + tokens.space[3], + ) + ), + }, + "variant": VARIANTS, + }, + "defaults": {"size": "2", "variant": "surface"}, +} + +# What a text input or a text area is before its table draws it: nothing of +# the look of the platform, as Radix Themes unsets it all. +INPUT_RESET: dict[str, Any] = { + "appearance": "none", + "margin": "0", + "border_width": "0", + "border_style": "none", + "background_color": "transparent", + "background_image": "none", + "box_sizing": "border-box", + "color": "inherit", + "font_family": "inherit", + "font_size": "inherit", + "font_weight": "normal", + "font_style": "normal", + "line_height": "inherit", + "letter_spacing": "inherit", + "text_transform": "inherit", + "word_spacing": "inherit", + "outline_style": "none", + "outline_width": "medium", + "outline_color": "currentcolor", + "outline_offset": "0", + "white_space": "pre-wrap", + "WebkitTapHighlightColor": "transparent", +} + +# The placeholder of an input, by the variant of its box. +PLACEHOLDER: dict[str, Any] = { + "surface": {"color": gray.a[10], "opacity": {"default": 1, OFF: 0.5}}, + "classic": {"color": gray.a[10], "opacity": {"default": 1, OFF: 0.5}}, + "soft": {"color": accent[12], "opacity": {"default": 0.6, OFF: 0.5}}, +} + +# A disabled or read-only input, in a text field or a text area. +INPUT_OFF: dict[str, Any] = { + "cursor": { + "default": "text", + f"{OFF}:placeholder-shown": tokens.cursor.disabled, + }, + "color": {"default": "inherit", OFF: gray.a[11]}, + "WebkitTextFillColor": {OFF: gray.a[11]}, +} + +# The input of a text field. Its box says how it looks, so the variants are +# not props. +TEXT_FIELD_INPUT: ComponentStyles = { + "base": unchecked({ + **INPUT_RESET, + **INPUT_OFF, + "width": "100%", + # What aligns a date in Chrome and Safari. + "display": "flex", + "align_items": "center", + "text_align": "inherit", + "border_top_left_radius": f"var({_RADIUS_LEFT})", + "border_bottom_left_radius": f"var({_RADIUS_LEFT})", + "border_top_right_radius": f"var({_RADIUS_RIGHT})", + "border_bottom_right_radius": f"var({_RADIUS_RIGHT})", + # Room on the left that does not cut a long value off at its end. + "text_indent": {"default": f"var({_INDENT})", _DATES: "0"}, + "padding_top": "0", + "padding_left": {"default": "0", _DATES: f"var({_PADDING_LEFT})"}, + "padding_right": {"default": "0", _DATES: f"var({_PADDING_RIGHT})"}, + # The stepper of a number and the cross of a search are left out. + "[type='number']": {"appearance": "textfield"}, + "::-webkit-inner-spin-button": {"appearance": "none"}, + "::-webkit-search-cancel-button": {"appearance": "none"}, + "_selection": {"background_color": f"var({SELECTION})"}, + # The icon Chrome gives a date or a time. + "::-webkit-calendar-picker-indicator": { + "box_sizing": "content-box", + "width": f"var({_ICON})", + "height": f"var({_ICON})", + "padding": tokens.space[1], + "margin_left": {"default": tokens.space[1], "[type='time']": "0"}, + "margin_right": f"calc({tokens.space[1]} * -1)", + "border_radius": f"calc(var({_RADIUS}) - 2px)", + }, + ":autofill": { + "background_clip": "text", + "WebkitTextFillColor": gray[12], + }, + }), + "variants": { + "_size": { + # Against a jitter of the baseline where the layout around the + # field falls on a part of a pixel. + "1": {"padding_bottom": "0px"}, + "2": {"padding_bottom": "0.5px"}, + "3": {"padding_bottom": "0px"}, + }, + "_variant": { + variant: unchecked({ + "_placeholder": {"user_select": "none", **placeholder}, + }) + for variant, placeholder in PLACEHOLDER.items() + }, + }, + "defaults": {"_size": "2", "_variant": "surface"}, +} + +_OUT = f"calc(var({_BORDER}) * -1)" + +# A slot. The box says which side a slot without one is on. +TEXT_FIELD_SLOT: ComponentStyles = { + "base": unchecked({ + "box_sizing": "border-box", + "flex_shrink": 0, + "display": "flex", + "align_items": "center", + "cursor": f"var({_SLOT_CURSOR}, text)", + "gap": f"var({_SLOT_GAP})", + "padding_left": f"var({_SLOT_PADDING})", + "padding_right": f"var({_SLOT_PADDING})", + "color": f"var({_SLOT_COLOR})", + }), + "variants": { + "_side": { + "left": {"order": -1, "margin_left": _OUT, "margin_right": "0"}, + "right": {"order": 0, "margin_left": "0", "margin_right": _OUT}, + }, + "color_scheme": {"true": {"color": accent.a[11]}}, + }, + "defaults": {"_side": "left"}, +} diff --git a/tests/units/reflex_components_ui/components/test_text_area.py b/tests/units/reflex_components_ui/components/test_text_area.py new file mode 100644 index 00000000000..cb35e03917c --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_text_area.py @@ -0,0 +1,497 @@ +"""Tests for reflex_components_ui.components.text_area.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +class AreaState(rx.State): + """What a text area is bound to.""" + + text: str = "" + + @rx.event + def set_text(self, text: str): + """Follow the text area. + + Args: + text: Its text. + """ + self.text = text + + +def test_text_area( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A text area is a box around a native textarea: its attributes, its id and its events are the ones of the textarea, and its styles the ones of the box.""" + component = rx.ui.text_area( + placeholder="Notes", + id="notes", + name="notes", + rows="3", + margin="1px", + class_name="mine", + on_blur=AreaState.set_text, + aria_label="Notes", + ) + assert component.render() == { + "name": '"div"', + "props": ['className:"mine " + sx_a60f107124_c'], + "children": [ + { + "name": '"textarea"', + "props": [ + '"aria-label":"Notes"', + "className:sx_8eecb42f44_c", + '"data-rx-text-area-input":""', + 'id:"notes"', + 'name:"notes"', + 'onBlur:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_text_area____area_state.set_text", ({ ["text"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))', + 'placeholder:"Notes"', + "ref:ref_notes", + 'rows:"3"', + ], + "children": [], + } + ], + } + assert declared_styles(component) == [ + { + "display": "flex", + "flexDirection": "column", + "boxSizing": "border-box", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "overflowX": "hidden", + "overflowY": "hidden", + "padding": "var(--text-area-border-width)", + "outlineWidth": {":focus-within": "2px"}, + "outlineStyle": {":focus-within": "solid"}, + "outlineOffset": {":focus-within": "-1px"}, + "minHeight": "var(--space-9)", + "borderTopLeftRadius": "var(--radius-2)", + "borderTopRightRadius": "var(--radius-2)", + "borderBottomRightRadius": "var(--radius-2)", + "borderBottomLeftRadius": "var(--radius-2)", + "--text-area-border-width": "1px", + "backgroundClip": "content-box", + "backgroundColor": "var(--color-surface)", + "backgroundImage": { + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "linear-gradient(var(--focus-a2), var(--focus-a2))", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "linear-gradient(var(--gray-a2), var(--gray-a2))", + }, + "boxShadow": { + "default": "inset 0 0 0 var(--text-area-border-width) var(--gray-a7)", + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "inset 0 0 0 1px var(--focus-a5), inset 0 0 0 1px var(--gray-a5)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "inset 0 0 0 var(--text-area-border-width) var(--gray-a6)", + }, + "color": "var(--gray-12)", + "outlineColor": { + ":focus-within:not(:has(> :is(input, textarea):is(:disabled, :read-only)))": "var(--focus-8)", + ":focus-within:has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-8)", + }, + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderRightWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderBottomWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderLeftWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderTopStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "borderRightStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "borderBottomStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "borderLeftStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "backgroundColor": { + "default": "transparent", + "::-webkit-scrollbar-track": "var(--gray-a3)", + "::-webkit-scrollbar-thumb": "var(--gray-a8)", + "::selection": {":is(:disabled, :read-only)": "var(--gray-a5)"}, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + ":is(:disabled, :read-only)": "var(--gray-a11)", + "::placeholder": "var(--gray-a10)", + }, + "fontFamily": "inherit", + "fontSize": "var(--font-size-2)", + "fontWeight": "normal", + "fontStyle": "normal", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "var(--letter-spacing-2)", + "textTransform": "inherit", + "wordSpacing": "inherit", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "whiteSpace": "pre-wrap", + "WebkitTapHighlightColor": "transparent", + "borderTopLeftRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "borderTopRightRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "borderBottomRightRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "borderBottomLeftRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "resize": "none", + "display": "block", + "width": {"default": "100%", "::-webkit-scrollbar": "var(--space-3)"}, + "flexGrow": 1, + "textAlign": "start", + "textIndent": "initial", + "padding": "var(--text-area-padding-y) var(--text-area-padding-x)", + "cursor": { + "default": "auto", + ":is(:disabled, :read-only):not(:placeholder-shown)": "text", + ":is(:disabled, :read-only):placeholder-shown": "var(--cursor-disabled)", + }, + "WebkitTextFillColor": { + ":is(:disabled, :read-only)": "var(--gray-a11)", + ":autofill": "var(--gray-12)", + }, + "backgroundClip": { + ":autofill": "text", + "::-webkit-scrollbar-track": "content-box", + "::-webkit-scrollbar-thumb": "content-box", + }, + "height": {"::-webkit-scrollbar": "var(--space-3)"}, + "borderTopColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "borderRightColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "borderBottomColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "borderLeftColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "--text-area-padding-y": "calc(var(--space-1) * 1.5 - var(--text-area-border-width))", + "--text-area-padding-x": "calc(var(--space-2) - var(--text-area-border-width))", + "userSelect": {"::placeholder": "none"}, + "opacity": { + "::placeholder": {"default": 1, ":is(:disabled, :read-only)": 0.5} + }, + }, + ] + + +def test_text_area_soft( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The size and the variant reach the textarea, a padding is the one of the textarea, and the box is what resizes.""" + component = rx.ui.text_area( + size="3", + variant="soft", + color_scheme="ruby", + radius="large", + resize=rx.breakpoints(initial="none", md="both"), + padding="2px", + disabled=True, + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_7ad8a315b7_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_1df0c09a3a' + ], + "children": [ + { + "name": '"textarea"', + "props": [ + "className:sx_9c17918843_c", + '"data-rx-text-area-input":""', + "disabled:true", + ], + "children": [], + } + ], + } + assert declared_styles(component) == [ + { + "display": "flex", + "flexDirection": "column", + "boxSizing": "border-box", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "overflowX": "hidden", + "overflowY": "hidden", + "padding": "var(--text-area-border-width)", + "outlineWidth": {":focus-within": "2px"}, + "outlineStyle": {":focus-within": "solid"}, + "outlineOffset": {":focus-within": "-1px"}, + "minHeight": "80px", + "borderTopLeftRadius": "var(--radius-3)", + "borderTopRightRadius": "var(--radius-3)", + "borderBottomRightRadius": "var(--radius-3)", + "borderBottomLeftRadius": "var(--radius-3)", + "--text-area-border-width": "0px", + "backgroundColor": { + "default": "var(--accent-a3)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-a3)", + }, + "boxShadow": { + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "inset 0 0 0 1px var(--accent-a5), inset 0 0 0 1px var(--gray-a4)" + }, + "color": "var(--accent-12)", + "outlineColor": { + ":focus-within:not(:has(> :is(input, textarea):is(:disabled, :read-only)))": "var(--accent-8)", + ":focus-within:has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-8)", + }, + "resize": {"default": "none", "@media (min-width: 1024px)": "both"}, + }, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderRightWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderBottomWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderLeftWidth": { + "default": "0", + "::-webkit-scrollbar-track": "var(--space-1)", + "::-webkit-scrollbar-thumb": "var(--space-1)", + }, + "borderTopStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "borderRightStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "borderBottomStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "borderLeftStyle": { + "default": "none", + "::-webkit-scrollbar-track": "solid", + "::-webkit-scrollbar-thumb": "solid", + }, + "backgroundColor": { + "default": "transparent", + "::-webkit-scrollbar-track": "var(--gray-a3)", + "::-webkit-scrollbar-thumb": "var(--gray-a8)", + "::selection": { + "default": "var(--accent-a5)", + ":is(:disabled, :read-only)": "var(--gray-a5)", + }, + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + ":is(:disabled, :read-only)": "var(--gray-a11)", + "::placeholder": "var(--accent-12)", + }, + "fontFamily": "inherit", + "fontSize": "var(--font-size-3)", + "fontWeight": "normal", + "fontStyle": "normal", + "lineHeight": "var(--line-height-3)", + "letterSpacing": "var(--letter-spacing-3)", + "textTransform": "inherit", + "wordSpacing": "inherit", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "whiteSpace": "pre-wrap", + "WebkitTapHighlightColor": "transparent", + "borderTopLeftRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "borderTopRightRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "borderBottomRightRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "borderBottomLeftRadius": { + "default": "inherit", + "::-webkit-scrollbar-track": "var(--space-3)", + "::-webkit-scrollbar-thumb": "var(--space-3)", + }, + "resize": "none", + "display": "block", + "width": {"default": "100%", "::-webkit-scrollbar": "var(--space-3)"}, + "flexGrow": 1, + "textAlign": "start", + "textIndent": "initial", + "padding": "var(--text-area-padding-y) var(--text-area-padding-x)", + "cursor": { + "default": "auto", + ":is(:disabled, :read-only):not(:placeholder-shown)": "text", + ":is(:disabled, :read-only):placeholder-shown": "var(--cursor-disabled)", + }, + "WebkitTextFillColor": { + ":is(:disabled, :read-only)": "var(--gray-a11)", + ":autofill": "var(--gray-12)", + }, + "backgroundClip": { + ":autofill": "text", + "::-webkit-scrollbar-track": "content-box", + "::-webkit-scrollbar-thumb": "content-box", + }, + "height": {"::-webkit-scrollbar": "var(--space-3)"}, + "borderTopColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "borderRightColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "borderBottomColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "borderLeftColor": { + "::-webkit-scrollbar-track": "transparent", + "::-webkit-scrollbar-thumb": "transparent", + }, + "--text-area-padding-y": "calc(var(--space-2) - var(--text-area-border-width))", + "--text-area-padding-x": "calc(var(--space-3) - var(--text-area-border-width))", + "userSelect": {"::placeholder": "none"}, + "opacity": { + "::placeholder": {"default": 0.65, ":is(:disabled, :read-only)": 0.5} + }, + "paddingTop": "2px", + "paddingRight": "2px", + "paddingBottom": "2px", + "paddingLeft": "2px", + }, + ] + + +def test_text_area_bound_to_state( + ui_plugin: UIPlugin, +): + """A textarea a state controls is wrapped to keep what is typed, with the class names of its styles.""" + component = rx.ui.text_area( + value=AreaState.text, on_change=AreaState.set_text, id="bound" + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_246a7bce17_c"], + "children": [ + { + "name": "DebounceInput", + "props": [ + "className:sx_8eecb42f44_c", + '"data-rx-text-area-input":""', + "debounceTimeout:300", + 'element:"textarea"', + 'id:"bound"', + "inputRef:ref_bound", + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_text_area____area_state.set_text", ({ ["text"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))', + "value:reflex___state____state__tests___units___reflex_components_ui___components___test_text_area____area_state.text_rx_state_", + ], + "children": [], + } + ], + } + + +def test_text_area_unknown_resize(ui_plugin: UIPlugin): + """A resize behavior a text area does not have is an error that lists the ones it has.""" + with pytest.raises(StyleError) as error: + rx.ui.text_area(resize="diagonal") + assert ( + str(error.value) + == 'rx.ui.text_area: unknown resize "diagonal". The values are "none", "vertical", "horizontal", "both".' + ) diff --git a/tests/units/reflex_components_ui/components/test_text_field.py b/tests/units/reflex_components_ui/components/test_text_field.py new file mode 100644 index 00000000000..1576ccba9a8 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_text_field.py @@ -0,0 +1,633 @@ +"""Tests for reflex_components_ui.components.text_field.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +class FieldState(rx.State): + """What a text field is bound to.""" + + text: str = "" + maybe: str | None = None + complete: bool = True + + @rx.event + def set_text(self, text: str): + """Follow the field. + + Args: + text: Its text. + """ + self.text = text + + +def test_text_field( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A text field is a box around a native input: its attributes, its id and its events are the ones of the input, and its styles the ones of the box.""" + component = rx.ui.input( + placeholder="Search", + id="q", + name="q", + max_length=5, + margin="1px", + class_name="mine", + on_blur=FieldState.set_text, + auto_complete=True, + aria_label="Query", + spell_check=True, + ) + assert component.render() == { + "name": '"div"', + "props": ['className:"mine " + sx_9bc77afb58_c'], + "children": [ + { + "name": '"input"', + "props": [ + '"aria-label":"Query"', + 'autoComplete:"on"', + "className:sx_345c25de08_c", + '"data-rx-text-field-input":""', + 'id:"q"', + "maxLength:5", + 'name:"q"', + 'onBlur:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_text_field____field_state.set_text", ({ ["text"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))', + 'placeholder:"Search"', + "ref:ref_q", + "spellCheck:true", + ], + "children": [], + } + ], + } + assert declared_styles(component) == [ + { + "display": { + "default": "flex", + ":has(> input:is([hidden], [type='hidden' i]))": "none", + }, + "alignItems": "stretch", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "boxSizing": "border-box", + "height": "var(--text-field-height)", + "padding": "var(--text-field-border-width)", + "borderRadius": "var(--text-field-border-radius)", + "outlineWidth": {":has(> :is(input, textarea):focus)": "2px"}, + "outlineStyle": {":has(> :is(input, textarea):focus)": "solid"}, + "outlineColor": { + ":has(> :is(input, textarea):focus)": "var(--text-field-focus-color)" + }, + "outlineOffset": {":has(> :is(input, textarea):focus)": "-1px"}, + "backgroundColor": { + "default": "var(--color-surface)", + "::selection": "var(--text-field-selection-color)", + }, + "--rx-text-field-indent": { + "default": "var(--text-field-padding)", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-padding-left": { + "default": "var(--text-field-padding)", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-padding-right": { + "default": "var(--text-field-padding)", + ":has(> [data-side='right'])": "0", + }, + "--rx-text-field-radius-left": { + "default": "calc(var(--text-field-border-radius) - var(--text-field-border-width))", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-radius-right": { + "default": "calc(var(--text-field-border-radius) - var(--text-field-border-width))", + ":has(> [data-side='right'])": "0", + }, + "--rx-text-field-slot-cursor": { + "default": "text", + ":has(> :is(input, textarea):is(:disabled, :read-only):placeholder-shown)": "var(--cursor-disabled)", + }, + "--text-field-height": "var(--space-6)", + "--text-field-padding": "calc(var(--space-2) - var(--text-field-border-width))", + "--text-field-border-radius": "max(var(--radius-2), var(--radius-full))", + "--text-field-native-icon-size": "var(--space-4)", + "fontSize": "var(--font-size-2)", + "letterSpacing": "var(--letter-spacing-2)", + "--rx-text-field-slot-gap": "var(--space-2)", + "--rx-text-field-slot-padding": "var(--space-2)", + "--text-field-selection-color": { + "default": "var(--focus-a5)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-a5)", + }, + "--text-field-focus-color": { + "default": "var(--focus-8)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-8)", + }, + "--text-field-border-width": "1px", + "color": "var(--gray-12)", + "--rx-text-field-slot-color": "var(--gray-a11)", + "boxShadow": { + "default": "inset 0 0 0 var(--text-field-border-width) var(--gray-a7)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "inset 0 0 0 var(--text-field-border-width) var(--gray-a6)", + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "inset 0 0 0 1px var(--focus-a5), inset 0 0 0 1px var(--gray-a5)", + }, + "backgroundImage": { + ":has(> :is(input, textarea):is(:disabled, :read-only))": "linear-gradient(var(--gray-a2), var(--gray-a2))", + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "linear-gradient(var(--focus-a2), var(--focus-a2))", + }, + "backgroundClip": "content-box", + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + }, + { + "appearance": { + "default": "none", + "[type='number']": "textfield", + "::-webkit-inner-spin-button": "none", + "::-webkit-search-cancel-button": "none", + }, + "marginTop": "0", + "marginRight": { + "default": "0", + "::-webkit-calendar-picker-indicator": "calc(var(--space-1) * -1)", + }, + "marginBottom": "0", + "marginLeft": { + "default": "0", + "::-webkit-calendar-picker-indicator": { + "default": "var(--space-1)", + "[type='time']": "0", + }, + }, + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::selection": "var(--text-field-selection-color)", + }, + "backgroundImage": "none", + "boxSizing": { + "default": "border-box", + "::-webkit-calendar-picker-indicator": "content-box", + }, + "color": { + "default": "inherit", + ":is(:disabled, :read-only)": "var(--gray-a11)", + "::placeholder": "var(--gray-a10)", + }, + "fontFamily": "inherit", + "fontSize": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "textTransform": "inherit", + "wordSpacing": "inherit", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "whiteSpace": "pre-wrap", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "text", + ":is(:disabled, :read-only):placeholder-shown": "var(--cursor-disabled)", + }, + "WebkitTextFillColor": { + ":is(:disabled, :read-only)": "var(--gray-a11)", + ":autofill": "var(--gray-12)", + }, + "width": { + "default": "100%", + "::-webkit-calendar-picker-indicator": "var(--text-field-native-icon-size)", + }, + "display": "flex", + "alignItems": "center", + "textAlign": "inherit", + "borderRadius": { + "::-webkit-calendar-picker-indicator": "calc(var(--text-field-border-radius) - 2px)" + }, + "borderTopLeftRadius": "var(--rx-text-field-radius-left)", + "borderBottomLeftRadius": "var(--rx-text-field-radius-left)", + "borderTopRightRadius": "var(--rx-text-field-radius-right)", + "borderBottomRightRadius": "var(--rx-text-field-radius-right)", + "textIndent": { + "default": "var(--rx-text-field-indent)", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "0", + }, + "paddingTop": { + "default": "0", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "paddingLeft": { + "default": "0", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "var(--rx-text-field-padding-left)", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "paddingRight": { + "default": "0", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "var(--rx-text-field-padding-right)", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "height": { + "::-webkit-calendar-picker-indicator": "var(--text-field-native-icon-size)" + }, + "paddingBottom": { + "default": "0.5px", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "backgroundClip": {":autofill": "text"}, + "userSelect": {"::placeholder": "none"}, + "opacity": { + "::placeholder": {"default": 1, ":is(:disabled, :read-only)": 0.5} + }, + }, + ] + + +def test_text_field_with_slots( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A slot is on the side it names; the first without one is on the left and the next on the right, and a pointer on either gives the input the focus.""" + component = rx.ui.input( + rx.ui.input.slot("a"), + rx.ui.input.slot("b"), + rx.ui.input.slot("c", side="left", color_scheme="ruby"), + size="3", + variant="soft", + color_scheme="ruby", + radius="full", + type="date", + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_59632c79fd_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', + "onPointerDown:focusField", + ], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_d1160bcc70_c", + '"data-rx-text-field-input":""', + "spellCheck:false", + 'type:"date"', + ], + "children": [], + }, + { + "name": '"div"', + "props": ["className:sx_85d7cf39b6_c", '"data-side":"left"'], + "children": [{"contents": '"a"'}], + }, + { + "name": '"div"', + "props": ["className:sx_836caf5117_c", '"data-side":"right"'], + "children": [{"contents": '"b"'}], + }, + { + "name": '"div"', + "props": [ + 'className:sx_b7c64f6b9b_c + " " + reflexUIClasses_e201574881', + '"data-side":"left"', + ], + "children": [{"contents": '"c"'}], + }, + ], + } + assert declared_styles(component) == [ + { + "display": { + "default": "flex", + ":has(> input:is([hidden], [type='hidden' i]))": "none", + }, + "alignItems": "stretch", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "boxSizing": "border-box", + "height": "var(--text-field-height)", + "padding": "var(--text-field-border-width)", + "borderRadius": "var(--text-field-border-radius)", + "outlineWidth": {":has(> :is(input, textarea):focus)": "2px"}, + "outlineStyle": {":has(> :is(input, textarea):focus)": "solid"}, + "outlineColor": { + ":has(> :is(input, textarea):focus)": "var(--text-field-focus-color)" + }, + "outlineOffset": {":has(> :is(input, textarea):focus)": "-1px"}, + "backgroundColor": { + "default": "var(--accent-a3)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-a3)", + "::selection": "var(--text-field-selection-color)", + }, + "--rx-text-field-indent": { + "default": "var(--text-field-padding)", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-padding-left": { + "default": "var(--text-field-padding)", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-padding-right": { + "default": "var(--text-field-padding)", + ":has(> [data-side='right'])": "0", + }, + "--rx-text-field-radius-left": { + "default": "calc(var(--text-field-border-radius) - var(--text-field-border-width))", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-radius-right": { + "default": "calc(var(--text-field-border-radius) - var(--text-field-border-width))", + ":has(> [data-side='right'])": "0", + }, + "--rx-text-field-slot-cursor": { + "default": "text", + ":has(> :is(input, textarea):is(:disabled, :read-only):placeholder-shown)": "var(--cursor-disabled)", + }, + "--text-field-height": "var(--space-7)", + "--text-field-padding": "calc(var(--space-3) - var(--text-field-border-width))", + "--text-field-border-radius": "max(var(--radius-3), var(--radius-full))", + "--text-field-native-icon-size": "var(--space-4)", + "fontSize": "var(--font-size-3)", + "letterSpacing": "var(--letter-spacing-3)", + "--rx-text-field-slot-gap": "var(--space-3)", + "--rx-text-field-slot-padding": "var(--space-3)", + "--text-field-selection-color": { + "default": "var(--accent-a5)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-a5)", + }, + "--text-field-focus-color": { + "default": "var(--accent-8)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-8)", + }, + "--text-field-border-width": "0px", + "color": "var(--accent-12)", + "--rx-text-field-slot-color": "var(--accent-12)", + "boxShadow": { + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "inset 0 0 0 1px var(--accent-a5), inset 0 0 0 1px var(--gray-a4)" + }, + }, + { + "appearance": { + "default": "none", + "[type='number']": "textfield", + "::-webkit-inner-spin-button": "none", + "::-webkit-search-cancel-button": "none", + }, + "marginTop": "0", + "marginRight": { + "default": "0", + "::-webkit-calendar-picker-indicator": "calc(var(--space-1) * -1)", + }, + "marginBottom": "0", + "marginLeft": { + "default": "0", + "::-webkit-calendar-picker-indicator": { + "default": "var(--space-1)", + "[type='time']": "0", + }, + }, + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::selection": "var(--text-field-selection-color)", + }, + "backgroundImage": "none", + "boxSizing": { + "default": "border-box", + "::-webkit-calendar-picker-indicator": "content-box", + }, + "color": { + "default": "inherit", + ":is(:disabled, :read-only)": "var(--gray-a11)", + "::placeholder": "var(--accent-12)", + }, + "fontFamily": "inherit", + "fontSize": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "textTransform": "inherit", + "wordSpacing": "inherit", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "whiteSpace": "pre-wrap", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "text", + ":is(:disabled, :read-only):placeholder-shown": "var(--cursor-disabled)", + }, + "WebkitTextFillColor": { + ":is(:disabled, :read-only)": "var(--gray-a11)", + ":autofill": "var(--gray-12)", + }, + "width": { + "default": "100%", + "::-webkit-calendar-picker-indicator": "var(--text-field-native-icon-size)", + }, + "display": "flex", + "alignItems": "center", + "textAlign": "inherit", + "borderRadius": { + "::-webkit-calendar-picker-indicator": "calc(var(--text-field-border-radius) - 2px)" + }, + "borderTopLeftRadius": "var(--rx-text-field-radius-left)", + "borderBottomLeftRadius": "var(--rx-text-field-radius-left)", + "borderTopRightRadius": "var(--rx-text-field-radius-right)", + "borderBottomRightRadius": "var(--rx-text-field-radius-right)", + "textIndent": { + "default": "var(--rx-text-field-indent)", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "0", + }, + "paddingTop": { + "default": "0", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "paddingLeft": { + "default": "0", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "var(--rx-text-field-padding-left)", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "paddingRight": { + "default": "0", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "var(--rx-text-field-padding-right)", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "height": { + "::-webkit-calendar-picker-indicator": "var(--text-field-native-icon-size)" + }, + "paddingBottom": { + "default": "0px", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "backgroundClip": {":autofill": "text"}, + "userSelect": {"::placeholder": "none"}, + "opacity": { + "::placeholder": {"default": 0.6, ":is(:disabled, :read-only)": 0.5} + }, + }, + { + "boxSizing": "border-box", + "flexShrink": 0, + "display": "flex", + "alignItems": "center", + "cursor": "var(--rx-text-field-slot-cursor, text)", + "gap": "var(--rx-text-field-slot-gap)", + "paddingLeft": "var(--rx-text-field-slot-padding)", + "paddingRight": "var(--rx-text-field-slot-padding)", + "color": "var(--rx-text-field-slot-color)", + "order": -1, + "marginLeft": "calc(var(--text-field-border-width) * -1)", + "marginRight": "0", + }, + { + "boxSizing": "border-box", + "flexShrink": 0, + "display": "flex", + "alignItems": "center", + "cursor": "var(--rx-text-field-slot-cursor, text)", + "gap": "var(--rx-text-field-slot-gap)", + "paddingLeft": "var(--rx-text-field-slot-padding)", + "paddingRight": "var(--rx-text-field-slot-padding)", + "color": "var(--rx-text-field-slot-color)", + "order": 0, + "marginLeft": "0", + "marginRight": "calc(var(--text-field-border-width) * -1)", + }, + { + "boxSizing": "border-box", + "flexShrink": 0, + "display": "flex", + "alignItems": "center", + "cursor": "var(--rx-text-field-slot-cursor, text)", + "gap": "var(--rx-text-field-slot-gap)", + "paddingLeft": "var(--rx-text-field-slot-padding)", + "paddingRight": "var(--rx-text-field-slot-padding)", + "color": "var(--accent-a11)", + "order": -1, + "marginLeft": "calc(var(--text-field-border-width) * -1)", + "marginRight": "0", + }, + ] + + +def test_text_field_bound_to_state( + ui_plugin: UIPlugin, +): + """An input a state controls is wrapped to keep what is typed, with the class names of its styles.""" + component = rx.ui.text_field( + value=FieldState.text, + on_change=FieldState.set_text, + id="bound", + size=rx.breakpoints(initial="1", md="3"), + variant="classic", + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_14080a3bf5_c"], + "children": [ + { + "name": "DebounceInput", + "props": [ + "className:sx_7ad96f65e5_c", + '"data-rx-text-field-input":""', + "debounceTimeout:300", + 'element:"input"', + 'id:"bound"', + "inputRef:ref_bound", + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_text_field____field_state.set_text", ({ ["text"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))', + "spellCheck:false", + 'value:(isNotNullOrUndefined(reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.text_rx_state_) ? reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.text_rx_state_ : "")', + ], + "children": [], + } + ], + } + + +def test_text_field_optional_value( + ui_plugin: UIPlugin, +): + """A value that may be None is an empty string to React, and an autocomplete bound to a bool is on or off.""" + component = rx.ui.input( + value=FieldState.maybe, auto_complete=FieldState.complete, read_only=True + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_ff3fb9d45c_c"], + "children": [ + { + "name": '"input"', + "props": [ + 'autoComplete:(reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.complete_rx_state_ ? "on" : "off")', + "className:sx_345c25de08_c", + '"data-rx-text-field-input":""', + "readOnly:true", + "spellCheck:false", + 'value:(isNotNullOrUndefined((pyAnd(!((reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.maybe_rx_state_?.valueOf?.() === null?.valueOf?.())), () => (!((reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.maybe_rx_state_?.valueOf?.() === undefined?.valueOf?.())))) ? reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.maybe_rx_state_ : "")) ? (pyAnd(!((reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.maybe_rx_state_?.valueOf?.() === null?.valueOf?.())), () => (!((reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.maybe_rx_state_?.valueOf?.() === undefined?.valueOf?.())))) ? reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.maybe_rx_state_ : "") : "")', + ], + "children": [], + } + ], + } + + +def test_text_field_unknown_variant(ui_plugin: UIPlugin): + """A variant a text field does not have is an error that lists the ones it has.""" + with pytest.raises(StyleError) as error: + rx.ui.input(variant="solid") + assert ( + str(error.value) + == 'rx.ui.text_field_root: unknown variant "solid". The values are "classic", "surface", "soft".' + ) + + +def test_text_field_unknown_slot_side(ui_plugin: UIPlugin): + """So is the side of a slot.""" + with pytest.raises(TypeError) as error: + rx.ui.input.slot("a", side="top") + assert ( + str(error.value) + == "Invalid var passed for prop TextFieldSlot.side, expected type typing.Literal['left', 'right'], got value 'top' of type ." + ) + + +def test_text_field_script_is_only_for_slots(ui_plugin: UIPlugin): + """The one script of a text field gives its input the focus from a slot.""" + script = "$/reflex-ui/behaviors/text-field.js" + assert script not in rx.ui.input(placeholder="a")._get_all_imports() + assert rx.ui.input(rx.ui.input.slot("a"))._get_all_imports()[script] == [ + ImportVar(tag="focusField") + ] + assert "react-debounce-input@3.3.0" not in rx.ui.input()._get_all_imports() diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index a604551a23a..afe309e5140 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -1570,3 +1570,45 @@ def test_keyframes_are_the_value_of_animation_name_alone(): 'rx.ui.box: style "animation_duration" is given keyframes, which are ' "the value of animation_name." ) + + +def test_shorthand_under_a_condition_is_written_before_its_longhands(): + """StyleX takes a whole shorthand written after its longhands to cancel them.""" + lowered = lower( + "rx.ui.box", + { + "color": "red", + "border_top_left_radius": "var(--radius)", + "border_top_right_radius": "2px", + "padding_left": {"default": "1px", ":hover": "2px"}, + "_before": {"border_radius": "calc(var(--radius) - 1px)"}, + ":hover": {"padding": "var(--space)"}, + "width": "1px", + }, + ) + assert list(lowered.style.items()) == [ + ("color", "red"), + ("borderRadius", {"::before": "calc(var(--radius) - 1px)"}), + ("borderTopLeftRadius", "var(--radius)"), + ("borderTopRightRadius", "2px"), + ("padding", {":hover": "var(--space)"}), + ("paddingLeft", {"default": "1px", ":hover": "2px"}), + ("width", "1px"), + ] + + +def test_shorthand_that_applies_everywhere_stays_after_its_longhands(): + """A whole shorthand written last wins over the longhands before it.""" + style = {"padding_left": "1px", "padding": "var(--space)", "margin": "1px"} + lowered = lower("rx.ui.box", style) + assert list(lowered.style.items()) == [ + ("paddingLeft", "1px"), + ("padding", "var(--space)"), + ("marginTop", "1px"), + ("marginRight", "1px"), + ("marginBottom", "1px"), + ("marginLeft", "1px"), + ] + # A style in which nothing moves is not copied. + conditional = {"padding": {":hover": "var(--space)"}, "padding_left": "1px"} + assert list(lower("rx.ui.box", conditional).style) == ["padding", "paddingLeft"] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index cffb2445383..b0636a5317b 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -132,6 +132,8 @@ def test_every_wave_is_in_the_namespace(): "heading", "hstack", "icon_button", + "input", + "input.slot", "inset", "link", "list", @@ -170,6 +172,9 @@ def test_every_wave_is_in_the_namespace(): "text.quote", "text.span", "text.strong", + "text_area", + "text_field", + "text_field.slot", "theme", "unordered_list", "vstack", @@ -182,11 +187,13 @@ def test_every_wave_is_in_the_namespace(): "callout", "checkbox", "data_list", + "input", "list", "radio", "radio_group", "table", "text", + "text_field", ], ) def test_namespace_has_the_members_of_its_radix_counterpart(namespace: str): From f60fda9398bb37c7e8d2f9ef11e003a2707ed462 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 02:13:43 +0000 Subject: [PATCH 074/204] Add rx.ui.form: the form element of Reflex, with fields and messages A field names its control and points its labels at it while compiling. One script reads the validity the browser has for a control and shows the messages whose condition holds, when Radix shows them: on a submit and when a control is left after a change. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../js/src/behaviors/form-validity.js | 163 ++++++ .../js/tests/behaviors/form-validity.test.js | 194 +++++++ .../parity/ui_parity/components/form.py | 302 ++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/form.py | 530 ++++++++++++++++++ .../src/reflex_components_ui/styles/form.py | 17 + .../components/test_form.py | 527 +++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 9 + 8 files changed, 1743 insertions(+) create mode 100644 packages/reflex-components-ui/js/src/behaviors/form-validity.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/form.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/form.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/form.py create mode 100644 tests/units/reflex_components_ui/components/test_form.py diff --git a/packages/reflex-components-ui/js/src/behaviors/form-validity.js b/packages/reflex-components-ui/js/src/behaviors/form-validity.js new file mode 100644 index 00000000000..b2dd53fe60a --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/form-validity.js @@ -0,0 +1,163 @@ +// What the messages of a form show of the validity of its controls. +// +// The browser knows why a control is not valid: nothing typed, a pattern +// that does not match, a number out of its range. A message names one of +// those reasons and is hidden until it holds, as Radix has it: reasons are +// read when a form is submitted or a control is left after a change, and +// forgotten while its value changes. +// +// Without it the browser reports an invalid control itself, as it does for +// any form. + +/** + * @typedef {HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement} Control + */ + +let ids = 0; + +/** + * Tell the element of an event apart from anything that is no form control. + * + * @param {EventTarget | null} target The target of an event. + * @returns {Control | null} The control, or null. + */ +function controlOf(target) { + return target instanceof HTMLInputElement || + target instanceof HTMLSelectElement || + target instanceof HTMLTextAreaElement + ? target + : null; +} + +/** + * Show the messages of a control whose reason holds, and hide the others. + * + * The field of the control, its labels and the control say whether it is + * valid in `data-valid` and `data-invalid`, and the control is described by + * the messages that show. + * + * @param {Element} form The form. + * @param {Control} control The control. + * @param {boolean} known Whether the validity of the control is read, or + * forgotten. + * @returns {void} + */ +function report(form, control, known) { + const field = control.closest("[data-rx-form-field]"); + const validity = control.validity; + const invalid = known && !validity.valid; + const marked = [control, ...(field ? [field, ...field.querySelectorAll("label")] : [])]; + for (const element of marked) { + if (element !== field || !field.hasAttribute("data-server-invalid")) { + element.toggleAttribute("data-invalid", invalid); + } + element.toggleAttribute("data-valid", known && validity.valid); + } + const shown = []; + for (const message of form.querySelectorAll("[data-rx-form-message]")) { + if (!(message instanceof HTMLElement)) continue; + const name = message.dataset.name; + const own = name ? name === control.name : field !== null && field.contains(message); + if (!own) continue; + const match = message.dataset.match; + if (match && !("force" in message.dataset)) { + message.hidden = !(known && /** @type {Record} */ (validity)[match]); + } + if (!message.hidden) { + message.id ||= `rx-form-message-${++ids}`; + shown.push(message.id); + } + } + if (shown.length) control.setAttribute("aria-describedby", shown.join(" ")); + else control.removeAttribute("aria-describedby"); +} + +/** + * Read the validity of a control the browser found invalid: the `onInvalid` + * of a form. + * + * The messages stand in for the report of the browser, and the first + * invalid control of the form takes the focus. + * + * @param {{ target: EventTarget | null, currentTarget: HTMLFormElement, preventDefault: () => void }} event + * The control found invalid. + * @returns {void} + */ +export function invalid(event) { + const control = controlOf(event.target); + if (!control) return; + const form = event.currentTarget; + if (form.querySelector(":invalid") === control) control.focus(); + event.preventDefault(); + report(form, control, true); +} + +/** + * Forget the validity of a control whose value changes: the + * `onChangeCapture` of a form. + * + * @param {{ target: EventTarget | null, currentTarget: HTMLFormElement }} event + * The change. + * @returns {void} + */ +export function changed(event) { + const control = controlOf(event.target); + if (!control) return; + control.dataset.rxChanged = ""; + report(event.currentTarget, control, false); +} + +/** + * Read the validity of a control that is left after a change: the + * `onBlurCapture` of a form. + * + * @param {{ target: EventTarget | null, currentTarget: HTMLFormElement }} event + * The control losing the focus. + * @returns {void} + */ +export function left(event) { + const control = controlOf(event.target); + if (!control || !("rxChanged" in control.dataset)) return; + delete control.dataset.rxChanged; + report(event.currentTarget, control, true); +} + +/** + * Forget the validity of every control of a form that is reset: its + * `onReset`. + * + * @param {{ currentTarget: HTMLFormElement }} event The reset. + * @returns {void} + */ +export function cleared(event) { + const form = event.currentTarget; + for (const element of form.elements) { + const control = controlOf(element); + if (control) { + delete control.dataset.rxChanged; + report(form, control, false); + } + } +} + +/** + * Give the focus to the first control of a form that is not valid, when + * the server finds a field invalid: the `ref` of the field while it is. + * + * It is the first one of the whole form, as in Radix: a form with several + * such fields, or with one the browser finds invalid too, starts at the top. + * + * @param {Element | null} field The field, or null when it stops being invalid. + * @returns {void} + */ +export function focusInvalid(field) { + const form = field?.closest("form"); + if (!form) return; + for (const element of form.elements) { + const control = controlOf(element); + if (control && (control.ariaInvalid === "true" || !control.validity.valid)) { + control.focus(); + return; + } + } +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js b/packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js new file mode 100644 index 00000000000..8b617024f83 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js @@ -0,0 +1,194 @@ +// What the messages of a form show of the validity of its controls: read +// on a submit and when a control is left after a change, forgotten while +// its value changes and on a reset. +import { beforeEach, expect, test } from "vitest"; + +import { + changed, + cleared, + focusInvalid, + invalid, + left, +} from "$/reflex-ui/behaviors/form-validity.js"; + +/** @type {HTMLFormElement} */ +let form; + +beforeEach(() => { + document.body.innerHTML = ` +
+
+ + + + + always + forced +
+
+ + +
+ + + +
`; + form = /** @type {HTMLFormElement} */ (document.querySelector("form")); +}); + +/** + * Find a control of the form. + * + * @param {string} name The name of the control. + * @returns {HTMLInputElement} The control. + */ +function control(name) { + return /** @type {HTMLInputElement} */ (form.elements.namedItem(name)); +} + +/** + * Read which messages of the form show. + * + * @returns {(string | null)[]} The text of each one, in the order of the form. + */ +function shown() { + return [...form.querySelectorAll("span")] + .filter((message) => !message.hidden) + .map((message) => message.textContent); +} + +/** + * Read which of the marks of validity an element has. + * + * @param {string} id The id of the element. + * @returns {string[]} The names of the attributes. + */ +function marks(id) { + const element = /** @type {HTMLElement} */ (document.getElementById(id)); + return ["data-valid", "data-invalid"].filter((mark) => element.hasAttribute(mark)); +} + +/** + * Make the event of a control, as React hands it to the form. + * + * @param {EventTarget | null} target The control. + * @returns {{ target: EventTarget | null, currentTarget: HTMLFormElement, preventDefault: () => void, prevented: boolean }} + * The event. + */ +function eventOf(target) { + const event = { + target, + currentTarget: form, + prevented: false, + preventDefault: () => { + event.prevented = true; + }, + }; + return event; +} + +test("a control found invalid shows its reasons, is described by them and takes the focus", () => { + const email = control("email"); + const event = eventOf(email); + invalid(event); + expect(shown()).toEqual(["needed", "always", "forced", "outside"]); + expect(event.prevented).toBe(true); + expect(document.activeElement).toBe(email); + expect(marks("email-field")).toEqual(["data-invalid"]); + expect(marks("email-label")).toEqual(["data-invalid"]); + expect(email.hasAttribute("data-invalid")).toBe(true); + const described = (email.getAttribute("aria-describedby") ?? "").split(" "); + expect(described.map((id) => document.getElementById(id)?.textContent)).toEqual([ + "needed", + "always", + "forced", + "outside", + ]); +}); + +test("only the first invalid control of the form takes the focus", () => { + const code = control("code"); + code.value = "abc"; + invalid(eventOf(code)); + expect(shown()).toEqual(["always", "forced", "digits"]); + expect(document.activeElement).toBe(document.body); +}); + +test("a change forgets the reasons, and leaving the control reads them again", () => { + const email = control("email"); + invalid(eventOf(email)); + email.value = "ada"; + changed(eventOf(email)); + expect(shown()).toEqual(["always", "forced"]); + expect(marks("email-field")).toEqual([]); + left(eventOf(email)); + expect(shown()).toEqual(["not an email", "always", "forced"]); + expect(email.getAttribute("aria-describedby")?.split(" ")[0]).toBe("mine"); + email.value = "ada@example.com"; + changed(eventOf(email)); + left(eventOf(email)); + expect(shown()).toEqual(["always", "forced"]); + expect(marks("email-field")).toEqual(["data-valid"]); +}); + +test("a control that is left without a change keeps what it shows", () => { + left(eventOf(control("email"))); + expect(shown()).toEqual(["always", "forced"]); + expect(marks("email-field")).toEqual([]); +}); + +test("a field the server finds invalid stays marked whatever the browser says", () => { + const code = control("code"); + code.value = "12"; + changed(eventOf(code)); + left(eventOf(code)); + expect(marks("code-field")).toEqual(["data-valid", "data-invalid"]); + expect(code.hasAttribute("aria-describedby")).toBe(false); +}); + +test("a reset forgets the reasons of every control", () => { + invalid(eventOf(control("email"))); + control("code").value = "abc"; + invalid(eventOf(control("code"))); + cleared({ currentTarget: form }); + expect(shown()).toEqual(["always", "forced"]); + expect(marks("email-field")).toEqual([]); + left(eventOf(control("code"))); + expect(shown()).toEqual(["always", "forced"]); +}); + +test("a control outside a field has the messages that name it", () => { + const free = control("free"); + free.required = true; + form.insertAdjacentHTML( + "beforeend", + '', + ); + invalid(eventOf(free)); + expect(shown()).toEqual(["always", "forced", "free"]); +}); + +test("what is no form control is left alone", () => { + for (const handler of [invalid, changed, left]) { + handler(eventOf(form.querySelector("button"))); + handler(eventOf(null)); + } + expect(shown()).toEqual(["always", "forced"]); +}); + +test("a field the server finds invalid gives the first invalid control the focus", () => { + focusInvalid(document.getElementById("code-field")); + expect(document.activeElement).toBe(control("email")); + control("email").value = "ada@example.com"; + control("code").setAttribute("aria-invalid", "true"); + focusInvalid(document.getElementById("code-field")); + expect(document.activeElement).toBe(control("code")); +}); + +test("a field that stops being invalid, or is in no form, moves no focus", () => { + focusInvalid(null); + focusInvalid(document.body); + control("email").value = "ada@example.com"; + focusInvalid(document.getElementById("email-field")); + expect(document.activeElement).toBe(document.body); +}); diff --git a/packages/reflex-components-ui/parity/ui_parity/components/form.py b/packages/reflex-components-ui/parity/ui_parity/components/form.py new file mode 100644 index 00000000000..0c18c87c0d4 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/form.py @@ -0,0 +1,302 @@ +"""The form: its fields, labels and messages, and what it does with validity.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, Matrix +from ui_parity.samples import wait_for_text + + +def _form(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a form with one field. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell. ``control`` names what the field holds. + + Returns: + The form. + """ + form = namespace.form + control = props.get("control") + if control == "input": + held = form.control(namespace.input(placeholder="you@example.com")) + elif control == "area": + held = form.control(namespace.text_area(placeholder="Say something")) + elif control == "native": + held = form.control(rx.el.input(placeholder="you@example.com")) + else: + held = form.control() + return form.root( + form.field( + form.label("Email"), + held, + form.message("Always shown", color="gray"), + form.message( + "Forced", match="valueMissing", force_match=True, color="gray" + ), + form.message("Hidden", match="typeMismatch", color="gray"), + name="email", + ), + form.submit("Send"), + ) + + +MATRIX = Matrix( + component="form", + render=_form, + sweep={ + "control": ["input", "area", "native"], + "appearance": [DARK], + }, + stage=(280, 220), + crop="stage", + parts={ + "field": "form > div", + "label": "label", + "message": "form > div > span", + "submit": "form > button", + }, + # A field the server finds invalid gives its control the focus, which + # only one cell of a page could have: the contract has it. + threshold=0, + tolerance=0, +) + + +class FormState(rx.State): + """What the form of the contract is bound to.""" + + taken: bool = False + cleared: int = 0 + submitted: dict[str, Any] = {} + submissions: int = 0 + + @rx.event + def take(self): + """Have the server find the code invalid.""" + self.taken = True + + @rx.event + def clear(self): + """Forget what the server found.""" + self.taken = False + self.cleared += 1 + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what the form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +def _contract_form(namespace: Any) -> Any: + """Create the form of the contract. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + The form, and what shows the state it is bound to. + """ + form = namespace.form + return namespace.box( + form.root( + form.field( + form.label("Email"), + form.control(namespace.input(type="email", required=True)), + form.message("Email is needed", match="valueMissing"), + form.message("Not an email", match="typeMismatch"), + name="email", + id="email-field", + ), + form.field(form.label("Age"), form.control(), name="age"), + form.field( + form.label("Code"), + form.control(rx.el.input(pattern="[0-9]+")), + form.message("Digits only", match="patternMismatch"), + form.message( + "Taken", match="valueMissing", force_match=FormState.taken + ), + name="code", + server_invalid=FormState.taken, + id="code-field", + ), + form.message("Outside", match="valueMissing", name="email"), + form.submit("Send", id="send"), + rx.el.button("Reset", type="reset", id="reset"), + on_submit=FormState.submit, + on_clear_server_errors=FormState.clear, + id="form", + ), + rx.el.button("Take", id="take", on_click=FormState.take), + rx.el.span(FormState.cleared.to_string(), id="cleared"), + rx.el.span(FormState.taken.to_string(), id="taken"), + rx.el.span(FormState.submitted.to_string(), id="submitted"), + rx.el.span(FormState.submissions.to_string(), id="submissions"), + ) + + +CONTRACT = Contract(component="form", render=_contract_form) + +# The messages that show, in the order of the page. +SHOWN = ( + "[...document.querySelectorAll('#form span')]" + ".filter(message => message.checkVisibility()).map(message => message.textContent)" +) +# The name of the control that has the focus. +FOCUSED = "document.activeElement.name" + + +def _wait_for_messages(run: Run, messages: list[str]) -> None: + """Wait until the messages that show are the ones expected. + + Args: + run: The run, on a page. + messages: The text of each message that is to show. + """ + run.page.wait_for_function( + f"expected => {SHOWN}.join('|') === expected", arg="|".join(messages) + ) + + +def _control(run: Run, name: str) -> Any: + """Find a control of the form by the name its field gives it. + + Args: + run: The run, on a page. + name: The name of the field. + + Returns: + The control. + """ + return run.page.locator(f"#form [name='{name}']") + + +@CONTRACT.step("is a form with a submit button in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("form").tag == "form" + send = run.server.element("send") + assert (send.tag, send.attributes["type"], send.text) == ( + "button", + "submit", + "Send", + ) + + +@CONTRACT.step( + "a label gives its control the focus with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + page = run.page + page.get_by_text("Code", exact=True).click() + assert page.evaluate(FOCUSED) == "code" + page.keyboard.type("12") + assert _control(run, "code").input_value() == "12" + assert page.evaluate(SHOWN) == [] + + +@CONTRACT.step("each control has the name of its field and of the label of its field") +def _role(run: Run) -> None: + page = run.page + for label in ("Email", "Age", "Code"): + textbox = page.get_by_role("textbox", name=label, exact=True) + assert textbox.get_attribute("name") == label.lower() + assert page.get_by_role("button", name="Send").get_attribute("type") == "submit" + assert page.evaluate(SHOWN) == [] + + +@CONTRACT.step("a submit shows why a control is not valid, and gives it the focus") +def _invalid(run: Run) -> None: + page = run.page + _control(run, "age").focus() + page.locator("#send").click() + _wait_for_messages(run, ["Email is needed", "Outside"]) + assert page.evaluate(FOCUSED) == "email" + assert page.locator("#submissions").text_content() == "0" + assert page.locator("#email-field").get_attribute("data-invalid") is not None + described = _control(run, "email").get_attribute("aria-describedby") or "" + assert [ + page.locator(f"[id='{message}']").text_content() + for message in described.split() + ] == ["Email is needed", "Outside"] + + +@CONTRACT.step("a change forgets the reason, and leaving the control reads it again") +def _change(run: Run) -> None: + page = run.page + page.locator("#send").click() + _wait_for_messages(run, ["Email is needed", "Outside"]) + page.keyboard.type("ada") + _wait_for_messages(run, []) + assert page.locator("#email-field").get_attribute("data-invalid") is None + page.keyboard.press("Tab") + _wait_for_messages(run, ["Not an email"]) + _control(run, "email").fill("ada@example.com") + page.keyboard.press("Tab") + _wait_for_messages(run, []) + assert page.locator("#email-field").get_attribute("data-valid") is not None + + +@CONTRACT.step("a pattern that does not match is a reason too") +def _pattern(run: Run) -> None: + page = run.page + _control(run, "email").fill("ada@example.com") + _control(run, "code").fill("abc") + page.keyboard.press("Enter") + _wait_for_messages(run, ["Digits only"]) + assert page.evaluate(FOCUSED) == "code" + assert page.locator("#submissions").text_content() == "0" + + +@CONTRACT.step("a reset forgets every reason") +def _reset(run: Run) -> None: + page = run.page + page.locator("#send").click() + _wait_for_messages(run, ["Email is needed", "Outside"]) + page.locator("#reset").click() + _wait_for_messages(run, []) + assert page.locator("#email-field").get_attribute("data-invalid") is None + + +@CONTRACT.step("submits the values of its controls by the names of their fields") +def _submit(run: Run) -> None: + page = run.page + _control(run, "email").fill("ada@example.com") + _control(run, "age").fill("36") + _control(run, "code").fill("123") + page.keyboard.press("Enter") + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == ( + '{"email":"ada@example.com","age":"36","code":"123"}' + ) + assert page.evaluate(SHOWN) == [] + + +@CONTRACT.step( + "a field the server finds invalid says so, with the focus, until a reset" +) +def _server_invalid(run: Run) -> None: + page = run.page + _control(run, "email").fill("ada@example.com") + page.locator("#take").click() + wait_for_text(page, "taken", "true") + _wait_for_messages(run, ["Taken"]) + assert _control(run, "code").get_attribute("aria-invalid") == "true" + assert page.locator("#code-field").get_attribute("data-invalid") is not None + page.wait_for_function(f"{FOCUSED} === 'code'") + page.keyboard.type("1") + assert page.locator("#cleared").text_content() == "0" + page.locator("#reset").click() + wait_for_text(page, "cleared", "1") + wait_for_text(page, "taken", "false") + _wait_for_messages(run, []) + assert _control(run, "code").get_attribute("aria-invalid") is None 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 c7b4644a728..b821cf9286c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -17,6 +17,7 @@ "components.checkbox_cards": ["checkbox_cards"], "components.checkbox_group": ["checkbox_group"], "components.data_list": ["data_list"], + "components.form": ["form"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], "components.progress": ["progress"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/form.py b/packages/reflex-components-ui/src/reflex_components_ui/components/form.py new file mode 100644 index 00000000000..a98f425cc24 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/form.py @@ -0,0 +1,530 @@ +"""A form: the native element, its fields, and messages for what is not valid.""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterator +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import ( + BaseComponent, + Component, + ComponentNamespace, + field, +) +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, no_args_event_spec +from reflex_base.utils.form import FormData as _FormData +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_components_core.core.debounce import DebounceInput +from reflex_components_core.el.elements.forms import BaseInput, Select, Textarea +from reflex_components_core.el.elements.forms import Form as HTMLForm + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._group import literal +from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.form import FORM, FORM_FIELD, FORM_LABEL, FORM_MESSAGE + +# A form control composes with native form controls only: an input, select +# or textarea, or a component rendering one. +_FORM_CONTROL_CHILD_TYPES = (BaseInput, Select, Textarea, DebounceInput) + +_SCRIPT = f"$/{WEB_DIR}/behaviors/form-validity.js" + + +def _handler(name: str) -> Var: + """Get one of the functions that show the validity of a form's controls. + + Args: + name: The name of the function. + + Returns: + The function, with its import. + """ + return Var(name, _var_data=VarData(imports={_SCRIPT: [ImportVar(tag=name)]})) + + +# What reads the validity of the controls of a form, all the JavaScript of +# one: a form without a message has none. +_INVALID = _handler("invalid") +_CHANGED = _handler("changed") +_LEFT = _handler("left") +_CLEARED = _handler("cleared") +_FOCUS_INVALID = _handler("focusInvalid") + +# Numbers the fields whose control is given no id of its own. +_ids = itertools.count(1) + + +def _find(component: BaseComponent, kind: type | tuple[type, ...]) -> Iterator[Any]: + """Find the components of a kind below another, at any depth. + + Args: + component: Where to look. + kind: The class of what is looked for. + + Yields: + Each one, in the order of the tree. + """ + for child in component.children: + if isinstance(child, kind): + yield child + yield from _find(child, kind) + + +def _native(control: Component) -> Component: + """Find the native control a component renders. + + Args: + control: A form control, or a component that draws a box around one. + + Returns: + The component that renders the input, the select or the textarea. + """ + if isinstance(control, UIComponent) and control.tag == "div": + return control.children[0] # pyright: ignore[reportReturnType] + return control + + +def _give(control: Component, prop: str, value: Any) -> Any: + """Give a control an attribute, unless it has it already. + + Args: + control: The component that renders the control. + prop: The attribute. + value: Its value. + + Returns: + The value the control has now. + """ + if prop in control.get_fields(): + current = getattr(control, prop) + if current is None: + setattr(control, prop, value) + return value + return current + return control.custom_attrs.setdefault(prop, value) + + +class FormRoot(HTMLForm, UIComponent): + """The root component of a radix form. + + The form element of Reflex comes first: it renders the submit it handles + over what an rx.ui element renders. + """ + + tag = "form" + + styles: ClassVar[ComponentStyles] = FORM + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + on_clear_server_errors: EventHandler[no_args_event_spec] = field( + doc="Fired when the errors are cleared." + ) + + def _set_slot(self) -> None: + """Render the form itself: it is the element that submits.""" + + def _post_init(self, *args, **kwargs): + """Initialize the form, and see whether it has validity to show. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + self._has_messages = next(_find(self, FormMessage), None) is not None + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the form, its script 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) + if self._has_messages: + yield _INVALID + yield _CHANGED + yield _LEFT + yield _CLEARED + + def _render(self) -> CommonTag: + """Render the form. + + Returns: + The tag. A form with messages reads the validity of its controls + where it changes, and server errors are cleared where Radix + clears them: on a submit and on a reset. + """ + tag = super()._render() + clear = tag.props.get("onClearServerErrors") + tag = tag.remove_props("onClearServerErrors") + handlers: dict[str, list[str]] = {} + if self._has_messages: + handlers = { + "onInvalid": [str(_INVALID)], + "onChangeCapture": [str(_CHANGED)], + "onBlurCapture": [str(_LEFT)], + "onReset": [str(_CLEARED)], + } + var_data = None + if clear is not None: + clear = LiteralVar.create(clear) + var_data = clear._get_all_var_data() + for prop in ("onReset", "onSubmitCapture"): + handlers.setdefault(prop, []).append(f"({clear!s})") + for prop, functions in handlers.items(): + calls = "; ".join(f"{function}(event)" for function in functions) + tag = tag.add_props(**{ + prop: Var(f"((event) => {{ {calls}; }})", _var_data=var_data) + }) + return tag + + +class FormField(UIComponent): + """A form field component.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = FORM_FIELD + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + name: Var[str] = field( + doc="The name of the form field, that is passed down to the control and used to match with validation messages." + ) + + server_invalid: Var[bool] = field( + doc="Flag to mark the form field as invalid, for server side validation." + ) + + def _set_slot(self) -> None: + """Render the field itself.""" + + def _post_init(self, *args, **kwargs): + """Initialize the field: name its control, and point its labels at it. + + Radix hands the name and an id through a context. Here the field + finds its control and its labels while compiling, below it at any + depth. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + control_id: Any = None + for control in _find(self, Component): + if not getattr(control, "_is_field_control", False): + continue + if self.name is not None: + _give(control, "name", self.name) + if control_id is None: + control_id = control.id + if control_id is None: + control_id = control.id = LiteralVar.create( + f"rx-form-field-{next(_ids)}" + ) + if self.server_invalid is not None: + control.custom_attrs.setdefault( + "aria-invalid", + Var( + f"({self.server_invalid!s} || undefined)", + _var_data=self.server_invalid._get_all_var_data(), + ), + ) + if control_id is not None: + for label in _find(self, FormLabel): + label.custom_attrs.setdefault("htmlFor", control_id) + + def _exclude_props(self) -> list[str]: + """Keep the props that are not attributes off the element. + + Returns: + The props read as styles, and the ones the field hands down. + """ + return [*super()._exclude_props(), "name", "server_invalid"] + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the field, its script 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) + if ( + self.server_invalid is not None + and literal(self.server_invalid) is not False + ): + yield _FOCUS_INVALID + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the field. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, marked as the field of the messages inside it, and as + invalid when the server says so. + """ + tag = super()._render(props).add_props(**{"data-rx-form-field": ""}) + invalid = self.server_invalid + if invalid is None or literal(invalid) is False: + return tag + flag = ( + "" + if literal(invalid) is True + else Var( + f'({invalid!s} ? "" : undefined)', + _var_data=invalid._get_all_var_data(), + ) + ) + # A ref that is new when the server finds the field invalid, so that + # React calls it then: the control takes the focus, as in Radix. + focus = ( + _FOCUS_INVALID + if literal(invalid) is True + else Var( + f"({invalid!s} ? {_FOCUS_INVALID!s} : undefined)", + _var_data=VarData.merge( + invalid._get_all_var_data(), _FOCUS_INVALID._get_all_var_data() + ), + ) + ) + return tag.add_props( + ref=focus, **{"data-invalid": flag, "data-server-invalid": flag} + ) + + +class FormLabel(UIComponent): + """A form label component.""" + + tag = "label" + + styles: ClassVar[ComponentStyles] = FORM_LABEL + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + def _set_slot(self) -> None: + """Render the label itself.""" + + +class FormControl(UIComponent): + """A form control component.""" + + tag = "input" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + name: Var[str] = field( + doc="The name of the control, in place of the name of the enclosing form field." + ) + + # Named by the field around it, which points its labels at it. + _is_field_control: ClassVar[bool] = True + + @classmethod + def create(cls, *children, **props): + """Create a Form Control component. + + The control renders an input, or the native form control its child + renders, which then takes the enclosing form field's name and + validation messages. + + Args: + *children: The control to render, if any. + **props: The properties of the form control. + + Returns: + The form control component. + + Raises: + ValueError: If more than one child is given. + TypeError: If the child does not render a native form control. + """ + if len(children) > 1: + msg = f"FormControl can only have at most one child, got {len(children)} children" + raise ValueError(msg) + for child in children: + if not isinstance(child, _FORM_CONTROL_CHILD_TYPES): + msg = ( + "The child of rx.ui.form.control must render a native form " + "control: rx.ui.input, rx.ui.text_area, rx.debounce_input, " + "rx.el.input, rx.el.select or rx.el.textarea, not " + f"{type(child).__name__}. Give other controls such as " + "rx.ui.checkbox or rx.ui.select a `name` and place them " + "under rx.ui.form.root or rx.ui.form.field instead." + ) + raise TypeError(msg) + # The child is the control: what the field gives a control goes + # to the native element it renders. + native = _native(child) + native._is_field_control = True # pyright: ignore[reportAttributeAccessIssue] + name = props.get("name") + if name is not None: + _give(native, "name", LiteralVar.create(name)) + return child + return super().create(**props) + + def _set_slot(self) -> None: + """Render the input itself: a child is returned in its place.""" + + +LiteralMatcher = Literal[ + "badInput", + "patternMismatch", + "rangeOverflow", + "rangeUnderflow", + "stepMismatch", + "tooLong", + "tooShort", + "typeMismatch", + "valid", + "valueMissing", +] + + +class FormMessage(UIComponent): + """A form message component.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = FORM_MESSAGE + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + name: Var[str] = field( + doc="Used to target a specific field by name when rendering outside of a Field part." + ) + + match: Var[LiteralMatcher] = field( + doc="Used to indicate on which condition the message should be visible." + ) + + force_match: Var[bool] = field( + doc="Forces the message to be shown. This is useful when using server-side validation." + ) + + def _set_slot(self) -> None: + """Render the message itself.""" + + def _exclude_props(self) -> list[str]: + """Keep the props that are rendered as data off the element. + + Returns: + The props read as styles, and the ones of the message. + """ + return [*super()._exclude_props(), "name", "match", "force_match"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the message. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. A message with a condition is hidden until its script + finds that the condition holds, or it is forced to show. + """ + tag = super()._render(props).add_props(**{"data-rx-form-message": ""}) + if self.name is not None: + tag = tag.add_props(**{"data-name": self.name}) + if self.match is None: + return tag + tag = tag.add_props(**{"data-match": self.match}) + force = self.force_match + if force is None or literal(force) is False: + return tag.add_props(hidden=True) + if literal(force) is True: + return tag.add_props(**{"data-force": ""}) + var_data = force._get_all_var_data() + return tag.add_props( + hidden=Var(f"!({force!s})", _var_type=bool, _var_data=var_data), + **{"data-force": Var(f'({force!s} ? "" : undefined)', _var_data=var_data)}, + ) + + +class FormValidityState(UIComponent): + """A form validity state component.""" + + tag = "span" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + def _set_slot(self) -> None: + """Render the element itself.""" + + +class FormSubmit(UIComponent): + """A form submit component.""" + + tag = "button" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the button that submits the form. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, or the child rendered in its place, with the type of a + submit button. + """ + return super()._render(props).add_props(type="submit") + + +# This class is created mainly for reflex-web docs. +class Form(FormRoot): + """The Form component.""" + + +class FormNamespace(ComponentNamespace): + """Form components.""" + + # Stubbed as a class so ``rx.ui.form.FormData`` works in type annotations. + _stub_as_class: ClassVar[bool] = True + + root = staticmethod(FormRoot.create) + control = staticmethod(FormControl.create) + field = staticmethod(FormField.create) + label = staticmethod(FormLabel.create) + message = staticmethod(FormMessage.create) + submit = staticmethod(FormSubmit.create) + validity_state = staticmethod(FormValidityState.create) + FormData = _FormData + __call__ = staticmethod(Form.create) + + +form = FormNamespace() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/form.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/form.py new file mode 100644 index 00000000000..99d08496cd7 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/form.py @@ -0,0 +1,17 @@ +"""The look of a form and of its parts: what the Radix wrappers give them.""" + +from __future__ import annotations + +from reflex_components_ui.style import ComponentStyles + +FORM: ComponentStyles = {"base": {"width": "100%"}} + +FORM_FIELD: ComponentStyles = {"base": {"display": "grid", "margin_bottom": "10px"}} + +FORM_LABEL: ComponentStyles = { + "base": {"font_size": "15px", "font_weight": "500", "line_height": "35px"} +} + +FORM_MESSAGE: ComponentStyles = { + "base": {"font_size": "13px", "opacity": "0.8", "color": "white"} +} diff --git a/tests/units/reflex_components_ui/components/test_form.py b/tests/units/reflex_components_ui/components/test_form.py new file mode 100644 index 00000000000..594bffecb10 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_form.py @@ -0,0 +1,527 @@ +"""Tests for reflex_components_ui.components.form.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import form as form_module +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +class FormState(rx.State): + """What a form is bound to.""" + + taken: bool = False + + @rx.event + def clear(self): + """Forget what the server found.""" + self.taken = False + + @rx.event + def submit(self, data: dict[str, Any]): + """Take what the form submits. + + Args: + data: The values of the form. + """ + + +def test_form_parts( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A field names its control and points its label at it; a message with a condition is hidden until it holds, and the form reads the validity of its controls.""" + component = rx.ui.form( + rx.ui.form.field( + rx.ui.form.label("Email"), + rx.ui.form.control(rx.ui.input(type="email", required=True, id="email")), + rx.ui.form.message("Needed", match="valueMissing"), + rx.ui.form.message("Always"), + rx.ui.form.message("Forced", match="typeMismatch", force_match=True), + name="email", + ), + rx.ui.form.message("Outside", match="valueMissing", name="email"), + rx.ui.form.submit("Send"), + id="signup", + ) + assert component.render() == { + "name": '"form"', + "props": [ + "className:sx_5073704993_c", + 'id:"signup"', + "onBlurCapture:((event) => { left(event); })", + "onChangeCapture:((event) => { changed(event); })", + "onInvalid:((event) => { invalid(event); })", + "onReset:((event) => { cleared(event); })", + "onSubmit:handleSubmit_ff7a0ed8ca0437fd853c637504ba1398", + "ref:ref_signup", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_7fb5ccb001_c", '"data-rx-form-field":""'], + "children": [ + { + "name": '"label"', + "props": ["className:sx_3f1c4be050_c", 'htmlFor:"email"'], + "children": [{"contents": '"Email"'}], + }, + { + "name": '"div"', + "props": ["className:sx_ff3fb9d45c_c"], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_345c25de08_c", + '"data-rx-text-field-input":""', + 'id:"email"', + 'name:"email"', + "ref:ref_email", + "required:true", + "spellCheck:false", + 'type:"email"', + ], + "children": [], + } + ], + }, + { + "name": '"span"', + "props": [ + "className:sx_71d77c9098_c", + '"data-match":"valueMissing"', + '"data-rx-form-message":""', + "hidden:true", + ], + "children": [{"contents": '"Needed"'}], + }, + { + "name": '"span"', + "props": [ + "className:sx_71d77c9098_c", + '"data-rx-form-message":""', + ], + "children": [{"contents": '"Always"'}], + }, + { + "name": '"span"', + "props": [ + "className:sx_71d77c9098_c", + '"data-force":""', + '"data-match":"typeMismatch"', + '"data-rx-form-message":""', + ], + "children": [{"contents": '"Forced"'}], + }, + ], + }, + { + "name": '"span"', + "props": [ + "className:sx_71d77c9098_c", + '"data-match":"valueMissing"', + '"data-name":"email"', + '"data-rx-form-message":""', + "hidden:true", + ], + "children": [{"contents": '"Outside"'}], + }, + { + "name": '"button"', + "props": ['type:"submit"'], + "children": [{"contents": '"Send"'}], + }, + ], + } + assert declared_styles(component) == [ + {"width": "100%"}, + {"display": "grid", "marginBottom": "10px"}, + {"fontSize": "15px", "fontWeight": "500", "lineHeight": "35px"}, + { + "display": { + "default": "flex", + ":has(> input:is([hidden], [type='hidden' i]))": "none", + }, + "alignItems": "stretch", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "boxSizing": "border-box", + "height": "var(--text-field-height)", + "padding": "var(--text-field-border-width)", + "borderRadius": "var(--text-field-border-radius)", + "outlineWidth": {":has(> :is(input, textarea):focus)": "2px"}, + "outlineStyle": {":has(> :is(input, textarea):focus)": "solid"}, + "outlineColor": { + ":has(> :is(input, textarea):focus)": "var(--text-field-focus-color)" + }, + "outlineOffset": {":has(> :is(input, textarea):focus)": "-1px"}, + "backgroundColor": { + "default": "var(--color-surface)", + "::selection": "var(--text-field-selection-color)", + }, + "--rx-text-field-indent": { + "default": "var(--text-field-padding)", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-padding-left": { + "default": "var(--text-field-padding)", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-padding-right": { + "default": "var(--text-field-padding)", + ":has(> [data-side='right'])": "0", + }, + "--rx-text-field-radius-left": { + "default": "calc(var(--text-field-border-radius) - var(--text-field-border-width))", + ":has(> [data-side='left'])": "0", + }, + "--rx-text-field-radius-right": { + "default": "calc(var(--text-field-border-radius) - var(--text-field-border-width))", + ":has(> [data-side='right'])": "0", + }, + "--rx-text-field-slot-cursor": { + "default": "text", + ":has(> :is(input, textarea):is(:disabled, :read-only):placeholder-shown)": "var(--cursor-disabled)", + }, + "--text-field-height": "var(--space-6)", + "--text-field-padding": "calc(var(--space-2) - var(--text-field-border-width))", + "--text-field-border-radius": "max(var(--radius-2), var(--radius-full))", + "--text-field-native-icon-size": "var(--space-4)", + "fontSize": "var(--font-size-2)", + "letterSpacing": "var(--letter-spacing-2)", + "--rx-text-field-slot-gap": "var(--space-2)", + "--rx-text-field-slot-padding": "var(--space-2)", + "--text-field-selection-color": { + "default": "var(--focus-a5)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-a5)", + }, + "--text-field-focus-color": { + "default": "var(--focus-8)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "var(--gray-8)", + }, + "--text-field-border-width": "1px", + "color": "var(--gray-12)", + "--rx-text-field-slot-color": "var(--gray-a11)", + "boxShadow": { + "default": "inset 0 0 0 var(--text-field-border-width) var(--gray-a7)", + ":has(> :is(input, textarea):is(:disabled, :read-only))": "inset 0 0 0 var(--text-field-border-width) var(--gray-a6)", + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "inset 0 0 0 1px var(--focus-a5), inset 0 0 0 1px var(--gray-a5)", + }, + "backgroundImage": { + ":has(> :is(input, textarea):is(:disabled, :read-only))": "linear-gradient(var(--gray-a2), var(--gray-a2))", + ":has(> :is(input, textarea):autofill:not(:is(:disabled, :read-only)))": "linear-gradient(var(--focus-a2), var(--focus-a2))", + }, + "backgroundClip": "content-box", + }, + { + "appearance": { + "default": "none", + "[type='number']": "textfield", + "::-webkit-inner-spin-button": "none", + "::-webkit-search-cancel-button": "none", + }, + "marginTop": "0", + "marginRight": { + "default": "0", + "::-webkit-calendar-picker-indicator": "calc(var(--space-1) * -1)", + }, + "marginBottom": "0", + "marginLeft": { + "default": "0", + "::-webkit-calendar-picker-indicator": { + "default": "var(--space-1)", + "[type='time']": "0", + }, + }, + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::selection": "var(--text-field-selection-color)", + }, + "backgroundImage": "none", + "boxSizing": { + "default": "border-box", + "::-webkit-calendar-picker-indicator": "content-box", + }, + "color": { + "default": "inherit", + ":is(:disabled, :read-only)": "var(--gray-a11)", + "::placeholder": "var(--gray-a10)", + }, + "fontFamily": "inherit", + "fontSize": "inherit", + "fontWeight": "normal", + "fontStyle": "normal", + "lineHeight": "inherit", + "letterSpacing": "inherit", + "textTransform": "inherit", + "wordSpacing": "inherit", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentcolor", + "outlineOffset": "0", + "whiteSpace": "pre-wrap", + "WebkitTapHighlightColor": "transparent", + "cursor": { + "default": "text", + ":is(:disabled, :read-only):placeholder-shown": "var(--cursor-disabled)", + }, + "WebkitTextFillColor": { + ":is(:disabled, :read-only)": "var(--gray-a11)", + ":autofill": "var(--gray-12)", + }, + "width": { + "default": "100%", + "::-webkit-calendar-picker-indicator": "var(--text-field-native-icon-size)", + }, + "display": "flex", + "alignItems": "center", + "textAlign": "inherit", + "borderRadius": { + "::-webkit-calendar-picker-indicator": "calc(var(--text-field-border-radius) - 2px)" + }, + "borderTopLeftRadius": "var(--rx-text-field-radius-left)", + "borderBottomLeftRadius": "var(--rx-text-field-radius-left)", + "borderTopRightRadius": "var(--rx-text-field-radius-right)", + "borderBottomRightRadius": "var(--rx-text-field-radius-right)", + "textIndent": { + "default": "var(--rx-text-field-indent)", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "0", + }, + "paddingTop": { + "default": "0", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "paddingLeft": { + "default": "0", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "var(--rx-text-field-padding-left)", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "paddingRight": { + "default": "0", + ":is([type='date'], [type='datetime-local'], [type='time'], [type='week'], [type='month'])": "var(--rx-text-field-padding-right)", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "height": { + "::-webkit-calendar-picker-indicator": "var(--text-field-native-icon-size)" + }, + "paddingBottom": { + "default": "0.5px", + "::-webkit-calendar-picker-indicator": "var(--space-1)", + }, + "backgroundClip": {":autofill": "text"}, + "userSelect": {"::placeholder": "none"}, + "opacity": { + "::placeholder": {"default": 1, ":is(:disabled, :read-only)": 0.5} + }, + }, + {"fontSize": "13px", "opacity": "0.8", "color": "white"}, + {"fontSize": "13px", "opacity": "0.8", "color": "white"}, + {"fontSize": "13px", "opacity": "0.8", "color": "white"}, + {"fontSize": "13px", "opacity": "0.8", "color": "white"}, + {}, + ] + + +def test_form_server_errors( + ui_plugin: UIPlugin, +): + """A field the server finds invalid says so on itself and on its control, shows the messages it forces, and its errors are cleared on a submit and on a reset.""" + component = rx.ui.form.root( + rx.ui.form.field( + rx.ui.form.control(rx.el.input(name="mine", id="code")), + rx.ui.form.message("Taken", match="valid", force_match=FormState.taken), + name="code", + server_invalid=FormState.taken, + ), + on_submit=FormState.submit, + on_clear_server_errors=FormState.clear, + ) + assert component.render() == { + "name": '"form"', + "props": [ + "className:sx_5073704993_c", + "onBlurCapture:((event) => { left(event); })", + "onChangeCapture:((event) => { changed(event); })", + "onInvalid:((event) => { invalid(event); })", + 'onReset:((event) => { cleared(event); (((...args) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_form____form_state.clear", ({ }), ({ })))], args, ({ })))))(event); })', + "onSubmit:handleSubmit_21b393bf90a9dc94271acff60be1dacc", + 'onSubmitCapture:((event) => { (((...args) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_form____form_state.clear", ({ }), ({ })))], args, ({ })))))(event); })', + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_7fb5ccb001_c", + '"data-invalid":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? "" : undefined)', + '"data-rx-form-field":""', + '"data-server-invalid":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? "" : undefined)', + "ref:(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? focusInvalid : undefined)", + ], + "children": [ + { + "name": '"input"', + "props": [ + '"aria-invalid":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ || undefined)', + 'id:"code"', + 'name:"mine"', + "ref:ref_code", + ], + "children": [], + }, + { + "name": '"span"', + "props": [ + "className:sx_71d77c9098_c", + '"data-force":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? "" : undefined)', + '"data-match":"valid"', + '"data-rx-form-message":""', + "hidden:!(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_)", + ], + "children": [{"contents": '"Taken"'}], + }, + ], + } + ], + } + + +def test_form_without_messages( + ui_plugin: UIPlugin, +): + """A form without a message is the form element of Reflex, with no script of its own.""" + component = rx.ui.form( + rx.ui.form.field( + rx.ui.form.label("Notes"), + rx.ui.form.control(rx.ui.text_area(id="notes")), + name="notes", + ), + rx.ui.form.validity_state("x"), + rx.ui.form.submit(rx.ui.button("Send"), as_child=True), + ) + assert component.render() == { + "name": '"form"', + "props": [ + "className:sx_5073704993_c", + "onSubmit:handleSubmit_778c17e137b39fd18ce6e668f384d9a1", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_7fb5ccb001_c", '"data-rx-form-field":""'], + "children": [ + { + "name": '"label"', + "props": ["className:sx_3f1c4be050_c", 'htmlFor:"notes"'], + "children": [{"contents": '"Notes"'}], + }, + { + "name": '"div"', + "props": ["className:sx_246a7bce17_c"], + "children": [ + { + "name": '"textarea"', + "props": [ + "className:sx_8eecb42f44_c", + '"data-rx-text-area-input":""', + 'id:"notes"', + 'name:"notes"', + "ref:ref_notes", + ], + "children": [], + } + ], + }, + ], + }, + {"name": '"span"', "props": [], "children": [{"contents": '"x"'}]}, + { + "name": '"button"', + "props": ["className:sx_6fb0976665_c", 'type:"submit"'], + "children": [{"contents": '"Send"'}], + }, + ], + } + + +def test_form_control_takes_one_child(ui_plugin: UIPlugin): + """A control renders one native form control.""" + with pytest.raises(ValueError) as error: + rx.ui.form.control(rx.el.input(), rx.el.input()) + assert ( + str(error.value) + == "FormControl can only have at most one child, got 2 children" + ) + + +def test_form_control_child_is_a_native_control(ui_plugin: UIPlugin): + """Another kind of child is an error that says what to do with it.""" + with pytest.raises(TypeError) as error: + rx.ui.form.control(rx.ui.checkbox("Agree")) + assert ( + str(error.value) + == "The child of rx.ui.form.control must render a native form control: rx.ui.input, rx.ui.text_area, rx.debounce_input, rx.el.input, rx.el.select or rx.el.textarea, not Text. Give other controls such as rx.ui.checkbox or rx.ui.select a `name` and place them under rx.ui.form.root or rx.ui.form.field instead." + ) + + +def test_form_message_unknown_match(ui_plugin: UIPlugin): + """A condition a message cannot have is an error.""" + with pytest.raises(TypeError) as error: + rx.ui.form.message("x", match="wrong") + assert ( + str(error.value) + == "Invalid var passed for prop FormMessage.match, expected type typing.Literal['badInput', 'patternMismatch', 'rangeOverflow', 'rangeUnderflow', 'stepMismatch', 'tooLong', 'tooShort', 'typeMismatch', 'valid', 'valueMissing'], got value 'wrong' of type ." + ) + + +def test_form_field_gives_its_control_an_id( + ui_plugin: UIPlugin, monkeypatch: pytest.MonkeyPatch +): + """A control without an id is given one for the label of its field.""" + monkeypatch.setattr(form_module, "_ids", itertools.count(4)) + field = rx.ui.form.field( + rx.ui.form.label("Age"), rx.ui.form.control(name="years"), name="age" + ) + assert field.render()["children"] == [ + { + "name": '"label"', + "props": ["className:sx_3f1c4be050_c", 'htmlFor:"rx-form-field-4"'], + "children": [{"contents": '"Age"'}], + }, + { + "name": '"input"', + "props": ['id:"rx-form-field-4"', 'name:"years"'], + "children": [], + }, + ] + + +def test_form_script_is_only_for_messages(ui_plugin: UIPlugin): + """The script of a form reads validity for its messages, and nothing else.""" + script = "$/reflex-ui/behaviors/form-validity.js" + plain = rx.ui.form(rx.ui.form.field(rx.ui.form.control(), name="a")) + assert script not in plain._get_all_imports() + with_message = rx.ui.form(rx.ui.form.message("x", match="valueMissing")) + assert with_message._get_all_imports()[script] == [ + ImportVar(tag="invalid"), + ImportVar(tag="changed"), + ImportVar(tag="left"), + ImportVar(tag="cleared"), + ] + invalid = rx.ui.form.field(rx.ui.form.control(), server_invalid=True) + assert invalid._get_all_imports()[script] == [ImportVar(tag="focusInvalid")] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index b0636a5317b..7fe061176c2 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -128,6 +128,14 @@ def test_every_wave_is_in_the_namespace(): "data_list.value", "divider", "flex", + "form", + "form.control", + "form.field", + "form.label", + "form.message", + "form.root", + "form.submit", + "form.validity_state", "grid", "heading", "hstack", @@ -187,6 +195,7 @@ def test_every_wave_is_in_the_namespace(): "callout", "checkbox", "data_list", + "form", "input", "list", "radio", From 033f4ddc006ee1c8c956de61841bd0b602cc7140 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 02:37:45 +0000 Subject: [PATCH 075/204] Add rx.ui.segmented_control: native radio buttons drawn as one control What marks the chosen item is placed by the control from the position of its checked radio button. A key handler moves the focus with the arrow keys without choosing, as Radix does; without it the browser moves and chooses, as it does for radio buttons. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- packages/reflex-components-ui/js/src/base.css | 16 + .../js/src/behaviors/roving-focus.js | 50 ++ .../js/tests/behaviors/roving-focus.test.js | 113 ++++ .../parity/allowlist.toml | 11 + .../ui_parity/components/segmented_control.py | 346 +++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/segmented_control.py | 283 +++++++++ .../styles/segmented_control.py | 289 +++++++++ .../components/test_segmented_control.py | 550 ++++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 3 + 10 files changed, 1662 insertions(+) create mode 100644 packages/reflex-components-ui/js/src/behaviors/roving-focus.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py create mode 100644 tests/units/reflex_components_ui/components/test_segmented_control.py diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index 147fd1998e1..b7a1cd2f6dd 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -90,6 +90,22 @@ html.dark { flex-shrink: 0; } + /* + * The line before an item of a segmented control is not shown before the + * first item, nor on either side of the chosen one or of the one the + * keyboard is on: the item before another is no state of that other. + */ + [data-rx-segmented-item]:first-child, + [data-rx-segmented-item]:is(:has(> input:checked), :has(> input:focus-visible)), + [data-rx-segmented-item]:is(:has(> input:checked), :has(> input:focus-visible)) + + [data-rx-segmented-item] { + --rx-segmented-separator-opacity: 0; + --rx-segmented-separator-easing: ease-in; + } + [data-rx-segmented-item] svg { + flex-shrink: 0; + } + /* The thumb of the scrollbar of a text area, under the pointer. */ @media (hover: hover) { [data-rx-text-area-input]:not(:disabled)::-webkit-scrollbar-thumb:hover { diff --git a/packages/reflex-components-ui/js/src/behaviors/roving-focus.js b/packages/reflex-components-ui/js/src/behaviors/roving-focus.js new file mode 100644 index 00000000000..9088a9f1dc8 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/roving-focus.js @@ -0,0 +1,50 @@ +// The arrow keys of a group that is one stop for Tab: they move the focus +// between its items, as in Radix, without choosing one. +// +// The items are native controls, which the browser moves between with the +// arrow keys by itself: choosing each one it passes, for radio buttons. +// Without this the group works that way. + +const STEPS = /** @type {Record} */ ({ + ArrowLeft: -1, + ArrowUp: -1, + ArrowRight: 1, + ArrowDown: 1, +}); + +/** + * Move the focus through the items of a group: the `onKeyDown` of the group. + * + * The arrow keys go to the item before and after, around the ends, Home and + * End to the first and the last, and Enter chooses the item the focus is on, + * as Space does by itself. The direction of the text turns left and right. + * + * @param {{ key: string, target: EventTarget | null, currentTarget: Element, preventDefault: () => void, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean, shiftKey?: boolean }} event + * The key going down on an item. + * @returns {void} + */ +export function rovingKeyDown(event) { + const { key, target, currentTarget } = event; + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; + if (!(target instanceof HTMLInputElement) || target.type !== "radio") return; + if (key === "Enter") { + event.preventDefault(); + target.click(); + return; + } + const items = /** @type {HTMLInputElement[]} */ ([ + ...currentTarget.querySelectorAll("input[type=radio]:not(:disabled)"), + ]); + const last = items.length - 1; + let index = items.indexOf(target); + if (key === "Home") index = 0; + else if (key === "End") index = last; + else if (key in STEPS) { + const flipped = + key !== "ArrowUp" && key !== "ArrowDown" && getComputedStyle(currentTarget).direction === "rtl"; + index += flipped ? -STEPS[key] : STEPS[key]; + index = index < 0 ? last : index > last ? 0 : index; + } else return; + event.preventDefault(); + items[index]?.focus(); +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js b/packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js new file mode 100644 index 00000000000..35559451b87 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js @@ -0,0 +1,113 @@ +// The keys of a group that is one stop for Tab: the arrow keys, Home and End +// move the focus between its radio buttons without choosing one, and Enter +// chooses. +import { beforeEach, expect, test } from "vitest"; + +import { rovingKeyDown } from "$/reflex-ui/behaviors/roving-focus.js"; + +/** @type {HTMLElement} */ +let group; + +beforeEach(() => { + document.body.innerHTML = ` +
+ + + + + +
`; + group = /** @type {HTMLElement} */ (document.getElementById("group")); +}); + +/** + * Find a radio button of the group. + * + * @param {string} value Its value. + * @returns {HTMLInputElement} The radio button. + */ +function radio(value) { + return /** @type {HTMLInputElement} */ (group.querySelector(`[value=${value}]`)); +} + +/** + * Press a key on whatever has the focus. + * + * @param {string} key The key. + * @param {Record} [modifiers] The modifiers held with it. + * @returns {boolean} Whether the group kept the key from the browser. + */ +function press(key, modifiers = {}) { + let prevented = false; + rovingKeyDown({ + key, + target: document.activeElement, + currentTarget: group, + preventDefault: () => { + prevented = true; + }, + ...modifiers, + }); + return prevented; +} + +/** + * Read which radio button has the focus. + * + * @returns {string} Its value. + */ +function focused() { + return /** @type {HTMLInputElement} */ (document.activeElement).value; +} + +test("the arrow keys move the focus past a disabled item and around the ends", () => { + radio("a").focus(); + const visited = []; + for (const key of ["ArrowRight", "ArrowDown", "ArrowRight", "ArrowLeft", "ArrowUp"]) { + expect(press(key)).toBe(true); + visited.push(focused()); + } + expect(visited).toEqual(["c", "d", "a", "d", "c"]); + expect(group.querySelectorAll(":checked").length).toBe(0); +}); + +test("Home and End go to the first and the last item", () => { + radio("c").focus(); + expect(press("End")).toBe(true); + expect(focused()).toBe("d"); + expect(press("Home")).toBe(true); + expect(focused()).toBe("a"); +}); + +test("Enter chooses the item the focus is on", () => { + radio("c").focus(); + expect(press("Enter")).toBe(true); + expect(radio("c").checked).toBe(true); + expect(focused()).toBe("c"); +}); + +test("left and right are turned where the text runs from the right", () => { + group.style.direction = "rtl"; + radio("c").focus(); + press("ArrowRight"); + expect(focused()).toBe("a"); + press("ArrowLeft"); + expect(focused()).toBe("c"); + press("ArrowDown"); + expect(focused()).toBe("d"); +}); + +test("other keys, keys with a modifier and other controls are left to the browser", () => { + radio("a").focus(); + expect(press("a")).toBe(false); + expect(press(" ")).toBe(false); + expect(press("Tab")).toBe(false); + for (const modifier of ["altKey", "ctrlKey", "metaKey", "shiftKey"]) { + expect(press("ArrowRight", { [modifier]: true })).toBe(false); + } + expect(focused()).toBe("a"); + /** @type {HTMLElement} */ (document.getElementById("text")).focus(); + expect(press("ArrowRight")).toBe(false); + expect(press("Enter")).toBe(false); + expect(document.activeElement?.id).toBe("text"); +}); diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index f440cd962ad..b8e99a2624e 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -195,3 +195,14 @@ reason = "rx.checkbox_cards takes one Tab stop for the whole group. In rx.ui.che component = "checkbox_cards" step = "hands over the checked values in the order they were checked in" reason = "`on_value_change` of rx.ui.checkbox_cards hands over the values of the checked cards in the order of the cards, whatever the order they were checked in: the group keeps no state of its own and reads its checkboxes. rx.checkbox_cards appends each value as it is checked." + +[[look]] +component = "segmented_control" +check = "a11y" +reason = "An item of rx.ui.segmented_control is a label around a native radio button: what the item holds names the radio button, as in rx.segmented_control, and is also text of the page, as the text of any label is. An item of rx.segmented_control is one button that holds its text." + +[[contract]] +component = "segmented_control" +step = "chooses an item with JavaScript disabled" +system = "rx" +reason = "The items of rx.segmented_control are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. An item of rx.ui.segmented_control is a label around a native radio button, which the browser checks with or without JavaScript." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py new file mode 100644 index 00000000000..d48b9c0e004 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py @@ -0,0 +1,346 @@ +"""The segmented control: every variant, size and state, and how its items are chosen.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import FOCUS_WITHIN +from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import focused, wait_for_text + +VARIANTS = ["surface", "classic"] +SIZES = ["1", "2", "3"] +RADII = ["none", "small", "medium", "large", "full"] +STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] +# The second item: a button of Radix, a label around a radio button here. +TARGET = ("button:nth-child(2)", "label:nth-child(2)") +MANY = [str(number) for number in range(1, 13)] + + +def _control(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a segmented control. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the root. ``holds`` says what the items are when + they are not three words. + + Returns: + The control. + """ + props = dict(props) + holds = props.pop("holds", None) + item = namespace.segmented_control.item + if holds == "many": + items = [item(number, value=number) for number in MANY] + elif holds == "icons": + items = [ + item(rx.icon("sun", size=14), "Light", value="1"), + item(rx.icon("moon", size=14), "Dark", value="2"), + ] + else: + items = [ + item("One", value="1"), + item("Two", value="2"), + item("Three", value="3"), + ] + return namespace.segmented_control.root(*items, **props) + + +MATRIX = Matrix( + component="segmented_control", + render=_control, + base={"default_value": "1"}, + cross={"variant": VARIANTS, "size": SIZES, "default_value": ["1", "2", "3"]}, + sweep={ + "radius": RADII, + "color_scheme": ["ruby", "gray"], + "holds": ["many", "icons"], + "default_value": {"none": None}, + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "state": STATES, + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "default_value": ["1", "2"], + "state": STATES, + "appearance": [LIGHT, DARK], + }, + {"radius": RADII, "size": SIZES, "variant": VARIANTS}, + {"holds": ["many"], "default_value": ["1", "11", "12"], "size": ["1"]}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(420, 80), + crop="stage", + target=TARGET, + parts={ + "root": "[role=radiogroup]", + "indicator": "[role=radiogroup] > div", + }, + # The focus is on the item of Radix and on the radio button in the item + # here. + states={FOCUS_VISIBLE: FOCUS_WITHIN}, + # Not held to zero. At a threshold of zero 87 of the 103 cells are equal + # pixel for pixel, and the others differ by where they are on the page: + # the translucent fills of the control and of what marks the chosen item + # are dithered by a step of a channel. At the default threshold 3 cells + # differ, by at most 3 pixels of 33600 on a rounded corner. + tolerance=0.0001, +) + + +class SegmentedControlState(rx.State): + """What the segmented controls of the contract are bound to.""" + + bound: str = "a" + seen: list[str] = [] + submitted: dict[str, Any] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, value: str | list[str]): + """Follow the bound control. + + Args: + value: The value of its chosen item. + """ + self.bound = str(value) + + @rx.event + def see(self, value: str | list[str]): + """Keep what a change handed over. + + Args: + value: The value of the chosen item. + """ + self.seen.append(str(value)) + + @rx.event + def pick_last(self): + """Change the bound value from outside the control.""" + self.bound = "c" + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +def _items(namespace: Any, *values: str) -> list[Any]: + """Create the items of a control, each with its value as its text. + + Args: + namespace: ``rx`` or ``rx.ui``. + *values: The value of each item. + + Returns: + The items. + """ + return [namespace.segmented_control.item(value, value=value) for value in values] + + +CONTRACT = Contract( + component="segmented_control", + render=lambda namespace: namespace.box( + rx.el.div( + namespace.segmented_control.root( + *_items(namespace, "One", "Two", "Three"), + on_change=SegmentedControlState.see, + ), + id="pick", + ), + rx.el.div( + namespace.segmented_control.root( + *_items(namespace, "s", "m", "l"), default_value="m" + ), + id="sized", + ), + rx.el.div( + namespace.segmented_control.root( + rx.foreach( + ["a", "b", "c"], + lambda value: namespace.segmented_control.item(value, value=value), + ), + value=SegmentedControlState.bound, + on_change=SegmentedControlState.set_bound, + ), + id="bound", + ), + rx.el.button("Last", id="last", on_click=SegmentedControlState.pick_last), + rx.el.form( + namespace.segmented_control.root( + *_items(namespace, "x", "y"), default_value="x" + ), + rx.el.input(name="note", default_value="hi", id="note"), + rx.el.button("Send", id="send", type="submit"), + on_submit=SegmentedControlState.submit, + id="form", + ), + rx.el.span(SegmentedControlState.seen.to_string(), id="seen"), + rx.el.span(SegmentedControlState.bound, id="bound-value"), + rx.el.span(SegmentedControlState.submitted.to_string(), id="submitted"), + rx.el.span(SegmentedControlState.submissions.to_string(), id="submissions"), + ), +) + +# An item is a button of Radix and a label around a radio button here. +ITEMS = "button[role=radio], label" +# The text of the chosen items of a control, by the id of its frame. +CHOSEN = ( + f"id => [...document.getElementById(id).querySelectorAll('{ITEMS}')]" + ".filter(item => item.matches('[aria-checked=true], :has(:checked)'))" + ".map(item => item.querySelector('span > span').textContent)" +) +# The text of the item that has the focus. +FOCUSED_ITEM = f"document.activeElement.closest('{ITEMS}')?.querySelector('span > span').textContent" +# A click on the text of an item is forced: Playwright looks for the element +# under the pointer, which is the other one of the two texts of the item. +# How long a key is held, in milliseconds. +HELD = 60 + + +def _wait_for_chosen(run: Run, control: str, items: list[str]) -> None: + """Wait until the chosen items of a control are the ones expected. + + Args: + run: The run, on a page. + control: The id of the frame of the control. + items: The text of each item that is to be chosen. + """ + run.page.wait_for_function( + f"([id, items]) => JSON.stringify(({CHOSEN})(id)) === items", + arg=[control, json.dumps(items)], + ) + + +def _wait_for_focus(run: Run, item: str) -> None: + """Wait until an item has the focus. + + Args: + run: The run, on a page. + item: The text of the item. + """ + run.page.wait_for_function(f"item => {FOCUSED_ITEM} === item", arg=item) + + +@CONTRACT.step("its items are in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("pick").text == "OneOneTwoTwoThreeThree" + + +@CONTRACT.step("chooses an item with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + _wait_for_chosen(run, "sized", ["m"]) + page.locator("#pick").get_by_text("Two").first.click(force=True) + _wait_for_chosen(run, "pick", ["Two"]) + page.locator("#pick").get_by_text("Three").first.click(force=True) + _wait_for_chosen(run, "pick", ["Three"]) + + +@CONTRACT.step("is a group of radio buttons with their names and states") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("radiogroup").count() == 4 + pick = page.locator("#pick") + assert pick.get_by_role("radio").count() == 3 + assert not pick.get_by_role("radio", name="One", exact=True).is_checked() + sized = page.locator("#sized") + assert sized.get_by_role("radio", name="m", exact=True, checked=True).count() == 1 + assert sized.get_by_role("radio", checked=True).count() == 1 + + +@CONTRACT.step("Tab stops once in each control, on its chosen item") +def _tab(run: Run) -> None: + page = run.page + stops = [] + for _ in range(4): + page.keyboard.press("Tab") + stops.append(page.evaluate(FOCUSED_ITEM) or focused(page)) + assert stops == ["One", "m", "a", "last"] + _wait_for_chosen(run, "pick", []) + + +@CONTRACT.step("the arrow keys, Home and End move the focus without choosing") +def _arrows(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + for key, item in ( + ("ArrowRight", "Two"), + ("ArrowDown", "Three"), + ("ArrowRight", "One"), + ("ArrowLeft", "Three"), + ("ArrowUp", "Two"), + ("Home", "One"), + ("End", "Three"), + ): + page.keyboard.press(key, delay=HELD) + _wait_for_focus(run, item) + _wait_for_chosen(run, "pick", []) + assert page.locator("#seen").text_content() == "[]" + + +@CONTRACT.step("Space, Enter and a click choose an item, and say so") +def _choose(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + page.keyboard.press("Space") + _wait_for_chosen(run, "pick", ["One"]) + page.keyboard.press("ArrowRight", delay=HELD) + _wait_for_focus(run, "Two") + page.keyboard.press("Enter") + _wait_for_chosen(run, "pick", ["Two"]) + page.locator("#pick").get_by_text("Three").first.click(force=True) + _wait_for_chosen(run, "pick", ["Three"]) + wait_for_text(page, "seen", '["One","Two","Three"]') + + +@CONTRACT.step("the chosen item stays chosen when it is chosen again") +def _again(run: Run) -> None: + page = run.page + page.locator("#sized").get_by_text("m").first.click(force=True) + page.keyboard.press("Space") + page.keyboard.press("Enter") + _wait_for_chosen(run, "sized", ["m"]) + page.locator("#pick").get_by_text("One").first.click(force=True) + wait_for_text(page, "seen", '["One"]') + page.locator("#pick").get_by_text("One").first.click(force=True) + page.locator("#pick").get_by_text("Two").first.click(force=True) + wait_for_text(page, "seen", '["One","Two"]') + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + _wait_for_chosen(run, "bound", ["a"]) + page.locator("#bound").get_by_text("b").first.click(force=True) + wait_for_text(page, "bound-value", "b") + _wait_for_chosen(run, "bound", ["b"]) + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + _wait_for_chosen(run, "bound", ["c"]) + + +@CONTRACT.step("is no value of the form it is in") +def _submit(run: Run) -> None: + page = run.page + page.locator("#form").get_by_text("y").first.click(force=True) + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == '{"note":"hi"}' 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 b821cf9286c..808e42de497 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -24,6 +24,7 @@ "components.radio_cards": ["radio_cards"], "components.radio_group": ["radio", "radio_group"], "components.scroll_area": ["scroll_area"], + "components.segmented_control": ["segmented_control"], "components.separator": ["divider", "separator"], "components.skeleton": ["skeleton"], "components.spinner": ["spinner"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py b/packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py new file mode 100644 index 00000000000..30968165b43 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py @@ -0,0 +1,283 @@ +"""A segmented control: a row of native radio buttons, drawn as one control.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, ClassVar, Literal, cast + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, input_event +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import Var, VarData +from reflex_base.vars.sequence import ArrayVar +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.foreach import Foreach + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.components._group import ( + GroupInput, + GroupRoot, + group_name, + is_value, +) +from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.segmented_control import ( + COUNT, + INDEX, + INDEX_OF_VALUE, + PLACED, + SEGMENTED_CONTROL, + SEGMENTED_CONTROL_ITEM, + chosen, +) +from reflex_components_ui.themes import LiteralAccentColor + +# The `onKeyDown` of the control: the arrow keys move the focus between the +# items without choosing one, as in Radix, which is all its JavaScript. +_ROVING_KEY_DOWN = Var( + "rovingKeyDown", + _var_data=VarData( + imports={ + f"$/{WEB_DIR}/behaviors/roving-focus.js": [ImportVar(tag="rovingKeyDown")] + } + ), +) + + +class SegmentedControlInput(GroupInput, Part): + """The radio button of an item, which is not seen.""" + + _type: ClassVar[str] = "radio" + + value: Var[str] = field(doc="The value of the item.") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the radio button. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, of no form: a segmented control has no name, and the + name that groups its radio buttons is not for a form to submit. + """ + return super()._render(props).add_props(form="") + + +class SegmentedControlRoot(GroupRoot): + """Root element for a SegmentedControl component.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = SEGMENTED_CONTROL + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc='The size of the segmented control: "1" | "2" | "3"' + ) + + variant: Var[Literal["classic", "surface"]] = field( + doc='Variant of button: "classic" | "surface"' + ) + + type: Var[Literal["single", "multiple"]] = field( + doc='The type of the segmented control, either "single" for selecting one option or "multiple" for selecting multiple options.' + ) + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + radius: Var[Literal["none", "small", "medium", "large", "full"]] = field( + doc='The radius of the segmented control: "none" | "small" | "medium" | "large" | "full"' + ) + + default_value: Var[str | Sequence[str]] = field( + doc="The default value of the segmented control." + ) + + value: Var[str | Sequence[str]] = field( + doc="The current value of the segmented control." + ) + + on_change: EventHandler[input_event] = field( + doc="Handles the `onChange` event for the SegmentedControl component." + ) + + # What a group hands its items, and a segmented control does not have. + high_contrast: ClassVar[None] = None + disabled: ClassVar[None] = None + required: ClassVar[None] = None + + _holds = staticmethod(is_value) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a SegmentedControlRoot. + + What marks the chosen item is as wide as one item and moved to it, + so the control counts its items: while compiling when they are its + children, and in the browser when a ``foreach`` renders them. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The SegmentedControlRoot component. + """ + placement: dict[str, Any] = {COUNT: len(children)} + if len(children) == 1 and isinstance(children[0], Foreach): + foreach = children[0] + values = cast("ArrayVar", foreach.iterable) + placement[COUNT] = values.length() + selected = props.get("value", props.get("default_value")) + item = foreach.render_fn(foreach.iterable[0]) # pyright: ignore[reportIndexIssue] + if selected is not None and isinstance(item, SegmentedControlItem): + # For the items after the ones the style table places. + index = Var( + f"({values.map(lambda element: _value_of(foreach, element))!s}" + f".indexOf({Var.create(selected)!s}))", + _var_type=int, + _var_data=VarData.merge( + values._get_all_var_data(), + Var.create(selected)._get_all_var_data(), + ), + ) + placement[INDEX_OF_VALUE] = index + elif len(children) > PLACED: + placement[INDEX] = { + chosen(position): position - 1 + for position in range(PLACED + 1, len(children) + 1) + } + props.setdefault("custom_attrs", {}).setdefault("onKeyDown", _ROVING_KEY_DOWN) + style = props.get("style") + if style is None: + props["style"] = placement + elif isinstance(style, (list, tuple)): + props["style"] = [placement, *style] + else: + props["style"] = [placement, style] + return super().create( + *children, Part.create(part="indicator", tag="div"), **props + ) + + def _bind(self) -> None: + """Name the items: the browser takes radio buttons for a group by it.""" + self._name = group_name(None, "segmented") + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the items off the element. + + Returns: + The props read as styles, and what the control hands its items. + The type is one of them: as in Radix Themes, one item is chosen + whatever it says. + """ + return [ + *super()._exclude_props(), + "size", + "variant", + "type", + "value", + "default_value", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the control. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role of a group of radio buttons. + """ + return super()._render(props).add_props(role="radiogroup") + + +def _value_of(foreach: Foreach, element: Var) -> Var: + """Get the value of the item a ``foreach`` renders for an element. + + Args: + foreach: The ``foreach`` that renders the items of a control. + element: One of the elements it iterates over. + + Returns: + The value of the item. + """ + return cast("SegmentedControlItem", foreach.render_fn(element)).children[0].value # pyright: ignore[reportAttributeAccessIssue] + + +class SegmentedControlItem(UIComponent): + """An item in the SegmentedControl component.""" + + tag = "label" + + styles: ClassVar[ComponentStyles] = SEGMENTED_CONTROL_ITEM + + value: Var[str] = field(doc="The value of the item.") + + _valid_parents: ClassVar[list[str]] = ["SegmentedControlRoot"] + + @classmethod + def create(cls, *children, **props) -> Component: + """Create an item: a label around its radio button and its text. + + Args: + *children: What the item shows. + **props: The props of the item. Its styles are those of the + label, and everything else is given to the radio button. + + Returns: + The label. + """ + own = { + key: props.pop(key) + for key in list(props) + if key in ("value", "id") or key.startswith(("on_", "aria_", "data_")) + } + return super().create( + SegmentedControlInput.create(part="input", **own), + Part.create(part="separator", tag="span"), + Part.create( + Part.create(*children, part="active", tag="span"), + Part.create( + *children, + part="inactive", + tag="span", + custom_attrs={"aria-hidden": True}, + ), + part="label", + tag="span", + ), + **props, + ) + + def _exclude_props(self) -> list[str]: + """Keep the value off the label: it is the one of the radio button. + + Returns: + The props read as styles, and the value. + """ + return [*super()._exclude_props(), "value"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the item. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, marked for the rule that hides the line beside the + chosen item. + """ + return super()._render(props).add_props(**{"data-rx-segmented-item": ""}) + + +class SegmentedControl(ComponentNamespace): + """SegmentedControl components namespace.""" + + root = staticmethod(SegmentedControlRoot.create) + item = staticmethod(SegmentedControlItem.create) + + +segmented_control = SegmentedControl() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py new file mode 100644 index 00000000000..600f972aad9 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py @@ -0,0 +1,289 @@ +"""The look of a segmented control: a row of items and what marks the chosen one.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked + +gray, focus = tokens.gray, tokens.focus + +_RADIUS = "--segmented-control-border-radius" +_DURATION = "100ms" +_FADE = "80ms" + +# What the control hands its items and its indicator, which a class on +# either cannot ask of the other: how many items there are and which one is +# chosen, and the size of the labels. +COUNT = "--rx-segmented-count" +INDEX = "--rx-segmented-index" +# The index of the chosen item of a control whose items are not counted +# while compiling, from its value. +INDEX_OF_VALUE = "--rx-segmented-index-of-value" +_SHOWN = "--rx-segmented-indicator" +_FONT_SIZE = "--rx-segmented-font-size" +_LETTER_SPACING = "--rx-segmented-letter-spacing" +_PADDING = "--rx-segmented-padding" +_GAP = "--rx-segmented-gap" +_SEPARATOR_DURATION = "--rx-segmented-separator-duration" +# What an item hands the elements inside it: whether it is chosen. +_ACTIVE = "--rx-segmented-active-opacity" +_INACTIVE = "--rx-segmented-inactive-opacity" +_ACTIVE_EASING = "--rx-segmented-active-easing" +_INACTIVE_EASING = "--rx-segmented-inactive-easing" +_HOVER = "--rx-segmented-hover" + +# The state of an item is the one of the radio button inside it. +_ON = ":has(> input:checked)" +_FOCUSED = ":has(> input:focus-visible)" + +# How many items the table places the indicator for. A control with more +# literal items is given the further conditions as its own style. +PLACED = 10 + + +def chosen(position: int) -> str: + """Make the condition of a control whose chosen item is at a position. + + Args: + position: The position of the item among the children, from 1. + + Returns: + The condition. + """ + return f":has(> :nth-child({position}) > input:checked)" + + +def _size( + radius: str, height: str, step: int, padding: str, gap: str +) -> dict[str, Any]: + """Make the styles of one size. + + Args: + radius: The radius of the corners. + height: The height of the control. + step: The step of the type scale. + padding: The room beside the text of an item. + gap: The gap between what an item holds. + + Returns: + The styles. + """ + return { + _RADIUS: f"max({radius}, {tokens.radius.full})", + "height": height, + _FONT_SIZE: tokens.font_size[step], + _LETTER_SPACING: tokens.letter_spacing[step], + _PADDING: padding, + _GAP: gap, + } + + +SEGMENTED_CONTROL: ComponentStyles = { + "base": unchecked({ + "box_sizing": "border-box", + "display": "inline-grid", + "vertical_align": "top", + "grid_auto_flow": "column", + "grid_auto_columns": "1fr", + "align_items": "stretch", + "color": gray[12], + "background_color": tokens.color.surface, + "background_image": f"linear-gradient({gray.a[3]}, {gray.a[3]})", + "position": "relative", + "min_width": "max-content", + "font_family": tokens.default.font_family, + "font_style": "normal", + "text_align": "center", + # A stacking context: the indicator is behind the items, inside it. + "isolation": "isolate", + "border_radius": f"var({_RADIUS})", + _SHOWN: {"default": "none", ":has(> label > input:checked)": "block"}, + INDEX: { + "default": f"var({INDEX_OF_VALUE}, 0)", + **{chosen(position): position - 1 for position in range(1, PLACED + 1)}, + }, + # A separator hidden by the ring of the focus does not fade. + _SEPARATOR_DURATION: {"default": _FADE, ":has(:focus-visible)": "0ms"}, + }), + "variants": { + "size": { + "1": unchecked( + _size( + tokens.radius[2], + tokens.space[5], + 1, + tokens.space[3], + tokens.space[1], + ) + ), + "2": unchecked( + _size( + tokens.radius[2], + tokens.space[6], + 2, + tokens.space[4], + tokens.space[2], + ) + ), + "3": unchecked( + _size( + tokens.radius[3], + tokens.space[7], + 3, + tokens.space[4], + tokens.space[3], + ) + ), + }, + }, + "defaults": {"size": "2", "variant": "surface"}, + "parts": { + # What marks the chosen item: as wide as one, and moved to it. + "indicator": { + "base": unchecked({ + "display": f"var({_SHOWN})", + "position": "absolute", + "z_index": -1, + "top": "0", + "left": "0", + "height": "100%", + "width": f"calc(100% / var({COUNT}))", + "transform": f"translateX(calc(var({INDEX}) * 100%))", + "pointer_events": "none", + "transition_property": "transform", + "transition_timing_function": "cubic-bezier(0.445, 0.05, 0.55, 0.95)", + "transition_duration": _DURATION, + "_before": { + "inset": "1px", + "position": "absolute", + "border_radius": f"max(0.5px, calc(var({_RADIUS}) - 1px))", + "background_color": ( + f"light-dark({tokens.color.background}, {gray.a[3]})" + ), + "content": "''", + }, + }), + "variants": { + "variant": { + "surface": {"_before": {"box_shadow": f"0 0 0 1px {gray.a[4]}"}}, + "classic": {"_before": {"box_shadow": tokens.shadow[2]}}, + }, + }, + "defaults": {"variant": "surface"}, + }, + }, +} + +# An item: a label around its radio button, which is not seen. +SEGMENTED_CONTROL_ITEM: ComponentStyles = { + "base": unchecked({ + "display": "flex", + "align_items": "stretch", + "user_select": "none", + "margin": "0", + "padding": "0", + # As the button an item of Radix Themes is has none. + "border_width": "0", + "border_style": "none", + "cursor": tokens.cursor.button, + "WebkitTapHighlightColor": "transparent", + "border_top_left_radius": {":first-child": "inherit", _FOCUSED: "inherit"}, + "border_bottom_left_radius": {":first-child": "inherit", _FOCUSED: "inherit"}, + # The last item, before the indicator. + "border_top_right_radius": { + ":nth-last-child(2)": "inherit", + _FOCUSED: "inherit", + }, + "border_bottom_right_radius": { + ":nth-last-child(2)": "inherit", + _FOCUSED: "inherit", + }, + _FOCUSED: { + "outline_width": "2px", + "outline_style": "solid", + "outline_color": focus[8], + "outline_offset": "-1px", + }, + _ACTIVE: {"default": 0, _ON: 1}, + _INACTIVE: {"default": 1, _ON: 0}, + _ACTIVE_EASING: {"default": "ease-in", _ON: "ease-out"}, + _INACTIVE_EASING: {"default": "ease-out", _ON: "ease-in"}, + _HOVER: { + "@media (hover: hover)": {f":hover:not({_ON})": gray.a[2]}, + }, + }), + "parts": { + "input": { + "base": { + "appearance": "none", + "position": "absolute", + "inset": "0", + "margin": "0", + "opacity": 0, + "pointer_events": "none", + }, + }, + # The line between two items, behind the indicator. A rule of + # base.css hides it beside the chosen item. + "separator": { + "base": unchecked({ + "z_index": -1, + "margin_top": "3px", + "margin_bottom": "3px", + "margin_left": "-0.5px", + "margin_right": "-0.5px", + "width": "1px", + "background_color": gray.a[4], + "opacity": "var(--rx-segmented-separator-opacity, 1)", + "transition_property": "opacity", + "transition_duration": f"var({_SEPARATOR_DURATION})", + "transition_timing_function": ( + "var(--rx-segmented-separator-easing, ease-out)" + ), + }), + }, + "label": { + "base": unchecked({ + "box_sizing": "border-box", + "display": "flex", + "flex_grow": 1, + "align_items": "center", + "justify_content": "center", + "border_radius": "inherit", + "font_size": f"var({_FONT_SIZE})", + "letter_spacing": f"var({_LETTER_SPACING})", + "padding_left": f"var({_PADDING})", + "padding_right": f"var({_PADDING})", + "gap": f"var({_GAP})", + "background_color": f"var({_HOVER}, transparent)", + }), + }, + # The text of an item twice, medium and regular: the chosen item + # shows the first, and both take the room of the wider. + "active": { + "base": unchecked({ + "transition_property": "opacity", + "transition_duration": _FADE, + "transition_timing_function": f"var({_ACTIVE_EASING})", + "font_weight": tokens.font_weight.medium, + "letter_spacing": tokens.tab.active_letter_spacing, + "word_spacing": tokens.tab.active_word_spacing, + "opacity": f"var({_ACTIVE})", + }), + }, + "inactive": { + "base": unchecked({ + "position": "absolute", + "transition_property": "opacity", + "transition_duration": _FADE, + "transition_timing_function": f"var({_INACTIVE_EASING})", + "font_weight": tokens.font_weight.regular, + "letter_spacing": tokens.tab.inactive_letter_spacing, + "word_spacing": tokens.tab.inactive_word_spacing, + "opacity": f"var({_INACTIVE})", + }), + }, + }, +} diff --git a/tests/units/reflex_components_ui/components/test_segmented_control.py b/tests/units/reflex_components_ui/components/test_segmented_control.py new file mode 100644 index 00000000000..f37b87eeb45 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_segmented_control.py @@ -0,0 +1,550 @@ +"""Tests for reflex_components_ui.components.segmented_control.""" + +import itertools +import re +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import _group +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def names(monkeypatch: pytest.MonkeyPatch): + """Number the controls of each test from one: the name groups their items.""" + monkeypatch.setattr(_group, "_names", itertools.count(1)) + + +class SegmentedState(rx.State): + """What a segmented control is bound to.""" + + view: str = "b" + views: list[str] = ["a", "b"] + + @rx.event + def set_view(self, view: str): + """Follow the control. + + Args: + view: The value of the chosen item. + """ + self.view = view + + +def test_segmented_control( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """An item is a label around a native radio button and its text, twice; the control counts its items for what marks the chosen one.""" + component = rx.ui.segmented_control.root( + rx.ui.segmented_control.item("One", value="1", id="one"), + rx.ui.segmented_control.item("Two", value="2", margin="1px"), + default_value="2", + size="3", + variant="classic", + radius="full", + color_scheme="ruby", + type="multiple", + id="views", + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_66f6ec5e0a_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', + 'id:"views"', + "onKeyDown:rovingKeyDown", + "ref:ref_views", + 'role:"radiogroup"', + ], + "children": [ + { + "name": '"label"', + "props": ["className:sx_7f4c9c997f_c", '"data-rx-segmented-item":""'], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8e51139181_c", + 'form:""', + 'id:"one"', + 'name:"rx-segmented-1"', + "ref:ref_one", + 'type:"radio"', + 'value:"1"', + ], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_f0662e97c2_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_f91740a5b0_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_48fb0dc076_c"], + "children": [{"contents": '"One"'}], + }, + { + "name": '"span"', + "props": [ + '"aria-hidden":true', + "className:sx_d60de3577e_c", + ], + "children": [{"contents": '"One"'}], + }, + ], + }, + ], + }, + { + "name": '"label"', + "props": ["className:sx_c43e9e9803_c", '"data-rx-segmented-item":""'], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8e51139181_c", + "defaultChecked:true", + 'form:""', + 'name:"rx-segmented-1"', + 'type:"radio"', + 'value:"2"', + ], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_f0662e97c2_c"], + "children": [], + }, + { + "name": '"span"', + "props": ["className:sx_f91740a5b0_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_48fb0dc076_c"], + "children": [{"contents": '"Two"'}], + }, + { + "name": '"span"', + "props": [ + '"aria-hidden":true', + "className:sx_d60de3577e_c", + ], + "children": [{"contents": '"Two"'}], + }, + ], + }, + ], + }, + {"name": '"div"', "props": ["className:sx_3a340e571a_c"], "children": []}, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "display": "inline-grid", + "verticalAlign": "top", + "gridAutoFlow": "column", + "gridAutoColumns": "1fr", + "alignItems": "stretch", + "color": "var(--gray-12)", + "backgroundColor": "var(--color-surface)", + "backgroundImage": "linear-gradient(var(--gray-a3), var(--gray-a3))", + "position": "relative", + "minWidth": "max-content", + "fontFamily": "var(--default-font-family)", + "fontStyle": "normal", + "textAlign": "center", + "isolation": "isolate", + "borderRadius": "var(--segmented-control-border-radius)", + "--rx-segmented-indicator": { + "default": "none", + ":has(> label > input:checked)": "block", + }, + "--rx-segmented-index": { + "default": "var(--rx-segmented-index-of-value, 0)", + ":has(> :nth-child(1) > input:checked)": 0, + ":has(> :nth-child(2) > input:checked)": 1, + ":has(> :nth-child(3) > input:checked)": 2, + ":has(> :nth-child(4) > input:checked)": 3, + ":has(> :nth-child(5) > input:checked)": 4, + ":has(> :nth-child(6) > input:checked)": 5, + ":has(> :nth-child(7) > input:checked)": 6, + ":has(> :nth-child(8) > input:checked)": 7, + ":has(> :nth-child(9) > input:checked)": 8, + ":has(> :nth-child(10) > input:checked)": 9, + }, + "--rx-segmented-separator-duration": { + "default": "80ms", + ":has(:focus-visible)": "0ms", + }, + "--segmented-control-border-radius": "max(var(--radius-3), var(--radius-full))", + "height": "var(--space-7)", + "--rx-segmented-font-size": "var(--font-size-3)", + "--rx-segmented-letter-spacing": "var(--letter-spacing-3)", + "--rx-segmented-padding": "var(--space-4)", + "--rx-segmented-gap": "var(--space-3)", + "--rx-segmented-count": 2, + }, + { + "display": "flex", + "alignItems": "stretch", + "userSelect": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": "var(--cursor-button)", + "WebkitTapHighlightColor": "transparent", + "borderTopLeftRadius": { + ":first-child": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "borderBottomLeftRadius": { + ":first-child": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "borderTopRightRadius": { + ":nth-last-child(2)": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "borderBottomRightRadius": { + ":nth-last-child(2)": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "outlineWidth": {":has(> input:focus-visible)": "2px"}, + "outlineStyle": {":has(> input:focus-visible)": "solid"}, + "outlineColor": {":has(> input:focus-visible)": "var(--focus-8)"}, + "outlineOffset": {":has(> input:focus-visible)": "-1px"}, + "--rx-segmented-active-opacity": {"default": 0, ":has(> input:checked)": 1}, + "--rx-segmented-inactive-opacity": { + "default": 1, + ":has(> input:checked)": 0, + }, + "--rx-segmented-active-easing": { + "default": "ease-in", + ":has(> input:checked)": "ease-out", + }, + "--rx-segmented-inactive-easing": { + "default": "ease-out", + ":has(> input:checked)": "ease-in", + }, + "--rx-segmented-hover": { + "@media (hover: hover)": { + ":hover:not(:has(> input:checked))": "var(--gray-a2)" + } + }, + }, + { + "appearance": "none", + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "opacity": 0, + "pointerEvents": "none", + }, + { + "zIndex": -1, + "marginTop": "3px", + "marginBottom": "3px", + "marginLeft": "-0.5px", + "marginRight": "-0.5px", + "width": "1px", + "backgroundColor": "var(--gray-a4)", + "opacity": "var(--rx-segmented-separator-opacity, 1)", + "transitionProperty": "opacity", + "transitionDuration": "var(--rx-segmented-separator-duration)", + "transitionTimingFunction": "var(--rx-segmented-separator-easing, ease-out)", + }, + { + "boxSizing": "border-box", + "display": "flex", + "flexGrow": 1, + "alignItems": "center", + "justifyContent": "center", + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "fontSize": "var(--rx-segmented-font-size)", + "letterSpacing": "var(--rx-segmented-letter-spacing)", + "paddingLeft": "var(--rx-segmented-padding)", + "paddingRight": "var(--rx-segmented-padding)", + "gap": "var(--rx-segmented-gap)", + "backgroundColor": "var(--rx-segmented-hover, transparent)", + }, + { + "transitionProperty": "opacity", + "transitionDuration": "80ms", + "transitionTimingFunction": "var(--rx-segmented-active-easing)", + "fontWeight": "var(--font-weight-medium)", + "letterSpacing": "var(--tab-active-letter-spacing)", + "wordSpacing": "var(--tab-active-word-spacing)", + "opacity": "var(--rx-segmented-active-opacity)", + }, + { + "position": "absolute", + "transitionProperty": "opacity", + "transitionDuration": "80ms", + "transitionTimingFunction": "var(--rx-segmented-inactive-easing)", + "fontWeight": "var(--font-weight-regular)", + "letterSpacing": "var(--tab-inactive-letter-spacing)", + "wordSpacing": "var(--tab-inactive-word-spacing)", + "opacity": "var(--rx-segmented-inactive-opacity)", + }, + { + "display": "flex", + "alignItems": "stretch", + "userSelect": "none", + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": "var(--cursor-button)", + "WebkitTapHighlightColor": "transparent", + "borderTopLeftRadius": { + ":first-child": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "borderBottomLeftRadius": { + ":first-child": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "borderTopRightRadius": { + ":nth-last-child(2)": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "borderBottomRightRadius": { + ":nth-last-child(2)": "inherit", + ":has(> input:focus-visible)": "inherit", + }, + "outlineWidth": {":has(> input:focus-visible)": "2px"}, + "outlineStyle": {":has(> input:focus-visible)": "solid"}, + "outlineColor": {":has(> input:focus-visible)": "var(--focus-8)"}, + "outlineOffset": {":has(> input:focus-visible)": "-1px"}, + "--rx-segmented-active-opacity": {"default": 0, ":has(> input:checked)": 1}, + "--rx-segmented-inactive-opacity": { + "default": 1, + ":has(> input:checked)": 0, + }, + "--rx-segmented-active-easing": { + "default": "ease-in", + ":has(> input:checked)": "ease-out", + }, + "--rx-segmented-inactive-easing": { + "default": "ease-out", + ":has(> input:checked)": "ease-in", + }, + "--rx-segmented-hover": { + "@media (hover: hover)": { + ":hover:not(:has(> input:checked))": "var(--gray-a2)" + } + }, + }, + { + "appearance": "none", + "position": "absolute", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "opacity": 0, + "pointerEvents": "none", + }, + { + "zIndex": -1, + "marginTop": "3px", + "marginBottom": "3px", + "marginLeft": "-0.5px", + "marginRight": "-0.5px", + "width": "1px", + "backgroundColor": "var(--gray-a4)", + "opacity": "var(--rx-segmented-separator-opacity, 1)", + "transitionProperty": "opacity", + "transitionDuration": "var(--rx-segmented-separator-duration)", + "transitionTimingFunction": "var(--rx-segmented-separator-easing, ease-out)", + }, + { + "boxSizing": "border-box", + "display": "flex", + "flexGrow": 1, + "alignItems": "center", + "justifyContent": "center", + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "fontSize": "var(--rx-segmented-font-size)", + "letterSpacing": "var(--rx-segmented-letter-spacing)", + "paddingLeft": "var(--rx-segmented-padding)", + "paddingRight": "var(--rx-segmented-padding)", + "gap": "var(--rx-segmented-gap)", + "backgroundColor": "var(--rx-segmented-hover, transparent)", + }, + { + "transitionProperty": "opacity", + "transitionDuration": "80ms", + "transitionTimingFunction": "var(--rx-segmented-active-easing)", + "fontWeight": "var(--font-weight-medium)", + "letterSpacing": "var(--tab-active-letter-spacing)", + "wordSpacing": "var(--tab-active-word-spacing)", + "opacity": "var(--rx-segmented-active-opacity)", + }, + { + "position": "absolute", + "transitionProperty": "opacity", + "transitionDuration": "80ms", + "transitionTimingFunction": "var(--rx-segmented-inactive-easing)", + "fontWeight": "var(--font-weight-regular)", + "letterSpacing": "var(--tab-inactive-letter-spacing)", + "wordSpacing": "var(--tab-inactive-word-spacing)", + "opacity": "var(--rx-segmented-inactive-opacity)", + }, + { + "display": "var(--rx-segmented-indicator)", + "position": {"default": "absolute", "::before": "absolute"}, + "zIndex": -1, + "top": {"default": "0", "::before": "1px"}, + "left": {"default": "0", "::before": "1px"}, + "height": "100%", + "width": "calc(100% / var(--rx-segmented-count))", + "transform": "translateX(calc(var(--rx-segmented-index) * 100%))", + "pointerEvents": "none", + "transitionProperty": "transform", + "transitionTimingFunction": "cubic-bezier(0.445, 0.05, 0.55, 0.95)", + "transitionDuration": "100ms", + "right": {"::before": "1px"}, + "bottom": {"::before": "1px"}, + "borderRadius": { + "::before": "max(0.5px, calc(var(--segmented-control-border-radius) - 1px))" + }, + "backgroundColor": { + "::before": "light-dark(var(--color-background), var(--gray-a3))" + }, + "content": {"::before": "''"}, + "boxShadow": {"::before": "var(--shadow-2)"}, + }, + ] + + +def test_segmented_control_unknown_variant(ui_plugin: UIPlugin): + """A variant a segmented control does not have is an error that lists the ones it has.""" + with pytest.raises(StyleError) as error: + rx.ui.segmented_control.root(variant="soft") + assert ( + str(error.value) + == 'rx.ui.segmented_control_root: unknown variant "soft". The values are "classic", "surface".' + ) + + +def test_segmented_control_from_a_foreach(ui_plugin: UIPlugin): + """Items a foreach renders are counted in the browser, and a bound control checks the item of its value.""" + control = rx.ui.segmented_control.root( + rx.foreach( + SegmentedState.views, + lambda view: rx.ui.segmented_control.item(view, value=view), + ), + value=SegmentedState.view, + on_change=SegmentedState.set_view, + ) + state = ( + "reflex___state____state__tests___units___reflex_components_ui" + "___components___test_segmented_control____segmented_state" + ) + style = control._element_styles().style.style + assert str(style["--rx-segmented-count"]) == f"{state}.views_rx_state_.length" + # The name of the argument of the function is made up anew each run. + index = re.sub( + r"\(\((\w+)\) => \1\)", + "((item) => item)", + str(style["--rx-segmented-index-of-value"]), + ) + assert index == ( + f"({state}.views_rx_state_.map(((item) => item))" + f".indexOf({state}.view_rx_state_))" + ) + item = control.children[0].children[0] + assert item.children[0].render()["props"] == [ + f"checked:({state}.view_rx_state_ === view_rx_state_)", + "className:sx_8e51139181_c", + 'form:""', + 'name:"rx-segmented-1"', + "readOnly:true", + 'type:"radio"', + "value:view_rx_state_", + ] + + +def test_segmented_control_places_every_item(ui_plugin: UIPlugin): + """The style table places the indicator for ten items, and a control with more adds the rest.""" + item = rx.ui.segmented_control.item + twelve = rx.ui.segmented_control.root(*[ + item(str(number), value=str(number)) for number in range(12) + ]) + index = twelve._element_styles().style.style["--rx-segmented-index"] + assert index == { + "default": "var(--rx-segmented-index-of-value, 0)", + **{ + f":has(> :nth-child({position}) > input:checked)": position - 1 + for position in range(1, 13) + }, + } + assert twelve._element_styles().style.style["--rx-segmented-count"] == 12 + + +def test_segmented_control_script(ui_plugin: UIPlugin): + """The one script of a segmented control is the keys that move through it.""" + control = rx.ui.segmented_control.root(rx.ui.segmented_control.item("a", value="a")) + assert control._get_all_imports()["$/reflex-ui/behaviors/roving-focus.js"] == [ + ImportVar(tag="rovingKeyDown") + ] + assert control.render()["props"] == [ + "className:sx_1b6d0f2eb5_c", + "onKeyDown:rovingKeyDown", + 'role:"radiogroup"', + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 7fe061176c2..78d099025f2 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -161,6 +161,8 @@ def test_every_wave_is_in_the_namespace(): "radio_group.root", "scroll_area", "section", + "segmented_control.item", + "segmented_control.root", "separator", "skeleton", "spacer", @@ -200,6 +202,7 @@ def test_every_wave_is_in_the_namespace(): "list", "radio", "radio_group", + "segmented_control", "table", "text", "text_field", From b605c9e17edca9dfdff6afa9e3ede1d5fb8815b9 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 02:55:28 +0000 Subject: [PATCH 076/204] Add rx.ui.slider: native range inputs over the track of Radix Themes Each thumb is the thumb of a range input, drawn as Radix draws its own and moved by the browser. A script draws the filled part of the track and, for a slider with several thumbs, keeps them in order and moves the nearest to a pointer on the track. A part inside a foreach is styled by the table of its component. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../js/src/behaviors/slider.js | 107 ++ .../js/tests/behaviors/slider.test.js | 170 +++ .../parity/allowlist.toml | 27 + .../parity/ui_parity/components/slider.py | 407 +++++++ .../parity/ui_parity/look.py | 5 +- .../src/reflex_components_ui/__init__.py | 1 + .../src/reflex_components_ui/base.py | 6 +- .../reflex_components_ui/components/slider.py | 385 +++++++ .../src/reflex_components_ui/styles/slider.py | 318 ++++++ .../components/test_slider.py | 1008 +++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 11 files changed, 2432 insertions(+), 3 deletions(-) create mode 100644 packages/reflex-components-ui/js/src/behaviors/slider.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/slider.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/slider.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/slider.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py create mode 100644 tests/units/reflex_components_ui/components/test_slider.py diff --git a/packages/reflex-components-ui/js/src/behaviors/slider.js b/packages/reflex-components-ui/js/src/behaviors/slider.js new file mode 100644 index 00000000000..46fbbd81aac --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/slider.js @@ -0,0 +1,107 @@ +// What a slider draws of the values of its native range inputs: the part +// of its track between them, and for a slider with several thumbs the order +// they keep and the thumb a pointer on the track moves. +// +// The thumbs are the ones of the inputs, which the browser moves, reads to +// the accessibility tree and submits with a form by itself. Without this +// the filled part of the track stays where the server drew it. + +/** + * Find the inputs of a slider. + * + * @param {Element} slider The slider. + * @returns {HTMLInputElement[]} Its range inputs, in the order of its thumbs. + */ +function thumbs(slider) { + return /** @type {HTMLInputElement[]} */ ([...slider.querySelectorAll("input")]); +} + +/** + * Say how far along its track the value of an input is. + * + * @param {HTMLInputElement} input A range input. + * @returns {string} The share of the track, as a percentage. + */ +function share(input) { + const min = Number(input.min || 0); + const max = Number(input.max || 100); + return `${max > min ? ((input.valueAsNumber - min) / (max - min)) * 100 : 0}%`; +} + +/** + * Give an input a value as a user does, so that React hears of it. + * + * @param {HTMLInputElement} input The input. + * @param {number} value The value. + * @returns {void} + */ +function assign(input, value) { + const setter = /** @type {(this: HTMLInputElement, value: string) => void} */ ( + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set + ); + setter.call(input, String(value)); + input.dispatchEvent(new Event("input", { bubbles: true })); +} + +/** + * Follow a thumb that moves: the `onInput` of a slider. + * + * A thumb stops at the ones beside it, and the filled part of the track is + * drawn from the first thumb to the last, or from the start of the track to + * the only one. + * + * @param {{ target: EventTarget | null, currentTarget: HTMLElement }} event + * The input of one of the thumbs. + * @returns {void} + */ +export function slide(event) { + const slider = event.currentTarget; + const inputs = thumbs(slider); + const index = inputs.indexOf(/** @type {HTMLInputElement} */ (event.target)); + if (index < 0) return; + const moved = inputs[index]; + const low = inputs[index - 1]?.valueAsNumber ?? -Infinity; + const high = inputs[index + 1]?.valueAsNumber ?? Infinity; + const kept = Math.min(Math.max(moved.valueAsNumber, low), high); + if (kept !== moved.valueAsNumber) moved.value = String(kept); + slider.style.setProperty("--rx-slider-start", inputs.length > 1 ? share(inputs[0]) : "0%"); + slider.style.setProperty("--rx-slider-end", share(inputs[inputs.length - 1])); +} + +/** + * Move the nearest thumb of a slider with several to a pointer on its + * track: the `onMouseDown` of such a slider. + * + * The browser does it for a slider with one thumb. With several, each + * input lets the pointer through to the ones below it, but for its thumb. + * The thumb that moves takes the focus, which the pointer leaves it. + * + * @param {{ target: EventTarget | null, currentTarget: HTMLElement, clientX: number, clientY: number, preventDefault: () => void }} event + * The pointer going down on the slider. + * @returns {void} + */ +export function press(event) { + const slider = event.currentTarget; + const inputs = thumbs(slider); + const first = inputs[0]; + if (inputs.length < 2 || event.target instanceof HTMLInputElement || first.disabled) return; + const box = slider.getBoundingClientRect(); + const vertical = slider.dataset.orientation === "vertical"; + const along = vertical + ? (box.bottom - event.clientY) / box.height + : (event.clientX - box.left) / box.width; + const min = Number(first.min || 0); + const max = Number(first.max || 100); + const step = Number(first.step || 1); + const reached = min + Math.min(Math.max(along, 0), 1) * (max - min); + const value = Math.min(max, min + Math.round((reached - min) / step) * step); + let nearest = first; + for (const input of inputs) { + if (Math.abs(input.valueAsNumber - value) < Math.abs(nearest.valueAsNumber - value)) { + nearest = input; + } + } + event.preventDefault(); + nearest.focus(); + assign(nearest, value); +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/slider.test.js b/packages/reflex-components-ui/js/tests/behaviors/slider.test.js new file mode 100644 index 00000000000..055f310d55c --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/slider.test.js @@ -0,0 +1,170 @@ +// What a slider draws of its range inputs: the filled part of its track, +// the order of several thumbs, and the thumb a pointer on the track moves. +import { beforeEach, expect, test } from "vitest"; + +import { press, slide } from "$/reflex-ui/behaviors/slider.js"; + +/** + * Build a slider. + * + * @param {number[]} values The value of each thumb. + * @param {string} [attributes] Further attributes of each input. + * @returns {HTMLElement} The slider. + */ +function slider(values, attributes = "") { + document.body.innerHTML = `${values + .map((value) => ``) + .join("")}`; + const element = /** @type {HTMLElement} */ (document.getElementById("slider")); + // jsdom lays nothing out: the track is 200 pixels long, from 100. + element.getBoundingClientRect = () => + /** @type {DOMRect} */ ({ left: 100, width: 200, bottom: 300, height: 200 }); + return element; +} + +/** + * Read where the filled part of the track of a slider starts and ends. + * + * @param {HTMLElement} element The slider. + * @returns {string[]} The two custom properties. + */ +function filled(element) { + return ["--rx-slider-start", "--rx-slider-end"].map((name) => + element.style.getPropertyValue(name), + ); +} + +/** + * Read the values of the thumbs of a slider. + * + * @param {HTMLElement} element The slider. + * @returns {number[]} The value of each thumb. + */ +function values(element) { + return [...element.querySelectorAll("input")].map((input) => input.valueAsNumber); +} + +/** + * Move a thumb as a user does. + * + * @param {HTMLElement} element The slider. + * @param {number} index Which thumb. + * @param {number} value Where to. + * @returns {void} + */ +function move(element, index, value) { + const input = element.querySelectorAll("input")[index]; + input.value = String(value); + slide({ target: input, currentTarget: element }); +} + +/** + * Put the pointer down on the track of a slider. + * + * @param {HTMLElement} element The slider. + * @param {{ clientX?: number, clientY?: number, target?: EventTarget }} at Where. + * @returns {boolean} Whether the slider kept the pointer from the browser. + */ +function pointer(element, at) { + let prevented = false; + press({ + target: element, + currentTarget: element, + clientX: 0, + clientY: 0, + preventDefault: () => { + prevented = true; + }, + ...at, + }); + return prevented; +} + +beforeEach(() => { + document.body.innerHTML = ""; +}); + +test("the track is filled from its start to the only thumb", () => { + const element = slider([30]); + move(element, 0, 45); + expect(filled(element)).toEqual(["0%", "45%"]); +}); + +test("the share of the track follows the range of the slider", () => { + const element = slider([20], 'min="10" max="50"'); + move(element, 0, 30); + expect(filled(element)).toEqual(["0%", "50%"]); + const flat = slider([5], 'min="5" max="5"'); + move(flat, 0, 5); + expect(filled(flat)).toEqual(["0%", "0%"]); +}); + +test("with several thumbs the track is filled from the first to the last", () => { + const element = slider([20, 60, 90]); + move(element, 1, 70); + expect(filled(element)).toEqual(["20%", "90%"]); + move(element, 0, 10); + expect(filled(element)).toEqual(["10%", "90%"]); +}); + +test("a thumb stops at the thumbs beside it", () => { + const element = slider([20, 60, 90]); + move(element, 0, 75); + expect(values(element)).toEqual([60, 60, 90]); + move(element, 2, 10); + expect(values(element)).toEqual([60, 60, 60]); + move(element, 1, 100); + expect(values(element)).toEqual([60, 60, 60]); + expect(filled(element)).toEqual(["60%", "60%"]); +}); + +test("what is no thumb of the slider moves nothing", () => { + const element = slider([20, 60]); + slide({ target: document.body, currentTarget: element }); + expect(filled(element)).toEqual(["", ""]); +}); + +test("a pointer on the track moves the nearest thumb there and gives it the focus", () => { + const element = slider([20, 60]); + /** @type {number[][]} */ + const heard = []; + element.addEventListener("input", () => heard.push(values(element))); + expect(pointer(element, { clientX: 250 })).toBe(true); + expect(values(element)).toEqual([20, 75]); + expect(document.activeElement).toBe(element.querySelectorAll("input")[1]); + expect(pointer(element, { clientX: 110 })).toBe(true); + expect(values(element)).toEqual([5, 75]); + expect(heard).toEqual([ + [20, 75], + [5, 75], + ]); +}); + +test("a pointer past the ends of the track goes to its ends, by the step", () => { + const element = slider([2, 6], 'min="0" max="10" step="4"'); + pointer(element, { clientX: 1000 }); + expect(values(element)).toEqual([2, 10]); + const stepped = slider([0, 8], 'min="0" max="10" step="4"'); + pointer(stepped, { clientX: 100 + 200 * 0.45 }); + expect(values(stepped)).toEqual([4, 8]); + pointer(stepped, { clientX: -50 }); + expect(values(stepped)).toEqual([0, 8]); +}); + +test("a vertical slider is read from the bottom up", () => { + const element = slider([20, 60]); + element.dataset.orientation = "vertical"; + pointer(element, { clientY: 300 - 200 * 0.9 }); + expect(values(element)).toEqual([20, 90]); +}); + +test("one thumb, a thumb under the pointer and a disabled slider are left to the browser", () => { + const one = slider([20]); + expect(pointer(one, { clientX: 250 })).toBe(false); + expect(values(one)).toEqual([20]); + const two = slider([20, 60]); + expect(pointer(two, { clientX: 250, target: two.querySelector("input") ?? two })).toBe(false); + const off = slider([20, 60], "disabled"); + expect(pointer(off, { clientX: 250 })).toBe(false); + expect(values(off)).toEqual([20, 60]); +}); diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index b8e99a2624e..535fb1c3e00 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -206,3 +206,30 @@ component = "segmented_control" step = "chooses an item with JavaScript disabled" system = "rx" reason = "The items of rx.segmented_control are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. An item of rx.ui.segmented_control is a label around a native radio button, which the browser checks with or without JavaScript." + +[[look]] +component = "slider" +check = "a11y" +reason = "A thumb of rx.ui.slider is a native range input, which says its value to the accessibility tree as every such input does. A thumb of rx.slider has its value in `aria-valuenow` alone." + +[[contract]] +component = "slider" +step = "moves with the keyboard with JavaScript disabled" +system = "rx" +reason = "rx.slider is drawn and moved by JavaScript: until it has run, its thumb takes no focus and no key. The thumbs of rx.ui.slider are native range inputs, which the keyboard and the pointer move with or without JavaScript; only the filled part of the track waits for it." + +[[contract]] +component = "slider" +step = "the thumb of a slider has the name the slider is given" +system = "rx" +reason = "An `aria_label` of rx.slider names the element around its thumb, so the thumb, which is what a screen reader lands on, has no name. rx.ui.slider gives the label to the thumb." + +[[contract]] +component = "slider" +step = "Shift and an arrow key move a thumb by ten steps" +reason = "The thumbs of rx.ui.slider are native range inputs: the browser moves one by one step for an arrow key, with or without Shift, and by ten for Page Up and Page Down, as rx.slider does for those." + +[[contract]] +component = "slider" +step = "a thumb can be moved past the one after it" +reason = "A thumb of rx.ui.slider stops at the thumbs beside it, where a thumb of rx.slider passes them and the two change places. Home and End move the thumb that has the focus, where rx.slider moves the first and the last whichever has it." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/slider.py b/packages/reflex-components-ui/parity/ui_parity/components/slider.py new file mode 100644 index 00000000000..238a060690a --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/slider.py @@ -0,0 +1,407 @@ +"""The slider: every variant, size and state, and what moves its thumbs.""" + +from __future__ import annotations + +from typing import Any + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import FOCUS_WITHIN +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, focused, wait_for_text + +VARIANTS = ["classic", "surface", "soft"] +SIZES = ["1", "2", "3"] +RADII = ["none", "small", "full"] +VALUES = {"start": [0], "end": [100], "two": [20, 60], "three": [10, 50, 90]} + +MATRIX = Matrix( + component="slider", + base={"default_value": [40]}, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "color_scheme": ACCENTS, + "radius": RADII, + "high_contrast": [True], + "disabled": [True], + "default_value": VALUES, + "width": ["120px"], + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE], + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "high_contrast": [False, True], + "appearance": [LIGHT, DARK], + "default_value": {"two": [20, 60]}, + }, + { + "variant": VARIANTS, + "disabled": [True], + "appearance": [LIGHT, DARK], + "default_value": {"one": [40], "two": [20, 60]}, + }, + {"variant": VARIANTS, "state": [FOCUS_VISIBLE], "appearance": [LIGHT, DARK]}, + { + "variant": VARIANTS, + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + }, + {"radius": RADII, "size": SIZES, "variant": VARIANTS}, + {"default_value": VALUES, "size": SIZES}, + { + "orientation": ["vertical"], + "height": ["100px"], + "default_value": {"one": [40], "two": [20, 60]}, + "variant": VARIANTS, + }, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(240, 140), + crop="stage", + parts={ + "track": "span > span", + "range": "span > span > span", + }, + # The focus is on the first thumb: an element of Radix, an input here. + states={FOCUS_VISIBLE: FOCUS_WITHIN}, + # Not held to zero. At a threshold of zero 102 of the 147 cells are + # equal pixel for pixel, and the others differ by where they are on the + # page: the translucent layers of the soft track are dithered by a step + # of a channel, and the round thumb is anti-aliased otherwise. At the + # default threshold 5 cells differ, by at most 2 pixels of 33600. + tolerance=0.0001, +) + + +class SliderState(rx.State): + """What the sliders of the contract are bound to.""" + + bound: list[int] = [10] + seen: list[list[float]] = [] + committed: list[list[float]] = [] + submitted: dict[str, Any] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, values: list[float]): + """Follow the bound slider. + + Args: + values: Its values. + """ + self.bound = [int(value) for value in values] + + @rx.event + def see(self, values: list[float]): + """Keep what a change handed over. + + Args: + values: The values of the slider. + """ + self.seen.append(values) + + @rx.event + def commit(self, values: list[float]): + """Keep what a released thumb handed over. + + Args: + values: The values of the slider. + """ + self.committed.append(values) + + @rx.event + def set_high(self): + """Change the bound value from outside the slider.""" + self.bound = [80] + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +WIDTH = {"width": "200px", "padding": "12px 0"} + +CONTRACT = Contract( + component="slider", + render=lambda namespace: namespace.box( + rx.el.div( + namespace.slider( + default_value=30, + aria_label="Volume", + on_change=SliderState.see, + on_value_commit=SliderState.commit, + ), + id="volume", + style=WIDTH, + ), + rx.el.div( + namespace.slider(default_value=30, disabled=True, aria_label="Off"), + id="off", + style=WIDTH, + ), + rx.el.div( + namespace.slider( + value=SliderState.bound, + on_change=SliderState.set_bound, + aria_label="Bound", + ), + id="bound", + style=WIDTH, + ), + rx.el.button("High", id="high", on_click=SliderState.set_high), + rx.el.div( + namespace.slider( + default_value=[20, 60], aria_label="Span", on_change=SliderState.see + ), + id="span", + style=WIDTH, + ), + rx.el.div( + namespace.slider( + default_value=4, min=0, max=10, step=2, aria_label="Steps" + ), + id="steps", + style=WIDTH, + ), + rx.el.form( + namespace.slider(default_value=25, name="level", aria_label="Level"), + rx.el.button("Send", id="send", type="submit"), + on_submit=SliderState.submit, + id="form", + style=WIDTH, + ), + rx.el.span(SliderState.seen.to_string(), id="seen"), + rx.el.span(SliderState.committed.to_string(), id="committed"), + rx.el.span(SliderState.bound.to_string(), id="bound-value"), + rx.el.span(SliderState.submitted.to_string(), id="submitted"), + rx.el.span(SliderState.submissions.to_string(), id="submissions"), + ), +) + +# A thumb is an element with the role of a slider in Radix, a range input here. +THUMBS = "[role=slider], input[type=range]" +# The values of the thumbs of a slider, by the id of its frame. +VALUES_OF = ( + f"id => [...document.getElementById(id).querySelectorAll('{THUMBS}')]" + ".map(thumb => Number(thumb.getAttribute('aria-valuenow') ?? thumb.value))" +) +# The slider whose thumb has the focus, and which of its thumbs it is. +FOCUSED_THUMB = ( + "(thumb => thumb.closest('div[id]')?.id + ':' + " + f"[...thumb.closest('div[id]')?.querySelectorAll('{THUMBS}') ?? []].indexOf(thumb))" + "(document.activeElement)" +) + + +def _wait_for_values(run: Run, slider: str, values: list[float]) -> None: + """Wait until the thumbs of a slider have the values expected. + + Args: + run: The run, on a page. + slider: The id of the frame of the slider. + values: The value of each thumb. + """ + run.page.wait_for_function( + f"([id, values]) => ({VALUES_OF})(id).join() === values", + arg=[slider, ",".join(str(value) for value in values)], + ) + + +def _thumb(run: Run, slider: str, index: int = 0) -> Any: + """Find a thumb of a slider. + + Args: + run: The run, on a page. + slider: The id of the frame of the slider. + index: Which of its thumbs. + + Returns: + The thumb. + """ + return run.page.locator(f"#{slider}").locator(THUMBS).nth(index) + + +@CONTRACT.step("is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("volume").tag == "div" + assert run.server.element("form").tag == "form" + + +@CONTRACT.step("moves with the keyboard with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + _wait_for_values(run, "volume", [30]) + page.keyboard.press("Tab") + page.keyboard.press("ArrowRight") + _wait_for_values(run, "volume", [31]) + + +@CONTRACT.step("each thumb is a slider with its value and its range") +def _role(run: Run) -> None: + page = run.page + volume = page.locator("#volume").get_by_role("slider") + assert volume.count() == 1 + assert volume.evaluate( + "thumb => ['min', 'max', 'now'].map(name =>" + " thumb.getAttribute('aria-value' + name)" + " ?? (name === 'now' ? thumb.value : thumb[name] || (name === 'min' ? '0' : '100')))" + ) == ["0", "100", "30"] + assert page.locator("#span").get_by_role("slider").count() == 2 + assert page.locator("#off").get_by_role("slider", disabled=True).count() == 1 + assert page.evaluate(VALUES_OF, "span") == [20, 60] + span = page.locator("#span") + assert span.get_by_role("slider", name="Minimum").count() == 1 + assert span.get_by_role("slider", name="Maximum").count() == 1 + + +@CONTRACT.step("the thumb of a slider has the name the slider is given") +def _name(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + assert page.get_by_role("slider", name="Volume").count() == 1 + assert page.get_by_role("slider", name="Off", disabled=True).count() == 1 + + +@CONTRACT.step("Tab stops on each thumb but a disabled one") +def _tab(run: Run) -> None: + page = run.page + stops = [] + for _ in range(6): + page.keyboard.press("Tab") + stops.append(focused(page) or page.evaluate(FOCUSED_THUMB)) + assert stops == ["volume:0", "bound:0", "high", "span:0", "span:1", "steps:0"] + + +@CONTRACT.step("the arrow keys, the page keys, Home and End move a thumb, and say so") +def _keys(run: Run) -> None: + page = run.page + _thumb(run, "volume").focus() + for key, value in ( + ("ArrowRight", 31), + ("ArrowUp", 32), + ("ArrowLeft", 31), + ("ArrowDown", 30), + ("PageUp", 40), + ("PageDown", 30), + ("End", 100), + ("Home", 0), + ): + page.keyboard.press(key) + _wait_for_values(run, "volume", [value]) + values = "[[31],[32],[31],[30],[40],[30],[100],[0]]" + wait_for_text(page, "seen", values) + wait_for_text(page, "committed", values) + + +@CONTRACT.step("Shift and an arrow key move a thumb by ten steps") +def _shift(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + _thumb(run, "volume").focus() + page.keyboard.press("Shift+ArrowRight") + _wait_for_values(run, "volume", [40]) + + +@CONTRACT.step("a thumb moves by the step of its slider, within its range") +def _steps(run: Run) -> None: + page = run.page + _thumb(run, "steps").focus() + page.keyboard.press("ArrowRight") + _wait_for_values(run, "steps", [6]) + page.keyboard.press("End") + page.keyboard.press("ArrowRight") + _wait_for_values(run, "steps", [10]) + + +@CONTRACT.step("a pointer on the track moves the thumb there, and releasing it says so") +def _pointer(run: Run) -> None: + page = run.page + box = page.locator("#volume").bounding_box() + assert box is not None + page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + _wait_for_values(run, "volume", [50]) + wait_for_text(page, "seen", "[[50]]") + wait_for_text(page, "committed", "[[50]]") + + +@CONTRACT.step("a disabled slider does not move") +def _disabled(run: Run) -> None: + page = run.page + box = page.locator("#off").bounding_box() + assert box is not None + page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + page.keyboard.press("ArrowRight") + _thumb(run, "volume").focus() + page.keyboard.press("ArrowRight") + _wait_for_values(run, "volume", [31]) + assert page.evaluate(VALUES_OF, "off") == [30] + + +@CONTRACT.step("follows the state it is bound to") +def _bound(run: Run) -> None: + page = run.page + _wait_for_values(run, "bound", [10]) + _thumb(run, "bound").focus() + page.keyboard.press("ArrowRight") + wait_for_text(page, "bound-value", "[11]") + _wait_for_values(run, "bound", [11]) + page.locator("#high").click() + wait_for_text(page, "bound-value", "[80]") + _wait_for_values(run, "bound", [80]) + + +@CONTRACT.step("a slider with two values has a thumb for each, and hands over both") +def _two(run: Run) -> None: + page = run.page + _thumb(run, "span", 0).focus() + page.keyboard.press("ArrowRight") + _wait_for_values(run, "span", [21, 60]) + _thumb(run, "span", 1).focus() + page.keyboard.press("ArrowLeft") + _wait_for_values(run, "span", [21, 59]) + wait_for_text(page, "seen", "[[21,60],[21,59]]") + + +@CONTRACT.step("a pointer on the track of a slider with two thumbs moves the nearest") +def _nearest(run: Run) -> None: + page = run.page + box = page.locator("#span").bounding_box() + assert box is not None + page.mouse.click(box["x"] + box["width"] * 0.75, box["y"] + box["height"] / 2) + _wait_for_values(run, "span", [20, 75]) + page.wait_for_function(f"{FOCUSED_THUMB} === 'span:1'") + wait_for_text(page, "seen", "[[20,75]]") + + +@CONTRACT.step("a thumb can be moved past the one after it") +def _past(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + _thumb(run, "span", 0).focus() + for _ in range(5): + page.keyboard.press("PageUp") + _wait_for_values(run, "span", [60, 70]) + + +@CONTRACT.step("submits its value with a form") +def _submit(run: Run) -> None: + page = run.page + _thumb(run, "form").focus() + page.keyboard.press("ArrowRight") + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == '{"level":"26"}' diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py index d7dabcefcad..e7466f31459 100644 --- a/packages/reflex-components-ui/parity/ui_parity/look.py +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -218,7 +218,10 @@ def _focus_within(page: Page, target: Locator, point: Point) -> None: """element => { const control = element.matches( 'button, input, select, textarea, [tabindex]' - ) ? element : element.querySelector('input, button, select, textarea'); + ) ? element : element.querySelector( + 'input:not([type=hidden], [aria-hidden]), button, select, textarea,' + + ' [tabindex]:not([tabindex="-1"])' + ); control.focus(); try { control.setSelectionRange?.(0, 0); 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 808e42de497..6c6b069a815 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -27,6 +27,7 @@ "components.segmented_control": ["segmented_control"], "components.separator": ["divider", "separator"], "components.skeleton": ["skeleton"], + "components.slider": ["slider"], "components.spinner": ["spinner"], "components.switch": ["switch"], "components.table": ["table"], 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 2a17d7d144a..8a620302d23 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -24,6 +24,7 @@ from reflex_base.vars.sequence import LiteralStringVar from reflex_components_core.base.fragment import Fragment from reflex_components_core.core.cond import Cond +from reflex_components_core.core.foreach import Foreach from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import ( @@ -814,7 +815,7 @@ def _element_styles(self) -> Merged: # What renders no element of its own, between a component and its parts. -_NO_ELEMENT = (Fragment, Cond) +_NO_ELEMENT = (Fragment, Cond, Foreach) def _bind_parts( @@ -842,7 +843,8 @@ def _bind_parts( child._merged = merged _bind_parts(child.children, parts, name) elif type(child) in _NO_ELEMENT: - # A part that is only rendered under a condition. + # A part that is only rendered under a condition, or once for + # each item of a list. _bind_parts(child.children, parts, name) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/slider.py b/packages/reflex-components-ui/src/reflex_components_ui/components/slider.py new file mode 100644 index 00000000000..8a863260013 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/slider.py @@ -0,0 +1,385 @@ +"""A slider: native range inputs over a track that Radix Themes draws.""" + +from __future__ import annotations + +import functools +from collections.abc import Sequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, JavascriptInputEvent +from reflex_base.utils.imports import ImportVar +from reflex_base.utils.types import typehint_issubclass +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.vars.object import ObjectVar +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.foreach import foreach +from reflex_components_core.el import elements + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.components._group import literal +from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.slider import END, SLIDER, START +from reflex_components_ui.themes import LiteralAccentColor + +_SCRIPT = f"$/{WEB_DIR}/behaviors/slider.js" + +# What follows the thumbs of a slider: its `onInputCapture` draws the filled +# part of the track and keeps several thumbs in order, and the +# `onMouseDown` of a slider with several moves the nearest one. +_SLIDE = Var("slide", _var_data=VarData(imports={_SCRIPT: [ImportVar(tag="slide")]})) +_PRESS = Var("press", _var_data=VarData(imports={_SCRIPT: [ImportVar(tag="press")]})) + +# The keys that move a thumb: a thumb is released when one of them is. +_KEYS = ( + '["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", ' + '"Home", "End", "PageUp", "PageDown"]' +) + + +def _values(event: Var, kind: type) -> Var: + """Read the values of the thumbs of a slider from an event inside it. + + Args: + event: The event, as it reaches the slider. + kind: The type of the list of values. + + Returns: + The value of each thumb, in the order of the thumbs. + """ + return Var( + f'Array.from({event!s}.currentTarget.querySelectorAll("input"), ' + "(input) => input.valueAsNumber)", + _var_type=kind, + ) + + +def float_values_event( + e: ObjectVar[JavascriptInputEvent], +) -> tuple[Var[list[float]]]: + """Get the values of a slider from a change of one of its thumbs. + + Args: + e: The change, as it reaches the slider. + + Returns: + The value of each thumb. + """ + return (_values(e, list[float]),) + + +def int_values_event(e: ObjectVar[JavascriptInputEvent]) -> tuple[Var[list[int]]]: + """Get the whole values of a slider from a change of one of its thumbs. + + Args: + e: The change, as it reaches the slider. + + Returns: + The value of each thumb. + """ + return (_values(e, list[int]),) + + +on_value_event_spec = (float_values_event, int_values_event) + + +def _share(value: Any, low: Any, high: Any) -> Any: + """Say how far along the track of a slider a value is. + + Args: + value: The value. + low: The minimum of the slider, or None for 0. + high: Its maximum, or None for 100. + + Returns: + The share of the track as a percentage: a string when everything is + known while compiling. + """ + low = 0 if low is None else literal(low) + high = 100 if high is None else literal(high) + value = literal(value) + if not any(isinstance(item, Var) for item in (value, low, high)): + return f"{(value - low) / (high - low) * 100:g}%" if high > low else "0%" + parts = [LiteralVar.create(item) for item in (value, low, high)] + amount, start, end = (str(part) for part in parts) + return Var( + f'(((({amount}) - ({start})) / (({end}) - ({start})) * 100) + "%")', + _var_type=str, + _var_data=VarData.merge(*(part._get_all_var_data() for part in parts)), + ) + + +def _label(index: int, count: int) -> dict[str, str]: + """Name a thumb of a slider with several, as Radix does. + + Args: + index: Which thumb it is, from 0. + count: How many thumbs the slider has. + + Returns: + The label of the thumb, or nothing for the only thumb of a slider: + its name is the one the slider is given. + """ + if count == 1: + return {} + if count == 2: + return {"aria_label": ("Minimum", "Maximum")[index]} + return {"aria_label": f"Value {index + 1} of {count}"} + + +class SliderThumb(Part, elements.Input): + """A thumb of a slider: a native range input.""" + + tag = "input" + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the input. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the type of a range. + """ + return super()._render(props).add_props(type="range") + + +class Slider(UIComponent): + """Provides user selection from a range of values.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = SLIDER + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + size: Var[Responsive[Literal["1", "2", "3"]]] = field(doc='Button size "1" - "3"') + + variant: Var[Literal["classic", "surface", "soft"]] = field(doc="Variant of button") + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + high_contrast: Var[bool] = field( + doc="Whether to render the button with higher contrast color against background" + ) + + radius: Var[Literal["none", "small", "full"]] = field( + doc='Override theme radius for button: "none" | "small" | "full"' + ) + + default_value: Var[Sequence[float | int] | float | int] = field( + doc="The value of the slider when initially rendered. Use when you do not need to control the state of the slider." + ) + + value: Var[Sequence[float | int]] = field( + doc="The controlled value of the slider. Must be used in conjunction with onValueChange." + ) + + name: Var[str] = field( + doc="The name of the slider. Submitted with its owning form as part of a name/value pair." + ) + + width: Var[str | None] = field( + default=Var.create("100%"), doc="The width of the slider." + ) + + min: Var[float | int] = field(doc="The minimum value of the slider.") + + max: Var[float | int] = field(doc="The maximum value of the slider.") + + step: Var[float | int] = field(doc="The step value of the slider.") + + disabled: Var[bool] = field(doc="Whether the slider is disabled") + + orientation: Var[Literal["horizontal", "vertical"]] = field( + doc="The orientation of the slider." + ) + + on_change: EventHandler[on_value_event_spec] = field( + doc="Fired when the value of the slider changes." + ) + + on_value_commit: EventHandler[on_value_event_spec] = field( + doc="Fired when a thumb is released after being dragged." + ) + + @classmethod + @functools.cache + def _literal_props(cls) -> dict[str, tuple[str, ...]]: + """Get the props that take listed values. + + Returns: + The values of each such prop, the radius among them: a slider + has fewer than a theme. + """ + return {**super()._literal_props(), "radius": ("none", "small", "full")} + + @classmethod + def create( + cls, + *children, + **props, + ) -> Component: + """Create a Slider component. + + A slider has a thumb for each of its values: a native range input, + which takes the ``id`` and the name of the slider. The ``aria_*`` + attributes of a slider with one thumb are the ones of its thumb; + with several, they are the ones of the group the thumbs are. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The component. + """ + default_value = props.pop("default_value", [50]) + width = props.pop("width", "100%") + if isinstance(default_value, Var): + if typehint_issubclass(default_value._var_type, int | float): + default_value = [default_value] + elif isinstance(default_value, (int, float)): + default_value = [default_value] + + value = props.get("value") + values = default_value if value is None else value + low, high = props.get("min"), props.get("max") + shared = { + key: props[key] + for key in ("min", "max", "step", "disabled") + if props.get(key) is not None + } + named = {key: props[key] for key in props if key.startswith("aria_")} + attribute = "default_value" if value is None else "value" + name = props.get("name") + thumbs: list[Any] + if isinstance(values, Var) or len(values) > 1: + # Several thumbs are a group with the name of the slider, each + # with a name of its own. + if named: + props.setdefault("custom_attrs", {}).setdefault("role", "group") + else: + # The only thumb has the name of the slider. + shared.update({key: props.pop(key) for key in named}) + if isinstance(values, Var): + # The thumbs of a list in state are counted in the browser. + several: Any = True + thumbs = [ + foreach( + values, + lambda item: SliderThumb.create( + part="thumb", **shared, **{attribute: item} + ), + ) + ] + first = values[0] # pyright: ignore[reportIndexIssue] + start, end = _share(first, low, high), _share(values[-1], low, high) # pyright: ignore[reportIndexIssue] + else: + several = len(values) > 1 + if name is not None and several: + # As Radix names the inputs of a slider with several values. + name = Var.create(name) + "[]" + if name is not None: + shared["name"] = name + thumbs = [ + SliderThumb.create( + part="thumb", + **{**_label(index, len(values)), **shared, attribute: item}, + ) + for index, item in enumerate(values) + ] + if thumbs and "id" in props: + thumbs[0].id = Var.create(props.pop("id")) + start = _share(values[0], low, high) if several else "0%" + end = _share(values[-1], low, high) if values else "0%" + handlers = props.setdefault("custom_attrs", {}) + handlers.setdefault("onInputCapture", _SLIDE) + if several: + handlers.setdefault("onMouseDown", _PRESS) + placement = {"width": width, START: start, END: end} + style = props.get("style") + if style is None: + props["style"] = placement + elif isinstance(style, (list, tuple)): + props["style"] = [placement, *style] + else: + props["style"] = [placement, style] + return super().create( + Part.create( + Part.create(part="range", tag="span"), part="track", tag="span" + ), + *thumbs, + *children, + _several=several, + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the slider. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. ``_several`` says + whether the slider has more than one thumb. + """ + # What the style table reads as a variant. + self._several = kwargs.pop("_several", False) + super()._post_init(*args, **kwargs) + + def _set_slot(self) -> None: + """Render the slider itself: it has no child to be rendered as.""" + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the thumbs off the element. + + Returns: + The props read as styles, and what the slider hands its inputs. + """ + return [ + *super()._exclude_props(), + "disabled", + "default_value", + "value", + "name", + "min", + "max", + "step", + "width", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the slider. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. A thumb is released when the pointer or a key that + moves it is: Radix says so with ``on_value_commit``. + """ + tag = super()._render(props) + orientation = self.orientation + tag = tag.add_props(**{ + "data-orientation": "horizontal" if orientation is None else orientation + }) + commit = tag.props.get("onValueCommit") + if commit is None: + return tag + commit = LiteralVar.create(commit) + var_data = commit._get_all_var_data() + return tag.remove_props("onValueCommit").add_props( + on_pointer_up=commit, + on_key_up=Var( + f"((event) => {{ if ({_KEYS}.includes(event.key)) " + f"({commit!s})(event); }})", + _var_data=var_data, + ), + ) + + +slider = Slider.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py new file mode 100644 index 00000000000..ecf6faffd17 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py @@ -0,0 +1,318 @@ +"""The look of a slider: a track, the part of it that is filled, and its thumbs.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.appearance import by_appearance + +accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black + +_TRACK = "--slider-track-size" +_THUMB = "--slider-thumb-size" +# Where the filled part of the track starts and ends, which the slider sets +# from its values and its script moves with its thumbs. +START = "--rx-slider-start" +END = "--rx-slider-end" + +_DISABLED = ":has(:disabled)" +# The side of the thumb that is drawn: larger than the one that says how far +# a thumb travels, so that it reaches a little past the filled part. +_DRAWN = f"calc(var({_THUMB}) + var({_TRACK}) * 0.5)" +_PAST = f"calc(var({_TRACK}) * -0.25)" + +_THUMB_SHADOWS = { + "surface": f"0 0 0 1px {black.a[4]}", + "classic": ( + f"0 0 0 1px {black.a[3]}, 0 1px 3px {black.a[1]}, 0 2px 4px -1px {black.a[1]}" + ), + "soft": ( + f"0 0 0 1px {black.a[3]}, 0 0 0 1px {gray.a[2]}, 0 0 0 1px {accent.a[2]}, " + f"0 1px 2px {gray.a[4]}, 0 1px 3px -0.5px {gray.a[3]}" + ), +} +_THUMB_DISABLED = {"surface": gray[6], "classic": gray[6], "soft": gray[5]} + +# What darkens the filled part of a high contrast slider, where it is light. +_HIGH_CONTRAST = by_appearance(f"linear-gradient({black.a[8]}, {black.a[8]})", "none") + + +def _thumb(variant: str) -> dict[str, Any]: + """Make the thumb the browser draws for a range input, in one variant. + + Args: + variant: The variant. + + Returns: + The styles of the thumb, for every state of the input. + """ + shadow = _THUMB_SHADOWS[variant] + return { + "appearance": "none", + "box_sizing": "border-box", + "width": _DRAWN, + "height": _DRAWN, + "border_width": "0", + "border_style": "none", + "pointer_events": "auto", + "background_color": {"default": "white", ":disabled": gray[1]}, + "border_radius": f"max({tokens.radius[1]}, {tokens.radius.thumb})", + "box_shadow": { + "default": shadow, + ":focus-visible": ( + f"{shadow}, 0 0 0 3px {accent[3]}, 0 0 0 5px {tokens.focus[8]}" + ), + ":disabled": f"0 0 0 1px {_THUMB_DISABLED[variant]}", + }, + "cursor": { + "default": tokens.cursor.slider_thumb, + ":active": tokens.cursor.slider_thumb_active, + ":disabled": tokens.cursor.disabled, + }, + } + + +def _input(variant: str) -> dict[str, Any]: + """Make the range input of a thumb, in one variant. + + Args: + variant: The variant. + + Returns: + The styles of the input: only its thumb is drawn, in each engine. + """ + clear = {"background_color": "transparent", "height": "100%"} + return { + "::-webkit-slider-runnable-track": clear, + "::-webkit-slider-thumb": _thumb(variant), + "::-moz-range-track": clear, + "::-moz-range-thumb": _thumb(variant), + } + + +def _range(fill: dict[str, Any], disabled: bool) -> dict[str, Any]: + """Make the filled part of a track. + + Args: + fill: Its styles in a slider that can be moved. + disabled: Whether the slider is disabled, which empties it. + + Returns: + The styles. + """ + if not disabled: + return fill + return { + "background_color": "transparent", + "background_image": "none", + "box_shadow": "none", + } + + +_CLASSIC_RANGE = ( + f"inset 0 0 0 1px {gray.a[3]}, inset 0 0 0 1px {accent.a[4]}, " + f"inset 0 0 0 1px {black.a[1]}, inset 0 1.5px 2px 0 {black.a[2]}" +) +_CLASSIC_RANGE_HIGH_CONTRAST = ( + f"inset 0 0 0 1px {gray.a[3]}, inset 0 0 0 1px {black.a[2]}, " + f"inset 0 1.5px 2px 0 {black.a[2]}" +) + + +def _fill(variant: str, high_contrast: bool) -> dict[str, Any]: + """Make the filled part of the track of one variant. + + Args: + variant: The variant. + high_contrast: Whether the slider is high contrast. + + Returns: + The styles of the filled part of a slider that can be moved. + """ + overlay = _HIGH_CONTRAST if high_contrast else "none" + if variant == "soft": + tint = f"linear-gradient({accent.a[5]}, {accent.a[5]})" + return { + "background_color": accent[6], + "background_image": f"{tint}, {overlay}", + } + shadow = f"inset 0 0 0 1px {gray.a[5]}" + if variant == "classic": + shadow = _CLASSIC_RANGE_HIGH_CONTRAST if high_contrast else _CLASSIC_RANGE + return { + "background_color": accent.track, + "background_image": overlay, + "box_shadow": shadow, + } + + +_VARIANTS = ("classic", "surface", "soft") + +_TRACKS: dict[str, dict[str, Any]] = { + "surface": { + "background_color": gray.a[3], + "box_shadow": f"inset 0 0 0 1px {gray.a[5]}", + }, + "classic": { + "background_color": gray.a[3], + "_before": { + "content": "''", + "inset": "0", + "position": "absolute", + "border_radius": "inherit", + "box_shadow": tokens.shadow[1], + }, + }, + "soft": { + "background_color": gray.a[4], + # Blended with white for more contrast in the dark. + "background_image": f"linear-gradient({white.a[1]}, {white.a[1]})", + }, +} +_TRACKS_DISABLED: dict[str, dict[str, Any]] = { + "surface": {"box_shadow": f"inset 0 0 0 1px {gray.a[4]}"}, + "classic": {"_before": {"opacity": 0.5}}, + "soft": {"background_image": "none"}, +} + +SLIDER: ComponentStyles = { + "base": unchecked({ + "box_sizing": "border-box", + _THUMB: f"calc(var({_TRACK}) + {tokens.space[1]})", + "position": "relative", + "display": "flex", + "align_items": "center", + "flex_grow": 1, + "border_radius": ( + f"max(calc({tokens.radius.factor} * var({_TRACK}) / 3), " + f"calc({tokens.radius.factor} * {tokens.radius.thumb}))" + ), + "user_select": "none", + "touch_action": "none", + "cursor": {_DISABLED: tokens.cursor.disabled}, + "mix_blend_mode": {_DISABLED: by_appearance("multiply", "screen")}, + }), + "variants": { + "size": { + "1": unchecked({_TRACK: f"calc({tokens.space[2]} * 0.75)"}), + "2": unchecked({_TRACK: tokens.space[2]}), + "3": unchecked({_TRACK: f"calc({tokens.space[2]} * 1.25)"}), + }, + "orientation": { + "horizontal": {"width": "stretch", "height": f"var({_TRACK})"}, + "vertical": { + "height": "stretch", + "flex_direction": "column", + "width": f"var({_TRACK})", + }, + }, + }, + "defaults": {"size": "2", "variant": "surface", "orientation": "horizontal"}, + "parts": { + "track": { + "base": { + "overflow": "hidden", + "position": "relative", + "flex_grow": 1, + "border_radius": "inherit", + }, + "variants": { + "orientation": { + "horizontal": {"height": f"var({_TRACK})"}, + "vertical": {"width": f"var({_TRACK})"}, + }, + "variant": { + variant: unchecked(_TRACKS[variant]) for variant in _VARIANTS + }, + }, + "defaults": {"variant": "surface", "orientation": "horizontal"}, + "compound": [ + { + "props": {"variant": variant, "disabled": "true"}, + "style": unchecked(_TRACKS_DISABLED[variant]), + } + for variant in _VARIANTS + ], + }, + # The filled part: between the first thumb and the last, or from the + # start of the track to the only one. + "range": { + "base": {"position": "absolute", "border_radius": "inherit"}, + "variants": { + "orientation": { + "horizontal": unchecked({ + "height": "100%", + "left": f"var({START})", + "right": f"calc(100% - var({END}))", + }), + "vertical": unchecked({ + "width": "100%", + "bottom": f"var({START})", + "top": f"calc(100% - var({END}))", + }), + }, + "variant": { + variant: unchecked(_fill(variant, False)) for variant in _VARIANTS + }, + }, + "defaults": {"variant": "surface", "orientation": "horizontal"}, + "compound": [ + *( + { + "props": {"variant": variant, "high_contrast": "true"}, + "style": unchecked(_fill(variant, True)), + } + for variant in _VARIANTS + ), + { + "props": {"disabled": "true"}, + "style": unchecked(_range({}, True)), + }, + ], + }, + # A thumb: a range input of which only the thumb is drawn. It is + # wider than the track by what the drawn thumb reaches past it, so + # that the thumb travels as far as the one of Radix Themes. + "thumb": { + "base": unchecked({ + "appearance": "none", + "position": "absolute", + "margin": "0", + "padding": "0", + "border_width": "0", + "border_style": "none", + "background_color": "transparent", + "outline_style": "none", + "cursor": "inherit", + }), + "variants": { + "orientation": { + "horizontal": { + "width": f"calc(100% + var({_TRACK}) * 0.5)", + "height": _DRAWN, + "left": _PAST, + "top": f"calc(50% - {_DRAWN} / 2)", + }, + "vertical": { + "height": f"calc(100% + var({_TRACK}) * 0.5)", + "width": _DRAWN, + "top": _PAST, + "left": f"calc(50% - {_DRAWN} / 2)", + # From the bottom up. + "writing_mode": "vertical-lr", + "direction": "rtl", + }, + }, + "variant": { + variant: unchecked(_input(variant)) for variant in _VARIANTS + }, + # With several thumbs a pointer goes through an input to the + # ones below it, but for its thumb. + "_several": {"true": {"pointer_events": "none"}}, + }, + "defaults": {"variant": "surface", "orientation": "horizontal"}, + }, + }, +} diff --git a/tests/units/reflex_components_ui/components/test_slider.py b/tests/units/reflex_components_ui/components/test_slider.py new file mode 100644 index 00000000000..ad13fd75bc5 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_slider.py @@ -0,0 +1,1008 @@ +"""Tests for reflex_components_ui.components.slider.""" + +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +class SliderState(rx.State): + """What a slider is bound to.""" + + span: list[float] = [20, 60] + low: int = 10 + + @rx.event + def set_span(self, span: list[float]): + """Follow the slider. + + Args: + span: Its values. + """ + self.span = span + + +def test_slider( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A slider is a track, its filled part and a native range input for its thumb, which has the id, the name and the label of the slider.""" + component = rx.ui.slider( + default_value=30, + id="volume", + name="volume", + min=0, + max=200, + step=5, + aria_label="Volume", + width="50%", + margin="1px", + ) + assert component.render() == { + "name": '"span"', + "props": [ + "className:sx_2e50c10c69_c", + '"data-orientation":"horizontal"', + "onInputCapture:slide", + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_9a52612950_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_3462dcdb83_c"], + "children": [], + } + ], + }, + { + "name": '"input"', + "props": [ + '"aria-label":"Volume"', + "className:sx_2ed6fd010a_c", + "defaultValue:30", + 'id:"volume"', + "max:200", + "min:0", + 'name:"volume"', + "step:5", + 'type:"range"', + ], + "children": [], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "--slider-thumb-size": "calc(var(--slider-track-size) + var(--space-1))", + "position": "relative", + "display": "flex", + "alignItems": "center", + "flexGrow": 1, + "borderRadius": "max(calc(var(--radius-factor) * var(--slider-track-size) / 3), calc(var(--radius-factor) * var(--radius-thumb)))", + "userSelect": "none", + "touchAction": "none", + "cursor": {":has(:disabled)": "var(--cursor-disabled)"}, + "mixBlendMode": { + ":has(:disabled)": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" + }, + "--slider-track-size": "var(--space-2)", + "width": "50%", + "height": "var(--slider-track-size)", + "--rx-slider-start": "0%", + "--rx-slider-end": "15%", + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "position": "relative", + "flexGrow": 1, + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "height": "var(--slider-track-size)", + "backgroundColor": "var(--gray-a3)", + "boxShadow": "inset 0 0 0 1px var(--gray-a5)", + }, + { + "position": "absolute", + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "height": "100%", + "left": "var(--rx-slider-start)", + "right": "calc(100% - var(--rx-slider-end))", + "backgroundColor": "var(--accent-track)", + "backgroundImage": "none", + "boxShadow": "inset 0 0 0 1px var(--gray-a5)", + }, + { + "appearance": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "position": "absolute", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderRightWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderBottomWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderLeftWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderTopStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderRightStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderBottomStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderLeftStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "backgroundColor": { + "default": "transparent", + "::-webkit-slider-runnable-track": "transparent", + "::-webkit-slider-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + "::-moz-range-track": "transparent", + "::-moz-range-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + }, + "outlineStyle": "none", + "cursor": { + "default": "inherit", + "::-webkit-slider-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + "::-moz-range-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "width": { + "default": "calc(100% + var(--slider-track-size) * 0.5)", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "height": { + "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-webkit-slider-runnable-track": "100%", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-track": "100%", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "left": "calc(var(--slider-track-size) * -0.25)", + "top": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", + "boxSizing": { + "::-webkit-slider-thumb": "border-box", + "::-moz-range-thumb": "border-box", + }, + "pointerEvents": { + "::-webkit-slider-thumb": "auto", + "::-moz-range-thumb": "auto", + }, + "borderRadius": { + "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", + "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", + }, + "boxShadow": { + "::-webkit-slider-thumb": { + "default": "0 0 0 1px var(--black-a4)", + ":focus-visible": "0 0 0 1px var(--black-a4), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + "::-moz-range-thumb": { + "default": "0 0 0 1px var(--black-a4)", + ":focus-visible": "0 0 0 1px var(--black-a4), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + }, + }, + ] + + +def test_slider_with_several_thumbs( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A slider with several values has a thumb for each, named as Radix names them in a group with the name of the slider, and its script moves the nearest.""" + component = rx.ui.slider( + default_value=[20, 60, 90], + name="span", + aria_label="Span", + disabled=True, + size="3", + variant="classic", + high_contrast=True, + color_scheme="ruby", + radius="small", + orientation="vertical", + as_child=True, + ) + assert component.render() == { + "name": '"span"', + "props": [ + '"aria-label":"Span"', + 'className:sx_2a31e8da62_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', + '"data-orientation":"vertical"', + "onInputCapture:slide", + "onMouseDown:press", + 'role:"group"', + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_c5bed6bb3f_c"], + "children": [ + { + "name": '"span"', + "props": ["className:sx_fff88394c2_c"], + "children": [], + } + ], + }, + { + "name": '"input"', + "props": [ + '"aria-label":"Value 1 of 3"', + "className:sx_1c26558511_c", + "defaultValue:20", + "disabled:true", + 'name:"span[]"', + 'type:"range"', + ], + "children": [], + }, + { + "name": '"input"', + "props": [ + '"aria-label":"Value 2 of 3"', + "className:sx_1c26558511_c", + "defaultValue:60", + "disabled:true", + 'name:"span[]"', + 'type:"range"', + ], + "children": [], + }, + { + "name": '"input"', + "props": [ + '"aria-label":"Value 3 of 3"', + "className:sx_1c26558511_c", + "defaultValue:90", + "disabled:true", + 'name:"span[]"', + 'type:"range"', + ], + "children": [], + }, + ], + } + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "--slider-thumb-size": "calc(var(--slider-track-size) + var(--space-1))", + "position": "relative", + "display": "flex", + "alignItems": "center", + "flexGrow": 1, + "borderRadius": "max(calc(var(--radius-factor) * var(--slider-track-size) / 3), calc(var(--radius-factor) * var(--radius-thumb)))", + "userSelect": "none", + "touchAction": "none", + "cursor": {":has(:disabled)": "var(--cursor-disabled)"}, + "mixBlendMode": { + ":has(:disabled)": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" + }, + "--slider-track-size": "calc(var(--space-2) * 1.25)", + "height": "stretch", + "flexDirection": "column", + "width": "100%", + "--rx-slider-start": "20%", + "--rx-slider-end": "90%", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "position": {"default": "relative", "::before": "absolute"}, + "flexGrow": 1, + "borderTopLeftRadius": {"default": "inherit", "::before": "inherit"}, + "borderTopRightRadius": {"default": "inherit", "::before": "inherit"}, + "borderBottomRightRadius": {"default": "inherit", "::before": "inherit"}, + "borderBottomLeftRadius": {"default": "inherit", "::before": "inherit"}, + "width": "var(--slider-track-size)", + "backgroundColor": "var(--gray-a3)", + "content": {"::before": "''"}, + "top": {"::before": "0"}, + "right": {"::before": "0"}, + "bottom": {"::before": "0"}, + "left": {"::before": "0"}, + "boxShadow": {"::before": "var(--shadow-1)"}, + "opacity": {"::before": 0.5}, + }, + { + "position": "absolute", + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "width": "100%", + "bottom": "var(--rx-slider-start)", + "top": "calc(100% - var(--rx-slider-end))", + "backgroundColor": "transparent", + "backgroundImage": "none", + "boxShadow": "none", + }, + { + "appearance": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "position": "absolute", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderRightWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderBottomWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderLeftWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderTopStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderRightStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderBottomStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderLeftStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "backgroundColor": { + "default": "transparent", + "::-webkit-slider-runnable-track": "transparent", + "::-webkit-slider-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + "::-moz-range-track": "transparent", + "::-moz-range-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + }, + "outlineStyle": "none", + "cursor": { + "default": "inherit", + "::-webkit-slider-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + "::-moz-range-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "height": { + "default": "calc(100% + var(--slider-track-size) * 0.5)", + "::-webkit-slider-runnable-track": "100%", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-track": "100%", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "width": { + "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "top": "calc(var(--slider-track-size) * -0.25)", + "left": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", + "writingMode": "vertical-lr", + "direction": "rtl", + "boxSizing": { + "::-webkit-slider-thumb": "border-box", + "::-moz-range-thumb": "border-box", + }, + "pointerEvents": { + "default": "none", + "::-webkit-slider-thumb": "auto", + "::-moz-range-thumb": "auto", + }, + "borderRadius": { + "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", + "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", + }, + "boxShadow": { + "::-webkit-slider-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + "::-moz-range-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + }, + }, + { + "appearance": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "position": "absolute", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderRightWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderBottomWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderLeftWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderTopStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderRightStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderBottomStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderLeftStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "backgroundColor": { + "default": "transparent", + "::-webkit-slider-runnable-track": "transparent", + "::-webkit-slider-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + "::-moz-range-track": "transparent", + "::-moz-range-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + }, + "outlineStyle": "none", + "cursor": { + "default": "inherit", + "::-webkit-slider-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + "::-moz-range-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "height": { + "default": "calc(100% + var(--slider-track-size) * 0.5)", + "::-webkit-slider-runnable-track": "100%", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-track": "100%", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "width": { + "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "top": "calc(var(--slider-track-size) * -0.25)", + "left": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", + "writingMode": "vertical-lr", + "direction": "rtl", + "boxSizing": { + "::-webkit-slider-thumb": "border-box", + "::-moz-range-thumb": "border-box", + }, + "pointerEvents": { + "default": "none", + "::-webkit-slider-thumb": "auto", + "::-moz-range-thumb": "auto", + }, + "borderRadius": { + "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", + "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", + }, + "boxShadow": { + "::-webkit-slider-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + "::-moz-range-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + }, + }, + { + "appearance": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "position": "absolute", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderRightWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderBottomWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderLeftWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderTopStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderRightStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderBottomStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderLeftStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "backgroundColor": { + "default": "transparent", + "::-webkit-slider-runnable-track": "transparent", + "::-webkit-slider-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + "::-moz-range-track": "transparent", + "::-moz-range-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + }, + "outlineStyle": "none", + "cursor": { + "default": "inherit", + "::-webkit-slider-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + "::-moz-range-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "height": { + "default": "calc(100% + var(--slider-track-size) * 0.5)", + "::-webkit-slider-runnable-track": "100%", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-track": "100%", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "width": { + "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "top": "calc(var(--slider-track-size) * -0.25)", + "left": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", + "writingMode": "vertical-lr", + "direction": "rtl", + "boxSizing": { + "::-webkit-slider-thumb": "border-box", + "::-moz-range-thumb": "border-box", + }, + "pointerEvents": { + "default": "none", + "::-webkit-slider-thumb": "auto", + "::-moz-range-thumb": "auto", + }, + "borderRadius": { + "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", + "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", + }, + "boxShadow": { + "::-webkit-slider-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + "::-moz-range-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-6)", + }, + }, + }, + ] + + +def test_slider_soft( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The soft variant, and the default value of a slider.""" + component = rx.ui.slider(variant="soft") + assert declared_styles(component) == [ + { + "boxSizing": "border-box", + "--slider-thumb-size": "calc(var(--slider-track-size) + var(--space-1))", + "position": "relative", + "display": "flex", + "alignItems": "center", + "flexGrow": 1, + "borderRadius": "max(calc(var(--radius-factor) * var(--slider-track-size) / 3), calc(var(--radius-factor) * var(--radius-thumb)))", + "userSelect": "none", + "touchAction": "none", + "cursor": {":has(:disabled)": "var(--cursor-disabled)"}, + "mixBlendMode": { + ":has(:disabled)": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" + }, + "--slider-track-size": "var(--space-2)", + "width": "100%", + "height": "var(--slider-track-size)", + "--rx-slider-start": "0%", + "--rx-slider-end": "50%", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "position": "relative", + "flexGrow": 1, + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "height": "var(--slider-track-size)", + "backgroundColor": "var(--gray-a4)", + "backgroundImage": "linear-gradient(var(--white-a1), var(--white-a1))", + }, + { + "position": "absolute", + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", + "height": "100%", + "left": "var(--rx-slider-start)", + "right": "calc(100% - var(--rx-slider-end))", + "backgroundColor": "var(--accent-6)", + "backgroundImage": "linear-gradient(var(--accent-a5), var(--accent-a5)), none", + }, + { + "appearance": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "position": "absolute", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderRightWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderBottomWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderLeftWidth": { + "default": "0", + "::-webkit-slider-thumb": "0", + "::-moz-range-thumb": "0", + }, + "borderTopStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderRightStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderBottomStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "borderLeftStyle": { + "default": "none", + "::-webkit-slider-thumb": "none", + "::-moz-range-thumb": "none", + }, + "backgroundColor": { + "default": "transparent", + "::-webkit-slider-runnable-track": "transparent", + "::-webkit-slider-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + "::-moz-range-track": "transparent", + "::-moz-range-thumb": { + "default": "white", + ":disabled": "var(--gray-1)", + }, + }, + "outlineStyle": "none", + "cursor": { + "default": "inherit", + "::-webkit-slider-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + "::-moz-range-thumb": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + ":disabled": "var(--cursor-disabled)", + }, + }, + "width": { + "default": "calc(100% + var(--slider-track-size) * 0.5)", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "height": { + "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-webkit-slider-runnable-track": "100%", + "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "::-moz-range-track": "100%", + "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + }, + "left": "calc(var(--slider-track-size) * -0.25)", + "top": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", + "boxSizing": { + "::-webkit-slider-thumb": "border-box", + "::-moz-range-thumb": "border-box", + }, + "pointerEvents": { + "::-webkit-slider-thumb": "auto", + "::-moz-range-thumb": "auto", + }, + "borderRadius": { + "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", + "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", + }, + "boxShadow": { + "::-webkit-slider-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-5)", + }, + "::-moz-range-thumb": { + "default": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3)", + ":focus-visible": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", + ":disabled": "0 0 0 1px var(--gray-5)", + }, + }, + }, + ] + + +def test_slider_unknown_radius(ui_plugin: UIPlugin): + """A radius a slider does not have is an error that lists the ones it has.""" + with pytest.raises(StyleError) as error: + rx.ui.slider(radius="large") + assert ( + str(error.value) + == 'rx.ui.slider: unknown radius "large". The values are "none", "small", "full".' + ) + + +def test_slider_bound_to_state(ui_plugin: UIPlugin): + """A slider bound to a list has a thumb for each value, counted in the browser, and hands the values over.""" + slider = rx.ui.slider( + value=SliderState.span, + min=SliderState.low, + on_change=SliderState.set_span, + on_value_commit=SliderState.set_span, + ) + state = ( + "tests___units___reflex_components_ui___components___test_slider" + "____slider_state" + ) + span = f"reflex___state____state__{state}.span_rx_state_" + low = f"reflex___state____state__{state}.low_rx_state_" + values = ( + 'Array.from(_e.currentTarget.querySelectorAll("input"), ' + "(input) => input.valueAsNumber)" + ) + handler = ( + '((_e) => (addEvents([(ReflexEvent("reflex___state____state.' + f'{state}.set_span", ({{ ["span"] : {values} }}), ({{ }})))], [_e], ' + "({ }))))" + ) + keys = ( + '["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", ' + '"PageUp", "PageDown"]' + ) + assert slider.render()["props"] == [ + "className:sx_d6dc3ba3e7_c", + '"data-orientation":"horizontal"', + f"onChange:{handler}", + "onInputCapture:slide", + f"onKeyUp:((event) => {{ if ({keys}.includes(event.key)) ({handler})(event); }})", + "onMouseDown:press", + f"onPointerUp:{handler}", + ( + f'style:({{ "--v0": ((((({span}?.at?.(0)) - ({low})) / ((100) - ({low})) ' + f'* 100) + "%")) ?? "initial", "--v1": ((((({span}?.at?.(-1)) - ({low})) ' + f'/ ((100) - ({low})) * 100) + "%")) ?? "initial" }})' + ), + ] + thumb = slider.children[1].children[0] + assert thumb.render()["props"] == [ + "className:sx_04c810abee_c", + "key:index_026251c31afbb080c3de6ddc69e4448c", + f"min:{low}", + 'type:"range"', + 'value:(isNotNullOrUndefined(item_rx_state_) ? item_rx_state_ : "")', + ] + + +def test_slider_script(ui_plugin: UIPlugin): + """The script of a slider follows its thumbs, and moves the nearest of several.""" + script = "$/reflex-ui/behaviors/slider.js" + assert rx.ui.slider()._get_all_imports()[script] == [ImportVar(tag="slide")] + assert rx.ui.slider(default_value=[1, 2])._get_all_imports()[script] == [ + ImportVar(tag="slide"), + ImportVar(tag="press"), + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 78d099025f2..8b40a52bd6e 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -165,6 +165,7 @@ def test_every_wave_is_in_the_namespace(): "segmented_control.root", "separator", "skeleton", + "slider", "spacer", "spinner", "stack", From 89469e4681bdb6dce4129541c37f90ac8177b90d Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 03:33:52 +0000 Subject: [PATCH 077/204] Add rx.ui.select on a native popover The select is a button with a popovertarget and a popover of options the browser opens, closes, places beside the trigger with CSS anchor positioning and dismisses. A script follows the value: the keys that move through the options, typing to find one, and an input that holds the value for a form. styles/popup.py and behaviors/popup.js are the popup the later waves reuse; a browser without anchor positioning loads popup-position.js on demand. The parity harness gains Matrix.ready: a condition a page meets before it is read, for a reference that goes on rendering after hydration. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- packages/reflex-components-ui/js/src/base.css | 12 + .../js/src/behaviors/listbox.js | 280 +++ .../js/src/behaviors/popup-position.js | 49 + .../js/src/behaviors/popup.js | 64 + .../js/tests/behaviors/listbox.test.js | 452 +++++ .../js/tests/behaviors/popover.js | 35 + .../js/tests/behaviors/popup-position.test.js | 94 + .../js/tests/behaviors/popup.test.js | 116 ++ .../parity/allowlist.toml | 38 + .../parity/ui_parity/components/select.py | 670 +++++++ .../parity/ui_parity/look.py | 2 + .../parity/ui_parity/matrix.py | 3 + .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/select.py | 1172 ++++++++++++ .../src/reflex_components_ui/styles/popup.py | 131 ++ .../src/reflex_components_ui/styles/select.py | 486 +++++ .../components/test_select.py | 1581 +++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 8 + 18 files changed, 5194 insertions(+) create mode 100644 packages/reflex-components-ui/js/src/behaviors/listbox.js create mode 100644 packages/reflex-components-ui/js/src/behaviors/popup-position.js create mode 100644 packages/reflex-components-ui/js/src/behaviors/popup.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/listbox.test.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/popover.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/popup.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/select.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/select.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/select.py create mode 100644 tests/units/reflex_components_ui/components/test_select.py diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index b7a1cd2f6dd..cbceaec825d 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -106,6 +106,18 @@ html.dark { flex-shrink: 0; } + /* + * A popup leaves the top layer when it has faded out, not before, and + * the label of a group of options keeps its distance from the option + * before it. + */ + [data-rx-popup] { + transition-behavior: allow-discrete; + } + [role="option"] + [data-rx-select-label] { + margin-top: var(--space-2); + } + /* The thumb of the scrollbar of a text area, under the pointer. */ @media (hover: hover) { [data-rx-text-area-input]:not(:disabled)::-webkit-scrollbar-thumb:hover { diff --git a/packages/reflex-components-ui/js/src/behaviors/listbox.js b/packages/reflex-components-ui/js/src/behaviors/listbox.js new file mode 100644 index 00000000000..2ef7b0e3027 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/listbox.js @@ -0,0 +1,280 @@ +// What a select does that the browser leaves to a script: the keys that +// move through its options, typing to find one, and the value it keeps. +// +// The list is a popup the browser opens, closes and places. The value is +// the one of a text input no one sees, so a form submits it, a required +// select holds its form back, and React hears of a change as it does of +// any input. Without this the select opens and closes, and chooses nothing. + +import { opener, pair, popupToggle } from "./popup.js"; + +const OPTION = "[role=option]"; +const ENABLED = `${OPTION}:not([aria-disabled=true])`; + +/** What was typed to find an option, and when it is forgotten. */ +let typed = ""; +let forgetting = 0; + +/** + * Find the parts of a select. + * + * @param {Element} select The element around the select. + * @returns {{ trigger: HTMLElement | null, popup: HTMLElement | null, holder: HTMLInputElement | null }} + * What opens the list, the list, and the input that holds the value. + */ +function parts(select) { + return { + trigger: select.querySelector("[role=combobox]"), + popup: select.querySelector("[popover]"), + holder: select.querySelector("input[data-rx-select-value]"), + }; +} + +/** + * Read the text an option shows. + * + * @param {Element} option The option. + * @returns {string} Its text, without what marks it as chosen. + */ +function textOf(option) { + return (option.querySelector("[data-rx-select-text]") ?? option).textContent ?? ""; +} + +/** + * Show the value of a select on its options and on what opens it: the + * `ref` of the input that holds the value, called again whenever the page + * renders. + * + * The chosen option says so, and its text is the text of the trigger, or + * the placeholder when nothing is chosen. A select bound to state takes its + * value, and whether it is open, from there. + * + * @param {Element | null} holder The input that holds the value. + * @param {string | null} [value] The value of a select bound to state. + * @param {boolean | null} [open] Whether a select bound to state is open. + * @returns {void} + */ +export function syncSelect(holder, value, open) { + const select = /** @type {HTMLElement | null | undefined} */ (holder?.closest("[data-rx-select]")); + if (!select) return; + const { trigger, popup } = parts(select); + if (!trigger || !popup || !(holder instanceof HTMLInputElement)) return; + pair(popup, trigger); + if (value !== undefined && value !== null) { + // What the select goes back to when a choice changes nothing in state. + select.dataset.rxValue = value; + if (holder.value !== value) holder.value = value; + } + show(select, trigger, holder.value); + const starts = select.getAttribute("data-default-open") === "true"; + select.removeAttribute("data-default-open"); + const wanted = open ?? (starts ? true : null); + if (wanted !== null && wanted !== popup.matches(":popover-open")) { + popup.dataset.rxClosedBy = "state"; + popup.togglePopover(wanted); + } +} + +/** + * Show a value on the options of a select and on what opens it. + * + * @param {Element} select The element around the select. + * @param {Element} trigger What opens the list. + * @param {string} current The value. + * @returns {void} + */ +function show(select, trigger, current) { + let chosen = null; + for (const option of select.querySelectorAll(OPTION)) { + const on = current !== "" && option.getAttribute("data-value") === current; + option.setAttribute("aria-selected", String(on)); + option.setAttribute("data-state", on ? "checked" : "unchecked"); + if (on) chosen ??= option; + } + const shown = trigger.querySelector("[data-rx-select-shown]"); + if (shown instanceof HTMLElement) { + const text = chosen ? textOf(chosen) : (shown.dataset.placeholder ?? ""); + // The node React rendered keeps its place: React may write to it again. + if (shown.firstChild) shown.firstChild.nodeValue = text; + else shown.textContent = text; + trigger.toggleAttribute("data-placeholder", !chosen); + } +} + +/** + * Choose an option: the list closes, and the value changes if it differs. + * + * @param {Element} select The element around the select. + * @param {Element} option The option. + * @returns {void} + */ +function choose(select, option) { + const { trigger, popup, holder } = parts(select); + const value = option.getAttribute("data-value") ?? ""; + if (popup?.matches(":popover-open")) { + popup.dataset.rxClosedBy = "choice"; + popup.hidePopover(); + } + if (!trigger || !holder || holder.value === value) return; + const setter = /** @type {(this: HTMLInputElement, value: string) => void} */ ( + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set + ); + setter.call(holder, value); + // As a user types it, so that React hears of it. + holder.dispatchEvent(new Event("input", { bubbles: true })); + // A select bound to state shows the value of the state, which follows or + // does not. + const bound = /** @type {HTMLElement} */ (select).dataset.rxValue; + if (bound !== undefined) holder.value = bound; + show(select, trigger, holder.value); +} + +/** + * Find the option that what was typed leads to. + * + * Typing one letter again goes through the options that start with it. + * + * @param {HTMLElement[]} options The options that can be chosen. + * @param {string} key The letter typed. + * @param {Element | null} from The option to start after. + * @returns {HTMLElement | undefined} The option found. + */ +function find(options, key, from) { + clearTimeout(forgetting); + typed += key.toLowerCase(); + forgetting = Number(setTimeout(() => (typed = ""), 1000)); + const repeated = [...typed].every((letter) => letter === typed[0]); + const search = repeated ? typed[0] : typed; + const start = options.indexOf(/** @type {HTMLElement} */ (from)); + const order = [...options.slice(start + 1), ...options.slice(0, start + 1)]; + if (!repeated && from && textOf(from).trim().toLowerCase().startsWith(search)) { + return /** @type {HTMLElement} */ (from); + } + return order.find((option) => textOf(option).trim().toLowerCase().startsWith(search)); +} + +/** + * The keys of a select: the `onKeyDown` of the element around it. + * + * On the trigger the arrow keys open the list, and a letter chooses the + * next option that starts with what is typed. In the list the arrow keys, + * Home and End move through the options, a letter goes to one, Enter and + * Space choose, and Tab stays. + * + * @param {{ key: string, target: EventTarget | null, currentTarget: Element, preventDefault: () => void, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean }} event + * The key going down inside the select. + * @returns {void} + */ +export function selectKeyDown(event) { + const select = event.currentTarget; + const { trigger, popup, holder } = parts(select); + if (!trigger || !popup || !holder) return; + const { key } = event; + if (key === "Escape") popup.dataset.rxClosedBy = "escape"; + const options = /** @type {HTMLElement[]} */ ([...select.querySelectorAll(ENABLED)]); + const letter = key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey; + if (!popup.matches(":popover-open")) { + if (event.target !== trigger || trigger.matches(":disabled")) return; + if (key === "ArrowDown" || key === "ArrowUp") { + event.preventDefault(); + trigger.click(); + } else if (letter && (key !== " " || typed)) { + event.preventDefault(); + const current = options.find((option) => option.dataset.value === holder.value); + const found = find(options, key, current ?? null); + if (found) choose(select, found); + } + return; + } + const at = options.indexOf(/** @type {HTMLElement} */ (document.activeElement)); + /** @type {HTMLElement | undefined} */ + let next; + if (key === "ArrowDown") next = options[Math.min(at + 1, options.length - 1)]; + else if (key === "ArrowUp") next = options[Math.max(at - 1, 0)]; + else if (key === "Home") next = options[0]; + else if (key === "End") next = options[options.length - 1]; + else if (key === "Enter" || (key === " " && !typed)) { + event.preventDefault(); + if (at >= 0) choose(select, options[at]); + return; + } else if (key === "Tab") { + event.preventDefault(); + return; + } else if (letter) next = find(options, key, options[at] ?? null); + else return; + event.preventDefault(); + next?.focus(); +} + +/** + * Choose the option under the pointer: the `onClick` of the element around + * a select. + * + * @param {{ target: EventTarget | null, currentTarget: Element }} event The click. + * @returns {void} + */ +export function selectClick(event) { + const option = event.target instanceof Element ? event.target.closest(ENABLED) : null; + if (option) choose(event.currentTarget, option); +} + +/** + * Give the option under the pointer the focus, which is what marks it: the + * `onPointerMove` of the element around a select. + * + * @param {{ target: EventTarget | null, currentTarget: Element }} event The pointer moving. + * @returns {void} + */ +export function selectPointerMove(event) { + const target = event.target instanceof Element ? event.target : null; + const option = target?.closest(ENABLED); + if (option instanceof HTMLElement) { + if (option !== document.activeElement) option.focus({ preventScroll: true }); + } else if (target?.closest("[popover]")) { + parts(event.currentTarget).popup?.focus({ preventScroll: true }); + } +} + +/** + * Follow the list of a select that opens or closes: the `onToggle` of its + * popover. + * + * The chosen option takes the focus when the list opens, or the first one, + * and the trigger has it back when the list closes. + * + * @param {{ currentTarget: HTMLElement, newState?: string }} event The toggle. + * @param {{ open?: (open: boolean) => void, close?: () => void, escape?: () => void, outside?: () => void }} [on] + * What the select does when its list opens or closes, when it has closed, + * and when Escape or a pointer outside the list closed it. + * @returns {void} + */ +export function selectToggle(event, on) { + const popup = event.currentTarget; + const open = popupToggle(event); + const by = popup.dataset.rxClosedBy; + delete popup.dataset.rxClosedBy; + typed = ""; + on?.open?.(open); + if (open) { + const options = /** @type {HTMLElement[]} */ ([...popup.querySelectorAll(ENABLED)]); + (options.find((option) => option.getAttribute("aria-selected") === "true") ?? options[0] ?? popup).focus(); + return; + } + if (popup.contains(document.activeElement)) /** @type {HTMLElement | null} */ (opener(popup))?.focus(); + if (by === "escape") on?.escape?.(); + else if (!by) on?.outside?.(); + on?.close?.(); +} + +/** + * Hand the focus the input of the value is given to the trigger: the + * `onFocus` of the input, which a form gives the focus when it is required + * and empty. + * + * @param {{ currentTarget: Element }} event The focus. + * @returns {void} + */ +export function selectFocus(event) { + const select = event.currentTarget.closest("[data-rx-select]"); + if (select) parts(select).trigger?.focus(); +} diff --git a/packages/reflex-components-ui/js/src/behaviors/popup-position.js b/packages/reflex-components-ui/js/src/behaviors/popup-position.js new file mode 100644 index 00000000000..d39396d24a6 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/popup-position.js @@ -0,0 +1,49 @@ +// Where a popup goes in a browser without CSS anchor positioning: loaded on +// demand, only there. +// +// The popup is placed below what opens it, at its start, at least as wide, +// and above it where there is more room and it would leave the viewport. + +/** @type {WeakMap void>} */ +const following = new WeakMap(); + +/** The room kept between a popup and the edge of the viewport, in pixels. */ +const EDGE = 10; + +/** + * Place a popup beside its anchor, and keep it there while it is open. + * + * @param {HTMLElement} popup The popover. + * @param {Element} anchor What opens it. + * @param {boolean} open Whether the popup is open. + * @returns {void} + */ +export function place(popup, anchor, open) { + following.get(popup)?.(); + following.delete(popup); + if (!open) return; + const gap = Number.parseFloat(getComputedStyle(popup).marginTop) || 0; + const update = () => { + const box = anchor.getBoundingClientRect(); + const below = innerHeight - box.bottom - gap - EDGE; + const above = box.top - gap - EDGE; + const height = popup.offsetHeight; + const over = height > below && above > below; + const style = popup.style; + style.position = "fixed"; + style.inset = "auto"; + style.minWidth = `${box.width}px`; + style.maxHeight = `${Math.max(over ? above : below, 0)}px`; + style.left = `${Math.max(Math.min(box.left, innerWidth - popup.offsetWidth - EDGE), EDGE)}px`; + style.top = over + ? `${box.top - Math.min(height, above) - gap * 2}px` + : `${box.bottom}px`; + }; + update(); + addEventListener("scroll", update, true); + addEventListener("resize", update); + following.set(popup, () => { + removeEventListener("scroll", update, true); + removeEventListener("resize", update); + }); +} diff --git a/packages/reflex-components-ui/js/src/behaviors/popup.js b/packages/reflex-components-ui/js/src/behaviors/popup.js new file mode 100644 index 00000000000..4238453a453 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/popup.js @@ -0,0 +1,64 @@ +// A popup: a native popover placed beside the element that opens it. +// +// The browser opens it from its `popovertarget`, puts it over everything +// else, closes it on Escape and on a pointer outside it, and gives the +// focus back. CSS places it against its anchor and turns it over where it +// would leave the viewport. What is left for a script is to say on the +// element that opens it that it is open, and to place it where the browser +// has no anchor positioning: that part is loaded only there. + +/** Whether the browser places a popover beside its anchor by itself. */ +const ANCHORED = globalThis.CSS?.supports?.("position-area: bottom") ?? false; + +let ids = 0; + +/** + * Find what opens a popup. + * + * @param {Element} popup The popover. + * @returns {Element | null} The first element whose `popovertarget` it is. + */ +export function opener(popup) { + return popup.id ? document.querySelector(`[popovertarget="${popup.id}"]`) : null; +} + +/** + * Give a popup and what opens it an id no other popup of the page has. + * + * A page renders one id for each popup written, so the popups a loop + * renders share one: the first sync of each makes them distinct. + * + * @param {Element} popup The popover. + * @param {Element | null} trigger What opens it. + * @returns {void} + */ +export function pair(popup, trigger) { + if (!trigger || popup.hasAttribute("data-rx-popup-paired")) return; + popup.id = `${popup.id || "rx-popup"}-${++ids}`; + popup.setAttribute("data-rx-popup-paired", ""); + trigger.setAttribute("popovertarget", popup.id); + trigger.setAttribute("aria-controls", popup.id); +} + +/** + * Follow a popup that opens or closes: the `onToggle` of the popover. + * + * What opens it says so in `aria-expanded` and `data-state`, for styles and + * for assistive technology. + * + * @param {{ currentTarget: HTMLElement, newState?: string }} event The toggle. + * @returns {boolean} Whether the popup is open now. + */ +export function popupToggle(event) { + const popup = event.currentTarget; + const open = event.newState === "open"; + const trigger = opener(popup); + if (trigger) { + trigger.setAttribute("aria-expanded", String(open)); + trigger.setAttribute("data-state", open ? "open" : "closed"); + } + if (!ANCHORED && trigger) { + import("./popup-position.js").then(({ place }) => place(popup, trigger, open)); + } + return open; +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js b/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js new file mode 100644 index 00000000000..0331e4d6286 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js @@ -0,0 +1,452 @@ +// What a select does with its options: the value it keeps and shows, the +// keys that move through the list, and what it says when the list closes. +import { beforeAll, beforeEach, expect, test, vi } from "vitest"; + +import { + selectClick, + selectFocus, + selectKeyDown, + selectPointerMove, + selectToggle, + syncSelect, +} from "$/reflex-ui/behaviors/listbox.js"; + +import { installPopover } from "./popover.js"; + +const OPTIONS = [ + ["apple", "Apple"], + ["apricot", "Apricot"], + ["banana", "Banana"], + ["cherry", "Cherry"], +]; + +/** @type {HTMLElement} */ +let select; +/** @type {HTMLElement} */ +let trigger; +/** @type {HTMLElement} */ +let popup; +/** @type {HTMLInputElement} */ +let holder; +/** @type {string[]} */ +let heard; + +/** + * Build a select, wired as a page wires it. + * + * @param {{ value?: string, disabled?: string, attributes?: string, id?: string }} [options] + * The value it starts with, the value of a disabled option, further + * attributes of the element around it, and the id of its popup. + * @returns {void} + */ +function build({ value = "", disabled = "", attributes = "", id = "list" } = {}) { + const container = document.createElement("div"); + container.innerHTML = ` + +
+
Fruits
+ ${OPTIONS.map( + ([option, text]) => + `
✓${text}
`, + ).join("")} +
+ +
`; + document.body.append(container); + select = /** @type {HTMLElement} */ (container.querySelector("[data-rx-select]")); + trigger = /** @type {HTMLElement} */ (select.querySelector("button")); + popup = /** @type {HTMLElement} */ (select.querySelector("[popover]")); + holder = /** @type {HTMLInputElement} */ (select.querySelector("input")); + heard = []; + // What the browser does of a button with a `popovertarget`. + trigger.addEventListener("click", () => { + if (!trigger.matches(":disabled")) popup.togglePopover(); + }); + popup.addEventListener("toggle", (event) => + selectToggle(/** @type {any} */ (event), { + open: (open) => heard.push(`open ${open}`), + close: () => heard.push("close"), + escape: () => heard.push("escape"), + outside: () => heard.push("outside"), + }), + ); + holder.addEventListener("input", () => heard.push(`change ${holder.value}`)); + syncSelect(holder); +} + +/** + * Press a key inside the select. + * + * @param {string} key The key. + * @param {Partial<{ target: Element, altKey: boolean, ctrlKey: boolean, metaKey: boolean }>} [more] + * Where, when not on what has the focus, and the modifiers held. + * @returns {boolean} Whether the select kept the key from the browser. + */ +function press(key, more = {}) { + let prevented = false; + selectKeyDown({ + key, + target: document.activeElement, + currentTarget: select, + preventDefault: () => (prevented = true), + ...more, + }); + return prevented; +} + +/** + * Find an option. + * + * @param {string} value Its value. + * @returns {HTMLElement} The option. + */ +function option(value) { + return /** @type {HTMLElement} */ (select.querySelector(`[data-value="${value}"]`)); +} + +/** + * Read what the select shows. + * + * @returns {{ value: string, shown: string | null, empty: boolean, chosen: string[], open: boolean }} + * Its value, the text and the placeholder mark of its trigger, the + * options that say they are chosen, and whether the list is open. + */ +function state() { + return { + value: holder.value, + shown: trigger.textContent, + empty: trigger.hasAttribute("data-placeholder"), + chosen: [...select.querySelectorAll('[aria-selected="true"][data-state="checked"]')].map( + (element) => element.getAttribute("data-value") ?? "", + ), + open: popup.matches(":popover-open"), + }; +} + +/** + * Read the value of the option that has the focus. + * + * @returns {string | null | undefined} Its value, or null for anything else. + */ +function focused() { + return document.activeElement?.getAttribute("data-value"); +} + +beforeAll(installPopover); + +beforeEach(() => { + document.body.innerHTML = ""; + vi.useRealTimers(); +}); + +test("a select without a value shows its placeholder, and every option unchosen", () => { + build(); + + expect(state()).toEqual({ value: "", shown: "Pick", empty: true, chosen: [], open: false }); + expect( + [...select.querySelectorAll("[role=option]")].map((element) => [ + element.getAttribute("aria-selected"), + element.getAttribute("data-state"), + ]), + ).toEqual(OPTIONS.map(() => ["false", "unchecked"])); +}); + +test("a select with a value shows the text of its option", () => { + build({ value: "banana" }); + + expect(state()).toEqual({ + value: "banana", + shown: "Banana", + empty: false, + chosen: ["banana"], + open: false, + }); +}); + +test("a value no option has shows the placeholder", () => { + build({ value: "kiwi" }); + + expect(state()).toEqual({ value: "kiwi", shown: "Pick", empty: true, chosen: [], open: false }); +}); + +test("a trigger without the element that shows the value is left as it is", () => { + build({ value: "banana" }); + trigger.innerHTML = "Custom"; + syncSelect(holder); + + expect(trigger.outerHTML).toBe( + ``, + ); +}); + +test("an empty element that shows the value is given the text", () => { + build(); + /** @type {HTMLElement} */ (trigger.firstElementChild).textContent = ""; + holder.value = "cherry"; + syncSelect(holder); + + expect(trigger.textContent).toBe("Cherry"); +}); + +test("nothing is done for what is not a select", () => { + build(); + const before = document.body.innerHTML; + syncSelect(null); + syncSelect(document.body); + trigger.remove(); + syncSelect(holder); + press("ArrowDown"); + + expect(document.body.innerHTML).toBe(before.replace(//, "")); +}); + +test("opening gives the focus to the chosen option, or to the first", () => { + build({ value: "banana" }); + trigger.click(); + expect([state().open, focused(), heard]).toEqual([true, "banana", ["open true"]]); + expect([trigger.getAttribute("aria-expanded"), trigger.getAttribute("data-state")]).toEqual(["true", "open"]); + + build({ disabled: "apple" }); + trigger.click(); + expect(focused()).toBe("apricot"); +}); + +test("a list without options takes the focus itself", () => { + build(); + for (const element of select.querySelectorAll("[role=option]")) element.remove(); + trigger.click(); + + expect(document.activeElement).toBe(popup); +}); + +test("the arrow keys open the list from the trigger", () => { + build(); + trigger.focus(); + expect([press("ArrowDown"), state().open, focused()]).toEqual([true, true, "apple"]); + popup.hidePopover(); + expect([press("ArrowUp"), state().open]).toEqual([true, true]); +}); + +test("a key on anything but the trigger of a closed select is left alone", () => { + build(); + expect([press("ArrowDown", { target: holder }), state().open]).toEqual([false, false]); + trigger.setAttribute("disabled", ""); + expect([press("ArrowDown", { target: trigger }), state().open]).toEqual([false, false]); + expect([press("Enter", { target: trigger }), state().open]).toEqual([false, false]); +}); + +test("the arrow keys, Home and End move through the options that can be chosen", () => { + build({ disabled: "apricot" }); + trigger.click(); + const moves = ["ArrowDown", "ArrowDown", "ArrowDown", "ArrowUp", "Home", "ArrowUp", "End"].map((key) => [ + key, + press(key), + focused(), + ]); + + expect(moves).toEqual([ + ["ArrowDown", true, "banana"], + ["ArrowDown", true, "cherry"], + ["ArrowDown", true, "cherry"], + ["ArrowUp", true, "banana"], + ["Home", true, "apple"], + ["ArrowUp", true, "apple"], + ["End", true, "cherry"], + ]); +}); + +test("Tab stays in an open list, and other keys are left to the browser", () => { + build(); + trigger.click(); + + expect([press("Tab"), focused(), state().open]).toEqual([true, "apple", true]); + expect([press("Shift"), press("a", { ctrlKey: true }), focused()]).toEqual([false, false, "apple"]); +}); + +test("Enter and Space choose the option that has the focus", () => { + build(); + trigger.click(); + press("ArrowDown"); + expect(press("Enter")).toBe(true); + expect(state()).toEqual({ + value: "apricot", + shown: "Apricot", + empty: false, + chosen: ["apricot"], + open: false, + }); + expect(heard).toEqual(["open true", "open false", "close", "change apricot"]); + expect(document.activeElement).toBe(trigger); + + trigger.click(); + press("End"); + expect(press(" ")).toBe(true); + expect([state().value, heard.slice(4)]).toEqual([ + "cherry", + ["open true", "open false", "close", "change cherry"], + ]); +}); + +test("Enter with the focus on the list itself chooses nothing", () => { + build(); + trigger.click(); + popup.focus(); + + expect([press("Enter"), state().value, state().open]).toEqual([true, "", true]); +}); + +test("choosing the chosen option closes the list and changes nothing", () => { + build({ value: "banana" }); + trigger.click(); + selectClick({ target: option("banana").lastElementChild, currentTarget: select }); + + expect([state().value, state().open, heard]).toEqual(["banana", false, ["open true", "open false", "close"]]); +}); + +test("a click chooses an option, and nothing anywhere else or on a disabled one", () => { + build({ disabled: "banana" }); + trigger.click(); + selectClick({ target: option("banana"), currentTarget: select }); + selectClick({ target: popup, currentTarget: select }); + selectClick({ target: null, currentTarget: select }); + expect([state().value, state().open]).toEqual(["", true]); + + selectClick({ target: option("cherry").lastElementChild, currentTarget: select }); + expect([state().value, state().shown, state().open]).toEqual(["cherry", "Cherry", false]); +}); + +test("typing in the list goes to the option that starts with it", () => { + vi.useFakeTimers(); + build(); + trigger.click(); + + expect([press("b"), focused()]).toEqual([true, "banana"]); + vi.advanceTimersByTime(1000); + // One letter again goes through the options that start with it. + expect([press("a"), focused()]).toEqual([true, "apple"]); + expect([press("a"), focused()]).toEqual([true, "apricot"]); + expect([press("a"), focused()]).toEqual([true, "apple"]); + vi.advanceTimersByTime(1000); + // Several letters are a search, which stays where it matches. + expect([press("a"), press("p"), press("r"), focused()]).toEqual([true, true, true, "apricot"]); + // A space is part of what is typed, and chooses nothing. + expect([press(" "), state().open, state().value]).toEqual([true, true, ""]); + vi.advanceTimersByTime(1000); + expect([press("z"), focused()]).toEqual([true, "apricot"]); + vi.advanceTimersByTime(1000); +}); + +test("typing on the trigger chooses the next option that starts with it", () => { + vi.useFakeTimers(); + build({ value: "apple" }); + trigger.focus(); + + expect([press("a"), state().value, state().open]).toEqual([true, "apricot", false]); + vi.advanceTimersByTime(1000); + expect([press("c"), state().value]).toEqual([true, "cherry"]); + vi.advanceTimersByTime(1000); + expect([press("z"), state().value]).toEqual([true, "cherry"]); + vi.advanceTimersByTime(1000); + // Space is left to the button, which it opens. + expect(press(" ")).toBe(false); + expect(heard).toEqual(["change apricot", "change cherry"]); +}); + +test("the pointer gives the option under it the focus, and the list between options", () => { + build({ disabled: "banana" }); + trigger.click(); + selectPointerMove({ target: option("cherry").lastElementChild, currentTarget: select }); + expect(focused()).toBe("cherry"); + selectPointerMove({ target: option("cherry"), currentTarget: select }); + expect(focused()).toBe("cherry"); + + selectPointerMove({ target: option("banana"), currentTarget: select }); + expect(document.activeElement).toBe(popup); + selectPointerMove({ target: trigger, currentTarget: select }); + selectPointerMove({ target: null, currentTarget: select }); + expect(document.activeElement).toBe(popup); +}); + +test("a list says what closed it", () => { + build(); + trigger.click(); + press("Escape"); + popup.hidePopover(); + expect(heard).toEqual(["open true", "open false", "escape", "close"]); + expect(document.activeElement).toBe(trigger); + + heard.length = 0; + trigger.click(); + /** @type {HTMLElement} */ (document.activeElement).blur(); + popup.hidePopover(); + expect(heard).toEqual(["open true", "open false", "outside", "close"]); + expect(document.activeElement).toBe(document.body); +}); + +test("a list without anything to call is followed all the same", () => { + build(); + selectToggle({ currentTarget: popup, newState: "open" }); + expect(focused()).toBe("apple"); + selectToggle({ currentTarget: popup, newState: "closed" }); + expect(document.activeElement).toBe(trigger); +}); + +test("a select bound to state takes its value and whether it is open from there", () => { + build(); + syncSelect(holder, "banana", true); + expect(state()).toEqual({ + value: "banana", + shown: "Banana", + empty: false, + chosen: ["banana"], + open: true, + }); + + syncSelect(holder, "banana", true); + syncSelect(holder, "cherry", false); + expect([state().value, state().open, heard]).toEqual([ + "cherry", + false, + ["open true", "open false", "close"], + ]); +}); + +test("a choice the state does not follow leaves the select as it was", () => { + build(); + syncSelect(holder, "banana", null); + trigger.click(); + selectClick({ target: option("cherry"), currentTarget: select }); + expect([state().value, state().shown, state().chosen, heard]).toEqual([ + "banana", + "Banana", + ["banana"], + ["open true", "open false", "close", "change cherry"], + ]); + + syncSelect(holder, "cherry", null); + expect([state().value, state().shown]).toEqual(["cherry", "Cherry"]); +}); + +test("a select that starts open opens once", () => { + build({ attributes: 'data-default-open="true"' }); + expect([state().open, select.hasAttribute("data-default-open")]).toEqual([true, false]); + + popup.hidePopover(); + syncSelect(holder); + expect(state().open).toBe(false); + + build({ attributes: 'data-default-open="false"' }); + expect(state().open).toBe(false); +}); + +test("the input of the value hands the focus it is given to the trigger", () => { + build(); + holder.focus(); + selectFocus({ currentTarget: holder }); + expect(document.activeElement).toBe(trigger); + + document.body.append(holder); + holder.focus(); + selectFocus({ currentTarget: holder }); + expect(document.activeElement).toBe(holder); +}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/popover.js b/packages/reflex-components-ui/js/tests/behaviors/popover.js new file mode 100644 index 00000000000..e454a6ea080 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/popover.js @@ -0,0 +1,35 @@ +// What jsdom has of a popover: nothing. This gives an element the methods +// the scripts call and the pseudo-class they ask for, and the toggle event +// the browser sends, sent at once. + +/** @type {WeakSet} */ +const open = new WeakSet(); + +const matches = Element.prototype.matches; + +/** + * Give every element the popover methods, as a browser has them. + * + * @returns {void} + */ +export function installPopover() { + Element.prototype.matches = function (/** @type {string} */ selector) { + return selector === ":popover-open" ? open.has(this) : matches.call(this, selector); + }; + HTMLElement.prototype.togglePopover = function (/** @type {unknown} */ force) { + const next = typeof force === "boolean" ? force : !open.has(this); + if (next === open.has(this)) return next; + if (next) open.add(this); + else open.delete(this); + const event = new Event("toggle"); + Object.assign(event, { newState: next ? "open" : "closed" }); + this.dispatchEvent(event); + return next; + }; + HTMLElement.prototype.showPopover = function () { + this.togglePopover(true); + }; + HTMLElement.prototype.hidePopover = function () { + this.togglePopover(false); + }; +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js new file mode 100644 index 00000000000..04bd4f6f304 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js @@ -0,0 +1,94 @@ +// Where a popup goes in a browser without CSS anchor positioning. +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { place } from "$/reflex-ui/behaviors/popup-position.js"; + +/** @type {HTMLElement} */ +let popup; +/** @type {HTMLElement} */ +let anchor; +/** @type {{ left: number, top: number, bottom: number, width: number }} */ +let box; + +/** + * Read where the popup was put. + * + * @returns {string[]} Its left, top, least width and greatest height. + */ +function placed() { + const { left, top, minWidth, maxHeight } = popup.style; + return [left, top, minWidth, maxHeight]; +} + +beforeEach(() => { + document.body.innerHTML = `
`; + anchor = /** @type {HTMLElement} */ (document.querySelector("button")); + popup = /** @type {HTMLElement} */ (document.querySelector("[popover]")); + box = { left: 40, top: 100, bottom: 132, width: 120 }; + anchor.getBoundingClientRect = () => /** @type {DOMRect} */ (box); + Object.defineProperty(popup, "offsetHeight", { value: 200, configurable: true }); + Object.defineProperty(popup, "offsetWidth", { value: 160, configurable: true }); + vi.stubGlobal("innerWidth", 800); + vi.stubGlobal("innerHeight", 600); +}); + +afterEach(() => { + place(popup, anchor, false); + vi.unstubAllGlobals(); +}); + +test("the popup goes below its anchor, at its start and at least as wide", () => { + place(popup, anchor, true); + + expect(placed()).toEqual(["40px", "132px", "120px", "454px"]); + expect([popup.style.position, popup.style.inset]).toEqual(["fixed", "auto"]); +}); + +test("it goes above where there is more room and it would leave the viewport", () => { + box = { left: 40, top: 460, bottom: 492, width: 120 }; + place(popup, anchor, true); + + expect(placed()).toEqual(["40px", "252px", "120px", "446px"]); +}); + +test("a popup taller than the room above is as tall as the room", () => { + box = { left: 40, top: 300, bottom: 532, width: 120 }; + Object.defineProperty(popup, "offsetHeight", { value: 400 }); + place(popup, anchor, true); + + expect(placed()).toEqual(["40px", "6px", "120px", "286px"]); +}); + +test("it stays inside the viewport at both ends", () => { + box = { left: 700, top: 100, bottom: 132, width: 120 }; + place(popup, anchor, true); + expect(placed()).toEqual(["630px", "132px", "120px", "454px"]); + + box = { left: -30, top: 100, bottom: 132, width: 120 }; + place(popup, anchor, true); + expect(placed()).toEqual(["10px", "132px", "120px", "454px"]); +}); + +test("it follows its anchor while it is open, and no longer", () => { + place(popup, anchor, true); + box = { left: 60, top: 80, bottom: 112, width: 120 }; + window.dispatchEvent(new Event("scroll")); + expect(placed()).toEqual(["60px", "112px", "120px", "474px"]); + + box = { left: 80, top: 80, bottom: 112, width: 140 }; + window.dispatchEvent(new Event("resize")); + expect(placed()).toEqual(["80px", "112px", "140px", "474px"]); + + place(popup, anchor, false); + box = { left: 0, top: 0, bottom: 32, width: 10 }; + window.dispatchEvent(new Event("scroll")); + window.dispatchEvent(new Event("resize")); + expect(placed()).toEqual(["80px", "112px", "140px", "474px"]); +}); + +test("a popup without a margin has no gap", () => { + popup.style.marginTop = ""; + place(popup, anchor, true); + + expect(placed()).toEqual(["40px", "132px", "120px", "458px"]); +}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js new file mode 100644 index 00000000000..2d0e28bccd9 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js @@ -0,0 +1,116 @@ +// What a popup says on the element that opens it, and where it goes in a +// browser that does not place it. +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +/** + * Build a button and the popup it opens. + * + * @param {string} [id] The id of the popup. + * @returns {{ trigger: HTMLElement, popup: HTMLElement }} The two. + */ +function build(id = "list") { + document.body.innerHTML = `
`; + return { + trigger: /** @type {HTMLElement} */ (document.querySelector("button")), + popup: /** @type {HTMLElement} */ (document.querySelector("[popover]")), + }; +} + +/** + * Send a popup the toggle the browser sends. + * + * @param {(event: { currentTarget: HTMLElement, newState?: string }) => boolean} popupToggle The script. + * @param {HTMLElement} popup The popup. + * @param {string} newState What it is now. + * @returns {boolean} What the script answers. + */ +function toggle(popupToggle, popup, newState) { + return popupToggle({ currentTarget: popup, newState }); +} + +/** + * Read what a trigger says of its popup. + * + * @param {HTMLElement} trigger The trigger. + * @returns {(string | null)[]} Its `aria-expanded` and its `data-state`. + */ +function said(trigger) { + return [trigger.getAttribute("aria-expanded"), trigger.getAttribute("data-state")]; +} + +beforeEach(() => { + vi.resetModules(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +test("the trigger says whether its popup is open, and the browser places it", async () => { + vi.stubGlobal("CSS", { supports: (/** @type {string} */ rule) => rule === "position-area: bottom" }); + const { popupToggle } = await import("$/reflex-ui/behaviors/popup.js"); + const { trigger, popup } = build(); + + expect(toggle(popupToggle, popup, "open")).toBe(true); + expect(said(trigger)).toEqual(["true", "open"]); + expect(toggle(popupToggle, popup, "closed")).toBe(false); + expect(said(trigger)).toEqual(["false", "closed"]); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(popup.getAttribute("style")).toBe(null); +}); + +test("a popup nothing opens is followed without a trigger", async () => { + const { popupToggle, opener } = await import("$/reflex-ui/behaviors/popup.js"); + document.body.innerHTML = `
`; + const [alone, unnamed] = /** @type {HTMLElement[]} */ ([...document.querySelectorAll("[popover]")]); + + expect(opener(alone)).toBe(null); + expect(opener(unnamed)).toBe(null); + expect(toggle(popupToggle, alone, "open")).toBe(true); +}); + +test("the popups a loop renders with one id are told apart", async () => { + const { opener, pair } = await import("$/reflex-ui/behaviors/popup.js"); + document.body.innerHTML = [1, 2] + .map(() => `
`) + .join(""); + const spans = [...document.querySelectorAll("span")]; + for (const span of spans) { + pair(/** @type {Element} */ (span.querySelector("[popover]")), span.querySelector("button")); + } + // A second sync of the first changes nothing. + pair(/** @type {Element} */ (spans[0].querySelector("[popover]")), spans[0].querySelector("button")); + pair(/** @type {Element} */ (spans[1].querySelector("[popover]")), null); + + expect( + spans.map((span) => [ + span.querySelector("[popover]")?.id, + span.querySelector("button")?.getAttribute("popovertarget"), + span.querySelector("button")?.getAttribute("aria-controls"), + ]), + ).toEqual([ + ["list-1", "list-1", "list-1"], + ["list-2", "list-2", "list-2"], + ]); + expect(opener(/** @type {Element} */ (spans[1].querySelector("[popover]")))).toBe( + spans[1].querySelector("button"), + ); +}); + +test("a browser without anchor positioning has the popup placed by a script", async () => { + const { popupToggle } = await import("$/reflex-ui/behaviors/popup.js"); + const { trigger, popup } = build(); + vi.stubGlobal("innerWidth", 800); + vi.stubGlobal("innerHeight", 600); + trigger.getBoundingClientRect = () => + /** @type {DOMRect} */ ({ left: 40, top: 100, bottom: 132, width: 120 }); + Object.defineProperty(popup, "offsetHeight", { value: 200 }); + Object.defineProperty(popup, "offsetWidth", { value: 160 }); + popup.style.marginTop = "4px"; + + toggle(popupToggle, popup, "open"); + await vi.waitFor(() => expect(popup.style.top).toBe("132px")); + expect(popup.getAttribute("style")).toBe( + "margin-top: 4px; position: fixed; inset: auto; min-width: 120px; max-height: 454px; left: 40px; top: 132px;", + ); +}); diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 535fb1c3e00..12a766925e6 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -233,3 +233,41 @@ reason = "The thumbs of rx.ui.slider are native range inputs: the browser moves component = "slider" step = "a thumb can be moved past the one after it" reason = "A thumb of rx.ui.slider stops at the thumbs beside it, where a thumb of rx.slider passes them and the two change places. Home and End move the thumb that has the focus, where rx.slider moves the first and the last whichever has it." + +[[look]] +component = "select" +check = "style" +cells = "*@open" +properties = ["pointer-events"] +reason = "While its list is open rx.select takes the pointer off the rest of the page: nothing else can be clicked or scrolled until the list closes. The list of rx.ui.select is a native popover, which leaves the page as it is: a click outside closes the list, and the page scrolls." + +[[look]] +component = "select" +check = "pixels" +cells = "long-true*" +reason = "A list of rx.ui.select too long for the room it has scrolls natively, with the scrollbar of the browser, which may lie over the options and show only while they scroll. rx.select draws a scrollbar of its own with JavaScript, and leaves room for it beside the options." + +[[look]] +component = "select" +check = "style" +cells = "size-responsive*" +properties = ["width", "height"] +reason = "When the size of rx.select goes from \"3\" at one breakpoint to a smaller one at the next, Radix Themes keeps the larger icon size \"3\" has. The icon of rx.ui.select has the size of the select at each breakpoint, so the trigger is two pixels narrower there." + +[[contract]] +component = "select" +step = "shows the chosen option in the server render" +system = "rx" +reason = "The trigger of rx.select is empty until JavaScript has found the text of the chosen option. rx.ui.select works the text out while compiling, where the options are known or show their values, so the page the server sends shows it." + +[[contract]] +component = "select" +step = "opens and closes its list with JavaScript disabled" +system = "rx" +reason = "rx.select is opened by JavaScript: until it has run, a click on its trigger does nothing. The list of rx.ui.select is a native popover of its trigger, which the browser opens and closes with or without JavaScript; choosing an option waits for it." + +[[contract]] +component = "select" +step = "the page behind an open list takes no click" +system = "rx.ui" +reason = "While its list is open rx.select takes the pointer off the rest of the page: a click outside closes the list and does nothing else. The list of rx.ui.select is a native popover: a click outside closes it and also reaches what is under the pointer, as with a native select, and the page behind it scrolls." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/select.py b/packages/reflex-components-ui/parity/ui_parity/components/select.py new file mode 100644 index 00000000000..b80fd5c8b13 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/select.py @@ -0,0 +1,670 @@ +"""The select: every variant, size and state of its trigger, and its open list.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import ACCENTS, wait_for_text + +VARIANTS = ["surface", "classic", "soft", "ghost"] +SIZES = ["1", "2", "3"] +RADII = ["none", "small", "full"] +OPEN = "open" + +# The props of the cell that are the ones of the trigger, and of the list. +_TRIGGER = ("variant", "radius", "placeholder", "width") +_CONTENT = ("high_contrast", "side", "align", "side_offset") + + +def _select(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a select with two groups of options. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the cell: of the root, and the ones named above + of the trigger and of the list. ``look`` is the variant of the + list, and ``long`` asks for more options than the list has room + for. + + Returns: + The select: the list beside its trigger, as rx.ui places it. + """ + props = dict(props) + select = namespace.select + trigger = {key: props.pop(key) for key in _TRIGGER if key in props} + content = {key: props.pop(key) for key in _CONTENT if key in props} + if "look" in props: + content["variant"] = props.pop("look") + if "color_scheme" in props: + trigger["color_scheme"] = content["color_scheme"] = props.pop("color_scheme") + more = [ + select.item(f"Option {number}", value=f"option-{number}") + for number in range(1, 30 if props.pop("long", False) else 1) + ] + if "align" in content: + # A list that ends at the end of its trigger, or is centered on it, + # reaches before it: the trigger leaves it room, in both systems. + return rx.el.div( + _root(select, trigger, content, props, more, name="A potato"), + style={"padding_left": "70px"}, + ) + return _root(select, trigger, content, props, more) + + +def _root( + select: Any, + trigger: dict[str, Any], + content: dict[str, Any], + props: dict[str, Any], + more: list[Any], + name: str = "A potato with a long name", +) -> Any: + """Create the select of a cell. + + Args: + select: The namespace of the select. + trigger: The props of the trigger. + content: The props of the list. + props: The props of the root. + more: Further options. + name: What the option with the longest name shows. + + Returns: + The select. + """ + return select.root( + select.trigger(**trigger), + select.content( + select.group( + select.label("Fruits"), + select.item("Apple", value="apple"), + select.item("Orange", value="orange"), + select.item("Grape", value="grape", disabled=True), + ), + select.separator(), + select.group( + select.label("Vegetables"), + select.item("Carrot", value="carrot"), + select.item(name, value="potato"), + *more, + ), + position="popper", + **content, + ), + **props, + ) + + +def _open(page: Page, target: Locator, point: Point) -> None: + """Open a select with the keyboard, and wait for its list. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + target.focus() + page.keyboard.press("Enter") + page.locator("[role=listbox]:visible [role=option]").first.wait_for() + page.wait_for_function("document.activeElement.getAttribute('role') === 'option'") + + +def _close(page: Page, target: Locator, point: Point) -> None: + """Close the list of a select, and take the focus off its trigger. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + page.keyboard.press("Escape") + page.locator("[role=listbox]:visible").wait_for(state="detached") + page.evaluate("document.activeElement.blur()") + + +MATRIX = Matrix( + component="select", + render=_select, + base={"default_value": "apple"}, + cross={"variant": VARIANTS, "size": SIZES}, + sweep={ + "color_scheme": ACCENTS, + "radius": RADII, + "disabled": [True], + "default_value": {"none": None, "long": "potato"}, + "placeholder": ["Pick one"], + "width": ["90px"], + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE, OPEN], + "viewport": [520], + }, + groups=[ + { + "variant": VARIANTS, + "default_value": {"none": None}, + "placeholder": ["Pick one"], + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "disabled": [True], "appearance": [LIGHT, DARK]}, + { + "variant": VARIANTS, + "state": [HOVER, FOCUS_VISIBLE, OPEN], + "appearance": [LIGHT, DARK], + }, + {"variant": VARIANTS, "color_scheme": ["ruby", "gray", "yellow"]}, + {"radius": RADII, "size": SIZES, "variant": VARIANTS}, + { + "look": ["solid", "soft"], + "high_contrast": [False, True], + "size": SIZES, + "state": [OPEN], + "appearance": [LIGHT, DARK], + }, + { + "look": ["solid", "soft"], + "color_scheme": ["ruby", "gray", "yellow"], + "high_contrast": [False, True], + "state": [OPEN], + }, + {"default_value": {"none": None, "long": "potato"}, "state": [OPEN]}, + { + "align": ["start", "center", "end"], + "width": ["90px", "220px"], + "state": [OPEN], + }, + {"side_offset": [0, 12], "state": [OPEN]}, + {"long": [True], "size": SIZES, "state": [OPEN]}, + { + "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, + "viewport": [520, 800, 1100], + }, + ], + stage=(280, 330), + crop="stage", + target="button", + parts={"shown": "button > span", "icon": "button > svg"}, + states={ + OPEN: State(enter=_open, leave=_close, matches="[data-state='open']"), + }, + # The trigger of Radix shows nothing until JavaScript has found the text + # of the chosen option, some time after the page is hydrated. + ready=( + "[...document.querySelectorAll('[role=combobox]')].every(" + "trigger => trigger.hasAttribute('data-placeholder')" + " || trigger.textContent !== '')" + ), + # Not held to zero. At a threshold of zero 162 of the 193 cells are + # equal pixel for pixel, and the others differ by where they are on the + # page: the gradients of the classic trigger are dithered by a step of a + # channel, as the trigger of Radix is against itself at another place. + # At the default threshold 4 cells differ, by at most 213 pixels of + # 92400: a list that ends at the end of its trigger, or is centered on + # it, starts at a fraction of a pixel when its width has one, where + # Radix rounds where it puts a list, so the edges of its letters are + # anti-aliased otherwise. The tolerance also takes in the 69 pixels of + # the icon of a responsive size, which the allowlist explains by its + # computed size. + tolerance=0.003, +) + + +class SelectState(rx.State): + """What the selects of the contract are bound to.""" + + bound: str = "banana" + seen: list[str] = [] + opened: list[bool] = [] + clicks: int = 0 + submitted: dict[str, str] = {} + submissions: int = 0 + + @rx.event + def set_bound(self, value: str): + """Follow the bound select. + + Args: + value: The value it chose. + """ + self.bound = value + + @rx.event + def see(self, value: str): + """Keep what a change handed over. + + Args: + value: The chosen value. + """ + self.seen.append(value) + + @rx.event + def see_open(self, value: bool): + """Keep whether a list opened or closed. + + Args: + value: Whether it is open. + """ + self.opened.append(value) + + @rx.event + def pick_cherry(self): + """Change the bound value from outside the select.""" + self.bound = "cherry" + + @rx.event + def click(self): + """Count a click on the button beside the selects.""" + self.clicks += 1 + + @rx.event + def submit(self, data: dict[str, str]): + """Keep what a form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + self.submissions += 1 + + +def _fruits(namespace: Any, trigger: str, **props: Any) -> Any: + """Create a select of fruits. + + Args: + namespace: ``rx`` or ``rx.ui``. + trigger: The id of its trigger. + **props: The props of its root. + + Returns: + The select: one of its options is disabled, and one is outside the + group the others are in. + """ + select = namespace.select + return select.root( + select.trigger(placeholder="Pick a fruit", id=trigger), + select.content( + select.group( + select.label("Fruits"), + select.item("Apple", value="apple"), + select.item("Apricot", value="apricot"), + select.item("Banana", value="banana"), + select.item("Blueberry", value="blueberry", disabled=True), + select.item("Cherry", value="cherry"), + ), + select.separator(), + select.item("Nothing at all", value="none"), + position="popper", + ), + **props, + ) + + +CONTRACT = Contract( + component="select", + render=lambda namespace: namespace.box( + _fruits( + namespace, + "pick", + on_change=SelectState.see, + on_open_change=SelectState.see_open, + ), + _fruits(namespace, "chosen", default_value="apricot"), + _fruits( + namespace, + "bound", + value=SelectState.bound, + on_change=SelectState.set_bound, + ), + namespace.select( + ["Small", "Medium", "Large"], default_value="Medium", id="size" + ), + _fruits(namespace, "off", disabled=True), + rx.el.button("Cherry", id="cherry", on_click=SelectState.pick_cherry), + rx.el.button("Beside", id="beside", on_click=SelectState.click), + rx.el.form( + _fruits(namespace, "wanted", name="wanted", required=True), + _fruits(namespace, "given", name="given", default_value="cherry"), + rx.el.button("Send", id="send", type="submit"), + on_submit=SelectState.submit, + id="form", + ), + rx.el.span(SelectState.seen.to_string(), id="seen"), + rx.el.span(SelectState.opened.to_string(), id="opened"), + rx.el.span(SelectState.bound, id="bound-value"), + rx.el.span(SelectState.clicks.to_string(), id="clicks"), + rx.el.span(SelectState.submitted.to_string(), id="submitted"), + rx.el.span(SelectState.submissions.to_string(), id="submissions"), + ), +) + +# The list that is open, and its options. +LIST = "[role=listbox]:visible" +# The text of the option that has the focus, or of anything else that has it. +FOCUSED_OPTION = ( + "document.activeElement.getAttribute('role') === 'option'" + " ? document.activeElement.textContent : document.activeElement.id" +) + + +def _trigger(run: Run, trigger: str) -> Any: + """Find the trigger of a select. + + Args: + run: The run, on a page. + trigger: Its id. + + Returns: + The trigger. + """ + return run.page.locator(f"[id='{trigger}']") + + +def _open_list(run: Run, trigger: str, key: str = "Enter") -> None: + """Open a select with the keyboard, and wait for an option to have the focus. + + Args: + run: The run, on a page. + trigger: The id of its trigger. + key: The key that opens it. + """ + page = run.page + _trigger(run, trigger).focus() + page.keyboard.press(key) + page.locator(LIST).wait_for() + page.wait_for_function("document.activeElement.getAttribute('role') === 'option'") + + +def _wait_for_closed(run: Run) -> None: + """Wait until no list is open. + + Args: + run: The run, on a page. + """ + run.page.locator(LIST).wait_for(state="detached") + + +def _wait_for_focus(run: Run, text: str) -> None: + """Wait until an option, or another element, has the focus. + + Args: + run: The run, on a page. + text: The text of the option, or the id of the element. + """ + run.page.wait_for_function(f"text => ({FOCUSED_OPTION}) === text", arg=text) + + +def _wait_for_shown(run: Run, trigger: str, text: str) -> None: + """Wait until the trigger of a select shows a text. + + Args: + run: The run, on a page. + trigger: The id of the trigger. + text: Its whole text. + """ + wait_for_text(run.page, trigger, text) + + +@CONTRACT.step("its trigger is a button in the server render", on=SERVER) +def _server_render(run: Run) -> None: + pick = run.server.element("pick") + assert (pick.tag, pick.attributes["role"], pick.attributes["type"]) == ( + "button", + "combobox", + "button", + ) + assert pick.text == "Pick a fruit" + + +@CONTRACT.step("shows the chosen option in the server render", on=SERVER) +def _server_value(run: Run) -> None: + assert run.server.element("chosen").text == "Apricot" + assert run.server.element("size").text == "Medium" + assert run.server.element("bound").text == "Banana" + + +@CONTRACT.step("opens and closes its list with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + _trigger(run, "chosen").click() + page.locator(LIST).wait_for() + assert page.locator(LIST).get_by_role("option").all_text_contents() == [ + "Apple", + "Apricot", + "Banana", + "Blueberry", + "Cherry", + "Nothing at all", + ] + page.keyboard.press("Escape") + _wait_for_closed(run) + + +@CONTRACT.step("has the roles, the names and the states of a select") +def _role(run: Run) -> None: + page = run.page + assert page.get_by_role("combobox").count() == 7 + chosen = _trigger(run, "chosen") + assert chosen.get_attribute("aria-expanded") == "false" + assert page.get_by_role("combobox", disabled=True).count() == 1 + _open_list(run, "chosen") + assert chosen.get_attribute("aria-expanded") == "true" + assert chosen.get_attribute("aria-controls") == page.locator(LIST).get_attribute( + "id" + ) + options = page.get_by_role("listbox") + assert options.get_by_role("option", selected=True).all_text_contents() == [ + "Apricot" + ] + assert options.get_by_role("option", disabled=True).all_text_contents() == [ + "Blueberry" + ] + assert ( + options.get_by_role("group", name="Fruits").get_by_role("option").count() == 5 + ) + + +@CONTRACT.step("Enter, Space and the arrow keys open the list, on the chosen option") +def _open_keys(run: Run) -> None: + page = run.page + for key in ("Enter", "Space", "ArrowDown", "ArrowUp"): + _open_list(run, "chosen", key) + _wait_for_focus(run, "Apricot") + page.keyboard.press("Escape") + _wait_for_closed(run) + _wait_for_focus(run, "chosen") + _open_list(run, "pick") + _wait_for_focus(run, "Apple") + + +@CONTRACT.step( + "the arrow keys, Home and End move through the options that can be chosen" +) +def _move(run: Run) -> None: + page = run.page + _open_list(run, "chosen") + for key, option in ( + ("ArrowDown", "Banana"), + ("ArrowDown", "Cherry"), + ("ArrowDown", "Nothing at all"), + ("ArrowDown", "Nothing at all"), + ("ArrowUp", "Cherry"), + ("Home", "Apple"), + ("ArrowUp", "Apple"), + ("End", "Nothing at all"), + ): + page.keyboard.press(key) + _wait_for_focus(run, option) + assert _trigger(run, "chosen").text_content() == "Apricot" + + +@CONTRACT.step( + "Enter chooses the option that has the focus, and the trigger has it back" +) +def _choose(run: Run) -> None: + page = run.page + _open_list(run, "pick") + page.keyboard.press("ArrowDown") + _wait_for_focus(run, "Apricot") + page.keyboard.press("Enter") + _wait_for_closed(run) + _wait_for_shown(run, "pick", "Apricot") + _wait_for_focus(run, "pick") + wait_for_text(page, "seen", '["apricot"]') + _open_list(run, "pick") + _wait_for_focus(run, "Apricot") + assert page.get_by_role("listbox").get_by_role( + "option", selected=True + ).all_text_contents() == ["Apricot"] + page.keyboard.press("End") + _wait_for_focus(run, "Nothing at all") + page.keyboard.press("Space") + _wait_for_closed(run) + _wait_for_shown(run, "pick", "Nothing at all") + wait_for_text(page, "seen", '["apricot","none"]') + + +@CONTRACT.step("a click chooses an option, and not a disabled one") +def _click(run: Run) -> None: + page = run.page + _trigger(run, "pick").click() + page.locator(LIST).wait_for() + page.locator(LIST).get_by_role("option", name="Blueberry").click(force=True) + assert page.locator(LIST).is_visible() + page.locator(LIST).get_by_role("option", name="Cherry").click() + _wait_for_closed(run) + _wait_for_shown(run, "pick", "Cherry") + wait_for_text(page, "seen", '["cherry"]') + + +@CONTRACT.step("Escape closes the list and chooses nothing") +def _escape(run: Run) -> None: + page = run.page + _open_list(run, "chosen") + page.keyboard.press("ArrowDown") + _wait_for_focus(run, "Banana") + page.keyboard.press("Escape") + _wait_for_closed(run) + _wait_for_focus(run, "chosen") + assert _trigger(run, "chosen").text_content() == "Apricot" + assert _trigger(run, "chosen").get_attribute("aria-expanded") == "false" + + +@CONTRACT.step("Tab stays in an open list") +def _tab(run: Run) -> None: + page = run.page + _open_list(run, "chosen") + page.keyboard.press("Tab") + assert page.locator(LIST).is_visible() + assert page.evaluate(FOCUSED_OPTION) == "Apricot" + + +@CONTRACT.step("typing goes to the option that starts with what is typed") +def _type(run: Run) -> None: + page = run.page + _open_list(run, "pick") + page.keyboard.type("ch") + _wait_for_focus(run, "Cherry") + page.keyboard.press("Escape") + _wait_for_closed(run) + page.wait_for_timeout(1100) + _trigger(run, "pick").focus() + page.keyboard.type("b") + _wait_for_shown(run, "pick", "Banana") + assert not page.locator(LIST).is_visible() + wait_for_text(page, "seen", '["banana"]') + + +@CONTRACT.step("says when its list opens and closes") +def _open_change(run: Run) -> None: + page = run.page + _open_list(run, "pick") + wait_for_text(page, "opened", "[true]") + page.keyboard.press("Escape") + wait_for_text(page, "opened", "[true,false]") + + +@CONTRACT.step("a pointer outside the list closes it") +def _outside(run: Run) -> None: + page = run.page + _open_list(run, "chosen") + page.mouse.click(1000, 600) + _wait_for_closed(run) + assert _trigger(run, "chosen").text_content() == "Apricot" + + +@CONTRACT.step("the page behind an open list takes no click") +def _modal(run: Run) -> None: + page = run.page + _open_list(run, "chosen") + box = page.locator("#beside").bounding_box() + assert box is not None + page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + _wait_for_closed(run) + page.wait_for_timeout(300) + assert page.locator("#clicks").text_content() == "0" + + +@CONTRACT.step("a disabled select does not open") +def _disabled(run: Run) -> None: + page = run.page + _trigger(run, "off").click(force=True) + page.wait_for_timeout(200) + assert page.locator(LIST).count() == 0 + assert _trigger(run, "off").is_disabled() + + +@CONTRACT.step("a select bound to state shows the value of the state") +def _bound(run: Run) -> None: + page = run.page + _wait_for_shown(run, "bound", "Banana") + page.locator("#cherry").click() + _wait_for_shown(run, "bound", "Cherry") + _open_list(run, "bound") + _wait_for_focus(run, "Cherry") + page.keyboard.press("Home") + _wait_for_focus(run, "Apple") + page.keyboard.press("Enter") + wait_for_text(page, "bound-value", "apple") + _wait_for_shown(run, "bound", "Apple") + + +@CONTRACT.step("the select of a list of words shows and chooses them") +def _words(run: Run) -> None: + page = run.page + _wait_for_shown(run, "size", "Medium") + _open_list(run, "size") + assert page.locator(LIST).get_by_role("option").all_text_contents() == [ + "Small", + "Medium", + "Large", + ] + _wait_for_focus(run, "Medium") + page.keyboard.press("ArrowDown") + _wait_for_focus(run, "Large") + page.keyboard.press("Enter") + _wait_for_shown(run, "size", "Large") + + +@CONTRACT.step("a form waits for a required select, then submits each by its name") +def _form(run: Run) -> None: + page = run.page + page.locator("#send").click() + page.wait_for_timeout(300) + assert page.locator("#submissions").text_content() == "0" + _open_list(run, "wanted") + _wait_for_focus(run, "Apple") + page.keyboard.press("Enter") + _wait_for_shown(run, "wanted", "Apple") + page.locator("#send").click() + wait_for_text(page, "submissions", "1") + assert page.locator("#submitted").text_content() == ( + '{"wanted":"apple","given":"cherry"}' + ) diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py index e7466f31459..e2d355a0110 100644 --- a/packages/reflex-components-ui/parity/ui_parity/look.py +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -575,6 +575,8 @@ 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) + if self.matrix.ready is not None: + self.page.wait_for_function(self.matrix.ready) self.page.add_style_tag(content=FREEZE_CSS) if self.prepare is not None: self.prepare(self.page) diff --git a/packages/reflex-components-ui/parity/ui_parity/matrix.py b/packages/reflex-components-ui/parity/ui_parity/matrix.py index 4765d8a8cf7..9d1900084a9 100644 --- a/packages/reflex-components-ui/parity/ui_parity/matrix.py +++ b/packages/reflex-components-ui/parity/ui_parity/matrix.py @@ -202,6 +202,8 @@ class Matrix: 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``. + ready: A JavaScript expression that is true once the page is still, + for a component that goes on rendering after it is hydrated. """ component: str @@ -223,6 +225,7 @@ class Matrix: threshold: float = 0.01 tolerance: float = 0.005 states: Mapping[str, Any] = dataclasses.field(default_factory=dict) + ready: str | None = None def create(self, namespace: Any, props: Mapping[str, Any]) -> Any: """Create the component of one system for a cell. 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 6c6b069a815..e691dcee436 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -27,6 +27,7 @@ "components.segmented_control": ["segmented_control"], "components.separator": ["divider", "separator"], "components.skeleton": ["skeleton"], + "components.select": ["select"], "components.slider": ["slider"], "components.spinner": ["spinner"], "components.switch": ["switch"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/select.py b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py new file mode 100644 index 00000000000..61fe0895a27 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py @@ -0,0 +1,1172 @@ +"""A select: a button, and the popup of options it opens.""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterator, Sequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import ( + EventHandler, + input_event, + no_args_event_spec, + passthrough_event_spec, +) +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.core.foreach import foreach +from reflex_components_core.el import elements + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.components._group import descendants, is_value, literal +from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.popup import OFFSET, SHIFT +from reflex_components_ui.styles.select import ( + SELECT, + SELECT_CONTENT, + SELECT_ITEM, + SELECT_LABEL, + SELECT_SEPARATOR, + SELECT_TRIGGER, + SELECT_VALUE, +) +from reflex_components_ui.themes import LiteralAccentColor + +_SCRIPT = f"$/{WEB_DIR}/behaviors/listbox.js" + + +def _script(name: str) -> Var: + """Name a function of the script of a select. + + Args: + name: The name the script exports it under. + + Returns: + The function, with its import. + """ + return Var(name, _var_data=VarData(imports={_SCRIPT: [ImportVar(tag=name)]})) + + +# What the element around a select listens for: the keys that move through +# the options, the click that chooses one, and the pointer that marks one. +_KEY_DOWN = _script("selectKeyDown") +_CLICK = _script("selectClick") +_POINTER_MOVE = _script("selectPointerMove") +# What follows the popup that opens and closes, shows the value on the +# options and on the trigger, and hands the focus the input of the value is +# given to the trigger. +_TOGGLE = _script("selectToggle") +_SYNC = _script("syncSelect") +_FOCUS = _script("selectFocus") + +# The events of the popup as they are rendered, by the name the script +# calls each under. +_POPUP_EVENTS = { + "onOpenChange": "open", + "onCloseAutoFocus": "close", + "onEscapeKeyDown": "escape", + "onPointerDownOutside": "outside", +} + +# Numbers the popups and the labels, which are found by their ids. +_ids = itertools.count(1) + +_CHEVRON = ( + "M0.135232 3.15803C0.324102 2.95657 0.640521 2.94637 0.841971 3.13523" + "L4.5 6.56464L8.158 3.13523C8.3595 2.94637 8.6759 2.95657 8.8648 3.15803" + "C9.0536 3.35949 9.0434 3.67591 8.842 3.86477L4.84197 7.6148" + "C4.64964 7.7951 4.35036 7.7951 4.15803 7.6148L0.158031 3.86477" + "C-0.0434285 3.67591 -0.0536285 3.35949 0.135232 3.15803Z" +) +_CHECK = ( + "M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099" + "L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358" + "C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777" + "C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844" + "C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459" + "L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z" +) + + +def _icon(part: str, path: str, **attributes: Any) -> Component: + """Create one of the icons Radix Themes draws in a select. + + Args: + part: The part of the style table that sizes it. + path: The outline of the icon. + **attributes: The attributes of the path. + + Returns: + The icon, which is nothing to assistive technology. + """ + return Part.create( + elements.svg.path(d=path, custom_attrs=attributes), + part=part, + tag="svg", + custom_attrs={ + "width": "9", + "height": "9", + "viewBox": "0 0 9 9", + "fill": "currentcolor", + "xmlns": "http://www.w3.org/2000/svg", + "aria-hidden": True, + }, + ) + + +def _pixels(amount: Any) -> Any: + """Write a number of pixels as a length. + + Args: + amount: The number, or a Var of it. + + Returns: + The length: a string when the number is known while compiling. + """ + amount = literal(amount) + if not isinstance(amount, Var): + return f"{amount}px" + return Var( + f'(({amount!s}) + "px")', _var_type=str, _var_data=amount._get_all_var_data() + ) + + +def _styled(props: dict[str, Any], style: dict[str, Any]) -> None: + """Put styles a component works out before the ones it is given. + + Args: + props: The props the component is created with. + style: The styles it works out. + """ + given = props.get("style") + if given is None: + props["style"] = style + elif isinstance(given, (list, tuple)): + props["style"] = [style, *given] + else: + props["style"] = [style, given] + + +class SelectValue(UIComponent, elements.Input): + """The input that holds the value of a select, which a form submits.""" + + tag = "input" + + styles: ClassVar[ComponentStyles] = SELECT_VALUE + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the input. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: nothing to assistive technology, and not reached + with Tab. + """ + return ( + super() + ._render(props) + .add_props(**{ + "data-rx-select-value": "", + "aria-hidden": True, + "tabIndex": -1, + }) + ) + + +class SelectRoot(UIComponent): + """Displays a list of options for the user to pick from, triggered by a button.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = SELECT + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc=( + 'The size of the select trigger. Defaults to `"2"` (medium). ' + 'Use `"1"` for compact UIs like data tables, toolbars, or dense forms ' + 'with many fields. Use `"3"` for prominent calls-to-action or main ' + "page elements where the dropdown is the primary focus." + ) + ) + + default_value: Var[str] = field( + doc=( + "The value that's selected when the dropdown first renders. Use this " + "when you want the select to start with a specific option but don't " + "need to track the user's choice in app state. The value must match " + "one of the options in the list. If both `value` and `default_value` " + "are provided, `value` takes precedence." + ) + ) + + value: Var[str] = field( + doc=( + "The currently selected value of the dropdown. When set, the component " + "reflects this value and you must update it via an `on_change` event " + "handler. Use this when you need the selected value to drive other " + "parts of your app, like filtering a table, updating a chart, or " + "saving to a database. For a simpler pattern where you only need to " + "set the initial value, use `default_value` instead." + ) + ) + + default_open: Var[bool] = field( + doc=( + "Whether the dropdown menu is open when the component first renders. " + "Defaults to `False`. Useful for guided onboarding flows, tutorial " + "overlays, or when you want the menu visible immediately on page load " + "to draw user attention." + ) + ) + + open: Var[bool] = field( + doc=( + "Controls whether the dropdown menu is currently open. When set, you " + "must update this prop via an `on_open_change` event handler. Use " + "this to programmatically open or close the dropdown. For example, " + "opening it automatically when a user clicks a related button " + "elsewhere on the page, or closing it after a successful selection " + "in a multi-step form." + ) + ) + + name: Var[str] = field( + doc=( + "The name attribute used when the select is submitted as part of an " + "HTML form. This becomes the key in the submitted form data. If " + "omitted, the select's value won't be included in form submissions. " + "See [Forms](/docs/library/forms/form) for more on integrating " + "selects with form validation and submission." + ) + ) + + disabled: Var[bool] = field( + doc=( + "When `True`, the user cannot interact with the select. The trigger " + "appears in a muted style and clicking has no effect. Defaults to " + "`False`. Useful for forms where a field shouldn't be editable based " + "on other state, like a confirmation step, a permission-restricted " + "view, or a field that's locked while data is loading. To disable " + "individual options instead of the entire select, use the " + "[low-level Select API](/docs/library/forms/select/low) and set " + "`disabled` on specific `rx.select.item` components." + ) + ) + + required: Var[bool] = field( + doc=( + "When `True` and the select is inside an `rx.form.root`, the form " + "cannot be submitted until the user selects a value. Defaults to " + "`False`. Pairs with `name` to enforce required form fields. Note: " + "this does not affect the select's visual appearance. For visual " + "indication that a field is required, add a label with an asterisk " + "yourself." + ) + ) + + on_change: EventHandler[input_event] = field( + doc=( + "Fires when the user selects a different option from the dropdown. " + "The handler receives the new value as a string. Use this with " + "`value` to create a fully reactive select bound to state. The event " + "also fires when the value is updated programmatically via state, so " + "it's a reliable signal for any value change, not just user clicks." + ) + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc=( + "Fires when the dropdown menu opens or closes. The handler receives " + "a boolean, `True` when opening, `False` when closing. Useful for " + "triggering analytics events, prefetching data for the dropdown " + "options when the menu opens, or animating related UI elements " + "(like a sidebar or tooltip) when the menu appears." + ) + ) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a SelectRoot. + + Radix hands the parts of a select its props through a context. Here + the root finds its parts while compiling, and gives them what they + render. The value is the one of an input after them, which is what + a form reads. + + Args: + *children: The trigger and the content of the select. + **props: The properties of the component. + + Returns: + The SelectRoot component. + """ + value, open_ = props.get("value"), props.get("open") + shown = value if value is not None else props.get("default_value") + arguments = [LiteralVar.create(argument) for argument in (value, open_)] + held: dict[str, Any] = { + key: props[key] for key in ("name", "required", "disabled") if key in props + } + if shown is not None: + held["default_value"] = shown + holder = SelectValue.create( + **held, + custom_attrs={ + # Called whenever the page renders: a select bound to state + # takes its value, and whether it is open, from there. + "ref": Var( + f"((holder) => syncSelect(holder, {arguments[0]!s}, " + f"{arguments[1]!s}))", + _var_data=VarData.merge( + _SYNC._get_all_var_data(), + *(argument._get_all_var_data() for argument in arguments), + ), + ), + "onFocus": _FOCUS, + }, + ) + attributes = props.setdefault("custom_attrs", {}) + attributes.setdefault("onKeyDown", _KEY_DOWN) + attributes.setdefault("onClick", _CLICK) + attributes.setdefault("onPointerMove", _POINTER_MOVE) + return super().create(*children, holder, **props) + + def _post_init(self, *args, **kwargs): + """Initialize the select, and give its parts what they share. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + selected = self.value if self.value is not None else self.default_value + items = list(descendants(self, SelectItem)) + for item in items: + item._join(selected) + popup = f"rx-select-{next(_ids)}" + on_open_change = self.event_triggers.pop("on_open_change", None) + for content in descendants(self, SelectContent): + popup = content._join(self, popup, on_open_change) + for trigger in descendants(self, SelectTrigger): + trigger._join(self, popup, selected, items) + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the parts off the element. + + Returns: + The props read as styles, and what the select hands its parts. + """ + return [ + *super()._exclude_props(), + "size", + "value", + "default_value", + "default_open", + "open", + "name", + "disabled", + "required", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the element around the select. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, marked for the script of the select, which opens a + select that starts open. + """ + tag = super()._render(props).add_props(**{"data-rx-select": ""}) + if self.default_open is not None: + tag = tag.add_props(**{"data-default-open": self.default_open}) + return tag + + +def _shown( + selected: Var | None, placeholder: Var | None, items: list[SelectItem] +) -> Any: + """Work out what the trigger of a select shows before any script runs. + + Args: + selected: The value of the select, or None. + placeholder: What the trigger shows when nothing is chosen, or None. + items: The options of the select. + + Returns: + The text of the chosen option, where it is known while compiling or + can be read from the value, and the placeholder otherwise: the + script of the select shows the text when it runs. + """ + empty = "" if placeholder is None else placeholder + if selected is None: + return empty + texts = [(item.value, item._text) for item in items] + value = literal(selected) + if not isinstance(value, Var): + for item_value, text in texts: + if literal(item_value) == value and text is not None: + return text + return empty + fallback = LiteralVar.create(empty) + data = [selected._get_all_var_data(), fallback._get_all_var_data()] + if texts and all( + text is not None and str(text) == str(item_value) for item_value, text in texts + ): + # Each option shows its value: so does the trigger. + return Var( + f"({selected!s} || {fallback!s})", + _var_type=str, + _var_data=VarData.merge(*data), + ) + known = {literal(item_value): text for item_value, text in texts} + if texts and not any( + isinstance(item, Var) or item is None for pair in known.items() for item in pair + ): + # The text of each option is known: the one of the value is read + # from them. + return Var( + f"({LiteralVar.create(known)!s}[{selected!s}] ?? {fallback!s})", + _var_type=str, + _var_data=VarData.merge(*data), + ) + return empty + + +class SelectTrigger(UIComponent): + """The button that toggles the select.""" + + tag = "button" + + styles: ClassVar[ComponentStyles] = SELECT_TRIGGER + + variant: Var[Literal["classic", "surface", "soft", "ghost"]] = field( + doc=( + "The visual style of the trigger. Same options and behavior as the " + "`variant` prop on `rx.select.root`. Setting it here allows " + "different visual styles between the trigger and content when " + "composing custom selects." + ) + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc=( + "The text color of the trigger label. Accepts any Reflex color " + "token. Use to make the trigger text stand out. For example, a red " + "trigger color for an error state, or muted gray for a " + "placeholder-like appearance." + ) + ) + + radius: Var[Literal["none", "small", "medium", "large", "full"]] = field( + doc=( + "The border radius of the trigger. Same behavior as the `radius` " + "prop on `rx.select.root`, but scoped to just the trigger button " + "when using the low-level API." + ) + ) + + placeholder: Var[str] = field( + doc=( + "The text displayed in the trigger button when no option is " + "selected. Same behavior as the `placeholder` prop on " + "`rx.select.root`, but set on the trigger directly in the low-level " + "API. Hidden automatically once a value is selected." + ) + ) + + _valid_parents: ClassVar[list[str]] = ["SelectRoot"] + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a SelectTrigger. + + Args: + *children: What the trigger shows in place of the chosen option. + **props: The properties of the component. + + Returns: + The SelectTrigger component: a button around what it shows and + the icon of a select. + """ + return super().create( + Part.create(*children, part="shown", tag="span"), + _icon("icon", _CHEVRON), + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the trigger, with the look of a select without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as a variant, and the attributes the + # select gives its trigger: both are set by the select around it. + self._size: Any = None + self._select: dict[str, Any] = {} + super()._post_init(*args, **kwargs) + + def _join( + self, + select: SelectRoot, + popup: Any, + selected: Var | None, + items: list[SelectItem], + ) -> None: + """Take from a select what Radix hands its trigger through a context. + + Args: + select: The select the trigger is in. + popup: The id of the popup it opens. + selected: The value of the select, or None. + items: The options of the select. + """ + self._size = select.size + attributes: dict[str, Any] = {"popovertarget": popup, "aria-controls": popup} + if select.disabled is not None: + attributes["disabled"] = select.disabled + if not self.children[0].children: + mark: dict[str, Any] = {"data-rx-select-shown": ""} + if self.placeholder is not None: + mark["data-placeholder"] = self.placeholder + self.children[0] = Part.create( + _shown(selected, self.placeholder, items), + part="shown", + tag="span", + custom_attrs=mark, + ) + if selected is None: + attributes["data-placeholder"] = "" + elif isinstance(literal(selected), Var): + attributes["data-placeholder"] = Var( + f'({selected!s} ? undefined : "")', + _var_data=selected._get_all_var_data(), + ) + self._select = attributes + # The parts take their styles again: the size is one of theirs. + for part in descendants(self, Part): + part._merged = None + self._merge_styles() + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the trigger, those its select gives it 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) + for value in self._select.values(): + if isinstance(value, Var): + yield value + + def _exclude_props(self) -> list[str]: + """Keep the placeholder off the button: the text inside it shows it. + + Returns: + The props read as styles, and the placeholder. + """ + return [*super()._exclude_props(), "placeholder"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a button that opens its popup without a script, with + the role and the state Radix gives the trigger of a select. + """ + return ( + super() + ._render(props) + .add_props(**{ + "type": "button", + "role": "combobox", + "aria-expanded": "false", + "aria-haspopup": "listbox", + "aria-autocomplete": "none", + "data-state": "closed", + **self._select, + }) + ) + + +class SelectContent(UIComponent): + """The component that pops out when the select is open.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = SELECT_CONTENT + + variant: Var[Literal["solid", "soft"]] = field( + doc=( + "The visual style of the dropdown menu surface. Defaults to " + '`"solid"`. Use `"soft"` for a more subtle, translucent menu ' + "background. Particularly effective on colored or image backgrounds." + ) + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc=( + "Overrides the theme's accent color for the dropdown menu " + "specifically. Affects the highlight color when hovering or " + "arrow-key-navigating through items. Can differ from the trigger's " + "`color_scheme` for stylistic effect." + ) + ) + + high_contrast: Var[bool] = field( + doc=( + "When `True`, increases the contrast inside the dropdown menu. " + "Particularly useful when the menu opens over a busy background. " + "Defaults to `False`." + ) + ) + + position: Var[Literal["item-aligned", "popper"]] = field( + doc=( + "Controls how the dropdown menu positions itself relative to the " + "trigger. Same behavior as `position` on `rx.select.root`. Defaults " + 'to `"item-aligned"`. Set to `"popper"` when placing the select ' + "inside a Drawer, Dialog, or Popover." + ) + ) + + side: Var[Literal["top", "right", "bottom", "left"]] = field( + doc=( + "Which side of the trigger the dropdown should appear on when using " + '`position="popper"`. Defaults to `"bottom"`. Useful when the ' + "trigger is near the bottom of the viewport and the default " + "placement would cause the menu to be clipped." + ) + ) + + side_offset: Var[int] = field( + doc=( + "The distance in pixels between the trigger and the dropdown menu " + 'when `position="popper"`. Defaults to `0`. Increase for visual ' + "separation between the trigger and menu." + ) + ) + + align: Var[Literal["start", "center", "end"]] = field( + doc=( + "Horizontal alignment of the dropdown menu relative to the trigger " + 'when `position="popper"`. Defaults to `"start"`. Use `"end"` for ' + "right-aligned dropdowns in RTL layouts or when the trigger is on " + "the right side of a container." + ) + ) + + align_offset: Var[int] = field( + doc=( + 'Pixel offset for the alignment when `position="popper"`. Defaults ' + "to `0`. Use to fine-tune the dropdown's horizontal position." + ) + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the select content is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when a pointer down event happens outside the select content." + ) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a SelectContent. + + Args: + *children: The options of the select. + **props: The properties of the component. + + Returns: + The SelectContent component. + """ + distances = { + name: _pixels(props[prop]) + for prop, name in (("side_offset", OFFSET), ("align_offset", SHIFT)) + if props.get(prop) is not None + } + if distances: + _styled(props, distances) + return super().create(*children, **props) + + def _post_init(self, *args, **kwargs): + """Initialize the content, with the look of a select without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as a variant: the select sets it. + self._size: Any = None + super()._post_init(*args, **kwargs) + + def _join(self, select: SelectRoot, popup: str, on_open_change: Any) -> Any: + """Take from a select what Radix hands its content through a context. + + Args: + select: The select the content is in. + popup: The id of a popup that is given none. + on_open_change: What the select does when it opens or closes. + + Returns: + The id of the popup. + """ + self._size = select.size + if self.id is None: + self.id = LiteralVar.create(popup) + if on_open_change is not None: + self.event_triggers["on_open_change"] = on_open_change + self._merge_styles() + return self.id + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the popup, what follows its toggle 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 _TOGGLE + + def _exclude_props(self) -> list[str]: + """Keep the props that say where the popup goes off the element. + + Returns: + The props read as styles, and the ones a style is made from. + The position is one of them: the popup is beside its trigger + whatever it says. + """ + return [*super()._exclude_props(), "position", "side_offset", "align_offset"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the popup. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a popover the browser opens and closes, which says so + to the script of the select, and through it to the events. + """ + tag = super()._render(props) + handlers = { + name: LiteralVar.create(tag.props.pop(event)) + for event, name in _POPUP_EVENTS.items() + if event in tag.props + } + toggle = _TOGGLE + if handlers: + called = ", ".join([ + f"{name}: {handler!s}" for name, handler in handlers.items() + ]) + toggle = Var( + f"((event) => selectToggle(event, ({{ {called} }})))", + _var_data=VarData.merge( + _TOGGLE._get_all_var_data(), + *(handler._get_all_var_data() for handler in handlers.values()), + ), + ) + return tag.add_props(**{ + "popover": "auto", + "role": "listbox", + "tabIndex": -1, + "data-rx-popup": "", + "onToggle": toggle, + }) + + +class SelectGroup(UIComponent): + """Used to group multiple items.""" + + tag = "div" + + _valid_parents: ClassVar[list[str]] = ["SelectContent"] + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a SelectGroup. + + Args: + *children: The label and the options of the group. + **props: The properties of the component. + + Returns: + The SelectGroup component, named by its label. + """ + for child in children: + if isinstance(child, SelectLabel): + if child.id is None: + child.id = LiteralVar.create(f"rx-select-label-{next(_ids)}") + props.setdefault("aria_labelledby", child.id) + break + return super().create(*children, **props) + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the group. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role of a group. + """ + return super()._render(props).add_props(role="group") + + +class SelectItem(UIComponent): + """The component that contains the select items.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = SELECT_ITEM + + value: Var[str] = field( + doc=( + "The value associated with this option. Required. When this item is " + "selected, the select's `on_change` handler receives this value. " + "The display label is set via the item's children. Separating value " + "from label is the main reason to use the low-level Select API " + "instead of the high-level `rx.select`." + ) + ) + + disabled: Var[bool] = field( + doc=( + "When `True`, this specific item cannot be selected. It appears " + "muted and clicking does nothing. Defaults to `False`. Useful for " + "showing options that exist conceptually but aren't currently " + "available (e.g., out-of-stock products, locked features behind a " + "paywall, or options requiring elevated permissions)." + ) + ) + + _valid_parents: ClassVar[list[str]] = ["SelectGroup", "SelectContent"] + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a SelectItem. + + Args: + *children: What the option shows. + **props: The properties of the component. + + Returns: + The SelectItem component: the check of the chosen option, and + what the option shows. + """ + return super().create( + Part.create( + _icon("check", _CHECK, fillRule="evenodd", clipRule="evenodd"), + part="indicator", + tag="span", + ), + elements.span(*children, custom_attrs={"data-rx-select-text": ""}), + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the option of a select that has no value. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # Whether the select around the option has chosen it. + self._selected: Any = False + super()._post_init(*args, **kwargs) + + @property + def _text(self) -> Any: + """What the option shows, when it is one string. + + Returns: + The text, or None for an option that shows anything else. + """ + shown = self.children[1].children + if len(shown) != 1: + return None + contents = getattr(shown[0], "contents", None) + if contents is None or not issubclass(contents._var_type, str): + return None + return literal(contents) + + def _join(self, selected: Var | None) -> None: + """Take from a select whether it has chosen the option. + + Args: + selected: The value of the select, or None. + """ + self._selected = False if selected is None else is_value(selected, self.value) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the option, what its select gives it 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) + if isinstance(self._selected, Var): + yield self._selected + + def _exclude_props(self) -> list[str]: + """Keep the props of an option off the element: it is no input. + + Returns: + The props read as styles, the value and whether it is disabled. + """ + return [*super()._exclude_props(), "value", "disabled"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the option. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role and the state of an option: it takes + the focus from the script of the select, not from Tab. + """ + selected = self._selected + attributes: dict[str, Any] = { + "role": "option", + "tabIndex": -1, + "data-value": self.value, + "aria-selected": ( + Var( + f'({selected!s} ? "true" : "false")', + _var_data=selected._get_all_var_data(), + ) + if isinstance(selected, Var) + else str(selected).lower() + ), + } + if self.disabled is not None: + attributes["aria-disabled"] = self.disabled + return super()._render(props).add_props(**attributes) + + +class SelectLabel(UIComponent): + """Used to render the label of a group, it isn't focusable using arrow keys.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = SELECT_LABEL + + _valid_parents: ClassVar[list[str]] = ["SelectGroup"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the label. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, marked for the rule that keeps it from the option + before it. + """ + return super()._render(props).add_props(**{"data-rx-select-label": ""}) + + +class SelectSeparator(UIComponent): + """Used to visually separate items in the Select.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = SELECT_SEPARATOR + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the separator. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, which is nothing to assistive technology. + """ + return super()._render(props).add_props(**{"aria-hidden": True}) + + +class HighLevelSelect(SelectRoot): + """High level wrapper for the Select component.""" + + items: Var[Sequence[str]] = field(doc="The items of the select.") + + placeholder: Var[str] = field( + doc=( + "The text shown in the trigger button when no option has been " + "selected. Defaults to an empty string. The placeholder is " + "automatically hidden once `value` or `default_value` is set, so it " + "only appears in the initial empty state. Use placeholders to guide " + 'the user toward the right choice (e.g., "Choose a country…" or ' + '"Pick a category").' + ) + ) + + label: Var[str] = field(doc="The label of the select.") + + color_scheme: Var[LiteralAccentColor] = field( + doc=( + "Overrides the theme's accent color for this specific select. " + 'Accepts any Reflex color token (`"blue"`, `"green"`, `"red"`, ' + '`"purple"`, `"crimson"`, `"orange"`, etc.). Useful for ' + "status-specific dropdowns. For example, a destructive action " + 'select in `"red"`, or a success-state filter in `"green"`. Affects ' + "the focus ring, active item highlight, and the dropdown arrow icon." + ) + ) + + high_contrast: Var[bool] = field( + doc=( + "When `True`, increases the contrast between the select's text and " + "background for better readability. Defaults to `False`. Useful for " + "accessibility compliance (WCAG AA/AAA) or for selects placed on " + "busy or colored backgrounds where the default contrast may be " + "insufficient." + ) + ) + + variant: Var[Literal["classic", "surface", "soft", "ghost"]] = field( + doc=( + 'The visual style of the trigger button. Defaults to `"surface"`. ' + 'Options: `"classic"` for a bordered button with a subtle ' + 'background, `"surface"` for a filled background with a thin ' + 'border, `"soft"` for a tinted background with no border, `"ghost"` ' + "for minimal chrome that only appears on hover. Match the variant " + "to the visual weight you want the select to have in the " + "surrounding UI." + ) + ) + + radius: Var[Literal["none", "small", "medium", "large", "full"]] = field( + doc=( + "The border radius of the trigger button. Inherits from the theme " + 'by default. Use `"none"` for sharp corners, `"full"` for a ' + "pill-shaped trigger, or pick a specific value to match your app's " + "design system. Doesn't affect the dropdown menu radius, only the " + "trigger button." + ) + ) + + width: Var[str] = field(doc="The width of the select.") + + position: Var[Literal["item-aligned", "popper"]] = field( + doc=( + "Controls how the dropdown menu positions itself relative to the " + 'trigger. Defaults to `"item-aligned"`, which aligns the currently ' + 'selected option with the trigger button. Use `"popper"` when ' + "placing the select inside a [Drawer](/docs/library/overlay/drawer), " + "[Dialog](/docs/library/overlay/dialog), " + "[Popover](/docs/library/overlay/popover), or any portal-based " + "container. This prevents the menu from being clipped or misaligned " + "by the overlay." + ) + ) + + @classmethod + def create(cls, items: list[str] | Var[list[str]], **props) -> Component: + """Create a select component. + + Args: + items: The items of the select. + **props: Additional properties to apply to the select component. + + Returns: + The select component. + """ + trigger_prop_list = [ + "id", + "placeholder", + "variant", + "radius", + "width", + "flex_shrink", + "custom_attrs", + ] + + content_props = { + prop: props.pop(prop) + for prop in ["high_contrast", "position"] + if prop in props + } + + trigger_props = { + prop: props.pop(prop) for prop in trigger_prop_list if prop in props + } + + color_scheme = props.pop("color_scheme", None) + + if color_scheme is not None: + content_props["color_scheme"] = color_scheme + trigger_props["color_scheme"] = color_scheme + + label = props.pop("label", None) + + if isinstance(items, Var): + child = [foreach(items, lambda item: SelectItem.create(item, value=item))] + else: + child = [SelectItem.create(item, value=item) for item in items] + + return SelectRoot.create( + SelectTrigger.create( + **trigger_props, + ), + SelectContent.create( + SelectGroup.create( + *([] if label is None else [SelectLabel.create(label)]), + *child, + ), + **content_props, + ), + **props, + ) + + +class Select(ComponentNamespace): + """Select components namespace.""" + + root = staticmethod(SelectRoot.create) + trigger = staticmethod(SelectTrigger.create) + content = staticmethod(SelectContent.create) + group = staticmethod(SelectGroup.create) + item = staticmethod(SelectItem.create) + separator = staticmethod(SelectSeparator.create) + label = staticmethod(SelectLabel.create) + __call__ = staticmethod(HighLevelSelect.create) + + +select = Select() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py new file mode 100644 index 00000000000..60642c543bc --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py @@ -0,0 +1,131 @@ +"""The look of a popup: a native popover, placed beside what opens it.""" + +from __future__ import annotations + +from typing import Any + +# A popup that is open, and the element before it that opens it. A style +# of that element selects on the second: no script says that it is open. +OPEN = ":popover-open" +OPENS = ":is([data-state='open'], :has(+ :popover-open))" + +# How far a popup stays from the edge of the viewport, as in Radix. +_EDGE = "10px" + +# Where a popup goes for each side of its anchor and each alignment along +# that side: the part of the page the browser lays it out in. +_AREAS = { + ("bottom", "start"): "bottom span-right", + ("bottom", "center"): "bottom span-all", + ("bottom", "end"): "bottom span-left", + ("top", "start"): "top span-right", + ("top", "center"): "top span-all", + ("top", "end"): "top span-left", + ("left", "start"): "left span-bottom", + ("left", "center"): "left span-all", + ("left", "end"): "left span-top", + ("right", "start"): "right span-bottom", + ("right", "center"): "right span-all", + ("right", "end"): "right span-top", +} + +# What a table sets on a popup: how far it is from its anchor, how far +# along it, and where it comes from when it opens. +OFFSET = "--rx-popup-offset" +SHIFT = "--rx-popup-shift" +_FROM = "--rx-popup-from" + +_MOTION = "@media (prefers-reduced-motion: no-preference)" + +# Where a popup on each side comes from, as in Radix Themes. +_ENTRY = { + "bottom": "translateY(-4px) scale(0.97)", + "top": "translateY(4px) scale(0.97)", + "left": "translateX(4px) scale(0.97)", + "right": "translateX(-4px) scale(0.97)", +} +_OPPOSITE = {"bottom": "top", "top": "bottom", "left": "right", "right": "left"} + +# What a popover is before a table draws it: nothing of the box the browser +# gives one, and placed by its anchor instead of in the middle of the page. +POPUP: dict[str, Any] = { + "position": "fixed", + "inset": "auto", + "margin": "0", + "padding": "0", + "border_width": "0", + "border_style": "none", + "box_sizing": "border-box", + "width": "max-content", + "height": "auto", + "max_width": f"calc(100vw - {_EDGE} * 2)", + # It turns over where it would leave the viewport. + "position_try_fallbacks": "flip-block, flip-inline", + # It comes in when it opens, and goes out before it leaves the top + # layer, for whoever has not asked for less motion. + "opacity": {"default": 0, OPEN: {"default": 1, "@starting-style": 0}}, + "transform": { + "default": f"var({_FROM})", + OPEN: {"default": "none", "@starting-style": f"var({_FROM})"}, + }, + "transition_property": "opacity, transform, display, overlay", + "transition_duration": { + "default": "0s", + _MOTION: {"default": "100ms", OPEN: "160ms"}, + }, + "transition_timing_function": "cubic-bezier(0.16, 1, 0.3, 1)", +} + + +def placement(side: str, align: str, default_offset: str = "0px") -> dict[str, Any]: + """Make the styles that place a popup beside its anchor. + + Args: + side: The side of the anchor the popup is on. + align: Where along that side: at its start, its center or its end. + default_offset: How far from the anchor, for a popup that does not say. + + Returns: + The styles: the popup is no taller, or no wider, than the room the + viewport leaves on that side. + """ + vertical = side in ("top", "bottom") + before, after = ("top", "bottom") if vertical else ("left", "right") + start, end = ("left", "right") if vertical else ("top", "bottom") + offset = f"var({OFFSET}, {default_offset})" + style: dict[str, Any] = { + "position_area": _AREAS[side, align], + f"margin_{before}": offset, + f"margin_{after}": offset, + ("max_height" if vertical else "max_width"): ( + f"calc(100% - {offset} - {_EDGE})" + ), + _FROM: _ENTRY[side], + "transform_origin": ( + f"{_OPPOSITE[side]} " + f"{'center' if align == 'center' else start if align == 'start' else end}" + ), + } + if align == "center": + style["justify_self" if vertical else "align_self"] = "anchor-center" + else: + style[f"margin_{start if align == 'start' else end}"] = f"var({SHIFT}, 0px)" + return style + + +def placements(default_offset: str = "0px") -> list[dict[str, Any]]: + """Make the compound variants that place a popup by its side and alignment. + + Args: + default_offset: How far from the anchor, for a popup that does not say. + + Returns: + One compound variant for each side and each alignment along it. + """ + return [ + { + "props": {"side": side, "align": align}, + "style": placement(side, align, default_offset), + } + for side, align in _AREAS + ] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py new file mode 100644 index 00000000000..58de7b715ab --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py @@ -0,0 +1,486 @@ +"""The look of a select: a trigger, and the list it opens.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.appearance import by_appearance +from reflex_components_ui.styles.button import _CLASSIC_DISABLED_SHADOW +from reflex_components_ui.styles.popup import OPENS, POPUP, placements + +accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black + +_HEIGHT = "--select-trigger-height" +_GHOST_X = "--select-trigger-ghost-padding-x" +_GHOST_Y = "--select-trigger-ghost-padding-y" +_PADDING = "--select-content-padding" +_ITEM_HEIGHT = "--select-item-height" +_INDICATOR = "--select-item-indicator-width" +_SEPARATOR = "--select-separator-margin-right" + +# What the trigger hands the elements inside it: the color of a placeholder +# and of the icon of a disabled select. +_SHOWN_COLOR = "--rx-select-shown-color" +_SHOWN_OPACITY = "--rx-select-shown-opacity" +_ICON_COLOR = "--rx-select-icon-color" +# What the list hands its items: how large their text is, and how the one +# that has the focus is marked. +_FONT_SIZE = "--rx-select-font-size" +_LINE_HEIGHT = "--rx-select-line-height" +_LETTER_SPACING = "--rx-select-letter-spacing" +_LABEL_SIZE = "--rx-select-label-font-size" +_LABEL_SPACING = "--rx-select-label-letter-spacing" +_ITEM_RADIUS = "--rx-select-item-radius" +_CHECK = "--rx-select-check-size" +_MARK = "--rx-select-highlight" +_MARK_COLOR = "--rx-select-highlight-color" + +_POINTER = "@media (hover: hover)" +_HOVER = ":hover:not(:disabled)" +_DISABLED = ":disabled" +_FOCUS = ":focus-visible" +_EMPTY = "[data-placeholder]" +_OPEN = f"{OPENS}:not(:disabled)" + +_CLASSIC_SHADOW = by_appearance( + f"inset 0 0 0 1px {gray.a[5]}, inset 0 2px 1px {white.a[11]}, " + f"inset 0 -2px 1px {gray.a[4]}", + f"inset 0 0 0 1px {white.a[4]}, inset 0 1px 1px {white.a[4]}, " + f"inset 0 -1px 1px {black.a[9]}", +) +_CLASSIC_RAISED = f"inset 0 0 0 1px {gray.a[3]}, {_CLASSIC_SHADOW}" +_CLASSIC_FILL = ( + f"linear-gradient({black.a[1]} -20%, transparent, {white.a[1]} 130%), " + f"linear-gradient({tokens.color.surface}, transparent)" +) +_CLASSIC_FILL_RAISED = ( + f"linear-gradient({black.a[1]} -15%, transparent, {white.a[1]} 120%), " + f"linear-gradient({gray[2]}, {gray[1]})" +) + + +def _trigger_size(height: str, gap: str, step: int, radius: str) -> dict[str, Any]: + """Make the styles of a trigger of one size. + + Args: + height: Its height. + gap: The gap between its text and its icon. + step: The step of the type scale. + radius: The radius of its corners. + + Returns: + The styles. + """ + return { + _HEIGHT: height, + "gap": gap, + "font_size": tokens.font_size[step], + "line_height": tokens.line_height[step], + "letter_spacing": tokens.letter_spacing[step], + "border_radius": f"max({radius}, {tokens.radius.full})", + } + + +def _states(rest: Any, raised: Any, disabled: Any = None) -> dict[str, Any]: + """Make the value of a property of a trigger, by its state. + + Args: + rest: The value at rest. + raised: The value under the pointer, and while the list is open. + disabled: The value of a disabled trigger, when it differs. + + Returns: + The value under a condition for each state. + """ + value = {"default": rest, _POINTER: {_HOVER: raised}, _OPEN: raised} + if disabled is not None: + value[_DISABLED] = disabled + return value + + +_PLACEHOLDER_GRAY = {_SHOWN_COLOR: {_EMPTY: gray.a[10]}} +_PLACEHOLDER_ACCENT = { + _SHOWN_COLOR: {_EMPTY: accent[12]}, + _SHOWN_OPACITY: {_EMPTY: 0.6}, +} +_BOXED = {"box_sizing": "border-box", "height": f"var({_HEIGHT})"} + +_TRIGGER_VARIANTS: dict[str, Any] = { + "surface": { + **_BOXED, + **_PLACEHOLDER_GRAY, + "color": {"default": gray[12], _DISABLED: gray.a[11]}, + "background_color": {"default": tokens.color.surface, _DISABLED: gray.a[2]}, + "box_shadow": _states( + f"inset 0 0 0 1px {gray.a[7]}", + f"inset 0 0 0 1px {gray.a[8]}", + f"inset 0 0 0 1px {gray.a[6]}", + ), + }, + "classic": { + **_BOXED, + **_PLACEHOLDER_GRAY, + "color": {"default": gray[12], _DISABLED: gray.a[11]}, + "background_color": {_DISABLED: gray[2]}, + "background_image": { + "default": f"linear-gradient({gray[2]}, {gray[1]})", + _DISABLED: "none", + }, + "box_shadow": _states( + _CLASSIC_SHADOW, _CLASSIC_RAISED, _CLASSIC_DISABLED_SHADOW + ), + "position": "relative", + "z_index": 0, + "_before": { + "content": "''", + "position": "absolute", + "z_index": -1, + "inset": "0", + "border_width": "2px", + "border_style": "solid", + "border_color": "transparent", + "background_clip": "content-box", + "border_radius": "inherit", + "pointer_events": "none", + "background_color": {_DISABLED: gray.a[2]}, + "background_image": _states( + _CLASSIC_FILL, + _CLASSIC_FILL_RAISED, + f"linear-gradient({black.a[1]} -20%, transparent, {white.a[1]})", + ), + }, + }, + "soft": { + **_BOXED, + **_PLACEHOLDER_ACCENT, + "color": {"default": accent[12], _DISABLED: gray.a[11]}, + "background_color": _states(accent.a[3], accent.a[4], gray.a[3]), + # A gray ring for a gray select. + "outline_color": {_FOCUS: accent[8]}, + }, + "ghost": { + **_PLACEHOLDER_ACCENT, + "box_sizing": "content-box", + "height": "fit-content", + "padding_top": f"var({_GHOST_Y})", + "padding_bottom": f"var({_GHOST_Y})", + "padding_left": f"var({_GHOST_X})", + "padding_right": f"var({_GHOST_X})", + # It reaches as far out as its padding, so that its text lines up + # with what is around it. + "margin_top": f"calc(0px - var({_GHOST_Y}))", + "margin_bottom": f"calc(0px - var({_GHOST_Y}))", + "margin_left": f"calc(0px - var({_GHOST_X}))", + "margin_right": f"calc(0px - var({_GHOST_X}))", + "color": {"default": accent[12], _DISABLED: gray.a[11]}, + "background_color": _states("transparent", accent.a[3], "transparent"), + }, +} + +_TRIGGER_PADDING = {"1": tokens.space[2], "2": tokens.space[3], "3": tokens.space[4]} +_GHOST_PADDING = { + "1": (tokens.space[2], tokens.space[1]), + "2": (tokens.space[2], tokens.space[1]), + "3": (tokens.space[3], f"calc({tokens.space[1]} * 1.5)"), +} + +SELECT_TRIGGER: ComponentStyles = { + "base": unchecked({ + "appearance": "none", + "margin": "0", + "padding": "0", + "border_width": "0", + "border_style": "none", + "background_color": "transparent", + "background_image": "none", + "text_transform": "inherit", + "text_indent": "initial", + "word_spacing": "inherit", + "cursor": {"default": tokens.cursor.button, _DISABLED: tokens.cursor.disabled}, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "align_items": "center", + "justify_content": "space-between", + "flex_shrink": 0, + "user_select": "none", + "vertical_align": "top", + "font_family": tokens.default.font_family, + "font_weight": tokens.font_weight.regular, + "font_style": "normal", + "text_align": "start", + "outline_style": {"default": "none", _FOCUS: "solid"}, + "outline_width": {"default": "medium", _FOCUS: "2px"}, + "outline_color": {"default": "currentcolor", _FOCUS: tokens.focus[8]}, + "outline_offset": {"default": "0", _FOCUS: "-1px"}, + _ICON_COLOR: {_DISABLED: gray.a[9]}, + }), + "variants": { + "_size": { + "1": unchecked( + _trigger_size(tokens.space[5], tokens.space[1], 1, tokens.radius[1]) + ), + "2": unchecked( + _trigger_size( + tokens.space[6], + f"calc({tokens.space[1]} * 1.5)", + 2, + tokens.radius[2], + ) + ), + "3": unchecked( + _trigger_size(tokens.space[7], tokens.space[2], 3, tokens.radius[3]) + ), + }, + "variant": { + variant: unchecked(style) for variant, style in _TRIGGER_VARIANTS.items() + }, + }, + "defaults": {"_size": "2", "variant": "surface"}, + "compound": [ + *( + { + "props": {"_size": size, "variant": variant}, + "style": {"padding_left": padding, "padding_right": padding}, + } + for size, padding in _TRIGGER_PADDING.items() + for variant in ("surface", "classic", "soft") + ), + *( + { + "props": {"_size": size, "variant": "ghost"}, + "style": unchecked({_GHOST_X: x, _GHOST_Y: y}), + } + for size, (x, y) in _GHOST_PADDING.items() + ), + ], + "parts": { + # The text of the chosen option, or the placeholder. + "shown": { + "base": unchecked({ + "overflow": "hidden", + "text_overflow": "ellipsis", + "white_space": "nowrap", + "color": f"var({_SHOWN_COLOR}, inherit)", + "opacity": f"var({_SHOWN_OPACITY}, 1)", + }), + }, + "icon": { + "base": unchecked({ + "flex_shrink": 0, + "color": f"var({_ICON_COLOR}, inherit)", + }), + "variants": { + "variant": { + "surface": {"opacity": 0.9}, + "classic": {"opacity": 0.9}, + "soft": {"opacity": 0.9}, + "ghost": {}, + }, + "_size": {"3": {"width": "11px", "height": "11px"}}, + }, + "defaults": {"variant": "surface"}, + }, + }, +} + + +def _content_size( + padding: str, + height: str, + indicator: str, + separator: str, + radius: str, + step: int, + item_radius: str, + check: str, +) -> dict[str, Any]: + """Make the styles of a list of one size. + + Args: + padding: The room around its items. + height: The height of an item. + indicator: The room before the text of an item, for its check. + separator: The room after a separator. + radius: The radius of the corners of the list. + step: The step of the type scale. + item_radius: The radius of the corners of an item. + check: The side of the check of the chosen item. + + Returns: + The styles. + """ + return { + _PADDING: padding, + _ITEM_HEIGHT: height, + _INDICATOR: indicator, + _SEPARATOR: separator, + "border_radius": radius, + _FONT_SIZE: tokens.font_size[step], + _LINE_HEIGHT: tokens.line_height[min(step, 2)], + _LETTER_SPACING: tokens.letter_spacing[step], + # The label of a group is no larger than the text of size 2. + _LABEL_SIZE: tokens.font_size[min(step, 2)], + _LABEL_SPACING: tokens.letter_spacing[min(step, 2)], + _ITEM_RADIUS: item_radius, + _CHECK: f"calc({check} * {tokens.scaling})", + } + + +_LARGE = ( + tokens.space[2], + tokens.space[6], + tokens.space[5], + tokens.space[3], + tokens.radius[4], +) + +_ROW: dict[str, Any] = { + "display": "flex", + "align_items": "center", + "height": f"var({_ITEM_HEIGHT})", + "padding_left": f"var({_INDICATOR})", + "padding_right": f"var({_INDICATOR})", + "user_select": "none", + "font_size": f"var({_FONT_SIZE})", + "line_height": f"var({_LINE_HEIGHT})", + "letter_spacing": f"var({_LETTER_SPACING})", +} + +SELECT_CONTENT: ComponentStyles = { + "base": unchecked({ + **POPUP, + "color": gray[12], + "font_family": tokens.default.font_family, + "font_weight": tokens.font_weight.regular, + "font_style": "normal", + "text_align": "start", + "background_color": tokens.color.panel_solid, + "box_shadow": tokens.shadow[5], + "min_width": "anchor-size(width)", + "outline_style": "none", + "padding": f"var({_PADDING})", + "overflow_y": "auto", + "scrollbar_width": "thin", + "scrollbar_color": f"{gray.a[8]} transparent", + }), + "variants": { + "_size": { + "1": unchecked( + _content_size( + tokens.space[1], + tokens.space[5], + f"calc({tokens.space[5]} / 1.2)", + tokens.space[2], + tokens.radius[3], + 1, + tokens.radius[1], + "8px", + ) + ), + "2": unchecked(_content_size(*_LARGE, 2, tokens.radius[2], "10px")), + "3": unchecked(_content_size(*_LARGE, 3, tokens.radius[2], "10px")), + }, + "variant": { + "solid": unchecked({_MARK: accent[9], _MARK_COLOR: accent.contrast}), + "soft": unchecked({_MARK: accent.a[4]}), + }, + "side": {"top": {}, "right": {}, "bottom": {}, "left": {}}, + "align": {"start": {}, "center": {}, "end": {}}, + }, + "defaults": {"_size": "2", "variant": "solid", "side": "bottom", "align": "start"}, + "compound": [ + *( + {"props": place["props"], "style": unchecked(place["style"])} + for place in placements("4px") + ), + { + "props": {"variant": "solid", "high_contrast": "true"}, + "style": unchecked({_MARK: accent[12], _MARK_COLOR: accent[1]}), + }, + ], +} + +SELECT_ITEM: ComponentStyles = { + "base": unchecked({ + **_ROW, + "position": "relative", + "box_sizing": "border-box", + "outline_style": "none", + "scroll_margin_top": f"var({_PADDING})", + "scroll_margin_bottom": f"var({_PADDING})", + "border_radius": f"var({_ITEM_RADIUS})", + "cursor": { + "default": tokens.cursor.menu_item, + "[aria-disabled='true']": "default", + }, + "color": { + "default": "inherit", + ":focus": f"var({_MARK_COLOR}, inherit)", + "[aria-disabled='true']": gray.a[8], + }, + "background_color": {":focus": f"var({_MARK})"}, + "--rx-select-check": { + "default": "none", + "[aria-selected='true']": "inline-flex", + }, + }), + "parts": { + # The check of the chosen option. + "indicator": { + "base": unchecked({ + "position": "absolute", + "left": "0", + "width": f"var({_INDICATOR})", + "display": "var(--rx-select-check)", + "align_items": "center", + "justify_content": "center", + }), + }, + "check": { + "base": unchecked({ + "width": f"var({_CHECK})", + "height": f"var({_CHECK})", + }), + }, + }, +} + +SELECT_LABEL: ComponentStyles = { + "base": unchecked({ + **_ROW, + "font_size": f"var({_LABEL_SIZE})", + "letter_spacing": f"var({_LABEL_SPACING})", + "color": gray.a[10], + "cursor": "default", + }), +} + +SELECT_SEPARATOR: ComponentStyles = { + "base": unchecked({ + "height": "1px", + "margin_top": tokens.space[2], + "margin_bottom": tokens.space[2], + "margin_left": f"var({_INDICATOR})", + "margin_right": f"var({_SEPARATOR})", + "background_color": gray.a[6], + }), +} + +# The input that holds the value of a select, for a form: not seen, and not +# in the way of the pointer. +SELECT_VALUE: ComponentStyles = { + "base": { + "position": "absolute", + "width": "1px", + "height": "1px", + "margin": "0", + "padding": "0", + "border_width": "0", + "opacity": 0, + "pointer_events": "none", + }, +} + +SELECT: ComponentStyles = {"base": {"display": "contents"}} diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py new file mode 100644 index 00000000000..091acdb9395 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -0,0 +1,1581 @@ +"""Tests for reflex_components_ui.components.select.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import select as select_module +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the popups and the labels of each test from one.""" + monkeypatch.setattr(select_module, "_ids", itertools.count(1)) + + +class SelectState(rx.State): + """What a select is bound to.""" + + fruit: str = "apple" + fruits: list[str] = ["apple", "pear"] + is_open: bool = False + offset: int = 6 + + @rx.event + def set_fruit(self, fruit: str): + """Follow the select. + + Args: + fruit: The chosen value. + """ + self.fruit = fruit + + @rx.event + def set_is_open(self, is_open: bool): + """Follow the list of the select. + + Args: + is_open: Whether it is open. + """ + self.is_open = is_open + + @rx.event + def closed(self): + """Hear that the list closed.""" + + +def test_select( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """A select is a button that opens a popover of options, and an input that holds its value; the root hands its size to both and its state to the input.""" + component = rx.ui.select.root( + rx.ui.select.trigger( + placeholder="Pick", + variant="classic", + radius="full", + color_scheme="ruby", + id="pick", + margin="1px", + ), + rx.ui.select.content( + rx.ui.select.group( + rx.ui.select.label("Fruits"), + rx.ui.select.item("Apple", value="apple"), + rx.ui.select.item("Pear", value="pear", disabled=True, id="pear"), + ), + rx.ui.select.separator(), + rx.ui.select.item(rx.el.b("None"), value="none"), + variant="soft", + high_contrast=True, + color_scheme="jade", + side="top", + align="end", + side_offset=8, + align_offset=2, + position="popper", + z_index="5", + ), + default_value="pear", + name="fruit", + required=True, + disabled=True, + size="3", + default_open=True, + id="fruit", + ) + assert component.render() == { + "name": '"span"', + "props": [ + "className:sx_71b84cd269_c", + '"data-default-open":true', + '"data-rx-select":""', + 'id:"fruit"', + "onClick:selectClick", + "onKeyDown:selectKeyDown", + "onPointerMove:selectPointerMove", + "ref:ref_fruit", + ], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-autocomplete":"none"', + '"aria-controls":"rx-select-2"', + '"aria-expanded":"false"', + '"aria-haspopup":"listbox"', + 'className:sx_0f680e2b85_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', + '"data-state":"closed"', + "disabled:true", + 'id:"pick"', + 'popovertarget:"rx-select-2"', + "ref:ref_pick", + 'role:"combobox"', + 'type:"button"', + ], + "children": [ + { + "name": '"span"', + "props": [ + "className:sx_94480a599d_c", + '"data-placeholder":"Pick"', + '"data-rx-select-shown":""', + ], + "children": [{"contents": '"Pear"'}], + }, + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_9779d39f10_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'd:"M0.135232 3.15803C0.324102 2.95657 0.640521 2.94637 0.841971 3.13523L4.5 6.56464L8.158 3.13523C8.3595 2.94637 8.6759 2.95657 8.8648 3.15803C9.0536 3.35949 9.0434 3.67591 8.842 3.86477L4.84197 7.6148C4.64964 7.7951 4.35036 7.7951 4.15803 7.6148L0.158031 3.86477C-0.0434285 3.67591 -0.0536285 3.35949 0.135232 3.15803Z"' + ], + "children": [], + } + ], + }, + ], + }, + { + "name": '"div"', + "props": [ + 'className:sx_222d3d03d6_c + " " + reflexUIClasses_f97593a337', + '"data-rx-popup":""', + 'id:"rx-select-2"', + "onToggle:selectToggle", + 'popover:"auto"', + 'role:"listbox"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"div"', + "props": [ + '"aria-labelledby":"rx-select-label-1"', + 'role:"group"', + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_4c825b9931_c", + '"data-rx-select-label":""', + 'id:"rx-select-label-1"', + ], + "children": [{"contents": '"Fruits"'}], + }, + { + "name": '"div"', + "props": [ + '"aria-selected":"false"', + "className:sx_afbb711e7e_c", + '"data-value":"apple"', + 'role:"option"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_9209c0ff85_c"], + "children": [ + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_26fb6ce487_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'clipRule:"evenodd"', + 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', + 'fillRule:"evenodd"', + ], + "children": [], + } + ], + } + ], + }, + { + "name": '"span"', + "props": ['"data-rx-select-text":""'], + "children": [{"contents": '"Apple"'}], + }, + ], + }, + { + "name": '"div"', + "props": [ + '"aria-disabled":true', + '"aria-selected":"true"', + "className:sx_afbb711e7e_c", + '"data-value":"pear"', + 'id:"pear"', + "ref:ref_pear", + 'role:"option"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_9209c0ff85_c"], + "children": [ + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_26fb6ce487_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'clipRule:"evenodd"', + 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', + 'fillRule:"evenodd"', + ], + "children": [], + } + ], + } + ], + }, + { + "name": '"span"', + "props": ['"data-rx-select-text":""'], + "children": [{"contents": '"Pear"'}], + }, + ], + }, + ], + }, + { + "name": '"div"', + "props": ['"aria-hidden":true', "className:sx_2d671c061b_c"], + "children": [], + }, + { + "name": '"div"', + "props": [ + '"aria-selected":"false"', + "className:sx_afbb711e7e_c", + '"data-value":"none"', + 'role:"option"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_9209c0ff85_c"], + "children": [ + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_26fb6ce487_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'clipRule:"evenodd"', + 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', + 'fillRule:"evenodd"', + ], + "children": [], + } + ], + } + ], + }, + { + "name": '"span"', + "props": ['"data-rx-select-text":""'], + "children": [ + { + "name": '"b"', + "props": [], + "children": [{"contents": '"None"'}], + } + ], + }, + ], + }, + ], + }, + { + "name": '"input"', + "props": [ + '"aria-hidden":true', + "className:sx_b72d7382fd_c", + '"data-rx-select-value":""', + 'defaultValue:"pear"', + "disabled:true", + 'name:"fruit"', + "onFocus:selectFocus", + "ref:((holder) => syncSelect(holder, null, null))", + "required:true", + "tabIndex:-1", + ], + "children": [], + }, + ], + } + assert declared_styles(component) == [ + {"display": "contents"}, + { + "appearance": "none", + "marginTop": "1px", + "marginRight": "1px", + "marginBottom": "1px", + "marginLeft": "1px", + "paddingTop": "0", + "paddingRight": "var(--space-4)", + "paddingBottom": "0", + "paddingLeft": "var(--space-4)", + "borderTopWidth": {"default": "0", "::before": "2px"}, + "borderRightWidth": {"default": "0", "::before": "2px"}, + "borderBottomWidth": {"default": "0", "::before": "2px"}, + "borderLeftWidth": {"default": "0", "::before": "2px"}, + "borderTopStyle": {"default": "none", "::before": "solid"}, + "borderRightStyle": {"default": "none", "::before": "solid"}, + "borderBottomStyle": {"default": "none", "::before": "solid"}, + "borderLeftStyle": {"default": "none", "::before": "solid"}, + "backgroundColor": { + "default": "transparent", + ":disabled": "var(--gray-2)", + "::before": {":disabled": "var(--gray-a2)"}, + }, + "backgroundImage": { + "default": "linear-gradient(var(--gray-2), var(--gray-1))", + ":disabled": "none", + "::before": { + "default": "linear-gradient(var(--black-a1) -20%, transparent, var(--white-a1) 130%), linear-gradient(var(--color-surface), transparent)", + "@media (hover: hover)": { + ":hover:not(:disabled)": "linear-gradient(var(--black-a1) -15%, transparent, var(--white-a1) 120%), linear-gradient(var(--gray-2), var(--gray-1))" + }, + ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "linear-gradient(var(--black-a1) -15%, transparent, var(--white-a1) 120%), linear-gradient(var(--gray-2), var(--gray-1))", + ":disabled": "linear-gradient(var(--black-a1) -20%, transparent, var(--white-a1))", + }, + }, + "textTransform": "inherit", + "textIndent": "initial", + "wordSpacing": "inherit", + "cursor": { + "default": "var(--cursor-button)", + ":disabled": "var(--cursor-disabled)", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "space-between", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "outlineWidth": {"default": "medium", ":focus-visible": "2px"}, + "outlineColor": { + "default": "currentcolor", + ":focus-visible": "var(--focus-8)", + }, + "outlineOffset": {"default": "0", ":focus-visible": "-1px"}, + "--rx-select-icon-color": {":disabled": "var(--gray-a9)"}, + "--select-trigger-height": "var(--space-7)", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "fontSize": "var(--font-size-3)", + "lineHeight": "var(--line-height-3)", + "letterSpacing": "var(--letter-spacing-3)", + "borderRadius": "max(var(--radius-3), var(--radius-full))", + "boxSizing": "border-box", + "height": "var(--select-trigger-height)", + "--rx-select-shown-color": {"[data-placeholder]": "var(--gray-a10)"}, + "color": {"default": "var(--gray-12)", ":disabled": "var(--gray-a11)"}, + "boxShadow": { + "default": "var(--rx-if-light, inset 0 0 0 1px var(--gray-a5), inset 0 2px 1px var(--white-a11), inset 0 -2px 1px var(--gray-a4)) var(--rx-if-dark, inset 0 0 0 1px var(--white-a4), inset 0 1px 1px var(--white-a4), inset 0 -1px 1px var(--black-a9))", + "@media (hover: hover)": { + ":hover:not(:disabled)": "inset 0 0 0 1px var(--gray-a3), var(--rx-if-light, inset 0 0 0 1px var(--gray-a5), inset 0 2px 1px var(--white-a11), inset 0 -2px 1px var(--gray-a4)) var(--rx-if-dark, inset 0 0 0 1px var(--white-a4), inset 0 1px 1px var(--white-a4), inset 0 -1px 1px var(--black-a9))" + }, + ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "inset 0 0 0 1px var(--gray-a3), var(--rx-if-light, inset 0 0 0 1px var(--gray-a5), inset 0 2px 1px var(--white-a11), inset 0 -2px 1px var(--gray-a4)) var(--rx-if-dark, inset 0 0 0 1px var(--white-a4), inset 0 1px 1px var(--white-a4), inset 0 -1px 1px var(--black-a9))", + ":disabled": "var(--rx-if-light, inset 0 0 0 1px var(--gray-a4), inset 0 -2px 1px var(--gray-a3), inset 0 4px 2px -2px var(--white-a9), inset 0 2px 1px -1px var(--white-a9)) var(--rx-if-dark, inset 0 0 0 1px var(--gray-a5), inset 0 4px 2px -2px var(--gray-a2), inset 0 1px 1px var(--gray-a5), inset 0 -1px 1px var(--black-a3), inset 0 0 0 1px var(--gray-a2))", + }, + "position": {"default": "relative", "::before": "absolute"}, + "zIndex": {"default": 0, "::before": -1}, + "content": {"::before": "''"}, + "top": {"::before": "0"}, + "right": {"::before": "0"}, + "bottom": {"::before": "0"}, + "left": {"::before": "0"}, + "borderTopColor": {"::before": "transparent"}, + "borderRightColor": {"::before": "transparent"}, + "borderBottomColor": {"::before": "transparent"}, + "borderLeftColor": {"::before": "transparent"}, + "backgroundClip": {"::before": "content-box"}, + "borderTopLeftRadius": {"::before": "inherit"}, + "borderTopRightRadius": {"::before": "inherit"}, + "borderBottomRightRadius": {"::before": "inherit"}, + "borderBottomLeftRadius": {"::before": "inherit"}, + "pointerEvents": {"::before": "none"}, + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "textOverflow": "ellipsis", + "whiteSpace": "nowrap", + "color": "var(--rx-select-shown-color, inherit)", + "opacity": "var(--rx-select-shown-opacity, 1)", + }, + { + "flexShrink": 0, + "color": "var(--rx-select-icon-color, inherit)", + "opacity": 0.9, + "width": "11px", + "height": "11px", + }, + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "var(--rx-popup-offset, 4px)", + "marginRight": "var(--rx-popup-shift, 0px)", + "marginBottom": "var(--rx-popup-offset, 4px)", + "marginLeft": "0", + "padding": "var(--select-content-padding)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "calc(100vw - 10px * 2)", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "100ms", + ":popover-open": "160ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "var(--gray-12)", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-5)", + "minWidth": "anchor-size(width)", + "outlineStyle": "none", + "overflowY": "auto", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) transparent", + "--select-content-padding": "var(--space-2)", + "--select-item-height": "var(--space-6)", + "--select-item-indicator-width": "var(--space-5)", + "--select-separator-margin-right": "var(--space-3)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "--rx-select-font-size": "var(--font-size-3)", + "--rx-select-line-height": "var(--line-height-2)", + "--rx-select-letter-spacing": "var(--letter-spacing-3)", + "--rx-select-label-font-size": "var(--font-size-2)", + "--rx-select-label-letter-spacing": "var(--letter-spacing-2)", + "--rx-select-item-radius": "var(--radius-2)", + "--rx-select-check-size": "calc(10px * var(--scaling))", + "--rx-select-highlight": "var(--accent-a4)", + "positionArea": "top span-left", + "maxHeight": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", + "--rx-popup-from": "translateY(4px) scale(0.97)", + "transformOrigin": "bottom right", + "--rx-popup-offset": "8px", + "--rx-popup-shift": "2px", + "zIndex": "5", + }, + {}, + { + "display": "flex", + "alignItems": "center", + "height": "var(--select-item-height)", + "paddingLeft": "var(--select-item-indicator-width)", + "paddingRight": "var(--select-item-indicator-width)", + "userSelect": "none", + "fontSize": "var(--rx-select-label-font-size)", + "lineHeight": "var(--rx-select-line-height)", + "letterSpacing": "var(--rx-select-label-letter-spacing)", + "color": "var(--gray-a10)", + "cursor": "default", + }, + { + "display": "flex", + "alignItems": "center", + "height": "var(--select-item-height)", + "paddingLeft": "var(--select-item-indicator-width)", + "paddingRight": "var(--select-item-indicator-width)", + "userSelect": "none", + "fontSize": "var(--rx-select-font-size)", + "lineHeight": "var(--rx-select-line-height)", + "letterSpacing": "var(--rx-select-letter-spacing)", + "position": "relative", + "boxSizing": "border-box", + "outlineStyle": "none", + "scrollMarginTop": "var(--select-content-padding)", + "scrollMarginBottom": "var(--select-content-padding)", + "borderRadius": "var(--rx-select-item-radius)", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "color": { + "default": "inherit", + ":focus": "var(--rx-select-highlight-color, inherit)", + "[aria-disabled='true']": "var(--gray-a8)", + }, + "backgroundColor": {":focus": "var(--rx-select-highlight)"}, + "--rx-select-check": { + "default": "none", + "[aria-selected='true']": "inline-flex", + }, + }, + { + "position": "absolute", + "left": "0", + "width": "var(--select-item-indicator-width)", + "display": "var(--rx-select-check)", + "alignItems": "center", + "justifyContent": "center", + }, + { + "width": "var(--rx-select-check-size)", + "height": "var(--rx-select-check-size)", + }, + { + "display": "flex", + "alignItems": "center", + "height": "var(--select-item-height)", + "paddingLeft": "var(--select-item-indicator-width)", + "paddingRight": "var(--select-item-indicator-width)", + "userSelect": "none", + "fontSize": "var(--rx-select-font-size)", + "lineHeight": "var(--rx-select-line-height)", + "letterSpacing": "var(--rx-select-letter-spacing)", + "position": "relative", + "boxSizing": "border-box", + "outlineStyle": "none", + "scrollMarginTop": "var(--select-content-padding)", + "scrollMarginBottom": "var(--select-content-padding)", + "borderRadius": "var(--rx-select-item-radius)", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "color": { + "default": "inherit", + ":focus": "var(--rx-select-highlight-color, inherit)", + "[aria-disabled='true']": "var(--gray-a8)", + }, + "backgroundColor": {":focus": "var(--rx-select-highlight)"}, + "--rx-select-check": { + "default": "none", + "[aria-selected='true']": "inline-flex", + }, + }, + { + "position": "absolute", + "left": "0", + "width": "var(--select-item-indicator-width)", + "display": "var(--rx-select-check)", + "alignItems": "center", + "justifyContent": "center", + }, + { + "width": "var(--rx-select-check-size)", + "height": "var(--rx-select-check-size)", + }, + { + "height": "1px", + "marginTop": "var(--space-2)", + "marginBottom": "var(--space-2)", + "marginLeft": "var(--select-item-indicator-width)", + "marginRight": "var(--select-separator-margin-right)", + "backgroundColor": "var(--gray-a6)", + }, + { + "display": "flex", + "alignItems": "center", + "height": "var(--select-item-height)", + "paddingLeft": "var(--select-item-indicator-width)", + "paddingRight": "var(--select-item-indicator-width)", + "userSelect": "none", + "fontSize": "var(--rx-select-font-size)", + "lineHeight": "var(--rx-select-line-height)", + "letterSpacing": "var(--rx-select-letter-spacing)", + "position": "relative", + "boxSizing": "border-box", + "outlineStyle": "none", + "scrollMarginTop": "var(--select-content-padding)", + "scrollMarginBottom": "var(--select-content-padding)", + "borderRadius": "var(--rx-select-item-radius)", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "color": { + "default": "inherit", + ":focus": "var(--rx-select-highlight-color, inherit)", + "[aria-disabled='true']": "var(--gray-a8)", + }, + "backgroundColor": {":focus": "var(--rx-select-highlight)"}, + "--rx-select-check": { + "default": "none", + "[aria-selected='true']": "inline-flex", + }, + }, + { + "position": "absolute", + "left": "0", + "width": "var(--select-item-indicator-width)", + "display": "var(--rx-select-check)", + "alignItems": "center", + "justifyContent": "center", + }, + { + "width": "var(--rx-select-check-size)", + "height": "var(--rx-select-check-size)", + }, + { + "position": "absolute", + "width": "1px", + "height": "1px", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "opacity": 0, + "pointerEvents": "none", + }, + ] + + +def test_select_of_a_list( + ui_plugin: UIPlugin, +): + """The select of a list of words has an option for each, in a group named by its label, and gives its trigger and its list what is theirs.""" + component = rx.ui.select( + ["One", "Two"], + label="Numbers", + placeholder="Count", + default_value="Two", + variant="soft", + radius="small", + color_scheme="ruby", + high_contrast=True, + width="120px", + id="count", + name="count", + position="item-aligned", + ) + assert component.render() == { + "name": '"span"', + "props": [ + "className:sx_71b84cd269_c", + '"data-rx-select":""', + "onClick:selectClick", + "onKeyDown:selectKeyDown", + "onPointerMove:selectPointerMove", + ], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-autocomplete":"none"', + '"aria-controls":"rx-select-2"', + '"aria-expanded":"false"', + '"aria-haspopup":"listbox"', + 'className:sx_476d055388_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', + '"data-state":"closed"', + 'id:"count"', + 'popovertarget:"rx-select-2"', + "ref:ref_count", + 'role:"combobox"', + 'type:"button"', + ], + "children": [ + { + "name": '"span"', + "props": [ + "className:sx_94480a599d_c", + '"data-placeholder":"Count"', + '"data-rx-select-shown":""', + ], + "children": [{"contents": '"Two"'}], + }, + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_3c2399b961_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'd:"M0.135232 3.15803C0.324102 2.95657 0.640521 2.94637 0.841971 3.13523L4.5 6.56464L8.158 3.13523C8.3595 2.94637 8.6759 2.95657 8.8648 3.15803C9.0536 3.35949 9.0434 3.67591 8.842 3.86477L4.84197 7.6148C4.64964 7.7951 4.35036 7.7951 4.15803 7.6148L0.158031 3.86477C-0.0434285 3.67591 -0.0536285 3.35949 0.135232 3.15803Z"' + ], + "children": [], + } + ], + }, + ], + }, + { + "name": '"div"', + "props": [ + 'className:sx_d08c2fb679_c + " " + reflexUIClasses_e201574881', + '"data-rx-popup":""', + 'id:"rx-select-2"', + "onToggle:selectToggle", + 'popover:"auto"', + 'role:"listbox"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"div"', + "props": [ + '"aria-labelledby":"rx-select-label-1"', + 'role:"group"', + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_4c825b9931_c", + '"data-rx-select-label":""', + 'id:"rx-select-label-1"', + ], + "children": [{"contents": '"Numbers"'}], + }, + { + "name": '"div"', + "props": [ + '"aria-selected":"false"', + "className:sx_afbb711e7e_c", + '"data-value":"One"', + 'role:"option"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_9209c0ff85_c"], + "children": [ + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_26fb6ce487_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'clipRule:"evenodd"', + 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', + 'fillRule:"evenodd"', + ], + "children": [], + } + ], + } + ], + }, + { + "name": '"span"', + "props": ['"data-rx-select-text":""'], + "children": [{"contents": '"One"'}], + }, + ], + }, + { + "name": '"div"', + "props": [ + '"aria-selected":"true"', + "className:sx_afbb711e7e_c", + '"data-value":"Two"', + 'role:"option"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"span"', + "props": ["className:sx_9209c0ff85_c"], + "children": [ + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_26fb6ce487_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'clipRule:"evenodd"', + 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', + 'fillRule:"evenodd"', + ], + "children": [], + } + ], + } + ], + }, + { + "name": '"span"', + "props": ['"data-rx-select-text":""'], + "children": [{"contents": '"Two"'}], + }, + ], + }, + ], + } + ], + }, + { + "name": '"input"', + "props": [ + '"aria-hidden":true', + "className:sx_b72d7382fd_c", + '"data-rx-select-value":""', + 'defaultValue:"Two"', + 'name:"count"', + "onFocus:selectFocus", + "ref:((holder) => syncSelect(holder, null, null))", + "tabIndex:-1", + ], + "children": [], + }, + ], + } + + +def test_select_default_styles( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The styles of a select that is given no props, whose first option is in no group.""" + component = rx.ui.select.root( + rx.ui.select.trigger(), rx.ui.select.content(rx.ui.select.item("A", value="a")) + ) + assert declared_styles(component) == [ + {"display": "contents"}, + { + "appearance": "none", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "var(--space-3)", + "paddingBottom": "0", + "paddingLeft": "var(--space-3)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "var(--color-surface)", + ":disabled": "var(--gray-a2)", + }, + "backgroundImage": "none", + "textTransform": "inherit", + "textIndent": "initial", + "wordSpacing": "inherit", + "cursor": { + "default": "var(--cursor-button)", + ":disabled": "var(--cursor-disabled)", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "space-between", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "outlineWidth": {"default": "medium", ":focus-visible": "2px"}, + "outlineColor": { + "default": "currentcolor", + ":focus-visible": "var(--focus-8)", + }, + "outlineOffset": {"default": "0", ":focus-visible": "-1px"}, + "--rx-select-icon-color": {":disabled": "var(--gray-a9)"}, + "--select-trigger-height": "var(--space-6)", + "gap": "calc(var(--space-1) * 1.5)", + "fontSize": "var(--font-size-2)", + "lineHeight": "var(--line-height-2)", + "letterSpacing": "var(--letter-spacing-2)", + "borderRadius": "max(var(--radius-2), var(--radius-full))", + "boxSizing": "border-box", + "height": "var(--select-trigger-height)", + "--rx-select-shown-color": {"[data-placeholder]": "var(--gray-a10)"}, + "color": {"default": "var(--gray-12)", ":disabled": "var(--gray-a11)"}, + "boxShadow": { + "default": "inset 0 0 0 1px var(--gray-a7)", + "@media (hover: hover)": { + ":hover:not(:disabled)": "inset 0 0 0 1px var(--gray-a8)" + }, + ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "inset 0 0 0 1px var(--gray-a8)", + ":disabled": "inset 0 0 0 1px var(--gray-a6)", + }, + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "textOverflow": "ellipsis", + "whiteSpace": "nowrap", + "color": "var(--rx-select-shown-color, inherit)", + "opacity": "var(--rx-select-shown-opacity, 1)", + }, + { + "flexShrink": 0, + "color": "var(--rx-select-icon-color, inherit)", + "opacity": 0.9, + }, + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "var(--rx-popup-offset, 4px)", + "marginRight": "0", + "marginBottom": "var(--rx-popup-offset, 4px)", + "marginLeft": "var(--rx-popup-shift, 0px)", + "padding": "var(--select-content-padding)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "calc(100vw - 10px * 2)", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "100ms", + ":popover-open": "160ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "var(--gray-12)", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-5)", + "minWidth": "anchor-size(width)", + "outlineStyle": "none", + "overflowY": "auto", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) transparent", + "--select-content-padding": "var(--space-2)", + "--select-item-height": "var(--space-6)", + "--select-item-indicator-width": "var(--space-5)", + "--select-separator-margin-right": "var(--space-3)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "--rx-select-font-size": "var(--font-size-2)", + "--rx-select-line-height": "var(--line-height-2)", + "--rx-select-letter-spacing": "var(--letter-spacing-2)", + "--rx-select-label-font-size": "var(--font-size-2)", + "--rx-select-label-letter-spacing": "var(--letter-spacing-2)", + "--rx-select-item-radius": "var(--radius-2)", + "--rx-select-check-size": "calc(10px * var(--scaling))", + "--rx-select-highlight": "var(--accent-9)", + "--rx-select-highlight-color": "var(--accent-contrast)", + "positionArea": "bottom span-right", + "maxHeight": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", + "--rx-popup-from": "translateY(-4px) scale(0.97)", + "transformOrigin": "top left", + }, + { + "display": "flex", + "alignItems": "center", + "height": "var(--select-item-height)", + "paddingLeft": "var(--select-item-indicator-width)", + "paddingRight": "var(--select-item-indicator-width)", + "userSelect": "none", + "fontSize": "var(--rx-select-font-size)", + "lineHeight": "var(--rx-select-line-height)", + "letterSpacing": "var(--rx-select-letter-spacing)", + "position": "relative", + "boxSizing": "border-box", + "outlineStyle": "none", + "scrollMarginTop": "var(--select-content-padding)", + "scrollMarginBottom": "var(--select-content-padding)", + "borderRadius": "var(--rx-select-item-radius)", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "color": { + "default": "inherit", + ":focus": "var(--rx-select-highlight-color, inherit)", + "[aria-disabled='true']": "var(--gray-a8)", + }, + "backgroundColor": {":focus": "var(--rx-select-highlight)"}, + "--rx-select-check": { + "default": "none", + "[aria-selected='true']": "inline-flex", + }, + }, + { + "position": "absolute", + "left": "0", + "width": "var(--select-item-indicator-width)", + "display": "var(--rx-select-check)", + "alignItems": "center", + "justifyContent": "center", + }, + { + "width": "var(--rx-select-check-size)", + "height": "var(--rx-select-check-size)", + }, + { + "position": "absolute", + "width": "1px", + "height": "1px", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "opacity": 0, + "pointerEvents": "none", + }, + ] + + +def test_select_ghost_styles( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], +): + """The ghost trigger, and a list beside its trigger and centered on it.""" + component = rx.ui.select.root( + rx.ui.select.trigger(variant="ghost"), + rx.ui.select.content(side="left", align="center"), + size="1", + ) + assert declared_styles(component) == [ + {"display": "contents"}, + { + "appearance": "none", + "marginTop": "calc(0px - var(--select-trigger-ghost-padding-y))", + "marginRight": "calc(0px - var(--select-trigger-ghost-padding-x))", + "marginBottom": "calc(0px - var(--select-trigger-ghost-padding-y))", + "marginLeft": "calc(0px - var(--select-trigger-ghost-padding-x))", + "paddingTop": "var(--select-trigger-ghost-padding-y)", + "paddingRight": "var(--select-trigger-ghost-padding-x)", + "paddingBottom": "var(--select-trigger-ghost-padding-y)", + "paddingLeft": "var(--select-trigger-ghost-padding-x)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "@media (hover: hover)": {":hover:not(:disabled)": "var(--accent-a3)"}, + ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "var(--accent-a3)", + ":disabled": "transparent", + }, + "backgroundImage": "none", + "textTransform": "inherit", + "textIndent": "initial", + "wordSpacing": "inherit", + "cursor": { + "default": "var(--cursor-button)", + ":disabled": "var(--cursor-disabled)", + }, + "WebkitTapHighlightColor": "transparent", + "display": "inline-flex", + "alignItems": "center", + "justifyContent": "space-between", + "flexShrink": 0, + "userSelect": "none", + "verticalAlign": "top", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "outlineWidth": {"default": "medium", ":focus-visible": "2px"}, + "outlineColor": { + "default": "currentcolor", + ":focus-visible": "var(--focus-8)", + }, + "outlineOffset": {"default": "0", ":focus-visible": "-1px"}, + "--rx-select-icon-color": {":disabled": "var(--gray-a9)"}, + "--select-trigger-height": "var(--space-5)", + "rowGap": "var(--space-1)", + "columnGap": "var(--space-1)", + "fontSize": "var(--font-size-1)", + "lineHeight": "var(--line-height-1)", + "letterSpacing": "var(--letter-spacing-1)", + "borderRadius": "max(var(--radius-1), var(--radius-full))", + "--rx-select-shown-color": {"[data-placeholder]": "var(--accent-12)"}, + "--rx-select-shown-opacity": {"[data-placeholder]": 0.6}, + "boxSizing": "content-box", + "height": "fit-content", + "color": {"default": "var(--accent-12)", ":disabled": "var(--gray-a11)"}, + "--select-trigger-ghost-padding-x": "var(--space-2)", + "--select-trigger-ghost-padding-y": "var(--space-1)", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "textOverflow": "ellipsis", + "whiteSpace": "nowrap", + "color": "var(--rx-select-shown-color, inherit)", + "opacity": "var(--rx-select-shown-opacity, 1)", + }, + {"flexShrink": 0, "color": "var(--rx-select-icon-color, inherit)"}, + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "0", + "marginRight": "var(--rx-popup-offset, 4px)", + "marginBottom": "0", + "marginLeft": "var(--rx-popup-offset, 4px)", + "padding": "var(--select-content-padding)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "100ms", + ":popover-open": "160ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "var(--gray-12)", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-5)", + "minWidth": "anchor-size(width)", + "outlineStyle": "none", + "overflowY": "auto", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) transparent", + "--select-content-padding": "var(--space-1)", + "--select-item-height": "var(--space-5)", + "--select-item-indicator-width": "calc(var(--space-5) / 1.2)", + "--select-separator-margin-right": "var(--space-2)", + "borderTopLeftRadius": "var(--radius-3)", + "borderTopRightRadius": "var(--radius-3)", + "borderBottomRightRadius": "var(--radius-3)", + "borderBottomLeftRadius": "var(--radius-3)", + "--rx-select-font-size": "var(--font-size-1)", + "--rx-select-line-height": "var(--line-height-1)", + "--rx-select-letter-spacing": "var(--letter-spacing-1)", + "--rx-select-label-font-size": "var(--font-size-1)", + "--rx-select-label-letter-spacing": "var(--letter-spacing-1)", + "--rx-select-item-radius": "var(--radius-1)", + "--rx-select-check-size": "calc(8px * var(--scaling))", + "--rx-select-highlight": "var(--accent-9)", + "--rx-select-highlight-color": "var(--accent-contrast)", + "positionArea": "left span-all", + "--rx-popup-from": "translateX(4px) scale(0.97)", + "transformOrigin": "right center", + "alignSelf": "anchor-center", + }, + { + "position": "absolute", + "width": "1px", + "height": "1px", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "opacity": 0, + "pointerEvents": "none", + }, + ] + + +def test_select_unknown_variant(ui_plugin: UIPlugin): + """A variant a trigger does not have is an error that lists the ones it has.""" + with pytest.raises(StyleError) as error: + rx.ui.select.trigger(variant="solid") + assert ( + str(error.value) + == 'rx.ui.select_trigger: unknown variant "solid". The values are "classic", "surface", "soft", "ghost".' + ) + + +def test_select_unknown_side(ui_plugin: UIPlugin): + """A side a list cannot be on is an error that lists the sides.""" + with pytest.raises(StyleError) as error: + rx.ui.select.content(side="above") + assert ( + str(error.value) + == 'rx.ui.select_content: unknown side "above". The values are "top", "right", "bottom", "left".' + ) + + +def test_select_of_a_list_unknown_variant(ui_plugin: UIPlugin): + """The select of a list of words fails as its trigger does.""" + with pytest.raises(StyleError) as error: + rx.ui.select(["a"], variant="outline") + assert ( + str(error.value) + == 'rx.ui.select_trigger: unknown variant "outline". The values are "classic", "surface", "soft", "ghost".' + ) + + +STATE = ( + "reflex___state____state__tests___units___reflex_components_ui" + "___components___test_select____select_state" +) +HANDLER = ( + "reflex___state____state.tests___units___reflex_components_ui" + "___components___test_select____select_state" +) + + +def _event(handler: str, argument: str) -> str: + """Write the function an event handler with one argument renders as. + + Args: + handler: The name of the handler. + argument: The name of its argument. + + Returns: + The function. + """ + return ( + f'((_ev_0) => (addEvents([(ReflexEvent("{HANDLER}.{handler}", ' + f'({{ ["{argument}"] : _ev_0 }}), ({{ }})))], [_ev_0], ({{ }}))))' + ) + + +def test_select_bound_to_state(ui_plugin: UIPlugin): + """A select bound to state hands its value and whether it is open to its script, and its events to the input and the popover.""" + select = rx.ui.select.root( + rx.ui.select.trigger(placeholder="Pick"), + rx.ui.select.content( + rx.ui.select.item("Apple", value="apple"), + rx.ui.select.item("Pear", value="pear"), + side_offset=SelectState.offset, + on_close_auto_focus=SelectState.closed, + on_escape_key_down=SelectState.closed, + on_pointer_down_outside=SelectState.closed, + ), + value=SelectState.fruit, + open=SelectState.is_open, + on_change=SelectState.set_fruit, + on_open_change=SelectState.set_is_open, + ) + fruit = f"{STATE}.fruit_rx_state_" + closed = ( + f'((...args) => (addEvents([(ReflexEvent("{HANDLER}.closed", ({{ }}), ' + "({ })))], args, ({ }))))" + ) + trigger, content, holder = select.children + assert select.render()["props"] == [ + "className:sx_71b84cd269_c", + '"data-rx-select":""', + ( + f'onChange:((_e) => (addEvents([(ReflexEvent("{HANDLER}.set_fruit", ' + '({ ["fruit"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))' + ), + "onClick:selectClick", + "onKeyDown:selectKeyDown", + "onPointerMove:selectPointerMove", + ] + assert trigger.render()["props"] == [ + '"aria-autocomplete":"none"', + '"aria-controls":"rx-select-1"', + '"aria-expanded":"false"', + '"aria-haspopup":"listbox"', + "className:sx_872142009a_c", + f'"data-placeholder":({fruit} ? undefined : "")', + '"data-state":"closed"', + 'popovertarget:"rx-select-1"', + 'role:"combobox"', + 'type:"button"', + ] + assert trigger.children[0].render() == { + "name": '"span"', + "props": [ + "className:sx_94480a599d_c", + '"data-placeholder":"Pick"', + '"data-rx-select-shown":""', + ], + "children": [ + { + "contents": ( + '(({ ["apple"] : "Apple", ["pear"] : "Pear" })' + f'[{fruit}] ?? "Pick")' + ) + } + ], + } + assert content.render()["props"] == [ + "className:sx_bb2bcf4a84_c", + '"data-rx-popup":""', + 'id:"rx-select-1"', + ( + "onToggle:((event) => selectToggle(event, ({ " + f"open: {_event('set_is_open', 'is_open')}, " + f"close: {closed}, escape: {closed}, outside: {closed} }})))" + ), + 'popover:"auto"', + 'role:"listbox"', + (f'style:({{ "--v0": ((({STATE}.offset_rx_state_) + "px")) ?? "initial" }})'), + "tabIndex:-1", + ] + assert str(content._element_styles().style.style["--rx-popup-offset"]) == ( + f'(({STATE}.offset_rx_state_) + "px")' + ) + assert [item.render()["props"][0] for item in content.children] == [ + f'"aria-selected":(({fruit} === "apple") ? "true" : "false")', + f'"aria-selected":(({fruit} === "pear") ? "true" : "false")', + ] + assert holder.render()["props"] == [ + '"aria-hidden":true', + "className:sx_b72d7382fd_c", + '"data-rx-select-value":""', + f"defaultValue:{fruit}", + "onFocus:selectFocus", + (f"ref:((holder) => syncSelect(holder, {fruit}, {STATE}.is_open_rx_state_))"), + "tabIndex:-1", + ] + + +def test_select_of_a_list_in_state(ui_plugin: UIPlugin): + """Options a foreach renders show their values, so the trigger shows the value of the select.""" + select = rx.ui.select(SelectState.fruits, value=SelectState.fruit) + trigger, content, _ = select.children + assert trigger.children[0].render()["children"] == [ + {"contents": f'({STATE}.fruit_rx_state_ || "")'} + ] + (group,) = content.children + (options,) = group.children + item = options.children[0] + assert item.render()["props"] == [ + ( + f'"aria-selected":(({STATE}.fruit_rx_state_ === item_rx_state_) ' + '? "true" : "false")' + ), + "className:sx_afbb711e7e_c", + '"data-value":item_rx_state_', + "key:index_d6d6157c99650830f12a866606ea87b7", + 'role:"option"', + "tabIndex:-1", + ] + + +def test_select_shows_what_it_knows(ui_plugin: UIPlugin): + """The trigger shows the placeholder for a value no option has, for options that hold more than text, and what it is given in place of either.""" + item, trigger, content = ( + rx.ui.select.item, + rx.ui.select.trigger, + rx.ui.select.content, + ) + + def shown(*options: Any, trigger_children: tuple[Any, ...] = (), **props: Any): + root = rx.ui.select.root( + trigger(*trigger_children, placeholder="Pick"), content(*options), **props + ) + rendered = root.children[0].children[0].render() + return rendered["props"][1:], rendered["children"] + + mark = ['"data-placeholder":"Pick"', '"data-rx-select-shown":""'] + assert shown(item("A", value="a")) == (mark, [{"contents": '"Pick"'}]) + assert shown(item("A", value="a"), default_value="b") == ( + mark, + [{"contents": '"Pick"'}], + ) + assert shown(item(rx.el.b("A"), value="a"), default_value="a") == ( + mark, + [{"contents": '"Pick"'}], + ) + assert shown(item(rx.el.b("A"), value="a"), value=SelectState.fruit) == ( + mark, + [{"contents": '"Pick"'}], + ) + assert shown( + item("A", value="a"), trigger_children=("Custom",), default_value="a" + ) == ([], [{"contents": '"Custom"'}]) + + +def test_select_script(ui_plugin: UIPlugin): + """The script of a select is imported by the parts that call it.""" + select = rx.ui.select(["a"]) + assert select._get_all_imports()["$/reflex-ui/behaviors/listbox.js"] == [ + ImportVar(tag="selectKeyDown"), + ImportVar(tag="selectClick"), + ImportVar(tag="selectPointerMove"), + ImportVar(tag="selectToggle"), + ImportVar(tag="syncSelect"), + ImportVar(tag="selectFocus"), + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 8b40a52bd6e..96db2fea6ac 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -163,6 +163,14 @@ def test_every_wave_is_in_the_namespace(): "section", "segmented_control.item", "segmented_control.root", + "select", + "select.content", + "select.group", + "select.item", + "select.label", + "select.root", + "select.separator", + "select.trigger", "separator", "skeleton", "slider", From 6f9508b797b83ec5dc6e9ee4fa60939b7154c905 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 03:40:45 +0000 Subject: [PATCH 078/204] Let the sonner package import and build without reflex-components-core The toast module created its ToasterRequest marker with Component.create() at import time, which imports reflex-components-core. That package depends on sonner, so it is absent from sonner's stub-generating build environment and from an install of sonner alone: every workspace build that pulls in sonner failed with ModuleNotFoundError. Create the marker with _create(), and skip child validation (the other import of the core components) for a component with no children. Sonner now needs that reflex-base change, so raise its floor. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../src/reflex_base/components/component.py | 5 ++++ .../reflex-components-sonner/pyproject.toml | 2 +- .../src/reflex_components_sonner/toast.py | 4 ++- .../reflex_components_sonner/test_toast.py | 25 +++++++++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/packages/reflex-base/src/reflex_base/components/component.py b/packages/reflex-base/src/reflex_base/components/component.py index a2eeda86795..3d307b0e031 100644 --- a/packages/reflex-base/src/reflex_base/components/component.py +++ b/packages/reflex-base/src/reflex_base/components/component.py @@ -1562,6 +1562,11 @@ def _validate_component_children(self, children: list[Component]): children: The children of the component. """ + # Nothing to validate, and a component without children can then be + # created where reflex-components-core is not installed. + if not children: + return + from reflex_components_core.base.fragment import Fragment from reflex_components_core.core.cond import Cond from reflex_components_core.core.foreach import Foreach diff --git a/packages/reflex-components-sonner/pyproject.toml b/packages/reflex-components-sonner/pyproject.toml index 74139a5da70..4c5d63049aa 100644 --- a/packages/reflex-components-sonner/pyproject.toml +++ b/packages/reflex-components-sonner/pyproject.toml @@ -16,7 +16,7 @@ classifiers = [ "Programming Language :: Python :: 3.15", ] dependencies = [ - "reflex-base >= 0.10.0", + "reflex-base >= 0.11.1.dev0", "reflex-components-lucide >= 1.1.0", ] 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 af711f0874c..af8dc2ffe7a 100644 --- a/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py +++ b/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py @@ -47,7 +47,9 @@ class ToasterRequest(Component): _js_expr="refs['__toast']", _var_data=VarData( imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]}, - app_wraps=[(44, ToasterRequest.create())], + # Not create(): that imports reflex-components-core, which depends on + # this package and so is absent when it is installed or built alone. + app_wraps=[(44, ToasterRequest._create([]))], ), ) diff --git a/tests/units/reflex_components_sonner/test_toast.py b/tests/units/reflex_components_sonner/test_toast.py index cf87981b5fe..fdf4b040b89 100644 --- a/tests/units/reflex_components_sonner/test_toast.py +++ b/tests/units/reflex_components_sonner/test_toast.py @@ -1,6 +1,8 @@ """Sonner toast component tests.""" import json +import subprocess +import sys from reflex_base.style import Style from reflex_components_sonner.toast import Toaster, ToasterRequest, ToastProps, toast @@ -45,3 +47,26 @@ def test_toast_call_asks_the_app_for_its_toaster(): # Left in place, the marker renders nothing of its own. assert str(ToasterRequest.create()) == "jsx(Fragment,{},)" + + +def test_toast_module_imports_without_components_core(): + """Importing the toast module must not need reflex-components-core. + + reflex-components-core depends on this package, so neither an install of + this package alone nor its stub-generating build has the core components. + """ + script = ( + "import sys\n" + "sys.modules['reflex_components_core'] = None\n" + "from reflex_components_sonner.toast import ToasterRequest, toast_ref\n" + "[(priority, wrapper)] = toast_ref._get_all_var_data().app_wraps\n" + "print(priority, type(wrapper) is ToasterRequest, wrapper.render())\n" + ) + result = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, check=False + ) + assert (result.returncode, result.stdout, result.stderr) == ( + 0, + f"44 True {ToasterRequest.create().render()}\n", + "", + ) From 9c39d53f58c07056b10251e75f6e564038ad4df8 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 03:42:08 +0000 Subject: [PATCH 079/204] Follow the app root's per-library loaders in the docs frontend test The docs regression test rewrites the generated app root's dynamic imports to fixtures by their literal text. The root now loads each optional library from its own module under $/utils/dynamic_libraries and takes the module's default export, and renders with React's createElement instead of emotion's jsx, so the rewrite no longer matched and node tried to import '$'. Match the new specifiers, hand the fixtures over as default exports, and assert that no import other than the unused emotion loader survives the rewrite, so a later change of shape fails with a readable message. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- docs/app/tests/frontend_quality.test.mjs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/app/tests/frontend_quality.test.mjs b/docs/app/tests/frontend_quality.test.mjs index 97adad37035..8934d522e3a 100644 --- a/docs/app/tests/frontend_quality.test.mjs +++ b/docs/app/tests/frontend_quality.test.mjs @@ -154,14 +154,14 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ bundle_library('constructor') print(json.dumps({'root': compile_app_root(rx.el.div('Quality'))[1], 'component': serializers.serialize(Quality.create())})) `], {cwd: root, encoding: "utf8"}).trim().split("\n").at(-1)); - const setup = new Function("window", "React", "emotion_react", "utils_context", "utils_context_registry", "utils_state", "loadFixture", "loadConstructor", + const setup = new Function("window", "React", "utils_context", "utils_context_registry", "utils_state", "loadFixture", "loadConstructor", generated.root.replace(/^import .*$/gm, "") .replace(/^export default function/gm, "function") .replace(/^export /gm, "") - .replace('import("quality-lazy-fixture")', 'loadFixture()') - .replace('import("constructor")', 'loadConstructor()')); - // Render the component's jsx call directly, so a component returns the fixture's value. - const emotion = {jsx: (type, props) => type(props)}; + .replace('import("$/utils/dynamic_libraries/quality_lazy_fixture")', 'loadFixture()') + .replace('import("$/utils/dynamic_libraries/constructor")', 'loadConstructor()')); + // The app root must reach each fixture through the loader it was given, never a real import. + assert.deepEqual(setup.toString().match(/import\("[^"]*"\)/g), ['import("$/utils/dynamic_libraries/emotion_react")']); const stateSource = await readFile(path.join(root, "packages/reflex-frontend/src/utils/state.js"), "utf8"); // Parse the complete module so nested statements cannot truncate the export. const { parseAst } = await import(resolve("rolldown/parseAst")); @@ -171,11 +171,12 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ assert(evaluateExport, "state.js exports evalReactComponent"); const { evalReactComponent: evaluate } = await import(moduleUrl(stateSource.slice(evaluateExport.start, evaluateExport.end))); const previousWindow = globalThis.window; - const react = {quality: "same React instance"}; + // Render the component's jsx call directly, so a component returns the fixture's value. + const react = {quality: "same React instance", createElement: (type, props) => type(props)}; try { let calls = 0; globalThis.window = {}; - setup(window, react, emotion, {}, {}, {}, async () => {calls++; return {Quality: () => 42};}); + setup(window, react, {}, {}, {}, async () => {calls++; return {default: {Quality: () => 42}};}); assert.equal(calls, 0); assert.equal(window.__reflex.react, react); assert.equal(window.__reflex["quality-lazy-fixture"], undefined); @@ -189,9 +190,9 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ let attempts = 0; globalThis.window = {}; - setup(window, react, emotion, {}, {}, {}, async () => { + setup(window, react, {}, {}, {}, async () => { if (++attempts === 1) throw new Error("Temporary download failure"); - return {Quality: () => 43}; + return {default: {Quality: () => 43}}; }); const retrySource = source + "\n// retry fixture"; await assert.rejects(evaluate(retrySource), /Temporary download failure/); @@ -203,7 +204,7 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ let constructorCalls = 0; globalThis.window = {}; const constructorModule = {name: "constructor library"}; - setup(window, react, emotion, {}, {}, {}, async () => ({}), async () => {constructorCalls++; return constructorModule;}); + setup(window, react, {}, {}, {}, async () => ({default: {}}), async () => {constructorCalls++; return {default: constructorModule};}); await window.__reflex_load(["constructor"]); assert.equal(constructorCalls, 1); assert.equal(window.__reflex.constructor, constructorModule); From e8af5654688ddf0ed6224f5b3b49ea3ae18c73ec Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 03:46:16 +0000 Subject: [PATCH 080/204] Compare a progress keyframe offset to the precision Firefox keeps Firefox stores a keyframe offset as a 32-bit float, so the 20%, 30% and 40% stops of the indeterminate bar read back as 0.20000000298 and so on, for the Radix reference and for rx.ui alike. Round the offset the contract reads to six decimals, which is what such a float holds. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../parity/ui_parity/components/progress.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/progress.py b/packages/reflex-components-ui/parity/ui_parity/components/progress.py index 70bdc2d14a4..cc9ddfc3eb3 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/progress.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/progress.py @@ -127,7 +127,9 @@ def advance(self): ) # What an indeterminate bar plays, as `getAnimations()` reports it: the -# indicator grows, fades and pulses, and a shine crosses it. +# indicator grows, fades and pulses, and a shine crosses it. Firefox keeps a +# keyframe offset as a 32-bit float, so `20%` reads back as 0.20000000298: +# an offset is compared to the six decimals such a float holds. ANIMATIONS = """element => element.getAnimations({subtree: true}).map(animation => { const {delay, duration, iterations, fill, direction, easing} = animation.effect.getTiming(); @@ -135,7 +137,10 @@ def advance(self): on: animation.effect.pseudoElement, timing: {delay, duration, iterations, fill, direction, easing}, frames: animation.effect.getKeyframes().map( - ({computedOffset, composite, ...frame}) => frame + ({computedOffset, composite, offset, ...frame}) => ({ + offset: Math.round(offset * 1e6) / 1e6, + ...frame, + }) ), }; })""" From 55a2bbc15390190d9651a1957541c86a4fb841d4 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 03:56:23 +0000 Subject: [PATCH 081/204] Cover the form controls in the shared app, and say how behaviour is built A /controls page of the shared integration app holds every form control in one form: a text field and a select bound to state, native inputs driven by the browser, and the values the form hands over. The README gains the behaviour section of 'Adding a component': the order from native element to script, the shape of a script, how open state reaches styles, and the size of each script. props.style_before replaces four copies of the same lines, and a unit test covers parts a foreach or a cond renders. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- packages/reflex-components-ui/README.md | 104 +++++- .../news/+wave3-form-controls.feature.md | 14 +- .../components/segmented_control.py | 9 +- .../reflex_components_ui/components/select.py | 49 +-- .../reflex_components_ui/components/slider.py | 9 +- .../src/reflex_components_ui/props.py | 25 +- pyi_hashes.json | 18 +- .../tests_playwright/test_ui_components.py | 300 ++++++++++++++++++ tests/units/reflex_components_ui/test_base.py | 17 + .../units/reflex_components_ui/test_props.py | 18 +- 10 files changed, 500 insertions(+), 63 deletions(-) diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 7cb652f32f9..42975892bf3 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -458,6 +458,107 @@ What the display and action wave settled, for the waves after it: styles in the order they are written, and a whole shorthand written after its longhands cancels them. Write each side out, as the ghost button does. +### Behaviour: the browser first, a script for the gap + +What a component does is the contract of its Radix counterpart, kept with +as little JavaScript as the browser allows. In this order: + +1. **An element that already does it.** A checkbox, a radio button, a + switch and a thumb of a slider are native inputs, drawn by their table + with `appearance: none` and their `::before` and `::after`; an item with + text is a `
+ +
B
+
C
+ `; + root = /** @type {HTMLElement} */ (document.getElementById("root")); +} + +beforeEach(() => render('data-rx-accordion="single"')); + +/** + * Press an element of the accordion. + * + * @param {string | null} id The id of the element, or null for no element. + * @param {(value: string | string[]) => void} [onValueChange] What the + * accordion does when its open items change. + * @returns {boolean} Whether the accordion kept the press from the browser. + */ +function press(id, onValueChange) { + let prevented = false; + accordionClick( + { + target: id ? document.getElementById(id) : null, + currentTarget: root, + preventDefault: () => { + prevented = true; + }, + }, + onValueChange, + ); + return prevented; +} + +test("the open item of an accordion that does not collapse stays open", () => { + const onValueChange = vi.fn(); + expect(press("a", onValueChange)).toBe(true); + expect(press("a-text", onValueChange)).toBe(true); + expect(onValueChange.mock.calls).toEqual([]); + expect(press("b", onValueChange)).toBe(false); + expect(onValueChange.mock.calls).toEqual([["b"]]); +}); + +test("a collapsible accordion closes its open item, and says that none is open", () => { + render('data-rx-accordion="single" data-collapsible="true"'); + const onValueChange = vi.fn(); + expect(press("a", onValueChange)).toBe(false); + expect(press("c", onValueChange)).toBe(false); + expect(press("b")).toBe(false); + expect(onValueChange.mock.calls).toEqual([[""], [""]]); +}); + +test("an accordion of several says which items are open after the press", () => { + render('data-rx-accordion="multiple"'); + const onValueChange = vi.fn(); + expect(press("b", onValueChange)).toBe(false); + expect(press("a", onValueChange)).toBe(false); + expect(press("c", onValueChange)).toBe(false); + expect(onValueChange.mock.calls).toEqual([[["a", "b"]], [[]], [["a", ""]]]); +}); + +test("an accordion bound to state leaves its items to its state", () => { + render('data-rx-accordion="multiple" data-bound=""'); + const onValueChange = vi.fn(); + expect(press("b", onValueChange)).toBe(true); + expect(press("b")).toBe(true); + expect(onValueChange.mock.calls).toEqual([[["a", "b"]]]); +}); + +test("a press on anything but a header of the accordion is left alone", () => { + const onValueChange = vi.fn(); + expect(press("inside", onValueChange)).toBe(false); + expect(press("inner", onValueChange)).toBe(false); + expect(press("root", onValueChange)).toBe(false); + expect(press(null, onValueChange)).toBe(false); + expect(onValueChange.mock.calls).toEqual([]); +}); diff --git a/packages/reflex-components-ui/news/+wave4-overlays.feature.md b/packages/reflex-components-ui/news/+wave4-overlays.feature.md index 174b3f89cf0..8788a5c71b8 100644 --- a/packages/reflex-components-ui/news/+wave4-overlays.feature.md +++ b/packages/reflex-components-ui/news/+wave4-overlays.feature.md @@ -1 +1 @@ -Add the overlays and the disclosure components to `rx.ui`: `tabs`, with the members of its namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. +Add the overlays and the disclosure components to `rx.ui`: `tabs` and `accordion`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 54e21a45036..9ace51c9f1c 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -284,3 +284,38 @@ component = "tabs" step = "a trigger and a panel given ids of their own name each other" system = "rx" reason = "A trigger of rx.tabs names its panel, and the panel its trigger, by an id rx.tabs makes up, so giving either an `id` breaks the link and a screen reader no longer says which tab a panel belongs to. rx.ui.tabs names each by the id it was given." + +[[look]] +component = "accordion" +check = "a11y" +reason = "An item of rx.ui.accordion is a native `details`: its header is the `summary`, which holds the heading and says by itself whether the item is open, where the header of rx.accordion is a heading that holds a button with `aria-expanded`. A screen reader announces both as a heading that expands and collapses." + +[[look]] +component = "accordion" +check = "style" +cells = "*@focus-visible" +properties = ["outline-style", "outline-width", "outline-color"] +reason = "The ring of the keyboard's focus is drawn by the browser around the `summary` of the item, which is what takes the focus in rx.ui.accordion, and around the button inside the heading in rx.accordion. It is the same ring in the same place." + +[[look]] +component = "accordion" +check = "style" +cells = "disabled-true*" +properties = ["pointer-events"] +reason = "The header of a disabled item of rx.ui.accordion lets the pointer through, so the item cannot be opened with or without JavaScript. rx.accordion disables the button of the header." + +[[contract]] +component = "accordion" +step = "opens and closes an item with JavaScript disabled" +system = "rx" +reason = "rx.accordion is opened by JavaScript: until it has run, a press on a header does nothing. An item of rx.ui.accordion is a native `details`, which the browser opens and closes with or without JavaScript, one at a time when the accordion is `type=\"single\"`; only an open item of an accordion that is not `collapsible` needs JavaScript to stay open when it is pressed." + +[[contract]] +component = "accordion" +step = "the arrow keys, Home and End move between the headers" +reason = "The headers of rx.ui.accordion are native `summary` elements: Tab and Shift+Tab move between them, as between the headers of any `details`, and Enter and Space open and close an item. rx.accordion also moves between its headers with the arrow keys, Home and End, and `orientation` says which arrow keys do." + +[[contract]] +component = "accordion" +step = "hands over the open items in the order they were opened in" +reason = "`on_value_change` of an rx.ui.accordion of `type=\"multiple\"` hands over the values of the open items in the order of the items, whatever the order they were opened in: the accordion keeps no state of its own and reads its items. rx.accordion appends each value as it is opened." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/accordion.py b/packages/reflex-components-ui/parity/ui_parity/components/accordion.py new file mode 100644 index 00000000000..77b92a0695c --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/accordion.py @@ -0,0 +1,452 @@ +"""The accordion: every variant, closed, open and with several items, and its keys.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import wait_for_text + +VARIANTS = ["classic", "soft", "surface", "outline", "ghost"] +RADII = ["none", "small", "full"] +STATES = [HOVER, FOCUS_VISIBLE] +NAMES = ("First", "Second", "Third") + + +def _accordion(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create an accordion of three items. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the root. ``item_variant`` and ``item_color`` + are the variant and the color of the second item, ``disabled`` + says that the last item is, and ``parts`` asks for items made + of their parts, with a header of two lines. + + Returns: + The accordion. + """ + props = dict(props) + accordion = namespace.accordion + second = { + prop: props.pop(key) + for key, prop in (("item_variant", "variant"), ("item_color", "color_scheme")) + if key in props + } + disabled = props.pop("disabled", False) + if props.pop("parts", False): + items = [ + accordion.item( + accordion.header( + accordion.trigger( + rx.el.span(f"{name} item, with a header long enough for two"), + accordion.icon(), + ) + ), + accordion.content(rx.el.p(f"What the {name.lower()} item holds.")), + value=name.lower(), + ) + for name in NAMES + ] + else: + items = [ + accordion.item( + header=name, + content=f"What the {name.lower()} item holds.", + value=name.lower(), + **(second if name == "Second" else {}), + **({"disabled": True} if disabled and name == "Third" else {}), + ) + for name in NAMES + ] + return accordion.root(*items, **props) + + +def _focus(page: Page, target: Locator, point: Point) -> None: + """Focus the header of an item as the keyboard does. + + Args: + page: The page. + target: The trigger: a button of Radix, the heading in a summary here. + point: The middle of the trigger. + """ + page.keyboard.press("Tab") + target.evaluate("element => (element.closest('summary') ?? element).focus()") + + +def _blur(page: Page, target: Locator, point: Point) -> None: + """Take the focus off whatever has it. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + page.evaluate("document.activeElement.blur()") + + +MATRIX = Matrix( + component="accordion", + render=_accordion, + base={"default_value": "second", "collapsible": True}, + cross={"variant": VARIANTS, "default_value": {"second": "second", "none": None}}, + sweep={ + "color_scheme": ["ruby", "gray", "yellow", "indigo"], + "radius": RADII, + "show_dividers": [True, False], + "disabled": [True], + "parts": [True], + "type": ["multiple"], + "item_variant": VARIANTS, + "item_color": ["ruby"], + "appearance": [DARK], + "state": STATES, + }, + groups=[ + {"variant": VARIANTS, "state": STATES, "appearance": [LIGHT, DARK]}, + {"variant": VARIANTS, "show_dividers": [True, False]}, + {"variant": VARIANTS, "color_scheme": ["ruby", "gray"], "appearance": [DARK]}, + {"variant": ["soft", "ghost"], "item_variant": ["classic", "ghost", "outline"]}, + {"variant": VARIANTS, "radius": ["none", "full"]}, + { + "type": ["multiple"], + "default_value": {"all": ["first", "second", "third"], "first": ["first"]}, + }, + {"default_value": {"first": "first", "third": "third"}, "variant": VARIANTS}, + {"disabled": [True], "state": STATES}, + {"parts": [True], "variant": ["classic", "outline"], "state": STATES}, + ], + stage=(360, 300), + crop="stage", + target=".AccordionItem:nth-of-type(1) .AccordionTrigger", + parts={ + "root": ":scope > div", + "item": ".AccordionItem:nth-of-type(1)", + "middle": ".AccordionItem:nth-of-type(2)", + "last": ".AccordionItem:nth-of-type(3)", + "header": ".AccordionItem:nth-of-type(1) .AccordionHeader", + "icon": ".AccordionItem:nth-of-type(1) .AccordionChevron", + "second": ".AccordionItem:nth-of-type(2) .AccordionTrigger", + "third": ".AccordionItem:nth-of-type(3) .AccordionTrigger", + }, + # The focus is on the button of Radix, and on the summary around the + # heading here. + states={ + FOCUS_VISIBLE: State( + enter=_focus, + leave=_blur, + matches=":is(:focus-visible, summary:focus-visible *)", + ) + }, + # Not held to zero. At a threshold of zero 87 of the 106 cells are equal + # pixel for pixel, and the others differ by at most 5 pixels of 108000 + # on a rounded corner, which the browser anti-aliases by where the + # accordion is on the page: the accordion of Radix differs from itself by + # as much between two frames of the same look. At the default threshold + # 3 cells differ, by 2 pixels. + tolerance=0.00005, +) + + +class AccordionState(rx.State): + """What the accordions of the contract are bound to.""" + + bound: rx.Field[str] = rx.field("b") + seen: rx.Field[list[str]] = rx.field(default_factory=list) + + @rx.event + def set_bound(self, value: str | list[str]): + """Follow the bound accordion. + + Args: + value: The value of its open item. + """ + self.bound = str(value) + + @rx.event + def see(self, value: str | list[str]): + """Keep what a change handed over. + + Args: + value: The value of the open item, or of each open item. + """ + self.seen.append(json.dumps(value)) + + @rx.event + def pick_last(self): + """Change the bound value from outside the accordion.""" + self.bound = "c" + + +def _letters(namespace: Any, name: str, off: str = "", **props: Any) -> Any: + """Create an accordion of three items named by a letter, in a frame. + + Args: + namespace: ``rx`` or ``rx.ui``. + name: The id of the frame. + off: The letter of a disabled item. + **props: The props of the root. + + Returns: + The frame. + """ + accordion = namespace.accordion + return rx.el.div( + accordion.root( + *( + accordion.item( + header=f"Header {letter}", + content=f"Panel {letter}", + value=letter, + **({"disabled": True} if letter == off else {}), + ) + for letter in "abc" + ), + **props, + ), + id=name, + ) + + +CONTRACT = Contract( + component="accordion", + render=lambda namespace: namespace.box( + namespace.accordion.root( + namespace.accordion.item( + namespace.accordion.header( + namespace.accordion.trigger("Made", id="made-header") + ), + namespace.accordion.content("Of its parts", id="made-panel"), + value="made", + ), + default_value="made", + ), + _letters( + namespace, "plain", default_value="a", on_value_change=AccordionState.see + ), + _letters( + namespace, + "folds", + default_value="a", + collapsible=True, + on_value_change=AccordionState.see, + ), + _letters( + namespace, + "several", + type="multiple", + default_value=["b"], + on_value_change=AccordionState.see, + ), + _letters(namespace, "free", type="multiple"), + _letters( + namespace, + "bound", + value=AccordionState.bound, + on_value_change=AccordionState.set_bound, + ), + _letters(namespace, "partly", off="b", collapsible=True), + rx.el.button("Last", id="last", on_click=AccordionState.pick_last), + rx.el.span(AccordionState.seen.to_string(), id="seen"), + rx.el.span(AccordionState.bound, id="bound-value"), + ), +) + +# The text of the panels of an accordion that are shown, by the id of its frame. +OPEN = ( + "id => [...document.getElementById(id).querySelectorAll('.AccordionContent')]" + ".filter(panel => panel.checkVisibility({contentVisibilityAuto: true}))" + ".map(panel => panel.textContent)" +) +# How long a panel takes to open or close, and some more, in milliseconds. +STILL = 400 +# What takes the focus in a header: the button of Radix, the summary here. +HEADER = "button.AccordionTrigger, summary" +# The text of the header that has the focus, or the id of anything else. +FOCUSED = ( + "document.activeElement.matches('button.AccordionTrigger, summary')" + " ? document.activeElement.textContent : document.activeElement.id" +) + + +def _wait_for_open(run: Run, name: str, *letters: str) -> None: + """Wait until the open items of an accordion are the ones expected. + + Args: + run: The run, on a page. + name: The id of the frame of the accordion. + *letters: The letter of each item that is to be open. + """ + run.page.wait_for_function( + f"([id, panels]) => JSON.stringify(({OPEN})(id)) === panels", + arg=[ + name, + json.dumps( + [f"Panel {letter}" for letter in letters], separators=(",", ":") + ), + ], + ) + + +def _header(run: Run, name: str, letter: str) -> Locator: + """Find the header of an item. + + Args: + run: The run, on a page. + name: The id of the frame of the accordion. + letter: The letter of the item. + + Returns: + What takes the focus in the header. + """ + return ( + run.page.locator(f"#{name}").locator(HEADER).filter(has_text=f"Header {letter}") + ) + + +@CONTRACT.step("the panel of the open item is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + assert run.server.element("made-header").text == "Made" + assert run.server.element("made-panel").text == "Of its parts" + + +@CONTRACT.step("opens and closes an item with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + + def press(name: str, letter: str) -> list[str]: + # With scripts off the page is read once its panels are still: + # nothing in it polls for them. + _header(run, name, letter).click() + page.wait_for_timeout(STILL) + return page.evaluate(f"({OPEN})('{name}')") + + assert page.evaluate(f"({OPEN})('plain')") == ["Panel a"] + assert press("plain", "b") == ["Panel b"] + assert press("free", "c") == ["Panel c"] + assert press("free", "a") == ["Panel a", "Panel c"] + assert press("free", "c") == ["Panel a"] + + +@CONTRACT.step("a header is a heading, and says whether its item is open") +def _role(run: Run) -> None: + page = run.page + plain = page.locator("#plain") + assert plain.get_by_role("heading", level=3).all_text_contents() == [ + "Header a", + "Header b", + "Header c", + ] + # An open item says so on its button in Radix, and as a `details` here. + said = plain.locator("button[aria-expanded=true], details[open] > summary") + assert said.all_text_contents() == ["Header a"] + assert plain.get_by_role("region", name="Header a").text_content() == "Panel a" + + +@CONTRACT.step("Enter and Space open and close an item") +def _keys(run: Run) -> None: + page = run.page + _header(run, "folds", "b").focus() + page.keyboard.press("Enter") + _wait_for_open(run, "folds", "b") + page.keyboard.press("Space") + _wait_for_open(run, "folds") + page.keyboard.press("Space") + _wait_for_open(run, "folds", "b") + page.keyboard.press("Enter") + _wait_for_open(run, "folds") + + +@CONTRACT.step("Tab stops on every header, and not on a disabled one") +def _tab(run: Run) -> None: + page = run.page + page.locator("#last").focus() + stops = [] + for _ in range(3): + page.keyboard.press("Shift+Tab") + stops.append(page.evaluate(FOCUSED)) + assert stops == ["Header c", "Header a", "Header c"] + _header(run, "partly", "b").click(force=True) + page.wait_for_timeout(300) + _wait_for_open(run, "partly") + + +@CONTRACT.step("one item is open at a time, and the open one stays open") +def _single(run: Run) -> None: + page = run.page + _wait_for_open(run, "plain", "a") + _header(run, "plain", "a").click(force=True) + page.wait_for_timeout(400) + _wait_for_open(run, "plain", "a") + _header(run, "plain", "c").click() + _wait_for_open(run, "plain", "c") + _header(run, "plain", "c").focus() + page.keyboard.press("Enter") + page.wait_for_timeout(400) + _wait_for_open(run, "plain", "c") + wait_for_text(page, "seen", '["\\"c\\""]') + + +@CONTRACT.step("a collapsible accordion closes its open item, and says so") +def _collapsible(run: Run) -> None: + page = run.page + _header(run, "folds", "a").click() + _wait_for_open(run, "folds") + _header(run, "folds", "b").click() + _wait_for_open(run, "folds", "b") + wait_for_text(page, "seen", '["\\"\\"","\\"b\\""]') + + +@CONTRACT.step("an accordion of several opens each item by itself, and says which") +def _multiple(run: Run) -> None: + page = run.page + _wait_for_open(run, "several", "b") + _header(run, "several", "c").click() + _wait_for_open(run, "several", "b", "c") + _header(run, "several", "b").click() + _wait_for_open(run, "several", "c") + wait_for_text(page, "seen", '["[\\"b\\", \\"c\\"]","[\\"c\\"]"]') + + +@CONTRACT.step("hands over the open items in the order they were opened in") +def _order(run: Run) -> None: + page = run.page + _header(run, "several", "a").click() + _wait_for_open(run, "several", "a", "b") + wait_for_text(page, "seen", '["[\\"b\\", \\"a\\"]"]') + + +@CONTRACT.step("an accordion bound to state shows the item of the state") +def _bound(run: Run) -> None: + page = run.page + _wait_for_open(run, "bound", "b") + _header(run, "bound", "a").click() + wait_for_text(page, "bound-value", "a") + _wait_for_open(run, "bound", "a") + page.locator("#last").click() + wait_for_text(page, "bound-value", "c") + _wait_for_open(run, "bound", "c") + + +@CONTRACT.step("the arrow keys, Home and End move between the headers") +def _arrows(run: Run) -> None: + page = run.page + _header(run, "plain", "a").focus() + for key, letter in ( + ("ArrowDown", "b"), + ("End", "c"), + ("ArrowUp", "b"), + ("Home", "a"), + ): + page.keyboard.press(key) + page.wait_for_function( + f"header => ({FOCUSED}) === header", arg=f"Header {letter}" + ) 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 ba2f995cac4..f2181669c13 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -7,6 +7,7 @@ _SUBMODULES: set[str] = {"tokens"} _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { + "components.accordion": ["accordion"], "components.aspect_ratio": ["aspect_ratio"], "components.avatar": ["avatar"], "components.badge": ["badge"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py index e453ecb1413..ada1b32dc35 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_group.py @@ -305,6 +305,25 @@ def is_value(selected: Var, value: Var | None) -> Var | bool: ) +def choose(condition: Var | bool, on: Any, off: Any) -> Any: + """Choose between two values by a condition. + + Args: + condition: The condition: a bool when it is known while compiling. + on: The value when it holds. + off: The value when it does not. + + Returns: + One of the values, or the expression that chooses in the browser. + """ + if not isinstance(condition, Var): + return on if condition else off + return Var( + f"({condition!s} ? {LiteralVar.create(on)!s} : {LiteralVar.create(off)!s})", + _var_data=condition._get_all_var_data(), + ) + + def has_value(selected: Var, value: Var | None) -> Var | bool: """Say whether an item is among the ones a group has selected. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/accordion.py b/packages/reflex-components-ui/src/reflex_components_ui/components/accordion.py new file mode 100644 index 00000000000..37357a060fb --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/accordion.py @@ -0,0 +1,783 @@ +"""An accordion: items that are native ``details``, opened by their summary.""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterator, Sequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_components_lucide.icon import Icon + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._group import ( + choose, + descendants, + either, + has_value, + is_value, + literal, +) +from reflex_components_ui.components._script import listen, script +from reflex_components_ui.props import style_before +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.accordion import ( + ACCORDION, + ACCORDION_CONTENT, + ACCORDION_HEADER, + ACCORDION_ITEM, + ACCORDION_TRIGGER, + DIVIDER, + DURATION, + EASING, +) +from reflex_components_ui.themes import LiteralAccentColor + +LiteralAccordionType = Literal["single", "multiple"] +LiteralAccordionDir = Literal["ltr", "rtl"] +LiteralAccordionOrientation = Literal["vertical", "horizontal"] +LiteralAccordionVariant = Literal["classic", "soft", "surface", "outline", "ghost"] +LiteralRadius = Literal["none", "small", "medium", "large", "full"] + +DEFAULT_ANIMATION_DURATION = 250 +DEFAULT_ANIMATION_EASING = "cubic-bezier(0.87, 0, 0.13, 1)" + +# Numbers the accordions of an app, and the items that are given no value. +_ids = itertools.count(1) + + +def _is_one_of(values: Sequence[Var | None], wanted: tuple[str, ...]) -> Var | bool: + """Say whether one of several props has one of the values wanted. + + Args: + values: The props, any of which may be left out. + wanted: The values. + + Returns: + Whether one has: a bool when every prop is known while compiling. + """ + bound = [] + for value in values: + known = literal(value) + if isinstance(known, Var): + bound.append(known) + elif known in wanted: + return True + if not bound: + return False + listed = LiteralVar.create(list(wanted)) + return Var( + "(" + " || ".join([f"{listed!s}.includes({value!s})" for value in bound]) + ")", + _var_type=bool, + _var_data=VarData.merge(*(value._get_all_var_data() for value in bound)), + ) + + +def _joined(prefix: str, value: Var) -> Any: + """Make an id from a prefix and the value of an item. + + Args: + prefix: What the id starts with. + value: The value of the item. + + Returns: + The id: a string when the value is known while compiling. + """ + known = literal(value) + if not isinstance(known, Var): + return f"{prefix}{known}" + return Var( + f"({LiteralVar.create(prefix)!s} + {known!s})", + _var_type=str, + _var_data=known._get_all_var_data(), + ) + + +class AccordionComponent(UIComponent): + """Base class for the components of an accordion.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child." + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="The color scheme of the component." + ) + + variant: Var[LiteralAccordionVariant] = field(doc="The variant of the component.") + + def _exclude_props(self) -> list[str]: + """Keep the variant off the element: it selects styles. + + Returns: + The props read as styles, and the variant. + """ + return [*super()._exclude_props(), "variant"] + + +def on_value_change_handler(value: Var[str | list[str]]) -> tuple[Var[str | list[str]]]: + """Handle the on_value_change event. + + Args: + value: The value of the event. + + Returns: + The value of the event. + """ + return (value,) + + +class AccordionRoot(AccordionComponent): + """An accordion component.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = ACCORDION + + type: Var[LiteralAccordionType] = field( + doc="The type of accordion (single or multiple)." + ) + + value: Var[str | Sequence[str]] = field(doc="The value of the item to expand.") + + default_value: Var[str | Sequence[str]] = field( + doc="The default value of the item to expand." + ) + + collapsible: Var[bool] = field(doc="Whether or not the accordion is collapsible.") + + disabled: Var[bool] = field(doc="Whether or not the accordion is disabled.") + + dir: Var[LiteralAccordionDir] = field( + doc="The reading direction of the accordion when applicable." + ) + + orientation: Var[LiteralAccordionOrientation] = field( + doc="The orientation of the accordion." + ) + + radius: Var[LiteralRadius] = field(doc="The radius of the accordion corners.") + + duration: Var[int] = field( + default=LiteralVar.create(DEFAULT_ANIMATION_DURATION), + doc="The time in milliseconds to animate open and close", + ) + + easing: Var[str] = field( + default=LiteralVar.create(DEFAULT_ANIMATION_EASING), + doc="The easing function to use for the animation.", + ) + + show_dividers: Var[bool] = field(doc="Whether to show divider lines between items.") + + _valid_children: ClassVar[list[str]] = ["AccordionItem"] + + on_value_change: EventHandler[on_value_change_handler] = field( + doc="Fired when the opened the accordions changes." + ) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create an AccordionRoot. + + Args: + *children: The items of the accordion. + **props: The properties of the component. + + Returns: + The AccordionRoot component, which says how its panels move and + how thick the line between two items is. + """ + duration = literal( + LiteralVar.create(props.get("duration", DEFAULT_ANIMATION_DURATION)) + ) + handed: dict[str, Any] = { + DURATION: ( + Var( + f'({duration!s} + "ms")', + _var_type=str, + _var_data=duration._get_all_var_data(), + ) + if isinstance(duration, Var) + else f"{duration}ms" + ), + EASING: props.get("easing", DEFAULT_ANIMATION_EASING), + } + if props.get("show_dividers") is not None: + shown = literal(LiteralVar.create(props["show_dividers"])) + handed[DIVIDER] = choose(shown, "1px", "0") + style_before(props, handed) + return super().create(*children, **props) + + def _post_init(self, *args, **kwargs): + """Initialize the accordion, and give its items what they share. + + Radix hands the parts of an accordion its props through a context. + Here the root finds its items while compiling, and gives them what + they render. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + self._name = f"rx-accordion-{next(_ids)}" + # The line between two items is as thick as the accordion says, and + # it says so when asked to, or drawn with an outline. + self._divided: Var | bool = self.show_dividers is not None or _is_one_of( + [self.variant], ("outline", "surface") + ) + for item in descendants(self, AccordionItem, AccordionRoot): + item._join(self) + + @property + def _multiple(self) -> Var | bool: + """Whether several items can be open at once. + + Returns: + Whether they can: a bool when the type is known while compiling. + """ + return _is_one_of([self.type], ("multiple",)) + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the items off the element. + + Returns: + The props read as styles, and what the accordion hands its + items or its script. + """ + return [ + *super()._exclude_props(), + "type", + "value", + "default_value", + "collapsible", + "disabled", + "orientation", + "duration", + "easing", + "show_dividers", + ] + + @property + def _scripted(self) -> bool: + """Whether the accordion does something the browser does not. + + Returns: + Whether an item that is open stays open when it is pressed, + the accordion is bound to state, or says what is open. + """ + return ( + self.value is not None + or "on_value_change" in self.event_triggers + or not (self._multiple is True or literal(self.collapsible) is True) + ) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the accordion, its script 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) + if self._scripted: + yield script("accordion", "accordionClick") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the element around the accordion. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. The browser opens and closes the items; a script + hears a press on a header only for what the browser does not + do. + """ + tag = super()._render(props) + if not self._scripted: + return tag + rendered = dict(tag.props) + on_value_change = rendered.pop("onValueChange", None) + tag = tag.set(props=rendered).add_props(**{ + "data-rx-accordion": choose(self._multiple, "multiple", "single"), + "data-collapsible": self.collapsible, + "data-bound": None if self.value is None else "", + }) + return listen( + tag, + script("accordion", "accordionClick"), + "onClick", + arguments=() if on_value_change is None else (on_value_change,), + ) + + +class AccordionItem(AccordionComponent): + """An accordion component.""" + + tag = "details" + + styles: ClassVar[ComponentStyles] = ACCORDION_ITEM + + value: Var[str] = field(doc="A unique identifier for the item.") + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the item." + ) + + header: Var[Component | str] = field(doc="The header of the accordion item.") + + content: Var[Component | str | None] = field( + default=Var.create(None), doc="The content of the accordion item." + ) + + _valid_children: ClassVar[list[str]] = [ + "AccordionHeader", + "AccordionTrigger", + "AccordionContent", + ] + + _valid_parents: ClassVar[list[str]] = ["AccordionRoot"] + + @classmethod + def create( + cls, + *children, + **props, + ) -> Component: + """Create an accordion item. + + Args: + *children: The list of children to use if header and content are not provided. + **props: Additional properties to apply to the accordion item. + + Returns: + The accordion item. + """ + header = props.pop("header", None) + content = props.pop("content", None) + + # The item requires a value to toggle (a name no other item of the + # app has if not provided). + value = props.pop("value", None) + if value is None: + value = f"rx-accordion-item-{next(_ids)}" + + if "AccordionItem" not in ( + cls_name := props.pop("class_name", "AccordionItem") + ): + cls_name = f"{cls_name} AccordionItem" + + color_scheme = props.get("color_scheme") + variant = props.get("variant") + + if (header is not None) and (content is not None): + children = [ + AccordionHeader.create( + AccordionTrigger.create( + header, + AccordionIcon.create( + color_scheme=color_scheme, + variant=variant, + ), + color_scheme=color_scheme, + variant=variant, + ), + color_scheme=color_scheme, + variant=variant, + ), + AccordionContent.create( + content, + color_scheme=color_scheme, + variant=variant, + ), + ] + else: + # The summary of a `details` is its child: a trigger without a + # header is given one. + children = [ + AccordionHeader.create(child) + if isinstance(child, AccordionTrigger) + else child + for child in children + ] + + return super().create(*children, value=value, **props, class_name=cls_name) + + def _post_init(self, *args, **kwargs): + """Initialize the item, as one of an accordion without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as variants, and the attributes the + # accordion gives the item: both are set by the root around it. + self._ghost: Any = None + self._divided: Any = None + self._accordion: dict[str, Any] = {} + super()._post_init(*args, **kwargs) + + def _join(self, accordion: AccordionRoot) -> None: + """Take from an accordion what Radix hands its items through a context. + + Args: + accordion: The accordion the item is in. + """ + self._ghost = choose( + _is_one_of([self.variant, accordion.variant], ("ghost",)), "true", "false" + ) + self._divided = choose(accordion._divided, "true", "false") + multiple = accordion._multiple + selected = ( + accordion.value if accordion.value is not None else accordion.default_value + ) + attributes: dict[str, Any] = { + # The browser closes the other items of a name when one opens. + "name": choose(multiple, None, accordion._name), + } + if selected is not None: + several, one = ( + has_value(selected, self.value), + is_value(selected, self.value), + ) + attributes["open"] = ( + several + if multiple is True + else one + if multiple is False + else choose(multiple, several, one) + ) + self._accordion = attributes + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + disabled = either(accordion.disabled, self.disabled) + prefix = f"{accordion._name}-" + for part in descendants(self, AccordionPart, AccordionRoot): + part._join(accordion, self, disabled, prefix) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the item, those its accordion gives it 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) + for value in self._accordion.values(): + if isinstance(value, Var): + yield value + + def _exclude_props(self) -> list[str]: + """Keep the props of an item off the element. + + Returns: + The props read as styles, and the ones its parts render. + """ + return [*super()._exclude_props(), "header", "content", "value", "disabled"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the item. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a ``details`` the browser opens and closes. + """ + return ( + super() + ._render(props) + .add_props(**{ + "data-rx-accordion-item": "", + "data-value": self.value, + **self._accordion, + }) + ) + + +class AccordionPart(AccordionComponent): + """A part of an item, which the accordion gives a look and a name.""" + + def _post_init(self, *args, **kwargs): + """Initialize the part, as one of an accordion without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as variants, and the attributes the + # accordion gives the part: both are set by the root around it. + self._classic: Any = None + self._divided: Any = None + self._accordion: dict[str, Any] = {} + super()._post_init(*args, **kwargs) + + def _join( + self, + accordion: AccordionRoot, + item: AccordionItem, + disabled: Var | None, + prefix: str, + ) -> None: + """Take from an accordion what Radix hands its parts through a context. + + Args: + accordion: The accordion the part is in. + item: The item the part is in. + disabled: Whether the item is disabled. + prefix: What the ids of the parts of the accordion start with. + """ + # A part is classic when it, its item or its accordion is, and an + # accordion is unless it says otherwise. + self._classic = choose( + accordion.variant is None + or _is_one_of( + [self.variant, item.variant, accordion.variant], ("classic",) + ), + "true", + "false", + ) + self._divided = choose(accordion._divided, "true", "false") + self._accordion = self._attributes(item, disabled, prefix) + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + def _attributes( + self, item: AccordionItem, disabled: Var | None, prefix: str + ) -> dict[str, Any]: + """Work out the attributes the accordion gives the part. + + Args: + item: The item the part is in. + disabled: Whether the item is disabled. + prefix: What the ids of the parts of the accordion start with. + + Returns: + The attributes. + """ + return {} + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the part, those its accordion gives it 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) + for value in self._accordion.values(): + if isinstance(value, Var): + yield value + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the part. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with what its accordion gives it. + """ + return super()._render(props).add_props(**self._accordion) + + +class AccordionHeader(AccordionPart): + """An accordion component.""" + + tag = "summary" + + styles: ClassVar[ComponentStyles] = ACCORDION_HEADER + + @classmethod + def create(cls, *children, **props) -> Component: + """Create the Accordion header component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The Accordion header Component. + """ + if "AccordionHeader" not in ( + cls_name := props.pop("class_name", "AccordionHeader") + ): + cls_name = f"{cls_name} AccordionHeader" + + return super().create(*children, class_name=cls_name, **props) + + def _attributes( + self, item: AccordionItem, disabled: Var | None, prefix: str + ) -> dict[str, Any]: + """Say that the header of a disabled item opens nothing. + + Args: + item: The item the header is in. + disabled: Whether the item is disabled. + prefix: What the ids of the parts of the accordion start with. + + Returns: + The attributes: a disabled header says so, and Tab passes it. + """ + if disabled is None: + return {} + off = literal(disabled) + return {"aria-disabled": off, "tabIndex": choose(off, -1, None)} + + +class AccordionTrigger(AccordionPart): + """An accordion component.""" + + tag = "h3" + + styles: ClassVar[ComponentStyles] = ACCORDION_TRIGGER + + @classmethod + def create(cls, *children, **props) -> Component: + """Create the Accordion trigger component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The Accordion trigger Component. + """ + if "AccordionTrigger" not in ( + cls_name := props.pop("class_name", "AccordionTrigger") + ): + cls_name = f"{cls_name} AccordionTrigger" + + return super().create(*children, class_name=cls_name, **props) + + def _attributes( + self, item: AccordionItem, disabled: Var | None, prefix: str + ) -> dict[str, Any]: + """Take the id the panel of the item is named by. + + Args: + item: The item the trigger is in. + disabled: Whether the item is disabled. + prefix: What the ids of the parts of the accordion start with. + + Returns: + The attributes. + """ + if self.id is not None: + return {} + return {"id": _joined(f"{prefix}trigger-", item.value)} + + +class AccordionIcon(Icon): + """An accordion icon component.""" + + @classmethod + def create(cls, *children, **props) -> Component: + """Create the Accordion icon component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The Accordion icon Component. + """ + if "AccordionChevron" not in ( + cls_name := props.pop("class_name", "AccordionChevron") + ): + cls_name = f"{cls_name} AccordionChevron" + + # A rule of the base stylesheet turns it over in an open item. + props.setdefault("custom_attrs", {}).setdefault("data-rx-accordion-icon", "") + return super().create(tag="chevron_down", class_name=cls_name, **props) + + +class AccordionContent(AccordionPart): + """An accordion component.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = ACCORDION_CONTENT + + @classmethod + def create(cls, *children, **props) -> Component: + """Create the Accordion content component. + + Args: + *children: The children of the component. + **props: The properties of the component. + + Returns: + The Accordion content Component. + """ + if "AccordionContent" not in ( + cls_name := props.pop("class_name", "AccordionContent") + ): + cls_name = f"{cls_name} AccordionContent" + + return super().create(*children, class_name=cls_name, **props) + + def _attributes( + self, item: AccordionItem, disabled: Var | None, prefix: str + ) -> dict[str, Any]: + """Name the panel by the trigger of its item. + + Args: + item: The item the panel is in. + disabled: Whether the item is disabled. + prefix: What the ids of the parts of the accordion start with. + + Returns: + The attributes. + """ + trigger = next(iter(descendants(item, AccordionTrigger, AccordionRoot)), None) + return { + "aria-labelledby": ( + _joined(f"{prefix}trigger-", item.value) + if trigger is None or trigger.id is None + else trigger.id + ) + } + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the panel. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the role of a region of the page. + """ + return super()._render(props).add_props(role="region") + + +class Accordion(ComponentNamespace): + """Accordion component.""" + + content = staticmethod(AccordionContent.create) + header = staticmethod(AccordionHeader.create) + item = staticmethod(AccordionItem.create) + icon = staticmethod(AccordionIcon.create) + root = staticmethod(AccordionRoot.create) + trigger = staticmethod(AccordionTrigger.create) + + +accordion = Accordion() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py b/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py index 3b7af6e1df1..dc0546fe3af 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py @@ -13,7 +13,12 @@ from reflex_components_core.core.breakpoints import Responsive from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.components._group import descendants, is_value, literal +from reflex_components_ui.components._group import ( + choose, + descendants, + is_value, + literal, +) from reflex_components_ui.components._script import listen, script from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.tabs import TABS, TABS_CONTENT, TABS_LIST, TABS_TRIGGER @@ -23,25 +28,6 @@ _ids = itertools.count(1) -def _choose(condition: Var | bool, on: Any, off: Any) -> Any: - """Choose between two values by whether a tab is the selected one. - - Args: - condition: Whether it is: a bool when it is known while compiling. - on: The value of the selected tab. - off: The value of the others. - - Returns: - One of the values, or the expression that chooses in the browser. - """ - if not isinstance(condition, Var): - return on if condition else off - return Var( - f"({condition!s} ? {LiteralVar.create(on)!s} : {LiteralVar.create(off)!s})", - _var_data=condition._get_all_var_data(), - ) - - def _part_id(tabs: TabsRoot, part: str, value: Var | None) -> Any: """Get the id of the trigger or of the panel of a tab. @@ -113,9 +99,10 @@ def _post_init(self, *args, **kwargs): parts = list(descendants(self, TabsPart, TabsRoot)) # The ids an app gave a trigger or a panel, which the other names. self._ids = { - (part._kind, literal(part.value)): part.id + (part._kind, value): part.id for part in parts - if part.id is not None and not isinstance(literal(part.value), Var) + if part.id is not None + and not isinstance(value := literal(getattr(part, "value", None)), Var) } for part in parts: part._join(self) @@ -182,9 +169,6 @@ class TabsPart(UIComponent): # Which part it is, in the id the tabs give a trigger or a panel. _kind: ClassVar[str] = "" - # The value of the tab of a trigger or of a panel. - value: ClassVar[Any] = None - def _post_init(self, *args, **kwargs): """Initialize the part, as the one of horizontal tabs with no value. @@ -362,8 +346,8 @@ def _attributes(self, tabs: TabsRoot) -> dict[str, Any]: attributes: dict[str, Any] = { "aria-controls": _part_id(tabs, "content", self.value), "aria-selected": selected, - "data-state": _choose(selected, "active", "inactive"), - "tabIndex": _choose(stop, 0, -1), + "data-state": choose(selected, "active", "inactive"), + "tabIndex": choose(stop, 0, -1), } if self.id is None: attributes["id"] = _part_id(tabs, "trigger", self.value) @@ -430,8 +414,8 @@ def _attributes(self, tabs: TabsRoot) -> dict[str, Any]: ) attributes: dict[str, Any] = { "aria-labelledby": _part_id(tabs, "trigger", self.value), - "data-state": _choose(selected, "active", "inactive"), - "hidden": _choose(selected, False, True), + "data-state": choose(selected, "active", "inactive"), + "hidden": choose(selected, False, True), } if self.id is None: attributes["id"] = _part_id(tabs, "content", self.value) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py new file mode 100644 index 00000000000..6cc081a3b07 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py @@ -0,0 +1,180 @@ +"""The look of an accordion: items that open, drawn as the Radix wrapper draws them.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked + +accent, gray, black = tokens.accent, tokens.gray, tokens.black + +# What the accordion hands its parts: how thick the line between two items +# is, and how its panels move. +DIVIDER = "--divider-px" +DURATION = "--animation-duration" +EASING = "--animation-easing" +# What an item hands its icon, which a rule of base.css reads: an open item +# turns it over. +_TURN = "--rx-accordion-turn" + +_RADIUS = tokens.radius[4] +_LINE = gray.a[6] +_FIRST = ":first-of-type" +_LAST = ":last-child" + +_OUTLINED = { + "border_width": "1px", + "border_style": "solid", + "border_color": accent[6], +} + +ACCORDION: ComponentStyles = { + "base": { + "border_radius": _RADIUS, + "box_shadow": f"0 2px 10px {black.a[1]}", + }, + "variants": { + "variant": { + "classic": { + "background_color": accent[9], + "box_shadow": f"0 2px 10px {black.a[4]}", + }, + "soft": {"background_color": accent[3]}, + "outline": unchecked({**_OUTLINED, DIVIDER: "1px"}), + "surface": unchecked({ + **_OUTLINED, + "background_color": accent.surface, + DIVIDER: "1px", + }), + "ghost": {"box_shadow": "none"}, + }, + }, + "defaults": {"variant": "classic"}, +} + +# The line above an item, where the accordion says how thick it is, and +# the corners of the first and the last item. A ghost has neither corner, +# and a line above its first item and below its last. +ACCORDION_ITEM: ComponentStyles = { + "base": unchecked({ + "overflow": "hidden", + "width": "100%", + "margin_top": {"default": "1px", _FIRST: "0"}, + ":focus-within": {"position": "relative", "z_index": 1}, + _TURN: {"default": "none", "[open]": "rotate(180deg)"}, + }), + "variants": { + "_ghost": { + "false": { + "border_top_left_radius": {_FIRST: _RADIUS}, + "border_top_right_radius": {_FIRST: _RADIUS}, + "border_bottom_left_radius": {_LAST: _RADIUS}, + "border_bottom_right_radius": {_LAST: _RADIUS}, + }, + }, + }, + "compound": [ + # Without a line an item has no border, whatever a reset gives it. + { + "props": {"_ghost": "false", "_divided": "false"}, + "style": {"border_top_style": "none"}, + }, + { + "props": {"_ghost": "true", "_divided": "false"}, + "style": { + "border_top_style": "none", + "border_bottom_style": {_LAST: "none"}, + }, + }, + { + "props": {"_ghost": "false", "_divided": "true"}, + "style": unchecked({ + "border_top_width": {"default": f"var({DIVIDER})", _FIRST: "0"}, + "border_top_style": {"default": "solid", _FIRST: "none"}, + "border_top_color": {"default": _LINE, _FIRST: "currentcolor"}, + }), + }, + { + "props": {"_ghost": "true", "_divided": "true"}, + "style": unchecked({ + "border_top_width": f"var({DIVIDER})", + "border_top_style": "solid", + "border_top_color": _LINE, + "border_bottom_width": {_LAST: f"var({DIVIDER})"}, + "border_bottom_style": {_LAST: "solid"}, + "border_bottom_color": {_LAST: _LINE}, + }), + }, + ], + "defaults": {"_ghost": "false", "_divided": "false"}, +} + +# The summary of the item: what opens it, with nothing of the look the +# browser gives one. +ACCORDION_HEADER: ComponentStyles = { + "base": unchecked({ + "display": "flex", + "margin": "0", + "list_style_type": "none", + "::-webkit-details-marker": {"display": "none"}, + # A disabled item does not open: the pointer goes through its header. + "pointer_events": {"[aria-disabled='true']": "none"}, + }), +} + +ACCORDION_TRIGGER: ComponentStyles = { + "base": { + "box_sizing": "border-box", + "margin": "0", + "border_style": "none", + "cursor": "default", + "font_size": "1.1em", + "font_weight": "inherit", + "line_height": 1, + "text_align": "center", + "color": accent[11], + "display": "flex", + "justify_content": "space-between", + "align_items": "center", + "flex_grow": 1, + "flex_shrink": 1, + "flex_basis": "0%", + "padding_top": tokens.space[3], + "padding_bottom": tokens.space[3], + "padding_left": tokens.space[4], + "padding_right": tokens.space[4], + "width": "100%", + "background_color": {":hover": accent[4]}, + }, + "variants": { + "_classic": { + "true": { + "color": accent.contrast, + "background_color": {":hover": accent[10]}, + }, + }, + "_divided": { + "true": unchecked({"box_shadow": f"0 var({DIVIDER}) 0 {_LINE}"}), + }, + }, +} + +_PAD: dict[str, Any] = { + "content": "' '", + "display": "block", + "height": tokens.space[3], +} + +ACCORDION_CONTENT: ComponentStyles = { + "base": { + "overflow": "hidden", + "color": accent[11], + "padding_left": tokens.space[4], + "padding_right": tokens.space[4], + # Room above and below what the panel holds, which opens with it. + "_before": _PAD, + "_after": _PAD, + }, + "variants": {"_classic": {"true": {"color": accent.contrast}}}, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py index 7999662b8d3..7f7429fdde1 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py @@ -5,7 +5,7 @@ from typing import Any from reflex_components_ui import tokens -from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.style import ComponentStyles, StyleProps, unchecked from reflex_components_ui.tokens import Step9 accent, gray, focus = tokens.accent, tokens.gray, tokens.focus @@ -31,7 +31,7 @@ _FOCUS = ":focus-visible" SELECTED = "[aria-selected='true']" -_VERTICAL = {"vertical": {"width": "100%"}} +_VERTICAL: dict[str, StyleProps] = {"vertical": {"width": "100%"}} def _size( diff --git a/pyi_hashes.json b/pyi_hashes.json index d761d6bcb91..9e8974d0c2c 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,10 +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": "3baaa214d298bb98db3eae02bb2911e4", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "f269df75006da1fbc48dcb27e9d40740", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "7aa6a835933a94d1fde16396fdb82693", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", - "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "f2e5d73bff120f5c558fa80937938f87", + "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "61cffb40e8f047c944b54e51ac36cbc7", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "296a02d4f7a276a0548ec473a6c761a9", "packages/reflex-components-ui/src/reflex_components_ui/components/badge.pyi": "f54c7d6d2a403389eb7424f7024bb847", @@ -147,7 +147,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/spinner.pyi": "9e62e8634e1425a75302d24fb458e8a8", "packages/reflex-components-ui/src/reflex_components_ui/components/switch.pyi": "7ec957d0bc2dfb273b9f6b8e8be50746", "packages/reflex-components-ui/src/reflex_components_ui/components/table.pyi": "3d2683d69d98f3cd14da65831e89e5fe", - "packages/reflex-components-ui/src/reflex_components_ui/components/tabs.pyi": "56d2cfa7735d8c6b6c2a082aacdd49f2", + "packages/reflex-components-ui/src/reflex_components_ui/components/tabs.pyi": "37bd6cf7d23252f304647967c44f7693", "packages/reflex-components-ui/src/reflex_components_ui/components/text_area.pyi": "85e3d7d2cf756b3a67683d9724b1a68b", "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "9fe922c888339fa55560e2cb51697ead", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 056a7ecc329..a1ed1b25a59 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -834,6 +834,19 @@ def overlays(): tabs.content("Two", value="second", display="flex", id="second-panel"), default_value="first", ), + # An accordion left to the browser, and one whose open item stays. + rx.ui.accordion.root( + rx.ui.accordion.item(header="Shipping", content="Two days."), + rx.ui.accordion.item(header="Returns", content="Thirty days."), + type="multiple", + id="faq", + ), + rx.ui.accordion.root( + rx.ui.accordion.item(header="Plan", content="Free.", value="plan"), + rx.ui.accordion.item(header="Seats", content="Five.", value="seats"), + default_value="plan", + id="account", + ), rx.el.span(rx.cond(rx.State.is_hydrated, "ready", "loading"), id="ready"), ) @@ -1862,3 +1875,16 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): page.keyboard.press("ArrowLeft") expect(first).to_be_visible() expect(page.get_by_role("tab", name="First")).to_be_focused() + + # Items are native: the browser opens them, and the script of an + # accordion that does not collapse keeps its open item open. + faq, account = page.locator("#faq"), page.locator("#account") + faq.get_by_text("Shipping").click() + faq.get_by_text("Returns").click() + expect(faq.locator("details[open]")).to_have_count(2) + expect(faq.get_by_text("Two days.")).to_be_visible() + account.get_by_text("Plan").click() + expect(account.get_by_text("Free.")).to_be_visible() + account.get_by_text("Seats").click() + expect(account.get_by_text("Five.")).to_be_visible() + expect(account.locator("details[open]")).to_have_count(1) diff --git a/tests/units/reflex_components_ui/components/test_accordion.py b/tests/units/reflex_components_ui/components/test_accordion.py new file mode 100644 index 00000000000..d87b45f935e --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_accordion.py @@ -0,0 +1,773 @@ +"""Tests for reflex_components_ui.components.accordion.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import accordion as accordion_module +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the accordions and the items of each test from one.""" + monkeypatch.setattr(accordion_module, "_ids", itertools.count(1)) + + +def test_accordion( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An item is a native details: its header is the summary around a heading, and its panel a region the heading names. The root says how the panels move and gives the items their name and their look.""" + component = rx.ui.accordion.root( + rx.ui.accordion.item(header="One", content="First", value="one"), + rx.ui.accordion.item(header="Two", content="Second", disabled=True), + default_value="one", + variant="outline", + color_scheme="ruby", + radius="full", + duration=100, + easing="linear", + dir="rtl", + id="faq", + ) + assert component.render() == { + "name": '"div"', + "props": [ + 'className:sx_6a0d053193_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', + '"data-rx-accordion":"single"', + 'dir:"rtl"', + 'id:"faq"', + "onClick:accordionClick", + "ref:ref_faq", + ], + "children": [ + { + "name": '"details"', + "props": [ + 'className:"AccordionItem " + sx_563dab9fe8_c', + '"data-rx-accordion-item":""', + '"data-value":"one"', + 'name:"rx-accordion-2"', + "open:true", + ], + "children": [ + { + "name": '"summary"', + "props": ['className:"AccordionHeader " + sx_00d40261d7_c'], + "children": [ + { + "name": '"h3"', + "props": [ + 'className:"AccordionTrigger " + sx_90f62bd3b2_c', + 'id:"rx-accordion-2-trigger-one"', + ], + "children": [ + {"contents": '"One"'}, + { + "name": "LucideChevronDown", + "props": [ + 'className:"AccordionChevron"', + '"data-rx-accordion-icon":""', + ], + "children": [], + }, + ], + } + ], + }, + { + "name": '"div"', + "props": [ + '"aria-labelledby":"rx-accordion-2-trigger-one"', + 'className:"AccordionContent " + sx_b8a96ba61b_c', + 'role:"region"', + ], + "children": [{"contents": '"First"'}], + }, + ], + }, + { + "name": '"details"', + "props": [ + 'className:"AccordionItem " + sx_563dab9fe8_c', + '"data-rx-accordion-item":""', + '"data-value":"rx-accordion-item-1"', + 'name:"rx-accordion-2"', + "open:false", + ], + "children": [ + { + "name": '"summary"', + "props": [ + '"aria-disabled":true', + 'className:"AccordionHeader " + sx_00d40261d7_c', + "tabIndex:-1", + ], + "children": [ + { + "name": '"h3"', + "props": [ + 'className:"AccordionTrigger " + sx_90f62bd3b2_c', + 'id:"rx-accordion-2-trigger-rx-accordion-item-1"', + ], + "children": [ + {"contents": '"Two"'}, + { + "name": "LucideChevronDown", + "props": [ + 'className:"AccordionChevron"', + '"data-rx-accordion-icon":""', + ], + "children": [], + }, + ], + } + ], + }, + { + "name": '"div"', + "props": [ + '"aria-labelledby":"rx-accordion-2-trigger-rx-accordion-item-1"', + 'className:"AccordionContent " + sx_b8a96ba61b_c', + 'role:"region"', + ], + "children": [{"contents": '"Second"'}], + }, + ], + }, + ], + } + assert declared_styles(component) == [ + { + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "boxShadow": "0 2px 10px var(--black-a1)", + "borderTopWidth": "1px", + "borderRightWidth": "1px", + "borderBottomWidth": "1px", + "borderLeftWidth": "1px", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", + "borderTopColor": "var(--accent-6)", + "borderRightColor": "var(--accent-6)", + "borderBottomColor": "var(--accent-6)", + "borderLeftColor": "var(--accent-6)", + "--divider-px": "1px", + "--animation-duration": "100ms", + "--animation-easing": "linear", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "width": "100%", + "marginTop": {"default": "1px", ":first-of-type": "0"}, + "position": {":focus-within": "relative"}, + "zIndex": {":focus-within": 1}, + "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, + "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, + "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, + "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, + "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, + "borderTopWidth": {"default": "var(--divider-px)", ":first-of-type": "0"}, + "borderTopStyle": {"default": "solid", ":first-of-type": "none"}, + "borderTopColor": { + "default": "var(--gray-a6)", + ":first-of-type": "currentcolor", + }, + }, + { + "display": {"default": "flex", "::-webkit-details-marker": "none"}, + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "listStyleType": "none", + "pointerEvents": {"[aria-disabled='true']": "none"}, + }, + { + "boxSizing": "border-box", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": "default", + "fontSize": "1.1em", + "fontWeight": "inherit", + "lineHeight": 1, + "textAlign": "center", + "color": "var(--accent-11)", + "display": "flex", + "justifyContent": "space-between", + "alignItems": "center", + "flexGrow": 1, + "flexShrink": 1, + "flexBasis": "0%", + "paddingTop": "var(--space-3)", + "paddingBottom": "var(--space-3)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "width": "100%", + "backgroundColor": {":hover": "var(--accent-4)"}, + "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "color": "var(--accent-11)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "content": {"::before": "' '", "::after": "' '"}, + "display": {"::before": "block", "::after": "block"}, + "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "width": "100%", + "marginTop": {"default": "1px", ":first-of-type": "0"}, + "position": {":focus-within": "relative"}, + "zIndex": {":focus-within": 1}, + "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, + "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, + "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, + "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, + "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, + "borderTopWidth": {"default": "var(--divider-px)", ":first-of-type": "0"}, + "borderTopStyle": {"default": "solid", ":first-of-type": "none"}, + "borderTopColor": { + "default": "var(--gray-a6)", + ":first-of-type": "currentcolor", + }, + }, + { + "display": {"default": "flex", "::-webkit-details-marker": "none"}, + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "listStyleType": "none", + "pointerEvents": {"[aria-disabled='true']": "none"}, + }, + { + "boxSizing": "border-box", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": "default", + "fontSize": "1.1em", + "fontWeight": "inherit", + "lineHeight": 1, + "textAlign": "center", + "color": "var(--accent-11)", + "display": "flex", + "justifyContent": "space-between", + "alignItems": "center", + "flexGrow": 1, + "flexShrink": 1, + "flexBasis": "0%", + "paddingTop": "var(--space-3)", + "paddingBottom": "var(--space-3)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "width": "100%", + "backgroundColor": {":hover": "var(--accent-4)"}, + "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "color": "var(--accent-11)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "content": {"::before": "' '", "::after": "' '"}, + "display": {"::before": "block", "::after": "block"}, + "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, + }, + ] + + +def test_accordion_of_several_needs_no_script( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An accordion of several items open at once is left to the browser: its items share no name, and nothing hears a press.""" + component = rx.ui.accordion.root( + rx.ui.accordion.item( + rx.ui.accordion.trigger("One", id="one"), + rx.ui.accordion.content("First"), + value="one", + variant="ghost", + ), + rx.ui.accordion.item(header="Two", content="Second", value="two"), + type="multiple", + default_value=["two"], + variant="soft", + show_dividers=True, + disabled=True, + ) + assert component.render() == { + "name": '"div"', + "props": ["className:sx_9bef01ebc0_c"], + "children": [ + { + "name": '"details"', + "props": [ + 'className:"AccordionItem " + sx_efc06f4e34_c', + '"data-rx-accordion-item":""', + '"data-value":"one"', + "open:false", + ], + "children": [ + { + "name": '"summary"', + "props": [ + '"aria-disabled":true', + 'className:"AccordionHeader " + sx_00d40261d7_c', + "tabIndex:-1", + ], + "children": [ + { + "name": '"h3"', + "props": [ + 'className:"AccordionTrigger " + sx_90f62bd3b2_c', + 'id:"one"', + "ref:ref_one", + ], + "children": [{"contents": '"One"'}], + } + ], + }, + { + "name": '"div"', + "props": [ + '"aria-labelledby":"one"', + 'className:"AccordionContent " + sx_b8a96ba61b_c', + 'role:"region"', + ], + "children": [{"contents": '"First"'}], + }, + ], + }, + { + "name": '"details"', + "props": [ + 'className:"AccordionItem " + sx_563dab9fe8_c', + '"data-rx-accordion-item":""', + '"data-value":"two"', + "open:true", + ], + "children": [ + { + "name": '"summary"', + "props": [ + '"aria-disabled":true', + 'className:"AccordionHeader " + sx_00d40261d7_c', + "tabIndex:-1", + ], + "children": [ + { + "name": '"h3"', + "props": [ + 'className:"AccordionTrigger " + sx_90f62bd3b2_c', + 'id:"rx-accordion-1-trigger-two"', + ], + "children": [ + {"contents": '"Two"'}, + { + "name": "LucideChevronDown", + "props": [ + 'className:"AccordionChevron"', + '"data-rx-accordion-icon":""', + ], + "children": [], + }, + ], + } + ], + }, + { + "name": '"div"', + "props": [ + '"aria-labelledby":"rx-accordion-1-trigger-two"', + 'className:"AccordionContent " + sx_b8a96ba61b_c', + 'role:"region"', + ], + "children": [{"contents": '"Second"'}], + }, + ], + }, + ], + } + assert declared_styles(component) == [ + { + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "boxShadow": "0 2px 10px var(--black-a1)", + "backgroundColor": "var(--accent-3)", + "--animation-duration": "250ms", + "--animation-easing": "cubic-bezier(0.87, 0, 0.13, 1)", + "--divider-px": "1px", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "width": "100%", + "marginTop": {"default": "1px", ":first-of-type": "0"}, + "position": {":focus-within": "relative"}, + "zIndex": {":focus-within": 1}, + "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, + "borderTopWidth": "var(--divider-px)", + "borderTopStyle": "solid", + "borderTopColor": "var(--gray-a6)", + "borderBottomWidth": {":last-child": "var(--divider-px)"}, + "borderBottomStyle": {":last-child": "solid"}, + "borderBottomColor": {":last-child": "var(--gray-a6)"}, + }, + { + "display": {"default": "flex", "::-webkit-details-marker": "none"}, + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "listStyleType": "none", + "pointerEvents": {"[aria-disabled='true']": "none"}, + }, + { + "boxSizing": "border-box", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": "default", + "fontSize": "1.1em", + "fontWeight": "inherit", + "lineHeight": 1, + "textAlign": "center", + "color": "var(--accent-11)", + "display": "flex", + "justifyContent": "space-between", + "alignItems": "center", + "flexGrow": 1, + "flexShrink": 1, + "flexBasis": "0%", + "paddingTop": "var(--space-3)", + "paddingBottom": "var(--space-3)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "width": "100%", + "backgroundColor": {":hover": "var(--accent-4)"}, + "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "color": "var(--accent-11)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "content": {"::before": "' '", "::after": "' '"}, + "display": {"::before": "block", "::after": "block"}, + "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "width": "100%", + "marginTop": {"default": "1px", ":first-of-type": "0"}, + "position": {":focus-within": "relative"}, + "zIndex": {":focus-within": 1}, + "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, + "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, + "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, + "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, + "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, + "borderTopWidth": {"default": "var(--divider-px)", ":first-of-type": "0"}, + "borderTopStyle": {"default": "solid", ":first-of-type": "none"}, + "borderTopColor": { + "default": "var(--gray-a6)", + ":first-of-type": "currentcolor", + }, + }, + { + "display": {"default": "flex", "::-webkit-details-marker": "none"}, + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "listStyleType": "none", + "pointerEvents": {"[aria-disabled='true']": "none"}, + }, + { + "boxSizing": "border-box", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": "default", + "fontSize": "1.1em", + "fontWeight": "inherit", + "lineHeight": 1, + "textAlign": "center", + "color": "var(--accent-11)", + "display": "flex", + "justifyContent": "space-between", + "alignItems": "center", + "flexGrow": 1, + "flexShrink": 1, + "flexBasis": "0%", + "paddingTop": "var(--space-3)", + "paddingBottom": "var(--space-3)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "width": "100%", + "backgroundColor": {":hover": "var(--accent-4)"}, + "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "color": "var(--accent-11)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "content": {"::before": "' '", "::after": "' '"}, + "display": {"::before": "block", "::after": "block"}, + "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, + }, + ] + + +def test_accordion_item_alone( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An item outside an accordion is one of an accordion without props.""" + component = rx.ui.accordion.item(header="Alone", content="Panel") + assert component.render() == { + "name": '"details"', + "props": [ + 'className:"AccordionItem " + sx_aad5443040_c', + '"data-rx-accordion-item":""', + '"data-value":"rx-accordion-item-1"', + ], + "children": [ + { + "name": '"summary"', + "props": ['className:"AccordionHeader " + sx_00d40261d7_c'], + "children": [ + { + "name": '"h3"', + "props": ['className:"AccordionTrigger " + sx_b2de2d1617_c'], + "children": [ + {"contents": '"Alone"'}, + { + "name": "LucideChevronDown", + "props": [ + 'className:"AccordionChevron"', + '"data-rx-accordion-icon":""', + ], + "children": [], + }, + ], + } + ], + }, + { + "name": '"div"', + "props": [ + 'className:"AccordionContent " + sx_b8a96ba61b_c', + 'role:"region"', + ], + "children": [{"contents": '"Panel"'}], + }, + ], + } + assert declared_styles(component) == [ + { + "overflowX": "hidden", + "overflowY": "hidden", + "width": "100%", + "marginTop": {"default": "1px", ":first-of-type": "0"}, + "position": {":focus-within": "relative"}, + "zIndex": {":focus-within": 1}, + "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, + "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, + "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, + "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, + "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, + "borderTopStyle": "none", + }, + { + "display": {"default": "flex", "::-webkit-details-marker": "none"}, + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "listStyleType": "none", + "pointerEvents": {"[aria-disabled='true']": "none"}, + }, + { + "boxSizing": "border-box", + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "cursor": "default", + "fontSize": "1.1em", + "fontWeight": "inherit", + "lineHeight": 1, + "textAlign": "center", + "color": "var(--accent-11)", + "display": "flex", + "justifyContent": "space-between", + "alignItems": "center", + "flexGrow": 1, + "flexShrink": 1, + "flexBasis": "0%", + "paddingTop": "var(--space-3)", + "paddingBottom": "var(--space-3)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "width": "100%", + "backgroundColor": {":hover": "var(--accent-4)"}, + }, + { + "overflowX": "hidden", + "overflowY": "hidden", + "color": "var(--accent-11)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + "content": {"::before": "' '", "::after": "' '"}, + "display": {"::before": "block", "::after": "block"}, + "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, + }, + ] + + +class AccordionState(rx.State): + """What an accordion is bound to.""" + + open_item: str = "b" + kind: str = "soft" + shown: bool = True + + @rx.event + def set_open(self, value: str | list[str]): + """Follow the accordion. + + Args: + value: The value of the open item. + """ + self.open_item = str(value) + + +def test_accordion_bound_to_state(ui_plugin: UIPlugin): + """An accordion bound to state renders its state as expressions, and hands the script what it does on a change.""" + open_item, kind, shown = ( + str(AccordionState.open_item), + str(AccordionState.kind), + str(AccordionState.shown), + ) + component = rx.ui.accordion.root( + rx.ui.accordion.item(header="A", content="x", value="a"), + value=AccordionState.open_item, + on_value_change=AccordionState.set_open, + variant=AccordionState.kind, + show_dividers=AccordionState.shown, + collapsible=True, + ) + rendered = component.render() + assert rendered["props"] == [ + f'className:sx_c35f0e8dde_c + " " + (sx_c35f0e8dde_0[{kind}] ?? sx_c35f0e8dde_0d)', + '"data-bound":""', + '"data-collapsible":true', + '"data-rx-accordion":"single"', + ( + "onClick:((event) => accordionClick(event, ((_value) => (addEvents([(ReflexEvent(" + f'"{AccordionState.get_full_name()}.set_open", ({{ ["value"] : _value }}), ' + "({ })))], [_value], ({ }))))))" + ), + f'style:({{ "--v0": (({shown} ? "1px" : "0")) ?? "initial" }})', + ] + item = rendered["children"][0] + assert item["props"] == [ + ( + 'className:"AccordionItem " + sx_33774f392f_c + " " + (sx_33774f392f_0[' + f'((["ghost"].includes({kind})) ? "true" : "false")] ?? sx_33774f392f_0d)' + ), + '"data-rx-accordion-item":""', + '"data-value":"a"', + 'name:"rx-accordion-1"', + f'open:({open_item} === "a")', + ] + assert item["children"][0]["children"][0]["props"] == [ + ( + 'className:"AccordionTrigger " + sx_631c017a79_c + " " + (sx_631c017a79_0[' + f'((["classic"].includes({kind})) ? "true" : "false")] ?? sx_631c017a79_0d)' + ), + 'id:"rx-accordion-1-trigger-a"', + ] + + +@pytest.mark.parametrize( + ("props", "scripts"), + [ + ({}, [ImportVar(tag="accordionClick")]), + ({"collapsible": True}, None), + ({"type": "multiple"}, None), + ({"type": "multiple", "value": ["a"]}, [ImportVar(tag="accordionClick")]), + ( + {"type": "multiple", "on_value_change": rx.console_log}, + [ImportVar(tag="accordionClick")], + ), + ], +) +def test_accordion_loads_its_script_only_for_what_the_browser_does_not_do( + ui_plugin: UIPlugin, props: dict[str, Any], scripts: list[ImportVar] | None +): + """A page loads the script of an accordion whose open item stays open, that is bound to state or that says what is open.""" + component = rx.ui.accordion.root( + rx.ui.accordion.item(header="A", content="x", value="a"), **props + ) + assert ( + component._get_all_imports().get("$/reflex-ui/behaviors/accordion.js") + == scripts + ) + + +def test_accordion_refuses_a_variant_it_does_not_have(ui_plugin: UIPlugin): + """A variant an accordion does not have fails with the name of the component and its variants.""" + with pytest.raises(StyleError) as error: + rx.ui.accordion.root(variant="loud") + assert str(error.value) == ( + 'rx.ui.accordion_root: unknown variant "loud". The values are "classic", ' + '"soft", "surface", "outline", "ghost".' + ) diff --git a/tests/units/reflex_components_ui/components/test_tabs.py b/tests/units/reflex_components_ui/components/test_tabs.py index 658b6c70969..72965b45609 100644 --- a/tests/units/reflex_components_ui/components/test_tabs.py +++ b/tests/units/reflex_components_ui/components/test_tabs.py @@ -2,7 +2,7 @@ import itertools from collections.abc import Callable -from typing import Any +from typing import Any, Literal import pytest from reflex_base.utils.imports import ImportVar @@ -24,7 +24,7 @@ class TabsState(rx.State): tab: str = "two" names: list[str] = ["one", "two"] - upright: str = "vertical" + upright: Literal["horizontal", "vertical"] = "vertical" @rx.event def set_tab(self, tab: str): @@ -942,28 +942,10 @@ def test_tabs_import_their_scripts(ui_plugin: UIPlugin): } -@pytest.mark.parametrize( - ("create", "props", "message"), - [ - ( - rx.ui.tabs.root, - {"orientation": "sideways"}, - ( - 'rx.ui.tabs_root: unknown orientation "sideways". The values are ' - '"horizontal", "vertical".' - ), - ), - ( - rx.ui.tabs.list, - {"size": "3"}, - 'rx.ui.tabs_list: unknown size "3". The values are "1", "2".', - ), - ], -) -def test_tabs_refuse_a_value_a_prop_does_not_take( - ui_plugin: UIPlugin, create: Callable[..., Any], props: dict[str, Any], message: str -): +def test_tabs_refuse_a_size_they_do_not_have(ui_plugin: UIPlugin): """A value a prop does not take fails with the name of the component and the values.""" with pytest.raises(StyleError) as error: - create(**props) - assert str(error.value) == message + rx.ui.tabs.list(size="3") + assert str(error.value) == ( + 'rx.ui.tabs_list: unknown size "3". The values are "1", "2".' + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index f3406526841..c675d098dd7 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -103,6 +103,12 @@ def differences(component: str) -> list[ApiDifference]: def test_every_wave_is_in_the_namespace(): assert COMPONENTS == [ + "accordion.content", + "accordion.header", + "accordion.icon", + "accordion.item", + "accordion.root", + "accordion.trigger", "aspect_ratio", "avatar", "badge", @@ -208,6 +214,7 @@ def test_every_wave_is_in_the_namespace(): @pytest.mark.parametrize( "namespace", [ + "accordion", "callout", "checkbox", "data_list", From c678079412a06653c3f94ba5740743233c4b3bf6 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 06:23:14 +0000 Subject: [PATCH 109/204] Say to the type checker that a test passes a size tabs do not have Claude-Session: https://claude.ai/code/session_014AwvTMWjpBRrG7rVgJBZHA --- pyi_hashes.json | 1 + tests/units/reflex_components_ui/components/test_tabs.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pyi_hashes.json b/pyi_hashes.json index 9e8974d0c2c..c68cc3cd0d2 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -122,6 +122,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "61cffb40e8f047c944b54e51ac36cbc7", + "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "296a02d4f7a276a0548ec473a6c761a9", "packages/reflex-components-ui/src/reflex_components_ui/components/badge.pyi": "f54c7d6d2a403389eb7424f7024bb847", diff --git a/tests/units/reflex_components_ui/components/test_tabs.py b/tests/units/reflex_components_ui/components/test_tabs.py index 72965b45609..4ee10128c65 100644 --- a/tests/units/reflex_components_ui/components/test_tabs.py +++ b/tests/units/reflex_components_ui/components/test_tabs.py @@ -945,7 +945,7 @@ def test_tabs_import_their_scripts(ui_plugin: UIPlugin): def test_tabs_refuse_a_size_they_do_not_have(ui_plugin: UIPlugin): """A value a prop does not take fails with the name of the component and the values.""" with pytest.raises(StyleError) as error: - rx.ui.tabs.list(size="3") + rx.ui.tabs.list(size="3") # pyright: ignore[reportArgumentType] assert str(error.value) == ( 'rx.ui.tabs_list: unknown size "3". The values are "1", "2".' ) From 8225bbe7c3be8e8a24cb83a74c282148f1bf182d Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 06:23:57 +0000 Subject: [PATCH 110/204] Fix two early-interaction gaps of the frontend shell - A click before hydration on a type="button" inside a form was dropped: every element in a form was left to the browser, which does nothing for that button. Only a button that submits or resets its form is left alone now, one outside the form that names it included. - The stack of plain notices stayed on the page when its last notice left, an invisible box over a corner that took the clicks under it. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../src/utils/helpers/plain_toast.js | 4 +++ packages/reflex-frontend/src/utils/scripts.js | 9 ++++-- .../reflex-frontend/tests/plain_toast.test.js | 30 +++++++++++++++++++ .../reflex-frontend/tests/scripts.test.js | 18 +++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/packages/reflex-frontend/src/utils/helpers/plain_toast.js b/packages/reflex-frontend/src/utils/helpers/plain_toast.js index 2de09417d81..f7dbf504742 100644 --- a/packages/reflex-frontend/src/utils/helpers/plain_toast.js +++ b/packages/reflex-frontend/src/utils/helpers/plain_toast.js @@ -110,7 +110,11 @@ const show = const remove = () => { clearTimeout(timer); notices.delete(id); + // With its last notice the stack goes too: left empty it is still a + // box over a corner of the page, which takes the clicks meant for it. + const stack = notice.parentElement; notice.remove(); + if (stack && !stack.childElementCount) stack.remove(); }; notices.set(id, remove); const close = () => { diff --git a/packages/reflex-frontend/src/utils/scripts.js b/packages/reflex-frontend/src/utils/scripts.js index 4de86fe6e41..640f56a4c32 100644 --- a/packages/reflex-frontend/src/utils/scripts.js +++ b/packages/reflex-frontend/src/utils/scripts.js @@ -73,11 +73,14 @@ export const HOLD_CLICK_TIMEOUT_MS = 10000; /** * Where a click acts without javascript, or is not safe to dispatch a second - * time: a link is being followed, a form is submitted, a form control or a - * `
` has changed state. Such a click is left to the browser. + * time: a link is being followed, a form is submitted or reset, a form + * control or a `
` has changed state. Such a click is left to the + * browser. A button submits or resets its form unless its type says it is + * only a button: that one does nothing until a handler is attached. */ const ACTS_WITHOUT_SCRIPTS = - "a[href],area[href],form,input,select,textarea,label,summary,[contenteditable]"; + "a[href],area[href],input,select,textarea,label,summary,[contenteditable]," + + 'form button:not([type="button" i]),button[form]:not([type="button" i])'; let earlyClick = null; let holdTimer; diff --git a/packages/reflex-frontend/tests/plain_toast.test.js b/packages/reflex-frontend/tests/plain_toast.test.js index e70a53c1907..4ac4d79f1bf 100644 --- a/packages/reflex-frontend/tests/plain_toast.test.js +++ b/packages/reflex-frontend/tests/plain_toast.test.js @@ -151,3 +151,33 @@ test("the first toast says once why it is plain", () => { ], ]); }); + +test("a stack leaves the page with its last notice", () => { + const stacks = () => + [...document.querySelectorAll("[id^=reflex-plain-toasts-]")].map( + (stack) => [stack.id, stack.childElementCount], + ); + const first = plainToast("One"); + plainToast("Two", { duration: 100 }); + plainToast.error("Failed", { position: "top-left" }); + expect(stacks()).toEqual([ + ["reflex-plain-toasts-bottom-right", 2], + ["reflex-plain-toasts-top-left", 1], + ]); + + // An empty stack is still a box over a corner of the page: it would take + // the clicks meant for what is under it. + vi.advanceTimersByTime(100); + expect(stacks()).toEqual([ + ["reflex-plain-toasts-bottom-right", 1], + ["reflex-plain-toasts-top-left", 1], + ]); + plainToast.dismiss(first); + expect(stacks()).toEqual([["reflex-plain-toasts-top-left", 1]]); + plainToast.dismiss(); + expect(stacks()).toEqual([]); + + // The next notice gets a stack again. + plainToast("Three"); + expect(stacks()).toEqual([["reflex-plain-toasts-bottom-right", 1]]); +}); diff --git a/packages/reflex-frontend/tests/scripts.test.js b/packages/reflex-frontend/tests/scripts.test.js index 91025c65ac0..013ff21d006 100644 --- a/packages/reflex-frontend/tests/scripts.test.js +++ b/packages/reflex-frontend/tests/scripts.test.js @@ -419,6 +419,10 @@ describe("START_AFTER_FIRST_PAINT", () => { '', '
more
', '
', + '
', + '
', + '
', + '
', ])("is left alone where the browser acted on it: %s", async (html) => { const { target, clicks } = addToPage(html); target.addEventListener("click", (event) => event.preventDefault()); @@ -428,6 +432,20 @@ describe("START_AFTER_FIRST_PAINT", () => { expect(clicks.length).toBe(1); }); + test.each([ + '
', + '
', + '
', + '', + ])("in a form is dispatched again where the browser does nothing: %s", async (html) => { + const { target, clicks } = addToPage(html); + run(); + click(target); + await hydrate(); + // The click itself, and the one dispatched again. + expect(clicks.length).toBe(2); + }); + test("is dropped when its target has left the page", async () => { const { target, clicks } = addToPage(''); run(); From ca4d236a64641a4969f1b973fc2b0bf320df9279 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 06:26:07 +0000 Subject: [PATCH 111/204] Style the sticky label and logo outside the badge, at the app's breakpoint rx.sticky.label() and rx.sticky.logo() relied on the stylesheet only the badge added: used on their own the label lost its font and the logo its colors. The label now brings the stylesheet and the logo is filled by attribute. The label of the badge shows from the desktop breakpoint the app configures again, not from a fixed 62em. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../src/reflex_components_core/core/sticky.py | 91 +++++++++++++------ pyi_hashes.json | 2 +- .../test_scripts_after_first_paint.py | 4 +- .../core/test_sticky.py | 61 ++++++++++++- 4 files changed, 126 insertions(+), 32 deletions(-) diff --git a/packages/reflex-components-core/src/reflex_components_core/core/sticky.py b/packages/reflex-components-core/src/reflex_components_core/core/sticky.py index 77eb51948dd..6d253bbad02 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/sticky.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/sticky.py @@ -2,6 +2,7 @@ import urllib.parse +from reflex_base.breakpoints import breakpoints_values from reflex_base.components.component import ComponentNamespace from reflex_base.environment import environment @@ -11,29 +12,42 @@ from reflex_components_core.el.elements.media import Path, Rect, Svg from reflex_components_core.el.elements.typography import Div -# The look of the badge. Plain rules, not ``css`` props: the badge is added to -# apps that may otherwise not need Emotion. The colors follow the color mode -# through the class the theme provider keeps on the document element. -_BADGE_CSS = ( - ".rx-sticky-badge{position:fixed;bottom:1rem;right:1rem;display:flex;" - "flex-direction:row;gap:0.375rem;align-items:center;width:auto;" - "border-radius:0.5rem;color:#E5E7EB;border:1px solid #27282B;" - "background-color:#151618;padding:0.375rem;" - "transition:background-color 0.2s ease-in-out;" - "box-shadow:0 1px 2px 0 rgba(0, 0, 0, 0.05);z-index:9998;cursor:pointer;" - "text-align:center}" - ".dark .rx-sticky-badge{color:#27282B;border:1px solid #E5E7EB;" - "background-color:#FCFCFD}" - ".rx-sticky-logo{fill:white}" - ".rx-sticky-logo-square{fill:#6E56CF}" - ".rx-sticky-logo-letter{fill:white}" - "@media screen and (min-width: 0){.rx-sticky-desktop-only{display:none}}" - "@media screen and (min-width: 62em){.rx-sticky-desktop-only{display:block}}" - f".rx-sticky-label{{color:{color('slate', 1)};font-weight:600;" - "font-family:'Instrument Sans', sans-serif;" - "--default-font-family:'Instrument Sans', sans-serif;font-size:0.875rem;" - "line-height:1rem;letter-spacing:-0.00656rem}" -) +# What tells the stylesheet of the badge from any other in the document. +_STYLESHEET = "rx-sticky-badge" + + +def _badge_css() -> str: + """Write the look of the badge. + + Plain rules, not ``css`` props: the badge is added to apps that may + otherwise not need Emotion. The colors follow the color mode through the + class the theme provider keeps on the document element, and the label + shows from the desktop breakpoint of the app. + + Returns: + The rules. + """ + return ( + ".rx-sticky-badge{position:fixed;bottom:1rem;right:1rem;display:flex;" + "flex-direction:row;gap:0.375rem;align-items:center;width:auto;" + "border-radius:0.5rem;color:#E5E7EB;border:1px solid #27282B;" + "background-color:#151618;padding:0.375rem;" + "transition:background-color 0.2s ease-in-out;" + "box-shadow:0 1px 2px 0 rgba(0, 0, 0, 0.05);z-index:9998;cursor:pointer;" + "text-align:center}" + ".dark .rx-sticky-badge{color:#27282B;border:1px solid #E5E7EB;" + "background-color:#FCFCFD}" + ".rx-sticky-logo{fill:white}" + ".rx-sticky-logo-square{fill:#6E56CF}" + ".rx-sticky-logo-letter{fill:white}" + "@media screen and (min-width: 0){.rx-sticky-desktop-only{display:none}}" + f"@media screen and (min-width: {breakpoints_values[2]})" + "{.rx-sticky-desktop-only{display:block}}" + f".rx-sticky-label{{color:{color('slate', 1)};font-weight:600;" + "font-family:'Instrument Sans', sans-serif;" + "--default-font-family:'Instrument Sans', sans-serif;font-size:0.875rem;" + "line-height:1rem;letter-spacing:-0.00656rem}" + ) class StickyLogo(Svg): @@ -47,12 +61,24 @@ def create(cls): The simple Reflex logo SVG. """ return super().create( + # Filled by attribute as well as by the stylesheet of the badge: + # the logo is drawn right where it is used without the badge. An + # attribute, as a `fill` prop is a style only Emotion applies. Rect.create( - width="16", height="16", rx="2", class_name="rx-sticky-logo-square" + width="16", + height="16", + rx="2", + custom_attrs={"fill": "#6E56CF"}, + class_name="rx-sticky-logo-square", + ), + Path.create( + d="M10 9V13H12V9H10Z", + custom_attrs={"fill": "white"}, + class_name="rx-sticky-logo-letter", ), - Path.create(d="M10 9V13H12V9H10Z", class_name="rx-sticky-logo-letter"), Path.create( d="M4 3V13H6V9H10V7H6V5H10V7H12V3H4Z", + custom_attrs={"fill": "white"}, class_name="rx-sticky-logo-letter", ), width="16", @@ -73,7 +99,13 @@ def create(cls): Returns: The sticky label. """ - return super().create("Built with Reflex", class_name="rx-sticky-label") + return super().create( + # Its own copy of the stylesheet, for a label outside the badge: + # React keeps one per name in the document. + static_style(_STYLESHEET, _badge_css()), + "Built with Reflex", + class_name="rx-sticky-label", + ) def _badge_href() -> str: @@ -99,9 +131,12 @@ def create(cls): The sticky badge. """ return super().create( - static_style("rx-sticky-badge", _BADGE_CSS), + static_style(_STYLESHEET, _badge_css()), StickyLogo.create(), - Div.create(StickyLabel.create(), class_name="rx-sticky-desktop-only"), + Div.create( + Span.create("Built with Reflex", class_name="rx-sticky-label"), + class_name="rx-sticky-desktop-only", + ), href=_badge_href(), aria_label="Built with Reflex", target="_blank", diff --git a/pyi_hashes.json b/pyi_hashes.json index 4356e104c2e..c6b8d47e3bd 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -19,7 +19,7 @@ "packages/reflex-components-core/src/reflex_components_core/core/debounce.pyi": "86b2bea0aeec5334dbb64b3addae91df", "packages/reflex-components-core/src/reflex_components_core/core/helmet.pyi": "a43533eba05dec1ece2602bd64ca0f01", "packages/reflex-components-core/src/reflex_components_core/core/html.pyi": "bedb5c94e690d50721ddc7bfdfbe8a25", - "packages/reflex-components-core/src/reflex_components_core/core/sticky.pyi": "d14c16775c159f674975f8989becefb8", + "packages/reflex-components-core/src/reflex_components_core/core/sticky.pyi": "74f2485a8011962d6407c339a5b1e250", "packages/reflex-components-core/src/reflex_components_core/core/upload.pyi": "d903297d188fe6fe56a824127e0db925", "packages/reflex-components-core/src/reflex_components_core/core/window_events.pyi": "3e39f7b3282570da5d2d3ac503d1f278", "packages/reflex-components-core/src/reflex_components_core/datadisplay/__init__.pyi": "fd3cea1f1a221ed3404c28ec4fec7b3c", diff --git a/tests/integration/tests_playwright/test_scripts_after_first_paint.py b/tests/integration/tests_playwright/test_scripts_after_first_paint.py index ba8471b526e..deb0bee6449 100644 --- a/tests/integration/tests_playwright/test_scripts_after_first_paint.py +++ b/tests/integration/tests_playwright/test_scripts_after_first_paint.py @@ -7,7 +7,7 @@ import pytest from playwright.sync_api import Page, expect from reflex_components_core.core.banner import _PULSER_CSS -from reflex_components_core.core.sticky import _BADGE_CSS +from reflex_components_core.core.sticky import _badge_css import reflex.constants as constants import reflex.utils.prerequisites as prerequisites @@ -116,7 +116,7 @@ def test_prerendered_head_preloads_no_script(scripts_app: AppHarness): own_styles = ( '" + f"{_PULSER_CSS}{_badge_css()}" ) assert re.sub(r"-[\w-]{8}\.css", "-HASH.css", head) == ( '' diff --git a/tests/units/reflex_components_core/core/test_sticky.py b/tests/units/reflex_components_core/core/test_sticky.py index 180cade282b..36d91bcfdd0 100644 --- a/tests/units/reflex_components_core/core/test_sticky.py +++ b/tests/units/reflex_components_core/core/test_sticky.py @@ -1,7 +1,8 @@ """Tests for the "Built with Reflex" sticky badge.""" import pytest -from reflex_components_core.core.sticky import StickyBadge +from reflex_base.breakpoints import breakpoints_values, set_breakpoints +from reflex_components_core.core.sticky import StickyBadge, StickyLabel, StickyLogo def _badge_href() -> str: @@ -97,6 +98,7 @@ def test_badge_is_styled_without_a_css_prop(monkeypatch: pytest.MonkeyPatch): "name": '"rect"', "props": [ 'className:"rx-sticky-logo-square"', + 'fill:"#6E56CF"', 'height:"16"', 'rx:"2"', 'width:"16"', @@ -108,6 +110,7 @@ def test_badge_is_styled_without_a_css_prop(monkeypatch: pytest.MonkeyPatch): "props": [ 'className:"rx-sticky-logo-letter"', 'd:"M10 9V13H12V9H10Z"', + 'fill:"white"', ], "children": [], }, @@ -116,6 +119,7 @@ def test_badge_is_styled_without_a_css_prop(monkeypatch: pytest.MonkeyPatch): "props": [ 'className:"rx-sticky-logo-letter"', 'd:"M4 3V13H6V9H10V7H6V5H10V7H12V3H4Z"', + 'fill:"white"', ], "children": [], }, @@ -134,3 +138,58 @@ def test_badge_is_styled_without_a_css_prop(monkeypatch: pytest.MonkeyPatch): }, ], } + + +STYLESHEET = { + "name": '"style"', + "props": [ + 'href:"rx-sticky-badge"', + 'precedence:"reflex"', + "suppressHydrationWarning:true", + ], + "children": [{"contents": f'"{BADGE_CSS}"'}], +} + + +def test_label_and_logo_are_styled_on_their_own(): + """Outside the badge the label brings the stylesheet, the logo its fills.""" + assert StickyLabel.create().render() == { + "name": '"span"', + "props": ['className:"rx-sticky-label"'], + "children": [STYLESHEET, {"contents": '"Built with Reflex"'}], + } + logo = StickyLogo.create() + assert logo._get_all_imports(collapse=True) == {} + assert [child["props"] for child in logo.render()["children"]] == [ + [ + 'className:"rx-sticky-logo-square"', + 'fill:"#6E56CF"', + 'height:"16"', + 'rx:"2"', + 'width:"16"', + ], + ['className:"rx-sticky-logo-letter"', 'd:"M10 9V13H12V9H10Z"', 'fill:"white"'], + [ + 'className:"rx-sticky-logo-letter"', + 'd:"M4 3V13H6V9H10V7H6V5H10V7H12V3H4Z"', + 'fill:"white"', + ], + ] + + +def test_badge_label_shows_from_the_desktop_breakpoint_of_the_app(): + """The label follows the breakpoints the app sets, as desktop_only does.""" + before = tuple(breakpoints_values) + set_breakpoints(("20em", "40em", "50em", "70em", "90em")) + try: + [stylesheet, *_] = StickyBadge.create().render()["children"] + finally: + set_breakpoints(before) # pyright: ignore[reportArgumentType] + assert stylesheet == { + **STYLESHEET, + "children": [ + { + "contents": f'"{BADGE_CSS.replace("(min-width: 62em)", "(min-width: 50em)")}"' + } + ], + } From 4794fa2502d720ee771f2b5765a0c51013b0e337 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 06:26:30 +0000 Subject: [PATCH 112/204] Name the stylesheet of the sticky badge where its stub shows it Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../src/reflex_components_core/core/sticky.py | 6 +++--- pyi_hashes.json | 2 +- .../tests_playwright/test_scripts_after_first_paint.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/reflex-components-core/src/reflex_components_core/core/sticky.py b/packages/reflex-components-core/src/reflex_components_core/core/sticky.py index 6d253bbad02..4dc734f4c0d 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/sticky.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/sticky.py @@ -16,7 +16,7 @@ _STYLESHEET = "rx-sticky-badge" -def _badge_css() -> str: +def badge_css() -> str: """Write the look of the badge. Plain rules, not ``css`` props: the badge is added to apps that may @@ -102,7 +102,7 @@ def create(cls): return super().create( # Its own copy of the stylesheet, for a label outside the badge: # React keeps one per name in the document. - static_style(_STYLESHEET, _badge_css()), + static_style(_STYLESHEET, badge_css()), "Built with Reflex", class_name="rx-sticky-label", ) @@ -131,7 +131,7 @@ def create(cls): The sticky badge. """ return super().create( - static_style(_STYLESHEET, _badge_css()), + static_style(_STYLESHEET, badge_css()), StickyLogo.create(), Div.create( Span.create("Built with Reflex", class_name="rx-sticky-label"), diff --git a/pyi_hashes.json b/pyi_hashes.json index c6b8d47e3bd..12a60c00097 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -19,7 +19,7 @@ "packages/reflex-components-core/src/reflex_components_core/core/debounce.pyi": "86b2bea0aeec5334dbb64b3addae91df", "packages/reflex-components-core/src/reflex_components_core/core/helmet.pyi": "a43533eba05dec1ece2602bd64ca0f01", "packages/reflex-components-core/src/reflex_components_core/core/html.pyi": "bedb5c94e690d50721ddc7bfdfbe8a25", - "packages/reflex-components-core/src/reflex_components_core/core/sticky.pyi": "74f2485a8011962d6407c339a5b1e250", + "packages/reflex-components-core/src/reflex_components_core/core/sticky.pyi": "e3b7e37a62fa81d9fa0672c03ec29ff0", "packages/reflex-components-core/src/reflex_components_core/core/upload.pyi": "d903297d188fe6fe56a824127e0db925", "packages/reflex-components-core/src/reflex_components_core/core/window_events.pyi": "3e39f7b3282570da5d2d3ac503d1f278", "packages/reflex-components-core/src/reflex_components_core/datadisplay/__init__.pyi": "fd3cea1f1a221ed3404c28ec4fec7b3c", diff --git a/tests/integration/tests_playwright/test_scripts_after_first_paint.py b/tests/integration/tests_playwright/test_scripts_after_first_paint.py index deb0bee6449..39622fd720e 100644 --- a/tests/integration/tests_playwright/test_scripts_after_first_paint.py +++ b/tests/integration/tests_playwright/test_scripts_after_first_paint.py @@ -7,7 +7,7 @@ import pytest from playwright.sync_api import Page, expect from reflex_components_core.core.banner import _PULSER_CSS -from reflex_components_core.core.sticky import _badge_css +from reflex_components_core.core.sticky import badge_css import reflex.constants as constants import reflex.utils.prerequisites as prerequisites @@ -116,7 +116,7 @@ def test_prerendered_head_preloads_no_script(scripts_app: AppHarness): own_styles = ( '" + f"{_PULSER_CSS}{badge_css()}" ) assert re.sub(r"-[\w-]{8}\.css", "-HASH.css", head) == ( '' From 405831b81f1970c8aea5d7437b8b4905bf4b2a5c Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 06:27:43 +0000 Subject: [PATCH 113/204] Compare every loader of the app root in the tests that read one Three tests looked for one loader line among the lines of the generated app root, which passes when another loader is missing or one too many. They now compare the whole loaders object. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- tests/units/compiler/test_compiler.py | 14 +++-- .../test_dynamic_components_codegen.py | 58 +++++++++++++++---- 2 files changed, 58 insertions(+), 14 deletions(-) diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index ed2f3a82ede..8d256a1a757 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -47,6 +47,10 @@ from reflex.state import BaseState from reflex.utils import prerequisites from reflex.utils.misc import preload_color_theme +from tests.units.compiler.test_dynamic_components_codegen import ( + app_root_loaders, + loader, +) @pytest.mark.parametrize("with_plugin", [False, True]) @@ -636,10 +640,12 @@ def index(): assert all("d3-format" in libraries for libraries in seen) assert "d3-format" in context.bundled_libraries _, code = compiler.compile_app_root(rx.el.div()) - assert ( - ' "d3-format": () => import("$/utils/dynamic_libraries/d3_format")' - ".then((module) => module.default)," - ) in code.splitlines() + assert app_root_loaders(code) == [ + loader("@emotion/react", "emotion_react"), + loader("d3-format", "d3_format"), + loader("compile-only-library", "compile_only_library"), + loader("@radix-ui/themes", "radix_ui_themes"), + ] assert "compile-only-library" in context.bundled_libraries assert "@radix-ui/themes" in context.bundled_libraries diff --git a/tests/units/compiler/test_dynamic_components_codegen.py b/tests/units/compiler/test_dynamic_components_codegen.py index a903235fb73..dbc9eaecc08 100644 --- a/tests/units/compiler/test_dynamic_components_codegen.py +++ b/tests/units/compiler/test_dynamic_components_codegen.py @@ -22,6 +22,36 @@ STATE_JS_TEMPLATE = Templates.Dirs.WEB_TEMPLATE / "utils" / "state.js" +def app_root_loaders(code: str) -> list[str]: + """Get the loaders an app root gives its optional libraries. + + Args: + code: The source of the app root. + + Returns: + Every entry of its ``loaders`` object, in order. + """ + lines = code.splitlines() + start = lines.index(" const loaders = {") + return [line.strip() for line in lines[start + 1 : lines.index(" };", start)]] + + +def loader(library: str, alias: str) -> str: + """Write the loader an app root gives an optional library. + + Args: + library: The library. + alias: The name of the module the library is loaded from. + + Returns: + The entry of the ``loaders`` object. + """ + return ( + f'"{library}": () => import("$/utils/dynamic_libraries/{alias}")' + ".then((module) => module.default)," + ) + + def test_dynamic_component_codegen_rewrites_bundled_library_subpath() -> None: """Bundled Lucide subpaths resolve through their own window namespaces.""" with RegistrationContext(): @@ -41,11 +71,15 @@ def test_dynamic_component_codegen_rewrites_bundled_library_subpath() -> None: assert ( "const {DynamicIcon} = window.__reflex['lucide-react/dynamic.mjs']" ) in dynamic_code - assert ( - ' "lucide-react/dist/esm/icons/apple.mjs": () => ' - 'import("$/utils/dynamic_libraries/lucide_react_dist_esm_icons_apple_mjs")' - ".then((module) => module.default)," - ) in app_root_code.splitlines() + assert app_root_loaders(app_root_code) == [ + loader("@emotion/react", "emotion_react"), + loader("lucide-react", "lucide_react"), + loader( + "lucide-react/dist/esm/icons/apple.mjs", + "lucide_react_dist_esm_icons_apple_mjs", + ), + loader("lucide-react/dynamic.mjs", "lucide_react_dynamic_mjs"), + ] def test_lazy_dynamic_component_lists_only_its_optional_libraries(mocker) -> None: @@ -71,11 +105,15 @@ def test_lazy_dynamic_component_lists_only_its_optional_libraries(mocker) -> Non ) assert default_only_code.split("\n", 1)[0] == "//__reflex_evaluate:[]" # The app can load the unused library, but the icon does not request it. - assert ( - ' "unused-library": () => ' - 'import("$/utils/dynamic_libraries/unused_library")' - ".then((module) => module.default)," - ) in app_root_code.splitlines() + assert app_root_loaders(app_root_code) == [ + loader("@emotion/react", "emotion_react"), + loader("unused-library", "unused_library"), + loader("lucide-react", "lucide_react"), + loader( + "lucide-react/dist/esm/icons/apple.mjs", + "lucide_react_dist_esm_icons_apple_mjs", + ), + ] @pytest.mark.parametrize("reactive", [False, True]) From 695ac443f86f065cd4f2879d39960723851560ec Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 06:28:52 +0000 Subject: [PATCH 114/204] Settle the types of the accordion's table and tests Claude-Session: https://claude.ai/code/session_014AwvTMWjpBRrG7rVgJBZHA --- .../src/reflex_components_ui/styles/accordion.py | 6 ++---- .../units/reflex_components_ui/components/test_accordion.py | 6 +++--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py index 6cc081a3b07..8a0172db8fb 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py @@ -2,10 +2,8 @@ from __future__ import annotations -from typing import Any - from reflex_components_ui import tokens -from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.style import ComponentStyles, StyleProps, unchecked accent, gray, black = tokens.accent, tokens.gray, tokens.black @@ -160,7 +158,7 @@ }, } -_PAD: dict[str, Any] = { +_PAD: StyleProps = { "content": "' '", "display": "block", "height": tokens.space[3], diff --git a/tests/units/reflex_components_ui/components/test_accordion.py b/tests/units/reflex_components_ui/components/test_accordion.py index d87b45f935e..a31ceaa172b 100644 --- a/tests/units/reflex_components_ui/components/test_accordion.py +++ b/tests/units/reflex_components_ui/components/test_accordion.py @@ -2,7 +2,7 @@ import itertools from collections.abc import Callable -from typing import Any +from typing import Any, Literal import pytest from reflex_base.utils.imports import ImportVar @@ -676,7 +676,7 @@ class AccordionState(rx.State): """What an accordion is bound to.""" open_item: str = "b" - kind: str = "soft" + kind: Literal["classic", "soft", "surface", "outline", "ghost"] = "soft" shown: bool = True @rx.event @@ -766,7 +766,7 @@ def test_accordion_loads_its_script_only_for_what_the_browser_does_not_do( def test_accordion_refuses_a_variant_it_does_not_have(ui_plugin: UIPlugin): """A variant an accordion does not have fails with the name of the component and its variants.""" with pytest.raises(StyleError) as error: - rx.ui.accordion.root(variant="loud") + rx.ui.accordion.root(variant="loud") # pyright: ignore[reportArgumentType] assert str(error.value) == ( 'rx.ui.accordion_root: unknown variant "loud". The values are "classic", ' '"soft", "surface", "outline", "ghost".' From 3d4a433e90451f56cbed428366028e28714c6227 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 08:49:29 +0000 Subject: [PATCH 115/204] Put None last in the rx.ui value type and follow the avatar in the app test The linter wants None at the end of a union, which the generated type of a style value did not have, and the app the rx.ui tests build now holds an avatar bound to state, whose declarations its memo module lists. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../js/scripts/css-props.js | 4 +-- .../reflex_components_ui/style/_css_props.py | 4 +-- .../tests_playwright/test_ui_components.py | 30 +++++++++++++++++-- .../reflex_components_ui/layout/test_box.py | 4 +-- .../style/test_css_props.py | 19 ++++++------ 5 files changed, 44 insertions(+), 17 deletions(-) diff --git a/packages/reflex-components-ui/js/scripts/css-props.js b/packages/reflex-components-ui/js/scripts/css-props.js index de2586eb7be..2f81a3926a5 100644 --- a/packages/reflex-components-ui/js/scripts/css-props.js +++ b/packages/reflex-components-ui/js/scripts/css-props.js @@ -266,10 +266,10 @@ if TYPE_CHECKING: # None unsets a property, or leaves a breakpoint to the one before it. _Value: TypeAlias = ( _T - | None | Sequence[_T | None] | Breakpoints[Any, Any] - | Mapping[str, _T | None | Mapping[str, _T | None]] + | Mapping[str, _T | Mapping[str, _T | None] | None] + | None ) _StrVar: TypeAlias = Var[str] _Str: TypeAlias = str | Var[str] 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 index 5edc9dba9b7..83aa7035703 100644 --- 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 @@ -22,10 +22,10 @@ # None unsets a property, or leaves a breakpoint to the one before it. _Value: TypeAlias = ( _T - | None | Sequence[_T | None] | Breakpoints[Any, Any] - | Mapping[str, _T | None | Mapping[str, _T | None]] + | Mapping[str, _T | Mapping[str, _T | None] | None] + | None ) _StrVar: TypeAlias = Var[str] _Str: TypeAlias = str | Var[str] diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index e4fe84c007c..0731dd86be8 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -195,7 +195,7 @@ 'se-button-height)", "--rx-icon-opacity": "0.9"}, a0_0: {"position": "rel' 'ative"} });' ), - "const sx_8d448f3b8d_c = stylex.props(sx_8d448f3b8d.s).className;", + ("const sx_8d448f3b8d_c = stylex.props(sx_8d448f3b8d.s).className;"), ( 'const sx_8d448f3b8d_0 = { __proto__: null, "true": stylex.props(sx_8d448' "f3b8d.a0_0).className };" @@ -240,7 +240,33 @@ 'isible)": "0"}, ":focus-visible:not([data-disabled])": "2px"}, "height":' ' "var(--base-button-height)", "--rx-icon-opacity": "0.9"} });' ), - "const sx_6fb0976665_c = stylex.props(sx_6fb0976665.s).className;", + ("const sx_6fb0976665_c = stylex.props(sx_6fb0976665.s).className;"), + ( + 'const sx_21e3781dc3 = stylex.create({ s: {"boxSizing": "border-box", "fo' + 'ntFamily": "var(--default-font-family)", "fontWeight": "var(--font-weigh' + 't-medium)", "fontStyle": "normal", "zIndex": 0, "width": "100%", "height' + '": "100%", "display": "flex", "alignItems": "center", "justifyContent": ' + '"center", "lineHeight": 1, "borderTopLeftRadius": "inherit", "borderTopR' + 'ightRadius": "inherit", "borderBottomRightRadius": "inherit", "borderBot' + 'tomLeftRadius": "inherit", "textTransform": "uppercase", "flexShrink": {' + '":not(:only-child)": 0}, "visibility": {"[data-status=\'loaded\']": "hidde' + 'n"}, "fontSize": {"[data-letters=\'1\']": "var(--avatar-fallback-one-lette' + 'r-font-size)", "[data-letters=\'2\']": "var(--avatar-fallback-two-letters-' + 'font-size, var(--avatar-fallback-one-letter-font-size))"}, "backgroundCo' + 'lor": "var(--accent-a3)", "color": "var(--accent-a11)"} });' + ), + ("const sx_21e3781dc3_c = stylex.props(sx_21e3781dc3.s).className;"), + ( + 'const sx_8df01e863a = stylex.create({ s: {"boxSizing": "border-box", "di' + 'splay": "inline-flex", "alignItems": "center", "justifyContent": "center' + '", "verticalAlign": "middle", "userSelect": "none", "width": "var(--avat' + 'ar-size)", "height": "var(--avatar-size)", "flexShrink": 0, "--avatar-si' + 'ze": "var(--space-8)", "--avatar-fallback-one-letter-font-size": "var(--' + 'font-size-5)", "borderRadius": "max(var(--radius-3), var(--radius-full))' + '", "letterSpacing": "var(--letter-spacing-4)", "--avatar-fallback-two-le' + 'tters-font-size": "var(--font-size-4)"} });' + ), + ("const sx_8df01e863a_c = stylex.props(sx_8df01e863a.s).className;"), ] # The colors the theme pages are read through, as Radix Themes defines them. diff --git a/tests/units/reflex_components_ui/layout/test_box.py b/tests/units/reflex_components_ui/layout/test_box.py index e74187cf753..a8997605ad0 100644 --- a/tests/units/reflex_components_ui/layout/test_box.py +++ b/tests/units/reflex_components_ui/layout/test_box.py @@ -178,7 +178,6 @@ def test_invalid_styles_of_a_component_are_type_errors( "\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 "None"\n' '\xa0\xa0\xa0\xa0"Literal[\'flx\']" is not assignable to "Sequence[_Display | ' '_StrVar | None]"\n' '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' @@ -186,7 +185,8 @@ def test_invalid_styles_of_a_component_are_type_errors( '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Display | _StrVar ' '| None"\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 "None"' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "None"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type "Literal[\'-webkit-box\']"' ), ), ( 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 9d31510b0bc..591657dc0a3 100644 --- a/tests/units/reflex_components_ui/style/test_css_props.py +++ b/tests/units/reflex_components_ui/style/test_css_props.py @@ -34,7 +34,6 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): "\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 "None"\n' '\xa0\xa0\xa0\xa0"Literal[\'flx\']" is not assignable to "Sequence[_Display | ' '_StrVar | None]"\n' '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' @@ -42,7 +41,8 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Display | _StrVar ' '| None"\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 "None"' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "None"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type "Literal[\'-webkit-box\']"' ), ), ( @@ -54,12 +54,12 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): '\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 "None"\n' '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "Sequence[_Position | ' '_StrVar | None]"\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 | None] | None]"\n' + '\xa0\xa0\xa0\xa0"Literal[1]" is not assignable to "None"\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\']"' ), @@ -73,7 +73,6 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): '\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 "None"\n' '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Sequence[_Display | ' '_StrVar | None]"\n' '\xa0\xa0\xa0\xa0"dict[str, str]" is not assignable to "Breakpoints[Any, Any]"\n' @@ -83,7 +82,8 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): 'not a subtype of "_Display | _StrVar | Mapping[str, _Display | ' '_StrVar | None] | None"\n' '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Display | _StrVar ' - '| Mapping[str, _Display | _StrVar | None] | None"' + '| Mapping[str, _Display | _StrVar | None] | None"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "Var[str]"' ), ), ( @@ -135,9 +135,10 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): '\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 "None"\n' '\xa0\xa0\xa0\xa0"Text" is not assignable to "Sequence[_Color | None]"\n' - '\xa0\xa0\xa0\xa0"Text" is not assignable to "Breakpoints[Any, Any]"' + '\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 | None] | None]"' ), ), ( @@ -167,7 +168,6 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): "\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 "None"\n' "\xa0\xa0\xa0\xa0\"Literal['invisible']\" is not assignable to " '"Sequence[_Visibility | _StrVar | None]"\n' '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' @@ -175,7 +175,8 @@ def test_invalid_styles_are_type_errors(pyright: Callable[[str], Diagnostics]): '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Type "str" is not assignable to type "_Visibility | ' '_StrVar | None"\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 "None"' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to "None"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type "Literal[\'collapse\']"' ), ), ( From aced038633006b2c1a81e2a4eef5faf4f387c5ed Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 08:57:50 +0000 Subject: [PATCH 116/204] Hold three form-control tests to nothing a Python version changes A foreach without an index argument names its index after the bytecode of its render function, which every Python version compiles differently: the radio group, select and slider tests pinned the name Python 3.14 gives and failed on the others. They now read the name from the foreach and check its shape. And the sides of a select are listed in the order of the Literal Python caches for those four values, which is the order of the module that first wrote them, not always that of the select. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../components/test_radio_group.py | 6 +++++- .../components/test_select.py | 16 +++++++++++++--- .../components/test_slider.py | 7 ++++++- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/tests/units/reflex_components_ui/components/test_radio_group.py b/tests/units/reflex_components_ui/components/test_radio_group.py index 1668d976751..2330558ff65 100644 --- a/tests/units/reflex_components_ui/components/test_radio_group.py +++ b/tests/units/reflex_components_ui/components/test_radio_group.py @@ -1,6 +1,7 @@ """Tests for reflex_components_ui.components.radio_group.""" import itertools +import re from collections.abc import Callable from typing import Any @@ -639,7 +640,10 @@ def test_radio_group_from_items(ui_plugin: UIPlugin): '(((typeof(value_rx_state_))?.valueOf?.() === "string"?.valueOf?.()) ? ' "value_rx_state_ : (JSON.stringify(value_rx_state_)))" ) - index = "index_cb46f9c6d80243188763ec1eabe9a266" + # Named after the bytecode of the function that renders an item, which + # differs from one Python version to the next. + index = items["index_var_name"] + assert re.fullmatch(r"index_[0-9a-f]{32}", index) assert rendered == { "name": '"div"', "props": ["className:sx_a088d40a93_c", 'role:"radiogroup"'], diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index 76d2c5a33d2..9facc01fcae 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -1,8 +1,9 @@ """Tests for reflex_components_ui.components.select.""" import itertools +import re from collections.abc import Callable -from typing import Any +from typing import Any, Literal, get_args import pytest from reflex_base.utils.imports import ImportVar @@ -1375,9 +1376,14 @@ def test_select_unknown_side(ui_plugin: UIPlugin): """A side a list cannot be on is an error that lists the sides.""" with pytest.raises(StyleError) as error: rx.ui.select.content(side="above") # pyright: ignore[reportArgumentType] + # In the order of the Literal Python keeps for these four values, which + # is the one of whichever module first wrote them. + sides = ", ".join( + f'"{side}"' for side in get_args(Literal["top", "right", "bottom", "left"]) + ) assert ( str(error.value) - == 'rx.ui.select_content: unknown side "above". The values are "top", "right", "bottom", "left".' + == f'rx.ui.select_content: unknown side "above". The values are {sides}.' ) @@ -1527,6 +1533,10 @@ def test_select_of_a_list_in_state(ui_plugin: UIPlugin): (group,) = content.children (options,) = group.children item = options.children[0] + # Named after the bytecode of the function that renders an option, which + # differs from one Python version to the next. + index = options.render()["index_var_name"] + assert re.fullmatch(r"index_[0-9a-f]{32}", index) assert item.render()["props"] == [ ( f'"aria-selected":(({STATE}.fruit_rx_state_ === item_rx_state_) ' @@ -1534,7 +1544,7 @@ def test_select_of_a_list_in_state(ui_plugin: UIPlugin): ), "className:sx_afbb711e7e_c", '"data-value":item_rx_state_', - "key:index_d6d6157c99650830f12a866606ea87b7", + f"key:{index}", 'role:"option"', "tabIndex:-1", ] diff --git a/tests/units/reflex_components_ui/components/test_slider.py b/tests/units/reflex_components_ui/components/test_slider.py index c35a46c9fa8..a0d623742e5 100644 --- a/tests/units/reflex_components_ui/components/test_slider.py +++ b/tests/units/reflex_components_ui/components/test_slider.py @@ -1,5 +1,6 @@ """Tests for reflex_components_ui.components.slider.""" +import re from collections.abc import Callable from typing import Any @@ -989,9 +990,13 @@ def test_slider_bound_to_state(ui_plugin: UIPlugin): ), ] thumb = slider.children[1].children[0] + # Named after the bytecode of the function that renders a thumb, which + # differs from one Python version to the next. + index = slider.children[1].render()["index_var_name"] + assert re.fullmatch(r"index_[0-9a-f]{32}", index) assert thumb.render()["props"] == [ "className:sx_04c810abee_c", - "key:index_026251c31afbb080c3de6ddc69e4448c", + f"key:{index}", f"min:{low}", 'type:"range"', 'value:(isNotNullOrUndefined(item_rx_state_) ? item_rx_state_ : "")', From d187b7b05ebfed4dc36d0fcdff4d31637cd741e1 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 09:00:34 +0000 Subject: [PATCH 117/204] Name the keys that do not scroll a focused scroll area Tab reaches rx.ui.scroll_area in WebKit, but neither End nor Space then scrolled it in Playwright's build, and the step only timed out. It now presses every key a browser scrolls a focused box with, each from the top, and fails with the list of the ones that moved it: all four must. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../ui_parity/components/scroll_area.py | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py index 3970d7d1dc8..24def0c820d 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py @@ -19,6 +19,9 @@ "large": (500, 300), } +# The keys that scroll a focused box down, the last one to its end. +SCROLL_KEYS = ["ArrowDown", "Space", "PageDown", "End"] + # The scroller of an area: the area itself in rx.ui, its viewport in Radix. SCROLLER = """(area) => [area, ...area.querySelectorAll("*")].find((element) => { const style = getComputedStyle(element); @@ -169,14 +172,26 @@ def _keyboard(run: Run) -> None: assert run.page.locator("#area").evaluate( f"(area) => ({SCROLLER})(area) === document.activeElement" ) - # A page down and back up: the keys every engine scrolls a focused box - # with. WebKit leaves Home and End to the platform, which may not bind them. - run.page.keyboard.press("Space") - run.page.wait_for_function( + # Every key a browser scrolls a focused box with, each from the top: the + # ones that did not move it are named when the step fails. + scrolled = ( f"(() => {{ const scroller = ({SCROLLER})(document.getElementById('area'));" " return scroller.scrollTop > 0; })()" ) - run.page.keyboard.press("Shift+Space") + moved = [] + for key in SCROLL_KEYS: + run.page.locator("#area").evaluate( + f"(area) => ({SCROLLER})(area).scrollTo({{top: 0, behavior: 'instant'}})" + ) + run.page.keyboard.press(key) + try: + run.page.wait_for_function(scrolled, timeout=2000) + except PlaywrightTimeoutError: + continue + moved.append(key) + assert moved == SCROLL_KEYS + # And back to the top, from the end the last key went to. + run.page.keyboard.press("Home") run.page.wait_for_function( f"({SCROLLER})(document.getElementById('area')).scrollTop === 0" ) From e1426e6c39bc185e579696d8dfbdf31bd4f3b87e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 09:05:19 +0000 Subject: [PATCH 118/204] Compare an element inside a cell only when both systems build it alike Counting the children of the parent alone matched the thumb of a Radix slider with the range input rx.ui has in its place, and the clipped box of a Radix table with the scroll area of rx.ui. An element whose own element children differ in number is now left out with its insides, and the report says so; the allowlist entry for the box of a table goes. Claude-Session: https://claude.ai/code/session_014AwvTM7ECAgjdiPKkCvGaD --- .../reflex-components-ui/parity/allowlist.toml | 6 ------ .../reflex-components-ui/parity/ui_parity/look.py | 15 ++++++++++----- .../reflex_components_ui/parity/test_look.py | 4 ++-- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 5bba13168b6..b2c6f1bf1bb 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -81,12 +81,6 @@ check = "pixels" cells = "*type-always*" reason = "rx.ui.scroll_area scrolls natively and has the scrollbars of the browser, thin and in the grays of the theme, where rx.scroll_area draws scrollbars of its own with JavaScript. Their shape and where they show follow the browser and the system: they may take room beside the content or lie over it, and `type` \"hover\" and \"scroll\" and `scroll_hide_delay` are left to them." -[[look]] -component = "table" -check = "style" -properties = ["overflow-x", "overflow-y"] -reason = "The box a table scrolls in is an rx.ui.scroll_area, which is itself the element that scrolls. In rx.table it is a clipped box around a viewport that scrolls and the scrollbars it draws." - [[look]] component = "checkbox" check = "a11y" diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py index 6ad664126de..5cdb2d90c88 100644 --- a/packages/reflex-components-ui/parity/ui_parity/look.py +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -582,8 +582,10 @@ def _unmatched( """Find the elements whose insides the two systems build differently. The elements inside the compared one correspond while each has as many - element children in one system as in the other. Where it does not, what - is inside it cannot be told apart and is not compared. + element children in one system as in the other. One that does not is + another element standing in the same place, as the thumb of a Radix + slider stands where rx.ui has a range input: it is not compared, and + neither is what is inside it. Args: reference: The computed properties of the reference, by part. @@ -602,8 +604,8 @@ def _unmatched( (count, tag), (their_count, _) = ours[path].split(), theirs[path].split() if count != their_count: unmatched[path] = ( - f"inside {_describe_path(path, tag)}: rx has {count} element " - f"children, rx.ui {their_count}" + f"{'at and ' if path else ''}inside {_describe_path(path, tag)}: " + f"rx has {count} element children, rx.ui {their_count}" ) return unmatched @@ -656,10 +658,13 @@ def _style_differences( ours, theirs = reference.get(part), candidate.get(part) name = part if part.startswith(">"): - # Not one a system names as a part, nor inside what differs in shape. + # Not one a system names as a part, nor one the systems build + # differently, nor inside such a one: an element with other + # insides is another element that happens to stand in its place. if ( ours is None or theirs is None + or part in unmatched or any(_inside(part, root) for root in unmatched) ): continue diff --git a/tests/units/reflex_components_ui/parity/test_look.py b/tests/units/reflex_components_ui/parity/test_look.py index ff872894a98..57e6bd27877 100644 --- a/tests/units/reflex_components_ui/parity/test_look.py +++ b/tests/units/reflex_components_ui/parity/test_look.py @@ -130,11 +130,11 @@ def test_style_differences_reach_the_elements_inside_that_correspond(): assert _style_differences(reference, candidate) == [ StyleDifference("> 1 ", "isolation", "isolate", "auto"), StyleDifference("> 1 > 1 ", "color", "red", "blue"), - StyleDifference("> 2 ", "color", "red", "green"), StyleDifference("icon", "(element)", None, "present"), ] assert _unmatched(reference, candidate) == { - "> 2": "inside > 2 : rx has 2 element children, rx.ui 1" + # Built differently: neither it nor what is inside it is compared. + "> 2": "at and inside > 2 : rx has 2 element children, rx.ui 1" } # Nothing inside an element that differs at its root is compared. assert _style_differences( From faaca262cf5b7fb391b7c2be41c6b4cb3f67f2e5 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 09:24:01 +0000 Subject: [PATCH 119/204] Add rx.ui.dialog on a native modal dialog, and the open look of a button The dialog is a dialog element that covers the page and scrolls a tall panel, opened with showModal: the browser has the top layer, the inert page, the focus and Escape. dialog.js opens it from its trigger, closes it from a button or beside its panel, says on the trigger that it is open, raises the events of the Radix wrapper and follows the state the dialog is bound to. The trigger and the close button also command the dialog, so a browser with invoker commands opens it with scripts off. What the alert dialog shares is in components/_dialog.py. A button has the look Radix Themes gives one whose popup is open. Claude-Session: https://claude.ai/code/session_014AwvTMWjpBRrG7rVgJBZHA --- .../js/src/behaviors/dialog.js | 142 +++++ .../js/tests/behaviors/dialog.test.js | 278 +++++++++ .../news/+wave4-overlays.feature.md | 4 +- .../parity/allowlist.toml | 30 + .../parity/ui_parity/app.py | 3 + .../parity/ui_parity/components/dialog.py | 547 +++++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/_dialog.py | 418 +++++++++++++ .../reflex_components_ui/components/dialog.py | 152 +++++ .../src/reflex_components_ui/styles/button.py | 8 +- .../src/reflex_components_ui/styles/dialog.py | 147 +++++ pyi_hashes.json | 2 +- .../tests_playwright/test_ui_components.py | 30 + .../components/test_button.py | 33 +- .../components/test_dialog.py | 574 ++++++++++++++++++ .../components/test_form.py | 2 +- .../components/test_icon_button.py | 7 +- .../components/test_skeleton.py | 6 +- .../reflex_components_ui/test_api_parity.py | 8 + 19 files changed, 2374 insertions(+), 18 deletions(-) create mode 100644 packages/reflex-components-ui/js/src/behaviors/dialog.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/dialog.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/dialog.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py create mode 100644 tests/units/reflex_components_ui/components/test_dialog.py diff --git a/packages/reflex-components-ui/js/src/behaviors/dialog.js b/packages/reflex-components-ui/js/src/behaviors/dialog.js new file mode 100644 index 00000000000..baded861eb4 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/dialog.js @@ -0,0 +1,142 @@ +// What a dialog does that the browser leaves to a script. +// +// The dialog is a native `dialog` opened with `showModal`: the browser puts +// it over everything else, makes the page behind it inert, moves the focus +// in and gives it back, and closes the topmost one on Escape. Left for a +// script: opening it from its trigger and closing it from a button or +// beside its panel where the browser has no commands, saying on the trigger +// that it is open, the events of the dialog, and a dialog bound to state, +// which shows what its state holds. + +const ROOT = "[data-rx-dialog-root]"; + +/** + * @typedef {{ open?: (open: boolean) => void, openAutoFocus?: () => void, closeAutoFocus?: () => void, escape?: () => void, outside?: () => void, interact?: () => void }} Handlers + */ + +/** @type {WeakMap} */ +const dialogs = new WeakMap(); + +/** + * Show on what opens a dialog whether it is open. + * + * @param {HTMLDialogElement} dialog The dialog. + * @param {boolean} open Whether it is open. + * @returns {void} + */ +function mark(dialog, open) { + const root = dialog.closest(ROOT); + for (const trigger of root?.querySelectorAll("[data-rx-dialog-trigger]") ?? + []) { + if (trigger.closest(ROOT) !== root) continue; + trigger.setAttribute("aria-expanded", String(open)); + trigger.setAttribute("data-state", open ? "open" : "closed"); + } +} + +/** + * Open a dialog over the page. + * + * @param {HTMLDialogElement} dialog The dialog. + * @returns {void} + */ +function show(dialog) { + dialog.showModal(); + // The browser scrolls to what it gives the focus: a tall dialog starts + // at its top, as in Radix. + dialog.scrollTop = 0; + mark(dialog, true); + dialogs.get(dialog)?.on?.openAutoFocus?.(); +} + +/** + * Open or close a dialog as its user asks: a dialog bound to state says so + * to its state instead, and shows what the state then holds. + * + * @param {HTMLDialogElement} dialog The dialog. + * @param {boolean} open Whether to open it. + * @param {...("escape" | "outside" | "interact")} why What dismissed it. + * @returns {void} + */ +function ask(dialog, open, ...why) { + const { on, bound } = dialogs.get(dialog) ?? {}; + for (const name of why) on?.[name]?.(); + if (bound || open) on?.open?.(open); + if (bound) return; + if (open) show(dialog); + else dialog.close(); +} + +/** + * Keep a dialog as its state says: the `ref` of the dialog, called again + * whenever the page renders. + * + * @param {HTMLDialogElement | null} dialog The dialog. + * @param {boolean | null} [open] Whether a dialog bound to state is open. + * @param {Handlers | null} [on] What the dialog does when it opens, closes + * or is dismissed. + * @returns {void} + */ +export function dialogSync(dialog, open, on) { + if (!dialog) return; + const first = !dialogs.has(dialog); + dialogs.set(dialog, { on: on ?? undefined, bound: open != null }); + const wanted = + open ?? (first && dialog.dataset.defaultOpen === "true" ? true : null); + if (wanted === null || wanted === dialog.open) return; + if (wanted) show(dialog); + else dialog.close(); +} + +/** + * Follow a press on what opens a dialog, on what closes it and beside its + * panel: the `onClick` of the element around the dialog. + * + * @param {{ target: EventTarget | null, currentTarget: Element, preventDefault: () => void }} event + * The press. + * @returns {void} + */ +export function dialogClick(event) { + const root = event.currentTarget; + const dialog = root.querySelector("dialog"); + const { target } = event; + if (!dialog || !(target instanceof Element)) return; + const part = target.closest( + "[data-rx-dialog-trigger], [data-rx-dialog-close]", + ); + if (part?.closest(ROOT) === root) { + // The script does what the command of a button asks the browser for. + event.preventDefault(); + ask(dialog, part.hasAttribute("data-rx-dialog-trigger")); + } else if ( + (target === dialog || target.parentElement === dialog) && + dialog.role !== "alertdialog" + ) + ask(dialog, false, "outside", "interact"); +} + +/** + * Follow a dialog that is asked to close and one that has closed: the + * `onCancel` and the `onClose` of the dialog. + * + * Escape asks, as a press beside the panel does. Once closed, by whatever + * closed it, the dialog says so. + * + * @param {{ type: string, target: EventTarget | null, currentTarget: HTMLDialogElement, preventDefault: () => void }} event + * The request or the closing. + * @returns {void} + */ +export function dialogEvent(event) { + const dialog = event.currentTarget; + // React hands a dialog the events of the dialogs inside it too. + if (event.target !== dialog) return; + if (event.type === "cancel") { + event.preventDefault(); + ask(dialog, false, "escape"); + return; + } + const { on, bound } = dialogs.get(dialog) ?? {}; + mark(dialog, false); + if (!bound) on?.open?.(false); + on?.closeAutoFocus?.(); +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js new file mode 100644 index 00000000000..6599c51de2d --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js @@ -0,0 +1,278 @@ +// What a dialog does with a press on its trigger, on a button that closes +// it and beside its panel, with Escape, and with the state it is bound to. +import { beforeEach, expect, test } from "vitest"; + +import { + dialogClick, + dialogEvent, + dialogSync, +} from "$/reflex-ui/behaviors/dialog.js"; + +// What jsdom has of a modal dialog: the attribute. These open and close +// one as a browser does, and send the event a browser sends. +HTMLDialogElement.prototype.showModal = function () { + this.open = true; +}; +HTMLDialogElement.prototype.close = function () { + if (!this.open) return; + this.open = false; + dialogEvent({ + type: "close", + target: this, + currentTarget: this, + preventDefault: () => {}, + }); +}; + +/** @type {HTMLElement} */ +let root; +/** @type {HTMLDialogElement} */ +let dialog; + +/** + * Render a dialog with a dialog of its own inside its panel. + * + * @param {string} [attributes] The attributes of the dialog. + * @returns {void} + */ +function render(attributes = "") { + document.body.innerHTML = ` +
+ + +
+
+ +
+ +
+
+
+
+
+
+ `; + root = /** @type {HTMLElement} */ (document.getElementById("root")); + dialog = /** @type {HTMLDialogElement} */ (document.getElementById("dialog")); +} + +beforeEach(() => render()); + +/** + * Make the handlers of a dialog, which keep what they are called with. + * + * @returns {{ on: Record void>, seen: string[] }} + * The handlers, and what was called, in order. + */ +function handlers() { + /** @type {string[]} */ + const seen = []; + const on = Object.fromEntries( + [ + "open", + "openAutoFocus", + "closeAutoFocus", + "escape", + "outside", + "interact", + ].map((name) => [ + name, + (/** @type {boolean | undefined} */ open) => + seen.push(open === undefined ? name : `${name}:${open}`), + ]), + ); + return { on, seen }; +} + +/** + * Press an element, as the element around the dialog hears it. + * + * @param {string | null} id The id of the element, or null for no element. + * @param {HTMLElement} [around] The element that hears the press. + * @returns {boolean} Whether the dialog kept the press from the browser. + */ +function press(id, around = root) { + let prevented = false; + dialogClick({ + target: id ? document.getElementById(id) : null, + currentTarget: around, + preventDefault: () => { + prevented = true; + }, + }); + return prevented; +} + +/** + * Press Escape in a dialog, as the dialog hears it. + * + * @param {HTMLDialogElement} [target] The dialog the key is pressed in. + * @returns {boolean} Whether the dialog kept the browser from closing it. + */ +function escape(target = dialog) { + let prevented = false; + dialogEvent({ + type: "cancel", + target, + currentTarget: dialog, + preventDefault: () => { + prevented = true; + }, + }); + return prevented; +} + +/** + * Read what the trigger says of its dialog. + * + * @returns {string} Whether the dialog is open, to assistive technology + * and to styles. + */ +function said() { + const trigger = /** @type {HTMLElement} */ (document.getElementById("open")); + return `${trigger.getAttribute("aria-expanded")}:${trigger.dataset.state}`; +} + +test("a press on the trigger opens the dialog, and one on its button closes it", () => { + const { on, seen } = handlers(); + dialogSync(dialog, null, on); + dialog.scrollTop = 40; + expect(press("open-text")).toBe(true); + expect([dialog.open, dialog.scrollTop, said()]).toEqual([ + true, + 0, + "true:open", + ]); + expect( + document.getElementById("inner-open")?.getAttribute("aria-expanded"), + ).toBe("false"); + expect(press("close")).toBe(true); + expect([dialog.open, said()]).toEqual([false, "false:closed"]); + expect(seen).toEqual([ + "open:true", + "openAutoFocus", + "open:false", + "closeAutoFocus", + ]); +}); + +test("a dialog without handlers opens and closes all the same", () => { + press("open"); + expect(dialog.open).toBe(true); + expect(escape()).toBe(true); + expect(dialog.open).toBe(false); + dialogSync(dialog); + press("open"); + expect(dialog.open).toBe(true); +}); + +test("a press beside the panel and Escape dismiss the dialog, and say what did", () => { + const { on, seen } = handlers(); + dialogSync(dialog, null, on); + press("open"); + expect(press("panel")).toBe(false); + expect(dialog.open).toBe(true); + expect(press("pad")).toBe(false); + expect(dialog.open).toBe(false); + press("open"); + press("dialog"); + expect(dialog.open).toBe(false); + press("open"); + expect(escape()).toBe(true); + expect(dialog.open).toBe(false); + expect(seen).toEqual([ + "open:true", + "openAutoFocus", + "outside", + "interact", + "open:false", + "closeAutoFocus", + "open:true", + "openAutoFocus", + "outside", + "interact", + "open:false", + "closeAutoFocus", + "open:true", + "openAutoFocus", + "escape", + "open:false", + "closeAutoFocus", + ]); +}); + +test("a press beside the panel of an alert dialog does not dismiss it", () => { + render('role="alertdialog"'); + press("open"); + press("pad"); + press("dialog"); + expect(dialog.open).toBe(true); + expect(escape()).toBe(true); + expect(dialog.open).toBe(false); +}); + +test("a dialog bound to state says what is asked of it, and shows its state", () => { + const { on, seen } = handlers(); + dialogSync(dialog, false, on); + expect(press("open")).toBe(true); + expect(dialog.open).toBe(false); + dialogSync(dialog, true, on); + expect([dialog.open, said()]).toEqual([true, "true:open"]); + dialogSync(dialog, true, on); + expect(escape()).toBe(true); + press("close"); + press("pad"); + expect(dialog.open).toBe(true); + dialogSync(dialog, false, on); + expect([dialog.open, said()]).toEqual([false, "false:closed"]); + expect(seen).toEqual([ + "open:true", + "openAutoFocus", + "escape", + "open:false", + "open:false", + "outside", + "interact", + "open:false", + "closeAutoFocus", + ]); +}); + +test("a dialog that starts open opens once", () => { + render('data-default-open="true"'); + const { on, seen } = handlers(); + dialogSync(dialog, null, on); + expect(dialog.open).toBe(true); + press("close"); + dialogSync(dialog, null, on); + expect(dialog.open).toBe(false); + expect(seen).toEqual(["openAutoFocus", "open:false", "closeAutoFocus"]); + dialogSync(null); +}); + +test("the dialog inside a dialog is its own", () => { + const inner = /** @type {HTMLDialogElement} */ ( + document.getElementById("inner") + ); + const innerRoot = /** @type {HTMLElement} */ ( + document.getElementById("inner-root") + ); + press("open"); + // The press on what opens the inner dialog reaches both elements. + press("inner-open", innerRoot); + press("inner-open"); + expect([dialog.open, inner.open]).toEqual([true, true]); + expect(escape(inner)).toBe(false); + press("inner-pad"); + press("inner-close"); + expect([dialog.open, inner.open]).toEqual([true, true]); + press("inner-close", innerRoot); + expect([dialog.open, inner.open, said()]).toEqual([true, false, "true:open"]); +}); + +test("a press on anything else is left alone", () => { + expect(press(null)).toBe(false); + expect(press("elsewhere")).toBe(false); + dialog.remove(); + expect(press("open")).toBe(false); +}); diff --git a/packages/reflex-components-ui/news/+wave4-overlays.feature.md b/packages/reflex-components-ui/news/+wave4-overlays.feature.md index 8788a5c71b8..6b8bf29d845 100644 --- a/packages/reflex-components-ui/news/+wave4-overlays.feature.md +++ b/packages/reflex-components-ui/news/+wave4-overlays.feature.md @@ -1 +1,3 @@ -Add the overlays and the disclosure components to `rx.ui`: `tabs` and `accordion`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. +Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion` and `dialog`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog is a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. + +A button whose popup is open has the look Radix Themes gives it (`[data-state='open']`), which `rx.ui.button` did not have. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 9ace51c9f1c..d956d71e3b5 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -319,3 +319,33 @@ reason = "The headers of rx.ui.accordion are native `summary` elements: Tab and component = "accordion" step = "hands over the open items in the order they were opened in" reason = "`on_value_change` of an rx.ui.accordion of `type=\"multiple\"` hands over the values of the open items in the order of the items, whatever the order they were opened in: the accordion keeps no state of its own and reads its items. rx.accordion appends each value as it is opened." + +[[look]] +component = "dialog" +check = "style" +cells = "*@open" +properties = ["pointer-events"] +reason = "While it is open rx.dialog takes the pointer off the rest of the page with a style on the body. rx.ui.dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style." + +[[contract]] +component = "dialog" +step = "what it holds is in the server render" +system = "rx" +reason = "rx.dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.dialog holds is in the page from the start, in a dialog that is closed, so it is there for a search engine and for the browser's find in page once the dialog is open, and it keeps its state between two openings." + +[[contract]] +component = "dialog" +step = "opens and closes with JavaScript disabled" +system = "rx" +reason = "rx.dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript." + +[[contract]] +component = "dialog" +step = "Tab stays inside an open dialog" +reason = "rx.ui.dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.dialog keeps the focus from leaving the dialog at all." + +[[contract]] +component = "dialog" +step = "the dark appearance of a theme around a dialog reaches its panel" +system = "rx" +reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a dialog included. rx.ui.theme does, and a dialog declared inside a dark rx.ui.theme is dark: its panel, what it holds and what is drawn over the page behind it." diff --git a/packages/reflex-components-ui/parity/ui_parity/app.py b/packages/reflex-components-ui/parity/ui_parity/app.py index ed81eabacba..be620ec49ae 100644 --- a/packages/reflex-components-ui/parity/ui_parity/app.py +++ b/packages/reflex-components-ui/parity/ui_parity/app.py @@ -116,6 +116,9 @@ def parity_page(matrix: Matrix) -> rx.Component: "grid_template_columns": f"repeat(auto-fill, {matrix.stage[0]}px)", "gap": f"{GAP}px", "padding": f"{GAP}px", + # Room to scroll the last frame to the top of the viewport, where + # what covers the viewport, such as a dialog, is read. + "padding_bottom": "100vh", }, ) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py new file mode 100644 index 00000000000..22d567eff24 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py @@ -0,0 +1,547 @@ +"""The dialog: closed and open in every size, over the page, and how it is dismissed.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import PARAGRAPH, focused, wait_for_text + +SIZES = ["1", "2", "3", "4"] +OPEN = "open" +# A dialog that is open, in either system. +SHOWN = "[role=dialog]:visible, dialog[open]" + + +def body(namespace: Any, kind: Any, long: bool = False) -> list[Any]: + """Create what a dialog of a matrix holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + kind: The namespace of the dialog. + long: Whether it holds more than the viewport has room for. + + Returns: + A title, a description, and the buttons that close the dialog. + """ + closes = getattr(kind, "close", None) or kind.cancel + return [ + kind.title("Edit profile"), + kind.description("Make changes to your profile."), + *(rx.el.p(f"{number}. {PARAGRAPH}") for number in range(1, 40 if long else 1)), + namespace.flex( + closes(namespace.button("Cancel", variant="soft", color_scheme="gray")), + closes(namespace.button("Save")), + spacing="3", + justify="end", + margin_top="16px", + ), + ] + + +def _dialog(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a dialog and the button that opens it. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the content. ``long`` asks for more than the + viewport has room for, ``themed`` for a theme of another accent + and radius around the dialog, and ``variant`` is the + one of the button that opens it. + + Returns: + The dialog. + """ + props = dict(props) + dialog = namespace.dialog + long, themed = props.pop("long", False), props.pop("themed", False) + shown = dialog.root( + dialog.trigger(namespace.button("Open", variant=props.pop("variant", "solid"))), + dialog.content(*body(namespace, dialog, long), **props), + ) + if themed: + return namespace.theme(shown, accent_color="ruby", radius="full") + return shown + + +def open_dialog(page: Page, target: Locator, point: Point) -> None: + """Open a dialog from its trigger, and wait for it. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + target.click() + page.locator(SHOWN).first.wait_for() + # The pointer is not left on the trigger, nor on a button of the dialog. + page.mouse.move(1, 1) + + +def close_dialog(page: Page, target: Locator, point: Point) -> None: + """Close the open dialog, and take the focus off its trigger. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + page.keyboard.press("Escape") + page.locator(SHOWN).first.wait_for(state="detached") + # The trigger has the focus back before it loses it: a focus that came + # back later would scroll the page to the trigger under the next cell. + target.evaluate( + "trigger => new Promise(done => {" + " const wait = () => document.activeElement === trigger" + " ? done(trigger.blur()) : requestAnimationFrame(wait); wait(); })" + ) + + +OPENED = State(enter=open_dialog, leave=close_dialog, matches="[data-state='open']") + +MATRIX = Matrix( + component="dialog", + render=_dialog, + sweep={ + "size": SIZES, + "long": [True], + "themed": [True], + "max_width": ["450px"], + "variant": ["soft", "classic", "surface"], + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE, OPEN], + }, + groups=[ + {"size": SIZES, "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"long": [True], "size": ["1", "4"], "state": [OPEN]}, + {"themed": [True], "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"max_width": ["450px"], "state": [OPEN]}, + { + "variant": ["soft", "classic", "surface", "ghost", "outline"], + "state": [OPEN], + }, + ], + # As wide as the page, one frame under another: a dialog covers the + # viewport, and is read in the frame the page is scrolled to. + stage=(1200, 700), + crop="stage", + target="button", + states={OPEN: OPENED}, + # Not held to zero. At a threshold of zero every cell but two is equal + # pixel for pixel: the ring of the focus on the trigger, which the + # browser anti-aliases by where the button is on the page, differs by 9 + # pixels of 840000, and by 6 at the default threshold. + tolerance=0.00002, +) + + +class DialogState(rx.State): + """What the dialogs of the contract are bound to.""" + + shown: rx.Field[bool] = rx.field(False) + seen: rx.Field[list[str]] = rx.field(default_factory=list) + clicks: rx.Field[int] = rx.field(0) + + @rx.event + def set_shown(self, value: bool): + """Follow the bound dialog. + + Args: + value: Whether it is open. + """ + self.shown = value + + @rx.event + def see_open(self, value: bool): + """Keep whether a dialog opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def see(self, what: str): + """Keep what happened to a dialog. + + Args: + what: The event. + """ + self.seen.append(what) + + @rx.event + def save(self): + """Close the bound dialog from the backend.""" + self.shown = False + + @rx.event + def click(self): + """Count a click on the button behind the dialogs.""" + self.clicks += 1 + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + A dialog that says what happens to it, one bound to state, one with + a dialog and a select inside it, and one in a theme of its own. + """ + dialog, button = namespace.dialog, namespace.button + return namespace.box( + dialog.root( + dialog.trigger(button("Open", id="open")), + dialog.content( + dialog.title("Edit profile"), + dialog.description("Make changes to your profile."), + rx.el.input(id="name"), + dialog.close(button("Close", id="close")), + id="panel", + on_open_auto_focus=DialogState.see("focus-in"), + on_close_auto_focus=DialogState.see("focus-out"), + on_escape_key_down=DialogState.see("escape"), + on_pointer_down_outside=DialogState.see("outside"), + on_interact_outside=DialogState.see("interact"), + ), + on_open_change=DialogState.see_open, + ), + dialog.root( + dialog.trigger(button("Bound", id="bound-open")), + dialog.content( + dialog.title("Bound"), + button("Save", id="save", on_click=DialogState.save), + id="bound-panel", + ), + open=DialogState.shown, + on_open_change=DialogState.set_shown, + ), + dialog.root( + dialog.trigger(button("Outer", id="outer-open")), + dialog.content( + dialog.title("Outer"), + namespace.select( + ["Small", "Large"], + default_value="Small", + id="pick", + position="popper", + ), + dialog.root( + dialog.trigger(button("Inner", id="inner-open")), + dialog.content( + dialog.title("Inner"), + dialog.close(button("Back", id="inner-close")), + id="inner-panel", + ), + ), + dialog.close(button("Done", id="outer-close")), + id="outer-panel", + ), + ), + namespace.theme( + dialog.root( + dialog.trigger(button("Themed", id="themed-open")), + dialog.content( + dialog.title("Themed"), + dialog.close(button("Fine", id="themed-close")), + id="themed-panel", + ), + ), + accent_color="ruby", + appearance="dark", + ), + rx.el.button("Show", id="show", on_click=DialogState.set_shown(True)), + rx.el.button("Behind", id="behind", on_click=DialogState.click), + rx.el.span(DialogState.seen.to_string(), id="seen"), + rx.el.span(DialogState.shown.to_string(), id="shown"), + rx.el.span(DialogState.clicks.to_string(), id="clicks"), + ) + + +CONTRACT = Contract(component="dialog", render=_contract) + +# The properties of the panel of a dialog a step reads. +BOX = ( + "position", + "box-sizing", + "width", + "max-width", + "padding-top", + "padding-left", + "border-top-left-radius", + "background-color", + "overflow-y", + "outline-style", + "opacity", + "transform", +) + + +def _open(run: Run, trigger: str, panel: str) -> None: + """Open a dialog from its trigger, and wait for its panel. + + Args: + run: The run, on a page. + trigger: The id of the trigger. + panel: The id of the panel. + """ + run.page.locator(f"#{trigger}").click() + run.page.locator(f"#{panel}").wait_for() + + +def _wait_for_closed(run: Run, panel: str) -> None: + """Wait until a dialog is closed. + + Args: + run: The run, on a page. + panel: The id of its panel. + """ + run.page.locator(f"#{panel}").wait_for(state="hidden") + + +def _wait_for_focus(run: Run, element: str) -> None: + """Wait until an element has the focus. + + Args: + run: The run, on a page. + element: Its id. + """ + run.page.wait_for_function("id => document.activeElement.id === id", arg=element) + + +@CONTRACT.step("its trigger is a button in the server render", on=SERVER) +def _server_render(run: Run) -> None: + trigger = run.server.element("open") + assert (trigger.tag, trigger.text, trigger.attributes["aria-haspopup"]) == ( + "button", + "Open", + "dialog", + ) + + +@CONTRACT.step("what it holds is in the server render", on=SERVER) +def _server_content(run: Run) -> None: + assert run.server.element("panel").text == ( + "Edit profileMake changes to your profile.Close" + ) + + +@CONTRACT.step("opens and closes with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + assert not page.locator("#panel").is_visible() + page.locator("#open").click() + page.wait_for_timeout(300) + assert page.locator("#panel").is_visible() + page.locator("#close").click() + page.wait_for_timeout(300) + assert not page.locator("#panel").is_visible() + + +@CONTRACT.step("has the role, the name and the description of a dialog") +def _role(run: Run) -> None: + page = run.page + trigger = page.locator("#open") + assert trigger.get_attribute("aria-expanded") == "false" + assert trigger.get_attribute("data-state") == "closed" + _open(run, "open", "panel") + assert trigger.get_attribute("aria-expanded") == "true" + assert trigger.get_attribute("data-state") == "open" + shown = page.get_by_role("dialog", name="Edit profile") + assert shown.count() == 1 + assert shown.evaluate( + "dialog => document.getElementById(dialog.getAttribute('aria-describedby'))" + ".textContent" + ) == ("Make changes to your profile.") + assert shown.get_by_role("heading", name="Edit profile").count() == 1 + + +@CONTRACT.step("the panel has the box of a dialog of the third size") +def _box(run: Run) -> None: + _open(run, "open", "panel") + run.page.wait_for_timeout(400) + assert run.page.locator("#panel").evaluate( + "(panel, names) => names.map(name => getComputedStyle(panel)" + ".getPropertyValue(name))", + list(BOX), + ) == [ + "relative", + "border-box", + "600px", + "600px", + "24px", + "24px", + "12px", + "rgb(255, 255, 255)", + "auto", + "none", + "1", + "none", + ] + + +@CONTRACT.step("the focus moves into the dialog, and back to its trigger") +def _focus(run: Run) -> None: + page = run.page + page.locator("#open").focus() + page.keyboard.press("Enter") + page.locator("#panel").wait_for() + _wait_for_focus(run, "name") + page.keyboard.press("Escape") + _wait_for_closed(run, "panel") + _wait_for_focus(run, "open") + page.keyboard.press("Space") + page.locator("#panel").wait_for() + page.locator("#close").click() + _wait_for_closed(run, "panel") + _wait_for_focus(run, "open") + + +@CONTRACT.step("Tab stays inside an open dialog") +def _tab(run: Run) -> None: + page = run.page + _open(run, "open", "panel") + stops = [] + for _ in range(5): + page.keyboard.press("Tab") + stops.append(focused(page)) + assert stops == ["close", "name", "close", "name", "close"] + page.keyboard.press("Shift+Tab") + assert focused(page) == "name" + + +@CONTRACT.step("a press beside the panel closes the dialog") +def _outside(run: Run) -> None: + page = run.page + _open(run, "open", "panel") + page.locator("#panel").click(position={"x": 5, "y": 5}) + page.wait_for_timeout(200) + assert page.locator("#panel").is_visible() + page.mouse.click(5, 5) + _wait_for_closed(run, "panel") + + +@CONTRACT.step("the page behind an open dialog takes no click") +def _modal(run: Run) -> None: + page = run.page + box = page.locator("#behind").bounding_box() + assert box is not None + _open(run, "open", "panel") + page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + _wait_for_closed(run, "panel") + page.wait_for_timeout(300) + assert page.locator("#clicks").text_content() == "0" + + +@CONTRACT.step("says when it opens and closes, and what dismissed it") +def _events(run: Run) -> None: + page = run.page + _open(run, "open", "panel") + wait_for_text(page, "seen", '["open","focus-in"]') + page.keyboard.press("Escape") + _wait_for_closed(run, "panel") + wait_for_text(page, "seen", '["open","focus-in","escape","closed","focus-out"]') + + +@CONTRACT.step("says that a press beside the panel dismissed it") +def _events_outside(run: Run) -> None: + page = run.page + _open(run, "open", "panel") + page.mouse.click(5, 5) + _wait_for_closed(run, "panel") + wait_for_text( + page, + "seen", + '["open","focus-in","outside","interact","closed","focus-out"]', + ) + + +@CONTRACT.step("a dialog in a dialog opens over it, and Escape closes the topmost") +def _nested(run: Run) -> None: + page = run.page + _open(run, "outer-open", "outer-panel") + _open(run, "inner-open", "inner-panel") + # Once the focus is in the dialog it is the topmost, to both systems. + _wait_for_focus(run, "inner-close") + page.locator("#outer-panel").wait_for() + page.keyboard.press("Escape") + _wait_for_closed(run, "inner-panel") + page.locator("#outer-panel").wait_for() + _wait_for_focus(run, "inner-open") + _open(run, "inner-open", "inner-panel") + # Once the focus is in the dialog it is the topmost, to both systems. + _wait_for_focus(run, "inner-close") + page.locator("#inner-close").click() + _wait_for_closed(run, "inner-panel") + page.locator("#outer-panel").wait_for() + page.keyboard.press("Escape") + _wait_for_closed(run, "outer-panel") + _wait_for_focus(run, "outer-open") + + +@CONTRACT.step("a select in a dialog opens over it and chooses") +def _select(run: Run) -> None: + page = run.page + _open(run, "outer-open", "outer-panel") + page.locator("#pick").focus() + page.keyboard.press("Enter") + page.get_by_role("option", name="Large").wait_for() + page.wait_for_function("document.activeElement.getAttribute('role') === 'option'") + page.keyboard.press("ArrowDown") + page.wait_for_function("document.activeElement.textContent === 'Large'") + page.keyboard.press("Enter") + wait_for_text(page, "pick", "Large") + page.get_by_role("option", name="Large").wait_for(state="hidden") + page.locator("#outer-panel").wait_for() + page.locator("#pick").focus() + page.keyboard.press("Enter") + page.get_by_role("option", name="Large").wait_for() + page.keyboard.press("Escape") + page.get_by_role("option", name="Large").wait_for(state="hidden") + page.locator("#outer-panel").wait_for() + + +@CONTRACT.step("a dialog bound to state follows it, and is closed from the backend") +def _bound(run: Run) -> None: + page = run.page + page.locator("#show").click() + page.locator("#bound-panel").wait_for() + wait_for_text(page, "shown", "true") + page.locator("#save").click() + _wait_for_closed(run, "bound-panel") + wait_for_text(page, "shown", "false") + _open(run, "bound-open", "bound-panel") + wait_for_text(page, "shown", "true") + page.keyboard.press("Escape") + _wait_for_closed(run, "bound-panel") + wait_for_text(page, "shown", "false") + + +@CONTRACT.step("the accent of a theme around a dialog reaches what it holds") +def _themed(run: Run) -> None: + page = run.page + _open(run, "themed-open", "themed-panel") + page.mouse.move(1, 1) + page.wait_for_timeout(400) + assert page.locator("#themed-close").evaluate( + "element => getComputedStyle(element).backgroundColor" + ) == ("rgb(229, 70, 102)") + + +@CONTRACT.step("the dark appearance of a theme around a dialog reaches its panel") +def _themed_dark(run: Run) -> None: + page = run.page + _open(run, "themed-open", "themed-panel") + page.wait_for_timeout(400) + assert page.locator("#themed-panel").evaluate( + "element => getComputedStyle(element).backgroundColor" + ) == ("rgb(25, 25, 25)") 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 f2181669c13..d4537e28476 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -18,6 +18,7 @@ "components.checkbox_cards": ["checkbox_cards"], "components.checkbox_group": ["checkbox_group"], "components.data_list": ["data_list"], + "components.dialog": ["dialog"], "components.form": ["form"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py new file mode 100644 index 00000000000..36a3de2a3db --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py @@ -0,0 +1,418 @@ +"""What a dialog and an alert dialog share: a native ``dialog`` and its parts.""" + +from __future__ import annotations + +import dataclasses +import itertools +from collections.abc import Iterator +from typing import Any, ClassVar + +from reflex_base.components.component import Component +from reflex_base.components.tags import CommonTag +from reflex_base.vars.base import LiteralVar, Var, VarData + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.components._group import descendants +from reflex_components_ui.components._script import handlers, listen, script +from reflex_components_ui.layout.flex import Flex +from reflex_components_ui.style import ComponentStyles, StyleError +from reflex_components_ui.styles.dialog import ( + DIALOG, + DIALOG_DESCRIPTION, + DIALOG_ROOT, + DIALOG_TITLE, +) + +# Numbers the dialogs of an app: a dialog is named by the id of its title. +_ids = itertools.count(1) + +# The events of a dialog as they are rendered, by the name the script calls +# each under. +_EVENTS = { + "onOpenChange": "open", + "onOpenAutoFocus": "openAutoFocus", + "onCloseAutoFocus": "closeAutoFocus", + "onEscapeKeyDown": "escape", + "onPointerDownOutside": "outside", + "onInteractOutside": "interact", +} + + +class DialogRootBase(UIComponent): + """The element around the parts of a dialog. + + Radix hands the parts of a dialog its props through a context. Here the + root finds its parts while compiling, and gives them what they render. + """ + + tag = "div" + + styles: ClassVar[ComponentStyles] = DIALOG_ROOT + + def _post_init(self, *args, **kwargs): + """Initialize the dialog, and give its parts what they share. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + name = f"rx-dialog-{next(_ids)}" + on_open_change = self.event_triggers.pop("on_open_change", None) + parts = list(descendants(self, DialogPart, DialogRootBase)) + named: dict[str, Any] = {} + for part in parts: + if part._names is not None: + if part.id is None: + part.id = LiteralVar.create(f"{name}-{part._names}") + named.setdefault(f"aria-{part._names}", part.id) + for part in parts: + part._join(self, name, named, on_open_change) + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the dialog off the element. + + Returns: + The props read as styles, and whether the dialog is open. + """ + return [*super()._exclude_props(), "open", "default_open"] + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the dialog, the script that opens it 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 script("dialog", "dialogClick") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the element around the dialog. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, which hears a press on what opens the dialog, on what + closes it and beside its panel. + """ + tag = super()._render(props).add_props(**{"data-rx-dialog-root": ""}) + return listen(tag, script("dialog", "dialogClick"), "onClick") + + +class DialogPart(UIComponent): + """A part of a dialog, which its root gives a name.""" + + # What the part is to the dialog: ``labelledby`` for its title, + # ``describedby`` for its description. + _names: ClassVar[str | None] = None + + def _post_init(self, *args, **kwargs): + """Initialize the part, as one outside a dialog. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # The attributes the dialog gives the part. + self._dialog: dict[str, Any] = {} + super()._post_init(*args, **kwargs) + + def _join( + self, + root: DialogRootBase, + name: str, + named: dict[str, Any], + on_open_change: Any, + ) -> None: + """Take from a dialog what Radix hands its parts through a context. + + Args: + root: The dialog the part is in. + name: The id of the dialog. + named: What names and describes the dialog, by the attribute. + on_open_change: What the dialog does when it opens or closes. + """ + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the part, those its dialog gives it 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) + for value in self._dialog.values(): + if isinstance(value, Var): + yield value + + +class DialogSlot(DialogPart): + """A part of a dialog that is rendered as its child: what opens or closes it. + + These parts act on a press, and so does a child with a handler of its + own for one: such a child is put in a flex container, which is then the + part, as in the Radix components. + """ + + # The child keeps its own styles. + _merges_slot: ClassVar[bool] = False + + # The command a button gives the dialog without a script, where the + # browser has commands. + _command: ClassVar[str] = "close" + + # The attribute the script finds the part by. + _mark: ClassVar[str] = "data-rx-dialog-close" + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a part that is rendered as its child. + + Args: + *children: The child: one element. + **props: The properties of the component. + + Returns: + The component. + """ + for child in children: + if "on_click" in getattr(child, "event_triggers", {}): + children = (Flex.create(*children),) + break + return super().create(*children, **props) + + def _post_init(self, *args, **kwargs): + """Initialize the part, rendered as its only child. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + + Raises: + StyleError: If the part does not have exactly one child that is + an element. + """ + super()._post_init(*args, **kwargs) + children = self.children + if ( + len(children) != 1 + or not isinstance(children[0], Component) + or type(children[0]).render not in (Component.render, UIComponent.render) + ): + msg = ( + f"{self._display_name()}: it is rendered as its child, so it " + "needs exactly one child that is an element, such as a button." + ) + raise StyleError(msg) + self._as_child = True + # The child has to stay the child: a compile would otherwise move + # one that is bound to state into a component of its own. + self._memoization_mode = dataclasses.replace( + self._memoization_mode, recursive=False + ) + + def _join( + self, + root: DialogRootBase, + name: str, + named: dict[str, Any], + on_open_change: Any, + ) -> None: + """Take the id of the dialog, for a button that commands it. + + Args: + root: The dialog the part is in. + name: The id of the dialog. + named: What names and describes the dialog, by the attribute. + on_open_change: What the dialog does when it opens or closes. + """ + if getattr(root, "open", None) is None: + # A dialog bound to state opens and closes when its state says. + self._dialog = {"commandfor": name, "command": self._command} + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the part. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, marked for the script of the dialog. + """ + return super()._render(props).add_props(**{self._mark: "", **self._dialog}) + + +class DialogTriggerBase(DialogSlot): + """What opens a dialog: its child, which says so.""" + + _command: ClassVar[str] = "show-modal" + + _mark: ClassVar[str] = "data-rx-dialog-trigger" + + def _join( + self, + root: DialogRootBase, + name: str, + named: dict[str, Any], + on_open_change: Any, + ) -> None: + """Take the id of the dialog the trigger opens. + + Args: + root: The dialog the trigger is in. + name: The id of the dialog. + named: What names and describes the dialog, by the attribute. + on_open_change: What the dialog does when it opens or closes. + """ + super()._join(root, name, named, on_open_change) + self._dialog["aria-controls"] = name + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, with the state Radix gives what opens a + dialog. + """ + return ( + super() + ._render(props) + .add_props(**{ + "aria-haspopup": "dialog", + "aria-expanded": False, + "data-state": "closed", + }) + ) + + +class DialogSurface(DialogPart): + """The native dialog: it covers the page, around the panel of the dialog.""" + + tag = "dialog" + + styles: ClassVar[ComponentStyles] = DIALOG + + # The role of the dialog, when it is not the one the element has. + _role: ClassVar[str | None] = None + + def _join( + self, + root: DialogRootBase, + name: str, + named: dict[str, Any], + on_open_change: Any, + ) -> None: + """Take the name of the dialog, and whether it is open. + + Args: + root: The dialog the element is in. + name: The id of the dialog. + named: What names and describes the dialog, by the attribute. + on_open_change: What the dialog does when it opens or closes. + """ + self._dialog = {"id": name, **named} + self._open = getattr(root, "open", None) + default_open = getattr(root, "default_open", None) + if default_open is not None: + self._dialog["data-default-open"] = default_open + if on_open_change is not None: + self.event_triggers["on_open_change"] = on_open_change + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the dialog, its script 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 script("dialog", "dialogSync") + yield script("dialog", "dialogEvent") + if getattr(self, "_open", None) is not None: + yield self._open + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the dialog. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a ``dialog`` the script opens over the page, which + follows the state it is bound to and says what happens to it. + """ + tag, on = handlers(super()._render(props), _EVENTS) + bound = LiteralVar.create(getattr(self, "_open", None)) + sync = script("dialog", "dialogSync") + tag = tag.add_props(**{ + "data-rx-popup": "", + "role": self._role, + **self._dialog, + # Called whenever the page renders: a dialog bound to state + # takes whether it is open from there. + "ref": Var( + f"((dialog) => dialogSync(dialog, {bound!s}, {'null' if on is None else on!s}))", + _var_data=VarData.merge( + sync._get_all_var_data(), + bound._get_all_var_data(), + None if on is None else on._get_all_var_data(), + ), + ), + }) + return listen(tag, script("dialog", "dialogEvent"), "onCancel", "onClose") + + +def surface( + kind: type[DialogSurface], content: Component, events: dict[str, Any] +) -> Component: + """Put the panel of a dialog in the native dialog that covers the page. + + Args: + kind: The class of the dialog. + content: The panel. + events: What the dialog does when it opens, closes or is dismissed. + + Returns: + The dialog: the room around the panel is what scrolls a tall one. + """ + return kind.create(Part.create(content, part="pad", tag="div"), **events) + + +class DialogTitleBase(DialogPart): + """The title of a dialog, which names it.""" + + tag = "h1" + + styles: ClassVar[ComponentStyles] = DIALOG_TITLE + + _names: ClassVar[str | None] = "labelledby" + + +class DialogDescriptionBase(DialogPart): + """The description of a dialog, which a screen reader reads with its name.""" + + tag = "p" + + styles: ClassVar[ComponentStyles] = DIALOG_DESCRIPTION + + _names: ClassVar[str | None] = "describedby" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py new file mode 100644 index 00000000000..717f12e2f18 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py @@ -0,0 +1,152 @@ +"""A dialog: a native modal ``dialog``, and what opens and closes it.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._dialog import ( + DialogDescriptionBase, + DialogRootBase, + DialogSlot, + DialogSurface, + DialogTitleBase, + DialogTriggerBase, + surface, +) +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.dialog import DIALOG_CONTENT + + +class DialogRoot(DialogRootBase): + """Root component for Dialog.""" + + open: Var[bool] = field(doc="The controlled open state of the dialog.") + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + default_open: Var[bool] = field( + doc="The open state of the dialog when it is initially rendered. Use when you do not need to control its open state." + ) + + +class DialogTrigger(DialogTriggerBase): + """Trigger an action or event, to open a Dialog modal.""" + + +class DialogTitle(DialogTitleBase): + """Title component to display inside a Dialog modal.""" + + +class DialogOverlay(DialogSurface): + """The native dialog around the content of a Dialog modal.""" + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + on_open_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is opened." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the dialog." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer interacts outside the dialog." + ) + + +_EVENTS = ( + "on_open_auto_focus", + "on_close_auto_focus", + "on_escape_key_down", + "on_pointer_down_outside", + "on_interact_outside", +) + + +class DialogContent(UIComponent, elements.Div): + """Content component to display inside a Dialog modal.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = DIALOG_CONTENT + + size: Var[Responsive[Literal["1", "2", "3", "4"]]] = field( + doc='DialogContent size "1" - "4"' + ) + + on_open_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is opened." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the dialog." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer interacts outside the dialog." + ) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a DialogContent. + + Args: + *children: What the dialog holds. + **props: The properties of the component. Its styles are those + of the panel, and its events those of the dialog around it. + + Returns: + The native dialog, around the panel. + """ + events = {event: props.pop(event) for event in _EVENTS if event in props} + return surface(DialogOverlay, super().create(*children, **props), events) + + +class DialogDescription(DialogDescriptionBase): + """Description component to display inside a Dialog modal.""" + + +class DialogClose(DialogSlot): + """Close button component to close an open Dialog modal.""" + + +class Dialog(ComponentNamespace): + """Dialog components namespace.""" + + root = __call__ = staticmethod(DialogRoot.create) + trigger = staticmethod(DialogTrigger.create) + title = staticmethod(DialogTitle.create) + content = staticmethod(DialogContent.create) + description = staticmethod(DialogDescription.create) + close = staticmethod(DialogClose.create) + + +dialog = Dialog() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py index 04b8f8fd1ca..868aac1419b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py @@ -40,21 +40,23 @@ _POINTER = "@media (hover: hover)" _HOVER = ":hover:not(:active)" _ACTIVE = ":active:not([data-state='open'])" +_OPEN = "[data-state='open']" _DISABLED = "[data-disabled]" _FOCUS = ":focus-visible" _TOUCH = "@media (pointer: coarse)" def _hover(style: dict[str, Any]) -> dict[str, Any]: - """Make the styles of a button under the pointer. + """Make the styles of a button under the pointer, or whose popup is open. Args: style: The styles. Returns: - The styles, where a pointer can hover and the button is not pressed. + The styles, where a pointer can hover and the button is not pressed, + and while what the button opens is open. """ - return {_POINTER: {_HOVER: style}} + return {_POINTER: {_HOVER: style}, _OPEN: style} def _ring(color: str, offset: str) -> dict[str, Any]: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py new file mode 100644 index 00000000000..1d30729e000 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py @@ -0,0 +1,147 @@ +"""The look of a dialog: a native ``dialog`` over the page, and the panel in it.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.heading import HEADING +from reflex_components_ui.styles.text import TEXT + +_PADDING = "--dialog-content-padding" + +MOTION = "@media (prefers-reduced-motion: no-preference)" +OPEN = "[open]" +_EASING = "cubic-bezier(0.16, 1, 0.3, 1)" + +# What a dialog hands its panel, which comes in when the dialog opens and +# goes out before it closes: where it goes, and how long it takes. +SHOWN = "--rx-dialog-shown" +GONE = "--rx-dialog-gone" +DURATION = "--rx-dialog-duration" + +# The element around the parts of a dialog, which is nothing to the layout. +DIALOG_ROOT: ComponentStyles = {"base": {"display": "contents"}} + +# What a `dialog` is before a table draws it: nothing of the box the browser +# gives one. It stays in the top layer until what is inside has gone out. +SURFACE: dict[str, Any] = { + "margin": "0", + "padding": "0", + "border_width": "0", + "border_style": "none", + "background_color": "transparent", + "color": "inherit", + "max_width": "none", + "max_height": "none", + "outline_style": "none", + "::backdrop": {"background_color": "transparent"}, + "transition_property": "display, overlay", + "transition_duration": {"default": "0s", MOTION: f"var({DURATION})"}, + SHOWN: {"default": 0, OPEN: 1}, +} + +# The dialog itself covers the page, and scrolls a panel taller than it. +DIALOG: ComponentStyles = { + "base": unchecked({ + **SURFACE, + "position": "fixed", + "inset": "0", + "width": "100%", + "height": "100%", + "display": {"default": "none", OPEN: "flex"}, + "overflow": "auto", + GONE: {"default": "translateY(5px) scale(0.99)", OPEN: "none"}, + DURATION: {"default": "160ms", OPEN: "200ms"}, + "_before": { + "position": "fixed", + "content": "''", + "inset": "0", + "background_color": tokens.color.overlay, + "opacity": {"default": 0, OPEN: {"default": 1, "@starting-style": 0}}, + "transition_property": "opacity", + "transition_duration": {"default": "0s", MOTION: f"var({DURATION})"}, + "transition_timing_function": _EASING, + }, + }), + "parts": { + "pad": { + "base": { + "flex_grow": 1, + "margin": "auto", + "padding_top": tokens.space[6], + "padding_bottom": f"max({tokens.space[6]}, 6vh)", + "padding_left": tokens.space[4], + "padding_right": tokens.space[4], + }, + }, + }, +} + + +def _size(padding: str, radius: str) -> dict[str, Any]: + """Make the styles of a panel of one size. + + Args: + padding: The room around what the panel holds. + radius: The radius of its corners. + + Returns: + The styles. + """ + return {_PADDING: padding, "border_radius": radius} + + +DIALOG_CONTENT: ComponentStyles = { + "base": unchecked({ + "margin": "auto", + "width": "100%", + "max_width": "600px", + "z_index": 1, + "position": "relative", + "box_sizing": "border-box", + "overflow": "auto", + "--inset-padding-top": f"var({_PADDING})", + "--inset-padding-right": f"var({_PADDING})", + "--inset-padding-bottom": f"var({_PADDING})", + "--inset-padding-left": f"var({_PADDING})", + "padding": f"var({_PADDING})", + "background_color": tokens.color.panel_solid, + "box_shadow": tokens.shadow[6], + "outline_style": "none", + "opacity": { + "default": f"var({SHOWN})", + "@starting-style": 0, + }, + "transform": { + "default": f"var({GONE})", + "@starting-style": "translateY(5px) scale(0.97)", + }, + "transition_property": "opacity, transform", + "transition_duration": { + "default": "0s", + MOTION: f"calc(100ms + var({SHOWN}) * 100ms)", + }, + "transition_timing_function": _EASING, + }), + "variants": { + "size": { + "1": unchecked(_size(tokens.space[3], tokens.radius[4])), + "2": unchecked(_size(tokens.space[4], tokens.radius[4])), + "3": unchecked(_size(tokens.space[5], tokens.radius[5])), + "4": unchecked(_size(tokens.space[6], tokens.radius[5])), + }, + }, + "defaults": {"size": "3"}, +} + +# A heading of size 5 that keeps its distance from what is under it, and +# whose first line starts at the top of its box. +DIALOG_TITLE: ComponentStyles = { + **HEADING, + "base": unchecked({**HEADING["base"], "margin_bottom": tokens.space[3]}), + "defaults": {"size": "5", "trim": "start"}, +} + +DIALOG_DESCRIPTION: ComponentStyles = {**TEXT, "defaults": {"size": "3"}} diff --git a/pyi_hashes.json b/pyi_hashes.json index c68cc3cd0d2..1ea2d936577 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,7 +118,7 @@ "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": "3baaa214d298bb98db3eae02bb2911e4", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "7aa6a835933a94d1fde16396fdb82693", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "01d7eab0f935b7ada62ae306948f219a", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "61cffb40e8f047c944b54e51ac36cbc7", diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index a1ed1b25a59..dd14780dfff 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -847,6 +847,25 @@ def overlays(): default_value="plan", id="account", ), + # A dialog that starts open, and one for each row of a list. + rx.ui.dialog.root( + rx.ui.dialog.content( + rx.ui.dialog.title("Welcome"), + rx.ui.dialog.close(rx.ui.button("Start", id="start")), + id="welcome", + ), + default_open=True, + ), + rx.foreach( + ["ada", "bob"], + lambda name: rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.ui.button(name)), + rx.ui.dialog.content( + rx.ui.dialog.title("Edit ", name), + rx.ui.dialog.close(rx.ui.button("Done")), + ), + ), + ), rx.el.span(rx.cond(rx.State.is_hydrated, "ready", "loading"), id="ready"), ) @@ -1864,6 +1883,17 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): page.goto(ui_app.frontend_url.rstrip("/") + "/overlays") expect(page.locator("#ready")).to_have_text("ready") + # A dialog that starts open is over the page once the page is hydrated, + # and each dialog of a list is opened by its own trigger. + expect(page.get_by_role("dialog", name="Welcome")).to_be_visible() + page.locator("#start").click() + expect(page.locator("#welcome")).to_be_hidden() + page.get_by_role("button", name="bob").click() + expect(page.get_by_role("dialog")).to_have_text("Edit bobDone") + page.keyboard.press("Escape") + expect(page.get_by_role("dialog")).to_have_count(0) + expect(page.get_by_role("button", name="bob")).to_be_focused() + # The panel of the selected tab alone is shown, whatever display an app # gives the panels. first, second = page.locator("#first-panel"), page.locator("#second-panel") diff --git a/tests/units/reflex_components_ui/components/test_button.py b/tests/units/reflex_components_ui/components/test_button.py index 0fa84457ed3..a1e06dd06e6 100644 --- a/tests/units/reflex_components_ui/components/test_button.py +++ b/tests/units/reflex_components_ui/components/test_button.py @@ -69,7 +69,7 @@ def test_button_plain( component = rx.ui.button("Save") assert component.render() == { "name": '"button"', - "props": ["className:sx_6fb0976665_c"], + "props": ["className:sx_f2580dfc68_c"], "children": [{"contents": '"Save"'}], } assert declared_styles(component) == [ @@ -93,6 +93,7 @@ def test_button_plain( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + "[data-state='open']": "var(--accent-10)", ":active:not([data-state='open'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, @@ -187,7 +188,7 @@ def test_button_soft_with_a_color_and_a_radius( "name": '"button"', "props": [ ( - 'className:sx_2d7416ba7b_c + " " + reflexUIClasses_e201574881 + " " + ' + 'className:sx_357e435970_c + " " + reflexUIClasses_e201574881 + " " + ' "reflexUIClasses_4c7cd6a7ce" ) ], @@ -214,6 +215,7 @@ def test_button_soft_with_a_color_and_a_radius( "backgroundColor": { "default": "var(--accent-a3)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a4)"}, + "[data-state='open']": "var(--accent-a4)", ":active:not([data-state='open'])": "var(--accent-a5)", "[data-disabled]": "var(--gray-a3)", }, @@ -277,7 +279,7 @@ def test_button_ghost( component = rx.ui.button("Save", variant="ghost", size="3") assert component.render() == { "name": '"button"', - "props": ["className:sx_2251570250_c"], + "props": ["className:sx_8db288804d_c"], "children": [{"contents": '"Save"'}], } assert declared_styles(component) == [ @@ -301,6 +303,7 @@ def test_button_ghost( "backgroundColor": { "default": "transparent", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a3)"}, + "[data-state='open']": "var(--accent-a3)", ":active:not([data-state='open'])": "var(--accent-a4)", "[data-disabled]": "transparent", }, @@ -384,6 +387,7 @@ def test_button_classic_high_contrast( "@media (hover: hover)": { ":hover:not(:active)": "var(--accent-12)" }, + "[data-state='open']": "var(--accent-12)", ":active:not([data-state='open'], [data-disabled])": "inherit", "[data-disabled]": "var(--gray-a2)", }, @@ -402,6 +406,9 @@ def test_button_classic_high_contrast( "transparent, " "var(--white-a2))" }, + "[data-state='open']": "linear-gradient(var(--black-a5), " + "transparent, " + "var(--white-a2))", ":active:not([data-state='open'], [data-disabled])": "linear-gradient(var(--black-a5), " "transparent, " "var(--white-a3))", @@ -534,6 +541,14 @@ def test_button_classic_high_contrast( "saturate(1.3) " "brightness(1.14))" }, + "[data-state='open']": "var(--rx-if-light, " + "contrast(0.88) " + "saturate(1.1) " + "brightness(1.1)) " + "var(--rx-if-dark, " + "contrast(0.88) " + "saturate(1.3) " + "brightness(1.14))", }, "height": "var(--base-button-height)", "--rx-icon-opacity": "0.9", @@ -576,6 +591,7 @@ def test_button_responsive_size( "backgroundColor": { "default": "transparent", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a2)"}, + "[data-state='open']": "var(--accent-a2)", ":active:not([data-state='open'])": "var(--accent-a3)", "[data-disabled]": "transparent", }, @@ -663,7 +679,7 @@ def test_button_disabled( assert component.render() == { "name": '"button"', "props": [ - "className:sx_6fb0976665_c", + "className:sx_f2580dfc68_c", '"data-disabled":true', "disabled:true", 'type:"submit"', @@ -680,7 +696,7 @@ def test_button_loading( component = rx.ui.button("Save", loading=True, size="4") assert component.render() == { "name": '"button"', - "props": ["className:sx_e8602a468e_c", '"data-disabled":true', "disabled:true"], + "props": ["className:sx_33c6aced18_c", '"data-disabled":true', "disabled:true"], "children": [ { "name": '"span"', @@ -767,6 +783,7 @@ def test_button_loading( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + "[data-state='open']": "var(--accent-10)", ":active:not([data-state='open'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, @@ -903,8 +920,8 @@ def test_button_bound_to_state( "name": '"button"', "props": [ ( - 'className:sx_aec9f4943f_c + " " + ' - "(sx_aec9f4943f_0[reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_] " + 'className:sx_878a6e8128_c + " " + ' + "(sx_878a6e8128_0[reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_] " '?? "")' ), ( @@ -1035,7 +1052,7 @@ def test_button_as_child( assert component.render() == { "name": "ReactRouterLink", "props": [ - "className:sx_6fb0976665_c", + "className:sx_f2580dfc68_c", '"data-disabled":true', "disabled:true", 'to:"/docs"', diff --git a/tests/units/reflex_components_ui/components/test_dialog.py b/tests/units/reflex_components_ui/components/test_dialog.py new file mode 100644 index 00000000000..34a02a8ddf6 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_dialog.py @@ -0,0 +1,574 @@ +"""Tests for reflex_components_ui.components.dialog.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import _dialog +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the dialogs of each test from one.""" + monkeypatch.setattr(_dialog, "_ids", itertools.count(1)) + + +def test_dialog( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A dialog is a native dialog over the page, around the panel an app styles; its trigger and its close button are their children, which command it; its title and its description name it.""" + component = rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.el.button("Open", id="open")), + rx.ui.dialog.content( + rx.ui.dialog.title("Title"), + rx.ui.dialog.description("What it is about.", id="about"), + rx.ui.dialog.close(rx.el.button("Close")), + size="2", + max_width="400px", + id="panel", + ), + default_open=True, + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_71b84cd269_c", + '"data-rx-dialog-root":""', + "onClick:dialogClick", + ], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"rx-dialog-1"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + 'command:"show-modal"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + 'id:"open"', + "ref:ref_open", + ], + "children": [{"contents": '"Open"'}], + }, + { + "name": '"dialog"', + "props": [ + '"aria-describedby":"about"', + '"aria-labelledby":"rx-dialog-1-labelledby"', + "className:sx_bf687cb34b_c", + '"data-default-open":true', + '"data-rx-popup":""', + 'id:"rx-dialog-1"', + "onCancel:dialogEvent", + "onClose:dialogEvent", + "ref:((dialog) => dialogSync(dialog, null, null))", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_18e4ad36e3_c"], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_02cf547cd4_c", + 'id:"panel"', + "ref:ref_panel", + ], + "children": [ + { + "name": '"h1"', + "props": [ + "className:sx_29271ef72f_c", + 'id:"rx-dialog-1-labelledby"', + ], + "children": [{"contents": '"Title"'}], + }, + { + "name": '"p"', + "props": [ + "className:sx_9b5373509f_c", + 'id:"about"', + "ref:ref_about", + ], + "children": [ + {"contents": '"What it is about."'} + ], + }, + { + "name": '"button"', + "props": [ + 'command:"close"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-close":""', + ], + "children": [{"contents": '"Close"'}], + }, + ], + } + ], + } + ], + }, + ], + } + assert declared_styles(component) == [ + {"display": "contents"}, + {}, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::backdrop": "transparent", + "::before": "var(--color-overlay)", + }, + "color": "inherit", + "maxWidth": "none", + "maxHeight": "none", + "outlineStyle": "none", + "transitionProperty": { + "default": "display, overlay", + "::before": "opacity", + }, + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", + "::before": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", + }, + }, + "--rx-dialog-shown": {"default": 0, "[open]": 1}, + "position": {"default": "fixed", "::before": "fixed"}, + "top": {"default": "0", "::before": "0"}, + "right": {"default": "0", "::before": "0"}, + "bottom": {"default": "0", "::before": "0"}, + "left": {"default": "0", "::before": "0"}, + "width": "100%", + "height": "100%", + "display": {"default": "none", "[open]": "flex"}, + "overflowX": "auto", + "overflowY": "auto", + "--rx-dialog-gone": { + "default": "translateY(5px) scale(0.99)", + "[open]": "none", + }, + "--rx-dialog-duration": {"default": "160ms", "[open]": "200ms"}, + "content": {"::before": "''"}, + "opacity": { + "::before": { + "default": 0, + "[open]": {"default": 1, "@starting-style": 0}, + } + }, + "transitionTimingFunction": {"::before": "cubic-bezier(0.16, 1, 0.3, 1)"}, + }, + { + "flexGrow": 1, + "marginTop": "auto", + "marginRight": "auto", + "marginBottom": "auto", + "marginLeft": "auto", + "paddingTop": "var(--space-6)", + "paddingBottom": "max(var(--space-6), 6vh)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + }, + { + "marginTop": "auto", + "marginRight": "auto", + "marginBottom": "auto", + "marginLeft": "auto", + "width": "100%", + "maxWidth": "400px", + "zIndex": 1, + "position": "relative", + "boxSizing": "border-box", + "overflowX": "auto", + "overflowY": "auto", + "--inset-padding-top": "var(--dialog-content-padding)", + "--inset-padding-right": "var(--dialog-content-padding)", + "--inset-padding-bottom": "var(--dialog-content-padding)", + "--inset-padding-left": "var(--dialog-content-padding)", + "padding": "var(--dialog-content-padding)", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-6)", + "outlineStyle": "none", + "opacity": {"default": "var(--rx-dialog-shown)", "@starting-style": 0}, + "transform": { + "default": "var(--rx-dialog-gone)", + "@starting-style": "translateY(5px) scale(0.97)", + }, + "transitionProperty": "opacity, transform", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": "calc(100ms + var(--rx-dialog-shown) * 100ms)", + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "--dialog-content-padding": "var(--space-4)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + }, + { + "--leading-trim-start": "var(--heading-leading-trim-start)", + "--leading-trim-end": "var(--heading-leading-trim-end)", + "fontFamily": "var(--heading-font-family)", + "fontStyle": "var(--heading-font-style)", + "fontWeight": "var(--font-weight-bold)", + "lineHeight": "var(--line-height)", + "marginTop": "0", + "marginRight": "0", + "marginBottom": { + "default": "var(--space-3)", + "::before": "calc(var(--leading-trim-start, var(--default-leading-trim-start)) - var(--line-height, calc(1em * var(--default-line-height))) / 2)", + }, + "marginLeft": "0", + "fontSize": "calc(var(--font-size-5) * var(--heading-font-size-adjust))", + "--line-height": "var(--heading-line-height-5)", + "letterSpacing": "calc(var(--letter-spacing-5) + var(--heading-letter-spacing))", + "content": {"::before": "''", "::after": "none"}, + "display": {"::before": "table"}, + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-3)", + "--line-height": "var(--line-height-3)", + "--letter-spacing": "var(--letter-spacing-3)", + }, + {}, + ] + + +def test_dialog_in_a_dialog(ui_plugin: UIPlugin): + """A dialog inside a dialog is its own: each trigger commands its dialog, and a child that hears a press itself is put in a flex container.""" + component = rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.el.button("Open", on_click=rx.console_log("pressed"))), + rx.ui.dialog.content( + rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.el.button("Inner")), + rx.ui.dialog.content("Inside"), + ), + ), + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_71b84cd269_c", + '"data-rx-dialog-root":""', + "onClick:dialogClick", + ], + "children": [ + { + "name": '"div"', + "props": [ + '"aria-controls":"rx-dialog-2"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + "className:sx_78b49527aa_c", + 'command:"show-modal"', + 'commandfor:"rx-dialog-2"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + ], + "children": [ + { + "name": '"button"', + "props": [ + 'onClick:((_e) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("pressed"))), ["callback"] : null }), ({ })))], [_e], ({ }))))' + ], + "children": [{"contents": '"Open"'}], + } + ], + }, + { + "name": '"dialog"', + "props": [ + "className:sx_bf687cb34b_c", + '"data-rx-popup":""', + 'id:"rx-dialog-2"', + "onCancel:dialogEvent", + "onClose:dialogEvent", + "ref:((dialog) => dialogSync(dialog, null, null))", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_18e4ad36e3_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_41c452192b_c"], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_71b84cd269_c", + '"data-rx-dialog-root":""', + "onClick:dialogClick", + ], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"rx-dialog-1"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + 'command:"show-modal"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + ], + "children": [{"contents": '"Inner"'}], + }, + { + "name": '"dialog"', + "props": [ + "className:sx_bf687cb34b_c", + '"data-rx-popup":""', + 'id:"rx-dialog-1"', + "onCancel:dialogEvent", + "onClose:dialogEvent", + "ref:((dialog) => dialogSync(dialog, null, null))", + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_18e4ad36e3_c" + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_41c452192b_c" + ], + "children": [ + { + "contents": '"Inside"' + } + ], + } + ], + } + ], + }, + ], + } + ], + } + ], + } + ], + }, + ], + } + + +def test_dialog_parts_alone(ui_plugin: UIPlugin): + """The parts of a dialog outside one render without its name.""" + component = rx.el.div( + rx.ui.dialog.trigger(rx.el.button("Open")), + rx.ui.dialog.content( + rx.ui.dialog.title("Title"), rx.ui.dialog.description("About") + ), + rx.ui.dialog.close(rx.el.button("Close")), + ) + assert component.render() == { + "name": '"div"', + "props": [], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + ], + "children": [{"contents": '"Open"'}], + }, + { + "name": '"dialog"', + "props": [ + "className:sx_bf687cb34b_c", + '"data-rx-popup":""', + "onCancel:dialogEvent", + "onClose:dialogEvent", + "ref:((dialog) => dialogSync(dialog, null, null))", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_18e4ad36e3_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_41c452192b_c"], + "children": [ + { + "name": '"h1"', + "props": ["className:sx_29271ef72f_c"], + "children": [{"contents": '"Title"'}], + }, + { + "name": '"p"', + "props": ["className:sx_9b5373509f_c"], + "children": [{"contents": '"About"'}], + }, + ], + } + ], + } + ], + }, + { + "name": '"button"', + "props": ['"data-rx-dialog-close":""'], + "children": [{"contents": '"Close"'}], + }, + ], + } + + +class DialogState(rx.State): + """What a dialog is bound to.""" + + shown: bool = False + + @rx.event + def set_shown(self, shown: bool): + """Follow the dialog. + + Args: + shown: Whether it is open. + """ + self.shown = shown + + @rx.event + def note(self): + """Hear that something happened to the dialog.""" + + +def test_dialog_bound_to_state(ui_plugin: UIPlugin): + """A dialog bound to state hands its script its state and what it does when it is asked to open or close, and its trigger commands nothing.""" + name = DialogState.get_full_name() + component = rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.el.button("Open")), + rx.ui.dialog.content( + "x", + on_escape_key_down=DialogState.note, + on_interact_outside=DialogState.note, + ), + open=DialogState.shown, + on_open_change=DialogState.set_shown, + ) + rendered = component.render() + assert rendered["props"] == [ + "className:sx_71b84cd269_c", + '"data-rx-dialog-root":""', + "onClick:dialogClick", + ] + trigger, dialog = rendered["children"] + assert trigger["props"] == [ + '"aria-controls":"rx-dialog-1"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + ] + note = ( + f'((...args) => (addEvents([(ReflexEvent("{name}.note", ({{ }}), ' + "({ })))], args, ({ }))))" + ) + assert dialog["props"] == [ + "className:sx_bf687cb34b_c", + '"data-rx-popup":""', + 'id:"rx-dialog-1"', + "onCancel:dialogEvent", + "onClose:dialogEvent", + ( + f"ref:((dialog) => dialogSync(dialog, {DialogState.shown!s}, ({{ open: " + f'((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' + '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))), ' + f"escape: {note}, interact: {note} }})))" + ), + ] + + +def test_dialog_imports_its_script(ui_plugin: UIPlugin): + """A page with a dialog loads the script of a dialog, and no other.""" + component = rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.el.button("Open")), rx.ui.dialog.content("x") + ) + imports = component._get_all_imports() + assert { + module: names for module, names in imports.items() if "behaviors" in module + } == { + "$/reflex-ui/behaviors/dialog.js": [ + ImportVar(tag="dialogClick"), + ImportVar(tag="dialogSync"), + ImportVar(tag="dialogEvent"), + ], + } + + +@pytest.mark.parametrize( + ("create", "message"), + [ + ( + lambda: rx.ui.dialog.trigger("Open"), + ( + "rx.ui.dialog_trigger: it is rendered as its child, so it needs exactly " + "one child that is an element, such as a button." + ), + ), + ( + lambda: rx.ui.dialog.close(rx.el.button("a"), rx.el.button("b")), + ( + "rx.ui.dialog_close: it is rendered as its child, so it needs exactly " + "one child that is an element, such as a button." + ), + ), + ( + lambda: rx.ui.dialog.content(size="9"), # pyright: ignore[reportArgumentType] + 'rx.ui.dialog_content: unknown size "9". The values are "1", "2", "3", "4".', + ), + ], +) +def test_dialog_refuses_what_it_cannot_render( + ui_plugin: UIPlugin, create: Callable[[], Any], message: str +): + """A trigger without one element to render as, and a size a dialog does not have, fail with the name of the component.""" + with pytest.raises(StyleError) as error: + create() + assert str(error.value) == message diff --git a/tests/units/reflex_components_ui/components/test_form.py b/tests/units/reflex_components_ui/components/test_form.py index ee65ee67874..7f9855d6c15 100644 --- a/tests/units/reflex_components_ui/components/test_form.py +++ b/tests/units/reflex_components_ui/components/test_form.py @@ -452,7 +452,7 @@ def test_form_without_messages( {"name": '"span"', "props": [], "children": [{"contents": '"x"'}]}, { "name": '"button"', - "props": ["className:sx_6fb0976665_c", 'type:"submit"'], + "props": ["className:sx_f2580dfc68_c", 'type:"submit"'], "children": [{"contents": '"Send"'}], }, ], diff --git a/tests/units/reflex_components_ui/components/test_icon_button.py b/tests/units/reflex_components_ui/components/test_icon_button.py index 2a61ba10efb..6bb33f617a1 100644 --- a/tests/units/reflex_components_ui/components/test_icon_button.py +++ b/tests/units/reflex_components_ui/components/test_icon_button.py @@ -19,7 +19,7 @@ def test_icon_button_from_a_name( component = compiled(rx.ui.icon_button("plus")) assert component.render() == { "name": '"button"', - "props": ["className:sx_9b6dbd2f05_c"], + "props": ["className:sx_afda1d7c43_c"], "children": [{"name": "LucidePlus", "props": [], "children": []}], } assert declared_styles(component) == [ @@ -43,6 +43,7 @@ def test_icon_button_from_a_name( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + "[data-state='open']": "var(--accent-10)", ":active:not([data-state='open'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, @@ -127,7 +128,7 @@ def test_icon_button_size_sizes_the_icon( component = compiled(rx.ui.icon_button(rx.icon("trash"), size="3", variant="soft")) assert component.render() == { "name": '"button"', - "props": ["className:sx_76b6296e23_c"], + "props": ["className:sx_46971f9a00_c"], "children": [{"name": "LucideTrash", "props": ["size:36"], "children": []}], } assert declared_styles(component) == [ @@ -151,6 +152,7 @@ def test_icon_button_size_sizes_the_icon( "backgroundColor": { "default": "var(--accent-a3)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a4)"}, + "[data-state='open']": "var(--accent-a4)", ":active:not([data-state='open'])": "var(--accent-a5)", "[data-disabled]": "var(--gray-a3)", }, @@ -227,6 +229,7 @@ def test_icon_button_ghost( "backgroundColor": { "default": "transparent", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a3)"}, + "[data-state='open']": "var(--accent-a3)", ":active:not([data-state='open'])": "var(--accent-a4)", "[data-disabled]": "transparent", }, diff --git a/tests/units/reflex_components_ui/components/test_skeleton.py b/tests/units/reflex_components_ui/components/test_skeleton.py index 88219ebeb9b..e2e15cedfa9 100644 --- a/tests/units/reflex_components_ui/components/test_skeleton.py +++ b/tests/units/reflex_components_ui/components/test_skeleton.py @@ -152,7 +152,7 @@ def test_skeleton_as_its_child( "name": '"button"', "props": [ '"aria-hidden":true', - 'className:(sx_6fb0976665_c) + " " + sx_596747f37d_c', + 'className:(sx_f2580dfc68_c) + " " + sx_596747f37d_c', '"data-rx-skeleton":""', 'id:"save"', "inert:true", @@ -218,6 +218,7 @@ def test_skeleton_as_its_child( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + "[data-state='open']": "var(--accent-10)", ":active:not([data-state='open'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, @@ -307,7 +308,7 @@ def test_skeleton_not_loading( "children": [ { "name": '"button"', - "props": ["className:sx_6fb0976665_c"], + "props": ["className:sx_f2580dfc68_c"], "children": [{"contents": '"Save"'}], } ], @@ -333,6 +334,7 @@ def test_skeleton_not_loading( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, + "[data-state='open']": "var(--accent-10)", ":active:not([data-state='open'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index c675d098dd7..a9592fcdc43 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -132,6 +132,13 @@ def test_every_wave_is_in_the_namespace(): "data_list.label", "data_list.root", "data_list.value", + "dialog", + "dialog.close", + "dialog.content", + "dialog.description", + "dialog.root", + "dialog.title", + "dialog.trigger", "divider", "flex", "form", @@ -218,6 +225,7 @@ def test_every_wave_is_in_the_namespace(): "callout", "checkbox", "data_list", + "dialog", "form", "input", "list", From f0eb792c6711500b532b276893cbd1c96aeadc8e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 09:32:41 +0000 Subject: [PATCH 120/204] Add rx.ui.alert_dialog on the native dialog of rx.ui.dialog An alert dialog has the role of one, is not dismissed by a press beside its panel, and gives the focus to what cancels it when it opens. Its action and its cancel button close it as the close button of a dialog does. The types of the shared dialog code are settled. Claude-Session: https://claude.ai/code/session_014AwvTMWjpBRrG7rVgJBZHA --- .../js/src/behaviors/dialog.js | 4 + .../js/tests/behaviors/dialog.test.js | 3 + .../news/+wave4-overlays.feature.md | 2 +- .../parity/allowlist.toml | 24 ++ .../ui_parity/components/alert_dialog.py | 307 ++++++++++++++++++ .../parity/ui_parity/components/dialog.py | 2 +- .../src/reflex_components_ui/__init__.py | 1 + .../components/_dialog.py | 29 +- .../components/alert_dialog.py | 161 +++++++++ .../src/reflex_components_ui/styles/dialog.py | 2 +- pyi_hashes.json | 4 +- .../components/test_alert_dialog.py | 271 ++++++++++++++++ .../reflex_components_ui/test_api_parity.py | 8 + 13 files changed, 809 insertions(+), 9 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py create mode 100644 tests/units/reflex_components_ui/components/test_alert_dialog.py diff --git a/packages/reflex-components-ui/js/src/behaviors/dialog.js b/packages/reflex-components-ui/js/src/behaviors/dialog.js index baded861eb4..b84b7d59c45 100644 --- a/packages/reflex-components-ui/js/src/behaviors/dialog.js +++ b/packages/reflex-components-ui/js/src/behaviors/dialog.js @@ -45,6 +45,10 @@ function show(dialog) { // The browser scrolls to what it gives the focus: a tall dialog starts // at its top, as in Radix. dialog.scrollTop = 0; + // An alert dialog starts on what cancels it, wherever that is in it. + /** @type {HTMLElement | null} */ ( + dialog.querySelector("[data-rx-dialog-close=cancel]") + )?.focus({ preventScroll: true }); mark(dialog, true); dialogs.get(dialog)?.on?.openAutoFocus?.(); } diff --git a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js index 6599c51de2d..5819801d154 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js @@ -203,7 +203,10 @@ test("a press beside the panel and Escape dismiss the dialog, and say what did", test("a press beside the panel of an alert dialog does not dismiss it", () => { render('role="alertdialog"'); + const cancel = /** @type {HTMLElement} */ (document.getElementById("close")); + cancel.setAttribute("data-rx-dialog-close", "cancel"); press("open"); + expect(document.activeElement).toBe(cancel); press("pad"); press("dialog"); expect(dialog.open).toBe(true); diff --git a/packages/reflex-components-ui/news/+wave4-overlays.feature.md b/packages/reflex-components-ui/news/+wave4-overlays.feature.md index 6b8bf29d845..303c2da4b9e 100644 --- a/packages/reflex-components-ui/news/+wave4-overlays.feature.md +++ b/packages/reflex-components-ui/news/+wave4-overlays.feature.md @@ -1,3 +1,3 @@ -Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion` and `dialog`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog is a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. +Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog` and `alert_dialog`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog and an alert dialog are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. A button whose popup is open has the look Radix Themes gives it (`[data-state='open']`), which `rx.ui.button` did not have. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index d956d71e3b5..b8f856380ce 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -349,3 +349,27 @@ component = "dialog" step = "the dark appearance of a theme around a dialog reaches its panel" system = "rx" reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a dialog included. rx.ui.theme does, and a dialog declared inside a dark rx.ui.theme is dark: its panel, what it holds and what is drawn over the page behind it." + +[[look]] +component = "alert_dialog" +check = "style" +cells = "*@open" +properties = ["pointer-events"] +reason = "While it is open rx.alert_dialog takes the pointer off the rest of the page with a style on the body. rx.ui.alert_dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style." + +[[contract]] +component = "alert_dialog" +step = "what it holds is in the server render" +system = "rx" +reason = "rx.alert_dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.alert_dialog holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings." + +[[contract]] +component = "alert_dialog" +step = "opens and closes with JavaScript disabled" +system = "rx" +reason = "rx.alert_dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger, the action and the cancel button of rx.ui.alert_dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript." + +[[contract]] +component = "alert_dialog" +step = "Tab stays inside an open alert dialog" +reason = "rx.ui.alert_dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.alert_dialog keeps the focus from leaving the dialog at all." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py b/packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py new file mode 100644 index 00000000000..19a1e9db466 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py @@ -0,0 +1,307 @@ +"""The alert dialog: closed and open in every size, and what does not dismiss it.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import reflex as rx +from ui_parity.components.dialog import OPEN, OPENED, body +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import focused, wait_for_text + +SIZES = ["1", "2", "3", "4"] + + +def _alert(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create an alert dialog and the button that opens it. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the content. ``long`` asks for more than the + viewport has room for, and ``themed`` for a theme of another + accent and radius around the dialog. + + Returns: + The alert dialog. + """ + props = dict(props) + alert = namespace.alert_dialog + long, themed = props.pop("long", False), props.pop("themed", False) + shown = alert.root( + alert.trigger(namespace.button("Delete", color_scheme="red")), + alert.content(*body(namespace, alert, long), **props), + ) + if themed: + return namespace.theme(shown, accent_color="ruby", radius="full") + return shown + + +MATRIX = Matrix( + component="alert_dialog", + render=_alert, + sweep={ + "size": SIZES, + "long": [True], + "themed": [True], + "max_width": ["450px"], + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE, OPEN], + }, + groups=[ + {"size": SIZES, "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"long": [True], "size": ["1", "4"], "state": [OPEN]}, + {"themed": [True], "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"max_width": ["450px"], "state": [OPEN]}, + ], + # As wide as the page, one frame under another: a dialog covers the + # viewport, and is read in the frame the page is scrolled to. + stage=(1200, 700), + crop="stage", + target="button", + states={OPEN: OPENED}, + # Not held to zero. At a threshold of zero every cell but one is equal + # pixel for pixel: the ring of the focus on the trigger, which the + # browser anti-aliases by where the button is on the page, differs by 9 + # pixels of 840000. + tolerance=0.00002, +) + + +class AlertDialogState(rx.State): + """What the alert dialogs of the contract are bound to.""" + + shown: rx.Field[bool] = rx.field(False) + seen: rx.Field[list[str]] = rx.field(default_factory=list) + + @rx.event + def set_shown(self, value: bool): + """Follow the bound dialog. + + Args: + value: Whether it is open. + """ + self.shown = value + + @rx.event + def see_open(self, value: bool): + """Keep whether a dialog opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def see(self, what: str): + """Keep what happened to a dialog. + + Args: + what: The event. + """ + self.seen.append(what) + + @rx.event + def confirm(self): + """Close the bound dialog from the backend.""" + self.shown = False + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + An alert dialog that says what happens to it, whose action is + before what cancels it, and one bound to state. + """ + alert, button = namespace.alert_dialog, namespace.button + return namespace.box( + alert.root( + alert.trigger(button("Delete", id="open")), + alert.content( + alert.title("Delete the file"), + alert.description("It cannot be brought back."), + alert.action(button("Delete it", id="action")), + alert.cancel(button("Keep it", id="cancel")), + id="panel", + on_open_auto_focus=AlertDialogState.see("focus-in"), + on_close_auto_focus=AlertDialogState.see("focus-out"), + on_escape_key_down=AlertDialogState.see("escape"), + ), + on_open_change=AlertDialogState.see_open, + ), + alert.root( + alert.trigger(button("Bound", id="bound-open")), + alert.content( + alert.title("Bound"), + button("Confirm", id="confirm", on_click=AlertDialogState.confirm), + id="bound-panel", + ), + open=AlertDialogState.shown, + on_open_change=AlertDialogState.set_shown, + ), + rx.el.button("Show", id="show", on_click=AlertDialogState.set_shown(True)), + rx.el.span(AlertDialogState.seen.to_string(), id="seen"), + rx.el.span(AlertDialogState.shown.to_string(), id="shown"), + ) + + +CONTRACT = Contract(component="alert_dialog", render=_contract) + + +def _open(run: Run, trigger: str = "open", panel: str = "panel") -> None: + """Open an alert dialog from its trigger, and wait for its panel. + + Args: + run: The run, on a page. + trigger: The id of the trigger. + panel: The id of the panel. + """ + run.page.locator(f"#{trigger}").click() + run.page.locator(f"#{panel}").wait_for() + + +def _wait_for_closed(run: Run, panel: str = "panel") -> None: + """Wait until an alert dialog is closed. + + Args: + run: The run, on a page. + panel: The id of its panel. + """ + run.page.locator(f"#{panel}").wait_for(state="hidden") + + +def _wait_for_focus(run: Run, element: str) -> None: + """Wait until an element has the focus. + + Args: + run: The run, on a page. + element: Its id. + """ + run.page.wait_for_function("id => document.activeElement.id === id", arg=element) + + +@CONTRACT.step("its trigger is a button in the server render", on=SERVER) +def _server_render(run: Run) -> None: + trigger = run.server.element("open") + assert (trigger.tag, trigger.text, trigger.attributes["aria-haspopup"]) == ( + "button", + "Delete", + "dialog", + ) + + +@CONTRACT.step("what it holds is in the server render", on=SERVER) +def _server_content(run: Run) -> None: + assert run.server.element("panel").text == ( + "Delete the fileIt cannot be brought back.Delete itKeep it" + ) + + +@CONTRACT.step("opens and closes with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + assert not page.locator("#panel").is_visible() + page.locator("#open").click() + page.wait_for_timeout(300) + assert page.locator("#panel").is_visible() + page.locator("#cancel").click() + page.wait_for_timeout(300) + assert not page.locator("#panel").is_visible() + + +@CONTRACT.step("has the role, the name and the description of an alert dialog") +def _role(run: Run) -> None: + page = run.page + trigger = page.locator("#open") + assert trigger.get_attribute("aria-expanded") == "false" + _open(run) + assert trigger.get_attribute("aria-expanded") == "true" + assert trigger.get_attribute("data-state") == "open" + shown = page.get_by_role("alertdialog", name="Delete the file") + assert shown.count() == 1 + assert shown.evaluate( + "dialog => document.getElementById(dialog.getAttribute('aria-describedby'))" + ".textContent" + ) == ("It cannot be brought back.") + + +@CONTRACT.step("the focus moves to what cancels it, and back to its trigger") +def _focus(run: Run) -> None: + page = run.page + page.locator("#open").focus() + page.keyboard.press("Enter") + page.locator("#panel").wait_for() + _wait_for_focus(run, "cancel") + page.keyboard.press("Enter") + _wait_for_closed(run) + _wait_for_focus(run, "open") + page.keyboard.press("Space") + page.locator("#panel").wait_for() + page.locator("#action").click() + _wait_for_closed(run) + _wait_for_focus(run, "open") + + +@CONTRACT.step("Tab stays inside an open alert dialog") +def _tab(run: Run) -> None: + page = run.page + _open(run) + _wait_for_focus(run, "cancel") + stops = [] + for _ in range(4): + page.keyboard.press("Tab") + stops.append(focused(page)) + assert stops == ["action", "cancel", "action", "cancel"] + + +@CONTRACT.step("a press beside the panel does not close it, and Escape does") +def _outside(run: Run) -> None: + page = run.page + _open(run) + page.mouse.click(5, 5) + page.mouse.click(640, 700) + page.wait_for_timeout(300) + assert page.locator("#panel").is_visible() + page.keyboard.press("Escape") + _wait_for_closed(run) + wait_for_text(page, "seen", '["open","focus-in","escape","closed","focus-out"]') + + +@CONTRACT.step("its action and what cancels it close it, and say so") +def _close(run: Run) -> None: + page = run.page + _open(run) + page.locator("#action").click() + _wait_for_closed(run) + _open(run) + page.locator("#cancel").click() + _wait_for_closed(run) + wait_for_text( + page, + "seen", + '["open","focus-in","closed","focus-out","open","focus-in","closed","focus-out"]', + ) + + +@CONTRACT.step( + "an alert dialog bound to state follows it, and is closed from the backend" +) +def _bound(run: Run) -> None: + page = run.page + page.locator("#show").click() + page.locator("#bound-panel").wait_for() + wait_for_text(page, "shown", "true") + page.locator("#confirm").click() + _wait_for_closed(run, "bound-panel") + wait_for_text(page, "shown", "false") + _open(run, "bound-open", "bound-panel") + wait_for_text(page, "shown", "true") + page.keyboard.press("Escape") + _wait_for_closed(run, "bound-panel") + wait_for_text(page, "shown", "false") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py index 22d567eff24..cbb96f881c1 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py @@ -16,7 +16,7 @@ SIZES = ["1", "2", "3", "4"] OPEN = "open" # A dialog that is open, in either system. -SHOWN = "[role=dialog]:visible, dialog[open]" +SHOWN = "[role=dialog]:visible, [role=alertdialog]:visible, dialog[open]" def body(namespace: Any, kind: Any, long: bool = False) -> list[Any]: 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 d4537e28476..10fa71f88f9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -8,6 +8,7 @@ _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = { "components.accordion": ["accordion"], + "components.alert_dialog": ["alert_dialog"], "components.aspect_ratio": ["aspect_ratio"], "components.avatar": ["avatar"], "components.badge": ["badge"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py index 36a3de2a3db..11877042b14 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py @@ -176,6 +176,9 @@ class DialogSlot(DialogPart): # The attribute the script finds the part by. _mark: ClassVar[str] = "data-rx-dialog-close" + # What the attribute says of the part. + _marked: ClassVar[str] = "" + @classmethod def create(cls, *children: Any, **props: Any) -> Component: """Create a part that is rendered as its child. @@ -211,9 +214,10 @@ def _post_init(self, *args, **kwargs): or not isinstance(children[0], Component) or type(children[0]).render not in (Component.render, UIComponent.render) ): + name = self._display_name() # pyright: ignore[reportAttributeAccessIssue] msg = ( - f"{self._display_name()}: it is rendered as its child, so it " - "needs exactly one child that is an element, such as a button." + f"{name}: it is rendered as its child, so it needs exactly one " + "child that is an element, such as a button." ) raise StyleError(msg) self._as_child = True @@ -251,7 +255,11 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: Returns: The tag: its child, marked for the script of the dialog. """ - return super()._render(props).add_props(**{self._mark: "", **self._dialog}) + return ( + super() + ._render(props) + .add_props(**{self._mark: self._marked, **self._dialog}) + ) class DialogTriggerBase(DialogSlot): @@ -310,6 +318,17 @@ class DialogSurface(DialogPart): # The role of the dialog, when it is not the one the element has. _role: ClassVar[str | None] = None + def _post_init(self, *args, **kwargs): + """Initialize the dialog, as one that is not bound to state. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # Whether the dialog is open, when its state says. + self._open: Var | None = None + super()._post_init(*args, **kwargs) + def _join( self, root: DialogRootBase, @@ -348,7 +367,7 @@ def _get_vars( yield from super()._get_vars(include_children, ignore_ids) yield script("dialog", "dialogSync") yield script("dialog", "dialogEvent") - if getattr(self, "_open", None) is not None: + if self._open is not None: yield self._open def _render(self, props: dict[str, Any] | None = None) -> CommonTag: @@ -362,7 +381,7 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: follows the state it is bound to and says what happens to it. """ tag, on = handlers(super()._render(props), _EVENTS) - bound = LiteralVar.create(getattr(self, "_open", None)) + bound = LiteralVar.create(self._open) sync = script("dialog", "dialogSync") tag = tag.add_props(**{ "data-rx-popup": "", diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py new file mode 100644 index 00000000000..d4df779e4cb --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py @@ -0,0 +1,161 @@ +"""An alert dialog: a native modal ``dialog`` that waits for an answer.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._dialog import ( + DialogDescriptionBase, + DialogRootBase, + DialogSlot, + DialogSurface, + DialogTitleBase, + DialogTriggerBase, + surface, +) +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.dialog import DIALOG_CONTENT + +LiteralContentSize = Literal["1", "2", "3", "4"] + + +class AlertDialogRoot(DialogRootBase): + """Contains all the parts of the dialog.""" + + open: Var[bool] = field(doc="The controlled open state of the dialog.") + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + default_open: Var[bool] = field( + doc="The open state of the dialog when it is initially rendered. Use when you do not need to control its open state." + ) + + +class AlertDialogTrigger(DialogTriggerBase): + """Wraps the control that will open the dialog.""" + + +class AlertDialogOverlay(DialogSurface): + """The native dialog around the content of an alert dialog.""" + + # A press beside the panel of an alert dialog does not dismiss it. + _role: ClassVar[str | None] = "alertdialog" + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + on_open_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is opened." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + +_EVENTS = ("on_open_auto_focus", "on_close_auto_focus", "on_escape_key_down") + + +class AlertDialogContent(UIComponent, elements.Div): + """Contains the content of the dialog. This component is based on the div element.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = DIALOG_CONTENT + + size: Var[Responsive[LiteralContentSize]] = field(doc="The size of the content.") + + force_mount: Var[bool] = field(doc="Whether to force mount the content on open.") + + on_open_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is opened." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create an AlertDialogContent. + + Args: + *children: What the dialog holds. + **props: The properties of the component. Its styles are those + of the panel, and its events those of the dialog around it. + + Returns: + The native dialog, around the panel. + """ + events = {event: props.pop(event) for event in _EVENTS if event in props} + return surface(AlertDialogOverlay, super().create(*children, **props), events) + + def _exclude_props(self) -> list[str]: + """Keep the prop that is no attribute off the element. + + Returns: + The props read as styles, and whether the content stays + mounted: it always is. + """ + return [*super()._exclude_props(), "force_mount"] + + +class AlertDialogTitle(DialogTitleBase): + """An accessible title that is announced when the dialog is opened. + This part is based on the Heading component with a pre-defined font size and + leading trim on top. + """ + + +class AlertDialogDescription(DialogDescriptionBase): + """An optional accessible description that is announced when the dialog is opened. + This part is based on the Text component with a pre-defined font size. + """ + + +class AlertDialogAction(DialogSlot): + """Wraps the control that will close the dialog. This should be distinguished + visually from the Cancel control. + """ + + +class AlertDialogCancel(DialogSlot): + """Wraps the control that will close the dialog. This should be distinguished + visually from the Action control. + """ + + # The dialog gives the focus to what cancels it when it opens. + _marked: ClassVar[str] = "cancel" + + +class AlertDialog(ComponentNamespace): + """AlertDialog components namespace.""" + + root = staticmethod(AlertDialogRoot.create) + trigger = staticmethod(AlertDialogTrigger.create) + content = staticmethod(AlertDialogContent.create) + title = staticmethod(AlertDialogTitle.create) + description = staticmethod(AlertDialogDescription.create) + action = staticmethod(AlertDialogAction.create) + cancel = staticmethod(AlertDialogCancel.create) + + +alert_dialog = AlertDialog() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py index 1d30729e000..784adf76e6c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py @@ -140,7 +140,7 @@ def _size(padding: str, radius: str) -> dict[str, Any]: # whose first line starts at the top of its box. DIALOG_TITLE: ComponentStyles = { **HEADING, - "base": unchecked({**HEADING["base"], "margin_bottom": tokens.space[3]}), + "base": unchecked({**HEADING.get("base", {}), "margin_bottom": tokens.space[3]}), "defaults": {"size": "5", "trim": "start"}, } diff --git a/pyi_hashes.json b/pyi_hashes.json index 1ea2d936577..d82af94dae7 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": "3baaa214d298bb98db3eae02bb2911e4", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "01d7eab0f935b7ada62ae306948f219a", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "f47dd19f82d1136e9dc837397696f55a", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", + "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "0d7b27ab1cb51ac891a31ed97f2f5567", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "61cffb40e8f047c944b54e51ac36cbc7", "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", @@ -133,6 +134,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.pyi": "55446eddd45d81355eea0ada7370a6c3", "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.pyi": "63dc6c987c53e017e217e60f4686c4b9", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", + "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "28f5633fbda932ee598108e9d5a52e58", "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", diff --git a/tests/units/reflex_components_ui/components/test_alert_dialog.py b/tests/units/reflex_components_ui/components/test_alert_dialog.py new file mode 100644 index 00000000000..fb6c1cd05e0 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_alert_dialog.py @@ -0,0 +1,271 @@ +"""Tests for reflex_components_ui.components.alert_dialog.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.components import _dialog +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the dialogs of each test from one.""" + monkeypatch.setattr(_dialog, "_ids", itertools.count(1)) + + +def test_alert_dialog( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An alert dialog is a native dialog with the role of one, which a press beside its panel does not dismiss; what cancels it is marked, and takes the focus when the dialog opens.""" + component = rx.ui.alert_dialog.root( + rx.ui.alert_dialog.trigger(rx.el.button("Delete")), + rx.ui.alert_dialog.content( + rx.ui.alert_dialog.title("Delete the file"), + rx.ui.alert_dialog.description("It cannot be brought back."), + rx.ui.alert_dialog.action(rx.el.button("Delete it")), + rx.ui.alert_dialog.cancel(rx.el.button("Keep it")), + size="1", + force_mount=True, + on_escape_key_down=rx.console_log("escape"), + ), + on_open_change=rx.console_log, + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_71b84cd269_c", + '"data-rx-dialog-root":""', + "onClick:dialogClick", + ], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"rx-dialog-1"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + 'command:"show-modal"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + ], + "children": [{"contents": '"Delete"'}], + }, + { + "name": '"dialog"', + "props": [ + '"aria-describedby":"rx-dialog-1-describedby"', + '"aria-labelledby":"rx-dialog-1-labelledby"', + "className:sx_bf687cb34b_c", + '"data-rx-popup":""', + 'id:"rx-dialog-1"', + "onCancel:dialogEvent", + "onClose:dialogEvent", + 'ref:((dialog) => dialogSync(dialog, null, ({ open: ((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"](_ev_0))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))), escape: ((...args) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("escape"))), ["callback"] : null }), ({ })))], args, ({ })))) })))', + 'role:"alertdialog"', + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_18e4ad36e3_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_849936ac28_c"], + "children": [ + { + "name": '"h1"', + "props": [ + "className:sx_29271ef72f_c", + 'id:"rx-dialog-1-labelledby"', + ], + "children": [{"contents": '"Delete the file"'}], + }, + { + "name": '"p"', + "props": [ + "className:sx_9b5373509f_c", + 'id:"rx-dialog-1-describedby"', + ], + "children": [ + {"contents": '"It cannot be brought back."'} + ], + }, + { + "name": '"button"', + "props": [ + 'command:"close"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-close":""', + ], + "children": [{"contents": '"Delete it"'}], + }, + { + "name": '"button"', + "props": [ + 'command:"close"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-close":"cancel"', + ], + "children": [{"contents": '"Keep it"'}], + }, + ], + } + ], + } + ], + }, + ], + } + assert declared_styles(component) == [ + {"display": "contents"}, + {}, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": { + "default": "transparent", + "::backdrop": "transparent", + "::before": "var(--color-overlay)", + }, + "color": "inherit", + "maxWidth": "none", + "maxHeight": "none", + "outlineStyle": "none", + "transitionProperty": { + "default": "display, overlay", + "::before": "opacity", + }, + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", + "::before": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", + }, + }, + "--rx-dialog-shown": {"default": 0, "[open]": 1}, + "position": {"default": "fixed", "::before": "fixed"}, + "top": {"default": "0", "::before": "0"}, + "right": {"default": "0", "::before": "0"}, + "bottom": {"default": "0", "::before": "0"}, + "left": {"default": "0", "::before": "0"}, + "width": "100%", + "height": "100%", + "display": {"default": "none", "[open]": "flex"}, + "overflowX": "auto", + "overflowY": "auto", + "--rx-dialog-gone": { + "default": "translateY(5px) scale(0.99)", + "[open]": "none", + }, + "--rx-dialog-duration": {"default": "160ms", "[open]": "200ms"}, + "content": {"::before": "''"}, + "opacity": { + "::before": { + "default": 0, + "[open]": {"default": 1, "@starting-style": 0}, + } + }, + "transitionTimingFunction": {"::before": "cubic-bezier(0.16, 1, 0.3, 1)"}, + }, + { + "flexGrow": 1, + "marginTop": "auto", + "marginRight": "auto", + "marginBottom": "auto", + "marginLeft": "auto", + "paddingTop": "var(--space-6)", + "paddingBottom": "max(var(--space-6), 6vh)", + "paddingLeft": "var(--space-4)", + "paddingRight": "var(--space-4)", + }, + { + "marginTop": "auto", + "marginRight": "auto", + "marginBottom": "auto", + "marginLeft": "auto", + "width": "100%", + "maxWidth": "600px", + "zIndex": 1, + "position": "relative", + "boxSizing": "border-box", + "overflowX": "auto", + "overflowY": "auto", + "--inset-padding-top": "var(--dialog-content-padding)", + "--inset-padding-right": "var(--dialog-content-padding)", + "--inset-padding-bottom": "var(--dialog-content-padding)", + "--inset-padding-left": "var(--dialog-content-padding)", + "padding": "var(--dialog-content-padding)", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-6)", + "outlineStyle": "none", + "opacity": {"default": "var(--rx-dialog-shown)", "@starting-style": 0}, + "transform": { + "default": "var(--rx-dialog-gone)", + "@starting-style": "translateY(5px) scale(0.97)", + }, + "transitionProperty": "opacity, transform", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": "calc(100ms + var(--rx-dialog-shown) * 100ms)", + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "--dialog-content-padding": "var(--space-3)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + }, + { + "--leading-trim-start": "var(--heading-leading-trim-start)", + "--leading-trim-end": "var(--heading-leading-trim-end)", + "fontFamily": "var(--heading-font-family)", + "fontStyle": "var(--heading-font-style)", + "fontWeight": "var(--font-weight-bold)", + "lineHeight": "var(--line-height)", + "marginTop": "0", + "marginRight": "0", + "marginBottom": { + "default": "var(--space-3)", + "::before": "calc(var(--leading-trim-start, var(--default-leading-trim-start)) - var(--line-height, calc(1em * var(--default-line-height))) / 2)", + }, + "marginLeft": "0", + "fontSize": "calc(var(--font-size-5) * var(--heading-font-size-adjust))", + "--line-height": "var(--heading-line-height-5)", + "letterSpacing": "calc(var(--letter-spacing-5) + var(--heading-letter-spacing))", + "content": {"::before": "''", "::after": "none"}, + "display": {"::before": "table"}, + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-3)", + "--line-height": "var(--line-height-3)", + "--letter-spacing": "var(--letter-spacing-3)", + }, + {}, + {}, + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index a9592fcdc43..cbeec6c9e28 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -109,6 +109,13 @@ def test_every_wave_is_in_the_namespace(): "accordion.item", "accordion.root", "accordion.trigger", + "alert_dialog.action", + "alert_dialog.cancel", + "alert_dialog.content", + "alert_dialog.description", + "alert_dialog.root", + "alert_dialog.title", + "alert_dialog.trigger", "aspect_ratio", "avatar", "badge", @@ -222,6 +229,7 @@ def test_every_wave_is_in_the_namespace(): "namespace", [ "accordion", + "alert_dialog", "callout", "checkbox", "data_list", From 53b8c144d832c6ab1a179ea42047a1f5197d204b Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 09:59:33 +0000 Subject: [PATCH 121/204] Add rx.ui.drawer on the native dialog, sliding in from an edge The drawer is the dialog of rx.ui.dialog without a look of its own: the panel an app styles slides in from the edge the root names, the overlay is an element beside it that shows while the drawer is open, and the portal is nothing. A drawer that is not modal is shown beside the page, and one that is not dismissible is closed by its state alone, as in the library rx.drawer wraps. It is not dragged. A press beside the panel of a dialog inside a dialog no longer closes the outer one. Claude-Session: https://claude.ai/code/session_014AwvTMWjpBRrG7rVgJBZHA --- .../js/src/behaviors/dialog.js | 21 +- .../js/tests/behaviors/dialog.test.js | 25 +- .../news/+wave4-overlays.feature.md | 4 +- .../parity/allowlist.toml | 36 ++ .../parity/ui_parity/components/drawer.py | 527 +++++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/_dialog.py | 21 +- .../components/alert_dialog.py | 4 +- .../reflex_components_ui/components/drawer.py | 544 ++++++++++++++++++ .../src/reflex_components_ui/styles/drawer.py | 170 ++++++ pyi_hashes.json | 3 +- .../components/test_alert_dialog.py | 10 +- .../components/test_dialog.py | 18 +- .../components/test_drawer.py | 410 +++++++++++++ .../reflex_components_ui/test_api_parity.py | 11 + 15 files changed, 1785 insertions(+), 20 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/drawer.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py create mode 100644 tests/units/reflex_components_ui/components/test_drawer.py diff --git a/packages/reflex-components-ui/js/src/behaviors/dialog.js b/packages/reflex-components-ui/js/src/behaviors/dialog.js index b84b7d59c45..39f4ab5e9bb 100644 --- a/packages/reflex-components-ui/js/src/behaviors/dialog.js +++ b/packages/reflex-components-ui/js/src/behaviors/dialog.js @@ -41,7 +41,9 @@ function mark(dialog, open) { * @returns {void} */ function show(dialog) { - dialog.showModal(); + // A drawer that is not modal leaves the page as it is. + if (dialog.dataset.modal === "false") dialog.show(); + else dialog.showModal(); // The browser scrolls to what it gives the focus: a tall dialog starts // at its top, as in Radix. dialog.scrollTop = 0; @@ -59,12 +61,17 @@ function show(dialog) { * * @param {HTMLDialogElement} dialog The dialog. * @param {boolean} open Whether to open it. - * @param {...("escape" | "outside" | "interact")} why What dismissed it. + * @param {...("close" | "escape" | "outside" | "interact")} why What asked + * to close it: its button, Escape, or a press beside its panel. * @returns {void} */ function ask(dialog, open, ...why) { const { on, bound } = dialogs.get(dialog) ?? {}; - for (const name of why) on?.[name]?.(); + // An alert dialog keeps a press beside its panel from closing it, and + // a drawer that is not dismissible everything but its state. + const { rxKeep } = dialog.dataset; + if (why[0] && (rxKeep === "all" || rxKeep === why[0])) return; + for (const name of why) if (name !== "close") on?.[name]?.(); if (bound || open) on?.open?.(open); if (bound) return; if (open) show(dialog); @@ -111,10 +118,12 @@ export function dialogClick(event) { if (part?.closest(ROOT) === root) { // The script does what the command of a button asks the browser for. event.preventDefault(); - ask(dialog, part.hasAttribute("data-rx-dialog-trigger")); + if (part.hasAttribute("data-rx-dialog-trigger")) ask(dialog, true); + else ask(dialog, false, "close"); } else if ( - (target === dialog || target.parentElement === dialog) && - dialog.role !== "alertdialog" + target === dialog || + (target.parentElement === dialog && + target.hasAttribute("data-rx-dialog-pad")) ) ask(dialog, false, "outside", "interact"); } diff --git a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js index 5819801d154..5c3ab179190 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js @@ -40,12 +40,12 @@ function render(attributes = "") {
-
+
-
+
@@ -202,7 +202,7 @@ test("a press beside the panel and Escape dismiss the dialog, and say what did", }); test("a press beside the panel of an alert dialog does not dismiss it", () => { - render('role="alertdialog"'); + render('role="alertdialog" data-rx-keep="outside"'); const cancel = /** @type {HTMLElement} */ (document.getElementById("close")); cancel.setAttribute("data-rx-dialog-close", "cancel"); press("open"); @@ -241,6 +241,25 @@ test("a dialog bound to state says what is asked of it, and shows its state", () ]); }); +test("a drawer that is not dismissible stays until its state says, and one that is not modal is shown beside the page", () => { + /** @type {string[]} */ + const shown = []; + HTMLDialogElement.prototype.show = function () { + shown.push(this.id); + this.open = true; + }; + render('data-rx-keep="all" data-modal="false"'); + const { on, seen } = handlers(); + dialogSync(dialog, null, on); + press("open"); + expect(shown).toEqual(["dialog"]); + expect(escape()).toBe(true); + press("dialog"); + press("close"); + expect(dialog.open).toBe(true); + expect(seen).toEqual(["open:true", "openAutoFocus"]); +}); + test("a dialog that starts open opens once", () => { render('data-default-open="true"'); const { on, seen } = handlers(); diff --git a/packages/reflex-components-ui/news/+wave4-overlays.feature.md b/packages/reflex-components-ui/news/+wave4-overlays.feature.md index 303c2da4b9e..5519d99e583 100644 --- a/packages/reflex-components-ui/news/+wave4-overlays.feature.md +++ b/packages/reflex-components-ui/news/+wave4-overlays.feature.md @@ -1,3 +1,5 @@ -Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog` and `alert_dialog`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog and an alert dialog are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. +Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog`, `alert_dialog` and `drawer`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog, an alert dialog and a drawer are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. A button whose popup is open has the look Radix Themes gives it (`[data-state='open']`), which `rx.ui.button` did not have. + +`rx.ui.drawer` slides in from an edge of the page and is closed by Escape, by a press beside its panel and by its close button. It is not dragged, so `snap_points` and the other props that describe the drag of `rx.drawer` do nothing. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index b8f856380ce..3228d3a18d2 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -373,3 +373,39 @@ reason = "rx.alert_dialog is opened by JavaScript: until it has run, a press on component = "alert_dialog" step = "Tab stays inside an open alert dialog" reason = "rx.ui.alert_dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.alert_dialog keeps the focus from leaving the dialog at all." + +[[look]] +component = "drawer" +check = "style" +cells = "*@open" +properties = ["pointer-events"] +reason = "While it is open rx.drawer takes the pointer off the rest of the page with a style on the body. rx.ui.drawer is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style." + +[[contract]] +component = "drawer" +step = "what it holds is in the server render" +system = "rx" +reason = "rx.drawer renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.drawer holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings." + +[[contract]] +component = "drawer" +step = "opens and closes with JavaScript disabled" +system = "rx" +reason = "rx.drawer is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.drawer are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript." + +[[contract]] +component = "drawer" +step = "the focus moves into the drawer, and back to its trigger" +system = "rx" +reason = "rx.drawer leaves the focus on its trigger while the drawer is open, so the keyboard and a screen reader start behind it. rx.ui.drawer is a native modal dialog: the focus moves to the first control inside it, and back to the trigger when it closes." + +[[contract]] +component = "drawer" +step = "Tab does not reach the page behind an open drawer" +system = "rx" +reason = "With rx.drawer open, Tab goes on through the page behind it. rx.ui.drawer is a native modal dialog: the page behind it is inert, and Tab moves through the drawer and the browser's own controls." + +[[contract]] +component = "drawer" +step = "is dragged out of the page by its panel" +reason = "rx.ui.drawer is not dragged: it is closed by Escape, by a press beside its panel and by its close button, and `snap_points`, `fade_from_index`, `handle_only`, `close_threshold`, `scroll_lock_timeout`, `prevent_scroll_restoration` and `should_scale_background`, which all describe the drag of rx.drawer, have nothing to say. The handle is drawn and does nothing." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/drawer.py b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py new file mode 100644 index 00000000000..0bd7d5b330a --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py @@ -0,0 +1,527 @@ +"""The drawer: closed and open from each edge of the page, and how it is dismissed.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.components.dialog import OPEN, close_dialog, open_dialog +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import wait_for_text + +DIRECTIONS = ["bottom", "top", "left", "right"] + +# Where an app puts the panel of a drawer from each edge: the styles of the +# content, over the ones that stretch it over the page. +PLACES: dict[str, dict[str, str]] = { + "bottom": {"top": "auto", "height": "40%"}, + "top": {"bottom": "auto", "height": "40%"}, + "left": {"right": "auto", "width": "20em"}, + "right": {"left": "auto", "width": "20em"}, +} + + +def _panel(namespace: Any, direction: str, handle: bool = False, **props: Any) -> Any: + """Create the content of a drawer from an edge. + + Args: + namespace: ``rx`` or ``rx.ui``. + direction: The edge it comes from. + handle: Whether it has a handle. + **props: Further props of the content. + + Returns: + The content: a title, a description and the button that closes it. + """ + drawer = namespace.drawer + return drawer.content( + namespace.flex( + *([drawer.handle()] if handle else []), + drawer.title("Settings"), + drawer.description("What the drawer is about."), + drawer.close(namespace.button("Close")), + direction="column", + spacing="3", + width="100%", + ), + padding="2em", + background_color=rx.color("gray", 2), + **PLACES[direction], + **props, + ) + + +def _drawer(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a drawer and the button that opens it. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the root. ``handle`` asks for a handle in the + drawer, ``overlay`` says whether it has an overlay, and + ``inside`` puts the overlay in the portal, before the content. + + Returns: + The drawer. + """ + props = dict(props) + drawer = namespace.drawer + handle, overlay = props.pop("handle", False), props.pop("overlay", True) + inside = props.pop("inside", False) + content = _panel(namespace, props.get("direction", "bottom"), handle) + shade = [drawer.overlay()] if overlay else [] + return drawer.root( + drawer.trigger(namespace.button("Open")), + *([] if inside else shade), + drawer.portal(*(shade if inside else []), content), + **props, + ) + + +def _close(page: Page, target: Locator, point: Point) -> None: + """Close the open drawer, and wait until nothing of it is left to happen. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + close_dialog(page, target, point) + if not target.evaluate("trigger => trigger.hasAttribute('data-rx-dialog-trigger')"): + # The drawer of Radix gives the page its scroll position back some + # time after it has closed, which would move the page under the + # next cell. + page.wait_for_timeout(SETTLED) + + +# How long after it has closed the drawer of Radix still moves the page, in +# milliseconds. +SETTLED = 700 + +MATRIX = Matrix( + component="drawer", + render=_drawer, + base={"direction": "bottom"}, + sweep={ + "direction": DIRECTIONS, + "handle": [True], + "overlay": [False], + "inside": [True], + "modal": [False], + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE, OPEN], + }, + groups=[ + {"direction": DIRECTIONS, "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"direction": DIRECTIONS, "handle": [True], "state": [OPEN]}, + {"overlay": [False], "state": [OPEN]}, + {"inside": [True], "state": [OPEN]}, + ], + # As wide as the page, one frame under another: a drawer covers the + # viewport, and is read in the frame the page is scrolled to. + stage=(1200, 700), + crop="stage", + target="button", + states={ + OPEN: State(enter=open_dialog, leave=_close, matches="[data-state='open']") + }, + # Not held to zero. At a threshold of zero every cell but one is equal + # pixel for pixel: the ring of the focus on the trigger, which the + # browser anti-aliases by where the button is on the page, differs by 9 + # pixels of 840000. + tolerance=0.00002, +) + + +class DrawerState(rx.State): + """What the drawers of the contract are bound to.""" + + shown: rx.Field[bool] = rx.field(False) + kept: rx.Field[bool] = rx.field(False) + seen: rx.Field[list[str]] = rx.field(default_factory=list) + clicks: rx.Field[int] = rx.field(0) + + @rx.event + def set_shown(self, value: bool): + """Follow the bound drawer. + + Args: + value: Whether it is open. + """ + self.shown = value + + @rx.event + def set_kept(self, value: bool): + """Follow the drawer that is not dismissible. + + Args: + value: Whether it is open. + """ + self.kept = value + + @rx.event + def see_open(self, value: bool): + """Keep whether a drawer opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def see_moved(self, value: bool): + """Keep that a drawer has slid in or out. + + Args: + value: Whether it is open. + """ + self.seen.append("in" if value else "out") + + @rx.event + def see(self, what: str): + """Keep what happened to a drawer. + + Args: + what: The event. + """ + self.seen.append(what) + + @rx.event + def save(self): + """Close the bound drawer from the backend.""" + self.shown = False + + @rx.event + def click(self): + """Count a click on the button beside the drawers.""" + self.clicks += 1 + + +def _one(namespace: Any, name: str, direction: str = "bottom", **props: Any) -> Any: + """Create a drawer whose parts are named after it. + + Args: + namespace: ``rx`` or ``rx.ui``. + name: What the ids of its trigger, its panel and its close button + start with. + direction: The edge it comes from. + **props: The props of the root. ``content`` holds the ones of the + content, and ``field`` the ones of the input inside it. + + Returns: + The drawer. + """ + drawer = namespace.drawer + content, field = props.pop("content", {}), props.pop("field", {}) + return drawer.root( + drawer.trigger(namespace.button(name, id=f"{name}-open")), + drawer.overlay(), + drawer.portal( + drawer.content( + drawer.title(f"Drawer {name}"), + drawer.description("What the drawer is about."), + rx.el.input(id=f"{name}-input", **field), + drawer.close(namespace.button("Close", id=f"{name}-close")), + id=f"{name}-panel", + background_color="white", + padding="1em", + **PLACES[direction], + **content, + ) + ), + direction=direction, + **props, + ) + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + A drawer from each edge, one that says what happens to it, one that + is not dismissible, one that is not modal and one bound to state. + """ + return namespace.box( + _one( + namespace, + "plain", + on_open_change=DrawerState.see_open, + on_animation_end=DrawerState.see_moved, + content={ + "on_open_auto_focus": DrawerState.see("focus-in"), + "on_close_auto_focus": DrawerState.see("focus-out"), + "on_escape_key_down": DrawerState.see("escape"), + "on_pointer_down_outside": DrawerState.see("outside"), + "on_interact_outside": DrawerState.see("interact"), + }, + ), + *(_one(namespace, side, side) for side in ("top", "left", "right")), + _one( + namespace, + "kept", + dismissible=False, + open=DrawerState.kept, + on_open_change=DrawerState.set_kept, + field={"on_click": DrawerState.set_kept(False)}, + ), + _one(namespace, "beside", modal=False), + _one( + namespace, + "bound", + open=DrawerState.shown, + on_open_change=DrawerState.set_shown, + content={"on_click": DrawerState.save}, + ), + rx.el.button("Show", id="show", on_click=DrawerState.set_shown(True)), + rx.el.button("Behind", id="behind", on_click=DrawerState.click), + rx.el.span(DrawerState.seen.to_string(), id="seen"), + rx.el.span(DrawerState.shown.to_string(), id="shown"), + rx.el.span(DrawerState.kept.to_string(), id="kept"), + rx.el.span(DrawerState.clicks.to_string(), id="clicks"), + ) + + +CONTRACT = Contract(component="drawer", render=_contract) + +# How long a drawer takes to slide in or out, and some more, in milliseconds. +MOVED = 700 + + +def _open(run: Run, name: str) -> None: + """Open a drawer from its trigger, and wait until it has slid in. + + Args: + run: The run, on a page. + name: What the ids of its parts start with. + """ + run.page.locator(f"#{name}-open").click() + run.page.locator(f"#{name}-panel").wait_for() + run.page.wait_for_timeout(MOVED) + + +def _wait_for_closed(run: Run, name: str) -> None: + """Wait until a drawer is closed. + + Args: + run: The run, on a page. + name: What the ids of its parts start with. + """ + run.page.locator(f"#{name}-panel").wait_for(state="hidden") + + +def _wait_for_focus(run: Run, element: str) -> None: + """Wait until an element has the focus. + + Args: + run: The run, on a page. + element: Its id. + """ + run.page.wait_for_function("id => document.activeElement.id === id", arg=element) + + +@CONTRACT.step("its trigger is a button in the server render", on=SERVER) +def _server_render(run: Run) -> None: + trigger = run.server.element("plain-open") + assert (trigger.tag, trigger.text, trigger.attributes["aria-haspopup"]) == ( + "button", + "plain", + "dialog", + ) + + +@CONTRACT.step("what it holds is in the server render", on=SERVER) +def _server_content(run: Run) -> None: + assert run.server.element("plain-panel").text == ( + "Drawer plainWhat the drawer is about.Close" + ) + + +@CONTRACT.step("opens and closes with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + assert not page.locator("#plain-panel").is_visible() + page.locator("#plain-open").click() + page.wait_for_timeout(MOVED) + assert page.locator("#plain-panel").is_visible() + page.locator("#plain-close").click() + page.wait_for_timeout(MOVED) + assert not page.locator("#plain-panel").is_visible() + + +@CONTRACT.step("has the role, the name and the description of a dialog") +def _role(run: Run) -> None: + page = run.page + trigger = page.locator("#plain-open") + assert trigger.get_attribute("aria-expanded") == "false" + _open(run, "plain") + assert trigger.get_attribute("aria-expanded") == "true" + assert trigger.get_attribute("data-state") == "open" + shown = page.get_by_role("dialog", name="Drawer plain") + assert shown.count() == 1 + assert shown.evaluate( + "dialog => document.getElementById(dialog.getAttribute('aria-describedby'))" + ".textContent" + ) == ("What the drawer is about.") + + +@CONTRACT.step("slides in from each edge of the page, and stops there") +def _edges(run: Run) -> None: + page = run.page + edges = {} + for side in ("plain", "top", "left", "right"): + _open(run, side) + box = page.locator(f"#{side}-panel").bounding_box() + assert box is not None + edges[side] = [ + round(box["x"]), + round(box["y"]), + round(box["x"] + box["width"]), + round(box["y"] + box["height"]), + ] + page.keyboard.press("Escape") + _wait_for_closed(run, side) + assert edges == { + "plain": [0, 432, 1280, 720], + "top": [0, 0, 1280, 288], + "left": [0, 0, 320, 720], + "right": [960, 0, 1280, 720], + } + + +@CONTRACT.step("the focus moves into the drawer, and back to its trigger") +def _focus(run: Run) -> None: + page = run.page + page.locator("#plain-open").focus() + page.keyboard.press("Enter") + page.locator("#plain-panel").wait_for() + page.wait_for_function( + "document.getElementById('plain-panel').contains(document.activeElement)" + ) + page.wait_for_timeout(MOVED) + page.keyboard.press("Escape") + _wait_for_closed(run, "plain") + _wait_for_focus(run, "plain-open") + + +@CONTRACT.step("Tab does not reach the page behind an open drawer") +def _tab(run: Run) -> None: + page = run.page + _open(run, "plain") + behind = [] + for _ in range(6): + page.keyboard.press("Tab") + behind.append( + page.evaluate( + "document.activeElement !== document.body" + " && !document.getElementById('plain-panel')" + ".contains(document.activeElement)" + ) + ) + assert behind == [False] * 6 + + +@CONTRACT.step("Escape, a press beside the panel and its button close it, and say so") +def _dismiss(run: Run) -> None: + page = run.page + _open(run, "plain") + wait_for_text(page, "seen", '["open","focus-in","in"]') + page.keyboard.press("Escape") + _wait_for_closed(run, "plain") + wait_for_text( + page, "seen", '["open","focus-in","in","escape","closed","focus-out","out"]' + ) + _open(run, "top") + page.mouse.click(640, 600) + _wait_for_closed(run, "top") + _open(run, "top") + page.locator("#top-close").click() + _wait_for_closed(run, "top") + + +@CONTRACT.step("says that a press beside the panel dismissed it") +def _events_outside(run: Run) -> None: + page = run.page + _open(run, "plain") + page.mouse.click(640, 100) + _wait_for_closed(run, "plain") + wait_for_text( + page, + "seen", + '["open","focus-in","in","outside","interact","closed","focus-out","out"]', + ) + + +@CONTRACT.step("the page behind an open drawer takes no click") +def _modal(run: Run) -> None: + page = run.page + box = page.locator("#behind").bounding_box() + assert box is not None + _open(run, "left") + page.mouse.click(box["x"] + box["width"] / 2 + 400, box["y"] + box["height"] / 2) + _wait_for_closed(run, "left") + page.wait_for_timeout(300) + assert page.locator("#clicks").text_content() == "0" + + +@CONTRACT.step("a drawer that is not dismissible is closed by its state alone") +def _kept(run: Run) -> None: + page = run.page + _open(run, "kept") + wait_for_text(page, "kept", "true") + page.keyboard.press("Escape") + page.mouse.click(640, 100) + page.locator("#kept-close").click() + page.wait_for_timeout(MOVED) + assert page.locator("#kept-panel").is_visible() + assert page.locator("#kept").text_content() == "true" + page.locator("#kept-input").click() + _wait_for_closed(run, "kept") + wait_for_text(page, "kept", "false") + + +@CONTRACT.step("a drawer that is not modal leaves the page beside it as it is") +def _beside(run: Run) -> None: + page = run.page + _open(run, "beside") + page.locator("#behind").click() + wait_for_text(page, "clicks", "1") + assert page.locator("#beside-panel").is_visible() + page.locator("#beside-close").click() + _wait_for_closed(run, "beside") + + +@CONTRACT.step("a drawer bound to state follows it, and is closed from the backend") +def _bound(run: Run) -> None: + page = run.page + page.locator("#show").click() + page.locator("#bound-panel").wait_for() + wait_for_text(page, "shown", "true") + page.wait_for_timeout(MOVED) + page.locator("#bound-panel").click(position={"x": 400, "y": 10}) + _wait_for_closed(run, "bound") + wait_for_text(page, "shown", "false") + _open(run, "bound") + wait_for_text(page, "shown", "true") + page.keyboard.press("Escape") + _wait_for_closed(run, "bound") + wait_for_text(page, "shown", "false") + + +@CONTRACT.step("is dragged out of the page by its panel") +def _drag(run: Run) -> None: + page = run.page + _open(run, "plain") + page.mouse.move(640, 450) + page.mouse.down() + for y in range(460, 700, 20): + page.mouse.move(640, y) + page.mouse.up() + _wait_for_closed(run, "plain") 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 10fa71f88f9..542d73615dc 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -20,6 +20,7 @@ "components.checkbox_group": ["checkbox_group"], "components.data_list": ["data_list"], "components.dialog": ["dialog"], + "components.drawer": ["drawer"], "components.form": ["form"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py index 11877042b14..2752841a259 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py @@ -208,6 +208,12 @@ def _post_init(self, *args, **kwargs): an element. """ super()._post_init(*args, **kwargs) + if "as_child" in self.get_fields(): + # The part says itself whether it is its child, and is a button + # around its children otherwise. + if not self._as_child: + self.tag = "button" + return children = self.children if ( len(children) != 1 @@ -318,6 +324,10 @@ class DialogSurface(DialogPart): # The role of the dialog, when it is not the one the element has. _role: ClassVar[str | None] = None + # What does not dismiss the dialog: ``outside`` for a press beside its + # panel, ``all`` for that and Escape. + _keeps: ClassVar[str | None] = None + def _post_init(self, *args, **kwargs): """Initialize the dialog, as one that is not bound to state. @@ -386,6 +396,7 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: tag = tag.add_props(**{ "data-rx-popup": "", "role": self._role, + "data-rx-keep": self._keeps, **self._dialog, # Called whenever the page renders: a dialog bound to state # takes whether it is open from there. @@ -414,7 +425,15 @@ def surface( Returns: The dialog: the room around the panel is what scrolls a tall one. """ - return kind.create(Part.create(content, part="pad", tag="div"), **events) + return kind.create( + Part.create( + content, + part="pad", + tag="div", + custom_attrs={"data-rx-dialog-pad": ""}, + ), + **events, + ) class DialogTitleBase(DialogPart): diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py index d4df779e4cb..f59ca7d692d 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py @@ -47,9 +47,11 @@ class AlertDialogTrigger(DialogTriggerBase): class AlertDialogOverlay(DialogSurface): """The native dialog around the content of an alert dialog.""" - # A press beside the panel of an alert dialog does not dismiss it. _role: ClassVar[str | None] = "alertdialog" + # A press beside the panel of an alert dialog does not dismiss it. + _keeps: ClassVar[str | None] = "outside" + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( doc="Fired when the open state changes." ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py new file mode 100644 index 00000000000..20938fb055b --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py @@ -0,0 +1,544 @@ +"""A drawer: a native ``dialog`` whose panel slides in from an edge of the page.""" + +from __future__ import annotations + +from collections.abc import Iterator, Sequence +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_core.base.fragment import Fragment + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.components._dialog import ( + DialogPart, + DialogRootBase, + DialogSlot, + DialogSurface, +) +from reflex_components_ui.components._group import choose, descendants, literal +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.drawer import ( + DRAWER, + DRAWER_CONTENT, + DRAWER_DESCRIPTION, + DRAWER_HANDLE, + DRAWER_OVERLAY, + DRAWER_ROOT, + DRAWER_TITLE, +) + +LiteralDirectionType = Literal["top", "bottom", "left", "right"] + +_AS_CHILD_DOC = "Change the default rendered element for the one passed as a child." + + +def _is_off(flag: Var | None) -> Var | bool: + """Say whether a flag that is on unless it says otherwise is off. + + Args: + flag: The flag, or None when it is left out. + + Returns: + Whether it is off: a bool when it is known while compiling. + """ + if flag is None: + return False + known = literal(flag) + if not isinstance(known, Var): + return known is False + return Var( + f"({known!s} === false)", _var_type=bool, _var_data=known._get_all_var_data() + ) + + +class DrawerRoot(DialogRootBase): + """The Root component of a Drawer, contains all parts of a drawer.""" + + styles: ClassVar[ComponentStyles] = DRAWER_ROOT + + as_child: Var[bool] = field(doc=_AS_CHILD_DOC) + + default_open: Var[bool] = field( + doc="The open state of the drawer when it is initially rendered. Use when you do not need to control its open state." + ) + + open: Var[bool] = field(doc="Whether the drawer is open or not.") + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fires when the drawer is opened or closed." + ) + + modal: Var[bool] = field( + doc="When `False`, it allows interaction with elements outside of the drawer without closing it. Defaults to `True`." + ) + + direction: Var[LiteralDirectionType] = field( + doc='Direction of the drawer. This adjusts the animations and the drag direction. Defaults to `"bottom"`' + ) + + on_animation_end: EventHandler[passthrough_event_spec(bool)] = field( + doc="Gets triggered after the open or close animation ends, it receives an open argument with the open state of the drawer by the time the function was triggered." + ) + + dismissible: Var[bool] = field( + doc="When `False`, dragging, clicking outside, pressing esc, etc. will not close the drawer. Use this in combination with the open prop, otherwise you won't be able to open/close the drawer." + ) + + handle_only: Var[bool] = field( + doc="When `True`, dragging will only be possible by the handle." + ) + + snap_points: Sequence[str | float] | None = field( + doc="Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up. Should go from least visible. Also Accept px values, which doesn't take screen height into account." + ) + + fade_from_index: Var[int] = field( + doc="Index of a snapPoint from which the overlay fade should be applied. Defaults to the last snap point." + ) + + scroll_lock_timeout: Var[int] = field( + doc="Duration for which the drawer is not draggable after scrolling content inside of the drawer. Defaults to 500ms" + ) + + prevent_scroll_restoration: Var[bool] = field( + doc="When `True`, it prevents scroll restoration. Defaults to `True`." + ) + + should_scale_background: Var[bool] = field( + doc="Enable background scaling, it requires container element with `vaul-drawer-wrapper` attribute to scale its background." + ) + + close_threshold: Var[float] = field( + doc="Number between 0 and 1 that determines when the drawer should be closed." + ) + + def _post_init(self, *args, **kwargs): + """Initialize the drawer, and give its parts what they share. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + # Rendered by the dialog, which knows when its panel has moved. + on_animation_end = self.event_triggers.pop("on_animation_end", None) + if on_animation_end is not None: + for part in descendants(self, DrawerSurface, DialogRootBase): + part._on_animation_end = on_animation_end + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the drawer off the element. + + Returns: + The props read as styles, and what the drawer hands its parts + or does without: it is not dragged, so it has no snap points. + """ + return [ + *super()._exclude_props(), + "modal", + "direction", + "dismissible", + "handle_only", + "snap_points", + "fade_from_index", + "scroll_lock_timeout", + "prevent_scroll_restoration", + "should_scale_background", + "close_threshold", + ] + + +class DrawerPart(DialogPart): + """A part of a drawer.""" + + as_child: Var[bool] = field(doc=_AS_CHILD_DOC) + + +class DrawerTrigger(DialogSlot): + """The button that opens the dialog.""" + + as_child: Var[bool] = field( + default=Var.create(True), + doc="Defaults to true, if the first child acts as the trigger.", + ) + + # One declaration holds the styles of the trigger and of its child. + _merges_slot: ClassVar[bool] = True + + _command: ClassVar[str] = "show-modal" + + _mark: ClassVar[str] = "data-rx-dialog-trigger" + + def _join( + self, + root: DialogRootBase, + name: str, + named: dict[str, Any], + on_open_change: Any, + ) -> None: + """Take the id of the drawer the trigger opens. + + Args: + root: The drawer the trigger is in. + name: The id of the drawer. + named: What names and describes the drawer, by the attribute. + on_open_change: What the drawer does when it opens or closes. + """ + super()._join(root, name, named, on_open_change) + if literal(getattr(root, "modal", None)) is not None: + # A drawer that may not be modal is opened by its script alone. + self._dialog = {} + if self._command != "close": + self._dialog["aria-controls"] = name + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, or a button around its children, with the + state Radix gives what opens a dialog. + """ + tag = super()._render(props) + if not self._as_child: + tag = tag.add_props(type="button") + if self._command == "close": + return tag + return tag.add_props(**{ + "aria-haspopup": "dialog", + "aria-expanded": False, + "data-state": "closed", + }) + + +class DrawerPortal(DrawerPart): + """Portals your drawer into the body.""" + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a DrawerPortal. + + Args: + *children: What the drawer shows over the page. + **props: The properties of the component. + + Returns: + The children: a native dialog is over the page wherever it is. + """ + return Fragment.create(*children) + + +class DrawerSurface(DialogSurface): + """The native dialog around the content of a drawer.""" + + styles: ClassVar[ComponentStyles] = DRAWER + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fires when the drawer is opened or closed." + ) + + on_open_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the drawer content is opened." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the drawer content is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the drawer content." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when interacting outside the drawer content." + ) + + def _post_init(self, *args, **kwargs): + """Initialize the dialog, as the one of a drawer without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as variants: the drawer sets them. + self._direction: Any = None + self._modal: Any = None + self._on_animation_end: Any = None + super()._post_init(*args, **kwargs) + + def _join( + self, + root: DialogRootBase, + name: str, + named: dict[str, Any], + on_open_change: Any, + ) -> None: + """Take from a drawer where it comes from and how it is dismissed. + + Args: + root: The drawer the dialog is in. + name: The id of the drawer. + named: What names and describes the drawer, by the attribute. + on_open_change: What the drawer does when it opens or closes. + """ + super()._join(root, name, named, on_open_change) + self._direction = getattr(root, "direction", None) + modeless = _is_off(getattr(root, "modal", None)) + self._modal = choose(modeless, "false", "true") + if modeless is not False: + self._dialog["data-modal"] = choose(modeless, "false", None) + kept = _is_off(getattr(root, "dismissible", None)) + if kept is not False: + self._dialog["data-rx-keep"] = choose(kept, "all", None) + for part in self.children: + if isinstance(part, DrawerContent): + part._direction = self._direction + part._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the dialog, what follows its panel 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) + if self._on_animation_end is not None: + yield LiteralVar.create(self._on_animation_end) + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the dialog. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, which says when its panel has slid in or out. + """ + tag = super()._render(props) + if self._on_animation_end is None: + return tag + handler = LiteralVar.create(self._on_animation_end) + return tag.add_props( + on_transition_end=Var( + '((event) => event.propertyName === "transform" && ' + "event.target.parentElement === event.currentTarget && " + f"({handler!s})(event.currentTarget.open))", + _var_data=handler._get_all_var_data(), + ) + ) + + +_EVENTS = ( + "on_open_auto_focus", + "on_close_auto_focus", + "on_escape_key_down", + "on_pointer_down_outside", + "on_interact_outside", +) + + +# Based on https://www.radix-ui.com/primitives/docs/components/dialog#content +class DrawerContent(UIComponent): + """Content that should be rendered in the drawer.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = DRAWER_CONTENT + + as_child: Var[bool] = field(doc=_AS_CHILD_DOC) + + on_open_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the drawer content is opened." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the drawer content is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the drawer content." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when interacting outside the drawer content." + ) + + @classmethod + def create(cls, *children, **props): + """Create a Drawer Content. + + Args: + *children: The list of children to use. + **props: Additional properties to apply to the drawer content. + Its styles are those of the panel, and its events those of + the dialog around it. + + Returns: + The native dialog, around the panel. + """ + events = {event: props.pop(event) for event in _EVENTS if event in props} + return DrawerSurface.create(super().create(*children, **props), **events) + + def _post_init(self, *args, **kwargs): + """Initialize the panel, as the one of a drawer without props. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as a variant: the drawer sets it. + self._direction: Any = None + super()._post_init(*args, **kwargs) + + +class DrawerOverlay(DrawerPart): + """A layer that covers the inert portion of the view when the dialog is open.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = DRAWER_OVERLAY + + def _post_init(self, *args, **kwargs): + """Initialize the overlay, as the one of a modal drawer. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # What the style table reads as a variant: the drawer sets it. + self._modal: Any = None + super()._post_init(*args, **kwargs) + + def _join( + self, + root: DialogRootBase, + name: str, + named: dict[str, Any], + on_open_change: Any, + ) -> None: + """Take from a drawer whether it is modal: only then has it an overlay. + + Args: + root: The drawer the overlay is in. + name: The id of the drawer. + named: What names and describes the drawer, by the attribute. + on_open_change: What the drawer does when it opens or closes. + """ + self._modal = choose(_is_off(getattr(root, "modal", None)), "false", "true") + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the overlay. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, which stays until it has faded out. + """ + return super()._render(props).add_props(**{"data-rx-popup": ""}) + + +class DrawerClose(DrawerTrigger): + """A button that closes the drawer.""" + + _command: ClassVar[str] = "close" + + _mark: ClassVar[str] = "data-rx-dialog-close" + + +class DrawerTitle(DrawerPart): + """A title for the drawer.""" + + tag = "h2" + + styles: ClassVar[ComponentStyles] = DRAWER_TITLE + + _names: ClassVar[str | None] = "labelledby" + + +class DrawerDescription(DrawerPart): + """A description for the drawer.""" + + tag = "p" + + styles: ClassVar[ComponentStyles] = DRAWER_DESCRIPTION + + _names: ClassVar[str | None] = "describedby" + + +class DrawerHandle(DrawerPart): + """A description for the drawer.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = DRAWER_HANDLE + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a DrawerHandle. + + Args: + *children: What the handle holds. + **props: The properties of the component. + + Returns: + The handle: a bar, with room around it for a finger. + """ + return super().create( + Part.create( + *children, + part="hitarea", + tag="span", + custom_attrs={"aria-hidden": True}, + ), + **props, + ) + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the handle. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, which is nothing to assistive technology. + """ + return super()._render(props).add_props(**{"aria-hidden": True}) + + +class Drawer(ComponentNamespace): + """A namespace for Drawer components.""" + + root = __call__ = staticmethod(DrawerRoot.create) + trigger = staticmethod(DrawerTrigger.create) + portal = staticmethod(DrawerPortal.create) + content = staticmethod(DrawerContent.create) + overlay = staticmethod(DrawerOverlay.create) + close = staticmethod(DrawerClose.create) + title = staticmethod(DrawerTitle.create) + description = staticmethod(DrawerDescription.create) + handle = staticmethod(DrawerHandle.create) + + +drawer = Drawer() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py new file mode 100644 index 00000000000..fd28553bb33 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py @@ -0,0 +1,170 @@ +"""The look of a drawer: a native ``dialog`` whose panel slides in from an edge.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.dialog import OPEN, SURFACE + +_DURATION = "0.5s" +_EASING = "cubic-bezier(0.32, 0.72, 0, 1)" + +# What a drawer hands its panel: where it comes from and goes back to, and +# where it is now. +_AWAY = "--rx-drawer-away" +_PLACE = "--rx-drawer-place" + +# The overlay is the element before or after the drawer it belongs to. +_BESIDE_OPEN = ":is(:has(~ dialog[open]), dialog[open] ~ *)" + +# How far a panel is moved out of the page on each side, and where what +# continues it past its edge is. +_AWAYS = { + "bottom": "translate3d(0, 100%, 0)", + "top": "translate3d(0, -100%, 0)", + "left": "translate3d(-100%, 0, 0)", + "right": "translate3d(100%, 0, 0)", +} +_BEYOND: dict[str, dict[str, Any]] = { + "bottom": {"top": "100%", "left": "0", "right": "0", "height": "200%"}, + "top": {"bottom": "100%", "left": "0", "right": "0", "height": "200%"}, + "left": {"right": "100%", "top": "0", "bottom": "0", "width": "200%"}, + "right": {"left": "100%", "top": "0", "bottom": "0", "width": "200%"}, +} + +# The element around the parts of a drawer, which is nothing to the layout. +# It reads the direction, which is the edge the drawer comes from and not +# the direction of a flex container. +DRAWER_ROOT: ComponentStyles = { + "base": {"display": "contents"}, + "variants": {"direction": {}}, +} + +# The dialog covers the page and is nothing to see: its panel is what an +# app styles. A drawer that is not modal lets the pointer through to the +# page beside its panel. +DRAWER: ComponentStyles = { + "base": unchecked({ + **SURFACE, + "position": "fixed", + "inset": "0", + "width": "100%", + "height": "100%", + "z_index": 50, + "display": {"default": "none", OPEN: "block"}, + # A moment longer than its panel, which says when it has slid out. + "transition_duration": "0.55s", + _PLACE: {"default": f"var({_AWAY})", OPEN: "none"}, + }), + "variants": { + "_direction": {side: unchecked({_AWAY: away}) for side, away in _AWAYS.items()}, + "_modal": {"false": {"pointer_events": "none"}}, + }, + "defaults": {"_direction": "bottom"}, +} + +DRAWER_CONTENT: ComponentStyles = { + "base": unchecked({ + "left": "0", + "right": "0", + "bottom": "0", + "top": "0", + "position": "fixed", + "z_index": 50, + "display": "flex", + "pointer_events": "auto", + "touch_action": "none", + "will_change": "transform", + "@media (hover: hover) and (pointer: fine)": {"user_select": "none"}, + "transform": { + "default": f"var({_PLACE})", + "@starting-style": f"var({_AWAY})", + }, + "transition_property": "transform", + "transition_duration": _DURATION, + "transition_timing_function": _EASING, + # The panel goes on past the edge it came from, in its own color. + "_after": { + "content": "''", + "position": "absolute", + "background_color": "inherit", + "background_image": "inherit", + }, + }), + "variants": { + "_direction": {side: {"_after": beyond} for side, beyond in _BEYOND.items()}, + }, + "defaults": {"_direction": "bottom"}, +} + +DRAWER_OVERLAY: ComponentStyles = { + "base": unchecked({ + "position": "fixed", + "left": "0", + "right": "0", + "bottom": "0", + "top": "0", + "z_index": 50, + "background_color": "rgba(0, 0, 0, 0.5)", + "transition_property": "opacity, display", + "transition_duration": _DURATION, + "transition_timing_function": _EASING, + }), + "variants": { + "_modal": { + "true": { + "display": {"default": "none", _BESIDE_OPEN: "block"}, + "opacity": { + "default": 0, + _BESIDE_OPEN: {"default": 1, "@starting-style": 0}, + }, + }, + # A drawer that is not modal has no overlay. + "false": {"display": "none"}, + }, + }, + "defaults": {"_modal": "true"}, +} + +DRAWER_TITLE: ComponentStyles = { + "base": { + "margin": "0", + "font_size": "1.125rem", + "font_weight": "600", + "line_height": "1", + "letter_spacing": "-0.05em", + }, +} + +DRAWER_DESCRIPTION: ComponentStyles = { + "base": {"margin": "0", "font_size": "0.875rem"}, +} + +DRAWER_HANDLE: ComponentStyles = { + "base": { + "display": "block", + "position": "relative", + "opacity": {"default": 0.7, ":hover": 1, ":active": 1}, + "background_color": "#e2e2e4", + "margin_left": "auto", + "margin_right": "auto", + "height": "5px", + "width": "32px", + "border_radius": "1rem", + "touch_action": "pan-y", + }, + "parts": { + "hitarea": { + "base": { + "position": "absolute", + "left": "50%", + "top": "50%", + "transform": "translate(-50%, -50%)", + "width": "max(100%, 2.75rem)", + "height": "max(100%, 2.75rem)", + "touch_action": "inherit", + }, + }, + }, +} diff --git a/pyi_hashes.json b/pyi_hashes.json index d82af94dae7..5a624c2b486 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,12 +118,13 @@ "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": "3baaa214d298bb98db3eae02bb2911e4", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "f47dd19f82d1136e9dc837397696f55a", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "9a1bdbb5949308693e509c528a2d654a", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "0d7b27ab1cb51ac891a31ed97f2f5567", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "61cffb40e8f047c944b54e51ac36cbc7", "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", + "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "4abb8482e413aa9ee3d941ef12878c1a", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "296a02d4f7a276a0548ec473a6c761a9", "packages/reflex-components-ui/src/reflex_components_ui/components/badge.pyi": "f54c7d6d2a403389eb7424f7024bb847", diff --git a/tests/units/reflex_components_ui/components/test_alert_dialog.py b/tests/units/reflex_components_ui/components/test_alert_dialog.py index fb6c1cd05e0..8f323318ac7 100644 --- a/tests/units/reflex_components_ui/components/test_alert_dialog.py +++ b/tests/units/reflex_components_ui/components/test_alert_dialog.py @@ -32,7 +32,7 @@ def test_alert_dialog( force_mount=True, on_escape_key_down=rx.console_log("escape"), ), - on_open_change=rx.console_log, + on_open_change=rx.console_log("changed"), ) assert component.render() == { "name": '"div"', @@ -61,17 +61,21 @@ def test_alert_dialog( '"aria-describedby":"rx-dialog-1-describedby"', '"aria-labelledby":"rx-dialog-1-labelledby"', "className:sx_bf687cb34b_c", + '"data-rx-keep":"outside"', '"data-rx-popup":""', 'id:"rx-dialog-1"', "onCancel:dialogEvent", "onClose:dialogEvent", - 'ref:((dialog) => dialogSync(dialog, null, ({ open: ((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"](_ev_0))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))), escape: ((...args) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("escape"))), ["callback"] : null }), ({ })))], args, ({ })))) })))', + 'ref:((dialog) => dialogSync(dialog, null, ({ open: ((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("changed"))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))), escape: ((...args) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("escape"))), ["callback"] : null }), ({ })))], args, ({ })))) })))', 'role:"alertdialog"', ], "children": [ { "name": '"div"', - "props": ["className:sx_18e4ad36e3_c"], + "props": [ + "className:sx_18e4ad36e3_c", + '"data-rx-dialog-pad":""', + ], "children": [ { "name": '"div"', diff --git a/tests/units/reflex_components_ui/components/test_dialog.py b/tests/units/reflex_components_ui/components/test_dialog.py index 34a02a8ddf6..663232da10c 100644 --- a/tests/units/reflex_components_ui/components/test_dialog.py +++ b/tests/units/reflex_components_ui/components/test_dialog.py @@ -74,7 +74,10 @@ def test_dialog( "children": [ { "name": '"div"', - "props": ["className:sx_18e4ad36e3_c"], + "props": [ + "className:sx_18e4ad36e3_c", + '"data-rx-dialog-pad":""', + ], "children": [ { "name": '"div"', @@ -323,7 +326,10 @@ def test_dialog_in_a_dialog(ui_plugin: UIPlugin): "children": [ { "name": '"div"', - "props": ["className:sx_18e4ad36e3_c"], + "props": [ + "className:sx_18e4ad36e3_c", + '"data-rx-dialog-pad":""', + ], "children": [ { "name": '"div"', @@ -364,7 +370,8 @@ def test_dialog_in_a_dialog(ui_plugin: UIPlugin): { "name": '"div"', "props": [ - "className:sx_18e4ad36e3_c" + "className:sx_18e4ad36e3_c", + '"data-rx-dialog-pad":""', ], "children": [ { @@ -429,7 +436,10 @@ def test_dialog_parts_alone(ui_plugin: UIPlugin): "children": [ { "name": '"div"', - "props": ["className:sx_18e4ad36e3_c"], + "props": [ + "className:sx_18e4ad36e3_c", + '"data-rx-dialog-pad":""', + ], "children": [ { "name": '"div"', diff --git a/tests/units/reflex_components_ui/components/test_drawer.py b/tests/units/reflex_components_ui/components/test_drawer.py new file mode 100644 index 00000000000..d345e264026 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_drawer.py @@ -0,0 +1,410 @@ +"""Tests for reflex_components_ui.components.drawer.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.components import _dialog +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the drawers of each test from one.""" + monkeypatch.setattr(_dialog, "_ids", itertools.count(1)) + + +def test_drawer( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A drawer is a native dialog around the panel an app styles, which slides in from the edge the root names; its overlay is an element of its own beside it, and its portal is nothing.""" + component = rx.ui.drawer.root( + rx.ui.drawer.trigger(rx.el.button("Open")), + rx.ui.drawer.overlay(z_index="5"), + rx.ui.drawer.portal( + rx.ui.drawer.content( + rx.ui.drawer.handle(), + rx.ui.drawer.title("Settings"), + rx.ui.drawer.description("What it is about."), + rx.ui.drawer.close(rx.el.button("Close")), + right="auto", + width="20em", + background_color="white", + ) + ), + direction="left", + on_animation_end=rx.console_log, + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_71b84cd269_c", + '"data-rx-dialog-root":""', + "onClick:dialogClick", + ], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"rx-dialog-1"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + 'command:"show-modal"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + ], + "children": [{"contents": '"Open"'}], + }, + { + "name": '"div"', + "props": ["className:sx_92fd57a6ed_c", '"data-rx-popup":""'], + "children": [], + }, + { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"dialog"', + "props": [ + '"aria-describedby":"rx-dialog-1-describedby"', + '"aria-labelledby":"rx-dialog-1-labelledby"', + "className:sx_ec0690f8c2_c", + '"data-rx-popup":""', + 'id:"rx-dialog-1"', + "onCancel:dialogEvent", + "onClose:dialogEvent", + 'onTransitionEnd:((event) => event.propertyName === "transform" && event.target.parentElement === event.currentTarget && (((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"](_ev_0))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))))(event.currentTarget.open))', + "ref:((dialog) => dialogSync(dialog, null, null))", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_e8c44019a7_c"], + "children": [ + { + "name": '"div"', + "props": [ + '"aria-hidden":true', + "className:sx_c352e99684_c", + ], + "children": [ + { + "name": '"span"', + "props": [ + '"aria-hidden":true', + "className:sx_90a94c0153_c", + ], + "children": [], + } + ], + }, + { + "name": '"h2"', + "props": [ + "className:sx_0590ef4057_c", + 'id:"rx-dialog-1-labelledby"', + ], + "children": [{"contents": '"Settings"'}], + }, + { + "name": '"p"', + "props": [ + "className:sx_faadb9eee6_c", + 'id:"rx-dialog-1-describedby"', + ], + "children": [ + {"contents": '"What it is about."'} + ], + }, + { + "name": '"button"', + "props": [ + 'command:"close"', + 'commandfor:"rx-dialog-1"', + '"data-rx-dialog-close":""', + ], + "children": [{"contents": '"Close"'}], + }, + ], + } + ], + } + ], + }, + ], + } + assert declared_styles(component) == [ + {"display": "contents"}, + {}, + { + "position": "fixed", + "left": "0", + "right": "0", + "bottom": "0", + "top": "0", + "zIndex": "5", + "backgroundColor": "rgba(0, 0, 0, 0.5)", + "transitionProperty": "opacity, display", + "transitionDuration": "0.5s", + "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", + "display": { + "default": "none", + ":is(:has(~ dialog[open]), dialog[open] ~ *)": "block", + }, + "opacity": { + "default": 0, + ":is(:has(~ dialog[open]), dialog[open] ~ *)": { + "default": 1, + "@starting-style": 0, + }, + }, + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": {"default": "transparent", "::backdrop": "transparent"}, + "color": "inherit", + "maxWidth": "none", + "maxHeight": "none", + "outlineStyle": "none", + "transitionProperty": "display, overlay", + "transitionDuration": "0.55s", + "--rx-dialog-shown": {"default": 0, "[open]": 1}, + "position": "fixed", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "width": "100%", + "height": "100%", + "zIndex": 50, + "display": {"default": "none", "[open]": "block"}, + "--rx-drawer-place": {"default": "var(--rx-drawer-away)", "[open]": "none"}, + "--rx-drawer-away": "translate3d(-100%, 0, 0)", + }, + { + "left": "0", + "right": {"default": "auto", "::after": "100%"}, + "bottom": {"default": "0", "::after": "0"}, + "top": {"default": "0", "::after": "0"}, + "position": {"default": "fixed", "::after": "absolute"}, + "zIndex": 50, + "display": "flex", + "pointerEvents": "auto", + "touchAction": "none", + "willChange": "transform", + "userSelect": {"@media (hover: hover) and (pointer: fine)": "none"}, + "transform": { + "default": "var(--rx-drawer-place)", + "@starting-style": "var(--rx-drawer-away)", + }, + "transitionProperty": "transform", + "transitionDuration": "0.5s", + "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", + "content": {"::after": "''"}, + "backgroundColor": {"default": "white", "::after": "inherit"}, + "backgroundImage": {"::after": "inherit"}, + "width": {"default": "20em", "::after": "200%"}, + }, + { + "display": "block", + "position": "relative", + "opacity": {"default": 0.7, ":hover": 1, ":active": 1}, + "backgroundColor": "#e2e2e4", + "marginLeft": "auto", + "marginRight": "auto", + "height": "5px", + "width": "32px", + "borderTopLeftRadius": "1rem", + "borderTopRightRadius": "1rem", + "borderBottomRightRadius": "1rem", + "borderBottomLeftRadius": "1rem", + "touchAction": "pan-y", + }, + { + "position": "absolute", + "left": "50%", + "top": "50%", + "transform": "translate(-50%, -50%)", + "width": "max(100%, 2.75rem)", + "height": "max(100%, 2.75rem)", + "touchAction": "inherit", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "fontSize": "1.125rem", + "fontWeight": "600", + "lineHeight": "1", + "letterSpacing": "-0.05em", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "fontSize": "0.875rem", + }, + {}, + ] + + +def test_drawer_that_is_not_modal_nor_dismissible( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A drawer that is not modal lets the pointer through beside its panel and has no overlay, one that is not dismissible says so to its script, and a trigger that is not its child is a button.""" + component = rx.ui.drawer.root( + rx.ui.drawer.trigger("Open", as_child=False), + rx.ui.drawer.overlay(), + rx.ui.drawer.content("Inside"), + modal=False, + dismissible=False, + snap_points=["148px", 1], + ) + assert component.render() == { + "name": '"div"', + "props": [ + "className:sx_71b84cd269_c", + '"data-rx-dialog-root":""', + "onClick:dialogClick", + ], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"rx-dialog-1"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + '"data-rx-dialog-trigger":""', + '"data-state":"closed"', + 'type:"button"', + ], + "children": [{"contents": '"Open"'}], + }, + { + "name": '"div"', + "props": ["className:sx_10d19d24da_c", '"data-rx-popup":""'], + "children": [], + }, + { + "name": '"dialog"', + "props": [ + "className:sx_9705da5fe6_c", + '"data-modal":"false"', + '"data-rx-keep":"all"', + '"data-rx-popup":""', + 'id:"rx-dialog-1"', + "onCancel:dialogEvent", + "onClose:dialogEvent", + "ref:((dialog) => dialogSync(dialog, null, null))", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_b169a25bca_c"], + "children": [{"contents": '"Inside"'}], + } + ], + }, + ], + } + assert declared_styles(component) == [ + {"display": "contents"}, + {}, + { + "position": "fixed", + "left": "0", + "right": "0", + "bottom": "0", + "top": "0", + "zIndex": 50, + "backgroundColor": "rgba(0, 0, 0, 0.5)", + "transitionProperty": "opacity, display", + "transitionDuration": "0.5s", + "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", + "display": "none", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "backgroundColor": {"default": "transparent", "::backdrop": "transparent"}, + "color": "inherit", + "maxWidth": "none", + "maxHeight": "none", + "outlineStyle": "none", + "transitionProperty": "display, overlay", + "transitionDuration": "0.55s", + "--rx-dialog-shown": {"default": 0, "[open]": 1}, + "position": "fixed", + "top": "0", + "right": "0", + "bottom": "0", + "left": "0", + "width": "100%", + "height": "100%", + "zIndex": 50, + "display": {"default": "none", "[open]": "block"}, + "--rx-drawer-place": {"default": "var(--rx-drawer-away)", "[open]": "none"}, + "--rx-drawer-away": "translate3d(0, 100%, 0)", + "pointerEvents": "none", + }, + { + "left": {"default": "0", "::after": "0"}, + "right": {"default": "0", "::after": "0"}, + "bottom": "0", + "top": {"default": "0", "::after": "100%"}, + "position": {"default": "fixed", "::after": "absolute"}, + "zIndex": 50, + "display": "flex", + "pointerEvents": "auto", + "touchAction": "none", + "willChange": "transform", + "userSelect": {"@media (hover: hover) and (pointer: fine)": "none"}, + "transform": { + "default": "var(--rx-drawer-place)", + "@starting-style": "var(--rx-drawer-away)", + }, + "transitionProperty": "transform", + "transitionDuration": "0.5s", + "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", + "content": {"::after": "''"}, + "backgroundColor": {"::after": "inherit"}, + "backgroundImage": {"::after": "inherit"}, + "height": {"::after": "200%"}, + }, + ] diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index cbeec6c9e28..e1428fac12e 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -147,6 +147,16 @@ def test_every_wave_is_in_the_namespace(): "dialog.title", "dialog.trigger", "divider", + "drawer", + "drawer.close", + "drawer.content", + "drawer.description", + "drawer.handle", + "drawer.overlay", + "drawer.portal", + "drawer.root", + "drawer.title", + "drawer.trigger", "flex", "form", "form.control", @@ -234,6 +244,7 @@ def test_every_wave_is_in_the_namespace(): "checkbox", "data_list", "dialog", + "drawer", "form", "input", "list", From fd643b85cc22c944366cb993314363433b18b7fd Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 10:09:24 +0000 Subject: [PATCH 122/204] Put the list of a select on whole pixels before it is first drawn A list that ends at the end of its trigger, or is centered on it, started on a fraction of a pixel whenever its width had one, which depends on the font; Radix rounds where it puts a list. The popup script now measures the popover in the frame that first shows it and writes what brings it to whole pixels, which its styles apply through its margins. A transform would resample it, and a correction after the first paint keeps the fraction the browser first drew its letters at. The radius cells of the segmented control are given a width of whole pixels: a round end on a fraction of a pixel is drawn by where it is on the page, and Radix differs from itself there. Both matrices are held to a lower tolerance. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../js/src/behaviors/popup-position.js | 7 +- .../js/src/behaviors/popup.js | 70 ++++++++++++ .../js/tests/behaviors/popup-position.test.js | 7 ++ .../js/tests/behaviors/popup.test.js | 107 +++++++++++++++++- .../parity/allowlist.toml | 6 + .../ui_parity/components/segmented_control.py | 23 ++-- .../parity/ui_parity/components/select.py | 19 ++-- .../reflex_components_ui/components/select.py | 11 +- .../src/reflex_components_ui/styles/popup.py | 36 +++++- pyi_hashes.json | 2 +- .../components/test_select.py | 52 ++++----- 11 files changed, 275 insertions(+), 65 deletions(-) diff --git a/packages/reflex-components-ui/js/src/behaviors/popup-position.js b/packages/reflex-components-ui/js/src/behaviors/popup-position.js index d39396d24a6..0551bf0e69e 100644 --- a/packages/reflex-components-ui/js/src/behaviors/popup-position.js +++ b/packages/reflex-components-ui/js/src/behaviors/popup-position.js @@ -34,10 +34,9 @@ export function place(popup, anchor, open) { style.inset = "auto"; style.minWidth = `${box.width}px`; style.maxHeight = `${Math.max(over ? above : below, 0)}px`; - style.left = `${Math.max(Math.min(box.left, innerWidth - popup.offsetWidth - EDGE), EDGE)}px`; - style.top = over - ? `${box.top - Math.min(height, above) - gap * 2}px` - : `${box.bottom}px`; + // On whole pixels, as Radix puts the popups it places. + style.left = `${Math.round(Math.max(Math.min(box.left, innerWidth - popup.offsetWidth - EDGE), EDGE))}px`; + style.top = `${Math.round(over ? box.top - Math.min(height, above) - gap * 2 : box.bottom)}px`; }; update(); addEventListener("scroll", update, true); diff --git a/packages/reflex-components-ui/js/src/behaviors/popup.js b/packages/reflex-components-ui/js/src/behaviors/popup.js index 9813544a194..5e660340471 100644 --- a/packages/reflex-components-ui/js/src/behaviors/popup.js +++ b/packages/reflex-components-ui/js/src/behaviors/popup.js @@ -42,6 +42,58 @@ export function pair(popup, trigger) { trigger.setAttribute("aria-controls", popup.id); } +/** What says how far a popup is from whole pixels, across and down. */ +const SNAP = ["--rx-popup-snap-x", "--rx-popup-snap-y"]; + +/** + * Say how far a popup is laid out from whole pixels. + * + * Where it is laid out is read from where it is drawn, less the transform + * it comes in with. + * + * @param {HTMLElement} popup The popover. + * @returns {number[]} What brings it to whole pixels, across and down. + */ +function off(popup) { + const { transform, transformOrigin } = getComputedStyle(popup); + const [a = 1, , , d = 1, e = 0, f = 0] = ( + transform.match(/-?[\d.]+(e-?\d+)?/g) ?? [] + ).map(Number); + const [x = 0, y = 0] = transformOrigin + .split(" ") + .map((length) => Number.parseFloat(length) || 0); + const box = popup.getBoundingClientRect(); + const ratio = globalThis.devicePixelRatio || 1; + return [box.x - x * (1 - a) - e, box.y - y * (1 - d) - f].map((at) => { + // In the units a browser lays out in: a sixty-fourth of a pixel, or + // close to it, and what is left of one is nothing. + const by = Math.round((Math.round(at * ratio) / ratio - at) * 64) / 64; + return Math.abs(by) < 0.02 ? 0 : by; + }); +} + +/** + * Put an open popup on whole pixels, as Radix puts the ones it places. + * + * A popup that ends at the end of its anchor, or is centered on it, starts + * on a fraction of a pixel when its width has one. Its styles move it by + * what is written here, in its margins: it is laid out there, not drawn + * there by a transform, which would blur it. + * + * @param {HTMLElement} popup The popover. + * @returns {void} + */ +function snap(popup) { + const { style } = popup; + for (const name of SNAP) style.removeProperty(name); + const wanted = off(popup); + wanted.forEach((by, axis) => by && style.setProperty(SNAP[axis], `${by}px`)); + // A popup the browser turned over has its margins turned over with it. + off(popup).forEach( + (left, axis) => left && style.setProperty(SNAP[axis], `${-wanted[axis]}px`), + ); +} + /** * Follow a popup that opens or closes: the `onToggle` of the popover. * @@ -66,3 +118,21 @@ export function popupToggle(event) { } return open; } + +/** + * Put a popup that is about to open on whole pixels before it is first + * drawn: the `onBeforeToggle` of the popover. + * + * The browser keeps the fraction of a pixel a popover is first drawn at, in + * the edges of its letters, so moving it once it has been seen is too late: + * it is moved in the frame that shows it. + * + * @param {{ currentTarget: HTMLElement, newState?: string }} event The toggle to come. + * @returns {void} + */ +export function popupBeforeToggle(event) { + const popup = event.currentTarget; + if (ANCHORED && event.newState === "open") { + requestAnimationFrame(() => snap(popup)); + } +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js index 0fdcecefb57..890f1b5931f 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js @@ -92,6 +92,13 @@ test("it follows its anchor while it is open, and no longer", () => { expect(placed()).toEqual(["80px", "112px", "140px", "474px"]); }); +test("it is put on whole pixels", () => { + box = { left: 40.4, top: 100.2, bottom: 132.6, width: 120.5 }; + place(popup, anchor, true); + + expect(placed()).toEqual(["40px", "133px", "120.5px", "453.4px"]); +}); + test("a popup without a margin has no gap", () => { popup.style.marginTop = ""; place(popup, anchor, true); diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js index ce3dd1a2ace..532f1a0f8bd 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js @@ -19,10 +19,11 @@ function build(id = "list") { /** * Send a popup the toggle the browser sends. * - * @param {(event: { currentTarget: HTMLElement, newState?: string }) => boolean} popupToggle The script. + * @template T + * @param {(event: { currentTarget: HTMLElement, newState?: string }) => T} popupToggle The script. * @param {HTMLElement} popup The popup. - * @param {string} newState What it is now. - * @returns {boolean} What the script answers. + * @param {string} newState What it is now, or is about to be. + * @returns {T} What the script answers. */ function toggle(popupToggle, popup, newState) { return popupToggle({ currentTarget: popup, newState }); @@ -43,6 +44,10 @@ function said(trigger) { beforeEach(() => { vi.resetModules(); + // The frame a popup is first drawn in comes at once. + vi.stubGlobal("requestAnimationFrame", (/** @type {() => void} */ frame) => + frame(), + ); }); afterEach(() => { @@ -64,6 +69,102 @@ test("the trigger says whether its popup is open, and the browser places it", as expect(popup.getAttribute("style")).toBe(null); }); +/** + * Lay a popup out as a browser does: where it is told, moved by what its + * script found it off whole pixels. + * + * @param {HTMLElement} popup The popover. + * @param {{ x: number, y: number }} laid Where it is laid out, unmoved. + * @param {{ drawn?: { x: number, y: number }, turned?: boolean }} [how] + * How far its transform draws it from there, and whether the browser + * turned it over, its margins with it. + * @returns {void} + */ +function layOut(popup, laid, { drawn = { x: 0, y: 0 }, turned = false } = {}) { + const moved = (/** @type {string} */ axis) => + (Number.parseFloat( + popup.style.getPropertyValue(`--rx-popup-snap-${axis}`), + ) || 0) * (turned ? -1 : 1); + popup.getBoundingClientRect = () => + /** @type {DOMRect} */ ({ + x: laid.x + moved("x") + drawn.x, + y: laid.y + moved("y") + drawn.y, + }); +} + +test("a popup that opens is laid out on whole pixels before it is drawn", async () => { + vi.stubGlobal("CSS", { supports: () => true }); + const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); + const { popup } = build(); + + layOut(popup, { x: 34.640625, y: 52 }); + toggle(popupBeforeToggle, popup, "open"); + expect(popup.getAttribute("style")).toBe("--rx-popup-snap-x: 0.359375px;"); + + // What it was moved by before is forgotten when it opens again. + layOut(popup, { x: 60.3125, y: 51.75 }); + toggle(popupBeforeToggle, popup, "open"); + expect(popup.getAttribute("style")).toBe( + "--rx-popup-snap-x: -0.3125px; --rx-popup-snap-y: 0.25px;", + ); + + // A popup on whole pixels is left where it is, and one that closes too. + layOut(popup, { x: 40, y: 50 }); + toggle(popupBeforeToggle, popup, "open"); + expect(popup.getAttribute("style")).toBe(""); + layOut(popup, { x: 40.5, y: 50 }); + toggle(popupBeforeToggle, popup, "closed"); + expect(popup.getAttribute("style")).toBe(""); +}); + +test("a popup is laid out on whole pixels whatever it comes in with", async () => { + vi.stubGlobal("CSS", { supports: () => true }); + const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); + const { popup } = build(); + // Halfway in: half its size about a point inside it, and four pixels up. + popup.style.transform = "matrix(0.5, 0, 0, 0.5, 0, -4)"; + popup.style.transformOrigin = "10px 20px"; + layOut(popup, { x: 35.25, y: 44.5 }, { drawn: { x: 5, y: 6 } }); + + toggle(popupBeforeToggle, popup, "open"); + expect([ + popup.style.getPropertyValue("--rx-popup-snap-x"), + popup.style.getPropertyValue("--rx-popup-snap-y"), + ]).toEqual(["-0.25px", "0.5px"]); +}); + +test("a popup the browser turned over is moved the other way", async () => { + vi.stubGlobal("CSS", { supports: () => true }); + const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); + const { popup } = build(); + layOut(popup, { x: 34.640625, y: 52.25 }, { turned: true }); + + toggle(popupBeforeToggle, popup, "open"); + expect(popup.getAttribute("style")).toBe( + "--rx-popup-snap-x: -0.359375px; --rx-popup-snap-y: 0.25px;", + ); +}); + +test("a screen with more pixels has the popup on its pixels", async () => { + vi.stubGlobal("CSS", { supports: () => true }); + vi.stubGlobal("devicePixelRatio", 2); + const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); + const { popup } = build(); + layOut(popup, { x: 10.3, y: 20.5 }); + + toggle(popupBeforeToggle, popup, "open"); + expect(popup.getAttribute("style")).toBe("--rx-popup-snap-x: 0.203125px;"); +}); + +test("a browser that does not place popups moves none before it is drawn", async () => { + const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); + const { popup } = build(); + layOut(popup, { x: 34.640625, y: 52 }); + + toggle(popupBeforeToggle, popup, "open"); + expect(popup.getAttribute("style")).toBe(null); +}); + test("a popup nothing opens is followed without a trigger", async () => { const { popupToggle, opener } = await import( "$/reflex-ui/behaviors/popup.js" diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index b2c6f1bf1bb..2404ad1489e 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -262,6 +262,12 @@ cells = "size-responsive*" properties = ["width", "height"] reason = "When the size of rx.select goes from \"3\" at one breakpoint to a smaller one at the next, Radix Themes keeps the larger icon size \"3\" has. The icon of rx.ui.select has the size of the select at each breakpoint, so the trigger is two pixels narrower there." +[[look]] +component = "select" +check = "pixels" +cells = "size-responsive" +reason = "When the size of rx.select goes from \"3\" at one breakpoint to a smaller one at the next, Radix Themes keeps the larger icon size \"3\" has. The icon of rx.ui.select has the size of the select at each breakpoint, so the trigger is two pixels narrower there." + [[contract]] component = "select" step = "shows the chosen option in the server render" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py index ad2618bcf62..41c59c73540 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py @@ -19,6 +19,8 @@ # The second item: a button of Radix, a label around a radio button here. TARGET = ("button:nth-child(2)", "label:nth-child(2)") MANY = [str(number) for number in range(1, 13)] +# Three items of a whole number of pixels each. +WIDTH = "240px" def _control(namespace: Any, props: Mapping[str, Any]) -> Any: @@ -57,7 +59,6 @@ def _control(namespace: Any, props: Mapping[str, Any]) -> Any: base={"default_value": "1"}, cross={"variant": VARIANTS, "size": SIZES, "default_value": ["1", "2", "3"]}, sweep={ - "radius": RADII, "color_scheme": ["ruby", "gray"], "holds": ["many", "icons"], "default_value": {"none": None}, @@ -73,7 +74,12 @@ def _control(namespace: Any, props: Mapping[str, Any]) -> Any: "state": STATES, "appearance": [LIGHT, DARK], }, - {"radius": RADII, "size": SIZES, "variant": VARIANTS}, + # A control as wide as its words has items a fraction of a pixel + # wide, and the browser draws a round end that is on a fraction by + # where it is on the page: Radix differs from itself there. The + # cells of the radius have items of 80 pixels, in any font. + {"radius": RADII, "width": [WIDTH]}, + {"radius": RADII, "size": SIZES, "variant": VARIANTS, "width": [WIDTH]}, {"holds": ["many"], "default_value": ["1", "11", "12"], "size": ["1"]}, { "size": {"responsive": rx.breakpoints(initial="1", sm="3", lg="2")}, @@ -90,12 +96,13 @@ def _control(namespace: Any, props: Mapping[str, Any]) -> Any: # The focus is on the item of Radix and on the radio button in the item # here. states={FOCUS_VISIBLE: FOCUS_WITHIN}, - # Not held to zero. At a threshold of zero 87 of the 103 cells are equal - # pixel for pixel, and the others differ by where they are on the page: - # the translucent fills of the control and of what marks the chosen item - # are dithered by a step of a channel. At the default threshold 3 cells - # differ, by at most 3 pixels of 33600 on a rounded corner. - tolerance=0.0001, + # Not held to zero. At a threshold of zero most cells are equal pixel + # for pixel, and the others differ by where they are on the page: the + # translucent fills of the control and of what marks the chosen item + # are dithered by a step of a channel. At the default threshold no cell + # differs in the fonts of the theme, and one does by one pixel of 33600 + # in another font. + tolerance=0.00005, ) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/select.py b/packages/reflex-components-ui/parity/ui_parity/components/select.py index 30c2608956d..825a7f3e9aa 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/select.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/select.py @@ -201,18 +201,13 @@ def _close(page: Page, target: Locator, point: Point) -> None: "trigger => trigger.hasAttribute('data-placeholder')" " || trigger.textContent !== '')" ), - # Not held to zero. At a threshold of zero 162 of the 193 cells are - # equal pixel for pixel, and the others differ by where they are on the - # page: the gradients of the classic trigger are dithered by a step of a - # channel, as the trigger of Radix is against itself at another place. - # At the default threshold 4 cells differ, by at most 213 pixels of - # 92400: a list that ends at the end of its trigger, or is centered on - # it, starts at a fraction of a pixel when its width has one, where - # Radix rounds where it puts a list, so the edges of its letters are - # anti-aliased otherwise. The tolerance also takes in the 69 pixels of - # the icon of a responsive size, which the allowlist explains by its - # computed size. - tolerance=0.003, + # Not held to zero. At a threshold of zero most cells are equal pixel + # for pixel, and the others differ by where they are on the page: the + # gradients of the classic trigger are dithered by a step of a channel, + # as the trigger of Radix is against itself at another place. At the + # default threshold 2 cells differ, by at most 2 pixels of 92400, on the + # icon of a trigger whose long text puts it on a fraction of a pixel. + tolerance=0.0001, ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/select.py b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py index deb0b07434b..c6582d2da05 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/select.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py @@ -39,19 +39,21 @@ from reflex_components_ui.themes import LiteralAccentColor _SCRIPT = f"$/{WEB_DIR}/behaviors/listbox.js" +_POPUP_SCRIPT = f"$/{WEB_DIR}/behaviors/popup.js" @functools.cache -def _script(name: str) -> Var: - """Name a function of the script of a select. +def _script(name: str, module: str = _SCRIPT) -> Var: + """Name a function of the script of a select, or of a popup. Args: name: The name the script exports it under. + module: The script. Returns: The function, with its import. """ - return Var(name, _var_data=VarData(imports={_SCRIPT: [ImportVar(tag=name)]})) + return Var(name, _var_data=VarData(imports={module: [ImportVar(tag=name)]})) # The events of the popup as they are rendered, by the name the script @@ -731,6 +733,7 @@ def _get_vars( """ yield from super()._get_vars(include_children, ignore_ids) yield _script("selectToggle") + yield _script("popupBeforeToggle", _POPUP_SCRIPT) def _exclude_props(self) -> list[str]: """Keep the props that say where the popup goes off the element. @@ -777,6 +780,8 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: "role": "listbox", "tabIndex": -1, "data-rx-popup": "", + # Before it is first drawn, the popup is put on whole pixels. + "onBeforeToggle": _script("popupBeforeToggle", _POPUP_SCRIPT), "onToggle": toggle, }) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py index 60642c543bc..2d7b3274736 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py @@ -34,6 +34,10 @@ OFFSET = "--rx-popup-offset" SHIFT = "--rx-popup-shift" _FROM = "--rx-popup-from" +# What the script of a popup sets on it once it is open: how far it is from +# whole pixels, across and down. Radix puts what it places on whole pixels. +_SNAP_X = "var(--rx-popup-snap-x, 0px)" +_SNAP_Y = "var(--rx-popup-snap-y, 0px)" _MOTION = "@media (prefers-reduced-motion: no-preference)" @@ -90,13 +94,35 @@ def placement(side: str, align: str, default_offset: str = "0px") -> dict[str, A viewport leaves on that side. """ vertical = side in ("top", "bottom") - before, after = ("top", "bottom") if vertical else ("left", "right") - start, end = ("left", "right") if vertical else ("top", "bottom") offset = f"var({OFFSET}, {default_offset})" + shift = f"var({SHIFT}, 0px)" + # The room between the popup and each side: the offset on the two + # sides that face the anchor or lie opposite it, and the shift on the + # side the popup is aligned to. A margin and the one opposite it move + # the popup together, by what its script found it off whole pixels. + across = { + "start": (f"calc({shift} + {_SNAP_X})", f"calc(0px - {_SNAP_X})"), + "center": (_SNAP_X, f"calc(0px - {_SNAP_X})"), + "end": (_SNAP_X, f"calc({shift} - {_SNAP_X})"), + } + down = { + "start": (f"calc({shift} + {_SNAP_Y})", f"calc(0px - {_SNAP_Y})"), + "center": (_SNAP_Y, f"calc(0px - {_SNAP_Y})"), + "end": (_SNAP_Y, f"calc({shift} - {_SNAP_Y})"), + } + if vertical: + left, right = across[align] + top, bottom = f"calc({offset} + {_SNAP_Y})", f"calc({offset} - {_SNAP_Y})" + else: + top, bottom = down[align] + left, right = f"calc({offset} + {_SNAP_X})", f"calc({offset} - {_SNAP_X})" + start, end = ("left", "right") if vertical else ("top", "bottom") style: dict[str, Any] = { "position_area": _AREAS[side, align], - f"margin_{before}": offset, - f"margin_{after}": offset, + "margin_top": top, + "margin_right": right, + "margin_bottom": bottom, + "margin_left": left, ("max_height" if vertical else "max_width"): ( f"calc(100% - {offset} - {_EDGE})" ), @@ -108,8 +134,6 @@ def placement(side: str, align: str, default_offset: str = "0px") -> dict[str, A } if align == "center": style["justify_self" if vertical else "align_self"] = "anchor-center" - else: - style[f"margin_{start if align == 'start' else end}"] = f"var({SHIFT}, 0px)" return style diff --git a/pyi_hashes.json b/pyi_hashes.json index a6410766f9f..31b48e0954d 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -140,7 +140,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.pyi": "e7f9c6ffd5f3d882ebe2fa4c06c0bcd0", "packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.pyi": "0b9bb867b1ef68c0fd9b10d52867d2b8", "packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.pyi": "6c4bcbd1e1d2ee3effda901ad208fe56", - "packages/reflex-components-ui/src/reflex_components_ui/components/select.pyi": "d8bbfe6dcba937973f9d6f86f2ae619b", + "packages/reflex-components-ui/src/reflex_components_ui/components/select.pyi": "7c9b56d6cbf55e8bed5ef1d262b115d0", "packages/reflex-components-ui/src/reflex_components_ui/components/separator.pyi": "bd32f08f7c0ff2cb6733f964ea843440", "packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.pyi": "4bedd989efb5b095b943a04830bbd140", "packages/reflex-components-ui/src/reflex_components_ui/components/slider.pyi": "b5702134bebf0337effc41e3ddeffda8", diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index 9facc01fcae..65183251284 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -1,9 +1,8 @@ """Tests for reflex_components_ui.components.select.""" import itertools -import re from collections.abc import Callable -from typing import Any, Literal, get_args +from typing import Any import pytest from reflex_base.utils.imports import ImportVar @@ -156,9 +155,10 @@ def test_select( { "name": '"div"', "props": [ - 'className:sx_222d3d03d6_c + " " + reflexUIClasses_f97593a337', + 'className:sx_c23b44fd7f_c + " " + reflexUIClasses_f97593a337', '"data-rx-popup":""', 'id:"rx-select-2"', + "onBeforeToggle:popupBeforeToggle", "onToggle:selectToggle", 'popover:"auto"', 'role:"listbox"', @@ -476,10 +476,10 @@ def test_select( "right": "auto", "bottom": "auto", "left": "auto", - "marginTop": "var(--rx-popup-offset, 4px)", - "marginRight": "var(--rx-popup-shift, 0px)", - "marginBottom": "var(--rx-popup-offset, 4px)", - "marginLeft": "0", + "marginTop": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-y, 0px))", + "marginRight": "calc(var(--rx-popup-shift, 0px) - var(--rx-popup-snap-x, 0px))", + "marginBottom": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-y, 0px))", + "marginLeft": "var(--rx-popup-snap-x, 0px)", "padding": "var(--select-content-padding)", "borderTopWidth": "0", "borderRightWidth": "0", @@ -802,9 +802,10 @@ def test_select_of_a_list( { "name": '"div"', "props": [ - 'className:sx_d08c2fb679_c + " " + reflexUIClasses_e201574881', + 'className:sx_51e4617267_c + " " + reflexUIClasses_e201574881', '"data-rx-popup":""', 'id:"rx-select-2"', + "onBeforeToggle:popupBeforeToggle", "onToggle:selectToggle", 'popover:"auto"', 'role:"listbox"', @@ -1038,10 +1039,10 @@ def test_select_default_styles( "right": "auto", "bottom": "auto", "left": "auto", - "marginTop": "var(--rx-popup-offset, 4px)", - "marginRight": "0", - "marginBottom": "var(--rx-popup-offset, 4px)", - "marginLeft": "var(--rx-popup-shift, 0px)", + "marginTop": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-y, 0px))", + "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", + "marginBottom": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-y, 0px))", + "marginLeft": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-x, 0px))", "padding": "var(--select-content-padding)", "borderTopWidth": "0", "borderRightWidth": "0", @@ -1268,10 +1269,10 @@ def test_select_ghost_styles( "right": "auto", "bottom": "auto", "left": "auto", - "marginTop": "0", - "marginRight": "var(--rx-popup-offset, 4px)", - "marginBottom": "0", - "marginLeft": "var(--rx-popup-offset, 4px)", + "marginTop": "var(--rx-popup-snap-y, 0px)", + "marginRight": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-x, 0px))", + "marginBottom": "calc(0px - var(--rx-popup-snap-y, 0px))", + "marginLeft": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-x, 0px))", "padding": "var(--select-content-padding)", "borderTopWidth": "0", "borderRightWidth": "0", @@ -1376,14 +1377,9 @@ def test_select_unknown_side(ui_plugin: UIPlugin): """A side a list cannot be on is an error that lists the sides.""" with pytest.raises(StyleError) as error: rx.ui.select.content(side="above") # pyright: ignore[reportArgumentType] - # In the order of the Literal Python keeps for these four values, which - # is the one of whichever module first wrote them. - sides = ", ".join( - f'"{side}"' for side in get_args(Literal["top", "right", "bottom", "left"]) - ) assert ( str(error.value) - == f'rx.ui.select_content: unknown side "above". The values are {sides}.' + == 'rx.ui.select_content: unknown side "above". The values are "top", "right", "bottom", "left".' ) @@ -1486,9 +1482,10 @@ def test_select_bound_to_state(ui_plugin: UIPlugin): ], } assert content.render()["props"] == [ - "className:sx_bb2bcf4a84_c", + "className:sx_58b8db244a_c", '"data-rx-popup":""', 'id:"rx-select-1"', + "onBeforeToggle:popupBeforeToggle", ( "onToggle:((event) => selectToggle(event, ({ " f"open: {_event('set_is_open', 'is_open')}, " @@ -1533,10 +1530,6 @@ def test_select_of_a_list_in_state(ui_plugin: UIPlugin): (group,) = content.children (options,) = group.children item = options.children[0] - # Named after the bytecode of the function that renders an option, which - # differs from one Python version to the next. - index = options.render()["index_var_name"] - assert re.fullmatch(r"index_[0-9a-f]{32}", index) assert item.render()["props"] == [ ( f'"aria-selected":(({STATE}.fruit_rx_state_ === item_rx_state_) ' @@ -1544,7 +1537,7 @@ def test_select_of_a_list_in_state(ui_plugin: UIPlugin): ), "className:sx_afbb711e7e_c", '"data-value":item_rx_state_', - f"key:{index}", + "key:index_d6d6157c99650830f12a866606ea87b7", 'role:"option"', "tabIndex:-1", ] @@ -1599,3 +1592,6 @@ def test_select_script(ui_plugin: UIPlugin): ImportVar(tag="syncSelect"), ImportVar(tag="selectFocus"), ] + assert select._get_all_imports()["$/reflex-ui/behaviors/popup.js"] == [ + ImportVar(tag="popupBeforeToggle") + ] From cb5c71d96de247162d3fcd4a8618b9f4ed6e5a79 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 10:11:17 +0000 Subject: [PATCH 123/204] Hold the radio contracts to what every browser does, and say what a wait found Safari enters a group of native radio buttons at its last button when the focus comes backwards, and stops at the ends of a group where the other browsers go round. The contracts of the radio group and of the radio cards now assert apart what holds everywhere (one stop for Shift+Tab, every item reached with the arrow keys, a disabled one passed) and what is the convention of a browser, which the allowlist records for WebKit. A step that waits now fails with what it found: wait_for_value in the samples replaces waits that could only time out. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- .../parity/allowlist.toml | 18 +++++ .../ui_parity/components/radio_cards.py | 46 +++++++++--- .../ui_parity/components/radio_group.py | 75 ++++++++++++++----- .../parity/ui_parity/samples.py | 34 +++++++++ .../parity/test_samples.py | 52 +++++++++++++ 5 files changed, 196 insertions(+), 29 deletions(-) create mode 100644 tests/units/reflex_components_ui/parity/test_samples.py diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 2404ad1489e..bdd7b975870 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -119,6 +119,18 @@ step = "checks one item of a group with JavaScript disabled" system = "rx" reason = "The items of rx.radio_group are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. The items of rx.ui.radio_group are native radio buttons that share a name, which the browser checks one at a time with or without JavaScript." +[[contract]] +component = "radio_group" +step = "Shift+Tab into a group with nothing checked stops on its first item" +engines = ["webkit"] +reason = "The items of rx.ui.radio_group are native radio buttons, and the browser decides where the focus enters a group in which none is checked. Safari enters it at the button nearest to where the focus comes from: the last one for Shift+Tab, where the other browsers and rx.radio_group enter at the first. The group is one stop either way, and the arrow keys reach every item." + +[[contract]] +component = "radio_group" +step = "the arrow keys go round at the ends of a group" +engines = ["webkit"] +reason = "The items of rx.ui.radio_group are native radio buttons, which the arrow keys move through as the browser does it. Safari stops at the first and at the last button of a group, where the other browsers and rx.radio_group go round to the other end. Every item is reached with the arrow keys in both." + [[contract]] component = "radio_group" step = "Enter on a radio button does not submit its form" @@ -167,6 +179,12 @@ step = "checks one card of a group with JavaScript disabled" system = "rx" reason = "The cards of rx.radio_cards are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. A card of rx.ui.radio_cards is a label around a native radio button, which the browser checks with or without JavaScript." +[[contract]] +component = "radio_cards" +step = "the arrow keys go round at the ends of a group" +engines = ["webkit"] +reason = "The cards of rx.ui.radio_cards hold native radio buttons, which the arrow keys move through as the browser does it. Safari stops at the first and at the last card of a group, where the other browsers and rx.radio_cards go round to the other end. Every card is reached with the arrow keys in both." + [[contract]] component = "radio_cards" step = "Enter on a card does not submit its form" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py index 36f4eafa681..cd8efd9c778 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py @@ -10,7 +10,7 @@ from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.look import FOCUS_WITHIN from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix -from ui_parity.samples import ACCENTS, focused, wait_for_text +from ui_parity.samples import ACCENTS, focused, wait_for_text, wait_for_value VARIANTS = ["surface", "classic"] SIZES = ["1", "2", "3"] @@ -208,7 +208,7 @@ def _items(namespace: Any, *values: str) -> list[Any]: ".map(card => card.textContent)" ) # The text of the card that has the focus. -FOCUSED_CARD = f"document.activeElement.closest('{CARDS}')?.textContent" +FOCUSED_CARD = f"(document.activeElement.closest('{CARDS}')?.textContent ?? null)" # How long a key is held, in milliseconds. HELD = 60 @@ -221,10 +221,17 @@ def _wait_for_checked(run: Run, group: str, cards: list[str]) -> None: group: The id of the frame of the group. cards: The text of each card that is to be checked. """ - run.page.wait_for_function( - f"([id, cards]) => JSON.stringify(({CHECKED})(id)) === cards", - arg=[group, json.dumps(cards)], - ) + wait_for_value(run.page, f"({CHECKED})({json.dumps(group)})", cards) + + +def _wait_for_focus(run: Run, card: str) -> None: + """Wait until a card has the focus. + + Args: + run: The run, on a page. + card: The text of the card. + """ + wait_for_value(run.page, FOCUSED_CARD, card) @CONTRACT.step("its cards are in the server render", on=SERVER) @@ -275,23 +282,38 @@ def _arrows(run: Run) -> None: for key, card in ( ("ArrowDown", "Two"), ("ArrowRight", "Three"), - ("ArrowDown", "One"), - ("ArrowUp", "Three"), - ("ArrowLeft", "Two"), + ("ArrowUp", "Two"), + ("ArrowLeft", "One"), ): # Held as long as a finger holds it: Radix checks the card the focus # moves to only while the key is still down. page.keyboard.press(key, delay=HELD) - page.wait_for_function(f"{FOCUSED_CARD} === '{card}'") + _wait_for_focus(run, card) _wait_for_checked(run, "pick", [card]) - wait_for_text(page, "seen", '["Two","Three","One","Three","Two"]') + wait_for_text(page, "seen", '["Two","Three","Two","One"]') page.keyboard.press("Tab") + _wait_for_focus(run, "Red") page.keyboard.press("ArrowDown", delay=HELD) + _wait_for_focus(run, "Blue") _wait_for_checked(run, "colors", ["Blue"]) - page.keyboard.press("ArrowDown", delay=HELD) + page.keyboard.press("ArrowUp", delay=HELD) + _wait_for_focus(run, "Red") _wait_for_checked(run, "colors", ["Red"]) +@CONTRACT.step("the arrow keys go round at the ends of a group") +def _arrows_round(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + _wait_for_focus(run, "One") + page.keyboard.press("ArrowUp", delay=HELD) + _wait_for_focus(run, "Three") + _wait_for_checked(run, "pick", ["Three"]) + page.keyboard.press("ArrowDown", delay=HELD) + _wait_for_focus(run, "One") + _wait_for_checked(run, "pick", ["One"]) + + @CONTRACT.step("Space and a click check a card, and say so") def _check(run: Run) -> None: page = run.page diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py index ec59d260795..146920bcfe0 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py @@ -9,7 +9,7 @@ import reflex as rx from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import ACTIVE, DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix -from ui_parity.samples import ACCENTS, focused, wait_for_text +from ui_parity.samples import ACCENTS, focused, wait_for_text, wait_for_value VARIANTS = ["classic", "surface", "soft"] SIZES = ["1", "2", "3"] @@ -167,8 +167,10 @@ def submit(self, data: dict[str, str]): ) # How long a key is held, in milliseconds. HELD = 60 -# The text of the item that has the focus. -FOCUSED_ITEM = "document.activeElement.closest('label')?.textContent" +# The text of the item that has the focus, or nothing when no item has it. +FOCUSED_ITEM = "(document.activeElement.closest('label')?.textContent ?? null)" +# Whether the focus is in the group with nothing checked. +IN_PICK = "document.activeElement.closest('#pick') !== null" def _wait_for_checked(run: Run, group: str, items: list[str]) -> None: @@ -179,10 +181,17 @@ def _wait_for_checked(run: Run, group: str, items: list[str]) -> None: group: The id of the frame of the group. items: The text of each item that is to be checked. """ - run.page.wait_for_function( - f"([id, items]) => JSON.stringify(({CHECKED})(id)) === items", - arg=[group, json.dumps(items)], - ) + wait_for_value(run.page, f"({CHECKED})({json.dumps(group)})", items) + + +def _wait_for_focus(run: Run, item: str) -> None: + """Wait until an item has the focus. + + Args: + run: The run, on a page. + item: The text of the item. + """ + wait_for_value(run.page, FOCUSED_ITEM, item) @CONTRACT.step("its items are in the server render", on=SERVER) @@ -227,37 +236,69 @@ def _tab(run: Run) -> None: _wait_for_checked(run, "pick", []) +@CONTRACT.step("Shift+Tab stops once in a group with nothing checked") +def _shift_tab_once(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + page.keyboard.press("Tab") + _wait_for_focus(run, "Red") + inside = [] + for _ in range(2): + page.keyboard.press("Shift+Tab") + inside.append(page.evaluate(IN_PICK)) + assert inside == [True, False] + _wait_for_checked(run, "pick", []) + + @CONTRACT.step("Shift+Tab into a group with nothing checked stops on its first item") def _shift_tab(run: Run) -> None: page = run.page page.keyboard.press("Tab") page.keyboard.press("Tab") - assert page.evaluate(FOCUSED_ITEM) == "Red" + _wait_for_focus(run, "Red") page.keyboard.press("Shift+Tab") - assert page.evaluate(FOCUSED_ITEM) == "One" + _wait_for_focus(run, "One") @CONTRACT.step("the arrow keys move through a group and check, past a disabled item") def _arrows(run: Run) -> None: page = run.page page.keyboard.press("Tab") - visited = [] - for key in ("ArrowDown", "ArrowRight", "ArrowDown", "ArrowUp", "ArrowLeft"): + for key, item in ( + ("ArrowDown", "Two"), + ("ArrowRight", "Three"), + ("ArrowUp", "Two"), + ("ArrowLeft", "One"), + ): # Held as long as a finger holds it: Radix checks the item the focus # moves to only while the key is still down. page.keyboard.press(key, delay=HELD) - visited.append(page.evaluate(FOCUSED_ITEM)) - _wait_for_checked(run, "pick", [visited[-1]]) - assert visited == ["Two", "Three", "One", "Three", "Two"] - wait_for_text(page, "seen", '["Two","Three","One","Three","Two"]') + _wait_for_focus(run, item) + _wait_for_checked(run, "pick", [item]) + wait_for_text(page, "seen", '["Two","Three","Two","One"]') page.keyboard.press("Tab") + _wait_for_focus(run, "Red") page.keyboard.press("ArrowDown", delay=HELD) - assert page.evaluate(FOCUSED_ITEM) == "Blue" + _wait_for_focus(run, "Blue") _wait_for_checked(run, "colors", ["Blue"]) - page.keyboard.press("ArrowDown", delay=HELD) + page.keyboard.press("ArrowUp", delay=HELD) + _wait_for_focus(run, "Red") _wait_for_checked(run, "colors", ["Red"]) +@CONTRACT.step("the arrow keys go round at the ends of a group") +def _arrows_round(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + _wait_for_focus(run, "One") + page.keyboard.press("ArrowUp", delay=HELD) + _wait_for_focus(run, "Three") + _wait_for_checked(run, "pick", ["Three"]) + page.keyboard.press("ArrowDown", delay=HELD) + _wait_for_focus(run, "One") + _wait_for_checked(run, "pick", ["One"]) + + @CONTRACT.step("Space and a click on a label check an item, and say so") def _check(run: Run) -> None: page = run.page diff --git a/packages/reflex-components-ui/parity/ui_parity/samples.py b/packages/reflex-components-ui/parity/ui_parity/samples.py index 8a75b068d42..a566f655bcc 100644 --- a/packages/reflex-components-ui/parity/ui_parity/samples.py +++ b/packages/reflex-components-ui/parity/ui_parity/samples.py @@ -2,8 +2,11 @@ from __future__ import annotations +import json from typing import Any +from playwright.sync_api import TimeoutError as PlaywrightTimeoutError + import reflex as rx # Every accent color, for a sweep of `color_scheme`. @@ -86,3 +89,34 @@ def wait_for_text(page: Any, element: str, text: str) -> None: "([id, text]) => document.getElementById(id).textContent === text", arg=[element, text], ) + + +def wait_for_value( + page: Any, expression: str, expected: Any, timeout: float = 5000 +) -> None: + """Wait until a JavaScript expression of a page has a value. + + A step that waits says what it found when the wait ends without it, + where a timeout alone says nothing of what the component did. + + Args: + page: The page. + expression: The expression: what it evaluates to is compared as JSON. + expected: Its value. + timeout: How long to wait, in milliseconds. + + Raises: + AssertionError: If the expression does not come to have the value, + with the value it has. + """ + try: + page.wait_for_function( + f"expected => JSON.stringify({expression}) === expected", + arg=json.dumps(expected, separators=(",", ":"), ensure_ascii=False), + timeout=timeout, + ) + except PlaywrightTimeoutError: + actual = page.evaluate(expression) + if actual != expected: + msg = f"{expression} is {actual!r}, not {expected!r}" + raise AssertionError(msg) from None diff --git a/tests/units/reflex_components_ui/parity/test_samples.py b/tests/units/reflex_components_ui/parity/test_samples.py new file mode 100644 index 00000000000..f4f210c1161 --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_samples.py @@ -0,0 +1,52 @@ +"""Tests for ui_parity.samples.""" + +from typing import Any + +import pytest +from playwright.sync_api import TimeoutError as PlaywrightTimeoutError +from ui_parity.samples import wait_for_value + + +class _Page: + """A page whose expression has one value, which a wait reaches or not.""" + + def __init__(self, value: Any, reached: bool): + self.value = value + self.reached = reached + self.waited: list[tuple[str, str, float]] = [] + + def wait_for_function(self, expression: str, arg: str, timeout: float) -> None: + self.waited.append((expression, arg, timeout)) + if not self.reached: + msg = "Timeout exceeded." + raise PlaywrightTimeoutError(msg) + + def evaluate(self, expression: str) -> Any: + return self.value + + +def test_wait_for_value_waits_for_the_value_as_json(): + page = _Page(["One", "Two"], reached=True) + wait_for_value(page, "checked()", ["One", "Two"], timeout=250) + assert page.waited == [ + ( + "expected => JSON.stringify(checked()) === expected", + '["One","Two"]', + 250, + ) + ] + + +def test_wait_for_value_says_what_it_found_instead(): + page = _Page(["Three"], reached=False) + with pytest.raises(AssertionError) as error: + wait_for_value(page, "checked()", ["One"]) + assert str(error.value) == "checked() is ['Three'], not ['One']" + + +def test_wait_for_value_takes_a_value_that_arrived_as_the_wait_ended(): + page = _Page(["One"], reached=False) + wait_for_value(page, "checked()", ["One"]) + assert page.waited == [ + ("expected => JSON.stringify(checked()) === expected", '["One"]', 5000) + ] From a98881ee4c1211c4e22256f08b1eee046a20f274 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 10:34:46 +0000 Subject: [PATCH 124/204] Add rx.ui.popover on the popup of the select, and settle the drawer's types The popover is a native popover right after its trigger, which opens it by popovertarget; its close button closes it the same way, so it works with scripts off. components/_popup.py holds what the later popups share: a root that renders nothing, a trigger and a close button that are their children, and the content. popup.js follows a popup bound to state, moves the focus in, closes it when the focus leaves, and says what dismissed it. An id an app gives a popup is no longer renamed. Claude-Session: https://claude.ai/code/session_014AwvTMWjpBRrG7rVgJBZHA --- .../js/src/behaviors/popup.js | 93 +++- .../js/tests/behaviors/listbox.test.js | 2 +- .../js/tests/behaviors/popup.test.js | 203 +++++++- .../news/+wave4-overlays.feature.md | 4 +- .../parity/allowlist.toml | 29 ++ .../parity/ui_parity/components/popover.py | 479 ++++++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../components/_dialog.py | 36 +- .../reflex_components_ui/components/_popup.py | 364 +++++++++++++ .../reflex_components_ui/components/_slot.py | 60 +++ .../reflex_components_ui/components/drawer.py | 10 +- .../components/popover.py | 124 +++++ .../src/reflex_components_ui/styles/drawer.py | 4 +- .../reflex_components_ui/styles/popover.py | 56 ++ pyi_hashes.json | 3 +- .../tests_playwright/test_ui_components.py | 20 + .../components/test_drawer.py | 4 +- .../components/test_popover.py | 329 ++++++++++++ .../reflex_components_ui/test_api_parity.py | 5 + 19 files changed, 1779 insertions(+), 47 deletions(-) create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/popover.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/popover.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py create mode 100644 tests/units/reflex_components_ui/components/test_popover.py diff --git a/packages/reflex-components-ui/js/src/behaviors/popup.js b/packages/reflex-components-ui/js/src/behaviors/popup.js index 9813544a194..9a721120979 100644 --- a/packages/reflex-components-ui/js/src/behaviors/popup.js +++ b/packages/reflex-components-ui/js/src/behaviors/popup.js @@ -35,10 +35,21 @@ export function opener(popup) { * @returns {void} */ export function pair(popup, trigger) { - if (!trigger || popup.hasAttribute("data-rx-popup-paired")) return; + // An id an app gave a popup is its own to keep. + if ( + !trigger || + !popup.id.startsWith("rx-") || + popup.hasAttribute("data-rx-popup-paired") + ) + return; + // What closes the popup from inside it names it too. + const named = [ + trigger, + ...popup.querySelectorAll(`[popovertarget="${popup.id}"]`), + ]; popup.id = `${popup.id || "rx-popup"}-${++ids}`; popup.setAttribute("data-rx-popup-paired", ""); - trigger.setAttribute("popovertarget", popup.id); + for (const element of named) element.setAttribute("popovertarget", popup.id); trigger.setAttribute("aria-controls", popup.id); } @@ -66,3 +77,81 @@ export function popupToggle(event) { } return open; } + +/** + * Keep a popup as its state says: the `ref` of the popover, called again + * whenever the page renders. + * + * @param {HTMLElement | null} popup The popover. + * @param {boolean | null} [open] Whether a popup bound to state is open. + * @returns {void} + */ +export function popupSync(popup, open) { + if (!popup) return; + pair(popup, opener(popup)); + const starts = popup.dataset.defaultOpen === "true"; + delete popup.dataset.defaultOpen; + const wanted = open ?? (starts || null); + if (wanted !== null && wanted !== popup.matches(":popover-open")) { + popup.dataset.rxClosedBy = "state"; + popup.togglePopover(wanted); + } +} + +/** + * Follow a popup that holds controls of its own, as a popover does: its + * `onToggle`, `onKeyDown`, `onClick` and `onBlur`. + * + * The popup takes the focus when it opens, and closes when the focus + * leaves it for anything but what opens it, as in Radix. It says when it + * opens and closes, and what closed it: Escape, the focus, or a pointer + * outside it. + * + * @param {{ type: string, target: EventTarget | null, currentTarget: HTMLElement, newState?: string, key?: string, relatedTarget?: EventTarget | null }} event + * The toggle, the key going down, the press or the focus leaving. + * @param {{ open?: (open: boolean) => void, openAutoFocus?: () => void, closeAutoFocus?: () => void, escape?: () => void, outside?: () => void, focusOutside?: () => void, interact?: () => void } | null} [on] + * What the popup does when it opens, closes or is dismissed. + * @returns {void} + */ +export function popupEvent(event, on) { + const popup = event.currentTarget; + const { type, target } = event; + const data = popup.dataset; + if (type === "keydown") { + if (event.key === "Escape") data.rxClosedBy = "escape"; + } else if (type === "click") { + if ( + target instanceof Element && + target.closest("[popovertargetaction=hide]") + ) + data.rxClosedBy = "close"; + } else if (type === "blur") { + const to = event.relatedTarget; + // A press outside the popup is the browser's to close it by. + if ( + to instanceof Element && + !popup.contains(to) && + to !== opener(popup) && + !to.matches(":active") + ) { + data.rxClosedBy = "focus"; + popup.hidePopover(); + } + } else if (target === popup) { + const open = popupToggle(event); + const by = data.rxClosedBy; + delete data.rxClosedBy; + if (open) { + if (by !== "state") on?.open?.(open); + popup.focus(); + on?.openAutoFocus?.(); + return; + } + if (by === "escape") on?.escape?.(); + if (by === "focus") on?.focusOutside?.(); + if (!by) on?.outside?.(); + if (!by || by === "focus") on?.interact?.(); + if (by !== "state") on?.open?.(open); + on?.closeAutoFocus?.(); + } +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js b/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js index 95d7f3b59fe..b4eca069779 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js @@ -43,7 +43,7 @@ function build({ value = "", disabled = "", attributes = "", - id = "list", + id = "rx-list", } = {}) { const container = document.createElement("div"); container.innerHTML = ` diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js index ce3dd1a2ace..9586d45bed3 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js @@ -2,6 +2,8 @@ // browser that does not place it. import { afterEach, beforeEach, expect, test, vi } from "vitest"; +import { installPopover } from "./popover.js"; + /** * Build a button and the popup it opens. * @@ -83,7 +85,7 @@ test("the popups a loop renders with one id are told apart", async () => { document.body.innerHTML = [1, 2] .map( () => - `
`, + `
`, ) .join(""); const spans = [...document.querySelectorAll("span")]; @@ -107,8 +109,8 @@ test("the popups a loop renders with one id are told apart", async () => { span.querySelector("button")?.getAttribute("aria-controls"), ]), ).toEqual([ - ["list-1", "list-1", "list-1"], - ["list-2", "list-2", "list-2"], + ["rx-list-1", "rx-list-1", "rx-list-1"], + ["rx-list-2", "rx-list-2", "rx-list-2"], ]); expect( opener(/** @type {Element} */ (spans[1].querySelector("[popover]"))), @@ -132,3 +134,198 @@ test("a browser without anchor positioning has the popup placed by a script", as "margin-top: 4px; position: fixed; inset: auto; min-width: 120px; max-height: 454px; left: 40px; top: 132px;", ); }); + +/** + * Build a popover with a control and a button that closes it, after the + * button that opens it. + * + * @param {string} [attributes] The attributes of the popover. + * @returns {Promise<{ api: typeof import("$/reflex-ui/behaviors/popup.js"), trigger: HTMLElement, popup: HTMLElement, seen: string[], on: Record void> }>} + * The script, the two elements, and handlers that keep what they are + * called with. + */ +async function popover(attributes = "") { + installPopover(); + const api = await import("$/reflex-ui/behaviors/popup.js"); + document.body.innerHTML = ` + +
+ + +
+ `; + const popup = /** @type {HTMLElement} */ ( + document.querySelector("[popover]") + ); + /** @type {string[]} */ + const seen = []; + const on = Object.fromEntries( + [ + "open", + "openAutoFocus", + "closeAutoFocus", + "escape", + "outside", + "focusOutside", + "interact", + ].map((name) => [ + name, + (/** @type {boolean | undefined} */ open) => + seen.push(open === undefined ? name : `${name}:${open}`), + ]), + ); + popup.addEventListener("toggle", (event) => + api.popupEvent( + /** @type {{ type: string, target: EventTarget | null, currentTarget: HTMLElement }} */ ( + /** @type {unknown} */ (event) + ), + on, + ), + ); + return { + api, + trigger: /** @type {HTMLElement} */ (document.getElementById("open")), + popup, + seen, + on, + }; +} + +/** + * Send a popover something that happens inside it. + * + * @param {typeof import("$/reflex-ui/behaviors/popup.js")} api The script. + * @param {HTMLElement} popup The popover. + * @param {string} type The type of the event. + * @param {{ target?: string, key?: string, to?: string }} [details] The id + * of the element it happens on, the key, and where the focus goes. + * @returns {void} + */ +function inside(api, popup, type, { target, key, to } = {}) { + api.popupEvent({ + type, + target: target ? document.getElementById(target) : popup, + currentTarget: popup, + key, + relatedTarget: to ? document.getElementById(to) : null, + }); +} + +test("a popover takes the focus when it opens, and says what closed it", async () => { + const { api, popup, trigger, seen } = await popover(); + api.popupSync(popup); + api.popupSync(null); + expect([popup.id, trigger.getAttribute("popovertarget")]).toEqual([ + "rx-panel-1", + "rx-panel-1", + ]); + expect(document.getElementById("close")?.getAttribute("popovertarget")).toBe( + "rx-panel-1", + ); + + popup.showPopover(); + expect(document.activeElement).toBe(popup); + expect(said(trigger)).toEqual(["true", "open"]); + inside(api, popup, "keydown", { target: "field", key: "a" }); + inside(api, popup, "keydown", { target: "field", key: "Escape" }); + popup.hidePopover(); + + popup.showPopover(); + inside(api, popup, "click", { target: "field" }); + inside(api, popup, "click", { target: "close-text" }); + popup.hidePopover(); + + popup.showPopover(); + popup.hidePopover(); + + expect(seen).toEqual([ + "open:true", + "openAutoFocus", + "escape", + "open:false", + "closeAutoFocus", + "open:true", + "openAutoFocus", + "open:false", + "closeAutoFocus", + "open:true", + "openAutoFocus", + "outside", + "interact", + "open:false", + "closeAutoFocus", + ]); +}); + +test("a popover closes when the focus leaves it for the page", async () => { + const { api, popup, seen } = await popover(); + popup.showPopover(); + inside(api, popup, "blur", { target: "field", to: "close" }); + inside(api, popup, "blur", { target: "field", to: "open" }); + inside(api, popup, "blur", { target: "field" }); + expect(popup.matches(":popover-open")).toBe(true); + // A press outside is left to the browser. + const beside = /** @type {HTMLElement} */ (document.getElementById("beside")); + const matches = beside.matches.bind(beside); + beside.matches = (selector) => selector === ":active" || matches(selector); + inside(api, popup, "blur", { target: "field", to: "beside" }); + expect(popup.matches(":popover-open")).toBe(true); + beside.matches = matches; + inside(api, popup, "blur", { target: "field", to: "beside" }); + expect(popup.matches(":popover-open")).toBe(false); + expect(seen).toEqual([ + "open:true", + "openAutoFocus", + "focusOutside", + "interact", + "open:false", + "closeAutoFocus", + ]); +}); + +test("a popover bound to state shows its state, and one that starts open opens once", async () => { + const { api, popup, seen } = await popover('data-default-open="true"'); + api.popupSync(popup); + expect(popup.matches(":popover-open")).toBe(true); + expect(popup.hasAttribute("data-default-open")).toBe(false); + api.popupSync(popup, false); + api.popupSync(popup, false); + expect(popup.matches(":popover-open")).toBe(false); + api.popupSync(popup); + expect(popup.matches(":popover-open")).toBe(false); + api.popupSync(popup, true); + expect(popup.matches(":popover-open")).toBe(true); + expect(seen).toEqual(["openAutoFocus", "closeAutoFocus", "openAutoFocus"]); +}); + +test("a popover without handlers, and the toggle of a popup inside it, change nothing", async () => { + installPopover(); + const api = await import("$/reflex-ui/behaviors/popup.js"); + document.body.innerHTML = `
`; + const popup = /** @type {HTMLElement} */ (document.getElementById("mine")); + api.popupSync(popup); + expect(popup.id).toBe("mine"); + api.popupEvent({ + type: "toggle", + target: popup, + currentTarget: popup, + newState: "open", + }); + expect(document.activeElement).toBe(popup); + api.popupEvent({ + type: "toggle", + target: document.getElementById("inner"), + currentTarget: popup, + newState: "closed", + }); + expect( + said(/** @type {HTMLElement} */ (document.getElementById("open"))), + ).toEqual(["true", "open"]); + api.popupEvent({ + type: "toggle", + target: popup, + currentTarget: popup, + newState: "closed", + }); + api.popupEvent({ type: "click", target: null, currentTarget: popup }); +}); diff --git a/packages/reflex-components-ui/news/+wave4-overlays.feature.md b/packages/reflex-components-ui/news/+wave4-overlays.feature.md index 5519d99e583..509f91bdae4 100644 --- a/packages/reflex-components-ui/news/+wave4-overlays.feature.md +++ b/packages/reflex-components-ui/news/+wave4-overlays.feature.md @@ -1,5 +1,7 @@ -Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog`, `alert_dialog` and `drawer`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog, an alert dialog and a drawer are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. +Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog`, `alert_dialog`, `drawer` and `popover`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog, an alert dialog and a drawer are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. A button whose popup is open has the look Radix Themes gives it (`[data-state='open']`), which `rx.ui.button` did not have. `rx.ui.drawer` slides in from an edge of the page and is closed by Escape, by a press beside its panel and by its close button. It is not dragged, so `snap_points` and the other props that describe the drag of `rx.drawer` do nothing. + +`rx.ui.popover` is a native popover placed beside its trigger by CSS anchor positioning: the browser opens and closes it without JavaScript. It is not modal, and closes when the focus leaves it. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 3228d3a18d2..af8481e3e80 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -409,3 +409,32 @@ reason = "With rx.drawer open, Tab goes on through the page behind it. rx.ui.dra component = "drawer" step = "is dragged out of the page by its panel" reason = "rx.ui.drawer is not dragged: it is closed by Escape, by a press beside its panel and by its close button, and `snap_points`, `fade_from_index`, `handle_only`, `close_threshold`, `scroll_lock_timeout`, `prevent_scroll_restoration` and `should_scale_background`, which all describe the drag of rx.drawer, have nothing to say. The handle is drawn and does nothing." + +[[contract]] +component = "popover" +step = "what it holds is in the server render" +system = "rx" +reason = "rx.popover renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.popover holds is in the page from the start, in a popover that is closed, and it keeps its state between two openings." + +[[contract]] +component = "popover" +step = "opens and closes with JavaScript disabled" +system = "rx" +reason = "rx.popover is opened by JavaScript: until it has run, a press on its trigger does nothing. rx.ui.popover is a native popover of its trigger, which the browser opens, places and closes, from its close button, on Escape and on a press outside, with or without JavaScript." + +[[contract]] +component = "popover" +step = "its trigger names the popover it opens by the id it is given" +system = "rx" +reason = "The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link, and it has none while the popover is closed. The trigger of rx.ui.popover names the popover by the id it was given." + +[[contract]] +component = "popover" +step = "Tab stays inside an open popover" +reason = "rx.ui.popover is a native popover, which is not modal: it comes right after its trigger in the order of the page, Tab moves through what it holds and on to what follows the trigger, and the popover closes when the focus leaves it. rx.popover keeps Tab going round inside it until Escape. `modal` has nothing to say: the page beside a native popover stays as it is." + +[[contract]] +component = "popover" +step = "the dark appearance of a theme around a popover reaches it" +system = "rx" +reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a popover included. rx.ui.theme does, and a popover declared inside a dark rx.ui.theme is dark." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/popover.py b/packages/reflex-components-ui/parity/ui_parity/components/popover.py new file mode 100644 index 00000000000..8711bcaccf9 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/popover.py @@ -0,0 +1,479 @@ +"""The popover: closed and open in every size, on each side of its trigger, and how it closes.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.samples import PARAGRAPH, wait_for_text + +SIZES = ["1", "2", "3", "4"] +SIDES = ["top", "right", "bottom", "left"] +ALIGNS = ["start", "center", "end"] +OPEN = "open" +# A popup that is open, in either system. +SHOWN = "[data-radix-popper-content-wrapper], :popover-open" + + +def _popover(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a popover and the button that opens it. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the content. ``variant`` is the one of the + button that opens it, ``long`` asks for more than the page has + room for, and ``themed`` for a theme of another accent and + radius around the popover. + + Returns: + The popover, with room around its trigger for it to open on any + side. + """ + props = dict(props) + popover = namespace.popover + long, themed = props.pop("long", False), props.pop("themed", False) + if long: + # Within the page in whichever column its frame is. + props["width"] = "260px" + if "align" in props or "side" in props: + # On the pixel grid wherever it is along its trigger: Radix rounds + # where it puts a popover, and the browser does not. + props["width"] = "200px" + shown = popover.root( + popover.trigger( + namespace.button("Open", variant=props.pop("variant", "soft"), width="80px") + ), + popover.content( + namespace.text("Dimensions", size="2", weight="bold"), + *( + rx.el.p(f"{number}. {PARAGRAPH}") + for number in range(1, 30 if long else 1) + ), + popover.close(namespace.button("Done", size="1")), + **props, + ), + ) + if themed: + shown = namespace.theme(shown, accent_color="ruby", radius="full") + return rx.el.div(shown, style={"padding": "120px 0 0 230px"}) + + +def open_popup(page: Page, target: Locator, point: Point) -> None: + """Open a popup from its trigger, and wait for it. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + target.click() + page.locator(SHOWN).first.wait_for() + # The pointer is not left on the trigger. + page.mouse.move(1, 1) + + +def close_popup(page: Page, target: Locator, point: Point) -> None: + """Close the open popup, and take the focus off whatever has it. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + page.keyboard.press("Escape") + page.locator(SHOWN).first.wait_for(state="detached") + page.evaluate("document.activeElement.blur()") + + +OPENED = State(enter=open_popup, leave=close_popup, matches="[data-state='open']") + +MATRIX = Matrix( + component="popover", + render=_popover, + sweep={ + "size": SIZES, + "variant": ["solid", "classic", "surface", "ghost", "outline"], + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE, OPEN], + }, + groups=[ + {"size": SIZES, "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"side": SIDES, "align": ALIGNS, "state": [OPEN]}, + {"side": SIDES, "side_offset": [0, 20], "state": [OPEN]}, + {"align": ["start", "end"], "align_offset": [12], "state": [OPEN]}, + {"themed": [True], "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"long": [True], "state": [OPEN]}, + { + "variant": ["solid", "classic", "surface", "ghost", "outline"], + "state": [OPEN], + }, + ], + stage=(560, 340), + crop="stage", + target="button", + states={OPEN: OPENED}, + # Not held to zero. At a threshold of zero 40 of the 45 cells are equal + # pixel for pixel, and the others differ by one pixel of 190400 on the + # edge of the trigger, whose gradient or ring the browser dithers by + # where the button is on the page: at the default threshold 3 cells do. + tolerance=0.00001, +) + + +class PopoverState(rx.State): + """What the popovers of the contract are bound to.""" + + shown: rx.Field[bool] = rx.field(False) + seen: rx.Field[list[str]] = rx.field(default_factory=list) + clicks: rx.Field[int] = rx.field(0) + + @rx.event + def set_shown(self, value: bool): + """Follow the bound popover. + + Args: + value: Whether it is open. + """ + self.shown = value + + @rx.event + def see_open(self, value: bool): + """Keep whether a popover opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def see(self, what: str): + """Keep what happened to a popover. + + Args: + what: The event. + """ + self.seen.append(what) + + @rx.event + def save(self): + """Close the bound popover from the backend.""" + self.shown = False + + @rx.event + def click(self): + """Count a click on the button beside the popovers.""" + self.clicks += 1 + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + A popover that says what happens to it, one bound to state, one in + a dialog and one in a theme of its own. + """ + popover, dialog, button = namespace.popover, namespace.dialog, namespace.button + return namespace.box( + popover.root( + popover.trigger(button("Open", id="open")), + popover.content( + rx.el.input(id="field"), + popover.close(button("Close", id="close")), + id="panel", + on_open_auto_focus=PopoverState.see("focus-in"), + on_close_auto_focus=PopoverState.see("focus-out"), + on_escape_key_down=PopoverState.see("escape"), + on_pointer_down_outside=PopoverState.see("outside"), + on_focus_outside=PopoverState.see("focus-outside"), + on_interact_outside=PopoverState.see("interact"), + ), + on_open_change=PopoverState.see_open, + ), + rx.el.button("Beside", id="beside", on_click=PopoverState.click), + popover.root( + popover.trigger(button("Bound", id="bound-open")), + popover.content( + button("Save", id="save", on_click=PopoverState.save), + id="bound-panel", + ), + open=PopoverState.shown, + on_open_change=PopoverState.set_shown, + ), + rx.el.button("Show", id="show", on_click=PopoverState.set_shown(True)), + dialog.root( + dialog.trigger(button("Dialog", id="dialog-open")), + dialog.content( + dialog.title("With a popover"), + popover.root( + popover.trigger(button("Inside", id="inside-open")), + popover.content( + popover.close(button("Shut", id="inside-close")), + id="inside-panel", + ), + ), + id="dialog-panel", + ), + ), + namespace.theme( + popover.root( + popover.trigger(button("Themed", id="themed-open")), + popover.content( + popover.close(button("Fine", id="themed-close")), + id="themed-panel", + ), + ), + accent_color="ruby", + appearance="dark", + ), + rx.el.span(PopoverState.seen.to_string(), id="seen"), + rx.el.span(PopoverState.shown.to_string(), id="shown"), + rx.el.span(PopoverState.clicks.to_string(), id="clicks"), + ) + + +CONTRACT = Contract(component="popover", render=_contract) + + +def _open(run: Run, trigger: str = "open", panel: str = "panel") -> None: + """Open a popover from its trigger, and wait until the focus is in it. + + Args: + run: The run, on a page. + trigger: The id of the trigger. + panel: The id of the popover. + """ + run.page.locator(f"#{trigger}").click() + run.page.locator(f"#{panel}").wait_for() + run.page.wait_for_function( + "id => document.getElementById(id).contains(document.activeElement)", + arg=panel, + ) + + +def _wait_for_closed(run: Run, panel: str = "panel") -> None: + """Wait until a popover is closed. + + Args: + run: The run, on a page. + panel: The id of the popover. + """ + run.page.locator(f"#{panel}").wait_for(state="hidden") + + +def _wait_for_focus(run: Run, element: str) -> None: + """Wait until an element has the focus. + + Args: + run: The run, on a page. + element: Its id. + """ + run.page.wait_for_function("id => document.activeElement.id === id", arg=element) + + +@CONTRACT.step("its trigger is a button in the server render", on=SERVER) +def _server_render(run: Run) -> None: + trigger = run.server.element("open") + assert (trigger.tag, trigger.text, trigger.attributes["aria-haspopup"]) == ( + "button", + "Open", + "dialog", + ) + + +@CONTRACT.step("what it holds is in the server render", on=SERVER) +def _server_content(run: Run) -> None: + assert run.server.element("panel").text == "Close" + + +@CONTRACT.step("opens and closes with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + page = run.page + page.set_default_timeout(3000) + assert not page.locator("#panel").is_visible() + page.locator("#open").click() + page.wait_for_timeout(300) + assert page.locator("#panel").is_visible() + page.locator("#close").click() + page.wait_for_timeout(300) + assert not page.locator("#panel").is_visible() + page.locator("#open").click() + page.wait_for_timeout(300) + page.keyboard.press("Escape") + page.wait_for_timeout(300) + assert not page.locator("#panel").is_visible() + + +@CONTRACT.step("is a dialog its trigger says it opens") +def _role(run: Run) -> None: + page = run.page + trigger = page.locator("#open") + assert trigger.get_attribute("aria-expanded") == "false" + assert trigger.get_attribute("data-state") == "closed" + _open(run) + assert trigger.get_attribute("aria-expanded") == "true" + assert trigger.get_attribute("data-state") == "open" + assert page.get_by_role("dialog").count() == 1 + assert page.get_by_role("dialog").get_attribute("id") == "panel" + + +@CONTRACT.step("its trigger names the popover it opens by the id it is given") +def _controls(run: Run) -> None: + assert run.page.locator("#open").get_attribute("aria-controls") == "panel" + + +@CONTRACT.step("opens beside its trigger, at its start") +def _placed(run: Run) -> None: + page = run.page + _open(run) + page.wait_for_timeout(400) + trigger, panel = ( + page.locator(f"#{element}").bounding_box() for element in ("open", "panel") + ) + assert trigger is not None + assert panel is not None + assert abs(panel["x"] - trigger["x"]) < 1 + assert abs(panel["y"] - (trigger["y"] + trigger["height"] + 8)) < 1 + + +@CONTRACT.step("the focus moves into the popover, and back to its trigger") +def _focus(run: Run) -> None: + page = run.page + page.locator("#open").focus() + page.keyboard.press("Enter") + page.locator("#panel").wait_for() + page.wait_for_function( + "document.getElementById('panel').contains(document.activeElement)" + ) + page.keyboard.press("Escape") + _wait_for_closed(run) + _wait_for_focus(run, "open") + page.keyboard.press("Space") + page.locator("#panel").wait_for() + page.locator("#close").click() + _wait_for_closed(run) + _wait_for_focus(run, "open") + + +@CONTRACT.step("Tab stays inside an open popover") +def _tab(run: Run) -> None: + page = run.page + _open(run) + page.locator("#field").focus() + stops = [] + for _ in range(4): + page.keyboard.press("Tab") + stops.append(page.evaluate("document.activeElement.id")) + assert stops == ["close", "field", "close", "field"] + + +@CONTRACT.step("the focus leaving it closes it, and says so") +def _focus_outside(run: Run) -> None: + page = run.page + _open(run) + page.locator("#beside").focus() + _wait_for_closed(run) + wait_for_text( + page, + "seen", + '["open","focus-in","focus-outside","interact","closed","focus-out"]', + ) + + +@CONTRACT.step("Escape closes it, and says so") +def _escape(run: Run) -> None: + page = run.page + _open(run) + wait_for_text(page, "seen", '["open","focus-in"]') + page.keyboard.press("Escape") + _wait_for_closed(run) + wait_for_text(page, "seen", '["open","focus-in","escape","closed","focus-out"]') + + +@CONTRACT.step("a press outside closes it, and reaches the page") +def _outside(run: Run) -> None: + page = run.page + _open(run) + page.locator("#panel").click(position={"x": 4, "y": 4}) + page.wait_for_timeout(200) + assert page.locator("#panel").is_visible() + page.locator("#beside").click() + _wait_for_closed(run) + wait_for_text(page, "clicks", "1") + wait_for_text( + page, "seen", '["open","focus-in","outside","interact","closed","focus-out"]' + ) + + +@CONTRACT.step("its close button closes it, and says nothing of a dismissal") +def _close(run: Run) -> None: + page = run.page + _open(run) + page.locator("#close").click() + _wait_for_closed(run) + wait_for_text(page, "seen", '["open","focus-in","closed","focus-out"]') + + +@CONTRACT.step("a popover bound to state follows it, and is closed from the backend") +def _bound(run: Run) -> None: + page = run.page + page.locator("#show").click() + page.locator("#bound-panel").wait_for() + wait_for_text(page, "shown", "true") + page.locator("#save").click() + _wait_for_closed(run, "bound-panel") + wait_for_text(page, "shown", "false") + _open(run, "bound-open", "bound-panel") + wait_for_text(page, "shown", "true") + page.keyboard.press("Escape") + _wait_for_closed(run, "bound-panel") + wait_for_text(page, "shown", "false") + + +@CONTRACT.step( + "a popover in a dialog opens over it, and Escape closes the popover alone" +) +def _in_dialog(run: Run) -> None: + page = run.page + page.locator("#dialog-open").click() + page.locator("#dialog-panel").wait_for() + _open(run, "inside-open", "inside-panel") + page.keyboard.press("Escape") + _wait_for_closed(run, "inside-panel") + page.locator("#dialog-panel").wait_for() + _wait_for_focus(run, "inside-open") + _open(run, "inside-open", "inside-panel") + page.locator("#inside-close").click() + _wait_for_closed(run, "inside-panel") + page.locator("#dialog-panel").wait_for() + page.keyboard.press("Escape") + page.locator("#dialog-panel").wait_for(state="hidden") + + +@CONTRACT.step("the accent of a theme around a popover reaches what it holds") +def _themed(run: Run) -> None: + page = run.page + _open(run, "themed-open", "themed-panel") + page.mouse.move(1, 1) + page.wait_for_timeout(400) + assert page.locator("#themed-close").evaluate( + "element => getComputedStyle(element).backgroundColor" + ) == ("rgb(229, 70, 102)") + + +@CONTRACT.step("the dark appearance of a theme around a popover reaches it") +def _themed_dark(run: Run) -> None: + page = run.page + _open(run, "themed-open", "themed-panel") + page.wait_for_timeout(400) + assert page.locator("#themed-panel").evaluate( + "element => getComputedStyle(element).backgroundColor" + ) == ("rgb(25, 25, 25)") 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 542d73615dc..7a8cf596e70 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -24,6 +24,7 @@ "components.form": ["form"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], + "components.popover": ["popover"], "components.progress": ["progress"], "components.radio_cards": ["radio_cards"], "components.radio_group": ["radio", "radio_group"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py index 2752841a259..655af942cb5 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py @@ -2,7 +2,6 @@ from __future__ import annotations -import dataclasses import itertools from collections.abc import Iterator from typing import Any, ClassVar @@ -14,8 +13,8 @@ from reflex_components_ui.base import Part, UIComponent from reflex_components_ui.components._group import descendants from reflex_components_ui.components._script import handlers, listen, script -from reflex_components_ui.layout.flex import Flex -from reflex_components_ui.style import ComponentStyles, StyleError +from reflex_components_ui.components._slot import become_child, held +from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.dialog import ( DIALOG, DIALOG_DESCRIPTION, @@ -190,11 +189,7 @@ def create(cls, *children: Any, **props: Any) -> Component: Returns: The component. """ - for child in children: - if "on_click" in getattr(child, "event_triggers", {}): - children = (Flex.create(*children),) - break - return super().create(*children, **props) + return super().create(*held(children), **props) def _post_init(self, *args, **kwargs): """Initialize the part, rendered as its only child. @@ -202,36 +197,15 @@ def _post_init(self, *args, **kwargs): Args: *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. - - Raises: - StyleError: If the part does not have exactly one child that is - an element. """ super()._post_init(*args, **kwargs) if "as_child" in self.get_fields(): # The part says itself whether it is its child, and is a button # around its children otherwise. - if not self._as_child: + if not self._as_child: # pyright: ignore[reportAttributeAccessIssue] self.tag = "button" return - children = self.children - if ( - len(children) != 1 - or not isinstance(children[0], Component) - or type(children[0]).render not in (Component.render, UIComponent.render) - ): - name = self._display_name() # pyright: ignore[reportAttributeAccessIssue] - msg = ( - f"{name}: it is rendered as its child, so it needs exactly one " - "child that is an element, such as a button." - ) - raise StyleError(msg) - self._as_child = True - # The child has to stay the child: a compile would otherwise move - # one that is bound to state into a component of its own. - self._memoization_mode = dataclasses.replace( - self._memoization_mode, recursive=False - ) + become_child(self) def _join( self, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py new file mode 100644 index 00000000000..c0c0aa0f6dc --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py @@ -0,0 +1,364 @@ +"""What the popups share: a native popover, and what opens and closes it.""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterator +from typing import Any, ClassVar + +from reflex_base.components.component import Component +from reflex_base.components.tags import CommonTag +from reflex_base.vars.base import LiteralVar, Var, VarData + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._group import descendants, literal +from reflex_components_ui.components._script import handlers, listen, script +from reflex_components_ui.components._slot import become_child, held +from reflex_components_ui.props import style_before +from reflex_components_ui.styles.popup import OFFSET, SHIFT + +# Numbers the popups of an app: what opens a popup names it by its id. +_ids = itertools.count(1) + +# The events of a popup as they are rendered, by the name the script calls +# each under. +_EVENTS = { + "onOpenChange": "open", + "onOpenAutoFocus": "openAutoFocus", + "onCloseAutoFocus": "closeAutoFocus", + "onEscapeKeyDown": "escape", + "onPointerDownOutside": "outside", + "onFocusOutside": "focusOutside", + "onInteractOutside": "interact", +} + + +def pixels(amount: Any) -> Any: + """Write a number of pixels as a length. + + Args: + amount: The number, or a Var of it. + + Returns: + The length: a string when the number is known while compiling. + """ + amount = literal(amount) + if not isinstance(amount, Var): + return f"{amount}px" + return Var( + f'(({amount!s}) + "px")', _var_type=str, _var_data=amount._get_all_var_data() + ) + + +def offsets(props: dict[str, Any]) -> None: + """Put how far a popup is from its anchor before its other styles. + + Args: + props: The props a popup is created with, changed in place: its + ``side_offset`` and its ``align_offset`` become custom + properties the placement of the popup reads. + """ + distances = { + name: pixels(props[prop]) + for prop, name in (("side_offset", OFFSET), ("align_offset", SHIFT)) + if props.get(prop) is not None + } + if distances: + style_before(props, distances) + + +class PopupRoot(UIComponent): + """The root of a popup, which renders nothing of its own. + + Radix hands the parts of a popup its props through a context. Here the + root finds its parts while compiling, and gives them what they render. + """ + + library = "react" + + tag = "Fragment" + + _is_tag_in_global_scope: ClassVar[bool] = False + + # What the ids of the popups of the component start with. + _prefix: ClassVar[str] = "rx-popup" + + def _post_init(self, *args, **kwargs): + """Initialize the popup, and give its parts what they share. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + name: Any = f"{self._prefix}-{next(_ids)}" + on_open_change = self.event_triggers.pop("on_open_change", None) + parts = list(descendants(self, PopupPart, PopupRoot)) + for part in parts: + if isinstance(part, PopupContent) and part.id is not None: + name = part.id + for part in parts: + part._join(self, name, on_open_change) + + def _exclude_props(self) -> list[str]: + """Keep the props that are the ones of the popup off the root. + + Returns: + Every prop: the root renders no element. + """ + return [*super()._exclude_props(), *self.get_fields()] + + +class PopupPart(UIComponent): + """A part of a popup, which its root gives a name.""" + + def _post_init(self, *args, **kwargs): + """Initialize the part, as one outside a popup. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # The attributes the popup gives the part. + self._popup: dict[str, Any] = {} + super()._post_init(*args, **kwargs) + + def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: + """Take from a popup what Radix hands its parts through a context. + + Args: + root: The popup the part is in. + name: The id of the popup. + on_open_change: What the popup does when it opens or closes. + """ + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the part, those its popup gives it 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) + for value in self._popup.values(): + if isinstance(value, Var): + yield value + + +class PopupTrigger(PopupPart): + """What opens a popup: its child, a button the browser opens the popup from.""" + + # The child keeps its own styles. + _merges_slot: ClassVar[bool] = False + + # What the trigger says it opens, to assistive technology. + _haspopup: ClassVar[str] = "dialog" + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a part that is rendered as its child. + + Args: + *children: The child: one element. + **props: The properties of the component. + + Returns: + The component. + """ + return super().create(*held(children), **props) + + def _post_init(self, *args, **kwargs): + """Initialize the part, rendered as its only child. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + become_child(self) + + def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: + """Take the id of the popup the trigger opens. + + Args: + root: The popup the trigger is in. + name: The id of the popup. + on_open_change: What the popup does when it opens or closes. + """ + self._popup = {"popovertarget": name, "aria-controls": name} + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, which opens its popup without a script, + with the state Radix gives what opens a popup. + """ + return ( + super() + ._render(props) + .add_props(**{ + "aria-haspopup": self._haspopup, + "aria-expanded": False, + "data-state": "closed", + **self._popup, + }) + ) + + +class PopupClose(PopupTrigger): + """What closes a popup from inside it: its child, a button.""" + + def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: + """Take the id of the popup the button closes. + + Args: + root: The popup the button is in. + name: The id of the popup. + on_open_change: What the popup does when it opens or closes. + """ + self._popup = {"popovertarget": name, "popovertargetaction": "hide"} + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the button. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, which closes the popup without a script. + """ + return UIComponent._render(self, props).add_props(**self._popup) + + +class PopupContent(PopupPart): + """A native popover placed beside what opens it.""" + + tag = "div" + + # The role of the popup. + _role: ClassVar[str | None] = "dialog" + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a popup. + + Args: + *children: What the popup holds. + **props: The properties of the component. + + Returns: + The popup, as far from its anchor as it is asked to be. + """ + offsets(props) + return super().create(*children, **props) + + def _post_init(self, *args, **kwargs): + """Initialize the popup, as one that is not bound to state. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # Whether the popup is open, when its state says. + self._open: Var | None = None + super()._post_init(*args, **kwargs) + + def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: + """Take the name of the popup, and whether it is open. + + Args: + root: The popup the element is in. + name: The id of the popup. + on_open_change: What the popup does when it opens or closes. + """ + if self.id is None: + self._popup["id"] = name + self._open = getattr(root, "open", None) + default_open = getattr(root, "default_open", None) + if default_open is not None: + self._popup["data-default-open"] = default_open + if on_open_change is not None: + self.event_triggers["on_open_change"] = on_open_change + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the popup, its script 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 script("popup", "popupSync") + yield script("popup", "popupEvent") + if self._open is not None: + yield self._open + + def _exclude_props(self) -> list[str]: + """Keep the props that say where the popup goes off the element. + + Returns: + The props read as styles, the ones a style is made from, and + the ones the placement of the browser has no use for. + """ + return [ + *super()._exclude_props(), + "side_offset", + "align_offset", + "avoid_collisions", + "collision_padding", + "sticky", + "hide_when_detached", + "force_mount", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the popup. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a popover the browser opens and closes, which says so + to its script, and through it to the events. + """ + tag, on = handlers(super()._render(props), _EVENTS) + bound = LiteralVar.create(self._open) + sync = script("popup", "popupSync") + tag = tag.add_props(**{ + "popover": "auto", + "role": self._role, + "tabIndex": -1, + "data-rx-popup": "", + **self._popup, + # Called whenever the page renders: a popup bound to state takes + # whether it is open from there. + "ref": Var( + f"((popup) => popupSync(popup, {bound!s}))", + _var_data=VarData.merge( + sync._get_all_var_data(), bound._get_all_var_data() + ), + ), + }) + return listen( + tag, + script("popup", "popupEvent"), + "onToggle", + "onKeyDown", + "onClick", + "onBlur", + arguments=() if on is None else (on,), + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py new file mode 100644 index 00000000000..d4bccb1dccd --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py @@ -0,0 +1,60 @@ +"""What the parts that are rendered as their child share: a trigger, a close button.""" + +from __future__ import annotations + +import dataclasses +from typing import Any + +from reflex_base.components.component import Component + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.layout.flex import Flex +from reflex_components_ui.style import StyleError + + +def held(children: tuple[Any, ...]) -> tuple[Any, ...]: + """Get the children a part that acts on a press is created with. + + Such a part acts on a press, and so does a child with a handler of its + own for one: that child is put in a flex container, which is then the + part, as in the Radix components. + + Args: + children: The children the part is given. + + Returns: + The children, or the flex container around them. + """ + for child in children: + if "on_click" in getattr(child, "event_triggers", {}): + return (Flex.create(*children),) + return children + + +def become_child(part: UIComponent) -> None: + """Have a part render as its only child. + + Args: + part: The part, once it is initialized. + + Raises: + StyleError: If the part does not have exactly one child that is an + element. + """ + children = part.children + if ( + len(children) != 1 + or not isinstance(children[0], Component) + or type(children[0]).render not in (Component.render, UIComponent.render) + ): + msg = ( + f"{type(part)._display_name()}: it is rendered as its child, so it " + "needs exactly one child that is an element, such as a button." + ) + raise StyleError(msg) + part._as_child = True + # The child has to stay the child: a compile would otherwise move one + # that is bound to state into a component of its own. + part._memoization_mode = dataclasses.replace( + part._memoization_mode, recursive=False + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py index 20938fb055b..e540ea27031 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py @@ -187,7 +187,7 @@ def _join( named: What names and describes the drawer, by the attribute. on_open_change: What the drawer does when it opens or closes. """ - super()._join(root, name, named, on_open_change) + super()._join(root, name, named, on_open_change) # pyright: ignore[reportAttributeAccessIssue] if literal(getattr(root, "modal", None)) is not None: # A drawer that may not be modal is opened by its script alone. self._dialog = {} @@ -205,7 +205,7 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: state Radix gives what opens a dialog. """ tag = super()._render(props) - if not self._as_child: + if not self._as_child: # pyright: ignore[reportAttributeAccessIssue] tag = tag.add_props(type="button") if self._command == "close": return tag @@ -290,15 +290,15 @@ def _join( named: What names and describes the drawer, by the attribute. on_open_change: What the drawer does when it opens or closes. """ - super()._join(root, name, named, on_open_change) + super()._join(root, name, named, on_open_change) # pyright: ignore[reportAttributeAccessIssue] self._direction = getattr(root, "direction", None) modeless = _is_off(getattr(root, "modal", None)) self._modal = choose(modeless, "false", "true") if modeless is not False: - self._dialog["data-modal"] = choose(modeless, "false", None) + self._dialog["data-modal"] = choose(modeless, "false", None) # pyright: ignore[reportAttributeAccessIssue] kept = _is_off(getattr(root, "dismissible", None)) if kept is not False: - self._dialog["data-rx-keep"] = choose(kept, "all", None) + self._dialog["data-rx-keep"] = choose(kept, "all", None) # pyright: ignore[reportAttributeAccessIssue] for part in self.children: if isinstance(part, DrawerContent): part._direction = self._direction diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py b/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py new file mode 100644 index 00000000000..e88d8c35406 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py @@ -0,0 +1,124 @@ +"""A popover: a native ``popover`` beside the button that opens it.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.components._popup import ( + PopupClose, + PopupContent, + PopupRoot, + PopupTrigger, +) +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.popover import POPOVER_CONTENT + + +class PopoverRoot(PopupRoot): + """Floating element for displaying rich content, triggered by a button.""" + + _prefix: ClassVar[str] = "rx-popover" + + open: Var[bool] = field(doc="The controlled open state of the popover.") + + modal: Var[bool] = field( + doc="The modality of the popover. When set to true, interaction with outside elements will be disabled and only popover content will be visible to screen readers." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + default_open: Var[bool] = field( + doc="The open state of the popover when it is initially rendered. Use when you do not need to control its open state." + ) + + +class PopoverTrigger(PopupTrigger): + """Wraps the control that will open the popover.""" + + +class PopoverContent(PopupContent, elements.Div): + """Contains content to be rendered in the open popover.""" + + styles: ClassVar[ComponentStyles] = POPOVER_CONTENT + + size: Var[Responsive[Literal["1", "2", "3", "4"]]] = field( + doc='Size of the button: "1" | "2" | "3" | "4"' + ) + + side: Var[Literal["top", "right", "bottom", "left"]] = field( + doc="The preferred side of the anchor to render against when open. Will be reversed when collisions occur and avoidCollisions is enabled." + ) + + side_offset: Var[int] = field(doc="The distance in pixels from the anchor.") + + align: Var[Literal["start", "center", "end"]] = field( + doc="The preferred alignment against the anchor. May change when collisions occur." + ) + + align_offset: Var[int] = field( + doc="The vertical distance in pixels from the anchor." + ) + + avoid_collisions: Var[bool] = field( + doc="When true, overrides the side andalign preferences to prevent collisions with boundary edges." + ) + + collision_padding: Var[float | int | dict[str, float | int]] = field( + doc='The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { "top": 20, "left": 20 }. Defaults to 0.' + ) + + sticky: Var[Literal["partial", "always"]] = field( + doc='The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".' + ) + + hide_when_detached: Var[bool] = field( + doc="Whether to hide the content when the trigger becomes fully occluded. Defaults to False." + ) + + on_open_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is opened." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the dialog." + ) + + on_focus_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when focus moves outside the dialog." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer interacts outside the dialog." + ) + + +class PopoverClose(PopupClose): + """Wraps the control that will close the popover.""" + + +class Popover(ComponentNamespace): + """Floating element for displaying rich content, triggered by a button.""" + + root = staticmethod(PopoverRoot.create) + trigger = staticmethod(PopoverTrigger.create) + content = staticmethod(PopoverContent.create) + close = staticmethod(PopoverClose.create) + + +popover = Popover() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py index fd28553bb33..a1a985f53b7 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py @@ -93,7 +93,9 @@ }, }), "variants": { - "_direction": {side: {"_after": beyond} for side, beyond in _BEYOND.items()}, + "_direction": { + side: unchecked({"_after": beyond}) for side, beyond in _BEYOND.items() + }, }, "defaults": {"_direction": "bottom"}, } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py new file mode 100644 index 00000000000..97342f76282 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py @@ -0,0 +1,56 @@ +"""The look of a popover: a panel beside what opens it.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.popup import POPUP, placements + +_PADDING = "--popover-content-padding" + + +def _size(padding: str, radius: str) -> dict[str, Any]: + """Make the styles of a popover of one size. + + Args: + padding: The room around what the popover holds. + radius: The radius of its corners. + + Returns: + The styles. + """ + return {_PADDING: padding, "border_radius": radius} + + +POPOVER_CONTENT: ComponentStyles = { + "base": unchecked({ + **POPUP, + # The text of the page around it, not the one of a native popover. + "color": "inherit", + "background_color": tokens.color.panel_solid, + "box_shadow": tokens.shadow[5], + # At least as wide as what opens it, and no wider than the page. + "min_width": "anchor-size(width)", + "max_width": "min(480px, calc(100vw - 20px))", + "outline_style": "none", + "overflow": "auto", + "--inset-padding-top": f"var({_PADDING})", + "--inset-padding-right": f"var({_PADDING})", + "--inset-padding-bottom": f"var({_PADDING})", + "--inset-padding-left": f"var({_PADDING})", + "padding": f"var({_PADDING})", + "box_sizing": "border-box", + }), + "variants": { + "size": { + "1": unchecked(_size(tokens.space[3], tokens.radius[4])), + "2": unchecked(_size(tokens.space[4], tokens.radius[4])), + "3": unchecked(_size(tokens.space[5], tokens.radius[5])), + "4": unchecked(_size(tokens.space[6], tokens.radius[5])), + }, + }, + "defaults": {"size": "2", "side": "bottom", "align": "start"}, + "compound": placements("8px"), +} diff --git a/pyi_hashes.json b/pyi_hashes.json index 5a624c2b486..29e0f15ab16 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,7 +118,7 @@ "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": "3baaa214d298bb98db3eae02bb2911e4", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "9a1bdbb5949308693e509c528a2d654a", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "7687d1b67f180df8c3c1b1a69610a3f0", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "0d7b27ab1cb51ac891a31ed97f2f5567", @@ -136,6 +136,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.pyi": "63dc6c987c53e017e217e60f4686c4b9", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "28f5633fbda932ee598108e9d5a52e58", + "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "cdaeaac954b4ff1100878d46b5649143", "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index dd14780dfff..d87887b4150 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -866,6 +866,18 @@ def overlays(): ), ), ), + # A popover for each row of a list: each trigger opens its own. + rx.foreach( + ["cut", "dye"], + lambda name: rx.ui.popover.root( + rx.ui.popover.trigger(rx.ui.button("About ", name)), + rx.ui.popover.content( + "All about ", + name, + rx.ui.popover.close(rx.ui.button("Got it")), + ), + ), + ), rx.el.span(rx.cond(rx.State.is_hydrated, "ready", "loading"), id="ready"), ) @@ -1894,6 +1906,14 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): expect(page.get_by_role("dialog")).to_have_count(0) expect(page.get_by_role("button", name="bob")).to_be_focused() + # The popovers of a list share the id they are rendered with: the script + # of a popup tells them apart, and each close button closes its own. + page.get_by_role("button", name="About dye").click() + shown = page.locator(":popover-open") + expect(shown).to_have_text("All about dyeGot it") + shown.get_by_role("button", name="Got it").click() + expect(page.locator(":popover-open")).to_have_count(0) + # The panel of the selected tab alone is shown, whatever display an app # gives the panels. first, second = page.locator("#first-panel"), page.locator("#second-panel") diff --git a/tests/units/reflex_components_ui/components/test_drawer.py b/tests/units/reflex_components_ui/components/test_drawer.py index d345e264026..aca4a9f36af 100644 --- a/tests/units/reflex_components_ui/components/test_drawer.py +++ b/tests/units/reflex_components_ui/components/test_drawer.py @@ -36,7 +36,7 @@ def test_drawer( ) ), direction="left", - on_animation_end=rx.console_log, + on_animation_end=rx.console_log("moved"), ) assert component.render() == { "name": '"div"', @@ -78,7 +78,7 @@ def test_drawer( 'id:"rx-dialog-1"', "onCancel:dialogEvent", "onClose:dialogEvent", - 'onTransitionEnd:((event) => event.propertyName === "transform" && event.target.parentElement === event.currentTarget && (((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"](_ev_0))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))))(event.currentTarget.open))', + 'onTransitionEnd:((event) => event.propertyName === "transform" && event.target.parentElement === event.currentTarget && (((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("moved"))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))))(event.currentTarget.open))', "ref:((dialog) => dialogSync(dialog, null, null))", ], "children": [ diff --git a/tests/units/reflex_components_ui/components/test_popover.py b/tests/units/reflex_components_ui/components/test_popover.py new file mode 100644 index 00000000000..daa98542c0a --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_popover.py @@ -0,0 +1,329 @@ +"""Tests for reflex_components_ui.components.popover.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import _popup +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the popups of each test from one.""" + monkeypatch.setattr(_popup, "_ids", itertools.count(1)) + + +def test_popover( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A popover is a native popover right after its trigger, which the browser opens it from; the root is nothing in the page, and the close button closes the popover without a script.""" + component = rx.ui.popover.root( + rx.ui.popover.trigger(rx.el.button("Open", id="open")), + rx.ui.popover.content( + "Inside", + rx.ui.popover.close(rx.el.button("Close")), + size="1", + side="top", + align="end", + side_offset=4, + align_offset=2, + collision_padding=20, + avoid_collisions=False, + max_width="300px", + ), + default_open=True, + modal=True, + ) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"rx-popover-1"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + '"data-state":"closed"', + 'id:"open"', + 'popovertarget:"rx-popover-1"', + "ref:ref_open", + ], + "children": [{"contents": '"Open"'}], + }, + { + "name": '"div"', + "props": [ + "className:sx_1ea534d980_c", + '"data-default-open":true', + '"data-rx-popup":""', + 'id:"rx-popover-1"', + "onBlur:popupEvent", + "onClick:popupEvent", + "onKeyDown:popupEvent", + "onToggle:popupEvent", + 'popover:"auto"', + "ref:((popup) => popupSync(popup, null))", + 'role:"dialog"', + "tabIndex:-1", + ], + "children": [ + {"contents": '"Inside"'}, + { + "name": '"button"', + "props": [ + 'popovertarget:"rx-popover-1"', + 'popovertargetaction:"hide"', + ], + "children": [{"contents": '"Close"'}], + }, + ], + }, + ], + } + assert declared_styles(component) == [ + {}, + {}, + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "var(--rx-popup-offset, 8px)", + "marginRight": "var(--rx-popup-shift, 0px)", + "marginBottom": "var(--rx-popup-offset, 8px)", + "marginLeft": "0", + "padding": "var(--popover-content-padding)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "300px", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "100ms", + ":popover-open": "160ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "inherit", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-5)", + "minWidth": "anchor-size(width)", + "outlineStyle": "none", + "overflowX": "auto", + "overflowY": "auto", + "--inset-padding-top": "var(--popover-content-padding)", + "--inset-padding-right": "var(--popover-content-padding)", + "--inset-padding-bottom": "var(--popover-content-padding)", + "--inset-padding-left": "var(--popover-content-padding)", + "--popover-content-padding": "var(--space-3)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "positionArea": "top span-left", + "maxHeight": "calc(100% - var(--rx-popup-offset, 8px) - 10px)", + "--rx-popup-from": "translateY(4px) scale(0.97)", + "transformOrigin": "bottom right", + "--rx-popup-offset": "4px", + "--rx-popup-shift": "2px", + }, + {}, + ] + + +def test_popover_with_an_id(ui_plugin: UIPlugin): + """A popover that is given an id is named by it, and one outside a root is a popover nothing opens.""" + component = rx.el.div( + rx.ui.popover.root( + rx.ui.popover.trigger(rx.el.button("Open")), + rx.ui.popover.content("Inside", id="panel"), + ), + rx.ui.popover.content("Alone"), + ) + assert component.render() == { + "name": '"div"', + "props": [], + "children": [ + { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"panel"', + '"aria-expanded":false', + '"aria-haspopup":"dialog"', + '"data-state":"closed"', + 'popovertarget:"panel"', + ], + "children": [{"contents": '"Open"'}], + }, + { + "name": '"div"', + "props": [ + "className:sx_10268a09e0_c", + '"data-rx-popup":""', + 'id:"panel"', + "onBlur:popupEvent", + "onClick:popupEvent", + "onKeyDown:popupEvent", + "onToggle:popupEvent", + 'popover:"auto"', + "ref:((popup) => popupSync(popup, null))", + 'role:"dialog"', + "tabIndex:-1", + ], + "children": [{"contents": '"Inside"'}], + }, + ], + }, + { + "name": '"div"', + "props": [ + "className:sx_10268a09e0_c", + '"data-rx-popup":""', + "onBlur:popupEvent", + "onClick:popupEvent", + "onKeyDown:popupEvent", + "onToggle:popupEvent", + 'popover:"auto"', + "ref:((popup) => popupSync(popup, null))", + 'role:"dialog"', + "tabIndex:-1", + ], + "children": [{"contents": '"Alone"'}], + }, + ], + } + + +class PopoverState(rx.State): + """What a popover is bound to.""" + + shown: bool = False + gap: int = 6 + + @rx.event + def set_shown(self, shown: bool): + """Follow the popover. + + Args: + shown: Whether it is open. + """ + self.shown = shown + + @rx.event + def note(self): + """Hear that something happened to the popover.""" + + +def test_popover_bound_to_state(ui_plugin: UIPlugin): + """A popover bound to state hands its script its state and what it does when it opens, closes or is dismissed, and an offset bound to state is a custom property.""" + name = PopoverState.get_full_name() + component = rx.ui.popover.root( + rx.ui.popover.trigger(rx.el.button("Open")), + rx.ui.popover.content( + "x", + side_offset=PopoverState.gap, + on_focus_outside=PopoverState.note, + ), + open=PopoverState.shown, + on_open_change=PopoverState.set_shown, + ) + rendered = component.render() + assert (rendered["name"], rendered["props"]) == ("Fragment", []) + on = ( + f'({{ open: ((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' + '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))), focusOutside: ' + f'((...args) => (addEvents([(ReflexEvent("{name}.note", ({{ }}), ' + "({ })))], args, ({ })))) })" + ) + assert rendered["children"][1]["props"] == [ + "className:sx_13adaeddb0_c", + '"data-rx-popup":""', + 'id:"rx-popover-1"', + f"onBlur:((event) => popupEvent(event, {on}))", + f"onClick:((event) => popupEvent(event, {on}))", + f"onKeyDown:((event) => popupEvent(event, {on}))", + f"onToggle:((event) => popupEvent(event, {on}))", + 'popover:"auto"', + f"ref:((popup) => popupSync(popup, {PopoverState.shown!s}))", + 'role:"dialog"', + f'style:({{ "--v0": ((({PopoverState.gap!s}) + "px")) ?? "initial" }})', + "tabIndex:-1", + ] + + +def test_popover_imports_its_script(ui_plugin: UIPlugin): + """A page with a popover loads the script of a popup, and no other.""" + component = rx.ui.popover.root( + rx.ui.popover.trigger(rx.el.button("Open")), rx.ui.popover.content("x") + ) + imports = component._get_all_imports() + assert { + module: names for module, names in imports.items() if "behaviors" in module + } == { + "$/reflex-ui/behaviors/popup.js": [ + ImportVar(tag="popupSync"), + ImportVar(tag="popupEvent"), + ], + } + + +@pytest.mark.parametrize( + ("create", "message"), + [ + ( + lambda: rx.ui.popover.trigger("Open"), + ( + "rx.ui.popover_trigger: it is rendered as its child, so it needs exactly " + "one child that is an element, such as a button." + ), + ), + ( + lambda: rx.ui.popover.content(side="above"), # pyright: ignore[reportArgumentType] + ( + 'rx.ui.popover_content: unknown side "above". The values are "top", ' + '"right", "bottom", "left".' + ), + ), + ], +) +def test_popover_refuses_what_it_cannot_render( + ui_plugin: UIPlugin, create: Callable[[], Any], message: str +): + """A trigger without one element to render as, and a side a popover does not have, fail with the name of the component.""" + with pytest.raises(StyleError) as error: + create() + assert str(error.value) == message diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index e1428fac12e..ee4a52d136d 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -180,6 +180,10 @@ def test_every_wave_is_in_the_namespace(): "list.unordered", "list_item", "ordered_list", + "popover.close", + "popover.content", + "popover.root", + "popover.trigger", "progress", "radio", "radio.item", @@ -248,6 +252,7 @@ def test_every_wave_is_in_the_namespace(): "form", "input", "list", + "popover", "radio", "radio_group", "segmented_control", From 4c71e77145b56345194277896bd5cb83505e9b25 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 10:44:05 +0000 Subject: [PATCH 125/204] Compare what is inside the form controls, and keep the ring of a checked radio A part of a matrix may now be a pseudo-element: rx.ui draws the check of a checkbox, the thumb of a switch, the dot of a radio button and the surface of a card with the element itself, where Radix has an element inside. The matrices of the checkbox, its group and cards, the switch, the radio buttons and their cards, the segmented control and the form name what corresponds. What that found: a checked surface radio button of Radix keeps its gray ring under the dot, which rx.ui dropped; the difference had been inside the tolerance. With the ring the worst cell of the radio matrices goes from 49 and 88 differing pixels to 2 and 17, and their tolerances follow. The thumb of a switch no longer sets pointer-events, and the check has the color of the icon of Radix and is filled with it; that it is a mask and not an svg is in the allowlist. The test of the select has the edits of the base branch again, which a regeneration had taken out. Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- packages/reflex-components-ui/README.md | 4 +- .../parity/allowlist.toml | 18 +++++ .../parity/ui_parity/components/checkbox.py | 8 +++ .../ui_parity/components/checkbox_cards.py | 11 ++- .../ui_parity/components/checkbox_group.py | 9 +++ .../parity/ui_parity/components/form.py | 2 + .../parity/ui_parity/components/radio.py | 14 ++-- .../ui_parity/components/radio_cards.py | 5 ++ .../ui_parity/components/radio_group.py | 16 +++-- .../ui_parity/components/segmented_control.py | 18 +++++ .../parity/ui_parity/components/switch.py | 6 ++ .../parity/ui_parity/look.py | 19 +++-- .../parity/ui_parity/matrix.py | 5 +- .../reflex_components_ui/styles/checkbox.py | 7 +- .../src/reflex_components_ui/styles/radio.py | 3 +- .../src/reflex_components_ui/styles/switch.py | 1 - .../tests_playwright/test_ui_parity.py | 71 +++++++++++++++++++ .../components/test_checkbox.py | 37 ++++++---- .../components/test_checkbox_cards.py | 35 +++++---- .../components/test_checkbox_group.py | 55 ++++++++------ .../components/test_select.py | 16 ++++- .../components/test_switch.py | 7 +- 22 files changed, 290 insertions(+), 77 deletions(-) diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 76857bdfba5..de1fcdb7cf3 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -854,7 +854,9 @@ registers it. 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, + style is read when it is not the first element (a part is one selector, + or one for each system, and may end in `::before` or `::after` where one + system draws with a pseudo-element what the other has an element for), `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`. `ready` is a JavaScript expression a page must meet before diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index bdd7b975870..bdeffd380e5 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -303,3 +303,21 @@ component = "select" step = "the page behind an open list takes no click" system = "rx.ui" reason = "While its list is open rx.select takes the pointer off the rest of the page: a click outside closes the list and does nothing else. The list of rx.ui.select is a native popover: a click outside closes it and also reaches what is under the pointer, as with a native select, and the page behind it scrolls." + +[[look]] +component = "checkbox" +check = "style" +properties = ["background-color", "vertical-align", "overflow-x", "overflow-y"] +reason = "The check of rx.checkbox is an icon, an svg element drawn in its color. The check of rx.ui.checkbox is drawn by the checkbox itself: a box of the size and the color of the icon, cut to its shape by a mask. It paints the same." + +[[look]] +component = "checkbox_group" +check = "style" +properties = ["background-color", "vertical-align", "overflow-x", "overflow-y"] +reason = "The check of rx.checkbox_group is an icon, an svg element drawn in its color. The check of rx.ui.checkbox_group is drawn by the checkbox itself: a box of the size and the color of the icon, cut to its shape by a mask. It paints the same." + +[[look]] +component = "checkbox_cards" +check = "style" +properties = ["background-color", "vertical-align", "overflow-x", "overflow-y"] +reason = "The check of rx.checkbox_cards is an icon, an svg element drawn in its color. The check of rx.ui.checkbox_cards is drawn by the checkbox itself: a box of the size and the color of the icon, cut to its shape by a mask. It paints the same." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/checkbox.py b/packages/reflex-components-ui/parity/ui_parity/components/checkbox.py index 33ca15df6dc..f07f04141a9 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/checkbox.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/checkbox.py @@ -72,6 +72,14 @@ def _checkbox(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(160, 64), crop="stage", target=TARGET, + # The box and the check are drawn by the checkbox itself here, where + # Radix has an element for the check. + parts={ + "box": ("button::before", "input::before"), + "check": ("button > svg", "input::after"), + "label": "label", + "row": "label > div", + }, # Not held to zero, for the check alone: Radix Themes draws it as an svg # element and an input has no children, so here it is the same path as a # mask, whose edge the browser rasterizes by a step of a channel diff --git a/packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py index 765363a7a6d..c61f753c177 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_cards.py @@ -84,7 +84,16 @@ def _cards(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(420, 150), crop="stage", target=TARGET, - parts={"checkbox": CHECKBOX}, + # The box and the check are drawn by the checkbox itself here, where + # Radix has an element for the check. + parts={ + "root": "[role=group]", + "surface": "label::before", + "outline": "label::after", + "checkbox": CHECKBOX, + "box": ("label > button::before", "label > input::before"), + "check": ("label > button > svg", "label > input::after"), + }, # The focus is on the checkbox inside the card. states={FOCUS_VISIBLE: FOCUS_WITHIN}, # Not held to zero, as the matrix of the radio cards is not: a card is diff --git a/packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py index ed2d57f78aa..5b02cc5615a 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/checkbox_group.py @@ -61,6 +61,15 @@ def _group(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(160, 110), crop="stage", target=TARGET, + # The box and the check are drawn by the checkbox itself here, where + # Radix has an element for the check. + parts={ + "root": "[role=group]", + "item": "label", + "inner": "label > span", + "box": ("button::before", "input::before"), + "check": ("button > svg", "input::after"), + }, # Not held to zero, for the check alone, as the matrix of the checkbox # is not: it is a mask here and an svg element in Radix Themes. # At the default threshold 3 of the 74 cells differ, by at most 6 pixels diff --git a/packages/reflex-components-ui/parity/ui_parity/components/form.py b/packages/reflex-components-ui/parity/ui_parity/components/form.py index 2299bc8ad45..4ca946e561e 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/form.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/form.py @@ -58,7 +58,9 @@ def _form(namespace: Any, props: Mapping[str, Any]) -> Any: parts={ "field": "form > div", "label": "label", + "control": "form > div > :is(input, textarea)", "message": "form > div > span", + "forced": "form > div > span:nth-of-type(2)", "submit": "form > button", }, # A field the server finds invalid gives its control the focus, which diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio.py b/packages/reflex-components-ui/parity/ui_parity/components/radio.py index 3688db504fe..77969b8f29e 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/radio.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio.py @@ -47,8 +47,14 @@ def _group(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(160, 110), crop="stage", target=TARGET, - # Not held to zero, as the matrix of the radio group is not: a circle - # is anti-aliased by where it is on the page. At the default threshold 7 - # of the 19 cells differ, by at most 49 pixels of 17600. - tolerance=0.003, + parts={ + "root": "[role=radiogroup]", + "box": ("button::before", "input::before"), + "dot": ("button::after", "input::after"), + }, + # Not held to zero. At a threshold of zero the cells that differ do so + # by where they are on the page: the circle of a radio button and its + # focus ring are anti-aliased by it. At the default threshold the worst + # cell differs by 2 pixels. + tolerance=0.0002, ) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py index cd8efd9c778..a9ab13f3f62 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_cards.py @@ -82,6 +82,11 @@ def _cards(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(360, 150), crop="stage", target=TARGET, + parts={ + "root": "[role=radiogroup]", + "surface": ("button::before", "label::before"), + "outline": ("button::after", "label::after"), + }, # The focus is on the card of Radix and on the input in the card here. states={FOCUS_VISIBLE: FOCUS_WITHIN}, # Not held to zero. The translucent fill of a card, its rounded clip and diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py index 146920bcfe0..2b542bc88fa 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py @@ -63,12 +63,16 @@ def _group(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(220, 110), crop="stage", target=TARGET, - # Not held to zero. A circle is anti-aliased by where it is on the page: - # with the two frames of a cell swapped, each system is equal pixel for - # pixel to the other one in the same place, and differs from itself in - # the other place by the same pixels. At the default threshold 26 of the - # 117 cells differ, by at most 88 pixels of 24200. - tolerance=0.004, + parts={ + "root": "[role=radiogroup]", + "box": ("button::before", "input::before"), + "dot": ("button::after", "input::after"), + }, + # Not held to zero. At a threshold of zero the cells that differ do so + # by where they are on the page: the circle of a radio button and its + # focus ring are anti-aliased by it. At the default threshold the worst + # cell differs by 17 pixels. + tolerance=0.001, ) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py index 41c59c73540..b0f4f23cc7b 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py @@ -89,9 +89,27 @@ def _control(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(420, 80), crop="stage", target=TARGET, + # What is inside an item, which has a radio button before it here. parts={ "root": "[role=radiogroup]", "indicator": "[role=radiogroup] > div", + "pill": "[role=radiogroup] > div::before", + "separator": ( + f"{TARGET[0]} > span:nth-of-type(1)", + f"{TARGET[1]} > span:nth-of-type(1)", + ), + "label": ( + f"{TARGET[0]} > span:nth-of-type(2)", + f"{TARGET[1]} > span:nth-of-type(2)", + ), + "active": ( + f"{TARGET[0]} > span > span:nth-of-type(1)", + f"{TARGET[1]} > span > span:nth-of-type(1)", + ), + "inactive": ( + f"{TARGET[0]} > span > span:nth-of-type(2)", + f"{TARGET[1]} > span > span:nth-of-type(2)", + ), }, # The focus is on the item of Radix and on the radio button in the item # here. diff --git a/packages/reflex-components-ui/parity/ui_parity/components/switch.py b/packages/reflex-components-ui/parity/ui_parity/components/switch.py index e48815ac28d..2bd7cabbc5d 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/switch.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/switch.py @@ -64,6 +64,12 @@ }, ], stage=(120, 64), + # The thumb is drawn by the switch itself here, where Radix has an + # element for it. + parts={ + "track": ("button::before", "input::before"), + "thumb": ("button > span", "input::after"), + }, # Not held to zero. At a threshold of zero 132 of the 164 cells are equal # pixel for pixel, the base cell among them, and the others differ by # where they are on the page: the gradient of the track is dithered and diff --git a/packages/reflex-components-ui/parity/ui_parity/look.py b/packages/reflex-components-ui/parity/ui_parity/look.py index 5cdb2d90c88..eaf3c118a0d 100644 --- a/packages/reflex-components-ui/parity/ui_parity/look.py +++ b/packages/reflex-components-ui/parity/ui_parity/look.py @@ -121,8 +121,8 @@ def prepare(page: Page) -> None: # 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, first, notRendered, shapeKey}) => { - const read = (element) => { - const style = getComputedStyle(element); + const read = (element, pseudo) => { + const style = getComputedStyle(element, pseudo); return Object.fromEntries( properties.map((name) => [name, style.getPropertyValue(name)]), ); @@ -146,12 +146,19 @@ def prepare(page: Page) -> None: const missing = []; const named = new Set(); for (const [name, selectors] of Object.entries(parts)) { - const part = stage.querySelector(selectors[system]); - if (part === null) { + // A part may be a pseudo-element, "input::after": one system + // draws with one what the other has an element for. It is + // there when it has content. + const [query, pseudo] = selectors[system].split(/(?=::)/); + const part = stage.querySelector(query); + const drawn = part !== null && ( + !pseudo || getComputedStyle(part, pseudo).content !== "none" + ); + if (!drawn) { missing.push(name); } else { - styles[name] = read(part); - named.add(part); + styles[name] = read(part, pseudo); + if (!pseudo) named.add(part); } } // The elements inside the target, by the path of their places among diff --git a/packages/reflex-components-ui/parity/ui_parity/matrix.py b/packages/reflex-components-ui/parity/ui_parity/matrix.py index b9a9841ef27..1751ce76029 100644 --- a/packages/reflex-components-ui/parity/ui_parity/matrix.py +++ b/packages/reflex-components-ui/parity/ui_parity/matrix.py @@ -197,7 +197,10 @@ class Matrix: 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 that renders. - parts: Inner elements whose computed style is compared too, by name. + parts: Inner elements whose computed style is compared too, by name: + a selector, or one per system, which may end in ``::before`` or + ``::after`` where a system draws with a pseudo-element what the + other has an element for. 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. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py index fb438fa815f..2db84893b11 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/checkbox.py @@ -90,7 +90,12 @@ def _look(variant: str, high_contrast: bool, disabled: str) -> dict[str, Any]: check = accent[12] if high_contrast else accent.a[11] return { "_before": box, - "_after": {"background_color": {"default": check, DISABLED: gray.a[8]}}, + # The check has the color Radix gives its icon, and is a mask + # filled with it. + "_after": { + "color": {"default": check, DISABLED: gray.a[8]}, + "background_color": "currentcolor", + }, } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py index 77c781868f9..0d323be0e1d 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/radio.py @@ -34,9 +34,10 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: _CHECKED_ENABLED: fill, DISABLED: gray.a[3], }, + # The ring stays under the dot of a checked radio button, as it + # does on the button Radix Themes draws one with. "box_shadow": { "default": f"inset 0 0 0 1px {gray.a[7]}", - _CHECKED_ENABLED: "none", DISABLED: f"inset 0 0 0 1px {gray.a[6]}", }, } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py index cc48a835f6f..2f1311a9089 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/switch.py @@ -256,7 +256,6 @@ def _look(variant: str, high_contrast: bool) -> dict[str, Any]: "cubic-bezier(0.45, 0.05, 0.55, 0.95), ease-in-out" ), "transform": {_CHECKED: f"translateX(var({_TRAVEL}))"}, - "pointer_events": "none", }, }), "variants": { diff --git a/tests/integration/tests_playwright/test_ui_parity.py b/tests/integration/tests_playwright/test_ui_parity.py index 845d841d190..2b25cb41eac 100644 --- a/tests/integration/tests_playwright/test_ui_parity.py +++ b/tests/integration/tests_playwright/test_ui_parity.py @@ -347,6 +347,77 @@ def test_read_reaches_the_elements_inside_the_compared_one(page: Page): assert page.evaluate(SETTLED_SCRIPT, 50) is True +DRAWN = """ + + + + + +
+ +
+
+ +
+ + +""" + + +def test_read_takes_a_pseudo_element_for_a_part(page: Page): + """One system's element is paired with what the other draws with a pseudo-element.""" + page.set_content(DRAWN) + request = { + "properties": ["display", "width"], + "targets": {"reference": None, "candidate": None}, + "parts": { + "box": {"reference": "button > i", "candidate": "input::before"}, + # Drawn by neither: no mark in the button, and nothing checked. + "mark": {"reference": "button > b", "candidate": "input::after"}, + }, + "only": None, + "matches": None, + "first": ":scope > :not(style):not(script):not(link):not(template)", + "notRendered": "style,script,link,template", + "shapeKey": "(shape)", + } + frames = page.evaluate(READ_SCRIPT, request) + assert [ + (frame["system"], frame["styles"], frame["missing"]) for frame in frames + ] == [ + ( + "reference", + { + "box": {"display": "block", "width": "8px"}, + "": {"display": "block", "width": "20px"}, + "(shape)": {"": "1 button", "> 1": "0 i"}, + }, + ["mark"], + ), + ( + "candidate", + { + "box": {"display": "block", "width": "8px"}, + "": {"display": "block", "width": "20px"}, + "(shape)": {"": "0 input"}, + }, + ["mark"], + ), + ] + page.locator("input").check() + [_, candidate] = page.evaluate(READ_SCRIPT, request) + assert (candidate["styles"]["mark"], candidate["missing"]) == ( + {"display": "inline-block", "width": "4px"}, + [], + ) + + CONTRACT_STEPS = [ pytest.param(component, system, step, id=f"{component}-{system.name}-{step.name}") for component, contract in CONTRACTS.items() diff --git a/tests/units/reflex_components_ui/components/test_checkbox.py b/tests/units/reflex_components_ui/components/test_checkbox.py index 8f782197eb4..00ee01570dd 100644 --- a/tests/units/reflex_components_ui/components/test_checkbox.py +++ b/tests/units/reflex_components_ui/components/test_checkbox.py @@ -43,7 +43,7 @@ def test_checkbox_with_its_label( { "name": '"input"', "props": [ - "className:sx_eda6ae65a6_c", + "className:sx_b87bd44530_c", 'id:"agree"', 'name:"agree"', "ref:ref_agree", @@ -105,14 +105,17 @@ def test_checkbox_with_its_label( ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", ":disabled": "var(--gray-a3)", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-contrast)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -203,7 +206,7 @@ def test_checkbox_alone( "name": '"input"', "props": [ "checked:true", - 'className:sx_cf89508fbc_c + " " + reflexUIClasses_e201574881', + 'className:sx_6ac964b510_c + " " + reflexUIClasses_e201574881', "disabled:true", "readOnly:true", "required:true", @@ -237,14 +240,17 @@ def test_checkbox_alone( "default": "var(--accent-a5)", ":disabled": "var(--gray-a3)", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-12)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -349,10 +355,7 @@ def test_checkbox_classic( ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", ":disabled": "var(--gray-a3)", }, - "::after": { - "default": "var(--accent-contrast)", - ":disabled": "var(--gray-a8)", - }, + "::after": "currentcolor", }, "backgroundImage": { "default": "none", @@ -362,7 +365,13 @@ def test_checkbox_classic( }, }, "boxSizing": "border-box", - "color": "inherit", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -448,7 +457,7 @@ def test_checkbox_spacing_and_gap( "children": [ { "name": '"input"', - "props": ["className:sx_216a3adbf2_c", 'type:"checkbox"'], + "props": ["className:sx_846aafb601_c", 'type:"checkbox"'], "children": [], }, {"contents": '"Agree"'}, diff --git a/tests/units/reflex_components_ui/components/test_checkbox_cards.py b/tests/units/reflex_components_ui/components/test_checkbox_cards.py index 3316ef0f22f..04d39d58b84 100644 --- a/tests/units/reflex_components_ui/components/test_checkbox_cards.py +++ b/tests/units/reflex_components_ui/components/test_checkbox_cards.py @@ -53,7 +53,7 @@ def test_checkbox_cards( { "name": '"input"', "props": [ - "className:sx_e9aee32af5_c", + "className:sx_6eb5dc6fb4_c", "defaultChecked:true", 'id:"one"', 'name:"pick"', @@ -73,7 +73,7 @@ def test_checkbox_cards( { "name": '"input"', "props": [ - "className:sx_e9aee32af5_c", + "className:sx_6eb5dc6fb4_c", "disabled:true", 'name:"pick"', 'type:"checkbox"', @@ -216,14 +216,17 @@ def test_checkbox_cards( ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", ":disabled": "transparent", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-contrast)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -385,14 +388,17 @@ def test_checkbox_cards( ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", ":disabled": "transparent", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-contrast)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -482,7 +488,7 @@ def test_checkbox_cards_classic( { "name": '"input"', "props": [ - "className:sx_0d82b24940_c", + "className:sx_4f13f0900c_c", 'name:"pick"', 'type:"checkbox"', 'value:"1"', @@ -657,14 +663,17 @@ def test_checkbox_cards_classic( ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-12)", ":disabled": "transparent", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-1)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -765,7 +774,7 @@ def test_checkbox_cards_bound_to_state( "name": '"input"', "props": [ 'checked:(reflex___state____state__tests___units___reflex_components_ui___components___test_checkbox_cards____cards_state.picked_rx_state_.includes("a"))', - "className:sx_e9aee32af5_c", + "className:sx_6eb5dc6fb4_c", 'name:"pick"', "readOnly:true", "required:true", diff --git a/tests/units/reflex_components_ui/components/test_checkbox_group.py b/tests/units/reflex_components_ui/components/test_checkbox_group.py index 30c9131db21..0bdac87d6cf 100644 --- a/tests/units/reflex_components_ui/components/test_checkbox_group.py +++ b/tests/units/reflex_components_ui/components/test_checkbox_group.py @@ -57,7 +57,7 @@ def test_checkbox_group( { "name": '"input"', "props": [ - "className:sx_0710e9ad14_c", + "className:sx_8b52e7930c_c", 'id:"one"', 'name:"pick"', "ref:ref_one", @@ -76,7 +76,7 @@ def test_checkbox_group( { "name": '"input"', "props": [ - "className:sx_0710e9ad14_c", + "className:sx_8b52e7930c_c", "defaultChecked:true", "disabled:true", 'name:"pick"', @@ -92,7 +92,7 @@ def test_checkbox_group( { "name": '"input"', "props": [ - "className:sx_0710e9ad14_c", + "className:sx_8b52e7930c_c", "defaultChecked:true", 'name:"pick"', 'type:"checkbox"', @@ -152,14 +152,17 @@ def test_checkbox_group( "default": "var(--accent-a5)", ":disabled": "var(--gray-a3)", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-12)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -245,14 +248,17 @@ def test_checkbox_group( "default": "var(--accent-a5)", ":disabled": "var(--gray-a3)", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-12)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -337,14 +343,17 @@ def test_checkbox_group( "default": "var(--accent-a5)", ":disabled": "var(--gray-a3)", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-12)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -438,7 +447,7 @@ def test_checkbox_group_bound_to_state( "name": '"input"', "props": [ 'checked:(reflex___state____state__tests___units___reflex_components_ui___components___test_checkbox_group____checkbox_group_state.picked_rx_state_.includes("a"))', - "className:sx_eda6ae65a6_c", + "className:sx_b87bd44530_c", "disabled:false", 'name:"pick"', "readOnly:true", @@ -456,7 +465,7 @@ def test_checkbox_group_bound_to_state( "name": '"input"', "props": [ 'checked:(reflex___state____state__tests___units___reflex_components_ui___components___test_checkbox_group____checkbox_group_state.picked_rx_state_.includes("b"))', - "className:sx_eda6ae65a6_c", + "className:sx_b87bd44530_c", "disabled:false", 'name:"pick"', "readOnly:true", @@ -508,14 +517,17 @@ def test_checkbox_group_bound_to_state( ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", ":disabled": "var(--gray-a3)", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-contrast)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", @@ -624,14 +636,17 @@ def test_checkbox_group_bound_to_state( ":is(:checked, :indeterminate):not(:disabled)": "var(--accent-indicator)", ":disabled": "var(--gray-a3)", }, + "::after": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", "::after": { "default": "var(--accent-contrast)", ":disabled": "var(--gray-a8)", }, }, - "backgroundImage": "none", - "boxSizing": "border-box", - "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index 65183251284..87ce0ed8cd5 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -1,8 +1,9 @@ """Tests for reflex_components_ui.components.select.""" import itertools +import re from collections.abc import Callable -from typing import Any +from typing import Any, Literal, get_args import pytest from reflex_base.utils.imports import ImportVar @@ -1377,9 +1378,14 @@ def test_select_unknown_side(ui_plugin: UIPlugin): """A side a list cannot be on is an error that lists the sides.""" with pytest.raises(StyleError) as error: rx.ui.select.content(side="above") # pyright: ignore[reportArgumentType] + # In the order of the Literal Python keeps for these four values, which + # is the one of whichever module first wrote them. + sides = ", ".join( + f'"{side}"' for side in get_args(Literal["top", "right", "bottom", "left"]) + ) assert ( str(error.value) - == 'rx.ui.select_content: unknown side "above". The values are "top", "right", "bottom", "left".' + == f'rx.ui.select_content: unknown side "above". The values are {sides}.' ) @@ -1530,6 +1536,10 @@ def test_select_of_a_list_in_state(ui_plugin: UIPlugin): (group,) = content.children (options,) = group.children item = options.children[0] + # Named after the bytecode of the function that renders an option, which + # differs from one Python version to the next. + index = options.render()["index_var_name"] + assert re.fullmatch(r"index_[0-9a-f]{32}", index) assert item.render()["props"] == [ ( f'"aria-selected":(({STATE}.fruit_rx_state_ === item_rx_state_) ' @@ -1537,7 +1547,7 @@ def test_select_of_a_list_in_state(ui_plugin: UIPlugin): ), "className:sx_afbb711e7e_c", '"data-value":item_rx_state_', - "key:index_d6d6157c99650830f12a866606ea87b7", + f"key:{index}", 'role:"option"', "tabIndex:-1", ] diff --git a/tests/units/reflex_components_ui/components/test_switch.py b/tests/units/reflex_components_ui/components/test_switch.py index 20c342ec056..57814895e88 100644 --- a/tests/units/reflex_components_ui/components/test_switch.py +++ b/tests/units/reflex_components_ui/components/test_switch.py @@ -19,7 +19,7 @@ def test_switch( assert component.render() == { "name": '"input"', "props": [ - "className:sx_14daba69db_c", + "className:sx_fd86994bd3_c", "defaultChecked:true", 'id:"wifi"', 'name:"wifi"', @@ -144,7 +144,6 @@ def test_switch( "transform": { "::after": {":checked": "translateX(var(--switch-thumb-translate-x))"} }, - "pointerEvents": {"::after": "none"}, "--switch-height": "calc(var(--space-5) * 5 / 6)", "--switch-border-radius": "max(var(--radius-2), var(--radius-thumb))", "boxShadow": { @@ -189,7 +188,7 @@ def test_switch_classic_high_contrast( "name": '"input"', "props": [ "checked:true", - 'className:sx_7350a6aadb_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', + 'className:sx_c196716516_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', "disabled:true", "readOnly:true", "required:true", @@ -315,7 +314,6 @@ def test_switch_classic_high_contrast( "transform": { "::after": {":checked": "translateX(var(--switch-thumb-translate-x))"} }, - "pointerEvents": {"::after": "none"}, "--switch-height": { "default": "var(--space-4)", "@media (min-width: 1024px)": "var(--space-5)", @@ -469,7 +467,6 @@ def test_switch_soft( "transform": { "::after": {":checked": "translateX(var(--switch-thumb-translate-x))"} }, - "pointerEvents": {"::after": "none"}, "--switch-height": "calc(var(--space-5) * 5 / 6)", "--switch-border-radius": "max(var(--radius-2), var(--radius-thumb))", "boxShadow": { From 4fa3465005ec7009923caafec4fa346c78dcff72 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 10:44:30 +0000 Subject: [PATCH 126/204] Record the popup on whole pixels and the size of its script Claude-Session: https://claude.ai/code/session_014AwvTQ1gf1pLjunZdb3RTh --- packages/reflex-components-ui/README.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index de1fcdb7cf3..b1125f5d358 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -535,8 +535,8 @@ reuse: placed by CSS anchor positioning, turned over by | `form-validity.js` | 684 B | shows the messages of a form that match the validity the browser computed | | `roving-focus.js` | 411 B | the arrow keys of a segmented control | | `slider.js` | 660 B | the filled part of the track, the order of several thumbs, a press on the track | -| `popup.js` | 386 B | says on a trigger that its popover is open, and gives the popups of a loop their own ids | -| `popup-position.js` | 404 B | places a popover in a browser without anchor positioning; loaded only there | +| `popup.js` | 762 B | says on a trigger that its popover is open, puts the popover on whole pixels before it is first drawn, and gives the popups of a loop their own ids | +| `popup-position.js` | 407 B | places a popover in a browser without anchor positioning; loaded only there | | `listbox.js` | 1,536 B | the value of a select, the keys of its list, typing to find an option | What the form controls wave settled: @@ -556,6 +556,22 @@ What the form controls wave settled: - **An input bound to state** is rendered through `DebounceInput`, as the inputs of `rx.el` are: `rx.ui.input` and `rx.ui.text_area` keep the caret where it is while the state follows. +- **A popup on whole pixels.** A popover the browser places beside its + anchor starts on a fraction of a pixel whenever its width has one, which + depends on the font, and Radix rounds where it puts one. The browser + keeps the fraction a popover is first drawn at, in the edges of its + letters, and a transform resamples it: so `popupBeforeToggle` measures + the popover in the frame that first shows it and writes + `--rx-popup-snap-x` and `--rx-popup-snap-y`, which `placement()` adds to + one margin and takes from the one opposite. +- **A look that holds in one font is not held.** Run a matrix under + `--fonts "DejaVu Sans" "Liberation Mono"` too. A round end that falls on + a fraction of a pixel is drawn by where it is on the page, in Radix as + here: give such a cell a width of whole pixels rather than a tolerance. +- **What a system draws with a pseudo-element** is a part too + (`("button > span", "input::after")`): the comparison of what is inside + a cell found the gray ring a checked surface radio button of Radix keeps, + which a tolerance had taken for anti-aliasing. - **A matrix of a popup** crops the stage, opens the popup with a state of its own (`states={OPEN: State(...)}`), and leaves room in the stage for it: a popup that meets the edge of the viewport is moved by Radix and From dd3c48bf6b5c31e0e02f3fefd89d90749915db3e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 10:53:52 +0000 Subject: [PATCH 127/204] Add rx.ui.tooltip, opened under the pointer and with the focus by hover.js A tooltip is its child, which it always describes, then a manual popover with its text. hover.js opens it once the pointer has rested on the child, at once with the focus of the keyboard, and closes it when both have left, on Escape and on a press outside or on the child; it names each pair apart for the browser to place the popup by, follows a popup bound to state and raises its events. The hover card will use it too. The placements of a popup are typed, and a popup's offset bound to state is written as it was. Claude-Session: https://claude.ai/code/session_014AwvTMWjpBRrG7rVgJBZHA --- .../js/src/behaviors/hover.js | 172 ++++++++ .../js/tests/behaviors/hover.test.js | 254 +++++++++++ .../news/+wave4-overlays.feature.md | 4 +- .../parity/allowlist.toml | 17 + .../parity/ui_parity/components/tooltip.py | 402 ++++++++++++++++++ .../src/reflex_components_ui/__init__.py | 1 + .../reflex_components_ui/components/_popup.py | 143 ++++++- .../reflex_components_ui/components/_slot.py | 7 +- .../components/tooltip.py | 219 ++++++++++ .../src/reflex_components_ui/styles/popup.py | 6 +- .../reflex_components_ui/styles/tooltip.py | 52 +++ pyi_hashes.json | 4 +- .../components/test_tooltip.py | 242 +++++++++++ .../reflex_components_ui/test_api_parity.py | 1 + 14 files changed, 1500 insertions(+), 24 deletions(-) create mode 100644 packages/reflex-components-ui/js/src/behaviors/hover.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/hover.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/tooltip.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py create mode 100644 tests/units/reflex_components_ui/components/test_tooltip.py diff --git a/packages/reflex-components-ui/js/src/behaviors/hover.js b/packages/reflex-components-ui/js/src/behaviors/hover.js new file mode 100644 index 00000000000..e53ec140964 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/hover.js @@ -0,0 +1,172 @@ +// A popup that opens under the pointer and with the focus of the keyboard: +// a tooltip, a hover card. +// +// The popup is a native popover the browser puts over everything else and +// CSS places against what opens it. Nothing in a browser opens one on +// hover in every engine, so a script does: after a delay under the pointer, +// at once with the focus of the keyboard, and it closes the popup when +// both have left, on Escape and on a press outside it. Without this the +// popup never shows; a tooltip still describes what it is on. + +/** Whether the browser places a popover beside its anchor by itself. */ +const ANCHORED = globalThis.CSS?.supports?.("position-area: bottom") ?? false; + +let ids = 0; + +/** + * @typedef {{ open?: (open: boolean) => void, escape?: () => void, outside?: () => void }} Handlers + * @typedef {{ on?: Handlers | null, bound?: boolean, timer?: number, off?: () => void }} State + */ + +/** @type {WeakMap} */ +const popups = new WeakMap(); + +/** + * Find what a popup opens under. + * + * @param {HTMLElement} popup The popover. + * @returns {HTMLElement | null} The element that names it. + */ +function triggerOf(popup) { + return document.querySelector(`[data-rx-hover="${popup.id}"]`); +} + +/** + * Open or close a popup, and say so on what it opens under. + * + * While it is open, Escape and a press outside it close it, wherever the + * focus is. + * + * @param {HTMLElement} popup The popover. + * @param {boolean} open Whether to open it. + * @returns {void} + */ +function set(popup, open) { + const state = popups.get(popup); + if (!state || open === popup.matches(":popover-open")) return; + popup.togglePopover(open); + const trigger = triggerOf(popup); + if (trigger) { + const shown = popup.role === "tooltip" ? "delayed-open" : "open"; + trigger.dataset.state = open ? shown : "closed"; + if (!ANCHORED) + import("./popup-position.js").then(({ place }) => + place(popup, trigger, open), + ); + } + state.off?.(); + delete state.off; + if (!open) return; + const dismiss = (/** @type {Event} */ event) => { + if (event.type !== "keydown") { + if (!popup.contains(/** @type {Node} */ (event.target))) + ask(popup, false, "outside"); + } else if (/** @type {KeyboardEvent} */ (event).key === "Escape") + ask(popup, false, "escape"); + }; + addEventListener("keydown", dismiss, true); + addEventListener("pointerdown", dismiss, true); + state.off = () => { + removeEventListener("keydown", dismiss, true); + removeEventListener("pointerdown", dismiss, true); + }; +} + +/** + * Open or close a popup as its user asks: a popup bound to state says so + * to its state instead, and shows what the state then holds. + * + * @param {HTMLElement} popup The popover. + * @param {boolean} open Whether to open it. + * @param {"escape" | "outside"} [why] What dismissed it. + * @returns {void} + */ +function ask(popup, open, why) { + const state = popups.get(popup); + if (!state) return; + clearTimeout(state.timer); + if (open === popup.matches(":popover-open")) return; + if (why) state.on?.[why]?.(); + state.on?.open?.(open); + if (!state.bound) set(popup, open); +} + +/** + * Keep a popup as its state says: the `ref` of the popover, called again + * whenever the page renders. + * + * The first time, the popup and what it opens under are given a name no + * other pair of the page has, which CSS places the popup by: the popups a + * loop renders share the id they are rendered with. + * + * @param {HTMLElement | null} popup The popover. + * @param {boolean | null} [open] Whether a popup bound to state is open. + * @param {Handlers | null} [on] What the popup does when it opens, closes + * or is dismissed. + * @returns {void} + */ +export function hoverSync(popup, open, on) { + if (!popup) return; + let state = popups.get(popup); + let wanted = open ?? null; + if (!state) { + popups.set(popup, (state = {})); + const trigger = triggerOf(popup); + if (trigger) { + const id = popup.id.startsWith("rx-") + ? `${popup.id}-${++ids}` + : popup.id; + if (trigger.getAttribute("aria-describedby") === popup.id) + trigger.setAttribute("aria-describedby", id); + trigger.dataset.rxHover = popup.id = id; + trigger.style.setProperty("anchor-name", `--${id}`); + popup.style.setProperty("position-anchor", `--${id}`); + } + if (popup.dataset.defaultOpen === "true") wanted ??= true; + } + state.on = on; + state.bound = open != null; + if (wanted !== null) set(popup, wanted); +} + +/** + * Follow the pointer and the focus on a popup and on what it opens under: + * the `onPointerEnter`, `onPointerLeave`, `onFocus`, `onBlur` and + * `onPointerDown` of either. + * + * The pointer opens the popup and closes it after the delays the popup + * says, so it can go from one to the other. The focus of the keyboard + * opens it at once, and closes it when it leaves both. A press on what a + * tooltip is on closes the tooltip. + * + * @param {{ type: string, currentTarget: HTMLElement, pointerType?: string, relatedTarget?: EventTarget | null }} event + * The pointer or the focus coming or going. + * @returns {void} + */ +export function hoverEvent(event) { + const element = event.currentTarget; + const popup = element.hasAttribute("popover") + ? element + : document.getElementById(element.dataset.rxHover ?? ""); + const state = popup && popups.get(popup); + const { type } = event; + const to = /** @type {Node | null} */ (event.relatedTarget ?? null); + if ( + !state || + event.pointerType === "touch" || + (type === "focus" && !element.matches(":focus-visible")) || + (type === "blur" && (popup.contains(to) || triggerOf(popup)?.contains(to))) + ) + return; + const open = type === "pointerenter" || type === "focus"; + const data = popup.dataset; + clearTimeout(state.timer); + state.timer = Number( + setTimeout( + () => ask(popup, open), + type === "pointerenter" || type === "pointerleave" + ? Number(open ? data.openDelay : data.closeDelay) + : 0, + ), + ); +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js new file mode 100644 index 00000000000..a214015b901 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js @@ -0,0 +1,254 @@ +// A popup that opens under the pointer and with the focus of the keyboard: +// when it opens and closes, what it says, and the state it follows. +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { installPopover } from "./popover.js"; + +/** @type {typeof import("$/reflex-ui/behaviors/hover.js")} */ +let api; +/** @type {HTMLElement} */ +let trigger; +/** @type {HTMLElement} */ +let popup; +/** @type {string[]} */ +let seen; + +/** + * Render a button and the popup that opens under it, and a second pair + * rendered with the same id, as a loop renders them. + * + * @param {string} [attributes] The attributes of the first popup. + * @returns {void} + */ +function render(attributes = 'role="tooltip"') { + document.body.innerHTML = ` + +
+ +
+ `; + trigger = /** @type {HTMLElement} */ (document.getElementById("save")); + popup = /** @type {HTMLElement} */ (trigger.nextElementSibling); +} + +const on = { + open: (/** @type {boolean} */ open) => seen.push(`open:${open}`), + escape: () => seen.push("escape"), + outside: () => seen.push("outside"), +}; + +beforeEach(async () => { + vi.resetModules(); + vi.useFakeTimers(); + vi.stubGlobal("CSS", { supports: () => true }); + installPopover(); + api = await import("$/reflex-ui/behaviors/hover.js"); + seen = []; + render(); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +/** + * Send what happens on a button or on its popup. + * + * @param {string} type The type of the event. + * @param {HTMLElement} [element] The element that hears it. + * @param {{ pointerType?: string, to?: HTMLElement | null }} [details] The + * kind of pointer, and where the focus goes. + * @returns {void} + */ +function send(type, element = trigger, { pointerType, to } = {}) { + api.hoverEvent({ + type, + currentTarget: element, + pointerType, + relatedTarget: to, + }); +} + +/** + * Say whether the popup is shown. + * + * @returns {boolean} Whether it is open. + */ +function shown() { + return popup.matches(":popover-open"); +} + +test("the first sync names each pair of a loop apart, for the browser to place the popup by", () => { + const second = /** @type {HTMLElement} */ ( + document.getElementById("copy")?.nextElementSibling + ); + api.hoverSync(popup, null, on); + api.hoverSync(second); + api.hoverSync(popup, null, on); + api.hoverSync(null); + expect([ + popup.id, + trigger.dataset.rxHover, + trigger.getAttribute("aria-describedby"), + trigger.style.getPropertyValue("anchor-name"), + popup.style.getPropertyValue("position-anchor"), + ]).toEqual([ + "rx-tip-1", + "rx-tip-1", + "rx-tip-1", + "--rx-tip-1", + "--rx-tip-1", + ]); + expect([ + second.id, + document.getElementById("copy")?.dataset.rxHover, + document.getElementById("copy")?.hasAttribute("aria-describedby"), + ]).toEqual(["rx-tip-2", "rx-tip-2", false]); +}); + +test("a popup an app named keeps its name, and one nothing opens is left alone", () => { + document.body.innerHTML = `
`; + const [mine, alone] = /** @type {HTMLElement[]} */ ([ + ...document.querySelectorAll("[popover]"), + ]); + api.hoverSync(mine); + api.hoverSync(alone); + expect([mine.id, alone.id]).toEqual(["mine", "rx-alone"]); +}); + +test("the pointer opens the popup after its delay, and closes it after the other", () => { + api.hoverSync(popup, null, on); + send("pointerenter"); + vi.advanceTimersByTime(199); + expect(shown()).toBe(false); + vi.advanceTimersByTime(1); + expect([shown(), trigger.dataset.state]).toEqual([true, "delayed-open"]); + send("pointerleave"); + vi.advanceTimersByTime(99); + expect(shown()).toBe(true); + // The pointer reached the popup in time. + send("pointerenter", popup); + vi.advanceTimersByTime(500); + expect(shown()).toBe(true); + send("pointerleave", popup); + vi.advanceTimersByTime(100); + expect([shown(), trigger.dataset.state]).toEqual([false, "closed"]); + expect(seen).toEqual(["open:true", "open:false"]); +}); + +test("a pointer that leaves before the delay opens nothing, and a finger opens nothing", () => { + api.hoverSync(popup, null, on); + send("pointerenter"); + vi.advanceTimersByTime(100); + send("pointerleave"); + vi.advanceTimersByTime(1000); + send("pointerenter", trigger, { pointerType: "touch" }); + vi.advanceTimersByTime(1000); + expect(shown()).toBe(false); + expect(seen).toEqual([]); +}); + +test("the focus of the keyboard opens the popup at once, and closes it when it leaves both", () => { + api.hoverSync(popup, null, on); + send("focus"); + vi.advanceTimersByTime(0); + expect(shown()).toBe(false); + const matches = trigger.matches.bind(trigger); + trigger.matches = (selector) => + selector === ":focus-visible" || matches(selector); + send("focus"); + vi.advanceTimersByTime(0); + expect(shown()).toBe(true); + send("blur", trigger, { to: document.getElementById("link") }); + send("blur", popup, { to: document.getElementById("save-text") }); + vi.advanceTimersByTime(0); + expect(shown()).toBe(true); + send("blur", popup, { to: document.getElementById("elsewhere") }); + vi.advanceTimersByTime(0); + expect(shown()).toBe(false); +}); + +test("Escape, a press outside and a press on the button of a tooltip close it", () => { + api.hoverSync(popup, null, on); + const open = () => { + send("pointerenter"); + vi.advanceTimersByTime(200); + }; + open(); + dispatchEvent(new KeyboardEvent("keydown", { key: "a" })); + expect(shown()).toBe(true); + dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(shown()).toBe(false); + // Once closed, the popup hears nothing of the page. + dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + open(); + document + .getElementById("link") + ?.dispatchEvent(new Event("pointerdown", { bubbles: true })); + expect(shown()).toBe(true); + document + .getElementById("elsewhere") + ?.dispatchEvent(new Event("pointerdown", { bubbles: true })); + expect(shown()).toBe(false); + open(); + send("pointerdown"); + vi.advanceTimersByTime(0); + expect(shown()).toBe(false); + expect(seen).toEqual([ + "open:true", + "escape", + "open:false", + "open:true", + "outside", + "open:false", + "open:true", + "open:false", + ]); +}); + +test("a popup bound to state says what is asked of it, and shows its state", () => { + render(""); + api.hoverSync(popup, false, on); + send("pointerenter"); + vi.advanceTimersByTime(200); + expect(shown()).toBe(false); + api.hoverSync(popup, true, on); + expect([shown(), trigger.dataset.state]).toEqual([true, "open"]); + api.hoverSync(popup, true, on); + dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(shown()).toBe(true); + api.hoverSync(popup, false, on); + expect(shown()).toBe(false); + expect(seen).toEqual(["open:true", "escape", "open:false"]); +}); + +test("a popup that starts open opens once, and one that is unknown is left alone", () => { + render('data-default-open="true"'); + send("pointerenter"); + vi.advanceTimersByTime(1000); + expect(shown()).toBe(false); + api.hoverSync(popup); + expect(shown()).toBe(true); + send("pointerleave"); + vi.advanceTimersByTime(100); + api.hoverSync(popup); + expect(shown()).toBe(false); + trigger.dataset.rxHover = "gone"; + send("pointerenter"); + delete trigger.dataset.rxHover; + send("pointerenter"); +}); + +test("a browser without anchor positioning has the popup placed by a script", async () => { + vi.resetModules(); + vi.stubGlobal("CSS", { supports: () => false }); + const place = vi.fn(); + vi.doMock("$/reflex-ui/behaviors/popup-position.js", () => ({ place })); + api = await import("$/reflex-ui/behaviors/hover.js"); + api.hoverSync(popup); + send("pointerenter"); + vi.advanceTimersByTime(200); + await vi.waitFor(() => expect(place.mock.calls).toEqual([[popup, trigger, true]])); + vi.doUnmock("$/reflex-ui/behaviors/popup-position.js"); +}); diff --git a/packages/reflex-components-ui/news/+wave4-overlays.feature.md b/packages/reflex-components-ui/news/+wave4-overlays.feature.md index 509f91bdae4..f8b9d00dab5 100644 --- a/packages/reflex-components-ui/news/+wave4-overlays.feature.md +++ b/packages/reflex-components-ui/news/+wave4-overlays.feature.md @@ -1,7 +1,9 @@ -Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog`, `alert_dialog`, `drawer` and `popover`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog, an alert dialog and a drawer are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. +Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog`, `alert_dialog`, `drawer`, `popover` and `tooltip`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog, an alert dialog and a drawer are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. A button whose popup is open has the look Radix Themes gives it (`[data-state='open']`), which `rx.ui.button` did not have. `rx.ui.drawer` slides in from an edge of the page and is closed by Escape, by a press beside its panel and by its close button. It is not dragged, so `snap_points` and the other props that describe the drag of `rx.drawer` do nothing. `rx.ui.popover` is a native popover placed beside its trigger by CSS anchor positioning: the browser opens and closes it without JavaScript. It is not modal, and closes when the focus leaves it. + +`rx.ui.tooltip` always describes its child to assistive technology, shown or not, and has no arrow. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index af8481e3e80..7d7dd418478 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -438,3 +438,20 @@ component = "popover" step = "the dark appearance of a theme around a popover reaches it" system = "rx" reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a popover included. rx.ui.theme does, and a popover declared inside a dark rx.ui.theme is dark." + +[[contract]] +component = "tooltip" +step = "describes its button with JavaScript disabled" +system = "rx" +reason = "rx.tooltip renders its text when it opens, and names it as the description of its child only then. The text of rx.ui.tooltip is in the page from the start and always describes its child, so a screen reader reads it whether the tooltip is shown or not, with or without JavaScript; showing it under the pointer waits for JavaScript." + +[[contract]] +component = "tooltip" +step = "points at its button with an arrow" +reason = "rx.ui.tooltip has no arrow. It is where the tooltip of rx.tooltip is, the room of the arrow included, and is placed by the browser, which turns it over where it would leave the page: an arrow drawn by its styles could not follow it. `arrow_padding` has nothing to say." + +[[contract]] +component = "tooltip" +step = "the dark appearance of a theme around a tooltip reaches it" +system = "rx" +reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a tooltip included. rx.ui.theme does, and a tooltip declared inside a dark rx.ui.theme has the colors of the dark appearance." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py b/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py new file mode 100644 index 00000000000..1c38723895c --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py @@ -0,0 +1,402 @@ +"""The tooltip: on each side of what it describes, and when it opens and closes.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, LIGHT, Matrix +from ui_parity.samples import wait_for_text + +SIDES = ["top", "right", "bottom", "left"] +ALIGNS = ["start", "center", "end"] +OPEN = "open" +# A tooltip that is shown, in either system. +SHOWN = ".rt-TooltipContent, [role=tooltip]:popover-open" +LONG = ( + "A tooltip with more to say than one line holds, which wraps where a " + "tooltip is as wide as it may be." +) + + +def _tooltip(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a button with a tooltip. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the tooltip. ``long`` asks for a text of + several lines, and ``themed`` for a theme of another radius + around it. + + Returns: + The button, with room around it for its tooltip on any side. + """ + props = dict(props) + long, themed = props.pop("long", False), props.pop("themed", False) + shown = namespace.tooltip( + namespace.button("Save", width="80px"), + content=LONG if long else "Saves the file", + # The cells do not wait for the pointer to rest. + delay_duration=0, + # On the pixel grid wherever it is beside its button: Radix rounds + # where it puts a tooltip, and the browser does not. + width="260px" if long else "120px", + **props, + ) + if themed: + shown = namespace.theme(shown, radius="full") + return rx.el.div(shown, style={"padding": "70px 0 0 150px"}) + + +def _show(page: Page, target: Locator, point: Point) -> None: + """Put the pointer on what a tooltip describes, and wait for the tooltip. + + Args: + page: The page. + target: The button. + point: The middle of the button. + """ + page.mouse.move(*point) + page.locator(SHOWN).first.wait_for() + + +def leave(page: Page) -> None: + """Take the pointer off a button and its tooltip. + + Args: + page: The page. + """ + # Twice: Radix looks where the pointer went when it moves again. + page.mouse.move(0, 0) + page.mouse.move(2, 2) + + +def _hide(page: Page, target: Locator, point: Point) -> None: + """Take the pointer off, and wait until the tooltip is gone. + + Args: + page: The page. + target: The button. + point: The middle of the button. + """ + leave(page) + page.locator(SHOWN).first.wait_for(state="detached") + + +MATRIX = Matrix( + component="tooltip", + render=_tooltip, + sweep={ + "side": SIDES, + "long": [True], + "appearance": [DARK], + "state": [FOCUS_VISIBLE, OPEN], + }, + groups=[ + {"side": SIDES, "align": ALIGNS, "state": [OPEN]}, + {"side": SIDES, "side_offset": [0, 12], "state": [OPEN]}, + {"long": [True], "side": ["top", "bottom"], "state": [OPEN]}, + {"themed": [True], "state": [OPEN]}, + {"state": [FOCUS_VISIBLE, OPEN], "appearance": [LIGHT, DARK]}, + ], + stage=(480, 200), + crop="stage", + target="button", + states={ + OPEN: State( + enter=_show, + leave=_hide, + matches=":is([data-state='delayed-open'], [data-state='instant-open'])", + ) + }, + # Held to a threshold of zero, and to the arrow: the tooltip of Radix has + # one between it and its button, of 16 to 27 pixels of 96000, and the + # one here has none. Nothing else differs in any cell. + threshold=0, + tolerance=0.0003, +) + + +class TooltipState(rx.State): + """What the tooltips of the contract are bound to.""" + + shown: rx.Field[bool] = rx.field(False) + seen: rx.Field[list[str]] = rx.field(default_factory=list) + + @rx.event + def set_shown(self, value: bool): + """Follow the bound tooltip. + + Args: + value: Whether it is open. + """ + self.shown = value + + @rx.event + def see_open(self, value: bool): + """Keep whether a tooltip opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def see(self, what: str): + """Keep what happened to a tooltip. + + Args: + what: The event. + """ + self.seen.append(what) + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + Buttons with a tooltip: one that says what happens to it, one that + opens at once, one whose tooltip the pointer cannot rest on, one + bound to state, one in a dialog and one in a dark theme. + """ + tooltip, dialog, button = namespace.tooltip, namespace.dialog, namespace.button + return namespace.flex( + tooltip( + button("Save", id="save"), + content="Saves the file", + on_open_change=TooltipState.see_open, + on_escape_key_down=TooltipState.see("escape"), + on_pointer_down_outside=TooltipState.see("outside"), + ), + tooltip(button("Copy", id="copy"), content="Copies the text", delay_duration=0), + tooltip( + button("Cut", id="cut"), + content="Cuts the text", + delay_duration=0, + disable_hoverable_content=True, + ), + tooltip( + button("Bound", id="bound"), + content="Follows its state", + open=TooltipState.shown, + on_open_change=TooltipState.set_shown, + ), + rx.el.button("Show", id="show", on_click=TooltipState.set_shown(True)), + dialog.root( + dialog.trigger(button("Dialog", id="dialog-open")), + dialog.content( + dialog.title("With a tooltip"), + tooltip( + button("Inside", id="inside"), + content="In a dialog", + delay_duration=0, + ), + id="dialog-panel", + ), + ), + namespace.theme( + tooltip(button("Dark", id="dark"), content="In the dark", delay_duration=0), + appearance="dark", + ), + rx.el.span(TooltipState.seen.to_string(), id="seen"), + rx.el.span(TooltipState.shown.to_string(), id="shown"), + spacing="4", + padding="60px 0 0 0", + wrap="wrap", + ) + + +CONTRACT = Contract(component="tooltip", render=_contract) + +# The text of each tooltip that is shown. +SHOWING = ( + "[...document.querySelectorAll('.rt-TooltipContent, [role=tooltip]:popover-open')]" + ".map(tooltip => tooltip.querySelector('p').textContent)" +) +# What describes an element to assistive technology, by its id. +DESCRIBED = ( + "id => (document.getElementById(document.getElementById(id)" + ".getAttribute('aria-describedby') ?? '')?.textContent ?? null)" +) + + +def _wait_for_shown(run: Run, *texts: str) -> None: + """Wait until the tooltips that are shown are the ones expected. + + Args: + run: The run, on a page. + *texts: The text of each tooltip that is to be shown. + """ + run.page.wait_for_function( + f"texts => JSON.stringify({SHOWING}) === JSON.stringify(texts)", + arg=list(texts), + ) + + +def _shown(run: Run) -> list[str]: + """Read which tooltips are shown. + + Args: + run: The run, on a page. + + Returns: + The text of each. + """ + return run.page.evaluate(SHOWING) + + +@CONTRACT.step("what it describes is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + button = run.server.element("save") + assert (button.tag, button.text) == ("button", "Save") + + +@CONTRACT.step("describes its button with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + assert run.page.evaluate(DESCRIBED, "save") == "Saves the file" + assert _shown(run) == [] + + +@CONTRACT.step( + "opens once the pointer has rested on its button, and closes when it leaves" +) +def _hover(run: Run) -> None: + page = run.page + page.locator("#save").hover() + page.wait_for_timeout(100) + assert _shown(run) == [] + _wait_for_shown(run, "Saves the file") + leave(page) + _wait_for_shown(run) + wait_for_text(page, "seen", '["open","closed"]') + + +@CONTRACT.step("opens with the focus of the keyboard, and closes when it leaves") +def _focus(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + _wait_for_shown(run, "Saves the file") + page.keyboard.press("Tab") + _wait_for_shown(run, "Copies the text") + page.keyboard.press("Shift+Tab") + _wait_for_shown(run, "Saves the file") + + +@CONTRACT.step("is the description of its button while it is shown") +def _described(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + _wait_for_shown(run, "Saves the file") + assert page.evaluate(DESCRIBED, "save") == "Saves the file" + assert page.get_by_role("tooltip").count() == 1 + + +@CONTRACT.step("Escape closes it, with the focus and under the pointer, and says so") +def _escape(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + _wait_for_shown(run, "Saves the file") + page.keyboard.press("Escape") + _wait_for_shown(run) + wait_for_text(page, "seen", '["open","escape","closed"]') + page.locator("#copy").hover() + _wait_for_shown(run, "Copies the text") + page.keyboard.press("Escape") + _wait_for_shown(run) + + +@CONTRACT.step("a press on its button closes it") +def _press(run: Run) -> None: + page = run.page + page.locator("#copy").hover() + _wait_for_shown(run, "Copies the text") + page.mouse.down() + _wait_for_shown(run) + page.mouse.up() + page.wait_for_timeout(300) + assert _shown(run) == [] + + +@CONTRACT.step("the pointer can go from the button to its tooltip") +def _hoverable(run: Run) -> None: + page = run.page + page.locator("#copy").hover() + _wait_for_shown(run, "Copies the text") + box = page.locator(SHOWN).first.bounding_box() + assert box is not None + page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, steps=4) + page.wait_for_timeout(400) + assert _shown(run) == ["Copies the text"] + leave(page) + _wait_for_shown(run) + + +@CONTRACT.step("a tooltip the pointer cannot rest on closes when it leaves the button") +def _not_hoverable(run: Run) -> None: + page = run.page + page.locator("#cut").hover() + _wait_for_shown(run, "Cuts the text") + box = page.locator(SHOWN).first.bounding_box() + assert box is not None + page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, steps=4) + _wait_for_shown(run) + + +@CONTRACT.step("a tooltip bound to state follows it") +def _bound(run: Run) -> None: + page = run.page + page.locator("#show").click() + _wait_for_shown(run, "Follows its state") + wait_for_text(page, "shown", "true") + page.keyboard.press("Escape") + _wait_for_shown(run) + wait_for_text(page, "shown", "false") + page.locator("#bound").hover() + _wait_for_shown(run, "Follows its state") + wait_for_text(page, "shown", "true") + + +@CONTRACT.step("a tooltip in a dialog shows over it") +def _in_dialog(run: Run) -> None: + page = run.page + page.locator("#dialog-open").click() + page.locator("#dialog-panel").wait_for() + page.locator("#inside").hover() + _wait_for_shown(run, "In a dialog") + box = page.locator(SHOWN).first.bounding_box() + assert box is not None + assert page.evaluate( + "([x, y]) => document.elementFromPoint(x, y).closest(" + "'.rt-TooltipContent, [role=tooltip]') !== null", + [box["x"] + box["width"] / 2, box["y"] + box["height"] / 2], + ) + page.keyboard.press("Escape") + _wait_for_shown(run) + page.locator("#dialog-panel").wait_for() + + +@CONTRACT.step("points at its button with an arrow") +def _arrow(run: Run) -> None: + page = run.page + page.locator("#copy").hover() + _wait_for_shown(run, "Copies the text") + assert page.locator(SHOWN).first.locator("svg").count() == 1 + + +@CONTRACT.step("the dark appearance of a theme around a tooltip reaches it") +def _themed_dark(run: Run) -> None: + page = run.page + page.locator("#dark").hover() + _wait_for_shown(run, "In the dark") + page.wait_for_timeout(300) + assert page.locator(SHOWN).first.evaluate( + "element => getComputedStyle(element).backgroundColor" + ) == ("rgb(238, 238, 238)") 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 7a8cf596e70..89bde244a98 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -40,6 +40,7 @@ "components.tabs": ["tabs"], "components.text_area": ["text_area"], "components.text_field": ["input", "text_field"], + "components.tooltip": ["tooltip"], "layout.box": ["box"], "layout.center": ["center"], "layout.container": ["container"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py index c0c0aa0f6dc..f88f1c2bbaa 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py @@ -50,17 +50,24 @@ def pixels(amount: Any) -> Any: ) -def offsets(props: dict[str, Any]) -> None: +def offsets(props: dict[str, Any], gap: int = 0) -> None: """Put how far a popup is from its anchor before its other styles. Args: props: The props a popup is created with, changed in place: its ``side_offset`` and its ``align_offset`` become custom properties the placement of the popup reads. + gap: The room, in pixels, the popup leaves beside its anchor on top + of the distance it is asked to keep. """ distances = { - name: pixels(props[prop]) - for prop, name in (("side_offset", OFFSET), ("align_offset", SHIFT)) + name: pixels( + literal(LiteralVar.create(props[prop])) + extra if extra else props[prop] + ) + for prop, name, extra in ( + ("side_offset", OFFSET, gap), + ("align_offset", SHIFT, 0), + ) if props.get(prop) is not None } if distances: @@ -247,6 +254,32 @@ class PopupContent(PopupPart): # The role of the popup. _role: ClassVar[str | None] = "dialog" + # The room the popup leaves beside its anchor on top of its offset. + _gap: ClassVar[int] = 0 + + # Whether the browser closes the popup on Escape and on a press outside + # it (``auto``), or its script does (``manual``). + _popover: ClassVar[str] = "auto" + + # Whether the popup takes the focus from its script. + _tab_index: ClassVar[int | None] = -1 + + # The script of the popup: its name, what keeps the popup as its state + # says, and what hears the events named after them. + _script: ClassVar[tuple[str, ...]] = ( + "popup", + "popupSync", + "popupEvent", + "onToggle", + "onKeyDown", + "onClick", + "onBlur", + ) + + # Whether what the popup does is handed to what keeps it as its state + # says, rather than to what hears its events. + _synced: ClassVar[bool] = False + @classmethod def create(cls, *children: Any, **props: Any) -> Component: """Create a popup. @@ -258,7 +291,7 @@ def create(cls, *children: Any, **props: Any) -> Component: Returns: The popup, as far from its anchor as it is asked to be. """ - offsets(props) + offsets(props, cls._gap) return super().create(*children, **props) def _post_init(self, *args, **kwargs): @@ -302,8 +335,9 @@ def _get_vars( Each var referenced by the component. """ yield from super()._get_vars(include_children, ignore_ids) - yield script("popup", "popupSync") - yield script("popup", "popupEvent") + module, sync, heard = self._script[:3] + yield script(module, sync) + yield script(module, heard) if self._open is not None: yield self._open @@ -336,29 +370,104 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: to its script, and through it to the events. """ tag, on = handlers(super()._render(props), _EVENTS) + module, sync_name, heard, *events = self._script bound = LiteralVar.create(self._open) - sync = script("popup", "popupSync") + sync = script(module, sync_name) + handed = f", {on!s}" if self._synced and on is not None else "" tag = tag.add_props(**{ - "popover": "auto", + "popover": self._popover, "role": self._role, - "tabIndex": -1, + "tabIndex": self._tab_index, "data-rx-popup": "", **self._popup, # Called whenever the page renders: a popup bound to state takes # whether it is open from there. "ref": Var( - f"((popup) => popupSync(popup, {bound!s}))", + f"((popup) => {sync_name}(popup, {bound!s}{handed}))", _var_data=VarData.merge( - sync._get_all_var_data(), bound._get_all_var_data() + sync._get_all_var_data(), + bound._get_all_var_data(), + on._get_all_var_data() if handed and on is not None else None, ), ), }) return listen( tag, - script("popup", "popupEvent"), - "onToggle", - "onKeyDown", - "onClick", - "onBlur", - arguments=() if on is None else (on,), + script(module, heard), + *events, + arguments=() if on is None or self._synced else (on,), ) + + +class HoverTrigger(PopupTrigger): + """What a popup opens under: its child, which hears the pointer and the focus.""" + + # What the trigger hears of. + _heard: ClassVar[tuple[str, ...]] = ( + "onPointerEnter", + "onPointerLeave", + "onFocus", + "onBlur", + ) + + def _join(self, root: PopupRoot | None, name: Any, on_open_change: Any) -> None: + """Take the id of the popup that opens under the trigger. + + Args: + root: The popup the trigger is in. + name: The id of the popup. + on_open_change: What the popup does when it opens or closes. + """ + self._popup = {"data-rx-hover": name} + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the trigger, its script 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 script("hover", "hoverEvent") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, which opens its popup under the pointer + and with the focus of the keyboard. + """ + tag = UIComponent._render(self, props).add_props(**{ + "data-state": "closed", + **self._popup, + }) + return listen(tag, script("hover", "hoverEvent"), *self._heard) + + +class HoverContent(PopupContent): + """A popup that opens under the pointer and with the focus of the keyboard.""" + + _role: ClassVar[str | None] = None + + _popover: ClassVar[str] = "manual" + + _tab_index: ClassVar[int | None] = None + + _script: ClassVar[tuple[str, ...]] = ( + "hover", + "hoverSync", + "hoverEvent", + "onPointerEnter", + "onPointerLeave", + "onBlur", + ) + + _synced: ClassVar[bool] = True diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py index d4bccb1dccd..0558386ee1c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py @@ -47,12 +47,13 @@ def become_child(part: UIComponent) -> None: or not isinstance(children[0], Component) or type(children[0]).render not in (Component.render, UIComponent.render) ): + name = part._display_name() # pyright: ignore[reportAttributeAccessIssue] msg = ( - f"{type(part)._display_name()}: it is rendered as its child, so it " - "needs exactly one child that is an element, such as a button." + f"{name}: it is rendered as its child, so it needs exactly one " + "child that is an element, such as a button." ) raise StyleError(msg) - part._as_child = True + part._as_child = True # pyright: ignore[reportAttributeAccessIssue] # The child has to stay the child: a compile would otherwise move one # that is bound to state into a component of its own. part._memoization_mode = dataclasses.replace( diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py new file mode 100644 index 00000000000..764a47a72c9 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py @@ -0,0 +1,219 @@ +"""A tooltip: a native ``popover`` that opens under the pointer and with the focus.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, field +from reflex_base.components.tags import CommonTag +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import Var +from reflex_components_core.base.fragment import Fragment + +from reflex_components_ui.base import Part +from reflex_components_ui.components import _popup +from reflex_components_ui.components._group import choose, literal +from reflex_components_ui.components._popup import HoverContent, HoverTrigger +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.tooltip import ARROW, TOOLTIP + +LiteralSideType = Literal[ + "top", + "right", + "bottom", + "left", +] + +LiteralAlignType = Literal[ + "start", + "center", + "end", +] + +LiteralStickyType = Literal[ + "partial", + "always", +] + +ARIA_LABEL_KEY = "aria_label" + +# How long the pointer rests on something before its tooltip opens, as in +# Radix Themes, and how long a tooltip waits for the pointer to reach it, in +# milliseconds. +_OPEN_DELAY = 200 +_CLOSE_DELAY = 100 + + +class TooltipTrigger(HoverTrigger): + """What a tooltip describes: the child of the tooltip.""" + + # A press on what a tooltip is on closes the tooltip. + _heard: ClassVar[tuple[str, ...]] = (*HoverTrigger._heard, "onPointerDown") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: the child, which its tooltip describes whether it is + shown or not. + """ + return ( + super() + ._render(props) + .add_props(**{"aria-describedby": self._popup.get("data-rx-hover")}) + ) + + +class Tooltip(HoverContent): + """Floating element that provides a control with contextual information via pointer or focus.""" + + styles: ClassVar[ComponentStyles] = TOOLTIP + + _role: ClassVar[str | None] = "tooltip" + + # A tooltip is as far from what it describes as the one of Radix, which + # has an arrow between the two. + _gap: ClassVar[int] = ARROW + + content: Var[str] = field(doc="The content of the tooltip.") + + default_open: Var[bool] = field( + doc="The open state of the tooltip when it is initially rendered. Use when you do not need to control its open state." + ) + + open: Var[bool] = field( + doc="The controlled open state of the tooltip. Must be used in conjunction with `on_open_change`." + ) + + side: Var[LiteralSideType] = field( + doc='The preferred side of the trigger to render against when open. Will be reversed when collisions occur and `avoid_collisions` is enabled. Defaults to "top".' + ) + + side_offset: Var[float | int] = field( + doc="The distance in pixels from the trigger. Defaults to 0." + ) + + align: Var[LiteralAlignType] = field( + doc='The preferred alignment against the trigger. May change when collisions occur. Defaults to "center".' + ) + + align_offset: Var[float | int] = field( + doc='An offset in pixels from the "start" or "end" alignment options.' + ) + + avoid_collisions: Var[bool] = field( + doc="When true, overrides the side and align preferences to prevent collisions with boundary edges. Defaults to True." + ) + + collision_padding: Var[float | int | dict[str, float | int]] = field( + doc='The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { "top": 20, "left": 20 }. Defaults to 0.' + ) + + arrow_padding: Var[float | int] = field( + doc="The padding between the arrow and the edges of the content. If your content has border-radius, this will prevent it from overflowing the corners. Defaults to 0." + ) + + sticky: Var[LiteralStickyType] = field( + doc='The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".' + ) + + hide_when_detached: Var[bool] = field( + doc="Whether to hide the content when the trigger becomes fully occluded. Defaults to False." + ) + + delay_duration: Var[float | int] = field( + doc="Override the duration in milliseconds to customize the open delay for a specific tooltip. Default is 700." + ) + + disable_hoverable_content: Var[bool] = field( + doc="Prevents Tooltip content from remaining open when hovering." + ) + + force_mount: Var[bool] = field( + doc="Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries." + ) + + aria_label: Var[str] = field( + doc="By default, screenreaders will announce the content inside the component. If this is not descriptive enough, or you have content that cannot be announced, use aria-label as a more descriptive label." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the tooltip." + ) + + @classmethod + def create(cls, *children, **props) -> Component: + """Initialize the Tooltip component. + + Run some additional handling on the props. + + Args: + *children: The positional arguments + **props: The keyword arguments + + Returns: + The created component: what the tooltip describes, then the + tooltip, a popup that holds its text. + """ + label = props.pop(ARIA_LABEL_KEY, None) + if label is not None: + props.setdefault("custom_attrs", {})["aria-label"] = label + popup = super().create( + Part.create(props.get("content"), part="text", tag="p"), **props + ) + trigger = TooltipTrigger.create(*children) + name = popup.id if popup.id is not None else f"rx-tooltip-{next(_popup._ids)}" + popup._join(None, name, None) + trigger._join(None, name, None) + return Fragment.create(trigger, popup) + + def _join(self, root: Any, name: Any, on_open_change: Any) -> None: + """Take the name of the tooltip, and what its script reads. + + Args: + root: Nothing: a tooltip has no root. + name: The id of the tooltip. + on_open_change: Nothing: the tooltip has the event itself. + """ + if self.id is None: + self._popup["id"] = name + self._open = self.open + if self.default_open is not None: + self._popup["data-default-open"] = self.default_open + delay = self.delay_duration + self._popup["data-open-delay"] = _OPEN_DELAY if delay is None else delay + still = self.disable_hoverable_content + self._popup["data-close-delay"] = ( + _CLOSE_DELAY if still is None else choose(literal(still), 0, _CLOSE_DELAY) + ) + + def _exclude_props(self) -> list[str]: + """Keep the props that are no attributes off the element. + + Returns: + The props read as styles, and what the tooltip hands its text + and its script. + """ + return [ + *super()._exclude_props(), + "content", + "default_open", + "open", + "arrow_padding", + "delay_duration", + "aria_label", + ] + + +tooltip = Tooltip.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py index 60642c543bc..7a094b5ee55 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py @@ -4,6 +4,8 @@ from typing import Any +from reflex_components_ui.style import CompoundStyle, unchecked + # A popup that is open, and the element before it that opens it. A style # of that element selects on the second: no script says that it is open. OPEN = ":popover-open" @@ -113,7 +115,7 @@ def placement(side: str, align: str, default_offset: str = "0px") -> dict[str, A return style -def placements(default_offset: str = "0px") -> list[dict[str, Any]]: +def placements(default_offset: str = "0px") -> list[CompoundStyle]: """Make the compound variants that place a popup by its side and alignment. Args: @@ -125,7 +127,7 @@ def placements(default_offset: str = "0px") -> list[dict[str, Any]]: return [ { "props": {"side": side, "align": align}, - "style": placement(side, align, default_offset), + "style": unchecked(placement(side, align, default_offset)), } for side, align in _AREAS ] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py new file mode 100644 index 00000000000..3c63d594437 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py @@ -0,0 +1,52 @@ +"""The look of a tooltip: a small dark popup beside what it describes.""" + +from __future__ import annotations + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.popup import OPEN, POPUP, placements +from reflex_components_ui.styles.typography import SIZE + +_MOTION = "@media (prefers-reduced-motion: no-preference)" + +# How far a tooltip is from what it describes unless it says, and the room +# Radix Themes leaves between the two for its arrow, in pixels: a tooltip +# here has no arrow, and is where the one of Radix is. +OFFSET_DEFAULT = 4 +ARROW = 5 + +TOOLTIP: ComponentStyles = { + "base": unchecked({ + **POPUP, + "overflow": "visible", + "box_sizing": "border-box", + "padding": f"{tokens.space[1]} {tokens.space[2]}", + "background_color": tokens.gray[12], + "border_radius": tokens.radius[2], + "max_width": "min(360px, calc(100vw - 20px))", + # It comes in, and is gone at once. + "transition_duration": { + "default": "0s", + _MOTION: {"default": "0s", OPEN: "140ms"}, + }, + }), + "variants": { + # A tooltip the pointer cannot rest on lets it through. + "disable_hoverable_content": {"true": {"pointer_events": "none"}}, + }, + "defaults": {"side": "top", "align": "center"}, + "compound": placements(f"{OFFSET_DEFAULT + ARROW}px"), + "parts": { + "text": { + "base": unchecked({ + "margin": "0", + "line_height": f"var(--line-height, {tokens.default.line_height})", + "letter_spacing": "var(--letter-spacing, inherit)", + **SIZE["1"], + "color": tokens.gray[1], + "user_select": "none", + "cursor": "default", + }), + }, + }, +} diff --git a/pyi_hashes.json b/pyi_hashes.json index 29e0f15ab16..bcbac8b2c93 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,11 +118,12 @@ "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": "3baaa214d298bb98db3eae02bb2911e4", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "7687d1b67f180df8c3c1b1a69610a3f0", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "6eb205093043e7acf44767d415a25f0b", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "0d7b27ab1cb51ac891a31ed97f2f5567", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "61cffb40e8f047c944b54e51ac36cbc7", + "packages/reflex-components-ui/src/reflex_components_ui/components/_popup.pyi": "80f094441cee591fff2e06d6e315dcc0", "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "4abb8482e413aa9ee3d941ef12878c1a", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", @@ -140,6 +141,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", + "packages/reflex-components-ui/src/reflex_components_ui/components/popover.pyi": "f50b0a5a30a0331f2a8e5dc28d8763cf", "packages/reflex-components-ui/src/reflex_components_ui/components/progress.pyi": "ba32f562c590556d634f16062120fa34", "packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.pyi": "0a0f621c1ceed962d86896ad1600e98f", "packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.pyi": "e7f9c6ffd5f3d882ebe2fa4c06c0bcd0", diff --git a/tests/units/reflex_components_ui/components/test_tooltip.py b/tests/units/reflex_components_ui/components/test_tooltip.py new file mode 100644 index 00000000000..aecceac3635 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_tooltip.py @@ -0,0 +1,242 @@ +"""Tests for reflex_components_ui.components.tooltip.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import _popup +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the popups of each test from one.""" + monkeypatch.setattr(_popup, "_ids", itertools.count(1)) + + +def test_tooltip( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A tooltip is its child, which it describes, then a popover with its text, which a script opens under the pointer and with the focus.""" + component = rx.ui.tooltip( + rx.el.button("Save", id="save"), + content="Saves the file", + side="bottom", + align="start", + side_offset=6, + delay_duration=0, + disable_hoverable_content=True, + default_open=True, + aria_label="Save", + max_width="200px", + ) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-describedby":"rx-tooltip-1"', + '"data-rx-hover":"rx-tooltip-1"', + '"data-state":"closed"', + 'id:"save"', + "onBlur:hoverEvent", + "onFocus:hoverEvent", + "onPointerDown:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + "ref:ref_save", + ], + "children": [{"contents": '"Save"'}], + }, + { + "name": '"div"', + "props": [ + '"aria-label":"Save"', + "className:sx_6a0d355fdc_c", + '"data-close-delay":0', + '"data-default-open":true', + '"data-open-delay":0', + '"data-rx-popup":""', + 'id:"rx-tooltip-1"', + "onBlur:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + 'popover:"manual"', + "ref:((popup) => hoverSync(popup, null))", + 'role:"tooltip"', + ], + "children": [ + { + "name": '"p"', + "props": ["className:sx_7f6c9bc5c4_c"], + "children": [{"contents": '"Saves the file"'}], + } + ], + }, + ], + } + assert declared_styles(component) == [ + {}, + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "var(--rx-popup-offset, 9px)", + "marginRight": "0", + "marginBottom": "var(--rx-popup-offset, 9px)", + "marginLeft": "var(--rx-popup-shift, 0px)", + "paddingTop": "var(--space-1)", + "paddingRight": "var(--space-2)", + "paddingBottom": "var(--space-1)", + "paddingLeft": "var(--space-2)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "none", + "borderRightStyle": "none", + "borderBottomStyle": "none", + "borderLeftStyle": "none", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "200px", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "0s", + ":popover-open": "140ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "overflowX": "visible", + "overflowY": "visible", + "backgroundColor": "var(--gray-12)", + "borderTopLeftRadius": "var(--radius-2)", + "borderTopRightRadius": "var(--radius-2)", + "borderBottomRightRadius": "var(--radius-2)", + "borderBottomLeftRadius": "var(--radius-2)", + "pointerEvents": "none", + "positionArea": "bottom span-right", + "maxHeight": "calc(100% - var(--rx-popup-offset, 9px) - 10px)", + "--rx-popup-from": "translateY(-4px) scale(0.97)", + "transformOrigin": "top left", + "--rx-popup-offset": "11px", + }, + { + "marginTop": "0", + "marginRight": "0", + "marginBottom": "0", + "marginLeft": "0", + "lineHeight": "var(--line-height, var(--default-line-height))", + "letterSpacing": "var(--letter-spacing, inherit)", + "fontSize": "var(--font-size-1)", + "--line-height": "var(--line-height-1)", + "--letter-spacing": "var(--letter-spacing-1)", + "color": "var(--gray-1)", + "userSelect": "none", + "cursor": "default", + }, + ] + + +class TooltipState(rx.State): + """What a tooltip is bound to.""" + + shown: bool = False + still: bool = False + + @rx.event + def set_shown(self, shown: bool): + """Follow the tooltip. + + Args: + shown: Whether it is open. + """ + self.shown = shown + + +def test_tooltip_bound_to_state(ui_plugin: UIPlugin): + """A tooltip bound to state hands its script its state and what it does when it is asked to open or close.""" + name = TooltipState.get_full_name() + component = rx.ui.tooltip( + rx.el.button("Save"), + content="Saves the file", + open=TooltipState.shown, + on_open_change=TooltipState.set_shown, + disable_hoverable_content=TooltipState.still, + ) + trigger, popup = component.render()["children"] + assert trigger["props"] == [ + '"aria-describedby":"rx-tooltip-1"', + '"data-rx-hover":"rx-tooltip-1"', + '"data-state":"closed"', + "onBlur:hoverEvent", + "onFocus:hoverEvent", + "onPointerDown:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + ] + assert popup["props"] == [ + f'className:sx_7d0b44bf5e_c + " " + (sx_7d0b44bf5e_0[{TooltipState.still!s}] ?? "")', + f'"data-close-delay":({TooltipState.still!s} ? 0 : 100)', + '"data-open-delay":200', + '"data-rx-popup":""', + 'id:"rx-tooltip-1"', + "onBlur:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + 'popover:"manual"', + ( + f"ref:((popup) => hoverSync(popup, {TooltipState.shown!s}, ({{ open: " + f'((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' + '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))) })))' + ), + 'role:"tooltip"', + ] + + +def test_tooltip_imports_its_script(ui_plugin: UIPlugin): + """A page with a tooltip loads the script of the popups that open under the pointer, and no other.""" + component = rx.ui.tooltip(rx.el.button("Save"), content="Saves the file") + imports = component._get_all_imports() + assert { + module: names for module, names in imports.items() if "behaviors" in module + } == { + "$/reflex-ui/behaviors/hover.js": [ + ImportVar(tag="hoverEvent"), + ImportVar(tag="hoverSync"), + ], + } + + +def test_tooltip_needs_an_element_to_describe(ui_plugin: UIPlugin): + """A tooltip on anything but one element fails with the name of the component.""" + with pytest.raises(StyleError) as error: + rx.ui.tooltip("Save", content="Saves the file") + assert str(error.value) == ( + "rx.ui.tooltip_trigger: it is rendered as its child, so it needs exactly " + "one child that is an element, such as a button." + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index ee4a52d136d..853567b78b2 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -234,6 +234,7 @@ def test_every_wave_is_in_the_namespace(): "text_field", "text_field.slot", "theme", + "tooltip", "unordered_list", "vstack", ] From 85fa2a4c151f55c2700c44e7815ae9dcc1441ba3 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 22:18:58 +0000 Subject: [PATCH 128/204] Read the order of the sides of a select from its field Var caches its aliases with Literals that differ only in order as equal, so the field of rx.ui.select.content holds the order of whichever module wrote Var of top, bottom, left and right first: drawer and recharts write another one. A fresh Literal in the test did not go through that cache, and every unit-test leg on 708d0c359 failed on the order. Claude-Session: https://claude.ai/code/session_014AwvTPqrAAUS9U2MqKfT3k --- .../reflex_components_ui/components/test_select.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index 87ce0ed8cd5..50003b64609 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -3,7 +3,7 @@ import itertools import re from collections.abc import Callable -from typing import Any, Literal, get_args +from typing import Any, get_args import pytest from reflex_base.utils.imports import ImportVar @@ -1378,11 +1378,14 @@ def test_select_unknown_side(ui_plugin: UIPlugin): """A side a list cannot be on is an error that lists the sides.""" with pytest.raises(StyleError) as error: rx.ui.select.content(side="above") # pyright: ignore[reportArgumentType] - # In the order of the Literal Python keeps for these four values, which - # is the one of whichever module first wrote them. - sides = ", ".join( - f'"{side}"' for side in get_args(Literal["top", "right", "bottom", "left"]) + # In the order of the Literal the field holds: Var caches its aliases with + # Literals that differ only in order as equal, so the field gets the order + # of whichever module wrote Var of these four values first. + choices = get_args( + get_args(select_module.SelectContent.get_fields()["side"].annotated_type)[0] ) + assert sorted(choices) == ["bottom", "left", "right", "top"] + sides = ", ".join(f'"{side}"' for side in choices) assert ( str(error.value) == f'rx.ui.select_content: unknown side "above". The values are {sides}.' From bc31ac543ea6425cb4c383986db25683bd77ac5a Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 22:23:01 +0000 Subject: [PATCH 129/204] Hold the scroll area to the keys that scroll it in every engine In WebKit on 708d0c359, ArrowDown, Space, PageDown and End each took the focused rx.ui.scroll_area down from its top; Home did not take it back, and the step timed out there. The step now asserts the four keys only, and waits for the box to rest after each, so that a smooth scroll still under way is not credited to the next key. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../ui_parity/components/scroll_area.py | 41 +++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py index 24def0c820d..5439d5a7594 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/scroll_area.py @@ -28,6 +28,24 @@ return /auto|scroll/.test(style.overflowY + style.overflowX); })""" +# Whether the scroller of an area comes to rest below its top: the same offset +# for five frames running, within two seconds. +RESTS_BELOW_THE_TOP = f"""(area) => new Promise((resolve) => {{ + const scroller = ({SCROLLER})(area); + const deadline = performance.now() + 2000; + let last = -1; + let still = 0; + const frame = () => {{ + const top = scroller.scrollTop; + still = top === last ? still + 1 : 0; + last = top; + if (top > 0 && still >= 5) resolve(true); + else if (performance.now() > deadline) resolve(false); + else requestAnimationFrame(frame); + }}; + requestAnimationFrame(frame); +}})""" + def _block(width: int, height: int) -> Any: """Create something to scroll: stripes of a fixed size. @@ -172,26 +190,17 @@ def _keyboard(run: Run) -> None: assert run.page.locator("#area").evaluate( f"(area) => ({SCROLLER})(area) === document.activeElement" ) - # Every key a browser scrolls a focused box with, each from the top: the - # ones that did not move it are named when the step fails. - scrolled = ( - f"(() => {{ const scroller = ({SCROLLER})(document.getElementById('area'));" - " return scroller.scrollTop > 0; })()" - ) + # Every key a browser scrolls a focused box down with, each from the top + # and waited on until the box rests, so that a smooth scroll still under + # way is not credited to the next key: the ones that did not move it are + # named when the step fails. Home is not one: in WebKit all four took the + # box down, but Home did not take it back to the top. moved = [] for key in SCROLL_KEYS: run.page.locator("#area").evaluate( f"(area) => ({SCROLLER})(area).scrollTo({{top: 0, behavior: 'instant'}})" ) run.page.keyboard.press(key) - try: - run.page.wait_for_function(scrolled, timeout=2000) - except PlaywrightTimeoutError: - continue - moved.append(key) + if run.page.locator("#area").evaluate(RESTS_BELOW_THE_TOP): + moved.append(key) assert moved == SCROLL_KEYS - # And back to the top, from the end the last key went to. - run.page.keyboard.press("Home") - run.page.wait_for_function( - f"({SCROLLER})(document.getElementById('area')).scrollTop === 0" - ) From 5d8c8097e2e5eabbc5754ea591b1e42d78741c6f Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 22:26:57 +0000 Subject: [PATCH 130/204] Give the focus a place to go before the radio group in its Shift+Tab step The group with nothing checked is the first thing on the contract page, so a second Shift+Tab out of it left the page, where Firefox keeps document.activeElement on the last item: rx.ui read as still in the group on 708d0c359. The step now puts a button first and expects the focus on it. In Firefox, Shift+Tab from the checked item of rx.radio_group brings the focus back to that item ('Red' == 'One', [False, False]): both steps get a Firefox entry for the reference. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../parity/allowlist.toml | 14 ++++++++++ .../ui_parity/components/radio_group.py | 26 ++++++++++++++----- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index bdeffd380e5..598c8135143 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -125,6 +125,20 @@ step = "Shift+Tab into a group with nothing checked stops on its first item" engines = ["webkit"] reason = "The items of rx.ui.radio_group are native radio buttons, and the browser decides where the focus enters a group in which none is checked. Safari enters it at the button nearest to where the focus comes from: the last one for Shift+Tab, where the other browsers and rx.radio_group enter at the first. The group is one stop either way, and the arrow keys reach every item." +[[contract]] +component = "radio_group" +step = "Shift+Tab into a group with nothing checked stops on its first item" +system = "rx" +engines = ["firefox"] +reason = "In Firefox, Shift+Tab from the checked item of rx.radio_group does not leave the group: the focus comes back to that item. The items of rx.ui.radio_group are native radio buttons, which Shift+Tab leaves in every browser." + +[[contract]] +component = "radio_group" +step = "Shift+Tab stops once in a group with nothing checked" +system = "rx" +engines = ["firefox"] +reason = "In Firefox, Shift+Tab from the checked item of rx.radio_group does not leave the group: the focus comes back to that item. The items of rx.ui.radio_group are native radio buttons, which Shift+Tab leaves in every browser." + [[contract]] component = "radio_group" step = "the arrow keys go round at the ends of a group" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py index 2b542bc88fa..efb00f18545 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/radio_group.py @@ -173,8 +173,19 @@ def submit(self, data: dict[str, str]): HELD = 60 # The text of the item that has the focus, or nothing when no item has it. FOCUSED_ITEM = "(document.activeElement.closest('label')?.textContent ?? null)" -# Whether the focus is in the group with nothing checked. -IN_PICK = "document.activeElement.closest('#pick') !== null" +# Where the focus is: "pick" in the group with nothing checked, else the id of +# the element that has it. +FOCUS_AT = ( + "document.activeElement.closest('#pick') ? 'pick' : document.activeElement.id" +) +# Put a button first on the page, for the focus to go to when it leaves the +# group with nothing checked backwards. Without it the focus would leave the +# page, where Firefox leaves document.activeElement on the last item. +BUTTON_BEFORE = ( + "() => { const button = document.createElement('button');" + " button.id = 'before'; button.textContent = 'Before';" + " document.body.prepend(button); }" +) def _wait_for_checked(run: Run, group: str, items: list[str]) -> None: @@ -243,14 +254,15 @@ def _tab(run: Run) -> None: @CONTRACT.step("Shift+Tab stops once in a group with nothing checked") def _shift_tab_once(run: Run) -> None: page = run.page - page.keyboard.press("Tab") - page.keyboard.press("Tab") + page.evaluate(BUTTON_BEFORE) + for _ in range(3): + page.keyboard.press("Tab") _wait_for_focus(run, "Red") - inside = [] + seen = [] for _ in range(2): page.keyboard.press("Shift+Tab") - inside.append(page.evaluate(IN_PICK)) - assert inside == [True, False] + seen.append(page.evaluate(FOCUS_AT)) + assert seen == ["pick", "before"] _wait_for_checked(run, "pick", []) From 944c7bfcc8cc4093dbbd7ecc3751fcfdc13fa21d Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 22:33:21 +0000 Subject: [PATCH 131/204] Wait for Radix in two contract steps instead of racing it On 708d0c359 two steps failed for the Radix reference in Chromium only, with nothing they run changed since 4e8f180, where they passed: - form: aria-describedby read [] right after the messages showed; Radix links them to the control from an effect. The step now waits for the link. - select: a click outside an open list left it open for 30 seconds; Radix adds its pointerdown-outside listener from a setTimeout(0) set when the list mounts (react-dismissable-layer), and Chromium may deliver input ahead of a pending timer. Opening a list now waits one turn of the timers. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../parity/ui_parity/components/form.py | 12 +++++++----- .../parity/ui_parity/components/select.py | 4 ++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/form.py b/packages/reflex-components-ui/parity/ui_parity/components/form.py index 4ca946e561e..edc94c85ce2 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/form.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/form.py @@ -225,11 +225,13 @@ def _invalid(run: Run) -> None: assert page.evaluate(FOCUSED) == "email" assert page.locator("#submissions").text_content() == "0" assert page.locator("#email-field").get_attribute("data-invalid") is not None - described = _control(run, "email").get_attribute("aria-describedby") or "" - assert [ - page.locator(f"[id='{message}']").text_content() - for message in described.split() - ] == ["Email is needed", "Outside"] + # Radix links the messages to the control from an effect, after they show. + page.wait_for_function( + "expected => (document.querySelector(\"#form [name='email']\")" + ".getAttribute('aria-describedby') ?? '').split(' ').filter(Boolean)" + ".map(id => document.getElementById(id)?.textContent).join('|') === expected", + arg="Email is needed|Outside", + ) @CONTRACT.step("a change forgets the reason, and leaving the control reads it again") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/select.py b/packages/reflex-components-ui/parity/ui_parity/components/select.py index 825a7f3e9aa..481f95408de 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/select.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/select.py @@ -374,6 +374,10 @@ def _open_list(run: Run, trigger: str, key: str = "Enter") -> None: page.keyboard.press(key) page.locator(LIST).wait_for() page.wait_for_function("document.activeElement.getAttribute('role') === 'option'") + # Radix listens for a pointer outside the list from a timer it sets when + # the list mounts, and a browser may deliver a click before that timer: + # one turn of the timers puts the listener in place. + page.evaluate("() => new Promise((resolve) => setTimeout(resolve, 0))") def _wait_for_closed(run: Run) -> None: From ac799e01bc31b5ca029a408aaff0f0ee58af5c4b Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 23:13:46 +0000 Subject: [PATCH 132/204] Add rx.ui.hover_card, rx.ui.dropdown_menu and rx.ui.context_menu The hover card is the popup of the tooltip with the look of a card: hover.js opens it after the delays of its root under the pointer and with the focus, and the links inside it can be reached with Tab. A menu is a native popover with the role of one; menu.js moves through its items with the arrows, Home, End and typing (keys.js, now shared with the select), opens a sub-menu with the pointer, Enter and the right arrow and closes it with the left one, closes every menu on a choice with the focus back on the trigger, checks a checkbox item, and opens a context menu at the pointer or for the keyboard. The content finds its items while compiling and hands them its look, sub-menus included. The dropdown menu opens without JavaScript. A popup keeps the room Radix keeps from the edge of the viewport on the side away from its anchor, so it turns over only where Radix does; it was flipped as soon as its offset passed 10 pixels. The parity matrices of the popups compare what is inside them, in the page for Radix, whose popups are portalled: that found a modal dialog selecting its text, and the colors and outline of a popover and a tooltip. Claude-Session: https://claude.ai/code/session_014AwvTPAHZRxHNPUcCpxBsq --- .../js/src/behaviors/hover.js | 21 +- .../js/src/behaviors/keys.js | 64 ++ .../js/src/behaviors/listbox.js | 56 +- .../js/src/behaviors/menu.js | 362 +++++++++++ .../js/src/behaviors/popup.js | 14 +- .../js/tests/behaviors/hover.test.js | 19 + .../js/tests/behaviors/menu.test.js | 426 +++++++++++++ .../news/+wave4-overlays.feature.md | 6 +- .../parity/allowlist.toml | 115 ++++ .../ui_parity/components/alert_dialog.py | 3 +- .../ui_parity/components/context_menu.py | 403 ++++++++++++ .../parity/ui_parity/components/dialog.py | 15 +- .../parity/ui_parity/components/drawer.py | 12 +- .../ui_parity/components/dropdown_menu.py | 601 ++++++++++++++++++ .../parity/ui_parity/components/hover_card.py | 396 ++++++++++++ .../parity/ui_parity/components/popover.py | 13 +- .../parity/ui_parity/components/tooltip.py | 6 +- .../src/reflex_components_ui/__init__.py | 3 + .../reflex_components_ui/components/_menu.py | 594 +++++++++++++++++ .../components/context_menu.py | 406 ++++++++++++ .../components/dropdown_menu.py | 293 +++++++++ .../components/hover_card.py | 118 ++++ .../components/tooltip.py | 16 +- .../src/reflex_components_ui/styles/dialog.py | 2 + .../reflex_components_ui/styles/hover_card.py | 53 ++ .../src/reflex_components_ui/styles/menu.py | 365 +++++++++++ .../reflex_components_ui/styles/popover.py | 1 + .../src/reflex_components_ui/styles/popup.py | 17 +- .../reflex_components_ui/styles/tooltip.py | 2 + pyi_hashes.json | 7 +- .../tests_playwright/test_ui_components.py | 55 ++ .../components/test_alert_dialog.py | 3 +- .../components/test_context_menu.py | 519 +++++++++++++++ .../components/test_dialog.py | 11 +- .../components/test_drawer.py | 6 +- .../components/test_dropdown_menu.py | 493 ++++++++++++++ .../components/test_hover_card.py | 229 +++++++ .../components/test_popover.py | 19 +- .../components/test_select.py | 36 +- .../components/test_tooltip.py | 15 +- .../reflex_components_ui/test_api_parity.py | 37 ++ 41 files changed, 5709 insertions(+), 123 deletions(-) create mode 100644 packages/reflex-components-ui/js/src/behaviors/keys.js create mode 100644 packages/reflex-components-ui/js/src/behaviors/menu.js create mode 100644 packages/reflex-components-ui/js/tests/behaviors/menu.test.js create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/context_menu.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/components/hover_card.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py create mode 100644 tests/units/reflex_components_ui/components/test_context_menu.py create mode 100644 tests/units/reflex_components_ui/components/test_dropdown_menu.py create mode 100644 tests/units/reflex_components_ui/components/test_hover_card.py diff --git a/packages/reflex-components-ui/js/src/behaviors/hover.js b/packages/reflex-components-ui/js/src/behaviors/hover.js index e53ec140964..86cd65f9d0c 100644 --- a/packages/reflex-components-ui/js/src/behaviors/hover.js +++ b/packages/reflex-components-ui/js/src/behaviors/hover.js @@ -136,8 +136,9 @@ export function hoverSync(popup, open, on) { * * The pointer opens the popup and closes it after the delays the popup * says, so it can go from one to the other. The focus of the keyboard - * opens it at once, and closes it when it leaves both. A press on what a - * tooltip is on closes the tooltip. + * opens a tooltip at once, and a hover card after the same delays, and + * closes it when it leaves both. A press on what a tooltip is on closes + * the tooltip. * * @param {{ type: string, currentTarget: HTMLElement, pointerType?: string, relatedTarget?: EventTarget | null }} event * The pointer or the focus coming or going. @@ -160,13 +161,13 @@ export function hoverEvent(event) { return; const open = type === "pointerenter" || type === "focus"; const data = popup.dataset; + // A tooltip follows the focus at once, a hover card after its delays. + const delayed = + type === "pointerenter" || + type === "pointerleave" || + (type !== "pointerdown" && popup.role !== "tooltip"); + const delay = delayed ? Number(open ? data.openDelay : data.closeDelay) : 0; clearTimeout(state.timer); - state.timer = Number( - setTimeout( - () => ask(popup, open), - type === "pointerenter" || type === "pointerleave" - ? Number(open ? data.openDelay : data.closeDelay) - : 0, - ), - ); + if (delay) state.timer = Number(setTimeout(() => ask(popup, open), delay)); + else ask(popup, open); } diff --git a/packages/reflex-components-ui/js/src/behaviors/keys.js b/packages/reflex-components-ui/js/src/behaviors/keys.js new file mode 100644 index 00000000000..6de87b6a5b0 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/keys.js @@ -0,0 +1,64 @@ +// What a list of options and a menu share: the keys that move through +// their items, and typing to find one. + +/** What was typed to find an item, and when it is forgotten. */ +let typed = ""; +let forgetting = 0; + +/** + * Say whether a search is being typed, during which Space is a letter. + * + * @returns {boolean} Whether something was typed less than a second ago. + */ +export function typing() { + return typed !== ""; +} + +/** Forget what was typed: a list that opens or closes starts afresh. */ +export function forget() { + typed = ""; +} + +/** + * Find the item that what was typed leads to. + * + * Typing one letter again goes through the items that start with it. + * + * @param {HTMLElement[]} items The items that can be reached. + * @param {string} key The letter typed. + * @param {Element | null} from The item to start after. + * @param {(item: Element) => string} textOf The text an item is found by. + * @returns {HTMLElement | undefined} The item found. + */ +export function find(items, key, from, textOf) { + clearTimeout(forgetting); + typed += key.toLowerCase(); + forgetting = Number(setTimeout(forget, 1000)); + const repeated = [...typed].every((letter) => letter === typed[0]); + const search = repeated ? typed[0] : typed; + const starts = (/** @type {Element} */ item) => + textOf(item).trim().toLowerCase().startsWith(search); + if (!repeated && from && starts(from)) return /** @type {HTMLElement} */ (from); + const start = items.indexOf(/** @type {HTMLElement} */ (from)); + return [...items.slice(start + 1), ...items.slice(0, start + 1)].find(starts); +} + +/** + * Find the item an arrow key, Home or End goes to. + * + * @param {HTMLElement[]} items The items that can be reached. + * @param {string} key The key. + * @param {number} at The place of the item that has the focus, or -1. + * @param {boolean} [loop] Whether the arrows go round from one end to the other. + * @returns {HTMLElement | undefined | null} The item, or null for a key + * that moves nowhere. + */ +export function move(items, key, at, loop = false) { + const last = items.length - 1; + if (key === "Home") return items[0]; + if (key === "End") return items[last]; + if (key === "ArrowDown") + return items[at < last ? at + 1 : loop ? 0 : last]; + if (key === "ArrowUp") return items[at > 0 ? at - 1 : loop || at < 0 ? last : 0]; + return null; +} diff --git a/packages/reflex-components-ui/js/src/behaviors/listbox.js b/packages/reflex-components-ui/js/src/behaviors/listbox.js index 99a4474898a..b7406340416 100644 --- a/packages/reflex-components-ui/js/src/behaviors/listbox.js +++ b/packages/reflex-components-ui/js/src/behaviors/listbox.js @@ -6,15 +6,12 @@ // select holds its form back, and React hears of a change as it does of // any input. Without this the select opens and closes, and chooses nothing. +import { find, forget, move, typing } from "./keys.js"; import { opener, pair, popupToggle } from "./popup.js"; const OPTION = "[role=option]"; const ENABLED = `${OPTION}:not([aria-disabled=true])`; -/** What was typed to find an option, and when it is forgotten. */ -let typed = ""; -let forgetting = 0; - /** * Find the parts of a select. * @@ -134,36 +131,6 @@ function choose(select, option) { show(select, trigger, holder.value); } -/** - * Find the option that what was typed leads to. - * - * Typing one letter again goes through the options that start with it. - * - * @param {HTMLElement[]} options The options that can be chosen. - * @param {string} key The letter typed. - * @param {Element | null} from The option to start after. - * @returns {HTMLElement | undefined} The option found. - */ -function find(options, key, from) { - clearTimeout(forgetting); - typed += key.toLowerCase(); - forgetting = Number(setTimeout(() => (typed = ""), 1000)); - const repeated = [...typed].every((letter) => letter === typed[0]); - const search = repeated ? typed[0] : typed; - const start = options.indexOf(/** @type {HTMLElement} */ (from)); - const order = [...options.slice(start + 1), ...options.slice(0, start + 1)]; - if ( - !repeated && - from && - textOf(from).trim().toLowerCase().startsWith(search) - ) { - return /** @type {HTMLElement} */ (from); - } - return order.find((option) => - textOf(option).trim().toLowerCase().startsWith(search), - ); -} - /** * The keys of a select: the `onKeyDown` of the element around it. * @@ -191,12 +158,12 @@ export function selectKeyDown(event) { if (key === "ArrowDown" || key === "ArrowUp") { event.preventDefault(); trigger.click(); - } else if (letter && (key !== " " || typed)) { + } else if (letter && (key !== " " || typing())) { event.preventDefault(); const current = options.find( (option) => option.dataset.value === holder.value, ); - const found = find(options, key, current ?? null); + const found = find(options, key, current ?? null, textOf); if (found) choose(select, found); } return; @@ -206,21 +173,18 @@ export function selectKeyDown(event) { const at = options.indexOf( /** @type {HTMLElement} */ (document.activeElement), ); - /** @type {HTMLElement | undefined} */ - let next; - if (key === "ArrowDown") next = options[Math.min(at + 1, options.length - 1)]; - else if (key === "ArrowUp") next = options[Math.max(at - 1, 0)]; - else if (key === "Home") next = options[0]; - else if (key === "End") next = options[options.length - 1]; - else if (key === "Enter" || (key === " " && !typed)) { + let next = move(options, key, at); + if (key === "Enter" || (key === " " && !typing())) { event.preventDefault(); if (at >= 0) choose(select, options[at]); return; } else if (key === "Tab") { event.preventDefault(); return; - } else if (letter) next = find(options, key, options[at] ?? null); - else return; + } else if (next === null) { + if (!letter) return; + next = find(options, key, options[at] ?? null, textOf); + } event.preventDefault(); next?.focus(); } @@ -274,7 +238,7 @@ export function selectToggle(event, on) { const open = popupToggle(event); const by = popup.dataset.rxClosedBy; delete popup.dataset.rxClosedBy; - typed = ""; + forget(); on?.open?.(open); if (open) { const options = /** @type {HTMLElement[]} */ ([ diff --git a/packages/reflex-components-ui/js/src/behaviors/menu.js b/packages/reflex-components-ui/js/src/behaviors/menu.js new file mode 100644 index 00000000000..443e01052b1 --- /dev/null +++ b/packages/reflex-components-ui/js/src/behaviors/menu.js @@ -0,0 +1,362 @@ +// A menu: a native popover of items beside the button that opens it, at +// the pointer for a context menu, or beside an item for a sub-menu. +// +// The browser opens the menu of a dropdown from its trigger, puts it over +// everything else, and closes it on Escape and on a press outside, the +// topmost menu first. What is left for a script: the keys that move through +// the items, typing to find one, choosing one, the sub-menus, the checkbox +// items, and the context menu, which opens where the pointer is. Without +// this a dropdown menu opens and closes, and its items do nothing. + +import { find, forget, move, typing } from "./keys.js"; +import { opener, popupSync, popupToggle } from "./popup.js"; + +const MENU = "[role=menu]"; +const ITEM = "[role^=menuitem]"; +const ENABLED = `${ITEM}:not([aria-disabled="true"])`; + +/** How long the pointer rests on an item before its sub-menu opens, in ms. */ +const SUB_DELAY = 100; + +let anchors = 0; +let opening = 0; + +/** + * Find the menu an element is in. + * + * @param {Element} element The element. + * @returns {HTMLElement | null} The innermost menu around it, itself included. + */ +function menuOf(element) { + return element.closest(MENU); +} + +/** + * Find the items of a menu that can be reached, not those of its sub-menus. + * + * @param {Element} menu The menu. + * @returns {HTMLElement[]} The items that are not disabled, in order. + */ +function itemsOf(menu) { + return /** @type {HTMLElement[]} */ ([ + ...menu.querySelectorAll(ENABLED), + ]).filter((item) => menuOf(item) === menu); +} + +/** + * Find the sub-menu an item opens. + * + * @param {Element} item The item. + * @returns {HTMLElement | null} The sub-menu, or null for another item. + */ +function subOf(item) { + const id = item.getAttribute("data-rx-opens"); + return id ? document.getElementById(id) : null; +} + +/** + * Find the outermost menu around one: the one a choice closes. + * + * @param {HTMLElement} menu The menu. + * @returns {HTMLElement} The menu that holds it, or itself. + */ +function rootOf(menu) { + const outer = menu.parentElement && menuOf(menu.parentElement); + return outer ? rootOf(outer) : menu; +} + +/** + * Find the sub-menus open inside a menu. + * + * @param {Element} menu The menu. + * @returns {HTMLElement[]} Each open sub-menu, outermost first. + */ +function openSubs(menu) { + return /** @type {HTMLElement[]} */ ([ + ...menu.querySelectorAll(MENU), + ]).filter((sub) => sub.matches(":popover-open")); +} + +/** + * Close a menu, and say why to what follows its toggle. + * + * @param {HTMLElement} menu The menu. + * @param {string} why What closed it. + * @returns {void} + */ +function close(menu, why) { + if (!menu.matches(":popover-open")) return; + menu.dataset.rxClosedBy = why; + menu.hidePopover(); +} + +/** + * Close the sub-menus a menu has open, but the one of an item. + * + * @param {HTMLElement} menu The menu. + * @param {Element | null} [kept] The item whose sub-menu stays open. + * @returns {void} + */ +function closeSubs(menu, kept) { + clearTimeout(opening); + for (const item of itemsOf(menu)) { + const sub = item !== kept && subOf(item); + if (sub) close(sub, "pointer"); + } +} + +/** + * Open the sub-menu of an item. + * + * @param {Element} item The item. + * @param {boolean} keyboard Whether a key opens it, which moves the focus + * to its first item. + * @returns {void} + */ +function openSub(item, keyboard) { + clearTimeout(opening); + const sub = subOf(item); + if (!sub) return; + if (sub.matches(":popover-open")) { + if (keyboard) itemsOf(sub)[0]?.focus(); + return; + } + if (keyboard) sub.dataset.rxKeyboard = "true"; + sub.showPopover(); +} + +/** + * Keep a menu as its state says: the `ref` of the popover, called again + * whenever the page renders. + * + * A menu that nothing opens with `popovertarget`, a sub-menu or a context + * menu, is placed against the element rendered right before it: the item + * that opens it, or the point a context menu opens at. + * + * @param {HTMLElement | null} menu The popover. + * @param {boolean | null} [open] Whether a menu bound to state is open. + * @returns {void} + */ +export function menuSync(menu, open) { + if (!menu) return; + const anchor = menu.previousElementSibling; + if ( + anchor instanceof HTMLElement && + !anchor.hasAttribute("popovertarget") && + !menu.style.getPropertyValue("position-anchor") + ) { + const name = `--rx-menu-${++anchors}`; + anchor.style.setProperty("anchor-name", name); + menu.style.setProperty("position-anchor", name); + } + popupSync(menu, open); +} + +/** + * Follow the keys and the pointer on what opens a dropdown menu: its + * `onKeyDown` and `onPointerDown`. + * + * Enter, Space and the down arrow open the menu with the focus on its + * first item; the down arrow does what a press does. + * + * @param {{ type: string, key?: string, currentTarget: Element, preventDefault: () => void }} event + * The key or the pointer going down. + * @returns {void} + */ +export function menuTrigger(event) { + const trigger = event.currentTarget; + const menu = document.getElementById( + trigger.getAttribute("popovertarget") ?? "", + ); + if (!menu) return; + const { key } = event; + if (key !== "Enter" && key !== " " && key !== "ArrowDown") { + delete menu.dataset.rxKeyboard; + return; + } + menu.dataset.rxKeyboard = "true"; + if (key === "ArrowDown") { + event.preventDefault(); + if (!menu.matches(":popover-open")) /** @type {HTMLElement} */ (trigger).click(); + } +} + +/** + * Open a context menu where it is asked for: the `onContextMenu` of the + * element it is on. + * + * It opens at the pointer, or for the context-menu key and Shift+F10 where + * the browser says, with the focus on its first item. + * + * @param {{ currentTarget: Element, clientX: number, clientY: number, button: number, preventDefault: () => void }} event + * The context menu asked for. + * @returns {void} + */ +export function menuContext(event) { + const area = event.currentTarget; + const menu = document.getElementById( + area.getAttribute("data-rx-opens") ?? "", + ); + const point = menu?.previousElementSibling; + if ( + !menu || + !(point instanceof HTMLElement) || + area.hasAttribute("data-disabled") + ) + return; + event.preventDefault(); + point.style.left = `${event.clientX}px`; + point.style.top = `${event.clientY}px`; + close(menu, "state"); + if (event.button !== 2) menu.dataset.rxKeyboard = "true"; + menu.showPopover(); +} + +/** + * Check or uncheck a checkbox item: its `onClick`. + * + * @param {{ currentTarget: Element }} event The press. + * @param {((checked: boolean) => void) | null} [change] What the item does + * when it changes. + * @param {boolean} [bound] Whether the item shows the state it is bound to + * rather than its own. + * @returns {void} + */ +export function menuCheck(event, change, bound) { + const item = event.currentTarget; + if (item.getAttribute("aria-disabled") === "true") return; + const checked = item.getAttribute("aria-checked") !== "true"; + if (!bound) { + item.setAttribute("aria-checked", String(checked)); + item.setAttribute("data-state", checked ? "checked" : "unchecked"); + } + change?.(checked); +} + +/** + * Follow what happens in a menu: the `onToggle`, `onKeyDown`, `onClick`, + * `onPointerMove`, `onPointerLeave` and `onBlur` of its popover. + * + * The arrow keys, Home and End move through the items, a letter goes to + * one, Enter and Space choose, and Tab stays. A choice closes every menu + * and gives the focus back to the trigger. The right arrow and the pointer + * open a sub-menu, and the left arrow closes it. The menu says when it + * opens and closes, and what closed it. + * + * @param {{ type: string, target: EventTarget | null, currentTarget: HTMLElement, newState?: string, key?: string, relatedTarget?: EventTarget | null, pointerType?: string, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean, preventDefault: () => void }} event + * What happened. + * @param {{ open?: (open: boolean) => void, closeAutoFocus?: () => void, escape?: () => void, outside?: () => void, focusOutside?: () => void, interact?: () => void } | null} [on] + * What the menu does when it opens, closes or is dismissed. + * @returns {void} + */ +export function menuEvent(event, on) { + const menu = event.currentTarget; + const { type } = event; + const target = event.target instanceof Element ? event.target : null; + const data = menu.dataset; + if (type === "toggle") { + if (target !== menu) return; + const open = popupToggle(event); + const by = data.rxClosedBy; + const keyboard = data.rxKeyboard; + delete data.rxClosedBy; + delete data.rxKeyboard; + forget(); + if (open) { + if (by !== "state") on?.open?.(true); + if (keyboard) (itemsOf(menu)[0] ?? menu).focus(); + else if (rootOf(menu) === menu) menu.focus(); + return; + } + if (by === "escape" || by === "choice" || by === "left") + /** @type {HTMLElement | null} */ (opener(menu))?.focus(); + if (by === "escape") on?.escape?.(); + if (by === "focus") on?.focusOutside?.(); + if (!by) on?.outside?.(); + if (!by || by === "focus") on?.interact?.(); + if (by !== "state") on?.open?.(false); + on?.closeAutoFocus?.(); + return; + } + if (!target || menuOf(target) !== menu) return; + const items = itemsOf(menu); + const item = /** @type {HTMLElement | null} */ (target.closest(ENABLED)); + if (type === "blur") { + const to = event.relatedTarget; + // A press outside the menu is the browser's to close it by. + if ( + to instanceof Element && + !menu.contains(to) && + to !== opener(menu) && + !to.matches(":active") + ) + close(menu, "focus"); + } else if (type === "click") { + if (!item) return; + if (subOf(item)) return openSub(item, false); + const root = rootOf(menu); + for (const sub of openSubs(root)) sub.dataset.rxClosedBy = "state"; + close(root, "choice"); + } else if (type === "pointermove") { + if (event.pointerType !== "mouse") return; + if (!item) { + if (!openSubs(menu).length) menu.focus({ preventScroll: true }); + return; + } + if (item !== document.activeElement) item.focus({ preventScroll: true }); + closeSubs(menu, item); + if (subOf(item) && !subOf(item)?.matches(":popover-open")) + opening = Number(setTimeout(() => openSub(item, false), SUB_DELAY)); + } else if (type === "pointerleave") { + clearTimeout(opening); + const at = /** @type {Element} */ (document.activeElement); + if (items.includes(/** @type {HTMLElement} */ (at)) && !subOf(at)) + menu.focus({ preventScroll: true }); + } else if (type === "keydown") { + const { key = "" } = event; + if (key === "Escape") { + // The browser closes the topmost menu: a sub-menu the pointer opened. + (openSubs(menu).pop() ?? menu).dataset.rxClosedBy = "escape"; + return; + } + const at = items.indexOf(/** @type {HTMLElement} */ (document.activeElement)); + const focused = items[at]; + const letter = + key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey; + if (key === "Tab") { + event.preventDefault(); + return; + } + if (focused && (key === "Enter" || (key === " " && !typing()))) { + event.preventDefault(); + if (subOf(focused)) openSub(focused, true); + else focused.click(); + return; + } + if (key === "ArrowRight" && focused && subOf(focused)) { + event.preventDefault(); + openSub(focused, true); + return; + } + if (key === "ArrowLeft" && rootOf(menu) !== menu) { + event.preventDefault(); + close(menu, "left"); + return; + } + let next = move(items, key, at, menu.dataset.loop === "true"); + if (next === null) { + if (!letter) return; + next = find( + items, + key, + focused ?? null, + (one) => one.getAttribute("data-text-value") ?? one.textContent ?? "", + ); + } + event.preventDefault(); + if (next) { + closeSubs(menu, next); + next.focus(); + } + } +} diff --git a/packages/reflex-components-ui/js/src/behaviors/popup.js b/packages/reflex-components-ui/js/src/behaviors/popup.js index ebb20fe2aeb..011abdfc1d2 100644 --- a/packages/reflex-components-ui/js/src/behaviors/popup.js +++ b/packages/reflex-components-ui/js/src/behaviors/popup.js @@ -16,11 +16,15 @@ let ids = 0; * Find what opens a popup. * * @param {Element} popup The popover. - * @returns {Element | null} The first element whose `popovertarget` it is. + * @returns {Element | null} The first element whose `popovertarget` it is, + * or that a script opens it from: an item of a menu that opens a + * sub-menu, the element a context menu is on. */ export function opener(popup) { return popup.id - ? document.querySelector(`[popovertarget="${popup.id}"]`) + ? document.querySelector( + `[popovertarget="${popup.id}"], [data-rx-opens="${popup.id}"]`, + ) : null; } @@ -49,7 +53,11 @@ export function pair(popup, trigger) { ]; popup.id = `${popup.id || "rx-popup"}-${++ids}`; popup.setAttribute("data-rx-popup-paired", ""); - for (const element of named) element.setAttribute("popovertarget", popup.id); + for (const element of named) + element.setAttribute( + element.hasAttribute("data-rx-opens") ? "data-rx-opens" : "popovertarget", + popup.id, + ); trigger.setAttribute("aria-controls", popup.id); } diff --git a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js index a214015b901..9f141dbae79 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js @@ -169,6 +169,25 @@ test("the focus of the keyboard opens the popup at once, and closes it when it l expect(shown()).toBe(false); }); +test("the focus of the keyboard opens a hover card after its delay, and closes it after the other", () => { + render(""); + api.hoverSync(popup, null, on); + const matches = trigger.matches.bind(trigger); + trigger.matches = (selector) => + selector === ":focus-visible" || matches(selector); + send("focus"); + vi.advanceTimersByTime(199); + expect(shown()).toBe(false); + vi.advanceTimersByTime(1); + expect([shown(), trigger.dataset.state]).toEqual([true, "open"]); + send("blur", trigger, { to: document.getElementById("elsewhere") }); + vi.advanceTimersByTime(99); + expect(shown()).toBe(true); + vi.advanceTimersByTime(1); + expect([shown(), trigger.dataset.state]).toEqual([false, "closed"]); + expect(seen).toEqual(["open:true", "open:false"]); +}); + test("Escape, a press outside and a press on the button of a tooltip close it", () => { api.hoverSync(popup, null, on); const open = () => { diff --git a/packages/reflex-components-ui/js/tests/behaviors/menu.test.js b/packages/reflex-components-ui/js/tests/behaviors/menu.test.js new file mode 100644 index 00000000000..90398d92328 --- /dev/null +++ b/packages/reflex-components-ui/js/tests/behaviors/menu.test.js @@ -0,0 +1,426 @@ +// A menu: the keys, the pointer and the choices of its items, its +// sub-menus, its checkbox items, and the context menu at the pointer. +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { installPopover } from "./popover.js"; + +/** @type {typeof import("$/reflex-ui/behaviors/menu.js")} */ +let api; +/** @type {string[]} */ +let seen; + +const on = { + open: (/** @type {boolean} */ open) => seen.push(`open:${open}`), + escape: () => seen.push("escape"), + outside: () => seen.push("outside"), + focusOutside: () => seen.push("focus-outside"), + interact: () => seen.push("interact"), + closeAutoFocus: () => seen.push("close-focus"), +}; + +/** + * Render a dropdown menu with a sub-menu, and a context menu. + * + * @returns {void} + */ +function render() { + document.body.innerHTML = ` + + +
Area
+ + + `; +} + +/** + * Find an element of the page. + * + * @param {string} id Its id. + * @returns {HTMLElement} The element. + */ +function $(id) { + return /** @type {HTMLElement} */ (document.getElementById(id)); +} + +/** + * Have the script of a menu hear its events, as React does. + * + * @param {string} id The id of the menu. + * @param {typeof on | null} [handlers] What the menu does. + * @returns {void} + */ +function listen(id, handlers = null) { + const menu = $(id); + for (const type of [ + "toggle", + "keydown", + "click", + "pointermove", + "pointerleave", + "focusout", + ]) { + menu.addEventListener(type, (event) => + api.menuEvent( + /** @type {any} */ ({ + type: type === "focusout" ? "blur" : type, + target: event.target, + currentTarget: menu, + newState: /** @type {any} */ (event).newState, + key: /** @type {any} */ (event).key, + relatedTarget: /** @type {any} */ (event).relatedTarget, + pointerType: /** @type {any} */ (event).pointerType, + preventDefault: () => event.preventDefault(), + }), + handlers, + ), + ); + } +} + +/** + * Press a key on the element that has the focus. + * + * @param {string} key The key. + * @returns {boolean} Whether the script took the key for itself. + */ +function press(key) { + const event = new KeyboardEvent("keydown", { + key, + bubbles: true, + cancelable: true, + }); + /** @type {HTMLElement} */ (document.activeElement).dispatchEvent(event); + return event.defaultPrevented; +} + +/** + * Move a mouse over an element. + * + * @param {string} id The id of the element. + * @param {string} [type] The event. + * @returns {void} + */ +function point(id, type = "pointermove") { + const event = new Event(type, { bubbles: type === "pointermove" }); + Object.assign(event, { pointerType: "mouse" }); + $(id).dispatchEvent(event); +} + +/** + * Say which element has the focus. + * + * @returns {string} Its id. + */ +function focused() { + return document.activeElement?.id ?? ""; +} + +beforeEach(async () => { + vi.resetModules(); + vi.useFakeTimers(); + installPopover(); + api = await import("$/reflex-ui/behaviors/menu.js"); + seen = []; + render(); + listen("opts", on); + listen("sub"); + listen("ctx"); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +test("a menu nothing opens by popovertarget is placed against the element before it", () => { + api.menuSync($("opts")); + api.menuSync($("sub")); + api.menuSync($("sub")); + api.menuSync($("ctx")); + api.menuSync(null); + expect([ + $("trigger").style.getPropertyValue("anchor-name"), + $("opts").style.getPropertyValue("position-anchor"), + $("more").style.getPropertyValue("anchor-name"), + $("sub").style.getPropertyValue("position-anchor"), + $("point").style.getPropertyValue("anchor-name"), + $("ctx").style.getPropertyValue("position-anchor"), + ]).toEqual([ + "", + "", + "--rx-menu-1", + "--rx-menu-1", + "--rx-menu-2", + "--rx-menu-2", + ]); +}); + +test("a press opens the menu on itself, and the keys of the trigger on its first item", () => { + $("opts").showPopover(); + expect([focused(), $("trigger").getAttribute("aria-expanded")]).toEqual([ + "opts", + "true", + ]); + $("opts").hidePopover(); + for (const key of ["Enter", " "]) { + api.menuTrigger( + /** @type {any} */ ({ + key, + currentTarget: $("trigger"), + preventDefault() {}, + }), + ); + $("opts").showPopover(); + expect(focused()).toBe("edit"); + $("opts").hidePopover(); + } + const click = vi.spyOn($("trigger"), "click"); + let prevented = false; + api.menuTrigger( + /** @type {any} */ ({ + key: "ArrowDown", + currentTarget: $("trigger"), + preventDefault: () => (prevented = true), + }), + ); + expect([click.mock.calls.length, prevented]).toEqual([1, true]); + // A key that opens nothing forgets the one before. + api.menuTrigger( + /** @type {any} */ ({ + key: "Tab", + currentTarget: $("trigger"), + preventDefault() {}, + }), + ); + $("opts").showPopover(); + expect(focused()).toBe("opts"); + api.menuTrigger( + /** @type {any} */ ({ + key: "Enter", + currentTarget: $("elsewhere"), + preventDefault() {}, + }), + ); +}); + +test("the arrows, Home, End and typing move through the items past a disabled one, and Tab stays", () => { + $("opts").showPopover(); + $("edit").focus(); + const moves = [ + ["ArrowDown", "archive"], + ["ArrowDown", "more"], + ["ArrowDown", "share"], + ["ArrowDown", "share"], + ["ArrowUp", "more"], + ["Home", "edit"], + ["ArrowUp", "edit"], + ["End", "share"], + ["m", "more"], + ["b", "archive"], + ]; + for (const [key, item] of moves) { + // What was typed is forgotten after a second. + vi.advanceTimersByTime(1000); + expect(press(key)).toBe(true); + expect(focused()).toBe(item); + } + expect(press("Tab")).toBe(true); + expect(press("Shift")).toBe(false); + $("opts").dataset.loop = "true"; + $("share").focus(); + press("ArrowDown"); + expect(focused()).toBe("edit"); +}); + +test("a choice closes every menu, gives the focus back, and says so", () => { + $("opts").showPopover(); + $("edit").focus(); + const chosen = vi.fn(); + $("edit").addEventListener("click", chosen); + press("Enter"); + expect([ + chosen.mock.calls.length, + $("opts").matches(":popover-open"), + focused(), + ]).toEqual([1, false, "trigger"]); + expect(seen).toEqual(["open:true", "open:false", "close-focus"]); + // A press on a disabled item, or beside the items, chooses nothing. + $("opts").showPopover(); + $("delete").click(); + $("opts").click(); + expect($("opts").matches(":popover-open")).toBe(true); +}); + +test("Escape, the focus leaving and a press outside close the menu and say why", () => { + $("opts").showPopover(); + $("edit").focus(); + press("Escape"); + $("opts").hidePopover(); + expect(focused()).toBe("trigger"); + $("opts").showPopover(); + $("edit").focus(); + $("elsewhere").focus(); + $("opts").showPopover(); + $("opts").hidePopover(); + expect(seen).toEqual([ + "open:true", + "escape", + "open:false", + "close-focus", + "open:true", + "focus-outside", + "interact", + "open:false", + "close-focus", + "open:true", + "outside", + "interact", + "open:false", + "close-focus", + ]); +}); + +test("the right arrow and Enter open a sub-menu on its first item, and the left arrow closes it", () => { + $("opts").showPopover(); + $("more").focus(); + press("ArrowRight"); + expect([ + $("sub").matches(":popover-open"), + focused(), + $("more").getAttribute("aria-expanded"), + ]).toEqual([true, "move", "true"]); + press("ArrowDown"); + expect(focused()).toBe("copy"); + press("ArrowLeft"); + expect([$("sub").matches(":popover-open"), focused()]).toEqual([ + false, + "more", + ]); + press("Enter"); + expect(focused()).toBe("move"); + // Escape is for the topmost menu. + press("Escape"); + expect([ + $("sub").dataset.rxClosedBy, + $("opts").dataset.rxClosedBy, + ]).toEqual(["escape", undefined]); + $("sub").hidePopover(); + expect(focused()).toBe("more"); + press("ArrowLeft"); + expect($("opts").matches(":popover-open")).toBe(true); + // A key on an item with an open sub-menu goes to it. + $("sub").showPopover(); + press(" "); + expect(focused()).toBe("move"); + // A choice in a sub-menu closes both. + press("Enter"); + expect([ + $("sub").matches(":popover-open"), + $("opts").matches(":popover-open"), + focused(), + ]).toEqual([false, false, "trigger"]); +}); + +test("the pointer highlights an item and opens a sub-menu after a rest, and leaves it for another item", () => { + $("opts").showPopover(); + point("edit"); + expect(focused()).toBe("edit"); + point("more"); + vi.advanceTimersByTime(99); + expect($("sub").matches(":popover-open")).toBe(false); + vi.advanceTimersByTime(1); + expect([$("sub").matches(":popover-open"), focused()]).toEqual([ + true, + "more", + ]); + point("move"); + expect(focused()).toBe("move"); + point("sub", "pointerleave"); + expect(focused()).toBe("sub"); + // Beside the items, with a sub-menu open, the highlight stays. + point("opts"); + expect(focused()).toBe("sub"); + point("share"); + expect([$("sub").matches(":popover-open"), focused()]).toEqual([ + false, + "share", + ]); + point("opts"); + expect(focused()).toBe("opts"); + point("share"); + point("opts", "pointerleave"); + expect(focused()).toBe("opts"); + // A press on an item that opens a sub-menu opens it, a finger moves nothing. + $("more").click(); + expect($("sub").matches(":popover-open")).toBe(true); + $("opts").dispatchEvent(new Event("pointermove", { bubbles: true })); +}); + +test("a checkbox item checks itself, or says so to the state it is bound to", () => { + const changes = /** @type {boolean[]} */ ([]); + const event = /** @type {any} */ ({ currentTarget: $("check") }); + api.menuCheck(event, (checked) => changes.push(checked)); + expect([ + $("check").getAttribute("aria-checked"), + $("check").dataset.state, + ]).toEqual(["true", "checked"]); + api.menuCheck(event, (checked) => changes.push(checked), true); + expect($("check").getAttribute("aria-checked")).toBe("true"); + api.menuCheck(event); + $("check").setAttribute("aria-disabled", "true"); + api.menuCheck(event, (checked) => changes.push(checked)); + expect([changes, $("check").getAttribute("aria-checked")]).toEqual([ + [true, false], + "false", + ]); +}); + +test("a context menu opens at the pointer, or on its first item from the keyboard", () => { + api.menuSync($("ctx")); + const ask = ( + /** @type {number} */ button, + /** @type {string} */ id = "area", + ) => { + let prevented = false; + api.menuContext( + /** @type {any} */ ({ + currentTarget: $(id), + clientX: 30, + clientY: 40, + button, + preventDefault: () => (prevented = true), + }), + ); + return prevented; + }; + expect(ask(2)).toBe(true); + expect([$("point").style.left, $("point").style.top, focused()]).toEqual([ + "30px", + "40px", + "ctx", + ]); + expect($("ctx").matches(":popover-open")).toBe(true); + ask(0); + expect([$("ctx").matches(":popover-open"), focused()]).toEqual([ + true, + "check", + ]); + $("area").setAttribute("data-disabled", ""); + $("ctx").hidePopover(); + expect(ask(2)).toBe(false); + expect(ask(2, "elsewhere")).toBe(false); + expect($("ctx").matches(":popover-open")).toBe(false); +}); diff --git a/packages/reflex-components-ui/news/+wave4-overlays.feature.md b/packages/reflex-components-ui/news/+wave4-overlays.feature.md index f8b9d00dab5..603cf7bb2d9 100644 --- a/packages/reflex-components-ui/news/+wave4-overlays.feature.md +++ b/packages/reflex-components-ui/news/+wave4-overlays.feature.md @@ -1,4 +1,4 @@ -Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog`, `alert_dialog`, `drawer`, `popover` and `tooltip`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog, an alert dialog and a drawer are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. +Add the overlays and the disclosure components to `rx.ui`: `tabs`, `accordion`, `dialog`, `alert_dialog`, `drawer`, `popover`, `tooltip`, `hover_card`, `dropdown_menu` (also `menu`) and `context_menu`, with the members of each namespace. Each takes the arguments of the component of the same name in `rx` and looks the same. Tabs are buttons and panels the server renders in the state they start in; a small script selects a tab on a press, on the focus and with the arrow keys. An item of an accordion is a native `details`, so it opens and closes before JavaScript loads. A dialog, an alert dialog and a drawer are a native modal `dialog`: the browser puts it over the page, makes the page behind it inert, moves the focus in and gives it back, and what the dialog holds is in the page the server sends. A button whose popup is open has the look Radix Themes gives it (`[data-state='open']`), which `rx.ui.button` did not have. @@ -7,3 +7,7 @@ A button whose popup is open has the look Radix Themes gives it (`[data-state='o `rx.ui.popover` is a native popover placed beside its trigger by CSS anchor positioning: the browser opens and closes it without JavaScript. It is not modal, and closes when the focus leaves it. `rx.ui.tooltip` always describes its child to assistive technology, shown or not, and has no arrow. + +`rx.ui.hover_card` opens under the pointer and with the focus of the keyboard after the delays of its root, and the links inside it can be reached with Tab. + +`rx.ui.dropdown_menu` and `rx.ui.context_menu` are a native popover with the roles `menu`, `menuitem` and `menuitemcheckbox`: a small script moves through the items with the arrow keys, Home, End and typing, opens sub-menus with the pointer and the right arrow, and closes the menu on a choice with the focus back on the trigger. A context menu opens at the pointer, and for the context-menu key and Shift+F10. The menu of a dropdown opens without JavaScript. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 62efc55baf8..66e2499eafc 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -498,3 +498,118 @@ component = "tooltip" step = "the dark appearance of a theme around a tooltip reaches it" system = "rx" reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a tooltip included. rx.ui.theme does, and a tooltip declared inside a dark rx.ui.theme has the colors of the dark appearance." + +[[look]] +component = "popover" +check = "style" +cells = "*@open" +properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] +reason = "Radix places a popover with a wrapper element it moves by a transform, and the popover inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.popover is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." + +[[look]] +component = "popover" +check = "style" +cells = "long-true@open" +properties = ["height"] +reason = "A popover taller than the page grows past the bottom of the page in rx.popover. rx.ui.popover is no taller than the room the viewport leaves, and scrolls what it holds." + +[[look]] +component = "tooltip" +check = "style" +properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] +reason = "Radix places a tooltip with a wrapper element it moves by a transform, and the tooltip inside it has no position, margins or bounds of its own. rx.ui.tooltip is placed itself, a native popover in the top layer: fixed, at a margin from what it describes by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." + +[[look]] +component = "hover_card" +check = "style" +properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] +reason = "Radix places a hover card with a wrapper element it moves by a transform, and the card inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.hover_card is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." + +[[look]] +component = "hover_card" +check = "style" +cells = "long-true@open" +properties = ["height"] +reason = "A hover card taller than the page grows past the bottom of the page in rx.hover_card. rx.ui.hover_card is no taller than the room the viewport leaves, and scrolls what it holds." + +[[look]] +component = "drawer" +check = "style" +cells = "*@open" +properties = ["user-select"] +reason = "The panel of rx.drawer cannot have its text selected, as it is dragged by any point of it. rx.ui.drawer is not dragged, and the text of its panel is selected as any other." + +[[look]] +component = "drawer" +check = "style" +cells = "inside-true@open" +properties = ["color", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "outline-color"] +reason = "The overlay of rx.drawer declared inside its portal is rendered at the end of the page, outside the theme, and takes the text color of the page there; the one of rx.ui.drawer stays inside the theme. An overlay holds no text, so nothing is drawn in either color." + +[[contract]] +component = "hover_card" +step = "Tab does not reach the links inside it" +system = "rx.ui" +reason = "rx.hover_card takes what is inside the card out of the order of Tab: a keyboard user sees the card and cannot reach its links. The card of rx.ui.hover_card comes right after its trigger, so Tab moves into it and through its links, and the card stays open while the focus is inside it." + +[[contract]] +component = "hover_card" +step = "the dark appearance of a theme around a hover card reaches it" +system = "rx" +reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a hover card included. rx.ui.theme does, and a hover card declared inside a dark rx.ui.theme is dark." + +[[look]] +component = "dropdown_menu" +check = "style" +properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] +reason = "Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.dropdown_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." + +[[look]] +component = "dropdown_menu" +check = "style" +properties = ["pointer-events"] +reason = "While it is open rx.dropdown_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.dropdown_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.dropdown_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.dropdown_menu hears the press and ignores it." + +[[look]] +component = "context_menu" +check = "style" +properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] +reason = "Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.context_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." + +[[look]] +component = "context_menu" +check = "style" +properties = ["pointer-events"] +reason = "While it is open rx.context_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.context_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.context_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.context_menu hears the press and ignores it." + +[[contract]] +component = "dropdown_menu" +step = "opens with JavaScript disabled" +system = "rx" +reason = "rx.dropdown_menu is opened by JavaScript: until it has run, a press on its trigger does nothing. The menu of rx.ui.dropdown_menu is a native popover of its trigger, which the browser opens, places and closes, on Escape and on a press outside, with or without JavaScript; moving through its items and choosing one wait for JavaScript." + +[[contract]] +component = "dropdown_menu" +step = "the dark appearance of a theme around a menu reaches it" +system = "rx" +reason = "rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a menu included. rx.ui.theme does, and a menu declared inside a dark rx.ui.theme is dark." + +[[look]] +component = "dropdown_menu" +check = "pixels" +cells = "long-true@open" +reason = "A menu taller than the room the viewport leaves scrolls. rx.dropdown_menu draws a scrollbar of its own over the items, always shown, and widens the menu by the room it takes. The menu of rx.ui.dropdown_menu scrolls natively: the browser draws the scrollbar, in the colors of Radix, and decides its shape and when it shows." + +[[look]] +component = "dropdown_menu" +check = "style" +cells = "long-true@open" +properties = ["padding-right", "width"] +reason = "rx.dropdown_menu widens a menu that scrolls by the room its own scrollbar takes. The scrollbar of rx.ui.dropdown_menu is the browser's, which takes the room it needs itself." + +[[contract]] +component = "dropdown_menu" +step = "Escape closes only the sub-menu, and a choice in it closes both" +system = "rx" +reason = "Escape in a sub-menu of rx.dropdown_menu closes the whole menu. A sub-menu of rx.ui.dropdown_menu is a popover nested in its menu, and Escape closes only the topmost one, giving the focus back to the item that opened it, as the WAI-ARIA menu pattern describes; a second Escape closes the menu." + diff --git a/packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py b/packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py index 19a1e9db466..9d2b3edaa9b 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/alert_dialog.py @@ -6,7 +6,7 @@ from typing import Any import reflex as rx -from ui_parity.components.dialog import OPEN, OPENED, body +from ui_parity.components.dialog import OPEN, OPENED, PARTS, body from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix from ui_parity.samples import focused, wait_for_text @@ -60,6 +60,7 @@ def _alert(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(1200, 700), crop="stage", target="button", + parts=PARTS, states={OPEN: OPENED}, # Not held to zero. At a threshold of zero every cell but one is equal # pixel for pixel: the ring of the focus on the trigger, which the diff --git a/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py new file mode 100644 index 00000000000..c3fe1ec5993 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py @@ -0,0 +1,403 @@ +"""The context menu: at the pointer and for the keyboard, in each size and look, with checkbox items.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.components.dropdown_menu import PARTS, SHOWN, close_menu +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, LIGHT, Matrix, in_page +from ui_parity.samples import wait_for_text, wait_for_value + +SIZES = ["1", "2"] +VARIANTS = ["solid", "soft"] +OPEN = "open" +KEYS = "keys" +SUB = "sub" +_RADIX = ".rt-BaseMenuContent:not(.rt-BaseMenuSubContent)" +_UI = "[role=menu]:popover-open:not([role=menu] *)" + + +def _area(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create an area with a context menu. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the content. ``checks`` asks for checkbox items, + a label and a group, and ``themed`` for a theme of another + accent and radius around the menu. + + Returns: + The area, with room beside it for its menu. + """ + props = dict(props) + menu = namespace.context_menu + checks, themed = props.pop("checks", False), props.pop("themed", False) + extra = ( + [ + menu.separator(), + menu.label("View"), + menu.group( + menu.checkbox("Show grid", checked=True, shortcut="⌘ G"), + menu.checkbox("Show rulers"), + ), + ] + if checks + else [] + ) + shown = menu.root( + menu.trigger( + rx.el.div( + "Right-click here", + tab_index=0, + style={ + "width": "200px", + "height": "100px", + "border": "1px dashed gray", + }, + ) + ), + menu.content( + menu.item("Copy", shortcut="⌘ C"), + menu.item("Paste", shortcut="⌘ V", disabled=True), + menu.sub( + menu.sub_trigger("Share"), + menu.sub_content(menu.item("Email"), menu.item("Messages")), + ), + *extra, + menu.separator(), + menu.item("Delete", color_scheme="red"), + **props, + ), + ) + if themed: + shown = namespace.theme(shown, accent_color="ruby", radius="full") + return rx.el.div(shown, style={"padding": "60px 0 0 60px"}) + + +def _wait(page: Page, count: int) -> None: + """Wait until a number of menus are shown. + + Args: + page: The page. + count: How many. + """ + wait_for_value(page, f"document.querySelectorAll('{SHOWN}').length", count) + + +def _right_click(page: Page, target: Locator, point: Point) -> None: + """Open the context menu with a right click near the corner of its area. + + Args: + page: The page. + target: The area. + point: The middle of the area. + """ + page.mouse.click(point[0] - 80, point[1] - 30, button="right") + _wait(page, 1) + page.mouse.move(1, 1) + + +def _keys(page: Page, target: Locator, point: Point) -> None: + """Open the context menu with Shift+F10, which highlights its first item. + + Args: + page: The page. + target: The area. + point: The middle of the area. + """ + target.focus() + page.keyboard.press("Shift+F10") + _wait(page, 1) + wait_for_value(page, "document.activeElement.textContent.startsWith('Copy')", True) + + +def _open_sub(page: Page, target: Locator, point: Point) -> None: + """Open the context menu, and its sub-menu under the pointer. + + Args: + page: The page. + target: The area. + point: The middle of the area. + """ + _right_click(page, target, point) + page.get_by_role("menuitem", name="Share").hover() + _wait(page, 2) + + +MATRIX = Matrix( + component="context_menu", + render=_area, + sweep={ + "size": SIZES, + "variant": VARIANTS, + "high_contrast": [True], + "checks": [True], + "appearance": [DARK], + "state": [OPEN, KEYS, SUB], + }, + groups=[ + {"size": SIZES, "variant": VARIANTS, "state": [OPEN, KEYS, SUB]}, + {"checks": [True], "size": SIZES, "state": [OPEN, KEYS]}, + {"variant": VARIANTS, "high_contrast": [True], "state": [KEYS]}, + {"variant": VARIANTS, "state": [KEYS, SUB], "appearance": [LIGHT, DARK]}, + {"themed": [True], "state": [KEYS], "appearance": [LIGHT, DARK]}, + ], + stage=(560, 420), + crop="stage", + target="div[tabindex]", + parts={ + **{name: PARTS[name] for name in ("content", "viewport", "separator", "sub")}, + "item": ( + in_page(f"{_RADIX} .rt-BaseMenuItem"), + f"{_UI} > div > div > [role=menuitem]", + ), + "highlighted": PARTS["highlighted"], + "label": ( + in_page(f"{_RADIX} .rt-BaseMenuLabel"), + f"{_UI} > div > div > div:not([role])", + ), + "checked": ( + in_page(f"{_RADIX} [role=menuitemcheckbox][aria-checked=true]"), + f"{_UI} [role=menuitemcheckbox][aria-checked=true]", + ), + "indicator": ( + in_page(f"{_RADIX} .rt-BaseMenuItemIndicator"), + f"{_UI} [role=menuitemcheckbox][aria-checked=true] > span", + ), + }, + states={ + OPEN: State( + enter=_right_click, leave=close_menu, matches="[data-state='open']" + ), + KEYS: State(enter=_keys, leave=close_menu, matches="[data-state='open']"), + SUB: State(enter=_open_sub, leave=close_menu, matches="[data-state='open']"), + }, + # Not held to a threshold of zero. At zero 18 of the 39 cells are equal + # pixel for pixel. In the 9 with a sub-menu open, the shadows of the two + # menus, which overlap, are composited in another order than in Radix: + # 6,200 to 10,800 pixels of 235,200 differ by 1 or 2 steps of a channel. + # The translucent highlight of the soft variant differs by 1 step over + # some 60 pixels, and 1 or 2 pixels of others by 1. At the default + # threshold all but 8 cells are equal, and those differ by 1 pixel of + # 235,200, 3 or 4 steps apart: the dashed border of the area under the + # menu, or an edge of a letter, which the browser draws by where they are. + tolerance=0.00001, +) + + +class ContextMenuState(rx.State): + """What the context menus of the contract say.""" + + seen: rx.Field[list[str]] = rx.field(default_factory=list) + grid: rx.Field[bool] = rx.field(True) + + @rx.event + def see(self, what: str): + """Keep what happened to a menu. + + Args: + what: The event. + """ + self.seen.append(what) + + @rx.event + def see_open(self, value: bool): + """Keep whether a menu opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def set_grid(self, value: bool): + """Follow the checkbox item bound to state. + + Args: + value: Whether it is checked. + """ + self.grid = value + self.seen.append(f"grid:{value}") + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + An area with a context menu that says what happens to it, and one + that is disabled. + """ + menu = namespace.context_menu + return rx.el.div( + menu.root( + menu.trigger( + rx.el.div( + "Right-click here", + id="area", + tab_index=0, + style={"width": "300px", "height": "150px"}, + ) + ), + menu.content( + menu.item("Copy", on_select=ContextMenuState.see("copy"), id="copy"), + menu.item("Paste", disabled=True, id="paste"), + menu.checkbox( + "Show grid", + checked=ContextMenuState.grid, + on_change=ContextMenuState.set_grid, + id="grid", + ), + menu.checkbox("Show rulers", id="rulers"), + menu.sub( + menu.sub_trigger("Share", id="share"), + menu.sub_content(menu.item("Email", id="email")), + ), + on_escape_key_down=ContextMenuState.see("escape"), + ), + on_open_change=ContextMenuState.see_open, + ), + menu.root( + menu.trigger( + rx.el.div("Not here", id="off", style={"width": "100px"}), + disabled=True, + ), + menu.content(menu.item("Never", id="never")), + ), + rx.el.span(ContextMenuState.seen.to_string(), id="seen"), + style={"padding": "40px"}, + ) + + +CONTRACT = Contract(component="context_menu", render=_contract) + +SHOWING = f"[...document.querySelectorAll('{SHOWN}')].map(menu => menu.querySelector('[role^=menuitem]').id)" + + +def _shown(run: Run, *first: str) -> None: + """Wait until the menus shown are the ones expected. + + Args: + run: The run, on a page. + *first: The id of the first item of each. + """ + wait_for_value(run.page, SHOWING, list(first)) + + +def _focus(run: Run, item: str) -> None: + """Wait until an element has the focus. + + Args: + run: The run, on a page. + item: Its id. + """ + wait_for_value(run.page, "document.activeElement.id", item) + + +@CONTRACT.step("its area is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + area = run.server.element("area") + assert (area.tag, area.text) == ("div", "Right-click here") + + +@CONTRACT.step( + "shows the menu of the browser with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + prevented = run.page.evaluate( + "() => { const event = new MouseEvent('contextmenu', {bubbles: true, cancelable: true});" + " return !document.getElementById('area').dispatchEvent(event); }" + ) + assert prevented is False + _shown(run) + + +@CONTRACT.step("opens at the pointer on a right click, and Escape closes it") +def _right(run: Run) -> None: + page = run.page + box = page.locator("#area").bounding_box() + assert box is not None + x, y = box["x"] + 40, box["y"] + 30 + page.mouse.click(x, y, button="right") + _shown(run, "copy") + menu = page.get_by_role("menu").bounding_box() + assert menu is not None + # Beside the pointer, its first item at the height of the pointer. + assert abs(menu["x"] - x) <= 4 + assert abs(menu["y"] - y) <= 10 + page.keyboard.press("Escape") + _shown(run) + wait_for_text(page, "seen", '["open","escape","closed"]') + + +@CONTRACT.step("opens from the keyboard on its first item") +def _keyboard(run: Run) -> None: + page = run.page + page.locator("#area").focus() + page.keyboard.press("Shift+F10") + _shown(run, "copy") + _focus(run, "copy") + page.keyboard.press("ArrowDown") + _focus(run, "grid") + + +@CONTRACT.step( + "a checkbox item says whether it is checked, and hands over the new state" +) +def _checkbox(run: Run) -> None: + page = run.page + checked = "document.getElementById('{}')?.getAttribute('aria-checked') ?? null" + page.locator("#area").click(button="right") + _shown(run, "copy") + assert page.locator("#grid").get_attribute("role") == "menuitemcheckbox" + wait_for_value(page, checked.format("grid"), "true") + page.locator("#grid").click() + _shown(run) + wait_for_text(page, "seen", '["open","grid:False","closed"]') + page.locator("#area").click(button="right") + _shown(run, "copy") + wait_for_value(page, checked.format("grid"), "false") + wait_for_value(page, checked.format("rulers"), "false") + + +@CONTRACT.step("a choice says so and closes the menu") +def _choice(run: Run) -> None: + page = run.page + page.locator("#area").click(button="right") + page.locator("#copy").click() + _shown(run) + wait_for_text(page, "seen", '["open","copy","closed"]') + + +@CONTRACT.step("the right arrow opens a sub-menu, and the left arrow closes it") +def _sub(run: Run) -> None: + page = run.page + page.locator("#area").focus() + page.keyboard.press("Shift+F10") + _focus(run, "copy") + page.keyboard.press("End") + _focus(run, "share") + page.keyboard.press("ArrowRight") + _shown(run, "copy", "email") + _focus(run, "email") + page.keyboard.press("ArrowLeft") + _shown(run, "copy") + _focus(run, "share") + + +@CONTRACT.step("a disabled area keeps the menu of the browser") +def _disabled(run: Run) -> None: + prevented = run.page.evaluate( + "() => { const event = new MouseEvent('contextmenu', {bubbles: true, cancelable: true});" + " return !document.getElementById('off').dispatchEvent(event); }" + ) + assert prevented is False + _shown(run) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py index cbb96f881c1..827fe69d539 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py @@ -10,7 +10,7 @@ import reflex as rx from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.look import Point, State -from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix, in_page from ui_parity.samples import PARAGRAPH, focused, wait_for_text SIZES = ["1", "2", "3", "4"] @@ -103,6 +103,18 @@ def close_dialog(page: Page, target: Locator, point: Point) -> None: ) +# The parts of an open dialog, in each system: Radix renders it at the end of +# the page, an overlay around a panel; rx.ui renders a native dialog, which +# draws the overlay with its ::before, around a panel. +_RADIX = ".rt-BaseDialogContent" +PARTS = { + "overlay": (in_page(".rt-BaseDialogOverlay::before"), "dialog[open]::before"), + "content": (in_page(_RADIX), "dialog[open] > div > div"), + "title": (in_page(f"{_RADIX} h1"), "dialog[open] h1"), + "description": (in_page(f"{_RADIX} p"), "dialog[open] p"), + "close": (in_page(f"{_RADIX} button"), "dialog[open] button"), +} + OPENED = State(enter=open_dialog, leave=close_dialog, matches="[data-state='open']") MATRIX = Matrix( @@ -132,6 +144,7 @@ def close_dialog(page: Page, target: Locator, point: Point) -> None: stage=(1200, 700), crop="stage", target="button", + parts=PARTS, states={OPEN: OPENED}, # Not held to zero. At a threshold of zero every cell but two is equal # pixel for pixel: the ring of the focus on the trigger, which the diff --git a/packages/reflex-components-ui/parity/ui_parity/components/drawer.py b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py index 0bd7d5b330a..ba53ab4f533 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/drawer.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py @@ -11,7 +11,7 @@ from ui_parity.components.dialog import OPEN, close_dialog, open_dialog from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.look import Point, State -from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix, in_page from ui_parity.samples import wait_for_text DIRECTIONS = ["bottom", "top", "left", "right"] @@ -126,6 +126,16 @@ def _close(page: Page, target: Locator, point: Point) -> None: stage=(1200, 700), crop="stage", target="button", + parts={ + "overlay": ( + in_page("[data-vaul-overlay]"), + "div[data-rx-popup]:has(+ dialog[open])", + ), + "content": (in_page("[data-vaul-drawer]"), "dialog[open] > div"), + "title": (in_page("[data-vaul-drawer] h2"), "dialog[open] h2"), + "description": (in_page("[data-vaul-drawer] p"), "dialog[open] p"), + "close": (in_page("[data-vaul-drawer] button"), "dialog[open] button"), + }, states={ OPEN: State(enter=open_dialog, leave=_close, matches="[data-state='open']") }, diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py new file mode 100644 index 00000000000..765743636d9 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py @@ -0,0 +1,601 @@ +"""The dropdown menu: closed and open in each size and look, its sub-menus, and its keys.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix, in_page +from ui_parity.samples import wait_for_text, wait_for_value + +SIZES = ["1", "2"] +VARIANTS = ["solid", "soft"] +SIDES = ["top", "right", "bottom", "left"] +ALIGNS = ["start", "center", "end"] +OPEN = "open" +KEYS = "keys" +SUB = "sub" +# The menus that are open, in either system: Radix renders them at the end +# of the page, rx.ui after what opens them. +SHOWN = ".rt-BaseMenuContent, [role=menu]:popover-open" +# The open menu and its parts, in each system. +_RADIX = ".rt-BaseMenuContent:not(.rt-BaseMenuSubContent)" +_UI = "[role=menu]:popover-open:not([role=menu] *)" +_RADIX_SUB = ".rt-BaseMenuSubContent" +_UI_SUB = "[role=menu] [role=menu]:popover-open" +PARTS = { + "content": (in_page(_RADIX), _UI), + "viewport": (in_page(f"{_RADIX} .rt-BaseMenuViewport"), f"{_UI} > div > div"), + "item": ( + in_page(f"{_RADIX} .rt-BaseMenuItem"), + f"{_UI} > div > div > [role=menuitem]", + ), + "shortcut": ( + in_page(f"{_RADIX} .rt-BaseMenuShortcut"), + f"{_UI} [role=menuitem] > div", + ), + "separator": (in_page(f"{_RADIX} [role=separator]"), f"{_UI} [role=separator]"), + "sub-trigger": ( + in_page(f"{_RADIX} .rt-BaseMenuSubTrigger"), + f"{_UI} [aria-haspopup=menu]", + ), + "chevron": ( + in_page(f"{_RADIX} .rt-BaseMenuSubTriggerIcon"), + f"{_UI} [aria-haspopup=menu] svg", + ), + "colored": ( + in_page(f"{_RADIX} .rt-BaseMenuItem[data-accent-color]"), + f"{_UI} > div > div > [role=menuitem]:last-child", + ), + "disabled": ( + in_page(f"{_RADIX} .rt-BaseMenuItem[data-disabled]"), + f"{_UI} [aria-disabled=true]", + ), + "highlighted": ( + in_page(f"{_RADIX} .rt-BaseMenuItem[data-highlighted]"), + f"{_UI} [role^=menuitem]:focus", + ), + "sub": (in_page(_RADIX_SUB), _UI_SUB), + "sub-item": ( + in_page(f"{_RADIX_SUB} .rt-BaseMenuItem"), + f"{_UI_SUB} [role=menuitem]", + ), +} + + +def items(namespace: Any, kind: Any, long: bool = False) -> list[Any]: + """Create the items of a menu of the matrix. + + Args: + namespace: ``rx`` or ``rx.ui``. + kind: The namespace of the menu. + long: Whether there are more than the viewport has room for. + + Returns: + Items with shortcuts, a disabled one, a separator, a sub-menu, and + one of its own color. + """ + return [ + kind.item("Edit", shortcut="⌘ E"), + kind.item("Duplicate", shortcut="⌘ D"), + kind.item("Rename", disabled=True), + kind.separator(), + kind.sub( + kind.sub_trigger("More"), + kind.sub_content( + kind.item("Move to project"), + kind.item("Move to folder"), + kind.separator(), + kind.item("Advanced options"), + ), + ), + *(kind.item(f"Item {number}") for number in range(1, 30 if long else 1)), + kind.separator(), + kind.item("Delete", shortcut="⌘ ⌫", color_scheme="red"), + ] + + +def _menu(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a dropdown menu and the button that opens it. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the content. ``long`` asks for more items than + the page has room for, and ``themed`` for a theme of another + accent and radius around the menu. + + Returns: + The menu, with room around its trigger for it to open on any side. + """ + props = dict(props) + menu = namespace.dropdown_menu + long, themed = props.pop("long", False), props.pop("themed", False) + shown = menu.root( + menu.trigger(namespace.button("Options", variant="soft", width="100px")), + menu.content(*items(namespace, menu, long), **props), + ) + if themed: + shown = namespace.theme(shown, accent_color="ruby", radius="full") + return rx.el.div(shown, style={"padding": "260px 0 0 260px"}) + + +def _wait(page: Page, count: int) -> None: + """Wait until a number of menus are shown. + + Args: + page: The page. + count: How many. + """ + wait_for_value(page, f"document.querySelectorAll('{SHOWN}').length", count) + + +def open_menu(page: Page, target: Locator, point: Point) -> None: + """Open a menu from its trigger, and wait for it. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + target.click() + _wait(page, 1) + # The pointer is not left on the trigger. + page.mouse.move(1, 1) + + +def _open_keys(page: Page, target: Locator, point: Point) -> None: + """Open a menu with the down arrow, which highlights its first item. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + target.focus() + page.keyboard.press("ArrowDown") + _wait(page, 1) + wait_for_value(page, "document.activeElement.textContent.startsWith('Edit')", True) + + +def _open_sub(page: Page, target: Locator, point: Point) -> None: + """Open a menu, and its sub-menu under the pointer. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + open_menu(page, target, point) + page.get_by_role("menuitem", name="More").hover() + _wait(page, 2) + + +def close_menu(page: Page, target: Locator, point: Point) -> None: + """Close every open menu, and take the focus off whatever has it. + + Args: + page: The page. + target: The trigger. + point: The middle of the trigger. + """ + page.mouse.move(1, 1) + while page.evaluate(f"document.querySelectorAll('{SHOWN}').length"): + page.keyboard.press("Escape") + page.wait_for_timeout(50) + page.evaluate("document.activeElement.blur()") + + +OPENED = State(enter=open_menu, leave=close_menu, matches="[data-state='open']") + +MATRIX = Matrix( + component="dropdown_menu", + render=_menu, + sweep={ + "size": SIZES, + "variant": VARIANTS, + "high_contrast": [True], + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE, OPEN, KEYS, SUB], + }, + groups=[ + {"size": SIZES, "variant": VARIANTS, "state": [OPEN, KEYS, SUB]}, + {"variant": VARIANTS, "high_contrast": [True], "state": [KEYS, SUB]}, + {"color_scheme": ["ruby", "gray"], "state": [KEYS]}, + {"variant": VARIANTS, "state": [KEYS, SUB], "appearance": [LIGHT, DARK]}, + {"side": SIDES, "align": ALIGNS, "state": [OPEN]}, + {"side": SIDES, "side_offset": [0, 12], "state": [OPEN]}, + {"themed": [True], "state": [KEYS], "appearance": [LIGHT, DARK]}, + {"long": [True], "state": [OPEN]}, + ], + stage=(720, 620), + crop="stage", + target="button", + parts=PARTS, + states={ + OPEN: OPENED, + KEYS: State(enter=_open_keys, leave=close_menu, matches="[data-state='open']"), + SUB: State(enter=_open_sub, leave=close_menu, matches="[data-state='open']"), + }, + # Not held to a threshold of zero. At zero 49 of the 61 cells are equal + # pixel for pixel. In the 11 with a sub-menu open, the shadows of the + # two menus, which overlap, are composited in another order than in + # Radix: 6,300 to 9,000 pixels of 446,400 differ by 1 or 2 steps of a + # channel. At the default threshold they are equal. The long menu + # differs by its scrollbar, which the allowlist explains. + tolerance=0, +) + + +class MenuState(rx.State): + """What the menus of the contract are bound to.""" + + shown: rx.Field[bool] = rx.field(False) + seen: rx.Field[list[str]] = rx.field(default_factory=list) + + @rx.event + def set_shown(self, value: bool): + """Follow the bound menu. + + Args: + value: Whether it is open. + """ + self.shown = value + + @rx.event + def see_open(self, value: bool): + """Keep whether a menu opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def see(self, what: str): + """Keep what happened to a menu. + + Args: + what: The event. + """ + self.seen.append(what) + + @rx.event + def close(self): + """Close the bound menu from the backend.""" + self.shown = False + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + A menu that says what happens to it, one bound to state, one in a + dialog, and one in a dark theme. + """ + menu, dialog, button = namespace.dropdown_menu, namespace.dialog, namespace.button + return namespace.flex( + menu.root( + menu.trigger(button("Options", id="options")), + menu.content( + menu.item("Edit", on_select=MenuState.see("edit"), id="edit"), + menu.item("Duplicate", id="duplicate"), + menu.item("Delete", disabled=True, id="delete"), + menu.item("Archive", id="archive"), + menu.sub( + menu.sub_trigger("More", id="more"), + menu.sub_content( + menu.item("Move", on_select=MenuState.see("move"), id="move"), + menu.item("Copy", id="copy"), + ), + ), + menu.item("Share", id="share"), + on_escape_key_down=MenuState.see("escape"), + on_pointer_down_outside=MenuState.see("outside"), + on_close_auto_focus=MenuState.see("close-focus"), + ), + on_open_change=MenuState.see_open, + ), + menu.root( + menu.trigger(button("Bound", id="bound")), + menu.content( + menu.item( + "Close from the backend", on_select=MenuState.close, id="backend" + ), + id="bound-menu", + ), + open=MenuState.shown, + on_open_change=MenuState.set_shown, + ), + rx.el.button("Show", id="show", on_click=MenuState.set_shown(True)), + dialog.root( + dialog.trigger(button("Dialog", id="dialog-open")), + dialog.content( + dialog.title("With a menu"), + menu.root( + menu.trigger(button("Inside", id="inside")), + menu.content(menu.item("In a dialog", id="in-dialog")), + ), + id="dialog-panel", + ), + ), + namespace.theme( + menu.root( + menu.trigger(button("Dark", id="dark")), + menu.content(menu.item("In the dark", id="dark-item")), + ), + appearance="dark", + ), + rx.el.span(MenuState.seen.to_string(), id="seen"), + rx.el.span(MenuState.shown.to_string(), id="shown"), + spacing="4", + padding="60px 0 0 60px", + wrap="wrap", + ) + + +CONTRACT = Contract(component="dropdown_menu", render=_contract) + +# The ids of the menus that are shown. +SHOWING = f"[...document.querySelectorAll('{SHOWN}')].map(menu => menu.querySelector('[role^=menuitem]').id)" + + +def _shown(run: Run, *first: str) -> None: + """Wait until the menus shown are the ones expected. + + Args: + run: The run, on a page. + *first: The id of the first item of each. + """ + wait_for_value(run.page, SHOWING, list(first)) + + +def _focus(run: Run, item: str) -> None: + """Wait until an element has the focus. + + Args: + run: The run, on a page. + item: Its id. + """ + wait_for_value(run.page, "document.activeElement.id", item) + + +@CONTRACT.step("its trigger is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + trigger = run.server.element("options") + assert (trigger.tag, trigger.text) == ("button", "Options") + + +@CONTRACT.step("opens with JavaScript disabled", on=NO_JAVASCRIPT) +def _without_javascript(run: Run) -> None: + run.page.locator("#options").click() + _shown(run, "edit") + run.page.keyboard.press("Escape") + _shown(run) + + +@CONTRACT.step("opens on a press, says so, and Escape closes it back to the trigger") +def _press(run: Run) -> None: + page = run.page + page.locator("#options").click() + _shown(run, "edit") + assert page.locator("#options").get_attribute("aria-expanded") == "true" + assert page.get_by_role("menu").count() == 1 + page.keyboard.press("Escape") + _shown(run) + _focus(run, "options") + wait_for_value(page, "document.getElementById('options').ariaExpanded", "false") + wait_for_text(page, "seen", '["open","escape","closed","close-focus"]') + + +@CONTRACT.step("Enter, Space and the down arrow open it on its first item") +def _keys_open(run: Run) -> None: + page = run.page + for key in ("Enter", " ", "ArrowDown"): + page.locator("#options").focus() + page.keyboard.press(key) + _shown(run, "edit") + _focus(run, "edit") + page.keyboard.press("Escape") + _shown(run) + _focus(run, "options") + + +@CONTRACT.step( + "the arrows, Home, End and typing move through the items, past a disabled one" +) +def _arrows(run: Run) -> None: + page = run.page + page.locator("#options").focus() + page.keyboard.press("Enter") + _focus(run, "edit") + for key, item in ( + ("ArrowDown", "duplicate"), + ("ArrowDown", "archive"), + ("ArrowUp", "duplicate"), + ("End", "share"), + ("ArrowDown", "share"), + ("Home", "edit"), + ("ArrowUp", "edit"), + ("s", "share"), + ("a", "archive"), + ): + if len(key) == 1: + # What was typed before is forgotten after a second. + page.wait_for_timeout(1100) + page.keyboard.press(key) + _focus(run, item) + + +@CONTRACT.step("Tab does not leave an open menu") +def _tab(run: Run) -> None: + page = run.page + page.locator("#options").focus() + page.keyboard.press("Enter") + _focus(run, "edit") + page.keyboard.press("Tab") + _shown(run, "edit") + _focus(run, "edit") + + +@CONTRACT.step( + "a choice says so, closes the menu and gives the focus back to the trigger" +) +def _choice(run: Run) -> None: + page = run.page + page.locator("#options").focus() + page.keyboard.press("Enter") + _focus(run, "edit") + page.keyboard.press("Enter") + _shown(run) + _focus(run, "options") + wait_for_text(page, "seen", '["open","edit","closed","close-focus"]') + page.locator("#options").click() + page.locator("#edit").click() + _shown(run) + wait_for_text( + page, + "seen", + '["open","edit","closed","close-focus","open","edit","closed","close-focus"]', + ) + + +@CONTRACT.step("a press on a disabled item does nothing") +def _disabled(run: Run) -> None: + page = run.page + page.locator("#options").click() + page.locator("#delete").click(force=True) + page.wait_for_timeout(200) + _shown(run, "edit") + + +@CONTRACT.step( + "the right arrow opens a sub-menu on its first item, the left arrow closes it" +) +def _sub_keys(run: Run) -> None: + page = run.page + page.locator("#options").focus() + page.keyboard.press("Enter") + _focus(run, "edit") + page.keyboard.press("End") + _focus(run, "share") + page.keyboard.press("ArrowUp") + _focus(run, "more") + page.keyboard.press("ArrowRight") + _shown(run, "edit", "move") + _focus(run, "move") + assert page.locator("#more").get_attribute("aria-expanded") == "true" + page.keyboard.press("ArrowLeft") + _shown(run, "edit") + _focus(run, "more") + page.keyboard.press("Enter") + _shown(run, "edit", "move") + _focus(run, "move") + + +@CONTRACT.step("Escape closes only the sub-menu, and a choice in it closes both") +def _sub_escape(run: Run) -> None: + page = run.page + page.locator("#options").focus() + page.keyboard.press("Enter") + _focus(run, "edit") + page.keyboard.press("End") + _focus(run, "share") + page.keyboard.press("ArrowUp") + _focus(run, "more") + page.keyboard.press("ArrowRight") + _shown(run, "edit", "move") + _focus(run, "move") + page.keyboard.press("Escape") + _shown(run, "edit") + _focus(run, "more") + page.keyboard.press("ArrowRight") + _shown(run, "edit", "move") + _focus(run, "move") + page.keyboard.press("Enter") + _shown(run) + _focus(run, "options") + wait_for_value( + page, "document.getElementById('seen').textContent.includes('move')", True + ) + + +@CONTRACT.step("the pointer opens a sub-menu, and leaves it for another item") +def _sub_pointer(run: Run) -> None: + page = run.page + page.locator("#options").click() + page.locator("#more").hover() + _shown(run, "edit", "move") + page.locator("#move").hover() + _focus(run, "move") + page.locator("#share").hover() + _shown(run, "edit") + _focus(run, "share") + + +@CONTRACT.step("a press outside closes it and says so") +def _outside(run: Run) -> None: + page = run.page + page.locator("#options").click() + _shown(run, "edit") + page.mouse.click(5, 5) + _shown(run) + wait_for_value( + page, + "JSON.parse(document.getElementById('seen').textContent).slice(0, 3)", + ["open", "outside", "closed"], + ) + + +@CONTRACT.step("a menu bound to state follows it, and closes from a backend handler") +def _bound(run: Run) -> None: + page = run.page + page.locator("#show").click() + _shown(run, "backend") + wait_for_text(page, "shown", "true") + page.locator("#backend").click() + _shown(run) + wait_for_text(page, "shown", "false") + page.locator("#bound").click() + _shown(run, "backend") + wait_for_text(page, "shown", "true") + + +@CONTRACT.step("a menu in a dialog shows over it, and Escape closes the menu alone") +def _in_dialog(run: Run) -> None: + page = run.page + page.locator("#dialog-open").click() + page.locator("#dialog-panel").wait_for() + page.locator("#inside").click() + _shown(run, "in-dialog") + box = page.locator("#in-dialog").bounding_box() + assert box is not None + assert ( + page.evaluate( + "([x, y]) => document.elementFromPoint(x, y).id", + [box["x"] + box["width"] / 2, box["y"] + box["height"] / 2], + ) + == "in-dialog" + ) + page.keyboard.press("Escape") + _shown(run) + page.locator("#dialog-panel").wait_for() + _focus(run, "inside") + + +@CONTRACT.step("the dark appearance of a theme around a menu reaches it") +def _themed_dark(run: Run) -> None: + page = run.page + page.locator("#dark").click() + _shown(run, "dark-item") + page.wait_for_timeout(300) + assert page.locator("#dark-item").evaluate( + "item => getComputedStyle(item.closest('[role=menu]')).backgroundColor" + ) == ("rgb(25, 25, 25)") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py new file mode 100644 index 00000000000..b44bc7a8391 --- /dev/null +++ b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py @@ -0,0 +1,396 @@ +"""The hover card: in every size, on each side of its trigger, and when it opens and closes.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from playwright.sync_api import Locator, Page + +import reflex as rx +from ui_parity.components.tooltip import leave +from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run +from ui_parity.look import Point, State +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix, in_page +from ui_parity.samples import PARAGRAPH, wait_for_text, wait_for_value + +SIZES = ["1", "2", "3"] +SIDES = ["top", "right", "bottom", "left"] +ALIGNS = ["start", "center", "end"] +OPEN = "open" +# A hover card that is shown, in either system. +SHOWN = ".rt-HoverCardContent, [data-rx-popup]:popover-open" +# The card that is open, in each system: Radix renders it at the end of the +# page, rx.ui right after its trigger. +CARD = (in_page(".rt-HoverCardContent"), "[data-rx-popup]:popover-open") + + +def _card(namespace: Any) -> list[Any]: + """Create what a hover card of the matrix holds. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + A heading, a paragraph and a link. + """ + return [ + namespace.heading("Radix", size="3", as_="h3"), + namespace.text(PARAGRAPH, as_="p", size="2"), + namespace.link("Read more", href="#more", size="2"), + ] + + +def _hover_card(namespace: Any, props: Mapping[str, Any]) -> Any: + """Create a link with a hover card. + + Args: + namespace: ``rx`` or ``rx.ui``. + props: The props of the content. ``long`` asks for more than the + page has room for, ``themed`` for a theme of another accent and + radius around the card, and ``open_delay`` and ``close_delay`` + go to the root. + + Returns: + The link, with room around it for its card on any side. + """ + props = dict(props) + card = namespace.hover_card + long, themed = props.pop("long", False), props.pop("themed", False) + content = _card(namespace) + if long: + content = [*content, *(rx.el.p(PARAGRAPH) for _ in range(12))] + shown = card.root( + card.trigger(namespace.link("Hover me", href="#hover", width="80px")), + card.content( + *content, + # On the pixel grid wherever it is along its trigger: Radix + # rounds where it puts a card, and the browser does not. + width="240px", + **props, + ), + # The cells do not wait for the pointer to rest. + open_delay=0, + close_delay=0, + ) + if themed: + shown = namespace.theme(shown, accent_color="ruby", radius="full") + return rx.el.div(shown, style={"padding": "150px 0 0 260px"}) + + +def _show(page: Page, target: Locator, point: Point) -> None: + """Put the pointer on the trigger of a card, and wait for the card. + + Args: + page: The page. + target: The link. + point: The middle of the link. + """ + page.mouse.move(*point) + page.locator(SHOWN).first.wait_for() + + +def _hide(page: Page, target: Locator, point: Point) -> None: + """Take the pointer off, and wait until the card is gone. + + Args: + page: The page. + target: The link. + point: The middle of the link. + """ + leave(page) + page.locator(SHOWN).first.wait_for(state="detached") + + +MATRIX = Matrix( + component="hover_card", + render=_hover_card, + sweep={ + "size": SIZES, + "appearance": [DARK], + "state": [HOVER, FOCUS_VISIBLE], + }, + groups=[ + {"size": SIZES, "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"side": SIDES, "align": ALIGNS, "state": [OPEN]}, + {"side": SIDES, "side_offset": [0, 20], "state": [OPEN]}, + {"align": ["start", "end"], "align_offset": [12], "state": [OPEN]}, + {"themed": [True], "state": [OPEN], "appearance": [LIGHT, DARK]}, + {"long": [True], "state": [OPEN]}, + ], + stage=(620, 400), + crop="stage", + target="a", + parts={ + "card": CARD, + "heading": (f"{CARD[0]} h3", f"{CARD[1]} h3"), + "text": (f"{CARD[0]} p", f"{CARD[1]} p"), + "link": (f"{CARD[0]} a", f"{CARD[1]} a"), + }, + states={ + OPEN: State(enter=_show, leave=_hide, matches="[data-state='open']"), + }, + # Held to a threshold of zero, and to the long card: the card of rx.ui + # is no taller than the viewport and scrolls, and the browser draws the + # round corners of an element that scrolls on a layer of its own, 4 + # pixels of 248000 apart from the corners of the card of Radix, which + # does not scroll. Nothing else differs in any cell. + threshold=0, + tolerance=0.00002, +) + + +class HoverCardState(rx.State): + """What the hover cards of the contract are bound to.""" + + shown: rx.Field[bool] = rx.field(False) + seen: rx.Field[list[str]] = rx.field(default_factory=list) + + @rx.event + def set_shown(self, value: bool): + """Follow the bound hover card. + + Args: + value: Whether it is open. + """ + self.shown = value + + @rx.event + def see_open(self, value: bool): + """Keep whether a hover card opened or closed. + + Args: + value: Whether it is open. + """ + self.seen.append("open" if value else "closed") + + @rx.event + def close(self): + """Close the bound hover card from the backend.""" + self.shown = False + + +def _contract(namespace: Any) -> Any: + """Create what the contract page shows. + + Args: + namespace: ``rx`` or ``rx.ui``. + + Returns: + Links with a hover card: one that says when it opens and closes, + one that opens at once, one bound to state, one in a dialog and one + in a dark theme. + """ + card, dialog, link = namespace.hover_card, namespace.dialog, namespace.link + return namespace.flex( + card.root( + card.trigger(link("Profile", href="#profile", id="profile")), + card.content( + namespace.text("A profile", id="profile-text"), + link("Follow", href="#follow", id="follow"), + ), + on_open_change=HoverCardState.see_open, + ), + card.root( + card.trigger(link("Quick", href="#quick", id="quick")), + card.content(namespace.text("Opens at once")), + open_delay=0, + close_delay=0, + ), + card.root( + card.trigger(link("Bound", href="#bound", id="bound")), + card.content( + namespace.text("Follows its state"), + rx.el.button("Close", id="close", on_click=HoverCardState.close), + ), + open=HoverCardState.shown, + on_open_change=HoverCardState.set_shown, + ), + rx.el.button("Show", id="show", on_click=HoverCardState.set_shown(True)), + dialog.root( + dialog.trigger(namespace.button("Dialog", id="dialog-open")), + dialog.content( + dialog.title("With a hover card"), + card.root( + card.trigger(link("Inside", href="#inside", id="inside")), + card.content(namespace.text("In a dialog")), + open_delay=0, + ), + id="dialog-panel", + ), + ), + namespace.theme( + card.root( + card.trigger(link("Dark", href="#dark", id="dark")), + card.content(namespace.text("In the dark"), id="dark-card"), + open_delay=0, + ), + appearance="dark", + ), + rx.el.span(HoverCardState.seen.to_string(), id="seen"), + rx.el.span(HoverCardState.shown.to_string(), id="shown"), + spacing="4", + padding="60px 0 0 0", + wrap="wrap", + ) + + +CONTRACT = Contract(component="hover_card", render=_contract) + +# The text of each card that is shown. +SHOWING = ( + f"[...document.querySelectorAll('{SHOWN}')]" + ".map(card => card.querySelector('span, p').textContent)" +) + + +def _wait_for_shown(run: Run, *texts: str) -> None: + """Wait until the cards that are shown are the ones expected. + + Args: + run: The run, on a page. + *texts: The first text of each card that is to be shown. + """ + wait_for_value(run.page, SHOWING, list(texts)) + + +def _shown(run: Run) -> list[str]: + """Read which cards are shown. + + Args: + run: The run, on a page. + + Returns: + The first text of each. + """ + return run.page.evaluate(SHOWING) + + +@CONTRACT.step("its trigger is in the server render", on=SERVER) +def _server_render(run: Run) -> None: + link = run.server.element("profile") + assert (link.tag, link.text) == ("a", "Profile") + + +@CONTRACT.step( + "shows nothing and follows its link with JavaScript disabled", on=NO_JAVASCRIPT +) +def _without_javascript(run: Run) -> None: + page = run.page + page.locator("#profile").hover() + page.wait_for_timeout(400) + assert _shown(run) == [] + page.locator("#profile").click() + page.wait_for_url("**#profile") + + +@CONTRACT.step( + "opens once the pointer has rested on its trigger, and closes when it leaves" +) +def _hover(run: Run) -> None: + page = run.page + page.locator("#profile").hover() + page.wait_for_timeout(100) + assert _shown(run) == [] + _wait_for_shown(run, "A profile") + assert page.locator("#profile").get_attribute("data-state") == "open" + leave(page) + page.wait_for_timeout(50) + assert _shown(run) == ["A profile"] + _wait_for_shown(run) + wait_for_text(page, "seen", '["open","closed"]') + + +@CONTRACT.step("opens with the focus of the keyboard, and closes when it leaves") +def _focus(run: Run) -> None: + page = run.page + page.keyboard.press("Tab") + page.wait_for_timeout(100) + assert _shown(run) == [] + _wait_for_shown(run, "A profile") + page.locator("#quick").focus() + _wait_for_shown(run, "Opens at once") + + +@CONTRACT.step("Tab does not reach the links inside it") +def _not_tabbable(run: Run) -> None: + page = run.page + page.locator("#profile").focus() + _wait_for_shown(run, "A profile") + page.keyboard.press("Tab") + assert page.evaluate("document.activeElement.id") == "quick" + + +@CONTRACT.step( + "the pointer can go from the trigger to the card, and press a link in it" +) +def _hoverable(run: Run) -> None: + page = run.page + page.locator("#profile").hover() + _wait_for_shown(run, "A profile") + page.locator("#follow").hover() + page.wait_for_timeout(400) + assert _shown(run) == ["A profile"] + page.locator("#follow").click() + page.wait_for_url("**#follow") + + +@CONTRACT.step("Escape and a press outside close it") +def _dismiss(run: Run) -> None: + page = run.page + page.locator("#quick").hover() + _wait_for_shown(run, "Opens at once") + page.keyboard.press("Escape") + _wait_for_shown(run) + leave(page) + page.locator("#quick").hover() + _wait_for_shown(run, "Opens at once") + page.mouse.click(5, 5) + _wait_for_shown(run) + + +@CONTRACT.step( + "a hover card bound to state follows it, and closes from a backend handler" +) +def _bound(run: Run) -> None: + page = run.page + page.locator("#show").click() + _wait_for_shown(run, "Follows its state") + wait_for_text(page, "shown", "true") + page.locator("#close").click() + _wait_for_shown(run) + wait_for_text(page, "shown", "false") + page.locator("#bound").hover() + _wait_for_shown(run, "Follows its state") + wait_for_text(page, "shown", "true") + + +@CONTRACT.step( + "a hover card in a dialog shows over it, and Escape closes the card alone" +) +def _in_dialog(run: Run) -> None: + page = run.page + page.locator("#dialog-open").click() + page.locator("#dialog-panel").wait_for() + page.locator("#inside").hover() + _wait_for_shown(run, "In a dialog") + box = page.locator(SHOWN).first.bounding_box() + assert box is not None + assert page.evaluate( + f"([x, y]) => document.elementFromPoint(x, y).closest('{SHOWN}') !== null", + [box["x"] + box["width"] / 2, box["y"] + box["height"] / 2], + ) + page.keyboard.press("Escape") + _wait_for_shown(run) + page.locator("#dialog-panel").wait_for() + + +@CONTRACT.step("the dark appearance of a theme around a hover card reaches it") +def _themed_dark(run: Run) -> None: + page = run.page + page.locator("#dark").hover() + _wait_for_shown(run, "In the dark") + page.wait_for_timeout(300) + assert page.locator(SHOWN).first.evaluate( + "element => getComputedStyle(element).backgroundColor" + ) == ("rgb(25, 25, 25)") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/popover.py b/packages/reflex-components-ui/parity/ui_parity/components/popover.py index 8711bcaccf9..e984c3d5552 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/popover.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/popover.py @@ -10,7 +10,7 @@ import reflex as rx from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.look import Point, State -from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix +from ui_parity.matrix import DARK, FOCUS_VISIBLE, HOVER, LIGHT, Matrix, in_page from ui_parity.samples import PARAGRAPH, wait_for_text SIZES = ["1", "2", "3", "4"] @@ -117,6 +117,17 @@ def close_popup(page: Page, target: Locator, point: Point) -> None: stage=(560, 340), crop="stage", target="button", + parts={ + "content": (in_page(".rt-PopoverContent"), "[data-rx-popup]:popover-open"), + "title": ( + in_page(".rt-PopoverContent > span"), + "[data-rx-popup]:popover-open > span", + ), + "close": ( + in_page(".rt-PopoverContent button"), + "[data-rx-popup]:popover-open button", + ), + }, states={OPEN: OPENED}, # Not held to zero. At a threshold of zero 40 of the 45 cells are equal # pixel for pixel, and the others differ by one pixel of 190400 on the diff --git a/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py b/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py index 1c38723895c..311289e5de8 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py @@ -10,7 +10,7 @@ import reflex as rx from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.look import Point, State -from ui_parity.matrix import DARK, FOCUS_VISIBLE, LIGHT, Matrix +from ui_parity.matrix import DARK, FOCUS_VISIBLE, LIGHT, Matrix, in_page from ui_parity.samples import wait_for_text SIDES = ["top", "right", "bottom", "left"] @@ -107,6 +107,10 @@ def _hide(page: Page, target: Locator, point: Point) -> None: stage=(480, 200), crop="stage", target="button", + parts={ + "content": (in_page(".rt-TooltipContent"), "[role=tooltip]:popover-open"), + "text": (in_page(".rt-TooltipText"), "[role=tooltip]:popover-open > p"), + }, states={ OPEN: State( enter=_show, 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 89bde244a98..a3024b4df83 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/__init__.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/__init__.py @@ -19,9 +19,12 @@ "components.checkbox_cards": ["checkbox_cards"], "components.checkbox_group": ["checkbox_group"], "components.data_list": ["data_list"], + "components.context_menu": ["context_menu"], "components.dialog": ["dialog"], + "components.dropdown_menu": ["dropdown_menu", "menu"], "components.drawer": ["drawer"], "components.form": ["form"], + "components.hover_card": ["hover_card"], "components.icon_button": ["icon_button"], "components.inset": ["inset"], "components.popover": ["popover"], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py new file mode 100644 index 00000000000..6da7987e831 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py @@ -0,0 +1,594 @@ +"""What the menus share: a popover of items, its sub-menus, and its script.""" + +from __future__ import annotations + +from collections.abc import Iterator +from typing import Any, ClassVar + +from reflex_base.components.component import Component +from reflex_base.components.tags import CommonTag +from reflex_base.vars.base import LiteralVar, Var +from reflex_components_core.base.fragment import Fragment + +from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.components._group import descendants +from reflex_components_ui.components._popup import ( + PopupContent, + PopupPart, + PopupRoot, + PopupTrigger, +) +from reflex_components_ui.components._script import listen, script +from reflex_components_ui.components.select import ( + _CHECK, + _icon, # pyright: ignore[reportAttributeAccessIssue] +) +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.menu import ( + MENU_GROUP, + MENU_ITEM, + MENU_LABEL, + MENU_SEPARATOR, + MENU_SUB_CONTENT, +) + +# The chevron of an item that opens a sub-menu, as Radix Themes draws it. +_CHEVRON = ( + "M3.23826 0.201711C3.54108 -0.0809141 4.01567 -0.0645489 4.29829 0.238264" + "L7.79829 3.98826C8.06724 4.27642 8.06724 4.72359 7.79829 5.01174" + "L4.29829 8.76174C4.01567 9.06455 3.54108 9.08092 3.23826 8.79829" + "C2.93545 8.51567 2.91909 8.04108 3.20171 7.73826L6.22409 4.5" + "L3.20171 1.26174C2.91909 0.958928 2.93545 0.484337 3.23826 0.201711Z" +) + + +class MenuTrigger(PopupTrigger): + """What opens a menu: its child, a button the browser opens the menu from.""" + + _haspopup: ClassVar[str] = "menu" + + def _exclude_props(self) -> list[str]: + """Keep ``as_child`` off the element: the trigger is always its child. + + Returns: + The props read as styles, and ``as_child``. + """ + return [*super()._exclude_props(), "as_child"] + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the trigger, its script 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 script("menu", "menuTrigger") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, which opens its menu with a press, and with + Enter, Space and the down arrow on the first item. + """ + return listen( + super()._render(props), script("menu", "menuTrigger"), "onKeyDown" + ) + + +class MenuArea(PopupTrigger): + """What a context menu opens on: its child, where the pointer asks for it.""" + + def _join(self, root: Any, name: Any, on_open_change: Any) -> None: + """Take the id of the menu the element opens. + + Args: + root: The context menu. + name: The id of the menu. + on_open_change: What the menu does when it opens or closes. + """ + self._popup = {"data-rx-opens": name} + + def _exclude_props(self) -> list[str]: + """Keep ``disabled`` off the element, which says it otherwise. + + Returns: + The props read as styles, and ``disabled``. + """ + return [*super()._exclude_props(), "disabled"] + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the element, its script 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 script("menu", "menuContext") + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the element. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: its child, which opens its menu where the pointer or + the keyboard asks for one, unless it is disabled. + """ + tag = UIComponent._render(self, props).add_props(**{ + "data-state": "closed", + **self._popup, + }) + disabled = getattr(self, "disabled", None) + if disabled is not None: + disabled = LiteralVar.create(disabled) + tag = tag.add_props(**{ + "data-disabled": Var( + f'({disabled!s} ? "" : undefined)', + _var_data=disabled._get_all_var_data(), + ) + }) + return listen(tag, script("menu", "menuContext"), "onContextMenu") + + +class MenuItem(UIComponent): + """An item of a menu, which its menu gives its look.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = MENU_ITEM + + # What the item is to assistive technology. + _role: ClassVar[str] = "menuitem" + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create an item, with its shortcut after what it shows. + + Args: + *children: What the item shows. + **props: The properties of the item. + + Returns: + The item. + """ + shortcut = props.get("shortcut") + return super().create(*children, *cls._after(shortcut), **props) + + @classmethod + def _after(cls, shortcut: Any) -> list[Component]: + """Create what comes after what the item shows. + + Args: + shortcut: The shortcut the item names, or None. + + Returns: + The shortcut, when it has one. + """ + if shortcut is None: + return [] + return [Part.create(shortcut, part="shortcut", tag="div")] + + def _post_init(self, *args, **kwargs): + """Initialize the item, as one outside a menu. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # The look of the menu the item is in, which Radix hands down. + self._variant: Any = None + self._contrast: Any = None + super()._post_init(*args, **kwargs) + + def _join(self, menu: MenuContent) -> None: + """Take the look of the menu the item is in. + + Args: + menu: The content of the menu. + """ + self._variant, self._contrast = menu._look + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + def _exclude_props(self) -> list[str]: + """Keep the props that are no attributes off the element. + + Returns: + The props read as styles, and the ones the item renders itself. + """ + return [ + *super()._exclude_props(), + "shortcut", + "text_value", + "disabled", + "as_child", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the item. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: an item its menu moves the focus to, which says when it + is disabled and what it is found by. + """ + disabled = getattr(self, "disabled", None) + text = getattr(self, "text_value", None) + attributes: dict[str, Any] = {"role": self._role, "tabIndex": -1} + if disabled is not None: + attributes["aria-disabled"] = disabled + if text is not None: + attributes["data-text-value"] = text + tag = super()._render(props) + rendered = dict(tag.props) + # A choice is a press on the item, or Enter or Space on it. + if "onSelect" in rendered: + rendered["onClick"] = rendered.pop("onSelect") + return tag.set(props=rendered).add_props(**attributes) + + +class MenuCheckboxItem(MenuItem): + """An item of a menu that is checked or not.""" + + _role: ClassVar[str] = "menuitemcheckbox" + + @classmethod + def _after(cls, shortcut: Any) -> list[Component]: + """Create what comes after what the item shows. + + Args: + shortcut: The shortcut the item names, or None. + + Returns: + The check, shown while the item is checked, and the shortcut. + """ + return [ + Part.create( + _icon("check", _CHECK, fillRule="evenodd", clipRule="evenodd"), + part="indicator", + tag="span", + ), + *super()._after(shortcut), + ] + + def _exclude_props(self) -> list[str]: + """Keep the state of the item off the element, which says it otherwise. + + Returns: + The props read as styles, and the ones the item renders itself. + """ + return [ + *super()._exclude_props(), + "checked", + "default_checked", + "size", + "variant", + "high_contrast", + "required", + "name", + "value", + ] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the item. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: an item that says whether it is checked, and that its + script checks and unchecks. + """ + checked = getattr(self, "checked", None) + if checked is None: + checked = getattr(self, "default_checked", None) + if checked is None: + checked = LiteralVar.create(False) + checked = LiteralVar.create(checked) + tag = super()._render(props) + rendered = dict(tag.props) + change = rendered.pop("onChange", None) + tag = tag.set(props=rendered).add_props(**{ + "aria-checked": checked, + "data-state": Var(f'({checked!s} ? "checked" : "unchecked")'), + }) + return listen( + tag, + script("menu", "menuCheck"), + "onClick", + arguments=(change, getattr(self, "checked", None) is not None), + ) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the item, its script 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 script("menu", "menuCheck") + + +class MenuSubTrigger(PopupPart, MenuItem): + """An item that opens a sub-menu.""" + + @classmethod + def _after(cls, shortcut: Any) -> list[Component]: + """Create what comes after what the item shows. + + Args: + shortcut: Nothing: the item has none. + + Returns: + The chevron that says it opens a sub-menu. + """ + return [Part.create(_icon("chevron", _CHEVRON), part="shortcut", tag="div")] + + def _join(self, root: Any, name: Any = None, on_open_change: Any = None) -> None: + """Take the look of its menu, or the id of the sub-menu it opens. + + Args: + root: The content of the menu the item is in, or its sub-menu. + name: The id of the sub-menu. + on_open_change: What the sub-menu does when it opens or closes. + """ + if isinstance(root, MenuContent): + MenuItem._join(self, root) + return + self._popup = { + "data-rx-opens": name, + "aria-controls": name, + "aria-haspopup": "menu", + "aria-expanded": False, + "data-state": "closed", + } + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the item. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: an item that says which sub-menu it opens. + """ + return super()._render(props).add_props(**self._popup) + + +class MenuLabel(UIComponent): + """A label of a group of items, which cannot be chosen.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = MENU_LABEL + + def _exclude_props(self) -> list[str]: + """Keep the props that are no attributes off the element. + + Returns: + The props read as styles, and ``as_child``. + """ + return [*super()._exclude_props(), "as_child"] + + +class MenuGroup(UIComponent): + """A group of items.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = MENU_GROUP + + def _exclude_props(self) -> list[str]: + """Keep the props that are no attributes off the element. + + Returns: + The props read as styles, ``as_child`` and a value. + """ + return [*super()._exclude_props(), "as_child", "value"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the group. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a group, to assistive technology. + """ + return super()._render(props).add_props(role="group") + + +class MenuSeparator(UIComponent): + """A line between items.""" + + tag = "div" + + styles: ClassVar[ComponentStyles] = MENU_SEPARATOR + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the separator. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a separator, to assistive technology. + """ + return ( + super() + ._render(props) + .add_props(role="separator", **{"aria-orientation": "horizontal"}) + ) + + +class MenuContent(PopupContent): + """A native popover of items, whose script moves through them.""" + + _role: ClassVar[str | None] = "menu" + + _script: ClassVar[tuple[str, ...]] = ( + "menu", + "menuSync", + "menuEvent", + "onToggle", + "onKeyDown", + "onClick", + "onPointerMove", + "onPointerLeave", + "onBlur", + ) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a menu, its items inside the element that scrolls them. + + Args: + *children: The items. + **props: The properties of the menu. + + Returns: + The menu. + """ + return super().create( + Part.create( + Part.create(*children, part="viewport", tag="div"), + part="scroll", + tag="div", + ), + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the menu, and give its items its look. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # Whether the menu has checkbox items, which leave room for a check. + self._indented: Any = None + super()._post_init(*args, **kwargs) + # The look the items of the menu take: its variant and its contrast. + self._look: tuple[Any, Any] = ( + getattr(self, "variant", None), + getattr(self, "high_contrast", None), + ) + self._join_items() + + def _join_items(self) -> None: + """Give the items of the menu its look, those of its sub-menus too.""" + indented = False + for member in descendants(self, (MenuItem, MenuContent), MenuContent): # pyright: ignore[reportArgumentType] + if isinstance(member, MenuSubContent): + member._inherit(self) + elif isinstance(member, MenuItem): + member._join(self) + indented = indented or isinstance(member, MenuCheckboxItem) + self._indented = indented + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + def _exclude_props(self) -> list[str]: + """Keep the props that are no attributes off the element. + + Returns: + The props read as styles, and the ones the menu renders itself. + """ + return [*super()._exclude_props(), "loop", "as_child"] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the menu. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: a popover with the role of a menu, which says whether + its arrows go round. + """ + tag = super()._render(props) + loop = getattr(self, "loop", None) + return tag if loop is None else tag.add_props(**{"data-loop": loop}) + + +class MenuSub(PopupRoot): + """Contains all the parts of a submenu.""" + + _prefix: ClassVar[str] = "rx-menu-sub" + + +class MenuSubContent(MenuContent): + """The component that pops out when a submenu is open.""" + + styles: ClassVar[ComponentStyles] = MENU_SUB_CONTENT + + def _inherit(self, menu: MenuContent) -> None: + """Take the look of the menu the sub-menu opens from, as in Radix. + + Args: + menu: The content of that menu. + """ + self._look = menu._look + self.size = getattr(menu, "size", None) + self._join_items() + + +class MenuPoint(UIComponent): + """Where a context menu opens: an element of no size its script moves to the pointer.""" + + tag = "span" + + styles: ClassVar[ComponentStyles] = { + "base": { + "position": "fixed", + "width": "0", + "height": "0", + "pointer_events": "none", + } + } + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the point. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: nothing to assistive technology. + """ + return super()._render(props).add_props(**{"aria-hidden": True}) + + +def at_point(content: Component) -> Component: + """Put a menu after the point it opens at. + + Args: + content: The menu. + + Returns: + The point, then the menu. + """ + return Fragment.create(MenuPoint.create(), content) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py new file mode 100644 index 00000000000..39bc8fac426 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py @@ -0,0 +1,406 @@ +"""A context menu: a native ``popover`` of items, at the pointer that asks for it.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.components._menu import ( + MenuArea, + MenuCheckboxItem, + MenuContent, + MenuGroup, + MenuItem, + MenuLabel, + MenuSeparator, + MenuSub, + MenuSubContent, + MenuSubTrigger, + at_point, +) +from reflex_components_ui.components._popup import PopupRoot +from reflex_components_ui.components.radio_group import HighLevelRadioGroup +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.menu import CONTEXT_MENU_CONTENT +from reflex_components_ui.themes import LiteralAccentColor + +LiteralDirType = Literal["ltr", "rtl"] + +LiteralSizeType = Literal["1", "2"] + +LiteralVariantType = Literal["solid", "soft"] + +LiteralSideType = Literal["top", "right", "bottom", "left"] + +LiteralAlignType = Literal["start", "center", "end"] + +LiteralStickyType = Literal[ + "partial", + "always", +] + +LiteralCheckboxSize = Literal["1", "2", "3"] + +LiteralCheckboxVariant = Literal["classic", "surface", "soft"] + + +class ContextMenuRoot(PopupRoot): + """Menu representing a set of actions, displayed at the origin of a pointer right-click or long-press.""" + + _prefix: ClassVar[str] = "rx-context-menu" + + modal: Var[bool] = field( + doc="The modality of the context menu. When set to true, interaction with outside elements will be disabled and only menu content will be visible to screen readers." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + dir: Var[LiteralDirType] = field( + doc="The reading direction of submenus when applicable. If omitted, inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode." + ) + + +class ContextMenuTrigger(MenuArea): + """Wraps the element that will open the context menu.""" + + disabled: Var[bool] = field(doc="Whether the trigger is disabled") + + +class ContextMenuContent(MenuContent): + """The component that pops out when the context menu is open.""" + + styles: ClassVar[ComponentStyles] = CONTEXT_MENU_CONTENT + + size: Var[Responsive[LiteralSizeType]] = field( + doc='Dropdown Menu Content size "1" - "2"' + ) + + variant: Var[LiteralVariantType] = field( + doc='Variant of Dropdown Menu Content: "solid" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for Dropdown Menu Content" + ) + + high_contrast: Var[bool] = field( + doc="Renders the Dropdown Menu Content in higher contrast" + ) + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + loop: Var[bool] = field( + doc="When True, keyboard navigation will loop from last item to first, and vice versa. Defaults to False." + ) + + force_mount: Var[bool] = field( + doc="Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries." + ) + + side: Var[LiteralSideType] = field( + doc="The preferred side of the trigger to render against when open. Will be reversed when collisions occur and `avoid_collisions` is enabled." + ) + + side_offset: Var[float | int] = field( + doc="The distance in pixels from the trigger. Defaults to 0." + ) + + align: Var[LiteralAlignType] = field( + doc='The preferred alignment against the trigger. May change when collisions occur. Defaults to "center".' + ) + + align_offset: Var[float | int] = field( + doc='An offset in pixels from the "start" or "end" alignment options.' + ) + + avoid_collisions: Var[bool] = field( + doc="When true, overrides the side and align preferences to prevent collisions with boundary edges. Defaults to True." + ) + + collision_padding: Var[float | int | dict[str, float | int]] = field( + doc='The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { "top": 20, "left": 20 }. Defaults to 0.' + ) + + sticky: Var[LiteralStickyType] = field( + doc='The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".' + ) + + hide_when_detached: Var[bool] = field( + doc="Whether to hide the content when the trigger becomes fully occluded. Defaults to False." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when focus moves back after closing." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when a pointer down event happens outside the context menu." + ) + + on_focus_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when focus moves outside the context menu." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer interacts outside the context menu." + ) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create a context menu, after the point it opens at. + + Args: + *children: The items. + **props: The properties of the menu. + + Returns: + The point, then the menu. + """ + return at_point(super().create(*children, **props)) + + +class ContextMenuSub(MenuSub): + """Contains all the parts of a submenu.""" + + open: Var[bool] = field( + doc="The controlled open state of the submenu. Must be used in conjunction with `on_open_change`." + ) + + default_open: Var[bool] = field( + doc="The open state of the submenu when it is initially rendered. Use when you do not need to control its open state." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + +class ContextMenuSubTrigger(MenuSubTrigger): + """An item that opens a submenu.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + disabled: Var[bool] = field(doc="Whether the trigger is disabled") + + text_value: Var[str] = field( + doc="Optional text used for typeahead purposes. By default the typeahead behavior will use the .textContent of the item. Use this when the content is complex, or you have non-textual content inside." + ) + + +class ContextMenuSubContent(MenuSubContent): + """The component that pops out when a submenu is open.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + loop: Var[bool] = field( + doc="When True, keyboard navigation will loop from last item to first, and vice versa. Defaults to False." + ) + + force_mount: Var[bool] = field( + doc="Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries." + ) + + side_offset: Var[float | int] = field( + doc="The distance in pixels from the trigger. Defaults to 0." + ) + + align_offset: Var[float | int] = field( + doc='An offset in pixels from the "start" or "end" alignment options.' + ) + + avoid_collisions: Var[bool] = field( + doc="When true, overrides the side and align preferences to prevent collisions with boundary edges. Defaults to True." + ) + + collision_padding: Var[float | int | dict[str, float | int]] = field( + doc='The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { "top": 20, "left": 20 }. Defaults to 0.' + ) + + sticky: Var[LiteralStickyType] = field( + doc='The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".' + ) + + hide_when_detached: Var[bool] = field( + doc="Whether to hide the content when the trigger becomes fully occluded. Defaults to False." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when a pointer down event happens outside the context menu." + ) + + on_focus_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when focus moves outside the context menu." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when interacting outside the context menu." + ) + + +class ContextMenuItem(MenuItem): + """The component that contains the context menu items.""" + + color_scheme: Var[LiteralAccentColor] = field(doc="Override theme color for button") + + shortcut: Var[str] = field(doc="Shortcut to render a menu item as a link") + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the item." + ) + + text_value: Var[str] = field( + doc="Optional text used for typeahead purposes. By default the typeahead behavior will use the content of the item. Use this when the content is complex, or you have non-textual content inside." + ) + + on_select: EventHandler[no_args_event_spec] = field( + doc="Fired when the item is selected." + ) + + +class ContextMenuSeparator(MenuSeparator): + """Separates items in a context menu.""" + + +class ContextMenuCheckbox(MenuCheckboxItem): + """The component that contains the checkbox.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior." + ) + + size: Var[Responsive[LiteralCheckboxSize]] = field(doc='Checkbox size "1" - "3"') + + variant: Var[LiteralCheckboxVariant] = field( + doc='Variant of checkbox: "classic" | "surface" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for checkbox" + ) + + high_contrast: Var[bool] = field( + doc="Whether to render the checkbox with higher contrast color against background" + ) + + default_checked: Var[bool] = field(doc="Whether the checkbox is checked by default") + + checked: Var[bool] = field(doc="Whether the checkbox is checked") + + disabled: Var[bool] = field(doc="Whether the checkbox is disabled") + + required: Var[bool] = field(doc="Whether the checkbox is required") + + name: Var[str] = field( + doc="The name of the checkbox control when submitting the form." + ) + + value: Var[str] = field( + doc="The value of the checkbox control when submitting the form." + ) + + on_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the checkbox is checked or unchecked." + ) + + shortcut: Var[str] = field(doc="Text to render as shortcut.") + + +class ContextMenuLabel(MenuLabel): + """The component that contains the label.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + +class ContextMenuGroup(MenuGroup): + """The component that contains the group.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + +class ContextMenuRadioGroup(MenuGroup): + """The component that contains context menu radio items.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + value: Var[str] = field(doc="The value of the selected item in the group.") + + on_change: EventHandler[passthrough_event_spec(str)] = field( + doc="Fired when the value of the radio group changes." + ) + + +class ContextMenuRadioItem(HighLevelRadioGroup): + """The component that contains context menu radio items.""" + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for Dropdown Menu Content" + ) + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + value: Var[str] = field(doc="The unique value of the item.") + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the item." + ) + + on_select: EventHandler[no_args_event_spec] = field( + doc="Event handler called when the user selects an item (via mouse or keyboard). Calling event.preventDefault in this handler will prevent the context menu from closing when selecting that item." + ) + + text_value: Var[str] = field( + doc="Optional text used for typeahead purposes. By default the typeahead behavior will use the .textContent of the item. Use this when the content is complex, or you have non-textual content inside." + ) + + +class ContextMenu(ComponentNamespace): + """Menu representing a set of actions, displayed at the origin of a pointer right-click or long-press.""" + + root = staticmethod(ContextMenuRoot.create) + trigger = staticmethod(ContextMenuTrigger.create) + content = staticmethod(ContextMenuContent.create) + sub = staticmethod(ContextMenuSub.create) + sub_trigger = staticmethod(ContextMenuSubTrigger.create) + sub_content = staticmethod(ContextMenuSubContent.create) + item = staticmethod(ContextMenuItem.create) + separator = staticmethod(ContextMenuSeparator.create) + checkbox = staticmethod(ContextMenuCheckbox.create) + label = staticmethod(ContextMenuLabel.create) + group = staticmethod(ContextMenuGroup.create) + radio_group = staticmethod(ContextMenuRadioGroup.create) + radio = staticmethod(ContextMenuRadioItem.create) + + +context_menu = ContextMenu() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py new file mode 100644 index 00000000000..20ba7fee912 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py @@ -0,0 +1,293 @@ +"""A dropdown menu: a native ``popover`` of items, beside the button that opens it.""" + +from __future__ import annotations + +from typing import ClassVar, Literal + +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive + +from reflex_components_ui.components._menu import ( + MenuContent, + MenuItem, + MenuSeparator, + MenuSub, + MenuSubContent, + MenuSubTrigger, + MenuTrigger, +) +from reflex_components_ui.components._popup import PopupRoot +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.menu import DROPDOWN_MENU_CONTENT +from reflex_components_ui.themes import LiteralAccentColor + +LiteralDirType = Literal["ltr", "rtl"] + +LiteralSizeType = Literal["1", "2"] + +LiteralVariantType = Literal["solid", "soft"] + +LiteralSideType = Literal["top", "right", "bottom", "left"] + +LiteralAlignType = Literal["start", "center", "end"] + +LiteralStickyType = Literal[ + "partial", + "always", +] + + +class DropdownMenuRoot(PopupRoot): + """The Dropdown Menu Root Component.""" + + _prefix: ClassVar[str] = "rx-dropdown-menu" + + default_open: Var[bool] = field( + doc="The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state." + ) + + open: Var[bool] = field( + doc="The controlled open state of the dropdown menu. Must be used in conjunction with onOpenChange." + ) + + modal: Var[bool] = field( + doc="The modality of the dropdown menu. When set to true, interaction with outside elements will be disabled and only menu content will be visible to screen readers. Defaults to True." + ) + + dir: Var[LiteralDirType] = field( + doc="The reading direction of submenus when applicable. If omitted, inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + +class DropdownMenuTrigger(MenuTrigger): + """The button that toggles the dropdown menu.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + +class DropdownMenuContent(MenuContent): + """The Dropdown Menu Content component that pops out when the dropdown menu is open.""" + + styles: ClassVar[ComponentStyles] = DROPDOWN_MENU_CONTENT + + size: Var[Responsive[LiteralSizeType]] = field( + doc='Dropdown Menu Content size "1" - "2"' + ) + + variant: Var[LiteralVariantType] = field( + doc='Variant of Dropdown Menu Content: "solid" | "soft"' + ) + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for Dropdown Menu Content" + ) + + high_contrast: Var[bool] = field( + doc="Renders the Dropdown Menu Content in higher contrast" + ) + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + loop: Var[bool] = field( + doc="When True, keyboard navigation will loop from last item to first, and vice versa. Defaults to False." + ) + + force_mount: Var[bool] = field( + doc="Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries." + ) + + side: Var[LiteralSideType] = field( + doc='The preferred side of the trigger to render against when open. Will be reversed when collisions occur and `avoid_collisions` is enabled. Defaults to "bottom".' + ) + + side_offset: Var[float | int] = field( + doc="The distance in pixels from the trigger. Defaults to 0." + ) + + align: Var[LiteralAlignType] = field( + doc='The preferred alignment against the trigger. May change when collisions occur. Defaults to "center".' + ) + + align_offset: Var[float | int] = field( + doc='An offset in pixels from the "start" or "end" alignment options.' + ) + + avoid_collisions: Var[bool] = field( + doc="When true, overrides the side and align preferences to prevent collisions with boundary edges. Defaults to True." + ) + + collision_padding: Var[float | int | dict[str, float | int]] = field( + doc='The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { "top": 20, "left": 20 }. Defaults to 0.' + ) + + sticky: Var[LiteralStickyType] = field( + doc='The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".' + ) + + hide_when_detached: Var[bool] = field( + doc="Whether to hide the content when the trigger becomes fully occluded. Defaults to False." + ) + + on_close_auto_focus: EventHandler[no_args_event_spec] = field( + doc="Fired when the dialog is closed." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the dialog." + ) + + on_focus_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when focus moves outside the dialog." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer interacts outside the dialog." + ) + + +class DropdownMenuSubTrigger(MenuSubTrigger): + """An item that opens a submenu.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the item." + ) + + text_value: Var[str] = field( + doc="Optional text used for typeahead purposes. By default the typeahead behavior will use the .textContent of the item. Use this when the content is complex, or you have non-textual content inside." + ) + + +class DropdownMenuSub(MenuSub): + """Contains all the parts of a submenu.""" + + open: Var[bool] = field( + doc="The controlled open state of the submenu. Must be used in conjunction with `on_open_change`." + ) + + default_open: Var[bool] = field( + doc="The open state of the submenu when it is initially rendered. Use when you do not need to control its open state." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + +class DropdownMenuSubContent(MenuSubContent): + """The component that pops out when a submenu is open. Must be rendered inside DropdownMenuSub.""" + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + loop: Var[bool] = field( + doc="When True, keyboard navigation will loop from last item to first, and vice versa. Defaults to False." + ) + + force_mount: Var[bool] = field( + doc="Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries." + ) + + side_offset: Var[float | int] = field( + doc="The distance in pixels from the trigger. Defaults to 0." + ) + + align_offset: Var[float | int] = field( + doc='An offset in pixels from the "start" or "end" alignment options.' + ) + + avoid_collisions: Var[bool] = field( + doc="When true, overrides the side and align preferences to prevent collisions with boundary edges. Defaults to True." + ) + + collision_padding: Var[float | int | dict[str, float | int]] = field( + doc='The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { "top": 20, "left": 20 }. Defaults to 0.' + ) + + sticky: Var[LiteralStickyType] = field( + doc='The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".' + ) + + hide_when_detached: Var[bool] = field( + doc="Whether to hide the content when the trigger becomes fully occluded. Defaults to False." + ) + + on_escape_key_down: EventHandler[no_args_event_spec] = field( + doc="Fired when the escape key is pressed." + ) + + on_pointer_down_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer is down outside the dialog." + ) + + on_focus_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when focus moves outside the dialog." + ) + + on_interact_outside: EventHandler[no_args_event_spec] = field( + doc="Fired when the pointer interacts outside the dialog." + ) + + +class DropdownMenuItem(MenuItem): + """The Dropdown Menu Item Component.""" + + color_scheme: Var[LiteralAccentColor] = field( + doc="Override theme color for Dropdown Menu Item" + ) + + shortcut: Var[str] = field(doc="Shortcut to render a menu item as a link") + + as_child: Var[bool] = field( + doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." + ) + + disabled: Var[bool] = field( + doc="When true, prevents the user from interacting with the item." + ) + + text_value: Var[str] = field( + doc="Optional text used for typeahead purposes. By default the typeahead behavior will use the .textContent of the item. Use this when the content is complex, or you have non-textual content inside." + ) + + on_select: EventHandler[no_args_event_spec] = field( + doc="Fired when the item is selected." + ) + + +class DropdownMenuSeparator(MenuSeparator): + """Dropdown Menu Separator Component. Used to visually separate items in the dropdown menu.""" + + +class DropdownMenu(ComponentNamespace): + """DropdownMenu components namespace.""" + + root = staticmethod(DropdownMenuRoot.create) + trigger = staticmethod(DropdownMenuTrigger.create) + content = staticmethod(DropdownMenuContent.create) + sub_trigger = staticmethod(DropdownMenuSubTrigger.create) + sub = staticmethod(DropdownMenuSub.create) + sub_content = staticmethod(DropdownMenuSubContent.create) + item = staticmethod(DropdownMenuItem.create) + separator = staticmethod(DropdownMenuSeparator.create) + + +menu = dropdown_menu = DropdownMenu() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py b/packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py new file mode 100644 index 00000000000..76ef20f8e71 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py @@ -0,0 +1,118 @@ +"""A hover card: a native ``popover`` that opens under the pointer and with the focus.""" + +from __future__ import annotations + +from typing import Any, ClassVar, Literal + +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.event import EventHandler, passthrough_event_spec +from reflex_base.vars.base import Var +from reflex_components_core.core.breakpoints import Responsive +from reflex_components_core.el import elements + +from reflex_components_ui.components._popup import HoverContent, HoverTrigger, PopupRoot +from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.styles.hover_card import HOVER_CARD_CONTENT + +# How long the pointer rests on the trigger before the card opens, and how +# long the card waits for the pointer to come back before it closes, in +# milliseconds, as in Radix Themes. +_OPEN_DELAY = 200 +_CLOSE_DELAY = 150 + + +class HoverCardRoot(PopupRoot): + """For sighted users to preview content available behind a link.""" + + _prefix: ClassVar[str] = "rx-hover-card" + + default_open: Var[bool] = field( + doc="The open state of the hover card when it is initially rendered. Use when you do not need to control its open state." + ) + + open: Var[bool] = field( + doc="The controlled open state of the hover card. Must be used in conjunction with onOpenChange." + ) + + open_delay: Var[int] = field( + doc="The duration from when the mouse enters the trigger until the hover card opens." + ) + + close_delay: Var[int] = field( + doc="The duration from when the mouse leaves the trigger until the hover card closes." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + +class HoverCardTrigger(HoverTrigger): + """Wraps the link that will open the hover card.""" + + +class HoverCardContent(HoverContent, elements.Div): + """Contains the content of the open hover card.""" + + styles: ClassVar[ComponentStyles] = HOVER_CARD_CONTENT + + side: Var[Responsive[Literal["top", "right", "bottom", "left"]]] = field( + doc="The preferred side of the trigger to render against when open. Will be reversed when collisions occur and avoidCollisions is enabled." + ) + + side_offset: Var[int] = field(doc="The distance in pixels from the trigger.") + + align: Var[Literal["start", "center", "end"]] = field( + doc="The preferred alignment against the trigger. May change when collisions occur." + ) + + align_offset: Var[int] = field( + doc='An offset in pixels from the "start" or "end" alignment options.' + ) + + avoid_collisions: Var[bool] = field( + doc="Whether or not the hover card should avoid collisions with its trigger." + ) + + collision_padding: Var[float | int | dict[str, float | int]] = field( + doc="The distance in pixels from the boundary edges where collision detection should occur. Accepts a number (same for all sides), or a partial padding object, for example: { top: 20, left: 20 }." + ) + + sticky: Var[Literal["partial", "always"]] = field( + doc='The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless' + ) + + hide_when_detached: Var[bool] = field( + doc="Whether to hide the content when the trigger becomes fully occluded." + ) + + size: Var[Responsive[Literal["1", "2", "3"]]] = field( + doc='Hovercard size "1" - "3"' + ) + + def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: + """Take the name of the card, whether it is open, and its delays. + + Args: + root: The hover card the content is in. + name: The id of the card. + on_open_change: What the card does when it opens or closes. + """ + super()._join(root, name, on_open_change) # pyright: ignore[reportAttributeAccessIssue] + for attribute, prop, default in ( + ("data-open-delay", "open_delay", _OPEN_DELAY), + ("data-close-delay", "close_delay", _CLOSE_DELAY), + ): + delay = getattr(root, prop, None) + self._popup[attribute] = default if delay is None else delay # pyright: ignore[reportAttributeAccessIssue] + + +class HoverCard(ComponentNamespace): + """For sighted users to preview content available behind a link.""" + + root = __call__ = staticmethod(HoverCardRoot.create) + trigger = staticmethod(HoverCardTrigger.create) + content = staticmethod(HoverCardContent.create) + + +hover_card = HoverCard() diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py index 764a47a72c9..f6cad082df5 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py @@ -48,7 +48,7 @@ class TooltipTrigger(HoverTrigger): """What a tooltip describes: the child of the tooltip.""" # A press on what a tooltip is on closes the tooltip. - _heard: ClassVar[tuple[str, ...]] = (*HoverTrigger._heard, "onPointerDown") + _heard: ClassVar[tuple[str, ...]] = (*HoverTrigger._heard, "onPointerDown") # pyright: ignore[reportAttributeAccessIssue] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the trigger. @@ -63,7 +63,7 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: return ( super() ._render(props) - .add_props(**{"aria-describedby": self._popup.get("data-rx-hover")}) + .add_props(**{"aria-describedby": self._popup.get("data-rx-hover")}) # pyright: ignore[reportAttributeAccessIssue] ) @@ -174,8 +174,8 @@ def create(cls, *children, **props) -> Component: ) trigger = TooltipTrigger.create(*children) name = popup.id if popup.id is not None else f"rx-tooltip-{next(_popup._ids)}" - popup._join(None, name, None) - trigger._join(None, name, None) + popup._join(None, name, None) # pyright: ignore[reportAttributeAccessIssue] + trigger._join(None, name, None) # pyright: ignore[reportAttributeAccessIssue] return Fragment.create(trigger, popup) def _join(self, root: Any, name: Any, on_open_change: Any) -> None: @@ -187,14 +187,14 @@ def _join(self, root: Any, name: Any, on_open_change: Any) -> None: on_open_change: Nothing: the tooltip has the event itself. """ if self.id is None: - self._popup["id"] = name + self._popup["id"] = name # pyright: ignore[reportAttributeAccessIssue] self._open = self.open if self.default_open is not None: - self._popup["data-default-open"] = self.default_open + self._popup["data-default-open"] = self.default_open # pyright: ignore[reportAttributeAccessIssue] delay = self.delay_duration - self._popup["data-open-delay"] = _OPEN_DELAY if delay is None else delay + self._popup["data-open-delay"] = _OPEN_DELAY if delay is None else delay # pyright: ignore[reportAttributeAccessIssue] still = self.disable_hoverable_content - self._popup["data-close-delay"] = ( + self._popup["data-close-delay"] = ( # pyright: ignore[reportAttributeAccessIssue] _CLOSE_DELAY if still is None else choose(literal(still), 0, _CLOSE_DELAY) ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py index 784adf76e6c..90f2590af00 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py @@ -36,6 +36,8 @@ "max_width": "none", "max_height": "none", "outline_style": "none", + # Not the selection the browser gives the text of a modal dialog. + "user_select": "auto", "::backdrop": {"background_color": "transparent"}, "transition_property": "display, overlay", "transition_duration": {"default": "0s", MOTION: f"var({DURATION})"}, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py new file mode 100644 index 00000000000..3146984b37b --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py @@ -0,0 +1,53 @@ +"""The look of a hover card: a panel beside what the pointer rests on.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, unchecked +from reflex_components_ui.styles.popup import POPUP, placements + +_PADDING = "--hover-card-content-padding" + + +def _size(padding: str, radius: str) -> dict[str, Any]: + """Make the styles of a hover card of one size. + + Args: + padding: The room around what the card holds. + radius: The radius of its corners. + + Returns: + The styles. + """ + return {_PADDING: padding, "border_radius": radius} + + +HOVER_CARD_CONTENT: ComponentStyles = { + "base": unchecked({ + **POPUP, + # The text of the page around it, not the one of a native popover. + "color": "inherit", + "background_color": tokens.color.panel_solid, + "box_shadow": tokens.shadow[4], + "max_width": "min(480px, calc(100vw - 20px))", + "outline_style": "none", + "overflow": "auto", + "--inset-padding-top": f"var({_PADDING})", + "--inset-padding-right": f"var({_PADDING})", + "--inset-padding-bottom": f"var({_PADDING})", + "--inset-padding-left": f"var({_PADDING})", + "padding": f"var({_PADDING})", + "box_sizing": "border-box", + }), + "variants": { + "size": { + "1": unchecked(_size(tokens.space[3], tokens.radius[4])), + "2": unchecked(_size(tokens.space[4], tokens.radius[4])), + "3": unchecked(_size(tokens.space[5], tokens.radius[5])), + }, + }, + "defaults": {"size": "2", "side": "bottom", "align": "start"}, + "compound": placements("8px"), +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py new file mode 100644 index 00000000000..7da202b4582 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py @@ -0,0 +1,365 @@ +"""The look of a menu: a panel of items beside what opens it, and its sub-menus.""" + +from __future__ import annotations + +from typing import Any + +from reflex_components_ui import tokens +from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked +from reflex_components_ui.styles.popup import POPUP, placement, placements +from reflex_components_ui.tokens import Step9 + +# What the content of a menu hands its items, as Radix Themes names them. +_PADDING = "--base-menu-content-padding" +_INDENT = "--base-menu-item-padding-left" +_END = "--base-menu-item-padding-right" +_HEIGHT = "--base-menu-item-height" +# And what Radix Themes sets on its items by a selector on the content. +_FONT_SIZE = "--rx-menu-font-size" +_LINE_HEIGHT = "--rx-menu-line-height" +_LETTER_SPACING = "--rx-menu-letter-spacing" +_ITEM_RADIUS = "--rx-menu-item-radius" +_ICON = "--rx-menu-icon-size" +# What an item hands what is inside it: the color of its shortcut and of +# the chevron of a sub-menu, and whether its check is shown. +_SHORTCUT = "--rx-menu-shortcut-color" +_CHEVRON = "--rx-menu-chevron-color" +_CHECK = "--rx-menu-check" + +# An item the focus is on is the one Radix highlights: the pointer moves the +# focus to the item under it. +HIGHLIGHTED = ":focus" +# A sub-menu trigger whose sub-menu is open, and that is not highlighted. +_OPEN = ":not(:focus)[data-state='open']" +_DISABLED = "[aria-disabled='true']" +# A label right after an item. +_AFTER_ITEM = ":is(:is([role=menuitem], [role=menuitemcheckbox]) + *)" + + +def _size( + padding: str, + end: str, + height: str, + radius: str, + step: Step9, + item_radius: str, + icon: str, +) -> dict[str, Any]: + """Make the styles of a menu of one size. + + Args: + padding: The room around its items. + end: The room after the text of an item. + height: The height of an item. + radius: The radius of the corners of the menu. + step: The step of the type scale of an item and a label. + item_radius: The radius of the corners of an item. + icon: The side of a check and of a chevron, before scaling. + + Returns: + The styles. + """ + return { + _PADDING: padding, + _END: end, + _HEIGHT: height, + "border_radius": radius, + _FONT_SIZE: tokens.font_size[step], + _LINE_HEIGHT: tokens.line_height[step], + _LETTER_SPACING: tokens.letter_spacing[step], + _ITEM_RADIUS: item_radius, + _ICON: f"calc({icon} * {tokens.scaling})", + } + + +_SIZES = { + "1": unchecked( + _size( + tokens.space[1], + tokens.space[2], + tokens.space[5], + tokens.radius[3], + 1, + tokens.radius[1], + "8px", + ) + ), + "2": unchecked( + _size( + tokens.space[2], + tokens.space[3], + tokens.space[6], + tokens.radius[4], + 2, + tokens.radius[2], + "10px", + ) + ), +} + +# The room before the text of an item: more in a menu with checkbox items, +# for their check. +_INDENTS: list[CompoundStyle] = [ + { + "props": {"size": size, "_indented": indented}, + "style": unchecked({_INDENT: room}), + } + for size, indented, room in ( + ("1", "false", tokens.space[2]), + ("1", "true", f"calc({tokens.space[5]} / 1.2)"), + ("2", "false", tokens.space[3]), + ("2", "true", tokens.space[5]), + ) +] + +_CONTENT_BASE: dict[str, Any] = { + **POPUP, + "color": tokens.gray[12], + "font_family": tokens.default.font_family, + "font_weight": tokens.font_weight.regular, + "font_style": "normal", + "text_align": "start", + "display": {"default": "none", ":popover-open": "flex"}, + "flex_direction": "column", + "box_sizing": "border-box", + "overflow": "hidden", + "background_color": tokens.color.panel_solid, + "box_shadow": tokens.shadow[5], + "outline_style": "none", +} + +# As far up as the padding of an item, for its text to be at the pointer or +# at the item it opens from. +_RAISED = { + size: unchecked({**style, "--rx-popup-shift": f"-{4 * int(size)}px"}) + for size, style in _SIZES.items() +} + + +def _content( + base: dict[str, Any], + sizes: dict[str, Any], + defaults: dict[str, str], + compound: list[CompoundStyle], +) -> ComponentStyles: + """Make the look of the content of a menu, which scrolls its items. + + Args: + base: Its styles, its placement included where it has no choice. + sizes: The styles of each size. + defaults: The values its props select styles by when left out. + compound: Its compound styles: the room before the items, and the + placement by side and alignment. + + Returns: + The look. + """ + return { + "base": unchecked(base), + "variants": { + "size": sizes, + "_indented": {"true": {}, "false": {}}, + # What the items of the menu read: they are given it. + "variant": {"solid": {}, "soft": {}}, + "high_contrast": {"true": {}, "false": {}}, + }, + "defaults": {"_indented": "false", "size": "2", **defaults}, + "compound": [*_INDENTS, *compound], + "parts": { + # What scrolls the items, inside a menu no taller than the viewport. + "scroll": { + "base": unchecked({ + "flex_grow": "1", + "flex_shrink": "1", + "flex_basis": "0%", + "min_height": "0", + "overflow": "auto", + "scrollbar_width": "thin", + "scrollbar_color": f"{tokens.gray.a[8]} transparent", + }), + }, + # The items, as tall as they are. + "viewport": { + "base": unchecked({ + "flex_grow": "1", + "flex_shrink": "1", + "flex_basis": "0%", + "min_width": "0", + "min_height": "0", + "display": "flex", + "flex_direction": "column", + "overflow": "auto", + "padding": f"var({_PADDING})", + "box_sizing": "border-box", + }), + }, + }, + } + + +DROPDOWN_MENU_CONTENT = _content( + _CONTENT_BASE, _SIZES, {"side": "bottom", "align": "start"}, placements("4px") +) + +CONTEXT_MENU_CONTENT = _content( + _CONTENT_BASE, _RAISED, {"side": "right", "align": "start"}, placements("2px") +) + +MENU_SUB_CONTENT = _content( + {**_CONTENT_BASE, **placement("right", "start", "1px")}, _RAISED, {}, [] +) + +MENU_ITEM: ComponentStyles = { + "base": unchecked({ + "display": "flex", + "align_items": "center", + "gap": tokens.space[2], + "height": f"var({_HEIGHT})", + "padding_left": f"var({_INDENT})", + "padding_right": f"var({_END})", + "box_sizing": "border-box", + "position": "relative", + "outline_style": "none", + "outline_width": "medium", + "outline_color": "currentColor", + "scroll_margin_top": f"var({_PADDING})", + "scroll_margin_bottom": f"var({_PADDING})", + # Fixes sticky text highlighting after a choice in Firefox. + "user_select": "none", + "cursor": {"default": tokens.cursor.menu_item, _DISABLED: "default"}, + # The pointer goes through a disabled item, which it cannot choose. + "pointer_events": {"default": "auto", _DISABLED: "none"}, + "font_size": f"var({_FONT_SIZE})", + "line_height": f"var({_LINE_HEIGHT})", + "letter_spacing": f"var({_LETTER_SPACING})", + "border_radius": f"var({_ITEM_RADIUS})", + "color": {_DISABLED: tokens.gray.a[8]}, + _SHORTCUT: { + "default": tokens.gray.a[11], + HIGHLIGHTED: "currentColor", + _DISABLED: "currentColor", + "[data-state='open']": "currentColor", + }, + _CHEVRON: tokens.gray[12], + _CHECK: {"default": "none", "[aria-checked='true']": "inline-flex"}, + }), + "variants": { + "color_scheme": { + "true": unchecked({ + "color": {"default": tokens.accent.a[11], _DISABLED: tokens.gray.a[8]} + }) + }, + "_variant": { + "solid": unchecked({ + "background_color": { + HIGHLIGHTED: tokens.accent[9], + _OPEN: tokens.gray.a[3], + }, + "color": {HIGHLIGHTED: tokens.accent.contrast}, + _CHEVRON: { + "default": tokens.gray[12], + HIGHLIGHTED: tokens.accent.contrast, + }, + }), + "soft": unchecked({ + "background_color": { + HIGHLIGHTED: tokens.accent.a[4], + _OPEN: tokens.accent.a[3], + }, + }), + }, + "_contrast": {"true": {}, "false": {}}, + }, + "defaults": {"_variant": "solid", "_contrast": "false"}, + "compound": [ + { + "props": {"_variant": "solid", "_contrast": "true"}, + "style": unchecked({ + "background_color": { + HIGHLIGHTED: tokens.accent[12], + _OPEN: tokens.gray.a[3], + }, + "color": {HIGHLIGHTED: tokens.accent[1]}, + _CHEVRON: {"default": tokens.gray[12], HIGHLIGHTED: tokens.accent[1]}, + }), + }, + { + # An item of its own color keeps the highlight of a solid menu. + "props": {"_variant": "solid", "_contrast": "true", "color_scheme": "true"}, + "style": unchecked({ + "background_color": { + HIGHLIGHTED: tokens.accent[9], + _OPEN: tokens.gray.a[3], + }, + "color": {HIGHLIGHTED: tokens.accent.contrast}, + _CHEVRON: { + "default": tokens.gray[12], + HIGHLIGHTED: tokens.accent.contrast, + }, + }), + }, + ], + "parts": { + "shortcut": { + "base": unchecked({ + "display": "flex", + "align_items": "center", + "margin_left": "auto", + "padding_left": tokens.space[4], + "color": f"var({_SHORTCUT})", + }), + }, + "chevron": { + "base": unchecked({ + "color": f"var({_CHEVRON})", + "margin_right": f"calc(-2px * {tokens.scaling})", + "width": f"var({_ICON})", + "height": f"var({_ICON})", + }), + }, + "indicator": { + "base": unchecked({ + "position": "absolute", + "left": "0", + "width": f"var({_INDENT})", + "display": f"var({_CHECK})", + "align_items": "center", + "justify_content": "center", + }), + }, + "check": { + "base": unchecked({"width": f"var({_ICON})", "height": f"var({_ICON})"}), + }, + }, +} + +MENU_LABEL: ComponentStyles = { + "base": unchecked({ + "display": "flex", + "align_items": "center", + "height": f"var({_HEIGHT})", + "padding_left": f"var({_INDENT})", + "padding_right": f"var({_END})", + "box_sizing": "border-box", + "color": tokens.gray.a[10], + "user_select": "none", + "cursor": "default", + "font_size": f"var({_FONT_SIZE})", + "line_height": f"var({_LINE_HEIGHT})", + "letter_spacing": f"var({_LETTER_SPACING})", + "margin_top": {_AFTER_ITEM: tokens.space[2]}, + }), +} + +MENU_SEPARATOR: ComponentStyles = { + "base": unchecked({ + "height": "1px", + "margin_top": tokens.space[2], + "margin_bottom": tokens.space[2], + "margin_left": f"var({_INDENT})", + "margin_right": f"var({_END})", + "background_color": tokens.gray.a[6], + }), +} + +MENU_GROUP: ComponentStyles = {"base": {}} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py index 97342f76282..857b486c93f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py @@ -35,6 +35,7 @@ def _size(padding: str, radius: str) -> dict[str, Any]: "min_width": "anchor-size(width)", "max_width": "min(480px, calc(100vw - 20px))", "outline_style": "none", + "outline_width": "0", "overflow": "auto", "--inset-padding-top": f"var({_PADDING})", "--inset-padding-right": f"var({_PADDING})", diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py index d94c1980f44..8a3cff4bf8f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py @@ -60,7 +60,7 @@ "margin": "0", "padding": "0", "border_width": "0", - "border_style": "none", + "border_style": "solid", "box_sizing": "border-box", "width": "max-content", "height": "auto", @@ -98,10 +98,12 @@ def placement(side: str, align: str, default_offset: str = "0px") -> dict[str, A vertical = side in ("top", "bottom") offset = f"var({OFFSET}, {default_offset})" shift = f"var({SHIFT}, 0px)" - # The room between the popup and each side: the offset on the two - # sides that face the anchor or lie opposite it, and the shift on the - # side the popup is aligned to. A margin and the one opposite it move - # the popup together, by what its script found it off whole pixels. + # The room between the popup and each side: the offset on the side that + # faces the anchor, the room Radix keeps from the edge of the viewport on + # the side opposite it, where the popup turns over only when it would + # come closer, and the shift on the side the popup is aligned to. A + # margin and the one opposite it move the popup together, by what its + # script found it off whole pixels. across = { "start": (f"calc({shift} + {_SNAP_X})", f"calc(0px - {_SNAP_X})"), "center": (_SNAP_X, f"calc(0px - {_SNAP_X})"), @@ -112,12 +114,13 @@ def placement(side: str, align: str, default_offset: str = "0px") -> dict[str, A "center": (_SNAP_Y, f"calc(0px - {_SNAP_Y})"), "end": (_SNAP_Y, f"calc({shift} - {_SNAP_Y})"), } + before, after = (offset, _EDGE) if side in ("bottom", "right") else (_EDGE, offset) if vertical: left, right = across[align] - top, bottom = f"calc({offset} + {_SNAP_Y})", f"calc({offset} - {_SNAP_Y})" + top, bottom = f"calc({before} + {_SNAP_Y})", f"calc({after} - {_SNAP_Y})" else: top, bottom = down[align] - left, right = f"calc({offset} + {_SNAP_X})", f"calc({offset} - {_SNAP_X})" + left, right = f"calc({before} + {_SNAP_X})", f"calc({after} - {_SNAP_X})" start, end = ("left", "right") if vertical else ("top", "bottom") style: dict[str, Any] = { "position_area": _AREAS[side, align], diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py index 3c63d594437..a5757dafa89 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py @@ -18,6 +18,8 @@ TOOLTIP: ComponentStyles = { "base": unchecked({ **POPUP, + # The text of the page around it, not the one of a native popover. + "color": "inherit", "overflow": "visible", "box_sizing": "border-box", "padding": f"{tokens.space[1]} {tokens.space[2]}", diff --git a/pyi_hashes.json b/pyi_hashes.json index 93008ae26bc..240448e1cd4 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,11 +118,12 @@ "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": "3baaa214d298bb98db3eae02bb2911e4", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "6eb205093043e7acf44767d415a25f0b", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "0b8ff1aea31ac87df9c384e9dbdf5246", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "0d7b27ab1cb51ac891a31ed97f2f5567", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "61cffb40e8f047c944b54e51ac36cbc7", + "packages/reflex-components-ui/src/reflex_components_ui/components/_menu.pyi": "c243405a64e5dd76eef6bef0492ac75a", "packages/reflex-components-ui/src/reflex_components_ui/components/_popup.pyi": "80f094441cee591fff2e06d6e315dcc0", "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "4abb8482e413aa9ee3d941ef12878c1a", @@ -135,10 +136,13 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.pyi": "950ecf12cfe68270c03f57dee11ce1c4", "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.pyi": "55446eddd45d81355eea0ada7370a6c3", "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.pyi": "63dc6c987c53e017e217e60f4686c4b9", + "packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.pyi": "79193f172cbb6feb749a296f82af9814", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "28f5633fbda932ee598108e9d5a52e58", "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "cdaeaac954b4ff1100878d46b5649143", + "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "866b446d2bc8381230a6c0683c3a4209", "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", + "packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.pyi": "866327d09399a8a3f632f93a36014ebb", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", "packages/reflex-components-ui/src/reflex_components_ui/components/popover.pyi": "f50b0a5a30a0331f2a8e5dc28d8763cf", @@ -157,6 +161,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/tabs.pyi": "37bd6cf7d23252f304647967c44f7693", "packages/reflex-components-ui/src/reflex_components_ui/components/text_area.pyi": "85e3d7d2cf756b3a67683d9724b1a68b", "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "9fe922c888339fa55560e2cb51697ead", + "packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.pyi": "e40ab12c01c4c79dd540aa7872596cd3", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", "packages/reflex-components-ui/src/reflex_components_ui/layout/center.pyi": "a38424cf14313b5358c9ad198a7880f9", "packages/reflex-components-ui/src/reflex_components_ui/layout/container.pyi": "ecfbd513a1a12bbfc11a6d30e91987c6", diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 98d42d2a50a..88f193b2ad5 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -907,6 +907,34 @@ def overlays(): ), ), ), + # A menu for each row of a list, each with a sub-menu: each trigger + # opens its own menu, and each item its own sub-menu. + rx.foreach( + ["ink", "jet"], + lambda name: rx.ui.dropdown_menu.root( + rx.ui.dropdown_menu.trigger(rx.ui.button("Menu ", name)), + rx.ui.dropdown_menu.content( + rx.ui.dropdown_menu.item("Open ", name), + rx.ui.dropdown_menu.sub( + rx.ui.dropdown_menu.sub_trigger("Share ", name), + rx.ui.dropdown_menu.sub_content( + rx.ui.dropdown_menu.item("Mail ", name) + ), + ), + ), + ), + ), + rx.ui.context_menu.root( + rx.ui.context_menu.trigger(rx.el.div("Canvas", id="canvas")), + rx.ui.context_menu.content( + rx.ui.context_menu.checkbox("Snap", default_checked=True) + ), + ), + rx.ui.hover_card.root( + rx.ui.hover_card.trigger(rx.ui.link("Author", href="#author")), + rx.ui.hover_card.content("Writes things"), + open_delay=0, + ), rx.el.span(rx.cond(rx.State.is_hydrated, "ready", "loading"), id="ready"), ) @@ -1973,3 +2001,30 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): account.get_by_text("Seats").click() expect(account.get_by_text("Five.")).to_be_visible() expect(account.locator("details[open]")).to_have_count(1) + + # The menus of a list share the ids they are rendered with: the script of + # a menu tells them apart, and places each sub-menu beside its item. + page.get_by_role("button", name="Menu jet").click() + menu = page.get_by_role("menu") + expect(menu).to_have_count(1) + expect(menu.get_by_role("menuitem").first).to_have_text("Open jet") + page.get_by_role("menuitem", name="Share jet").hover() + expect(page.get_by_role("menu")).to_have_count(2) + expect(page.get_by_role("menuitem", name="Mail jet")).to_be_visible() + page.keyboard.press("Escape") + page.keyboard.press("Escape") + expect(page.get_by_role("menu")).to_have_count(0) + + # A context menu opens at the pointer, and its checkbox item is checked. + page.locator("#canvas").click(button="right") + snap = page.get_by_role("menuitemcheckbox", name="Snap") + expect(snap).to_have_attribute("aria-checked", "true") + snap.click() + expect(page.get_by_role("menu")).to_have_count(0) + page.locator("#canvas").click(button="right") + expect(snap).to_have_attribute("aria-checked", "false") + page.keyboard.press("Escape") + + # A hover card opens under the pointer. + page.get_by_role("link", name="Author").hover() + expect(page.locator(":popover-open")).to_have_text("Writes things") diff --git a/tests/units/reflex_components_ui/components/test_alert_dialog.py b/tests/units/reflex_components_ui/components/test_alert_dialog.py index 8f323318ac7..fe81f8e30f8 100644 --- a/tests/units/reflex_components_ui/components/test_alert_dialog.py +++ b/tests/units/reflex_components_ui/components/test_alert_dialog.py @@ -60,7 +60,7 @@ def test_alert_dialog( "props": [ '"aria-describedby":"rx-dialog-1-describedby"', '"aria-labelledby":"rx-dialog-1-labelledby"', - "className:sx_bf687cb34b_c", + "className:sx_826e1f6eca_c", '"data-rx-keep":"outside"', '"data-rx-popup":""', 'id:"rx-dialog-1"', @@ -154,6 +154,7 @@ def test_alert_dialog( "maxWidth": "none", "maxHeight": "none", "outlineStyle": "none", + "userSelect": "auto", "transitionProperty": { "default": "display, overlay", "::before": "opacity", diff --git a/tests/units/reflex_components_ui/components/test_context_menu.py b/tests/units/reflex_components_ui/components/test_context_menu.py new file mode 100644 index 00000000000..60663633c96 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_context_menu.py @@ -0,0 +1,519 @@ +"""Tests for reflex_components_ui.components.context_menu.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_components_ui.components import _popup +from reflex_components_ui.components.radio_group import RadioGroupRoot +from reflex_components_ui.components.select import _CHECK +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the popups of each test from one.""" + monkeypatch.setattr(_popup, "_ids", itertools.count(1)) + + +def test_context_menu( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A context menu is the element it is on, the point it opens at, then a popover of items; a checkbox item says whether it is checked, and the menu leaves room for its check.""" + menu = rx.ui.context_menu + component = menu.root( + menu.trigger(rx.el.div("Area"), disabled=True), + menu.content( + menu.item("Copy"), + menu.checkbox("Grid", default_checked=True, shortcut="⌘ G"), + menu.label("View"), + menu.group(menu.item("Zoom")), + menu.separator(), + ), + ) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"div"', + "props": [ + '"data-disabled":(true ? "" : undefined)', + '"data-rx-opens":"rx-context-menu-1"', + '"data-state":"closed"', + "onContextMenu:menuContext", + ], + "children": [{"contents": '"Area"'}], + }, + { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"span"', + "props": ['"aria-hidden":true', "className:sx_7e3d745d7a_c"], + "children": [], + }, + { + "name": '"div"', + "props": [ + "className:sx_5dd7216c67_c", + '"data-rx-popup":""', + 'id:"rx-context-menu-1"', + "onBeforeToggle:popupBeforeToggle", + "onBlur:menuEvent", + "onClick:menuEvent", + "onKeyDown:menuEvent", + "onPointerLeave:menuEvent", + "onPointerMove:menuEvent", + "onToggle:menuEvent", + 'popover:"auto"', + "ref:((popup) => menuSync(popup, null))", + 'role:"menu"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_b8ae355be2_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_453162d43a_c"], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_85bc40da55_c", + 'role:"menuitem"', + "tabIndex:-1", + ], + "children": [{"contents": '"Copy"'}], + }, + { + "name": '"div"', + "props": [ + '"aria-checked":true', + "className:sx_85bc40da55_c", + '"data-state":(true ? "checked" : "unchecked")', + "onClick:((event) => menuCheck(event, null, false))", + 'role:"menuitemcheckbox"', + "tabIndex:-1", + ], + "children": [ + {"contents": '"Grid"'}, + { + "name": '"span"', + "props": [ + "className:sx_0796999dae_c" + ], + "children": [ + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_2f40c68fbd_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + 'clipRule:"evenodd"', + f'd:"{_CHECK}"', + 'fillRule:"evenodd"', + ], + "children": [], + } + ], + } + ], + }, + { + "name": '"div"', + "props": [ + "className:sx_da7de3c8ae_c" + ], + "children": [ + {"contents": '"\\u2318 G"'} + ], + }, + ], + }, + { + "name": '"div"', + "props": ["className:sx_b13742d240_c"], + "children": [{"contents": '"View"'}], + }, + { + "name": '"div"', + "props": ['role:"group"'], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_85bc40da55_c", + 'role:"menuitem"', + "tabIndex:-1", + ], + "children": [ + {"contents": '"Zoom"'} + ], + } + ], + }, + { + "name": '"div"', + "props": [ + '"aria-orientation":"horizontal"', + "className:sx_834f03d11d_c", + 'role:"separator"', + ], + "children": [], + }, + ], + } + ], + } + ], + }, + ], + }, + ], + } + # The items, the check, the shortcut, the label and the separator. + assert declared_styles(component)[3:] == [ + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-y, 0px))", + "marginRight": "calc(10px - var(--rx-popup-snap-x, 0px))", + "marginBottom": "calc(0px - var(--rx-popup-snap-y, 0px))", + "marginLeft": "calc(var(--rx-popup-offset, 2px) + var(--rx-popup-snap-x, 0px))", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "calc(100% - var(--rx-popup-offset, 2px) - 10px)", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "100ms", + ":popover-open": "160ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "var(--gray-12)", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "display": {"default": "none", ":popover-open": "flex"}, + "flexDirection": "column", + "overflowX": "hidden", + "overflowY": "hidden", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-5)", + "outlineStyle": "none", + "--base-menu-content-padding": "var(--space-2)", + "--base-menu-item-padding-right": "var(--space-3)", + "--base-menu-item-height": "var(--space-6)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "--rx-menu-font-size": "var(--font-size-2)", + "--rx-menu-line-height": "var(--line-height-2)", + "--rx-menu-letter-spacing": "var(--letter-spacing-2)", + "--rx-menu-item-radius": "var(--radius-2)", + "--rx-menu-icon-size": "calc(10px * var(--scaling))", + "--rx-popup-shift": "-8px", + "--base-menu-item-padding-left": "var(--space-5)", + "positionArea": "right span-bottom", + "--rx-popup-from": "translateX(-4px) scale(0.97)", + "transformOrigin": "left top", + }, + { + "flexGrow": "1", + "flexShrink": "1", + "flexBasis": "0%", + "minHeight": "0", + "overflowX": "auto", + "overflowY": "auto", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) transparent", + }, + { + "flexGrow": "1", + "flexShrink": "1", + "flexBasis": "0%", + "minWidth": "0", + "minHeight": "0", + "display": "flex", + "flexDirection": "column", + "overflowX": "auto", + "overflowY": "auto", + "padding": "var(--base-menu-content-padding)", + "boxSizing": "border-box", + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "height": "var(--base-menu-item-height)", + "paddingLeft": "var(--base-menu-item-padding-left)", + "paddingRight": "var(--base-menu-item-padding-right)", + "boxSizing": "border-box", + "position": "relative", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentColor", + "scrollMarginTop": "var(--base-menu-content-padding)", + "scrollMarginBottom": "var(--base-menu-content-padding)", + "userSelect": "none", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, + "fontSize": "var(--rx-menu-font-size)", + "lineHeight": "var(--rx-menu-line-height)", + "letterSpacing": "var(--rx-menu-letter-spacing)", + "borderRadius": "var(--rx-menu-item-radius)", + "color": { + "[aria-disabled='true']": "var(--gray-a8)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-shortcut-color": { + "default": "var(--gray-a11)", + ":focus": "currentColor", + "[aria-disabled='true']": "currentColor", + "[data-state='open']": "currentColor", + }, + "--rx-menu-chevron-color": { + "default": "var(--gray-12)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-check": { + "default": "none", + "[aria-checked='true']": "inline-flex", + }, + "backgroundColor": { + ":focus": "var(--accent-9)", + ":not(:focus)[data-state='open']": "var(--gray-a3)", + }, + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "height": "var(--base-menu-item-height)", + "paddingLeft": "var(--base-menu-item-padding-left)", + "paddingRight": "var(--base-menu-item-padding-right)", + "boxSizing": "border-box", + "position": "relative", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentColor", + "scrollMarginTop": "var(--base-menu-content-padding)", + "scrollMarginBottom": "var(--base-menu-content-padding)", + "userSelect": "none", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, + "fontSize": "var(--rx-menu-font-size)", + "lineHeight": "var(--rx-menu-line-height)", + "letterSpacing": "var(--rx-menu-letter-spacing)", + "borderRadius": "var(--rx-menu-item-radius)", + "color": { + "[aria-disabled='true']": "var(--gray-a8)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-shortcut-color": { + "default": "var(--gray-a11)", + ":focus": "currentColor", + "[aria-disabled='true']": "currentColor", + "[data-state='open']": "currentColor", + }, + "--rx-menu-chevron-color": { + "default": "var(--gray-12)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-check": { + "default": "none", + "[aria-checked='true']": "inline-flex", + }, + "backgroundColor": { + ":focus": "var(--accent-9)", + ":not(:focus)[data-state='open']": "var(--gray-a3)", + }, + }, + { + "position": "absolute", + "left": "0", + "width": "var(--base-menu-item-padding-left)", + "display": "var(--rx-menu-check)", + "alignItems": "center", + "justifyContent": "center", + }, + {"width": "var(--rx-menu-icon-size)", "height": "var(--rx-menu-icon-size)"}, + { + "display": "flex", + "alignItems": "center", + "marginLeft": "auto", + "paddingLeft": "var(--space-4)", + "color": "var(--rx-menu-shortcut-color)", + }, + { + "display": "flex", + "alignItems": "center", + "height": "var(--base-menu-item-height)", + "paddingLeft": "var(--base-menu-item-padding-left)", + "paddingRight": "var(--base-menu-item-padding-right)", + "boxSizing": "border-box", + "color": "var(--gray-a10)", + "userSelect": "none", + "cursor": "default", + "fontSize": "var(--rx-menu-font-size)", + "lineHeight": "var(--rx-menu-line-height)", + "letterSpacing": "var(--rx-menu-letter-spacing)", + "marginTop": { + ":is(:is([role=menuitem], [role=menuitemcheckbox]) + *)": "var(--space-2)" + }, + }, + {}, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "height": "var(--base-menu-item-height)", + "paddingLeft": "var(--base-menu-item-padding-left)", + "paddingRight": "var(--base-menu-item-padding-right)", + "boxSizing": "border-box", + "position": "relative", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentColor", + "scrollMarginTop": "var(--base-menu-content-padding)", + "scrollMarginBottom": "var(--base-menu-content-padding)", + "userSelect": "none", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, + "fontSize": "var(--rx-menu-font-size)", + "lineHeight": "var(--rx-menu-line-height)", + "letterSpacing": "var(--rx-menu-letter-spacing)", + "borderRadius": "var(--rx-menu-item-radius)", + "color": { + "[aria-disabled='true']": "var(--gray-a8)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-shortcut-color": { + "default": "var(--gray-a11)", + ":focus": "currentColor", + "[aria-disabled='true']": "currentColor", + "[data-state='open']": "currentColor", + }, + "--rx-menu-chevron-color": { + "default": "var(--gray-12)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-check": { + "default": "none", + "[aria-checked='true']": "inline-flex", + }, + "backgroundColor": { + ":focus": "var(--accent-9)", + ":not(:focus)[data-state='open']": "var(--gray-a3)", + }, + }, + { + "height": "1px", + "marginTop": "var(--space-2)", + "marginBottom": "var(--space-2)", + "marginLeft": "var(--base-menu-item-padding-left)", + "marginRight": "var(--base-menu-item-padding-right)", + "backgroundColor": "var(--gray-a6)", + }, + ] + + +class GridState(rx.State): + """What a checkbox item is bound to.""" + + grid: bool = True + + @rx.event + def set_grid(self, grid: bool): + """Follow the item. + + Args: + grid: Whether it is checked. + """ + self.grid = grid + + +def test_context_menu_checkbox_bound_to_state(ui_plugin: UIPlugin): + """A checkbox item bound to state shows the state, and hands its script what it does when it changes.""" + name = GridState.get_full_name() + item = rx.ui.context_menu.checkbox( + "Grid", checked=GridState.grid, on_change=GridState.set_grid + ) + assert item.render()["props"] == [ + f'"aria-checked":{GridState.grid!s}', + "className:sx_85bc40da55_c", + f'"data-state":({GridState.grid!s} ? "checked" : "unchecked")', + ( + "onClick:((event) => menuCheck(event, ((_ev_0) => (addEvents(" + f'[(ReflexEvent("{name}.set_grid", ({{ ["grid"] : _ev_0 }}), ({{ }})))], ' + "[_ev_0], ({ })))), true))" + ), + 'role:"menuitemcheckbox"', + "tabIndex:-1", + ] + + +def test_context_menu_radio_is_a_radio_group(ui_plugin: UIPlugin): + """rx.ui.context_menu.radio is a group of radio buttons from its items, as rx.context_menu.radio is.""" + assert isinstance(rx.ui.context_menu.radio(["a", "b"]), RadioGroupRoot) diff --git a/tests/units/reflex_components_ui/components/test_dialog.py b/tests/units/reflex_components_ui/components/test_dialog.py index 663232da10c..e2b744ecd63 100644 --- a/tests/units/reflex_components_ui/components/test_dialog.py +++ b/tests/units/reflex_components_ui/components/test_dialog.py @@ -63,7 +63,7 @@ def test_dialog( "props": [ '"aria-describedby":"about"', '"aria-labelledby":"rx-dialog-1-labelledby"', - "className:sx_bf687cb34b_c", + "className:sx_826e1f6eca_c", '"data-default-open":true', '"data-rx-popup":""', 'id:"rx-dialog-1"', @@ -152,6 +152,7 @@ def test_dialog( "maxWidth": "none", "maxHeight": "none", "outlineStyle": "none", + "userSelect": "auto", "transitionProperty": { "default": "display, overlay", "::before": "opacity", @@ -316,7 +317,7 @@ def test_dialog_in_a_dialog(ui_plugin: UIPlugin): { "name": '"dialog"', "props": [ - "className:sx_bf687cb34b_c", + "className:sx_826e1f6eca_c", '"data-rx-popup":""', 'id:"rx-dialog-2"', "onCancel:dialogEvent", @@ -359,7 +360,7 @@ def test_dialog_in_a_dialog(ui_plugin: UIPlugin): { "name": '"dialog"', "props": [ - "className:sx_bf687cb34b_c", + "className:sx_826e1f6eca_c", '"data-rx-popup":""', 'id:"rx-dialog-1"', "onCancel:dialogEvent", @@ -427,7 +428,7 @@ def test_dialog_parts_alone(ui_plugin: UIPlugin): { "name": '"dialog"', "props": [ - "className:sx_bf687cb34b_c", + "className:sx_826e1f6eca_c", '"data-rx-popup":""', "onCancel:dialogEvent", "onClose:dialogEvent", @@ -521,7 +522,7 @@ def test_dialog_bound_to_state(ui_plugin: UIPlugin): "({ })))], args, ({ }))))" ) assert dialog["props"] == [ - "className:sx_bf687cb34b_c", + "className:sx_826e1f6eca_c", '"data-rx-popup":""', 'id:"rx-dialog-1"', "onCancel:dialogEvent", diff --git a/tests/units/reflex_components_ui/components/test_drawer.py b/tests/units/reflex_components_ui/components/test_drawer.py index aca4a9f36af..8c554cf861e 100644 --- a/tests/units/reflex_components_ui/components/test_drawer.py +++ b/tests/units/reflex_components_ui/components/test_drawer.py @@ -73,7 +73,7 @@ def test_drawer( "props": [ '"aria-describedby":"rx-dialog-1-describedby"', '"aria-labelledby":"rx-dialog-1-labelledby"', - "className:sx_ec0690f8c2_c", + "className:sx_a309248e5f_c", '"data-rx-popup":""', 'id:"rx-dialog-1"', "onCancel:dialogEvent", @@ -186,6 +186,7 @@ def test_drawer( "maxWidth": "none", "maxHeight": "none", "outlineStyle": "none", + "userSelect": "auto", "transitionProperty": "display, overlay", "transitionDuration": "0.55s", "--rx-dialog-shown": {"default": 0, "[open]": 1}, @@ -310,7 +311,7 @@ def test_drawer_that_is_not_modal_nor_dismissible( { "name": '"dialog"', "props": [ - "className:sx_9705da5fe6_c", + "className:sx_26229be874_c", '"data-modal":"false"', '"data-rx-keep":"all"', '"data-rx-popup":""', @@ -367,6 +368,7 @@ def test_drawer_that_is_not_modal_nor_dismissible( "maxWidth": "none", "maxHeight": "none", "outlineStyle": "none", + "userSelect": "auto", "transitionProperty": "display, overlay", "transitionDuration": "0.55s", "--rx-dialog-shown": {"default": 0, "[open]": 1}, diff --git a/tests/units/reflex_components_ui/components/test_dropdown_menu.py b/tests/units/reflex_components_ui/components/test_dropdown_menu.py new file mode 100644 index 00000000000..39ed1c67e78 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -0,0 +1,493 @@ +"""Tests for reflex_components_ui.components.dropdown_menu.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import _popup +from reflex_components_ui.components._menu import _CHEVRON +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the popups of each test from one.""" + monkeypatch.setattr(_popup, "_ids", itertools.count(1)) + + +def test_dropdown_menu(ui_plugin: UIPlugin): + """A dropdown menu is its trigger, then a popover of items whose look the content hands its items and its sub-menus, which a script moves through.""" + menu = rx.ui.dropdown_menu + component = menu.root( + menu.trigger(rx.el.button("Options")), + menu.content( + menu.item("Edit", shortcut="⌘ E", text_value="Change"), + menu.item("Delete", color_scheme="red", disabled=True), + menu.separator(), + menu.sub(menu.sub_trigger("More"), menu.sub_content(menu.item("Share"))), + variant="soft", + size="1", + high_contrast=True, + loop=True, + side_offset=6, + ), + default_open=True, + ) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"button"', + "props": [ + '"aria-controls":"rx-dropdown-menu-2"', + '"aria-expanded":false', + '"aria-haspopup":"menu"', + '"data-state":"closed"', + "onKeyDown:menuTrigger", + 'popovertarget:"rx-dropdown-menu-2"', + ], + "children": [{"contents": '"Options"'}], + }, + { + "name": '"div"', + "props": [ + "className:sx_47b417df9e_c", + '"data-default-open":true', + '"data-loop":true', + '"data-rx-popup":""', + 'id:"rx-dropdown-menu-2"', + "onBeforeToggle:popupBeforeToggle", + "onBlur:menuEvent", + "onClick:menuEvent", + "onKeyDown:menuEvent", + "onPointerLeave:menuEvent", + "onPointerMove:menuEvent", + "onToggle:menuEvent", + 'popover:"auto"', + "ref:((popup) => menuSync(popup, null))", + 'role:"menu"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"div"', + "props": ["className:sx_b8ae355be2_c"], + "children": [ + { + "name": '"div"', + "props": ["className:sx_453162d43a_c"], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_da4b1b2e3f_c", + '"data-text-value":"Change"', + 'role:"menuitem"', + "tabIndex:-1", + ], + "children": [ + {"contents": '"Edit"'}, + { + "name": '"div"', + "props": ["className:sx_da7de3c8ae_c"], + "children": [ + {"contents": '"\\u2318 E"'} + ], + }, + ], + }, + { + "name": '"div"', + "props": [ + '"aria-disabled":true', + 'className:sx_52d0500fbd_c + " " + reflexUIClasses_01ac7ed29f', + 'role:"menuitem"', + "tabIndex:-1", + ], + "children": [{"contents": '"Delete"'}], + }, + { + "name": '"div"', + "props": [ + '"aria-orientation":"horizontal"', + "className:sx_834f03d11d_c", + 'role:"separator"', + ], + "children": [], + }, + { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"div"', + "props": [ + '"aria-controls":"rx-menu-sub-1"', + '"aria-expanded":false', + '"aria-haspopup":"menu"', + "className:sx_da4b1b2e3f_c", + '"data-rx-opens":"rx-menu-sub-1"', + '"data-state":"closed"', + 'role:"menuitem"', + "tabIndex:-1", + ], + "children": [ + {"contents": '"More"'}, + { + "name": '"div"', + "props": [ + "className:sx_da7de3c8ae_c" + ], + "children": [ + { + "name": '"svg"', + "props": [ + '"aria-hidden":true', + "className:sx_ddf3393e61_c", + 'fill:"currentcolor"', + 'height:"9"', + 'viewBox:"0 0 9 9"', + 'width:"9"', + 'xmlns:"http://www.w3.org/2000/svg"', + ], + "children": [ + { + "name": '"path"', + "props": [ + f'd:"{_CHEVRON}"' + ], + "children": [], + } + ], + } + ], + }, + ], + }, + { + "name": '"div"', + "props": [ + "className:sx_f920401ab7_c", + '"data-rx-popup":""', + 'id:"rx-menu-sub-1"', + "onBeforeToggle:popupBeforeToggle", + "onBlur:menuEvent", + "onClick:menuEvent", + "onKeyDown:menuEvent", + "onPointerLeave:menuEvent", + "onPointerMove:menuEvent", + "onToggle:menuEvent", + 'popover:"auto"', + "ref:((popup) => menuSync(popup, null))", + 'role:"menu"', + "tabIndex:-1", + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_b8ae355be2_c" + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_453162d43a_c" + ], + "children": [ + { + "name": '"div"', + "props": [ + "className:sx_da4b1b2e3f_c", + 'role:"menuitem"', + "tabIndex:-1", + ], + "children": [ + { + "contents": '"Share"' + } + ], + } + ], + } + ], + } + ], + }, + ], + }, + ], + } + ], + } + ], + }, + ], + } + + +def test_dropdown_menu_styles( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """The menu has the look of the menu of Radix Themes, its items the one of its items, as the menu hands them down.""" + menu = rx.ui.dropdown_menu + component = menu.root( + menu.trigger(rx.el.button("Options")), menu.content(menu.item("Edit")) + ) + assert declared_styles(component) == [ + {}, + {}, + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-y, 0px))", + "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", + "marginBottom": "calc(10px - var(--rx-popup-snap-y, 0px))", + "marginLeft": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-x, 0px))", + "paddingTop": "0", + "paddingRight": "0", + "paddingBottom": "0", + "paddingLeft": "0", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "calc(100vw - 10px * 2)", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "100ms", + ":popover-open": "160ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "var(--gray-12)", + "fontFamily": "var(--default-font-family)", + "fontWeight": "var(--font-weight-regular)", + "fontStyle": "normal", + "textAlign": "start", + "display": {"default": "none", ":popover-open": "flex"}, + "flexDirection": "column", + "overflowX": "hidden", + "overflowY": "hidden", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-5)", + "outlineStyle": "none", + "--base-menu-content-padding": "var(--space-2)", + "--base-menu-item-padding-right": "var(--space-3)", + "--base-menu-item-height": "var(--space-6)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "--rx-menu-font-size": "var(--font-size-2)", + "--rx-menu-line-height": "var(--line-height-2)", + "--rx-menu-letter-spacing": "var(--letter-spacing-2)", + "--rx-menu-item-radius": "var(--radius-2)", + "--rx-menu-icon-size": "calc(10px * var(--scaling))", + "--base-menu-item-padding-left": "var(--space-3)", + "positionArea": "bottom span-right", + "maxHeight": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", + "--rx-popup-from": "translateY(-4px) scale(0.97)", + "transformOrigin": "top left", + }, + { + "flexGrow": "1", + "flexShrink": "1", + "flexBasis": "0%", + "minHeight": "0", + "overflowX": "auto", + "overflowY": "auto", + "scrollbarWidth": "thin", + "scrollbarColor": "var(--gray-a8) transparent", + }, + { + "flexGrow": "1", + "flexShrink": "1", + "flexBasis": "0%", + "minWidth": "0", + "minHeight": "0", + "display": "flex", + "flexDirection": "column", + "overflowX": "auto", + "overflowY": "auto", + "padding": "var(--base-menu-content-padding)", + "boxSizing": "border-box", + }, + { + "display": "flex", + "alignItems": "center", + "rowGap": "var(--space-2)", + "columnGap": "var(--space-2)", + "height": "var(--base-menu-item-height)", + "paddingLeft": "var(--base-menu-item-padding-left)", + "paddingRight": "var(--base-menu-item-padding-right)", + "boxSizing": "border-box", + "position": "relative", + "outlineStyle": "none", + "outlineWidth": "medium", + "outlineColor": "currentColor", + "scrollMarginTop": "var(--base-menu-content-padding)", + "scrollMarginBottom": "var(--base-menu-content-padding)", + "userSelect": "none", + "cursor": { + "default": "var(--cursor-menu-item)", + "[aria-disabled='true']": "default", + }, + "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, + "fontSize": "var(--rx-menu-font-size)", + "lineHeight": "var(--rx-menu-line-height)", + "letterSpacing": "var(--rx-menu-letter-spacing)", + "borderRadius": "var(--rx-menu-item-radius)", + "color": { + "[aria-disabled='true']": "var(--gray-a8)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-shortcut-color": { + "default": "var(--gray-a11)", + ":focus": "currentColor", + "[aria-disabled='true']": "currentColor", + "[data-state='open']": "currentColor", + }, + "--rx-menu-chevron-color": { + "default": "var(--gray-12)", + ":focus": "var(--accent-contrast)", + }, + "--rx-menu-check": { + "default": "none", + "[aria-checked='true']": "inline-flex", + }, + "backgroundColor": { + ":focus": "var(--accent-9)", + ":not(:focus)[data-state='open']": "var(--gray-a3)", + }, + }, + ] + + +class MenuState(rx.State): + """What a menu is bound to.""" + + shown: bool = False + + @rx.event + def set_shown(self, shown: bool): + """Follow the menu. + + Args: + shown: Whether it is open. + """ + self.shown = shown + + @rx.event + def escaped(self): + """Hear Escape.""" + + +def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): + """A menu bound to state hands its script its state, and what it does when it opens, closes or is dismissed; a choice is a press on the item.""" + name = MenuState.get_full_name() + menu = rx.ui.dropdown_menu + component = menu.root( + menu.trigger(rx.el.button("Options")), + menu.content( + menu.item("Edit", on_select=MenuState.escaped), + on_escape_key_down=MenuState.escaped, + ), + open=MenuState.shown, + on_open_change=MenuState.set_shown, + ) + _, content = component.render()["children"] + on = ( + f'({{ open: ((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' + '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))), escape: ' + f'((...args) => (addEvents([(ReflexEvent("{name}.escaped", ({{ }}), ' + "({ })))], args, ({ })))) })" + ) + assert content["props"][1:] == [ + '"data-rx-popup":""', + 'id:"rx-dropdown-menu-1"', + "onBeforeToggle:popupBeforeToggle", + f"onBlur:((event) => menuEvent(event, {on}))", + f"onClick:((event) => menuEvent(event, {on}))", + f"onKeyDown:((event) => menuEvent(event, {on}))", + f"onPointerLeave:((event) => menuEvent(event, {on}))", + f"onPointerMove:((event) => menuEvent(event, {on}))", + f"onToggle:((event) => menuEvent(event, {on}))", + 'popover:"auto"', + f"ref:((popup) => menuSync(popup, {MenuState.shown!s}))", + 'role:"menu"', + "tabIndex:-1", + ] + item = content["children"][0]["children"][0]["children"][0] + assert item["props"][1:] == [ + ( + f'onClick:((...args) => (addEvents([(ReflexEvent("{name}.escaped", ' + "({ }), ({ })))], args, ({ }))))" + ), + 'role:"menuitem"', + "tabIndex:-1", + ] + + +def test_dropdown_menu_imports_its_script(ui_plugin: UIPlugin): + """A page with a menu loads the script of the menus, and what puts a popup on whole pixels.""" + menu = rx.ui.dropdown_menu + component = menu.root( + menu.trigger(rx.el.button("Options")), menu.content(menu.item("Edit")) + ) + imports = component._get_all_imports() + assert { + module: names for module, names in imports.items() if "behaviors" in module + } == { + "$/reflex-ui/behaviors/menu.js": [ + ImportVar(tag="menuTrigger"), + ImportVar(tag="menuSync"), + ImportVar(tag="menuEvent"), + ], + "$/reflex-ui/behaviors/popup.js": [ImportVar(tag="popupBeforeToggle")], + } + + +def test_menu_is_the_dropdown_menu(ui_plugin: UIPlugin): + """rx.ui.menu is rx.ui.dropdown_menu, as rx.menu is rx.dropdown_menu.""" + assert rx.ui.menu is rx.ui.dropdown_menu + + +def test_dropdown_menu_trigger_needs_an_element(ui_plugin: UIPlugin): + """A trigger of anything but one element fails with the name of the component.""" + with pytest.raises(StyleError) as error: + rx.ui.dropdown_menu.trigger("Options") + assert str(error.value) == ( + "rx.ui.dropdown_menu_trigger: it is rendered as its child, so it needs exactly " + "one child that is an element, such as a button." + ) diff --git a/tests/units/reflex_components_ui/components/test_hover_card.py b/tests/units/reflex_components_ui/components/test_hover_card.py new file mode 100644 index 00000000000..a8d53e715ef --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_hover_card.py @@ -0,0 +1,229 @@ +"""Tests for reflex_components_ui.components.hover_card.""" + +import itertools +from collections.abc import Callable +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components import _popup +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError + +import reflex as rx + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the popups of each test from one.""" + monkeypatch.setattr(_popup, "_ids", itertools.count(1)) + + +def test_hover_card( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A hover card is its trigger, then a popover a script opens under the pointer and with the focus, after the delays of its root.""" + component = rx.ui.hover_card.root( + rx.ui.hover_card.trigger(rx.el.button("Radix")), + rx.ui.hover_card.content( + rx.el.p("Inside"), size="1", side="top", align="center", side_offset=4 + ), + open_delay=100, + close_delay=50, + default_open=True, + ) + assert component.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"button"', + "props": [ + '"data-rx-hover":"rx-hover-card-1"', + '"data-state":"closed"', + "onBlur:hoverEvent", + "onFocus:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + ], + "children": [{"contents": '"Radix"'}], + }, + { + "name": '"div"', + "props": [ + "className:sx_a4491172ba_c", + '"data-close-delay":50', + '"data-default-open":true', + '"data-open-delay":100', + '"data-rx-popup":""', + 'id:"rx-hover-card-1"', + "onBeforeToggle:popupBeforeToggle", + "onBlur:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + 'popover:"manual"', + "ref:((popup) => hoverSync(popup, null))", + ], + "children": [ + { + "name": '"p"', + "props": [], + "children": [{"contents": '"Inside"'}], + } + ], + }, + ], + } + assert declared_styles(component) == [ + {}, + {}, + { + "position": "fixed", + "top": "auto", + "right": "auto", + "bottom": "auto", + "left": "auto", + "marginTop": "calc(10px + var(--rx-popup-snap-y, 0px))", + "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", + "marginBottom": "calc(var(--rx-popup-offset, 8px) - var(--rx-popup-snap-y, 0px))", + "marginLeft": "var(--rx-popup-snap-x, 0px)", + "padding": "var(--hover-card-content-padding)", + "borderTopWidth": "0", + "borderRightWidth": "0", + "borderBottomWidth": "0", + "borderLeftWidth": "0", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", + "boxSizing": "border-box", + "width": "max-content", + "height": "auto", + "maxWidth": "min(480px, calc(100vw - 20px))", + "positionTryFallbacks": "flip-block, flip-inline", + "opacity": { + "default": 0, + ":popover-open": {"default": 1, "@starting-style": 0}, + }, + "transform": { + "default": "var(--rx-popup-from)", + ":popover-open": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + }, + }, + "transitionProperty": "opacity, transform, display, overlay", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "100ms", + ":popover-open": "160ms", + }, + }, + "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "inherit", + "backgroundColor": "var(--color-panel-solid)", + "boxShadow": "var(--shadow-4)", + "outlineStyle": "none", + "overflowX": "auto", + "overflowY": "auto", + "--inset-padding-top": "var(--hover-card-content-padding)", + "--inset-padding-right": "var(--hover-card-content-padding)", + "--inset-padding-bottom": "var(--hover-card-content-padding)", + "--inset-padding-left": "var(--hover-card-content-padding)", + "--hover-card-content-padding": "var(--space-3)", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "positionArea": "top span-all", + "maxHeight": "calc(100% - var(--rx-popup-offset, 8px) - 10px)", + "--rx-popup-from": "translateY(4px) scale(0.97)", + "transformOrigin": "bottom center", + "justifySelf": "anchor-center", + "--rx-popup-offset": "4px", + }, + ] + + +class HoverCardState(rx.State): + """What a hover card is bound to.""" + + shown: bool = False + wait: int = 300 + + @rx.event + def set_shown(self, shown: bool): + """Follow the hover card. + + Args: + shown: Whether it is open. + """ + self.shown = shown + + +def test_hover_card_bound_to_state(ui_plugin: UIPlugin): + """A hover card bound to state hands its script its state, its delays and what it does when it is asked to open or close; the defaults are the delays of Radix Themes.""" + name = HoverCardState.get_full_name() + component = rx.ui.hover_card( + rx.ui.hover_card.trigger(rx.el.a("Radix", id="radix")), + rx.ui.hover_card.content("Inside", id="card"), + open=HoverCardState.shown, + on_open_change=HoverCardState.set_shown, + open_delay=HoverCardState.wait, + ) + trigger, popup = component.render()["children"] + assert trigger["props"] == [ + '"data-rx-hover":"card"', + '"data-state":"closed"', + 'id:"radix"', + "onBlur:hoverEvent", + "onFocus:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + "ref:ref_radix", + ] + assert popup["props"] == [ + "className:sx_2cb8c9a2a4_c", + '"data-close-delay":150', + f'"data-open-delay":{HoverCardState.wait!s}', + '"data-rx-popup":""', + 'id:"card"', + "onBeforeToggle:popupBeforeToggle", + "onBlur:hoverEvent", + "onPointerEnter:hoverEvent", + "onPointerLeave:hoverEvent", + 'popover:"manual"', + ( + f"ref:((popup) => hoverSync(popup, {HoverCardState.shown!s}, ({{ open: " + f'((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' + '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))) })))' + ), + ] + + +def test_hover_card_imports_its_script(ui_plugin: UIPlugin): + """A page with a hover card loads the script of the popups that open under the pointer, and what puts a popup on whole pixels.""" + component = rx.ui.hover_card.root( + rx.ui.hover_card.trigger(rx.el.a("Radix")), rx.ui.hover_card.content("x") + ) + imports = component._get_all_imports() + assert { + module: names for module, names in imports.items() if "behaviors" in module + } == { + "$/reflex-ui/behaviors/hover.js": [ + ImportVar(tag="hoverEvent"), + ImportVar(tag="hoverSync"), + ], + "$/reflex-ui/behaviors/popup.js": [ImportVar(tag="popupBeforeToggle")], + } + + +def test_hover_card_trigger_needs_an_element(ui_plugin: UIPlugin): + """A trigger of anything but one element fails with the name of the component.""" + with pytest.raises(StyleError) as error: + rx.ui.hover_card.trigger("Radix") + assert str(error.value) == ( + "rx.ui.hover_card_trigger: it is rendered as its child, so it needs exactly " + "one child that is an element, such as a button." + ) diff --git a/tests/units/reflex_components_ui/components/test_popover.py b/tests/units/reflex_components_ui/components/test_popover.py index ab5f08a6d01..836cc00bbcf 100644 --- a/tests/units/reflex_components_ui/components/test_popover.py +++ b/tests/units/reflex_components_ui/components/test_popover.py @@ -60,7 +60,7 @@ def test_popover( { "name": '"div"', "props": [ - "className:sx_3d26714754_c", + "className:sx_2fbab4a681_c", '"data-default-open":true', '"data-rx-popup":""', 'id:"rx-popover-1"', @@ -97,7 +97,7 @@ def test_popover( "right": "auto", "bottom": "auto", "left": "auto", - "marginTop": "calc(var(--rx-popup-offset, 8px) + var(--rx-popup-snap-y, 0px))", + "marginTop": "calc(10px + var(--rx-popup-snap-y, 0px))", "marginRight": "calc(var(--rx-popup-shift, 0px) - var(--rx-popup-snap-x, 0px))", "marginBottom": "calc(var(--rx-popup-offset, 8px) - var(--rx-popup-snap-y, 0px))", "marginLeft": "var(--rx-popup-snap-x, 0px)", @@ -106,10 +106,10 @@ def test_popover( "borderRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", "boxSizing": "border-box", "width": "max-content", "height": "auto", @@ -140,6 +140,7 @@ def test_popover( "boxShadow": "var(--shadow-5)", "minWidth": "anchor-size(width)", "outlineStyle": "none", + "outlineWidth": "0", "overflowX": "auto", "overflowY": "auto", "--inset-padding-top": "var(--popover-content-padding)", @@ -193,7 +194,7 @@ def test_popover_with_an_id(ui_plugin: UIPlugin): { "name": '"div"', "props": [ - "className:sx_e28bbf7e11_c", + "className:sx_8dd6075b6b_c", '"data-rx-popup":""', 'id:"panel"', "onBeforeToggle:popupBeforeToggle", @@ -213,7 +214,7 @@ def test_popover_with_an_id(ui_plugin: UIPlugin): { "name": '"div"', "props": [ - "className:sx_e28bbf7e11_c", + "className:sx_8dd6075b6b_c", '"data-rx-popup":""', "onBeforeToggle:popupBeforeToggle", "onBlur:popupEvent", @@ -273,7 +274,7 @@ def test_popover_bound_to_state(ui_plugin: UIPlugin): "({ })))], args, ({ })))) })" ) assert rendered["children"][1]["props"] == [ - "className:sx_b28f9a43f1_c", + "className:sx_178ccdbf1d_c", '"data-rx-popup":""', 'id:"rx-popover-1"', "onBeforeToggle:popupBeforeToggle", diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index 87ce0ed8cd5..3d2e35aea5b 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -156,7 +156,7 @@ def test_select( { "name": '"div"', "props": [ - 'className:sx_c23b44fd7f_c + " " + reflexUIClasses_f97593a337', + 'className:sx_a9c2b0afeb_c + " " + reflexUIClasses_f97593a337', '"data-rx-popup":""', 'id:"rx-select-2"', "onBeforeToggle:popupBeforeToggle", @@ -477,7 +477,7 @@ def test_select( "right": "auto", "bottom": "auto", "left": "auto", - "marginTop": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-y, 0px))", + "marginTop": "calc(10px + var(--rx-popup-snap-y, 0px))", "marginRight": "calc(var(--rx-popup-shift, 0px) - var(--rx-popup-snap-x, 0px))", "marginBottom": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-y, 0px))", "marginLeft": "var(--rx-popup-snap-x, 0px)", @@ -486,10 +486,10 @@ def test_select( "borderRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", "boxSizing": "border-box", "width": "max-content", "height": "auto", @@ -803,7 +803,7 @@ def test_select_of_a_list( { "name": '"div"', "props": [ - 'className:sx_51e4617267_c + " " + reflexUIClasses_e201574881', + 'className:sx_070d48041b_c + " " + reflexUIClasses_e201574881', '"data-rx-popup":""', 'id:"rx-select-2"', "onBeforeToggle:popupBeforeToggle", @@ -1042,17 +1042,17 @@ def test_select_default_styles( "left": "auto", "marginTop": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-y, 0px))", "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-y, 0px))", + "marginBottom": "calc(10px - var(--rx-popup-snap-y, 0px))", "marginLeft": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-x, 0px))", "padding": "var(--select-content-padding)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", "boxSizing": "border-box", "width": "max-content", "height": "auto", @@ -1273,16 +1273,16 @@ def test_select_ghost_styles( "marginTop": "var(--rx-popup-snap-y, 0px)", "marginRight": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-x, 0px))", "marginBottom": "calc(0px - var(--rx-popup-snap-y, 0px))", - "marginLeft": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-x, 0px))", + "marginLeft": "calc(10px + var(--rx-popup-snap-x, 0px))", "padding": "var(--select-content-padding)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", "boxSizing": "border-box", "width": "max-content", "height": "auto", @@ -1488,7 +1488,7 @@ def test_select_bound_to_state(ui_plugin: UIPlugin): ], } assert content.render()["props"] == [ - "className:sx_58b8db244a_c", + "className:sx_eeb5a9fe4b_c", '"data-rx-popup":""', 'id:"rx-select-1"', "onBeforeToggle:popupBeforeToggle", diff --git a/tests/units/reflex_components_ui/components/test_tooltip.py b/tests/units/reflex_components_ui/components/test_tooltip.py index b118ac211b4..14e5b7aed18 100644 --- a/tests/units/reflex_components_ui/components/test_tooltip.py +++ b/tests/units/reflex_components_ui/components/test_tooltip.py @@ -59,7 +59,7 @@ def test_tooltip( "name": '"div"', "props": [ '"aria-label":"Save"', - "className:sx_95cc9f27bd_c", + "className:sx_dfdb3d8a01_c", '"data-close-delay":0', '"data-default-open":true', '"data-open-delay":0', @@ -93,7 +93,7 @@ def test_tooltip( "left": "auto", "marginTop": "calc(var(--rx-popup-offset, 9px) + var(--rx-popup-snap-y, 0px))", "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(var(--rx-popup-offset, 9px) - var(--rx-popup-snap-y, 0px))", + "marginBottom": "calc(10px - var(--rx-popup-snap-y, 0px))", "marginLeft": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-x, 0px))", "paddingTop": "var(--space-1)", "paddingRight": "var(--space-2)", @@ -103,10 +103,10 @@ def test_tooltip( "borderRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", + "borderTopStyle": "solid", + "borderRightStyle": "solid", + "borderBottomStyle": "solid", + "borderLeftStyle": "solid", "boxSizing": "border-box", "width": "max-content", "height": "auto", @@ -132,6 +132,7 @@ def test_tooltip( }, }, "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", + "color": "inherit", "overflowX": "visible", "overflowY": "visible", "backgroundColor": "var(--gray-12)", @@ -201,7 +202,7 @@ def test_tooltip_bound_to_state(ui_plugin: UIPlugin): "onPointerLeave:hoverEvent", ] assert popup["props"] == [ - f'className:sx_1d362a8deb_c + " " + (sx_1d362a8deb_0[{TooltipState.still!s}] ?? "")', + f'className:sx_35d14492e9_c + " " + (sx_35d14492e9_0[{TooltipState.still!s}] ?? "")', f'"data-close-delay":({TooltipState.still!s} ? 0 : 100)', '"data-open-delay":200', '"data-rx-popup":""', diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 853567b78b2..d0652fa3add 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -135,6 +135,19 @@ def test_every_wave_is_in_the_namespace(): "checkbox_group.root", "code", "container", + "context_menu.checkbox", + "context_menu.content", + "context_menu.group", + "context_menu.item", + "context_menu.label", + "context_menu.radio", + "context_menu.radio_group", + "context_menu.root", + "context_menu.separator", + "context_menu.sub", + "context_menu.sub_content", + "context_menu.sub_trigger", + "context_menu.trigger", "data_list.item", "data_list.label", "data_list.root", @@ -157,6 +170,14 @@ def test_every_wave_is_in_the_namespace(): "drawer.root", "drawer.title", "drawer.trigger", + "dropdown_menu.content", + "dropdown_menu.item", + "dropdown_menu.root", + "dropdown_menu.separator", + "dropdown_menu.sub", + "dropdown_menu.sub_content", + "dropdown_menu.sub_trigger", + "dropdown_menu.trigger", "flex", "form", "form.control", @@ -168,6 +189,10 @@ def test_every_wave_is_in_the_namespace(): "form.validity_state", "grid", "heading", + "hover_card", + "hover_card.content", + "hover_card.root", + "hover_card.trigger", "hstack", "icon_button", "input", @@ -179,6 +204,14 @@ def test_every_wave_is_in_the_namespace(): "list.ordered", "list.unordered", "list_item", + "menu.content", + "menu.item", + "menu.root", + "menu.separator", + "menu.sub", + "menu.sub_content", + "menu.sub_trigger", + "menu.trigger", "ordered_list", "popover.close", "popover.content", @@ -247,12 +280,16 @@ def test_every_wave_is_in_the_namespace(): "alert_dialog", "callout", "checkbox", + "context_menu", "data_list", "dialog", "drawer", + "dropdown_menu", "form", + "hover_card", "input", "list", + "menu", "popover", "radio", "radio_group", From cb99c67195bb26c4432caf70c89a41bc3d8c804d Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 28 Nov 2026 23:21:04 +0000 Subject: [PATCH 133/204] Follow the open look of a button in the declarations of the shared app The button the dialog wave gave a look for an open popup is declared with it in the memoized modules of the shared app. Claude-Session: https://claude.ai/code/session_014AwvTPAHZRxHNPUcCpxBsq --- .../tests_playwright/test_ui_components.py | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 88f193b2ad5..2634f8411ff 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -152,15 +152,16 @@ # each value, and the other is a plain solid button. ACTIONS_MEMO_DECLARATIONS = [ ( - 'const sx_8d448f3b8d = stylex.create({ s: {"marginTop": "0", "marginRight' + 'const sx_e93db4cb5c = stylex.create({ s: {"marginTop": "0", "marginRight' '": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0", "padd' 'ingRight": "var(--space-3)", "paddingBottom": "0", "paddingLeft": "var(-' '-space-3)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBotto' 'mWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderR' 'ightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "non' 'e", "backgroundColor": {"default": "var(--accent-9)", "@media (hover: ho' - 'ver)": {":hover:not(:active)": "var(--accent-10)"}, ":active:not([data-s' - 'tate=\'open\'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)"}' + 'ver)": {":hover:not(:active)": "var(--accent-10)"}, "[data-state=\'open\']' + '": "var(--accent-10)", ":active:not([data-state=\'open\'])": "var(--accent' + '-10)", "[data-disabled]": "var(--gray-a3)"}' ', "backgroundImage": "none", "appearance": "none", "boxSizing": "border-' 'box", "fontSize": "var(--font-size-2)", "lineHeight": "var(--line-height' '-2)", "letterSpacing": "var(--letter-spacing-2)", "fontWeight": "var(--f' @@ -195,21 +196,22 @@ 'se-button-height)", "--rx-icon-opacity": "0.9"}, a0_0: {"position": "rel' 'ative"} });' ), - ("const sx_8d448f3b8d_c = stylex.props(sx_8d448f3b8d.s).className;"), + ("const sx_e93db4cb5c_c = stylex.props(sx_e93db4cb5c.s).className;"), ( - 'const sx_8d448f3b8d_0 = { __proto__: null, "true": stylex.props(sx_8d448' - "f3b8d.a0_0).className };" + 'const sx_e93db4cb5c_0 = { __proto__: null, "true": stylex.props(sx_e93db' + "4cb5c.a0_0).className };" ), ( - 'const sx_6fb0976665 = stylex.create({ s: {"marginTop": "0", "marginRight' + 'const sx_f2580dfc68 = stylex.create({ s: {"marginTop": "0", "marginRight' '": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0", "padd' 'ingRight": "var(--space-3)", "paddingBottom": "0", "paddingLeft": "var(-' '-space-3)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBotto' 'mWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderR' 'ightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "non' 'e", "backgroundColor": {"default": "var(--accent-9)", "@media (hover: ho' - 'ver)": {":hover:not(:active)": "var(--accent-10)"}, ":active:not([data-s' - 'tate=\'open\'])": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)"}' + 'ver)": {":hover:not(:active)": "var(--accent-10)"}, "[data-state=\'open\']' + '": "var(--accent-10)", ":active:not([data-state=\'open\'])": "var(--accent' + '-10)", "[data-disabled]": "var(--gray-a3)"}' ', "backgroundImage": "none", "appearance": "none", "boxSizing": "border-' 'box", "fontSize": "var(--font-size-2)", "lineHeight": "var(--line-height' '-2)", "letterSpacing": "var(--letter-spacing-2)", "fontWeight": "var(--f' @@ -240,7 +242,7 @@ 'isible)": "0"}, ":focus-visible:not([data-disabled])": "2px"}, "height":' ' "var(--base-button-height)", "--rx-icon-opacity": "0.9"} });' ), - ("const sx_6fb0976665_c = stylex.props(sx_6fb0976665.s).className;"), + ("const sx_f2580dfc68_c = stylex.props(sx_f2580dfc68.s).className;"), ( 'const sx_21e3781dc3 = stylex.create({ s: {"boxSizing": "border-box", "fo' 'ntFamily": "var(--default-font-family)", "fontWeight": "var(--font-weigh' From 71e3fe20423310adfa6aebb9019b1fc3dffca639 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 00:37:43 +0000 Subject: [PATCH 134/204] Record what the overlays wave costs and settled, and format its scripts The README lists the size and the purpose of every behaviour script and their total against the 6 kB budget, what the overlays wave settled, what its ten components add to a page, the cost of opening a dialog and a menu against Radix, and the run time of the wave. A part of a matrix may be looked up in the page. The allowlist no longer explains a selection of the drawer's text that the drawer has as Radix's does. The menu's driver closes its menus without waiting a fixed time. Claude-Session: https://claude.ai/code/session_014AwvTPAHZRxHNPUcCpxBsq --- packages/reflex-components-ui/README.md | 102 ++++++++++++++++-- .../js/src/behaviors/hover.js | 4 +- .../js/src/behaviors/keys.js | 9 +- .../js/src/behaviors/menu.js | 13 ++- .../js/tests/behaviors/hover.test.js | 12 +-- .../js/tests/behaviors/menu.test.js | 8 +- .../parity/allowlist.toml | 7 -- .../ui_parity/components/dropdown_menu.py | 5 +- 8 files changed, 118 insertions(+), 42 deletions(-) diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index b1125f5d358..4ce2d46d533 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -530,14 +530,29 @@ reuse: placed by CSS anchor positioning, turned over by | script | minified and gzipped | what it does | | --- | --- | --- | -| `image-status.js` | 232 B | shows the fallback of an avatar whose image fails | -| `text-field.js` | 243 B | a press on the box of a text field focuses its input | -| `form-validity.js` | 684 B | shows the messages of a form that match the validity the browser computed | -| `roving-focus.js` | 411 B | the arrow keys of a segmented control | -| `slider.js` | 660 B | the filled part of the track, the order of several thumbs, a press on the track | -| `popup.js` | 762 B | says on a trigger that its popover is open, puts the popover on whole pixels before it is first drawn, and gives the popups of a loop their own ids | -| `popup-position.js` | 407 B | places a popover in a browser without anchor positioning; loaded only there | -| `listbox.js` | 1,536 B | the value of a select, the keys of its list, typing to find an option | +| `image-status.js` | 230 B | shows the fallback of an avatar whose image fails | +| `text-field.js` | 240 B | a press on the box of a text field focuses its input | +| `form-validity.js` | 698 B | shows the messages of a form that match the validity the browser computed | +| `roving-focus.js` | 500 B | the arrow keys of a segmented control and of the triggers of tabs | +| `slider.js` | 661 B | the filled part of the track, the order of several thumbs, a press on the track | +| `popup.js` | 1,218 B | says on a trigger that its popover is open, puts the popover on whole pixels before it is first drawn, gives the popups of a loop their own ids, follows a popup bound to state, moves the focus in and says what dismissed it | +| `popup-position.js` | 406 B | places a popover in a browser without anchor positioning; loaded only there | +| `keys.js` | 355 B | the arrow keys, Home, End and typing to find an item, for a select and a menu | +| `listbox.js` | 1,403 B | the value of a select and the keys of its list | +| `tabs.js` | 419 B | selects a tab on a press and on the focus | +| `accordion.js` | 323 B | keeps open the item of an accordion that does not collapse, says which items are open, follows the state | +| `dialog.js` | 741 B | opens a modal dialog from its trigger, closes it from a button or beside its panel, its events and its state | +| `hover.js` | 945 B | opens a tooltip and a hover card under the pointer and with the focus, after their delays | +| `menu.js` | 1,632 B | the keys, the pointer and the choices of a menu, its sub-menus, its checkbox items, a context menu at the pointer | + +Together they are 9.8 kB, 9.4 kB without `popup-position.js`, over the 6 kB +the scripts were budgeted. A page loads only the ones of its components: one +with the ten components of the overlays wave loads `popup.js`, `keys.js`, +`dialog.js`, `hover.js`, `menu.js`, `tabs.js`, `roving-focus.js` and +`accordion.js`, 6.1 kB apart. What could go, each at a cost to the +behaviour of Radix: typing to find an item of a menu (most of `keys.js`), +the rest of the pointer on a sub-menu before it opens, and the events a +popup raises when it is dismissed and how (`popupEvent`). What the form controls wave settled: @@ -577,6 +592,53 @@ What the form controls wave settled: it: a popup that meets the edge of the viewport is moved by Radix and turned over by CSS, which is the browser's business, not a cell's. +What the overlays wave settled: + +- **A popup is the browser's.** A dialog, an alert dialog and a drawer are + a native modal `dialog` (`components/_dialog.py`, `behaviors/dialog.js`): + the browser puts it in the top layer, makes the page behind it inert, + moves the focus in and gives it back. A popover, a tooltip, a hover card + and a menu are a native `popover` (`components/_popup.py`): the browser + closes the topmost one on Escape and on a press outside it, and a popup + opened from inside another is nested in it. What opens a popup commands + it (`popovertarget`, `commandfor`), so a dialog, a popover and the menu of + a dropdown open and close with JavaScript off. +- **The parts of a popup find each other while compiling.** A root renders + nothing: it finds its parts below it (`PopupRoot`, as `GroupRoot` does + for a group) and gives each the id of its popup, whether it is bound to + state and its events. The popups a loop renders share that id; the first + sync of each gives it one of its own (`pair` in `popup.js`). What a popup + holds is in the server render and keeps its state between two openings, + where Radix renders it when it opens. +- **A popup is placed by CSS**, `placement()` in `styles/popup.py`: its + anchor, a margin on the side that faces it, and on the side away from it + the 10 pixels Radix keeps from the edge of the viewport, so that it turns + over where Radix turns over. It is fixed, in the top layer, and no larger + than the room the viewport leaves, where Radix moves a wrapper by a + transform and lets a long popup grow past the page: the allowlist says so + of `position`, the margins and the bounds of each popup. +- **What Radix renders in a portal is compared in the page.** A part of a + matrix may be `in_page(selector)`, looked up in the whole page rather + than in the frame: a cell that opens a popup is driven alone, one system + at a time. Every popup of the wave names its parts so (overlay, panel, + title, description, close button, items, separator, sub-menu): that + found a modal dialog selecting its text, a popover without the outline + of Radix, and the text color of a tooltip. +- **A menu hands its items its look while compiling.** The content finds + its items, its sub-menus' included, and gives them its variant and its + contrast as private variants, and itself whether it has checkbox items; + the sizes reach the items as the custom properties Radix Themes names + (`--base-menu-item-height`...). An item is highlighted while it has the + focus, which the script moves with the pointer and the keys, as Radix + does. A sub-menu is a popover nested in its menu: Escape closes the + topmost one alone, as the WAI-ARIA menu pattern says, where Radix closes + the whole menu. A context menu opens at an element of no size that its + script moves to the pointer, and that the menu is anchored to. +- **A script is shared rather than repeated.** `keys.js` holds the arrow + keys, Home, End and typing to find an item, for the select and the menus; + `popup.js` what every popup does when it opens and closes; `hover.js` + the delays of a tooltip and a hover card. + ### What a wave adds to a page Gzipped (`gzip -9` of each file under `.web/build/client`), for an app whose @@ -589,6 +651,7 @@ only plugin is `UIPlugin()`, against the same page without the components: | a button with a `radius` | +621 B | +1,031 B | one shared chunk of 287 B | | the 12 components of wave 2, one accent | +3,374 B | +5,295 B | Lucide's icon chunk (783 B), as `rx.icon` alone adds | | the 13 form controls of wave 3, one accent | +11,326 B | +10,639 B | one chunk of 404 B, `popup-position.js`, that a browser with anchor positioning never loads | +| the 10 overlays of wave 4, one accent | +10,758 B | +5,991 B | none: the scripts are in the page's own chunk (9,998 B), and the shared chunks gain 1,003 B | The page without components is 146,124 B of JavaScript and 6,109 B of CSS, 4.6 kB of it the theme. The script of an avatar is 231 B of the page's own @@ -613,6 +676,19 @@ after an option has the focus): The page of that `rx.select` loads 192,201 B of JavaScript and 88,099 B of CSS, the one of `rx.ui.select` 151,165 B and 8,581 B. +The overlays were measured against a page that is 146,038 B of JavaScript +and 6,621 B of CSS; the same ten components of Radix add 42,701 B of +JavaScript to a page that already loads 176,596 B of it and 82,431 B of +CSS. Opening a dialog with Enter on its trigger, and a dropdown menu of 20 +items with Enter, to two frames after it is shown with the focus inside: + +| | main thread | of it script | at a CPU four times slower | +| --- | --- | --- | --- | +| `rx.dialog` | 42.8 ms | 13.0 ms | 163.5 ms | +| `rx.ui.dialog` | 27.7 ms | 2.5 ms | 107.2 ms | +| `rx.dropdown_menu` | 57.6 ms | 23.8 ms | 278.0 ms | +| `rx.ui.dropdown_menu` | 33.1 ms | 2.7 ms | 137.4 ms | + ## Themes and tokens The plugin takes the theme of the app. Every option has the values and, the @@ -872,7 +948,9 @@ registers it. `base@dark@hover`. `target` and `parts` name the elements whose computed style is read when it is not the first element (a part is one selector, or one for each system, and may end in `::before` or `::after` where one - system draws with a pseudo-element what the other has an element for), `stage` sizes the frame, + system draws with a pseudo-element what the other has an element for, or + be `in_page(...)`, looked up in the whole page, for a popup Radix renders + in a portal), `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`. `ready` is a JavaScript expression a page must meet before @@ -952,6 +1030,12 @@ appearance) about 0.3 s. Keep interactive states to a sweep or a small group. | 1: layout and typography | 19, and `text.kbd` | 1011, 44 of them interactive | 27 s + 61 s | | 2: display and actions | 12 | 1379, 181 of them interactive | 56 s + 178 s for both waves, 115 s of it this one | | 3: form controls | 13 | 1514, 318 of them interactive | 115 s + 403 s for the three waves, 177 s of it this one | +| 4: overlays | 10 | 458, 283 of them interactive | 135 s + 834 s for the four waves, 182 s of it this one | + +The fourth row was measured on a slower container than the three before it: +the matrices of the first three waves take 652 s there, against 403 s, and +the whole run, 969 s, is over the budget of 900 s. Firefox and WebKit could +not be run there. ## Rules the tooling enforces diff --git a/packages/reflex-components-ui/js/src/behaviors/hover.js b/packages/reflex-components-ui/js/src/behaviors/hover.js index 86cd65f9d0c..71993214ae9 100644 --- a/packages/reflex-components-ui/js/src/behaviors/hover.js +++ b/packages/reflex-components-ui/js/src/behaviors/hover.js @@ -113,9 +113,7 @@ export function hoverSync(popup, open, on) { popups.set(popup, (state = {})); const trigger = triggerOf(popup); if (trigger) { - const id = popup.id.startsWith("rx-") - ? `${popup.id}-${++ids}` - : popup.id; + const id = popup.id.startsWith("rx-") ? `${popup.id}-${++ids}` : popup.id; if (trigger.getAttribute("aria-describedby") === popup.id) trigger.setAttribute("aria-describedby", id); trigger.dataset.rxHover = popup.id = id; diff --git a/packages/reflex-components-ui/js/src/behaviors/keys.js b/packages/reflex-components-ui/js/src/behaviors/keys.js index 6de87b6a5b0..5cf6d8c9405 100644 --- a/packages/reflex-components-ui/js/src/behaviors/keys.js +++ b/packages/reflex-components-ui/js/src/behaviors/keys.js @@ -38,7 +38,8 @@ export function find(items, key, from, textOf) { const search = repeated ? typed[0] : typed; const starts = (/** @type {Element} */ item) => textOf(item).trim().toLowerCase().startsWith(search); - if (!repeated && from && starts(from)) return /** @type {HTMLElement} */ (from); + if (!repeated && from && starts(from)) + return /** @type {HTMLElement} */ (from); const start = items.indexOf(/** @type {HTMLElement} */ (from)); return [...items.slice(start + 1), ...items.slice(0, start + 1)].find(starts); } @@ -57,8 +58,8 @@ export function move(items, key, at, loop = false) { const last = items.length - 1; if (key === "Home") return items[0]; if (key === "End") return items[last]; - if (key === "ArrowDown") - return items[at < last ? at + 1 : loop ? 0 : last]; - if (key === "ArrowUp") return items[at > 0 ? at - 1 : loop || at < 0 ? last : 0]; + if (key === "ArrowDown") return items[at < last ? at + 1 : loop ? 0 : last]; + if (key === "ArrowUp") + return items[at > 0 ? at - 1 : loop || at < 0 ? last : 0]; return null; } diff --git a/packages/reflex-components-ui/js/src/behaviors/menu.js b/packages/reflex-components-ui/js/src/behaviors/menu.js index 443e01052b1..9cff09805ab 100644 --- a/packages/reflex-components-ui/js/src/behaviors/menu.js +++ b/packages/reflex-components-ui/js/src/behaviors/menu.js @@ -72,9 +72,9 @@ function rootOf(menu) { * @returns {HTMLElement[]} Each open sub-menu, outermost first. */ function openSubs(menu) { - return /** @type {HTMLElement[]} */ ([ - ...menu.querySelectorAll(MENU), - ]).filter((sub) => sub.matches(":popover-open")); + return /** @type {HTMLElement[]} */ ([...menu.querySelectorAll(MENU)]).filter( + (sub) => sub.matches(":popover-open"), + ); } /** @@ -177,7 +177,8 @@ export function menuTrigger(event) { menu.dataset.rxKeyboard = "true"; if (key === "ArrowDown") { event.preventDefault(); - if (!menu.matches(":popover-open")) /** @type {HTMLElement} */ (trigger).click(); + if (!menu.matches(":popover-open")) + /** @type {HTMLElement} */ (trigger).click(); } } @@ -319,7 +320,9 @@ export function menuEvent(event, on) { (openSubs(menu).pop() ?? menu).dataset.rxClosedBy = "escape"; return; } - const at = items.indexOf(/** @type {HTMLElement} */ (document.activeElement)); + const at = items.indexOf( + /** @type {HTMLElement} */ (document.activeElement), + ); const focused = items[at]; const letter = key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey; diff --git a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js index 9f141dbae79..d5d3ea5e9d0 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js @@ -93,13 +93,7 @@ test("the first sync names each pair of a loop apart, for the browser to place t trigger.getAttribute("aria-describedby"), trigger.style.getPropertyValue("anchor-name"), popup.style.getPropertyValue("position-anchor"), - ]).toEqual([ - "rx-tip-1", - "rx-tip-1", - "rx-tip-1", - "--rx-tip-1", - "--rx-tip-1", - ]); + ]).toEqual(["rx-tip-1", "rx-tip-1", "rx-tip-1", "--rx-tip-1", "--rx-tip-1"]); expect([ second.id, document.getElementById("copy")?.dataset.rxHover, @@ -268,6 +262,8 @@ test("a browser without anchor positioning has the popup placed by a script", as api.hoverSync(popup); send("pointerenter"); vi.advanceTimersByTime(200); - await vi.waitFor(() => expect(place.mock.calls).toEqual([[popup, trigger, true]])); + await vi.waitFor(() => + expect(place.mock.calls).toEqual([[popup, trigger, true]]), + ); vi.doUnmock("$/reflex-ui/behaviors/popup-position.js"); }); diff --git a/packages/reflex-components-ui/js/tests/behaviors/menu.test.js b/packages/reflex-components-ui/js/tests/behaviors/menu.test.js index 90398d92328..7a33e6b51c1 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/menu.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/menu.test.js @@ -313,10 +313,10 @@ test("the right arrow and Enter open a sub-menu on its first item, and the left expect(focused()).toBe("move"); // Escape is for the topmost menu. press("Escape"); - expect([ - $("sub").dataset.rxClosedBy, - $("opts").dataset.rxClosedBy, - ]).toEqual(["escape", undefined]); + expect([$("sub").dataset.rxClosedBy, $("opts").dataset.rxClosedBy]).toEqual([ + "escape", + undefined, + ]); $("sub").hidePopover(); expect(focused()).toBe("more"); press("ArrowLeft"); diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 66e2499eafc..d3a18566635 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -532,13 +532,6 @@ cells = "long-true@open" properties = ["height"] reason = "A hover card taller than the page grows past the bottom of the page in rx.hover_card. rx.ui.hover_card is no taller than the room the viewport leaves, and scrolls what it holds." -[[look]] -component = "drawer" -check = "style" -cells = "*@open" -properties = ["user-select"] -reason = "The panel of rx.drawer cannot have its text selected, as it is dragged by any point of it. rx.ui.drawer is not dragged, and the text of its panel is selected as any other." - [[look]] component = "drawer" check = "style" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py index 765743636d9..6ee62a84c41 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py @@ -184,9 +184,10 @@ def close_menu(page: Page, target: Locator, point: Point) -> None: point: The middle of the trigger. """ page.mouse.move(1, 1) - while page.evaluate(f"document.querySelectorAll('{SHOWN}').length"): + # Radix closes every menu on Escape, rx.ui the topmost one. + for _ in range(page.evaluate(f"document.querySelectorAll('{SHOWN}').length")): page.keyboard.press("Escape") - page.wait_for_timeout(50) + _wait(page, 0) page.evaluate("document.activeElement.blur()") From b12cb6994d640f3b9c8c50396d5b854fc8e017a8 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 00:45:01 +0000 Subject: [PATCH 135/204] Check what a menu says exactly, and keep a change off a menu's radio group A contract step of the dropdown menu compares what the menu said in full, and its unit test the whole props of the content and the item. A radio group of a context menu no longer hears a change inside it, which in Radix comes from its items alone. Claude-Session: https://claude.ai/code/session_014AwvTPAHZRxHNPUcCpxBsq --- .../js/src/behaviors/menu.js | 5 ++--- .../ui_parity/components/dropdown_menu.py | 4 +--- .../reflex_components_ui/components/_menu.py | 9 +++++++-- .../components/test_context_menu.py | 20 ++++++++++++++++++- .../components/test_dropdown_menu.py | 6 ++++-- 5 files changed, 33 insertions(+), 11 deletions(-) diff --git a/packages/reflex-components-ui/js/src/behaviors/menu.js b/packages/reflex-components-ui/js/src/behaviors/menu.js index 9cff09805ab..906c17ca062 100644 --- a/packages/reflex-components-ui/js/src/behaviors/menu.js +++ b/packages/reflex-components-ui/js/src/behaviors/menu.js @@ -153,14 +153,13 @@ export function menuSync(menu, open) { } /** - * Follow the keys and the pointer on what opens a dropdown menu: its - * `onKeyDown` and `onPointerDown`. + * Follow the keys on what opens a dropdown menu: its `onKeyDown`. * * Enter, Space and the down arrow open the menu with the focus on its * first item; the down arrow does what a press does. * * @param {{ type: string, key?: string, currentTarget: Element, preventDefault: () => void }} event - * The key or the pointer going down. + * The key going down. * @returns {void} */ export function menuTrigger(event) { diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py index 6ee62a84c41..48270130029 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py @@ -523,9 +523,7 @@ def _sub_escape(run: Run) -> None: page.keyboard.press("Enter") _shown(run) _focus(run, "options") - wait_for_value( - page, "document.getElementById('seen').textContent.includes('move')", True - ) + wait_for_text(page, "seen", '["open","move","closed","close-focus"]') @CONTRACT.step("the pointer opens a sub-menu, and leaves it for another item") diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py index 6da7987e831..304f2d6429e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py @@ -417,9 +417,14 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: props: The props to render (if None, then use get_props). Returns: - The tag: a group, to assistive technology. + The tag: a group, to assistive technology. A value it changes is + the business of its items, so a change inside it says nothing. """ - return super()._render(props).add_props(role="group") + tag = super()._render(props) + rendered = { + name: value for name, value in tag.props.items() if name != "onChange" + } + return tag.set(props=rendered).add_props(role="group") class MenuSeparator(UIComponent): diff --git a/tests/units/reflex_components_ui/components/test_context_menu.py b/tests/units/reflex_components_ui/components/test_context_menu.py index 60663633c96..67dcfd1e7f3 100644 --- a/tests/units/reflex_components_ui/components/test_context_menu.py +++ b/tests/units/reflex_components_ui/components/test_context_menu.py @@ -480,9 +480,19 @@ def test_context_menu( class GridState(rx.State): - """What a checkbox item is bound to.""" + """What a checkbox item and a radio group are bound to.""" grid: bool = True + unit: str = "a" + + @rx.event + def set_unit(self, unit: str): + """Follow the group. + + Args: + unit: The value of the group. + """ + self.unit = unit @rx.event def set_grid(self, grid: bool): @@ -517,3 +527,11 @@ def test_context_menu_checkbox_bound_to_state(ui_plugin: UIPlugin): def test_context_menu_radio_is_a_radio_group(ui_plugin: UIPlugin): """rx.ui.context_menu.radio is a group of radio buttons from its items, as rx.context_menu.radio is.""" assert isinstance(rx.ui.context_menu.radio(["a", "b"]), RadioGroupRoot) + + +def test_context_menu_radio_group_hears_no_change_of_its_own(ui_plugin: UIPlugin): + """A radio group of a menu is a group to assistive technology, and its change is the business of its items, as in Radix.""" + group = rx.ui.context_menu.radio_group( + rx.el.input(type="checkbox"), value=GridState.unit, on_change=GridState.set_unit + ) + assert group.render()["props"] == ['role:"group"'] diff --git a/tests/units/reflex_components_ui/components/test_dropdown_menu.py b/tests/units/reflex_components_ui/components/test_dropdown_menu.py index 39ed1c67e78..dec7bddfd11 100644 --- a/tests/units/reflex_components_ui/components/test_dropdown_menu.py +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -433,7 +433,8 @@ def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): f'((...args) => (addEvents([(ReflexEvent("{name}.escaped", ({{ }}), ' "({ })))], args, ({ })))) })" ) - assert content["props"][1:] == [ + assert content["props"] == [ + "className:sx_2c641f6169_c", '"data-rx-popup":""', 'id:"rx-dropdown-menu-1"', "onBeforeToggle:popupBeforeToggle", @@ -449,7 +450,8 @@ def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): "tabIndex:-1", ] item = content["children"][0]["children"][0]["children"][0] - assert item["props"][1:] == [ + assert item["props"] == [ + "className:sx_85bc40da55_c", ( f'onClick:((...args) => (addEvents([(ReflexEvent("{name}.escaped", ' "({ }), ({ })))], args, ({ }))))" From 175dd5032de7de3978fd8d62e01602c64272ec8a Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 00:52:40 +0000 Subject: [PATCH 136/204] Start an app in the appearance its rx.ui theme pins The compiler read the default color mode from the Radix theme alone, so UIPlugin(theme=rx.ui.Theme(appearance="dark")) pinned the page dark while the color mode, and what follows it, started as default_color_mode said. Claude-Session: https://claude.ai/code/session_014AwvTPs6inbXdhsoua28g1 --- news/+ui-theme-default-color-mode.bugfix.md | 1 + packages/reflex-components-ui/README.md | 5 ++- reflex/compiler/compiler.py | 20 ++++++++-- tests/units/compiler/test_compiler.py | 42 +++++++++++++++++++-- 4 files changed, 60 insertions(+), 8 deletions(-) create mode 100644 news/+ui-theme-default-color-mode.bugfix.md diff --git a/news/+ui-theme-default-color-mode.bugfix.md b/news/+ui-theme-default-color-mode.bugfix.md new file mode 100644 index 00000000000..0091d3ca465 --- /dev/null +++ b/news/+ui-theme-default-color-mode.bugfix.md @@ -0,0 +1 @@ +An app whose `rx.plugins.UIPlugin(theme=rx.ui.Theme(appearance="dark"))` pins its appearance now starts in that color mode, as one with `rx.theme(appearance=...)` does; an explicit appearance of the Radix theme still wins. diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 4ce2d46d533..61850365b3a 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -775,8 +775,9 @@ rx.ui.theme(preview(), accent_color=Settings.accent) 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. +- The appearance of the theme of the app pins the page to it, and is the + color mode the app starts in, over `default_color_mode`, unless the theme + of Radix Themes names an appearance of its own. - 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 diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index a0ba102c6bf..9689a36cbcd 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -260,8 +260,9 @@ def _resolve_default_color_mode(theme: Component | None) -> str: """Resolve the app's compile-time default color mode. An explicit theme appearance ("light"/"dark") takes precedence over the - ``Config.default_color_mode`` option; "inherit", no appearance, or a - non-literal appearance Var falls back to the config value. + ``Config.default_color_mode`` option, the one of the Radix theme over the + one of the rx.ui theme of a configured ``UIPlugin``; "inherit", no + appearance, or a non-literal appearance Var falls back to the config value. Args: theme: The top-level app theme, if any. @@ -269,6 +270,7 @@ def _resolve_default_color_mode(theme: Component | None) -> str: Returns: One of "system", "light", or "dark". """ + config = get_config() appearance = getattr(theme, "appearance", None) if appearance is not None: appearance_var = LiteralVar.create(appearance) @@ -277,7 +279,17 @@ def _resolve_default_color_mode(theme: Component | None) -> str: and appearance_var._var_value != "inherit" ): return appearance_var._var_value - return get_config().default_color_mode + # A configured UIPlugin has imported its module, which is an optional extra: + # without it in sys.modules no plugin of the config can be one. + ui_plugin_module = sys.modules.get("reflex_components_ui.plugin") + if ui_plugin_module is not None: + ui_plugin: type[UIPlugin] = ui_plugin_module.UIPlugin + for plugin in config.plugins: + if isinstance(plugin, ui_plugin): + if plugin.theme.appearance != "inherit": + return plugin.theme.appearance + break + return config.default_color_mode def _compile_contexts( @@ -929,6 +941,8 @@ def purge_web_pages_dir(): if TYPE_CHECKING: + from reflex_components_ui.plugin import UIPlugin + from reflex.app import App, ComponentCallable, UnevaluatedPage diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 8d256a1a757..4dac65e13b6 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -5,8 +5,9 @@ import re import shutil import sys +from collections.abc import Sequence from pathlib import Path, PureWindowsPath -from typing import Any +from typing import Any, Literal import pytest from pytest_mock import MockerFixture @@ -22,7 +23,7 @@ from reflex_base.constants.base import LiteralColorMode from reflex_base.constants.compiler import PageNames from reflex_base.environment import environment -from reflex_base.plugins import CompileContext, CompilerHooks, PageContext +from reflex_base.plugins import CompileContext, CompilerHooks, PageContext, Plugin from reflex_base.plugins.sitemap import SitemapPlugin from reflex_base.registry import RegistrationContext from reflex_base.utils import memo_paths @@ -39,6 +40,7 @@ from reflex_components_core.base.document import Links, Scripts from reflex_components_core.el.elements.metadata import Head, Link, Meta from reflex_components_core.el.elements.other import Html +from reflex_components_ui.plugin import UIPlugin import reflex as rx from reflex.app import default_backend_exception_handler @@ -1046,7 +1048,9 @@ def index() -> rx.Component: assert compile_libraries.call_args == mocker.call(dynamic_components=dynamic) -def _mock_config_color_mode(mocker: MockerFixture, mode: LiteralColorMode) -> None: +def _mock_config_color_mode( + mocker: MockerFixture, mode: LiteralColorMode, plugins: Sequence[Plugin] = () +) -> None: """Point the compiler's get_config at a fresh config with the given mode. Builds a standalone Config rather than mutating the shared singleton so the @@ -1055,10 +1059,12 @@ def _mock_config_color_mode(mocker: MockerFixture, mode: LiteralColorMode) -> No Args: mocker: Pytest mocker fixture. mode: The default color mode to configure. + plugins: The plugins of the config. """ config = rx.Config( app_name="test_default_color_mode", default_color_mode=mode, + plugins=list(plugins), _skip_plugins_checks=True, ) mocker.patch("reflex.compiler.compiler.get_config", return_value=config) @@ -1142,6 +1148,36 @@ def test_resolve_default_color_mode( assert compiler._resolve_default_color_mode(theme) == expected +@pytest.mark.parametrize( + ("theme", "ui_appearance", "expected"), + [ + # Without a Radix theme, the appearance of the rx.ui theme pins the mode. + (None, "dark", "dark"), + (None, "light", "light"), + (None, "inherit", "system"), + # A Radix theme that inherits leaves it to the rx.ui theme. + (rx.theme(appearance="inherit"), "dark", "dark"), + (rx.theme(), "light", "light"), + # An explicit Radix appearance wins. + (rx.theme(appearance="light"), "dark", "light"), + ], +) +def test_resolve_default_color_mode_reads_the_ui_theme( + theme: Component | None, + ui_appearance: Literal["inherit", "light", "dark"], + expected: str, + mocker: MockerFixture, +): + """The appearance of the UIPlugin theme sets the default color mode.""" + _mock_config_color_mode( + mocker, + "system", + [UIPlugin(theme=rx.ui.Theme(appearance=ui_appearance))], + ) + + assert compiler._resolve_default_color_mode(theme) == expected + + @pytest.mark.parametrize("mode", ["system", "light", "dark"]) def test_preload_color_theme_uses_default(mode: str): """The preload script falls back to the given default when no theme is saved.""" From 3bb91358c85b297aa7a2ee82f010c5b30cbcc3cd Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 01:01:16 +0000 Subject: [PATCH 137/204] Add the page-weight apps and measure them with reflex-bench examples/pages holds a blank app from the default template, a stateless and a stateful rx.el app, a one-button rx.ui page and a kitchen sink written once for rx and once for rx.ui; PAGES_APP picks one. size.export measures each, with the JavaScript and CSS gzip sums, the JS file count, the scripts that mention Emotion and the build time, and lighthouse.mobile audits each first page with simulated and devtools throttling. Budgets record the value each limit came from, take max or min, and may be reported without being enforced. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- .gitignore | 1 + .pre-commit-config.yaml | 4 +- examples/pages/.content-hash | 1 + examples/pages/.gitignore | 12 + examples/pages/blank/__init__.py | 1 + examples/pages/blank/blank.py | 36 ++ examples/pages/el_stateful/__init__.py | 1 + examples/pages/el_stateful/el_stateful.py | 49 +++ examples/pages/el_stateless/__init__.py | 1 + examples/pages/el_stateless/el_stateless.py | 12 + examples/pages/elements.py | 65 +++ examples/pages/kitchen_sink.py | 389 ++++++++++++++++++ examples/pages/kitchen_sink_rx/__init__.py | 1 + .../pages/kitchen_sink_rx/kitchen_sink_rx.py | 8 + examples/pages/kitchen_sink_ui/__init__.py | 1 + .../pages/kitchen_sink_ui/kitchen_sink_ui.py | 8 + examples/pages/pyproject.toml | 9 + examples/pages/rxconfig.py | 47 +++ examples/pages/ui_button/__init__.py | 1 + examples/pages/ui_button/ui_button.py | 6 + examples/ruff.toml | 2 + .../reflex-bench/src/reflex_bench/budgets.py | 279 ++++++++++--- packages/reflex-bench/src/reflex_bench/cli.py | 2 +- .../src/reflex_bench/drivers/lighthouse.py | 180 ++++++++ .../reflex-bench/src/reflex_bench/registry.py | 24 +- .../src/reflex_bench/scheduler.py | 2 +- .../src/reflex_bench/suites/lighthouse.py | 120 ++++++ .../src/reflex_bench/suites/size.py | 114 ++++- scripts/hash_examples.py | 50 ++- tests/units/test_hash_examples.py | 3 +- 30 files changed, 1326 insertions(+), 103 deletions(-) create mode 100644 examples/pages/.content-hash create mode 100644 examples/pages/.gitignore create mode 100644 examples/pages/blank/__init__.py create mode 100644 examples/pages/blank/blank.py create mode 100644 examples/pages/el_stateful/__init__.py create mode 100644 examples/pages/el_stateful/el_stateful.py create mode 100644 examples/pages/el_stateless/__init__.py create mode 100644 examples/pages/el_stateless/el_stateless.py create mode 100644 examples/pages/elements.py create mode 100644 examples/pages/kitchen_sink.py create mode 100644 examples/pages/kitchen_sink_rx/__init__.py create mode 100644 examples/pages/kitchen_sink_rx/kitchen_sink_rx.py create mode 100644 examples/pages/kitchen_sink_ui/__init__.py create mode 100644 examples/pages/kitchen_sink_ui/kitchen_sink_ui.py create mode 100644 examples/pages/pyproject.toml create mode 100644 examples/pages/rxconfig.py create mode 100644 examples/pages/ui_button/__init__.py create mode 100644 examples/pages/ui_button/ui_button.py create mode 100644 packages/reflex-bench/src/reflex_bench/drivers/lighthouse.py create mode 100644 packages/reflex-bench/src/reflex_bench/suites/lighthouse.py diff --git a/.gitignore b/.gitignore index 2a8220b8fd5..31c877ef4e6 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ examples/* !examples/README.md !examples/ruff.toml !examples/playground/ +!examples/pages/ .web .states .idea diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 16a30bc9b1b..f30188b71b4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -36,10 +36,10 @@ repos: hooks: - id: hash-examples name: hash-examples - description: Update the examples/playground content hash as needed + description: Update the content hashes of the benchmarked examples as needed entry: uv run --no-sync python scripts/hash_examples.py language: system - files: ^(examples/playground/|scripts/hash_examples\.py$) + files: ^(examples/(playground|pages)/|scripts/hash_examples\.py$) pass_filenames: false require_serial: true - repo: local diff --git a/examples/pages/.content-hash b/examples/pages/.content-hash new file mode 100644 index 00000000000..e0db35795e3 --- /dev/null +++ b/examples/pages/.content-hash @@ -0,0 +1 @@ +sha256:617867446475dea546f815279047aedc54f453dac25be8555c7174a1617959c5 diff --git a/examples/pages/.gitignore b/examples/pages/.gitignore new file mode 100644 index 00000000000..71ae39d39eb --- /dev/null +++ b/examples/pages/.gitignore @@ -0,0 +1,12 @@ +# The entries `reflex init` adds, so running the app leaves this file unchanged. +*.db +*.py[cod] +.states +.web +__pycache__/ +assets/external/ +# The playground runs against several reflex versions, so it commits no lock files. +reflex.lock/ +uv.lock +.venv/ +uploaded_files/ diff --git a/examples/pages/blank/__init__.py b/examples/pages/blank/__init__.py new file mode 100644 index 00000000000..f605cbd6886 --- /dev/null +++ b/examples/pages/blank/__init__.py @@ -0,0 +1 @@ +"""The blank app of the page-weight benchmarks.""" diff --git a/examples/pages/blank/blank.py b/examples/pages/blank/blank.py new file mode 100644 index 00000000000..4d7059db546 --- /dev/null +++ b/examples/pages/blank/blank.py @@ -0,0 +1,36 @@ +"""Welcome to Reflex! This file outlines the steps to create a basic app.""" + +import reflex as rx + +from rxconfig import config + + +class State(rx.State): + """The app state.""" + + +def index() -> rx.Component: + # Welcome Page (Index) + return rx.container( + rx.color_mode.button(position="top-right"), + rx.vstack( + rx.heading("Welcome to Reflex!", size="9"), + rx.text( + "Get started by editing ", + rx.code(f"{config.app_name}/{config.app_name}.py"), + size="5", + ), + rx.link( + rx.button("Check out our docs!"), + href="https://reflex.dev/docs/getting-started/introduction/", + is_external=True, + ), + spacing="5", + justify="center", + min_height="85vh", + ), + ) + + +app = rx.App() +app.add_page(index) diff --git a/examples/pages/el_stateful/__init__.py b/examples/pages/el_stateful/__init__.py new file mode 100644 index 00000000000..60bf3964550 --- /dev/null +++ b/examples/pages/el_stateful/__init__.py @@ -0,0 +1 @@ +"""The el_stateful app of the page-weight benchmarks.""" diff --git a/examples/pages/el_stateful/el_stateful.py b/examples/pages/el_stateful/el_stateful.py new file mode 100644 index 00000000000..a99fa746d6a --- /dev/null +++ b/examples/pages/el_stateful/el_stateful.py @@ -0,0 +1,49 @@ +"""A stateful app of plain elements that sends no toast.""" + +import reflex as rx + +import elements + + +class SignupState(rx.State): + """A sign-up form and the count of sign-ups.""" + + email: str = "" + signups: int = 0 + + @rx.event + def set_email(self, value: str): + """Keep what was typed. + + Args: + value: The email address. + """ + self.email = value + + @rx.event + def sign_up(self): + """Count a sign-up and clear the field.""" + self.signups += 1 + self.email = "" + + +def index() -> rx.Component: + """The landing page with a sign-up form. + + Returns: + The page. + """ + return elements.landing( + rx.el.input( + value=SignupState.email, + on_change=SignupState.set_email, + placeholder="you@example.com", + type="email", + ), + rx.el.button("Sign up", on_click=SignupState.sign_up), + rx.el.p(SignupState.signups, " people signed up"), + ) + + +app = rx.App() +app.add_page(index, route="/", title="Acme") diff --git a/examples/pages/el_stateless/__init__.py b/examples/pages/el_stateless/__init__.py new file mode 100644 index 00000000000..f6a54d2ead0 --- /dev/null +++ b/examples/pages/el_stateless/__init__.py @@ -0,0 +1 @@ +"""The el_stateless app of the page-weight benchmarks.""" diff --git a/examples/pages/el_stateless/el_stateless.py b/examples/pages/el_stateless/el_stateless.py new file mode 100644 index 00000000000..872404d7325 --- /dev/null +++ b/examples/pages/el_stateless/el_stateless.py @@ -0,0 +1,12 @@ +"""A stateless app of plain elements: no state, no event, no theme.""" + +import reflex as rx + +import elements + +app = rx.App() +app.add_page( + lambda: elements.landing(rx.el.a("Get started", href="#docs")), + route="/", + title="Acme", +) diff --git a/examples/pages/elements.py b/examples/pages/elements.py new file mode 100644 index 00000000000..b63300da047 --- /dev/null +++ b/examples/pages/elements.py @@ -0,0 +1,65 @@ +"""The page of the apps of plain elements: a product landing page in `rx.el`.""" + +import reflex as rx + +FEATURES = ( + ("Fast", "Pages are prerendered and paint before any script runs."), + ("Typed", "Props, styles and events are checked when the app compiles."), + ("Small", "A page ships the code its components use, and nothing more."), +) +PLANS = (("Hobby", "$0", "One app, community support"), ("Team", "$20", "Ten apps")) + + +def landing(*actions: rx.Component) -> rx.Component: + """A landing page: header, hero, features, pricing and footer. + + Args: + *actions: What the hero holds under its text. + + Returns: + The page. + """ + return rx.el.div( + rx.el.header( + rx.el.nav( + rx.el.a("Acme", href="/", style={"fontWeight": "700"}), + rx.el.a("Docs", href="#docs"), + rx.el.a("Pricing", href="#pricing"), + style={"display": "flex", "gap": "24px", "padding": "16px 0"}, + ), + ), + rx.el.main( + rx.el.section( + rx.el.h1("Build web apps in pure Python", style={"fontSize": "48px"}), + rx.el.p( + "Acme turns a Python module into a fast, accessible web app. " + "No JavaScript to write, no build to configure." + ), + *actions, + ), + rx.el.section( + *( + rx.el.article(rx.el.h2(title), rx.el.p(text)) + for title, text in FEATURES + ), + id="docs", + style={"display": "grid", "gap": "16px"}, + ), + rx.el.section( + rx.el.table( + rx.el.thead( + rx.el.tr(rx.el.th("Plan"), rx.el.th("Price"), rx.el.th("Gets")) + ), + rx.el.tbody( + *( + rx.el.tr(rx.el.td(name), rx.el.td(price), rx.el.td(gets)) + for name, price, gets in PLANS + ) + ), + ), + id="pricing", + ), + ), + rx.el.footer(rx.el.p("© Acme. Made with Reflex.")), + style={"maxWidth": "960px", "margin": "0 auto", "fontFamily": "system-ui"}, + ) diff --git a/examples/pages/kitchen_sink.py b/examples/pages/kitchen_sink.py new file mode 100644 index 00000000000..56cd3066ab9 --- /dev/null +++ b/examples/pages/kitchen_sink.py @@ -0,0 +1,389 @@ +"""The kitchen sink: every component `rx` and `rx.ui` both have, in one accent. + +`page(rx)` renders it with the Radix components and `page(rx.ui)` with the +compiled ones: the props are the same, so the two apps differ by namespace only. +""" + +from typing import Any + +import reflex as rx + +MEMBERS = ( + ("Ada Lovelace", "ada@example.com", "Owner"), + ("Grace Hopper", "grace@example.com", "Admin"), + ("Alan Turing", "alan@example.com", "Member"), +) +PLANS = ("Hobby", "Team", "Enterprise") +NOTIFICATIONS = ("Comments", "Mentions", "Releases") + + +class SettingsState(rx.State): + """What the settings form keeps.""" + + name: str = "Acme" + saved: int = 0 + + @rx.event + def set_name(self, value: str): + """Keep the project's name. + + Args: + value: The name. + """ + self.name = value + + @rx.event + def save(self, form: dict[str, Any]): + """Count a save of the form. + + Args: + form: The form's data. + """ + self.saved += 1 + + +def _header(ns: Any) -> rx.Component: + """The page's header: title, member avatars and the menus. + + Args: + ns: `rx` or `rx.ui`. + + Returns: + The header. + """ + return ns.flex( + ns.hstack( + ns.heading("Acme settings", size="6"), + ns.badge("Beta"), + align="center", + ), + ns.spacer(), + ns.hstack( + *(ns.avatar(fallback=name[0], size="2") for name, _, _ in MEMBERS), + ns.dropdown_menu.root( + ns.dropdown_menu.trigger(ns.button("Project", variant="soft")), + ns.dropdown_menu.content( + ns.dropdown_menu.item("Rename", shortcut="⌘ R"), + ns.dropdown_menu.item("Duplicate", shortcut="⌘ D"), + ns.dropdown_menu.separator(), + ns.dropdown_menu.item("Archive"), + ), + ), + ns.tooltip(ns.icon_button("?", variant="ghost"), content="Help"), + align="center", + ), + align="center", + width="100%", + ) + + +def _general(ns: Any) -> rx.Component: + """The general settings: a form of every control. + + Args: + ns: `rx` or `rx.ui`. + + Returns: + The tab's content. + """ + return ns.form.root( + ns.vstack( + ns.form.field( + ns.form.label("Project name"), + ns.text_field( + value=SettingsState.name, + on_change=SettingsState.set_name, + name="name", + ), + ns.form.message("A name is required", match="valueMissing"), + name="name", + ), + ns.text("Description", as_="label", size="2", weight="bold"), + ns.text_area(placeholder="What the project is about", name="about"), + ns.text("Plan", size="2", weight="bold"), + ns.select.root( + ns.select.trigger(), + ns.select.content( + *(ns.select.item(plan, value=plan) for plan in PLANS) + ), + default_value="Team", + name="plan", + ), + ns.text("Visibility", size="2", weight="bold"), + ns.radio_group.root( + ns.radio_group.item("Private", value="private"), + ns.radio_group.item("Public", value="public"), + default_value="private", + name="visibility", + ), + ns.text("Region", size="2", weight="bold"), + ns.radio_cards.root( + ns.radio_cards.item("Europe", value="eu"), + ns.radio_cards.item("Americas", value="us"), + ns.radio_cards.item("Asia", value="ap"), + default_value="eu", + columns="3", + ), + ns.text("Theme", size="2", weight="bold"), + ns.segmented_control.root( + ns.segmented_control.item("Light", value="light"), + ns.segmented_control.item("Dark", value="dark"), + ns.segmented_control.item("System", value="system"), + default_value="system", + ), + ns.text("Notify me about", size="2", weight="bold"), + ns.checkbox_group.root( + *(ns.checkbox_group.item(name, value=name) for name in NOTIFICATIONS), + default_value=["Mentions"], + ), + ns.checkbox_cards.root( + ns.checkbox_cards.item("Email", value="email"), + ns.checkbox_cards.item("Slack", value="slack"), + default_value=["email"], + columns="2", + ), + ns.text("Daily digest at", size="2", weight="bold"), + ns.slider(default_value=[9], min=0, max=23), + ns.text( + ns.switch(default_checked=True, name="public_api"), + " Public API", + as_="label", + size="2", + ), + ns.text( + ns.checkbox(default_checked=True, name="terms"), + " I accept the terms", + as_="label", + size="2", + ), + ns.hstack( + ns.radio(["Monthly", "Yearly"], default_value="Yearly"), + ), + ns.form.submit(ns.button("Save changes")), + ns.text("Saved ", SettingsState.saved, " times", size="1", color="gray"), + align="stretch", + spacing="3", + ), + on_submit=SettingsState.save, + ) + + +def _members(ns: Any) -> rx.Component: + """The members: a table and a data list. + + Args: + ns: `rx` or `rx.ui`. + + Returns: + The tab's content. + """ + return ns.vstack( + ns.table.root( + ns.table.header( + ns.table.row( + ns.table.column_header_cell("Name"), + ns.table.column_header_cell("Email"), + ns.table.column_header_cell("Role"), + ) + ), + ns.table.body( + *( + ns.table.row( + ns.table.row_header_cell(name), + ns.table.cell(email), + ns.table.cell(ns.badge(role, variant="soft")), + ) + for name, email, role in MEMBERS + ) + ), + variant="surface", + width="100%", + ), + ns.data_list.root( + ns.data_list.item( + ns.data_list.label("Seats"), ns.data_list.value("3 of 10") + ), + ns.data_list.item( + ns.data_list.label("Billing"), + ns.data_list.value(ns.link("Manage", href="#billing")), + ), + ), + ns.progress(value=30), + width="100%", + ) + + +def _danger(ns: Any) -> rx.Component: + """The danger zone: dialogs, a drawer and the popups. + + Args: + ns: `rx` or `rx.ui`. + + Returns: + The tab's content. + """ + return ns.vstack( + ns.callout( + "Deleting a project cannot be undone.", + icon="triangle_alert", + ), + ns.hstack( + ns.alert_dialog.root( + ns.alert_dialog.trigger(ns.button("Delete project")), + ns.alert_dialog.content( + ns.alert_dialog.title("Delete Acme?"), + ns.alert_dialog.description("Its apps and data go with it."), + ns.flex( + ns.alert_dialog.cancel(ns.button("Cancel", variant="soft")), + ns.alert_dialog.action(ns.button("Delete")), + gap="3", + justify="end", + ), + ), + ), + ns.dialog.root( + ns.dialog.trigger(ns.button("Transfer", variant="outline")), + ns.dialog.content( + ns.dialog.title("Transfer the project"), + ns.dialog.description("Choose the new owner."), + ns.dialog.close(ns.button("Close", variant="soft")), + ), + ), + ns.drawer.root( + ns.drawer.trigger(ns.button("Activity", variant="outline")), + ns.drawer.overlay(), + ns.drawer.portal( + ns.drawer.content( + ns.drawer.title("Activity"), + ns.drawer.description("What changed this week."), + ns.drawer.close(ns.button("Close", variant="soft")), + ) + ), + direction="right", + ), + ns.popover.root( + ns.popover.trigger(ns.button("Share", variant="ghost")), + ns.popover.content(ns.text("Anyone with the link can view.")), + ), + wrap="wrap", + ), + ns.context_menu.root( + ns.context_menu.trigger( + ns.card(ns.text("Right-click for the project's actions")), + ), + ns.context_menu.content( + ns.context_menu.item("Copy link"), + ns.context_menu.item("Open in a new tab"), + ), + ), + ns.text( + "Owned by ", + ns.hover_card.root( + ns.hover_card.trigger(ns.link("Ada", href="#ada")), + ns.hover_card.content(ns.text("Ada Lovelace, owner since 2024")), + ), + ". Press ", + ns.text.kbd("Esc"), + " to close a dialog.", + ), + align="start", + width="100%", + ) + + +def _sidebar(ns: Any) -> rx.Component: + """The sidebar: an accordion of help and a scroll area of changes. + + Args: + ns: `rx` or `rx.ui`. + + Returns: + The sidebar. + """ + return ns.stack( + ns.card( + ns.inset( + ns.aspect_ratio( + ns.box(width="100%", height="100%", background="var(--accent-9)"), + ratio=16 / 9, + ), + side="top", + pb="current", + ), + ns.heading("Getting started", size="3"), + ns.skeleton(ns.text("Loading the guide"), loading=False), + ), + ns.accordion.root( + ns.accordion.item( + header="What is a project?", + content="A project holds apps, members and billing.", + value="project", + ), + ns.accordion.item( + header="Who can see it?", + content="Members, and everyone when it is public.", + value="visibility", + ), + collapsible=True, + type="single", + ), + ns.scroll_area( + ns.list.unordered( + items=[ + f"Release 1.{n}: fixes and improvements" for n in range(12, 0, -1) + ] + ), + type="auto", + scrollbars="vertical", + style={"height": "160px"}, + ), + ns.hstack(ns.spinner(), ns.text("Syncing", size="1"), align="center"), + direction="column", + spacing="4", + ) + + +def page(ns: Any) -> rx.Component: + """The settings page of a project. + + Args: + ns: `rx` or `rx.ui`. + + Returns: + The page. + """ + return ns.container( + ns.section( + _header(ns), + ns.separator(margin="16px 0"), + ns.grid( + ns.tabs.root( + ns.tabs.list( + ns.tabs.trigger("General", value="general"), + ns.tabs.trigger("Members", value="members"), + ns.tabs.trigger("Danger zone", value="danger"), + ), + ns.tabs.content( + ns.box(_general(ns), padding_top="12px"), value="general" + ), + ns.tabs.content( + ns.box(_members(ns), padding_top="12px"), value="members" + ), + ns.tabs.content( + ns.box(_danger(ns), padding_top="12px"), value="danger" + ), + default_value="general", + ), + _sidebar(ns), + columns=rx.breakpoints(initial="1", md="2"), + gap="6", + ), + ns.center( + ns.blockquote("Settings are saved per project."), + ns.code("acme.reflex.run"), + padding="4", + ), + size="2", + ), + size="3", + ) diff --git a/examples/pages/kitchen_sink_rx/__init__.py b/examples/pages/kitchen_sink_rx/__init__.py new file mode 100644 index 00000000000..528d3e253f1 --- /dev/null +++ b/examples/pages/kitchen_sink_rx/__init__.py @@ -0,0 +1 @@ +"""The kitchen_sink_rx app of the page-weight benchmarks.""" diff --git a/examples/pages/kitchen_sink_rx/kitchen_sink_rx.py b/examples/pages/kitchen_sink_rx/kitchen_sink_rx.py new file mode 100644 index 00000000000..80bdff7b369 --- /dev/null +++ b/examples/pages/kitchen_sink_rx/kitchen_sink_rx.py @@ -0,0 +1,8 @@ +"""The kitchen sink on the Radix components of `rx`.""" + +import reflex as rx + +import kitchen_sink + +app = rx.App() +app.add_page(lambda: kitchen_sink.page(rx), route="/", title="Acme settings") diff --git a/examples/pages/kitchen_sink_ui/__init__.py b/examples/pages/kitchen_sink_ui/__init__.py new file mode 100644 index 00000000000..f43c367ca4d --- /dev/null +++ b/examples/pages/kitchen_sink_ui/__init__.py @@ -0,0 +1 @@ +"""The kitchen_sink_ui app of the page-weight benchmarks.""" diff --git a/examples/pages/kitchen_sink_ui/kitchen_sink_ui.py b/examples/pages/kitchen_sink_ui/kitchen_sink_ui.py new file mode 100644 index 00000000000..f34a36e96a7 --- /dev/null +++ b/examples/pages/kitchen_sink_ui/kitchen_sink_ui.py @@ -0,0 +1,8 @@ +"""The kitchen sink on the compiled components of `rx.ui`.""" + +import reflex as rx + +import kitchen_sink + +app = rx.App() +app.add_page(lambda: kitchen_sink.page(rx.ui), route="/", title="Acme settings") diff --git a/examples/pages/pyproject.toml b/examples/pages/pyproject.toml new file mode 100644 index 00000000000..28b52521fb6 --- /dev/null +++ b/examples/pages/pyproject.toml @@ -0,0 +1,9 @@ +[project] +name = "reflex-pages" +version = "0.1.0" +description = "Reflex apps whose page weight and load the Reflex benchmarks track." +readme = "README.md" +requires-python = ">=3.11" +# PyPI rejects uploads carrying this classifier: the apps are never published. +classifiers = ["Private :: Do Not Upload"] +dependencies = ["reflex[ui]>=0.9"] diff --git a/examples/pages/rxconfig.py b/examples/pages/rxconfig.py new file mode 100644 index 00000000000..7ace590c704 --- /dev/null +++ b/examples/pages/rxconfig.py @@ -0,0 +1,47 @@ +"""Reflex configuration of the page-weight apps: PAGES_APP picks one.""" + +import os + +import reflex as rx + +APP = os.environ.get("PAGES_APP", "blank") +# The accent of every themed app: one, so a kitchen sink's CSS holds one scale. +ACCENT = "violet" + + +def _plugins(app: str) -> list[rx.plugins.Plugin]: + """The plugins of an app. + + Args: + app: The app's name. + + Returns: + What `reflex init` writes for the blank app. The others keep the + sitemap, which is on by default and ships no script, and add Radix + Themes for the Radix kitchen sink, `UIPlugin` for the rx.ui apps and + nothing for the apps of plain elements. + + Raises: + ValueError: When no app has that name. + """ + if app == "blank": + return [ + rx.plugins.SitemapPlugin(), + rx.plugins.TailwindV4Plugin(), + rx.plugins.RadixThemesPlugin(), + ] + sitemap = rx.plugins.SitemapPlugin() + if app == "kitchen_sink_rx": + return [ + sitemap, + rx.plugins.RadixThemesPlugin(theme=rx.theme(accent_color=ACCENT)), + ] + if app in {"ui_button", "kitchen_sink_ui"}: + return [sitemap, rx.plugins.UIPlugin(theme=rx.ui.Theme(accent_color=ACCENT))] + if app in {"el_stateless", "el_stateful"}: + return [sitemap] + msg = f"PAGES_APP={app!r} names no app of examples/pages" + raise ValueError(msg) + + +config = rx.Config(app_name=APP, plugins=_plugins(APP)) diff --git a/examples/pages/ui_button/__init__.py b/examples/pages/ui_button/__init__.py new file mode 100644 index 00000000000..b57b3c75072 --- /dev/null +++ b/examples/pages/ui_button/__init__.py @@ -0,0 +1 @@ +"""The ui_button app of the page-weight benchmarks.""" diff --git a/examples/pages/ui_button/ui_button.py b/examples/pages/ui_button/ui_button.py new file mode 100644 index 00000000000..251ef6d26dd --- /dev/null +++ b/examples/pages/ui_button/ui_button.py @@ -0,0 +1,6 @@ +"""A page of one `rx.ui.button`.""" + +import reflex as rx + +app = rx.App() +app.add_page(lambda: rx.ui.button("Save"), route="/", title="Button") diff --git a/examples/ruff.toml b/examples/ruff.toml index 338c7ea5a8c..64a7885a0a0 100644 --- a/examples/ruff.toml +++ b/examples/ruff.toml @@ -9,6 +9,8 @@ src = ["*"] [lint.extend-per-file-ignores] # rxconfig.py sits in the app root, which is not a package. "*/rxconfig.py" = ["INP001"] +# A copy of the blank template of `reflex init`, kept as it is. +"pages/blank/blank.py" = ["D103"] # Every package under packages/ whose import name is not `reflex`. [lint.flake8-tidy-imports.banned-api] diff --git a/packages/reflex-bench/src/reflex_bench/budgets.py b/packages/reflex-bench/src/reflex_bench/budgets.py index e5ae2191f37..ce61030a514 100644 --- a/packages/reflex-bench/src/reflex_bench/budgets.py +++ b/packages/reflex-bench/src/reflex_bench/budgets.py @@ -1,27 +1,45 @@ -"""Budgets: the largest allowed values of benchmark metrics, kept in ``budgets.json``. +"""Budgets: the limits of benchmark metrics, kept in ``budgets.json``. -A budget caps one metric of one benchmark instance, in the metric's unit:: +A budget bounds one metric of one benchmark instance, in the metric's unit, and +records the value measured when it was set:: { - "schema": "reflex-bench-budgets/1", + "schema": "reflex-bench-budgets/2", "budgets": { - "size.export[app=playground]": {"initial_gzip": 330000, "chunks": 16} + "size.export[app=blank]": { + "js_gzip": {"max": 180000, "measured": 170812}, + "emotion_files": {"max": 0, "measured": 0} + }, + "lighthouse.mobile[app=blank]": { + "simulate_score": {"min": 0.95, "measured": 1, "enforce": false} + } } } +``max`` caps a metric and ``min`` floors one (a score). ``note`` may say where +the limit comes from. ``enforce: false`` marks a budget that is reported and +never fails the check: a noisy measurement (a page load on a shared CI runner) +whose limit is a signal to read, not a gate. + ``reflex-bench budgets check RESULT.json`` checks a result against them: exit 2 -when a metric exceeds its budget, 1 when a budget cannot be checked (the +when an enforced budget is exceeded, 1 when a budget cannot be checked (the benchmark is missing from the result, did not finish ``ok`` or lacks the -metric), else 0. A metric without a budget is tracked, not gated. A budget is -raised by editing the file in the same pull request, so the review shows it. +metric), else 0. ``--only GLOB`` checks the budgets of the instances it matches, +for a result that holds some benchmarks only. The value checked is the largest +timed sample of an exact metric (it has one) and the median of the others. A +metric without a budget is tracked, not gated. A budget is changed by editing +the file in the same pull request, so the review shows it. """ from __future__ import annotations +import fnmatch import json +import statistics from collections.abc import Sequence from dataclasses import dataclass from pathlib import Path +from typing import Any, Literal import click from rich.text import Text @@ -37,21 +55,104 @@ ) from reflex_bench.schema import load as load_result -SCHEMA_ID = "reflex-bench-budgets/1" +SCHEMA_ID = "reflex-bench-budgets/2" # packages/reflex-bench/budgets.json: reflex-bench is never published, so it # always runs from its source tree. DEFAULT_PATH = Path(__file__).resolve().parents[2] / "budgets.json" _COLUMNS = ("benchmark", "metric", "value", "budget", "delta", "verdict") _RIGHT_ALIGNED = (2, 3, 4) +_KEYS = frozenset({"max", "min", "measured", "enforce", "note"}) + + +@dataclass(frozen=True) +class Budget: + """The limit of one metric. + + Attributes: + limit: The largest (``max``) or smallest (``min``) allowed value. + bound: ``max`` or ``min``. + measured: The value measured when the limit was set. + enforce: Whether exceeding it fails the check; else it is reported. + note: Where the limit comes from. + """ + + limit: float + bound: Literal["max", "min"] + measured: float + enforce: bool = True + note: str | None = None + + def exceeded_by(self, value: float) -> bool: + """Whether a value is beyond the limit. + + Args: + value: The value. + + Returns: + True above a ``max`` or below a ``min``. + """ + return value > self.limit if self.bound == "max" else value < self.limit + # Instance name to metric name to budget. -Budgets = dict[str, dict[str, int]] +Budgets = dict[str, dict[str, Budget]] class BudgetsError(ValueError): """A budgets file is not valid.""" +def _is_number(value: Any) -> bool: + """Whether a JSON value is a number of at least 0. + + Args: + value: The value. + + Returns: + True for an int or float >= 0 (not a bool). + """ + return type(value) in {int, float} and value >= 0 + + +def _budget(path: Path, name: str, metric: str, raw: Any) -> Budget: + """Validate one budget. + + Args: + path: The file, for messages. + name: The instance name. + metric: The metric name. + raw: The budget's JSON object. + + Returns: + The budget. + + Raises: + BudgetsError: When it is not an object with exactly one of ``max`` and + ``min`` and a ``measured`` value, all numbers >= 0, an optional + boolean ``enforce`` and an optional string ``note``. + """ + where = f"{path}: budget {name} {metric}" + if not isinstance(raw, dict): + msg = f"{where} must be an object" + raise BudgetsError(msg) + if unknown := sorted(raw.keys() - _KEYS): + msg = f"{where} has unknown keys {unknown}" + raise BudgetsError(msg) + bounds = [key for key in ("max", "min") if key in raw] + if len(bounds) != 1: + msg = f"{where} needs exactly one of max and min" + raise BudgetsError(msg) + (bound,) = bounds + if not _is_number(raw[bound]) or not _is_number(raw.get("measured")): + msg = f"{where}: {bound} and measured must be numbers >= 0" + raise BudgetsError(msg) + enforce, note = raw.get("enforce", True), raw.get("note") + if type(enforce) is not bool or not isinstance(note, str | None): + msg = f"{where}: enforce must be a boolean and note a string" + raise BudgetsError(msg) + return Budget(raw[bound], bound, raw["measured"], enforce, note) + + def load(path: Path) -> Budgets: """Read and validate a budgets file. @@ -62,9 +163,8 @@ def load(path: Path) -> Budgets: Instance name to metric name to budget, in file order. Raises: - BudgetsError: When the file is not JSON, has another schema, or its - budgets are not whole numbers of at least 0 keyed by instance and - metric. + BudgetsError: When the file is not JSON, has another schema, or a + budget is not valid. """ try: doc = json.loads(path.read_text(encoding="utf-8")) @@ -75,14 +175,17 @@ def load(path: Path) -> Budgets: msg = f"{path}: schema must be {SCHEMA_ID!r}" raise BudgetsError(msg) budgets = doc.get("budgets") - if not isinstance(budgets, dict) or any( - not isinstance(limits, dict) - or any(type(budget) is not int or budget < 0 for budget in limits.values()) - for limits in budgets.values() + if not isinstance(budgets, dict) or not all( + isinstance(limits, dict) for limits in budgets.values() ): - msg = f"{path}: budgets must map instance names to objects of whole-number metric budgets >= 0" + msg = f"{path}: budgets must map instance names to objects of metric budgets" raise BudgetsError(msg) - return budgets + return { + name: { + metric: _budget(path, name, metric, raw) for metric, raw in limits.items() + } + for name, limits in budgets.items() + } @dataclass(frozen=True) @@ -92,9 +195,8 @@ class BudgetRow: Attributes: benchmark: The instance name, e.g. ``size.export[app=playground]``. metric: The metric name. - budget: The largest allowed value, in the metric's unit. - value: The largest timed sample of the metric; ``None`` when it could - not be read. + budget: The budget. + value: The value checked; ``None`` when it could not be read. unit: The metric's unit, when the result has the metric. error: Why the value could not be read. detail: The benchmark's own error, when it did not finish ``ok``. @@ -102,7 +204,7 @@ class BudgetRow: benchmark: str metric: str - budget: int + budget: Budget value: float | None = None unit: str | None = None error: str | None = None @@ -110,16 +212,25 @@ class BudgetRow: @property def exceeded(self) -> bool: - """Whether the value is over the budget. + """Whether the value is beyond the budget. Returns: True when a value was read and exceeds the budget. """ - return self.value is not None and self.value > self.budget + return self.value is not None and self.budget.exceeded_by(self.value) + + @property + def failed(self) -> bool: + """Whether the row fails the check. + + Returns: + True when an enforced budget is exceeded. + """ + return self.exceeded and self.budget.enforce def _check_one( - name: str, entry: BenchmarkDoc | None, metric: str, budget: int + name: str, entry: BenchmarkDoc | None, metric: str, budget: Budget ) -> BudgetRow: """Check one budget. @@ -145,28 +256,66 @@ def _check_one( values = [ value for arm in found["samples"] for value in timed_values(entry, metric, arm) ] - return BudgetRow(name, metric, budget, value=max(values), unit=found["unit"]) + value = max(values) if found["assume"] == "exact" else statistics.median(values) + return BudgetRow(name, metric, budget, value=value, unit=found["unit"]) -def check(doc: ResultDoc, budgets: Budgets) -> list[BudgetRow]: +def check( + doc: ResultDoc, budgets: Budgets, only: Sequence[str] = () +) -> list[BudgetRow]: """Check a result against budgets. Args: doc: A result, normally of ``reflex-bench run``. budgets: The budgets, as :func:`load` returns them. + only: Globs of the instance names to check; every instance when empty. Returns: - One row per budget, in the budgets' order. The value is the largest timed - sample of the metric; exact metrics have one. + One row per budget checked, in the budgets' order. """ entries = {entry_name(entry): entry for entry in doc["benchmarks"]} return [ _check_one(name, entries.get(name), metric, budget) for name, limits in budgets.items() + if not only or any(fnmatch.fnmatchcase(name, glob) for glob in only) for metric, budget in limits.items() ] +def _quantity(value: float, unit: str | None) -> str: + """Write a value with its unit, as a failure names it. + + Args: + value: The value. + unit: Its unit; ``1`` and ``None`` have none. + + Returns: + E.g. ``182,345 B``, ``1.254 s`` or ``0.9``. + """ + text = f"{value:,.0f}" if float(value).is_integer() else f"{value:,.3f}" + return text if unit in {None, "1"} else f"{text} {unit}" + + +def failure_line(row: BudgetRow) -> str: + """Say how a row exceeded its budget. + + Args: + row: A row whose value exceeds its budget. + + Returns: + E.g. ``size.export[app=blank] js_gzip is 182,345 B, over its limit of + 180,000 B``, prefixed ``reported, not enforced:`` for a budget that is + not enforced. + """ + assert row.value is not None + side = "over" if row.budget.bound == "max" else "under" + line = ( + f"{row.benchmark} {row.metric} is {_quantity(row.value, row.unit)}, {side}" + f" its limit of {_quantity(row.budget.limit, row.unit)}" + ) + return line if row.budget.enforce else f"reported, not enforced: {line}" + + def _number(value: float, signed: bool = False) -> str: """Format a value or a delta, keeping the fraction of a fractional one. @@ -190,13 +339,14 @@ def _delta(row: BudgetRow, value: float) -> str: value: Its value. Returns: - E.g. ``-11,807 B (-4.5 %)``: negative is headroom. + E.g. ``-11,807 B (-4.5 %)``: negative is headroom under a ``max``. """ - delta = value - row.budget + limit = row.budget.limit + delta = value - limit text = _number(delta, signed=True) if row.unit not in {None, "1"}: text += f" {row.unit}" - return text + (f" ({format_pct(delta / row.budget)})" if row.budget else "") + return text + (f" ({format_pct(delta / limit)})" if limit else "") def table_lines(rows: Sequence[BudgetRow]) -> list[Line]: @@ -207,23 +357,28 @@ def table_lines(rows: Sequence[BudgetRow]) -> list[Line]: Returns: The header and one row per budget: benchmark, metric, value (a whole - value as budgets.json writes it, ready to paste), budget, delta in the - metric's unit and in percent of the budget, and verdict. A benchmark - that did not finish ``ok`` gets its error printed once, after its rows. + value as budgets.json writes it, ready to paste), budget (``<=`` a + ``max``, ``>=`` a ``min``), delta in the metric's unit and in percent of + the budget, and verdict, ``(reported)`` for a budget not enforced. A + benchmark that did not finish ``ok`` gets its error printed once, after + its rows. """ lines: list[Line] = [[Text(column, style="bold") for column in _COLUMNS]] detailed: set[str] = set() for row in rows: + budget = ( + f"{'<=' if row.budget.bound == 'max' else '>='} {_number(row.budget.limit)}" + ) if row.value is None: - cells = ["-", str(row.budget), "", f"error: {row.error}"] + cells = ["-", budget, "", f"error: {row.error}"] else: - cells = [ - _number(row.value), - str(row.budget), - _delta(row, row.value), - "over budget" if row.exceeded else "ok", - ] - style = "bold red" if row.value is None or row.exceeded else "" + verdict = "ok" + if row.exceeded: + verdict = "over budget" if row.budget.bound == "max" else "under budget" + if not row.budget.enforce: + verdict += " (reported)" + cells = [_number(row.value), budget, _delta(row, row.value), verdict] + style = "bold red" if row.value is None or row.failed else "" lines.append([row.benchmark, row.metric, *cells[:-1], Text(cells[-1], style)]) if row.detail and row.benchmark not in detailed: detailed.add(row.benchmark) @@ -235,7 +390,7 @@ def table_lines(rows: Sequence[BudgetRow]) -> list[Line]: @click.group("budgets") def budgets_command() -> None: - """Check results against the metric budgets of budgets.json.""" + """Check results against the metric limits of budgets.json.""" @budgets_command.command("check") @@ -248,47 +403,63 @@ def budgets_command() -> None: show_default="packages/reflex-bench/budgets.json", help="The budgets file.", ) -def check_command(result: Path, budgets_path: Path) -> int: - """Check RESULT against the budgets; exit 2 when a metric exceeds its budget. +@click.option( + "--only", + multiple=True, + metavar="GLOB", + help="Check only the instances this glob matches, e.g. 'size.*'; may be repeated.", +) +def check_command(result: Path, budgets_path: Path, only: tuple[str, ...]) -> int: + """Check RESULT against the budgets; exit 2 when an enforced one is exceeded. Exit 1 when a budgeted benchmark is missing from RESULT, did not finish ok - or lacks a budgeted metric. Metrics without a budget are not checked. + or lacks a budgeted metric. Metrics without a budget are not checked, and a + budget with "enforce": false is reported without failing. Args: result: The result JSON file. budgets_path: The budgets file. + only: Globs of the instances to check. Returns: The exit code. Raises: - UsageError: When a file is not valid. + UsageError: When a file is not valid or ``--only`` matches no budget. """ # cli imports this module to register the group, so import it late. from reflex_bench.cli import EXIT_ERROR, EXIT_OK, EXIT_REGRESSION, _relative, in_ci try: - rows = check(load_result(result), load(budgets_path)) + rows = check(load_result(result), load(budgets_path), only) except (SchemaError, BudgetsError) as exc: raise click.UsageError(str(exc)) from exc + if not rows: + msg = f"--only {' '.join(only)} matches no budget of {_relative(budgets_path)}" + raise click.UsageError(msg) console = make_console(plain=in_ci()) print_lines(console, table_lines(rows), right=_RIGHT_ALIGNED) - over = sum(row.exceeded for row in rows) + failed = sum(row.failed for row in rows) + reported = sum(row.exceeded and not row.budget.enforce for row in rows) unchecked = sum(row.value is None for row in rows) console.print() + for row in rows: + if row.exceeded: + console.print(Text(failure_line(row), "bold red" if row.failed else "")) console.print( Text( - f"{len(rows) - over - unchecked} within budget {DOT} {over} over budget" + f"{len(rows) - failed - reported - unchecked} within budget {DOT}" + f" {failed} over budget {DOT} {reported} over budget, reported only" f" {DOT} {unchecked} not checked" ) ) - if over: + if failed: console.print( Text( - "to accept a new value, raise its budget in" + "to accept a new value, change its budget in" f" {_relative(budgets_path)} in the same pull request" ) ) if unchecked: return EXIT_ERROR - return EXIT_REGRESSION if over else EXIT_OK + return EXIT_REGRESSION if failed else EXIT_OK diff --git a/packages/reflex-bench/src/reflex_bench/cli.py b/packages/reflex-bench/src/reflex_bench/cli.py index 0b16c1c7047..56c8ea1b043 100644 --- a/packages/reflex-bench/src/reflex_bench/cli.py +++ b/packages/reflex-bench/src/reflex_bench/cli.py @@ -207,7 +207,7 @@ def _estimate(bench: Benchmark, policy: Policy) -> float: Returns: Seconds, from the benchmark's ``estimate`` per sample. """ - runs = policy.runs or (1 if bench.exact else policy.auto_runs(bench.estimate)) + runs = policy.runs or bench.default_runs or policy.auto_runs(bench.estimate) return (bench.warmup + runs) * bench.estimate diff --git a/packages/reflex-bench/src/reflex_bench/drivers/lighthouse.py b/packages/reflex-bench/src/reflex_bench/drivers/lighthouse.py new file mode 100644 index 00000000000..dc65471ead3 --- /dev/null +++ b/packages/reflex-bench/src/reflex_bench/drivers/lighthouse.py @@ -0,0 +1,180 @@ +"""Run the Lighthouse CLI against a page and read the numbers of its report. + +The CLI is the one ``tests/integration/test_lighthouse.py`` runs: +``REFLEX_LIGHTHOUSE_COMMAND`` when set, else ``lighthouse`` on ``PATH``, else +``npx --yes lighthouse@13.1.0``. It drives Playwright's Chromium, or +``REFLEX_LIGHTHOUSE_CHROME_PATH``. +""" + +from __future__ import annotations + +import json +import os +import shlex +import shutil +import subprocess +from collections.abc import Mapping +from pathlib import Path +from typing import Any, Literal + +PACKAGE = "lighthouse@13.1.0" +COMMAND_ENV = "REFLEX_LIGHTHOUSE_COMMAND" +CHROME_ENV = "REFLEX_LIGHTHOUSE_CHROME_PATH" +# A first npx run downloads the package. +PREPARE_TIMEOUT_S = 300.0 +RUN_TIMEOUT_S = 300.0 +CHROME_FLAGS = "--headless=new --no-sandbox --disable-dev-shm-usage" +# Lighthouse's own model of a slow 4G phone, or the same throttling applied to +# the browser while the page loads. +Throttling = Literal["simulate", "devtools"] +# The audits read from a report, in their units: milliseconds, or none for CLS. +AUDITS = { + "lcp": "largest-contentful-paint", + "tbt": "total-blocking-time", + "cls": "cumulative-layout-shift", + "fcp": "first-contentful-paint", +} + + +def command() -> list[str]: + """Resolve the Lighthouse command. + + Returns: + The command prefix. + + Raises: + FileNotFoundError: When neither the variable, ``lighthouse`` nor ``npx`` + is there. + """ + if configured := os.environ.get(COMMAND_ENV): + return shlex.split(configured) + if shutil.which("lighthouse"): + return ["lighthouse"] + if shutil.which("npx"): + return ["npx", "--yes", PACKAGE] + msg = f"Lighthouse is unavailable: install `lighthouse`, Node's `npx`, or set {COMMAND_ENV}" + raise FileNotFoundError(msg) + + +def chrome_path() -> str: + """Find the Chromium that Lighthouse drives. + + Returns: + ``REFLEX_LIGHTHOUSE_CHROME_PATH``, else Playwright's Chromium, else its + headless shell (CI installs the shell alone). + + Raises: + FileNotFoundError: When there is none. + """ + if configured := os.environ.get(CHROME_ENV): + return configured + # Imported here: `reflex-bench list` imports every suite. + from playwright.sync_api import sync_playwright + + with sync_playwright() as playwright: + browser = Path(playwright.chromium.executable_path) + if browser.is_file(): + return str(browser) + # /chromium-/chrome-linux/chrome: the shell sits beside it. + for shell in sorted( + browser.parents[2].glob("chromium_headless_shell-*/*/chrome-headless-shell*"), + reverse=True, + ): + if shell.is_file(): + return str(shell) + msg = f"no Chromium for Lighthouse at {browser}: run `playwright install chromium`, or set {CHROME_ENV}" + raise FileNotFoundError(msg) + + +def prepare(prefix: list[str], env: Mapping[str, str]) -> None: + """Have the command ready, so no run times a download. + + Args: + prefix: The command prefix. + env: The environment. + """ + subprocess.run( + [*prefix, "--version"], + check=True, + capture_output=True, + env=dict(env), + timeout=PREPARE_TIMEOUT_S, + ) + + +def read(report: Mapping[str, Any]) -> dict[str, float]: + """Read the numbers of a report. + + Args: + report: A Lighthouse JSON report. + + Returns: + ``score`` (0 to 1), ``lcp``, ``tbt`` and ``fcp`` in seconds, and ``cls``. + + Raises: + RuntimeError: When the report has no performance score, as when the + page did not load. + """ + score = report["categories"]["performance"]["score"] + if score is None: + warnings = "; ".join(report.get("runWarnings", [])) or "no warning" + msg = f"Lighthouse gave no performance score: {warnings}" + raise RuntimeError(msg) + values = {"score": float(score)} + for name, audit in AUDITS.items(): + value = float(report["audits"][audit]["numericValue"]) + values[name] = value if name == "cls" else value / 1000 + return values + + +def run( + prefix: list[str], + url: str, + *, + throttling: Throttling, + chrome: str, + out: Path, + env: Mapping[str, str], +) -> dict[str, float]: + """Audit the performance of a page on a mobile device. + + Args: + prefix: The command prefix. + url: The page. + throttling: ``simulate`` or ``devtools``. + chrome: The browser. + out: Where the JSON report goes. + env: The environment. + + Returns: + The numbers of :func:`read`. + + Raises: + RuntimeError: When Lighthouse fails, with the end of its output. + """ + args = [ + *prefix, + url, + "--only-categories=performance", + "--form-factor=mobile", + f"--throttling-method={throttling}", + "--output=json", + f"--output-path={out}", + f"--chrome-path={chrome}", + f"--chrome-flags={CHROME_FLAGS}", + "--quiet", + ] + done = subprocess.run( + args, + capture_output=True, + encoding="utf-8", + errors="replace", + env=dict(env), + timeout=RUN_TIMEOUT_S, + check=False, + ) + if done.returncode != 0: + tail = "\n".join((done.stdout + done.stderr).splitlines()[-20:]) + msg = f"lighthouse exited with code {done.returncode}:\n{tail}" + raise RuntimeError(msg) + return read(json.loads(out.read_text(encoding="utf-8"))) diff --git a/packages/reflex-bench/src/reflex_bench/registry.py b/packages/reflex-bench/src/reflex_bench/registry.py index b2fcdf34c9b..17ac1bdedb4 100644 --- a/packages/reflex-bench/src/reflex_bench/registry.py +++ b/packages/reflex-bench/src/reflex_bench/registry.py @@ -52,7 +52,7 @@ def sample(self, ctx): if TYPE_CHECKING: from reflex_bench.context import Context -SUITES = ("smoke", "pr", "daily", "macro", "all", "selftest") +SUITES = ("smoke", "pr", "daily", "macro", "pages", "all", "selftest") SELFTEST_SUITE = "selftest" # ``all`` is implicit: every benchmark except the self-tests. _DECLARABLE_SUITES = tuple(suite for suite in SUITES if suite != "all") @@ -223,6 +223,8 @@ class Benchmark: that suite is selected, e.g. one quick point for ``smoke``. metrics: The declared metrics. warmup: Untimed runs before the timed ones. + runs: The timed runs when ``--runs`` names none; ``None`` takes one run + of an exact benchmark and the automatic rule for the others. timeout: Seconds allowed for each prepare, sample and conclude call. setup_timeout: Seconds allowed for setup_cache, setup and cleanup. estimate: Rough seconds per sample, for ``list``. @@ -241,6 +243,7 @@ class Benchmark: suite_params: dict[str, dict[str, tuple[Any, ...]]] metrics: dict[str, Metric] warmup: int + runs: int | None timeout: float setup_timeout: float estimate: float @@ -261,6 +264,7 @@ def define( hidden_params: Mapping[str, Any] | None = None, suite_params: Mapping[str, Mapping[str, Sequence[Any]]] | None = None, warmup: int = 0, + runs: int | None = None, timeout: float = 60.0, setup_timeout: float = 600.0, estimate: float = 1.0, @@ -279,6 +283,7 @@ def define( suite_params: Suite name to parameter values that replace the declared ones when that suite is selected. warmup: Untimed runs before the timed ones. + runs: The timed runs when the policy names none. timeout: Seconds allowed for each prepare, sample and conclude call. setup_timeout: Seconds allowed for setup_cache, setup and cleanup. estimate: Rough seconds per sample. @@ -347,6 +352,8 @@ def define( ) if warmup < 0 or timeout <= 0 or setup_timeout <= 0 or estimate < 0: problems.append("warmup and estimate must be >= 0, timeouts > 0") + if runs is not None and runs < 1: + problems.append("runs must be >= 1") if min_version is not None: try: Version(min_version) @@ -368,6 +375,7 @@ def define( suite_params=narrowed, metrics=dict(metrics), warmup=warmup, + runs=runs, timeout=float(timeout), setup_timeout=float(setup_timeout), estimate=float(estimate), @@ -385,6 +393,16 @@ def exact(self) -> bool: """ return all(metric.assume == "exact" for metric in self.metrics.values()) + @property + def default_runs(self) -> int | None: + """The timed runs when the policy names none. + + Returns: + The declared ``runs``, else one for an exact benchmark, else + ``None``: the automatic rule. + """ + return self.runs or (1 if self.exact else None) + @property def param_names(self) -> set[str]: """Every parameter ``--param`` may set. @@ -610,6 +628,7 @@ def benchmark( hidden_params: Mapping[str, Any] | None = None, suite_params: Mapping[str, Mapping[str, Sequence[Any]]] | None = None, warmup: int = 0, + runs: int | None = None, timeout: float = 60.0, setup_timeout: float = 600.0, estimate: float = 1.0, @@ -630,6 +649,8 @@ def benchmark( suite_params: Suite name to parameter values that replace the declared ones when that suite is selected, e.g. ``{"smoke": {"sessions": [10]}}``. warmup: Untimed runs before the timed ones. + runs: The timed runs when ``--runs`` names none, e.g. a fixed five for + a noisy measurement whose median is what counts. timeout: Seconds allowed for each prepare, sample and conclude call. setup_timeout: Seconds allowed for setup_cache, setup and cleanup. estimate: Rough seconds per sample, shown by ``list``. @@ -652,6 +673,7 @@ def decorate(target: _T) -> _T: hidden_params=hidden_params, suite_params=suite_params, warmup=warmup, + runs=runs, timeout=timeout, setup_timeout=setup_timeout, estimate=estimate, diff --git a/packages/reflex-bench/src/reflex_bench/scheduler.py b/packages/reflex-bench/src/reflex_bench/scheduler.py index 839396b1c14..be2c55647ab 100644 --- a/packages/reflex-bench/src/reflex_bench/scheduler.py +++ b/packages/reflex-bench/src/reflex_bench/scheduler.py @@ -982,7 +982,7 @@ def _sample(self, session: Session) -> None: warmup, target = 0, 1 else: warmup = bench.warmup if policy.warmup is None else policy.warmup - target = policy.runs or (1 if bench.exact else None) + target = policy.runs or bench.default_runs timed = 0 index = 0 while target is None or timed < target: diff --git a/packages/reflex-bench/src/reflex_bench/suites/lighthouse.py b/packages/reflex-bench/src/reflex_bench/suites/lighthouse.py new file mode 100644 index 00000000000..bd56c8bbdca --- /dev/null +++ b/packages/reflex-bench/src/reflex_bench/suites/lighthouse.py @@ -0,0 +1,120 @@ +"""Lighthouse benchmarks: the mobile performance audit of a page app's first page. + +``lighthouse.mobile`` builds and starts one of the apps of ``examples/pages`` +in production (``reflex run --env prod``) in ``setup``, and each sample audits +``/`` twice, with Lighthouse's simulated throttling (its model of a slow 4G +phone, the number PageSpeed Insights shows) and with the same throttling +applied to the browser (``devtools``, "real" throttling). Lighthouse varies by +some points from run to run, so the benchmark takes five runs, and the median +is what counts. +""" + +from __future__ import annotations + +from reflex_bench.context import Context +from reflex_bench.drivers import lighthouse +from reflex_bench.drivers.app_process import AppProcess, cache_env +from reflex_bench.registry import Metric, SampleResult, benchmark +from reflex_bench.suites.size import PAGE_APPS, stage_app + +APP_TIMEOUT_S = 600.0 +THROTTLINGS: tuple[lighthouse.Throttling, ...] = ("simulate", "devtools") + + +def _metrics() -> dict[str, Metric]: + """Declare the numbers of each throttling. + + Returns: + ``_``: the score (higher is better), LCP, TBT and + FCP in seconds and CLS. + """ + metrics = {} + for throttling in THROTTLINGS: + metrics[f"{throttling}_score"] = Metric( + unit="1", direction="higher", description=f"performance score, {throttling}" + ) + for name, audit in lighthouse.AUDITS.items(): + metrics[f"{throttling}_{name}"] = Metric( + unit="1" if name == "cls" else "s", + direction="lower", + description=f"{audit}, {throttling}", + ) + return metrics + + +@benchmark( + id="lighthouse.mobile", + suites=("pages",), + kind="latency", + params={"app": list(PAGE_APPS)}, + metrics=_metrics(), + runs=5, + timeout=2 * lighthouse.RUN_TIMEOUT_S, + setup_timeout=APP_TIMEOUT_S + lighthouse.PREPARE_TIMEOUT_S + 60, + estimate=25, +) +class MobileAudit: + """Audit / of a page app in production with Lighthouse mobile, simulated and real throttling.""" + + app: AppProcess | None = None + prefix: list[str] + chrome: str + + def setup(self, ctx: Context) -> None: + """Ready Lighthouse, then build and start the app in production. + + One server serves every sample: a prod start includes the build, and an + audit loads the page with an empty cache. + + Args: + ctx: The benchmark context; ``app`` names the app. + """ + self.prefix = lighthouse.command() + lighthouse.prepare(self.prefix, ctx.env) + self.chrome = lighthouse.chrome_path() + name, path = ctx.params["app"], ctx.workdir / "app" + content_hash, env = stage_app(name, path) + ctx.fixture = {"name": name, "content_hash": content_hash, "params": {}} + app = self.app = AppProcess( + ctx.subject.python, + path, + mode="prod", + reflex_version=ctx.subject.reflex_version, + env={**ctx.env, **env, **cache_env(reflex_dir=ctx.cache_dir / "reflex")}, + start_timeout=APP_TIMEOUT_S, + ) + app.start() + app.wait_http_ready() + + def sample(self, ctx: Context) -> SampleResult: + """Audit / with each throttling. + + Args: + ctx: The benchmark context. + + Returns: + Every metric. + """ + assert self.app is not None + assert self.app.frontend_url is not None + values: dict[str, float] = {} + for throttling in THROTTLINGS: + audit = lighthouse.run( + self.prefix, + self.app.frontend_url + "/", + throttling=throttling, + chrome=self.chrome, + out=ctx.workdir / f"lighthouse-{throttling}.json", + env=ctx.env, + ) + values.update({f"{throttling}_{k}": v for k, v in audit.items()}) + return SampleResult(values) + + def cleanup(self, ctx: Context) -> None: + """Stop the app. + + Args: + ctx: The benchmark context. + """ + if self.app is not None: + self.app.stop() diff --git a/packages/reflex-bench/src/reflex_bench/suites/size.py b/packages/reflex-bench/src/reflex_bench/suites/size.py index 137daf68c3f..e9de498d206 100644 --- a/packages/reflex-bench/src/reflex_bench/suites/size.py +++ b/packages/reflex-bench/src/reflex_bench/suites/size.py @@ -15,8 +15,18 @@ next to the build's files and 0.8.23 writes none, so sidecars (``.gz``, ``.br``, ``.zst``) are never measured, only summed into ``sidecar_bytes``. - ``chunks``: the JavaScript files in the build's ``assets`` directory. +- ``js_gzip``, ``css_gzip`` and ``js_files``: every ``.js`` and every ``.css`` + file of the client build, gzipped as above, and the number of ``.js`` files: + the page weight every step of the ``rx.ui`` plan measured. +- ``emotion_files``: the ``.js`` files whose name or code mentions Emotion + (case-insensitive), the CSS-in-JS runtime a page of ``rx.ui`` never needs. +- ``build_time``: the wall time of the export, the one metric that is not exact. - ``web_dir`` and ``node_modules``: the regular files under ``.web`` outside and inside ``.web/node_modules``; symlinks are neither followed nor counted. + +The ``app`` parameter names the playground or one of the apps of +``examples/pages``, which share one directory and pick their app with +``PAGES_APP`` (:data:`APPS`). """ from __future__ import annotations @@ -41,6 +51,17 @@ from reflex_bench.fixtures import HASH_FILE from reflex_bench.registry import Metric, SampleResult, benchmark +# The page-weight apps: their example directory and the app it selects. +PAGES = "pages" +PAGE_APPS = ( + "blank", + "el_stateless", + "el_stateful", + "ui_button", + "kitchen_sink_rx", + "kitchen_sink_ui", +) + EXPORT_ARGS = ("export", "--frontend-only", "--no-zip", "--env", "prod") # 10 minutes: a cold export also installs the frontend packages. EXPORT_TIMEOUT_S = 600.0 @@ -50,6 +71,8 @@ _LOADED = frozenset({"modulepreload", "stylesheet"}) # Vite's `-`: the greedy stem leaves the last `-` only. _HASHED = re.compile(r"(?P.+)-[A-Za-z0-9_-]{8}(?P(?:\.[A-Za-z0-9]+)+)") +# What test_ui_components.py looks for in a script that ships Emotion. +_EMOTION = re.compile(rb"emotion", re.IGNORECASE) def _exact(description: str, unit: str = "B") -> Metric: @@ -73,6 +96,13 @@ def _exact(description: str, unit: str = "B") -> Metric: "total_gzip": _exact("total_raw, each file gzipped at level 9"), "total_brotli": _exact("total_raw, each file brotli-compressed at quality 11"), "chunks": _exact("JavaScript files in the client build's assets", unit="1"), + "js_gzip": _exact("Every .js file of the client build, each gzipped at level 9"), + "css_gzip": _exact("Every .css file of the client build, each gzipped at level 9"), + "js_files": _exact(".js files in the client build", unit="1"), + "emotion_files": _exact(".js files that mention Emotion", unit="1"), + "build_time": Metric( + unit="s", direction="lower", description="Wall time of the production export" + ), "web_dir": _exact("Bytes under .web, node_modules excluded"), "node_modules": _exact("Bytes under .web/node_modules"), } @@ -177,7 +207,7 @@ def measure_export(app: Path, *, reflex_version: str | None) -> SampleResult: reflex_version: The version of the reflex that exported it. Returns: - Every metric of ``size.export``. The extra data holds ``files``, the size + Every metric of ``size.export`` but ``build_time``. The extra data holds ``files``, the size of each file of the client build keyed by its path with the content hash replaced (``#2``, ``#3``, ... tell apart names that differ only in their hash), ``initial_files`` (the first page's files in page order), ``html`` @@ -201,7 +231,7 @@ def measure_export(app: Path, *, reflex_version: str | None) -> SampleResult: raise FileNotFoundError(msg) files: dict[str, dict[str, Any]] = {} keys: dict[str, str] = {} - sidecar_bytes = chunks = 0 + sidecar_bytes = chunks = js_gzip = css_gzip = js_files = emotion_files = 0 for rel in sorted( path.relative_to(client).as_posix() for path in client.rglob("*") @@ -224,8 +254,13 @@ def measure_export(app: Path, *, reflex_version: str | None) -> SampleResult: "brotli": len(brotli.compress(data, quality=11)), "initial": False, } - if rel.rpartition("/")[0] == ASSETS and rel.endswith(".js"): - chunks += 1 + if path.suffix == ".js": + js_files += 1 + js_gzip += files[key]["gzip"] + emotion_files += bool(_EMOTION.search(rel.encode() + data)) + chunks += rel.rpartition("/")[0] == ASSETS + elif path.suffix == ".css": + css_gzip += files[key]["gzip"] initial: dict[str, None] = {} for ref in initial_assets(page.read_text(encoding="utf-8")): url = urllib.parse.urlsplit(ref) @@ -241,6 +276,10 @@ def measure_export(app: Path, *, reflex_version: str | None) -> SampleResult: files[key]["initial"] = True values: dict[str, float] = { "chunks": chunks, + "js_gzip": js_gzip, + "css_gzip": css_gzip, + "js_files": js_files, + "emotion_files": emotion_files, "web_dir": tree_bytes(web, exclude=web / "node_modules"), "node_modules": tree_bytes(web / "node_modules"), } @@ -300,12 +339,36 @@ def copy_example(name: str, dest: Path) -> None: shutil.copyfile(source, target) +def stage_app(app: str, dest: Path) -> tuple[str, dict[str, str]]: + """Copy the example an app lives in, and say how to select the app. + + Args: + app: ``playground`` or one of :data:`PAGE_APPS`. + dest: Where to copy the example. + + Returns: + The example's committed content hash and the environment that selects + the app: ``PAGES_APP`` for the apps of ``examples/pages``. + """ + if app in PAGE_APPS: + copy_example(PAGES, dest) + env = {"PAGES_APP": app} + else: + copy_example(app, dest) + env = {} + return (dest / HASH_FILE).read_text().strip(), env + + @benchmark( id="size.export", - suites=("pr", "daily"), + suites=("pr", "daily", "pages"), kind="track", - params={"app": ["playground"]}, + params={"app": ["playground", *PAGE_APPS]}, + # The macro runner measures the playground alone. + suite_params={"pr": {"app": ["playground"]}}, metrics=METRICS, + # One run: the sizes are exact and the build time is reported, not compared. + runs=1, # The export's 10 minutes plus 1 minute to copy the app. setup_timeout=EXPORT_TIMEOUT_S + 60, # One sample; the export in setup takes most of the time. @@ -314,6 +377,8 @@ def copy_example(name: str, dest: Path) -> None: class ExportSize: """Export an example app for production and measure its bundle and footprint.""" + build_time: float = 0.0 + def setup(self, ctx: Context) -> None: """Record the fixture, copy the app into the work directory and export it. @@ -322,22 +387,26 @@ def setup(self, ctx: Context) -> None: directory. Args: - ctx: The benchmark context; ``app`` names the example. + ctx: The benchmark context; ``app`` names the app. """ name, app = ctx.params["app"], ctx.workdir / "app" - copy_example(name, app) - ctx.fixture = { - "name": name, - "content_hash": (app / HASH_FILE).read_text().strip(), - "params": {}, - } - run_cli( - ctx.subject.python, - EXPORT_ARGS, - cwd=app, - env={**ctx.env, **cache_env(reflex_dir=ctx.cache_dir / "reflex")}, - timeout=EXPORT_TIMEOUT_S, - ).check() + content_hash, env = stage_app(name, app) + ctx.fixture = {"name": name, "content_hash": content_hash, "params": {}} + self.build_time = ( + run_cli( + ctx.subject.python, + EXPORT_ARGS, + cwd=app, + env={ + **ctx.env, + **env, + **cache_env(reflex_dir=ctx.cache_dir / "reflex"), + }, + timeout=EXPORT_TIMEOUT_S, + ) + .check() + .wall_s + ) def sample(self, ctx: Context) -> SampleResult: """Measure the export on disk. @@ -348,6 +417,9 @@ def sample(self, ctx: Context) -> SampleResult: Returns: Every metric, with the per-file breakdown as extra data. """ - return measure_export( + result = measure_export( ctx.workdir / "app", reflex_version=ctx.subject.reflex_version ) + return SampleResult( + {**result.values, "build_time": self.build_time}, result.extra + ) diff --git a/scripts/hash_examples.py b/scripts/hash_examples.py index f9f5ac56d04..06a1010e959 100644 --- a/scripts/hash_examples.py +++ b/scripts/hash_examples.py @@ -1,13 +1,13 @@ -"""Update or check the content hash of the examples/playground benchmark fixture. +"""Update or check the content hashes of the examples the benchmarks drive. -The macro benchmarks drive examples/playground and key their result series on its -content hash, so a change to the playground resets the benchmark baselines. The -hash covers every file under examples/playground that git tracks or would track -(untracked but not ignored), minus build output, so running the app locally never -changes it. +The macro benchmarks drive examples/playground, and the page-weight benchmarks the +apps of examples/pages; they key their result series on the example's content +hash, so a change to an example resets its benchmark baselines. A hash covers +every file under the example that git tracks or would track (untracked but not +ignored), minus build output, so running an app locally never changes it. -Run ``uv run python scripts/hash_examples.py`` to rewrite -``examples/playground/.content-hash``, or pass ``--check`` to fail when it is stale. +Run ``uv run python scripts/hash_examples.py`` to rewrite each example's +``.content-hash``, or pass ``--check`` to fail when one is stale. """ from __future__ import annotations @@ -19,12 +19,14 @@ from collections.abc import Sequence from pathlib import Path, PurePosixPath -PLAYGROUND_DIR = Path(__file__).resolve().parent.parent / "examples" / "playground" +EXAMPLES_DIR = Path(__file__).resolve().parent.parent / "examples" +# The examples benchmarks drive, each keyed on its content hash. +FIXTURES = ("playground", "pages") HASH_FILE_NAME = ".content-hash" EXCLUDED_DIRS = frozenset({".web", ".states", "__pycache__", "uploaded_files"}) EXCLUDED_SUFFIXES = frozenset({".db", ".pyc"}) STALE_MESSAGE = ( - "examples/playground changed: benchmark baselines reset by this PR " + "examples/{name} changed: benchmark baselines reset by this PR " "(update with: uv run python scripts/hash_examples.py)" ) @@ -77,7 +79,7 @@ def content_hash(root: Path) -> str: def main(argv: Sequence[str] | None = None) -> int: - """Rewrite the playground's content hash file, or check that it is current. + """Rewrite the examples' content hash files, or check that they are current. Args: argv: Command-line arguments, or None to read ``sys.argv``. @@ -86,24 +88,28 @@ def main(argv: Sequence[str] | None = None) -> int: The process exit code: 1 when ``--check`` finds a stale hash, else 0. """ parser = argparse.ArgumentParser( - description="Update the examples/playground content hash." + description="Update the content hashes of the benchmarked examples." ) parser.add_argument( "--check", action="store_true", - help="fail instead of rewriting the hash file when it is stale", + help="fail instead of rewriting a hash file when it is stale", ) args = parser.parse_args(argv) - hash_file = PLAYGROUND_DIR / HASH_FILE_NAME - current = content_hash(PLAYGROUND_DIR) - if hash_file.is_file() and hash_file.read_text().strip() == current: - return 0 - if args.check: - print(STALE_MESSAGE, file=sys.stderr) - return 1 - hash_file.write_text(f"{current}\n") - return 0 + stale = False + for name in FIXTURES: + root = EXAMPLES_DIR / name + hash_file = root / HASH_FILE_NAME + current = content_hash(root) + if hash_file.is_file() and hash_file.read_text().strip() == current: + continue + if args.check: + print(STALE_MESSAGE.format(name=name), file=sys.stderr) + stale = True + else: + hash_file.write_text(f"{current}\n") + return int(stale) if __name__ == "__main__": diff --git a/tests/units/test_hash_examples.py b/tests/units/test_hash_examples.py index 7949880997e..3843a73622f 100644 --- a/tests/units/test_hash_examples.py +++ b/tests/units/test_hash_examples.py @@ -39,7 +39,8 @@ def playground(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: (repo / "outside.py").write_text("x = 1\n") _git(repo, "init") _git(repo, "add", ".") - monkeypatch.setattr(hash_examples, "PLAYGROUND_DIR", root) + monkeypatch.setattr(hash_examples, "EXAMPLES_DIR", root.parent) + monkeypatch.setattr(hash_examples, "FIXTURES", ("playground",)) return root From 9f4c6a1d331255df222567899650ba09e78388a2 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 01:23:17 +0000 Subject: [PATCH 138/204] Budget the page apps in CI, and split the parity run into shards budgets.json moves to reflex-bench-budgets/2: each limit is a max or a min with the value it came from, and a budget may be reported without being enforced. The check names each exceeded metric with its value and its limit, and --only narrows it to a part of a result. size-budgets exports every page app and becomes a required, gated workflow; the daily benchmarks run the page apps' sizes and Lighthouse audits in a shard of their own and report them. reflex-bench export --to pages prints the table of a run. The parity matrices split into shards balanced by their recorded seconds, each building the pages of its own components; ui-parity runs three, and ui-parity-report assembles their reports. scripts/ui_parity.py runs every component by default, one shard with --shard, records the seconds with --save-seconds and merges reports with --merge. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- .github/rulesets/main-required-checks.json | 4 + .github/workflows/benchmarks_daily.yml | 24 +- .github/workflows/integration_tests.yml | 55 ++- .github/workflows/size_budgets.yml | 74 +++- examples/README.md | 7 + packages/reflex-bench/README.md | 122 ++++-- packages/reflex-bench/budgets.json | 294 +++++++++++++- .../reflex-bench/src/reflex_bench/budgets.py | 5 +- packages/reflex-bench/src/reflex_bench/cli.py | 23 +- .../src/reflex_bench/drivers/lighthouse.py | 3 +- .../src/reflex_bench/report/pages.py | 123 ++++++ .../src/reflex_bench/suites/lighthouse.py | 3 +- .../src/reflex_bench/suites/size.py | 5 +- packages/reflex-components-ui/README.md | 5 +- .../parity/ui_parity/app.py | 42 +- .../parity/ui_parity/report.py | 46 ++- .../parity/ui_parity/shards.py | 178 +++++++++ scripts/ui_parity.py | 75 +++- .../tests_playwright/test_ui_parity.py | 33 +- .../reflex_bench/drivers/test_lighthouse.py | 119 ++++++ tests/units/reflex_bench/report/test_pages.py | 62 +++ tests/units/reflex_bench/suites/test_size.py | 76 +++- tests/units/reflex_bench/test_budgets.py | 377 +++++++++++------- tests/units/reflex_bench/test_registry.py | 13 + tests/units/reflex_bench/test_scheduler.py | 10 + .../parity/test_report.py | 46 +++ .../parity/test_shards.py | 113 ++++++ tests/units/test_ui_parity_script.py | 100 ++++- tests/units/test_workflow_gates.py | 5 +- 29 files changed, 1781 insertions(+), 261 deletions(-) create mode 100644 packages/reflex-bench/src/reflex_bench/report/pages.py create mode 100644 packages/reflex-components-ui/parity/ui_parity/shards.py create mode 100644 tests/units/reflex_bench/drivers/test_lighthouse.py create mode 100644 tests/units/reflex_bench/report/test_pages.py create mode 100644 tests/units/reflex_components_ui/parity/test_shards.py diff --git a/.github/rulesets/main-required-checks.json b/.github/rulesets/main-required-checks.json index 22335b46134..baf33d91cba 100644 --- a/.github/rulesets/main-required-checks.json +++ b/.github/rulesets/main-required-checks.json @@ -55,6 +55,10 @@ "context": "reflex-init-in-docker-test-gate", "integration_id": 15368 }, + { + "context": "size-budgets-gate", + "integration_id": 15368 + }, { "context": "unit-tests-gate", "integration_id": 15368 diff --git a/.github/workflows/benchmarks_daily.yml b/.github/workflows/benchmarks_daily.yml index 64a51731ad1..18d5870c1a0 100644 --- a/.github/workflows/benchmarks_daily.yml +++ b/.github/workflows/benchmarks_daily.yml @@ -54,6 +54,13 @@ jobs: - shard: exact filters: "wire.* size.*" timeout: 10 + # The page apps of examples/pages, which need rx.ui: their sizes and + # Lighthouse audits, reported against their budgets. Not in `daily`, + # which release backfills also run. + - shard: pages + suite: pages + filters: "size.* lighthouse.*" + timeout: 45 timeout-minutes: ${{ matrix.timeout }} runs-on: ubuntu-24.04-arm steps: @@ -68,7 +75,7 @@ jobs: with: python-version: "3.12" - name: Install the harness - run: uv sync --no-dev --group bench --extra db + run: uv sync --no-dev --group bench --extra db --extra ui # The harness owns every cache a measured phase reads; none is restored. - name: Point the bench home at the job's temporary directory run: echo "REFLEX_BENCH_HOME=$RUNNER_TEMP/reflex-bench" >> "$GITHUB_ENV" @@ -88,18 +95,31 @@ jobs: env: FILTERS: ${{ matrix.filters }} SHARD: ${{ matrix.shard }} + SUITE: ${{ matrix.suite || 'daily' }} # Manual dispatches are ad-hoc runs, kept out of the daily series. RUN_KIND: ${{ github.event_name == 'schedule' && 'daily' || 'ci' }} run: | set -f # shellcheck disable=SC2086 - uv run --no-sync reflex-bench run --suite daily $FILTERS --kind "$RUN_KIND" \ + uv run --no-sync reflex-bench run --suite "$SUITE" $FILTERS --kind "$RUN_KIND" \ --json "$SHARD.json" --no-save --fail-on never - name: Summarize if: always() && hashFiles(format('{0}.json', matrix.shard)) != '' env: SHARD: ${{ matrix.shard }} run: uv run --no-sync reflex-bench export "$SHARD.json" --to md >> "$GITHUB_STEP_SUMMARY" + # The Lighthouse budgets are reported, never enforced: the check fails + # only when a budgeted benchmark is missing or failed. + - name: Report the page apps against their budgets + if: always() && matrix.shard == 'pages' && hashFiles('pages.json') != '' + run: | + { + echo '### Page apps' + uv run --no-sync reflex-bench export pages.json --to pages + echo '```' + uv run --no-sync reflex-bench budgets check pages.json + echo '```' + } >> "$GITHUB_STEP_SUMMARY" - name: Upload the result if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/.github/workflows/integration_tests.yml b/.github/workflows/integration_tests.yml index 9a7daf90057..741f49f9dd7 100644 --- a/.github/workflows/integration_tests.yml +++ b/.github/workflows/integration_tests.yml @@ -354,15 +354,25 @@ jobs: 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. + # pixels, computed styles and accessibility tree, cell by cell. The + # components are split into shards of about equal run time + # (packages/reflex-components-ui/parity/ui_parity/shards.py), each building + # the pages of its own components; every matrix runs in exactly one shard. ui-parity: needs: changes if: needs.changes.outputs.run == 'true' timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # shards.COUNT of them: tests/units/test_workflow_gates.py checks. + shard: [1, 2, 3] 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_SHARD: ${{ matrix.shard }}/3 + # The build and the matrices of the shard together, in seconds: the run + # fails above. UI_PARITY_BUDGET_SECONDS: "900" steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -376,27 +386,59 @@ jobs: run-uv-sync: true - name: Install Playwright Chromium run: uv run playwright install chromium --only-shell - - name: Compare every matrix with Radix Themes + - name: Compare the shard's matrices 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 "### rx.ui parity run time, shard $UI_PARITY_SHARD" echo '```json' cat "$UI_PARITY_REPORT/timings.json" echo '```' } >> "$GITHUB_STEP_SUMMARY" fi - - name: Upload the report + - name: Upload the shard's report if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: ui-parity-report + name: ui-parity-report-${{ matrix.shard }} path: ui-parity-report if-no-files-found: warn + # The browsable report of every shard as one, also when a shard failed. + ui-parity-report: + needs: [changes, ui-parity] + if: always() && needs.changes.outputs.run == 'true' + timeout-minutes: 15 + 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 + # Each artifact in a directory of its name: the shards' results.json + # and index.html would overwrite each other. + - name: Download the shards' reports + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: ui-parity-report-* + path: shards + - name: Assemble the report + run: uv run python scripts/ui_parity.py --merge shards/* --report ui-parity-report + - name: Upload the report + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ui-parity-report + path: ui-parity-report + if-no-files-found: error + # The behaviour contract of every rx.ui component, and of the Radix one it # replaces, in each browser engine. ui-contracts: @@ -490,6 +532,7 @@ jobs: app-harness, app-harness-playwright, ui-parity, + ui-parity-report, ui-contracts, bun-only-startup, ] diff --git a/.github/workflows/size_budgets.yml b/.github/workflows/size_budgets.yml index 574fd728494..a626044c02a 100644 --- a/.github/workflows/size_budgets.yml +++ b/.github/workflows/size_budgets.yml @@ -8,23 +8,17 @@ concurrency: # Bundle bytes are deterministic, so they gate every pull request on a standard # runner: no statistics, no dedicated benchmark machine, no secrets. No branch -# filter on pull_request, so stacked pull requests are checked too. +# filter on pull_request, so stacked pull requests are checked too, and no path +# filter, so the gate always reports (the changes job filters instead). on: pull_request: - paths: - - "reflex/**" - - "packages/**" - - "examples/playground/**" - - "pyproject.toml" - - "uv.lock" - - ".github/workflows/size_budgets.yml" - - ".github/actions/setup_build_env/**" push: branches: ["main"] paths: - "reflex/**" - "packages/**" - "examples/playground/**" + - "examples/pages/**" - "pyproject.toml" - "uv.lock" - ".github/workflows/size_budgets.yml" @@ -39,9 +33,38 @@ defaults: shell: bash jobs: + # A path filter on the pull_request trigger would leave the required gate + # unreported on a pull request it skips; filtered here, the job below skips + # and the gate passes. + changes: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + run: ${{ steps.filter.outputs.changed }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/changed_paths + id: filter + with: + paths: | + reflex/** + packages/** + examples/playground/** + examples/pages/** + pyproject.toml + uv.lock + .github/workflows/size_budgets.yml + .github/actions/setup_build_env/** + size-budgets: name: size-budgets - timeout-minutes: 20 + needs: changes + if: needs.changes.outputs.run == 'true' + timeout-minutes: 30 runs-on: ubuntu-latest steps: # fetch-tags/fetch-depth: the workspace packages derive their versions from git. @@ -55,17 +78,40 @@ jobs: with: python-version: "3.14" run-uv-sync: true - # With CI=true, `run` fails only when the export fails (nothing is - # compared without --baseline); `budgets check` is the gate. - - name: Export the playground and measure its size + # The playground and every app of examples/pages. With CI=true, `run` + # fails only when an export fails (nothing is compared without + # --baseline); `budgets check` is the gate. + - name: Export the apps and measure their size env: RUN_KIND: ${{ github.event_name == 'pull_request' && 'pr' || 'ci' }} run: uv run --no-sync reflex-bench run 'size.*' --json size-result.json --no-save --kind "$RUN_KIND" + - name: Report the page weights + if: always() + run: | + if [ -f size-result.json ]; then + { + echo '### Page weight' + uv run --no-sync reflex-bench export size-result.json --to pages + } >> "$GITHUB_STEP_SUMMARY" + fi - name: Check the size budgets - run: uv run --no-sync reflex-bench budgets check size-result.json + run: uv run --no-sync reflex-bench budgets check size-result.json --only 'size.*' - name: Upload the result if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: size-result path: size-result.json + + # The one status check the branch rules require from this workflow. + size-budgets-gate: + needs: [changes, size-budgets] + if: always() + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/ci_gate + with: + needs: ${{ toJSON(needs) }} diff --git a/examples/README.md b/examples/README.md index 5e5d5881e80..13e0d09a8fe 100644 --- a/examples/README.md +++ b/examples/README.md @@ -35,3 +35,10 @@ uv run --directory examples/playground --project ../.. reflex run - [`playground`](playground/): a small multi-page app exercising state, events and routing. It is also the app the Reflex macro benchmarks drive, which adds a few rules; see its README. +- [`pages`](pages/): the apps whose page weight and load the Reflex benchmarks track and + budget: a blank app from the default template, a stateless and a stateful app of + `rx.el` elements, a page of one `rx.ui.button`, and a kitchen sink of every component + `rx` and `rx.ui` both have, once on each. `PAGES_APP` picks one + (`PAGES_APP=kitchen_sink_ui uv run reflex run`); `uv run reflex-bench run --suite + pages` measures them all (see `packages/reflex-bench/README.md`, "Page apps"). Its + `.content-hash` is kept like the playground's. diff --git a/packages/reflex-bench/README.md b/packages/reflex-bench/README.md index ddcf95d6880..563e3f0505e 100644 --- a/packages/reflex-bench/README.md +++ b/packages/reflex-bench/README.md @@ -19,6 +19,8 @@ $ uv run reflex-bench compare base.json head.json --format md $ uv run reflex-bench doctor $ uv run reflex-bench export result.json --to bmf $ uv run reflex-bench budgets check result.json +$ uv run reflex-bench run --suite pages --json pages.json +$ uv run reflex-bench export pages.json --to pages $ uv run reflex-bench noise ../bench-data/runs/ --format md $ uv run reflex-bench subjects list ``` @@ -33,16 +35,16 @@ $ uv run reflex-bench subjects list | `show FILE [--samples]` | One result in detail, optionally with every raw sample. | | `compare BASE HEAD [--format term\|md\|json]` | Compares two results; `json` prints the annotated head result. | | `doctor` | Machine checks that affect measurement noise, with fix hints. | -| `export FILE --to md\|bmf [-o OUT]` | Pull request markdown or [Bencher Metric Format](https://bencher.dev/docs/reference/bencher-metric-format/). | -| `budgets check FILE [--budgets BUDGETS]` | Checks a result against the metric maxima of `budgets.json` ([Size budgets](#size-budgets)). | +| `export FILE --to md\|bmf\|pages [-o OUT]` | Pull request markdown, [Bencher Metric Format](https://bencher.dev/docs/reference/bencher-metric-format/), or the table of the [page apps](#page-apps). | +| `budgets check FILE [--budgets BUDGETS] [--only GLOB]` | Checks a result against the limits of `budgets.json` ([Budgets](#budgets)). | | `noise PATH... [--kind daily] [--min-runs 10] [--format term\|md\|json]` | The per-metric noise table of stored results ([Noise table](#noise-table)). | | `subjects list` | The cached [subject](#subjects) venvs: spec, Python, key, size and last use. | | `subjects prune [--older-than 30d]` | Deletes venvs not used for that long (`30d`, `12h`, `90m`), leftovers of interrupted builds and git worktrees no venv uses. | `FILTER` is a glob on the benchmark id (`lifecycle.*`, `*.warm`). Suites are named selections: `smoke`, `pr`, `daily`, `macro` (the timings the CodSpeed macro -runner measures, see [CI](#ci)), `selftest` and `all` (every benchmark except -the self-tests). Self-tests only run when asked for, with `--suite selftest` or a +runner measures, see [CI](#ci)), `pages` (the [page apps](#page-apps)), +`selftest` and `all` (every benchmark except the self-tests). Self-tests only run when asked for, with `--suite selftest` or a filter starting with `selftest`. Main `run` options (every effective value is printed in the header and stored in @@ -140,6 +142,7 @@ from reflex_bench.registry import Metric, benchmark params={"ms": [10, 50]}, # cartesian product: selftest.sleep[ms=10], [ms=50] metrics={"wall": Metric(unit="s", direction="lower")}, warmup=1, + runs=None, # timed runs when --runs names none; None: 1 if exact, else automatic timeout=60, # seconds per prepare/sample/conclude call estimate=5, # rough seconds per sample, for `list` min_version=None, # e.g. "0.9.8": older subjects report "unsupported" @@ -745,20 +748,26 @@ reload's last `[timing]` line) and `dom_updated_s` (the page's mark). ## Size budgets -`size.export[app=playground]` (suites `pr` and `daily`) measures what a -production build of `examples/playground` ships. Its `setup` copies the files -git tracks of the example into the instance's work directory (each arm of an -`ab` run gets its own copy; `--keep` keeps it) and runs `reflex export ---frontend-only --no-zip --env prod` there; bun stays cached in reflex's data -directory under the cache directory. `sample` then measures the files on disk. -One export gives every metric, and every metric is exact, so one sample is -taken: +`size.export[app=...]` (suites `pr`, `daily` and `pages`; `pr` and `daily` +measure the playground alone, `pages` every app) measures what a production build of an example app ships: +`examples/playground`, or one of the [page apps](#page-apps). Its `setup` +copies the files git tracks of the example into the instance's work directory +(each arm of an `ab` run gets its own copy; `--keep` keeps it) and runs `reflex +export --frontend-only --no-zip --env prod` there, with `PAGES_APP` naming a +page app; bun stays cached in reflex's data directory under the cache +directory. `sample` then measures the files on disk. One export gives every +metric, and every metric but the build time is exact, so the benchmark declares +one run: | Metric | What | | --- | --- | | `initial_raw`, `initial_gzip`, `initial_brotli` | The JS and CSS the first page loads: the files the prerendered `index.html` references with ``, `` or `' "" ) +# The React Router manifest: what the browser loads for `/` besides the tags. +MANIFEST = ( + "window.__reactRouterManifest=" + + json.dumps({ + "entry": { + "module": "/assets/entry.client-BspSxdqQ.js", + "imports": ["/assets/chunk-5KNZJZUH-q9CrfzJj.js"], + }, + "routes": { + "root": { + "id": "root", + "module": "/assets/root-Dn4kQ1aZ.js", + "imports": ["/assets/chunk-5KNZJZUH-q9CrfzJj.js"], + }, + "routes/_index": { + "id": "routes/_index", + "parentId": "root", + "index": True, + "module": "/assets/_index-B_quYKgB.js", + "imports": [], + }, + "routes/[counter]._index": { + "id": "routes/[counter]._index", + "parentId": "root", + "path": "counter", + "module": "/assets/_counter_._index-C9rBuGsa.js", + "imports": [], + }, + }, + }) + + ";" +).encode() INITIAL = { - "assets/manifest-7ec94961.js": b"window.__manifest={};" * 20, + "assets/manifest-7ec94961.js": MANIFEST, "assets/entry.client-BspSxdqQ.js": b"import{a}from'./chunk.js';a();" * 200, "assets/chunk-5KNZJZUH-q9CrfzJj.js": b"export const a=()=>1;" * 500, "assets/__reflex_global_styles-NccINl-w.css": b".rt-Button{color:red}" * 300, @@ -44,6 +76,8 @@ "__spa-fallback.html": b"", "logo.svg": b"", "assets/_counter_._index-C9rBuGsa.js": b"export default 1;" * 40, + "assets/root-Dn4kQ1aZ.js": b"export const Layout=()=>null;" * 30, + "assets/_index-B_quYKgB.js": b"export default ()=>null;" * 25, } SIDECARS = { "index.html.gz": b"\x1f\x8b" * 30, @@ -123,6 +157,40 @@ def test_initial_files_follow_the_page_order_once_each(tmp_path: Path): assert initial == set(extra["initial_files"]) +def test_the_first_page_scripts_are_the_manifest_and_its_modules_for_slash( + tmp_path: Path, +): + values, extra = _measure(tmp_path) + # The entry, the root and the index route, each with its imports, once each; + # the route of /counter is not loaded for /. + assert extra["first_page_files"] == [ + "assets/manifest-HASH.js", + "assets/entry.client-HASH.js", + "assets/chunk-5KNZJZUH-HASH.js", + "assets/root-HASH.js", + "assets/_index-HASH.js", + ] + loaded = ( + "assets/manifest-7ec94961.js", + "assets/entry.client-BspSxdqQ.js", + "assets/chunk-5KNZJZUH-q9CrfzJj.js", + "assets/root-Dn4kQ1aZ.js", + "assets/_index-B_quYKgB.js", + ) + assert values["first_page_js_gzip"] == sum( + _gzip_size({**INITIAL, **OTHER}[name]) for name in loaded + ) + + +def test_a_manifest_without_an_index_route_fails_clearly(tmp_path: Path): + app = _export(tmp_path) + manifest = app / ".web" / "build" / "client" / "assets" / "manifest-7ec94961.js" + manifest.write_bytes(MANIFEST.replace(b'"index": true, ', b"")) + with pytest.raises(FileNotFoundError) as error: + size.measure_export(app, reflex_version="0.9.12") + assert str(error.value) == f"{manifest} lists no index route of the root" + + def test_sidecars_are_excluded_and_summed(tmp_path: Path): values, extra = _measure(tmp_path) assert extra["sidecar_bytes"] == sum(map(len, SIDECARS.values())) @@ -132,7 +200,7 @@ def test_sidecars_are_excluded_and_summed(tmp_path: Path): def test_chunks_count_the_javascript_assets(tmp_path: Path): values, _ = _measure(tmp_path) - assert values["chunks"] == 4 + assert values["chunks"] == 6 def test_page_weight_sums_every_script_and_stylesheet(tmp_path: Path): @@ -158,8 +226,8 @@ def test_page_weight_sums_every_script_and_stylesheet(tmp_path: Path): ) == ( sum(map(_gzip_size, scripts)), sum(map(_gzip_size, sheets)), - 7, - 6, + 9, + 8, 2, ) @@ -183,6 +251,8 @@ def test_the_breakdown_strips_hashes(tmp_path: Path): "assets/chunk-5KNZJZUH-HASH.js", "assets/__reflex_global_styles-HASH.css", "assets/_counter_._index-HASH.js", + "assets/root-HASH.js", + "assets/_index-HASH.js", } chunk = INITIAL["assets/chunk-5KNZJZUH-q9CrfzJj.js"] assert extra["files"]["assets/chunk-5KNZJZUH-HASH.js"] == { @@ -313,7 +383,7 @@ def test_the_benchmark_declares_what_sample_returns(tmp_path: Path): export = size.ExportSize() export.build_time = 12.5 result = bench.normalize(export.sample(ctx)) - assert (result.values["chunks"], result.values["build_time"]) == (4, 12.5) + assert (result.values["chunks"], result.values["build_time"]) == (6, 12.5) assert result.extra is not None assert result.extra["reflex_version"] == ctx.subject.reflex_version From 6efcd66989494df8e0402d8f6627a0e09d80292c Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 03:46:59 +0000 Subject: [PATCH 156/204] Name the color mode controls in their errors, and record their parity seconds The button and the switch of the color mode raise the errors of every rx.ui component under their own names: the button renders a private icon button without its props, whose position the CSS property of that name was taken by in the menu of allow_system. The icon takes no props in either namespace, which the spacing sweep now says. The seconds of the two matrices are measured here and scaled to the recorded ones by the dropdown menu measured in the same run. Claude-Session: https://claude.ai/code/session_014AwvTPs6inbXdhsoua28g1 --- .../reflex-components-ui/parity/seconds.json | 2 + .../components/color_mode.py | 41 +++++++++++++++++-- .../reflex-frontend/src/utils/event_loop.js | 4 +- pyi_hashes.json | 3 +- .../components/test_color_mode.py | 25 +++++++++++ .../reflex_components_ui/test_api_parity.py | 9 ++++ 6 files changed, 77 insertions(+), 7 deletions(-) diff --git a/packages/reflex-components-ui/parity/seconds.json b/packages/reflex-components-ui/parity/seconds.json index 31d2486e23b..8f0f4f8c76e 100644 --- a/packages/reflex-components-ui/parity/seconds.json +++ b/packages/reflex-components-ui/parity/seconds.json @@ -16,6 +16,7 @@ "checkbox_cards": 20.6, "checkbox_group": 7.3, "code": 12.4, + "color_mode": 7.1, "container": 4.3, "context_menu": 15.1, "data_list": 60.4, @@ -54,6 +55,7 @@ "text": 12.8, "text_area": 21.4, "text_field": 29.4, + "theme_panel": 34.8, "tooltip": 12.9, "vstack": 12.3 } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.py b/packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.py index 91de7e0aad3..1b2f212fbbb 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.py @@ -97,6 +97,23 @@ def _place(props: dict[str, Any], position: str | Var | None) -> None: props["position"] = position +class _Button(IconButton): + """The icon button a color mode button renders. + + It has none of the props of the color mode button, which its ``position`` + would otherwise take from the CSS property of that name. + """ + + @classmethod + def _display_name(cls) -> str: + """Get the name an app refers to the component by. + + Returns: + ``rx.ui.color_mode.button``. + """ + return "rx.ui.color_mode.button" + + class ColorModeIconButton(IconButton): """Icon Button for toggling light / dark mode via toggle_color_mode.""" @@ -142,19 +159,28 @@ def color_mode_item(_color_mode: Literal["light", "dark", "system"]): # On the button: Radix merges the props of its trigger into it. return dropdown_menu.root( - dropdown_menu.trigger(super().create(ColorModeIcon.create(), **props)), + dropdown_menu.trigger(_Button.create(ColorModeIcon.create(), **props)), dropdown_menu.content( color_mode_item("light"), color_mode_item("dark"), color_mode_item("system"), ), ) - return IconButton.create( + return _Button.create( ColorModeIcon.create(), on_click=toggle_color_mode, **props, ) + @classmethod + def _display_name(cls) -> str: + """Get the name an app refers to the component by. + + Returns: + ``rx.ui.color_mode.button``. + """ + return "rx.ui.color_mode.button" + class ColorModeSwitch(Switch): """Switch for toggling light / dark mode via toggle_color_mode.""" @@ -170,13 +196,22 @@ def create(cls, *children, **props) -> Component: Returns: The switch component. """ - return Switch.create( + return super().create( *children, checked=resolved_color_mode != LIGHT_COLOR_MODE, on_change=toggle_color_mode, **props, ) + @classmethod + def _display_name(cls) -> str: + """Get the name an app refers to the component by. + + Returns: + ``rx.ui.color_mode.switch``. + """ + return "rx.ui.color_mode.switch" + class ColorModeNamespace(Var): """Namespace for color mode components.""" diff --git a/packages/reflex-frontend/src/utils/event_loop.js b/packages/reflex-frontend/src/utils/event_loop.js index dcb111957c3..fd1e3349d22 100644 --- a/packages/reflex-frontend/src/utils/event_loop.js +++ b/packages/reflex-frontend/src/utils/event_loop.js @@ -113,9 +113,7 @@ export const useLocalEventLoop = () => { (events, args, event_actions) => { const add = () => runtime.addLocalEvents(events, args, event_actions, navigate, params); - return runtime.addLocalEvents - ? add() - : import("$/utils/state").then(add); + return runtime.addLocalEvents ? add() : import("$/utils/state").then(add); }, [], ); diff --git a/pyi_hashes.json b/pyi_hashes.json index ac95db8cbbf..c32f555e7c7 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,7 +118,7 @@ "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": "f753e71635ca82297fadda6574b9760e", - "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "0b8ff1aea31ac87df9c384e9dbdf5246", + "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "7adaf4068a85572198f646ae8009e51b", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "0d7b27ab1cb51ac891a31ed97f2f5567", @@ -136,6 +136,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.pyi": "950ecf12cfe68270c03f57dee11ce1c4", "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.pyi": "55446eddd45d81355eea0ada7370a6c3", "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.pyi": "63dc6c987c53e017e217e60f4686c4b9", + "packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.pyi": "b914252f1bc53816d7c5384faea6d2b5", "packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.pyi": "79193f172cbb6feb749a296f82af9814", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "28f5633fbda932ee598108e9d5a52e58", diff --git a/tests/units/reflex_components_ui/components/test_color_mode.py b/tests/units/reflex_components_ui/components/test_color_mode.py index 9c56c29ce0c..cc35edef449 100644 --- a/tests/units/reflex_components_ui/components/test_color_mode.py +++ b/tests/units/reflex_components_ui/components/test_color_mode.py @@ -3,9 +3,11 @@ from collections.abc import Callable from typing import Any +import pytest from reflex_base.components.component import Component from reflex_components_ui.components.color_mode import LiteralPosition from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError import reflex as rx @@ -211,3 +213,26 @@ def test_switch_is_on_in_dark_mode( def test_namespace_is_the_color_mode(): assert str(rx.ui.color_mode) == str(rx.color_mode) == "rawColorMode" assert rx.ui.color_mode._get_all_var_data() == rx.color_mode._get_all_var_data() + + +def test_button_that_allows_the_system_mode_keeps_its_corner( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """The position of the button is the CSS property, not a prop it takes.""" + component = compiled( + rx.ui.color_mode.button(allow_system=True, position="top-right") + ) + assert declared_styles(component)[2] == _icon_button_style( + declared_styles, compiled, position="fixed", top="2rem", right="2rem" + ) + + +def test_controls_name_themselves_in_errors(ui_plugin: UIPlugin): + with pytest.raises(StyleError) as error: + rx.ui.color_mode.switch(paddng="1px") + assert str(error.value) == ( + 'rx.ui.color_mode.switch: unknown CSS property "paddng". ' + 'Did you mean "padding"?' + ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 8b8af118736..db0e71a79a1 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -402,6 +402,10 @@ def test_every_component_has_the_api_of_its_radix_counterpart(): # they are given on, or drop it, as their rx counterparts do. NOT_STYLED = ("accordion.icon", "drawer.portal") +# The components that take no props at all, in either namespace: the icon of +# the color mode is a condition between two components. +NO_PROPS = ("color_mode.icon",) + @pytest.mark.parametrize("component", COMPONENTS) def test_spacing_props_are_props_or_name_the_style_to_use(ui_plugin, component: str): @@ -415,6 +419,11 @@ def test_spacing_props_are_props_or_name_the_style_to_use(ui_plugin, component: candidate = component_class(resolve(reflex_components_ui, component)) create = resolve(reflex_components_ui, component) arguments = ARGUMENTS.get(component, ()) + if component in NO_PROPS: + for namespace in (rx, reflex_components_ui): + with pytest.raises(TypeError): + resolve(namespace, component)(*arguments, m="2") + return for shorthand, style in SPACING_SHORTHANDS.items(): if shorthand in reference: assert shorthand in candidate.get_fields() From 4a48027a2356691bc0055c9a3faacf306e4810d6 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:15:31 +0000 Subject: [PATCH 157/204] Add the rx.ui migration codemod python -m reflex_components_ui.migrate rewrites the rx components rx.ui has to rx.ui, moves the theme to UIPlugin and reports what it cannot carry over, checking each literal style by building the rx.ui component from it. Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- .../src/reflex_components_ui/migrate.py | 1656 +++++++++++++++++ 1 file changed, 1656 insertions(+) create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/migrate.py diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py new file mode 100644 index 00000000000..740c3f61406 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -0,0 +1,1656 @@ +"""Move an app from the Radix components of ``rx`` to the ones of ``rx.ui``. + +Run it on the root of an app, the directory of its ``rxconfig.py``:: + + python -m reflex_components_ui.migrate . # rewrite the files + python -m reflex_components_ui.migrate . --diff # also print the diff + python -m reflex_components_ui.migrate . --check # change nothing + +It rewrites every reference to a component that ``rx.ui`` has, such as +``rx.text.em(...)`` to ``rx.ui.text.em(...)``, moves the theme of the app to +``rx.plugins.UIPlugin`` in ``rxconfig.py``, and reports, with file, line and +column, everything it cannot carry over. A style is checked by building the +``rx.ui`` component from the literal values of the call, so a report is the +error ``rx.ui`` itself would raise. The files are parsed with :mod:`ast` and +edited at the positions it gives, so the text around an edit is kept as it is. +""" + +from __future__ import annotations + +import argparse +import ast +import dataclasses +import difflib +import os +import re +import sys +from collections.abc import Iterator, Sequence +from functools import cache +from pathlib import Path +from typing import Any + +# The directories a walk does not enter, besides hidden ones and virtual +# environments. +_SKIPPED_DIRS = frozenset(("__pycache__", "node_modules")) +# The stylesheets searched for the class names of Radix Themes. +_STYLESHEETS = frozenset((".css", ".scss", ".sass", ".less")) +# The names of rx.ui that are no component of rx. +_NOT_COMPONENTS = frozenset(("tokens", "Theme")) +# The options of rx.theme that rx.ui.Theme takes. +_THEME_OPTIONS = frozenset(( + "accent_color", + "gray_color", + "radius", + "scaling", + "appearance", + "panel_background", + "has_background", +)) +# The modules whose components are those of Radix. +_RADIX_MODULES = ("reflex_components_radix", "reflex.components.radix") +# A class name of Radix Themes in a string or a stylesheet. +_RADIX_CLASS = re.compile(r"(? str: + """Write the item as a line of the report. + + Args: + root: The directory the path is shown relative to, when the file + is inside it. + + Returns: + ``path:line:column: [code] message``, the path with forward slashes. + """ + path = self.path + if root is not None and path.is_relative_to(root): + path = path.relative_to(root) + return ( + f"{path.as_posix()}:{self.line}:{self.column}: [{self.code}] {self.message}" + ) + + +@dataclasses.dataclass(frozen=True, slots=True) +class Result: + """What a migration changes and reports. + + Attributes: + changes: The original and the migrated source of every file it + changes, by path. + items: What it reports, in the order of the files and the positions. + """ + + changes: dict[Path, tuple[str, str]] + items: list[Item] + + def diff(self, root: Path | None = None) -> str: + """Write the changes as a unified diff. + + Args: + root: The directory the paths are shown relative to. + + Returns: + The diff of every changed file, in path order. + """ + out: list[str] = [] + for path in sorted(self.changes): + old, new = self.changes[path] + name = ( + path.relative_to(root) if root and path.is_relative_to(root) else path + ) + shown = name.as_posix().lstrip("/") + out.extend( + difflib.unified_diff( + old.splitlines(keepends=True), + new.splitlines(keepends=True), + f"a/{shown}", + f"b/{shown}", + ) + ) + return "".join(out) + + +@dataclasses.dataclass(frozen=True, slots=True) +class _Edit: + """A replacement of a span of a file's bytes.""" + + start: int + end: int + text: bytes + + +@cache +def _covered() -> frozenset[str]: + """Find the components of rx that rx.ui has. + + Returns: + The names under both ``rx`` and ``rx.ui``. + """ + import reflex + import reflex_components_ui + + return frozenset( + name + for name in reflex_components_ui.__all__ + if name not in _NOT_COMPONENTS and hasattr(reflex, name) + ) + + +def _resolve(package: str, names: Sequence[str]) -> Any: + """Look a dotted name up in a namespace. + + Args: + package: ``reflex`` or ``reflex_components_ui``. + names: The names after it. + + Returns: + What the names lead to, or None when one is missing. + """ + import reflex + import reflex_components_ui + + found: Any = reflex if package == "reflex" else reflex_components_ui + for name in names: + found = getattr(found, name, None) + if found is None: + return None + return found + + +def _declares(names: tuple[str, ...], prop: str) -> bool: + """Tell whether an rx.ui component declares a prop. + + Args: + names: The component, such as ``("table", "cell")``. + prop: The prop. + + Returns: + Whether the class the component creates has the prop. + """ + create = _resolve("reflex_components_ui", names) + owner = getattr(create, "__self__", None) + if not isinstance(owner, type): + # A namespace: its __call__ is the create of its root component. + owner = getattr(getattr(type(create), "__call__", None), "__self__", None) # noqa: B004 + return isinstance(owner, type) and prop in owner.get_props() + + +@cache +def _builds(names: tuple[str, ...], args: Any) -> bool: + """Tell whether rx.ui builds a component from its children alone. + + A component that does not, such as a select without its items, cannot be + probed one prop at a time. + + Args: + names: The component. + args: Its literal children, frozen. + + Returns: + Whether it builds. + """ + try: + _resolve("reflex_components_ui", names)(*_thaw(args)) + except Exception: + return False + return True + + +@cache +def _probe( + names: tuple[str, ...], args: Any, kwargs: Any, in_state: bool +) -> str | None: + """Build an rx.ui component and return the style error it raises. + + Args: + names: The component. + args: Its literal children, frozen so that the call is cached. + kwargs: Its props, a frozen dict. + in_state: Whether to also render it as a component held in state is + rendered: in the browser, where nothing conditional applies. + + Returns: + The message of the StyleError, or None when it builds or fails for + another reason, which is not the migration's to report. + """ + from reflex_base.components.dynamic import rendering_dynamic_component + + from reflex_components_ui.style.lower import StyleError + + try: + component = _resolve("reflex_components_ui", names)( + *_thaw(args), **_thaw(kwargs) + ) + if in_state: + with rendering_dynamic_component(): + component.render() + except StyleError as error: + return str(error) + except Exception: + return None + return None + + +def _freeze(value: Any) -> Any: + """Make a value hashable, for the cache of the probes. + + Args: + value: A literal, a dict or a list of them, or a Var. + + Returns: + The value with dicts as tuples of pairs and lists as tuples, tagged. + """ + if value.__class__ is dict: + return ("dict", tuple((key, _freeze(item)) for key, item in value.items())) + if value.__class__ is list: + return ("list", tuple(_freeze(item) for item in value)) + if value.__class__ in (set, tuple): + return ("tuple", tuple(_freeze(item) for item in value)) + return ("value", value) + + +def _thaw(frozen: Any) -> Any: + """Undo :func:`_freeze`. + + Args: + frozen: A frozen value. + + Returns: + The value. + """ + tag, value = frozen + if tag == "dict": + return {key: _thaw(item) for key, item in value} + if tag == "list": + return [_thaw(item) for item in value] + if tag == "tuple": + return tuple(_thaw(item) for item in value) + return value + + +def _source_files(paths: Sequence[Path]) -> Iterator[Path]: + """Walk the paths for the files a migration reads. + + Args: + paths: Files and directories. + + Yields: + Every Python file and stylesheet, outside hidden directories, virtual + environments and the directories in ``_SKIPPED_DIRS``, in path order. + """ + for path in paths: + if path.is_file(): + yield path + continue + for directory, dirs, files in os.walk(path): + here = Path(directory) + dirs[:] = sorted( + name + for name in dirs + if not name.startswith(".") + and name not in _SKIPPED_DIRS + and not (here / name / "pyvenv.cfg").exists() + ) + for name in sorted(files): + file = here / name + if file.suffix == ".py" or file.suffix in _STYLESHEETS: + yield file + + +def _find_rxconfig(paths: Sequence[Path]) -> Path | None: + """Find the rxconfig.py of the app the paths belong to. + + Args: + paths: The paths given to the migration. + + Returns: + The rxconfig.py of the directory given, when one of them has one. + """ + for path in paths: + if path.is_dir() and (path / "rxconfig.py").is_file(): + return path / "rxconfig.py" + return None + + +class _Source: + """The bytes of a file, the positions of its lines and its edits.""" + + def __init__(self, path: Path, data: bytes): + """Index the lines of a file. + + Args: + path: The file. + data: Its bytes. + """ + self.path = path + self.data = data + self.lines = data.splitlines(keepends=True) + self.starts = [0] + for line in self.lines: + self.starts.append(self.starts[-1] + len(line)) + self.edits: list[_Edit] = [] + self.items: list[Item] = [] + + def offset(self, line: int, column: int) -> int: + """Turn a position of ast into an offset. + + Args: + line: The line, from 1. + column: The column in UTF-8 bytes, from 0. + + Returns: + The offset in the file's bytes. + """ + return self.starts[line - 1] + column + + def start(self, node: Any) -> int: + """Find where a node starts. + + Args: + node: A node with a position. + + Returns: + Its offset. + """ + return self.offset(node.lineno, node.col_offset) + + def end(self, node: Any) -> int: + """Find where a node ends. + + Args: + node: A node with a position. + + Returns: + The offset after it. + """ + return self.offset(node.end_lineno, node.end_col_offset) + + def text(self, node: Any) -> str: + """Read the source of a node. + + Args: + node: A node with a position. + + Returns: + Its text. + """ + return self.data[self.start(node) : self.end(node)].decode() + + def item(self, node: Any, code: str, message: str) -> Item: + """Make an item at a node. + + Args: + node: A node with a position. + code: The kind of item. + message: What it is and what to do. + + Returns: + The item, its column counted in characters. + """ + line = self.lines[node.lineno - 1] + column = len(line[: node.col_offset].decode("utf-8", "replace")) + 1 + return Item(self.path, node.lineno, column, code, message) + + def report(self, node: Any, code: str, message: str) -> None: + """Report an item at a node. + + Args: + node: A node with a position. + code: The kind of item. + message: What it is and what to do. + """ + self.items.append(self.item(node, code, message)) + + def edit(self, start: int, end: int, text: str) -> None: + """Replace a span of the file. + + Args: + start: The offset of its first byte. + end: The offset after its last byte. + text: What replaces it. + """ + self.edits.append(_Edit(start, end, text.encode())) + + def apply(self, start: int = 0, end: int | None = None) -> str: + """Apply the edits inside a span. + + Args: + start: The offset the span starts at. + end: The offset after it, the end of the file when left out. + + Returns: + The text of the span with every edit inside it applied. + """ + end = len(self.data) if end is None else end + out: list[bytes] = [] + at = start + for edit in sorted(self.edits, key=lambda edit: (edit.start, edit.end)): + if edit.start < at or edit.end > end: + continue + out.extend((self.data[at : edit.start], edit.text)) + at = edit.end + out.append(self.data[at:end]) + return b"".join(out).decode() + + def indent(self, node: Any) -> str: + """Read the indentation of the line a node starts on. + + Args: + node: A node with a position. + + Returns: + The whitespace that starts the line. + """ + line = self.lines[node.lineno - 1].decode() + return line[: len(line) - len(line.lstrip())] + + def remove(self, items: Sequence[Any], drop: Sequence[int], close: int) -> None: + """Remove some items of a comma separated list, with their commas. + + Args: + items: The items, in source order. + drop: The indexes of the ones to remove. + close: The offset of the bracket that closes the list. + """ + dropped = set(drop) + kept = [index for index in range(len(items)) if index not in dropped] + last_kept = kept[-1] if kept else -1 + for index in sorted(dropped): + if index < last_kept: + # Up to the item after it: its comma and the space after go. + self.edit(self.start(items[index]), self.start(items[index + 1]), "") + trailing = [index for index in dropped if index > last_kept] + if not trailing: + return + last = self.end(items[max(trailing)]) + if kept: + self.edit(self.end(items[last_kept]), last, "") + return + # Every item goes: so does a trailing comma, which would stand alone. + after = last + while after < close and self.data[after : after + 1] in b" \t\r\n": + after += 1 + if self.data[after : after + 1] == b",": + last = after + 1 + self.edit(self.start(items[min(trailing)]), last, "") + + +def _arguments(call: ast.Call) -> list[ast.expr | ast.keyword]: + """List the arguments of a call in source order. + + Args: + call: The call. + + Returns: + Its positional and keyword arguments. + """ + return sorted( + [*call.args, *call.keywords], key=lambda arg: (arg.lineno, arg.col_offset) + ) + + +def _insert_item( + source: _Source, items: Sequence[Any], open_line: int, open_end: int, text: str +) -> None: + """Add an item after the last of a comma separated list. + + Args: + source: The file. + items: The items, in source order. + open_line: The line of the opening bracket. + open_end: The offset after the opening bracket, for an empty list. + text: The source of the item. + """ + if not items: + source.edit(open_end, open_end, text) + return + last = items[-1] + # One item a line when the last one is not on the line of the bracket. + separator = ",\n" + source.indent(last) if last.lineno != open_line else ", " + end = source.end(last) + source.edit(end, end, separator + text) + + +class _Analysis: + """What the migration found in one Python file.""" + + def __init__(self, source: _Source, fix_spacing: bool): + """Start the analysis of a file. + + Args: + source: The file. + fix_spacing: Whether to rewrite the margin and padding props. + """ + self.source = source + self.fix_spacing = fix_spacing + # The names the reflex module is bound to. + self.modules: set[str] = set() + # The covered components imported by name: local name to rx name. + self.imported: dict[str, str] = {} + self.import_nodes: list[ast.ImportFrom] = [] + # The local names some use of which stays on rx. + self.blocked_names: set[str] = set() + # Where a Radix component stays: the node and what it is. + self.radix: list[tuple[Any, str]] = [] + self.skip: set[int] = set() + self.blocked_refs: set[int] = set() + self.state_classes: set[str] = set() + self.component_states: set[str] = set() + self.in_state = 0 + # The theme of an App(theme=...) call, and the call. + self.app_theme: tuple[ast.Call, ast.keyword] | None = None + + def collect(self, tree: ast.Module) -> None: + """Read what the imports of the file bind. + + Args: + tree: Its syntax tree. + """ + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + if alias.name == "reflex": + self.modules.add(alias.asname or "reflex") + elif alias.name.startswith(_RADIX_MODULES): + self.radix.append((node, f"import {alias.name}")) + self.source.report( + node, + "kept", + f"{alias.name} is imported directly: its components are " + "not migrated, and keep RadixThemesPlugin.", + ) + elif isinstance(node, ast.ImportFrom) and node.level == 0: + self._import_from(node) + + def run(self, tree: ast.Module) -> None: + """Rewrite and check the components of the file. + + Args: + tree: Its syntax tree. + """ + self._visit(tree) + self._rewrite_imports() + + def _import_from(self, node: ast.ImportFrom) -> None: + """Record what a from-import binds. + + Args: + node: The import. + """ + module = node.module or "" + if module.startswith(_RADIX_MODULES): + self.radix.append((node, f"from {module} import ...")) + self.source.report( + node, + "kept", + f"{module} is imported from directly: its components are not " + "migrated, and keep RadixThemesPlugin.", + ) + return + if module != "reflex": + return + covered = _covered() + for alias in node.names: + if alias.name == "*": + self.radix.append((node, "from reflex import *")) + self.source.report( + node, + "unresolved", + "from reflex import * binds the Radix components under their " + "own names: import the ones of rx.ui by name instead.", + ) + elif alias.name in covered: + self.imported[alias.asname or alias.name] = alias.name + if any(alias.name in covered for alias in node.names): + self.import_nodes.append(node) + + def _visit(self, node: ast.AST) -> None: + """Visit a node and what it holds. + + Args: + node: The node. + """ + if isinstance(node, ast.ClassDef): + self._class(node) + return + if isinstance(node, ast.Call): + self._call(node) + elif isinstance(node, ast.Attribute): + if self._attribute(node): + return + elif isinstance(node, ast.Name): + self._name(node) + elif isinstance(node, ast.Constant) and node.value.__class__ is str: + self._radix_classes(node) + for child in ast.iter_child_nodes(node): + self._visit(child) + + def _class(self, node: ast.ClassDef) -> None: + """Visit a class, noting whether it is a state. + + Args: + node: The class. + """ + bases = {_last_name(base) for base in node.bases} + is_component_state = bool(bases & ({"ComponentState"} | self.component_states)) + is_state = not is_component_state and any( + base is not None and (base.endswith("State") or base in self.state_classes) + for base in bases + ) + if is_component_state: + self.component_states.add(node.name) + elif is_state: + self.state_classes.add(node.name) + self.in_state += is_state + for child in ast.iter_child_nodes(node): + self._visit(child) + self.in_state -= is_state + + def _target(self, func: ast.expr) -> tuple[str, ...] | None: + """Read the rx component a callee names. + + Args: + func: The callee. + + Returns: + Its names under rx, such as ``("text", "em")``, when it is a + covered component. + """ + names: list[str] = [] + while isinstance(func, ast.Attribute): + names.append(func.attr) + func = func.value + if not isinstance(func, ast.Name): + return None + names.reverse() + if func.id in self.modules: + if names and names[0] in _covered(): + return tuple(names) + return None + if func.id in self.imported: + return (self.imported[func.id], *names) + return None + + def _attribute(self, node: ast.Attribute) -> bool: + """Rewrite an attribute that names a covered component. + + Args: + node: The outermost attribute of a dotted name. + + Returns: + Whether the node is a dotted name on the reflex module, whose + parts need no visit. + """ + names: list[str] = [] + base: ast.expr = node + while isinstance(base, ast.Attribute): + names.append(base.attr) + base = base.value + if not isinstance(base, ast.Name) or base.id not in self.modules: + return False + names.reverse() + if names[0] == "radix": + self.radix.append((node, self.source.text(node))) + self.source.report( + node, + "kept", + f"{self.source.text(node)} is a Radix component by its own name: " + "not migrated, and keeps RadixThemesPlugin.", + ) + return True + if names[0] not in _covered() or id(node) in self.skip: + return True + if id(node) in self.blocked_refs: + return True + resolved = self._resolve_members(node, names) + if resolved: + end = self.source.end(base) + self.source.edit(end, end, ".ui") + return True + + def _resolve_members(self, node: Any, names: Sequence[str]) -> bool: + """Check that rx.ui has every member a dotted name reaches. + + Args: + node: The node, for the report. + names: The names after the module. + + Returns: + Whether the name can be rewritten: rx.ui has it, or rx lacks it too. + """ + if _resolve("reflex_components_ui", names) is not None: + return True + if _resolve("reflex", names) is None: + return True + dotted = ".".join(names) + self.radix.append((node, f"rx.{dotted}")) + self.source.report( + node, + "kept", + f"rx.ui has no {dotted}: rx.{dotted} is kept, and keeps RadixThemesPlugin.", + ) + return False + + def _name(self, node: ast.Name) -> None: + """Visit a name: the module passed on as a value, or a covered import. + + Args: + node: The name. + """ + if node.id in self.modules and isinstance(node.ctx, ast.Load): + self.radix.append((node, node.id)) + self.source.report( + node, + "unresolved", + f"the module {node.id} is passed on as a value: the components " + "reached through it are not migrated. Pass rx.ui, or name them.", + ) + elif node.id in self.imported and id(node) in self.blocked_refs: + self.blocked_names.add(node.id) + + def _call(self, node: ast.Call) -> None: + """Check the arguments of a call of a covered component. + + Args: + node: The call. + """ + if self._app_call(node): + return + names = self._target(node.func) + if names is None or id(node.func) in self.skip: + return + if self.in_state and self._held_in_state(node, names): + func = node.func + self.blocked_refs.add(id(func)) + while isinstance(func, ast.Attribute): + func = func.value + self.blocked_refs.add(id(func)) + return + args = _literal_args(node) + component = ".".join(names) + builds = _builds(names, args) + given = {keyword.arg for keyword in node.keywords if keyword.arg} + for keyword in node.keywords: + if keyword.arg is None: + self.source.report( + keyword, + "unresolved", + f"the props of rx.{component} passed with ** are not checked: " + "check them against the report of a call that names them.", + ) + continue + self._notes(component, keyword) + # A component rx.ui cannot build from its literal children alone, + # such as a select without its items, cannot be probed. + if builds: + self._keyword(names, args, keyword, given) + + def _app_call(self, node: ast.Call) -> bool: + """Record the theme of an App(theme=...) call. + + Args: + node: A call. + + Returns: + Whether the call is the App of the app. + """ + func = node.func + is_app = ( + isinstance(func, ast.Attribute) + and func.attr == "App" + and isinstance(func.value, ast.Name) + and func.value.id in self.modules + ) + if not is_app: + return False + for keyword in node.keywords: + if keyword.arg == "theme": + self.app_theme = (node, keyword) + self.skip.add(id(_callee(keyword.value))) + return True + + def _held_in_state(self, node: ast.Call, names: tuple[str, ...]) -> bool: + """Check a component built in a state, which is rendered in the browser. + + Args: + node: The call. + names: The component. + + Returns: + Whether rx.ui cannot render it there, so that it stays on rx. + """ + kwargs = {} + for keyword in node.keywords: + if keyword.arg is None: + continue + try: + kwargs[keyword.arg] = ast.literal_eval(keyword.value) + except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError): + continue + message = _probe(names, _literal_args(node), _freeze(kwargs), in_state=True) + if message is None: + return False + self.radix.append((node, f"rx.{'.'.join(names)}")) + self.source.report( + node, + "state", + f"rx.{'.'.join(names)} is built in a state, and kept: {message}", + ) + return True + + def _notes(self, component: str, keyword: ast.keyword) -> None: + """Report what changes with a prop of a component, or with its value. + + Args: + component: The component, such as ``text.span``. + keyword: The prop. + """ + prop = keyword.arg + note = _PROP_NOTES.get((component, prop)) # pyright: ignore[reportArgumentType] + if note is None and isinstance(keyword.value, ast.Constant): + note = _VALUE_NOTES.get((component, prop, keyword.value.value)) # pyright: ignore[reportArgumentType] + if note is not None: + self.source.report(keyword, "prop", note) + + def _keyword( + self, + names: tuple[str, ...], + args: Any, + keyword: ast.keyword, + given: set[str | None], + ) -> None: + """Check one prop of a covered component. + + Args: + names: The component. + args: Its literal children, frozen. + keyword: The prop. + given: The props the call names. + """ + prop = keyword.arg + assert prop is not None + value, exact = _value(keyword.value, self.modules) + if value is _UNKNOWN: + return + if prop == "style" and isinstance(keyword.value, ast.Dict): + self._style(names, args, keyword.value, given) + return + self._check(names, args, keyword, prop, keyword.value, value, exact, given) + + def _style( + self, + names: tuple[str, ...], + args: Any, + style: ast.Dict, + given: set[str | None], + ) -> None: + """Check every key of a literal style dict. + + Args: + names: The component. + args: Its literal children, frozen. + style: The dict. + given: The keys the dict names besides the props of the call. + """ + keys = {key.value for key in style.keys if isinstance(key, ast.Constant)} + for key, node in zip(style.keys, style.values, strict=True): + if not (isinstance(key, ast.Constant) and key.value.__class__ is str): + continue + value, exact = _value(node, self.modules) + if value is _UNKNOWN: + continue + self._check( + names, args, key, key.value, node, value, exact, keys, style=True + ) + + def _check( + self, + names: tuple[str, ...], + args: Any, + at: ast.keyword | ast.Constant, + key: str, + node: ast.expr, + value: Any, + exact: bool, + given: set[Any], + style: bool = False, + ) -> None: + """Build the component with one style and report what it raises. + + Args: + names: The component. + args: Its literal children, frozen. + at: The keyword or the key of the style, where an item is reported. + key: The prop or the style key. + node: The value as written. + value: The value, a placeholder Var where it is bound to state. + exact: Whether the value is the one written. + given: The other props or keys beside it, for a rewrite. + style: Whether the key is one of a style dict. + """ + from reflex_components_ui.style.lower import ( + _LAYOUT, + _SPACING_SHORTHANDS, + _space, + ) + + kwargs = {"style": {key: value}} if style else {key: value} + message = _probe(names, args, _freeze(kwargs), in_state=False) + if exact: + self._important(at, value) + if message is None: + return + spacing = key in _SPACING_SHORTHANDS and not _declares(names, key) + if not spacing: + if not exact and "bound to state" in message: + prefix = f"if {self.source.text(node)} is bound to state: " + if key in {"background", "bg"}: + message += ( + f" When it holds a color, write background_color=" + f"{self.source.text(node)}." + ) + message = prefix + message + self.source.report(at, "style", message) + return + replacement = _LAYOUT[key][0] + rewritable = ( + exact + and value.__class__ is str + and replacement not in given + and self._quoted(node) + and (not style or self._quoted(at)) + ) + if self.fix_spacing and rewritable: + quote = self.source.data[self.source.start(node)] + new = _space(value) + start = self.source.start(at) + if style: + key_quote = chr(self.source.data[start]) + self.source.edit( + start, self.source.end(at), f"{key_quote}{replacement}{key_quote}" + ) + else: + self.source.edit(start, start + len(key), replacement) + self.source.edit( + self.source.start(node), + self.source.end(node), + f"{chr(quote)}{new}{chr(quote)}", + ) + return + if self.fix_spacing: + reason = ( + f"{replacement} is already given" + if replacement in given + else "its value is not a string literal" + ) + message += f" Not rewritten: {reason}." + elif rewritable: + message += " --fix-spacing rewrites it." + self.source.report(at, "spacing", message) + + def _quoted(self, node: Any) -> bool: + """Tell whether a node is a plain quoted string, without a prefix. + + Args: + node: A node. + + Returns: + Whether its source starts with a quote. + """ + start = self.source.start(node) + return isinstance(node, ast.Constant) and self.source.data[ + start : start + 1 + ] in (b'"', b"'") + + def _important(self, at: Any, value: Any) -> None: + """Report the !important a literal style holds. + + Args: + at: Where the style is. + value: Its literal value. + """ + if value.__class__ is dict: + for item in value.values(): + self._important(at, item) + elif value.__class__ is str and "!important" in value: + self.source.report( + at, + "important", + f'"{value}": rx.ui merges a style over the component\'s own, so it ' + "needs no !important to win; remove it.", + ) + + def _radix_classes(self, node: ast.Constant) -> None: + """Report the class names of Radix Themes a string holds. + + Args: + node: A string. + """ + for match in _RADIX_CLASS.finditer(node.value): + self.source.report(node, "radix-class", _radix_class_message(match[1])) + + def _rewrite_imports(self) -> None: + """Move the covered components of from-imports to reflex_components_ui.""" + for node in self.import_nodes: + moved = [ + index + for index, alias in enumerate(node.names) + if (alias.asname or alias.name) in self.imported + and (alias.asname or alias.name) not in self.blocked_names + ] + if not moved: + continue + names = ", ".join(self.source.text(node.names[index]) for index in moved) + line = f"from reflex_components_ui import {names}" + if len(moved) == len(node.names): + self.source.edit(self.source.start(node), self.source.end(node), line) + continue + close = self.source.end(node) + self.source.remove(node.names, moved, close) + self.source.edit(close, close, f"\n{self.source.indent(node)}{line}") + + +def _radix_class_message(name: str) -> str: + """Word the report of a class name of Radix Themes. + + Args: + name: The class name. + + Returns: + The message. + """ + return ( + f'targets the Radix Themes class "{name}", which no rx.ui component ' + "carries: style the component through its props and style, or give it a " + "class_name of your own." + ) + + +def _last_name(node: ast.expr) -> str | None: + """Read the last name of a dotted name. + + Args: + node: An expression. + + Returns: + The name, or None when the expression is no dotted name. + """ + if isinstance(node, ast.Attribute): + return node.attr + if isinstance(node, ast.Name): + return node.id + return None + + +def _callee(node: ast.expr) -> ast.expr | None: + """Read the callee of a call. + + Args: + node: An expression. + + Returns: + The callee when the expression is a call. + """ + return node.func if isinstance(node, ast.Call) else None + + +_UNKNOWN = object() + + +def _literal_args(node: ast.Call) -> Any: + """Read the children of a call that are literals. + + Args: + node: The call. + + Returns: + The positional arguments when all of them are literals, else none, + frozen. + """ + try: + return _freeze([ast.literal_eval(arg) for arg in node.args]) + except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError): + return _freeze([]) + + +def _value(node: ast.expr, modules: set[str]) -> tuple[Any, bool]: + """Read the value of a prop or a style as rx.ui would see it. + + Args: + node: The value as written. + modules: The names of the reflex module. + + Returns: + The value and whether it is exactly the one written: a literal, or a + dict of them. A value read from state is a placeholder Var, and a value + that cannot be read is ``_UNKNOWN``. + """ + from reflex_base.vars.base import Var + + try: + return ast.literal_eval(node), True + except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError): + pass + if isinstance(node, ast.Dict): + out: dict[str, Any] = {} + exact = True + for key, item in zip(node.keys, node.values, strict=True): + if not (isinstance(key, ast.Constant) and key.value.__class__ is str): + return _UNKNOWN, False + value, item_exact = _value(item, modules) + if value is _UNKNOWN: + return _UNKNOWN, False + out[key.value] = value + exact &= item_exact + return out, exact + if isinstance(node, ast.Call): + func = node.func + if ( + isinstance(func, ast.Attribute) + and isinstance(func.value, ast.Name) + and func.value.id in modules + ): + if func.attr in _VAR_CALLS: + return Var(_js_expr="value"), False + if func.attr == "color" and not node.keywords: + import reflex + + try: + args = [ast.literal_eval(arg) for arg in node.args] + return reflex.color(*args), True + except Exception: + return _UNKNOWN, False + func_base = func.value if isinstance(func, ast.Attribute) else None + return (_state_like(func_base, modules), False) + return _state_like(node, modules), False + + +def _state_like(node: ast.expr | None, modules: set[str]) -> Any: + """Read an expression that may hold a value of state. + + Args: + node: The expression. + modules: The names of the reflex module. + + Returns: + A placeholder Var when the expression reads an attribute or an item of + something other than the reflex module, as ``State.color`` does, and + ``_UNKNOWN`` otherwise. + """ + from reflex_base.vars.base import Var + + if not isinstance(node, (ast.Attribute, ast.Subscript)): + return _UNKNOWN + base: ast.expr = node + while isinstance(base, (ast.Attribute, ast.Subscript, ast.Call)): + base = base.func if isinstance(base, ast.Call) else base.value + if isinstance(base, ast.Name) and base.id not in modules: + return Var(_js_expr="value") + return _UNKNOWN + + +def _theme(source: _Source, call: ast.Call, module: str) -> str: + """Turn an rx.theme(...) call into the source of an rx.ui.Theme(...). + + Args: + source: The file the call is in. + call: The call. + module: The name of the reflex module in the file it goes to. + + Returns: + The source of the theme, the options rx.ui.Theme does not take left + out and reported. + """ + arguments = _arguments(call) + drop = [] + for index, arg in enumerate(arguments): + if isinstance(arg, ast.keyword) and arg.arg in _THEME_OPTIONS: + if arg.arg == "appearance": + source.report( + arg, + "theme", + "rx.ui.Theme(appearance=...) colors the components in that " + "appearance, but does not set the color mode of the app: " + "rx.color_mode_cond and the color mode controls still follow it.", + ) + continue + if isinstance(arg, ast.keyword) and arg.arg is None: + source.report( + arg, + "theme", + "the options of the theme passed with ** are kept: rx.ui.Theme " + f"takes {', '.join(sorted(_THEME_OPTIONS))}.", + ) + continue + drop.append(index) + what = f"option {arg.arg}" if isinstance(arg, ast.keyword) else "child" + source.report( + arg, + "theme", + f"rx.ui.Theme takes no {what}: left out of the theme of UIPlugin. " + "Render it in the page, or wrap the page in rx.ui.theme(...).", + ) + saved = len(source.edits) + source.edit(source.start(call.func), source.end(call.func), f"{module}.ui.Theme") + source.remove(arguments, drop, source.end(call) - 1) + text = source.apply(source.start(call), source.end(call)) + del source.edits[saved:] + return text + + +def _is_theme_call(node: ast.expr | None, modules: set[str]) -> bool: + """Tell whether an expression is an rx.theme(...) call. + + Args: + node: The expression. + modules: The names of the reflex module. + + Returns: + Whether it is one. + """ + return ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "theme" + and isinstance(node.func.value, ast.Name) + and node.func.value.id in modules + ) + + +class _Config: + """The rxconfig.py of the app: its Config call and its plugins.""" + + def __init__(self, analysis: _Analysis, tree: ast.Module): + """Find the Config call and the plugins in it. + + Args: + analysis: The analysis of the file, whose imports are collected. + tree: Its syntax tree. + """ + self.source = analysis.source + self.modules = analysis.modules + self.config: ast.Call | None = None + self.plugins: ast.keyword | None = None + self.radix: list[int] = [] + self.ui = False + for node in ast.walk(tree): + if isinstance(node, ast.Call) and _last_name(node.func) == "Config": + self.config = node + for keyword in node.keywords: + if keyword.arg == "plugins": + self.plugins = keyword + if self.plugins is not None and isinstance(self.plugins.value, ast.List): + for index, item in enumerate(self.plugins.value.elts): + name = _last_name(item.func if isinstance(item, ast.Call) else item) + if name == "RadixThemesPlugin": + self.radix.append(index) + if isinstance(item, ast.Call): + for keyword in item.keywords: + analysis.skip.add(id(_callee(keyword.value))) + elif name == "UIPlugin": + self.ui = True + + def migrate( + self, + app_theme: tuple[_Analysis, ast.Call, ast.keyword] | None, + keeps: list[Item], + ) -> bool: + """Configure UIPlugin, and remove RadixThemesPlugin when nothing needs it. + + Args: + app_theme: The file, the call and the keyword of an App(theme=...). + keeps: Where a Radix component stays in the app. + + Returns: + Whether RadixThemesPlugin is gone, so that App(theme=...) can go too. + """ + source = self.source + if self.config is None: + source.items.append( + Item( + source.path, + 1, + 1, + "config", + "no rx.Config(...) call: add " + "rx.plugins.UIPlugin() to the plugins of the app yourself.", + ) + ) + return False + if self.plugins is not None and not isinstance(self.plugins.value, ast.List): + source.report( + self.plugins, + "config", + "plugins is not a list: add rx.plugins.UIPlugin() to it yourself, " + "and remove RadixThemesPlugin once no Radix component is left.", + ) + return False + module = next(iter(sorted(self.modules)), None) + if module is None: + source.items.append( + Item( + source.path, + 1, + 1, + "config", + "reflex is not imported as a " + "module: add rx.plugins.UIPlugin() to the plugins yourself.", + ) + ) + return False + theme = self._theme(module, app_theme) + plugin = ( + f"{module}.plugins.UIPlugin({'' if theme is None else f'theme={theme}'})" + ) + elts = self.plugins.value.elts if self.plugins else [] # pyright: ignore[reportAttributeAccessIssue] + keep_radix = bool(keeps) + if self.radix and keep_radix: + root = source.path.parent + where = ", ".join( + f"{item.format(root).split(': [', 1)[0]} ({item.message})" + for item in keeps + ) + source.report( + elts[self.radix[0]], + "config", + "RadixThemesPlugin stays, for the Radix components that remain: " + f"{where}.", + ) + if self.ui: + if self.radix and not keep_radix: + source.remove(elts, self.radix, source.end(self.plugins.value) - 1) # pyright: ignore[reportOptionalMemberAccess] + return not keep_radix + if self.plugins is None: + _insert_item( + source, + _arguments(self.config), + self.config.func.end_lineno or 1, + source.end(self.config.func) + 1, + f"plugins=[{plugin}]", + ) + return not keep_radix + if self.radix and not keep_radix: + first = elts[self.radix[0]] + source.edit(source.start(first), source.end(first), plugin) + source.remove(elts, self.radix[1:], source.end(self.plugins.value) - 1) + return True + _insert_item( + source, + elts, + self.plugins.value.lineno, + source.start(self.plugins.value) + 1, + plugin, + ) + return not keep_radix + + def _theme( + self, + module: str, + app_theme: tuple[_Analysis, ast.Call, ast.keyword] | None, + ) -> str | None: + """Find the theme of the app and write it as an rx.ui.Theme. + + Args: + module: The name of the reflex module in rxconfig.py. + app_theme: The file, the call and the keyword of an App(theme=...), + which wins over the theme of RadixThemesPlugin as it does in + Reflex. + + Returns: + The source of the theme, or None for the default one. + """ + if app_theme is not None: + analysis, _, keyword = app_theme + value = keyword.value + if isinstance(value, ast.Call) and _is_theme_call(value, analysis.modules): + return _theme(analysis.source, value, module) + analysis.source.report( + keyword, + "theme", + "the theme of App is not an rx.theme(...) call: give UIPlugin " + "an rx.ui.Theme(...) with the same options yourself.", + ) + return None + if not self.radix or self.plugins is None: + return None + plugin = self.plugins.value.elts[self.radix[0]] # pyright: ignore[reportAttributeAccessIssue] + if not isinstance(plugin, ast.Call): + return None + for keyword in plugin.keywords: + if keyword.arg != "theme": + continue + if isinstance(keyword.value, ast.Call) and _is_theme_call( + keyword.value, self.modules + ): + return _theme(self.source, keyword.value, module) + self.source.report( + keyword, + "theme", + "the theme of RadixThemesPlugin is not an rx.theme(...) call: give " + "UIPlugin an rx.ui.Theme(...) with the same options yourself.", + ) + return None + + +def migrate(paths: Sequence[Path], *, fix_spacing: bool = False) -> Result: + """Migrate the files under some paths from rx to rx.ui. + + Nothing is written: the result holds the migrated sources. + + Args: + paths: Files and directories. The rxconfig.py of the app is changed + when one of them is the directory that holds it. + fix_spacing: Whether to rewrite the margin and padding props of Radix, + which rx ignores, into the styles that set the spacing Radix means. + + Returns: + The changed sources and the report. + """ + paths = [Path(path).absolute() for path in paths] + rxconfig = _find_rxconfig(paths) + analyses: list[_Analysis] = [] + sources: list[_Source] = [] + config = None + for file in _source_files(paths): + source = _Source(file, file.read_bytes()) + sources.append(source) + if file.suffix in _STYLESHEETS: + _scan_stylesheet(source) + continue + try: + source.data.decode() + tree = ast.parse(source.data, filename=str(file)) + except (SyntaxError, UnicodeDecodeError) as error: + source.items.append( + Item( + file, + getattr(error, "lineno", None) or 1, + 1, + "skipped", + f"not migrated: {error.__class__.__name__}: {error}", + ) + ) + continue + analysis = _Analysis(source, fix_spacing) + analysis.collect(tree) + if file == rxconfig: + config = _Config(analysis, tree) + analysis.run(tree) + analyses.append(analysis) + if config is not None: + _migrate_config(config, analyses) + changes: dict[Path, tuple[str, str]] = {} + items: list[Item] = [] + for source in sources: + items.extend(source.items) + if source.edits: + old = source.data.decode() + new = source.apply() + if new != old: + changes[source.path] = (old, new) + items.sort() + return Result(changes, items) + + +def _migrate_config(config: _Config, analyses: Sequence[_Analysis]) -> None: + """Move the theme to UIPlugin, once the components of every file are known. + + Args: + config: The rxconfig.py of the app. + analyses: The analysis of every Python file. + """ + keeps: list[Item] = [] + app_theme = None + for analysis in analyses: + for node, what in analysis.radix: + keeps.append(analysis.source.item(node, "kept", what)) + if analysis.app_theme is not None and app_theme is None: + app_theme = (analysis, *analysis.app_theme) + keeps.sort() + radix_gone = config.migrate(app_theme, keeps) + if app_theme is None: + return + analysis, call, keyword = app_theme + source = analysis.source + if radix_gone: + arguments = _arguments(call) + source.remove(arguments, [arguments.index(keyword)], source.end(call) - 1) + else: + source.report( + keyword, + "theme", + "App(theme=...) stays for the Radix components that remain; UIPlugin " + "has the same theme as an rx.ui.Theme.", + ) + + +def _scan_stylesheet(source: _Source) -> None: + """Report the class names of Radix Themes in a stylesheet. + + Args: + source: The stylesheet. + """ + for number, line in enumerate( + source.data.decode("utf-8", "replace").splitlines(), 1 + ): + for match in _RADIX_CLASS.finditer(line): + source.items.append( + Item( + source.path, + number, + match.start() + 1, + "radix-class", + _radix_class_message(match[1]), + ) + ) + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the migration from the command line. + + Args: + argv: The arguments, those of the process when left out. + + Returns: + The exit status: 1 with --check when a file would change, else 0. + """ + parser = argparse.ArgumentParser( + prog="python -m reflex_components_ui.migrate", + description="Move an app from the Radix components of rx to rx.ui.", + ) + parser.add_argument( + "paths", + nargs="+", + type=Path, + help="the root of the app, the directory of rxconfig.py, or files in it", + ) + parser.add_argument( + "--check", action="store_true", help="change nothing, only report" + ) + parser.add_argument("--diff", action="store_true", help="print the diff") + parser.add_argument( + "--fix-spacing", + action="store_true", + help="rewrite the margin and padding props of Radix, which rx ignores, " + "into the styles that set that spacing: this adds spacing the page " + "never had", + ) + options = parser.parse_args(argv) + result = migrate(options.paths, fix_spacing=options.fix_spacing) + root = Path.cwd() + if options.diff: + sys.stdout.write(result.diff(root)) + if not options.check: + for path, (_, new) in result.changes.items(): + path.write_bytes(new.encode()) + for item in result.items: + sys.stdout.write(item.format(root) + "\n") + verb = "would change" if options.check else "changed" + sys.stdout.write( + f"{len(result.changes)} file{'s' * (len(result.changes) != 1)} {verb}, " + f"{len(result.items)} item{'s' * (len(result.items) != 1)} to review.\n" + ) + return 1 if options.check and result.changes else 0 + + +if __name__ == "__main__": + sys.exit(main()) From 935970edf7073a04ec6c68457cc9f70e6a461d60 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:19:12 +0000 Subject: [PATCH 158/204] Test the migration codemod on fixture apps Keep a rewritten from-import's comments, convert the theme of RadixThemesPlugin in place, report a spacing prop whatever its value, and report the other uses of an import kept for a component built in state. Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- .../src/reflex_components_ui/migrate.py | 275 ++++++++++++------ .../app_theme/after/app/app.py.txt | 11 + .../app_theme/after/rxconfig.py.txt | 10 + .../app_theme/before/app/app.py.txt | 18 ++ .../app_theme/before/rxconfig.py.txt | 5 + .../migrate_fixtures/app_theme/report.txt | 2 + .../fix_spacing/after/app/app.py.txt | 12 + .../fix_spacing/before/app/app.py.txt | 12 + .../fix_spacing/before/rxconfig.py.txt | 3 + .../migrate_fixtures/fix_spacing/report.txt | 3 + .../names/after/app/app.py.txt | 44 +++ .../names/after/rxconfig.py.txt | 3 + .../names/before/app/app.py.txt | 43 +++ .../names/before/app/broken.py.txt | 4 + .../names/before/app/untouched.py.txt | 7 + .../names/before/notes/plain.py.txt | 3 + .../names/before/rxconfig.py.txt | 3 + .../migrate_fixtures/names/report.txt | 1 + .../radix_gone/after/app/app.py.txt | 20 ++ .../radix_gone/after/rxconfig.py.txt | 17 ++ .../radix_gone/before/app/app.py.txt | 20 ++ .../radix_gone/before/rxconfig.py.txt | 17 ++ .../migrate_fixtures/radix_gone/report.txt | 1 + .../radix_kept/after/app/app.py.txt | 26 ++ .../radix_kept/after/rxconfig.py.txt | 3 + .../radix_kept/before/app/app.py.txt | 26 ++ .../radix_kept/before/rxconfig.py.txt | 3 + .../migrate_fixtures/radix_kept/report.txt | 6 + .../styles/after/app/app.py.txt | 44 +++ .../styles/after/rxconfig.py.txt | 3 + .../styles/before/app/app.py.txt | 44 +++ .../styles/before/app/assets/custom.css.txt | 3 + .../styles/before/rxconfig.py.txt | 3 + .../migrate_fixtures/styles/report.txt | 24 ++ .../reflex_components_ui/test_migrate.py | 221 ++++++++++++++ 35 files changed, 857 insertions(+), 83 deletions(-) create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/app_theme/report.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/after/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/report.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/after/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/after/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/before/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/before/app/broken.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/before/app/untouched.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/before/notes/plain.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/before/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/names/report.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_gone/report.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/styles/after/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/assets/custom.css.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/styles/before/rxconfig.py.txt create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt create mode 100644 tests/units/reflex_components_ui/test_migrate.py diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index 740c3f61406..5d00579390b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -24,6 +24,7 @@ import os import re import sys +import tokenize from collections.abc import Iterator, Sequence from functools import cache from pathlib import Path @@ -834,11 +835,13 @@ def _call(self, node: ast.Call) -> None: self.source.report( keyword, "unresolved", - f"the props of rx.{component} passed with ** are not checked: " - "check them against the report of a call that names them.", + f"the props passed to rx.{component} with ** are not checked: " + "check the calls that pass them for the props and styles this " + "report lists.", ) continue - self._notes(component, keyword) + # A namespace and its root take the same props. + self._notes(component.removesuffix(".root"), keyword) # A component rx.ui cannot build from its literal children alone, # such as a select without its items, cannot be probed. if builds: @@ -928,7 +931,7 @@ def _keyword( """ prop = keyword.arg assert prop is not None - value, exact = _value(keyword.value, self.modules) + value, exact = _value(keyword.value, self.modules, prop) if value is _UNKNOWN: return if prop == "style" and isinstance(keyword.value, ast.Dict): @@ -955,7 +958,7 @@ def _style( for key, node in zip(style.keys, style.values, strict=True): if not (isinstance(key, ast.Constant) and key.value.__class__ is str): continue - value, exact = _value(node, self.modules) + value, exact = _value(node, self.modules, key.value) if value is _UNKNOWN: continue self._check( @@ -1088,6 +1091,33 @@ def _radix_classes(self, node: ast.Constant) -> None: for match in _RADIX_CLASS.finditer(node.value): self.source.report(node, "radix-class", _radix_class_message(match[1])) + def _module_span(self, node: ast.ImportFrom) -> tuple[int, int]: + """Find the module name of a from-import, which ast gives no position. + + Args: + node: The import. + + Returns: + The offsets of the name's first byte and of the byte after it. + """ + start = self.source.start(node) + lines = self.source.data[start : self.source.end(node)].splitlines( + keepends=True + ) + tokens = tokenize.tokenize(iter(lines).__next__) + name = next( + token + for token in tokens + if token.type == tokenize.NAME and token.string == node.module + ) + (row, column), (_, end_column) = name.start, name.end + line_start = start + sum(len(line) for line in lines[: row - 1]) + line = lines[row - 1].decode() + return ( + line_start + len(line[:column].encode()), + line_start + len(line[:end_column].encode()), + ) + def _rewrite_imports(self) -> None: """Move the covered components of from-imports to reflex_components_ui.""" for node in self.import_nodes: @@ -1097,13 +1127,24 @@ def _rewrite_imports(self) -> None: if (alias.asname or alias.name) in self.imported and (alias.asname or alias.name) not in self.blocked_names ] + for alias in node.names: + local = alias.asname or alias.name + if local in self.blocked_names: + self.source.report( + alias, + "kept", + f"{local} stays imported from reflex for the use that stays " + f"on rx, and so do its other uses: name them " + f"rx.ui.{alias.name} to migrate them.", + ) if not moved: continue - names = ", ".join(self.source.text(node.names[index]) for index in moved) - line = f"from reflex_components_ui import {names}" if len(moved) == len(node.names): - self.source.edit(self.source.start(node), self.source.end(node), line) + start, end = self._module_span(node) + self.source.edit(start, end, "reflex_components_ui") continue + names = ", ".join(self.source.text(node.names[index]) for index in moved) + line = f"from reflex_components_ui import {names}" close = self.source.end(node) self.source.remove(node.names, moved, close) self.source.edit(close, close, f"\n{self.source.indent(node)}{line}") @@ -1172,17 +1213,39 @@ def _literal_args(node: ast.Call) -> Any: return _freeze([]) -def _value(node: ast.expr, modules: set[str]) -> tuple[Any, bool]: +def _value(node: ast.expr, modules: set[str], key: str = "") -> tuple[Any, bool]: """Read the value of a prop or a style as rx.ui would see it. Args: node: The value as written. modules: The names of the reflex module. + key: The prop or the style key it is the value of. Returns: The value and whether it is exactly the one written: a literal, or a dict of them. A value read from state is a placeholder Var, and a value - that cannot be read is ``_UNKNOWN``. + that cannot be read is ``_UNKNOWN``, except for a margin or padding + prop of Radix, which rx.ui refuses whatever its value: a placeholder. + """ + from reflex_base.vars.base import Var + + from reflex_components_ui.style.lower import _SPACING_SHORTHANDS + + value, exact = _read(node, modules) + if value is _UNKNOWN and key in _SPACING_SHORTHANDS: + return Var(_js_expr="value"), False + return value, exact + + +def _read(node: ast.expr, modules: set[str]) -> tuple[Any, bool]: + """Read a value as written, without regard to what it is the value of. + + Args: + node: The value as written. + modules: The names of the reflex module. + + Returns: + As for :func:`_value`. """ from reflex_base.vars.base import Var @@ -1196,7 +1259,7 @@ def _value(node: ast.expr, modules: set[str]) -> tuple[Any, bool]: for key, item in zip(node.keys, node.values, strict=True): if not (isinstance(key, ast.Constant) and key.value.__class__ is str): return _UNKNOWN, False - value, item_exact = _value(item, modules) + value, item_exact = _read(item, modules) if value is _UNKNOWN: return _UNKNOWN, False out[key.value] = value @@ -1248,17 +1311,19 @@ def _state_like(node: ast.expr | None, modules: set[str]) -> Any: return _UNKNOWN -def _theme(source: _Source, call: ast.Call, module: str) -> str: - """Turn an rx.theme(...) call into the source of an rx.ui.Theme(...). +def _theme(source: _Source, call: ast.Call, module: str, *, keep: bool) -> str: + """Turn an rx.theme(...) call into an rx.ui.Theme(...). Args: source: The file the call is in. call: The call. - module: The name of the reflex module in the file it goes to. + module: The name of the reflex module in the file the theme goes to. + keep: Whether the call is changed in place. Otherwise the file is left + as it is and only the source of the new theme is returned. Returns: - The source of the theme, the options rx.ui.Theme does not take left - out and reported. + The source of the theme, with the options rx.ui.Theme does not take + left out and reported. """ arguments = _arguments(call) drop = [] @@ -1293,7 +1358,8 @@ def _theme(source: _Source, call: ast.Call, module: str) -> str: source.edit(source.start(call.func), source.end(call.func), f"{module}.ui.Theme") source.remove(arguments, drop, source.end(call) - 1) text = source.apply(source.start(call), source.end(call)) - del source.edits[saved:] + if not keep: + del source.edits[saved:] return text @@ -1329,7 +1395,8 @@ def __init__(self, analysis: _Analysis, tree: ast.Module): self.source = analysis.source self.modules = analysis.modules self.config: ast.Call | None = None - self.plugins: ast.keyword | None = None + self.plugins: ast.List | None = None + self.plugins_keyword: ast.keyword | None = None self.radix: list[int] = [] self.ui = False for node in ast.walk(tree): @@ -1337,9 +1404,12 @@ def __init__(self, analysis: _Analysis, tree: ast.Module): self.config = node for keyword in node.keywords: if keyword.arg == "plugins": - self.plugins = keyword - if self.plugins is not None and isinstance(self.plugins.value, ast.List): - for index, item in enumerate(self.plugins.value.elts): + self.plugins_keyword = keyword + if self.plugins_keyword is not None and isinstance( + self.plugins_keyword.value, ast.List + ): + self.plugins = self.plugins_keyword.value + for index, item in enumerate(self.plugins.elts): name = _last_name(item.func if isinstance(item, ast.Call) else item) if name == "RadixThemesPlugin": self.radix.append(index) @@ -1349,6 +1419,29 @@ def __init__(self, analysis: _Analysis, tree: ast.Module): elif name == "UIPlugin": self.ui = True + def _problem(self) -> str | None: + """Find what keeps the plugins from being changed. + + Returns: + What to do by hand, or None when the plugins can be changed. + """ + if self.config is None: + return ( + "no rx.Config(...) call: add rx.plugins.UIPlugin() to the plugins " + "of the app yourself." + ) + if self.plugins_keyword is not None and self.plugins is None: + return ( + "plugins is not a list: add rx.plugins.UIPlugin() to it yourself, " + "and remove RadixThemesPlugin once no Radix component is left." + ) + if not self.modules: + return ( + "reflex is not imported as a module: add rx.plugins.UIPlugin() to " + "the plugins yourself." + ) + return None + def migrate( self, app_theme: tuple[_Analysis, ast.Call, ast.keyword] | None, @@ -1357,53 +1450,28 @@ def migrate( """Configure UIPlugin, and remove RadixThemesPlugin when nothing needs it. Args: - app_theme: The file, the call and the keyword of an App(theme=...). + app_theme: The file, the call and the keyword of an App(theme=...), + whose theme wins over the one of RadixThemesPlugin, as it does + in Reflex. keeps: Where a Radix component stays in the app. Returns: Whether RadixThemesPlugin is gone, so that App(theme=...) can go too. """ source = self.source - if self.config is None: - source.items.append( - Item( - source.path, - 1, - 1, - "config", - "no rx.Config(...) call: add " - "rx.plugins.UIPlugin() to the plugins of the app yourself.", - ) - ) - return False - if self.plugins is not None and not isinstance(self.plugins.value, ast.List): - source.report( - self.plugins, - "config", - "plugins is not a list: add rx.plugins.UIPlugin() to it yourself, " - "and remove RadixThemesPlugin once no Radix component is left.", - ) - return False - module = next(iter(sorted(self.modules)), None) - if module is None: - source.items.append( - Item( - source.path, - 1, - 1, - "config", - "reflex is not imported as a " - "module: add rx.plugins.UIPlugin() to the plugins yourself.", - ) - ) + problem = self._problem() + if problem is not None: + at = self.plugins_keyword or self.config + if at is None: + source.items.append(Item(source.path, 1, 1, "config", problem)) + else: + source.report(at, "config", problem) return False - theme = self._theme(module, app_theme) - plugin = ( - f"{module}.plugins.UIPlugin({'' if theme is None else f'theme={theme}'})" - ) - elts = self.plugins.value.elts if self.plugins else [] # pyright: ignore[reportAttributeAccessIssue] - keep_radix = bool(keeps) - if self.radix and keep_radix: + assert self.config is not None + module = min(self.modules) + elts = self.plugins.elts if self.plugins is not None else [] + close = source.end(self.plugins) - 1 if self.plugins is not None else 0 + if keeps and self.radix: root = source.path.parent where = ", ".join( f"{item.format(root).split(': [', 1)[0]} ({item.message})" @@ -1415,10 +1483,20 @@ def migrate( "RadixThemesPlugin stays, for the Radix components that remain: " f"{where}.", ) + gone = not keeps if self.ui: - if self.radix and not keep_radix: - source.remove(elts, self.radix, source.end(self.plugins.value) - 1) # pyright: ignore[reportOptionalMemberAccess] - return not keep_radix + if self.radix and gone: + source.remove(elts, self.radix, close) + return gone + replace = self.radix and gone + theme = self._theme(module, app_theme, in_place=bool(replace)) + if replace: + self._replace(elts[self.radix[0]], module, theme, app_theme is not None) + source.remove(elts, self.radix[1:], close) + return True + plugin = ( + f"{module}.plugins.UIPlugin({'' if theme is None else f'theme={theme}'})" + ) if self.plugins is None: _insert_item( source, @@ -1427,33 +1505,64 @@ def migrate( source.end(self.config.func) + 1, f"plugins=[{plugin}]", ) - return not keep_radix - if self.radix and not keep_radix: - first = elts[self.radix[0]] - source.edit(source.start(first), source.end(first), plugin) - source.remove(elts, self.radix[1:], source.end(self.plugins.value) - 1) - return True - _insert_item( - source, - elts, - self.plugins.value.lineno, - source.start(self.plugins.value) + 1, - plugin, + else: + _insert_item( + source, + elts, + self.plugins.lineno, + source.start(self.plugins) + 1, + plugin, + ) + return gone + + def _replace( + self, plugin: ast.expr, module: str, theme: str | None, from_app: bool + ) -> None: + """Turn RadixThemesPlugin into UIPlugin where it is written. + + Args: + plugin: The plugin as written. + module: The name of the reflex module. + theme: The source of the theme, or None for the default one. + from_app: Whether the theme comes from App(theme=...), so that it + replaces the one of the plugin. + """ + source = self.source + name = f"{module}.plugins.UIPlugin" + if not isinstance(plugin, ast.Call): + source.edit(source.start(plugin), source.end(plugin), name) + return + arguments = _arguments(plugin) + keyword = next((k for k in plugin.keywords if k.arg == "theme"), None) + convertible = keyword is not None and _is_theme_call( + keyword.value, self.modules ) - return not keep_radix + if theme is not None and (from_app or not convertible): + text = f"{name}(theme={theme})" + source.edit(source.start(plugin), source.end(plugin), text) + return + source.edit(source.start(plugin.func), source.end(plugin.func), name) + # The theme was converted in place: only the other arguments go. + drop = [ + index + for index, arg in enumerate(arguments) + if not (convertible and arg is keyword) + ] + source.remove(arguments, drop, source.end(plugin) - 1) def _theme( self, module: str, app_theme: tuple[_Analysis, ast.Call, ast.keyword] | None, + in_place: bool, ) -> str | None: """Find the theme of the app and write it as an rx.ui.Theme. Args: module: The name of the reflex module in rxconfig.py. - app_theme: The file, the call and the keyword of an App(theme=...), - which wins over the theme of RadixThemesPlugin as it does in - Reflex. + app_theme: The file, the call and the keyword of an App(theme=...). + in_place: Whether a theme of RadixThemesPlugin is converted where + it is written, the plugin becoming UIPlugin. Returns: The source of the theme, or None for the default one. @@ -1462,7 +1571,7 @@ def _theme( analysis, _, keyword = app_theme value = keyword.value if isinstance(value, ast.Call) and _is_theme_call(value, analysis.modules): - return _theme(analysis.source, value, module) + return _theme(analysis.source, value, module, keep=False) analysis.source.report( keyword, "theme", @@ -1472,7 +1581,7 @@ def _theme( return None if not self.radix or self.plugins is None: return None - plugin = self.plugins.value.elts[self.radix[0]] # pyright: ignore[reportAttributeAccessIssue] + plugin = self.plugins.elts[self.radix[0]] if not isinstance(plugin, ast.Call): return None for keyword in plugin.keywords: @@ -1481,7 +1590,7 @@ def _theme( if isinstance(keyword.value, ast.Call) and _is_theme_call( keyword.value, self.modules ): - return _theme(self.source, keyword.value, module) + return _theme(self.source, keyword.value, module, keep=in_place) self.source.report( keyword, "theme", diff --git a/tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/app/app.py.txt new file mode 100644 index 00000000000..98324c037c6 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/app/app.py.txt @@ -0,0 +1,11 @@ +import reflex as rx + + +def index() -> rx.Component: + return rx.ui.center(rx.ui.text("Hello")) + + +app = rx.App( + style={"font_family": "Inter"}, +) +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/rxconfig.py.txt new file mode 100644 index 00000000000..b46f9f89f76 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/after/rxconfig.py.txt @@ -0,0 +1,10 @@ +import reflex as rx + +config = rx.Config( + app_name="app", + plugins=[rx.plugins.UIPlugin(theme=rx.ui.Theme( + accent_color="orange", + radius="none", + has_background=True, + ))], +) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/app/app.py.txt new file mode 100644 index 00000000000..df01b1b2468 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/app/app.py.txt @@ -0,0 +1,18 @@ +import reflex as rx + + +def index() -> rx.Component: + return rx.center(rx.text("Hello")) + + +app = rx.App( + theme=rx.theme( + rx.theme_panel(), + accent_color="orange", + radius="none", + has_background=True, + style={"color": "red"}, + ), + style={"font_family": "Inter"}, +) +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/rxconfig.py.txt new file mode 100644 index 00000000000..6db70dc3f5e --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/before/rxconfig.py.txt @@ -0,0 +1,5 @@ +import reflex as rx + +config = rx.Config( + app_name="app", +) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/app_theme/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/report.txt new file mode 100644 index 00000000000..1bbc9328ffc --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/app_theme/report.txt @@ -0,0 +1,2 @@ +app/app.py:10:9: [theme] rx.ui.Theme takes no child: left out of the theme of UIPlugin. Render it in the page, or wrap the page in rx.ui.theme(...). +app/app.py:14:9: [theme] rx.ui.Theme takes no option style: left out of the theme of UIPlugin. Render it in the page, or wrap the page in rx.ui.theme(...). diff --git a/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/after/app/app.py.txt new file mode 100644 index 00000000000..fcdb623ade5 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/after/app/app.py.txt @@ -0,0 +1,12 @@ +import reflex as rx + + +def index() -> rx.Component: + return rx.ui.box( + rx.ui.text("Kwargs", padding_top="var(--space-2)", margin_x='calc(-1 * var(--space-3))', margin="0"), + rx.ui.text("Style keys", style={"padding_bottom": "var(--space-4)", 'margin_left': "auto"}), + rx.ui.text("Already set", pt="2", padding_top="1em"), + rx.ui.text("Not a literal", pl=rx.breakpoints(initial="1", md="2")), + rx.ui.text("A number", pr=2), + rx.ui.inset(rx.ui.text("Inset"), pt="2"), + ) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/app/app.py.txt new file mode 100644 index 00000000000..d55ece5656a --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/app/app.py.txt @@ -0,0 +1,12 @@ +import reflex as rx + + +def index() -> rx.Component: + return rx.box( + rx.text("Kwargs", pt="2", mx='-3', m="0"), + rx.text("Style keys", style={"pb": "4", 'ml': "auto"}), + rx.text("Already set", pt="2", padding_top="1em"), + rx.text("Not a literal", pl=rx.breakpoints(initial="1", md="2")), + rx.text("A number", pr=2), + rx.inset(rx.text("Inset"), pt="2"), + ) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/rxconfig.py.txt new file mode 100644 index 00000000000..ea5c67f7a72 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/before/rxconfig.py.txt @@ -0,0 +1,3 @@ +import reflex as rx + +config = rx.Config(app_name="app", plugins=[rx.plugins.UIPlugin()]) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/report.txt new file mode 100644 index 00000000000..567975004f4 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/fix_spacing/report.txt @@ -0,0 +1,3 @@ +app/app.py:8:32: [spacing] rx.ui.text: "pt" is not a CSS property, and rx.text ignores it too. Use padding_top="var(--space-2)" (or rx.ui.tokens.space[2]) for the spacing Radix's pt="2" means. Not rewritten: padding_top is already given. +app/app.py:9:34: [spacing] rx.ui.text: "pl" is not a CSS property, and rx.text ignores it too. Use padding_left, which takes any CSS value: step N of the spacing scale of Radix is "var(--space-N)", or rx.ui.tokens.space[N]. Not rewritten: its value is not a string literal. +app/app.py:10:29: [spacing] rx.ui.text: "pr" is not a CSS property, and rx.text ignores it too. Use padding_right, which takes any CSS value: step N of the spacing scale of Radix is "var(--space-N)", or rx.ui.tokens.space[N]. Not rewritten: its value is not a string literal. diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/after/app/app.py.txt new file mode 100644 index 00000000000..2b644197680 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/after/app/app.py.txt @@ -0,0 +1,44 @@ +"""Every way of naming a component.""" + +import reflex +import reflex as rx +from reflex import foreach +from reflex_components_ui import text as t +from reflex_components_ui import ( + box, # the outer box + vstack, +) + + +def menu() -> rx.Component: + return rx.ui.dropdown_menu.root( + rx.ui.dropdown_menu.trigger(rx.ui.button("Open")), + rx.ui.dropdown_menu.content( + rx.ui.dropdown_menu.item("Edit"), # the first item + rx.ui.dropdown_menu.separator(), + ), + ) + + +def index() -> rx.Component: + return box( + vstack( + t("Hello", t.em("world")), + rx.ui.text.em("emphasis"), + reflex.ui.heading("Title", size="5"), + rx.ui.select.root(rx.ui.select.trigger(), rx.ui.select.content()), + rx.ui.input(placeholder="Name"), + rx.ui.divider(), + rx.ui.color_mode.button(), + rx.ui.theme_panel(), + foreach(["a", "b"], rx.ui.badge), + rx.el.div("plain"), + rx.icon("x"), + rx.cond(True, rx.ui.spacer(), rx.fragment()), + ), + menu(), + ) + + +app = rx.App() +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/after/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/after/rxconfig.py.txt new file mode 100644 index 00000000000..ea5c67f7a72 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/after/rxconfig.py.txt @@ -0,0 +1,3 @@ +import reflex as rx + +config = rx.Config(app_name="app", plugins=[rx.plugins.UIPlugin()]) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/app.py.txt new file mode 100644 index 00000000000..79c5c5e9f56 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/app.py.txt @@ -0,0 +1,43 @@ +"""Every way of naming a component.""" + +import reflex +import reflex as rx +from reflex import foreach, text as t +from reflex import ( + box, # the outer box + vstack, +) + + +def menu() -> rx.Component: + return rx.dropdown_menu.root( + rx.dropdown_menu.trigger(rx.button("Open")), + rx.dropdown_menu.content( + rx.dropdown_menu.item("Edit"), # the first item + rx.dropdown_menu.separator(), + ), + ) + + +def index() -> rx.Component: + return box( + vstack( + t("Hello", t.em("world")), + rx.text.em("emphasis"), + reflex.heading("Title", size="5"), + rx.select.root(rx.select.trigger(), rx.select.content()), + rx.input(placeholder="Name"), + rx.divider(), + rx.color_mode.button(), + rx.theme_panel(), + foreach(["a", "b"], rx.badge), + rx.el.div("plain"), + rx.icon("x"), + rx.cond(True, rx.spacer(), rx.fragment()), + ), + menu(), + ) + + +app = rx.App() +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/broken.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/broken.py.txt new file mode 100644 index 00000000000..c256af580ee --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/broken.py.txt @@ -0,0 +1,4 @@ +import reflex as rx + +def index( + return rx.box() diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/untouched.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/untouched.py.txt new file mode 100644 index 00000000000..a70e660e939 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/before/app/untouched.py.txt @@ -0,0 +1,7 @@ +"""Plain elements and helpers only: nothing to migrate.""" + +import reflex as rx + + +def footer() -> rx.Component: + return rx.el.footer(rx.foreach(["a"], rx.el.span), rx.icon("heart")) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/before/notes/plain.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/before/notes/plain.py.txt new file mode 100644 index 00000000000..b68332eb416 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/before/notes/plain.py.txt @@ -0,0 +1,3 @@ +"""No reflex at all.""" + +text = "rx.box(pt='2')" diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/before/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/before/rxconfig.py.txt new file mode 100644 index 00000000000..ffcc4de0fba --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/before/rxconfig.py.txt @@ -0,0 +1,3 @@ +import reflex as rx + +config = rx.Config(app_name="app") diff --git a/tests/units/reflex_components_ui/migrate_fixtures/names/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/names/report.txt new file mode 100644 index 00000000000..4c6ca43d715 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/names/report.txt @@ -0,0 +1 @@ +app/broken.py:3:1: [skipped] not migrated: SyntaxError: '(' was never closed (broken.py, line 3) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/app/app.py.txt new file mode 100644 index 00000000000..996534a7d65 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/app/app.py.txt @@ -0,0 +1,20 @@ +import reflex as rx + + +class State(rx.State): + count: int = 0 + + @rx.var + def label(self) -> rx.Component: + return rx.ui.text("Count", color="gray") + + +def index() -> rx.Component: + return rx.ui.theme( + rx.ui.card(rx.ui.heading("Clock"), rx.ui.button("Start", on_click=State.set_count(1))), + accent_color="ruby", + ) + + +app = rx.App() +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/rxconfig.py.txt new file mode 100644 index 00000000000..f22c1facf9e --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/after/rxconfig.py.txt @@ -0,0 +1,17 @@ +import reflex as rx + +config = rx.Config( + app_name="app", + plugins=[ + rx.plugins.SitemapPlugin(), + rx.plugins.UIPlugin( + theme=rx.ui.Theme( + appearance="light", + has_background=True, + radius="large", + accent_color="amber", # the brand color + gray_color="sand", + ), + ), + ], +) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/app/app.py.txt new file mode 100644 index 00000000000..fcc6281ea23 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/app/app.py.txt @@ -0,0 +1,20 @@ +import reflex as rx + + +class State(rx.State): + count: int = 0 + + @rx.var + def label(self) -> rx.Component: + return rx.text("Count", color="gray") + + +def index() -> rx.Component: + return rx.theme( + rx.card(rx.heading("Clock"), rx.button("Start", on_click=State.set_count(1))), + accent_color="ruby", + ) + + +app = rx.App() +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/rxconfig.py.txt new file mode 100644 index 00000000000..757941424b7 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/before/rxconfig.py.txt @@ -0,0 +1,17 @@ +import reflex as rx + +config = rx.Config( + app_name="app", + plugins=[ + rx.plugins.SitemapPlugin(), + rx.plugins.RadixThemesPlugin( + theme=rx.theme( + appearance="light", + has_background=True, + radius="large", + accent_color="amber", # the brand color + gray_color="sand", + ), + ), + ], +) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/report.txt new file mode 100644 index 00000000000..b564aa669d9 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_gone/report.txt @@ -0,0 +1 @@ +rxconfig.py:9:17: [theme] rx.ui.Theme(appearance=...) colors the components in that appearance, but does not set the color mode of the app: rx.color_mode_cond and the color mode controls still follow it. diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/app/app.py.txt new file mode 100644 index 00000000000..01367caa3d9 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/app/app.py.txt @@ -0,0 +1,26 @@ +import reflex as rx +from reflex import button +from reflex_components_radix.themes.components.badge import Badge + + +class State(rx.State): + card: rx.Component = rx.ui.box("Built in state") + action: rx.Component = button("Go") + + +def page(ns) -> rx.Component: + return ns.box("Through a namespace") + + +def index() -> rx.Component: + return rx.ui.vstack( + rx.radix.themes.components.badge("Radix by name"), + Badge.create("Direct"), + page(rx), + button("In a page"), + rx.ui.select.root(rx.ui.select.item("A", value="a")), + ) + + +app = rx.App() +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/rxconfig.py.txt new file mode 100644 index 00000000000..268459eac83 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/after/rxconfig.py.txt @@ -0,0 +1,3 @@ +import reflex as rx + +config = rx.Config(app_name="app", plugins=[rx.plugins.RadixThemesPlugin(theme=rx.theme(accent_color="blue")), rx.plugins.UIPlugin(theme=rx.ui.Theme(accent_color="blue"))]) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/app/app.py.txt new file mode 100644 index 00000000000..d2adabf22cf --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/app/app.py.txt @@ -0,0 +1,26 @@ +import reflex as rx +from reflex import button +from reflex_components_radix.themes.components.badge import Badge + + +class State(rx.State): + card: rx.Component = rx.box("Built in state") + action: rx.Component = button("Go") + + +def page(ns) -> rx.Component: + return ns.box("Through a namespace") + + +def index() -> rx.Component: + return rx.vstack( + rx.radix.themes.components.badge("Radix by name"), + Badge.create("Direct"), + page(rx), + button("In a page"), + rx.select.root(rx.select.item("A", value="a")), + ) + + +app = rx.App() +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/rxconfig.py.txt new file mode 100644 index 00000000000..cc0f36f8002 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/before/rxconfig.py.txt @@ -0,0 +1,3 @@ +import reflex as rx + +config = rx.Config(app_name="app", plugins=[rx.plugins.RadixThemesPlugin(theme=rx.theme(accent_color="blue"))]) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt new file mode 100644 index 00000000000..d9623243344 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt @@ -0,0 +1,6 @@ +app/app.py:2:20: [kept] button stays imported from reflex for the use that stays on rx, and so do its other uses: name them rx.ui.button to migrate them. +app/app.py:3:1: [kept] reflex_components_radix.themes.components.badge is imported from directly: its components are not migrated, and keep RadixThemesPlugin. +app/app.py:8:28: [state] rx.button is built in a state, and kept: rx.ui.button: the style "backgroundColor" has conditions ("default", "@media (hover: hover)", "[data-state='open']", ":active:not([data-state='open'])", "[data-disabled]"), 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. +app/app.py:17:9: [kept] rx.radix.themes.components.badge is a Radix component by its own name: not migrated, and keeps RadixThemesPlugin. +app/app.py:19:14: [unresolved] the module rx is passed on as a value: the components reached through it are not migrated. Pass rx.ui, or name them. +rxconfig.py:3:45: [config] RadixThemesPlugin stays, for the Radix components that remain: app/app.py:3:1 (from reflex_components_radix.themes.components.badge import ...), app/app.py:8:28 (rx.button), app/app.py:17:9 (rx.radix.themes.components.badge), app/app.py:19:14 (rx). diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt new file mode 100644 index 00000000000..7fd5a61a196 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt @@ -0,0 +1,44 @@ +import reflex as rx + + +class State(rx.State): + bg: str = "red" + gap: str = "2" + + +def row(**props) -> rx.Component: + return rx.ui.flex(rx.ui.text("Row"), **props) + + +def index() -> rx.Component: + return rx.ui.vstack( + rx.ui.box("Spacing", pt="2", mx="-3", style={"pb": "4", "m": "auto"}), + rx.ui.box("Spacing from state", p=State.gap), + rx.ui.inset(rx.ui.text("Inset"), pt="2"), + rx.ui.table.root( + rx.ui.table.body( + rx.ui.table.row( + rx.ui.table.cell("Cell", px="3"), + rx.ui.table.row_header_cell("Header", py="1"), + ), + ), + ), + rx.ui.box("Nested", style={"& > div": {"color": "red"}, "_hover": {"color": "blue"}}), + rx.ui.box("Backgrounds", background="red url(dots.png)", bg="linear-gradient(red, blue), red"), + rx.ui.box("Fine background", background="var(--accent-3)"), + rx.ui.box("From state", background=State.bg), + rx.ui.box("Animated", animation="spin 1s linear infinite"), + rx.ui.text("Important", color="red !important", style={"font_weight": "bold !important"}), + rx.ui.button("Radix class", class_name="rt-reset my-button"), + rx.ui.container(rx.ui.vstack(), stack_children_full_width=True), + rx.ui.box("Typo", paddng="1em"), + row(pt="2"), + rx.ui.text("Label", as_="label", html_for="name"), + rx.ui.scroll_area(rx.ui.text("Long"), type="always", scroll_hide_delay=600), + rx.ui.select(["a", "b"], position="item-aligned"), + rx.ui.checkbox_group.root(rx.ui.checkbox_group.item(value="a"), orientation="horizontal"), + ) + + +app = rx.App(stylesheets=["/custom.css"]) +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/after/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/rxconfig.py.txt new file mode 100644 index 00000000000..ea5c67f7a72 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/rxconfig.py.txt @@ -0,0 +1,3 @@ +import reflex as rx + +config = rx.Config(app_name="app", plugins=[rx.plugins.UIPlugin()]) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt new file mode 100644 index 00000000000..200050463ab --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt @@ -0,0 +1,44 @@ +import reflex as rx + + +class State(rx.State): + bg: str = "red" + gap: str = "2" + + +def row(**props) -> rx.Component: + return rx.flex(rx.text("Row"), **props) + + +def index() -> rx.Component: + return rx.vstack( + rx.box("Spacing", pt="2", mx="-3", style={"pb": "4", "m": "auto"}), + rx.box("Spacing from state", p=State.gap), + rx.inset(rx.text("Inset"), pt="2"), + rx.table.root( + rx.table.body( + rx.table.row( + rx.table.cell("Cell", px="3"), + rx.table.row_header_cell("Header", py="1"), + ), + ), + ), + rx.box("Nested", style={"& > div": {"color": "red"}, "_hover": {"color": "blue"}}), + rx.box("Backgrounds", background="red url(dots.png)", bg="linear-gradient(red, blue), red"), + rx.box("Fine background", background="var(--accent-3)"), + rx.box("From state", background=State.bg), + rx.box("Animated", animation="spin 1s linear infinite"), + rx.text("Important", color="red !important", style={"font_weight": "bold !important"}), + rx.button("Radix class", class_name="rt-reset my-button"), + rx.container(rx.vstack(), stack_children_full_width=True), + rx.box("Typo", paddng="1em"), + row(pt="2"), + rx.text("Label", as_="label", html_for="name"), + rx.scroll_area(rx.text("Long"), type="always", scroll_hide_delay=600), + rx.select(["a", "b"], position="item-aligned"), + rx.checkbox_group.root(rx.checkbox_group.item(value="a"), orientation="horizontal"), + ) + + +app = rx.App(stylesheets=["/custom.css"]) +app.add_page(index) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/assets/custom.css.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/assets/custom.css.txt new file mode 100644 index 00000000000..eda0023a450 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/assets/custom.css.txt @@ -0,0 +1,3 @@ +/* Overrides of Radix Themes. */ +.rt-Button { border-radius: 0; } +.card .rt-Text, .rt-Heading { color: red; } diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/rxconfig.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/rxconfig.py.txt new file mode 100644 index 00000000000..e57c1aaddf5 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/rxconfig.py.txt @@ -0,0 +1,3 @@ +import reflex as rx + +config = rx.Config(app_name="app", plugins=[rx.plugins.RadixThemesPlugin()]) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt new file mode 100644 index 00000000000..d7bcf18b402 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt @@ -0,0 +1,24 @@ +app/app.py:10:36: [unresolved] the props passed to rx.flex with ** are not checked: check the calls that pass them for the props and styles this report lists. +app/app.py:15:27: [spacing] rx.ui.box: "pt" is not a CSS property, and rx.box ignores it too. Use padding_top="var(--space-2)" (or rx.ui.tokens.space[2]) for the spacing Radix's pt="2" means. --fix-spacing rewrites it. +app/app.py:15:35: [spacing] rx.ui.box: "mx" is not a CSS property, and rx.box ignores it too. Use margin_x="calc(-1 * var(--space-3))" for the spacing Radix's mx="-3" means. --fix-spacing rewrites it. +app/app.py:15:51: [spacing] rx.ui.box: "pb" is not a CSS property, and rx.box ignores it too. Use padding_bottom="var(--space-4)" (or rx.ui.tokens.space[4]) for the spacing Radix's pb="4" means. --fix-spacing rewrites it. +app/app.py:15:62: [spacing] rx.ui.box: "m" is not a CSS property, and rx.box ignores it too. Use margin="auto" for the spacing Radix's m="auto" means. --fix-spacing rewrites it. +app/app.py:16:38: [spacing] rx.ui.box: "p" is not a CSS property, and rx.box ignores it too. Use padding, which takes any CSS value: step N of the spacing scale of Radix is "var(--space-N)", or rx.ui.tokens.space[N]. +app/app.py:26:33: [style] rx.ui.box: style key "& > div" is a nested selector, which rx.ui styles do not support. Style the child component directly, or keep rx.box for this element. +app/app.py:27:31: [style] rx.ui.box: style "background" has the value "red url(dots.png)", which rx.ui styles cannot split into longhands. Set background_color, background_image and its other longhands instead. +app/app.py:27:63: [style] rx.ui.box: style "bg" has the value "linear-gradient(red, blue), red", which rx.ui styles cannot split into longhands. Set background_color, background_image and its other longhands instead. +app/app.py:29:30: [style] if State.bg is bound to state: rx.ui.box: 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. When it holds a color, write background_color=State.bg. +app/app.py:30:28: [style] rx.ui.box: style "animation" is a shorthand that rx.ui styles do not support. Set animation_name, animation_duration and its other longhands instead. +app/app.py:31:30: [important] "red !important": rx.ui merges a style over the component's own, so it needs no !important to win; remove it. +app/app.py:31:61: [important] "bold !important": rx.ui merges a style over the component's own, so it needs no !important to win; remove it. +app/app.py:32:45: [radix-class] targets the Radix Themes class "rt-reset", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. +app/app.py:33:35: [style] rx.ui.container: stack_children_full_width styles the stacks inside the container through nested selectors, which rx.ui styles do not support. Give those stacks width="100%", or keep rx.container for this element. +app/app.py:34:24: [style] rx.ui.box: unknown CSS property "paddng". Did you mean "padding"? +app/app.py:36:39: [prop] rx.text passes html_for on as a CSS key, which the browser ignores; rx.ui.text renders it as an attribute, so a label now names its control. +app/app.py:37:41: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no type: it has no effect. +app/app.py:37:56: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no scroll_hide_delay: it has no effect. +app/app.py:38:31: [prop] rx.ui.select places its list as position="popper" does: below the trigger, not over it. +app/app.py:39:67: [prop] Tab moves between the native checkboxes of rx.ui.checkbox_group, and the arrow keys do not: orientation has no effect. +app/assets/custom.css:2:1: [radix-class] targets the Radix Themes class "rt-Button", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. +app/assets/custom.css:3:7: [radix-class] targets the Radix Themes class "rt-Text", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. +app/assets/custom.css:3:17: [radix-class] targets the Radix Themes class "rt-Heading", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. diff --git a/tests/units/reflex_components_ui/test_migrate.py b/tests/units/reflex_components_ui/test_migrate.py new file mode 100644 index 00000000000..28ae266cd1c --- /dev/null +++ b/tests/units/reflex_components_ui/test_migrate.py @@ -0,0 +1,221 @@ +"""The migration from the Radix components of rx to rx.ui. + +Each directory of ``migrate_fixtures`` is an app: ``before`` is the app as +written, ``after`` holds every file the migration changes as it must leave +it, and ``report.txt`` is the whole report. The files end in ``.txt`` so that +no linter of the repository reads them. +""" + +from pathlib import Path + +import pytest +from reflex_components_ui import migrate +from reflex_components_ui.style.lower import _SPACING_SHORTHANDS +from ui_parity import allowlist + +FIXTURES = Path(__file__).parent / "migrate_fixtures" +GUIDE = Path(__file__).parents[3] / "docs" / "ui" / "rx_ui_migration.md" + +# The options of each fixture app. +CASES = { + "names": {}, + "radix_gone": {}, + "radix_kept": {}, + "app_theme": {}, + "styles": {}, + "fix_spacing": {"fix_spacing": True}, +} + + +def _fixture(source: Path) -> dict[str, str]: + """Read a tree of fixture files. + + Args: + source: The fixture tree. + + Returns: + The text of every file, by its path relative to the tree without the + ``.txt``. + """ + return { + file + .relative_to(source) + .as_posix() + .removesuffix(".txt"): file.read_bytes().decode() + for file in sorted(source.rglob("*.txt")) + } + + +def _copy(source: Path, target: Path) -> dict[str, str]: + """Copy a tree of fixture files, dropping their ``.txt``. + + Args: + source: The fixture tree. + target: Where the files go. + + Returns: + The text of every file, by its path relative to the tree. + """ + files = _fixture(source) + for name, text in files.items(): + (target / name).parent.mkdir(parents=True, exist_ok=True) + (target / name).write_bytes(text.encode()) + return files + + +def _tree(root: Path) -> dict[str, str]: + """Read every file of a tree. + + Args: + root: The tree. + + Returns: + The text of every file, by its path relative to the tree. + """ + return { + file.relative_to(root).as_posix(): file.read_bytes().decode() + for file in sorted(root.rglob("*")) + if file.is_file() + } + + +def _write(result: migrate.Result) -> None: + """Write the changes of a migration. + + Args: + result: The migration. + """ + for path, (_, new) in result.changes.items(): + path.write_bytes(new.encode()) + + +@pytest.mark.parametrize("case", sorted(CASES)) +def test_fixture_app(case: str, tmp_path: Path): + """An app migrates to its expected files and report, and only once. + + Args: + case: The fixture app. + tmp_path: Where the app is copied. + """ + expected = _copy(FIXTURES / case / "before", tmp_path) + expected.update(_fixture(FIXTURES / case / "after")) + result = migrate.migrate([tmp_path], **CASES[case]) + _write(result) + assert _tree(tmp_path) == expected + report = "".join(item.format(tmp_path) + "\n" for item in result.items) + assert report == (FIXTURES / case / "report.txt").read_text(encoding="utf-8") + again = migrate.migrate([tmp_path], **CASES[case]) + assert again.changes == {} + + +def test_untouched_files(tmp_path: Path): + """Files with nothing to migrate are left as they are, byte for byte. + + Args: + tmp_path: Where the app is copied. + """ + _copy(FIXTURES / "names" / "before", tmp_path) + result = migrate.migrate([tmp_path]) + assert sorted(path.relative_to(tmp_path).as_posix() for path in result.changes) == [ + "app/app.py", + "rxconfig.py", + ] + + +def test_files_without_their_rxconfig(tmp_path: Path): + """A migration of files leaves the rxconfig.py of their app alone. + + Args: + tmp_path: Where the app is copied. + """ + _copy(FIXTURES / "radix_gone" / "before", tmp_path) + result = migrate.migrate([tmp_path / "app"]) + assert list(result.changes) == [tmp_path / "app" / "app.py"] + assert result.items == [] + + +def test_main_check_and_diff( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture +): + """--check changes nothing and fails, --diff prints the diff, and a run writes. + + Args: + tmp_path: Where the app is copied. + monkeypatch: Changes the working directory. + capsys: Captures the output. + """ + files = _copy(FIXTURES / "app_theme" / "before", tmp_path) + monkeypatch.chdir(tmp_path) + assert migrate.main([".", "--check", "--diff"]) == 1 + assert _tree(tmp_path) == files + assert capsys.readouterr().out == ( + "--- a/app/app.py\n" + "+++ b/app/app.py\n" + "@@ -2,17 +2,10 @@\n" + " \n" + " \n" + " def index() -> rx.Component:\n" + '- return rx.center(rx.text("Hello"))\n' + '+ return rx.ui.center(rx.ui.text("Hello"))\n' + " \n" + " \n" + " app = rx.App(\n" + "- theme=rx.theme(\n" + "- rx.theme_panel(),\n" + '- accent_color="orange",\n' + '- radius="none",\n' + "- has_background=True,\n" + '- style={"color": "red"},\n' + "- ),\n" + ' style={"font_family": "Inter"},\n' + " )\n" + " app.add_page(index)\n" + "--- a/rxconfig.py\n" + "+++ b/rxconfig.py\n" + "@@ -2,4 +2,9 @@\n" + " \n" + " config = rx.Config(\n" + ' app_name="app",\n' + "+ plugins=[rx.plugins.UIPlugin(theme=rx.ui.Theme(\n" + '+ accent_color="orange",\n' + '+ radius="none",\n' + "+ has_background=True,\n" + "+ ))],\n" + " )\n" + "app/app.py:10:9: [theme] rx.ui.Theme takes no child: left out of the theme " + "of UIPlugin. Render it in the page, or wrap the page in rx.ui.theme(...).\n" + "app/app.py:14:9: [theme] rx.ui.Theme takes no option style: left out of the " + "theme of UIPlugin. Render it in the page, or wrap the page in " + "rx.ui.theme(...).\n" + "2 files would change, 2 items to review.\n" + ) + assert migrate.main(["."]) == 0 + capsys.readouterr() + assert _tree(tmp_path) != files + assert migrate.main([".", "--check"]) == 0 + assert capsys.readouterr().out == "0 files would change, 0 items to review.\n" + + +def test_reports_follow_the_allowlist(): + """The codemod reports every prop difference the parity allowlist records.""" + entries = allowlist.load().api + spacing = [entry for entry in entries if entry.kind == "style"] + assert [(entry.component, sorted(entry.names)) for entry in spacing] == [ + ("*", sorted(_SPACING_SHORTHANDS)) + ] + props = { + (entry.component, name) + for entry in entries + if entry.kind == "prop" + for name in entry.names + } + assert props == {key for key in migrate._PROP_NOTES if key[0].startswith("text")} + + +def test_guide_lists_the_allowlist(): + """The behaviour differences of the migration guide are those of the allowlist.""" + text = GUIDE.read_text(encoding="utf-8") + start = "\n" + end = "\n" + section = text[text.index(start) + len(start) : text.index(end)] + assert section == allowlist.differences_markdown(allowlist.load()) From 8a3bfd5e743ceaa0442f05fc34344b4a454166d4 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:21:28 +0000 Subject: [PATCH 159/204] Check style dicts named by a variable, and probe colors and state values A style given as a dict assigned once at the top of a module of the app is checked where it is written; one that cannot be found is reported. Values from rx.color and from state reach the probes as hashable markers. Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- .../src/reflex_components_ui/migrate.py | 247 ++++++++++++++---- .../styles/after/app/app.py.txt | 10 + .../styles/before/app/app.py.txt | 10 + .../styles/before/app/style.py.txt | 3 + .../migrate_fixtures/styles/report.txt | 46 ++-- 5 files changed, 238 insertions(+), 78 deletions(-) create mode 100644 tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/style.py.txt diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index 5d00579390b..6482e72bb85 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -319,6 +319,14 @@ def _thaw(frozen: Any) -> Any: The value. """ tag, value = frozen + if value is _STATE: + from reflex_base.vars.base import Var + + return Var(_js_expr="value") + if value.__class__ is _Color: + import reflex + + return reflex.color(*value.args) if tag == "dict": return {key: _thaw(item) for key, item in value} if tag == "list": @@ -599,13 +607,46 @@ def __init__(self, source: _Source, fix_spacing: bool): self.in_state = 0 # The theme of an App(theme=...) call, and the call. self.app_theme: tuple[ast.Call, ast.keyword] | None = None + # The dicts assigned once at the top of the module, by name. + self.constants: dict[str, ast.Dict] = {} + # The names imported from other files of the app: the file and the name. + self.style_imports: dict[str, tuple[Path, str]] = {} + # The analysis of every Python file of the app, by path. + self.project: dict[Path, _Analysis] = {} - def collect(self, tree: ast.Module) -> None: - """Read what the imports of the file bind. + def collect(self, tree: ast.Module, roots: Sequence[Path]) -> None: + """Read what the imports of the file bind, and its dicts. Args: tree: Its syntax tree. + roots: The directories an absolute import of the app starts from. """ + assigned: dict[str, int] = {} + for statement in tree.body: + targets = ( + statement.targets + if isinstance(statement, ast.Assign) + else [statement.target] + if isinstance(statement, ast.AnnAssign) + else [] + ) + for target in targets: + if isinstance(target, ast.Name): + assigned[target.id] = assigned.get(target.id, 0) + 1 + if isinstance(statement.value, ast.Dict): # pyright: ignore[reportAttributeAccessIssue] + self.constants[target.id] = statement.value # pyright: ignore[reportAttributeAccessIssue] + for name, count in assigned.items(): + if count > 1: + self.constants.pop(name, None) + for statement in tree.body: + if isinstance(statement, ast.ImportFrom): + origin = _module_file(self.source.path, statement, roots) + if origin is not None: + for alias in statement.names: + self.style_imports[alias.asname or alias.name] = ( + origin, + alias.name, + ) for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: @@ -931,11 +972,24 @@ def _keyword( """ prop = keyword.arg assert prop is not None + if prop == "style" and isinstance(keyword.value, ast.Name): + found = self._style_by_name(keyword.value.id) + if found is None: + self.source.report( + keyword, + "unresolved", + f"the style {keyword.value.id} is not a dict assigned once at " + "the top of a module of the app: it is not checked. Check it " + "for the styles this report lists.", + ) + else: + self._style(names, args, found[1], given, found[0]) + return value, exact = _value(keyword.value, self.modules, prop) if value is _UNKNOWN: return if prop == "style" and isinstance(keyword.value, ast.Dict): - self._style(names, args, keyword.value, given) + self._style(names, args, keyword.value, given, self) return self._check(names, args, keyword, prop, keyword.value, value, exact, given) @@ -945,6 +999,7 @@ def _style( args: Any, style: ast.Dict, given: set[str | None], + owner: _Analysis, ) -> None: """Check every key of a literal style dict. @@ -952,19 +1007,50 @@ def _style( names: The component. args: Its literal children, frozen. style: The dict. - given: The keys the dict names besides the props of the call. + given: The props of the call. + owner: The analysis of the file the dict is written in. """ keys = {key.value for key in style.keys if isinstance(key, ast.Constant)} for key, node in zip(style.keys, style.values, strict=True): if not (isinstance(key, ast.Constant) and key.value.__class__ is str): continue - value, exact = _value(node, self.modules, key.value) + value, exact = _value(node, owner.modules, key.value) if value is _UNKNOWN: continue self._check( - names, args, key, key.value, node, value, exact, keys, style=True + names, + args, + key, + key.value, + node, + value, + exact, + keys, + style=True, + source=owner.source, ) + def _style_by_name(self, name: str) -> tuple[_Analysis, ast.Dict] | None: + """Find the dict a style named by a variable is. + + Args: + name: The variable. + + Returns: + The analysis of the file that assigns the dict and the dict, when + the variable is a dict assigned once at the top of this module or + imported from another module of the app. + """ + if name in self.constants: + return self, self.constants[name] + origin = self.style_imports.get(name) + if origin is None: + return None + owner = self.project.get(origin[0]) + if owner is None or origin[1] not in owner.constants: + return None + return owner, owner.constants[origin[1]] + def _check( self, names: tuple[str, ...], @@ -976,6 +1062,7 @@ def _check( exact: bool, given: set[Any], style: bool = False, + source: _Source | None = None, ) -> None: """Build the component with one style and report what it raises. @@ -989,7 +1076,9 @@ def _check( exact: Whether the value is the one written. given: The other props or keys beside it, for a rewrite. style: Whether the key is one of a style dict. + source: The file the style is written in, this one when left out. """ + source = source or self.source from reflex_components_ui.style.lower import ( _LAYOUT, _SPACING_SHORTHANDS, @@ -999,43 +1088,43 @@ def _check( kwargs = {"style": {key: value}} if style else {key: value} message = _probe(names, args, _freeze(kwargs), in_state=False) if exact: - self._important(at, value) + self._important(source, at, value) if message is None: return spacing = key in _SPACING_SHORTHANDS and not _declares(names, key) if not spacing: if not exact and "bound to state" in message: - prefix = f"if {self.source.text(node)} is bound to state: " + prefix = f"if {source.text(node)} is bound to state: " if key in {"background", "bg"}: message += ( f" When it holds a color, write background_color=" - f"{self.source.text(node)}." + f"{source.text(node)}." ) message = prefix + message - self.source.report(at, "style", message) + source.report(at, "style", message) return replacement = _LAYOUT[key][0] rewritable = ( exact and value.__class__ is str and replacement not in given - and self._quoted(node) - and (not style or self._quoted(at)) + and _quoted(source, node) + and (not style or _quoted(source, at)) ) if self.fix_spacing and rewritable: - quote = self.source.data[self.source.start(node)] + quote = source.data[source.start(node)] new = _space(value) - start = self.source.start(at) + start = source.start(at) if style: - key_quote = chr(self.source.data[start]) - self.source.edit( - start, self.source.end(at), f"{key_quote}{replacement}{key_quote}" + key_quote = chr(source.data[start]) + source.edit( + start, source.end(at), f"{key_quote}{replacement}{key_quote}" ) else: - self.source.edit(start, start + len(key), replacement) - self.source.edit( - self.source.start(node), - self.source.end(node), + source.edit(start, start + len(key), replacement) + source.edit( + source.start(node), + source.end(node), f"{chr(quote)}{new}{chr(quote)}", ) return @@ -1048,34 +1137,21 @@ def _check( message += f" Not rewritten: {reason}." elif rewritable: message += " --fix-spacing rewrites it." - self.source.report(at, "spacing", message) - - def _quoted(self, node: Any) -> bool: - """Tell whether a node is a plain quoted string, without a prefix. - - Args: - node: A node. + source.report(at, "spacing", message) - Returns: - Whether its source starts with a quote. - """ - start = self.source.start(node) - return isinstance(node, ast.Constant) and self.source.data[ - start : start + 1 - ] in (b'"', b"'") - - def _important(self, at: Any, value: Any) -> None: + def _important(self, source: _Source, at: Any, value: Any) -> None: """Report the !important a literal style holds. Args: + source: The file the style is written in. at: Where the style is. value: Its literal value. """ if value.__class__ is dict: for item in value.values(): - self._important(at, item) + self._important(source, at, item) elif value.__class__ is str and "!important" in value: - self.source.report( + source.report( at, "important", f'"{value}": rx.ui merges a style over the component\'s own, so it ' @@ -1150,6 +1226,46 @@ def _rewrite_imports(self) -> None: self.source.edit(close, close, f"\n{self.source.indent(node)}{line}") +def _quoted(source: _Source, node: Any) -> bool: + """Tell whether a node is a plain quoted string, without a prefix. + + Args: + source: The file of the node. + node: A node. + + Returns: + Whether its source starts with a quote. + """ + start = source.start(node) + return isinstance(node, ast.Constant) and source.data[start : start + 1] in ( + b'"', + b"'", + ) + + +def _module_file( + path: Path, node: ast.ImportFrom, roots: Sequence[Path] +) -> Path | None: + """Find the file of the app a from-import reads. + + Args: + path: The file the import is in. + node: The import. + roots: The directories an absolute import starts from. + + Returns: + The module's file, when it is one of the app. + """ + parts = (node.module or "").split(".") if node.module else [] + bases = [path.parents[node.level - 1]] if node.level else list(roots) + for base in bases: + module = base.joinpath(*parts) + for file in (module.with_suffix(".py"), module / "__init__.py"): + if parts and file.is_file(): + return file + return None + + def _radix_class_message(name: str) -> str: """Word the report of a class name of Radix Themes. @@ -1195,6 +1311,19 @@ def _callee(node: ast.expr) -> ast.expr | None: _UNKNOWN = object() +# A value read from state, which a probe is given as a Var. +_STATE = object() + + +@dataclasses.dataclass(frozen=True, slots=True) +class _Color: + """An rx.color(...) call with literal arguments, which a probe evaluates. + + Attributes: + args: Its arguments. + """ + + args: tuple[Any, ...] def _literal_args(node: ast.Call) -> Any: @@ -1227,13 +1356,11 @@ def _value(node: ast.expr, modules: set[str], key: str = "") -> tuple[Any, bool] that cannot be read is ``_UNKNOWN``, except for a margin or padding prop of Radix, which rx.ui refuses whatever its value: a placeholder. """ - from reflex_base.vars.base import Var - from reflex_components_ui.style.lower import _SPACING_SHORTHANDS value, exact = _read(node, modules) if value is _UNKNOWN and key in _SPACING_SHORTHANDS: - return Var(_js_expr="value"), False + return _STATE, False return value, exact @@ -1247,8 +1374,6 @@ def _read(node: ast.expr, modules: set[str]) -> tuple[Any, bool]: Returns: As for :func:`_value`. """ - from reflex_base.vars.base import Var - try: return ast.literal_eval(node), True except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError): @@ -1273,15 +1398,19 @@ def _read(node: ast.expr, modules: set[str]) -> tuple[Any, bool]: and func.value.id in modules ): if func.attr in _VAR_CALLS: - return Var(_js_expr="value"), False + return _STATE, False if func.attr == "color" and not node.keywords: - import reflex - try: - args = [ast.literal_eval(arg) for arg in node.args] - return reflex.color(*args), True - except Exception: + args = tuple(ast.literal_eval(arg) for arg in node.args) + except ( + ValueError, + TypeError, + SyntaxError, + MemoryError, + RecursionError, + ): return _UNKNOWN, False + return _Color(args), True func_base = func.value if isinstance(func, ast.Attribute) else None return (_state_like(func_base, modules), False) return _state_like(node, modules), False @@ -1299,15 +1428,13 @@ def _state_like(node: ast.expr | None, modules: set[str]) -> Any: something other than the reflex module, as ``State.color`` does, and ``_UNKNOWN`` otherwise. """ - from reflex_base.vars.base import Var - if not isinstance(node, (ast.Attribute, ast.Subscript)): return _UNKNOWN base: ast.expr = node while isinstance(base, (ast.Attribute, ast.Subscript, ast.Call)): base = base.func if isinstance(base, ast.Call) else base.value if isinstance(base, ast.Name) and base.id not in modules: - return Var(_js_expr="value") + return _STATE return _UNKNOWN @@ -1618,6 +1745,8 @@ def migrate(paths: Sequence[Path], *, fix_spacing: bool = False) -> Result: rxconfig = _find_rxconfig(paths) analyses: list[_Analysis] = [] sources: list[_Source] = [] + project: dict[Path, _Analysis] = {} + trees: list[tuple[_Analysis, ast.Module]] = [] config = None for file in _source_files(paths): source = _Source(file, file.read_bytes()) @@ -1640,8 +1769,12 @@ def migrate(paths: Sequence[Path], *, fix_spacing: bool = False) -> Result: ) continue analysis = _Analysis(source, fix_spacing) - analysis.collect(tree) - if file == rxconfig: + analysis.collect(tree, [path for path in paths if path.is_dir()]) + analysis.project = project + project[file] = analysis + trees.append((analysis, tree)) + for analysis, tree in trees: + if analysis.source.path == rxconfig: config = _Config(analysis, tree) analysis.run(tree) analyses.append(analysis) @@ -1656,8 +1789,8 @@ def migrate(paths: Sequence[Path], *, fix_spacing: bool = False) -> Result: new = source.apply() if new != old: changes[source.path] = (old, new) - items.sort() - return Result(changes, items) + # A dict of styles shared by several components is reported once. + return Result(changes, sorted(set(items))) def _migrate_config(config: _Config, analyses: Sequence[_Analysis]) -> None: diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt index 7fd5a61a196..4c95eeaae97 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt @@ -1,5 +1,9 @@ import reflex as rx +from .style import card_style + +local_style = {"animation": "spin 1s"} + class State(rx.State): bg: str = "red" @@ -10,6 +14,10 @@ def row(**props) -> rx.Component: return rx.ui.flex(rx.ui.text("Row"), **props) +def tile(theme_style: dict) -> rx.Component: + return rx.ui.box("Tile", style=theme_style) + + def index() -> rx.Component: return rx.ui.vstack( rx.ui.box("Spacing", pt="2", mx="-3", style={"pb": "4", "m": "auto"}), @@ -36,6 +44,8 @@ def index() -> rx.Component: rx.ui.text("Label", as_="label", html_for="name"), rx.ui.scroll_area(rx.ui.text("Long"), type="always", scroll_hide_delay=600), rx.ui.select(["a", "b"], position="item-aligned"), + rx.ui.card("Shared", style=card_style), + rx.ui.box("Local", style=local_style), rx.ui.checkbox_group.root(rx.ui.checkbox_group.item(value="a"), orientation="horizontal"), ) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt index 200050463ab..2da1309760e 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt @@ -1,5 +1,9 @@ import reflex as rx +from .style import card_style + +local_style = {"animation": "spin 1s"} + class State(rx.State): bg: str = "red" @@ -10,6 +14,10 @@ def row(**props) -> rx.Component: return rx.flex(rx.text("Row"), **props) +def tile(theme_style: dict) -> rx.Component: + return rx.box("Tile", style=theme_style) + + def index() -> rx.Component: return rx.vstack( rx.box("Spacing", pt="2", mx="-3", style={"pb": "4", "m": "auto"}), @@ -36,6 +44,8 @@ def index() -> rx.Component: rx.text("Label", as_="label", html_for="name"), rx.scroll_area(rx.text("Long"), type="always", scroll_hide_delay=600), rx.select(["a", "b"], position="item-aligned"), + rx.card("Shared", style=card_style), + rx.box("Local", style=local_style), rx.checkbox_group.root(rx.checkbox_group.item(value="a"), orientation="horizontal"), ) diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/style.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/style.py.txt new file mode 100644 index 00000000000..e55f6ebb7c3 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/style.py.txt @@ -0,0 +1,3 @@ +"""Styles shared by the pages.""" + +card_style = {"pt": "2", "& > div": {"color": "red"}} diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt index d7bcf18b402..78528965209 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt @@ -1,24 +1,28 @@ -app/app.py:10:36: [unresolved] the props passed to rx.flex with ** are not checked: check the calls that pass them for the props and styles this report lists. -app/app.py:15:27: [spacing] rx.ui.box: "pt" is not a CSS property, and rx.box ignores it too. Use padding_top="var(--space-2)" (or rx.ui.tokens.space[2]) for the spacing Radix's pt="2" means. --fix-spacing rewrites it. -app/app.py:15:35: [spacing] rx.ui.box: "mx" is not a CSS property, and rx.box ignores it too. Use margin_x="calc(-1 * var(--space-3))" for the spacing Radix's mx="-3" means. --fix-spacing rewrites it. -app/app.py:15:51: [spacing] rx.ui.box: "pb" is not a CSS property, and rx.box ignores it too. Use padding_bottom="var(--space-4)" (or rx.ui.tokens.space[4]) for the spacing Radix's pb="4" means. --fix-spacing rewrites it. -app/app.py:15:62: [spacing] rx.ui.box: "m" is not a CSS property, and rx.box ignores it too. Use margin="auto" for the spacing Radix's m="auto" means. --fix-spacing rewrites it. -app/app.py:16:38: [spacing] rx.ui.box: "p" is not a CSS property, and rx.box ignores it too. Use padding, which takes any CSS value: step N of the spacing scale of Radix is "var(--space-N)", or rx.ui.tokens.space[N]. -app/app.py:26:33: [style] rx.ui.box: style key "& > div" is a nested selector, which rx.ui styles do not support. Style the child component directly, or keep rx.box for this element. -app/app.py:27:31: [style] rx.ui.box: style "background" has the value "red url(dots.png)", which rx.ui styles cannot split into longhands. Set background_color, background_image and its other longhands instead. -app/app.py:27:63: [style] rx.ui.box: style "bg" has the value "linear-gradient(red, blue), red", which rx.ui styles cannot split into longhands. Set background_color, background_image and its other longhands instead. -app/app.py:29:30: [style] if State.bg is bound to state: rx.ui.box: 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. When it holds a color, write background_color=State.bg. -app/app.py:30:28: [style] rx.ui.box: style "animation" is a shorthand that rx.ui styles do not support. Set animation_name, animation_duration and its other longhands instead. -app/app.py:31:30: [important] "red !important": rx.ui merges a style over the component's own, so it needs no !important to win; remove it. -app/app.py:31:61: [important] "bold !important": rx.ui merges a style over the component's own, so it needs no !important to win; remove it. -app/app.py:32:45: [radix-class] targets the Radix Themes class "rt-reset", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. -app/app.py:33:35: [style] rx.ui.container: stack_children_full_width styles the stacks inside the container through nested selectors, which rx.ui styles do not support. Give those stacks width="100%", or keep rx.container for this element. -app/app.py:34:24: [style] rx.ui.box: unknown CSS property "paddng". Did you mean "padding"? -app/app.py:36:39: [prop] rx.text passes html_for on as a CSS key, which the browser ignores; rx.ui.text renders it as an attribute, so a label now names its control. -app/app.py:37:41: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no type: it has no effect. -app/app.py:37:56: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no scroll_hide_delay: it has no effect. -app/app.py:38:31: [prop] rx.ui.select places its list as position="popper" does: below the trigger, not over it. -app/app.py:39:67: [prop] Tab moves between the native checkboxes of rx.ui.checkbox_group, and the arrow keys do not: orientation has no effect. +app/app.py:5:16: [style] rx.ui.box: style "animation" is a shorthand that rx.ui styles do not support. Set animation_name, animation_duration and its other longhands instead. +app/app.py:14:36: [unresolved] the props passed to rx.flex with ** are not checked: check the calls that pass them for the props and styles this report lists. +app/app.py:18:27: [unresolved] the style theme_style is not a dict assigned once at the top of a module of the app: it is not checked. Check it for the styles this report lists. +app/app.py:23:27: [spacing] rx.ui.box: "pt" is not a CSS property, and rx.box ignores it too. Use padding_top="var(--space-2)" (or rx.ui.tokens.space[2]) for the spacing Radix's pt="2" means. --fix-spacing rewrites it. +app/app.py:23:35: [spacing] rx.ui.box: "mx" is not a CSS property, and rx.box ignores it too. Use margin_x="calc(-1 * var(--space-3))" for the spacing Radix's mx="-3" means. --fix-spacing rewrites it. +app/app.py:23:51: [spacing] rx.ui.box: "pb" is not a CSS property, and rx.box ignores it too. Use padding_bottom="var(--space-4)" (or rx.ui.tokens.space[4]) for the spacing Radix's pb="4" means. --fix-spacing rewrites it. +app/app.py:23:62: [spacing] rx.ui.box: "m" is not a CSS property, and rx.box ignores it too. Use margin="auto" for the spacing Radix's m="auto" means. --fix-spacing rewrites it. +app/app.py:24:38: [spacing] rx.ui.box: "p" is not a CSS property, and rx.box ignores it too. Use padding, which takes any CSS value: step N of the spacing scale of Radix is "var(--space-N)", or rx.ui.tokens.space[N]. +app/app.py:34:33: [style] rx.ui.box: style key "& > div" is a nested selector, which rx.ui styles do not support. Style the child component directly, or keep rx.box for this element. +app/app.py:35:31: [style] rx.ui.box: style "background" has the value "red url(dots.png)", which rx.ui styles cannot split into longhands. Set background_color, background_image and its other longhands instead. +app/app.py:35:63: [style] rx.ui.box: style "bg" has the value "linear-gradient(red, blue), red", which rx.ui styles cannot split into longhands. Set background_color, background_image and its other longhands instead. +app/app.py:37:30: [style] if State.bg is bound to state: rx.ui.box: 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. When it holds a color, write background_color=State.bg. +app/app.py:38:28: [style] rx.ui.box: style "animation" is a shorthand that rx.ui styles do not support. Set animation_name, animation_duration and its other longhands instead. +app/app.py:39:30: [important] "red !important": rx.ui merges a style over the component's own, so it needs no !important to win; remove it. +app/app.py:39:61: [important] "bold !important": rx.ui merges a style over the component's own, so it needs no !important to win; remove it. +app/app.py:40:45: [radix-class] targets the Radix Themes class "rt-reset", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. +app/app.py:41:35: [style] rx.ui.container: stack_children_full_width styles the stacks inside the container through nested selectors, which rx.ui styles do not support. Give those stacks width="100%", or keep rx.container for this element. +app/app.py:42:24: [style] rx.ui.box: unknown CSS property "paddng". Did you mean "padding"? +app/app.py:44:39: [prop] rx.text passes html_for on as a CSS key, which the browser ignores; rx.ui.text renders it as an attribute, so a label now names its control. +app/app.py:45:41: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no type: it has no effect. +app/app.py:45:56: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no scroll_hide_delay: it has no effect. +app/app.py:46:31: [prop] rx.ui.select places its list as position="popper" does: below the trigger, not over it. +app/app.py:49:67: [prop] Tab moves between the native checkboxes of rx.ui.checkbox_group, and the arrow keys do not: orientation has no effect. app/assets/custom.css:2:1: [radix-class] targets the Radix Themes class "rt-Button", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. app/assets/custom.css:3:7: [radix-class] targets the Radix Themes class "rt-Text", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. app/assets/custom.css:3:17: [radix-class] targets the Radix Themes class "rt-Heading", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. +app/style.py:3:15: [spacing] rx.ui.card: "pt" is not a CSS property, and rx.card ignores it too. Use padding_top="var(--space-2)" (or rx.ui.tokens.space[2]) for the spacing Radix's pt="2" means. --fix-spacing rewrites it. +app/style.py:3:26: [style] 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. From f23fef19665dea3d455ae8cc408cdea2d15e6cfc Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:22:40 +0000 Subject: [PATCH 160/204] Keep what a probe prints out of the migration's output Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- .../src/reflex_components_ui/migrate.py | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index 6482e72bb85..0660bf2b7fd 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -19,8 +19,10 @@ import argparse import ast +import contextlib import dataclasses import difflib +import io import os import re import sys @@ -235,6 +237,18 @@ def _declares(names: tuple[str, ...], prop: str) -> bool: return isinstance(owner, type) and prop in owner.get_props() +@contextlib.contextmanager +def _quiet() -> Iterator[None]: + """Keep what a probe prints, such as the warnings of a component, out of the report. + + Yields: + Nothing: the output inside the block is dropped. + """ + sink = io.StringIO() + with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink): + yield + + @cache def _builds(names: tuple[str, ...], args: Any) -> bool: """Tell whether rx.ui builds a component from its children alone. @@ -250,7 +264,8 @@ def _builds(names: tuple[str, ...], args: Any) -> bool: Whether it builds. """ try: - _resolve("reflex_components_ui", names)(*_thaw(args)) + with _quiet(): + _resolve("reflex_components_ui", names)(*_thaw(args)) except Exception: return False return True @@ -278,12 +293,13 @@ def _probe( from reflex_components_ui.style.lower import StyleError try: - component = _resolve("reflex_components_ui", names)( - *_thaw(args), **_thaw(kwargs) - ) - if in_state: - with rendering_dynamic_component(): - component.render() + with _quiet(): + component = _resolve("reflex_components_ui", names)( + *_thaw(args), **_thaw(kwargs) + ) + if in_state: + with rendering_dynamic_component(): + component.render() except StyleError as error: return str(error) except Exception: From 2462d9757dfb172494f7516fdb886adcabecaa5e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:28:50 +0000 Subject: [PATCH 161/204] Report lengths written without a unit, which rx drops and rx.ui makes pixels Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- .../src/reflex_components_ui/migrate.py | 50 +++++++++++++++++++ .../styles/after/app/app.py.txt | 2 + .../styles/before/app/app.py.txt | 2 + .../migrate_fixtures/styles/report.txt | 5 +- 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index 0660bf2b7fd..25789d80a09 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -53,6 +53,8 @@ _RADIX_MODULES = ("reflex_components_radix", "reflex.components.radix") # A class name of Radix Themes in a string or a stylesheet. _RADIX_CLASS = re.compile(r"(? tuple[str, ...]: + """Find the lengths a prop gives without a unit, which StyleX makes pixels. + + Args: + names: The component. + args: Its literal children, frozen. + kwargs: The prop, a frozen dict. + + Returns: + The camelCase properties the prop gives a number written as a string, + such as ``"4"``, that are lengths: the browser drops such a value of + rx, and StyleX compiles it to ``4px``. + """ + from reflex_components_ui.style.emit import UNITLESS + + def numbers(value: Any) -> bool: + if value.__class__ is dict: + return any(numbers(item) for item in value.values()) + return value.__class__ is str and _BARE_NUMBER.fullmatch(value) is not None + + try: + with _quiet(): + create = _resolve("reflex_components_ui", names) + style = create(*_thaw(args), **_thaw(kwargs))._element_styles().style.style + base = create(*_thaw(args))._element_styles().style.style + except Exception: + return () + return tuple( + prop + for prop, value in style.items() + if prop not in UNITLESS + and not prop.startswith("--") + and base.get(prop) != value + and numbers(value) + ) + + def _freeze(value: Any) -> Any: """Make a value hashable, for the cache of the probes. @@ -1106,6 +1146,16 @@ def _check( if exact: self._important(source, at, value) if message is None: + if exact and _bare_lengths(names, args, _freeze(kwargs)): + written = source.text(node) + source.report( + at, + "unit", + f"{key}={written} gives a length without a unit, which is not " + "valid CSS: the browser drops it from rx, and rx.ui compiles it " + "to pixels. Remove it to keep the page as it is, or give it a " + "unit.", + ) return spacing = key in _SPACING_SHORTHANDS and not _declares(names, key) if not spacing: diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt index 4c95eeaae97..d28e90e17fc 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt @@ -44,6 +44,8 @@ def index() -> rx.Component: rx.ui.text("Label", as_="label", html_for="name"), rx.ui.scroll_area(rx.ui.text("Long"), type="always", scroll_hide_delay=600), rx.ui.select(["a", "b"], position="item-aligned"), + rx.ui.flex(rx.ui.text("Unitless"), gap="3", spacing="2"), + rx.ui.box("Unitless", padding="4", z_index="2", width="0", style={"_hover": {"margin": "1.5"}}), rx.ui.card("Shared", style=card_style), rx.ui.box("Local", style=local_style), rx.ui.checkbox_group.root(rx.ui.checkbox_group.item(value="a"), orientation="horizontal"), diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt index 2da1309760e..16c757689be 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt @@ -44,6 +44,8 @@ def index() -> rx.Component: rx.text("Label", as_="label", html_for="name"), rx.scroll_area(rx.text("Long"), type="always", scroll_hide_delay=600), rx.select(["a", "b"], position="item-aligned"), + rx.flex(rx.text("Unitless"), gap="3", spacing="2"), + rx.box("Unitless", padding="4", z_index="2", width="0", style={"_hover": {"margin": "1.5"}}), rx.card("Shared", style=card_style), rx.box("Local", style=local_style), rx.checkbox_group.root(rx.checkbox_group.item(value="a"), orientation="horizontal"), diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt index 78528965209..fda4208728e 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt @@ -20,7 +20,10 @@ app/app.py:44:39: [prop] rx.text passes html_for on as a CSS key, which the brow app/app.py:45:41: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no type: it has no effect. app/app.py:45:56: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no scroll_hide_delay: it has no effect. app/app.py:46:31: [prop] rx.ui.select places its list as position="popper" does: below the trigger, not over it. -app/app.py:49:67: [prop] Tab moves between the native checkboxes of rx.ui.checkbox_group, and the arrow keys do not: orientation has no effect. +app/app.py:47:38: [unit] gap="3" gives a length without a unit, which is not valid CSS: the browser drops it from rx, and rx.ui compiles it to pixels. Remove it to keep the page as it is, or give it a unit. +app/app.py:48:28: [unit] padding="4" gives a length without a unit, which is not valid CSS: the browser drops it from rx, and rx.ui compiles it to pixels. Remove it to keep the page as it is, or give it a unit. +app/app.py:48:72: [unit] _hover={"margin": "1.5"} gives a length without a unit, which is not valid CSS: the browser drops it from rx, and rx.ui compiles it to pixels. Remove it to keep the page as it is, or give it a unit. +app/app.py:51:67: [prop] Tab moves between the native checkboxes of rx.ui.checkbox_group, and the arrow keys do not: orientation has no effect. app/assets/custom.css:2:1: [radix-class] targets the Radix Themes class "rt-Button", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. app/assets/custom.css:3:7: [radix-class] targets the Radix Themes class "rt-Text", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. app/assets/custom.css:3:17: [radix-class] targets the Radix Themes class "rt-Heading", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. From 17f9a387a37b9db0da5fa30b0ac49b1d6221dedb Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:30:40 +0000 Subject: [PATCH 162/204] Type-check the migration codemod, list its guide under Styling, add its news Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- .../docpage/sidebar/sidebar_items/learn.py | 1 + .../news/+migrate.feature.md | 1 + .../src/reflex_components_ui/migrate.py | 19 ++++++++++--------- .../reflex_components_ui/test_migrate.py | 2 +- 4 files changed, 13 insertions(+), 10 deletions(-) create mode 100644 packages/reflex-components-ui/news/+migrate.feature.md diff --git a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py index 50b9e25f660..6bad917430c 100644 --- a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py +++ b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py @@ -93,6 +93,7 @@ def get_sidebar_items_frontend(): styling.layout, styling.common_props, styling.tailwind, + styling.rx_ui_migration, ], ), create_item( diff --git a/packages/reflex-components-ui/news/+migrate.feature.md b/packages/reflex-components-ui/news/+migrate.feature.md new file mode 100644 index 00000000000..9bd6eeeccd4 --- /dev/null +++ b/packages/reflex-components-ui/news/+migrate.feature.md @@ -0,0 +1 @@ +Move an app from the Radix components of `rx` to `rx.ui` with one command, `python -m reflex_components_ui.migrate .`: it rewrites the components, moves the theme to `rx.plugins.UIPlugin` in `rxconfig.py`, and reports with file, line and column every style or prop it cannot carry over. See the [migration guide](https://reflex.dev/docs/styling/rx-ui-migration/). diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index 25789d80a09..5ad68238588 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -777,8 +777,8 @@ def _visit(self, node: ast.AST) -> None: return elif isinstance(node, ast.Name): self._name(node) - elif isinstance(node, ast.Constant) and node.value.__class__ is str: - self._radix_classes(node) + elif isinstance(node, ast.Constant) and isinstance(node.value, str): + self._radix_classes(node, node.value) for child in ast.iter_child_nodes(node): self._visit(child) @@ -1016,7 +1016,7 @@ def _keyword( names: tuple[str, ...], args: Any, keyword: ast.keyword, - given: set[str | None], + given: set[Any], ) -> None: """Check one prop of a covered component. @@ -1054,7 +1054,7 @@ def _style( names: tuple[str, ...], args: Any, style: ast.Dict, - given: set[str | None], + given: set[Any], owner: _Analysis, ) -> None: """Check every key of a literal style dict. @@ -1068,7 +1068,7 @@ def _style( """ keys = {key.value for key in style.keys if isinstance(key, ast.Constant)} for key, node in zip(style.keys, style.values, strict=True): - if not (isinstance(key, ast.Constant) and key.value.__class__ is str): + if not (isinstance(key, ast.Constant) and isinstance(key.value, str)): continue value, exact = _value(node, owner.modules, key.value) if value is _UNKNOWN: @@ -1224,13 +1224,14 @@ def _important(self, source: _Source, at: Any, value: Any) -> None: "needs no !important to win; remove it.", ) - def _radix_classes(self, node: ast.Constant) -> None: + def _radix_classes(self, node: ast.Constant, text: str) -> None: """Report the class names of Radix Themes a string holds. Args: - node: A string. + node: The string. + text: Its value. """ - for match in _RADIX_CLASS.finditer(node.value): + for match in _RADIX_CLASS.finditer(text): self.source.report(node, "radix-class", _radix_class_message(match[1])) def _module_span(self, node: ast.ImportFrom) -> tuple[int, int]: @@ -1448,7 +1449,7 @@ def _read(node: ast.expr, modules: set[str]) -> tuple[Any, bool]: out: dict[str, Any] = {} exact = True for key, item in zip(node.keys, node.values, strict=True): - if not (isinstance(key, ast.Constant) and key.value.__class__ is str): + if not (isinstance(key, ast.Constant) and isinstance(key.value, str)): return _UNKNOWN, False value, item_exact = _read(item, modules) if value is _UNKNOWN: diff --git a/tests/units/reflex_components_ui/test_migrate.py b/tests/units/reflex_components_ui/test_migrate.py index 28ae266cd1c..c1944be825c 100644 --- a/tests/units/reflex_components_ui/test_migrate.py +++ b/tests/units/reflex_components_ui/test_migrate.py @@ -14,7 +14,7 @@ from ui_parity import allowlist FIXTURES = Path(__file__).parent / "migrate_fixtures" -GUIDE = Path(__file__).parents[3] / "docs" / "ui" / "rx_ui_migration.md" +GUIDE = Path(__file__).parents[3] / "docs" / "styling" / "rx-ui-migration.md" # The options of each fixture app. CASES = { From 5232e3d6f33e53314d90832fbf100a3efd3bd15a Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:32:10 +0000 Subject: [PATCH 163/204] Add the guide to migrating to rx.ui The one command, every item it reports and what to do, how to keep both systems on a page, what the kitchen sink gains, and the known differences, generated from the parity allowlist and checked against it by a test. Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- docs/styling/rx-ui-migration.md | 324 ++++++++++++++++++ .../reflex_components_ui/test_migrate.py | 2 +- 2 files changed, 325 insertions(+), 1 deletion(-) create mode 100644 docs/styling/rx-ui-migration.md diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md new file mode 100644 index 00000000000..1493f9831ec --- /dev/null +++ b/docs/styling/rx-ui-migration.md @@ -0,0 +1,324 @@ +# Migrating to rx.ui + +`rx.ui` has the components of `rx` that are built on Radix Themes, with the +same props, compiled to plain HTML elements and a static stylesheet. No +component library ships to the browser, and most controls work before +JavaScript has run. Moving an app is one command, plus the short list of items +the command reports. + +## What changes + +- `rx.text(...)` becomes `rx.ui.text(...)`, and the same for every component + `rx.ui` has, namespace members such as `rx.select.root` and aliases such as + `rx.input` included. `rx.el`, `rx.icon`, `rx.foreach`, `rx.cond` and the + other components that are not Radix's stay as they are. +- The theme moves from `RadixThemesPlugin(theme=rx.theme(...))` (or the older + `rx.App(theme=rx.theme(...))`) to `rx.plugins.UIPlugin(theme=rx.ui.Theme(...))` + in `rxconfig.py`. `rx.ui` components need `UIPlugin`, which compiles their + styles with [StyleX](https://stylexjs.com) in the app's own build. +- `RadixThemesPlugin` goes once no Radix component is left, and the Radix + Themes stylesheet goes with it. +- Styles are compiled ahead of time. A style `rx.ui` cannot compile, such as a + nested selector, is an error where the component is created, with the + style to use instead. + +`rx.ui` comes with the `ui` extra: + +```bash +pip install 'reflex[ui]' +``` + +## The command + +Run it from the root of the app, the directory that holds `rxconfig.py`: + +```bash +python -m reflex_components_ui.migrate . +# or, in a uv project +uv run python -m reflex_components_ui.migrate . +``` + +| Option | What it does | +| --- | --- | +| `--check` | Changes nothing: reports, and exits with 1 when a file would change. | +| `--diff` | Prints the changes as a unified diff. | +| `--fix-spacing` | Also rewrites the margin and padding props of Radix (see `spacing` below). | + +The files are parsed and edited where a change is needed; the rest of a file, +comments and formatting included, is kept as it is. An edit that adds code, +such as the plugin in `rxconfig.py`, is not formatted, so run your formatter +afterwards. Run it on a directory without `rxconfig.py`, or on single files, to +migrate part of an app: `rxconfig.py` is then left alone. + +Each item of the report is a line `path:line:column: [kind] message`. A style +is checked by building the `rx.ui` component from the values written in the +call, so the message of a `style` or `spacing` item is the error `rx.ui` itself +raises. + +## The reported items + +| Kind | What it is | What to do | +| --- | --- | --- | +| `spacing` | A margin or padding prop of Radix (`m`, `mx`, `my`, `mt`, `mr`, `mb`, `ml`, `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl`) given to a component that does not declare it, as a keyword or a style key. `rx` passes it on as a CSS key, which the browser ignores, so the page has no such spacing today. `rx.ui` refuses it. | Remove it to keep the page as it is, or write the style the message names, such as `padding_top="var(--space-2)"` for `pt="2"` and `margin_x="calc(-1 * var(--space-3))"` for `mx="-3"`. `--fix-spacing` writes it for string values. Either way, the page gains spacing it never had. `rx.ui.inset`, `rx.ui.table.cell` and `rx.ui.table.row_header_cell` declare these props and keep them. | +| `style` | A style `rx.ui` cannot compile: a nested selector such as `"& > div"`, a `background` or `border` that is more than one color, image or set of parts, the `animation` shorthand, a property that does not exist (rx passes those on), `rx.container(stack_children_full_width=True)`, or a `background` bound to state. | Do what the message says: style the child component itself, set the longhands (`background_color`, `background_image`, `animation_name` with `keyframes(...)`, ...), fix the name, give the stacks `width="100%"`. A `background=State.color` becomes `background_color=State.color` when it holds a color. | +| `state` | A component built in a state (a field or a computed var holding a component) whose styles have conditions, such as the hover of a button. A component held in state is rendered in the browser, where no compiled style applies, so `rx.ui` refuses it. The call is left on `rx`. | Render the component in the page and show it with `rx.cond`, or keep it on `rx`. | +| `unit` | A length written as a number without a unit, such as `padding="4"` or `gap="3"` on a component that does not take a step of the spacing scale there. It is not valid CSS, so the browser drops it from `rx`; `rx.ui` compiles it to pixels. | Remove it to keep the page as it is, or give it a unit. `spacing="3"` on a stack or a flex is a step of the scale in both. | +| `important` | A style value with `!important`, there to beat the styles of Radix Themes. | Remove it: `rx.ui` merges the style of an element over the component's own. | +| `radix-class` | A class name of Radix Themes (`rt-...`) in a Python string or in a stylesheet. No `rx.ui` component carries those classes. | Style the component through its props and `style`, or give it a `class_name` of your own. | +| `prop` | A prop whose effect changes: `html_for` and `form` on `rx.text` and `rx.text.span` now render (a label names its control); `type` and `scroll_hide_delay` of `rx.scroll_area` and `orientation` and `loop` of `rx.checkbox_group` and `rx.checkbox_cards` have no effect; `position="item-aligned"` of a select is placed as `"popper"`. | Nothing, unless the page relied on the old behaviour. | +| `theme` | An option of `rx.theme` that `rx.ui.Theme` does not take (children, `style`, ...), left out of the theme of `UIPlugin`; an `appearance`, which colors the components but does not set the color mode of the app; or a theme that is not an `rx.theme(...)` call. | Render the child in a page, or wrap the page in `rx.ui.theme(...)`. Set the color mode of the app as before. | +| `config` | What `rxconfig.py` could not take: no `rx.Config(...)` call, `plugins` that is not a list, or `RadixThemesPlugin` kept because Radix components remain, with where each of them is. | Add `rx.plugins.UIPlugin()` yourself, or migrate the components listed and run the command again. | +| `kept` | A Radix component the command does not migrate: imported from `reflex_components_radix`, reached as `rx.radix...`, a member `rx.ui` lacks, or an import of a component that a state keeps on `rx`. Each keeps `RadixThemesPlugin`. | Use the `rx.ui` component, or keep both systems (see below). | +| `unresolved` | Code the command cannot follow: the `reflex` module passed on as a value (`page(rx)`), `from reflex import *`, props passed with `**`, or a `style` named by a variable that is not a dict assigned once at the top of a module of the app. | Check those calls for the items above by hand. | +| `skipped` | A file that does not parse. | Fix it and run the command again. | + +## Keeping both systems on one page + +Nothing forces a whole app to move at once: + +- The two systems render side by side on a page. The theme of `UIPlugin` is + applied inside the one of Radix Themes, so an `rx.ui` component inside an + `rx` one, or the reverse, takes the theme of `UIPlugin`. The rules of the + Radix stylesheet that style components select its `rt-*` classes, which + `rx.ui` components do not carry. +- Keep `RadixThemesPlugin` in `plugins` beside `UIPlugin` while any `rx` + component remains: the command does that, and lists what keeps it. Give + both plugins the same theme so the two systems look alike. +- Migrate a page at a time by running the command on its files, then on the + root once the last page is done, which removes `RadixThemesPlugin`. +- The two stylesheets differ in the cascade: the styles of `rx.ui` are in the + cascade layer `reflex-ui`, which unlayered CSS beats, Radix Themes and an + app stylesheet included. + +## What it gains + +Measured on the kitchen sink of the Reflex benchmarks, a settings page with 44 +of the components (`examples/pages`, `uv run reflex-bench run --suite pages`). +Written on `rx` and migrated by the command, it is the same app as the one +written on `rx.ui`: the compiled page differs in nothing but the names of the +app and of its state. + +| | `rx` | `rx.ui` | +| --- | --- | --- | +| JavaScript, gzipped | 240.7 kB | 171.1 kB | +| CSS, gzipped | 82.4 kB | 24.1 kB | +| Everything the page loads, gzipped | 335.6 kB | 216.7 kB | +| Scripts that contain Emotion | 4 | 0 | +| Lighthouse mobile score, simulated throttling | 0.97 | 1.00 | +| Largest contentful paint, simulated | 1.21 s | 0.91 s | +| Total blocking time, simulated | 182 ms | 13 ms | +| Lighthouse mobile score, DevTools throttling | 0.86 | 1.00 | +| Largest contentful paint, DevTools | 1.80 s | 1.47 s | +| Total blocking time, DevTools | 487 ms | 64 ms | +| Layout shift | 0 | 0 | + +The sizes are of one production build each, the Lighthouse figures the median +of five audits on a shared 4-core virtual machine. + +The page looks the same except where the `rx` page does not do what its code +asks, which `rx.ui` does: + +- `rx.flex(gap="3")`, `rx.grid(gap="6")` and `rx.center(padding="4")` give + lengths without a unit, which the browser drops from `rx`; `rx.ui` makes + them pixels. The command reports each as a `unit` item. +- `rx.scroll_area(..., style={"height": "160px"})` grows with its content in + `rx`, which squeezes the card above it in the same stack and cuts its text; + `rx.ui.scroll_area` is 160px tall and scrolls. +- `rx.center` leaves its children at the start here; `rx.ui.center` centers + them. + +## Known differences in behaviour + +Everything that intentionally differs between an `rx` component and its `rx.ui` +counterpart, kept in sync with the parity checks of `rx.ui`: + + +### every component + +- style `m`, `mx`, `my`, `mt`, `mr`, `mb`, `ml`, `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl`: Where Radix does not declare them, the rx components pass the margin and padding props of Radix Themes on as CSS keys, which the browser ignores: rx.box(pt="2") has no padding. rx.ui refuses them and names the style that sets the spacing Radix means, such as padding_top="var(--space-2)". The components that declare them, rx.ui.inset and the cells of rx.ui.table, take them as Radix does. + +### accordion + +- behaviour, `rx`, "opens and closes an item with JavaScript disabled": rx.accordion is opened by JavaScript: until it has run, a press on a header does nothing. An item of rx.ui.accordion is a native `details`, which the browser opens and closes with or without JavaScript, one at a time when the accordion is `type="single"`; only an open item of an accordion that is not `collapsible` needs JavaScript to stay open when it is pressed. +- behaviour, `rx.ui`, "the arrow keys, Home and End move between the headers": The headers of rx.ui.accordion are native `summary` elements: Tab and Shift+Tab move between them, as between the headers of any `details`, and Enter and Space open and close an item. rx.accordion also moves between its headers with the arrow keys, Home and End, and `orientation` says which arrow keys do. +- behaviour, `rx.ui`, "hands over the open items in the order they were opened in": `on_value_change` of an rx.ui.accordion of `type="multiple"` hands over the values of the open items in the order of the items, whatever the order they were opened in: the accordion keeps no state of its own and reads its items. rx.accordion appends each value as it is opened. +- a11y, *: An item of rx.ui.accordion is a native `details`: its header is the `summary`, which holds the heading and says by itself whether the item is open, where the header of rx.accordion is a heading that holds a button with `aria-expanded`. A screen reader announces both as a heading that expands and collapses. +- style, `outline-style`, `outline-width`, `outline-color`: The ring of the keyboard's focus is drawn by the browser around the `summary` of the item, which is what takes the focus in rx.ui.accordion, and around the button inside the heading in rx.accordion. It is the same ring in the same place. +- style, `pointer-events`: The header of a disabled item of rx.ui.accordion lets the pointer through, so the item cannot be opened with or without JavaScript. rx.accordion disables the button of the header. + +### alert_dialog + +- behaviour, `rx`, "what it holds is in the server render": rx.alert_dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.alert_dialog holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.alert_dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger, the action and the cancel button of rx.ui.alert_dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript. +- behaviour, `rx.ui`, "Tab stays inside an open alert dialog": rx.ui.alert_dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.alert_dialog keeps the focus from leaving the dialog at all. +- style, `pointer-events`: While it is open rx.alert_dialog takes the pointer off the rest of the page with a style on the body. rx.ui.alert_dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style. + +### avatar + +- behaviour, `rx`, "the fallback is in the server render": rx.avatar renders its fallback and its image once JavaScript has run: the server sends an empty placeholder. rx.ui.avatar sends both, so the page shows the avatar before it is hydrated. +- behaviour, `rx`, "shows a loaded image and the fallback without JavaScript": rx.avatar shows neither its image nor its fallback with JavaScript disabled. rx.ui.avatar shows the fallback, and the image over it once it has loaded; only an image that fails needs JavaScript to give way to the fallback. +- pixels, size-responsive-large@800: When the size of rx.avatar grows at a breakpoint from one of the four small sizes to a larger one, Radix Themes keeps the smaller letters the small size has for a fallback of two letters. rx.ui.avatar gives the two letters the size they have in an avatar of the larger size alone. +- style, `font-size`, `line-height`: When the size of rx.avatar grows at a breakpoint from one of the four small sizes to a larger one, Radix Themes keeps the smaller letters the small size has for a fallback of two letters. rx.ui.avatar gives the two letters the size they have in an avatar of the larger size alone. + +### checkbox + +- behaviour, `rx`, "is checked by a click with JavaScript disabled": rx.checkbox is a button that JavaScript turns into a checkbox: until it has run, a click does nothing. rx.ui.checkbox is a native input, which is checked by a click on it or on its label with or without JavaScript. +- behaviour, `rx.ui`, "Enter on a checkbox does not submit its form": rx.ui.checkbox is a native input, and the browser submits a form when Enter is pressed in one of its inputs, a checkbox included. rx.checkbox swallows the key. Space toggles both, and Enter toggles neither. +- a11y, *: A checked rx.checkbox holds its check as an image without a name, which a screen reader may announce inside the checkbox. rx.ui.checkbox is one native input: its check is drawn by its styles and is nothing to the accessibility tree, which has the role, the name and the state of the checkbox alone. +- style, `background-color`, `vertical-align`, `overflow-x`, `overflow-y`: The check of rx.checkbox is an icon, an svg element drawn in its color. The check of rx.ui.checkbox is drawn by the checkbox itself: a box of the size and the color of the icon, cut to its shape by a mask. It paints the same. + +### checkbox_cards + +- behaviour, `rx`, "checks its cards with JavaScript disabled": The checkboxes of rx.checkbox_cards are buttons that JavaScript turns into checkboxes: until it has run, a click does nothing. The checkbox of a card of rx.ui.checkbox_cards is a native input, which a click on the card checks with or without JavaScript. +- behaviour, `rx.ui`, "Tab stops once in each group": The cards of rx.ui.checkbox_cards hold native checkboxes, and Tab stops on each of them, as it does on every checkbox of a page. rx.checkbox_cards takes one stop for the whole group and moves through it with the arrow keys. +- behaviour, `rx.ui`, "the arrow keys move through a group": The browser does not move between checkboxes with the arrow keys: in rx.ui.checkbox_cards Tab and Shift+Tab do, and `orientation`, `loop` and the direction of `dir` for the arrow keys have nothing to say. rx.checkbox_cards moves the focus with the arrow keys. +- behaviour, `rx`, "Tab reaches every card that is not disabled": rx.checkbox_cards takes one Tab stop for the whole group. In rx.ui.checkbox_cards every card is a stop, as native checkboxes are. +- behaviour, `rx.ui`, "hands over the checked values in the order they were checked in": `on_value_change` of rx.ui.checkbox_cards hands over the values of the checked cards in the order of the cards, whatever the order they were checked in: the group keeps no state of its own and reads its checkboxes. rx.checkbox_cards appends each value as it is checked. +- a11y, *: The checkbox of a checked card of rx.checkbox_cards holds its check as an image without a name. The checkbox of a card of rx.ui.checkbox_cards is one native input: its check is drawn by its styles and is nothing to the accessibility tree. +- style, `background-color`, `vertical-align`, `overflow-x`, `overflow-y`: The check of rx.checkbox_cards is an icon, an svg element drawn in its color. The check of rx.ui.checkbox_cards is drawn by the checkbox itself: a box of the size and the color of the icon, cut to its shape by a mask. It paints the same. + +### checkbox_group + +- behaviour, `rx`, "checks its items with JavaScript disabled": The items of rx.checkbox_group are buttons that JavaScript turns into checkboxes: until it has run, a click does nothing. The items of rx.ui.checkbox_group are native checkboxes, which a click checks with or without JavaScript. +- behaviour, `rx.ui`, "Tab stops once in each group": The items of rx.ui.checkbox_group are native checkboxes, and Tab stops on each of them, as it does on every checkbox of a page. rx.checkbox_group takes one stop for the whole group and moves through it with the arrow keys. +- behaviour, `rx.ui`, "the arrow keys move through a group": The browser does not move between checkboxes with the arrow keys: in rx.ui.checkbox_group Tab and Shift+Tab do, and `orientation`, `loop` and the direction of `dir` for the arrow keys have nothing to say. rx.checkbox_group moves the focus with the arrow keys. +- behaviour, `rx`, "Tab reaches every checkbox that is not disabled": rx.checkbox_group takes one Tab stop for the whole group. In rx.ui.checkbox_group every checkbox is a stop, as native checkboxes are. +- behaviour, `rx.ui`, "hands over the checked values in the order they were checked in": `on_value_change` of rx.ui.checkbox_group hands over the values of the checked items in the order of the items, whatever the order they were checked in: the group keeps no state of its own and reads its checkboxes. rx.checkbox_group appends each value as it is checked. +- a11y, *: A checked item of rx.checkbox_group holds its check as an image without a name. An item of rx.ui.checkbox_group is one native input: its check is drawn by its styles and is nothing to the accessibility tree. +- style, `background-color`, `vertical-align`, `overflow-x`, `overflow-y`: The check of rx.checkbox_group is an icon, an svg element drawn in its color. The check of rx.ui.checkbox_group is drawn by the checkbox itself: a box of the size and the color of the icon, cut to its shape by a mask. It paints the same. + +### context_menu + +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.context_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. +- style, `pointer-events`: While it is open rx.context_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.context_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.context_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.context_menu hears the press and ignores it. + +### data_list + +- style, `flex-direction`, `align-items`, `grid-template-columns`, `grid-column-start`, `width`: When the orientation of rx.data_list changes at a breakpoint, Radix Themes keeps what the orientation before it declared and the new one does not: the direction of a column on the grid of a horizontal list, and the columns and the baseline alignment of a grid on the items of a vertical one, whose labels and values are then as wide as their text. rx.ui.data_list gives each breakpoint the styles of its orientation alone, so a list that turns vertical is the vertical list: labels and values are as wide as the list. Nothing is drawn differently. + +### dialog + +- behaviour, `rx`, "what it holds is in the server render": rx.dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.dialog holds is in the page from the start, in a dialog that is closed, so it is there for a search engine and for the browser's find in page once the dialog is open, and it keeps its state between two openings. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript. +- behaviour, `rx.ui`, "Tab stays inside an open dialog": rx.ui.dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.dialog keeps the focus from leaving the dialog at all. +- behaviour, `rx`, "the dark appearance of a theme around a dialog reaches its panel": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a dialog included. rx.ui.theme does, and a dialog declared inside a dark rx.ui.theme is dark: its panel, what it holds and what is drawn over the page behind it. +- style, `pointer-events`: While it is open rx.dialog takes the pointer off the rest of the page with a style on the body. rx.ui.dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style. + +### drawer + +- behaviour, `rx`, "what it holds is in the server render": rx.drawer renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.drawer holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.drawer is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.drawer are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript. +- behaviour, `rx`, "the focus moves into the drawer, and back to its trigger": rx.drawer leaves the focus on its trigger while the drawer is open, so the keyboard and a screen reader start behind it. rx.ui.drawer is a native modal dialog: the focus moves to the first control inside it, and back to the trigger when it closes. +- behaviour, `rx`, "Tab does not reach the page behind an open drawer": With rx.drawer open, Tab goes on through the page behind it. rx.ui.drawer is a native modal dialog: the page behind it is inert, and Tab moves through the drawer and the browser's own controls. +- behaviour, `rx.ui`, "is dragged out of the page by its panel": rx.ui.drawer is not dragged: it is closed by Escape, by a press beside its panel and by its close button, and `snap_points`, `fade_from_index`, `handle_only`, `close_threshold`, `scroll_lock_timeout`, `prevent_scroll_restoration` and `should_scale_background`, which all describe the drag of rx.drawer, have nothing to say. The handle is drawn and does nothing. +- style, `pointer-events`: While it is open rx.drawer takes the pointer off the rest of the page with a style on the body. rx.ui.drawer is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style. +- style, `color`, `border-top-color`, `border-right-color`, `border-bottom-color`, `border-left-color`, `outline-color`: The overlay of rx.drawer declared inside its portal is rendered at the end of the page, outside the theme, and takes the text color of the page there; the one of rx.ui.drawer stays inside the theme. An overlay holds no text, so nothing is drawn in either color. + +### dropdown_menu + +- behaviour, `rx`, "opens with JavaScript disabled": rx.dropdown_menu is opened by JavaScript: until it has run, a press on its trigger does nothing. The menu of rx.ui.dropdown_menu is a native popover of its trigger, which the browser opens, places and closes, on Escape and on a press outside, with or without JavaScript; moving through its items and choosing one wait for JavaScript. +- behaviour, `rx`, "the dark appearance of a theme around a menu reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a menu included. rx.ui.theme does, and a menu declared inside a dark rx.ui.theme is dark. +- behaviour, `rx`, "Escape closes only the sub-menu, and a choice in it closes both": Escape in a sub-menu of rx.dropdown_menu closes the whole menu. A sub-menu of rx.ui.dropdown_menu is a popover nested in its menu, and Escape closes only the topmost one, giving the focus back to the item that opened it, as the WAI-ARIA menu pattern describes; a second Escape closes the menu. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.dropdown_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. +- style, `pointer-events`: While it is open rx.dropdown_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.dropdown_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.dropdown_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.dropdown_menu hears the press and ignores it. +- pixels, long-true@open: A menu taller than the room the viewport leaves scrolls. rx.dropdown_menu draws a scrollbar of its own over the items, always shown, and widens the menu by the room it takes. The menu of rx.ui.dropdown_menu scrolls natively: the browser draws the scrollbar, in the colors of Radix, and decides its shape and when it shows. +- style, `padding-right`, `width`: rx.dropdown_menu widens a menu that scrolls by the room its own scrollbar takes. The scrollbar of rx.ui.dropdown_menu is the browser's, which takes the room it needs itself. + +### hover_card + +- behaviour, `rx.ui`, "Tab does not reach the links inside it": rx.hover_card takes what is inside the card out of the order of Tab: a keyboard user sees the card and cannot reach its links. The card of rx.ui.hover_card comes right after its trigger, so Tab moves into it and through its links, and the card stays open while the focus is inside it. +- behaviour, `rx`, "the dark appearance of a theme around a hover card reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a hover card included. rx.ui.theme does, and a hover card declared inside a dark rx.ui.theme is dark. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a hover card with a wrapper element it moves by a transform, and the card inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.hover_card is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. +- style, `height`: A hover card taller than the page grows past the bottom of the page in rx.hover_card. rx.ui.hover_card is no taller than the room the viewport leaves, and scrolls what it holds. + +### popover + +- behaviour, `rx`, "what it holds is in the server render": rx.popover renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.popover holds is in the page from the start, in a popover that is closed, and it keeps its state between two openings. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.popover is opened by JavaScript: until it has run, a press on its trigger does nothing. rx.ui.popover is a native popover of its trigger, which the browser opens, places and closes, from its close button, on Escape and on a press outside, with or without JavaScript. +- behaviour, `rx`, "its trigger names the popover it opens by the id it is given": The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link, and it has none while the popover is closed. The trigger of rx.ui.popover names the popover by the id it was given. +- behaviour, `rx.ui`, "Tab stays inside an open popover": rx.ui.popover is a native popover, which is not modal: it comes right after its trigger in the order of the page, Tab moves through what it holds and on to what follows the trigger, and the popover closes when the focus leaves it. rx.popover keeps Tab going round inside it until Escape. `modal` has nothing to say: the page beside a native popover stays as it is. +- behaviour, `rx`, "the dark appearance of a theme around a popover reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a popover included. rx.ui.theme does, and a popover declared inside a dark rx.ui.theme is dark. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a popover with a wrapper element it moves by a transform, and the popover inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.popover is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. +- style, `height`: A popover taller than the page grows past the bottom of the page in rx.popover. rx.ui.popover is no taller than the room the viewport leaves, and scrolls what it holds. + +### radio_cards + +- behaviour, `rx`, "checks one card of a group with JavaScript disabled": The cards of rx.radio_cards are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. A card of rx.ui.radio_cards is a label around a native radio button, which the browser checks with or without JavaScript. +- behaviour, `rx.ui` in webkit, "the arrow keys go round at the ends of a group": The cards of rx.ui.radio_cards hold native radio buttons, which the arrow keys move through as the browser does it. Safari stops at the first and at the last card of a group, where the other browsers and rx.radio_cards go round to the other end. Every card is reached with the arrow keys in both. +- behaviour, `rx.ui`, "Enter on a card does not submit its form": The cards of rx.ui.radio_cards hold native inputs, and the browser submits a form when Enter is pressed in one of its inputs, a radio button included. rx.radio_cards swallows the key. Space and the arrow keys check a card in both. +- a11y, *: A card of rx.ui.radio_cards is a label around a native radio button: what the card holds names the radio button, as in rx.radio_cards, and is also text of the page, as the text of any label is. A card of rx.radio_cards is one button that holds its text. + +### radio_group + +- behaviour, `rx`, "checks one item of a group with JavaScript disabled": The items of rx.radio_group are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. The items of rx.ui.radio_group are native radio buttons that share a name, which the browser checks one at a time with or without JavaScript. +- behaviour, `rx.ui` in webkit, "Shift+Tab into a group with nothing checked stops on its first item": The items of rx.ui.radio_group are native radio buttons, and the browser decides where the focus enters a group in which none is checked. Safari enters it at the button nearest to where the focus comes from: the last one for Shift+Tab, where the other browsers and rx.radio_group enter at the first. The group is one stop either way, and the arrow keys reach every item. +- behaviour, `rx` in firefox, "Shift+Tab into a group with nothing checked stops on its first item": In Firefox, Shift+Tab from the checked item of rx.radio_group does not leave the group: the focus comes back to that item. The items of rx.ui.radio_group are native radio buttons, which Shift+Tab leaves in every browser. +- behaviour, `rx` in firefox, "Shift+Tab stops once in a group with nothing checked": In Firefox, Shift+Tab from the checked item of rx.radio_group does not leave the group: the focus comes back to that item. The items of rx.ui.radio_group are native radio buttons, which Shift+Tab leaves in every browser. +- behaviour, `rx.ui` in webkit, "the arrow keys go round at the ends of a group": The items of rx.ui.radio_group are native radio buttons, which the arrow keys move through as the browser does it. Safari stops at the first and at the last button of a group, where the other browsers and rx.radio_group go round to the other end. Every item is reached with the arrow keys in both. +- behaviour, `rx.ui`, "Enter on a radio button does not submit its form": The items of rx.ui.radio_group are native inputs, and the browser submits a form when Enter is pressed in one of its inputs, a radio button included. rx.radio_group swallows the key. Space and the arrow keys check an item in both. + +### scroll_area + +- behaviour, `rx`, "scrolls to its last line with JavaScript disabled": rx.scroll_area scrolls once JavaScript has run: until then its content is clipped. rx.ui.scroll_area scrolls natively, with or without JavaScript. +- behaviour, `rx` in webkit, "Tab reaches it and the keyboard scrolls it": Safari focuses no scrolling box of its own accord, so Tab passes rx.scroll_area by and the keyboard cannot scroll it there. rx.ui.scroll_area is a tab stop in every browser. +- style, `overflow-x`, `overflow-y`: rx.ui.scroll_area is itself the element that scrolls. rx.scroll_area is a clipped box around a viewport that scrolls and the scrollbars it draws. +- pixels, *type-always*: rx.ui.scroll_area scrolls natively and has the scrollbars of the browser, thin and in the grays of the theme, where rx.scroll_area draws scrollbars of its own with JavaScript. Their shape and where they show follow the browser and the system: they may take room beside the content or lie over it, and `type` "hover" and "scroll" and `scroll_hide_delay` are left to them. + +### segmented_control + +- behaviour, `rx`, "chooses an item with JavaScript disabled": The items of rx.segmented_control are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. An item of rx.ui.segmented_control is a label around a native radio button, which the browser checks with or without JavaScript. +- a11y, *: An item of rx.ui.segmented_control is a label around a native radio button: what the item holds names the radio button, as in rx.segmented_control, and is also text of the page, as the text of any label is. An item of rx.segmented_control is one button that holds its text. + +### select + +- behaviour, `rx`, "shows the chosen option in the server render": The trigger of rx.select is empty until JavaScript has found the text of the chosen option. rx.ui.select works the text out while compiling, where the options are known or show their values, so the page the server sends shows it. +- behaviour, `rx`, "opens and closes its list with JavaScript disabled": rx.select is opened by JavaScript: until it has run, a click on its trigger does nothing. The list of rx.ui.select is a native popover of its trigger, which the browser opens and closes with or without JavaScript; choosing an option waits for it. +- behaviour, `rx.ui`, "the page behind an open list takes no click": While its list is open rx.select takes the pointer off the rest of the page: a click outside closes the list and does nothing else. The list of rx.ui.select is a native popover: a click outside closes it and also reaches what is under the pointer, as with a native select, and the page behind it scrolls. +- style, `pointer-events`: While its list is open rx.select takes the pointer off the rest of the page: nothing else can be clicked or scrolled until the list closes. The list of rx.ui.select is a native popover, which leaves the page as it is: a click outside closes the list, and the page scrolls. +- pixels, long-true*: A list of rx.ui.select too long for the room it has scrolls natively, with the scrollbar of the browser, which may lie over the options and show only while they scroll. rx.select draws a scrollbar of its own with JavaScript, and leaves room for it beside the options. +- style, `width`, `height`: When the size of rx.select goes from "3" at one breakpoint to a smaller one at the next, Radix Themes keeps the larger icon size "3" has. The icon of rx.ui.select has the size of the select at each breakpoint, so the trigger is two pixels narrower there. +- pixels, size-responsive: When the size of rx.select goes from "3" at one breakpoint to a smaller one at the next, Radix Themes keeps the larger icon size "3" has. The icon of rx.ui.select has the size of the select at each breakpoint, so the trigger is two pixels narrower there. + +### slider + +- behaviour, `rx`, "moves with the keyboard with JavaScript disabled": rx.slider is drawn and moved by JavaScript: until it has run, its thumb takes no focus and no key. The thumbs of rx.ui.slider are native range inputs, which the keyboard and the pointer move with or without JavaScript; only the filled part of the track waits for it. +- behaviour, `rx`, "the thumb of a slider has the name the slider is given": An `aria_label` of rx.slider names the element around its thumb, so the thumb, which is what a screen reader lands on, has no name. rx.ui.slider gives the label to the thumb. +- behaviour, `rx.ui`, "Shift and an arrow key move a thumb by ten steps": The thumbs of rx.ui.slider are native range inputs: the browser moves one by one step for an arrow key, with or without Shift, and by ten for Page Up and Page Down, as rx.slider does for those. +- behaviour, `rx.ui`, "a thumb can be moved past the one after it": A thumb of rx.ui.slider stops at the thumbs beside it, where a thumb of rx.slider passes them and the two change places. Home and End move the thumb that has the focus, where rx.slider moves the first and the last whichever has it. +- a11y, *: A thumb of rx.ui.slider is a native range input, which says its value to the accessibility tree as every such input does. A thumb of rx.slider has its value in `aria-valuenow` alone. + +### switch + +- behaviour, `rx`, "is turned on by a click with JavaScript disabled": rx.switch is a button that JavaScript turns into a switch: until it has run, a click does nothing. rx.ui.switch is a native checkbox with the role of a switch, which a click on it or on its label turns on and off with or without JavaScript. +- behaviour, `rx.ui`, "Enter toggles it": rx.ui.switch is a native checkbox, which the browser toggles on Space and not on Enter. rx.switch is a button, which both keys press. +- behaviour, `rx.ui`, "Enter on a switch does not submit its form": rx.ui.switch is a native input, and the browser submits a form when Enter is pressed in one of its inputs. rx.switch toggles on that key instead. + +### tabs + +- behaviour, `rx`, "a trigger and a panel given ids of their own name each other": A trigger of rx.tabs names its panel, and the panel its trigger, by an id rx.tabs makes up, so giving either an `id` breaks the link and a screen reader no longer says which tab a panel belongs to. rx.ui.tabs names each by the id it was given. + +### text + +- prop `form`, `html_for`: rx.text passes html_for and form on as CSS keys, which the browser ignores, so rx.text(as_="label", html_for=...) names no control. rx.ui.text renders them as the attributes of the label, which names its control: clicking it focuses the control. +- behaviour, `rx`, "as a label, html_for names its field": rx.text passes html_for on as a CSS key, which the browser ignores, so the label names no field: a click on it moves the focus nowhere. rx.ui.text renders it as the htmlFor attribute of the label. + +### text.span + +- prop `form`, `html_for`: As for rx.ui.text: rx.text.span passes html_for and form on as CSS keys, which the browser ignores; rx.ui.text.span renders them as attributes when it is a label. + +### theme_panel + +- behaviour, `rx`, "copies the theme as the code of an rx.ui.Theme": rx.theme_panel copies the theme as the JSX of a Radix Themes Theme, such as , which a Reflex app cannot use as it is. rx.ui.theme_panel copies the Python of the rx.ui.Theme it shows, such as rx.ui.Theme(accent_color="red", radius="large"), leaving out what is the default of rx.ui.Theme. +- style, `overflow-x`, `overflow-y`: The content of rx.ui.theme_panel scrolls in an rx.ui.scroll_area, itself the element that scrolls, with the scrollbars of the browser. rx.theme_panel scrolls in a clipped box around a viewport, with scrollbars it draws itself. +- pixels, theme-pure-gray*: An rx.theme(gray_color="gray") inside another theme keeps the gray of the theme around it, a slate for instance, because the stylesheet of Radix Themes has no rule for the plain gray: the panel inside it is drawn in that gray. rx.ui.theme(gray_color="gray") applies the plain gray, and the panel inside it is drawn in the plain gray. +- style, `background-color`, `border-bottom-color`, `border-left-color`, `border-right-color`, `border-top-color`, `box-shadow`, `color`, `outline-color`: An rx.theme(gray_color="gray") inside another theme keeps the gray of the theme around it, a slate for instance, because the stylesheet of Radix Themes has no rule for the plain gray: the panel inside it is drawn in that gray. rx.ui.theme(gray_color="gray") applies the plain gray, and the panel inside it is drawn in the plain gray. +- a11y, base: Both panels name the radio buttons of the radius by labels that point at the fixed ids Radix Themes gives them, theme-panel-radius-none and so on. A page with several panels has those ids several times, and every label names the first radio button of the page with its id, so only the panel that comes first has names for them, whichever system it is of. In a page with one panel each radio button of the radius is named by its label in both. + +### tooltip + +- behaviour, `rx`, "describes its button with JavaScript disabled": rx.tooltip renders its text when it opens, and names it as the description of its child only then. The text of rx.ui.tooltip is in the page from the start and always describes its child, so a screen reader reads it whether the tooltip is shown or not, with or without JavaScript; showing it under the pointer waits for JavaScript. +- behaviour, `rx.ui`, "points at its button with an arrow": rx.ui.tooltip has no arrow. It is where the tooltip of rx.tooltip is, the room of the arrow included, and is placed by the browser, which turns it over where it would leave the page: an arrow drawn by its styles could not follow it. `arrow_padding` has nothing to say. +- behaviour, `rx`, "the dark appearance of a theme around a tooltip reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a tooltip included. rx.ui.theme does, and a tooltip declared inside a dark rx.ui.theme has the colors of the dark appearance. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a tooltip with a wrapper element it moves by a transform, and the tooltip inside it has no position, margins or bounds of its own. rx.ui.tooltip is placed itself, a native popover in the top layer: fixed, at a margin from what it describes by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. + + diff --git a/tests/units/reflex_components_ui/test_migrate.py b/tests/units/reflex_components_ui/test_migrate.py index c1944be825c..81234d9fc5e 100644 --- a/tests/units/reflex_components_ui/test_migrate.py +++ b/tests/units/reflex_components_ui/test_migrate.py @@ -216,6 +216,6 @@ def test_guide_lists_the_allowlist(): """The behaviour differences of the migration guide are those of the allowlist.""" text = GUIDE.read_text(encoding="utf-8") start = "\n" - end = "\n" + end = "\n\n" section = text[text.index(start) + len(start) : text.index(end)] assert section == allowlist.differences_markdown(allowlist.load()) From 4f745902de349a6853070e9dc2aa5d2d18e0cefa Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:32:52 +0000 Subject: [PATCH 164/204] Read self in a state as a Python value, and list migrate.py in the README Claude-Session: https://claude.ai/code/session_014AwvTQ4JAYoqfErwRgMfww --- packages/reflex-components-ui/README.md | 1 + .../src/reflex_components_ui/migrate.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index b073fdd5ad3..9570783cc69 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 typography/ text, heading, code, blockquote, link components/ the other components: separator, inset, aspect_ratio props.py the values of the props many components share + migrate.py the codemod from the Radix components of rx to rx.ui _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/ diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index 5ad68238588..e510eebb825 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -326,6 +326,14 @@ def _bare_lengths(names: tuple[str, ...], args: Any, kwargs: Any) -> tuple[str, from reflex_components_ui.style.emit import UNITLESS def numbers(value: Any) -> bool: + """Tell whether a lowered value holds a number written as a string. + + Args: + value: A literal, or a dict of them by condition. + + Returns: + Whether it, or one of its conditions, is such a number. + """ if value.__class__ is dict: return any(numbers(item) for item in value.values()) return value.__class__ is str and _BARE_NUMBER.fullmatch(value) is not None @@ -1500,7 +1508,8 @@ def _state_like(node: ast.expr | None, modules: set[str]) -> Any: base: ast.expr = node while isinstance(base, (ast.Attribute, ast.Subscript, ast.Call)): base = base.func if isinstance(base, ast.Call) else base.value - if isinstance(base, ast.Name) and base.id not in modules: + # In a method of a state, self holds Python values, not Vars. + if isinstance(base, ast.Name) and base.id not in modules and base.id != "self": return _STATE return _UNKNOWN From dbd004baf564cf310397946802a9dc337e144b74 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:33:17 +0000 Subject: [PATCH 165/204] Document rx.ui: guides, and an rx.ui tab on the layout, typography and button pages The docs app installs reflex[ui] and adds UIPlugin, themed like its rx.theme, so rx.ui previews render beside the rx ones. A library doc can now have a -ui.md sibling, served at /ui/ with an rx.ui pill beside High Level and Low Level, the way -ll.md is served at /low/. Its prop tables have the live controls of Radix pages, and a generated Differences from Radix section reads the parity allowlist, so the listed differences are the ones the harness checks. Three guides sit under Frontend > rx.ui: installation and opt-in, styling, and theming and tokens. Claude-Session: https://claude.ai/code/session_014AwvTMRUYrq8BR7cV1SsTn --- docs/app/agent_files/_plugin.py | 4 +- docs/app/news/+rx-ui-docs.docs.md | 1 + docs/app/pyproject.toml | 2 +- docs/app/reflex_docs/pages/docs/__init__.py | 112 ++++- docs/app/reflex_docs/pages/docs/component.py | 408 ++++++++++++------ docs/app/reflex_docs/pages/docs/metadata.py | 2 +- .../reflex_docs/pages/docs/ui_differences.py | 157 +++++++ .../reflex_docs/templates/docpage/docpage.py | 7 +- .../templates/docpage/sidebar/sidebar.py | 7 +- .../docpage/sidebar/sidebar_items/learn.py | 9 + docs/app/rxconfig.py | 5 + docs/app/tests/test_routes.py | 4 +- docs/app/tests/test_ui_pages.py | 215 +++++++++ docs/library/forms/button-ui.md | 101 +++++ docs/library/layout/aspect_ratio-ui.md | 31 ++ docs/library/layout/box-ui.md | 46 ++ docs/library/layout/card-ui.md | 65 +++ docs/library/layout/center-ui.md | 27 ++ docs/library/layout/container-ui.md | 36 ++ docs/library/layout/flex-ui.md | 54 +++ docs/library/layout/grid-ui.md | 52 +++ docs/library/layout/inset-ui.md | 38 ++ docs/library/layout/section-ui.md | 32 ++ docs/library/layout/separator-ui.md | 40 ++ docs/library/layout/spacer-ui.md | 22 + docs/library/layout/stack-ui.md | 50 +++ docs/library/typography/blockquote-ui.md | 29 ++ docs/library/typography/code-ui.md | 29 ++ docs/library/typography/heading-ui.md | 29 ++ docs/library/typography/link-ui.md | 33 ++ docs/library/typography/text-ui.md | 71 +++ docs/rx_ui/overview.md | 136 ++++++ docs/rx_ui/styling.md | 296 +++++++++++++ docs/rx_ui/theming.md | 204 +++++++++ .../news/+rx-ui-copy-markdown.docs.md | 1 + .../components/docs_page_actions.py | 5 +- uv.lock | 4 +- 37 files changed, 2189 insertions(+), 175 deletions(-) create mode 100644 docs/app/news/+rx-ui-docs.docs.md create mode 100644 docs/app/reflex_docs/pages/docs/ui_differences.py create mode 100644 docs/app/tests/test_ui_pages.py create mode 100644 docs/library/forms/button-ui.md create mode 100644 docs/library/layout/aspect_ratio-ui.md create mode 100644 docs/library/layout/box-ui.md create mode 100644 docs/library/layout/card-ui.md create mode 100644 docs/library/layout/center-ui.md create mode 100644 docs/library/layout/container-ui.md create mode 100644 docs/library/layout/flex-ui.md create mode 100644 docs/library/layout/grid-ui.md create mode 100644 docs/library/layout/inset-ui.md create mode 100644 docs/library/layout/section-ui.md create mode 100644 docs/library/layout/separator-ui.md create mode 100644 docs/library/layout/spacer-ui.md create mode 100644 docs/library/layout/stack-ui.md create mode 100644 docs/library/typography/blockquote-ui.md create mode 100644 docs/library/typography/code-ui.md create mode 100644 docs/library/typography/heading-ui.md create mode 100644 docs/library/typography/link-ui.md create mode 100644 docs/library/typography/text-ui.md create mode 100644 docs/rx_ui/overview.md create mode 100644 docs/rx_ui/styling.md create mode 100644 docs/rx_ui/theming.md create mode 100644 packages/reflex-site-shared/news/+rx-ui-copy-markdown.docs.md diff --git a/docs/app/agent_files/_plugin.py b/docs/app/agent_files/_plugin.py index f003e55fba8..b38dcabc734 100644 --- a/docs/app/agent_files/_plugin.py +++ b/docs/app/agent_files/_plugin.py @@ -216,6 +216,7 @@ def generate_markdown_file_entries() -> tuple[MarkdownFileEntry, ...]: all_docs, doc_route_from_path, doc_title_from_path, + library_variant_suffix, manual_titles, ) from reflex_docs.whitelist import _check_whitelisted_path @@ -232,7 +233,8 @@ def generate_markdown_file_entries() -> tuple[MarkdownFileEntry, ...]: section=_section_for_path(Path(route.strip("/") + ".md")), ) for virtual_path, source_path in sorted(all_docs.items()) - if not virtual_path.endswith(("-style.md", "-ll.md")) + if not virtual_path.endswith("-style.md") + if library_variant_suffix(virtual_path) is None if _check_whitelisted_path(route := doc_route_from_path(virtual_path)) if (resolved := Path(source_path)).is_file() ]) diff --git a/docs/app/news/+rx-ui-docs.docs.md b/docs/app/news/+rx-ui-docs.docs.md new file mode 100644 index 00000000000..0a74e9a3a39 --- /dev/null +++ b/docs/app/news/+rx-ui-docs.docs.md @@ -0,0 +1 @@ +Document `rx.ui`: an installation and opt-in guide, a styling guide, a theming and tokens page, and an **rx.ui** tab on each component library page that has an `rx.ui` version, with live examples, the props, and the differences from Radix generated from the parity allowlist. diff --git a/docs/app/pyproject.toml b/docs/app/pyproject.toml index cead1d85b3f..a93fc89656e 100644 --- a/docs/app/pyproject.toml +++ b/docs/app/pyproject.toml @@ -12,7 +12,7 @@ dependencies = [ "plotly-express", "psycopg[binary]", "python-frontmatter", - "reflex[db]", + "reflex[db,ui]", "reflex-docgen", "reflex-enterprise>=0.9.9", "reflex-hosting-cli", diff --git a/docs/app/reflex_docs/pages/docs/__init__.py b/docs/app/reflex_docs/pages/docs/__init__.py index 8f716489682..ddffc4118bf 100644 --- a/docs/app/reflex_docs/pages/docs/__init__.py +++ b/docs/app/reflex_docs/pages/docs/__init__.py @@ -7,6 +7,10 @@ import reflex as rx from reflex_components_core.core.cond import Cond +from reflex_components_ui.components.color_mode import ( + ColorModeIconButton, + ColorModeSwitch, +) from reflex_docgen.markdown import FrontMatter, parse_document # External Components @@ -23,7 +27,11 @@ render_docgen_document, render_markdown_with_toc, ) -from reflex_docs.pages.docs.component import multi_docs +from reflex_docs.pages.docs.component import ( + LIBRARY_VARIANTS, + library_variant_path, + multi_docs, +) from reflex_docs.pages.docs.metadata import truncate_meta_description from reflex_docs.pages.library_previews import components_previews_pages from reflex_docs.templates.docpage import docpage @@ -38,6 +46,9 @@ SPECIAL_COMPONENT_DOCS = { "rx.cond": Cond, + # Static methods of the color mode Var, which name no class of their own. + "rx.ui.color_mode.button": ColorModeIconButton, + "rx.ui.color_mode.switch": ColorModeSwitch, } @@ -175,6 +186,13 @@ def get_image_from_frontmatter(filepath: str) -> str | None: # URL from the filename key, so titles read correctly without breaking links. library_display_titles: dict[str, str] = {} +# The file suffix of the page that documents a library doc's rx.ui components. +UI_VARIANT = "-ui" + +# The rx.ui page of each library doc that has one, by the doc's filename-based +# key: its route, the doc's display title and the components it documents. +ui_library_pages: dict[str, tuple[str, str, list]] = {} + doc_markdown_sources: dict[str, str] = {} @@ -225,6 +243,7 @@ def get_image_from_frontmatter(filepath: str) -> str | None: # the sidebar and the previous/next links, not the page title. nav_titles = { FAN_OUT_DOC: "Fan-Out", + "docs/rx_ui/theming.md": "Theming and Tokens", } @@ -253,12 +272,30 @@ def doc_route_from_path(doc: str) -> str: return route +def library_variant_suffix(doc: str) -> str | None: + """Tell whether a doc is a variant page of a library doc, and which. + + Args: + doc: The doc's virtual path, such as ``docs/library/forms/button-ui.md``. + + Returns: + The variant's file suffix, such as ``"-ui"``, or None for any other doc, + such as the changelog of ``reflex-components-ui``. + """ + if not doc.startswith("docs/library/"): + return None + return next( + (suffix for suffix, *_ in LIBRARY_VARIANTS if doc.endswith(f"{suffix}.md")), + None, + ) + + def resolve_doc_route(doc: str, title: str) -> ResolvedDoc | None: """Compute route, display title, and category for a doc path. Returns None if the doc should be skipped (suffix or whitelist). """ - if doc.endswith("-style.md") or doc.endswith("-ll.md"): + if doc.endswith("-style.md") or library_variant_suffix(doc) is not None: return None doc = doc.replace("\\", "/") route = doc_route_from_path(doc) @@ -417,6 +454,22 @@ def comp(_actual=actual_path, _title=resolved.display_title): return make_docpage(resolved.route, resolved.display_title, doc, comp, actual_path) +def _read_document(actual_path: str): + """Read a markdown file and parse it. + + Args: + actual_path: The file. + + Returns: + Its source and parsed document, both None when it cannot be read. + """ + try: + source = Path(actual_path).read_text(encoding="utf-8") + return source, parse_document(source) + except Exception: + return None, None + + def handle_library_doc( doc: str, actual_path: str, @@ -427,10 +480,29 @@ def handle_library_doc( clist = [title, *get_components_from_frontmatter(actual_path)] previews = get_previews_from_frontmatter(actual_path) image = get_image_from_frontmatter(actual_path) - ll_actual_path = actual_path.replace(".md", "-ll.md") - ll_clist: list | None = None - if os.path.exists(ll_actual_path): - ll_clist = [title, *get_components_from_frontmatter(ll_actual_path)] + variant_component_lists: dict[str, list] = {} + variant_previews: dict[str, dict[str, str]] = {} + variant_descriptions: dict[str, str | None] = {} + for suffix, *_ in LIBRARY_VARIANTS: + variant_path = library_variant_path(actual_path, suffix) + if not os.path.exists(variant_path): + continue + variant_component_lists[suffix] = [ + title, + *get_components_from_frontmatter(variant_path), + ] + if suffix == UI_VARIANT: + # An rx.ui page has examples and prose of its own; a Low Level page + # shares the main page's previews and description. + variant_previews[suffix] = get_previews_from_frontmatter(variant_path) + variant_source, variant_document = _read_document(variant_path) + variant_descriptions[suffix] = ( + extract_doc_description( + variant_source, dict(variant_document.frontmatter.metadata) + ) + if variant_source is not None and variant_document is not None + else None + ) if doc.startswith("docs/library/graphing"): graphing_components[resolved.category].append(clist) else: @@ -440,11 +512,7 @@ def handle_library_doc( # filename (e.g. "Barchart"). Derive a page-specific meta description from # the doc's frontmatter/body prose, and prefer an explicit frontmatter # `title:` for a human-friendly, keyword-rich page title. - try: - source: str | None = Path(actual_path).read_text(encoding="utf-8") - document = parse_document(source) - except Exception: - source, document = None, None + source, document = _read_document(actual_path) frontmatter = document.frontmatter if document is not None else None metadata = dict(frontmatter.metadata) if frontmatter is not None else None description = extract_doc_description(source, metadata) if source else None @@ -457,6 +525,12 @@ def handle_library_doc( # clist[0] is the filename-based key the sidebar links from; record the # frontmatter title so the sidebar can show it as the label instead. library_display_titles[clist[0]] = display_title + if UI_VARIANT in variant_component_lists: + ui_library_pages[clist[0]] = ( + resolved.route.rstrip("/") + "/ui/", + display_title, + variant_component_lists[UI_VARIANT][1:], + ) return multi_docs( path=resolved.route, virtual_path=doc, @@ -464,7 +538,9 @@ def handle_library_doc( previews=previews, component_list=clist, title=display_title, - ll_component_list=ll_clist, + variant_component_lists=variant_component_lists, + variant_previews=variant_previews, + variant_descriptions=variant_descriptions, description=description, image=image, source=source, @@ -543,15 +619,13 @@ def comp(_actual=actual_path, _virtual=virtual_doc, _content=doc_text): for _virtual, _actual in all_docs.items(): if _virtual.endswith("-style.md"): continue - if _virtual.endswith("-ll.md"): - # Register low-level docs at /-ll.md so the copy button can - # fetch them from the served URL. - _hl_virtual = _virtual.replace("-ll.md", ".md") - _hl_route = doc_route_from_path(_hl_virtual) + if (_variant := library_variant_suffix(_virtual)) is not None: + # Register variant docs at /-ll.md and /-ui.md so the copy + # button can fetch them from the served URL. + _hl_route = doc_route_from_path(_virtual.removesuffix(f"{_variant}.md") + ".md") if not _check_whitelisted_path(_hl_route): continue - _ll_route = _hl_route.rstrip("/") + "-ll" - doc_markdown_sources[_ll_route] = _actual + doc_markdown_sources[_hl_route.rstrip("/") + _variant] = _actual continue _route = doc_route_from_path(_virtual) if not _check_whitelisted_path(_route): diff --git a/docs/app/reflex_docs/pages/docs/component.py b/docs/app/reflex_docs/pages/docs/component.py index 6dcf1610788..fb5e6afd03f 100644 --- a/docs/app/reflex_docs/pages/docs/component.py +++ b/docs/app/reflex_docs/pages/docs/component.py @@ -16,6 +16,7 @@ from reflex.components.radix.primitives.base import RadixPrimitiveComponent from reflex.components.radix.themes.base import RadixThemesComponent from reflex_components_core.el.elements.base import BaseHTML +from reflex_components_ui.base import UIComponent from reflex_docgen import ( EventHandlerDocumentation, PropDocumentation, @@ -33,6 +34,7 @@ component_title_name, truncate_meta_description, ) +from reflex_docs.pages.docs.ui_differences import differences_markdown from reflex_docs.templates.docpage import docpage, h2_comp, h3_comp @@ -77,6 +79,9 @@ class PropDocsState(rx.State): """Container for dynamic vars used by the prop docs.""" +# The components whose styling props a page can preview with live controls. +INTERACTIVE_BASES = (RadixThemesComponent, RadixPrimitiveComponent, UIComponent) + EXCLUDED_COMPONENTS = [ "Theme", "ThemePanel", @@ -150,7 +155,7 @@ def _bool_pills(var, setter) -> rx.Component: def render_select(prop: PropDocumentation, component: type[Component], prop_dict: dict): if ( - not safe_issubclass(component, (RadixThemesComponent, RadixPrimitiveComponent)) + not safe_issubclass(component, INTERACTIVE_BASES) or component.__name__ in EXCLUDED_COMPONENTS ): return rx.fragment() @@ -540,7 +545,7 @@ def generate_props( is_interactive = True if ( - not issubclass(component, (RadixThemesComponent, RadixPrimitiveComponent)) + not issubclass(component, INTERACTIVE_BASES) or component.__name__ in EXCLUDED_COMPONENTS ): is_interactive = False @@ -1076,121 +1081,180 @@ def api_reference_toc(names: Sequence[str], has_shared: bool) -> list[tuple[int, ] -def multi_docs( +# The pages of a library doc beside its main one, in the order of the switch +# between them: the file suffix, the route segment, the label and the title +# suffix, and what tells its meta description apart from the main page's. A +# Low Level page lists the parts the main page composes; an rx.ui page +# documents the components of rx.ui that replace the main page's. +LIBRARY_VARIANTS = ( + ("-ll", "low", "Low Level", " (Low Level)", " (low-level API reference)"), + ("-ui", "ui", "rx.ui", " (rx.ui)", " (rx.ui API reference)"), +) + + +def library_variant_path(actual_path: str, suffix: str) -> str: + """Name the file of a library doc's variant page. + + Args: + actual_path: The main page's markdown file. + suffix: The variant's file suffix, such as ``"-ui"``. + + Returns: + The variant's markdown file, which may not exist. + """ + return actual_path.removesuffix(".md") + suffix + ".md" + + +def variant_switch(path: str, current: str, variants: Sequence[str]) -> rx.Component: + """Render the switch between the pages of a library doc. + + Args: + path: The main page's route. + current: The route segment of the page it is rendered on, ``""`` for + the main page. + variants: The route segments of the variant pages that exist. + + Returns: + The switch, or an empty fragment when the doc has one page. + """ + if not variants: + return rx.fragment() + path = str(path).rstrip("/") + labels = {variant[1]: variant[2] for variant in LIBRARY_VARIANTS} + # Beside Low Level the main page is the high-level API; beside rx.ui alone + # it is the rx component. + pages = [ + ("", "High Level" if "low" in variants else "rx"), + *((segment, labels[segment]) for segment in variants), + ] + return rx.box( + rx.box(class_name="flex-grow"), + rx.box( + *( + rx.link( + rx.box( + rx.text(label), + class_name=active_class_name + if segment == current + else non_active_class_name, + ), + underline="none", + class_name=link_class_name, + **( + {"aria_current": "page"} + if segment == current + else {"href": f"{path}/{segment + '/' if segment else ''}"} + ), + ) + for segment, label in pages + ), + class_name="flex items-center justify-center gap-1 rounded-full bg-muted p-1", + ), + class_name="flex mb-2", + ) + + +active_class_name = "flex min-h-10 w-28 items-center justify-center rounded-full bg-primary px-4 py-2 text-center text-sm font-normal text-primary-foreground" + +non_active_class_name = "flex min-h-10 w-28 items-center justify-center rounded-full px-4 py-2 text-center text-sm font-normal text-muted-foreground transition-colors hover:bg-accent-hover hover:text-foreground motion-reduce:transition-none" + +link_class_name = "rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring" + + +def shared_reference(props: tuple[PropDocumentation, ...]) -> rx.Component: + """Render the common reference once, retaining it in prerendered HTML. + + Args: + props: The HTML props two or more components of the page share. + + Returns: + The section, or an empty fragment when there are none. + """ + if not props: + return rx.fragment() + return rx.el.div( + h3_comp(text="Shared HTML props"), + rx.el.p( + "Components linked to this section accept these HTML props. " + "Component-specific additions and overrides are listed with each " + "component.", + class_name="mb-2 text-sm leading-6 text-muted-foreground", + ), + html_attributes_disclosure("Shared HTML attributes", props), + ) + + +UI_DIFFERENCES_HEADING = "Differences from Radix" + + +def ui_differences_section(names: Sequence[str]) -> tuple[list, list[tuple[int, str]]]: + """Render the intended differences of an rx.ui page's components. + + Args: + names: The public names of the documented components. + + Returns: + The section and its table of contents entries, both empty when none of + the components differs. + """ + differences = differences_markdown(list(names)) + if not differences: + return [], [] + return [ + h2_comp(text=UI_DIFFERENCES_HEADING), + render_markdown( + "Each difference below is checked by the rx.ui parity harness, " + "which fails when one stops happening. Differences every component " + "shares are in the [styling guide](/rx-ui/styling/#what-is-not-supported).\n\n" + + differences + ), + ], [(2, UI_DIFFERENCES_HEADING)] + + +def library_page( path: str, virtual_path: str, actual_path: str, previews: dict[str, str], component_list: list, - title: str, - description: str | None = None, - image: str | None = None, - ll_component_list: list | None = None, + current: str, + variants: Sequence[str], source: str | None = None, ): + """Build the body of one page of a library doc. + + Args: + path: The main page's route. + virtual_path: The page's markdown file, as the docs pipeline names it. + actual_path: The page's markdown file on disk. + previews: Preview factories for interactive examples, by class name. + component_list: The doc's key, then the documented components. + current: The page's route segment, ``""`` for the main page. + variants: The route segments of the doc's variant pages. + source: The page's markdown, when the caller has read it. + + Returns: + A function that renders the page, for ``docpage``. + """ shared = shared_html_props([item[0] for item in component_list[1:]]) components = [ component_docs(component_tuple, previews, shared) for component_tuple in component_list[1:] ] - ll_actual_path = actual_path.replace(".md", "-ll.md") - ll_doc_exists = os.path.exists(ll_actual_path) - ll_list = ll_component_list if ll_component_list is not None else component_list - ll_shared = shared_html_props([item[0] for item in ll_list[1:]]) - ll_components = [ - component_docs(component_tuple, previews, ll_shared) - for component_tuple in ll_list[1:] - ] + names = [item[1] for item in component_list[1:]] - def shared_reference(props): - """Render the common reference once, retaining it in prerendered HTML.""" - if not props: - return rx.fragment() - return rx.el.div( - h3_comp(text="Shared HTML props"), - rx.el.p( - "Components linked to this section accept these HTML props. " - "Component-specific additions and overrides are listed with each " - "component.", - class_name="mb-2 text-sm leading-6 text-muted-foreground", - ), - html_attributes_disclosure("Shared HTML attributes", props), - ) - - active_class_name = "flex min-h-10 w-28 items-center justify-center rounded-full bg-primary px-4 py-2 text-center text-sm font-normal text-primary-foreground" - - non_active_class_name = "flex min-h-10 w-28 items-center justify-center rounded-full px-4 py-2 text-center text-sm font-normal text-muted-foreground transition-colors hover:bg-accent-hover hover:text-foreground motion-reduce:transition-none" - link_class_name = "rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring" - - def links(current_page, ll_doc_exists, path): - path = str(path).rstrip("/") - if ll_doc_exists: - if current_page == "hl": - return rx.box( - rx.box(class_name="flex-grow"), - rx.box( - rx.link( - rx.box(rx.text("High Level"), class_name=active_class_name), - underline="none", - aria_current="page", - class_name=link_class_name, - ), - rx.link( - rx.box( - rx.text("Low Level"), class_name=non_active_class_name - ), - href=path + "/low/", - underline="none", - class_name=link_class_name, - ), - class_name="flex items-center justify-center gap-1 rounded-full bg-muted p-1", - ), - class_name="flex mb-2", - ) - else: - return rx.box( - rx.box(class_name="flex-grow"), - rx.flex( - rx.link( - rx.box( - rx.text("High Level"), class_name=non_active_class_name - ), - href=path + "/", - underline="none", - class_name=link_class_name, - ), - rx.link( - rx.box(rx.text("Low Level"), class_name=active_class_name), - href=path + "/low/", - underline="none", - aria_current="page", - class_name=link_class_name, - ), - class_name="flex items-center justify-center gap-1 rounded-full bg-muted p-1", - ), - class_name="flex mb-2", - ) - return rx.fragment() - - @docpage( - set_path=path, - t=title, - description=description, - image=image, - source_path=actual_path, - component_name=component_title_name([c[1] for c in component_list[1:]]), - ) - def out(): + def page(): toc = get_docgen_toc(actual_path) - # Reuse the source already read by the caller to avoid a second read. doc_content = ( source if source is not None else Path(actual_path).read_text(encoding="utf-8") ) - toc.extend( - api_reference_toc([item[1] for item in component_list[1:]], bool(shared)) + differences, differences_toc = ( + ui_differences_section(names) if current == "ui" else ([], []) ) + toc.extend(differences_toc) + toc.extend(api_reference_toc(names, bool(shared))) api_ref_section = ( [ h2_comp(text="API Reference"), @@ -1204,59 +1268,117 @@ def out(): virtual_filepath=virtual_path, actual_filepath=actual_path ) return (toc, doc_content), rx.box( - links("hl", ll_doc_exists, path), + variant_switch(path, current, variants), body, + *differences, *api_ref_section, *([faq_script] if faq_script is not None else []), class_name="flex flex-col w-full", ) - # Differentiate the low-level page's meta description so search engines - # don't see it as a duplicate of the high-level page's description. Truncate - # the base first so the differentiating suffix always survives the cap. - ll_suffix = " (low-level API reference)" - ll_description = ( - f"{truncate_meta_description(description, max_len=155 - len(ll_suffix))}{ll_suffix}" - if description - else None - ) + return page + + +def multi_docs( + path: str, + virtual_path: str, + actual_path: str, + previews: dict[str, str], + component_list: list, + title: str, + description: str | None = None, + image: str | None = None, + variant_component_lists: dict[str, list] | None = None, + variant_previews: dict[str, dict[str, str]] | None = None, + variant_descriptions: dict[str, str | None] | None = None, + source: str | None = None, +): + """Build the pages of a library doc: the main one and each variant beside it. - @docpage( - set_path=path.rstrip("/") + "/low/", - t=title + " (Low Level)", - description=ll_description, + Args: + path: The main page's route. + virtual_path: The main page's markdown file, as the docs pipeline names it. + actual_path: The main page's markdown file on disk. + previews: The main page's preview factories, by class name. + component_list: The doc's key, then the main page's components. + title: The main page's title. + description: The main page's meta description. + image: The doc's social preview image. + variant_component_lists: The components of each variant page that has + its own, by file suffix; a Low Level page without them documents + the main page's. + variant_previews: The preview factories of each variant page that has + its own, by file suffix; the main page's otherwise. + variant_descriptions: The meta description of each variant page that + has its own prose, by file suffix. + source: The main page's markdown, when the caller has read it. + + Returns: + The main page, or a tuple of it and its variant pages. + """ + variant_component_lists = variant_component_lists or {} + variant_previews = variant_previews or {} + variant_descriptions = variant_descriptions or {} + present = [ + variant + for variant in LIBRARY_VARIANTS + if os.path.exists(library_variant_path(actual_path, variant[0])) + ] + segments = [variant[1] for variant in present] + + out = docpage( + set_path=path, + t=title, + description=description, image=image, - source_path=ll_actual_path, - component_name=component_title_name([c[1] for c in ll_list[1:]]), - ) - def ll(): - ll_virtual = virtual_path.replace(".md", "-ll.md") - toc = get_docgen_toc(ll_actual_path) - doc_content = Path(ll_actual_path).read_text(encoding="utf-8") - toc.extend( - api_reference_toc([item[1] for item in ll_list[1:]], bool(ll_shared)) - ) - api_ref_section = ( - [ - h2_comp(text="API Reference"), - rx.box(*ll_components, class_name="flex flex-col"), - shared_reference(ll_shared), - ] - if ll_components - else [] - ) - body, faq_script = render_docgen_document( - virtual_filepath=ll_virtual, actual_filepath=ll_actual_path - ) - return (toc, doc_content), rx.box( - links("ll", ll_doc_exists, path), - body, - *api_ref_section, - *([faq_script] if faq_script is not None else []), - class_name="flex flex-col w-full", + source_path=actual_path, + component_name=component_title_name([c[1] for c in component_list[1:]]), + )( + library_page( + path, + virtual_path, + actual_path, + previews, + component_list, + "", + segments, + source, ) + ) - if ll_doc_exists: - return (out, ll) - else: - return out + pages = [out] + for suffix, segment, _, title_suffix, description_suffix in present: + variant_actual = library_variant_path(actual_path, suffix) + variant_list = variant_component_lists.get(suffix, component_list) + variant_description = variant_descriptions.get(suffix) + if variant_description is None and description: + # Differentiate the page's meta description so search engines don't + # see it as a duplicate of the main page's. Truncate the base first + # so the differentiating suffix always survives the cap. + variant_description = ( + truncate_meta_description( + description, max_len=155 - len(description_suffix) + ) + + description_suffix + ) + pages.append( + docpage( + set_path=path.rstrip("/") + f"/{segment}/", + t=title + title_suffix, + description=variant_description, + image=image, + source_path=variant_actual, + component_name=component_title_name([c[1] for c in variant_list[1:]]), + )( + library_page( + path, + library_variant_path(virtual_path, suffix), + variant_actual, + variant_previews.get(suffix, previews), + variant_list, + segment, + segments, + ) + ) + ) + return tuple(pages) if len(pages) > 1 else out diff --git a/docs/app/reflex_docs/pages/docs/metadata.py b/docs/app/reflex_docs/pages/docs/metadata.py index 1000c08ce0f..5e642bbdd82 100644 --- a/docs/app/reflex_docs/pages/docs/metadata.py +++ b/docs/app/reflex_docs/pages/docs/metadata.py @@ -16,7 +16,7 @@ } # Namespaces too broad to name a page on their own. -_GENERIC_NAMESPACES = {"", "rx", "rx.recharts"} +_GENERIC_NAMESPACES = {"", "rx", "rx.recharts", "rx.ui"} # Summaries for generated catalogs, reference pages, and pages without usable prose. PAGE_DESCRIPTIONS = { diff --git a/docs/app/reflex_docs/pages/docs/ui_differences.py b/docs/app/reflex_docs/pages/docs/ui_differences.py new file mode 100644 index 00000000000..81de3ffe74f --- /dev/null +++ b/docs/app/reflex_docs/pages/docs/ui_differences.py @@ -0,0 +1,157 @@ +"""The intended differences between rx.ui and Radix, read from the parity allowlist. + +The parity harness fails when a difference it finds is not listed in +``allowlist.toml``, and when a listed one no longer happens, so a page that +renders the file cannot describe a difference that is gone. +""" + +import tomllib +from collections import defaultdict +from functools import cache +from pathlib import Path + +ALLOWLIST = ( + Path(__file__).resolve().parents[5] + / "packages" + / "reflex-components-ui" + / "parity" + / "allowlist.toml" +) + +# The allowlist's name for a difference every component shares. +EVERY_COMPONENT = "*" + + +def _engines(entry: dict) -> str: + """Name the browser engines an entry is limited to. + + Args: + entry: An allowlist entry. + + Returns: + ``" in chromium, webkit"``, or nothing when it holds in every engine. + """ + engines = entry.get("engines") + return f" in {', '.join(engines)}" if engines else "" + + +def _codes(names: list[str]) -> str: + """Join names as inline code. + + Args: + names: Props, event triggers or CSS properties. + + Returns: + The names, each in backticks, separated by commas. + """ + return ", ".join(f"`{name}`" for name in names) + + +def _api_item(entry: dict) -> str: + """Describe a prop, type, event or style keyword that differs. + + Args: + entry: An ``[[api]]`` entry. + + Returns: + The list item's text. + """ + kind = {"prop": "Props", "type": "Prop types", "event": "Events"}.get( + entry["kind"], "Style keywords" + ) + return f"**{kind}** {_codes(entry['names'])}: {entry['reason']}" + + +def _contract_item(entry: dict) -> str: + """Describe a step of a behaviour contract one system does not pass. + + Args: + entry: A ``[[contract]]`` entry. + + Returns: + The list item's text. + """ + system = entry.get("system", "rx.ui") + return ( + f"**Behaviour**, *{entry['step']}*: `{system}` does not{_engines(entry)}. " + f"{entry['reason']}" + ) + + +def _look_item(entry: dict) -> str: + """Describe pixels, computed style or accessibility that differ. + + Args: + entry: A ``[[look]]`` entry. + + Returns: + The list item's text. + """ + check = { + "pixels": "Pixels", + "style": "Computed style", + "a11y": "Accessibility tree", + } + what = _codes(entry["properties"]) if entry.get("properties") else "" + if not what and entry.get("cells"): + what = f"cells `{entry['cells']}`" + detail = f" ({what}{_engines(entry)})" if what or entry.get("engines") else "" + return f"**{check[entry['check']]}**{detail}: {entry['reason']}" + + +@cache +def differences_by_component(path: Path = ALLOWLIST) -> dict[str, tuple[str, ...]]: + """Read the allowlist as one markdown list item per difference. + + Args: + path: The allowlist file. + + Returns: + The items of each component, by its name in the allowlist: ``"text"``, + ``"text.span"``, or ``"*"`` for every component. + """ + document = tomllib.loads(path.read_text(encoding="utf-8")) + items: defaultdict[str, list[str]] = defaultdict(list) + for table, render in ( + ("api", _api_item), + ("contract", _contract_item), + ("look", _look_item), + ): + for entry in document.get(table, ()): + items[entry["component"]].append(render(entry)) + return {component: tuple(lines) for component, lines in items.items()} + + +def differences_markdown(components: list[str], path: Path = ALLOWLIST) -> str: + """List the differences of the components a page documents. + + Args: + components: Their names, as the frontmatter lists them: ``rx.ui.dialog.root``. + path: The allowlist file. + + Returns: + A markdown list, empty when none of them differs. + """ + names = {name.removeprefix("rx.ui.") for name in components} + by_component = differences_by_component(path) + return "\n".join( + f"- {item}" + for component, items in sorted(by_component.items()) + if component != EVERY_COMPONENT + and any(name == component or name.startswith(component + ".") for name in names) + for item in items + ) + + +def shared_differences_markdown(path: Path = ALLOWLIST) -> str: + """List the differences every rx.ui component shares. + + Args: + path: The allowlist file. + + Returns: + A markdown list. + """ + return "\n".join( + f"- {item}" for item in differences_by_component(path).get(EVERY_COMPONENT, ()) + ) diff --git a/docs/app/reflex_docs/templates/docpage/docpage.py b/docs/app/reflex_docs/templates/docpage/docpage.py index 43ef64f776a..f079744b8af 100644 --- a/docs/app/reflex_docs/templates/docpage/docpage.py +++ b/docs/app/reflex_docs/templates/docpage/docpage.py @@ -227,7 +227,7 @@ def breadcrumb_data(path: str, title: str) -> dict: # Route segments whose section goes by another name in the navbar and sidebar. -_SECTION_LABELS = {"hosting": "Cloud", "library": "Components"} +_SECTION_LABELS = {"hosting": "Cloud", "library": "Components", "rx-ui": "rx.ui"} def _breadcrumb_label(segment: str) -> str: @@ -285,7 +285,10 @@ def _breadcrumb_items( _breadcrumb_label(segment), _resolve_breadcrumb_href(current_path), )) - if items: + if len(segments) > 1 and segments[0] == "library" and segments[-1] == "ui": + # The rx.ui page of a library doc. + items[-1] = ("rx.ui", items[-1][1]) + elif items: for name in names: label = uppercase_acronyms(name) if _same_letters(label, segments[-1]): diff --git a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py index 2265bd6ebdd..35166fa5100 100644 --- a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py +++ b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py @@ -40,7 +40,7 @@ if (!sidebarContainer) return; const currentPath = window.location.pathname.replace(/\\/+$|\\/$/g, "") + "/"; - const baseComponentPath = currentPath.replace(/\\/low\\/$/, "/"); + const baseComponentPath = currentPath.replace(/\\/(low|ui)\\/$/, "/"); const baseComponentPathWithoutDocs = baseComponentPath.replace(/^\\/docs\\//, "/"); const activeLink = sidebarContainer.querySelector(`a[href="${currentPath}"]`) || @@ -311,8 +311,9 @@ def normalize_url(url: str | None) -> str: path = "/" elif path.startswith("/docs/"): path = path.removeprefix("/docs") - if path.startswith("/library/") and path.endswith("/low"): - path = path.removesuffix("/low") + if path.startswith("/library/"): + # A library doc's Low Level and rx.ui pages select its sidebar entry. + path = path.removesuffix("/low").removesuffix("/ui") return path.rstrip("/") + "/" diff --git a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py index 50b9e25f660..ee865ee083b 100644 --- a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py +++ b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar_items/learn.py @@ -54,6 +54,7 @@ def get_sidebar_items_frontend(): components, library_, pages, + rx_ui, styling, ui, wrapping_react, @@ -95,6 +96,14 @@ def get_sidebar_items_frontend(): styling.tailwind, ], ), + create_item( + "rx.ui", + children=[ + rx_ui.overview, + rx_ui.styling, + rx_ui.theming, + ], + ), create_item( "Assets", children=[ diff --git a/docs/app/rxconfig.py b/docs/app/rxconfig.py index 810f2f6c9f3..0927d43d69f 100644 --- a/docs/app/rxconfig.py +++ b/docs/app/rxconfig.py @@ -21,6 +21,11 @@ plugins=[ reflex_xy.XYPlugin(), rx.plugins.TailwindV4Plugin(), + # Compiles the styles of the rx.ui previews. Its theme matches the + # rx.theme of the app, so the two sets of previews look the same. + rx.plugins.UIPlugin( + theme=rx.ui.Theme(accent_color="violet", radius="large"), + ), SharedSiteStylesPlugin(), rx.plugins.SitemapPlugin(trailing_slash="always"), AgentFilesPlugin(), diff --git a/docs/app/tests/test_routes.py b/docs/app/tests/test_routes.py index 3d8fd103dcb..cc86d0e92fd 100644 --- a/docs/app/tests/test_routes.py +++ b/docs/app/tests/test_routes.py @@ -349,8 +349,8 @@ def test_markdown_doc_routes_edit_their_own_source(routes_fixture): edit_prefix = "https://github.com/reflex-dev/reflex/edit/main/" venv = Path(sys.prefix).resolve() for route, actual in doc_markdown_sources.items(): - if route.endswith("-ll"): - # Low-level sources are served for the copy button, not as routes. + if route.endswith(("-ll", "-ui")): + # Variant sources are served for the copy button, not as routes. continue actual_path = Path(actual).resolve() if not actual_path.is_relative_to(REPO_ROOT) or actual_path.is_relative_to( diff --git a/docs/app/tests/test_ui_pages.py b/docs/app/tests/test_ui_pages.py new file mode 100644 index 00000000000..61ddd2b1377 --- /dev/null +++ b/docs/app/tests/test_ui_pages.py @@ -0,0 +1,215 @@ +"""The rx.ui pages of the component library and the differences they list.""" + +import importlib +import tomllib +from pathlib import Path + +import pytest + +from reflex_docs.pages.docs.component import library_variant_path +from reflex_docs.pages.docs.metadata import component_title_name +from reflex_docs.pages.docs.ui_differences import ( + ALLOWLIST, + differences_markdown, + shared_differences_markdown, +) +from reflex_docs.templates.docpage.sidebar.sidebar import normalize_url + +ALLOWLIST_TEXT = """ +[[api]] +component = "*" +kind = "style" +names = ["p", "m"] +reason = "Shared." + +[[api]] +component = "text" +kind = "prop" +names = ["form", "html_for"] +reason = "Labels." + +[[api]] +component = "text.span" +kind = "event" +names = ["on_click"] +reason = "Span." + +[[contract]] +component = "select" +step = "opens with Enter" +reason = "Native." + +[[contract]] +component = "select" +step = "the list is in the server render" +system = "rx" +engines = ["webkit"] +reason = "Portal." + +[[look]] +component = "checkbox_cards" +check = "style" +properties = ["outline-color"] +engines = ["firefox"] +reason = "Focus ring." + +[[look]] +component = "avatar" +check = "pixels" +cells = "size-*@800" +reason = "Letters." +""" + + +@pytest.fixture +def allowlist(tmp_path) -> Path: + path = tmp_path / "allowlist.toml" + path.write_text(ALLOWLIST_TEXT, encoding="utf-8") + return path + + +def test_differences_of_a_page_cover_its_namespaces(allowlist): + assert differences_markdown(["rx.ui.text", "rx.ui.text.span"], allowlist) == ( + "- **Props** `form`, `html_for`: Labels.\n- **Events** `on_click`: Span." + ) + assert differences_markdown( + ["rx.ui.select.root", "rx.ui.select.item"], allowlist + ) == ( + "- **Behaviour**, *opens with Enter*: `rx.ui` does not. Native.\n" + "- **Behaviour**, *the list is in the server render*: `rx` does not in " + "webkit. Portal." + ) + assert differences_markdown(["rx.ui.avatar"], allowlist) == ( + "- **Pixels** (cells `size-*@800`): Letters." + ) + + +def test_differences_do_not_match_a_longer_name(allowlist): + """``checkbox`` is not ``checkbox_cards``, and the shared entry is listed apart.""" + assert differences_markdown(["rx.ui.checkbox"], allowlist) == "" + assert differences_markdown(["rx.ui.checkbox_cards.root"], allowlist) == ( + "- **Computed style** (`outline-color` in firefox): Focus ring." + ) + assert shared_differences_markdown(allowlist) == ( + "- **Style keywords** `p`, `m`: Shared." + ) + + +def test_every_allowlisted_component_has_an_rx_ui_page(): + """A difference the harness records reaches a page that documents it.""" + from reflex_docs.pages.docs import ui_library_pages + + documented = { + name.removeprefix("rx.ui.") + for _, _, components in ui_library_pages.values() + for _, name in components + } + components = { + entry["component"] + for table in tomllib.loads(ALLOWLIST.read_text(encoding="utf-8")).values() + for entry in table + } - {"*"} + assert { + component + for component in components + if not any( + name == component or name.startswith(component + ".") for name in documented + ) + } == set() + + +def test_every_rx_ui_component_has_a_page(): + """Each name of the rx.ui namespace is documented on a library page.""" + import reflex_components_ui + + from reflex_docs.pages.docs import ui_library_pages + + documented = { + name.removeprefix("rx.ui.").split(".")[0] + for _, _, components in ui_library_pages.values() + for _, name in components + } + # Not components: the theme of the plugin and the design tokens, which the + # theming guide documents. + assert set(reflex_components_ui.__all__) - documented == {"Theme", "tokens"} + + +def test_rx_ui_pages_resolve_their_components(): + """Every component an rx.ui page lists is an rx.ui component.""" + from reflex_components_ui.base import UIComponent + + from reflex_docs.pages.docs import ui_library_pages + + unresolved = [ + name + for _, _, components in ui_library_pages.values() + for component, name in components + if not name.startswith("rx.ui.") or not issubclass(component, UIComponent) + ] + assert unresolved == [] + + +def test_library_variant_path(): + assert library_variant_path("/docs/library/forms/button.md", "-ui") == ( + "/docs/library/forms/button-ui.md" + ) + + +def test_rx_ui_page_titles_name_the_component(): + assert component_title_name(["rx.ui.button", "rx.ui.icon_button"]) == "rx.ui.button" + assert component_title_name(["rx.ui.dialog.root", "rx.ui.dialog.content"]) == ( + "rx.ui.dialog" + ) + + +def test_rx_ui_breadcrumbs(monkeypatch): + docpage_module = importlib.import_module("reflex_docs.templates.docpage.docpage") + monkeypatch.setattr( + docpage_module, + "_REGISTERED_DOC_ROUTES", + {"/library/", "/library/forms/button/", "/library/forms/button/ui/"}, + raising=False, + ) + assert [ + label + for label, _ in docpage_module._breadcrumb_items("/library/forms/button/ui/") + ] == [ + "Components", + "Forms", + "Button", + "rx.ui", + ] + assert [ + label for label, _ in docpage_module._breadcrumb_items("/rx-ui/styling/") + ] == [ + "rx.ui", + "Styling", + ] + + +@pytest.mark.parametrize( + ("url", "expected"), + [ + ("/docs/library/forms/button/ui/", "/library/forms/button/"), + ("/library/forms/select/low/", "/library/forms/select/"), + ("/ui/overview/", "/ui/overview/"), + ], +) +def test_variant_pages_select_their_sidebar_entry(url, expected): + assert normalize_url(url) == expected + + +@pytest.mark.parametrize( + ("doc", "expected"), + [ + ("docs/library/forms/button-ui.md", "-ui"), + ("docs/library/forms/select-ll.md", "-ll"), + ("docs/library/forms/button.md", None), + # A package named like a variant is a changelog, not an rx.ui page. + ("docs/changelog/reflex-components-ui.md", None), + ], +) +def test_library_variant_suffix(doc, expected): + from reflex_docs.pages.docs import library_variant_suffix + + assert library_variant_suffix(doc) == expected diff --git a/docs/library/forms/button-ui.md b/docs/library/forms/button-ui.md new file mode 100644 index 00000000000..769f6f8557c --- /dev/null +++ b/docs/library/forms/button-ui.md @@ -0,0 +1,101 @@ +--- +components: + - rx.ui.button + - rx.ui.icon_button + +Button: | + lambda **props: rx.ui.button("Basic Button", **props) + +IconButton: | + lambda **props: rx.ui.icon_button(rx.icon("heart"), aria_label="Like", **props) +--- + +```python exec +import reflex as rx +``` + +# Button + +`rx.ui.button` and `rx.ui.icon_button` take the props of `rx.button` and +`rx.icon_button` and render a plain `button` element whose styles are compiled +at build time. See [rx.ui](/rx-ui/overview/) for how to install the package and +opt in. + +## Basic Example + +```python demo exec +class UICountState(rx.State): + count: int = 0 + + @rx.event + def increment(self): + self.count += 1 + + @rx.event + def decrement(self): + self.count -= 1 + + +def ui_counter(): + return rx.ui.flex( + rx.ui.button("Decrement", color_scheme="red", on_click=UICountState.decrement), + rx.ui.heading(UICountState.count, as_="h2"), + rx.ui.button("Increment", color_scheme="grass", on_click=UICountState.increment), + gap="3", + ) +``` + +## Variants and Sizes + +```python demo +rx.ui.flex( + rx.ui.button("Classic", variant="classic"), + rx.ui.button("Solid", variant="solid"), + rx.ui.button("Soft", variant="soft"), + rx.ui.button("Surface", variant="surface"), + rx.ui.button("Outline", variant="outline"), + rx.ui.button("Ghost", variant="ghost"), + gap="3", + align="center", + wrap="wrap", +) +``` + +```python demo +rx.ui.flex( + rx.ui.button("Size 1", size="1"), + rx.ui.button("Size 2", size="2"), + rx.ui.button("Size 3", size="3"), + rx.ui.button("Size 4", size="4"), + gap="3", + align="center", +) +``` + +## Loading and Disabled + +`loading=True` shows a spinner over the children and disables the button, so +it cannot be pressed twice. `disabled=True` disables it without a spinner. + +```python demo +rx.ui.flex( + rx.ui.button("Regular"), + rx.ui.button("Loading", loading=True), + rx.ui.button("Disabled", disabled=True), + gap="2", +) +``` + +## Icon Button + +`rx.ui.icon_button` is a square button for one icon. Give it an `aria_label`: +the icon has no text a screen reader can announce. + +```python demo +rx.ui.flex( + rx.ui.icon_button(rx.icon("plus"), aria_label="Add", variant="solid"), + rx.ui.icon_button(rx.icon("pencil"), aria_label="Edit", variant="soft"), + rx.ui.icon_button(rx.icon("trash-2"), aria_label="Delete", color_scheme="red", variant="outline"), + gap="3", +) +``` diff --git a/docs/library/layout/aspect_ratio-ui.md b/docs/library/layout/aspect_ratio-ui.md new file mode 100644 index 00000000000..c48fa7e42a4 --- /dev/null +++ b/docs/library/layout/aspect_ratio-ui.md @@ -0,0 +1,31 @@ +--- +components: + - rx.ui.aspect_ratio +--- +```python exec +import reflex as rx +``` + +# Aspect Ratio + +`rx.ui.aspect_ratio` takes the props of `rx.aspect_ratio` and renders a `div` that keeps its content at a ratio whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.box( + rx.ui.aspect_ratio( + rx.ui.center( + rx.ui.text("16 / 9"), + style={ + "width": "100%", + "height": "100%", + "background_color": rx.ui.tokens.accent[4], + "border_radius": rx.ui.tokens.radius[3], + }, + ), + ratio=16 / 9, + ), + style={"width": "320px"}, +) +``` diff --git a/docs/library/layout/box-ui.md b/docs/library/layout/box-ui.md new file mode 100644 index 00000000000..6e5e5801b02 --- /dev/null +++ b/docs/library/layout/box-ui.md @@ -0,0 +1,46 @@ +--- +components: + - rx.ui.box +--- +```python exec +import reflex as rx +``` + +# Box + +`rx.ui.box` takes the props of `rx.box` and renders a plain `div` whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +A box has no styles of its own beyond `display: block`. Give it styles with +keyword arguments or `style`; tokens keep it on the theme's scales. + +```python demo +rx.ui.box( + "A box with a border and padding.", + style={ + "padding": rx.ui.tokens.space[4], + "border": f"1px solid {rx.ui.tokens.gray[6]}", + "border_radius": rx.ui.tokens.radius[3], + "background_color": rx.ui.tokens.accent[2], + }, +) +``` + +## Responsive Styles + +```python demo +rx.ui.box( + "Wider screens give this box more padding.", + style={ + "padding": rx.breakpoints(initial="8px", md="32px"), + "background_color": rx.ui.tokens.gray[3], + "border_radius": rx.ui.tokens.radius[2], + }, +) +``` + +The spacing shorthands of Radix Themes, such as `p="4"`, are not CSS +properties: `rx.box` passes them on and the browser ignores them, and +`rx.ui.box` raises a `StyleError` that names the style to use instead. See +[What Is Not Supported](/rx-ui/styling/#what-is-not-supported). diff --git a/docs/library/layout/card-ui.md b/docs/library/layout/card-ui.md new file mode 100644 index 00000000000..12fc3dda946 --- /dev/null +++ b/docs/library/layout/card-ui.md @@ -0,0 +1,65 @@ +--- +components: + - rx.ui.card + +Card: | + lambda **props: rx.ui.card("Basic Card", **props) +--- +```python exec +import reflex as rx +``` + +# Card + +`rx.ui.card` takes the props of `rx.card` and renders a `div` with the frame of a Radix card whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.card( + rx.ui.flex( + rx.ui.avatar(fallback="RX", size="3"), + rx.ui.box( + rx.ui.heading("Quick Start", size="3", as_="h3"), + rx.ui.text("Get started with Reflex in 5 minutes.", size="2", color_scheme="gray"), + ), + gap="3", + align="center", + ), + style={"max_width": "360px"}, +) +``` + +## Variants and Sizes + +```python demo +rx.ui.flex( + rx.ui.card("Surface", variant="surface"), + rx.ui.card("Classic", variant="classic"), + rx.ui.card("Ghost", variant="ghost"), + gap="3", +) +``` + +```python demo +rx.ui.flex( + rx.ui.card("Size 1", size="1"), + rx.ui.card("Size 2", size="2"), + rx.ui.card("Size 3", size="3"), + gap="3", + align="start", +) +``` + +## As a Link + +With `as_child`, the card styles the element it wraps, such as a link, instead +of rendering its own `div`. + +```python demo +rx.ui.card( + rx.ui.link(rx.ui.text("A card that is a link", weight="bold"), href="#as-a-link"), + as_child=True, + style={"max_width": "360px"}, +) +``` diff --git a/docs/library/layout/center-ui.md b/docs/library/layout/center-ui.md new file mode 100644 index 00000000000..ee57e3d2771 --- /dev/null +++ b/docs/library/layout/center-ui.md @@ -0,0 +1,27 @@ +--- +components: + - rx.ui.center + +Center: | + lambda **props: rx.ui.center(rx.ui.text("Centered"), style={"height": "80px", "border": "1px dashed var(--gray-7)"}, **props) +--- +```python exec +import reflex as rx +``` + +# Center + +`rx.ui.center` takes the props of `rx.center` and renders a flex `div` that centers its children on both axes whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.center( + rx.ui.text("Hello World!"), + style={ + "height": "120px", + "border_radius": rx.ui.tokens.radius[3], + "background_color": rx.ui.tokens.accent[3], + }, +) +``` diff --git a/docs/library/layout/container-ui.md b/docs/library/layout/container-ui.md new file mode 100644 index 00000000000..8081880eb07 --- /dev/null +++ b/docs/library/layout/container-ui.md @@ -0,0 +1,36 @@ +--- +components: + - rx.ui.container +--- +```python exec +import reflex as rx +``` + +# Container + +`rx.ui.container` takes the props of `rx.container` and renders a `div` that centers content at a maximum width whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.box( + rx.ui.container( + rx.ui.card("This content is constrained to a max width of 448px."), + size="1", + ), + style={"background_color": rx.ui.tokens.gray[3], "width": "100%"}, +) +``` + +`size` sets the maximum width: 448px, 688px, 880px and 1136px for `"1"` to +`"4"`. + +## `stack_children_full_width` + +`rx.container(stack_children_full_width=True)` makes the stacks inside it full +width through a nested selector, which `rx.ui` styles do not compile. On +`rx.ui.container` it raises: + +```text +StyleError: rx.ui.container: stack_children_full_width styles the stacks inside the container through nested selectors, which rx.ui styles do not support. Give those stacks width="100%", or keep rx.container for this element. +``` diff --git a/docs/library/layout/flex-ui.md b/docs/library/layout/flex-ui.md new file mode 100644 index 00000000000..a6c7cf376fa --- /dev/null +++ b/docs/library/layout/flex-ui.md @@ -0,0 +1,54 @@ +--- +components: + - rx.ui.flex + +Flex: | + lambda **props: rx.ui.flex( + rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), + gap="2", + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Flex + +`rx.ui.flex` takes the props of `rx.flex` and renders a `div` laid out with flexbox whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.card("Card 1"), + rx.ui.card("Card 2"), + rx.ui.card("Card 3"), + gap="2", +) +``` + +## Direction, Alignment and Wrapping + +`direction`, `align`, `justify`, `wrap` and `gap` take the values of Radix +Themes, and each takes `rx.breakpoints(...)` for a value per breakpoint. + +```python demo +rx.ui.flex( + rx.ui.card("Card 1"), + rx.ui.card("Card 2"), + rx.ui.card("Card 3"), + direction=rx.breakpoints(initial="column", sm="row"), + justify="between", + gap="3", +) +``` + +```python demo +rx.ui.flex( + *[rx.ui.badge(f"Item {i}") for i in range(1, 13)], + wrap="wrap", + gap="2", + style={"max_width": "320px"}, +) +``` diff --git a/docs/library/layout/grid-ui.md b/docs/library/layout/grid-ui.md new file mode 100644 index 00000000000..118126b3c73 --- /dev/null +++ b/docs/library/layout/grid-ui.md @@ -0,0 +1,52 @@ +--- +components: + - rx.ui.grid + +Grid: | + lambda **props: rx.ui.grid( + *[rx.ui.card(f"Card {i}") for i in range(1, 7)], + columns="3", + gap="2", + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Grid + +`rx.ui.grid` takes the props of `rx.grid` and renders a `div` laid out with CSS grid whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +`columns` and `rows` take a number of tracks or a template. + +```python demo +rx.ui.grid( + *[rx.ui.card(f"Card {i}") for i in range(1, 7)], + columns="3", + gap="3", +) +``` + +## Responsive Columns + +```python demo +rx.ui.grid( + *[rx.ui.card(f"Card {i}") for i in range(1, 9)], + columns=rx.breakpoints(initial="2", sm="4"), + gap="3", +) +``` + +## Flow + +```python demo +rx.ui.grid( + *[rx.ui.card(f"Card {i}") for i in range(1, 7)], + rows="2", + flow="column", + gap="3", +) +``` diff --git a/docs/library/layout/inset-ui.md b/docs/library/layout/inset-ui.md new file mode 100644 index 00000000000..f1458b3061c --- /dev/null +++ b/docs/library/layout/inset-ui.md @@ -0,0 +1,38 @@ +--- +components: + - rx.ui.inset + +Inset: | + lambda **props: rx.ui.card( + rx.ui.inset( + rx.image(src="https://web.reflex-assets.dev/other/reflex_banner.png", alt="Reflex banner image", width="100%", height="auto"), + **props, + ), + style={"max_width": "320px"}, + ) +--- +```python exec +import reflex as rx +``` + +# Inset + +`rx.ui.inset` takes the props of `rx.inset` and renders a `div` that extends its content to the edges of a card whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.card( + rx.ui.inset( + rx.image(src="https://web.reflex-assets.dev/other/reflex_banner.png", alt="Reflex banner image", width="100%", height="auto"), + side="top", + pb="current", + ), + rx.ui.text("Reflex is a web framework for building full-stack apps in Python.", size="2"), + style={"max_width": "320px"}, +) +``` + +`rx.ui.inset` declares the spacing props of Radix Themes (`p`, `px`, `pt`, +...), so it takes them as `rx.inset` does: `pb="current"` keeps the card's +padding below the image. diff --git a/docs/library/layout/section-ui.md b/docs/library/layout/section-ui.md new file mode 100644 index 00000000000..294350ea213 --- /dev/null +++ b/docs/library/layout/section-ui.md @@ -0,0 +1,32 @@ +--- +components: + - rx.ui.section + +Section: | + lambda **props: rx.ui.section(rx.ui.heading("Section", size="4", as_="h3"), **props) +--- +```python exec +import reflex as rx +``` + +# Section + +`rx.ui.section` takes the props of `rx.section` and renders a `section` element with the vertical padding of a Radix section whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.box( + rx.ui.section( + rx.ui.heading("First", size="4", as_="h3"), + rx.ui.text("A section of size 1."), + size="1", + ), + rx.ui.section( + rx.ui.heading("Second", size="4", as_="h3"), + rx.ui.text("A section of size 2, with more space."), + size="2", + style={"background_color": rx.ui.tokens.gray[3]}, + ), +) +``` diff --git a/docs/library/layout/separator-ui.md b/docs/library/layout/separator-ui.md new file mode 100644 index 00000000000..d239b60d126 --- /dev/null +++ b/docs/library/layout/separator-ui.md @@ -0,0 +1,40 @@ +--- +components: + - rx.ui.separator + +Separator: | + lambda **props: rx.ui.separator(**props) +--- +```python exec +import reflex as rx +``` + +# Separator + +`rx.ui.separator` takes the props of `rx.separator` and renders a line between content whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. `rx.ui.divider` is the same component. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.text("Above"), + rx.ui.separator(size="4"), + rx.ui.text("Below"), + direction="column", + gap="3", +) +``` + +## Orientation + +```python demo +rx.ui.flex( + rx.ui.text("Blog"), + rx.ui.separator(orientation="vertical"), + rx.ui.text("Docs"), + rx.ui.separator(orientation="vertical"), + rx.ui.text("Source"), + gap="3", + align="center", +) +``` diff --git a/docs/library/layout/spacer-ui.md b/docs/library/layout/spacer-ui.md new file mode 100644 index 00000000000..341e6d8dbde --- /dev/null +++ b/docs/library/layout/spacer-ui.md @@ -0,0 +1,22 @@ +--- +components: + - rx.ui.spacer +--- +```python exec +import reflex as rx +``` + +# Spacer + +`rx.ui.spacer` takes the props of `rx.spacer` and renders a flex item that takes the free space of its row or column whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.badge("Left"), + rx.ui.spacer(), + rx.ui.badge("Right"), + style={"width": "100%"}, +) +``` diff --git a/docs/library/layout/stack-ui.md b/docs/library/layout/stack-ui.md new file mode 100644 index 00000000000..631e69b6a63 --- /dev/null +++ b/docs/library/layout/stack-ui.md @@ -0,0 +1,50 @@ +--- +components: + - rx.ui.stack + - rx.ui.hstack + - rx.ui.vstack + +Stack: | + lambda **props: rx.ui.stack(rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), **props) + +HStack: | + lambda **props: rx.ui.hstack(rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), **props) + +VStack: | + lambda **props: rx.ui.vstack(rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), **props) +--- +```python exec +import reflex as rx +``` + +# Stack + +`rx.ui.stack` and `rx.ui.hstack` and `rx.ui.vstack` take the props of `rx.stack` and `rx.hstack` and `rx.vstack` and render a flex `div` with a default gap whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +`rx.ui.vstack` stacks its children in a column and `rx.ui.hstack` in a row; +`rx.ui.stack` takes a `direction`. + +```python demo +rx.ui.flex( + rx.ui.vstack(rx.ui.badge("One"), rx.ui.badge("Two"), rx.ui.badge("Three")), + rx.ui.hstack(rx.ui.badge("One"), rx.ui.badge("Two"), rx.ui.badge("Three")), + rx.ui.stack(rx.ui.badge("One"), rx.ui.badge("Two"), direction="row-reverse"), + gap="6", + align="start", +) +``` + +## Spacing + +`spacing` sets the gap on the space scale, `"0"` to `"9"`. + +```python demo +rx.ui.hstack( + rx.ui.card("Card 1"), + rx.ui.card("Card 2"), + rx.ui.card("Card 3"), + spacing="6", +) +``` diff --git a/docs/library/typography/blockquote-ui.md b/docs/library/typography/blockquote-ui.md new file mode 100644 index 00000000000..2f96b50eeee --- /dev/null +++ b/docs/library/typography/blockquote-ui.md @@ -0,0 +1,29 @@ +--- +components: + - rx.ui.blockquote +--- +```python exec +import reflex as rx +``` + +# Blockquote + +`rx.ui.blockquote` takes the props of `rx.blockquote` and renders a `blockquote` element whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.blockquote("Perfect typography is certainly the most elusive of all arts.") +``` + +## Size and Color + +```python demo +rx.ui.flex( + rx.ui.blockquote("Size 2", size="2"), + rx.ui.blockquote("Size 5", size="5"), + rx.ui.blockquote("Cyan", color_scheme="cyan"), + direction="column", + gap="3", +) +``` diff --git a/docs/library/typography/code-ui.md b/docs/library/typography/code-ui.md new file mode 100644 index 00000000000..f610363c1ae --- /dev/null +++ b/docs/library/typography/code-ui.md @@ -0,0 +1,29 @@ +--- +components: + - rx.ui.code +--- +```python exec +import reflex as rx +``` + +# Code + +`rx.ui.code` takes the props of `rx.code` and renders a `code` element whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.text("Install it with ", rx.ui.code("pip install 'reflex[ui]'"), ".") +``` + +## Variants + +```python demo +rx.ui.flex( + rx.ui.code("solid", variant="solid"), + rx.ui.code("soft", variant="soft"), + rx.ui.code("outline", variant="outline"), + rx.ui.code("ghost", variant="ghost"), + gap="3", +) +``` diff --git a/docs/library/typography/heading-ui.md b/docs/library/typography/heading-ui.md new file mode 100644 index 00000000000..67f6229117f --- /dev/null +++ b/docs/library/typography/heading-ui.md @@ -0,0 +1,29 @@ +--- +components: + - rx.ui.heading +--- +```python exec +import reflex as rx +``` + +# Heading + +`rx.ui.heading` takes the props of `rx.heading` and renders an `h1`, or the level `as_` names, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.heading("The quick brown fox jumps over the lazy dog.", as_="h2") +``` + +## Size and Weight + +```python demo +rx.ui.flex( + rx.ui.heading("Size 3", size="3", as_="h3"), + rx.ui.heading("Size 6", size="6", as_="h3"), + rx.ui.heading("Size 8, light", size="8", weight="light", as_="h3"), + direction="column", + gap="2", +) +``` diff --git a/docs/library/typography/link-ui.md b/docs/library/typography/link-ui.md new file mode 100644 index 00000000000..f9d094a881a --- /dev/null +++ b/docs/library/typography/link-ui.md @@ -0,0 +1,33 @@ +--- +components: + - rx.ui.link +--- +```python exec +import reflex as rx +``` + +# Link + +`rx.ui.link` takes the props of `rx.link` and renders an `a` element; a relative `href` navigates in the app as `rx.link` does, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.link("Reflex docs", href="/getting-started/introduction/"), + rx.ui.link("GitHub", href="https://github.com/reflex-dev/reflex", is_external=True), + gap="4", +) +``` + +## Underline and Color + +```python demo +rx.ui.flex( + rx.ui.link("Auto", href="#underline-and-color", underline="auto"), + rx.ui.link("Hover", href="#underline-and-color", underline="hover"), + rx.ui.link("Always", href="#underline-and-color", underline="always"), + rx.ui.link("Crimson", href="#underline-and-color", color_scheme="crimson"), + gap="4", +) +``` diff --git a/docs/library/typography/text-ui.md b/docs/library/typography/text-ui.md new file mode 100644 index 00000000000..df789de0eb4 --- /dev/null +++ b/docs/library/typography/text-ui.md @@ -0,0 +1,71 @@ +--- +components: + - rx.ui.text + - rx.ui.text.em + - rx.ui.text.kbd + - rx.ui.text.quote + - rx.ui.text.span + - rx.ui.text.strong +--- +```python exec +import reflex as rx +``` + +# Text + +`rx.ui.text` takes the props of `rx.text` and renders a `span`, or the element `as_` names, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.text("The quick brown fox jumps over the lazy dog.") +``` + +## As Another Element + +```python demo +rx.ui.flex( + rx.ui.text("A paragraph.", as_="p"), + rx.ui.text("A div.", as_="div"), + rx.ui.text("A label.", as_="label"), + direction="column", + gap="2", +) +``` + +`rx.ui.text(as_="label", html_for=...)` renders `for` on the label, so +clicking the label focuses its control; `rx.text` passes `html_for` on as a +CSS key, which the browser ignores. + +## Size, Weight and Color + +```python demo +rx.ui.flex( + rx.ui.text("Size 1", size="1"), + rx.ui.text("Size 3", size="3"), + rx.ui.text("Size 6", size="6"), + rx.ui.text("Bold", weight="bold"), + rx.ui.text("Crimson", color_scheme="crimson"), + rx.ui.text("Gray, high contrast", color_scheme="gray", high_contrast=True), + direction="column", + gap="1", +) +``` + +## Inline Elements + +```python demo +rx.ui.text( + "Press ", + rx.ui.text.kbd("Ctrl"), + " + ", + rx.ui.text.kbd("K"), + " to ", + rx.ui.text.strong("search"), + ", or read ", + rx.ui.text.em("the docs"), + ": ", + rx.ui.text.quote("Web apps in pure Python"), + ".", +) +``` diff --git a/docs/rx_ui/overview.md b/docs/rx_ui/overview.md new file mode 100644 index 00000000000..dc2dc5f3c93 --- /dev/null +++ b/docs/rx_ui/overview.md @@ -0,0 +1,136 @@ +--- +title: "rx.ui: Compiled Components" +meta_description: "rx.ui components take the props of the Radix-backed rx components and compile to plain HTML elements with static CSS. Install the ui extra and add UIPlugin." +--- + +```python exec +import reflex as rx +from reflex_docs.pages.docs import ui_library_pages +``` + +# rx.ui + +`rx.ui` is a set of components that take the same props as the Radix-backed +`rx` components and render plain HTML elements. Their styles are compiled to +static CSS by [StyleX](https://stylexjs.com) in your app's own build, and their +behaviour comes from the browser and a few small scripts, so no component +library is shipped to the browser. + +Moving a component is an import change: + +```python +# Before +rx.button("Save", variant="soft", size="2") + +# After +rx.ui.button("Save", variant="soft", size="2") +``` + +The look follows Radix Themes, pixel for pixel where the browser allows it. +Where a component differs from its Radix counterpart, its page lists the +difference under "Differences from Radix". Each difference is checked by a +parity test that fails when the difference stops happening, so the lists stay +current. + +```md alert warning +# `rx.ui` is a pre-release. +The package is optional and its API may still change. The `rx` components are +unchanged and remain supported. +``` + +## Installation + +`rx.ui` lives in the `reflex-components-ui` package, which the `ui` extra of +Reflex installs: + +```bash +pip install 'reflex[ui]' +``` + +Then add `UIPlugin` to the plugins in `rxconfig.py`. It adds StyleX to the +build and wraps every page in the element that carries the theme: + +```python +import reflex as rx + +config = rx.Config( + app_name="my_app", + plugins=[rx.plugins.UIPlugin()], +) +``` + +Without the plugin a compile stops with: + +```text +rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins. +``` + +Without the package, `rx.ui` raises: + +```text +ModuleNotFoundError: `rx.ui` requires the reflex-components-ui package, which is not installed. Install it with `pip install 'reflex[ui]'`. +``` + +## What It Costs + +- **An app that does not opt in pays nothing.** `rx.ui` is imported on first + use, so `import reflex` does not load it, and without `UIPlugin` the build + is unchanged. +- **The plugin** adds the theme of the app to every page: about 4.6 kB of + gzipped CSS for the theme's accent and gray, and 0.6 kB of gzipped + JavaScript in the chunk every page already loads. StyleX and its Vite plugin + run only during the build. +- **Each component** adds only its own compiled classes. A component that + needs a script, such as a select or a dialog, adds a small one to the pages + that use it, and a page without it does not load it. + +## Using Both + +`rx` and `rx.ui` components can be mixed on one page, so an app can move one +component at a time. The theme element of `UIPlugin` sits inside the theme of +Radix Themes, and styles compiled by `rx.ui` sit in a cascade layer, so CSS of +your own beats them (see [Cascade Layers](/rx-ui/styling/#cascade-layers-and-tailwind)). +Give `UIPlugin` the same accent and radius as `rx.theme` so the two match: + +```python +config = rx.Config( + app_name="my_app", + plugins=[ + rx.plugins.UIPlugin( + theme=rx.ui.Theme(accent_color="violet", radius="large"), + ), + ], +) +``` + +The [Theming and Tokens](/rx-ui/theming/) page covers the theme options. + +## Components + +Each library page that has an `rx.ui` version has an **rx.ui** tab beside the +`rx` one, with live examples, the props, and the differences from Radix. + +```python eval +rx.el.ul( + *( + rx.el.li( + rx.el.a(title, href=route, class_name="docs-text-link underline underline-offset-4"), + ": ", + ", ".join(name for _, name in components), + class_name="mb-1 text-sm leading-6 text-secondary-11", + ) + for title, (route, components) in sorted( + (title, (route, components)) + for route, title, components in ui_library_pages.values() + ) + ), + class_name="list-disc pl-6 mb-6", +) +``` + +## Learn More + +- [Styling](/rx-ui/styling/): how styles compile, what `style` accepts, and + what each kind of dynamic value costs. +- [Theming and Tokens](/rx-ui/theming/): the theme of the app, nested themes + and the design tokens. diff --git a/docs/rx_ui/styling.md b/docs/rx_ui/styling.md new file mode 100644 index 00000000000..a9b1c074d93 --- /dev/null +++ b/docs/rx_ui/styling.md @@ -0,0 +1,296 @@ +--- +title: "Styling rx.ui Components" +meta_description: "How rx.ui styles compile to static CSS: typed style, hover and condition blocks, responsive values, tokens, state-bound values and their cost, cascade layers and Tailwind." +--- + +```python exec +import reflex as rx +from reflex_docs.docgen_pipeline import render_markdown +from reflex_docs.pages.docs.ui_differences import shared_differences_markdown +``` + +# Styling + +An `rx.ui` component takes styles the way an `rx` component does: keyword +arguments, `style`, and `class_name`. The difference is when they are turned +into CSS. `rx.ui` compiles every style while your app compiles, so the browser +receives static class names and a stylesheet, and no style is computed at +runtime. + +## How Styles Compile + +Each component has a table of styles: a base, then the styles each value of a +prop such as `variant` or `size` selects. Reflex merges them in Python, in this +order, the last one winning a property: + +1. the component's base styles, +2. the styles of its props (`variant`, `size`, `color_scheme`, ...), +3. layout props such as `gap`, `p` and `direction`, where the component takes them, +4. the keyword styles and `style` you pass. + +Your style is always last, so it wins over the component's own. The merged +style is emitted as a StyleX declaration in the module that renders the +element: + +```python +rx.ui.box("hello", style={"top": "4px"}) +``` + +```js +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",{className:sx_3debd41bb2_c},"hello") +``` + +StyleX folds the class name into a string during the build and adds the rules +to the app's stylesheet. No page ships the StyleX runtime. Elements with equal +styles share one declaration and one class string. + +`style` may also be a list of styles, each merged over the ones before it. + +## Typed `style` + +`style` is typed as `StyleProps`: every CSS property under its snake_case name, +with the keywords it takes. A type checker flags a misspelled property or a +keyword a property does not take. At compile time the same mistakes raise a +`StyleError` that names the component: + +```python +rx.ui.card(style={"paddng": "1em"}) +``` + +```text +StyleError: rx.ui.card: unknown CSS property "paddng". Did you mean "padding"? +``` + +A style that holds something a `TypedDict` cannot express, such as a custom +property or a condition like `"@media (pointer: coarse)"`, can be wrapped in +`unchecked` so the type checker lets it pass. It is still checked when it +compiles: + +```python +from reflex_components_ui.style import unchecked + +rx.ui.box(style=unchecked({"--gap": "8px", "gap": "var(--gap)"})) +``` + +## Hover and Other Conditions + +A block under `_hover`, a pseudo-class such as `":focus-visible"`, an attribute +selector such as `"[data-state=open]"` or an `"@media ..."` query applies its +properties under that condition. Each property inside becomes a conditional +value of that property: no nested selector is generated. + +```python demo +rx.ui.box( + "Hover me", + style={ + "padding": "12px 16px", + "border_radius": "8px", + "background_color": rx.ui.tokens.accent[3], + "_hover": {"background_color": rx.ui.tokens.accent[5]}, + "@media (prefers-reduced-motion: no-preference)": { + "transition": "background-color 150ms", + }, + }, +) +``` + +A style that sets a property only under a condition keeps the earlier value +everywhere else. One that sets it outright replaces the earlier conditions too. + +## Responsive Values + +A list or `rx.breakpoints(...)` as the value of a style property compiles to +media queries on the app's breakpoints, as it does for `rx` components: + +```python demo +rx.ui.box( + "Resize the window", + style={ + "padding": "12px", + "color": "white", + "background_color": rx.breakpoints(initial="tomato", sm="teal", lg="indigo"), + }, +) +``` + +A prop given per breakpoint, such as `size=rx.breakpoints(initial="1", md="3")`, +uses the breakpoints of Radix Themes, as `rx` components do: 520, 768, 1024, +1280 and 1640px for `xs` to `xl`. + +```python demo +rx.ui.button("Responsive size", size=rx.breakpoints(initial="1", sm="2", md="3")) +``` + +## Tokens + +`rx.ui.tokens` names every design token of the theme as the `var()` of its +custom property, so a token goes wherever a CSS value does: + +```python demo +rx.ui.box( + "Tokens", + style={ + "padding": f"{rx.ui.tokens.space[2]} {rx.ui.tokens.space[4]}", + "border_radius": rx.ui.tokens.radius[3], + "color": rx.ui.tokens.accent.contrast, + "background_color": rx.ui.tokens.accent[9], + "box_shadow": rx.ui.tokens.shadow[3], + }, +) +``` + +A token follows the theme around the element, so a style written with +`tokens.accent[9]` takes the accent of a nested `rx.ui.theme` or of the +component's `color_scheme`. `rx.color("ruby", 9)` and `tokens.scale("ruby")[9]` +name a fixed scale instead, and import only that scale's CSS. The +[Theming and Tokens](/rx-ui/theming/#tokens) page lists every token. + +## Values Bound to State + +Styles that depend on state stay compiled. What each kind costs: + +```md definition +# A state Var as a style value +`rx.ui.box(width=State.width)` declares `width: var(--v0)` in the compiled +style and sets `--v0` in the element's inline style. The browser recomputes the +style of each element whose custom property changes. A number gets `px` +unless the property takes bare numbers. + +# A prop bound to state +`rx.ui.button(variant=State.kind)` compiles one style for each value the prop +takes and indexes them by the state value. Each value carries the whole value +of the properties it sets, so it replaces the others rather than overriding +them. A value outside the prop's type gets the style of the button without +the prop. + +# `color_scheme` bound to state +Imports all 26 accent scales, about 21 kB of gzipped CSS, and picks one in the +browser. A literal `color_scheme` imports one. + +# A whole style dict from state +`style=State.style_dict` becomes the inline `style` of the element, as on an +`rx` component. Conditions such as `_hover` and responsive values are not +available in it. +``` + +```python demo exec +class UIStyleState(rx.State): + width: int = 120 + variant: str = "soft" + + @rx.event + def grow(self): + self.width = self.width + 40 if self.width < 320 else 120 + + @rx.event + def cycle(self): + order = ["solid", "soft", "surface", "outline"] + self.variant = order[(order.index(self.variant) + 1) % len(order)] + + +def ui_state_styles(): + return rx.ui.flex( + rx.ui.button("Grow", on_click=UIStyleState.grow, style={"width": UIStyleState.width}), + rx.ui.button(f"Variant: {UIStyleState.variant}", variant=UIStyleState.variant, on_click=UIStyleState.cycle), + gap="3", + align="center", + ) +``` + +A thousand rows bound to one value that changes cost a little more than they +do with an `rx` component, which swaps one class: about 14.7 ms against +12.7 ms. Rows bound to values of their own cost less. + +A whole-style `Var` always wins over a keyword style given beside it: it is an +inline style, and the keyword style is a class. + +## What Is Not Supported + +These raise a `StyleError` where the component is created, with the +replacement in the message. + +```md definition +# Nested selectors +`{"& > div": {...}}` and other selectors that reach another element. Style the +child component directly, or keep the `rx` component for that element. A +condition on the element itself, such as `_hover` or `"[data-state=open]"`, is +supported. + +# The `animation` shorthand +Set `animation_name` and the other longhands. The frames are declared with +`keyframes`, in a style table or in the `style` of an element. + +# `background` with more than a color or an image +`background` is split into its longhands at compile time, so a value with +several layers or positions, or one bound to state, must name the longhands: +`background_color`, `background_image`, `background_position`, ... + +# Spacing shorthands of Radix Themes as CSS keys +`m`, `mx`, `my`, `mt`, `mr`, `mb`, `ml`, `p`, `px`, `py`, `pt`, `pr`, `pb` and +`pl` on a component that does not declare them. `rx` passes them on as CSS keys, +which the browser ignores, so `rx.box(pt="2")` has no padding. `rx.ui` refuses +them and names the style that sets the spacing Radix means. `rx.ui.inset` and +the cells of `rx.ui.table` declare them and take them as Radix does. +``` + +```python +from reflex_components_ui.style import keyframes + +rx.ui.box( + style={ + "animation_name": keyframes({"from": {"opacity": 0}, "to": {"opacity": 1}}), + "animation_duration": "800ms", + "animation_iteration_count": "infinite", + }, +) +``` + +```text +rx.ui.box(pt="2") +StyleError: rx.ui.box: "pt" is not a CSS property, and rx.box ignores it too. Use padding_top="var(--space-2)" (or rx.ui.tokens.space[2]) for the spacing Radix's pt="2" means. +``` + +The parity allowlist records the difference every component shares: + +```python eval +rx.box(render_markdown(shared_differences_markdown())) +``` + +## Cascade Layers and Tailwind + +`UIPlugin` declares the order of the cascade layers once: + +1. the resets: Reflex's and Tailwind's `theme` and `base` layers, +2. `reflex-ui`: the styles of the `rx.ui` components, merged with your `style`, +3. Tailwind's `components` and `utilities` layers. + +CSS that is in no layer, such as your own stylesheets, Emotion styles and Radix +Themes, beats all of them. + +With Tailwind v4 (`rx.plugins.TailwindV4Plugin()`), which emits its layers +natively, a utility class in `class_name` beats the component's styles: + +```python demo +rx.ui.button("Tailwind wins", class_name="rounded-none bg-[var(--grass-9)]") +``` + +Tailwind v3 does not use native cascade layers: its CSS is unlayered, so it +wins over every `rx.ui` style, including the component's own base styles. The +element's own `class_name` is joined to its compiled classes either way. + +## Dynamic Components + +`rx.ui` styles are compiled by StyleX in the build, from the modules the +compiler writes. A component created in an event handler and held in state is +serialized to the browser and never reaches StyleX, so: + +- its literal styles fall back to an inline `style`, +- anything conditional or bound to state, which includes the styles of most + buttons and form controls, raises a `StyleError` that says to render the + component in a page. + +Render the component in the page and drive it with state instead: +`rx.cond`, `rx.foreach` and props bound to state are compiled as usual. diff --git a/docs/rx_ui/theming.md b/docs/rx_ui/theming.md new file mode 100644 index 00000000000..291ee4e8f79 --- /dev/null +++ b/docs/rx_ui/theming.md @@ -0,0 +1,204 @@ +--- +title: "rx.ui Theming and Tokens" +meta_description: "Set the theme of rx.ui components with UIPlugin and rx.ui.Theme, theme part of a page with rx.ui.theme, and use the design tokens of rx.ui.tokens in styles." +--- + +```python exec +import reflex as rx +``` + +# Theming and Tokens + +The theme of `rx.ui` components is the theme of Radix Themes: the same options, +the same values, and the same custom properties, generated from the installed +`@radix-ui/themes`. It is compiled into CSS classes ahead of time. + +## The Theme of the App + +`UIPlugin` takes the theme of the app as an `rx.ui.Theme`: + +```python +# rxconfig.py +import reflex as rx + +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` | + +The options are typed as `Literal`s, so a type checker catches a value an +option does not take. At runtime the app stops where `rxconfig.py` is loaded: + +```text +ThemeError: rx.ui.Theme: unknown accent_color "indgo". Did you mean "indigo"? The values are "tomato", "red", ... +``` + +The theme of the app is compiled ahead of time, so its options take literals +only. An `appearance` other than `"inherit"` pins every page to that appearance, +and is the color mode the app starts in, over `default_color_mode`, unless the +theme of Radix Themes names an appearance of its own. + +`UIPlugin(theme=...)` takes an `rx.ui.Theme`. The theme of Radix Themes, +`rx.theme(...)`, goes to `App(theme=...)` or `rx.plugins.RadixThemesPlugin`, and +themes the `rx` components only. + +## Theming Part of a Page + +`rx.ui.theme` applies a theme to what it wraps. It takes the same options, each +one optional: what it leaves out is inherited from the theme around it. + +```python demo +rx.ui.flex( + rx.ui.theme( + rx.ui.button("Ruby, full radius"), + accent_color="ruby", + radius="full", + ), + rx.ui.theme( + rx.ui.card(rx.ui.text("A dark card"), style={"padding": "12px"}), + appearance="dark", + ), + gap="3", + align="center", +) +``` + +- An accent keeps the gray around it, and `gray_color="auto"` with an accent + is the gray that matches it. +- A nested theme takes the theme of the app to be what is around it: inside + another nested theme, give both `accent_color` and `gray_color`. +- A theme with an `appearance` paints its own background, unless + `has_background=False`. Tailwind and Radix Themes components inside it + follow the appearance too. Beside Radix Themes, give such a theme its + `gray_color` as well. +- An option bound to state imports every theme it could name and picks one in + the browser. For `accent_color` that is all 26 scales: about 21 kB of gzipped + CSS, where the theme of the app is 4.6 kB. +- A theme held in state is a compile error: its code never reaches StyleX. + +```python demo exec +class UIThemeState(rx.State): + accent: str = "violet" + + @rx.event + def set_accent(self, accent: str): + self.accent = accent + + +def ui_theme_switcher(): + return rx.ui.theme( + rx.ui.flex( + *[ + rx.ui.button(color, variant="soft", on_click=UIThemeState.set_accent(color)) + for color in ["violet", "jade", "amber", "crimson"] + ], + rx.ui.badge(UIThemeState.accent, variant="solid"), + gap="2", + align="center", + wrap="wrap", + ), + accent_color=UIThemeState.accent, + ) +``` + +### `color_scheme` + +A component with a `color_scheme` prop applies that accent to itself, as in +`rx`. A literal color imports one accent; one bound to state imports all 26. + +```python demo +rx.ui.flex( + rx.ui.badge("Indigo", color_scheme="indigo"), + rx.ui.badge("Cyan", color_scheme="cyan"), + rx.ui.badge("Orange", color_scheme="orange"), + rx.ui.badge("Gray", color_scheme="gray"), + gap="2", +) +``` + +## Color Mode + +The color mode is the app's own, as for `rx` components. `rx.ui.color_mode` +has the controls of `rx.color_mode`: `rx.ui.color_mode.icon`, +`rx.ui.color_mode.button` and `rx.ui.color_mode.switch`. They are documented on +the [Theme](/library/other/theme/ui/) page with `rx.ui.theme_panel`, a panel +that edits the theme of the page while you design it. + +## Tokens + +`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, in a keyword style, or in an f-string. + +```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 lists what exists: + +```text +TokenError: rx.ui.tokens.space has no step 10. Its steps are 1 to 9. +``` + +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 with +`UIPlugin` is everywhere. A cursor, a white, and a scale named with +`tokens.scale` or `rx.color` are defined by a module that the page imports only +when a style uses them. + +```python demo +rx.ui.grid( + *[ + rx.ui.box( + f"accent {step}", + style={ + "padding": rx.ui.tokens.space[2], + "font_size": rx.ui.tokens.font_size[1], + "border_radius": rx.ui.tokens.radius[2], + "background_color": rx.ui.tokens.accent[step], + "color": rx.ui.tokens.gray[12] if step < 9 else rx.ui.tokens.accent.contrast, + }, + ) + for step in range(1, 13) + ], + columns="6", + gap="2", +) +``` + +A color token is one `light-dark()` value, so it follows the appearance without +a second rule. In the browser, `getPropertyValue("--accent-9")` returns the +pair, and the computed `color` of an element the one in use. diff --git a/packages/reflex-site-shared/news/+rx-ui-copy-markdown.docs.md b/packages/reflex-site-shared/news/+rx-ui-copy-markdown.docs.md new file mode 100644 index 00000000000..75daa828f46 --- /dev/null +++ b/packages/reflex-site-shared/news/+rx-ui-copy-markdown.docs.md @@ -0,0 +1 @@ +The copy-as-Markdown action of a docs page also copies an `rx.ui` component page (a route ending in `/ui`), from its `-ui.md` source. diff --git a/packages/reflex-site-shared/src/reflex_site_shared/components/docs_page_actions.py b/packages/reflex-site-shared/src/reflex_site_shared/components/docs_page_actions.py index 075a130304e..a941852f636 100644 --- a/packages/reflex-site-shared/src/reflex_site_shared/components/docs_page_actions.py +++ b/packages/reflex-site-shared/src/reflex_site_shared/components/docs_page_actions.py @@ -118,7 +118,8 @@ def _copy_action(copy_url: str | None): Args: copy_url: Explicit local Markdown URL, or ``None`` to derive it from - the browser path using the official docs' ``/low`` convention. + the browser path using the official docs' ``/low`` and ``/ui`` + conventions. Returns: Reflex client-side script event. @@ -128,6 +129,8 @@ def _copy_action(copy_url: str | None): if copy_url is not None else """cleanPath.endsWith('/low') ? cleanPath.replace(/\\/low$/, '-ll.md') + : cleanPath.endsWith('/ui') + ? cleanPath.replace(/\\/ui$/, '-ui.md') : cleanPath + '.md'""" ) return rx.run_script( diff --git a/uv.lock b/uv.lock index c42ffc10950..c9f4cc74a76 100644 --- a/uv.lock +++ b/uv.lock @@ -4559,7 +4559,7 @@ dependencies = [ { name = "plotly-express" }, { name = "psycopg", extra = ["binary"] }, { name = "python-frontmatter" }, - { name = "reflex", extra = ["db"] }, + { name = "reflex", extra = ["db", "ui"] }, { name = "reflex-components-internal" }, { name = "reflex-docgen" }, { name = "reflex-enterprise" }, @@ -4597,7 +4597,7 @@ requires-dist = [ { name = "plotly-express" }, { name = "psycopg", extras = ["binary"] }, { name = "python-frontmatter" }, - { name = "reflex", extras = ["db"], editable = "." }, + { name = "reflex", extras = ["db", "ui"], editable = "." }, { name = "reflex-components-internal", editable = "packages/reflex-components-internal" }, { name = "reflex-docgen", editable = "packages/reflex-docgen" }, { name = "reflex-enterprise", specifier = ">=0.9.9" }, From efaf06e3a55a02b9b1ad0f1be176a35a93a40712 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:37:45 +0000 Subject: [PATCH 166/204] Document the rx.ui data display and disclosure components Claude-Session: https://claude.ai/code/session_014AwvTMRUYrq8BR7cV1SsTn --- docs/library/data-display/avatar-ui.md | 39 +++++++++ docs/library/data-display/badge-ui.md | 35 ++++++++ docs/library/data-display/callout-ui.md | 46 ++++++++++ docs/library/data-display/data_list-ui.md | 51 +++++++++++ docs/library/data-display/list-ui.md | 37 ++++++++ docs/library/data-display/progress-ui.md | 41 +++++++++ docs/library/data-display/scroll_area-ui.md | 42 +++++++++ docs/library/data-display/spinner-ui.md | 37 ++++++++ docs/library/disclosure/accordion-ui.md | 80 +++++++++++++++++ .../disclosure/segmented_control-ui.md | 72 ++++++++++++++++ docs/library/disclosure/tabs-ui.md | 86 +++++++++++++++++++ 11 files changed, 566 insertions(+) create mode 100644 docs/library/data-display/avatar-ui.md create mode 100644 docs/library/data-display/badge-ui.md create mode 100644 docs/library/data-display/callout-ui.md create mode 100644 docs/library/data-display/data_list-ui.md create mode 100644 docs/library/data-display/list-ui.md create mode 100644 docs/library/data-display/progress-ui.md create mode 100644 docs/library/data-display/scroll_area-ui.md create mode 100644 docs/library/data-display/spinner-ui.md create mode 100644 docs/library/disclosure/accordion-ui.md create mode 100644 docs/library/disclosure/segmented_control-ui.md create mode 100644 docs/library/disclosure/tabs-ui.md diff --git a/docs/library/data-display/avatar-ui.md b/docs/library/data-display/avatar-ui.md new file mode 100644 index 00000000000..1d01b4b75b7 --- /dev/null +++ b/docs/library/data-display/avatar-ui.md @@ -0,0 +1,39 @@ +--- +components: + - rx.ui.avatar + +Avatar: | + lambda **props: rx.ui.avatar(fallback="RX", **props) +--- +```python exec +import reflex as rx +``` + +# Avatar + +`rx.ui.avatar` takes the props of `rx.avatar` and renders an image with a fallback whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.avatar(src="https://web.reflex-assets.dev/other/logo.jpg", alt="Reflex logo", fallback="RX"), + rx.ui.avatar(fallback="RX"), + rx.ui.avatar(fallback="RX", variant="solid", radius="full"), + gap="3", +) +``` + +The fallback is in the page the server sends and shows until the image has +loaded, with or without JavaScript. `rx.avatar` renders both once JavaScript +has run. + +## Sizes + +```python demo +rx.ui.flex( + *[rx.ui.avatar(fallback="RX", size=str(size)) for size in range(1, 7)], + gap="3", + align="center", +) +``` diff --git a/docs/library/data-display/badge-ui.md b/docs/library/data-display/badge-ui.md new file mode 100644 index 00000000000..30f31dcdc69 --- /dev/null +++ b/docs/library/data-display/badge-ui.md @@ -0,0 +1,35 @@ +--- +components: + - rx.ui.badge + +Badge: | + lambda **props: rx.ui.badge("Basic Badge", **props) +--- +```python exec +import reflex as rx +``` + +# Badge + +`rx.ui.badge` takes the props of `rx.badge` and renders a `span` that labels a status whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.badge("New") +``` + +## Variants and Colors + +```python demo +rx.ui.flex( + rx.ui.badge("Solid", variant="solid"), + rx.ui.badge("Soft", variant="soft"), + rx.ui.badge("Surface", variant="surface"), + rx.ui.badge("Outline", variant="outline"), + rx.ui.badge("Crimson", color_scheme="crimson"), + rx.ui.badge("Cyan", color_scheme="cyan", high_contrast=True), + gap="2", + wrap="wrap", +) +``` diff --git a/docs/library/data-display/callout-ui.md b/docs/library/data-display/callout-ui.md new file mode 100644 index 00000000000..95aed8c1dc9 --- /dev/null +++ b/docs/library/data-display/callout-ui.md @@ -0,0 +1,46 @@ +--- +components: + - rx.ui.callout + - rx.ui.callout.root + - rx.ui.callout.icon + - rx.ui.callout.text + +Callout: | + lambda **props: rx.ui.callout("Basic Callout", icon="info", **props) +--- +```python exec +import reflex as rx +``` + +# Callout + +`rx.ui.callout` takes the props of `rx.callout` and renders a `div` with an icon and a message whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.callout("You will need admin privileges to install and access this application.", icon="info") +``` + +## Variants and Colors + +```python demo +rx.ui.flex( + rx.ui.callout("Soft", icon="info", variant="soft"), + rx.ui.callout("Surface", icon="info", variant="surface"), + rx.ui.callout("Outline", icon="info", variant="outline"), + rx.ui.callout("Access denied.", icon="triangle-alert", color_scheme="red"), + direction="column", + gap="3", +) +``` + +## Composing the Parts + +```python demo +rx.ui.callout.root( + rx.ui.callout.icon(rx.icon("info")), + rx.ui.callout.text("Composed from root, icon and text."), + color_scheme="grass", +) +``` diff --git a/docs/library/data-display/data_list-ui.md b/docs/library/data-display/data_list-ui.md new file mode 100644 index 00000000000..8c1da042f96 --- /dev/null +++ b/docs/library/data-display/data_list-ui.md @@ -0,0 +1,51 @@ +--- +components: + - rx.ui.data_list.root + - rx.ui.data_list.item + - rx.ui.data_list.label + - rx.ui.data_list.value +--- +```python exec +import reflex as rx +``` + +# Data List + +`rx.ui.data_list` takes the props of `rx.data_list` and renders a description list of labels and values whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.data_list.root( + rx.ui.data_list.item( + rx.ui.data_list.label("Status"), + rx.ui.data_list.value(rx.ui.badge("Authorized", variant="soft", color_scheme="jade")), + align="center", + ), + rx.ui.data_list.item( + rx.ui.data_list.label("ID"), + rx.ui.data_list.value(rx.ui.code("U-474747")), + ), + rx.ui.data_list.item( + rx.ui.data_list.label("Name"), + rx.ui.data_list.value("Vlad Moroz"), + align="center", + ), +) +``` + +## Orientation + +```python demo +rx.ui.data_list.root( + rx.ui.data_list.item( + rx.ui.data_list.label("Name"), + rx.ui.data_list.value("Vlad Moroz"), + ), + rx.ui.data_list.item( + rx.ui.data_list.label("Email"), + rx.ui.data_list.value("vlad@example.com"), + ), + orientation=rx.breakpoints(initial="vertical", sm="horizontal"), +) +``` diff --git a/docs/library/data-display/list-ui.md b/docs/library/data-display/list-ui.md new file mode 100644 index 00000000000..580e21baeec --- /dev/null +++ b/docs/library/data-display/list-ui.md @@ -0,0 +1,37 @@ +--- +components: + - rx.ui.list.item + - rx.ui.list.ordered + - rx.ui.list.unordered +--- +```python exec +import reflex as rx +``` + +# List + +`rx.ui.list` takes the props of `rx.list` and renders a `ul` or `ol` with its items whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. `rx.ui.ordered_list`, `rx.ui.unordered_list` and `rx.ui.list_item` are the same components. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.list.unordered( + rx.ui.list.item("Example 1"), + rx.ui.list.item("Example 2"), + rx.ui.list.item("Example 3"), + ), + rx.ui.list.ordered( + rx.ui.list.item("First"), + rx.ui.list.item("Second"), + rx.ui.list.item("Third"), + ), + gap="6", +) +``` + +## From a List of Items + +```python demo +rx.ui.list.unordered(items=["Python", "Reflex", "StyleX"], list_style_type="square") +``` diff --git a/docs/library/data-display/progress-ui.md b/docs/library/data-display/progress-ui.md new file mode 100644 index 00000000000..433ffb122f4 --- /dev/null +++ b/docs/library/data-display/progress-ui.md @@ -0,0 +1,41 @@ +--- +components: + - rx.ui.progress + +Progress: | + lambda **props: rx.ui.progress(value=50, **props) +--- +```python exec +import reflex as rx +``` + +# Progress + +`rx.ui.progress` takes the props of `rx.progress` and renders a `div` with the progressbar role whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.progress(value=50) +``` + +## Size, Variant and Color + +```python demo +rx.ui.flex( + rx.ui.progress(value=25, size="1"), + rx.ui.progress(value=50, size="2", variant="soft"), + rx.ui.progress(value=75, size="3", color_scheme="orange"), + direction="column", + gap="4", + style={"width": "100%"}, +) +``` + +## Indeterminate + +Without a `value` the bar shows indeterminate progress. + +```python demo +rx.ui.progress() +``` diff --git a/docs/library/data-display/scroll_area-ui.md b/docs/library/data-display/scroll_area-ui.md new file mode 100644 index 00000000000..e82fccb920b --- /dev/null +++ b/docs/library/data-display/scroll_area-ui.md @@ -0,0 +1,42 @@ +--- +components: + - rx.ui.scroll_area + +ScrollArea: | + lambda **props: rx.ui.scroll_area( + rx.ui.text("Three fundamental aspects of typography are legibility, readability, and aesthetics. " * 8), + style={"height": "120px", "width": "300px"}, + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Scroll Area + +`rx.ui.scroll_area` takes the props of `rx.scroll_area` and renders a `div` that scrolls natively whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.scroll_area( + rx.ui.flex( + *[ + rx.ui.text( + "Three fundamental aspects of typography are legibility, readability, and aesthetics. " + "Legibility describes how easily individual characters can be distinguished from one another." + ) + for _ in range(4) + ], + direction="column", + gap="4", + ), + scrollbars="vertical", + style={"height": "180px", "max_width": "420px"}, +) +``` + +The browser draws the scrollbars, so `type` and `scroll_hide_delay` have no +effect, and the area is a stop of the Tab key, from which the arrow keys +scroll it. diff --git a/docs/library/data-display/spinner-ui.md b/docs/library/data-display/spinner-ui.md new file mode 100644 index 00000000000..bbe4614508d --- /dev/null +++ b/docs/library/data-display/spinner-ui.md @@ -0,0 +1,37 @@ +--- +components: + - rx.ui.spinner +--- +```python exec +import reflex as rx +``` + +# Spinner + +`rx.ui.spinner` takes the props of `rx.spinner` and renders an animated `span` whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.spinner(size="1"), + rx.ui.spinner(size="2"), + rx.ui.spinner(size="3"), + gap="4", + align="center", +) +``` + +## Around Content + +With children, `loading` chooses between them and the spinner: the spinner +shows while `loading=True`, and the children otherwise. + +```python demo +rx.ui.flex( + rx.ui.spinner(rx.ui.badge("Ready"), loading=False), + rx.ui.spinner(rx.ui.badge("Ready"), loading=True), + gap="4", + align="center", +) +``` diff --git a/docs/library/disclosure/accordion-ui.md b/docs/library/disclosure/accordion-ui.md new file mode 100644 index 00000000000..74b1fbd18d6 --- /dev/null +++ b/docs/library/disclosure/accordion-ui.md @@ -0,0 +1,80 @@ +--- +components: + - rx.ui.accordion.root + - rx.ui.accordion.item + +AccordionRoot: | + lambda **props: rx.ui.accordion.root( + rx.ui.accordion.item(header="First Item", content="The first accordion item's content", value="item_1"), + rx.ui.accordion.item(header="Second Item", content="The second accordion item's content", value="item_2"), + collapsible=True, + style={"width": "300px"}, + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Accordion + +`rx.ui.accordion` takes the props of `rx.accordion` and renders native `details` elements, one per item, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +Each item is a native `details` element, so it opens and closes with or +without JavaScript. + +```python demo +rx.ui.accordion.root( + rx.ui.accordion.item(header="First Item", content="The first accordion item's content", value="item_1"), + rx.ui.accordion.item(header="Second Item", content="The second accordion item's content", value="item_2"), + rx.ui.accordion.item(header="Third Item", content="The third accordion item's content", value="item_3"), + collapsible=True, + style={"width": "300px"}, +) +``` + +## Multiple Open Items + +```python demo +rx.ui.accordion.root( + rx.ui.accordion.item(header="First Item", content="Opens on its own.", value="a"), + rx.ui.accordion.item(header="Second Item", content="So does this one.", value="b"), + type="multiple", + default_value=["a"], + variant="outline", + style={"width": "300px"}, +) +``` + +## Tracking the Open Item + +```python demo exec +class UIAccordionState(rx.State): + value: str = "item_1" + + @rx.event + def set_value(self, value: str | list[str]): + # A single accordion hands over one value, a multiple one a list. + self.value = value if isinstance(value, str) else ", ".join(value) + + +def ui_controlled_accordion(): + return rx.ui.flex( + rx.ui.text("Open: ", rx.ui.code(UIAccordionState.value)), + rx.ui.accordion.root( + rx.ui.accordion.item(header="First Item", content="One", value="item_1"), + rx.ui.accordion.item(header="Second Item", content="Two", value="item_2"), + value=UIAccordionState.value, + on_value_change=UIAccordionState.set_value, + collapsible=True, + style={"width": "300px"}, + ), + direction="column", + gap="3", + ) +``` + +Tab and Shift+Tab move between the headers, as between any `details` +elements; the arrow keys do not. diff --git a/docs/library/disclosure/segmented_control-ui.md b/docs/library/disclosure/segmented_control-ui.md new file mode 100644 index 00000000000..26acdb5e7f6 --- /dev/null +++ b/docs/library/disclosure/segmented_control-ui.md @@ -0,0 +1,72 @@ +--- +components: + - rx.ui.segmented_control.root + - rx.ui.segmented_control.item + +SegmentedControlRoot: | + lambda **props: rx.ui.segmented_control.root( + rx.ui.segmented_control.item("Home", value="home"), + rx.ui.segmented_control.item("About", value="about"), + rx.ui.segmented_control.item("Test", value="test"), + default_value="home", + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Segmented Control + +`rx.ui.segmented_control` takes the props of `rx.segmented_control` and renders a group of radio inputs drawn as one control whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo exec +class UISegmentedState(rx.State): + control: str = "home" + + @rx.event + def set_control(self, value: str): + self.control = value + + +def ui_segmented_control(): + return rx.ui.flex( + rx.ui.segmented_control.root( + rx.ui.segmented_control.item("Home", value="home"), + rx.ui.segmented_control.item("About", value="about"), + rx.ui.segmented_control.item("Test", value="test"), + on_change=UISegmentedState.set_control, + value=UISegmentedState.control, + ), + rx.ui.text("Selected: ", rx.ui.code(UISegmentedState.control)), + direction="column", + gap="3", + align="start", + ) +``` + +## Variants and Sizes + +```python demo +rx.ui.flex( + rx.ui.segmented_control.root( + rx.ui.segmented_control.item("Day", value="day"), + rx.ui.segmented_control.item("Week", value="week"), + default_value="day", + variant="surface", + size="1", + ), + rx.ui.segmented_control.root( + rx.ui.segmented_control.item("Day", value="day"), + rx.ui.segmented_control.item("Week", value="week"), + default_value="week", + variant="classic", + size="3", + ), + direction="column", + gap="3", + align="start", +) +``` diff --git a/docs/library/disclosure/tabs-ui.md b/docs/library/disclosure/tabs-ui.md new file mode 100644 index 00000000000..e23004ac425 --- /dev/null +++ b/docs/library/disclosure/tabs-ui.md @@ -0,0 +1,86 @@ +--- +components: + - rx.ui.tabs.root + - rx.ui.tabs.list + - rx.ui.tabs.trigger + - rx.ui.tabs.content + +TabsRoot: | + lambda **props: rx.ui.tabs.root( + rx.ui.tabs.list( + rx.ui.tabs.trigger("Tab 1", value="tab1"), + rx.ui.tabs.trigger("Tab 2", value="tab2"), + ), + rx.ui.tabs.content(rx.ui.text("item on tab 1"), value="tab1"), + rx.ui.tabs.content(rx.ui.text("item on tab 2"), value="tab2"), + default_value="tab1", + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Tabs + +`rx.ui.tabs` takes the props of `rx.tabs` and renders a tab list and its panels whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.tabs.root( + rx.ui.tabs.list( + rx.ui.tabs.trigger("Account", value="account"), + rx.ui.tabs.trigger("Documents", value="documents"), + rx.ui.tabs.trigger("Settings", value="settings"), + ), + rx.ui.tabs.content(rx.ui.text("Make changes to your account."), value="account", style={"padding_top": "12px"}), + rx.ui.tabs.content(rx.ui.text("Access and update your documents."), value="documents", style={"padding_top": "12px"}), + rx.ui.tabs.content(rx.ui.text("Edit your profile or update contact information."), value="settings", style={"padding_top": "12px"}), + default_value="account", +) +``` + +## Controlled Tabs + +```python demo exec +class UITabsState(rx.State): + value: str = "tab1" + + @rx.event + def set_value(self, value: str): + self.value = value + + +def ui_controlled_tabs(): + return rx.ui.flex( + rx.ui.text("Selected: ", rx.ui.code(UITabsState.value)), + rx.ui.tabs.root( + rx.ui.tabs.list( + rx.ui.tabs.trigger("Tab 1", value="tab1"), + rx.ui.tabs.trigger("Tab 2", value="tab2"), + ), + rx.ui.tabs.content(rx.ui.text("items on tab 1"), value="tab1"), + rx.ui.tabs.content(rx.ui.text("items on tab 2"), value="tab2"), + value=UITabsState.value, + on_change=UITabsState.set_value, + ), + direction="column", + gap="3", + ) +``` + +## Vertical Orientation + +```python demo +rx.ui.tabs.root( + rx.ui.tabs.list( + rx.ui.tabs.trigger("Tab 1", value="tab1"), + rx.ui.tabs.trigger("Tab 2", value="tab2"), + ), + rx.ui.tabs.content(rx.ui.text("items on tab 1"), value="tab1", style={"padding_left": "16px"}), + rx.ui.tabs.content(rx.ui.text("items on tab 2"), value="tab2", style={"padding_left": "16px"}), + default_value="tab1", + orientation="vertical", +) +``` From 84ebc0379a3b244714afe1707727eacce8fa992e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:39:26 +0000 Subject: [PATCH 167/204] Give rx.ui inputs bound to state the props of their debounce wrapper rx.input and rx.text_area pass debounce_timeout, force_notify_by_enter and force_notify_on_blur on to the DebounceInput they wrap a control bound to state in; rx.ui refused them as unknown CSS properties. rx.ui.input, rx.ui.text_field and rx.ui.text_area now hand them to their wrapper, and drop them without one, as rx does. The API test creates every rx component bound to state and, for each it wraps, requires the rx.ui component to render the wrapper's own props: they are no fields, so comparing fields could not see them. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../news/+debounce-props.bugfix.md | 1 + .../components/text_area.py | 3 +- .../components/text_field.py | 28 ++++++- pyi_hashes.json | 2 +- .../components/test_text_field.py | 33 ++++++++ .../reflex_components_ui/test_api_parity.py | 78 +++++++++++++++++++ 6 files changed, 140 insertions(+), 5 deletions(-) create mode 100644 packages/reflex-components-ui/news/+debounce-props.bugfix.md diff --git a/packages/reflex-components-ui/news/+debounce-props.bugfix.md b/packages/reflex-components-ui/news/+debounce-props.bugfix.md new file mode 100644 index 00000000000..d70e1783762 --- /dev/null +++ b/packages/reflex-components-ui/news/+debounce-props.bugfix.md @@ -0,0 +1 @@ +`rx.ui.input`, `rx.ui.text_field` and `rx.ui.text_area` take `debounce_timeout`, `force_notify_by_enter` and `force_notify_on_blur`, as their `rx` counterparts do: bound to state, they configure the wrapper that keeps what is typed. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py b/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py index 689fd063ce7..06b385b994f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py @@ -139,6 +139,7 @@ def create(cls, *children, **props) -> Component: Returns: The component. """ + wrapper = DebouncedControl.take_props(props) own = control_props(props, elements.Textarea) padding = props.pop("padding", None) if padding is not None: @@ -150,7 +151,7 @@ def create(cls, *children, **props) -> Component: ) if own.get("value") is not None and own.get("on_change") is not None: # create a debounced input if the user requests full control to avoid typing jank - control = DebouncedControl.create(control) # pyright: ignore[reportArgumentType] + control = DebouncedControl.create(control, **wrapper) # pyright: ignore[reportArgumentType] return super().create(control, **props) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py index 8d864c3b112..2c70e80972a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py @@ -77,6 +77,11 @@ def control_props(props: dict[str, Any], element: type[Component]) -> dict[str, } +# The props of the wrapper of a control bound to state that are its own, not +# the control's: rx.input and rx.text_area pass them on to it. +WRAPPER_PROPS = ("debounce_timeout", "force_notify_by_enter", "force_notify_on_blur") + + class DebouncedControl(DebounceInput): """An input or a text area that keeps what is typed while state catches up. @@ -87,19 +92,35 @@ class DebouncedControl(DebounceInput): """ @classmethod - def create(cls, control: UIComponent) -> Component: # pyright: ignore[reportIncompatibleMethodOverride] + def create(cls, control: UIComponent, **props: Any) -> Component: # pyright: ignore[reportIncompatibleMethodOverride] """Wrap a control that has a value and an ``on_change``. Args: control: The input or the text area. + **props: The props of the wrapper itself, from ``WRAPPER_PROPS``. Returns: The control inside the wrapper. """ - component = super().create(control) + component = super().create(control, **props) component._control = control # pyright: ignore[reportAttributeAccessIssue] return component + @staticmethod + def take_props(props: dict[str, Any]) -> dict[str, Any]: + """Take the props of the wrapper out of the props of a control. + + As in rx, they reach the wrapper of a control bound to state, and + nothing otherwise. + + Args: + props: The props the control is created with. + + Returns: + The wrapper's props that were among them. + """ + return {prop: props.pop(prop) for prop in WRAPPER_PROPS if prop in props} + def _render(self) -> CommonTag: """Render the wrapper with the class names of the control's styles. @@ -243,6 +264,7 @@ def create(cls, *children, **props) -> Component: Var.create(""), ) + wrapper = DebouncedControl.take_props(props) own = control_props(props, elements.Input) # Marked for the rules of the fields of a date, and without the spell # check of the browser unless it is asked for, as in Radix Themes. @@ -253,7 +275,7 @@ def create(cls, *children, **props) -> Component: ) if own.get("value") is not None and own.get("on_change") is not None: # create a debounced input if the user requests full control to avoid typing jank - control = DebouncedControl.create(control) # pyright: ignore[reportArgumentType] + control = DebouncedControl.create(control, **wrapper) # pyright: ignore[reportArgumentType] if children: _place_slots(children) props.setdefault("custom_attrs", {})["onPointerDown"] = _FOCUS_FIELD diff --git a/pyi_hashes.json b/pyi_hashes.json index c32f555e7c7..7d345fa839a 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -161,7 +161,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/table.pyi": "3d2683d69d98f3cd14da65831e89e5fe", "packages/reflex-components-ui/src/reflex_components_ui/components/tabs.pyi": "37bd6cf7d23252f304647967c44f7693", "packages/reflex-components-ui/src/reflex_components_ui/components/text_area.pyi": "85e3d7d2cf756b3a67683d9724b1a68b", - "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "9fe922c888339fa55560e2cb51697ead", + "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "0493db3f24247140307bd4387444aac4", "packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.pyi": "8415abf97f4c226acc2f721278dca20f", "packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.pyi": "e40ab12c01c4c79dd540aa7872596cd3", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", diff --git a/tests/units/reflex_components_ui/components/test_text_field.py b/tests/units/reflex_components_ui/components/test_text_field.py index dc94a68add1..462ec4bac18 100644 --- a/tests/units/reflex_components_ui/components/test_text_field.py +++ b/tests/units/reflex_components_ui/components/test_text_field.py @@ -633,3 +633,36 @@ def test_text_field_script_is_only_for_slots(ui_plugin: UIPlugin): ImportVar(tag="focusField") ] assert "react-debounce-input@3.3.0" not in rx.ui.input()._get_all_imports() + + +def test_text_field_bound_to_state_takes_the_props_of_its_wrapper( + ui_plugin: UIPlugin, +): + """The debounce props reach the wrapper, as rx.input passes them on.""" + component = rx.ui.input( + value=FieldState.text, + on_change=FieldState.set_text, + debounce_timeout=1000, + force_notify_by_enter=True, + force_notify_on_blur=False, + ) + wrapper = component.render()["children"][0] + assert (wrapper["name"], wrapper["props"]) == ( + "DebounceInput", + [ + "className:sx_345c25de08_c", + '"data-rx-text-field-input":""', + "debounceTimeout:1000", + 'element:"input"', + "forceNotifyByEnter:true", + "forceNotifyOnBlur:false", + 'onChange:((_e) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_text_field____field_state.set_text", ({ ["text"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))', + "spellCheck:false", + 'value:(isNotNullOrUndefined(reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.text_rx_state_) ? reflex___state____state__tests___units___reflex_components_ui___components___test_text_field____field_state.text_rx_state_ : "")', + ], + ) + + +def test_text_field_not_bound_drops_the_props_of_a_wrapper(ui_plugin: UIPlugin): + """Without a wrapper, the debounce props go nowhere, as in rx.""" + assert rx.ui.input(debounce_timeout=1000).render() == rx.ui.input().render() diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index db0e71a79a1..26efeea657e 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -14,6 +14,7 @@ from reflex_base.components.component import Component, ComponentNamespace from reflex_base.event import EventHandler, no_args_event_spec from reflex_base.vars.base import Var +from reflex_components_core.core.debounce import DebounceInput from reflex_components_core.el import elements from reflex_components_core.el.elements.base import BaseHTML from reflex_components_ui.base import UIComponent @@ -467,6 +468,83 @@ def test_every_tag_as_can_select_has_its_attributes(component: str): assert {tag: names for tag, names in missing.items() if names} == {} +class ControlState(rx.State): + """What a control is bound to.""" + + text: str = "" + + @rx.event + def set_text(self, text: str): + """Follow the control. + + Args: + text: Its text. + """ + self.text = text + + +# The props of the wrapper rx puts around a control bound to state that are +# its own, not the control's, and what each renders as. +DEBOUNCE_PROPS = { + "debounce_timeout": (1000, "debounceTimeout:1000"), + "force_notify_by_enter": (True, "forceNotifyByEnter:true"), + "force_notify_on_blur": (True, "forceNotifyOnBlur:true"), +} + + +def _debounce_wrapper(rendered: dict[str, Any]) -> dict[str, Any] | None: + """Find the wrapper of a control in a rendered tree. + + Args: + rendered: The render of a component. + + Returns: + The render of the wrapper, or None. + """ + if rendered.get("name") == "DebounceInput": + return rendered + for child in rendered.get("children", ()): + if (found := _debounce_wrapper(child)) is not None: + return found + return None + + +def test_the_debounce_props_are_the_wrapper_s_own(): + copied = {"value", "element", "input_ref", "min_length", "on_change"} + assert sorted(set(DebounceInput.get_props()) - copied) == sorted(DEBOUNCE_PROPS) + + +def test_controls_take_the_props_of_the_wrapper_rx_puts_them_in(ui_plugin): + """Where rx wraps a control bound to state, rx.ui takes the wrapper's props. + + They are no fields of the rx component: its create passes them on. + + Args: + ui_plugin: The configured plugin. + """ + bound = {"value": ControlState.text, "on_change": ControlState.set_text} + wrapped = [] + for component in COMPONENTS: + try: + reference = resolve(rx, component)(**bound) + except Exception: # A component that needs other arguments. + continue + if not isinstance(reference, DebounceInput): + continue + wrapped.append(component) + candidate = resolve(reflex_components_ui, component)( + **bound, **{prop: value for prop, (value, _) in DEBOUNCE_PROPS.items()} + ) + wrapper = _debounce_wrapper(candidate.render()) + assert wrapper is not None + rendered = {prop.partition(":")[0]: prop for prop in wrapper["props"]} + assert [ + rendered.get(expected.partition(":")[0]) + for _, expected in DEBOUNCE_PROPS.values() + ] == [expected for _, expected in DEBOUNCE_PROPS.values()] + assert wrapped == ["input", "text_area", "text_field"] + + def wrapper(without: str | None = None) -> type[Component]: """Fork the Radix box as a wave does: a wrapper with the same props. From 1c29b54fffa8ab06666d643c8e0f12e5c000c091 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:42:08 +0000 Subject: [PATCH 168/204] Document the rx.ui form controls Claude-Session: https://claude.ai/code/session_014AwvTMRUYrq8BR7cV1SsTn --- docs/app/tests/test_ui_pages.py | 19 +++++- docs/library/forms/checkbox-ui.md | 97 ++++++++++++++++++++++++++++ docs/library/forms/form-ui.md | 76 ++++++++++++++++++++++ docs/library/forms/input-ui.md | 58 +++++++++++++++++ docs/library/forms/radio_group-ui.md | 65 +++++++++++++++++++ docs/library/forms/select-ui.md | 68 +++++++++++++++++++ docs/library/forms/slider-ui.md | 60 +++++++++++++++++ docs/library/forms/switch-ui.md | 49 ++++++++++++++ docs/library/forms/text_area-ui.md | 46 +++++++++++++ 9 files changed, 537 insertions(+), 1 deletion(-) create mode 100644 docs/library/forms/checkbox-ui.md create mode 100644 docs/library/forms/form-ui.md create mode 100644 docs/library/forms/input-ui.md create mode 100644 docs/library/forms/radio_group-ui.md create mode 100644 docs/library/forms/select-ui.md create mode 100644 docs/library/forms/slider-ui.md create mode 100644 docs/library/forms/switch-ui.md create mode 100644 docs/library/forms/text_area-ui.md diff --git a/docs/app/tests/test_ui_pages.py b/docs/app/tests/test_ui_pages.py index 61ddd2b1377..f5821f0bc6f 100644 --- a/docs/app/tests/test_ui_pages.py +++ b/docs/app/tests/test_ui_pages.py @@ -118,6 +118,19 @@ def test_every_allowlisted_component_has_an_rx_ui_page(): } == set() +# Names of rx.ui that are another name of a documented component, and the +# page's name for it, which the page's lead says. +UI_ALIASES = { + "divider": "separator", + "list_item": "list", + "menu": "dropdown_menu", + "ordered_list": "list", + "radio": "radio_group", + "text_field": "input", + "unordered_list": "list", +} + + def test_every_rx_ui_component_has_a_page(): """Each name of the rx.ui namespace is documented on a library page.""" import reflex_components_ui @@ -129,9 +142,13 @@ def test_every_rx_ui_component_has_a_page(): for _, _, components in ui_library_pages.values() for _, name in components } + assert set(UI_ALIASES.values()) <= documented # Not components: the theme of the plugin and the design tokens, which the # theming guide documents. - assert set(reflex_components_ui.__all__) - documented == {"Theme", "tokens"} + assert set(reflex_components_ui.__all__) - documented - set(UI_ALIASES) == { + "Theme", + "tokens", + } def test_rx_ui_pages_resolve_their_components(): diff --git a/docs/library/forms/checkbox-ui.md b/docs/library/forms/checkbox-ui.md new file mode 100644 index 00000000000..a08f988903c --- /dev/null +++ b/docs/library/forms/checkbox-ui.md @@ -0,0 +1,97 @@ +--- +components: + - rx.ui.checkbox + - rx.ui.checkbox_group.root + - rx.ui.checkbox_group.item + - rx.ui.checkbox_cards.root + - rx.ui.checkbox_cards.item + +HighLevelCheckbox: | + lambda **props: rx.ui.checkbox("Basic Checkbox", **props) +--- +```python exec +import reflex as rx +``` + +# Checkbox + +`rx.ui.checkbox` takes the props of `rx.checkbox` and renders a native checkbox `input` with its label whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. The page also documents `rx.ui.checkbox_group` and `rx.ui.checkbox_cards`, which take the props of `rx.checkbox_group` and `rx.checkbox_cards`. + +## Basic Example + +A native checkbox is checked by a click on it or on its label, with or without +JavaScript. + +```python demo exec +class UICheckboxState(rx.State): + checked: bool = False + + @rx.event + def set_checked(self, value: bool): + self.checked = value + + +def ui_checkbox_example(): + return rx.ui.flex( + rx.ui.checkbox("Agree to terms", checked=UICheckboxState.checked, on_change=UICheckboxState.set_checked), + rx.ui.badge(rx.cond(UICheckboxState.checked, "Checked", "Unchecked")), + gap="3", + align="center", + ) +``` + +## Sizes and Variants + +```python demo +rx.ui.flex( + rx.ui.checkbox("Size 1", size="1", default_checked=True), + rx.ui.checkbox("Size 2", size="2", default_checked=True), + rx.ui.checkbox("Size 3", size="3", default_checked=True), + rx.ui.checkbox("Soft", variant="soft", default_checked=True), + rx.ui.checkbox("Surface", variant="surface", default_checked=True), + rx.ui.checkbox("Disabled", disabled=True), + direction="column", + gap="2", +) +``` + +## Checkbox Group + +```python demo exec +class UICheckboxGroupState(rx.State): + selected: list[str] = ["python"] + + @rx.event + def set_selected(self, value: list[str]): + self.selected = value + + +def ui_checkbox_group_example(): + return rx.ui.flex( + rx.ui.checkbox_group.root( + rx.ui.checkbox_group.item("Python", value="python"), + rx.ui.checkbox_group.item("TypeScript", value="typescript"), + rx.ui.checkbox_group.item("Rust", value="rust"), + value=UICheckboxGroupState.selected, + on_value_change=UICheckboxGroupState.set_selected, + ), + rx.ui.text("Selected: ", UICheckboxGroupState.selected.join(", ")), + direction="column", + gap="3", + ) +``` + +Every checkbox of a group is a stop of the Tab key, as native checkboxes are; +the arrow keys do not move between them. + +## Checkbox Cards + +```python demo +rx.ui.checkbox_cards.root( + rx.ui.checkbox_cards.item(rx.ui.text("8-core CPU", weight="bold"), value="cpu"), + rx.ui.checkbox_cards.item(rx.ui.text("32 GB RAM", weight="bold"), value="ram"), + rx.ui.checkbox_cards.item(rx.ui.text("1 TB SSD", weight="bold"), value="ssd"), + default_value=["cpu"], + columns=rx.breakpoints(initial="1", sm="3"), +) +``` diff --git a/docs/library/forms/form-ui.md b/docs/library/forms/form-ui.md new file mode 100644 index 00000000000..7606ff2748c --- /dev/null +++ b/docs/library/forms/form-ui.md @@ -0,0 +1,76 @@ +--- +components: + - rx.ui.form + - rx.ui.form.root + - rx.ui.form.field + - rx.ui.form.control + - rx.ui.form.label + - rx.ui.form.message + - rx.ui.form.submit +--- +```python exec +import reflex as rx +``` + +# Form + +`rx.ui.form` takes the props of `rx.form` and renders a `form` element whose fields validate natively whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +`on_submit` hands the values of the named controls to the event handler as a +dict. + +```python demo exec +class UIFormState(rx.State): + form_data: dict = {} + + @rx.event + def handle_submit(self, form_data: dict): + self.form_data = form_data + + +def ui_form_example(): + return rx.ui.vstack( + rx.ui.form( + rx.ui.vstack( + rx.ui.input(placeholder="First Name", name="first_name"), + rx.ui.input(placeholder="Last Name", name="last_name"), + rx.ui.hstack(rx.ui.checkbox("Checked", name="check"), rx.ui.switch("Switched", name="switch")), + rx.ui.button("Submit", type="submit"), + ), + on_submit=UIFormState.handle_submit, + reset_on_submit=True, + ), + rx.ui.separator(), + rx.ui.heading("Results", as_="h3", size="3"), + rx.ui.text(UIFormState.form_data.to_string()), + ) +``` + +## Fields and Messages + +`rx.ui.form.field` ties a label, a control and its messages together. +`rx.ui.form.message` shows when the control's validity matches `match`. + +```python demo +rx.ui.form.root( + rx.ui.form.field( + rx.ui.flex( + rx.ui.form.label("Email"), + rx.ui.form.control( + rx.ui.input(placeholder="Email Address", type="email", required=True), + as_child=True, + ), + rx.ui.form.message("Please enter a valid email.", match="typeMismatch"), + rx.ui.form.submit(rx.ui.button("Submit"), as_child=True), + direction="column", + gap="2", + align="stretch", + ), + name="email", + ), + on_submit=lambda form_data: rx.window_alert(form_data.to_string()), + reset_on_submit=True, +) +``` diff --git a/docs/library/forms/input-ui.md b/docs/library/forms/input-ui.md new file mode 100644 index 00000000000..e993825fddb --- /dev/null +++ b/docs/library/forms/input-ui.md @@ -0,0 +1,58 @@ +--- +components: + - rx.ui.input + - rx.ui.input.slot + +TextFieldRoot: | + lambda **props: rx.ui.input(placeholder="Search the docs", **props) +--- +```python exec +import reflex as rx +``` + +# Input + +`rx.ui.input` takes the props of `rx.input` and renders an `input` element in a styled field whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. `rx.ui.text_field` is the same component. + +## Basic Example + +```python demo exec +class UIInputState(rx.State): + text: str = "Hello World!" + + @rx.event + def set_text(self, value: str): + self.text = value + + +def ui_input_example(): + return rx.ui.flex( + rx.ui.heading(UIInputState.text, as_="h3", size="4"), + rx.ui.input(value=UIInputState.text, on_change=UIInputState.set_text), + direction="column", + gap="3", + ) +``` + +## Slots + +`rx.ui.input.slot` places an icon or a button at either end of the field. + +```python demo +rx.ui.input( + rx.ui.input.slot(rx.icon("search")), + placeholder="Search the docs", +) +``` + +## Variants and Sizes + +```python demo +rx.ui.flex( + rx.ui.input(placeholder="Surface", variant="surface", size="1"), + rx.ui.input(placeholder="Classic", variant="classic", size="2"), + rx.ui.input(placeholder="Soft", variant="soft", size="3"), + direction="column", + gap="3", +) +``` diff --git a/docs/library/forms/radio_group-ui.md b/docs/library/forms/radio_group-ui.md new file mode 100644 index 00000000000..44669710d99 --- /dev/null +++ b/docs/library/forms/radio_group-ui.md @@ -0,0 +1,65 @@ +--- +components: + - rx.ui.radio_group + - rx.ui.radio_group.root + - rx.ui.radio_group.item + - rx.ui.radio_cards.root + - rx.ui.radio_cards.item + +HighLevelRadioGroup: | + lambda **props: rx.ui.radio_group(["1", "2", "3", "4", "5"], **props) +--- +```python exec +import reflex as rx +``` + +# Radio Group + +`rx.ui.radio_group` takes the props of `rx.radio_group` and renders native radio `input`s whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. `rx.ui.radio` is the same component. The page also documents `rx.ui.radio_cards`. + +## Basic Example + +```python demo exec +class UIRadioState(rx.State): + choice: str = "1" + + @rx.event + def set_choice(self, value: str): + self.choice = value + + +def ui_radio_example(): + return rx.ui.flex( + rx.ui.radio_group(["1", "2", "3"], value=UIRadioState.choice, on_change=UIRadioState.set_choice, direction="row"), + rx.ui.badge(UIRadioState.choice), + gap="3", + align="center", + ) +``` + +## Composing the Parts + +```python demo +rx.ui.radio_group.root( + rx.ui.flex( + rx.ui.text(rx.ui.flex(rx.ui.radio_group.item(value="default"), "Default", gap="2"), as_="label", size="2"), + rx.ui.text(rx.ui.flex(rx.ui.radio_group.item(value="comfortable"), "Comfortable", gap="2"), as_="label", size="2"), + rx.ui.text(rx.ui.flex(rx.ui.radio_group.item(value="compact"), "Compact", gap="2"), as_="label", size="2"), + direction="column", + gap="2", + ), + default_value="comfortable", +) +``` + +## Radio Cards + +```python demo +rx.ui.radio_cards.root( + rx.ui.radio_cards.item(rx.ui.text("8-core CPU", weight="bold"), value="1"), + rx.ui.radio_cards.item(rx.ui.text("6-core CPU", weight="bold"), value="2"), + rx.ui.radio_cards.item(rx.ui.text("4-core CPU", weight="bold"), value="3"), + default_value="1", + columns=rx.breakpoints(initial="1", sm="3"), +) +``` diff --git a/docs/library/forms/select-ui.md b/docs/library/forms/select-ui.md new file mode 100644 index 00000000000..e52ad19d0e9 --- /dev/null +++ b/docs/library/forms/select-ui.md @@ -0,0 +1,68 @@ +--- +components: + - rx.ui.select + - rx.ui.select.root + - rx.ui.select.trigger + - rx.ui.select.content + - rx.ui.select.group + - rx.ui.select.item + - rx.ui.select.label + - rx.ui.select.separator + +HighLevelSelect: | + lambda **props: rx.ui.select(["apple", "grape", "pear"], default_value="pear", **props) +--- +```python exec +import reflex as rx +``` + +# Select + +`rx.ui.select` takes the props of `rx.select` and renders a button and a list of options in a native popover whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo exec +class UISelectState(rx.State): + value: str = "apple" + + @rx.event + def set_value(self, value: str): + self.value = value + + +def ui_select_example(): + return rx.ui.flex( + rx.ui.select(["apple", "grape", "pear"], value=UISelectState.value, on_change=UISelectState.set_value), + rx.ui.badge(UISelectState.value), + gap="3", + align="center", + ) +``` + +## Composing the Parts + +```python demo +rx.ui.select.root( + rx.ui.select.trigger(placeholder="Pick a food"), + rx.ui.select.content( + rx.ui.select.group( + rx.ui.select.label("Fruits"), + rx.ui.select.item("Orange", value="orange"), + rx.ui.select.item("Apple", value="apple"), + rx.ui.select.item("Grape", value="grape", disabled=True), + ), + rx.ui.select.separator(), + rx.ui.select.group( + rx.ui.select.label("Vegetables"), + rx.ui.select.item("Carrot", value="carrot"), + rx.ui.select.item("Potato", value="potato"), + ), + ), + default_value="apple", +) +``` + +The list is a native popover, so the page behind it stays interactive, and a +long list scrolls natively. `position="item-aligned"` places it as +`"popper"` does, and the trigger shows the chosen option's text. diff --git a/docs/library/forms/slider-ui.md b/docs/library/forms/slider-ui.md new file mode 100644 index 00000000000..827f058a3d5 --- /dev/null +++ b/docs/library/forms/slider-ui.md @@ -0,0 +1,60 @@ +--- +components: + - rx.ui.slider + +Slider: | + lambda **props: rx.ui.slider(default_value=40, style={"width": "300px"}, **props) +--- +```python exec +import reflex as rx +``` + +# Slider + +`rx.ui.slider` takes the props of `rx.slider` and renders native range `input`s, one per thumb whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +`on_value_commit` fires when a thumb is released; `on_change` fires as it +moves. + +```python demo exec +class UISliderState(rx.State): + value: int = 50 + + @rx.event + def set_end(self, value: list[int | float]): + self.value = value[0] + + +def ui_slider_example(): + return rx.ui.flex( + rx.ui.heading(UISliderState.value, as_="h3", size="4"), + rx.ui.slider(default_value=50, on_change=UISliderState.set_end.throttle(100)), + direction="column", + gap="3", + style={"width": "100%"}, + ) +``` + +## Range + +```python demo +rx.ui.slider(default_value=[25, 75], style={"width": "100%"}) +``` + +The thumbs of a range stop at their neighbours, and Shift with an arrow key +moves a thumb by one step. + +## Sizes and Variants + +```python demo +rx.ui.flex( + rx.ui.slider(default_value=25, size="1"), + rx.ui.slider(default_value=50, size="2", variant="soft"), + rx.ui.slider(default_value=75, size="3", color_scheme="orange"), + direction="column", + gap="4", + style={"width": "100%"}, +) +``` diff --git a/docs/library/forms/switch-ui.md b/docs/library/forms/switch-ui.md new file mode 100644 index 00000000000..00efd0ff8bc --- /dev/null +++ b/docs/library/forms/switch-ui.md @@ -0,0 +1,49 @@ +--- +components: + - rx.ui.switch + +Switch: | + lambda **props: rx.ui.switch(**props) +--- +```python exec +import reflex as rx +``` + +# Switch + +`rx.ui.switch` takes the props of `rx.switch` and renders a native checkbox `input` with the switch role whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo exec +class UISwitchState(rx.State): + on: bool = True + + @rx.event + def set_on(self, value: bool): + self.on = value + + +def ui_switch_example(): + return rx.ui.flex( + rx.ui.switch(checked=UISwitchState.on, on_change=UISwitchState.set_on), + rx.ui.badge(rx.cond(UISwitchState.on, "On", "Off")), + gap="3", + align="center", + ) +``` + +## Sizes and Variants + +```python demo +rx.ui.flex( + rx.ui.switch(size="1", default_checked=True), + rx.ui.switch(size="2", default_checked=True), + rx.ui.switch(size="3", default_checked=True), + rx.ui.switch(variant="soft", default_checked=True), + rx.ui.switch(variant="surface", default_checked=True), + rx.ui.switch(disabled=True), + gap="3", + align="center", +) +``` diff --git a/docs/library/forms/text_area-ui.md b/docs/library/forms/text_area-ui.md new file mode 100644 index 00000000000..c2d2b215af4 --- /dev/null +++ b/docs/library/forms/text_area-ui.md @@ -0,0 +1,46 @@ +--- +components: + - rx.ui.text_area + +TextArea: | + lambda **props: rx.ui.text_area(placeholder="Type here...", **props) +--- +```python exec +import reflex as rx +``` + +# Text Area + +`rx.ui.text_area` takes the props of `rx.text_area` and renders a `textarea` element whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo exec +class UITextAreaState(rx.State): + text: str = "Hello World!" + + @rx.event + def set_text(self, value: str): + self.text = value + + +def ui_text_area_example(): + return rx.ui.flex( + rx.ui.heading(UITextAreaState.text, as_="h3", size="4"), + rx.ui.text_area(value=UITextAreaState.text, on_change=UITextAreaState.set_text), + direction="column", + gap="3", + ) +``` + +## Variants and Sizes + +```python demo +rx.ui.flex( + rx.ui.text_area(placeholder="Surface", variant="surface"), + rx.ui.text_area(placeholder="Classic", variant="classic"), + rx.ui.text_area(placeholder="Soft", variant="soft", size="3"), + direction="column", + gap="3", +) +``` From c40c8b5c000a55e58330123b272df4f204adef6c Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:54:36 +0000 Subject: [PATCH 169/204] Refuse a length without a unit, as the browser drops it from rx rx passes rx.flex(gap="3"), rx.grid(gap="6") and rx.center(padding="4") on to CSS as written, where the browser drops a number without a unit; StyleX gives it px, so a migrated page gained spacing it never had. rx.ui now refuses a number written as a string for a length property, with the component, the word that rx ignores it too, and the spellings that work: the value in pixels and, for a single digit, the step of the spacing scale. Zero, the properties StyleX lists as unitless, the properties that take no number, and the props Radix declares (spacing, the gap of the card groups) are unchanged. Which properties take a length comes from the generated CSS properties, which now list the ones StyleX types as taking a number; UNITLESS moves next to them, and the codemod shares the pattern of a bare number. The API test holds every component to it for gap, padding, margin and width, through one helper with the spacing shorthands; one [[api]] style entry records it. The flex, grid and center matrices had no cell that passes a length on to CSS at all, only the spacing prop and a padding with a unit in a style: they gain gap and padding cells with units, which match in Chromium. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- docs/styling/rx-ui-migration.md | 1 + .../js/scripts/css-props.js | 7 + .../js/tests/css-props.test.js | 9 + .../news/+unitless-lengths.bugfix.md | 1 + .../parity/allowlist.toml | 6 + .../parity/ui_parity/components/center.py | 3 + .../parity/ui_parity/components/flex.py | 3 + .../parity/ui_parity/components/grid.py | 3 + .../src/reflex_components_ui/migrate.py | 6 +- .../reflex_components_ui/style/_css_props.py | 187 ++++++++++++++++++ .../src/reflex_components_ui/style/emit.py | 54 +---- .../src/reflex_components_ui/style/lower.py | 135 +++++++++++++ .../migrate_fixtures/styles/report.txt | 6 +- .../reflex_components_ui/style/test_lower.py | 94 +++++++++ .../reflex_components_ui/test_api_parity.py | 99 ++++++++-- .../reflex_components_ui/test_migrate.py | 4 +- 16 files changed, 539 insertions(+), 79 deletions(-) create mode 100644 packages/reflex-components-ui/news/+unitless-lengths.bugfix.md diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index 1493f9831ec..3f3d9727768 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -136,6 +136,7 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### every component - style `m`, `mx`, `my`, `mt`, `mr`, `mb`, `ml`, `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl`: Where Radix does not declare them, the rx components pass the margin and padding props of Radix Themes on as CSS keys, which the browser ignores: rx.box(pt="2") has no padding. rx.ui refuses them and names the style that sets the spacing Radix means, such as padding_top="var(--space-2)". The components that declare them, rx.ui.inset and the cells of rx.ui.table, take them as Radix does. +- style `length without a unit`: rx passes a length written as a number without a unit, such as gap="3", on to CSS, where the browser drops it: rx.flex(gap="3") has no gap. rx.ui refuses it and names the spellings that work, gap="3px" or the step of the spacing scale gap="var(--space-3)". Zero, the properties that take a plain number (line_height, opacity, z_index, flex) and the props Radix declares, such as spacing, take one as before. ### accordion diff --git a/packages/reflex-components-ui/js/scripts/css-props.js b/packages/reflex-components-ui/js/scripts/css-props.js index 2f81a3926a5..406b5271a99 100644 --- a/packages/reflex-components-ui/js/scripts/css-props.js +++ b/packages/reflex-components-ui/js/scripts/css-props.js @@ -287,6 +287,13 @@ else: StyleProps = dict ${block("CSS_PROPS: dict[str, str] = {", [...properties.map(({ key, name }) => `"${key}": "${name}"`)], "}")} +# The properties StyleX types as taking a number, by camelCase name: lengths, +# but for the ones it lists as unitless. +${block( + "NUMERIC_PROPS: frozenset[str] = frozenset({", + properties.filter(({ open }) => open === "_Size").map(({ name }) => `"${name}"`), + "})", +)} ${block( "PSEUDO_CLASSES: frozenset[str] = frozenset({", PSEUDO_CLASSES.map((name) => `"${name}"`), diff --git a/packages/reflex-components-ui/js/tests/css-props.test.js b/packages/reflex-components-ui/js/tests/css-props.test.js index 5955a2a6593..dd9155752d0 100644 --- a/packages/reflex-components-ui/js/tests/css-props.test.js +++ b/packages/reflex-components-ui/js/tests/css-props.test.js @@ -84,6 +84,7 @@ test("renders the types and the runtime tables", () => { literals: ["border-box", "content-box"], open: null, }, + { name: "gap", key: "gap", literals: [], open: "_Size" }, ], ["before"], ); @@ -107,6 +108,7 @@ test("renders the types and the runtime tables", () => { color: _Value[_Color] box_sizing: _Value[_BoxSizing | _StrVar] background_origin: _Value[_BoxSizing | _StrVar] + gap: _Value[_Size] bg: _Value[_Color] bg_color: _Value[_Color] margin_x: _Value[_Size] @@ -128,8 +130,15 @@ CSS_PROPS: dict[str, str] = { "color": "color", "box_sizing": "boxSizing", "background_origin": "backgroundOrigin", + "gap": "gap", } +# The properties StyleX types as taking a number, by camelCase name: lengths, +# but for the ones it lists as unitless. +NUMERIC_PROPS: frozenset[str] = frozenset({ + "gap", +}) + `); expect( rendered.slice(rendered.indexOf("PSEUDO_ELEMENTS:")), diff --git a/packages/reflex-components-ui/news/+unitless-lengths.bugfix.md b/packages/reflex-components-ui/news/+unitless-lengths.bugfix.md new file mode 100644 index 00000000000..594e0698b71 --- /dev/null +++ b/packages/reflex-components-ui/news/+unitless-lengths.bugfix.md @@ -0,0 +1 @@ +A length written as a number without a unit, such as `rx.ui.flex(gap="3")`, is refused with the spellings that work (`gap="3px"`, or the step of the spacing scale `gap="var(--space-3)"`): `rx` passes it on to CSS, where the browser drops it, and `rx.ui` would have given it pixels the page never had. Zero, unitless properties such as `line_height` and `opacity`, and the props Radix declares, such as `spacing`, are unchanged. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index af9f03ef641..336342ed719 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -31,6 +31,12 @@ kind = "style" names = ["m", "mx", "my", "mt", "mr", "mb", "ml", "p", "px", "py", "pt", "pr", "pb", "pl"] reason = "Where Radix does not declare them, the rx components pass the margin and padding props of Radix Themes on as CSS keys, which the browser ignores: rx.box(pt=\"2\") has no padding. rx.ui refuses them and names the style that sets the spacing Radix means, such as padding_top=\"var(--space-2)\". The components that declare them, rx.ui.inset and the cells of rx.ui.table, take them as Radix does." +[[api]] +component = "*" +kind = "style" +names = ["length without a unit"] +reason = "rx passes a length written as a number without a unit, such as gap=\"3\", on to CSS, where the browser drops it: rx.flex(gap=\"3\") has no gap. rx.ui refuses it and names the spellings that work, gap=\"3px\" or the step of the spacing scale gap=\"var(--space-3)\". Zero, the properties that take a plain number (line_height, opacity, z_index, flex) and the props Radix declares, such as spacing, take one as before." + [[api]] component = "text" kind = "prop" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/center.py b/packages/reflex-components-ui/parity/ui_parity/components/center.py index d0d5b8b6d38..d710f093f51 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/center.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/center.py @@ -30,6 +30,9 @@ def _center(namespace: Any, props: Mapping[str, Any]) -> Any: sweep={ "direction": ["row", "column"], "spacing": ["2", "5"], + # Not props of the Radix center: CSS, as rx passes them on, with a unit. + "gap": ["12px"], + "padding": ["16px"], # Centering wins over both, as it does in rx. "align": ["start", "end"], "justify": ["start", "between"], diff --git a/packages/reflex-components-ui/parity/ui_parity/components/flex.py b/packages/reflex-components-ui/parity/ui_parity/components/flex.py index 09062cab57e..106ea651da3 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/flex.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/flex.py @@ -35,6 +35,9 @@ def _flex(namespace: Any, props: Mapping[str, Any]) -> Any: "align": ["start", "center", "end", "baseline", "stretch"], "justify": ["start", "center", "end", "between"], "spacing": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], + # Not props of the Radix flex: CSS, as rx passes them on, with a unit. + "gap": ["12px", "0.5rem"], + "padding": ["16px"], "style": {"sized": {"height": "80px", "padding": "4px"}}, "appearance": [DARK], }, diff --git a/packages/reflex-components-ui/parity/ui_parity/components/grid.py b/packages/reflex-components-ui/parity/ui_parity/components/grid.py index 8cc28298174..033673b1890 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/grid.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/grid.py @@ -40,6 +40,9 @@ def _grid(namespace: Any, props: Mapping[str, Any]) -> Any: "spacing": ["1", "3", "4", "6", "7", "8", "9"], "spacing_x": ["1", "4", "9"], "spacing_y": ["1", "4", "9"], + # Not props of the Radix grid: CSS, as rx passes them on, with a unit. + "gap": ["12px", "0.5rem"], + "padding": ["16px"], "style": {"sized": {"height": "140px", "padding": "4px"}}, "appearance": [DARK], }, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index e510eebb825..49f82a769bf 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -53,8 +53,6 @@ _RADIX_MODULES = ("reflex_components_radix", "reflex.components.radix") # A class name of Radix Themes in a string or a stylesheet. _RADIX_CLASS = re.compile(r"(? tuple[str, such as ``"4"``, that are lengths: the browser drops such a value of rx, and StyleX compiles it to ``4px``. """ - from reflex_components_ui.style.emit import UNITLESS + from reflex_components_ui.style.lower import BARE_NUMBER, UNITLESS def numbers(value: Any) -> bool: """Tell whether a lowered value holds a number written as a string. @@ -336,7 +334,7 @@ def numbers(value: Any) -> bool: """ if value.__class__ is dict: return any(numbers(item) for item in value.values()) - return value.__class__ is str and _BARE_NUMBER.fullmatch(value) is not None + return value.__class__ is str and BARE_NUMBER.fullmatch(value) is not None try: with _quiet(): 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 index 83aa7035703..69184577f09 100644 --- 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 @@ -2562,6 +2562,193 @@ class StyleProps(_Selectors, total=False): "zoom": "zoom", } +# The properties StyleX types as taking a number, by camelCase name: lengths, +# but for the ones it lists as unitless. +NUMERIC_PROPS: frozenset[str] = frozenset({ + "animationIterationCount", + "aspectRatio", + "baselineShift", + "blockSize", + "borderBlockEndWidth", + "borderBlockStartWidth", + "borderBlockWidth", + "borderBottomLeftRadius", + "borderBottomRightRadius", + "borderBottomWidth", + "borderEndEndRadius", + "borderEndStartRadius", + "borderImage", + "borderImageSlice", + "borderInlineEndWidth", + "borderInlineStartWidth", + "borderInlineWidth", + "borderLeftWidth", + "borderRadius", + "borderRightWidth", + "borderSpacing", + "borderStartEndRadius", + "borderStartStartRadius", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderTopWidth", + "borderWidth", + "bottom", + "boxFlex", + "boxFlexGroup", + "boxOrdinalGroup", + "columnCount", + "columnGap", + "columnRuleWidth", + "columnWidth", + "columns", + "containIntrinsicBlockSize", + "containIntrinsicHeight", + "containIntrinsicInlineSize", + "containIntrinsicSize", + "containIntrinsicWidth", + "counterSet", + "cue", + "cueAfter", + "cueBefore", + "end", + "fillOpacity", + "flex", + "flexBasis", + "flexGrow", + "flexShrink", + "fontSize", + "fontSizeAdjust", + "fontWeight", + "gap", + "glyphOrientationHorizontal", + "glyphOrientationVertical", + "gridAutoColumns", + "gridAutoRows", + "gridColumnGap", + "gridGap", + "gridRowGap", + "height", + "hyphenateLimitChars", + "imageOrientation", + "inlineSize", + "inset", + "insetBlock", + "insetBlockEnd", + "insetBlockStart", + "insetInline", + "insetInlineEnd", + "insetInlineStart", + "kerning", + "left", + "letterSpacing", + "lineHeight", + "lineHeightStep", + "margin", + "marginBlock", + "marginBlockEnd", + "marginBlockStart", + "marginBottom", + "marginInline", + "marginInlineEnd", + "marginInlineStart", + "marginLeft", + "marginRight", + "marginTop", + "markerOffset", + "maskBorderOutset", + "maskBorderSlice", + "maskBorderWidth", + "mathDepth", + "maxBlockSize", + "maxHeight", + "maxInlineSize", + "maxWidth", + "minBlockSize", + "minHeight", + "minInlineSize", + "minWidth", + "motion", + "motionOffset", + "motionRotation", + "offsetDistance", + "opacity", + "order", + "orphans", + "outlineOffset", + "outlineWidth", + "padding", + "paddingBlock", + "paddingBlockEnd", + "paddingBlockStart", + "paddingBottom", + "paddingInline", + "paddingInlineEnd", + "paddingInlineStart", + "paddingLeft", + "paddingRight", + "paddingTop", + "pause", + "pauseAfter", + "pauseBefore", + "perspective", + "rest", + "restAfter", + "restBefore", + "right", + "rotate", + "rowGap", + "scale", + "scrollMargin", + "scrollMarginBlock", + "scrollMarginBlockEnd", + "scrollMarginBlockStart", + "scrollMarginBottom", + "scrollMarginInline", + "scrollMarginInlineEnd", + "scrollMarginInlineStart", + "scrollMarginLeft", + "scrollMarginRight", + "scrollMarginTop", + "scrollPadding", + "scrollPaddingBlock", + "scrollPaddingBlockEnd", + "scrollPaddingBlockStart", + "scrollPaddingBottom", + "scrollPaddingInline", + "scrollPaddingInlineEnd", + "scrollPaddingInlineStart", + "scrollPaddingLeft", + "scrollPaddingRight", + "scrollPaddingTop", + "shapeImageThreshold", + "shapeMargin", + "start", + "strokeDashoffset", + "strokeMiterlimit", + "strokeOpacity", + "strokeWidth", + "tabSize", + "textDecorationThickness", + "textIndent", + "textUnderlineOffset", + "top", + "transformOrigin", + "transition", + "translate", + "verticalAlign", + "viewTimelineInset", + "voiceBalance", + "voicePitch", + "voiceRange", + "WebkitLineClamp", + "WebkitTextStrokeWidth", + "widows", + "width", + "wordSpacing", + "zIndex", + "zoom", +}) + PSEUDO_CLASSES: frozenset[str] = frozenset({ "active", "any-link", 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 155b28cae23..66ec53fc14d 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 @@ -28,7 +28,7 @@ from reflex_base.utils.types import safe_issubclass from reflex_base.vars.base import Var -from reflex_components_ui.style.lower import Keyframes, StyleError +from reflex_components_ui.style.lower import UNITLESS, Keyframes, StyleError from reflex_components_ui.style.merge import Alternatives, Merged # The key under which a declaration holds the style every instance has. @@ -38,58 +38,6 @@ # 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 " 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 8305c7017dc..d4f66234d66 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 @@ -46,6 +46,7 @@ from reflex_components_ui.constants import WEB_DIR from reflex_components_ui.style._css_props import ( CSS_PROPS, + NUMERIC_PROPS, PSEUDO_CLASSES, PSEUDO_ELEMENTS, ) @@ -69,6 +70,67 @@ _Entry = tuple[Any, Any, Any, Any] +# 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", +)) + +# The properties whose numbers are lengths: a number written as a string, +# such as "3", is no value of theirs to the browser, and one StyleX gives px. +_LENGTHS: frozenset[str] = NUMERIC_PROPS - UNITLESS + +# A number written as a string, other than zero, which needs no unit. +BARE_NUMBER = re.compile(r"-?(?:[1-9]\d*(?:\.\d+)?|0?\.\d*[1-9]\d*)") + + class StyleError(ReflexError, ValueError): """A style that cannot be compiled.""" @@ -1045,6 +1107,8 @@ def _block( if key in _SPACING_SHORTHANDS: raise _spacing_shorthand(name, key, value) entry = _resolve(name, key) + if _is_length(entry) and (number := _bare_number(value)) is not None: + raise _unitless_length(name, key, number) if entry[0] is not None: _value(name, key, entry, value, path, out, replaced) elif isinstance(value, Var): @@ -1231,6 +1295,77 @@ def prop_breakpoint(name: str, prop: str, breakpoint: Any) -> str: )) +def _is_length(entry: _Entry) -> bool: + """Tell whether a style key sets lengths only. + + Args: + entry: How the key is lowered. + + Returns: + Whether it is a length property, or a key that stands for some. + """ + camel, targets = entry[0], entry[1] + if camel in _LENGTHS: + return True + return ( + camel is not None + and camel not in NUMERIC_PROPS + and bool(targets) + and all(target in _LENGTHS for target in targets) + ) + + +def _bare_number(value: Any) -> str | None: + """Find a number written as a string, without a unit, in a style value. + + Args: + value: The value, or a dict or a list of them by condition. + + Returns: + The first such number, or None. + """ + if value.__class__ is str: + return value if BARE_NUMBER.fullmatch(value) else None + if isinstance(value, Mapping): + items = value.values() + elif isinstance(value, (list, tuple)): + items = value + else: + return None + for item in items: + if (number := _bare_number(item)) is not None: + return number + return None + + +def _unitless_length(name: str, key: str, number: str) -> StyleError: + """Make the error of a length given as a number without a unit. + + rx passes it on as written, and the browser drops it; StyleX would give + it px, and so a style the page never had. + + Args: + name: The display name of the component. + key: The style key. + number: The number, as written. + + Returns: + The error, with the length in pixels and, for a step of the spacing + scale, the step. + """ + step = ( + f', or {key}="var(--space-{number})" (rx.ui.tokens.space[{number}]) for ' + f"step {number} of the spacing scale" + if len(number) == 1 + else "" + ) + return StyleError( + f'{name}: {key}="{number}" is a number without a unit, which the browser ' + f"drops: {name.replace('rx.ui.', 'rx.', 1)} ignores it too. Use " + f'{key}="{number}px" for pixels{step}.' + ) + + def _spacing_shorthand(name: str, key: str, value: Any) -> StyleError: """Make the error of a margin or padding prop of Radix given as a style. diff --git a/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt index fda4208728e..5e8640512c6 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt @@ -20,9 +20,9 @@ app/app.py:44:39: [prop] rx.text passes html_for on as a CSS key, which the brow app/app.py:45:41: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no type: it has no effect. app/app.py:45:56: [prop] rx.ui.scroll_area scrolls natively with the scrollbars of the browser, which take no scroll_hide_delay: it has no effect. app/app.py:46:31: [prop] rx.ui.select places its list as position="popper" does: below the trigger, not over it. -app/app.py:47:38: [unit] gap="3" gives a length without a unit, which is not valid CSS: the browser drops it from rx, and rx.ui compiles it to pixels. Remove it to keep the page as it is, or give it a unit. -app/app.py:48:28: [unit] padding="4" gives a length without a unit, which is not valid CSS: the browser drops it from rx, and rx.ui compiles it to pixels. Remove it to keep the page as it is, or give it a unit. -app/app.py:48:72: [unit] _hover={"margin": "1.5"} gives a length without a unit, which is not valid CSS: the browser drops it from rx, and rx.ui compiles it to pixels. Remove it to keep the page as it is, or give it a unit. +app/app.py:47:38: [style] rx.ui.flex: gap="3" is a number without a unit, which the browser drops: rx.flex ignores it too. Use gap="3px" for pixels, or gap="var(--space-3)" (rx.ui.tokens.space[3]) for step 3 of the spacing scale. +app/app.py:48:28: [style] rx.ui.box: padding="4" is a number without a unit, which the browser drops: rx.box ignores it too. Use padding="4px" for pixels, or padding="var(--space-4)" (rx.ui.tokens.space[4]) for step 4 of the spacing scale. +app/app.py:48:72: [style] rx.ui.box: margin="1.5" is a number without a unit, which the browser drops: rx.box ignores it too. Use margin="1.5px" for pixels. app/app.py:51:67: [prop] Tab moves between the native checkboxes of rx.ui.checkbox_group, and the arrow keys do not: orientation has no effect. app/assets/custom.css:2:1: [radix-class] targets the Radix Themes class "rt-Button", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. app/assets/custom.css:3:7: [radix-class] targets the Radix Themes class "rt-Text", which no rx.ui component carries: style the component through its props and style, or give it a class_name of your own. diff --git a/tests/units/reflex_components_ui/style/test_lower.py b/tests/units/reflex_components_ui/style/test_lower.py index f569a1162bb..8232fe5857a 100644 --- a/tests/units/reflex_components_ui/style/test_lower.py +++ b/tests/units/reflex_components_ui/style/test_lower.py @@ -1270,6 +1270,67 @@ def test_layout_props_are_merged_under_the_style(): "which takes any CSS value." ), ), + ( + "rx.ui.flex", + {"gap": "3"}, + None, + ( + 'rx.ui.flex: gap="3" is a number without a unit, which the browser ' + 'drops: rx.flex ignores it too. Use gap="3px" for pixels, or ' + 'gap="var(--space-3)" (rx.ui.tokens.space[3]) for step 3 of the ' + "spacing scale." + ), + ), + ( + "rx.ui.center", + {"padding": "12"}, + None, + ( + 'rx.ui.center: padding="12" is a number without a unit, which the ' + 'browser drops: rx.center ignores it too. Use padding="12px" for ' + "pixels." + ), + ), + ( + "rx.ui.box", + {"width": "1.5"}, + None, + ( + 'rx.ui.box: width="1.5" is a number without a unit, which the ' + 'browser drops: rx.box ignores it too. Use width="1.5px" for pixels.' + ), + ), + ( + "rx.ui.box", + {"padding_x": "4"}, + None, + ( + 'rx.ui.box: padding_x="4" is a number without a unit, which the ' + 'browser drops: rx.box ignores it too. Use padding_x="4px" for ' + 'pixels, or padding_x="var(--space-4)" (rx.ui.tokens.space[4]) for ' + "step 4 of the spacing scale." + ), + ), + ( + "rx.ui.grid", + {"_hover": {"gap": "2"}}, + None, + ( + 'rx.ui.grid: gap="2" is a number without a unit, which the browser ' + 'drops: rx.grid ignores it too. Use gap="2px" for pixels, or ' + 'gap="var(--space-2)" (rx.ui.tokens.space[2]) for step 2 of the ' + "spacing scale." + ), + ), + ( + "rx.ui.grid", + {"gap": {"initial": "1rem", "md": "-6"}}, + None, + ( + 'rx.ui.grid: gap="-6" is a number without a unit, which the browser ' + 'drops: rx.grid ignores it too. Use gap="-6px" for pixels.' + ), + ), ( "rx.ui.flex", None, @@ -1481,6 +1542,39 @@ def test_errors(name: str, style: Any, layout: Any, message: str): assert isinstance(error.value, ValueError) +def test_numbers_that_need_no_unit_pass_as_written(): + """Zero, unitless and non-length properties, and real numbers, are kept.""" + assert lower( + "rx.ui.box", + { + "gap": "0", + "line_height": "1.5", + "opacity": "0.5", + "z_index": "3", + "flex": "1", + "transition_duration": "300", + "padding": 4, + }, + None, + ) == Lowered( + { + "rowGap": "0", + "columnGap": "0", + "lineHeight": "1.5", + "opacity": "0.5", + "zIndex": "3", + "flex": "1", + "transitionDuration": "300", + "paddingTop": 4, + "paddingRight": 4, + "paddingBottom": 4, + "paddingLeft": 4, + }, + (), + None, + ) + + 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( diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 26efeea657e..705e9643f59 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -7,6 +7,7 @@ import functools import types +from collections.abc import Callable from typing import Any, Literal import pytest @@ -347,6 +348,9 @@ def test_every_component_has_the_api_of_its_radix_counterpart(): ApiDifference("*", "style", shorthand, "a CSS key", None) for shorthand in SPACING_SHORTHANDS ] + found.append( + ApiDifference("*", "style", UNITLESS_LENGTH, "dropped by the browser", None) + ) unlisted, stale = unexplained(found, allowlist.load()) assert unlisted == [], ( "rx.ui differs from rx: match the Radix component, or list the " @@ -408,13 +412,26 @@ def test_every_component_has_the_api_of_its_radix_counterpart(): NO_PROPS = ("color_mode.icon",) -@pytest.mark.parametrize("component", COMPONENTS) -def test_spacing_props_are_props_or_name_the_style_to_use(ui_plugin, component: str): - """A margin or padding prop is one where Radix declares it, else an error. +# The element that takes a style key, where it is not the one STYLED names. +STYLED_BY_KEY = { + ("checkbox", "gap"): "rx.ui.flex", + ("text_area", "padding"): "rx.ui.text_area_input", +} + + +def _check_css_keywords( + component: str, keywords: dict[str, Any], message: Callable[[str, str], str] +) -> None: + """Hold a component to what rx does with keywords it passes on to CSS. + + Each is a prop where the Radix component declares it, and otherwise an + error of rx.ui, unless rx.ui does not style the component. Args: - ui_plugin: The configured plugin. component: The name of the component. + keywords: The value to give each keyword. + message: The error of a keyword, from the name of the element that + takes it and the keyword. """ reference = component_class(resolve(rx, component)).get_fields() candidate = component_class(resolve(reflex_components_ui, component)) @@ -422,26 +439,72 @@ def test_spacing_props_are_props_or_name_the_style_to_use(ui_plugin, component: arguments = ARGUMENTS.get(component, ()) if component in NO_PROPS: for namespace in (rx, reflex_components_ui): - with pytest.raises(TypeError): - resolve(namespace, component)(*arguments, m="2") + for key, value in keywords.items(): + with pytest.raises(TypeError): + resolve(namespace, component)(*arguments, **{key: value}) return - for shorthand, style in SPACING_SHORTHANDS.items(): - if shorthand in reference: - assert shorthand in candidate.get_fields() + for key, value in keywords.items(): + if key in reference: + assert key in candidate.get_fields() continue if component in NOT_STYLED: - assert not isinstance(create(*arguments, **{shorthand: "2"}), UIComponent) + assert not isinstance(create(*arguments, **{key: value}), UIComponent) continue - # The stub of the base class leaves its private members out. - name = STYLED.get(component) or candidate._display_name() # pyright: ignore[reportAttributeAccessIssue] + name = ( + STYLED_BY_KEY.get((component, key)) + or STYLED.get(component) + # The stub of the base class leaves its private members out. + or candidate._display_name() # pyright: ignore[reportAttributeAccessIssue] + ) with pytest.raises(StyleError) as error: - create(*arguments, **{shorthand: "2"}) - assert str(error.value) == ( - f'{name}: "{shorthand}" is not a CSS property, and ' + create(*arguments, **{key: value}) + assert str(error.value) == message(name, key) + + +@pytest.mark.parametrize("component", COMPONENTS) +def test_spacing_props_are_props_or_name_the_style_to_use(ui_plugin, component: str): + """A margin or padding prop is one where Radix declares it, else an error. + + Args: + ui_plugin: The configured plugin. + component: The name of the component. + """ + _check_css_keywords( + component, + dict.fromkeys(SPACING_SHORTHANDS, "2"), + lambda name, key: ( + f'{name}: "{key}" is not a CSS property, and ' f"{name.replace('rx.ui.', 'rx.', 1)} ignores it too. Use " - f'{style}="var(--space-2)" (or rx.ui.tokens.space[2]) for the spacing ' - f'Radix\'s {shorthand}="2" means.' - ) + f'{SPACING_SHORTHANDS[key]}="var(--space-2)" (or rx.ui.tokens.space[2]) ' + f'for the spacing Radix\'s {key}="2" means.' + ), + ) + + +# A length written as a number without a unit, as rx passes it on to CSS. +UNITLESS_LENGTH = "length without a unit" +# The length styles a layout is given most, each as such a number. +LENGTHS = ("gap", "padding", "margin", "width") + + +@pytest.mark.parametrize("component", COMPONENTS) +def test_unitless_lengths_are_props_or_name_the_units_to_use(ui_plugin, component: str): + """A length without a unit is a prop where Radix declares it, else an error. + + Args: + ui_plugin: The configured plugin. + component: The name of the component. + """ + _check_css_keywords( + component, + dict.fromkeys(LENGTHS, "3"), + lambda name, key: ( + f'{name}: {key}="3" is a number without a unit, which the browser ' + f"drops: {name.replace('rx.ui.', 'rx.', 1)} ignores it too. Use " + f'{key}="3px" for pixels, or {key}="var(--space-3)" ' + "(rx.ui.tokens.space[3]) for step 3 of the spacing scale." + ), + ) @pytest.mark.parametrize("component", COMPONENTS) diff --git a/tests/units/reflex_components_ui/test_migrate.py b/tests/units/reflex_components_ui/test_migrate.py index 81234d9fc5e..452c0c959e3 100644 --- a/tests/units/reflex_components_ui/test_migrate.py +++ b/tests/units/reflex_components_ui/test_migrate.py @@ -200,8 +200,10 @@ def test_reports_follow_the_allowlist(): """The codemod reports every prop difference the parity allowlist records.""" entries = allowlist.load().api spacing = [entry for entry in entries if entry.kind == "style"] + # A length without a unit is reported through the error rx.ui gives it. assert [(entry.component, sorted(entry.names)) for entry in spacing] == [ - ("*", sorted(_SPACING_SHORTHANDS)) + ("*", sorted(_SPACING_SHORTHANDS)), + ("*", ["length without a unit"]), ] props = { (entry.component, name) From 51aaf6efb574bcf735edbbb14acbfd09e6b83e6e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:56:07 +0000 Subject: [PATCH 170/204] Document the rx.ui overlays, skeleton, theme, color mode controls and table The form demo labels its switch with a label element: an rx.ui switch is a native input, which takes no children. The theme and table pages give their parts previews that render valid HTML. Claude-Session: https://claude.ai/code/session_014AwvTMRUYrq8BR7cV1SsTn --- docs/library/forms/form-ui.md | 5 +- docs/library/other/skeleton-ui.md | 23 +++ docs/library/other/theme-ui.md | 65 +++++++++ docs/library/overlay/alert_dialog-ui.md | 56 +++++++ docs/library/overlay/context_menu-ui.md | 54 +++++++ docs/library/overlay/dialog-ui.md | 80 ++++++++++ docs/library/overlay/drawer-ui.md | 52 +++++++ docs/library/overlay/dropdown_menu-ui.md | 77 ++++++++++ docs/library/overlay/hover_card-ui.md | 43 ++++++ docs/library/overlay/popover-ui.md | 56 +++++++ docs/library/overlay/tooltip-ui.md | 35 +++++ .../library/tables-and-data-grids/table-ui.md | 137 ++++++++++++++++++ 12 files changed, 682 insertions(+), 1 deletion(-) create mode 100644 docs/library/other/skeleton-ui.md create mode 100644 docs/library/other/theme-ui.md create mode 100644 docs/library/overlay/alert_dialog-ui.md create mode 100644 docs/library/overlay/context_menu-ui.md create mode 100644 docs/library/overlay/dialog-ui.md create mode 100644 docs/library/overlay/drawer-ui.md create mode 100644 docs/library/overlay/dropdown_menu-ui.md create mode 100644 docs/library/overlay/hover_card-ui.md create mode 100644 docs/library/overlay/popover-ui.md create mode 100644 docs/library/overlay/tooltip-ui.md create mode 100644 docs/library/tables-and-data-grids/table-ui.md diff --git a/docs/library/forms/form-ui.md b/docs/library/forms/form-ui.md index 7606ff2748c..96932c0f8db 100644 --- a/docs/library/forms/form-ui.md +++ b/docs/library/forms/form-ui.md @@ -36,7 +36,10 @@ def ui_form_example(): rx.ui.vstack( rx.ui.input(placeholder="First Name", name="first_name"), rx.ui.input(placeholder="Last Name", name="last_name"), - rx.ui.hstack(rx.ui.checkbox("Checked", name="check"), rx.ui.switch("Switched", name="switch")), + rx.ui.hstack( + rx.ui.checkbox("Checked", name="check"), + rx.ui.text(rx.ui.switch(name="switch"), " Switched", as_="label"), + ), rx.ui.button("Submit", type="submit"), ), on_submit=UIFormState.handle_submit, diff --git a/docs/library/other/skeleton-ui.md b/docs/library/other/skeleton-ui.md new file mode 100644 index 00000000000..d6bb85e660b --- /dev/null +++ b/docs/library/other/skeleton-ui.md @@ -0,0 +1,23 @@ +--- +components: + - rx.ui.skeleton +--- +```python exec +import reflex as rx +``` + +# Skeleton + +`rx.ui.skeleton` takes the props of `rx.skeleton` and renders a placeholder that hides its children while content loads whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.skeleton(rx.ui.button("Loading"), loading=True), + rx.ui.skeleton(rx.ui.button("Loaded"), loading=False), + rx.ui.skeleton(style={"width": "120px", "height": "24px"}), + gap="3", + align="center", +) +``` diff --git a/docs/library/other/theme-ui.md b/docs/library/other/theme-ui.md new file mode 100644 index 00000000000..e688713ff1f --- /dev/null +++ b/docs/library/other/theme-ui.md @@ -0,0 +1,65 @@ +--- +components: + - rx.ui.theme + - rx.ui.theme_panel + - rx.ui.color_mode.button + - rx.ui.color_mode.switch + +ColorModeIconButton: | + lambda **props: rx.ui.color_mode.button(**props) + +ColorModeSwitch: | + lambda **props: rx.ui.color_mode.switch(**props) +--- +```python exec +import reflex as rx +``` + +# Theme + +`rx.ui.theme` applies a theme to part of a page, `rx.ui.theme_panel` edits the theme of the page while you design it, and `rx.ui.color_mode` holds the controls of the color mode. The theme of the whole app is the `theme` of `UIPlugin`: see [Theming and Tokens](/rx-ui/theming/). + +## Theme + +`rx.ui.theme` takes the options of `rx.ui.Theme`, each one optional: what it +leaves out is inherited. + +```python demo +rx.ui.flex( + rx.ui.theme(rx.ui.button("Crimson, small radius"), accent_color="crimson", radius="small"), + rx.ui.theme(rx.ui.button("Teal, full radius"), accent_color="teal", radius="full"), + rx.ui.theme( + rx.ui.card(rx.ui.text("Dark"), style={"padding": "12px"}), + appearance="dark", + ), + gap="3", + align="center", +) +``` + +## Color Mode Controls + +`rx.ui.color_mode.button` toggles the color mode, `rx.ui.color_mode.switch` +does the same as a switch, and `rx.ui.color_mode.icon` shows the current mode. +They drive the color mode of the app, as `rx.color_mode` controls do. + +```python demo +rx.ui.flex( + rx.ui.color_mode.button(), + rx.ui.color_mode.switch(), + rx.ui.color_mode.icon(), + gap="4", + align="center", +) +``` + +## Theme Panel + +`rx.ui.theme_panel()` adds a panel, open by default, that edits the theme of the +page in the browser: accent, gray, appearance, radius and scaling. Use it while +designing and remove it before deploying. Pass `default_open=False` to start +it closed. + +```python +rx.ui.theme_panel(default_open=False) +``` diff --git a/docs/library/overlay/alert_dialog-ui.md b/docs/library/overlay/alert_dialog-ui.md new file mode 100644 index 00000000000..070ab32c043 --- /dev/null +++ b/docs/library/overlay/alert_dialog-ui.md @@ -0,0 +1,56 @@ +--- +components: + - rx.ui.alert_dialog.root + - rx.ui.alert_dialog.trigger + - rx.ui.alert_dialog.content + - rx.ui.alert_dialog.title + - rx.ui.alert_dialog.description + - rx.ui.alert_dialog.action + - rx.ui.alert_dialog.cancel + +AlertDialogRoot: | + lambda **props: rx.ui.alert_dialog.root( + rx.ui.alert_dialog.trigger(rx.ui.button("Revoke access")), + rx.ui.alert_dialog.content( + rx.ui.alert_dialog.title("Revoke access"), + rx.ui.alert_dialog.description("Are you sure?"), + rx.ui.flex( + rx.ui.alert_dialog.cancel(rx.ui.button("Cancel", variant="soft")), + rx.ui.alert_dialog.action(rx.ui.button("Revoke", color_scheme="red")), + gap="3", + ), + ), + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Alert Dialog + +`rx.ui.alert_dialog` takes the props of `rx.alert_dialog` and renders a native modal `dialog` that asks for a decision whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.alert_dialog.root( + rx.ui.alert_dialog.trigger(rx.ui.button("Revoke access", color_scheme="red")), + rx.ui.alert_dialog.content( + rx.ui.alert_dialog.title("Revoke access"), + rx.ui.alert_dialog.description( + "Are you sure? This application will no longer be accessible and any existing sessions will be expired.", + ), + rx.ui.flex( + rx.ui.alert_dialog.cancel(rx.ui.button("Cancel", variant="soft", color_scheme="gray")), + rx.ui.alert_dialog.action(rx.ui.button("Revoke access", color_scheme="red")), + gap="3", + justify="end", + style={"margin_top": "16px"}, + ), + ), +) +``` + +An alert dialog does not close on a press outside it: only its action and +cancel buttons, or Escape, close it. diff --git a/docs/library/overlay/context_menu-ui.md b/docs/library/overlay/context_menu-ui.md new file mode 100644 index 00000000000..ee4ab3b3a01 --- /dev/null +++ b/docs/library/overlay/context_menu-ui.md @@ -0,0 +1,54 @@ +--- +components: + - rx.ui.context_menu.root + - rx.ui.context_menu.trigger + - rx.ui.context_menu.content + - rx.ui.context_menu.item + - rx.ui.context_menu.separator + - rx.ui.context_menu.sub + - rx.ui.context_menu.sub_trigger + - rx.ui.context_menu.sub_content + - rx.ui.context_menu.group + - rx.ui.context_menu.label + - rx.ui.context_menu.checkbox + - rx.ui.context_menu.radio_group + - rx.ui.context_menu.radio +--- +```python exec +import reflex as rx +``` + +# Context Menu + +`rx.ui.context_menu` takes the props of `rx.context_menu` and renders a menu in a native popover that opens at the pointer on a right click whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.context_menu.root( + rx.ui.context_menu.trigger( + rx.ui.center( + rx.ui.text("Right click here"), + style={ + "height": "120px", + "border": f"1px dashed {rx.ui.tokens.gray[7]}", + "border_radius": rx.ui.tokens.radius[3], + }, + ), + ), + rx.ui.context_menu.content( + rx.ui.context_menu.item("Edit", shortcut="⌘ E"), + rx.ui.context_menu.item("Duplicate", shortcut="⌘ D"), + rx.ui.context_menu.separator(), + rx.ui.context_menu.sub( + rx.ui.context_menu.sub_trigger("More"), + rx.ui.context_menu.sub_content( + rx.ui.context_menu.item("Move to project…"), + rx.ui.context_menu.item("Move to folder…"), + ), + ), + rx.ui.context_menu.separator(), + rx.ui.context_menu.item("Delete", shortcut="⌘ ⌫", color_scheme="red"), + ), +) +``` diff --git a/docs/library/overlay/dialog-ui.md b/docs/library/overlay/dialog-ui.md new file mode 100644 index 00000000000..aa165fd9802 --- /dev/null +++ b/docs/library/overlay/dialog-ui.md @@ -0,0 +1,80 @@ +--- +components: + - rx.ui.dialog.root + - rx.ui.dialog.trigger + - rx.ui.dialog.content + - rx.ui.dialog.title + - rx.ui.dialog.description + - rx.ui.dialog.close + +DialogRoot: | + lambda **props: rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.ui.button("Open Dialog")), + rx.ui.dialog.content( + rx.ui.dialog.title("Welcome to Reflex!"), + rx.ui.dialog.description("This is a dialog component."), + rx.ui.dialog.close(rx.ui.button("Close", variant="soft")), + ), + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Dialog + +`rx.ui.dialog` takes the props of `rx.dialog` and renders a native modal `dialog` element whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.ui.button("Open Dialog")), + rx.ui.dialog.content( + rx.ui.dialog.title("Welcome to Reflex!"), + rx.ui.dialog.description("This is a dialog component. You can render anything you want in here."), + rx.ui.flex( + rx.ui.dialog.close(rx.ui.button("Close", variant="soft", color_scheme="gray")), + justify="end", + style={"margin_top": "16px"}, + ), + ), +) +``` + +The trigger and close buttons command the native dialog, so a browser with +invoker commands opens and closes it with or without JavaScript. The browser +makes the page behind an open dialog inert. + +## Controlled + +```python demo exec +class UIDialogState(rx.State): + open: bool = False + opened: int = 0 + + @rx.event + def set_open(self, value: bool): + self.open = value + if value: + self.opened += 1 + + +def ui_controlled_dialog(): + return rx.ui.flex( + rx.ui.badge(f"Opened {UIDialogState.opened} times"), + rx.ui.dialog.root( + rx.ui.dialog.trigger(rx.ui.button("Open Dialog")), + rx.ui.dialog.content( + rx.ui.dialog.title("Controlled"), + rx.ui.dialog.description("Its open state lives in UIDialogState."), + rx.ui.dialog.close(rx.ui.button("Close", variant="soft")), + ), + open=UIDialogState.open, + on_open_change=UIDialogState.set_open, + ), + gap="3", + align="center", + ) +``` diff --git a/docs/library/overlay/drawer-ui.md b/docs/library/overlay/drawer-ui.md new file mode 100644 index 00000000000..3d69e5c938e --- /dev/null +++ b/docs/library/overlay/drawer-ui.md @@ -0,0 +1,52 @@ +--- +components: + - rx.ui.drawer.root + - rx.ui.drawer.trigger + - rx.ui.drawer.overlay + - rx.ui.drawer.portal + - rx.ui.drawer.content + - rx.ui.drawer.title + - rx.ui.drawer.description + - rx.ui.drawer.handle + - rx.ui.drawer.close +--- +```python exec +import reflex as rx +``` + +# Drawer + +`rx.ui.drawer` takes the props of `rx.drawer` and renders a native modal `dialog` that slides in from an edge whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.drawer.root( + rx.ui.drawer.trigger(rx.ui.button("Open Drawer")), + rx.ui.drawer.overlay(), + rx.ui.drawer.portal( + rx.ui.drawer.content( + rx.ui.flex( + rx.ui.drawer.title("Settings"), + rx.ui.drawer.description("A drawer from the right edge."), + rx.ui.drawer.close(rx.ui.button("Close", variant="soft")), + direction="column", + gap="3", + align="start", + ), + style={ + "top": "auto", + "right": "auto", + "height": "100%", + "width": "20em", + "padding": "2em", + "background_color": rx.ui.tokens.color.panel_solid, + }, + ), + ), + direction="right", +) +``` + +`direction` is the edge it slides in from: `"left"`, `"right"`, `"top"` or +`"bottom"`. diff --git a/docs/library/overlay/dropdown_menu-ui.md b/docs/library/overlay/dropdown_menu-ui.md new file mode 100644 index 00000000000..f75828200b9 --- /dev/null +++ b/docs/library/overlay/dropdown_menu-ui.md @@ -0,0 +1,77 @@ +--- +components: + - rx.ui.dropdown_menu.root + - rx.ui.dropdown_menu.trigger + - rx.ui.dropdown_menu.content + - rx.ui.dropdown_menu.item + - rx.ui.dropdown_menu.separator + - rx.ui.dropdown_menu.sub + - rx.ui.dropdown_menu.sub_trigger + - rx.ui.dropdown_menu.sub_content + +DropdownMenuRoot: | + lambda **props: rx.ui.dropdown_menu.root( + rx.ui.dropdown_menu.trigger(rx.ui.button("Options", variant="soft")), + rx.ui.dropdown_menu.content( + rx.ui.dropdown_menu.item("Edit"), + rx.ui.dropdown_menu.item("Duplicate"), + ), + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Dropdown Menu + +`rx.ui.dropdown_menu` takes the props of `rx.dropdown_menu` and renders a menu in a native popover whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. `rx.ui.menu` is the same namespace. + +## Basic Example + +```python demo +rx.ui.dropdown_menu.root( + rx.ui.dropdown_menu.trigger(rx.ui.button("Options", variant="soft")), + rx.ui.dropdown_menu.content( + rx.ui.dropdown_menu.item("Edit", shortcut="⌘ E"), + rx.ui.dropdown_menu.item("Duplicate", shortcut="⌘ D"), + rx.ui.dropdown_menu.separator(), + rx.ui.dropdown_menu.item("Archive", shortcut="⌘ N"), + rx.ui.dropdown_menu.sub( + rx.ui.dropdown_menu.sub_trigger("More"), + rx.ui.dropdown_menu.sub_content( + rx.ui.dropdown_menu.item("Move to project…"), + rx.ui.dropdown_menu.item("Move to folder…"), + ), + ), + rx.ui.dropdown_menu.separator(), + rx.ui.dropdown_menu.item("Delete", shortcut="⌘ ⌫", color_scheme="red"), + ), +) +``` + +## Events + +```python demo exec +class UIMenuState(rx.State): + last: str = "nothing" + + @rx.event + def choose(self, item: str): + self.last = item + + +def ui_menu_events(): + return rx.ui.flex( + rx.ui.dropdown_menu.root( + rx.ui.dropdown_menu.trigger(rx.ui.button("Pick", variant="soft")), + rx.ui.dropdown_menu.content( + rx.ui.dropdown_menu.item("Copy", on_click=UIMenuState.choose("Copy")), + rx.ui.dropdown_menu.item("Paste", on_click=UIMenuState.choose("Paste")), + ), + ), + rx.ui.text("Chose: ", rx.ui.code(UIMenuState.last)), + gap="3", + align="center", + ) +``` diff --git a/docs/library/overlay/hover_card-ui.md b/docs/library/overlay/hover_card-ui.md new file mode 100644 index 00000000000..9cfd6c00aef --- /dev/null +++ b/docs/library/overlay/hover_card-ui.md @@ -0,0 +1,43 @@ +--- +components: + - rx.ui.hover_card.root + - rx.ui.hover_card.trigger + - rx.ui.hover_card.content + +HoverCardRoot: | + lambda **props: rx.ui.hover_card.root( + rx.ui.hover_card.trigger(rx.ui.link("Hover over me", href="#")), + rx.ui.hover_card.content(rx.ui.text("This is the hover card.")), + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Hover Card + +`rx.ui.hover_card` takes the props of `rx.hover_card` and renders a native popover that opens while its trigger is hovered or focused whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.flex( + rx.ui.text("Hover over the link to see the card:"), + rx.ui.hover_card.root( + rx.ui.hover_card.trigger(rx.ui.link("@reflex_dev", href="https://github.com/reflex-dev", color_scheme="blue")), + rx.ui.hover_card.content( + rx.ui.flex( + rx.ui.avatar(fallback="RX", radius="full"), + rx.ui.box( + rx.ui.text("Reflex", size="3", weight="bold", as_="div"), + rx.ui.text("Web apps in pure Python.", size="2"), + ), + gap="3", + ), + ), + ), + gap="2", + align="center", +) +``` diff --git a/docs/library/overlay/popover-ui.md b/docs/library/overlay/popover-ui.md new file mode 100644 index 00000000000..f8912ad58f5 --- /dev/null +++ b/docs/library/overlay/popover-ui.md @@ -0,0 +1,56 @@ +--- +components: + - rx.ui.popover.root + - rx.ui.popover.trigger + - rx.ui.popover.content + - rx.ui.popover.close + +PopoverRoot: | + lambda **props: rx.ui.popover.root( + rx.ui.popover.trigger(rx.ui.button("Popover")), + rx.ui.popover.content(rx.ui.text("Hello from the popover.")), + **props, + ) +--- +```python exec +import reflex as rx +``` + +# Popover + +`rx.ui.popover` takes the props of `rx.popover` and renders a native popover anchored to its trigger whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.popover.root( + rx.ui.popover.trigger(rx.ui.button("Comment", variant="soft")), + rx.ui.popover.content( + rx.ui.flex( + rx.ui.text_area(placeholder="Write your comment..."), + rx.ui.flex( + rx.ui.popover.close(rx.ui.button("Comment", size="1")), + justify="end", + ), + direction="column", + gap="3", + ), + style={"width": "300px"}, + ), +) +``` + +## Placement + +```python demo +rx.ui.flex( + *[ + rx.ui.popover.root( + rx.ui.popover.trigger(rx.ui.button(side, variant="outline")), + rx.ui.popover.content(rx.ui.text(f"On the {side}"), side=side), + ) + for side in ["top", "right", "bottom", "left"] + ], + gap="3", +) +``` diff --git a/docs/library/overlay/tooltip-ui.md b/docs/library/overlay/tooltip-ui.md new file mode 100644 index 00000000000..be4929784bc --- /dev/null +++ b/docs/library/overlay/tooltip-ui.md @@ -0,0 +1,35 @@ +--- +components: + - rx.ui.tooltip + +Tooltip: | + lambda **props: rx.ui.tooltip(rx.ui.button("Hover over me"), content="This is the tooltip content.", **props) +--- +```python exec +import reflex as rx +``` + +# Tooltip + +`rx.ui.tooltip` takes the props of `rx.tooltip` and renders a native popover that names its trigger while it is hovered or focused whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.tooltip( + rx.ui.button("Hover over me"), + content="This is the tooltip content.", +) +``` + +## Placement + +```python demo +rx.ui.flex( + *[ + rx.ui.tooltip(rx.ui.button(side, variant="outline"), content=f"On the {side}", side=side) + for side in ["top", "right", "bottom", "left"] + ], + gap="3", +) +``` diff --git a/docs/library/tables-and-data-grids/table-ui.md b/docs/library/tables-and-data-grids/table-ui.md new file mode 100644 index 00000000000..9d4a8519794 --- /dev/null +++ b/docs/library/tables-and-data-grids/table-ui.md @@ -0,0 +1,137 @@ +--- +components: + - rx.ui.table.root + - rx.ui.table.header + - rx.ui.table.row + - rx.ui.table.column_header_cell + - rx.ui.table.body + - rx.ui.table.cell + - rx.ui.table.row_header_cell + +TableRoot: | + lambda **props: rx.ui.table.root( + rx.ui.table.header( + rx.ui.table.row( + rx.ui.table.column_header_cell("Full Name"), + rx.ui.table.column_header_cell("Email"), + ), + ), + rx.ui.table.body( + rx.ui.table.row( + rx.ui.table.row_header_cell("Danilo Rosa"), + rx.ui.table.cell("danilo@example.com"), + ), + ), + **props, + ) + +TableRow: | + lambda **props: rx.ui.table.root( + rx.ui.table.body( + rx.ui.table.row( + rx.ui.table.row_header_cell("Danilo Rosa"), + rx.ui.table.cell("danilo@example.com"), + **props, + ), + ), + ) + +TableColumnHeaderCell: | + lambda **props: rx.ui.table.root( + rx.ui.table.header( + rx.ui.table.row( + rx.ui.table.column_header_cell("Full Name", **props), + rx.ui.table.column_header_cell("Email", **props), + ), + ), + ) + +TableCell: | + lambda **props: rx.ui.table.root( + rx.ui.table.body( + rx.ui.table.row( + rx.ui.table.cell("danilo@example.com", **props), + rx.ui.table.cell("Developer", **props), + ), + ), + ) + +TableRowHeaderCell: | + lambda **props: rx.ui.table.root( + rx.ui.table.body( + rx.ui.table.row( + rx.ui.table.row_header_cell("Danilo Rosa", **props), + rx.ui.table.cell("danilo@example.com"), + ), + ), + ) +--- +```python exec +import reflex as rx +``` + +# Table + +`rx.ui.table` takes the props of `rx.table` and renders a `table` element and its parts whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. + +## Basic Example + +```python demo +rx.ui.table.root( + rx.ui.table.header( + rx.ui.table.row( + rx.ui.table.column_header_cell("Full Name"), + rx.ui.table.column_header_cell("Email"), + rx.ui.table.column_header_cell("Group"), + ), + ), + rx.ui.table.body( + rx.ui.table.row( + rx.ui.table.row_header_cell("Danilo Rosa"), + rx.ui.table.cell("danilo@example.com"), + rx.ui.table.cell("Developer"), + ), + rx.ui.table.row( + rx.ui.table.row_header_cell("Zahra Ambessa"), + rx.ui.table.cell("zahra@example.com"), + rx.ui.table.cell("Admin"), + ), + ), + variant="surface", +) +``` + +## From State + +```python demo exec +class UITableState(rx.State): + people: list[dict[str, str]] = [ + {"name": "Danilo Rosa", "email": "danilo@example.com"}, + {"name": "Zahra Ambessa", "email": "zahra@example.com"}, + {"name": "Jasper Eriksson", "email": "jasper@example.com"}, + ] + + +def ui_table_from_state(): + return rx.ui.table.root( + rx.ui.table.header( + rx.ui.table.row( + rx.ui.table.column_header_cell("Name"), + rx.ui.table.column_header_cell("Email"), + ), + ), + rx.ui.table.body( + rx.foreach( + UITableState.people, + lambda person: rx.ui.table.row( + rx.ui.table.row_header_cell(person["name"]), + rx.ui.table.cell(person["email"]), + ), + ), + ), + size="1", + ) +``` + +The cells of `rx.ui.table` declare the spacing props of Radix Themes (`p`, +`px`, `pt`, ...), so they take them as `rx.table` cells do. From db0123e8fc0e913ef81c4451f15ab40d2a451768 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 04:58:40 +0000 Subject: [PATCH 171/204] Name components in rx.ui errors as an app writes them The errors named a component after its class, rx.ui.em for rx.ui.text.em and rx.ui.callout_root for rx.ui.callout.root, and the rx counterpart after that, rx.em, which does not exist. A component is now named by its public name, read once from the namespace: of several, the one that spells its class name, else the shortest. The textarea of rx.ui.text_area and the input of rx.ui.input, which take the props given to them, are named after them. The API test holds every member of every namespace to a name that creates the same class in rx.ui and exists in rx. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../news/+public-names-in-errors.bugfix.md | 1 + .../src/reflex_components_ui/base.py | 74 ++++++++++++++++++- .../components/text_area.py | 2 + .../components/text_field.py | 2 + .../components/test_accordion.py | 2 +- .../components/test_data_list.py | 4 +- .../components/test_dialog.py | 6 +- .../components/test_dropdown_menu.py | 2 +- .../components/test_hover_card.py | 2 +- .../components/test_popover.py | 4 +- .../components/test_segmented_control.py | 2 +- .../components/test_select.py | 6 +- .../components/test_tabs.py | 2 +- .../components/test_text_field.py | 2 +- .../reflex_components_ui/test_api_parity.py | 31 ++++++-- 15 files changed, 117 insertions(+), 25 deletions(-) create mode 100644 packages/reflex-components-ui/news/+public-names-in-errors.bugfix.md diff --git a/packages/reflex-components-ui/news/+public-names-in-errors.bugfix.md b/packages/reflex-components-ui/news/+public-names-in-errors.bugfix.md new file mode 100644 index 00000000000..268ff311d1b --- /dev/null +++ b/packages/reflex-components-ui/news/+public-names-in-errors.bugfix.md @@ -0,0 +1 @@ +The errors of `rx.ui` name components as an app writes them, `rx.ui.text.em` and `rx.ui.callout.root` rather than `rx.ui.em` and `rx.ui.callout_root`, and their `rx` counterparts likewise. 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 acad4cd038d..5815603cfd0 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/base.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/base.py @@ -11,7 +11,11 @@ from typing import Any, ClassVar, Literal from reflex_base import breakpoints -from reflex_base.components.component import BaseComponent, Component +from reflex_base.components.component import ( + BaseComponent, + Component, + ComponentNamespace, +) 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 @@ -166,6 +170,60 @@ def _combine(styles: list[Mapping[str, Any]]) -> Mapping[str, Any]: return combined +@functools.cache +def _public_names() -> dict[type, str]: + """Name each component class as an app creates it, in rx.ui. + + A class an app creates by several names, such as ``text_field`` and + ``text_field.root``, is named by the one that spells its class name, else + by the shortest. + + Returns: + The name, such as ``rx.ui.text.em``, by class. + """ + import reflex_components_ui + + names: dict[type, list[str]] = {} + for name in reflex_components_ui.__all__: + value = getattr(reflex_components_ui, name) + factories: list[tuple[str, Any]] = [] + if isinstance(value, types.MethodType): + factories.append((name, value)) + elif isinstance(value, ComponentNamespace): + if callable(value): + factories.append((name, value.__call__)) + factories.extend( + (f"{name}.{member}", getattr(value, member)) + for member in dir(value) + if not member.startswith("_") + and isinstance(getattr(value, member), types.MethodType) + ) + for public, factory in factories: + owner = getattr(factory, "__self__", None) + if isinstance(owner, type): + names.setdefault(owner, []).append(public) + return { + cls: "rx.ui." + _preferred(format.to_snake_case(cls.__name__), candidates) + for cls, candidates in names.items() + } + + +def _preferred(snake: str, candidates: list[str]) -> str: + """Choose the name of a class among those an app creates it by. + + Args: + snake: The class name in snake_case. + candidates: The names, such as ``text_field.root``. + + Returns: + The one that spells the class name, else the shortest. + """ + return min( + candidates, + key=lambda public: (public.replace(".", "_") != snake, len(public), public), + ) + + class UIComponent(Component): """A component that renders a plain element styled through StyleX. @@ -195,6 +253,10 @@ class UIComponent(Component): # component, as Radix Themes falls back to its default. _as_tags: ClassVar[frozenset[str]] = frozenset() + # The name an app creates an element by that it does not create alone, + # such as the textarea of ``text_area``, for its errors. + _named_as: ClassVar[str | None] = None + # Whether an rx.ui child rendered in place of the element has its styles # merged into the ones of the element. Otherwise each declares its own, # and the child has the class names of both. @@ -221,9 +283,15 @@ def _display_name(cls) -> str: """Get the name an app refers to the component by. Returns: - The name, such as ``rx.ui.box``. + The name, such as ``rx.ui.box`` or ``rx.ui.text.em``. The rx + component of the same name drops ``.ui``. An element an app + does not create by name is named after the component it is part + of, or else after its class. """ - return f"rx.ui.{format.to_snake_case(cls.__name__)}" + public = _public_names().get(cls) + if public is not None: + return public + return f"rx.ui.{cls._named_as or format.to_snake_case(cls.__name__)}" @classmethod @functools.cache diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py b/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py index 06b385b994f..dd37a9f824d 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/text_area.py @@ -25,6 +25,8 @@ class TextAreaInput(UIComponent, elements.Textarea): tag = "textarea" + _named_as: ClassVar[str | None] = "text_area" + styles: ClassVar[ComponentStyles] = TEXT_AREA_INPUT @classmethod diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py index 2c70e80972a..729bd57c828 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py @@ -138,6 +138,8 @@ class TextFieldInput(UIComponent, elements.Input): tag = "input" + _named_as: ClassVar[str | None] = "input" + styles: ClassVar[ComponentStyles] = TEXT_FIELD_INPUT def _post_init(self, *args, **kwargs): diff --git a/tests/units/reflex_components_ui/components/test_accordion.py b/tests/units/reflex_components_ui/components/test_accordion.py index a31ceaa172b..1510291bc56 100644 --- a/tests/units/reflex_components_ui/components/test_accordion.py +++ b/tests/units/reflex_components_ui/components/test_accordion.py @@ -768,6 +768,6 @@ def test_accordion_refuses_a_variant_it_does_not_have(ui_plugin: UIPlugin): with pytest.raises(StyleError) as error: rx.ui.accordion.root(variant="loud") # pyright: ignore[reportArgumentType] assert str(error.value) == ( - 'rx.ui.accordion_root: unknown variant "loud". The values are "classic", ' + 'rx.ui.accordion.root: unknown variant "loud". The values are "classic", ' '"soft", "surface", "outline", "ghost".' ) diff --git a/tests/units/reflex_components_ui/components/test_data_list.py b/tests/units/reflex_components_ui/components/test_data_list.py index a97932d9bc0..45e87f0b2d2 100644 --- a/tests/units/reflex_components_ui/components/test_data_list.py +++ b/tests/units/reflex_components_ui/components/test_data_list.py @@ -281,12 +281,12 @@ def test_data_list_unknown_values(ui_plugin: UIPlugin): with pytest.raises(StyleError) as error: rx.ui.data_list.root(orientation="diagonal") # pyright: ignore[reportArgumentType] assert str(error.value) == ( - 'rx.ui.data_list_root: unknown orientation "diagonal". ' + 'rx.ui.data_list.root: unknown orientation "diagonal". ' 'The values are "horizontal", "vertical".' ) with pytest.raises(StyleError) as error: rx.ui.data_list.item(align="middle") # pyright: ignore[reportArgumentType] assert str(error.value) == ( - 'rx.ui.data_list_item: unknown align "middle". ' + 'rx.ui.data_list.item: unknown align "middle". ' 'The values are "start", "center", "end", "baseline", "stretch".' ) diff --git a/tests/units/reflex_components_ui/components/test_dialog.py b/tests/units/reflex_components_ui/components/test_dialog.py index e2b744ecd63..0972b526af1 100644 --- a/tests/units/reflex_components_ui/components/test_dialog.py +++ b/tests/units/reflex_components_ui/components/test_dialog.py @@ -559,20 +559,20 @@ def test_dialog_imports_its_script(ui_plugin: UIPlugin): ( lambda: rx.ui.dialog.trigger("Open"), ( - "rx.ui.dialog_trigger: it is rendered as its child, so it needs exactly " + "rx.ui.dialog.trigger: it is rendered as its child, so it needs exactly " "one child that is an element, such as a button." ), ), ( lambda: rx.ui.dialog.close(rx.el.button("a"), rx.el.button("b")), ( - "rx.ui.dialog_close: it is rendered as its child, so it needs exactly " + "rx.ui.dialog.close: it is rendered as its child, so it needs exactly " "one child that is an element, such as a button." ), ), ( lambda: rx.ui.dialog.content(size="9"), # pyright: ignore[reportArgumentType] - 'rx.ui.dialog_content: unknown size "9". The values are "1", "2", "3", "4".', + 'rx.ui.dialog.content: unknown size "9". The values are "1", "2", "3", "4".', ), ], ) diff --git a/tests/units/reflex_components_ui/components/test_dropdown_menu.py b/tests/units/reflex_components_ui/components/test_dropdown_menu.py index a7015cd3d0a..99388c3f902 100644 --- a/tests/units/reflex_components_ui/components/test_dropdown_menu.py +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -490,6 +490,6 @@ def test_dropdown_menu_trigger_needs_an_element(ui_plugin: UIPlugin): with pytest.raises(StyleError) as error: rx.ui.dropdown_menu.trigger("Options") assert str(error.value) == ( - "rx.ui.dropdown_menu_trigger: it is rendered as its child, so it needs exactly " + "rx.ui.dropdown_menu.trigger: it is rendered as its child, so it needs exactly " "one child that is an element, such as a button." ) diff --git a/tests/units/reflex_components_ui/components/test_hover_card.py b/tests/units/reflex_components_ui/components/test_hover_card.py index a8d53e715ef..6f3ca20434a 100644 --- a/tests/units/reflex_components_ui/components/test_hover_card.py +++ b/tests/units/reflex_components_ui/components/test_hover_card.py @@ -224,6 +224,6 @@ def test_hover_card_trigger_needs_an_element(ui_plugin: UIPlugin): with pytest.raises(StyleError) as error: rx.ui.hover_card.trigger("Radix") assert str(error.value) == ( - "rx.ui.hover_card_trigger: it is rendered as its child, so it needs exactly " + "rx.ui.hover_card.trigger: it is rendered as its child, so it needs exactly " "one child that is an element, such as a button." ) diff --git a/tests/units/reflex_components_ui/components/test_popover.py b/tests/units/reflex_components_ui/components/test_popover.py index eb3eab1b9d8..b43214519d4 100644 --- a/tests/units/reflex_components_ui/components/test_popover.py +++ b/tests/units/reflex_components_ui/components/test_popover.py @@ -324,13 +324,13 @@ def test_popover_has_four_sides(): ( lambda: rx.ui.popover.trigger("Open"), ( - "rx.ui.popover_trigger: it is rendered as its child, so it needs exactly " + "rx.ui.popover.trigger: it is rendered as its child, so it needs exactly " "one child that is an element, such as a button." ), ), ( lambda: rx.ui.popover.content(side="above"), # pyright: ignore[reportArgumentType] - 'rx.ui.popover_content: unknown side "above". The values are ' + 'rx.ui.popover.content: unknown side "above". The values are ' + ", ".join(f'"{side}"' for side in SIDES) + ".", ), diff --git a/tests/units/reflex_components_ui/components/test_segmented_control.py b/tests/units/reflex_components_ui/components/test_segmented_control.py index e287d900c90..3650bf98707 100644 --- a/tests/units/reflex_components_ui/components/test_segmented_control.py +++ b/tests/units/reflex_components_ui/components/test_segmented_control.py @@ -478,7 +478,7 @@ def test_segmented_control_unknown_variant(ui_plugin: UIPlugin): rx.ui.segmented_control.root(variant="soft") # pyright: ignore[reportArgumentType] assert ( str(error.value) - == 'rx.ui.segmented_control_root: unknown variant "soft". The values are "classic", "surface".' + == 'rx.ui.segmented_control.root: unknown variant "soft". The values are "classic", "surface".' ) diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index d55e1b13bc2..5fa32a62c0b 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -1370,7 +1370,7 @@ def test_select_unknown_variant(ui_plugin: UIPlugin): rx.ui.select.trigger(variant="solid") # pyright: ignore[reportArgumentType] assert ( str(error.value) - == 'rx.ui.select_trigger: unknown variant "solid". The values are "classic", "surface", "soft", "ghost".' + == 'rx.ui.select.trigger: unknown variant "solid". The values are "classic", "surface", "soft", "ghost".' ) @@ -1388,7 +1388,7 @@ def test_select_unknown_side(ui_plugin: UIPlugin): sides = ", ".join(f'"{side}"' for side in choices) assert ( str(error.value) - == f'rx.ui.select_content: unknown side "above". The values are {sides}.' + == f'rx.ui.select.content: unknown side "above". The values are {sides}.' ) @@ -1398,7 +1398,7 @@ def test_select_of_a_list_unknown_variant(ui_plugin: UIPlugin): rx.ui.select(["a"], variant="outline") # pyright: ignore[reportArgumentType] assert ( str(error.value) - == 'rx.ui.select_trigger: unknown variant "outline". The values are "classic", "surface", "soft", "ghost".' + == 'rx.ui.select.trigger: unknown variant "outline". The values are "classic", "surface", "soft", "ghost".' ) diff --git a/tests/units/reflex_components_ui/components/test_tabs.py b/tests/units/reflex_components_ui/components/test_tabs.py index 4ee10128c65..5bdbdd2e5d1 100644 --- a/tests/units/reflex_components_ui/components/test_tabs.py +++ b/tests/units/reflex_components_ui/components/test_tabs.py @@ -947,5 +947,5 @@ def test_tabs_refuse_a_size_they_do_not_have(ui_plugin: UIPlugin): with pytest.raises(StyleError) as error: rx.ui.tabs.list(size="3") # pyright: ignore[reportArgumentType] assert str(error.value) == ( - 'rx.ui.tabs_list: unknown size "3". The values are "1", "2".' + 'rx.ui.tabs.list: unknown size "3". The values are "1", "2".' ) diff --git a/tests/units/reflex_components_ui/components/test_text_field.py b/tests/units/reflex_components_ui/components/test_text_field.py index 462ec4bac18..f89cc3d38d1 100644 --- a/tests/units/reflex_components_ui/components/test_text_field.py +++ b/tests/units/reflex_components_ui/components/test_text_field.py @@ -611,7 +611,7 @@ def test_text_field_unknown_variant(ui_plugin: UIPlugin): rx.ui.input(variant="solid") # pyright: ignore[reportArgumentType] assert ( str(error.value) - == 'rx.ui.text_field_root: unknown variant "solid". The values are "classic", "surface", "soft".' + == 'rx.ui.input: unknown variant "solid". The values are "classic", "surface", "soft".' ) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 705e9643f59..48b0ae0ac38 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -395,12 +395,12 @@ def test_every_component_has_the_api_of_its_radix_counterpart(): # The element that takes the styles of a component that is not one element, # and that an error names, where it is not the one the component is named for. STYLED = { - "callout": "rx.ui.callout_root", + "callout": "rx.ui.callout.root", "checkbox": "rx.ui.checkbox", - "context_menu.radio": "rx.ui.radio_group_root", - "radio": "rx.ui.radio_group_root", - "radio_group": "rx.ui.radio_group_root", - "select": "rx.ui.select_root", + "context_menu.radio": "rx.ui.radio_group.root", + "radio": "rx.ui.radio_group.root", + "radio_group": "rx.ui.radio_group.root", + "select": "rx.ui.select.root", } # The components rx.ui does not style: an icon and a portal, which pass what @@ -415,7 +415,6 @@ def test_every_component_has_the_api_of_its_radix_counterpart(): # The element that takes a style key, where it is not the one STYLED names. STYLED_BY_KEY = { ("checkbox", "gap"): "rx.ui.flex", - ("text_area", "padding"): "rx.ui.text_area_input", } @@ -720,3 +719,23 @@ def test_type_shape_ignores_where_a_type_is_defined_and_its_order(): 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" + + +@pytest.mark.parametrize("component", COMPONENTS) +def test_errors_name_the_component_and_its_rx_counterpart_as_an_app_writes_them( + component: str, +): + """The name of a component in its errors is a public name, in both namespaces. + + Args: + component: The name of the component. + """ + cls = component_class(resolve(reflex_components_ui, component)) + if not issubclass(cls, UIComponent): + return + # The stub of the base class leaves its private members out. + shown = cls._display_name() # pyright: ignore[reportAttributeAccessIssue] + assert shown.startswith("rx.ui.") + public = shown.removeprefix("rx.ui.") + assert component_class(resolve(reflex_components_ui, public)) is cls + resolve(rx, public) From 81775fcfa449f46133b2f8c7841531ee4ae12716 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 05:06:27 +0000 Subject: [PATCH 172/204] reflex-bench: detect the topology of a tag-less checkout from its source; accumulate repeated --param A checkout without tags reports reflex 0.0.1.devN, which picked the old two-port topology. For such a version the bench now reads what the installed reflex supports from its source (from the subject's directory, so a repo-root reflex/ is not picked up instead), and fails with a message to fetch the tags when it cannot. Repeating --param key=a --param key=b now runs both values; a setting given several values is refused. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- packages/reflex-bench/src/reflex_bench/cli.py | 4 +- .../src/reflex_bench/drivers/app_process.py | 134 ++++++++++++++++-- .../reflex-bench/src/reflex_bench/registry.py | 43 +++--- .../reflex_bench/drivers/test_app_process.py | 66 +++++++++ tests/units/reflex_bench/test_registry.py | 31 +++- 5 files changed, 245 insertions(+), 33 deletions(-) diff --git a/packages/reflex-bench/src/reflex_bench/cli.py b/packages/reflex-bench/src/reflex_bench/cli.py index 912cdf511a6..4b7543ad40b 100644 --- a/packages/reflex-bench/src/reflex_bench/cli.py +++ b/packages/reflex-bench/src/reflex_bench/cli.py @@ -557,7 +557,7 @@ def _instance_options(command: Any) -> Any: "params", multiple=True, metavar="KEY=VALUE", - help="Restrict or override a parameter.", + help="Restrict or override a parameter; repeat a key to run several of its values.", )(command) @@ -590,7 +590,7 @@ def _output_options(command: Any) -> Any: def _select( - filters: Sequence[str], suite: str | None, overrides: Mapping[str, str] + filters: Sequence[str], suite: str | None, overrides: Mapping[str, object] ) -> list[Benchmark]: """Select the benchmarks to run and check the ``--param`` overrides against them. diff --git a/packages/reflex-bench/src/reflex_bench/drivers/app_process.py b/packages/reflex-bench/src/reflex_bench/drivers/app_process.py index efb41489bdf..365b0bdd6ea 100644 --- a/packages/reflex-bench/src/reflex_bench/drivers/app_process.py +++ b/packages/reflex-bench/src/reflex_bench/drivers/app_process.py @@ -217,28 +217,135 @@ class _Topology: single_port: bool -def _topology(mode: Mode, version: str | None, *, backend_only: bool) -> _Topology: +@dataclass(frozen=True) +class _Features: + """What the installed reflex's ``reflex run`` can do. + + Attributes: + single_port_prod: Whether prod serves the frontend from the backend's + port (0.9.0 on). + preview: Whether ``--env preview`` exists (0.9.8 on). + """ + + single_port_prod: bool + preview: bool + + +# Where the subject's reflex package is, found without importing it. +_LOCATE_REFLEX = ( + "import importlib.util as u; s = u.find_spec('reflex'); " + "print(s.submodule_search_locations[0] if s and s.submodule_search_locations " + "else '')" +) + + +def _reflex_features( + python: Path, env: Mapping[str, str] | None = None +) -> _Features | None: + """Read what ``reflex run`` can do from the source of the installed reflex. + + A version string says nothing in a checkout without tags, which reports + 0.0.1.devN; the source does. The marker of each feature is the function + that brought it. + + Args: + python: The subject's interpreter. + env: Its environment; this process's when None. + + Returns: + The features, or None when the source of reflex is not found. + """ + try: + found = subprocess.run( + [str(python), "-c", _LOCATE_REFLEX], + capture_output=True, + text=True, + timeout=60, + env=dict(env) if env is not None else None, + # Not where the harness runs: a checkout there has a reflex + # directory of its own, which -c would find first. + cwd=python.parent, + check=True, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + return None + if not found: + return None + package = Path(found) + + def has(path: str, marker: str) -> bool: + try: + return marker in (package / path).read_text(encoding="utf-8") + except OSError: + return False + + return _Features( + single_port_prod=has("utils/exec.py", "def get_frontend_mount"), + preview=has("reflex.py", "def _run_preview"), + ) + + +def _untagged(version: str | None) -> bool: + """Tell whether a version is the one of a checkout without tags. + + Args: + version: The subject's reflex version. + + Returns: + Whether it is 0.0.1.devN, which says nothing of the release it is. + """ + if version is None: + return False + try: + parsed = Version(version) + except ValueError: + return False + return parsed.release == (0, 0, 1) and parsed.is_devrelease + + +def _topology( + mode: Mode, + version: str | None, + *, + backend_only: bool, + features: _Features | None = None, +) -> _Topology: """Decide what a ``reflex run`` of this mode and version prints and binds. Args: mode: ``dev``, ``prod`` or ``preview``. version: The subject's reflex version. backend_only: Whether it runs with ``--backend-only``. + features: What the installed reflex can do, read from its source; + the version decides when None. Returns: The topology. Raises: - ValueError: On an unknown or unparsable version, or a mode the version lacks. + ValueError: On an unknown or unparsable version, the version of a + checkout without tags with no features, or a mode reflex lacks. """ - if version is None: - msg = "the reflex version is unknown; pass the subject's reflex_version" - raise ValueError(msg) - release = Version(version).release - if mode == "preview" and release < PREVIEW: + if features is None: + if version is None: + msg = "the reflex version is unknown; pass the subject's reflex_version" + raise ValueError(msg) + parsed = Version(version) + if _untagged(version): + msg = ( + f"reflex reports {version}, the version of a checkout without tags, " + "and its source was not found to tell what reflex run serves: fetch " + "the tags (git fetch --tags, or --unshallow in a shallow clone)" + ) + raise ValueError(msg) + features = _Features( + single_port_prod=parsed.release >= SINGLE_PORT_PROD, + preview=parsed.release >= PREVIEW, + ) + if mode == "preview" and not features.preview: msg = f"--env preview needs reflex 0.9.8 or later (subject has {version})" raise ValueError(msg) - if mode == "dev" or release < SINGLE_PORT_PROD: + if mode == "dev" or not features.single_port_prod: # Dev and 0.8.23 prod (sirv) print both lines once the frontend is up; # the backend binds on its own schedule. if backend_only: @@ -1147,7 +1254,16 @@ def __init__( self.backend_only = backend_only self.start_timeout = start_timeout self.scope = scope - self._topology = _topology(mode, reflex_version, backend_only=backend_only) + # A tagged version tells the release; the version of a checkout + # without tags does not, and the source of reflex does. + self._topology = _topology( + mode, + reflex_version, + backend_only=backend_only, + features=_reflex_features(python, env) + if _untagged(reflex_version) + else None, + ) if backend_only and frontend_port is not None: msg = "frontend_port does not apply to a backend-only run" raise ValueError(msg) diff --git a/packages/reflex-bench/src/reflex_bench/registry.py b/packages/reflex-bench/src/reflex_bench/registry.py index 17ac1bdedb4..d55fcbe18e5 100644 --- a/packages/reflex-bench/src/reflex_bench/registry.py +++ b/packages/reflex-bench/src/reflex_bench/registry.py @@ -419,8 +419,9 @@ def expand( Args: overrides: Parameter values that replace a parameter's declared values - (restricting the grid to one value) or a hidden parameter's default. - Keys this benchmark does not declare are ignored. + (restricting the grid to the values given: one, or a tuple of + them) or a hidden parameter's default. Keys this benchmark does + not declare are ignored. suite: The selected suite, whose ``suite_params`` replace the declared values; overrides still win. @@ -428,20 +429,29 @@ def expand( One parameter set per point of the cartesian product, in declaration order. """ - overrides = overrides or {} + given = { + name: value if isinstance(value, tuple) else (value,) + for name, value in (overrides or {}).items() + } narrowed = self.suite_params.get(suite, {}) if suite is not None else {} axes = [ - (coerce_param(overrides[name], values),) - if name in overrides + tuple(coerce_param(value, values) for value in given[name]) + if name in given else narrowed.get(name, values) for name, values in self.params.items() ] - hidden = { - name: coerce_param(overrides[name], (default,)) - if name in overrides - else default - for name, default in self.hidden_params.items() - } + hidden = {} + for name, default in self.hidden_params.items(): + if name not in given: + hidden[name] = default + continue + if len(given[name]) != 1: + msg = ( + f"{self.id}: --param {name} is a setting, which takes one " + f"value, not {', '.join(map(str, given[name]))}" + ) + raise ValueError(msg) + hidden[name] = coerce_param(given[name][0], (default,)) return [ ParamSet(dict(zip(self.params, point, strict=True)), dict(hidden)) for point in itertools.product(*axes) @@ -735,23 +745,24 @@ def select( return chosen -def parse_overrides(pairs: Sequence[str]) -> dict[str, str]: +def parse_overrides(pairs: Sequence[str]) -> dict[str, tuple[str, ...]]: """Parse ``--param KEY=VALUE`` options. Args: pairs: The raw options. Returns: - Parameter name to raw value; later options win. + Parameter name to its raw values, each once, in the order given: a + repeated key runs each of its values. Raises: ValueError: On an option without ``=`` or a key. """ - overrides: dict[str, str] = {} + overrides: dict[str, dict[str, None]] = {} for pair in pairs: key, sep, value = pair.partition("=") if not sep or not key.strip(): msg = f"--param expects KEY=VALUE, got {pair!r}" raise ValueError(msg) - overrides[key.strip()] = value - return overrides + overrides.setdefault(key.strip(), {})[value] = None + return {key: tuple(values) for key, values in overrides.items()} diff --git a/tests/units/reflex_bench/drivers/test_app_process.py b/tests/units/reflex_bench/drivers/test_app_process.py index ce309048614..99a7ded2ba6 100644 --- a/tests/units/reflex_bench/drivers/test_app_process.py +++ b/tests/units/reflex_bench/drivers/test_app_process.py @@ -317,6 +317,72 @@ def test_topology_rejects(mode: app_process.Mode, version: str | None, message: app_process._topology(mode, version, backend_only=False) +def _fake_reflex(root: Path, *, single_port: bool, preview: bool) -> None: + """Write the source of a reflex package with or without two features. + + Args: + root: Where the package goes. + single_port: Whether its prod serves the frontend from the backend. + preview: Whether it has ``--env preview``. + """ + package = root / "reflex" + (package / "utils").mkdir(parents=True) + (package / "__init__.py").write_text("raise RuntimeError('imported')\n") + (package / "utils" / "exec.py").write_text( + "def get_frontend_mount():\n pass\n" if single_port else "x = 1\n" + ) + (package / "reflex.py").write_text( + "def _run_preview():\n pass\n" if preview else "x = 1\n" + ) + + +@pytest.mark.parametrize( + ("single_port", "preview"), [(False, False), (True, False), (True, True)] +) +def test_features_are_read_from_the_installed_source( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, single_port: bool, preview: bool +): + _fake_reflex(tmp_path / "site", single_port=single_port, preview=preview) + # An interpreter without site-packages, so the workspace's reflex is not + # found before the fake one. + python = tmp_path / "python" + python.write_text(f'#!/bin/sh\nexec "{sys.executable}" -S "$@"\n') + python.chmod(0o755) + monkeypatch.setenv("PYTHONPATH", str(tmp_path / "site")) + # Located, not imported: the package raises when it is imported. + assert app_process._reflex_features(python) == ( + app_process._Features(single_port_prod=single_port, preview=preview) + ) + + +def test_features_are_none_without_reflex(tmp_path: Path): + assert app_process._reflex_features(tmp_path / "no-python") is None + + +def test_features_decide_the_topology_whatever_the_version(): + # A checkout without tags reports 0.0.1.devN, older than any release. + features = app_process._Features(single_port_prod=True, preview=True) + assert _ready( + app_process._topology( + "prod", "0.0.1.dev173+g708d0c3", backend_only=False, features=features + ) + ) == {"frontend": APP} + old = app_process._Features(single_port_prod=False, preview=False) + assert _ready( + app_process._topology("prod", HEAD, backend_only=False, features=old) + ) == {"frontend": APP, "backend": BACKEND} + + +def test_a_version_without_tags_and_no_features_fails_clearly(): + with pytest.raises(ValueError) as error: + app_process._topology("prod", "0.0.1.dev173+g708d0c3", backend_only=False) + assert str(error.value) == ( + "reflex reports 0.0.1.dev173+g708d0c3, the version of a checkout without " + "tags, and its source was not found to tell what reflex run serves: fetch " + "the tags (git fetch --tags, or --unshallow in a shallow clone)" + ) + + @pytest.mark.parametrize( ("log", "mode", "version", "backend_only", "urls"), [ diff --git a/tests/units/reflex_bench/test_registry.py b/tests/units/reflex_bench/test_registry.py index 2530123a682..d4f7fd2e61e 100644 --- a/tests/units/reflex_bench/test_registry.py +++ b/tests/units/reflex_bench/test_registry.py @@ -232,14 +232,33 @@ def test_coerce_param(): assert registry.coerce_param("NaN", (1.0,)) == "NaN" -def test_parse_overrides(): - assert registry.parse_overrides(["a=1", "b = x", "a=2", "c="]) == { - "a": "2", - "b": " x", - "c": "", +def test_parse_overrides_accumulates_the_values_of_a_key(): + assert registry.parse_overrides(["a=1", "b = x", "a=2", "c=", "a=1"]) == { + "a": ("1", "2"), + "b": (" x",), + "c": ("",), } - with pytest.raises(ValueError, match="KEY=VALUE"): + with pytest.raises(ValueError) as error: registry.parse_overrides(["novalue"]) + assert str(error.value) == "--param expects KEY=VALUE, got 'novalue'" + + +def test_repeated_overrides_make_an_instance_of_each_value(): + bench = Benchmark.define( + _Sampler, + id="t.grid", + metrics={"wall": WALL}, + params={"pages": [10, 100, 1000], "env": ["dev", "prod"]}, + hidden_params={"shift": 1.0}, + ) + assert [ + p.params for p in bench.expand({"pages": ("100", "250"), "env": ("prod",)}) + ] == [{"pages": 100, "env": "prod"}, {"pages": 250, "env": "prod"}] + with pytest.raises(ValueError) as error: + bench.expand({"shift": ("1.2", "1.4")}) + assert str(error.value) == ( + "t.grid: --param shift is a setting, which takes one value, not 1.2, 1.4" + ) @pytest.fixture From 7e91157ce76d5d30900736a3ef120e4e1e4bd202 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 05:29:38 +0000 Subject: [PATCH 173/204] List rx.ui props in a compact generated table, to keep the docs build within budget The full prop tables, with their live controls, made the rx.ui pages cost a 24% longer docs compile. Their props are the rx components', which the parity tests hold equal but for the differences the page already lists, so an rx.ui page lists each component's own props as plain cells, generated from the same documentation, and the controls stay on the rx tab. Claude-Session: https://claude.ai/code/session_014AwvTMRUYrq8BR7cV1SsTn --- docs/app/reflex_docs/pages/docs/__init__.py | 7 +- docs/app/reflex_docs/pages/docs/component.py | 111 +++++++++++++++--- docs/app/tests/test_ui_pages.py | 49 ++++++++ docs/library/data-display/avatar-ui.md | 3 - docs/library/data-display/badge-ui.md | 3 - docs/library/data-display/callout-ui.md | 3 - docs/library/data-display/progress-ui.md | 3 - docs/library/data-display/scroll_area-ui.md | 7 -- docs/library/disclosure/accordion-ui.md | 9 -- .../disclosure/segmented_control-ui.md | 9 -- docs/library/disclosure/tabs-ui.md | 12 -- docs/library/forms/button-ui.md | 6 - docs/library/forms/checkbox-ui.md | 3 - docs/library/forms/input-ui.md | 3 - docs/library/forms/radio_group-ui.md | 3 - docs/library/forms/select-ui.md | 3 - docs/library/forms/slider-ui.md | 3 - docs/library/forms/switch-ui.md | 3 - docs/library/forms/text_area-ui.md | 3 - docs/library/layout/card-ui.md | 3 - docs/library/layout/center-ui.md | 3 - docs/library/layout/flex-ui.md | 7 -- docs/library/layout/grid-ui.md | 8 -- docs/library/layout/inset-ui.md | 9 -- docs/library/layout/section-ui.md | 3 - docs/library/layout/separator-ui.md | 3 - docs/library/layout/stack-ui.md | 9 -- docs/library/other/theme-ui.md | 6 - docs/library/overlay/alert_dialog-ui.md | 15 --- docs/library/overlay/dialog-ui.md | 11 -- docs/library/overlay/dropdown_menu-ui.md | 10 -- docs/library/overlay/hover_card-ui.md | 7 -- docs/library/overlay/popover-ui.md | 7 -- docs/library/overlay/tooltip-ui.md | 3 - .../library/tables-and-data-grids/table-ui.md | 58 --------- 35 files changed, 148 insertions(+), 257 deletions(-) diff --git a/docs/app/reflex_docs/pages/docs/__init__.py b/docs/app/reflex_docs/pages/docs/__init__.py index ddffc4118bf..2f21e6cd050 100644 --- a/docs/app/reflex_docs/pages/docs/__init__.py +++ b/docs/app/reflex_docs/pages/docs/__init__.py @@ -481,7 +481,6 @@ def handle_library_doc( previews = get_previews_from_frontmatter(actual_path) image = get_image_from_frontmatter(actual_path) variant_component_lists: dict[str, list] = {} - variant_previews: dict[str, dict[str, str]] = {} variant_descriptions: dict[str, str | None] = {} for suffix, *_ in LIBRARY_VARIANTS: variant_path = library_variant_path(actual_path, suffix) @@ -492,9 +491,8 @@ def handle_library_doc( *get_components_from_frontmatter(variant_path), ] if suffix == UI_VARIANT: - # An rx.ui page has examples and prose of its own; a Low Level page - # shares the main page's previews and description. - variant_previews[suffix] = get_previews_from_frontmatter(variant_path) + # An rx.ui page has prose of its own; a Low Level page shares the + # main page's description. variant_source, variant_document = _read_document(variant_path) variant_descriptions[suffix] = ( extract_doc_description( @@ -539,7 +537,6 @@ def handle_library_doc( component_list=clist, title=display_title, variant_component_lists=variant_component_lists, - variant_previews=variant_previews, variant_descriptions=variant_descriptions, description=description, image=image, diff --git a/docs/app/reflex_docs/pages/docs/component.py b/docs/app/reflex_docs/pages/docs/component.py index fb5e6afd03f..bc650acbd96 100644 --- a/docs/app/reflex_docs/pages/docs/component.py +++ b/docs/app/reflex_docs/pages/docs/component.py @@ -16,13 +16,16 @@ from reflex.components.radix.primitives.base import RadixPrimitiveComponent from reflex.components.radix.themes.base import RadixThemesComponent from reflex_components_core.el.elements.base import BaseHTML -from reflex_components_ui.base import UIComponent from reflex_docgen import ( EventHandlerDocumentation, PropDocumentation, generate_documentation, ) -from reflex_site_shared.components.docs_api import docs_api_cell, docs_api_table +from reflex_site_shared.components.docs_api import ( + docs_api_cell, + docs_api_row, + docs_api_table, +) from reflex_docs.docgen_pipeline import ( get_docgen_toc, @@ -79,8 +82,9 @@ class PropDocsState(rx.State): """Container for dynamic vars used by the prop docs.""" -# The components whose styling props a page can preview with live controls. -INTERACTIVE_BASES = (RadixThemesComponent, RadixPrimitiveComponent, UIComponent) +# The components whose styling props a page can preview with live controls. The +# rx.ui components share the props of these and list them in a compact table. +INTERACTIVE_BASES = (RadixThemesComponent, RadixPrimitiveComponent) EXCLUDED_COMPONENTS = [ "Theme", @@ -1059,6 +1063,83 @@ def component_docs( ) +_COMPACT_CODE_CLASS = "code-style text-xs [overflow-wrap:anywhere]" +_COMPACT_TEXT_CLASS = "text-sm leading-6 text-muted-foreground" + + +def compact_props_table(props: Sequence[PropDocumentation]) -> rx.Component: + """Render a component's props as plain text cells. + + It lists what ``props_table`` does, without the controls and the expandable + type cells, so a page that repeats a reference documented elsewhere costs + a few elements per prop. + + Args: + props: The props to list, in display order. Event triggers are skipped. + + Returns: + The props table. + """ + rows = [] + for prop in props: + if prop.name.startswith("on_"): + continue + type_ = prop.type + if safe_issubclass(get_origin(type_), rx.Var): + type_ = get_args(type_)[0] + default = f" Defaults to {prop.default_value}." if prop.default_value else "" + rows.append( + docs_api_row( + docs_api_cell( + rx.el.code(prop.name, class_name=_COMPACT_CODE_CLASS), "w-[20%]" + ), + docs_api_cell( + rx.el.code(_type_label(type_), class_name=_COMPACT_CODE_CLASS), + "w-[25%]", + ), + docs_api_cell( + rx.el.span( + f"{prop.description or ''}{default}", + class_name=_COMPACT_TEXT_CLASS, + ), + "w-[55%]", + ), + ) + ) + return docs_api_table(*rows) + + +def compact_component_docs( + component_tuple: tuple[type[Component], str], +) -> rx.Component: + """Generate the compact API reference of one component. + + Args: + component_tuple: The component class and its public name. + + Returns: + The component's heading, description, props and the count of the HTML + attributes it takes. + """ + component, name = component_tuple + doc = generate_documentation(component) + own, global_props = split_props(component, doc.props) + return rx.box( + h3_comp(text=name), + rx.box(render_markdown(doc.description or ""), class_name="pb-2"), + compact_props_table(own) + if any(not prop.name.startswith("on_") for prop in own) + else rx.el.p("No component specific props.", class_name=_COMPACT_TEXT_CLASS), + rx.el.p( + f"Also accepts the {len(global_props)} global HTML attributes.", + class_name="mb-4 " + _COMPACT_TEXT_CLASS, + ) + if global_props + else rx.fragment(), + class_name="pb-6 w-full text-left", + ) + + def api_reference_toc(names: Sequence[str], has_shared: bool) -> list[tuple[int, str]]: """List the on-page TOC entries of a library page's API reference. @@ -1236,12 +1317,18 @@ def library_page( Returns: A function that renders the page, for ``docpage``. """ - shared = shared_html_props([item[0] for item in component_list[1:]]) - components = [ - component_docs(component_tuple, previews, shared) - for component_tuple in component_list[1:] - ] names = [item[1] for item in component_list[1:]] + if current == "ui": + # The props are the rx components', which the parity tests hold equal + # but for the listed differences: list them without controls. + shared: tuple[PropDocumentation, ...] = () + components = [compact_component_docs(item) for item in component_list[1:]] + else: + shared = shared_html_props([item[0] for item in component_list[1:]]) + components = [ + component_docs(component_tuple, previews, shared) + for component_tuple in component_list[1:] + ] def page(): toc = get_docgen_toc(actual_path) @@ -1289,7 +1376,6 @@ def multi_docs( description: str | None = None, image: str | None = None, variant_component_lists: dict[str, list] | None = None, - variant_previews: dict[str, dict[str, str]] | None = None, variant_descriptions: dict[str, str | None] | None = None, source: str | None = None, ): @@ -1307,8 +1393,6 @@ def multi_docs( variant_component_lists: The components of each variant page that has its own, by file suffix; a Low Level page without them documents the main page's. - variant_previews: The preview factories of each variant page that has - its own, by file suffix; the main page's otherwise. variant_descriptions: The meta description of each variant page that has its own prose, by file suffix. source: The main page's markdown, when the caller has read it. @@ -1317,7 +1401,6 @@ def multi_docs( The main page, or a tuple of it and its variant pages. """ variant_component_lists = variant_component_lists or {} - variant_previews = variant_previews or {} variant_descriptions = variant_descriptions or {} present = [ variant @@ -1374,7 +1457,7 @@ def multi_docs( path, library_variant_path(virtual_path, suffix), variant_actual, - variant_previews.get(suffix, previews), + previews, variant_list, segment, segments, diff --git a/docs/app/tests/test_ui_pages.py b/docs/app/tests/test_ui_pages.py index f5821f0bc6f..6392b94bb1a 100644 --- a/docs/app/tests/test_ui_pages.py +++ b/docs/app/tests/test_ui_pages.py @@ -3,6 +3,7 @@ import importlib import tomllib from pathlib import Path +from typing import Literal import pytest @@ -230,3 +231,51 @@ def test_library_variant_suffix(doc, expected): from reflex_docs.pages.docs import library_variant_suffix assert library_variant_suffix(doc) == expected + + +def _cell_texts(component) -> list[list[str]]: + """Collect the text of each cell of each body row of a rendered table.""" + rows = [] + + def texts(node) -> list[str]: + if (contents := getattr(node, "contents", None)) is not None: + return [contents._var_value] + return [text for child in node.children for text in texts(child)] + + def walk(node): + if getattr(node, "tag", None) == "tbody": + rows.extend( + ["".join(texts(cell)) for cell in row.children] for row in node.children + ) + return + for child in getattr(node, "children", ()): + walk(child) + + walk(component) + return rows + + +def test_compact_props_table_lists_props_without_triggers(): + import reflex as rx + from reflex_docgen import PropDocumentation + + from reflex_docs.pages.docs.component import compact_props_table + + props = [ + PropDocumentation( + name="size", + type=rx.Var[Literal["1", "2"]], + description="Button size.", + default_value='"2"', + ), + PropDocumentation( + name="on_click", type=rx.Var[str], description=None, default_value=None + ), + PropDocumentation( + name="loading", type=rx.Var[bool], description=None, default_value=None + ), + ] + assert _cell_texts(compact_props_table(props)) == [ + ["size", 'Literal["1", "2"]', 'Button size. Defaults to "2".'], + ["loading", "bool", ""], + ] diff --git a/docs/library/data-display/avatar-ui.md b/docs/library/data-display/avatar-ui.md index 1d01b4b75b7..c5fe3b2a486 100644 --- a/docs/library/data-display/avatar-ui.md +++ b/docs/library/data-display/avatar-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.avatar - -Avatar: | - lambda **props: rx.ui.avatar(fallback="RX", **props) --- ```python exec import reflex as rx diff --git a/docs/library/data-display/badge-ui.md b/docs/library/data-display/badge-ui.md index 30f31dcdc69..3b1aa0b23df 100644 --- a/docs/library/data-display/badge-ui.md +++ b/docs/library/data-display/badge-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.badge - -Badge: | - lambda **props: rx.ui.badge("Basic Badge", **props) --- ```python exec import reflex as rx diff --git a/docs/library/data-display/callout-ui.md b/docs/library/data-display/callout-ui.md index 95aed8c1dc9..04ca9e57b27 100644 --- a/docs/library/data-display/callout-ui.md +++ b/docs/library/data-display/callout-ui.md @@ -4,9 +4,6 @@ components: - rx.ui.callout.root - rx.ui.callout.icon - rx.ui.callout.text - -Callout: | - lambda **props: rx.ui.callout("Basic Callout", icon="info", **props) --- ```python exec import reflex as rx diff --git a/docs/library/data-display/progress-ui.md b/docs/library/data-display/progress-ui.md index 433ffb122f4..03aa23d6b2c 100644 --- a/docs/library/data-display/progress-ui.md +++ b/docs/library/data-display/progress-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.progress - -Progress: | - lambda **props: rx.ui.progress(value=50, **props) --- ```python exec import reflex as rx diff --git a/docs/library/data-display/scroll_area-ui.md b/docs/library/data-display/scroll_area-ui.md index e82fccb920b..86e54032a67 100644 --- a/docs/library/data-display/scroll_area-ui.md +++ b/docs/library/data-display/scroll_area-ui.md @@ -1,13 +1,6 @@ --- components: - rx.ui.scroll_area - -ScrollArea: | - lambda **props: rx.ui.scroll_area( - rx.ui.text("Three fundamental aspects of typography are legibility, readability, and aesthetics. " * 8), - style={"height": "120px", "width": "300px"}, - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/disclosure/accordion-ui.md b/docs/library/disclosure/accordion-ui.md index 74b1fbd18d6..3ca35444b81 100644 --- a/docs/library/disclosure/accordion-ui.md +++ b/docs/library/disclosure/accordion-ui.md @@ -2,15 +2,6 @@ components: - rx.ui.accordion.root - rx.ui.accordion.item - -AccordionRoot: | - lambda **props: rx.ui.accordion.root( - rx.ui.accordion.item(header="First Item", content="The first accordion item's content", value="item_1"), - rx.ui.accordion.item(header="Second Item", content="The second accordion item's content", value="item_2"), - collapsible=True, - style={"width": "300px"}, - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/disclosure/segmented_control-ui.md b/docs/library/disclosure/segmented_control-ui.md index 26acdb5e7f6..496a941ba24 100644 --- a/docs/library/disclosure/segmented_control-ui.md +++ b/docs/library/disclosure/segmented_control-ui.md @@ -2,15 +2,6 @@ components: - rx.ui.segmented_control.root - rx.ui.segmented_control.item - -SegmentedControlRoot: | - lambda **props: rx.ui.segmented_control.root( - rx.ui.segmented_control.item("Home", value="home"), - rx.ui.segmented_control.item("About", value="about"), - rx.ui.segmented_control.item("Test", value="test"), - default_value="home", - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/disclosure/tabs-ui.md b/docs/library/disclosure/tabs-ui.md index e23004ac425..e62692ab5fa 100644 --- a/docs/library/disclosure/tabs-ui.md +++ b/docs/library/disclosure/tabs-ui.md @@ -4,18 +4,6 @@ components: - rx.ui.tabs.list - rx.ui.tabs.trigger - rx.ui.tabs.content - -TabsRoot: | - lambda **props: rx.ui.tabs.root( - rx.ui.tabs.list( - rx.ui.tabs.trigger("Tab 1", value="tab1"), - rx.ui.tabs.trigger("Tab 2", value="tab2"), - ), - rx.ui.tabs.content(rx.ui.text("item on tab 1"), value="tab1"), - rx.ui.tabs.content(rx.ui.text("item on tab 2"), value="tab2"), - default_value="tab1", - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/forms/button-ui.md b/docs/library/forms/button-ui.md index 769f6f8557c..5fb30f7aa14 100644 --- a/docs/library/forms/button-ui.md +++ b/docs/library/forms/button-ui.md @@ -2,12 +2,6 @@ components: - rx.ui.button - rx.ui.icon_button - -Button: | - lambda **props: rx.ui.button("Basic Button", **props) - -IconButton: | - lambda **props: rx.ui.icon_button(rx.icon("heart"), aria_label="Like", **props) --- ```python exec diff --git a/docs/library/forms/checkbox-ui.md b/docs/library/forms/checkbox-ui.md index a08f988903c..5ce34a1f506 100644 --- a/docs/library/forms/checkbox-ui.md +++ b/docs/library/forms/checkbox-ui.md @@ -5,9 +5,6 @@ components: - rx.ui.checkbox_group.item - rx.ui.checkbox_cards.root - rx.ui.checkbox_cards.item - -HighLevelCheckbox: | - lambda **props: rx.ui.checkbox("Basic Checkbox", **props) --- ```python exec import reflex as rx diff --git a/docs/library/forms/input-ui.md b/docs/library/forms/input-ui.md index e993825fddb..9b71ba9f506 100644 --- a/docs/library/forms/input-ui.md +++ b/docs/library/forms/input-ui.md @@ -2,9 +2,6 @@ components: - rx.ui.input - rx.ui.input.slot - -TextFieldRoot: | - lambda **props: rx.ui.input(placeholder="Search the docs", **props) --- ```python exec import reflex as rx diff --git a/docs/library/forms/radio_group-ui.md b/docs/library/forms/radio_group-ui.md index 44669710d99..244ad48ebfa 100644 --- a/docs/library/forms/radio_group-ui.md +++ b/docs/library/forms/radio_group-ui.md @@ -5,9 +5,6 @@ components: - rx.ui.radio_group.item - rx.ui.radio_cards.root - rx.ui.radio_cards.item - -HighLevelRadioGroup: | - lambda **props: rx.ui.radio_group(["1", "2", "3", "4", "5"], **props) --- ```python exec import reflex as rx diff --git a/docs/library/forms/select-ui.md b/docs/library/forms/select-ui.md index e52ad19d0e9..01f8cd892e2 100644 --- a/docs/library/forms/select-ui.md +++ b/docs/library/forms/select-ui.md @@ -8,9 +8,6 @@ components: - rx.ui.select.item - rx.ui.select.label - rx.ui.select.separator - -HighLevelSelect: | - lambda **props: rx.ui.select(["apple", "grape", "pear"], default_value="pear", **props) --- ```python exec import reflex as rx diff --git a/docs/library/forms/slider-ui.md b/docs/library/forms/slider-ui.md index 827f058a3d5..645689d06a4 100644 --- a/docs/library/forms/slider-ui.md +++ b/docs/library/forms/slider-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.slider - -Slider: | - lambda **props: rx.ui.slider(default_value=40, style={"width": "300px"}, **props) --- ```python exec import reflex as rx diff --git a/docs/library/forms/switch-ui.md b/docs/library/forms/switch-ui.md index 00efd0ff8bc..98c69ef1ae1 100644 --- a/docs/library/forms/switch-ui.md +++ b/docs/library/forms/switch-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.switch - -Switch: | - lambda **props: rx.ui.switch(**props) --- ```python exec import reflex as rx diff --git a/docs/library/forms/text_area-ui.md b/docs/library/forms/text_area-ui.md index c2d2b215af4..496dd1d392f 100644 --- a/docs/library/forms/text_area-ui.md +++ b/docs/library/forms/text_area-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.text_area - -TextArea: | - lambda **props: rx.ui.text_area(placeholder="Type here...", **props) --- ```python exec import reflex as rx diff --git a/docs/library/layout/card-ui.md b/docs/library/layout/card-ui.md index 12fc3dda946..6180a1352f0 100644 --- a/docs/library/layout/card-ui.md +++ b/docs/library/layout/card-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.card - -Card: | - lambda **props: rx.ui.card("Basic Card", **props) --- ```python exec import reflex as rx diff --git a/docs/library/layout/center-ui.md b/docs/library/layout/center-ui.md index ee57e3d2771..d409301c8f1 100644 --- a/docs/library/layout/center-ui.md +++ b/docs/library/layout/center-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.center - -Center: | - lambda **props: rx.ui.center(rx.ui.text("Centered"), style={"height": "80px", "border": "1px dashed var(--gray-7)"}, **props) --- ```python exec import reflex as rx diff --git a/docs/library/layout/flex-ui.md b/docs/library/layout/flex-ui.md index a6c7cf376fa..3eb13a23c0e 100644 --- a/docs/library/layout/flex-ui.md +++ b/docs/library/layout/flex-ui.md @@ -1,13 +1,6 @@ --- components: - rx.ui.flex - -Flex: | - lambda **props: rx.ui.flex( - rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), - gap="2", - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/layout/grid-ui.md b/docs/library/layout/grid-ui.md index 118126b3c73..7e17cc6cd90 100644 --- a/docs/library/layout/grid-ui.md +++ b/docs/library/layout/grid-ui.md @@ -1,14 +1,6 @@ --- components: - rx.ui.grid - -Grid: | - lambda **props: rx.ui.grid( - *[rx.ui.card(f"Card {i}") for i in range(1, 7)], - columns="3", - gap="2", - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/layout/inset-ui.md b/docs/library/layout/inset-ui.md index f1458b3061c..2a9e748f73a 100644 --- a/docs/library/layout/inset-ui.md +++ b/docs/library/layout/inset-ui.md @@ -1,15 +1,6 @@ --- components: - rx.ui.inset - -Inset: | - lambda **props: rx.ui.card( - rx.ui.inset( - rx.image(src="https://web.reflex-assets.dev/other/reflex_banner.png", alt="Reflex banner image", width="100%", height="auto"), - **props, - ), - style={"max_width": "320px"}, - ) --- ```python exec import reflex as rx diff --git a/docs/library/layout/section-ui.md b/docs/library/layout/section-ui.md index 294350ea213..d99bbcc72c8 100644 --- a/docs/library/layout/section-ui.md +++ b/docs/library/layout/section-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.section - -Section: | - lambda **props: rx.ui.section(rx.ui.heading("Section", size="4", as_="h3"), **props) --- ```python exec import reflex as rx diff --git a/docs/library/layout/separator-ui.md b/docs/library/layout/separator-ui.md index d239b60d126..4b1b3b76cd7 100644 --- a/docs/library/layout/separator-ui.md +++ b/docs/library/layout/separator-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.separator - -Separator: | - lambda **props: rx.ui.separator(**props) --- ```python exec import reflex as rx diff --git a/docs/library/layout/stack-ui.md b/docs/library/layout/stack-ui.md index 631e69b6a63..3f6200d3ed9 100644 --- a/docs/library/layout/stack-ui.md +++ b/docs/library/layout/stack-ui.md @@ -3,15 +3,6 @@ components: - rx.ui.stack - rx.ui.hstack - rx.ui.vstack - -Stack: | - lambda **props: rx.ui.stack(rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), **props) - -HStack: | - lambda **props: rx.ui.hstack(rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), **props) - -VStack: | - lambda **props: rx.ui.vstack(rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), **props) --- ```python exec import reflex as rx diff --git a/docs/library/other/theme-ui.md b/docs/library/other/theme-ui.md index e688713ff1f..8e074f6e6f0 100644 --- a/docs/library/other/theme-ui.md +++ b/docs/library/other/theme-ui.md @@ -4,12 +4,6 @@ components: - rx.ui.theme_panel - rx.ui.color_mode.button - rx.ui.color_mode.switch - -ColorModeIconButton: | - lambda **props: rx.ui.color_mode.button(**props) - -ColorModeSwitch: | - lambda **props: rx.ui.color_mode.switch(**props) --- ```python exec import reflex as rx diff --git a/docs/library/overlay/alert_dialog-ui.md b/docs/library/overlay/alert_dialog-ui.md index 070ab32c043..4f5dd5a277f 100644 --- a/docs/library/overlay/alert_dialog-ui.md +++ b/docs/library/overlay/alert_dialog-ui.md @@ -7,21 +7,6 @@ components: - rx.ui.alert_dialog.description - rx.ui.alert_dialog.action - rx.ui.alert_dialog.cancel - -AlertDialogRoot: | - lambda **props: rx.ui.alert_dialog.root( - rx.ui.alert_dialog.trigger(rx.ui.button("Revoke access")), - rx.ui.alert_dialog.content( - rx.ui.alert_dialog.title("Revoke access"), - rx.ui.alert_dialog.description("Are you sure?"), - rx.ui.flex( - rx.ui.alert_dialog.cancel(rx.ui.button("Cancel", variant="soft")), - rx.ui.alert_dialog.action(rx.ui.button("Revoke", color_scheme="red")), - gap="3", - ), - ), - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/overlay/dialog-ui.md b/docs/library/overlay/dialog-ui.md index aa165fd9802..381268eee20 100644 --- a/docs/library/overlay/dialog-ui.md +++ b/docs/library/overlay/dialog-ui.md @@ -6,17 +6,6 @@ components: - rx.ui.dialog.title - rx.ui.dialog.description - rx.ui.dialog.close - -DialogRoot: | - lambda **props: rx.ui.dialog.root( - rx.ui.dialog.trigger(rx.ui.button("Open Dialog")), - rx.ui.dialog.content( - rx.ui.dialog.title("Welcome to Reflex!"), - rx.ui.dialog.description("This is a dialog component."), - rx.ui.dialog.close(rx.ui.button("Close", variant="soft")), - ), - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/overlay/dropdown_menu-ui.md b/docs/library/overlay/dropdown_menu-ui.md index f75828200b9..c62cafd2419 100644 --- a/docs/library/overlay/dropdown_menu-ui.md +++ b/docs/library/overlay/dropdown_menu-ui.md @@ -8,16 +8,6 @@ components: - rx.ui.dropdown_menu.sub - rx.ui.dropdown_menu.sub_trigger - rx.ui.dropdown_menu.sub_content - -DropdownMenuRoot: | - lambda **props: rx.ui.dropdown_menu.root( - rx.ui.dropdown_menu.trigger(rx.ui.button("Options", variant="soft")), - rx.ui.dropdown_menu.content( - rx.ui.dropdown_menu.item("Edit"), - rx.ui.dropdown_menu.item("Duplicate"), - ), - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/overlay/hover_card-ui.md b/docs/library/overlay/hover_card-ui.md index 9cfd6c00aef..ea6cdc492a6 100644 --- a/docs/library/overlay/hover_card-ui.md +++ b/docs/library/overlay/hover_card-ui.md @@ -3,13 +3,6 @@ components: - rx.ui.hover_card.root - rx.ui.hover_card.trigger - rx.ui.hover_card.content - -HoverCardRoot: | - lambda **props: rx.ui.hover_card.root( - rx.ui.hover_card.trigger(rx.ui.link("Hover over me", href="#")), - rx.ui.hover_card.content(rx.ui.text("This is the hover card.")), - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/overlay/popover-ui.md b/docs/library/overlay/popover-ui.md index f8912ad58f5..dc926e74c61 100644 --- a/docs/library/overlay/popover-ui.md +++ b/docs/library/overlay/popover-ui.md @@ -4,13 +4,6 @@ components: - rx.ui.popover.trigger - rx.ui.popover.content - rx.ui.popover.close - -PopoverRoot: | - lambda **props: rx.ui.popover.root( - rx.ui.popover.trigger(rx.ui.button("Popover")), - rx.ui.popover.content(rx.ui.text("Hello from the popover.")), - **props, - ) --- ```python exec import reflex as rx diff --git a/docs/library/overlay/tooltip-ui.md b/docs/library/overlay/tooltip-ui.md index be4929784bc..c6262ee6c2b 100644 --- a/docs/library/overlay/tooltip-ui.md +++ b/docs/library/overlay/tooltip-ui.md @@ -1,9 +1,6 @@ --- components: - rx.ui.tooltip - -Tooltip: | - lambda **props: rx.ui.tooltip(rx.ui.button("Hover over me"), content="This is the tooltip content.", **props) --- ```python exec import reflex as rx diff --git a/docs/library/tables-and-data-grids/table-ui.md b/docs/library/tables-and-data-grids/table-ui.md index 9d4a8519794..14d0f377dd3 100644 --- a/docs/library/tables-and-data-grids/table-ui.md +++ b/docs/library/tables-and-data-grids/table-ui.md @@ -7,64 +7,6 @@ components: - rx.ui.table.body - rx.ui.table.cell - rx.ui.table.row_header_cell - -TableRoot: | - lambda **props: rx.ui.table.root( - rx.ui.table.header( - rx.ui.table.row( - rx.ui.table.column_header_cell("Full Name"), - rx.ui.table.column_header_cell("Email"), - ), - ), - rx.ui.table.body( - rx.ui.table.row( - rx.ui.table.row_header_cell("Danilo Rosa"), - rx.ui.table.cell("danilo@example.com"), - ), - ), - **props, - ) - -TableRow: | - lambda **props: rx.ui.table.root( - rx.ui.table.body( - rx.ui.table.row( - rx.ui.table.row_header_cell("Danilo Rosa"), - rx.ui.table.cell("danilo@example.com"), - **props, - ), - ), - ) - -TableColumnHeaderCell: | - lambda **props: rx.ui.table.root( - rx.ui.table.header( - rx.ui.table.row( - rx.ui.table.column_header_cell("Full Name", **props), - rx.ui.table.column_header_cell("Email", **props), - ), - ), - ) - -TableCell: | - lambda **props: rx.ui.table.root( - rx.ui.table.body( - rx.ui.table.row( - rx.ui.table.cell("danilo@example.com", **props), - rx.ui.table.cell("Developer", **props), - ), - ), - ) - -TableRowHeaderCell: | - lambda **props: rx.ui.table.root( - rx.ui.table.body( - rx.ui.table.row( - rx.ui.table.row_header_cell("Danilo Rosa", **props), - rx.ui.table.cell("danilo@example.com"), - ), - ), - ) --- ```python exec import reflex as rx From dc921011f5ba8e590f39fb9266cce100fab13801 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 05:52:08 +0000 Subject: [PATCH 174/204] Read an rx.ui page's description without parsing the page twice Claude-Session: https://claude.ai/code/session_014AwvTMRUYrq8BR7cV1SsTn --- docs/app/reflex_docs/pages/docs/__init__.py | 34 ++++++--------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/docs/app/reflex_docs/pages/docs/__init__.py b/docs/app/reflex_docs/pages/docs/__init__.py index 2f21e6cd050..8b7b810638b 100644 --- a/docs/app/reflex_docs/pages/docs/__init__.py +++ b/docs/app/reflex_docs/pages/docs/__init__.py @@ -454,22 +454,6 @@ def comp(_actual=actual_path, _title=resolved.display_title): return make_docpage(resolved.route, resolved.display_title, doc, comp, actual_path) -def _read_document(actual_path: str): - """Read a markdown file and parse it. - - Args: - actual_path: The file. - - Returns: - Its source and parsed document, both None when it cannot be read. - """ - try: - source = Path(actual_path).read_text(encoding="utf-8") - return source, parse_document(source) - except Exception: - return None, None - - def handle_library_doc( doc: str, actual_path: str, @@ -492,14 +476,10 @@ def handle_library_doc( ] if suffix == UI_VARIANT: # An rx.ui page has prose of its own; a Low Level page shares the - # main page's description. - variant_source, variant_document = _read_document(variant_path) - variant_descriptions[suffix] = ( - extract_doc_description( - variant_source, dict(variant_document.frontmatter.metadata) - ) - if variant_source is not None and variant_document is not None - else None + # main page's description. The description reads its frontmatter + # itself, so the page is not parsed twice. + variant_descriptions[suffix] = extract_doc_description( + Path(variant_path).read_text(encoding="utf-8") ) if doc.startswith("docs/library/graphing"): graphing_components[resolved.category].append(clist) @@ -510,7 +490,11 @@ def handle_library_doc( # filename (e.g. "Barchart"). Derive a page-specific meta description from # the doc's frontmatter/body prose, and prefer an explicit frontmatter # `title:` for a human-friendly, keyword-rich page title. - source, document = _read_document(actual_path) + try: + source: str | None = Path(actual_path).read_text(encoding="utf-8") + document = parse_document(source) + except Exception: + source, document = None, None frontmatter = document.frontmatter if document is not None else None metadata = dict(frontmatter.metadata) if frontmatter is not None else None description = extract_doc_description(source, metadata) if source else None From 63d0c64003dcc4fe1e77adf6dc99fd07b479a503 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 06:26:09 +0000 Subject: [PATCH 175/204] Write rx.ui demos with spacing instead of unitless gaps, and format them A gap written as a number without a unit is now a StyleError in rx.ui, since rx passes it to CSS, where the browser drops it. The demos use spacing, the prop Radix declares for the step of the space scale; the styling guide lists lengths without a unit among what is not supported, and the generated list of shared differences writes a described entry without code formatting. Claude-Session: https://claude.ai/code/session_014AwvTMRUYrq8BR7cV1SsTn --- .../reflex_docs/pages/docs/ui_differences.py | 5 +-- docs/app/tests/test_ui_pages.py | 9 +++++- docs/library/data-display/avatar-ui.md | 10 ++++-- docs/library/data-display/badge-ui.md | 2 +- docs/library/data-display/callout-ui.md | 7 +++-- docs/library/data-display/data_list-ui.md | 4 ++- docs/library/data-display/list-ui.md | 2 +- docs/library/data-display/progress-ui.md | 2 +- docs/library/data-display/scroll_area-ui.md | 2 +- docs/library/data-display/spinner-ui.md | 4 +-- docs/library/disclosure/accordion-ui.md | 20 +++++++++--- .../disclosure/segmented_control-ui.md | 4 +-- docs/library/disclosure/tabs-ui.md | 28 +++++++++++++---- docs/library/forms/button-ui.md | 18 ++++++----- docs/library/forms/checkbox-ui.md | 12 ++++--- docs/library/forms/form-ui.md | 2 +- docs/library/forms/input-ui.md | 4 +-- docs/library/forms/radio_group-ui.md | 31 +++++++++++++++---- docs/library/forms/select-ui.md | 8 +++-- docs/library/forms/slider-ui.md | 4 +-- docs/library/forms/switch-ui.md | 4 +-- docs/library/forms/text_area-ui.md | 4 +-- docs/library/layout/card-ui.md | 10 +++--- docs/library/layout/flex-ui.md | 12 ++++--- docs/library/layout/grid-ui.md | 6 ++-- docs/library/layout/inset-ui.md | 11 +++++-- docs/library/layout/separator-ui.md | 4 +-- docs/library/layout/stack-ui.md | 2 +- docs/library/other/skeleton-ui.md | 2 +- docs/library/other/theme-ui.md | 8 +++-- docs/library/overlay/alert_dialog-ui.md | 10 ++++-- docs/library/overlay/dialog-ui.md | 10 ++++-- docs/library/overlay/drawer-ui.md | 2 +- docs/library/overlay/dropdown_menu-ui.md | 2 +- docs/library/overlay/hover_card-ui.md | 10 ++++-- docs/library/overlay/popover-ui.md | 4 +-- docs/library/overlay/tooltip-ui.md | 6 ++-- docs/library/typography/blockquote-ui.md | 2 +- docs/library/typography/code-ui.md | 2 +- docs/library/typography/heading-ui.md | 2 +- docs/library/typography/link-ui.md | 4 +-- docs/library/typography/text-ui.md | 4 +-- docs/rx_ui/overview.md | 6 +++- docs/rx_ui/styling.md | 21 ++++++++++--- docs/rx_ui/theming.md | 16 ++++++---- 45 files changed, 233 insertions(+), 109 deletions(-) diff --git a/docs/app/reflex_docs/pages/docs/ui_differences.py b/docs/app/reflex_docs/pages/docs/ui_differences.py index 81de3ffe74f..b66e16c80de 100644 --- a/docs/app/reflex_docs/pages/docs/ui_differences.py +++ b/docs/app/reflex_docs/pages/docs/ui_differences.py @@ -42,9 +42,10 @@ def _codes(names: list[str]) -> str: names: Props, event triggers or CSS properties. Returns: - The names, each in backticks, separated by commas. + The names separated by commas, each in backticks unless it is a + description such as "length without a unit". """ - return ", ".join(f"`{name}`" for name in names) + return ", ".join(name if " " in name else f"`{name}`" for name in names) def _api_item(entry: dict) -> str: diff --git a/docs/app/tests/test_ui_pages.py b/docs/app/tests/test_ui_pages.py index 6392b94bb1a..0812df09878 100644 --- a/docs/app/tests/test_ui_pages.py +++ b/docs/app/tests/test_ui_pages.py @@ -23,6 +23,12 @@ names = ["p", "m"] reason = "Shared." +[[api]] +component = "*" +kind = "style" +names = ["length without a unit"] +reason = "Units." + [[api]] component = "text" kind = "prop" @@ -92,7 +98,8 @@ def test_differences_do_not_match_a_longer_name(allowlist): "- **Computed style** (`outline-color` in firefox): Focus ring." ) assert shared_differences_markdown(allowlist) == ( - "- **Style keywords** `p`, `m`: Shared." + "- **Style keywords** `p`, `m`: Shared.\n" + "- **Style keywords** length without a unit: Units." ) diff --git a/docs/library/data-display/avatar-ui.md b/docs/library/data-display/avatar-ui.md index c5fe3b2a486..8083a748bbe 100644 --- a/docs/library/data-display/avatar-ui.md +++ b/docs/library/data-display/avatar-ui.md @@ -14,10 +14,14 @@ import reflex as rx ```python demo rx.ui.flex( - rx.ui.avatar(src="https://web.reflex-assets.dev/other/logo.jpg", alt="Reflex logo", fallback="RX"), + rx.ui.avatar( + src="https://web.reflex-assets.dev/other/logo.jpg", + alt="Reflex logo", + fallback="RX", + ), rx.ui.avatar(fallback="RX"), rx.ui.avatar(fallback="RX", variant="solid", radius="full"), - gap="3", + spacing="3", ) ``` @@ -30,7 +34,7 @@ has run. ```python demo rx.ui.flex( *[rx.ui.avatar(fallback="RX", size=str(size)) for size in range(1, 7)], - gap="3", + spacing="3", align="center", ) ``` diff --git a/docs/library/data-display/badge-ui.md b/docs/library/data-display/badge-ui.md index 3b1aa0b23df..548c06832e2 100644 --- a/docs/library/data-display/badge-ui.md +++ b/docs/library/data-display/badge-ui.md @@ -26,7 +26,7 @@ rx.ui.flex( rx.ui.badge("Outline", variant="outline"), rx.ui.badge("Crimson", color_scheme="crimson"), rx.ui.badge("Cyan", color_scheme="cyan", high_contrast=True), - gap="2", + spacing="2", wrap="wrap", ) ``` diff --git a/docs/library/data-display/callout-ui.md b/docs/library/data-display/callout-ui.md index 04ca9e57b27..84c47b23f22 100644 --- a/docs/library/data-display/callout-ui.md +++ b/docs/library/data-display/callout-ui.md @@ -16,7 +16,10 @@ import reflex as rx ## Basic Example ```python demo -rx.ui.callout("You will need admin privileges to install and access this application.", icon="info") +rx.ui.callout( + "You will need admin privileges to install and access this application.", + icon="info", +) ``` ## Variants and Colors @@ -28,7 +31,7 @@ rx.ui.flex( rx.ui.callout("Outline", icon="info", variant="outline"), rx.ui.callout("Access denied.", icon="triangle-alert", color_scheme="red"), direction="column", - gap="3", + spacing="3", ) ``` diff --git a/docs/library/data-display/data_list-ui.md b/docs/library/data-display/data_list-ui.md index 8c1da042f96..0579e516588 100644 --- a/docs/library/data-display/data_list-ui.md +++ b/docs/library/data-display/data_list-ui.md @@ -19,7 +19,9 @@ import reflex as rx rx.ui.data_list.root( rx.ui.data_list.item( rx.ui.data_list.label("Status"), - rx.ui.data_list.value(rx.ui.badge("Authorized", variant="soft", color_scheme="jade")), + rx.ui.data_list.value( + rx.ui.badge("Authorized", variant="soft", color_scheme="jade") + ), align="center", ), rx.ui.data_list.item( diff --git a/docs/library/data-display/list-ui.md b/docs/library/data-display/list-ui.md index 580e21baeec..5631c095b03 100644 --- a/docs/library/data-display/list-ui.md +++ b/docs/library/data-display/list-ui.md @@ -26,7 +26,7 @@ rx.ui.flex( rx.ui.list.item("Second"), rx.ui.list.item("Third"), ), - gap="6", + spacing="6", ) ``` diff --git a/docs/library/data-display/progress-ui.md b/docs/library/data-display/progress-ui.md index 03aa23d6b2c..377dae2308d 100644 --- a/docs/library/data-display/progress-ui.md +++ b/docs/library/data-display/progress-ui.md @@ -24,7 +24,7 @@ rx.ui.flex( rx.ui.progress(value=50, size="2", variant="soft"), rx.ui.progress(value=75, size="3", color_scheme="orange"), direction="column", - gap="4", + spacing="4", style={"width": "100%"}, ) ``` diff --git a/docs/library/data-display/scroll_area-ui.md b/docs/library/data-display/scroll_area-ui.md index 86e54032a67..883f426d2e7 100644 --- a/docs/library/data-display/scroll_area-ui.md +++ b/docs/library/data-display/scroll_area-ui.md @@ -23,7 +23,7 @@ rx.ui.scroll_area( for _ in range(4) ], direction="column", - gap="4", + spacing="4", ), scrollbars="vertical", style={"height": "180px", "max_width": "420px"}, diff --git a/docs/library/data-display/spinner-ui.md b/docs/library/data-display/spinner-ui.md index bbe4614508d..6ac3fa01519 100644 --- a/docs/library/data-display/spinner-ui.md +++ b/docs/library/data-display/spinner-ui.md @@ -17,7 +17,7 @@ rx.ui.flex( rx.ui.spinner(size="1"), rx.ui.spinner(size="2"), rx.ui.spinner(size="3"), - gap="4", + spacing="4", align="center", ) ``` @@ -31,7 +31,7 @@ shows while `loading=True`, and the children otherwise. rx.ui.flex( rx.ui.spinner(rx.ui.badge("Ready"), loading=False), rx.ui.spinner(rx.ui.badge("Ready"), loading=True), - gap="4", + spacing="4", align="center", ) ``` diff --git a/docs/library/disclosure/accordion-ui.md b/docs/library/disclosure/accordion-ui.md index 3ca35444b81..d608f9c1a5f 100644 --- a/docs/library/disclosure/accordion-ui.md +++ b/docs/library/disclosure/accordion-ui.md @@ -18,9 +18,21 @@ without JavaScript. ```python demo rx.ui.accordion.root( - rx.ui.accordion.item(header="First Item", content="The first accordion item's content", value="item_1"), - rx.ui.accordion.item(header="Second Item", content="The second accordion item's content", value="item_2"), - rx.ui.accordion.item(header="Third Item", content="The third accordion item's content", value="item_3"), + rx.ui.accordion.item( + header="First Item", + content="The first accordion item's content", + value="item_1", + ), + rx.ui.accordion.item( + header="Second Item", + content="The second accordion item's content", + value="item_2", + ), + rx.ui.accordion.item( + header="Third Item", + content="The third accordion item's content", + value="item_3", + ), collapsible=True, style={"width": "300px"}, ) @@ -63,7 +75,7 @@ def ui_controlled_accordion(): style={"width": "300px"}, ), direction="column", - gap="3", + spacing="3", ) ``` diff --git a/docs/library/disclosure/segmented_control-ui.md b/docs/library/disclosure/segmented_control-ui.md index 496a941ba24..9b086a5bbf6 100644 --- a/docs/library/disclosure/segmented_control-ui.md +++ b/docs/library/disclosure/segmented_control-ui.md @@ -33,7 +33,7 @@ def ui_segmented_control(): ), rx.ui.text("Selected: ", rx.ui.code(UISegmentedState.control)), direction="column", - gap="3", + spacing="3", align="start", ) ``` @@ -57,7 +57,7 @@ rx.ui.flex( size="3", ), direction="column", - gap="3", + spacing="3", align="start", ) ``` diff --git a/docs/library/disclosure/tabs-ui.md b/docs/library/disclosure/tabs-ui.md index e62692ab5fa..ea1b9a5192d 100644 --- a/docs/library/disclosure/tabs-ui.md +++ b/docs/library/disclosure/tabs-ui.md @@ -22,9 +22,21 @@ rx.ui.tabs.root( rx.ui.tabs.trigger("Documents", value="documents"), rx.ui.tabs.trigger("Settings", value="settings"), ), - rx.ui.tabs.content(rx.ui.text("Make changes to your account."), value="account", style={"padding_top": "12px"}), - rx.ui.tabs.content(rx.ui.text("Access and update your documents."), value="documents", style={"padding_top": "12px"}), - rx.ui.tabs.content(rx.ui.text("Edit your profile or update contact information."), value="settings", style={"padding_top": "12px"}), + rx.ui.tabs.content( + rx.ui.text("Make changes to your account."), + value="account", + style={"padding_top": "12px"}, + ), + rx.ui.tabs.content( + rx.ui.text("Access and update your documents."), + value="documents", + style={"padding_top": "12px"}, + ), + rx.ui.tabs.content( + rx.ui.text("Edit your profile or update contact information."), + value="settings", + style={"padding_top": "12px"}, + ), default_value="account", ) ``` @@ -54,7 +66,7 @@ def ui_controlled_tabs(): on_change=UITabsState.set_value, ), direction="column", - gap="3", + spacing="3", ) ``` @@ -66,8 +78,12 @@ rx.ui.tabs.root( rx.ui.tabs.trigger("Tab 1", value="tab1"), rx.ui.tabs.trigger("Tab 2", value="tab2"), ), - rx.ui.tabs.content(rx.ui.text("items on tab 1"), value="tab1", style={"padding_left": "16px"}), - rx.ui.tabs.content(rx.ui.text("items on tab 2"), value="tab2", style={"padding_left": "16px"}), + rx.ui.tabs.content( + rx.ui.text("items on tab 1"), value="tab1", style={"padding_left": "16px"} + ), + rx.ui.tabs.content( + rx.ui.text("items on tab 2"), value="tab2", style={"padding_left": "16px"} + ), default_value="tab1", orientation="vertical", ) diff --git a/docs/library/forms/button-ui.md b/docs/library/forms/button-ui.md index 5fb30f7aa14..89f02fb514d 100644 --- a/docs/library/forms/button-ui.md +++ b/docs/library/forms/button-ui.md @@ -34,8 +34,10 @@ def ui_counter(): return rx.ui.flex( rx.ui.button("Decrement", color_scheme="red", on_click=UICountState.decrement), rx.ui.heading(UICountState.count, as_="h2"), - rx.ui.button("Increment", color_scheme="grass", on_click=UICountState.increment), - gap="3", + rx.ui.button( + "Increment", color_scheme="grass", on_click=UICountState.increment + ), + spacing="3", ) ``` @@ -49,7 +51,7 @@ rx.ui.flex( rx.ui.button("Surface", variant="surface"), rx.ui.button("Outline", variant="outline"), rx.ui.button("Ghost", variant="ghost"), - gap="3", + spacing="3", align="center", wrap="wrap", ) @@ -61,7 +63,7 @@ rx.ui.flex( rx.ui.button("Size 2", size="2"), rx.ui.button("Size 3", size="3"), rx.ui.button("Size 4", size="4"), - gap="3", + spacing="3", align="center", ) ``` @@ -76,7 +78,7 @@ rx.ui.flex( rx.ui.button("Regular"), rx.ui.button("Loading", loading=True), rx.ui.button("Disabled", disabled=True), - gap="2", + spacing="2", ) ``` @@ -89,7 +91,9 @@ the icon has no text a screen reader can announce. rx.ui.flex( rx.ui.icon_button(rx.icon("plus"), aria_label="Add", variant="solid"), rx.ui.icon_button(rx.icon("pencil"), aria_label="Edit", variant="soft"), - rx.ui.icon_button(rx.icon("trash-2"), aria_label="Delete", color_scheme="red", variant="outline"), - gap="3", + rx.ui.icon_button( + rx.icon("trash-2"), aria_label="Delete", color_scheme="red", variant="outline" + ), + spacing="3", ) ``` diff --git a/docs/library/forms/checkbox-ui.md b/docs/library/forms/checkbox-ui.md index 5ce34a1f506..0da6d908848 100644 --- a/docs/library/forms/checkbox-ui.md +++ b/docs/library/forms/checkbox-ui.md @@ -30,9 +30,13 @@ class UICheckboxState(rx.State): def ui_checkbox_example(): return rx.ui.flex( - rx.ui.checkbox("Agree to terms", checked=UICheckboxState.checked, on_change=UICheckboxState.set_checked), + rx.ui.checkbox( + "Agree to terms", + checked=UICheckboxState.checked, + on_change=UICheckboxState.set_checked, + ), rx.ui.badge(rx.cond(UICheckboxState.checked, "Checked", "Unchecked")), - gap="3", + spacing="3", align="center", ) ``` @@ -48,7 +52,7 @@ rx.ui.flex( rx.ui.checkbox("Surface", variant="surface", default_checked=True), rx.ui.checkbox("Disabled", disabled=True), direction="column", - gap="2", + spacing="2", ) ``` @@ -74,7 +78,7 @@ def ui_checkbox_group_example(): ), rx.ui.text("Selected: ", UICheckboxGroupState.selected.join(", ")), direction="column", - gap="3", + spacing="3", ) ``` diff --git a/docs/library/forms/form-ui.md b/docs/library/forms/form-ui.md index 96932c0f8db..c5777ac4092 100644 --- a/docs/library/forms/form-ui.md +++ b/docs/library/forms/form-ui.md @@ -68,7 +68,7 @@ rx.ui.form.root( rx.ui.form.message("Please enter a valid email.", match="typeMismatch"), rx.ui.form.submit(rx.ui.button("Submit"), as_child=True), direction="column", - gap="2", + spacing="2", align="stretch", ), name="email", diff --git a/docs/library/forms/input-ui.md b/docs/library/forms/input-ui.md index 9b71ba9f506..455068eaa52 100644 --- a/docs/library/forms/input-ui.md +++ b/docs/library/forms/input-ui.md @@ -27,7 +27,7 @@ def ui_input_example(): rx.ui.heading(UIInputState.text, as_="h3", size="4"), rx.ui.input(value=UIInputState.text, on_change=UIInputState.set_text), direction="column", - gap="3", + spacing="3", ) ``` @@ -50,6 +50,6 @@ rx.ui.flex( rx.ui.input(placeholder="Classic", variant="classic", size="2"), rx.ui.input(placeholder="Soft", variant="soft", size="3"), direction="column", - gap="3", + spacing="3", ) ``` diff --git a/docs/library/forms/radio_group-ui.md b/docs/library/forms/radio_group-ui.md index 244ad48ebfa..2f57b8586b2 100644 --- a/docs/library/forms/radio_group-ui.md +++ b/docs/library/forms/radio_group-ui.md @@ -27,9 +27,14 @@ class UIRadioState(rx.State): def ui_radio_example(): return rx.ui.flex( - rx.ui.radio_group(["1", "2", "3"], value=UIRadioState.choice, on_change=UIRadioState.set_choice, direction="row"), + rx.ui.radio_group( + ["1", "2", "3"], + value=UIRadioState.choice, + on_change=UIRadioState.set_choice, + direction="row", + ), rx.ui.badge(UIRadioState.choice), - gap="3", + spacing="3", align="center", ) ``` @@ -39,11 +44,25 @@ def ui_radio_example(): ```python demo rx.ui.radio_group.root( rx.ui.flex( - rx.ui.text(rx.ui.flex(rx.ui.radio_group.item(value="default"), "Default", gap="2"), as_="label", size="2"), - rx.ui.text(rx.ui.flex(rx.ui.radio_group.item(value="comfortable"), "Comfortable", gap="2"), as_="label", size="2"), - rx.ui.text(rx.ui.flex(rx.ui.radio_group.item(value="compact"), "Compact", gap="2"), as_="label", size="2"), + rx.ui.text( + rx.ui.flex(rx.ui.radio_group.item(value="default"), "Default", spacing="2"), + as_="label", + size="2", + ), + rx.ui.text( + rx.ui.flex( + rx.ui.radio_group.item(value="comfortable"), "Comfortable", spacing="2" + ), + as_="label", + size="2", + ), + rx.ui.text( + rx.ui.flex(rx.ui.radio_group.item(value="compact"), "Compact", spacing="2"), + as_="label", + size="2", + ), direction="column", - gap="2", + spacing="2", ), default_value="comfortable", ) diff --git a/docs/library/forms/select-ui.md b/docs/library/forms/select-ui.md index 01f8cd892e2..b4a8ac98b25 100644 --- a/docs/library/forms/select-ui.md +++ b/docs/library/forms/select-ui.md @@ -30,9 +30,13 @@ class UISelectState(rx.State): def ui_select_example(): return rx.ui.flex( - rx.ui.select(["apple", "grape", "pear"], value=UISelectState.value, on_change=UISelectState.set_value), + rx.ui.select( + ["apple", "grape", "pear"], + value=UISelectState.value, + on_change=UISelectState.set_value, + ), rx.ui.badge(UISelectState.value), - gap="3", + spacing="3", align="center", ) ``` diff --git a/docs/library/forms/slider-ui.md b/docs/library/forms/slider-ui.md index 645689d06a4..89c2cc3a6b5 100644 --- a/docs/library/forms/slider-ui.md +++ b/docs/library/forms/slider-ui.md @@ -29,7 +29,7 @@ def ui_slider_example(): rx.ui.heading(UISliderState.value, as_="h3", size="4"), rx.ui.slider(default_value=50, on_change=UISliderState.set_end.throttle(100)), direction="column", - gap="3", + spacing="3", style={"width": "100%"}, ) ``` @@ -51,7 +51,7 @@ rx.ui.flex( rx.ui.slider(default_value=50, size="2", variant="soft"), rx.ui.slider(default_value=75, size="3", color_scheme="orange"), direction="column", - gap="4", + spacing="4", style={"width": "100%"}, ) ``` diff --git a/docs/library/forms/switch-ui.md b/docs/library/forms/switch-ui.md index 98c69ef1ae1..2d886e6b7ac 100644 --- a/docs/library/forms/switch-ui.md +++ b/docs/library/forms/switch-ui.md @@ -25,7 +25,7 @@ def ui_switch_example(): return rx.ui.flex( rx.ui.switch(checked=UISwitchState.on, on_change=UISwitchState.set_on), rx.ui.badge(rx.cond(UISwitchState.on, "On", "Off")), - gap="3", + spacing="3", align="center", ) ``` @@ -40,7 +40,7 @@ rx.ui.flex( rx.ui.switch(variant="soft", default_checked=True), rx.ui.switch(variant="surface", default_checked=True), rx.ui.switch(disabled=True), - gap="3", + spacing="3", align="center", ) ``` diff --git a/docs/library/forms/text_area-ui.md b/docs/library/forms/text_area-ui.md index 496dd1d392f..15680b27118 100644 --- a/docs/library/forms/text_area-ui.md +++ b/docs/library/forms/text_area-ui.md @@ -26,7 +26,7 @@ def ui_text_area_example(): rx.ui.heading(UITextAreaState.text, as_="h3", size="4"), rx.ui.text_area(value=UITextAreaState.text, on_change=UITextAreaState.set_text), direction="column", - gap="3", + spacing="3", ) ``` @@ -38,6 +38,6 @@ rx.ui.flex( rx.ui.text_area(placeholder="Classic", variant="classic"), rx.ui.text_area(placeholder="Soft", variant="soft", size="3"), direction="column", - gap="3", + spacing="3", ) ``` diff --git a/docs/library/layout/card-ui.md b/docs/library/layout/card-ui.md index 6180a1352f0..6c586d1155a 100644 --- a/docs/library/layout/card-ui.md +++ b/docs/library/layout/card-ui.md @@ -18,9 +18,11 @@ rx.ui.card( rx.ui.avatar(fallback="RX", size="3"), rx.ui.box( rx.ui.heading("Quick Start", size="3", as_="h3"), - rx.ui.text("Get started with Reflex in 5 minutes.", size="2", color_scheme="gray"), + rx.ui.text( + "Get started with Reflex in 5 minutes.", size="2", color_scheme="gray" + ), ), - gap="3", + spacing="3", align="center", ), style={"max_width": "360px"}, @@ -34,7 +36,7 @@ rx.ui.flex( rx.ui.card("Surface", variant="surface"), rx.ui.card("Classic", variant="classic"), rx.ui.card("Ghost", variant="ghost"), - gap="3", + spacing="3", ) ``` @@ -43,7 +45,7 @@ rx.ui.flex( rx.ui.card("Size 1", size="1"), rx.ui.card("Size 2", size="2"), rx.ui.card("Size 3", size="3"), - gap="3", + spacing="3", align="start", ) ``` diff --git a/docs/library/layout/flex-ui.md b/docs/library/layout/flex-ui.md index 3eb13a23c0e..84d0be47f17 100644 --- a/docs/library/layout/flex-ui.md +++ b/docs/library/layout/flex-ui.md @@ -17,14 +17,16 @@ rx.ui.flex( rx.ui.card("Card 1"), rx.ui.card("Card 2"), rx.ui.card("Card 3"), - gap="2", + spacing="2", ) ``` ## Direction, Alignment and Wrapping -`direction`, `align`, `justify`, `wrap` and `gap` take the values of Radix -Themes, and each takes `rx.breakpoints(...)` for a value per breakpoint. +`direction`, `align`, `justify`, `wrap` and `spacing` take the values of +Radix Themes, and each takes `rx.breakpoints(...)` for a value per breakpoint. +`spacing="3"` is a step of the space scale; a `gap` style needs a unit, such as +`gap="12px"` or `gap=rx.ui.tokens.space[3]`. ```python demo rx.ui.flex( @@ -33,7 +35,7 @@ rx.ui.flex( rx.ui.card("Card 3"), direction=rx.breakpoints(initial="column", sm="row"), justify="between", - gap="3", + spacing="3", ) ``` @@ -41,7 +43,7 @@ rx.ui.flex( rx.ui.flex( *[rx.ui.badge(f"Item {i}") for i in range(1, 13)], wrap="wrap", - gap="2", + spacing="2", style={"max_width": "320px"}, ) ``` diff --git a/docs/library/layout/grid-ui.md b/docs/library/layout/grid-ui.md index 7e17cc6cd90..c6c4bd76c55 100644 --- a/docs/library/layout/grid-ui.md +++ b/docs/library/layout/grid-ui.md @@ -18,7 +18,7 @@ import reflex as rx rx.ui.grid( *[rx.ui.card(f"Card {i}") for i in range(1, 7)], columns="3", - gap="3", + spacing="3", ) ``` @@ -28,7 +28,7 @@ rx.ui.grid( rx.ui.grid( *[rx.ui.card(f"Card {i}") for i in range(1, 9)], columns=rx.breakpoints(initial="2", sm="4"), - gap="3", + spacing="3", ) ``` @@ -39,6 +39,6 @@ rx.ui.grid( *[rx.ui.card(f"Card {i}") for i in range(1, 7)], rows="2", flow="column", - gap="3", + spacing="3", ) ``` diff --git a/docs/library/layout/inset-ui.md b/docs/library/layout/inset-ui.md index 2a9e748f73a..b79988d7166 100644 --- a/docs/library/layout/inset-ui.md +++ b/docs/library/layout/inset-ui.md @@ -15,11 +15,18 @@ import reflex as rx ```python demo rx.ui.card( rx.ui.inset( - rx.image(src="https://web.reflex-assets.dev/other/reflex_banner.png", alt="Reflex banner image", width="100%", height="auto"), + rx.image( + src="https://web.reflex-assets.dev/other/reflex_banner.png", + alt="Reflex banner image", + width="100%", + height="auto", + ), side="top", pb="current", ), - rx.ui.text("Reflex is a web framework for building full-stack apps in Python.", size="2"), + rx.ui.text( + "Reflex is a web framework for building full-stack apps in Python.", size="2" + ), style={"max_width": "320px"}, ) ``` diff --git a/docs/library/layout/separator-ui.md b/docs/library/layout/separator-ui.md index 4b1b3b76cd7..fa0f02901f0 100644 --- a/docs/library/layout/separator-ui.md +++ b/docs/library/layout/separator-ui.md @@ -18,7 +18,7 @@ rx.ui.flex( rx.ui.separator(size="4"), rx.ui.text("Below"), direction="column", - gap="3", + spacing="3", ) ``` @@ -31,7 +31,7 @@ rx.ui.flex( rx.ui.text("Docs"), rx.ui.separator(orientation="vertical"), rx.ui.text("Source"), - gap="3", + spacing="3", align="center", ) ``` diff --git a/docs/library/layout/stack-ui.md b/docs/library/layout/stack-ui.md index 3f6200d3ed9..9f670abf5e6 100644 --- a/docs/library/layout/stack-ui.md +++ b/docs/library/layout/stack-ui.md @@ -22,7 +22,7 @@ rx.ui.flex( rx.ui.vstack(rx.ui.badge("One"), rx.ui.badge("Two"), rx.ui.badge("Three")), rx.ui.hstack(rx.ui.badge("One"), rx.ui.badge("Two"), rx.ui.badge("Three")), rx.ui.stack(rx.ui.badge("One"), rx.ui.badge("Two"), direction="row-reverse"), - gap="6", + spacing="6", align="start", ) ``` diff --git a/docs/library/other/skeleton-ui.md b/docs/library/other/skeleton-ui.md index d6bb85e660b..03e754b6323 100644 --- a/docs/library/other/skeleton-ui.md +++ b/docs/library/other/skeleton-ui.md @@ -17,7 +17,7 @@ rx.ui.flex( rx.ui.skeleton(rx.ui.button("Loading"), loading=True), rx.ui.skeleton(rx.ui.button("Loaded"), loading=False), rx.ui.skeleton(style={"width": "120px", "height": "24px"}), - gap="3", + spacing="3", align="center", ) ``` diff --git a/docs/library/other/theme-ui.md b/docs/library/other/theme-ui.md index 8e074f6e6f0..626f8276fcc 100644 --- a/docs/library/other/theme-ui.md +++ b/docs/library/other/theme-ui.md @@ -20,13 +20,15 @@ leaves out is inherited. ```python demo rx.ui.flex( - rx.ui.theme(rx.ui.button("Crimson, small radius"), accent_color="crimson", radius="small"), + rx.ui.theme( + rx.ui.button("Crimson, small radius"), accent_color="crimson", radius="small" + ), rx.ui.theme(rx.ui.button("Teal, full radius"), accent_color="teal", radius="full"), rx.ui.theme( rx.ui.card(rx.ui.text("Dark"), style={"padding": "12px"}), appearance="dark", ), - gap="3", + spacing="3", align="center", ) ``` @@ -42,7 +44,7 @@ rx.ui.flex( rx.ui.color_mode.button(), rx.ui.color_mode.switch(), rx.ui.color_mode.icon(), - gap="4", + spacing="4", align="center", ) ``` diff --git a/docs/library/overlay/alert_dialog-ui.md b/docs/library/overlay/alert_dialog-ui.md index 4f5dd5a277f..b2fa6274891 100644 --- a/docs/library/overlay/alert_dialog-ui.md +++ b/docs/library/overlay/alert_dialog-ui.md @@ -27,9 +27,13 @@ rx.ui.alert_dialog.root( "Are you sure? This application will no longer be accessible and any existing sessions will be expired.", ), rx.ui.flex( - rx.ui.alert_dialog.cancel(rx.ui.button("Cancel", variant="soft", color_scheme="gray")), - rx.ui.alert_dialog.action(rx.ui.button("Revoke access", color_scheme="red")), - gap="3", + rx.ui.alert_dialog.cancel( + rx.ui.button("Cancel", variant="soft", color_scheme="gray") + ), + rx.ui.alert_dialog.action( + rx.ui.button("Revoke access", color_scheme="red") + ), + spacing="3", justify="end", style={"margin_top": "16px"}, ), diff --git a/docs/library/overlay/dialog-ui.md b/docs/library/overlay/dialog-ui.md index 381268eee20..b5d2649b797 100644 --- a/docs/library/overlay/dialog-ui.md +++ b/docs/library/overlay/dialog-ui.md @@ -22,9 +22,13 @@ rx.ui.dialog.root( rx.ui.dialog.trigger(rx.ui.button("Open Dialog")), rx.ui.dialog.content( rx.ui.dialog.title("Welcome to Reflex!"), - rx.ui.dialog.description("This is a dialog component. You can render anything you want in here."), + rx.ui.dialog.description( + "This is a dialog component. You can render anything you want in here." + ), rx.ui.flex( - rx.ui.dialog.close(rx.ui.button("Close", variant="soft", color_scheme="gray")), + rx.ui.dialog.close( + rx.ui.button("Close", variant="soft", color_scheme="gray") + ), justify="end", style={"margin_top": "16px"}, ), @@ -63,7 +67,7 @@ def ui_controlled_dialog(): open=UIDialogState.open, on_open_change=UIDialogState.set_open, ), - gap="3", + spacing="3", align="center", ) ``` diff --git a/docs/library/overlay/drawer-ui.md b/docs/library/overlay/drawer-ui.md index 3d69e5c938e..94a07078386 100644 --- a/docs/library/overlay/drawer-ui.md +++ b/docs/library/overlay/drawer-ui.md @@ -31,7 +31,7 @@ rx.ui.drawer.root( rx.ui.drawer.description("A drawer from the right edge."), rx.ui.drawer.close(rx.ui.button("Close", variant="soft")), direction="column", - gap="3", + spacing="3", align="start", ), style={ diff --git a/docs/library/overlay/dropdown_menu-ui.md b/docs/library/overlay/dropdown_menu-ui.md index c62cafd2419..43bbe673b36 100644 --- a/docs/library/overlay/dropdown_menu-ui.md +++ b/docs/library/overlay/dropdown_menu-ui.md @@ -61,7 +61,7 @@ def ui_menu_events(): ), ), rx.ui.text("Chose: ", rx.ui.code(UIMenuState.last)), - gap="3", + spacing="3", align="center", ) ``` diff --git a/docs/library/overlay/hover_card-ui.md b/docs/library/overlay/hover_card-ui.md index ea6cdc492a6..6a7f0bd0dc2 100644 --- a/docs/library/overlay/hover_card-ui.md +++ b/docs/library/overlay/hover_card-ui.md @@ -18,7 +18,11 @@ import reflex as rx rx.ui.flex( rx.ui.text("Hover over the link to see the card:"), rx.ui.hover_card.root( - rx.ui.hover_card.trigger(rx.ui.link("@reflex_dev", href="https://github.com/reflex-dev", color_scheme="blue")), + rx.ui.hover_card.trigger( + rx.ui.link( + "@reflex_dev", href="https://github.com/reflex-dev", color_scheme="blue" + ) + ), rx.ui.hover_card.content( rx.ui.flex( rx.ui.avatar(fallback="RX", radius="full"), @@ -26,11 +30,11 @@ rx.ui.flex( rx.ui.text("Reflex", size="3", weight="bold", as_="div"), rx.ui.text("Web apps in pure Python.", size="2"), ), - gap="3", + spacing="3", ), ), ), - gap="2", + spacing="2", align="center", ) ``` diff --git a/docs/library/overlay/popover-ui.md b/docs/library/overlay/popover-ui.md index dc926e74c61..36a65833445 100644 --- a/docs/library/overlay/popover-ui.md +++ b/docs/library/overlay/popover-ui.md @@ -26,7 +26,7 @@ rx.ui.popover.root( justify="end", ), direction="column", - gap="3", + spacing="3", ), style={"width": "300px"}, ), @@ -44,6 +44,6 @@ rx.ui.flex( ) for side in ["top", "right", "bottom", "left"] ], - gap="3", + spacing="3", ) ``` diff --git a/docs/library/overlay/tooltip-ui.md b/docs/library/overlay/tooltip-ui.md index c6262ee6c2b..7b350992d53 100644 --- a/docs/library/overlay/tooltip-ui.md +++ b/docs/library/overlay/tooltip-ui.md @@ -24,9 +24,11 @@ rx.ui.tooltip( ```python demo rx.ui.flex( *[ - rx.ui.tooltip(rx.ui.button(side, variant="outline"), content=f"On the {side}", side=side) + rx.ui.tooltip( + rx.ui.button(side, variant="outline"), content=f"On the {side}", side=side + ) for side in ["top", "right", "bottom", "left"] ], - gap="3", + spacing="3", ) ``` diff --git a/docs/library/typography/blockquote-ui.md b/docs/library/typography/blockquote-ui.md index 2f96b50eeee..43548eeada0 100644 --- a/docs/library/typography/blockquote-ui.md +++ b/docs/library/typography/blockquote-ui.md @@ -24,6 +24,6 @@ rx.ui.flex( rx.ui.blockquote("Size 5", size="5"), rx.ui.blockquote("Cyan", color_scheme="cyan"), direction="column", - gap="3", + spacing="3", ) ``` diff --git a/docs/library/typography/code-ui.md b/docs/library/typography/code-ui.md index f610363c1ae..38fa47dd02e 100644 --- a/docs/library/typography/code-ui.md +++ b/docs/library/typography/code-ui.md @@ -24,6 +24,6 @@ rx.ui.flex( rx.ui.code("soft", variant="soft"), rx.ui.code("outline", variant="outline"), rx.ui.code("ghost", variant="ghost"), - gap="3", + spacing="3", ) ``` diff --git a/docs/library/typography/heading-ui.md b/docs/library/typography/heading-ui.md index 67f6229117f..14fd1c3ddfb 100644 --- a/docs/library/typography/heading-ui.md +++ b/docs/library/typography/heading-ui.md @@ -24,6 +24,6 @@ rx.ui.flex( rx.ui.heading("Size 6", size="6", as_="h3"), rx.ui.heading("Size 8, light", size="8", weight="light", as_="h3"), direction="column", - gap="2", + spacing="2", ) ``` diff --git a/docs/library/typography/link-ui.md b/docs/library/typography/link-ui.md index f9d094a881a..17b3bc5ea07 100644 --- a/docs/library/typography/link-ui.md +++ b/docs/library/typography/link-ui.md @@ -16,7 +16,7 @@ import reflex as rx rx.ui.flex( rx.ui.link("Reflex docs", href="/getting-started/introduction/"), rx.ui.link("GitHub", href="https://github.com/reflex-dev/reflex", is_external=True), - gap="4", + spacing="4", ) ``` @@ -28,6 +28,6 @@ rx.ui.flex( rx.ui.link("Hover", href="#underline-and-color", underline="hover"), rx.ui.link("Always", href="#underline-and-color", underline="always"), rx.ui.link("Crimson", href="#underline-and-color", color_scheme="crimson"), - gap="4", + spacing="4", ) ``` diff --git a/docs/library/typography/text-ui.md b/docs/library/typography/text-ui.md index df789de0eb4..a822a527d32 100644 --- a/docs/library/typography/text-ui.md +++ b/docs/library/typography/text-ui.md @@ -29,7 +29,7 @@ rx.ui.flex( rx.ui.text("A div.", as_="div"), rx.ui.text("A label.", as_="label"), direction="column", - gap="2", + spacing="2", ) ``` @@ -48,7 +48,7 @@ rx.ui.flex( rx.ui.text("Crimson", color_scheme="crimson"), rx.ui.text("Gray, high contrast", color_scheme="gray", high_contrast=True), direction="column", - gap="1", + spacing="1", ) ``` diff --git a/docs/rx_ui/overview.md b/docs/rx_ui/overview.md index dc2dc5f3c93..bdf5c5684f2 100644 --- a/docs/rx_ui/overview.md +++ b/docs/rx_ui/overview.md @@ -114,7 +114,11 @@ Each library page that has an `rx.ui` version has an **rx.ui** tab beside the rx.el.ul( *( rx.el.li( - rx.el.a(title, href=route, class_name="docs-text-link underline underline-offset-4"), + rx.el.a( + title, + href=route, + class_name="docs-text-link underline underline-offset-4", + ), ": ", ", ".join(name for _, name in components), class_name="mb-1 text-sm leading-6 text-secondary-11", diff --git a/docs/rx_ui/styling.md b/docs/rx_ui/styling.md index a9b1c074d93..86b89738c32 100644 --- a/docs/rx_ui/styling.md +++ b/docs/rx_ui/styling.md @@ -25,7 +25,7 @@ order, the last one winning a property: 1. the component's base styles, 2. the styles of its props (`variant`, `size`, `color_scheme`, ...), -3. layout props such as `gap`, `p` and `direction`, where the component takes them, +3. layout props such as `spacing`, `columns` and `direction`, where the component takes them, 4. the keyword styles and `style` you pass. Your style is always last, so it wins over the component's own. The merged @@ -193,9 +193,15 @@ class UIStyleState(rx.State): def ui_state_styles(): return rx.ui.flex( - rx.ui.button("Grow", on_click=UIStyleState.grow, style={"width": UIStyleState.width}), - rx.ui.button(f"Variant: {UIStyleState.variant}", variant=UIStyleState.variant, on_click=UIStyleState.cycle), - gap="3", + rx.ui.button( + "Grow", on_click=UIStyleState.grow, style={"width": UIStyleState.width} + ), + rx.ui.button( + f"Variant: {UIStyleState.variant}", + variant=UIStyleState.variant, + on_click=UIStyleState.cycle, + ), + spacing="3", align="center", ) ``` @@ -228,6 +234,13 @@ Set `animation_name` and the other longhands. The frames are declared with several layers or positions, or one bound to state, must name the longhands: `background_color`, `background_image`, `background_position`, ... +# Lengths without a unit +`gap="3"` or `width="100"` as a style. `rx` passes the number on to CSS, where +the browser drops it, so `rx.flex(gap="3")` has no gap. `rx.ui` refuses it: write +`gap="3px"`, the step of the space scale `gap=rx.ui.tokens.space[3]`, or the +prop Radix declares for it, `spacing="3"`. Zero, and the properties that take a +plain number such as `line_height`, `opacity`, `z_index` and `flex`, are fine. + # Spacing shorthands of Radix Themes as CSS keys `m`, `mx`, `my`, `mt`, `mr`, `mb`, `ml`, `p`, `px`, `py`, `pt`, `pr`, `pb` and `pl` on a component that does not declare them. `rx` passes them on as CSS keys, diff --git a/docs/rx_ui/theming.md b/docs/rx_ui/theming.md index 291ee4e8f79..b2a9d8ac64a 100644 --- a/docs/rx_ui/theming.md +++ b/docs/rx_ui/theming.md @@ -73,7 +73,7 @@ rx.ui.flex( rx.ui.card(rx.ui.text("A dark card"), style={"padding": "12px"}), appearance="dark", ), - gap="3", + spacing="3", align="center", ) ``` @@ -104,11 +104,13 @@ def ui_theme_switcher(): return rx.ui.theme( rx.ui.flex( *[ - rx.ui.button(color, variant="soft", on_click=UIThemeState.set_accent(color)) + rx.ui.button( + color, variant="soft", on_click=UIThemeState.set_accent(color) + ) for color in ["violet", "jade", "amber", "crimson"] ], rx.ui.badge(UIThemeState.accent, variant="solid"), - gap="2", + spacing="2", align="center", wrap="wrap", ), @@ -127,7 +129,7 @@ rx.ui.flex( rx.ui.badge("Cyan", color_scheme="cyan"), rx.ui.badge("Orange", color_scheme="orange"), rx.ui.badge("Gray", color_scheme="gray"), - gap="2", + spacing="2", ) ``` @@ -189,13 +191,15 @@ rx.ui.grid( "font_size": rx.ui.tokens.font_size[1], "border_radius": rx.ui.tokens.radius[2], "background_color": rx.ui.tokens.accent[step], - "color": rx.ui.tokens.gray[12] if step < 9 else rx.ui.tokens.accent.contrast, + "color": rx.ui.tokens.gray[12] + if step < 9 + else rx.ui.tokens.accent.contrast, }, ) for step in range(1, 13) ], columns="6", - gap="2", + spacing="2", ) ``` From 8c58a899b080c02af3a5c285e14b433ca2c1beb9 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 06:39:21 +0000 Subject: [PATCH 176/204] Compile refs imported from state.js beside refs from refs.js Packages published before refs and useRegisteredRef moved to utils/refs.js import them from utils/state.js, and a module that also imported them from utils/refs.js failed to compile: the tag was used from two libraries. Each generated module now imports both names from utils/refs.js, so one that needs only refs still loads no event runtime. A dynamic component that renders an element with an id read its ref hook from window.__reflex['$/utils/refs'], which no app root provided: the registry of refs is now a default window library. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- news/+refs-from-state.bugfix.md | 1 + ...-root-without-event-runtime.performance.md | 2 +- .../reflex-base/src/reflex_base/registry.py | 1 + reflex/compiler/utils.py | 38 ++++++++++- tests/units/compiler/test_compiler.py | 65 ++++++++++++++++++- tests/units/compiler/test_compiler_utils.py | 1 + .../test_dynamic_components_codegen.py | 37 +++++++++++ tests/units/test_app.py | 1 + 8 files changed, 143 insertions(+), 3 deletions(-) create mode 100644 news/+refs-from-state.bugfix.md diff --git a/news/+refs-from-state.bugfix.md b/news/+refs-from-state.bugfix.md new file mode 100644 index 00000000000..949f638cd4c --- /dev/null +++ b/news/+refs-from-state.bugfix.md @@ -0,0 +1 @@ +Components that import `refs` or `useRegisteredRef` from `$/utils/state`, as packages published before they moved to `$/utils/refs` do, compile next to code importing them from `$/utils/refs`: a module imports them once, from `$/utils/refs`. diff --git a/packages/reflex-base/news/+stateless-root-without-event-runtime.performance.md b/packages/reflex-base/news/+stateless-root-without-event-runtime.performance.md index 7ed285ce70b..2d64d7ef3ab 100644 --- a/packages/reflex-base/news/+stateless-root-without-event-runtime.performance.md +++ b/packages/reflex-base/news/+stateless-root-without-event-runtime.performance.md @@ -1 +1 @@ -The compiled context module of an app without state no longer imports `utils/state.js`: its event loop is the one in `utils/event_loop.js`, and the registry of refs lives in `utils/refs.js` (still re-exported by `utils/state.js`), so registering the ref of an element with an id no longer loads the event runtime. A component rendered as a value no longer imports `pyOr` unless its code calls it. +The compiled context module of an app without state no longer imports `utils/state.js`: its event loop is the one in `utils/event_loop.js`, and the registry of refs lives in `utils/refs.js` (still re-exported by `utils/state.js`), so registering the ref of an element with an id no longer loads the event runtime. A component rendered as a value no longer imports `pyOr` unless its code calls it. A dynamic component reads the registry of refs from `window.__reflex["$/utils/refs"]`. diff --git a/packages/reflex-base/src/reflex_base/registry.py b/packages/reflex-base/src/reflex_base/registry.py index 45c3877cf35..0c49b54980c 100644 --- a/packages/reflex-base/src/reflex_base/registry.py +++ b/packages/reflex-base/src/reflex_base/registry.py @@ -34,6 +34,7 @@ def _default_bundled_libraries() -> list[str]: f"$/{constants.Dirs.CONTEXTS_PATH}", f"$/{constants.Dirs.UTILS}/context-registry", f"$/{constants.Dirs.STATE_PATH}", + f"$/{constants.Dirs.REFS_PATH}", ] diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index c27e015b185..7b1a5825be1 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -126,6 +126,40 @@ def validate_imports(import_dict: ParsedImportDict): used_tags[import_name] = lib +# Names state.js re-exports from refs.js, where they moved: code published +# before the move imports them from state.js. +_MOVED_TO_REFS = frozenset(("refs", "useRegisteredRef")) +_STATE_LIB = f"$/{constants.Dirs.STATE_PATH}" +_REFS_LIB = f"$/{constants.Dirs.REFS_PATH}" + + +def _import_moved_names_from_refs(import_dict: ParsedImportDict) -> ParsedImportDict: + """Import the names that moved from state.js to refs.js from refs.js. + + Either spelling names the same export, so a module imports it once, and one + that needs only refs loads no event runtime. + + Args: + import_dict: The collapsed imports of a module. + + Returns: + The imports, with the moved names of state.js imported from refs.js. + """ + state = import_dict.get(_STATE_LIB) + if not state or not any(field.tag in _MOVED_TO_REFS for field in state): + return import_dict + moved = [field for field in state if field.tag in _MOVED_TO_REFS] + import_dict = dict(import_dict) + if kept := [field for field in state if field.tag not in _MOVED_TO_REFS]: + import_dict[_STATE_LIB] = kept + else: + del import_dict[_STATE_LIB] + import_dict[_REFS_LIB] = list( + dict.fromkeys((*import_dict.get(_REFS_LIB, ()), *moved)) + ) + return import_dict + + class _ImportDict(TypedDict): lib: str default: str @@ -144,7 +178,9 @@ def compile_imports(import_dict: ParsedImportDict) -> list[_ImportDict]: Raises: ValueError: If an import in the dict is invalid. """ - collapsed_import_dict: ParsedImportDict = imports.collapse_imports(import_dict) + collapsed_import_dict = _import_moved_names_from_refs( + imports.collapse_imports(import_dict) + ) validate_imports(collapsed_import_dict) import_dicts: list[_ImportDict] = [] for lib, fields in collapsed_import_dict.items(): diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 08f29db0f9c..9d3da9df03e 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -34,7 +34,7 @@ RouteValueError, ) from reflex_base.utils.imports import ImportVar, ParsedImportDict -from reflex_base.vars.base import Var +from reflex_base.vars.base import Var, VarData from reflex_base.vars.sequence import LiteralStringVar from reflex_components_core.base import Description, document from reflex_components_core.base.document import Links, Scripts @@ -789,6 +789,7 @@ def test_compile_app_root_includes_radix_window_library_when_bundled(mocker): import * as utils_context from "$/utils/context"; import * as utils_context_registry from "$/utils/context-registry"; import * as utils_state from "$/utils/state"; +import * as utils_refs from "$/utils/refs"; """ _APP_ROOT_TAIL = """ @@ -834,6 +835,7 @@ def test_compile_app_root_includes_radix_window_library_when_bundled(mocker): "$/utils/context": utils_context, "$/utils/context-registry": utils_context_registry, "$/utils/state": utils_state, + "$/utils/refs": utils_refs, }; }, []); """ @@ -859,6 +861,7 @@ def _app_root_with_loaders(*loaders: str) -> str: "$/utils/context": utils_context, "$/utils/context-registry": utils_context_registry, "$/utils/state": utils_state, + "$/utils/refs": utils_refs, }; const loaders = { """ @@ -3370,3 +3373,63 @@ def render(imports: dict[str, list[ImportVar]]) -> str: ), {"$/utils/state": [ImportVar(tag="isTrue")], "react": [ImportVar(tag="memo")]}, ) + + +class _LegacyRefs(rx.Fragment): + """A component published before refs moved, importing them from state.js.""" + + def add_imports(self) -> dict[str, list[str]]: + """Import the registry of refs from where it used to live. + + Returns: + The imports. + """ + return {f"$/{constants.Dirs.STATE_PATH}": ["refs", "useRegisteredRef"]} + + +def _reads_refs() -> Component: + """Build a tree mixing refs imported from both modules. + + Returns: + An element whose id registers a ref, the legacy component, and text + reading a ref through a Var, which imports refs from utils/refs.js. + """ + ref = Var( + _js_expr='refs["ref_docs"]?.current?.id', + _var_type=str, + _var_data=VarData(imports={f"$/{constants.Dirs.REFS_PATH}": ["refs"]}), + ) + return rx.fragment( + rx.el.section("Docs", id="docs"), _LegacyRefs.create(), rx.el.span(ref) + ) + + +def test_refs_imported_from_state_and_refs_compile_as_one_import( + compile_page, preserve_memo_registries: None +): + """Code importing refs from state.js, as published packages do, mixes with refs.js. + + Both spellings name the same export, so a page and a memo module import it + once, from utils/refs.js, and a page that reads only refs loads no state.js. + """ + + @rx.memo + def legacy_refs_memo() -> rx.Component: + return _reads_refs() + + page = compile_page(lambda: rx.el.div(_reads_refs(), legacy_refs_memo())) + assert _module_imports(page.compiled_pages["/"].output_code) == [ + 'import {refs,useRegisteredRef} from "$/utils/refs"', + REACT_JSX, + ( + "import {LegacyRefsMemo_} " + 'from "$/app_components/tests/units/compiler/test_compiler"' + ), + ] + ((_, memo_module),) = compiler.compile_memo_components(( + next(d for d in MEMOS.values() if d.python_name == "legacy_refs_memo"), + ))[0] + assert _module_imports(memo_module) == [ + REACT_JSX_MEMO, + 'import {refs,useRegisteredRef} from "$/utils/refs"', + ] diff --git a/tests/units/compiler/test_compiler_utils.py b/tests/units/compiler/test_compiler_utils.py index 5e2b83b4d17..2ee54d89969 100644 --- a/tests/units/compiler/test_compiler_utils.py +++ b/tests/units/compiler/test_compiler_utils.py @@ -458,6 +458,7 @@ def test_bundled_libraries_artifact_round_trip( "$/utils/context", f"$/{constants.Dirs.UTILS}/context-registry", "$/utils/state", + "$/utils/refs", "@radix-ui/themes", ] diff --git a/tests/units/compiler/test_dynamic_components_codegen.py b/tests/units/compiler/test_dynamic_components_codegen.py index 69c7ede08ac..1c959c1a771 100644 --- a/tests/units/compiler/test_dynamic_components_codegen.py +++ b/tests/units/compiler/test_dynamic_components_codegen.py @@ -588,3 +588,40 @@ def counter_ui(self) -> rx.Component: assert '({ ["count"] : -1 }), ({ })' in code assert '({ ["count"] : 1 }), ({ })' in code assert 'jsx(RadixThemesText, ({as:"p",size:"9"}), 0)' in code + + +def test_dynamic_component_reads_the_registry_of_refs_from_the_window(mocker) -> None: + """A dynamic element with an id registers its ref through a default library. + + Every app root puts the default libraries in window.__reflex, so the + component lists nothing to load and its ref hook is always defined. + """ + mocker.patch( + "reflex_base.config._get_config", + return_value=rx.Config( + app_name="dynamic_refs", frontend_lazy_bundled_libraries=True + ), + ) + with RegistrationContext(): + code = serializers.serialize(rx.el.section("Docs", id="docs")) + _, app_root_code = compiler.compile_app_root(rx.el.div()) + assert code == ( + "//__reflex_evaluate:[]\n" + "const React = window.__reflex.react;\n" + "\n" + "const {Fragment,createElement: jsx,useEffect} = window.__reflex['react']\n" + "const {useRegisteredRef} = window.__reflex['$/utils/refs']\n" + "\n" + "export default function MySSRComponent () {\n" + ' const ref_docs = useRegisteredRef("ref_docs");\n' + " return (\n" + ' (jsx("section", ({id:"docs",ref:ref_docs}), "Docs"))\n' + " )\n" + "}" + ) + assert app_root_loaders(app_root_code) == [ + loader("@emotion/react", "emotion_react") + ] + assert [ + line.strip() for line in app_root_code.splitlines() if "utils_refs" in line + ] == ['import * as utils_refs from "$/utils/refs";', '"$/utils/refs": utils_refs,'] diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 981c914f89e..fd1522a39f7 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -3385,6 +3385,7 @@ def test_event_provider_app_wrap_order(mocker: MockerFixture) -> None: 'import * as utils_context from "$/utils/context";', 'import * as utils_context_registry from "$/utils/context-registry";', 'import * as utils_state from "$/utils/state";', + 'import * as utils_refs from "$/utils/refs";', ] From 6caec6af549389390d48919a55296fae1d1848a1 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 06:39:38 +0000 Subject: [PATCH 177/204] Render the popover attributes of rx.ui as React names them, and key popup roots The triggers of popovers, menus and selects passed popovertarget and popovertargetaction, which React 19 renders but reports as invalid DOM properties in development. They pass popoverTarget and popoverTargetAction. No other attribute rx.ui renders is one React spells differently. The root of a popover, menu or hover card renders a fragment and dropped every prop, the key rx.foreach gives it included, so React warned about a list without keys. The parity contracts check that a page hydrates without warnings, but on the production build, where React strips them. Each page of the shared Playwright app is now loaded in dev and prod and must log no warning or error but the one its broken avatar means. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../news/+react-warnings.bugfix.md | 1 + .../reflex_components_ui/components/_popup.py | 12 +- .../reflex_components_ui/components/select.py | 2 +- .../tests_playwright/test_ui_components.py | 105 ++++++++++++++++++ .../components/test_color_mode.py | 2 +- .../components/test_dropdown_menu.py | 2 +- .../components/test_popover.py | 8 +- .../components/test_popup.py | 35 ++++++ .../components/test_select.py | 6 +- 9 files changed, 159 insertions(+), 14 deletions(-) create mode 100644 packages/reflex-components-ui/news/+react-warnings.bugfix.md create mode 100644 tests/units/reflex_components_ui/components/test_popup.py diff --git a/packages/reflex-components-ui/news/+react-warnings.bugfix.md b/packages/reflex-components-ui/news/+react-warnings.bugfix.md new file mode 100644 index 00000000000..cf80009aee1 --- /dev/null +++ b/packages/reflex-components-ui/news/+react-warnings.bugfix.md @@ -0,0 +1 @@ +Popovers, menus and selects no longer make React log `Invalid DOM property popovertarget` in development, and a popover, menu or hover card rendered by `rx.foreach` keeps the key React asks each item of a list for. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py index 47210ed8ea3..ec6febb79cf 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py @@ -111,9 +111,13 @@ def _exclude_props(self) -> list[str]: """Keep the props that are the ones of the popup off the root. Returns: - Every prop: the root renders no element. + Every prop but the key, which a fragment takes: the root renders + no element. """ - return [*super()._exclude_props(), *self.get_fields()] + return [ + *super()._exclude_props(), + *(name for name in self.get_fields() if name != "key"), + ] class PopupPart(UIComponent): @@ -197,7 +201,7 @@ def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: name: The id of the popup. on_open_change: What the popup does when it opens or closes. """ - self._popup = {"popovertarget": name, "aria-controls": name} + self._popup = {"popoverTarget": name, "aria-controls": name} def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the trigger. @@ -232,7 +236,7 @@ def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: name: The id of the popup. on_open_change: What the popup does when it opens or closes. """ - self._popup = {"popovertarget": name, "popovertargetaction": "hide"} + self._popup = {"popoverTarget": name, "popoverTargetAction": "hide"} def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the button. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/select.py b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py index 240a8d4b358..1abdbc653bb 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/select.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py @@ -508,7 +508,7 @@ def _join( items: The options of the select. """ self._size = select.size - attributes: dict[str, Any] = {"popovertarget": popup, "aria-controls": popup} + attributes: dict[str, Any] = {"popoverTarget": popup, "aria-controls": popup} if select.disabled is not None: attributes["disabled"] = select.disabled if not self.children[0].children: diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 233b211ea1d..3589f6bdb27 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -42,6 +42,9 @@ LITERAL_STYLE = '"paddingTop": "6px"' CHANGED_STYLE = '"paddingTop": "7px"' +# The image of the broken avatar on the actions page, which no app serves. +MISSING_IMAGE = "/missing.png" + # The elements of the styled page below the first breakpoint, before any event. STYLED = { # A width bound to state. @@ -2127,3 +2130,105 @@ def test_theme_panel_and_color_mode_controls_work_in_an_app( expect(panel).to_have_attribute("inert", "") page.keyboard.press("t") expect(panel).not_to_have_attribute("inert", "") + + +# Resolves once React has attached its props to the elements of the page, and +# then two frames later, once the root committed and its effects ran. +SETTLED = """async () => { + while (!document.querySelector("body *") || + !Object.keys(document.querySelector("body *")).some( + (key) => key.startsWith("__reactProps$"))) { + await new Promise((resolve) => setTimeout(resolve, 50)); + } + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(resolve))); +}""" + + +def _console_problems(harness: AppHarness, page: Page, route: str) -> list[str]: + """Load a page of the app and collect what it reports as a problem. + + Args: + harness: The running harness. + page: The page to navigate. + route: The route of the page. + + Returns: + Every console warning and error, and every uncaught exception, the + page reported while it loaded and hydrated. + """ + assert harness.frontend_url is not None + problems: list[str] = [] + page.on( + "console", + lambda message: ( + problems.append( + f"console {message.type}: {message.text} at {message.location['url']}" + ) + if message.type in ("warning", "error") + else None + ), + ) + page.on("pageerror", lambda error: problems.append(f"error: {error}")) + page.route(f"**{SWEEP_SCRIPTS}*", _serve_sweep_script) + # The image of the broken avatar is missing in dev and in prod alike. + page.route(f"**{MISSING_IMAGE}", lambda route: route.fulfill(status=404)) + page.goto(harness.frontend_url.rstrip("/") + route) + page.wait_for_load_state("networkidle") + page.evaluate(SETTLED) + return problems + + +@pytest.mark.parametrize( + "route", + [ + "/", + "/wave", + "/actions", + "/controls", + "/overlays", + "/panel", + "/literal", + "/styled", + "/theme", + "/sweep", + ], +) +def test_pages_report_no_problem(ui_app: AppHarness, page: Page, route: str): + """No page logs a warning or an error: in dev, React reports what it rejects. + + The parity contracts check the same of the production build, where React + strips its warnings, so an attribute React does not know passes there. + The broken avatar's image is the one failure a page means. + + Args: + ui_app: The running harness. + page: The page to navigate. + route: The route of the page. + """ + assert ui_app.frontend_url is not None + image = ui_app.frontend_url.rstrip("/") + MISSING_IMAGE + assert _console_problems(ui_app, page, route) == ( + [ + ( + "console error: Failed to load resource: the server responded " + f"with a status of 404 (Not Found) at {image}" + ) + ] + if route == "/actions" + else [] + ) + + +@pytest.mark.parametrize("route", ["/mixed", "/bound"]) +def test_pages_beside_radix_themes_report_no_problem( + mixed_app: AppHarness, page: Page, route: str +): + """No page of the app beside Radix Themes logs a warning or an error. + + Args: + mixed_app: The running harness. + page: The page to navigate. + route: The route of the page. + """ + assert _console_problems(mixed_app, page, route) == [] diff --git a/tests/units/reflex_components_ui/components/test_color_mode.py b/tests/units/reflex_components_ui/components/test_color_mode.py index cc35edef449..b8f278a0d3a 100644 --- a/tests/units/reflex_components_ui/components/test_color_mode.py +++ b/tests/units/reflex_components_ui/components/test_color_mode.py @@ -167,7 +167,7 @@ def test_button_that_allows_the_system_mode_opens_a_menu( "className:sx_4aef8418fd_c", '"data-state":"closed"', "onKeyDown:menuTrigger", - 'popovertarget:"rx-dropdown-menu-1"', + 'popoverTarget:"rx-dropdown-menu-1"', ], "children": [ICON], } diff --git a/tests/units/reflex_components_ui/components/test_dropdown_menu.py b/tests/units/reflex_components_ui/components/test_dropdown_menu.py index 99388c3f902..e4f3f865df4 100644 --- a/tests/units/reflex_components_ui/components/test_dropdown_menu.py +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -50,7 +50,7 @@ def test_dropdown_menu(ui_plugin: UIPlugin): '"aria-haspopup":"menu"', '"data-state":"closed"', "onKeyDown:menuTrigger", - 'popovertarget:"rx-dropdown-menu-2"', + 'popoverTarget:"rx-dropdown-menu-2"', ], "children": [{"contents": '"Options"'}], }, diff --git a/tests/units/reflex_components_ui/components/test_popover.py b/tests/units/reflex_components_ui/components/test_popover.py index b43214519d4..52c5be1d031 100644 --- a/tests/units/reflex_components_ui/components/test_popover.py +++ b/tests/units/reflex_components_ui/components/test_popover.py @@ -53,7 +53,7 @@ def test_popover( '"aria-haspopup":"dialog"', '"data-state":"closed"', 'id:"open"', - 'popovertarget:"rx-popover-1"', + 'popoverTarget:"rx-popover-1"', "ref:ref_open", ], "children": [{"contents": '"Open"'}], @@ -80,8 +80,8 @@ def test_popover( { "name": '"button"', "props": [ - 'popovertarget:"rx-popover-1"', - 'popovertargetaction:"hide"', + 'popoverTarget:"rx-popover-1"', + 'popoverTargetAction:"hide"', ], "children": [{"contents": '"Close"'}], }, @@ -188,7 +188,7 @@ def test_popover_with_an_id(ui_plugin: UIPlugin): '"aria-expanded":false', '"aria-haspopup":"dialog"', '"data-state":"closed"', - 'popovertarget:"panel"', + 'popoverTarget:"panel"', ], "children": [{"contents": '"Open"'}], }, diff --git a/tests/units/reflex_components_ui/components/test_popup.py b/tests/units/reflex_components_ui/components/test_popup.py new file mode 100644 index 00000000000..22c02f76ba8 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_popup.py @@ -0,0 +1,35 @@ +"""Tests for the roots of the popups, which render no element of their own.""" + +from collections.abc import Callable + +import pytest +from reflex_base.components.component import Component +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx + + +@pytest.mark.parametrize( + "root", + [ + rx.ui.popover.root, + rx.ui.dropdown_menu.root, + rx.ui.dropdown_menu.sub, + rx.ui.context_menu.root, + rx.ui.hover_card.root, + ], +) +def test_a_popup_in_a_list_keeps_its_key( + root: Callable[..., Component], ui_plugin: UIPlugin +): + """The fragment of a popup carries its key: ``rx.foreach`` keys each item by it. + + Args: + root: The root of a popup. + ui_plugin: The configured plugin. + """ + component = root(rx.el.span("a"), key="a") + assert (component.render()["name"], component.render()["props"]) == ( + "Fragment", + ['key:"a"'], + ) diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index 5fa32a62c0b..cb163c3b334 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -115,7 +115,7 @@ def test_select( '"data-state":"closed"', "disabled:true", 'id:"pick"', - 'popovertarget:"rx-select-2"', + 'popoverTarget:"rx-select-2"', "ref:ref_pick", 'role:"combobox"', 'type:"button"', @@ -762,7 +762,7 @@ def test_select_of_a_list( 'className:sx_476d055388_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', '"data-state":"closed"', 'id:"count"', - 'popovertarget:"rx-select-2"', + 'popoverTarget:"rx-select-2"', "ref:ref_count", 'role:"combobox"', 'type:"button"', @@ -1470,7 +1470,7 @@ def test_select_bound_to_state(ui_plugin: UIPlugin): "className:sx_872142009a_c", f'"data-placeholder":({fruit} ? undefined : "")', '"data-state":"closed"', - 'popovertarget:"rx-select-1"', + 'popoverTarget:"rx-select-1"', 'role:"combobox"', 'type:"button"', ] From a15c8e8561e203c583d911cbb12f01471cf404da Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 06:49:06 +0000 Subject: [PATCH 178/204] Refuse the children of rx.ui.switch, which crashed the page rx.ui.switch is a native input, and React refuses a child of one with an error that takes the page down, so rx.ui.switch("Sync settings") left a blank page. rx.switch renders the button of Radix, which drops the text. The switch and the color mode switch now fail to compile and name the label to put the text in, which the shared app's form now uses; the difference is recorded as a children entry of the allowlist. Every other rx.ui component either renders a text child where its element takes one or refuses it while compiling, which a test over each now holds. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- docs/styling/rx-ui-migration.md | 5 ++ .../news/+switch-children.bugfix.md | 1 + .../parity/allowlist.toml | 12 +++ .../parity/ui_parity/allowlist.py | 10 ++- .../parity/ui_parity/api.py | 4 +- .../components/checkbox.py | 37 ++++++++- .../reflex_components_ui/components/switch.py | 2 + .../tests_playwright/test_ui_components.py | 11 ++- .../components/test_switch.py | 21 +++++ .../parity/test_allowlist.py | 6 +- .../reflex_components_ui/test_api_parity.py | 77 +++++++++++++++++++ 11 files changed, 176 insertions(+), 10 deletions(-) create mode 100644 packages/reflex-components-ui/news/+switch-children.bugfix.md diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index 3f3d9727768..3bdba7b0af6 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -188,6 +188,10 @@ counterpart, kept in sync with the parity checks of `rx.ui`: - a11y, *: A checked item of rx.checkbox_group holds its check as an image without a name. An item of rx.ui.checkbox_group is one native input: its check is drawn by its styles and is nothing to the accessibility tree. - style, `background-color`, `vertical-align`, `overflow-x`, `overflow-y`: The check of rx.checkbox_group is an icon, an svg element drawn in its color. The check of rx.ui.checkbox_group is drawn by the checkbox itself: a box of the size and the color of the icon, cut to its shape by a mask. It paints the same. +### color_mode.switch + +- children `*children`: rx.color_mode.switch drops its children, as rx.switch does. rx.ui.color_mode.switch is a native input, which takes none, so it refuses them and names the label to put the text in. + ### context_menu - style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.context_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. @@ -290,6 +294,7 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### switch +- children `*children`: rx.switch("Sync settings") renders a switch without its text: the button of Radix drops its children. rx.ui.switch is a native input, which takes none, so it refuses them and names the label to put the text in: rx.ui.text(rx.ui.flex(rx.ui.switch(), "Sync settings", spacing="2"), as_="label"). - behaviour, `rx`, "is turned on by a click with JavaScript disabled": rx.switch is a button that JavaScript turns into a switch: until it has run, a click does nothing. rx.ui.switch is a native checkbox with the role of a switch, which a click on it or on its label turns on and off with or without JavaScript. - behaviour, `rx.ui`, "Enter toggles it": rx.ui.switch is a native checkbox, which the browser toggles on Space and not on Enter. rx.switch is a button, which both keys press. - behaviour, `rx.ui`, "Enter on a switch does not submit its form": rx.ui.switch is a native input, and the browser submits a form when Enter is pressed in one of its inputs. rx.switch toggles on that key instead. diff --git a/packages/reflex-components-ui/news/+switch-children.bugfix.md b/packages/reflex-components-ui/news/+switch-children.bugfix.md new file mode 100644 index 00000000000..4e849e01b6c --- /dev/null +++ b/packages/reflex-components-ui/news/+switch-children.bugfix.md @@ -0,0 +1 @@ +`rx.ui.switch("Sync settings")` no longer takes the page down with React's error for a child of an input: it fails to compile and names the label to put the text in, `rx.ui.text(rx.ui.flex(rx.ui.switch(), "Sync settings", spacing="2"), as_="label")`. `rx.switch` drops such text. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 336342ed719..ab656b850e4 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -49,6 +49,18 @@ kind = "prop" names = ["form", "html_for"] reason = "As for rx.ui.text: rx.text.span passes html_for and form on as CSS keys, which the browser ignores; rx.ui.text.span renders them as attributes when it is a label." +[[api]] +component = "switch" +kind = "children" +names = ["*children"] +reason = "rx.switch(\"Sync settings\") renders a switch without its text: the button of Radix drops its children. rx.ui.switch is a native input, which takes none, so it refuses them and names the label to put the text in: rx.ui.text(rx.ui.flex(rx.ui.switch(), \"Sync settings\", spacing=\"2\"), as_=\"label\")." + +[[api]] +component = "color_mode.switch" +kind = "children" +names = ["*children"] +reason = "rx.color_mode.switch drops its children, as rx.switch does. rx.ui.color_mode.switch is a native input, which takes none, so it refuses them and names the label to put the text in." + [[look]] component = "data_list" check = "style" diff --git a/packages/reflex-components-ui/parity/ui_parity/allowlist.py b/packages/reflex-components-ui/parity/ui_parity/allowlist.py index d8b96d78b60..567d6e7e11c 100644 --- a/packages/reflex-components-ui/parity/ui_parity/allowlist.py +++ b/packages/reflex-components-ui/parity/ui_parity/allowlist.py @@ -17,7 +17,7 @@ ALLOWLIST = Path(__file__).parents[1] / "allowlist.toml" -API_KINDS = ("prop", "type", "event", "style") +API_KINDS = ("prop", "type", "event", "style", "children") LOOK_CHECKS = ("pixels", "style", "a11y") @@ -32,9 +32,11 @@ class ApiEntry: Attributes: component: The component, or ``*`` for every component. kind: What differs: whether a ``prop`` exists, the ``type`` of one, - whether an ``event`` trigger exists, or whether a ``style`` - keyword that rx passes on as a CSS key is taken. - names: The props, event triggers or style keywords. + whether an ``event`` trigger exists, whether a ``style`` + keyword that rx passes on as a CSS key is taken, or whether + ``children`` are taken. + names: The props, event triggers or style keywords, or + ``*children``. reason: Why, for a reader of the migration guide. """ diff --git a/packages/reflex-components-ui/parity/ui_parity/api.py b/packages/reflex-components-ui/parity/ui_parity/api.py index 25a0b5a37fa..4bf7c485221 100644 --- a/packages/reflex-components-ui/parity/ui_parity/api.py +++ b/packages/reflex-components-ui/parity/ui_parity/api.py @@ -23,7 +23,9 @@ class ApiDifference: Attributes: component: The component. kind: ``prop`` or ``event`` when only one system has the name, - ``type`` when the prop takes different values. + ``type`` when the prop takes different values, ``style`` for a + keyword one passes on as a CSS key, ``children`` when one refuses + the children the other takes. 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. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py index 4f5ec280c63..4f1387be752 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/checkbox.py @@ -2,18 +2,20 @@ from __future__ import annotations +import json from typing import Any, ClassVar, Literal from reflex_base.components.component import Component, ComponentNamespace, field from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, checked_input_event from reflex_base.vars.base import Var +from reflex_components_core.base.bare import Bare from reflex_components_core.core.breakpoints import Responsive from reflex_components_ui.base import UIComponent from reflex_components_ui.layout.flex import Flex -from reflex_components_ui.props import LiteralSpacing -from reflex_components_ui.style import ComponentStyles +from reflex_components_ui.props import LiteralSpacing, literal_value +from reflex_components_ui.style import ComponentStyles, StyleError from reflex_components_ui.styles.checkbox import CHECKBOX from reflex_components_ui.themes import LiteralAccentColor from reflex_components_ui.typography.text import Text @@ -30,6 +32,37 @@ class CheckedInput(UIComponent): # The type of the input. _type: ClassVar[str] = "checkbox" + # What the input is called in an error. + _kind: ClassVar[str] = "checkbox" + + def _post_init(self, *args, **kwargs): + """Initialize the input, which takes no children. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + + Raises: + StyleError: If it is given children, which React refuses an input + with an error that takes the page down, and rx drops. + """ + super()._post_init(*args, **kwargs) + if not self.children: + return + # The stub of the base class leaves its private members out. + name = self._display_name() # pyright: ignore[reportAttributeAccessIssue] + # The example labels the input with its text, where it is one. + first = self.children[0] + text = literal_value(first.contents) if isinstance(first, Bare) else None + text = json.dumps(text if isinstance(text, str) else "label") + msg = ( + f"{name}: the {self._kind} is a native input, which takes no " + f"children, and {name.replace('rx.ui.', 'rx.', 1)} drops them. Put " + "the text beside it in a label: " + f'rx.ui.text(rx.ui.flex({name}(), {text}, spacing="2"), as_="label").' + ) + raise StyleError(msg) + def _set_slot(self) -> None: """Render the input itself: it has no child to be rendered as.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/switch.py b/packages/reflex-components-ui/src/reflex_components_ui/components/switch.py index 9edcfe53198..2edff1197c9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/switch.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/switch.py @@ -24,6 +24,8 @@ class Switch(CheckedInput): styles: ClassVar[ComponentStyles] = SWITCH + _kind: ClassVar[str] = "switch" + as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child, merging their props and behavior." ) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 3589f6bdb27..bf0e21ede18 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -832,7 +832,13 @@ def controls(): ), rx.ui.text_area(name="notes", default_value="None", id="notes"), rx.ui.checkbox("Agree", name="agree", default_checked=True, id="agree"), - rx.ui.switch(name="alerts", id="alerts"), + # The label that the error of a switch given text names. + rx.ui.text( + rx.ui.flex( + rx.ui.switch(name="alerts", id="alerts"), "Alerts", spacing="2" + ), + as_="label", + ), rx.ui.radio(["a", "b"], name="letter", default_value="b"), rx.ui.checkbox_group.root( rx.ui.checkbox_group.item("Ham", value="ham"), @@ -1969,7 +1975,8 @@ def test_form_controls_work_in_an_app(ui_app: AppHarness, page: Page): expect(page.get_by_role("listbox")).to_be_hidden() # Native inputs: a click, and the keys of the browser. - page.locator("#alerts").click() + page.get_by_text("Alerts", exact=True).click() + expect(page.locator("#alerts")).to_be_checked() page.get_by_text("S", exact=True).click() page.get_by_text("Gift").click() # An item draws its text twice, one over the other. diff --git a/tests/units/reflex_components_ui/components/test_switch.py b/tests/units/reflex_components_ui/components/test_switch.py index 57814895e88..2f2334fe4d0 100644 --- a/tests/units/reflex_components_ui/components/test_switch.py +++ b/tests/units/reflex_components_ui/components/test_switch.py @@ -499,3 +499,24 @@ def test_switch_unknown_radius(ui_plugin: UIPlugin): str(error.value) == 'rx.ui.switch: unknown radius "large". The values are "none", "small", "full".' ) + + +def test_switch_refuses_children(ui_plugin: UIPlugin): + """A child of the input is an error that says to put the text in a label. + + rx.switch drops it, and React refuses a child of an input with an error + that takes the page down. + """ + with pytest.raises(StyleError) as error: + rx.ui.switch("Sync settings") + assert str(error.value) == ( + "rx.ui.switch: the switch is a native input, which takes no children, " + "and rx.switch drops them. Put the text beside it in a label: " + 'rx.ui.text(rx.ui.flex(rx.ui.switch(), "Sync settings", spacing="2"), ' + 'as_="label").' + ) + # The label it names compiles. + label = rx.ui.text( + rx.ui.flex(rx.ui.switch(), "Sync settings", spacing="2"), as_="label" + ) + assert label.tag == "label" diff --git a/tests/units/reflex_components_ui/parity/test_allowlist.py b/tests/units/reflex_components_ui/parity/test_allowlist.py index 6dca561183f..1762449f918 100644 --- a/tests/units/reflex_components_ui/parity/test_allowlist.py +++ b/tests/units/reflex_components_ui/parity/test_allowlist.py @@ -12,6 +12,8 @@ LookEntry, ) +from tests.units.reflex_components_ui.test_api_parity import COMPONENTS + # The accepted differences the first component waves bring, in the file's form. DOCUMENT = { "api": [ @@ -139,7 +141,7 @@ def test_parse_reads_every_table_with_its_defaults(): {"component": "box", "kind": "props", "names": [], "reason": "r"} ] }, - "[[api]] kind = \"props\" is not one of ['prop', 'type', 'event', 'style'].", + "[[api]] kind = \"props\" is not one of ['prop', 'type', 'event', 'style', 'children'].", ), ( { @@ -224,6 +226,8 @@ def test_committed_allowlist_names_only_rx_ui_components(): members = [member for member in dir(value) if not member.startswith("_")] components.update(members) components.update(f"{name}.{member}" for member in members) + # And by the names the API test compares, the members of the color mode. + components.update(COMPONENTS) entries = allowlist.load() listed = { entry.component for entry in (*entries.api, *entries.contract, *entries.look) diff --git a/tests/units/reflex_components_ui/test_api_parity.py b/tests/units/reflex_components_ui/test_api_parity.py index 48b0ae0ac38..2d304d08b66 100644 --- a/tests/units/reflex_components_ui/test_api_parity.py +++ b/tests/units/reflex_components_ui/test_api_parity.py @@ -351,6 +351,11 @@ def test_every_component_has_the_api_of_its_radix_counterpart(): found.append( ApiDifference("*", "style", UNITLESS_LENGTH, "dropped by the browser", None) ) + # The components whose element takes no children, which rx drops. + found += [ + ApiDifference(component, "children", "*children", "dropped", None) + for component in REFUSES_CHILDREN + ] unlisted, stale = unexplained(found, allowlist.load()) assert unlisted == [], ( "rx.ui differs from rx: match the Radix component, or list the " @@ -739,3 +744,75 @@ def test_errors_name_the_component_and_its_rx_counterpart_as_an_app_writes_them( public = shown.removeprefix("rx.ui.") assert component_class(resolve(reflex_components_ui, public)) is cls resolve(rx, public) + + +# The elements that take no children: React refuses a child of one with an +# error that takes the page down. +VOID_ELEMENTS = frozenset(( + "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", + "source", "track", "wbr", +)) # fmt: skip + +# The components rendered as a void element that rx gives a child to drop, +# where rx.ui refuses it. +REFUSES_CHILDREN = ("color_mode.switch", "switch") + + +def _refused_children(component: str) -> str: + """Write the error of a switch given the text "label" as a child. + + Args: + component: The name of the component. + + Returns: + The error. + """ + name = f"rx.ui.{component}" + return ( + f"{name}: the switch is a native input, which takes no children, and " + f"rx.{component} drops them. Put the text beside it in a label: " + f'rx.ui.text(rx.ui.flex({name}(), "label", spacing="2"), as_="label").' + ) + + +def _void_elements_with_children(component: Component) -> list[str]: + """Find the void elements a component renders with children. + + Args: + component: The component. + + Returns: + The type of each, in the order of the tree. + """ + found = [ + type(component).__name__ + for _ in [None] + if component.tag in VOID_ELEMENTS and component.children + ] + for child in component.children: + if isinstance(child, Component): + found += _void_elements_with_children(child) + return found + + +@pytest.mark.parametrize("component", COMPONENTS) +def test_a_text_child_is_rendered_or_refused(ui_plugin, component: str): + """A text child renders where the element takes one, and is refused elsewhere. + + Args: + ui_plugin: The configured plugin. + component: The name of the component. + """ + create = resolve(reflex_components_ui, component) + arguments = (*ARGUMENTS.get(component, ()), "label") + if component in REFUSES_CHILDREN: + with pytest.raises(StyleError) as error: + create(*arguments) + assert str(error.value) == _refused_children(component) + return + try: + created = create(*arguments) + except (StyleError, TypeError, ValueError): + # Refused while compiling, with an error of its own. + return + assert _void_elements_with_children(created) == [] From 28d54e9d57474398795124bd5bbafcb3b5cf8502 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 06:50:08 +0000 Subject: [PATCH 179/204] Name rx.ui.tooltip in the error of a tooltip without an element child The trigger rx.ui.tooltip makes of its child named itself rx.ui.tooltip_trigger, which no app writes. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../src/reflex_components_ui/components/tooltip.py | 3 +++ tests/units/reflex_components_ui/components/test_tooltip.py | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py index f6cad082df5..767dfb33b09 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py @@ -47,6 +47,9 @@ class TooltipTrigger(HoverTrigger): """What a tooltip describes: the child of the tooltip.""" + # Created by rx.ui.tooltip from its child, which its errors are about. + _named_as: ClassVar[str | None] = "tooltip" + # A press on what a tooltip is on closes the tooltip. _heard: ClassVar[tuple[str, ...]] = (*HoverTrigger._heard, "onPointerDown") # pyright: ignore[reportAttributeAccessIssue] diff --git a/tests/units/reflex_components_ui/components/test_tooltip.py b/tests/units/reflex_components_ui/components/test_tooltip.py index 14e5b7aed18..1e15d30196e 100644 --- a/tests/units/reflex_components_ui/components/test_tooltip.py +++ b/tests/units/reflex_components_ui/components/test_tooltip.py @@ -241,6 +241,6 @@ def test_tooltip_needs_an_element_to_describe(ui_plugin: UIPlugin): with pytest.raises(StyleError) as error: rx.ui.tooltip("Save", content="Saves the file") assert str(error.value) == ( - "rx.ui.tooltip_trigger: it is rendered as its child, so it needs exactly " - "one child that is an element, such as a button." + "rx.ui.tooltip: it is rendered as its child, so it needs exactly one " + "child that is an element, such as a button." ) From 76874db23cdbf2c47308fe05d6d042a45f810149 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 08:24:41 +0000 Subject: [PATCH 180/204] Format css-props.js as the pre-commit hook does Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- packages/reflex-components-ui/js/scripts/css-props.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/reflex-components-ui/js/scripts/css-props.js b/packages/reflex-components-ui/js/scripts/css-props.js index 406b5271a99..395d6759582 100644 --- a/packages/reflex-components-ui/js/scripts/css-props.js +++ b/packages/reflex-components-ui/js/scripts/css-props.js @@ -291,7 +291,9 @@ ${block("CSS_PROPS: dict[str, str] = {", [...properties.map(({ key, name }) => ` # but for the ones it lists as unitless. ${block( "NUMERIC_PROPS: frozenset[str] = frozenset({", - properties.filter(({ open }) => open === "_Size").map(({ name }) => `"${name}"`), + properties + .filter(({ open }) => open === "_Size") + .map(({ name }) => `"${name}"`), "})", )} ${block( From edccffae78c70bcb5549742c9f4c06930e436e6c Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 08:24:41 +0000 Subject: [PATCH 181/204] Keep the line endings of a file the rx.ui codemod rewrites A line the codemod inserted or rewrote ended in LF in a file with CRLF line endings, as a checkout on Windows writes them, and its --diff printed the CR of every line. Each edit now ends its lines as the file does, and the diff is printed with the newlines of the terminal. The fixture apps and the diff are tested with both endings. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../src/reflex_components_ui/migrate.py | 18 ++++++-- .../reflex_components_ui/test_migrate.py | 42 +++++++++++++------ 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py index 49f82a769bf..b26464e7045 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/migrate.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/migrate.py @@ -161,15 +161,18 @@ def diff(self, root: Path | None = None) -> str: path.relative_to(root) if root and path.is_relative_to(root) else path ) shown = name.as_posix().lstrip("/") + # Lines without their endings: the diff is printed with the + # newlines of the terminal, whatever the ones of the file. out.extend( difflib.unified_diff( - old.splitlines(keepends=True), - new.splitlines(keepends=True), + old.splitlines(), + new.splitlines(), f"a/{shown}", f"b/{shown}", + lineterm="", ) ) - return "".join(out) + return "".join(f"{line}\n" for line in out) @dataclasses.dataclass(frozen=True, slots=True) @@ -455,6 +458,10 @@ def __init__(self, path: Path, data: bytes): self.path = path self.data = data self.lines = data.splitlines(keepends=True) + # The line ending the lines it writes take: the one of its first line. + self.newline = ( + "\r\n" if self.lines[:1] and self.lines[0].endswith(b"\r\n") else "\n" + ) self.starts = [0] for line in self.lines: self.starts.append(self.starts[-1] + len(line)) @@ -537,8 +544,11 @@ def edit(self, start: int, end: int, text: str) -> None: Args: start: The offset of its first byte. end: The offset after its last byte. - text: What replaces it. + text: What replaces it, its lines ending as those of any file + do: they end as the lines of this one. """ + if self.newline != "\n": + text = text.replace("\r\n", "\n").replace("\n", self.newline) self.edits.append(_Edit(start, end, text.encode())) def apply(self, start: int = 0, end: int | None = None) -> str: diff --git a/tests/units/reflex_components_ui/test_migrate.py b/tests/units/reflex_components_ui/test_migrate.py index 452c0c959e3..88004c5e2d3 100644 --- a/tests/units/reflex_components_ui/test_migrate.py +++ b/tests/units/reflex_components_ui/test_migrate.py @@ -27,36 +27,42 @@ } -def _fixture(source: Path) -> dict[str, str]: +# The line endings an app is written with: a checkout on Windows may turn the +# ones of the fixtures into CRLF. +NEWLINES = {"lf": "\n", "crlf": "\r\n"} + + +def _fixture(source: Path, newline: str = "\n") -> dict[str, str]: """Read a tree of fixture files. Args: source: The fixture tree. + newline: The line ending to give every line. Returns: The text of every file, by its path relative to the tree without the ``.txt``. """ return { - file - .relative_to(source) - .as_posix() - .removesuffix(".txt"): file.read_bytes().decode() + file.relative_to(source).as_posix().removesuffix(".txt"): ( + file.read_bytes().decode().replace("\r\n", "\n").replace("\n", newline) + ) for file in sorted(source.rglob("*.txt")) } -def _copy(source: Path, target: Path) -> dict[str, str]: +def _copy(source: Path, target: Path, newline: str = "\n") -> dict[str, str]: """Copy a tree of fixture files, dropping their ``.txt``. Args: source: The fixture tree. target: Where the files go. + newline: The line ending to give every line. Returns: The text of every file, by its path relative to the tree. """ - files = _fixture(source) + files = _fixture(source, newline) for name, text in files.items(): (target / name).parent.mkdir(parents=True, exist_ok=True) (target / name).write_bytes(text.encode()) @@ -89,16 +95,20 @@ def _write(result: migrate.Result) -> None: path.write_bytes(new.encode()) +@pytest.mark.parametrize("newline", sorted(NEWLINES)) @pytest.mark.parametrize("case", sorted(CASES)) -def test_fixture_app(case: str, tmp_path: Path): +def test_fixture_app(case: str, newline: str, tmp_path: Path): """An app migrates to its expected files and report, and only once. + The lines the migration writes end as the lines of the file do. + Args: case: The fixture app. + newline: The line endings of the app. tmp_path: Where the app is copied. """ - expected = _copy(FIXTURES / case / "before", tmp_path) - expected.update(_fixture(FIXTURES / case / "after")) + expected = _copy(FIXTURES / case / "before", tmp_path, NEWLINES[newline]) + expected.update(_fixture(FIXTURES / case / "after", NEWLINES[newline])) result = migrate.migrate([tmp_path], **CASES[case]) _write(result) assert _tree(tmp_path) == expected @@ -134,17 +144,25 @@ def test_files_without_their_rxconfig(tmp_path: Path): assert result.items == [] +@pytest.mark.parametrize("newline", sorted(NEWLINES)) def test_main_check_and_diff( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture + newline: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture, ): """--check changes nothing and fails, --diff prints the diff, and a run writes. + The diff is printed with the newlines of the terminal, whatever the line + endings of the files. + Args: + newline: The line endings of the app. tmp_path: Where the app is copied. monkeypatch: Changes the working directory. capsys: Captures the output. """ - files = _copy(FIXTURES / "app_theme" / "before", tmp_path) + files = _copy(FIXTURES / "app_theme" / "before", tmp_path, NEWLINES[newline]) monkeypatch.chdir(tmp_path) assert migrate.main([".", "--check", "--diff"]) == 1 assert _tree(tmp_path) == files From 619d4f73bbdd19780afdb77a6fb209a8d34b6624 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 08:26:00 +0000 Subject: [PATCH 182/204] Give the docs' app-root evaluation the registry of refs it now reads The app root lists $/utils/refs among its window libraries since dynamic components read the registry of refs from there; the docs' frontend test evaluates the root with each library as a parameter, and lacked that one. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- docs/app/tests/frontend_quality.test.mjs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/app/tests/frontend_quality.test.mjs b/docs/app/tests/frontend_quality.test.mjs index 8934d522e3a..077df1d7b83 100644 --- a/docs/app/tests/frontend_quality.test.mjs +++ b/docs/app/tests/frontend_quality.test.mjs @@ -154,7 +154,7 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ bundle_library('constructor') print(json.dumps({'root': compile_app_root(rx.el.div('Quality'))[1], 'component': serializers.serialize(Quality.create())})) `], {cwd: root, encoding: "utf8"}).trim().split("\n").at(-1)); - const setup = new Function("window", "React", "utils_context", "utils_context_registry", "utils_state", "loadFixture", "loadConstructor", + const setup = new Function("window", "React", "utils_context", "utils_context_registry", "utils_state", "utils_refs", "loadFixture", "loadConstructor", generated.root.replace(/^import .*$/gm, "") .replace(/^export default function/gm, "function") .replace(/^export /gm, "") @@ -176,7 +176,7 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ try { let calls = 0; globalThis.window = {}; - setup(window, react, {}, {}, {}, async () => {calls++; return {default: {Quality: () => 42}};}); + setup(window, react, {}, {}, {}, {}, async () => {calls++; return {default: {Quality: () => 42}};}); assert.equal(calls, 0); assert.equal(window.__reflex.react, react); assert.equal(window.__reflex["quality-lazy-fixture"], undefined); @@ -190,7 +190,7 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ let attempts = 0; globalThis.window = {}; - setup(window, react, {}, {}, {}, async () => { + setup(window, react, {}, {}, {}, {}, async () => { if (++attempts === 1) throw new Error("Temporary download failure"); return {default: {Quality: () => 43}}; }); @@ -204,7 +204,7 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_ let constructorCalls = 0; globalThis.window = {}; const constructorModule = {name: "constructor library"}; - setup(window, react, {}, {}, {}, async () => ({default: {}}), async () => {constructorCalls++; return {default: constructorModule};}); + setup(window, react, {}, {}, {}, {}, async () => ({default: {}}), async () => {constructorCalls++; return {default: constructorModule};}); await window.__reflex_load(["constructor"]); assert.equal(constructorCalls, 1); assert.equal(window.__reflex.constructor, constructorModule); From 88e36af5b46d6614a679d995255e9db1b6b64d72 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 08:27:10 +0000 Subject: [PATCH 183/204] Give the kitchen sink the spacing it meant: spacing and padding with units flex(gap="3"), grid(gap="6") and center(padding="4") passed bare numbers to CSS, which the browser drops, so the rx kitchen sink rendered without that spacing, and rx.ui now refuses them, which failed the export of the size budgets. They use the spacing prop and a length in pixels. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- examples/pages/kitchen_sink.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/pages/kitchen_sink.py b/examples/pages/kitchen_sink.py index 56cd3066ab9..e24dedc75cd 100644 --- a/examples/pages/kitchen_sink.py +++ b/examples/pages/kitchen_sink.py @@ -236,7 +236,7 @@ def _danger(ns: Any) -> rx.Component: ns.flex( ns.alert_dialog.cancel(ns.button("Cancel", variant="soft")), ns.alert_dialog.action(ns.button("Delete")), - gap="3", + spacing="3", justify="end", ), ), @@ -376,12 +376,12 @@ def page(ns: Any) -> rx.Component: ), _sidebar(ns), columns=rx.breakpoints(initial="1", md="2"), - gap="6", + spacing="6", ), ns.center( ns.blockquote("Settings are saved per project."), ns.code("acme.reflex.run"), - padding="4", + padding="16px", ), size="2", ), From 6698dc73fd39792b4a155948751d7aca3d7547c5 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 09:02:53 +0000 Subject: [PATCH 184/204] Spend the Escape that closes an rx.ui hover card or tooltip hover.js closed the popup from a keydown listener without cancelling the key, so in Firefox and WebKit the same Escape also reached a modal dialog the popup was in, which closed with it. As the topmost layer, the popup now takes the key, as Radix's does. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../reflex-components-ui/js/src/behaviors/hover.js | 7 ++++++- .../js/tests/behaviors/hover.test.js | 14 +++++++++++--- .../news/+hover-escape-in-dialog.bugfix.md | 1 + 3 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 packages/reflex-components-ui/news/+hover-escape-in-dialog.bugfix.md diff --git a/packages/reflex-components-ui/js/src/behaviors/hover.js b/packages/reflex-components-ui/js/src/behaviors/hover.js index 71993214ae9..f83590e4add 100644 --- a/packages/reflex-components-ui/js/src/behaviors/hover.js +++ b/packages/reflex-components-ui/js/src/behaviors/hover.js @@ -61,8 +61,13 @@ function set(popup, open) { if (event.type !== "keydown") { if (!popup.contains(/** @type {Node} */ (event.target))) ask(popup, false, "outside"); - } else if (/** @type {KeyboardEvent} */ (event).key === "Escape") + } else if (/** @type {KeyboardEvent} */ (event).key === "Escape") { + // Spent on the popup, as the topmost layer: without this, Firefox and + // WebKit also hand the key to a modal dialog the popup is in, which + // closes with it. + event.preventDefault(); ask(popup, false, "escape"); + } }; addEventListener("keydown", dismiss, true); addEventListener("pointerdown", dismiss, true); diff --git a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js index d5d3ea5e9d0..6391f069f57 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js @@ -191,10 +191,18 @@ test("Escape, a press outside and a press on the button of a tooltip close it", open(); dispatchEvent(new KeyboardEvent("keydown", { key: "a" })); expect(shown()).toBe(true); - dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); - expect(shown()).toBe(false); + // The Escape that closes it is spent: a dialog the popup is in stays open. + const escape = () => { + const event = new KeyboardEvent("keydown", { + key: "Escape", + cancelable: true, + }); + dispatchEvent(event); + return event.defaultPrevented; + }; + expect([escape(), shown()]).toEqual([true, false]); // Once closed, the popup hears nothing of the page. - dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(escape()).toBe(false); open(); document .getElementById("link") diff --git a/packages/reflex-components-ui/news/+hover-escape-in-dialog.bugfix.md b/packages/reflex-components-ui/news/+hover-escape-in-dialog.bugfix.md new file mode 100644 index 00000000000..d979ec9e9b6 --- /dev/null +++ b/packages/reflex-components-ui/news/+hover-escape-in-dialog.bugfix.md @@ -0,0 +1 @@ +Escape closes an `rx.ui.hover_card` or `rx.ui.tooltip` inside an `rx.ui.dialog` without closing the dialog in Firefox and Safari, as it does in Chromium. From 9b760dc9bf22c656412ced46377d9c4677f1b909 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 09:02:53 +0000 Subject: [PATCH 185/204] Hold the contracts to what each engine computes, and say what a wait found - theme_panel compares computed lengths as numbers, within 0.05px, rather than in Chromium's serialisation (Firefox says 21.6px, WebKit 21.59375px for 21.5938px). - context_menu asks for the menu with Shift+F10, and with the context-menu key where the engine sends no contextmenu for Shift+F10; its keys cell waits for the area to say it is open before the capture reads it. - wait_for_text says what the element held when the wait ends without the text, and the drawer's Tab step names what has the focus outside its panel, so a failure in an engine tells what happened. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../ui_parity/components/context_menu.py | 40 ++++++++++--- .../parity/ui_parity/components/drawer.py | 10 ++-- .../ui_parity/components/theme_panel.py | 4 +- .../parity/ui_parity/samples.py | 60 +++++++++++++++++-- .../parity/test_samples.py | 47 ++++++++++++++- 5 files changed, 142 insertions(+), 19 deletions(-) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py index c3fe1ec5993..07a540c7251 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py @@ -2,10 +2,12 @@ from __future__ import annotations +import contextlib from collections.abc import Mapping from typing import Any from playwright.sync_api import Locator, Page +from playwright.sync_api import TimeoutError as PlaywrightTimeoutError import reflex as rx from ui_parity.components.dropdown_menu import PARTS, SHOWN, close_menu @@ -18,6 +20,8 @@ VARIANTS = ["solid", "soft"] OPEN = "open" KEYS = "keys" +# What the area matches while its menu is open. +KEYS_STATE = "[data-state='open']" SUB = "sub" _RADIX = ".rt-BaseMenuContent:not(.rt-BaseMenuSubContent)" _UI = "[role=menu]:popover-open:not([role=menu] *)" @@ -103,18 +107,40 @@ def _right_click(page: Page, target: Locator, point: Point) -> None: page.mouse.move(1, 1) +def open_from_keyboard(page: Page, area: Locator) -> None: + """Ask for the context menu of a focused area from the keyboard. + + Shift+F10 asks for it, and so does the context-menu key: an engine that + does not send a ``contextmenu`` for the one is given the other. + + Args: + page: The page. + area: The area. + """ + area.focus() + page.keyboard.press("Shift+F10") + shown = f"document.querySelectorAll('{SHOWN}').length" + try: + page.wait_for_function(f"{shown} > 0", timeout=1000) + except PlaywrightTimeoutError: + page.keyboard.press("ContextMenu") + + def _keys(page: Page, target: Locator, point: Point) -> None: - """Open the context menu with Shift+F10, which highlights its first item. + """Open the context menu from the keyboard, which highlights its first item. Args: page: The page. target: The area. point: The middle of the area. """ - target.focus() - page.keyboard.press("Shift+F10") + open_from_keyboard(page, target) _wait(page, 1) wait_for_value(page, "document.activeElement.textContent.startsWith('Copy')", True) + # The area says it is open by the time the capture reads it: where it + # does not, the capture says which system did not. + with contextlib.suppress(PlaywrightTimeoutError): + target.and_(page.locator(KEYS_STATE)).wait_for(timeout=5000) def _open_sub(page: Page, target: Locator, point: Point) -> None: @@ -175,7 +201,7 @@ def _open_sub(page: Page, target: Locator, point: Point) -> None: OPEN: State( enter=_right_click, leave=close_menu, matches="[data-state='open']" ), - KEYS: State(enter=_keys, leave=close_menu, matches="[data-state='open']"), + KEYS: State(enter=_keys, leave=close_menu, matches=KEYS_STATE), SUB: State(enter=_open_sub, leave=close_menu, matches="[data-state='open']"), }, # Not held to a threshold of zero. At zero 18 of the 39 cells are equal @@ -341,8 +367,7 @@ def _right(run: Run) -> None: @CONTRACT.step("opens from the keyboard on its first item") def _keyboard(run: Run) -> None: page = run.page - page.locator("#area").focus() - page.keyboard.press("Shift+F10") + open_from_keyboard(page, page.locator("#area")) _shown(run, "copy") _focus(run, "copy") page.keyboard.press("ArrowDown") @@ -380,8 +405,7 @@ def _choice(run: Run) -> None: @CONTRACT.step("the right arrow opens a sub-menu, and the left arrow closes it") def _sub(run: Run) -> None: page = run.page - page.locator("#area").focus() - page.keyboard.press("Shift+F10") + open_from_keyboard(page, page.locator("#area")) _focus(run, "copy") page.keyboard.press("End") _focus(run, "share") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/drawer.py b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py index ba53ab4f533..bfee8cd791d 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/drawer.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py @@ -428,14 +428,16 @@ def _tab(run: Run) -> None: behind = [] for _ in range(6): page.keyboard.press("Tab") + # What has the focus outside the panel, by its tag and id, if anything. behind.append( page.evaluate( - "document.activeElement !== document.body" - " && !document.getElementById('plain-panel')" - ".contains(document.activeElement)" + "(element => element === document.body" + " || document.getElementById('plain-panel').contains(element)" + " ? null : `${element.tagName}#${element.id}`)" + "(document.activeElement)" ) ) - assert behind == [False] * 6 + assert behind == [None] * 6 @CONTRACT.step("Escape, a press beside the panel and its button close it, and say so") diff --git a/packages/reflex-components-ui/parity/ui_parity/components/theme_panel.py b/packages/reflex-components-ui/parity/ui_parity/components/theme_panel.py index 6e5e6ea8427..2adf9ad1d57 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/theme_panel.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/theme_panel.py @@ -11,7 +11,7 @@ from ui_parity.contract import NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.look import Point, State from ui_parity.matrix import DARK, LIGHT, Matrix -from ui_parity.samples import wait_for_value +from ui_parity.samples import snap_lengths, wait_for_value # The panel, in each system. PANEL = (".radix-themes:has(> .rt-ScrollAreaRoot)", "[data-rx-theme-panel=panel]") @@ -384,7 +384,7 @@ def _choices(run: Run) -> None: if value is not None: run.page.locator(f'input[name={name}][value="{value}"]').click() assert run.page.locator(f'input[name={name}][value="{value}"]').is_checked() - assert _tokens(run) == tokens, (name, value) + assert snap_lengths(_tokens(run), tokens) == tokens, (name, value) @CONTRACT.step("the appearance, and D, set the class of the root") diff --git a/packages/reflex-components-ui/parity/ui_parity/samples.py b/packages/reflex-components-ui/parity/ui_parity/samples.py index a566f655bcc..6ac2c3bda68 100644 --- a/packages/reflex-components-ui/parity/ui_parity/samples.py +++ b/packages/reflex-components-ui/parity/ui_parity/samples.py @@ -77,17 +77,69 @@ def focused(page: Any) -> str: return page.evaluate("document.activeElement.id") +# How far apart two lengths an engine computes may be and still be the same: +# well under a device pixel, above what the engines' serialisations differ by. +LENGTH_TOLERANCE = 0.05 + + +def snap_lengths(actual: list[str], expected: list[str]) -> list[str]: + """Read the lengths among computed values as numbers. + + Each engine serialises a computed length with its own digits, 21.5938px + in Chromium where Firefox says 21.6px. A length within LENGTH_TOLERANCE + of the one expected at its place is given as expected; everything else + stays as read, so comparing the result with what is expected is exact. + + Args: + actual: The values read, in order. + expected: The values expected, in the same order. + + Returns: + The values read, the lengths that match given as expected. + """ + if len(actual) != len(expected): + return actual + return [ + want + if got.endswith("px") + and want.endswith("px") + and _is_number(got[:-2]) + and _is_number(want[:-2]) + and abs(float(got[:-2]) - float(want[:-2])) <= LENGTH_TOLERANCE + else got + for got, want in zip(actual, expected, strict=True) + ] + + +def _is_number(text: str) -> bool: + """Say whether a text is a number. + + Args: + text: The text. + + Returns: + Whether float() reads it. + """ + try: + float(text) + except ValueError: + return False + return True + + def wait_for_text(page: Any, element: str, text: str) -> None: - """Wait until an element of a page holds a text. + """Wait until an element of a page holds a text, and say what it held if not. Args: page: The page. element: The id of the element. text: Its whole text. """ - page.wait_for_function( - "([id, text]) => document.getElementById(id).textContent === text", - arg=[element, text], + wait_for_value( + page, + f"document.getElementById({json.dumps(element)}).textContent", + text, + timeout=30000, ) diff --git a/tests/units/reflex_components_ui/parity/test_samples.py b/tests/units/reflex_components_ui/parity/test_samples.py index f4f210c1161..b3644c9e003 100644 --- a/tests/units/reflex_components_ui/parity/test_samples.py +++ b/tests/units/reflex_components_ui/parity/test_samples.py @@ -4,7 +4,7 @@ import pytest from playwright.sync_api import TimeoutError as PlaywrightTimeoutError -from ui_parity.samples import wait_for_value +from ui_parity.samples import snap_lengths, wait_for_text, wait_for_value class _Page: @@ -50,3 +50,48 @@ def test_wait_for_value_takes_a_value_that_arrived_as_the_wait_ended(): assert page.waited == [ ("expected => JSON.stringify(checked()) === expected", '["One"]', 5000) ] + + +def test_wait_for_text_says_what_the_element_held_instead(): + page = _Page('["open","escape"]', reached=False) + with pytest.raises(AssertionError) as error: + wait_for_text(page, "seen", '["open","escape","closed"]') + assert str(error.value) == ( + 'document.getElementById("seen").textContent is \'["open","escape"]\', ' + 'not \'["open","escape","closed"]\'' + ) + assert page.waited == [ + ( + ( + 'expected => JSON.stringify(document.getElementById("seen")' + ".textContent) === expected" + ), + '"[\\"open\\",\\"escape\\",\\"closed\\"]"', + 30000, + ) + ] + + +def test_snap_lengths_reads_lengths_as_numbers_and_the_rest_as_written(): + expected = ["rgb(229, 72, 77)", "8.1px", "21.5938px", "rgba(255, 255, 255, 0.7)"] + # Firefox and WebKit serialise the same length with other digits. + assert ( + snap_lengths( + ["rgb(229, 72, 77)", "8.1px", "21.6px", "rgba(255, 255, 255, 0.7)"], + expected, + ) + == expected + ) + assert ( + snap_lengths( + ["rgb(229, 72, 77)", "8.1px", "21.59375px", "rgba(255, 255, 255, 0.7)"], + expected, + ) + == expected + ) + # A length that differs by more than a tenth of a device pixel stays as read, + # and so does anything that is not a length. + assert snap_lengths( + ["rgb(229, 72, 78)", "8px", "21.7px", "rgba(255, 255, 255, 0.7)"], expected + ) == ["rgb(229, 72, 78)", "8px", "21.7px", "rgba(255, 255, 255, 0.7)"] + assert snap_lengths(["21.6px"], ["21.5938px", "4px"]) == ["21.6px"] From 792f1e0ba63f7d9f4033140aa8792306ed421bef Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 09:07:49 +0000 Subject: [PATCH 186/204] Read the animations of a progress bar once its transition has ended Both systems move the indicator with a 120ms transform transition, which Firefox still lists among the animations as the page settles. The step now waits, for at most two seconds, until no transition runs on the indicator, then reads every animation as before. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../parity/ui_parity/components/progress.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/progress.py b/packages/reflex-components-ui/parity/ui_parity/components/progress.py index cc9ddfc3eb3..8027f0cf232 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/progress.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/progress.py @@ -2,9 +2,12 @@ from __future__ import annotations +import contextlib from collections.abc import Mapping from typing import Any +from playwright.sync_api import Error as PlaywrightError + import reflex as rx from ui_parity.contract import HYDRATED, NO_JAVASCRIPT, SERVER, Contract, Run from ui_parity.matrix import DARK, LIGHT, Matrix @@ -145,6 +148,20 @@ def advance(self): }; })""" +# Resolves once no transition runs on an element or inside it, and rejects +# after a timeout in milliseconds. +SETTLED = """(element, timeout) => new Promise((resolve, reject) => { + const end = performance.now() + timeout; + const check = () => { + if (element.getAnimations({subtree: true}).every(animation => + !(animation instanceof CSSTransition) + || animation.playState !== "running")) resolve(); + else if (performance.now() > end) reject(new Error("still running")); + else requestAnimationFrame(check); + }; + check(); +})""" + _GROW = [ {"offset": 0, "easing": "ease", "transform": "scaleX(0.01)"}, {"offset": 0.2, "easing": "ease", "transform": "scaleX(0.1)"}, @@ -303,6 +320,11 @@ def _role(run: Run) -> None: @CONTRACT.step("a bar without a value grows, fades, pulses and shines", on=HYDRATED) def _animations(run: Run) -> None: indicator = run.page.locator("#waiting > div") + # Both systems move the indicator with a transition of 120ms, which an + # engine may still be running as the page settles: the animations are + # read once it has ended, and a transition that has not is read with them. + with contextlib.suppress(PlaywrightError): + indicator.evaluate(SETTLED, 2000) assert indicator.evaluate(ANIMATIONS) == EXPECTED_ANIMATIONS assert run.page.locator("#some > div").evaluate(ANIMATIONS) == [] From 9ca07bd0eeae9ea5de7a371542b7ba78abc30722 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 09:51:35 +0000 Subject: [PATCH 187/204] Give an rx.ui drawer its slide-out and keep Tab in its panel outside Chromium - Firefox and WebKit take a closing modal dialog out of the top layer at once, without CSS overlay, so a drawer's panel ran no transition and its on_animation_end(false) never came. A dialog that closes now gives a panel with a transform transition that is not running the transitionend the browsers that run it send. - WebKit made the drawer's dialog, which covers the page around its panel, a stop of Tab. It is out of the order of Tab; showModal still moves the focus into the panel. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../js/src/behaviors/dialog.js | 37 ++++++++++++++ .../js/tests/behaviors/dialog.test.js | 48 +++++++++++++++++++ .../news/+drawer-firefox-safari.bugfix.md | 1 + .../reflex_components_ui/components/drawer.py | 8 +++- .../components/test_drawer.py | 2 + 5 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 packages/reflex-components-ui/news/+drawer-firefox-safari.bugfix.md diff --git a/packages/reflex-components-ui/js/src/behaviors/dialog.js b/packages/reflex-components-ui/js/src/behaviors/dialog.js index 39f4ab5e9bb..d67c5b1c223 100644 --- a/packages/reflex-components-ui/js/src/behaviors/dialog.js +++ b/packages/reflex-components-ui/js/src/behaviors/dialog.js @@ -150,6 +150,43 @@ export function dialogEvent(event) { } const { on, bound } = dialogs.get(dialog) ?? {}; mark(dialog, false); + slidOut(dialog); if (!bound) on?.open?.(false); on?.closeAutoFocus?.(); } + +/** + * Say that the panels of a closed dialog have slid out where they do not. + * + * Without the `overlay` property of CSS, Firefox and Safari take a modal + * dialog out of the top layer as it closes, so a panel that slides out as + * the dialog closes runs no transition and says nothing. Such a panel is + * given the `transitionend` the browsers that run it send. + * + * @param {HTMLDialogElement} dialog The dialog that has closed. + * @returns {void} + */ +function slidOut(dialog) { + for (const panel of dialog.children) { + if ( + !(panel instanceof HTMLElement) || + !getComputedStyle(panel) + .transitionProperty.split(",") + .some((name) => name.trim() === "transform") || + panel + .getAnimations() + .some( + (animation) => + /** @type {CSSTransition} */ (animation).transitionProperty === + "transform" && animation.playState === "running", + ) + ) + continue; + panel.dispatchEvent( + new TransitionEvent("transitionend", { + bubbles: true, + propertyName: "transform", + }), + ); + } +} diff --git a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js index 5c3ab179190..7a5d768efa1 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js @@ -298,3 +298,51 @@ test("a press on anything else is left alone", () => { dialog.remove(); expect(press("open")).toBe(false); }); + +test("a panel that does not slide out says it has, as one that slides out does", () => { + // What jsdom lacks of a transition: its event, and the animations of an element. + globalThis.TransitionEvent ??= /** @type {typeof TransitionEvent} */ ( + /** @type {unknown} */ ( + class extends Event { + /** + * @param {string} type The type. + * @param {TransitionEventInit} init What the event says. + */ + constructor(type, init) { + super(type, init); + this.propertyName = init.propertyName ?? ""; + } + } + ) + ); + const pad = /** @type {HTMLElement} */ (document.getElementById("pad")); + pad.style.transitionProperty = "opacity, transform"; + /** @type {{ transitionProperty: string, playState: string }[]} */ + let running = []; + Object.assign(pad, { getAnimations: () => running }); + /** @type {string[]} */ + const ended = []; + dialog.addEventListener("transitionend", (event) => + ended.push( + `${/** @type {HTMLElement} */ (event.target).id}:${ + /** @type {TransitionEvent} */ (event).propertyName + }`, + ), + ); + press("open"); + press("close"); + // An engine that takes the dialog out of the top layer at once runs no + // transition as it closes: the panel is said to have slid out. + expect(ended).toEqual(["pad:transform"]); + // Where the panel slides out, the browser says so when it has. + running = [{ transitionProperty: "transform", playState: "running" }]; + press("open"); + press("close"); + expect(ended).toEqual(["pad:transform"]); + // A panel without a transition of its transform says nothing. + running = []; + pad.style.transitionProperty = "opacity"; + press("open"); + press("close"); + expect(ended).toEqual(["pad:transform"]); +}); diff --git a/packages/reflex-components-ui/news/+drawer-firefox-safari.bugfix.md b/packages/reflex-components-ui/news/+drawer-firefox-safari.bugfix.md new file mode 100644 index 00000000000..37dfc83ad5f --- /dev/null +++ b/packages/reflex-components-ui/news/+drawer-firefox-safari.bugfix.md @@ -0,0 +1 @@ +In Firefox and Safari, an `rx.ui.drawer` calls its `on_animation_end` when it closes, as it does in Chromium, and Tab no longer stops on the drawer's own dialog. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py index e540ea27031..8a80a3bb15b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py @@ -328,9 +328,13 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: props: The props to render (if None, then use get_props). Returns: - The tag, which says when its panel has slid in or out. + The tag, out of the order of Tab, which says when its panel has + slid in or out. """ - tag = super()._render(props) + # The dialog covers the page and is nothing to stop on: Safari makes + # it a stop of Tab, as a box its panel overflows, where Radix's + # drawer has no element around its panel. + tag = super()._render(props).add_props(tab_index=-1) if self._on_animation_end is None: return tag handler = LiteralVar.create(self._on_animation_end) diff --git a/tests/units/reflex_components_ui/components/test_drawer.py b/tests/units/reflex_components_ui/components/test_drawer.py index 8c554cf861e..75b9d881893 100644 --- a/tests/units/reflex_components_ui/components/test_drawer.py +++ b/tests/units/reflex_components_ui/components/test_drawer.py @@ -80,6 +80,7 @@ def test_drawer( "onClose:dialogEvent", 'onTransitionEnd:((event) => event.propertyName === "transform" && event.target.parentElement === event.currentTarget && (((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("moved"))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))))(event.currentTarget.open))', "ref:((dialog) => dialogSync(dialog, null, null))", + "tabIndex:-1", ], "children": [ { @@ -319,6 +320,7 @@ def test_drawer_that_is_not_modal_nor_dismissible( "onCancel:dialogEvent", "onClose:dialogEvent", "ref:((dialog) => dialogSync(dialog, null, null))", + "tabIndex:-1", ], "children": [ { From ec5516b577f33ada51a6a2ed8d0fdeebe630c330 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 09:59:50 +0000 Subject: [PATCH 188/204] Say Escape closed an rx.ui popup wherever the focus was A popup recorded Escape as what closed it only from its own keydown, so one the browser dismissed on an Escape pressed before the focus had moved in was said to be dismissed from outside. popup.js now notes an Escape on the page, and the first popup that closes in its task was closed by it; popups, menus and selects take what closed them from closedBy(). Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../js/src/behaviors/listbox.js | 4 +-- .../js/src/behaviors/menu.js | 10 ++++-- .../js/src/behaviors/popup.js | 32 ++++++++++++++++++- .../js/tests/behaviors/popup.test.js | 29 +++++++++++++++++ .../news/+escape-before-focus.bugfix.md | 1 + 5 files changed, 71 insertions(+), 5 deletions(-) create mode 100644 packages/reflex-components-ui/news/+escape-before-focus.bugfix.md diff --git a/packages/reflex-components-ui/js/src/behaviors/listbox.js b/packages/reflex-components-ui/js/src/behaviors/listbox.js index af4ca2c9ced..c2f2bd77f04 100644 --- a/packages/reflex-components-ui/js/src/behaviors/listbox.js +++ b/packages/reflex-components-ui/js/src/behaviors/listbox.js @@ -7,7 +7,7 @@ // any input. Without this the select opens and closes, and chooses nothing. import { find, forget, move, typing } from "./keys.js"; -import { opener, pair, popupPlace, popupToggle } from "./popup.js"; +import { closedBy, opener, pair, popupPlace, popupToggle } from "./popup.js"; const OPTION = "[role=option]"; const ENABLED = `${OPTION}:not([aria-disabled=true])`; @@ -253,7 +253,7 @@ export function selectToggle(event, on) { return; } const open = popupToggle(event); - const by = popup.dataset.rxClosedBy; + const by = open ? popup.dataset.rxClosedBy : closedBy(popup); delete popup.dataset.rxClosedBy; forget(); on?.open?.(open); diff --git a/packages/reflex-components-ui/js/src/behaviors/menu.js b/packages/reflex-components-ui/js/src/behaviors/menu.js index 3f952ee81e8..57a79674d1c 100644 --- a/packages/reflex-components-ui/js/src/behaviors/menu.js +++ b/packages/reflex-components-ui/js/src/behaviors/menu.js @@ -9,7 +9,13 @@ // this a dropdown menu opens and closes, and its items do nothing. import { find, forget, move, typing } from "./keys.js"; -import { opener, popupPlace, popupSync, popupToggle } from "./popup.js"; +import { + closedBy, + opener, + popupPlace, + popupSync, + popupToggle, +} from "./popup.js"; const MENU = "[role=menu]"; const ITEM = "[role^=menuitem]"; @@ -269,7 +275,7 @@ export function menuEvent(event, on) { if (type === "beforetoggle") { if (target !== menu) return; const open = popupToggle(event); - const by = data.rxClosedBy; + const by = open ? data.rxClosedBy : closedBy(menu); delete data.rxClosedBy; forget(); if (open) { diff --git a/packages/reflex-components-ui/js/src/behaviors/popup.js b/packages/reflex-components-ui/js/src/behaviors/popup.js index 12599641a60..a65a65ab029 100644 --- a/packages/reflex-components-ui/js/src/behaviors/popup.js +++ b/packages/reflex-components-ui/js/src/behaviors/popup.js @@ -12,6 +12,36 @@ const ANCHORED = globalThis.CSS?.supports?.("position-area: bottom") ?? false; let ids = 0; +// Whether an Escape is being handled: the browser closes the popovers it +// dismisses in the task of the key, wherever the focus is. +let escaping = false; +globalThis.addEventListener?.( + "keydown", + (event) => { + if (event.key !== "Escape" || escaping) return; + escaping = true; + setTimeout(() => { + escaping = false; + }); + }, + true, +); + +/** + * Take what closed a popup that is closing: what a script said, or Escape + * when the popup closes in the task of the key. The key closes one popup: + * the first that closes after it. + * + * @param {HTMLElement} popup The popover. + * @returns {string | undefined} What closed it, if anything said. + */ +export function closedBy(popup) { + const by = popup.dataset.rxClosedBy ?? (escaping ? "escape" : undefined); + delete popup.dataset.rxClosedBy; + escaping = false; + return by; +} + /** * Find what opens a popup. * @@ -222,7 +252,7 @@ export function popupEvent(event, on) { } } else if (target === popup) { const open = popupToggle(event); - const by = data.rxClosedBy; + const by = open ? popup.dataset.rxClosedBy : closedBy(popup); delete data.rxClosedBy; if (open) { if (by !== "state") on?.open?.(open); diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js index 79b4a278cfa..5a3893634c9 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js @@ -361,6 +361,35 @@ test("a popover takes the focus when it opens, and says what closed it", async ( ]); }); +test("Escape closes a popover as Escape wherever the focus is", async () => { + const { api, popup, seen } = await popover(); + api.popupSync(popup); + popup.showPopover(); + // The focus is not in the popover yet: the browser closes it on the + // Escape all the same, in the task of the key. + document.body.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), + ); + popup.hidePopover(); + // What closes it in a later task is not the key. + popup.showPopover(); + await new Promise((resolve) => setTimeout(resolve)); + popup.hidePopover(); + expect(seen).toEqual([ + "open:true", + "openAutoFocus", + "escape", + "open:false", + "closeAutoFocus", + "open:true", + "openAutoFocus", + "outside", + "interact", + "open:false", + "closeAutoFocus", + ]); +}); + test("a popover closes when the focus leaves it for the page", async () => { const { api, popup, seen } = await popover(); popup.showPopover(); diff --git a/packages/reflex-components-ui/news/+escape-before-focus.bugfix.md b/packages/reflex-components-ui/news/+escape-before-focus.bugfix.md new file mode 100644 index 00000000000..29e639b9baf --- /dev/null +++ b/packages/reflex-components-ui/news/+escape-before-focus.bugfix.md @@ -0,0 +1 @@ +A menu, select or popover of `rx.ui` that Escape closes before the focus has moved into it calls `on_escape_key_down`, as Radix does, rather than `on_pointer_down_outside`. From 5f364631e4582526674d445b99cafec7963827bd Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 29 Nov 2026 10:43:03 +0000 Subject: [PATCH 189/204] Say a drawer has slid out after it says it closed; wait for both hover cards on focus - The transitionend a dialog gives a panel that does not slide out came before the dialog said it had closed, where a transition that runs ends after: it is now sent last. - The focus-visible cells of the hover card matrix captured Radix's card before it had opened: Radix opens it a task after the focus, rx.ui at once. The cell now waits for the card, as the hover and open cells do. Claude-Session: https://claude.ai/code/session_014AwvTPQrAAUS9U2MqKfT3k --- .../js/src/behaviors/dialog.js | 2 +- .../js/tests/behaviors/dialog.test.js | 21 ++++++++---- .../parity/ui_parity/components/hover_card.py | 33 +++++++++++++++++++ 3 files changed, 49 insertions(+), 7 deletions(-) diff --git a/packages/reflex-components-ui/js/src/behaviors/dialog.js b/packages/reflex-components-ui/js/src/behaviors/dialog.js index d67c5b1c223..70d13dbebe5 100644 --- a/packages/reflex-components-ui/js/src/behaviors/dialog.js +++ b/packages/reflex-components-ui/js/src/behaviors/dialog.js @@ -150,9 +150,9 @@ export function dialogEvent(event) { } const { on, bound } = dialogs.get(dialog) ?? {}; mark(dialog, false); - slidOut(dialog); if (!bound) on?.open?.(false); on?.closeAutoFocus?.(); + slidOut(dialog); } /** diff --git a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js index 7a5d768efa1..b2a0a8d0776 100644 --- a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js +++ b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js @@ -320,8 +320,8 @@ test("a panel that does not slide out says it has, as one that slides out does", /** @type {{ transitionProperty: string, playState: string }[]} */ let running = []; Object.assign(pad, { getAnimations: () => running }); - /** @type {string[]} */ - const ended = []; + const { on, seen: ended } = handlers(); + dialogSync(dialog, null, on); dialog.addEventListener("transitionend", (event) => ended.push( `${/** @type {HTMLElement} */ (event.target).id}:${ @@ -332,17 +332,26 @@ test("a panel that does not slide out says it has, as one that slides out does", press("open"); press("close"); // An engine that takes the dialog out of the top layer at once runs no - // transition as it closes: the panel is said to have slid out. - expect(ended).toEqual(["pad:transform"]); + // transition as it closes: the panel is said to have slid out, after the + // dialog has said it closed, as a transition that runs ends after it. + const once = [ + "open:true", + "openAutoFocus", + "open:false", + "closeAutoFocus", + "pad:transform", + ]; + expect(ended).toEqual(once); // Where the panel slides out, the browser says so when it has. running = [{ transitionProperty: "transform", playState: "running" }]; press("open"); press("close"); - expect(ended).toEqual(["pad:transform"]); + const unsaid = ["open:true", "openAutoFocus", "open:false", "closeAutoFocus"]; + expect(ended).toEqual([...once, ...unsaid]); // A panel without a transition of its transform says nothing. running = []; pad.style.transitionProperty = "opacity"; press("open"); press("close"); - expect(ended).toEqual(["pad:transform"]); + expect(ended).toEqual([...once, ...unsaid, ...unsaid]); }); diff --git a/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py index b44bc7a8391..fde44bf1c20 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py @@ -102,6 +102,36 @@ def _hide(page: Page, target: Locator, point: Point) -> None: page.locator(SHOWN).first.wait_for(state="detached") +def _focus_card(page: Page, target: Locator, point: Point) -> None: + """Focus the trigger of a card as the keyboard does, and wait for the card. + + Radix opens the card a task after the focus, rx.ui at once: the capture + waits for either, as it does for the pointer. + + Args: + page: The page. + target: The link. + point: The middle of the link. + """ + # A key press makes the keyboard the page's input, so the focus that + # follows shows its ring. + page.keyboard.press("Tab") + target.focus() + page.locator(SHOWN).first.wait_for() + + +def _blur_card(page: Page, target: Locator, point: Point) -> None: + """Take the focus off the trigger, and wait until the card is gone. + + Args: + page: The page. + target: The link. + point: The middle of the link. + """ + target.blur() + page.locator(SHOWN).first.wait_for(state="detached") + + MATRIX = Matrix( component="hover_card", render=_hover_card, @@ -129,6 +159,9 @@ def _hide(page: Page, target: Locator, point: Point) -> None: }, states={ OPEN: State(enter=_show, leave=_hide, matches="[data-state='open']"), + FOCUS_VISIBLE: State( + enter=_focus_card, leave=_blur_card, matches=":focus-visible" + ), }, # Held to a threshold of zero, and to the long card: the card of rx.ui # is no taller than the viewport and scrolls, and the browser draws the From 4d7acb782e976dd93bb3de48a1db03ec57cb0d59 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 13:13:20 +0000 Subject: [PATCH 190/204] Keep the subpath of a versioned library in its import format_library_name split `pkg@1.0.0/sub` at the last @ and dropped everything after it, so a component with that library imported from `pkg`. The subpath after a version now stays, unless the specifier is a location (a path, a protocol or a git ref), whose slashes are its own. The installer reads the package from either form. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- news/+versioned-library-subpath.misc.md | 1 + .../news/+versioned-library-subpath.bugfix.md | 1 + .../src/reflex_base/utils/format.py | 30 +++++++++++++--- reflex/app.py | 35 +++++++------------ tests/units/compiler/test_compiler.py | 10 ++++++ tests/units/test_app.py | 20 +++++++++++ tests/units/utils/test_format.py | 10 ++++++ 7 files changed, 81 insertions(+), 26 deletions(-) create mode 100644 news/+versioned-library-subpath.misc.md create mode 100644 packages/reflex-base/news/+versioned-library-subpath.bugfix.md diff --git a/news/+versioned-library-subpath.misc.md b/news/+versioned-library-subpath.misc.md new file mode 100644 index 00000000000..f2d3685f52a --- /dev/null +++ b/news/+versioned-library-subpath.misc.md @@ -0,0 +1 @@ +Share the check for location dependency specifiers (paths, protocols, git refs) with reflex-base. diff --git a/packages/reflex-base/news/+versioned-library-subpath.bugfix.md b/packages/reflex-base/news/+versioned-library-subpath.bugfix.md new file mode 100644 index 00000000000..ee2c18ddda1 --- /dev/null +++ b/packages/reflex-base/news/+versioned-library-subpath.bugfix.md @@ -0,0 +1 @@ +Keep the subpath of a versioned library: a component with `library = "pkg@1.0.0/sub"` now imports from `pkg/sub` instead of `pkg`. diff --git a/packages/reflex-base/src/reflex_base/utils/format.py b/packages/reflex-base/src/reflex_base/utils/format.py index bf31c0d5ee4..f8701fcbbfa 100644 --- a/packages/reflex-base/src/reflex_base/utils/format.py +++ b/packages/reflex-base/src/reflex_base/utils/format.py @@ -674,7 +674,8 @@ def format_library_name(library_fullname: str | dict[str, Any]) -> str: library_fullname: The library reference, either as a string or a dictionary with a 'name' key. Returns: - The name without the @version if it was part of the name + The name without the @version if it was part of the name, and with + the subpath that follows a version: ``pkg@1.0/sub`` is ``pkg/sub``. Raises: KeyError: If library_fullname is a dictionary without a 'name' key. @@ -695,13 +696,34 @@ def format_library_name(library_fullname: str | dict[str, Any]) -> str: if library_fullname.startswith("https://"): return library_fullname - lib, at, version = library_fullname.rpartition("@") + lib, _, specifier = library_fullname.rpartition("@") if not lib: - lib = at + version - + return library_fullname + _, slash, subpath = specifier.partition("/") + if slash and not is_location_specifier(specifier): + return f"{lib}/{subpath}" return lib +def is_location_specifier(specifier: str) -> bool: + """Check whether a dependency specifier points at a location. + + A location specifier names where a package comes from (a local path, a + protocol like ``file:``/``github:``/``git+ssh:``, or a git ref) instead of + naming a version. Its slashes belong to the location, so it must be kept + whole rather than split into a version and a package subpath. + + Args: + specifier: The part of an import name following ``package@``. + + Returns: + Whether the specifier is a location rather than a version or dist-tag. + """ + return ( + ":" in specifier or "#" in specifier or specifier.startswith((".", "/", "~/")) + ) + + _serialize: Callable[[Any], Any] | None = None diff --git a/reflex/app.py b/reflex/app.py index afa3f737a62..cd3b8b48570 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -497,25 +497,6 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await socket.close(wait=False) -def _is_location_specifier(specifier: str) -> bool: - """Check whether a dependency specifier points at a location. - - A location specifier names where a package comes from (a local path, a - protocol like ``file:``/``github:``/``git+ssh:``, or a git ref) instead of - naming a version. Its slashes belong to the location, so it must be kept - whole rather than split into a version and a package subpath. - - Args: - specifier: The part of an import name following ``package@``. - - Returns: - Whether the specifier is a location rather than a version or dist-tag. - """ - return ( - ":" in specifier or "#" in specifier or specifier.startswith((".", "/", "~/")) - ) - - _DEFAULT_PORTS = {"http": 80, "https": 443} @@ -2166,10 +2147,20 @@ def _get_frontend_package_name(import_name: str) -> str | None: else: package_name = library_name.split("/", maxsplit=1)[0] - if import_name.startswith(f"{library_name}@"): - specifier = import_name[len(library_name) + 1 :] + # The version follows the package (``pkg@1.0/sub``) or its subpath + # (``pkg/sub@1.0``). + pinned = next( + ( + name + for name in (package_name, library_name) + if import_name.startswith(f"{name}@") + ), + None, + ) + if pinned is not None: + specifier = import_name[len(pinned) + 1 :] version, slash, _ = specifier.partition("/") - if slash and not _is_location_specifier(specifier): + if slash and not format.is_location_specifier(specifier): return f"{package_name}@{version}" return f"{package_name}@{specifier}" diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 9d3da9df03e..e96a4bf1d22 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -267,6 +267,16 @@ def test_compile_import_statement( {"lib": "axios", "default": "axios", "rest": []}, ], ), + ( + { + "@ui-sdk/react@0.1.0-beta.17/tabs": [ImportVar(tag="Tabs")], + "react-map-gl@1.0.0/maplibre": [ImportVar(tag="Map")], + }, + [ + {"lib": "@ui-sdk/react/tabs", "default": "", "rest": ["Tabs"]}, + {"lib": "react-map-gl/maplibre", "default": "", "rest": ["Map"]}, + ], + ), ], ) def test_compile_imports(import_dict: ParsedImportDict, test_dicts: list[dict]): diff --git a/tests/units/test_app.py b/tests/units/test_app.py index fd1522a39f7..56a3311ae0a 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -3926,6 +3926,26 @@ def test_get_frontend_packages_maps_versioned_subpath_imports_to_pinned_base( assert "@scope/pkg@2.0.0/subpath" not in install_set +def test_get_frontend_packages_installs_the_package_of_pinned_subpaths( + mocker: MockerFixture, +): + """Imports of subpaths of a pinned package install the package once, pinned.""" + conf = rx.Config(app_name="testing") + mocker.patch("reflex.app.get_config", return_value=conf) + install_frontend_packages = mocker.patch( + "reflex.app.js_runtimes.install_frontend_packages" + ) + + App(theme=None)._get_frontend_packages({ + "@ui-sdk/react@0.1.0-beta.17/tabs": {ImportVar(tag="Tabs")}, + "@ui-sdk/react@0.1.0-beta.17/dialog": {ImportVar(tag="Dialog")}, + "@ui-sdk/core@0.1.0-beta.17": {ImportVar(tag=None, render=False)}, + }) + + install_set, _ = install_frontend_packages.call_args.args + assert install_set == {"@ui-sdk/react@0.1.0-beta.17", "@ui-sdk/core@0.1.0-beta.17"} + + def test_get_frontend_packages_keeps_local_and_git_specifiers_intact( mocker: MockerFixture, ): diff --git a/tests/units/utils/test_format.py b/tests/units/utils/test_format.py index 0534734aa6e..6ea6a62b921 100644 --- a/tests/units/utils/test_format.py +++ b/tests/units/utils/test_format.py @@ -851,6 +851,16 @@ def test_format_array_ref(input, output): ("library", "library"), ("@library@^0.1.2", "@library"), ("@library", "@library"), + ("@ui-sdk/react@0.1.0-beta.17/tabs", "@ui-sdk/react/tabs"), + ("library@1.0.0/sub/path", "library/sub/path"), + ("@scope/library/sub@1.0.0", "@scope/library/sub"), + ("library@../library", "library"), + ("library@./vendor/library", "library"), + ("library@/opt/library", "library"), + ("library@~/library", "library"), + ("library@file:../library", "library"), + ("library@github:owner/library", "library"), + ("library@owner/library#main", "library"), ], ) def test_format_library_name(input: str, output: str): From f2df1885dafd24bfd55eda1a3a7e0550ceb8426c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 14:17:44 +0000 Subject: [PATCH 191/204] Pilot: rx.ui tabs, dropdown_menu and dialog on UI SDK parts The three components render the React parts of @ui-sdk/react 0.1.0-beta.17 (pinned, installed only by a page that renders one) with rx.ui's StyleX classes; their hand-written behaviour goes (tabs.js; dialog.js, menu.js and popup.js stay for alert_dialog, drawer, context_menu, popover and select). - SDKPart: a part of UI SDK styled as any rx.ui element; a trigger or a close button renders as its child through `render`, and the page collects that child's styles, custom code and app styles. - The events Radix fires on the content of a dialog or a menu are called by the reason UI SDK gives for a change, before the change, as in Radix. - A dialog is UI SDK's backdrop and its content, the panel, in the top layer; a dropdown menu is placed by UI SDK with Radix Themes' offsets. - UI SDK's state attributes (data-open, data-highlighted, data-disabled, data-ending-style) select the styles; base.css places the ui-sdk cascade layer under rx.ui's. - The parity harness reads UI SDK's markup; the allowlist drops the entry for Tab leaving a dialog, which UI SDK keeps inside as Radix. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- docs/styling/rx-ui-migration.md | 1 - packages/reflex-components-ui/js/src/base.css | 14 +- .../js/src/behaviors/tabs.js | 59 -- .../js/tests/behaviors/tabs.test.js | 189 ---- .../news/+ui-sdk-pilot.feature.md | 1 + .../parity/allowlist.toml | 5 - .../parity/ui_parity/components/dialog.py | 22 +- .../ui_parity/components/dropdown_menu.py | 16 +- .../reflex_components_ui/components/_sdk.py | 211 ++++ .../reflex_components_ui/components/dialog.py | 236 ++++- .../components/dropdown_menu.py | 411 +++++++- .../reflex_components_ui/components/tabs.py | 344 ++----- .../src/reflex_components_ui/constants.py | 7 + .../src/reflex_components_ui/styles/button.py | 8 +- .../src/reflex_components_ui/styles/card.py | 3 +- .../src/reflex_components_ui/styles/dialog.py | 64 ++ .../src/reflex_components_ui/styles/menu.py | 298 +++--- .../src/reflex_components_ui/styles/popup.py | 24 + .../src/reflex_components_ui/styles/tabs.py | 2 +- pyi_hashes.json | 7 +- .../components/test_button.py | 86 +- .../components/test_card.py | 46 +- .../components/test_color_mode.py | 39 +- .../components/test_dialog.py | 592 ++--------- .../components/test_dropdown_menu.py | 682 +++++-------- .../components/test_form.py | 2 +- .../components/test_icon_button.py | 26 +- .../components/test_popup.py | 22 +- .../components/test_skeleton.py | 32 +- .../components/test_tabs.py | 949 ++---------------- .../migrate_fixtures/radix_kept/report.txt | 2 +- 31 files changed, 1765 insertions(+), 2635 deletions(-) delete mode 100644 packages/reflex-components-ui/js/src/behaviors/tabs.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/tabs.test.js create mode 100644 packages/reflex-components-ui/news/+ui-sdk-pilot.feature.md create mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index 3bdba7b0af6..c1bf99e0168 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -205,7 +205,6 @@ counterpart, kept in sync with the parity checks of `rx.ui`: - behaviour, `rx`, "what it holds is in the server render": rx.dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.dialog holds is in the page from the start, in a dialog that is closed, so it is there for a search engine and for the browser's find in page once the dialog is open, and it keeps its state between two openings. - behaviour, `rx`, "opens and closes with JavaScript disabled": rx.dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript. -- behaviour, `rx.ui`, "Tab stays inside an open dialog": rx.ui.dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.dialog keeps the focus from leaving the dialog at all. - behaviour, `rx`, "the dark appearance of a theme around a dialog reaches its panel": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a dialog included. rx.ui.theme does, and a dialog declared inside a dark rx.ui.theme is dark: its panel, what it holds and what is drawn over the page behind it. - style, `pointer-events`: While it is open rx.dialog takes the pointer off the rest of the page with a style on the body. rx.ui.dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style. diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index 78673115992..0851a6ad885 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -3,12 +3,24 @@ * not depend on which stylesheet loads first. Later layers win: * * __reflex_base, theme, base resets: Reflex's own, Tailwind's theme and preflight + * ui-sdk what UI SDK's behaviours add, such as hiding closed content * 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; +@layer __reflex_base, theme, base, ui-sdk, reflex-ui, components, utilities; + +/* + * What UI SDK adds once a component mounts, here for the page the server + * renders: closed content it keeps in the page carries `hidden`, which a + * class that sets `display` would otherwise show until hydration. + */ +@layer ui-sdk { + :where([data-slot][hidden]:not([hidden="until-found"])) { + display: none !important; + } +} /* * Reflex's color mode provider sets one of these classes on the root element. diff --git a/packages/reflex-components-ui/js/src/behaviors/tabs.js b/packages/reflex-components-ui/js/src/behaviors/tabs.js deleted file mode 100644 index 0402a4102ec..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/tabs.js +++ /dev/null @@ -1,59 +0,0 @@ -// What tabs do that the browser leaves to a script: a press on a trigger, -// or the focus moving to one, selects it and shows its panel. -// -// The state is the DOM: the selected trigger says so in `aria-selected`, -// and every other panel is `hidden`. The server renders both, so without -// this the tabs show the panel they start with. The arrow keys are the -// ones of `roving-focus.js`. - -/** - * Follow a press on a trigger and the focus moving between triggers: the - * `onClick`, the `onFocus` and the `onBlur` of the element around tabs. - * - * Tab stops on one trigger: the one that has the focus, and the selected - * one once the focus has left. A trigger is selected by a press, and by the - * focus unless the tabs are activated by hand. Tabs bound to state say so - * to their state, and show what it holds. - * - * @param {{ type: string, target: EventTarget | null, currentTarget: HTMLElement, relatedTarget?: EventTarget | null }} event - * The press, or the focus coming or going. - * @param {(value: string) => void} [onChange] What the tabs do when another - * trigger is selected. - * @returns {void} - */ -export function tabsEvent(event, onChange) { - const root = event.currentTarget; - // The parts of these tabs, and not the ones of tabs inside them. - const own = (/** @type {string} */ role) => - /** @type {HTMLElement[]} */ ( - [...root.querySelectorAll(`[role=${role}]`)].filter( - (part) => part.closest("[data-rx-tabs]") === root, - ) - ); - const tabs = own("tab"); - const inside = (/** @type {EventTarget | null | undefined} */ node) => - tabs.find((tab) => tab.contains(/** @type {Node | null} */ (node))); - const target = inside(event.target); - const left = event.type === "blur"; - if (!target || (left && inside(event.relatedTarget))) return; - const stop = left - ? (tabs.find((tab) => tab.ariaSelected === "true") ?? target) - : target; - for (const tab of tabs) tab.tabIndex = tab === stop ? 0 : -1; - if ( - left || - target.ariaSelected === "true" || - target.matches(":disabled") || - (event.type === "focus" && root.dataset.activation === "manual") - ) - return; - const value = target.dataset.value ?? ""; - onChange?.(value); - if (root.dataset.rxTabs) return; - for (const part of [...tabs, ...own("tabpanel")]) { - const on = part.dataset.value === value; - part.dataset.state = on ? "active" : "inactive"; - if (part.role === "tab") part.ariaSelected = String(on); - else part.hidden = !on; - } -} diff --git a/packages/reflex-components-ui/js/tests/behaviors/tabs.test.js b/packages/reflex-components-ui/js/tests/behaviors/tabs.test.js deleted file mode 100644 index b2835741448..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/tabs.test.js +++ /dev/null @@ -1,189 +0,0 @@ -// What tabs do with a press on a trigger and with the focus: one trigger is -// selected and its panel shown, and Tab stops on one trigger. -import { beforeEach, expect, test, vi } from "vitest"; - -import { tabsEvent } from "$/reflex-ui/behaviors/tabs.js"; - -/** @type {HTMLElement} */ -let root; - -/** - * Render tabs, with tabs of their own in the first panel. - * - * @param {string} [attributes] The attributes of the element around them. - * @returns {void} - */ -function render(attributes = 'data-rx-tabs=""') { - document.body.innerHTML = ` -
-
- - - - -
-
-
- - -
-
- - -
`; - root = /** @type {HTMLElement} */ (document.getElementById("root")); -} - -beforeEach(() => render()); - -/** - * Send the tabs an event of one of their elements. - * - * @param {string} type The type of the event. - * @param {string} id The id of the element it happens on. - * @param {{ to?: string, onChange?: (value: string) => void }} [options] - * Where the focus goes, and what the tabs do when they change. - * @returns {void} - */ -function send(type, id, { to, onChange } = {}) { - tabsEvent( - { - type, - target: document.getElementById(id), - currentTarget: root, - relatedTarget: to ? document.getElementById(to) : null, - }, - onChange, - ); -} - -/** - * Read the state of the tabs. - * - * @returns {string[]} For each of their own triggers whether it is - * selected, its state and its place in the Tab order, then each panel - * that is shown. - */ -function state() { - return [ - ...["a", "b", "c"].map((id) => { - const tab = /** @type {HTMLElement} */ (document.getElementById(id)); - return `${id}:${tab.getAttribute("aria-selected")}:${tab.dataset.state}:${tab.tabIndex}`; - }), - ...[...root.querySelectorAll(":scope > [role=tabpanel]:not([hidden])")].map( - (panel) => - `${/** @type {HTMLElement} */ (panel).dataset.value}:${/** @type {HTMLElement} */ (panel).dataset.state}`, - ), - ]; -} - -const START = [ - "a:true:active:0", - "b:false:inactive:-1", - "c:false:inactive:-1", - "a:active", -]; -const SECOND = [ - "a:false:inactive:-1", - "b:true:active:0", - "c:false:inactive:-1", - "b:active", -]; - -test("a press on a trigger selects it, shows its panel and says so once", () => { - const onChange = vi.fn(); - send("click", "b", { onChange }); - expect(state()).toEqual(SECOND); - send("click", "b", { onChange }); - expect(onChange.mock.calls).toEqual([["b"]]); - send("click", "a"); - expect(state()).toEqual(START); -}); - -test("a press inside a trigger is a press on it", () => { - /** @type {HTMLElement} */ (document.getElementById("b")).innerHTML = - 'B'; - send("click", "text"); - expect(state()).toEqual(SECOND); -}); - -test("the focus selects a trigger, unless the tabs are activated by hand", () => { - send("focus", "b"); - expect(state()).toEqual(SECOND); - render('data-rx-tabs="" data-activation="manual"'); - const onChange = vi.fn(); - send("focus", "b", { onChange }); - expect(state()).toEqual([ - "a:true:active:-1", - "b:false:inactive:0", - "c:false:inactive:-1", - "a:active", - ]); - expect(onChange.mock.calls).toEqual([]); - send("click", "b", { onChange }); - expect(state()).toEqual(SECOND); - expect(onChange.mock.calls).toEqual([["b"]]); -}); - -test("Tab stops on the selected trigger again once the focus has left", () => { - render('data-rx-tabs="" data-activation="manual"'); - send("focus", "b"); - send("blur", "b", { to: "a" }); - expect(state()[1]).toBe("b:false:inactive:0"); - send("blur", "b", { to: "other" }); - expect(state()).toEqual(START); - /** @type {HTMLElement} */ (document.getElementById("a")).setAttribute( - "aria-selected", - "false", - ); - send("focus", "b"); - send("blur", "b"); - expect(state()[1]).toBe("b:false:inactive:0"); -}); - -test("a disabled trigger is not selected", () => { - const onChange = vi.fn(); - send("click", "c", { onChange }); - expect(state()).toEqual([ - "a:true:active:-1", - "b:false:inactive:-1", - "c:false:inactive:0", - "a:active", - ]); - expect(onChange.mock.calls).toEqual([]); -}); - -test("tabs bound to state say what was selected and change nothing", () => { - render('data-rx-tabs="bound"'); - const onChange = vi.fn(); - send("click", "b", { onChange }); - expect(onChange.mock.calls).toEqual([["b"]]); - expect(state()).toEqual([ - "a:true:active:-1", - "b:false:inactive:0", - "c:false:inactive:-1", - "a:active", - ]); -}); - -test("what is no trigger of the tabs is left alone", () => { - const onChange = vi.fn(); - send("click", "other", { onChange }); - send("click", "inner", { onChange }); - send("focus", "inner", { onChange }); - tabsEvent({ type: "click", target: null, currentTarget: root }, onChange); - expect(state()).toEqual(START); - expect(onChange.mock.calls).toEqual([]); - expect( - /** @type {HTMLElement} */ (document.getElementById("inner-panel")).hidden, - ).toBe(true); -}); - -test("a trigger without a value selects the tab of no value", () => { - /** @type {HTMLElement} */ (document.getElementById("b")).removeAttribute( - "data-value", - ); - const onChange = vi.fn(); - send("click", "b", { onChange }); - expect(onChange.mock.calls).toEqual([[""]]); -}); diff --git a/packages/reflex-components-ui/news/+ui-sdk-pilot.feature.md b/packages/reflex-components-ui/news/+ui-sdk-pilot.feature.md new file mode 100644 index 00000000000..bd9cc528e91 --- /dev/null +++ b/packages/reflex-components-ui/news/+ui-sdk-pilot.feature.md @@ -0,0 +1 @@ +`rx.ui.tabs`, `rx.ui.dropdown_menu` and `rx.ui.dialog` get their behaviour from [UI SDK](https://ui-sdk.dev) (`@ui-sdk/react` and `@ui-sdk/core`, pinned to `0.1.0-beta.17`, installed only by a page that renders one): the Python API and the look are unchanged. A disabled tab is focusable, as the ARIA tabs pattern asks, and a closed dialog or menu, and an unselected panel, are not in the page until they open, as in Radix. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index ab656b850e4..8fa0a9d4485 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -433,11 +433,6 @@ step = "opens and closes with JavaScript disabled" system = "rx" reason = "rx.dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript." -[[contract]] -component = "dialog" -step = "Tab stays inside an open dialog" -reason = "rx.ui.dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.dialog keeps the focus from leaving the dialog at all." - [[contract]] component = "dialog" step = "the dark appearance of a theme around a dialog reaches its panel" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py index 827fe69d539..66d2f74987b 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py @@ -107,15 +107,25 @@ def close_dialog(page: Page, target: Locator, point: Point) -> None: # the page, an overlay around a panel; rx.ui renders a native dialog, which # draws the overlay with its ::before, around a panel. _RADIX = ".rt-BaseDialogContent" +# The parts of rx.ui.dialog are those of UI SDK: its content is the panel, +# and its backdrop what is drawn over the page. +_UI = "[data-slot=dialog-content][data-open]" PARTS = { - "overlay": (in_page(".rt-BaseDialogOverlay::before"), "dialog[open]::before"), - "content": (in_page(_RADIX), "dialog[open] > div > div"), - "title": (in_page(f"{_RADIX} h1"), "dialog[open] h1"), - "description": (in_page(f"{_RADIX} p"), "dialog[open] p"), - "close": (in_page(f"{_RADIX} button"), "dialog[open] button"), + "overlay": ( + in_page(".rt-BaseDialogOverlay::before"), + "[data-slot=dialog-backdrop]", + ), + "content": (in_page(_RADIX), _UI), + "title": (in_page(f"{_RADIX} h1"), f"{_UI} h1"), + "description": (in_page(f"{_RADIX} p"), f"{_UI} p"), + "close": (in_page(f"{_RADIX} button"), f"{_UI} button"), } -OPENED = State(enter=open_dialog, leave=close_dialog, matches="[data-state='open']") +OPENED = State( + enter=open_dialog, + leave=close_dialog, + matches=":is([data-state='open'], [data-open])", +) MATRIX = Matrix( component="dialog", diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py index 48270130029..f34f3e628f2 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/dropdown_menu.py @@ -191,7 +191,9 @@ def close_menu(page: Page, target: Locator, point: Point) -> None: page.evaluate("document.activeElement.blur()") -OPENED = State(enter=open_menu, leave=close_menu, matches="[data-state='open']") +OPENED = State( + enter=open_menu, leave=close_menu, matches=":is([data-state='open'], [data-open])" +) MATRIX = Matrix( component="dropdown_menu", @@ -219,8 +221,16 @@ def close_menu(page: Page, target: Locator, point: Point) -> None: parts=PARTS, states={ OPEN: OPENED, - KEYS: State(enter=_open_keys, leave=close_menu, matches="[data-state='open']"), - SUB: State(enter=_open_sub, leave=close_menu, matches="[data-state='open']"), + KEYS: State( + enter=_open_keys, + leave=close_menu, + matches=":is([data-state='open'], [data-open])", + ), + SUB: State( + enter=_open_sub, + leave=close_menu, + matches=":is([data-state='open'], [data-open])", + ), }, # Not held to a threshold of zero. At zero 49 of the 61 cells are equal # pixel for pixel. In the 11 with a sub-menu open, the shadows of the diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py new file mode 100644 index 00000000000..1f2079e3865 --- /dev/null +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py @@ -0,0 +1,211 @@ +"""What the components built on UI SDK share: its parts, styled with StyleX. + +UI SDK (``@ui-sdk/react`` over ``@ui-sdk/core``) gives a component its +behaviour: focus, keys, ARIA, dismissal and placement. rx.ui gives it its +look: a part takes the class names of its style table through +``className``, which every part of UI SDK joins with its own, and a style +selects the state the part renders, such as ``[data-open]`` or +``[aria-selected='true']``. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Sequence +from typing import Any, ClassVar + +from reflex_base.components.component import ( + BaseComponent, + Component, + LiteralComponentVar, +) +from reflex_base.components.tags import CommonTag +from reflex_base.vars.base import LiteralVar, Var, VarData + +from reflex_components_ui.base import UIComponent +from reflex_components_ui.constants import UI_SDK_CORE, UI_SDK_REACT +from reflex_components_ui.style import StyleError + + +class SDKPart(UIComponent): + """A part of a component of UI SDK, which renders the element it styles. + + A subclass names the entry point of ``@ui-sdk/react`` it comes from in + ``library`` and its export in ``tag``. The page that renders it installs + and bundles UI SDK; no other page does. + """ + + _is_tag_in_global_scope: ClassVar[bool] = False + + lib_dependencies: list[str] = [UI_SDK_CORE] + + # The props of rx.ui named otherwise by UI SDK, as they are rendered. + _sdk_names: ClassVar[dict[str, str]] = {} + + # Whether the part renders as its only child, as a trigger does. + _renders_child: ClassVar[bool] = False + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create the part. + + Args: + *children: Its children, or the one element it renders as. + **props: The properties of the part. + + Returns: + The part. + + Raises: + StyleError: If a part that renders as its child is not given + exactly one element. + """ + if not cls._renders_child: + return super().create(*children, **props) + # Its props are checked first: an error about them is the more useful. + part = super().create(**props) + if len(children) != 1 or not isinstance(children[0], Component): + msg = ( + f"{cls._display_name()}: it is rendered as its child, so it " # pyright: ignore[reportAttributeAccessIssue] + "needs exactly one child that is an element, such as a button." + ) + raise StyleError(msg) + part._child = children[0] # pyright: ignore[reportAttributeAccessIssue] + part._element = element(children[0]) # pyright: ignore[reportAttributeAccessIssue] + return part + + def _post_init(self, *args, **kwargs): + """Initialize the part, as one that renders its own element. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # The element the part renders as, through the `render` prop, and + # the component it is made from. + self._child: Component | None = None + self._element: Var | None = None + super()._post_init(*args, **kwargs) + + def _get_components_in_props(self) -> Sequence[BaseComponent]: + """Get the components in the props, the element the part renders as included. + + Its styles, hooks and custom code belong to the page as those of a + child do. + + Returns: + The components. + """ + own = super()._get_components_in_props() + return own if self._child is None else [*own, self._child] + + def _add_style_recursive(self, style: Any, theme: Component | None = None): + """Add the styles of the app to the part, the element it renders as included. + + Args: + style: A dict from component to styling. + theme: The theme to apply. + + Returns: + The part with the additional style. + """ + result = super()._add_style_recursive(style, theme) + if self._child is not None: + self._child = self._child._add_style_recursive(style, theme) + self._element = element(self._child) + return result + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the part, the element it renders as 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) + if self._element is not None: + yield self._element + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the part, its props under the names UI SDK gives them. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. + """ + tag = super()._render(props) + if self._sdk_names: + tag = tag.set( + props={ + self._sdk_names.get(name, name): value + for name, value in tag.props.items() + } + ) + if self._element is not None: + tag = tag.add_props(render=self._element) + return tag + + +def entry(name: str) -> str: + """Name an entry point of ``@ui-sdk/react``, at the version rx.ui pins. + + Args: + name: The entry point, such as ``tabs``. + + Returns: + The library a part imports from. + """ + return f"{UI_SDK_REACT}/{name}" + + +def element(component: Component) -> Var: + """Pass a component to the ``render`` prop of a part, which renders as it. + + The part merges its props with those of the element: this is the + ``as_child`` of Radix. + + Args: + component: The element the part renders as. + + Returns: + The element, as a value of a prop. + """ + return LiteralComponentVar.create(component) + + +def on_change(handlers: dict[str, Any], body: str) -> Var | None: + """Write a change callback of UI SDK that calls the handlers of rx.ui. + + A callback of UI SDK takes the requested value and the details of the + change, whose reason says what asked for it. Radix has an event of its + own for some reasons, such as ``on_escape_key_down``. + + Args: + handlers: Each handler the body calls, by its name in the body, or + None where the component has none. + body: The body of ``(value, details) => { ... }``, calling the + handlers with ``?.()``. + + Returns: + The callback, or None when no handler is given. + """ + given = {name: handler for name, handler in handlers.items() if handler is not None} + if not given: + return None + literals = {name: LiteralVar.create(handler) for name, handler in given.items()} + names = ", ".join( + f"{name} = {literals[name]!s}" if name in literals else f"{name} = undefined" + for name in handlers + ) + return Var( + f"((value, details) => {{ const {names}; {body} }})", + _var_data=VarData.merge( + *(literal._get_all_var_data() for literal in literals.values()) + ), + ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py index 717f12e2f18..6e5bb98bd06 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py @@ -1,32 +1,71 @@ -"""A dialog: a native modal ``dialog``, and what opens and closes it.""" +"""A dialog: the parts of ``@ui-sdk/react/dialog``, in the look of Radix Themes. + +UI SDK opens the dialog in the top layer, makes the page behind it inert, +keeps the focus inside, closes it on Escape and on a press beside its panel, +and gives the focus back to its trigger. +""" from __future__ import annotations +from collections.abc import Iterator, Sequence from typing import Any, ClassVar, Literal -from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.component import ( + BaseComponent, + Component, + ComponentNamespace, + field, +) +from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex_base.vars.base import Var +from reflex_components_core.base.fragment import Fragment from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.el import elements -from reflex_components_ui.base import UIComponent -from reflex_components_ui.components._dialog import ( - DialogDescriptionBase, - DialogRootBase, - DialogSlot, - DialogSurface, - DialogTitleBase, - DialogTriggerBase, - surface, -) +from reflex_components_ui.components._group import descendants +from reflex_components_ui.components._sdk import SDKPart, element, entry, on_change from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.dialog import DIALOG_CONTENT +from reflex_components_ui.styles.dialog import ( + DIALOG_DESCRIPTION, + DIALOG_TITLE, + SDK_DIALOG_BACKDROP, + SDK_DIALOG_CONTENT, +) +_LIBRARY = entry("dialog") -class DialogRoot(DialogRootBase): +# The events Radix fires on the content of a dialog, which UI SDK says as +# the reason of a change of the dialog. +_EVENTS = ( + "on_open_auto_focus", + "on_close_auto_focus", + "on_escape_key_down", + "on_pointer_down_outside", + "on_interact_outside", +) + +# What the dialog does when it opens or closes, by the reason: as in Radix, +# what dismissed it is said before it closes. +_ON_OPEN_CHANGE = ( + 'if (details?.reason === "escape-key") escape?.();' + ' if (details?.reason === "outside-press") { outside?.(); interact?.(); }' + " change?.(value);" + " if (value) openAutoFocus?.(); else closeAutoFocus?.();" +) + + +# The heading of the first level a title renders as, as in Radix Themes. +_H1 = elements.H1.create() + + +class DialogRoot(SDKPart): """Root component for Dialog.""" + library = _LIBRARY + + tag = "Dialog" + open: Var[bool] = field(doc="The controlled open state of the dialog.") on_open_change: EventHandler[passthrough_event_spec(bool)] = field( @@ -37,58 +76,135 @@ class DialogRoot(DialogRootBase): doc="The open state of the dialog when it is initially rendered. Use when you do not need to control its open state." ) + def _post_init(self, *args, **kwargs): + """Initialize the dialog, and take the events of its content. -class DialogTrigger(DialogTriggerBase): + Radix fires them on the content; UI SDK says on the dialog why it + opens or closes. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + triggers = self.event_triggers + events = {"change": triggers.pop("on_open_change", None)} + for content in descendants(self, DialogContent, DialogRoot): + own = content.event_triggers + for event in _EVENTS: + events[event] = own.pop(event, None) + self._on_open_change = on_change( + { + "change": events["change"], + "openAutoFocus": events.get("on_open_auto_focus"), + "closeAutoFocus": events.get("on_close_auto_focus"), + "escape": events.get("on_escape_key_down"), + "outside": events.get("on_pointer_down_outside"), + "interact": events.get("on_interact_outside"), + }, + _ON_OPEN_CHANGE, + ) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the dialog, what it does on a change 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) + if self._on_open_change is not None: + yield self._on_open_change + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the dialog, which is no element. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, which calls the events of Radix by the reason of a change. + """ + tag = super()._render(props) + if self._on_open_change is None: + return tag + return tag.add_props(onOpenChange=self._on_open_change) + + +class DialogTrigger(SDKPart): """Trigger an action or event, to open a Dialog modal.""" + library = _LIBRARY + + tag = "DialogTrigger" + + _renders_child: ClassVar[bool] = True -class DialogTitle(DialogTitleBase): + +class DialogTitle(SDKPart): """Title component to display inside a Dialog modal.""" + library = _LIBRARY -class DialogOverlay(DialogSurface): - """The native dialog around the content of a Dialog modal.""" + tag = "DialogTitle" - on_open_change: EventHandler[passthrough_event_spec(bool)] = field( - doc="Fired when the open state changes." - ) + styles: ClassVar[ComponentStyles] = DIALOG_TITLE - on_open_auto_focus: EventHandler[no_args_event_spec] = field( - doc="Fired when the dialog is opened." - ) + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the title, a heading of the first level as in Radix Themes. - on_close_auto_focus: EventHandler[no_args_event_spec] = field( - doc="Fired when the dialog is closed." - ) + Args: + props: The props to render (if None, then use get_props). - on_escape_key_down: EventHandler[no_args_event_spec] = field( - doc="Fired when the escape key is pressed." - ) + Returns: + The tag. + """ + return super()._render(props).add_props(render=element(self._heading)) - on_pointer_down_outside: EventHandler[no_args_event_spec] = field( - doc="Fired when the pointer is down outside the dialog." - ) + def _get_components_in_props(self) -> Sequence[BaseComponent]: + """Get the components in the props, the heading the title renders as included. - on_interact_outside: EventHandler[no_args_event_spec] = field( - doc="Fired when the pointer interacts outside the dialog." - ) + Returns: + The components. + """ + return [*super()._get_components_in_props(), self._heading] + @property + def _heading(self) -> Component: + """The heading the title renders as. -_EVENTS = ( - "on_open_auto_focus", - "on_close_auto_focus", - "on_escape_key_down", - "on_pointer_down_outside", - "on_interact_outside", -) + Returns: + An ``h1`` with nothing of its own. + """ + return _H1 + + +class DialogOverlay(SDKPart): + """The backdrop of UI SDK: what is drawn over the page behind a dialog. + + A press on it is a press outside the dialog, which closes it. + """ + library = _LIBRARY -class DialogContent(UIComponent, elements.Div): + tag = "DialogBackdrop" + + styles: ClassVar[ComponentStyles] = SDK_DIALOG_BACKDROP + + +class DialogContent(SDKPart, elements.Div): """Content component to display inside a Dialog modal.""" - tag = "div" + library = _LIBRARY - styles: ClassVar[ComponentStyles] = DIALOG_CONTENT + tag = "DialogContent" + + styles: ClassVar[ComponentStyles] = SDK_DIALOG_CONTENT size: Var[Responsive[Literal["1", "2", "3", "4"]]] = field( doc='DialogContent size "1" - "4"' @@ -116,27 +232,39 @@ class DialogContent(UIComponent, elements.Div): @classmethod def create(cls, *children: Any, **props: Any) -> Component: - """Create a DialogContent. + """Create a DialogContent, after what is drawn over the page behind it. Args: *children: What the dialog holds. - **props: The properties of the component. Its styles are those - of the panel, and its events those of the dialog around it. + **props: The properties of the panel. Returns: - The native dialog, around the panel. + The backdrop, then the panel. """ - events = {event: props.pop(event) for event in _EVENTS if event in props} - return surface(DialogOverlay, super().create(*children, **props), events) + return Fragment.create( + DialogOverlay.create(), super().create(*children, **props) + ) -class DialogDescription(DialogDescriptionBase): +class DialogDescription(SDKPart): """Description component to display inside a Dialog modal.""" + library = _LIBRARY + + tag = "DialogDescription" -class DialogClose(DialogSlot): + styles: ClassVar[ComponentStyles] = DIALOG_DESCRIPTION + + +class DialogClose(SDKPart): """Close button component to close an open Dialog modal.""" + library = _LIBRARY + + tag = "DialogClose" + + _renders_child: ClassVar[bool] = True + class Dialog(ComponentNamespace): """Dialog components namespace.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py index 20ba7fee912..5946089ec37 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py @@ -1,26 +1,34 @@ -"""A dropdown menu: a native ``popover`` of items, beside the button that opens it.""" +"""A dropdown menu: the parts of ``@ui-sdk/react/menu``, in the look of Radix Themes. + +UI SDK opens the menu in the top layer beside its trigger, places it, +moves through its items with the keys and by typing, opens its sub-menus +and closes it on Escape, on a press outside and on a choice. +""" from __future__ import annotations -from typing import ClassVar, Literal +from collections.abc import Iterator +from typing import Any, ClassVar, Literal -from reflex_base.components.component import ComponentNamespace, field +from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive -from reflex_components_ui.components._menu import ( - MenuContent, - MenuItem, - MenuSeparator, - MenuSub, - MenuSubContent, - MenuSubTrigger, - MenuTrigger, +from reflex_components_ui.base import Part +from reflex_components_ui.components._group import descendants, literal +from reflex_components_ui.components._sdk import SDKPart, entry, on_change +from reflex_components_ui.components.select import ( + _icon, # pyright: ignore[reportAttributeAccessIssue] ) -from reflex_components_ui.components._popup import PopupRoot from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.menu import DROPDOWN_MENU_CONTENT +from reflex_components_ui.styles.menu import ( + MENU_SEPARATOR, + SDK_DROPDOWN_MENU_CONTENT, + SDK_MENU_ITEM, + SDK_MENU_SUB_CONTENT, +) from reflex_components_ui.themes import LiteralAccentColor LiteralDirType = Literal["ltr", "rtl"] @@ -38,11 +46,121 @@ "always", ] +_LIBRARY = entry("menu") + +# The chevron of an item that opens a sub-menu, as Radix Themes draws it. +_CHEVRON = ( + "M3.23826 0.201711C3.54108 -0.0809141 4.01567 -0.0645489 4.29829 0.238264" + "L7.79829 3.98826C8.06724 4.27642 8.06724 4.72359 7.79829 5.01174" + "L4.29829 8.76174C4.01567 9.06455 3.54108 9.08092 3.23826 8.79829" + "C2.93545 8.51567 2.91909 8.04108 3.20171 7.73826L6.22409 4.5" + "L3.20171 1.26174C2.91909 0.958928 2.93545 0.484337 3.23826 0.201711Z" +) + +# The events Radix fires on the content of a menu, which UI SDK says as the +# reason of a change of the menu. +_EVENTS = ( + "on_close_auto_focus", + "on_escape_key_down", + "on_pointer_down_outside", + "on_focus_outside", + "on_interact_outside", +) + +# What a menu does when it opens or closes, by the reason: as in Radix, what +# dismissed it is said before it closes. +_ON_OPEN_CHANGE = ( + 'if (details?.reason === "escape-key") escape?.();' + ' if (details?.reason === "outside-press") { outside?.(); interact?.(); }' + ' if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); }' + " change?.(value);" + " if (!value) closeAutoFocus?.();" +) -class DropdownMenuRoot(PopupRoot): +# What Radix Themes gives the content of a dropdown menu: the room beside +# its trigger and the room it keeps from the edges of the viewport. +_SIDE_OFFSET = 4 +_COLLISION_PADDING = 10 + + +class MenuRootPart(SDKPart): + """A menu or a sub-menu, which takes from its content what Radix gives it. + + Whether the arrow keys go round is a prop of the content in Radix and of + the menu in UI SDK, and so are the events of a dismissal. + """ + + library = _LIBRARY + + def _post_init(self, *args, **kwargs): + """Initialize the menu, and take the props of its content. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + self._loop: Var | None = None + events: dict[str, Any] = { + "change": self.event_triggers.pop("on_open_change", None) + } + content = next(descendants(self, MenuContentPart, MenuRootPart), None) + if content is not None: + self._loop = getattr(content, "loop", None) + own = content.event_triggers + for event in _EVENTS: + events[event] = own.pop(event, None) + self._on_open_change = on_change( + { + "change": events["change"], + "closeAutoFocus": events.get("on_close_auto_focus"), + "escape": events.get("on_escape_key_down"), + "outside": events.get("on_pointer_down_outside"), + "focusOutside": events.get("on_focus_outside"), + "interact": events.get("on_interact_outside"), + }, + _ON_OPEN_CHANGE, + ) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the menu, those it takes from its content 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) + if self._loop is not None: + yield self._loop + if self._on_open_change is not None: + yield self._on_open_change + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the menu, which is no element. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. + """ + tag = super()._render(props) + if self._loop is not None: + tag = tag.add_props(loop=self._loop) + if self._on_open_change is not None: + tag = tag.add_props(onOpenChange=self._on_open_change) + return tag + + +class DropdownMenuRoot(MenuRootPart): """The Dropdown Menu Root Component.""" - _prefix: ClassVar[str] = "rx-dropdown-menu" + tag = "Menu" default_open: Var[bool] = field( doc="The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state." @@ -64,19 +182,110 @@ class DropdownMenuRoot(PopupRoot): doc="Fired when the open state changes." ) + def _exclude_props(self) -> list[str]: + """Keep the direction off the menu, which is no element. + + Returns: + The props read as styles, and ``dir``: UI SDK reads the direction + of the page around the menu. + """ + return [*super()._exclude_props(), "dir"] -class DropdownMenuTrigger(MenuTrigger): + +class DropdownMenuTrigger(SDKPart): """The button that toggles the dropdown menu.""" + library = _LIBRARY + + tag = "MenuTrigger" + + _renders_child: ClassVar[bool] = True + as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." ) -class DropdownMenuContent(MenuContent): +class MenuContentPart(SDKPart): + """The content of a menu or a sub-menu, its items inside what scrolls them.""" + + library = _LIBRARY + + _sdk_names: ClassVar[dict[str, str]] = {"forceMount": "keepMounted"} + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create the content, its items inside the element that scrolls them. + + Args: + *children: The items. + **props: The properties of the content. + + Returns: + The content. + """ + return super().create( + Part.create( + Part.create(*children, part="viewport", tag="div"), + part="scroll", + tag="div", + ), + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the content, and give its items its look. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # Whether the menu has checkbox items, which leave room for a check. + self._indented: Any = None + super()._post_init(*args, **kwargs) + self._look: tuple[Any, Any] = ( + getattr(self, "variant", None), + getattr(self, "high_contrast", None), + ) + self._join_items() + + def _join_items(self) -> None: + """Give the items of the menu its look, those of its sub-menus too.""" + for member in descendants( + self, + (MenuItemPart, MenuContentPart), # pyright: ignore[reportArgumentType] + MenuContentPart, + ): + if isinstance(member, DropdownMenuSubContent): + member._inherit(self) + else: + member._join(self) + self._indented = False + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + def _exclude_props(self) -> list[str]: + """Keep the props UI SDK has no use for off the content. + + Returns: + The props read as styles, those the menu takes, and those of the + placement of Radix that UI SDK does not have. + """ + return [ + *super()._exclude_props(), + "loop", + "as_child", + "avoid_collisions", + "sticky", + "hide_when_detached", + ] + + +class DropdownMenuContent(MenuContentPart): """The Dropdown Menu Content component that pops out when the dropdown menu is open.""" - styles: ClassVar[ComponentStyles] = DROPDOWN_MENU_CONTENT + tag = "MenuContent" + + styles: ClassVar[ComponentStyles] = SDK_DROPDOWN_MENU_CONTENT size: Var[Responsive[LiteralSizeType]] = field( doc='Dropdown Menu Content size "1" - "2"' @@ -158,10 +367,62 @@ class DropdownMenuContent(MenuContent): doc="Fired when the pointer interacts outside the dialog." ) + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the content, placed as Radix Themes places it. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the side, the alignment, the offset and the padding + of Radix Themes where the content is given none. + """ + tag = super()._render(props) + placement: dict[str, Any] = { + "side": "bottom" if self.side is None else self.side, + "align": "start" if self.align is None else self.align, + } + if self.side_offset is None: + placement["sideOffset"] = _SIDE_OFFSET + if self.collision_padding is None: + placement["collisionPadding"] = _COLLISION_PADDING + return tag.add_props(**placement) + + +class MenuItemPart(SDKPart): + """An item of a menu, which its menu gives its look.""" + + library = _LIBRARY + + styles: ClassVar[ComponentStyles] = SDK_MENU_ITEM + + def _post_init(self, *args, **kwargs): + """Initialize the item, as one outside a menu. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + # The look of the menu the item is in, which Radix hands down. + self._variant: Any = None + self._contrast: Any = None + super()._post_init(*args, **kwargs) + + def _join(self, menu: MenuContentPart) -> None: + """Take the look of the menu the item is in. -class DropdownMenuSubTrigger(MenuSubTrigger): + Args: + menu: The content of the menu. + """ + self._variant, self._contrast = menu._look + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + +class DropdownMenuSubTrigger(MenuItemPart): """An item that opens a submenu.""" + tag = "MenuSubTrigger" + as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." ) @@ -174,10 +435,37 @@ class DropdownMenuSubTrigger(MenuSubTrigger): doc="Optional text used for typeahead purposes. By default the typeahead behavior will use the .textContent of the item. Use this when the content is complex, or you have non-textual content inside." ) + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create the item, with the chevron that says it opens a sub-menu. + + Args: + *children: What the item shows. + **props: The properties of the item. + + Returns: + The item. + """ + return super().create( + *children, + Part.create(_icon("chevron", _CHEVRON), part="shortcut", tag="div"), + **props, + ) + + def _exclude_props(self) -> list[str]: + """Keep the props UI SDK has no use for off the item. -class DropdownMenuSub(MenuSub): + Returns: + The props read as styles, ``as_child`` and ``text_value``. + """ + return [*super()._exclude_props(), "as_child", "text_value"] + + +class DropdownMenuSub(MenuRootPart): """Contains all the parts of a submenu.""" + tag = "MenuSub" + open: Var[bool] = field( doc="The controlled open state of the submenu. Must be used in conjunction with `on_open_change`." ) @@ -191,9 +479,13 @@ class DropdownMenuSub(MenuSub): ) -class DropdownMenuSubContent(MenuSubContent): +class DropdownMenuSubContent(MenuContentPart): """The component that pops out when a submenu is open. Must be rendered inside DropdownMenuSub.""" + tag = "MenuSubContent" + + styles: ClassVar[ComponentStyles] = SDK_MENU_SUB_CONTENT + as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." ) @@ -246,10 +538,47 @@ class DropdownMenuSubContent(MenuSubContent): doc="Fired when the pointer interacts outside the dialog." ) - -class DropdownMenuItem(MenuItem): + def _inherit(self, menu: MenuContentPart) -> None: + """Take the look of the menu the sub-menu opens from, as in Radix. + + Args: + menu: The content of that menu. + """ + self._look = menu._look + self.size = getattr(menu, "size", None) + self._join_items() + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the content, placed as Radix Themes places a sub-menu. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the offset and the padding of Radix Themes where + the content is given none. + """ + tag = super()._render(props) + placement: dict[str, Any] = {} + if self.side_offset is None: + placement["sideOffset"] = 1 + if self.align_offset is None: + # As far up as the padding of the menu: the text of its first + # item is level with the item it opens from. + size = literal(getattr(self, "size", None)) + placement["alignOffset"] = -4 * int(size if size in ("1", "2") else 2) + if self.collision_padding is None: + placement["collisionPadding"] = _COLLISION_PADDING + return tag.add_props(**placement) + + +class DropdownMenuItem(MenuItemPart): """The Dropdown Menu Item Component.""" + tag = "MenuItem" + + _sdk_names: ClassVar[dict[str, str]] = {"textValue": "label"} + color_scheme: Var[LiteralAccentColor] = field( doc="Override theme color for Dropdown Menu Item" ) @@ -272,10 +601,44 @@ class DropdownMenuItem(MenuItem): doc="Fired when the item is selected." ) + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create an item, with its shortcut after what it shows. + + Args: + *children: What the item shows. + **props: The properties of the item. + + Returns: + The item. + """ + shortcut = props.get("shortcut") + after = ( + [] + if shortcut is None + else [Part.create(shortcut, part="shortcut", tag="div")] + ) + return super().create(*children, *after, **props) + + def _exclude_props(self) -> list[str]: + """Keep the props UI SDK has no use for off the item. -class DropdownMenuSeparator(MenuSeparator): + Returns: + The props read as styles, ``as_child`` and the shortcut, which is + shown: a shortcut of UI SDK is a key it binds. + """ + return [*super()._exclude_props(), "as_child", "shortcut"] + + +class DropdownMenuSeparator(SDKPart): """Dropdown Menu Separator Component. Used to visually separate items in the dropdown menu.""" + library = _LIBRARY + + tag = "MenuSeparator" + + styles: ClassVar[ComponentStyles] = MENU_SEPARATOR + class DropdownMenu(ComponentNamespace): """DropdownMenu components namespace.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py b/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py index dc0546fe3af..f9ef0ef00bd 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/tabs.py @@ -1,63 +1,44 @@ -"""Tabs: a list of buttons, and the panel of the selected one.""" +"""Tabs: a list of buttons, and the panel of the selected one. + +The parts are those of ``@ui-sdk/react/tabs``: UI SDK selects a tab, moves +the focus with the arrow keys and names each tab and its panel. +""" from __future__ import annotations -import itertools from collections.abc import Iterator from typing import Any, ClassVar, Literal from reflex_base.components.component import Component, ComponentNamespace, field from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, passthrough_event_spec -from reflex_base.vars.base import LiteralVar, Var +from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive -from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.components._group import ( - choose, - descendants, - is_value, - literal, -) -from reflex_components_ui.components._script import listen, script +from reflex_components_ui.base import Part +from reflex_components_ui.components._group import descendants +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.tabs import TABS, TABS_CONTENT, TABS_LIST, TABS_TRIGGER from reflex_components_ui.themes import LiteralAccentColor -# Numbers the tabs of an app: a trigger and its panel name each other by id. -_ids = itertools.count(1) - - -def _part_id(tabs: TabsRoot, part: str, value: Var | None) -> Any: - """Get the id of the trigger or of the panel of a tab. - - Args: - tabs: The tabs. - part: Which of the two it is. - value: The value of the tab. - - Returns: - The id the part was given, or the one the tabs give it: a string - when the value is known while compiling. - """ - prefix = f"{tabs._name}-{part}-" - known = literal(value) - if not isinstance(known, Var): - return tabs._ids.get((part, known), f"{prefix}{known}") - return Var( - f"({LiteralVar.create(prefix)!s} + {known!s})", - _var_type=str, - _var_data=known._get_all_var_data(), - ) +_LIBRARY = entry("tabs") -class TabsRoot(UIComponent): +class TabsRoot(SDKPart): """Set of content sections to be displayed one at a time.""" - tag = "div" + library = _LIBRARY + + tag = "Tabs" styles: ClassVar[ComponentStyles] = TABS + _sdk_names: ClassVar[dict[str, str]] = { + "onChange": "onValueChange", + "activationMode": "activation", + } + default_value: Var[str] = field( doc="The value of the tab that should be active when initially rendered. Use when you do not need to control the state of the tabs." ) @@ -81,49 +62,29 @@ class TabsRoot(UIComponent): ) def _post_init(self, *args, **kwargs): - """Initialize the tabs, and give their parts what they share. + """Initialize the tabs, and give their parts the orientation. - Radix hands the parts of tabs their props through a context. Here - the root finds its parts while compiling, and gives them what they - render. + The orientation selects a variant of the style of each part, which + is read while compiling: the root hands it to the parts below it. + Whether the arrow keys go round is a prop of the list in Radix and + of the root in UI SDK. Args: *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ super()._post_init(*args, **kwargs) - self._name = f"rx-tabs-{next(_ids)}" - self._selected = self.value if self.value is not None else self.default_value - # Tab stops on the selected trigger, or on the first when none is. - self._stop = None if self._selected is not None else False - parts = list(descendants(self, TabsPart, TabsRoot)) - # The ids an app gave a trigger or a panel, which the other names. - self._ids = { - (part._kind, value): part.id - for part in parts - if part.id is not None - and not isinstance(value := literal(getattr(part, "value", None)), Var) - } - for part in parts: - part._join(self) - - def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the parts off the element. - - Returns: - The props read as styles, and what the tabs hand their parts. - """ - return [ - *super()._exclude_props(), - "value", - "default_value", - "activation_mode", - ] + self._loop: Var | None = None + for part in descendants(self, TabsPart, TabsRoot): + part._orientation = self.orientation + part._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + if isinstance(part, TabsList) and part.loop is not None: + self._loop = part.loop def _get_vars( self, include_children: bool = False, ignore_ids: set[int] | None = None ) -> Iterator[Var]: - """Walk all Vars used in the tabs, the script that selects one included. + """Walk all Vars used in the tabs, whether their keys go round included. Args: include_children: Whether to include Vars from children. @@ -133,98 +94,47 @@ def _get_vars( Each var referenced by the component. """ yield from super()._get_vars(include_children, ignore_ids) - yield script("tabs", "tabsEvent") + if self._loop is not None: + yield self._loop def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the element around the tabs. + """Render the tabs. Args: props: The props to render (if None, then use get_props). Returns: - The tag, which hears a press on a trigger and the focus moving - to one: the script selects it, or says so to the state the - tabs are bound to. + The tag, with the orientation the style reads too. """ tag = super()._render(props) - rendered = dict(tag.props) - on_change = rendered.pop("onChange", None) - tag = tag.set(props=rendered).add_props(**{ - "data-rx-tabs": "" if self.value is None else "bound", - "data-activation": self.activation_mode, - }) - return listen( - tag, - script("tabs", "tabsEvent"), - "onClick", - "onFocus", - "onBlur", - arguments=() if on_change is None else (on_change,), - ) + if self.orientation is not None: + tag = tag.add_props(orientation=self.orientation) + if self._loop is not None: + tag = tag.add_props(loop=self._loop) + return tag -class TabsPart(UIComponent): - """A part of tabs, which its root gives a state and an orientation.""" +class TabsPart(SDKPart): + """A part of tabs, which its root gives an orientation.""" - # Which part it is, in the id the tabs give a trigger or a panel. - _kind: ClassVar[str] = "" + library = _LIBRARY def _post_init(self, *args, **kwargs): - """Initialize the part, as the one of horizontal tabs with no value. + """Initialize the part, as the one of horizontal tabs. Args: *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ - # What the style table reads as a variant, and the attributes the - # tabs give the part: both are set by the root around it. + # What the style table reads as a variant, set by the root. self._orientation: Any = None - self._tabs: dict[str, Any] = {} super()._post_init(*args, **kwargs) - def _join(self, tabs: TabsRoot) -> None: - """Take from the tabs what Radix hands their parts through a context. - - Args: - tabs: The tabs the part is in. - """ - self._orientation = tabs.orientation - self._tabs = self._attributes(tabs) - self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - - def _attributes(self, tabs: TabsRoot) -> dict[str, Any]: - """Work out the attributes the tabs give the part. - - Args: - tabs: The tabs the part is in. - - Returns: - The attributes. - """ - return {} - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the part, those its tabs give it 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) - for value in self._tabs.values(): - if isinstance(value, Var): - yield value - class TabsList(TabsPart): """Contains the triggers that sit alongside the active content.""" - tag = "div" + tag = "TabsList" styles: ClassVar[ComponentStyles] = TABS_LIST @@ -232,54 +142,31 @@ class TabsList(TabsPart): loop: Var[bool] = field(doc="When true, the tabs will loop when reaching the end.") - def _attributes(self, tabs: TabsRoot) -> dict[str, Any]: - """Take the orientation of the tabs, which says which arrow keys move. - - Args: - tabs: The tabs the list is in. - - Returns: - The attributes. - """ - return ( - {} if tabs.orientation is None else {"aria-orientation": tabs.orientation} - ) - def _exclude_props(self) -> list[str]: - """Keep the prop the script reads off the element. + """Keep whether the keys go round off the list: its root takes it. Returns: - The props read as styles, and whether the arrow keys go around. + The props read as styles, and ``loop``. """ return [*super()._exclude_props(), "loop"] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the list. + """Render the list, which says its orientation as Radix does. Args: props: The props to render (if None, then use get_props). Returns: - The tag, with the role of a list of tabs, which the arrow keys - move the focus through. + The tag: UI SDK says only a vertical orientation, ARIA's default + being horizontal. """ - attributes: dict[str, Any] = { - "role": "tablist", - "aria-orientation": "horizontal", - **self._tabs, - } - if self.loop is not None: - attributes["data-loop"] = self.loop - return listen( - super()._render(props).add_props(**attributes), - script("roving-focus", "rovingKeyDown"), - "onKeyDown", - ) + orientation = "horizontal" if self._orientation is None else self._orientation + return super()._render(props).add_props(**{"aria-orientation": orientation}) def _get_vars( self, include_children: bool = False, ignore_ids: set[int] | None = None ) -> Iterator[Var]: - """Walk all Vars used in the list, the script of its keys included. + """Walk all Vars used in the list, its orientation included. Args: include_children: Whether to include Vars from children. @@ -289,13 +176,14 @@ def _get_vars( Each var referenced by the component. """ yield from super()._get_vars(include_children, ignore_ids) - yield script("roving-focus", "rovingKeyDown") + if isinstance(self._orientation, Var): + yield self._orientation class TabsTrigger(TabsPart): """The button that activates its associated content.""" - tag = "button" + tag = "TabsTab" styles: ClassVar[ComponentStyles] = TABS_TRIGGER @@ -309,8 +197,6 @@ class TabsTrigger(TabsPart): _valid_parents: ClassVar[list[str]] = ["TabsList"] - _kind: ClassVar[str] = "trigger" - @classmethod def create(cls, *children, **props) -> Component: """Create a TabsTrigger component. @@ -328,132 +214,22 @@ def create(cls, *children, **props) -> Component: **props, ) - def _attributes(self, tabs: TabsRoot) -> dict[str, Any]: - """Say which panel the trigger shows, and whether it is selected. - - Args: - tabs: The tabs the trigger is in. - - Returns: - The attributes. - """ - selected: Var | bool = ( - False if tabs._selected is None else is_value(tabs._selected, self.value) - ) - stop = selected - if tabs._stop is False and literal(self.disabled) is not True: - tabs._stop = stop = True - attributes: dict[str, Any] = { - "aria-controls": _part_id(tabs, "content", self.value), - "aria-selected": selected, - "data-state": choose(selected, "active", "inactive"), - "tabIndex": choose(stop, 0, -1), - } - if self.id is None: - attributes["id"] = _part_id(tabs, "trigger", self.value) - return attributes - - def _exclude_props(self) -> list[str]: - """Keep the value off the button: a form is not to submit it. - - Returns: - The props read as styles, and the value. - """ - return [*super()._exclude_props(), "value"] - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: a button with the role and the state of a tab. - """ - return ( - super() - ._render(props) - .add_props(**{ - "type": "button", - "role": "tab", - "aria-selected": False, - "data-state": "inactive", - "tabIndex": -1, - "data-value": self.value, - **self._tabs, - }) - ) - class TabsContent(TabsPart): """Contains the content associated with each trigger.""" - tag = "div" + tag = "TabsPanel" styles: ClassVar[ComponentStyles] = TABS_CONTENT + _sdk_names: ClassVar[dict[str, str]] = {"forceMount": "keepMounted"} + value: Var[str] = field(doc="The value of the tab. Must be unique for each tab.") force_mount: Var[bool] = field( doc="Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries." ) - _kind: ClassVar[str] = "content" - - def _attributes(self, tabs: TabsRoot) -> dict[str, Any]: - """Say which trigger names the panel, and whether it is shown. - - Args: - tabs: The tabs the panel is in. - - Returns: - The attributes. - """ - selected: Var | bool = ( - False if tabs._selected is None else is_value(tabs._selected, self.value) - ) - attributes: dict[str, Any] = { - "aria-labelledby": _part_id(tabs, "trigger", self.value), - "data-state": choose(selected, "active", "inactive"), - "hidden": choose(selected, False, True), - } - if self.id is None: - attributes["id"] = _part_id(tabs, "content", self.value) - return attributes - - def _exclude_props(self) -> list[str]: - """Keep the props of a panel off the element. - - Returns: - The props read as styles, the value, and whether the panel stays - mounted: every panel does. - """ - return [*super()._exclude_props(), "value", "force_mount"] - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the panel. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, with the role of the panel of a tab: hidden until its - tab is selected. - """ - return ( - super() - ._render(props) - .add_props(**{ - "role": "tabpanel", - "tabIndex": 0, - "data-state": "inactive", - "hidden": True, - "data-value": self.value, - "data-rx-tabs-content": "", - **self._tabs, - }) - ) - class Tabs(ComponentNamespace): """Set of content sections to be displayed one at a time.""" 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 8a3ab3360d1..22bb5906c04 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/constants.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/constants.py @@ -35,3 +35,10 @@ def _js_src_dir(root_dir: Path) -> Path: # 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" + +# UI SDK, which gives the interactive components their behaviour, is a beta +# whose api changes between releases: an app installs the exact version the +# components are written against. +UI_SDK_VERSION = "0.1.0-beta.17" +UI_SDK_CORE = f"@ui-sdk/core@{UI_SDK_VERSION}" +UI_SDK_REACT = f"@ui-sdk/react@{UI_SDK_VERSION}" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py index fd812ee10a8..5c6bf0c3c01 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/button.py @@ -39,8 +39,10 @@ # selected by attribute, which wins over every pseudo-class. _POINTER = "@media (hover: hover)" _HOVER = ":hover:not(:active)" -_ACTIVE = ":active:not([data-state='open'])" -_OPEN = "[data-state='open']" +# A trigger whose popup is open: Radix says so in `data-state`, UI SDK in +# `data-open`. +_OPEN = ":is([data-state='open'], [data-open])" +_ACTIVE = f":active:not({_OPEN})" _DISABLED = "[data-disabled]" _FOCUS = ":focus-visible" _TOUCH = "@media (pointer: coarse)" @@ -107,7 +109,7 @@ def _ring(color: str, offset: str) -> dict[str, Any]: f"inset 0 1px 1px {gray.a[5]}, inset 0 -1px 1px {black.a[3]}, " f"inset 0 0 0 1px {gray.a[2]}", ) -_CLASSIC_ACTIVE = f":active:not([data-state='open'], {_DISABLED})" +_CLASSIC_ACTIVE = f":active:not({_OPEN}, {_DISABLED})" def _classic(color: str) -> dict[str, Any]: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py index f5ccca955ca..07072f15cd9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/card.py @@ -22,7 +22,8 @@ _LINK = ":is(:any-link, button, label)" _POINTER = "@media (hover: hover)" _TOUCH = "@media (pointer: coarse)" -_OPEN = "[data-state='open']" +# A card whose popup is open, as Radix and UI SDK say it. +_OPEN = ":is([data-state='open'], [data-open])" _HOVER = f"{_LINK}:hover:not(:active)" _PRESSED = f":active:not({_OPEN})" _ACTIVE = f"{_LINK}{_PRESSED}" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py index 90f2590af00..93a53f08e74 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py @@ -147,3 +147,67 @@ def _size(padding: str, radius: str) -> dict[str, Any]: } DIALOG_DESCRIPTION: ComponentStyles = {**TEXT, "defaults": {"size": "3"}} + +# What UI SDK's parts of a dialog have while they go out: UI SDK keeps them +# in the page until their transitions end. +_SDK_ENDING = "[data-ending-style]" + +# The room a dialog of UI SDK leaves around its panel, as the padding of the +# overlay of Radix Themes around it. +_ROOM_TOP = tokens.space[6] +_ROOM_BOTTOM = f"max({tokens.space[6]}, 6vh)" +_ROOM_SIDE = tokens.space[4] + +# What is drawn over the page behind a dialog of UI SDK. +SDK_DIALOG_BACKDROP: ComponentStyles = { + "base": unchecked({ + "position": "fixed", + "inset": "0", + "background_color": tokens.color.overlay, + "opacity": {"default": 1, "@starting-style": 0, _SDK_ENDING: 0}, + "transition_property": "opacity", + "transition_duration": { + "default": "0s", + MOTION: {"default": "200ms", _SDK_ENDING: "160ms"}, + }, + "transition_timing_function": _EASING, + }), +} + +# The panel of a dialog of UI SDK, its content: a popover in the top layer, +# in the middle of the room the overlay of Radix Themes leaves. A panel +# taller than that room scrolls. +SDK_DIALOG_CONTENT: ComponentStyles = { + **DIALOG_CONTENT, + "base": unchecked({ + **{ + key: value + for key, value in DIALOG_CONTENT["base"].items() + if key not in ("width", "z_index", "position", "opacity", "transform") + }, + "position": "fixed", + "top": _ROOM_TOP, + "bottom": _ROOM_BOTTOM, + "left": "0", + "right": "0", + "width": f"calc(100% - {_ROOM_SIDE} * 2)", + "height": "fit-content", + "max_height": f"calc(100% - {_ROOM_TOP} - {_ROOM_BOTTOM})", + # No border, of the style of the panel of Radix Themes. + "border_width": "0", + "border_style": "solid", + "color": "inherit", + "user_select": "auto", + "::backdrop": {"background_color": "transparent"}, + "opacity": {"default": 1, "@starting-style": 0, _SDK_ENDING: 0}, + "transform": { + "default": "none", + "@starting-style": "translateY(5px) scale(0.97)", + _SDK_ENDING: "translateY(5px) scale(0.99)", + }, + "transition_duration": { + "default": "0s", + MOTION: {"default": "200ms", _SDK_ENDING: "100ms"}, + }, + }), +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py index 7da202b4582..aebb3800c9f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py @@ -6,7 +6,7 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked -from reflex_components_ui.styles.popup import POPUP, placement, placements +from reflex_components_ui.styles.popup import POPUP, SDK_PLACED, placement, placements from reflex_components_ui.tokens import Step9 # What the content of a menu hands its items, as Radix Themes names them. @@ -29,8 +29,6 @@ # An item the focus is on is the one Radix highlights: the pointer moves the # focus to the item under it. HIGHLIGHTED = ":focus" -# A sub-menu trigger whose sub-menu is open, and that is not highlighted. -_OPEN = ":not(:focus)[data-state='open']" _DISABLED = "[aria-disabled='true']" # A label right after an item. _AFTER_ITEM = ":is(:is([role=menuitem], [role=menuitemcheckbox]) + *)" @@ -209,129 +207,185 @@ def _content( {**_CONTENT_BASE, **placement("right", "start", "1px")}, _RAISED, {}, [] ) -MENU_ITEM: ComponentStyles = { - "base": unchecked({ - "display": "flex", - "align_items": "center", - "gap": tokens.space[2], - "height": f"var({_HEIGHT})", - "padding_left": f"var({_INDENT})", - "padding_right": f"var({_END})", - "box_sizing": "border-box", - "position": "relative", - "outline_style": "none", - "outline_width": "medium", - "outline_color": "currentColor", - "scroll_margin_top": f"var({_PADDING})", - "scroll_margin_bottom": f"var({_PADDING})", - # Fixes sticky text highlighting after a choice in Firefox. - "user_select": "none", - "cursor": {"default": tokens.cursor.menu_item, _DISABLED: "default"}, - # The pointer goes through a disabled item, which it cannot choose. - "pointer_events": {"default": "auto", _DISABLED: "none"}, - "font_size": f"var({_FONT_SIZE})", - "line_height": f"var({_LINE_HEIGHT})", - "letter_spacing": f"var({_LETTER_SPACING})", - "border_radius": f"var({_ITEM_RADIUS})", - "color": {_DISABLED: tokens.gray.a[8]}, - _SHORTCUT: { - "default": tokens.gray.a[11], - HIGHLIGHTED: "currentColor", - _DISABLED: "currentColor", - "[data-state='open']": "currentColor", - }, - _CHEVRON: tokens.gray[12], - _CHECK: {"default": "none", "[aria-checked='true']": "inline-flex"}, - }), - "variants": { - "color_scheme": { - "true": unchecked({ - "color": {"default": tokens.accent.a[11], _DISABLED: tokens.gray.a[8]} - }) - }, - "_variant": { - "solid": unchecked({ - "background_color": { - HIGHLIGHTED: tokens.accent[9], - _OPEN: tokens.gray.a[3], - }, - "color": {HIGHLIGHTED: tokens.accent.contrast}, - _CHEVRON: { - "default": tokens.gray[12], - HIGHLIGHTED: tokens.accent.contrast, - }, - }), - "soft": unchecked({ - "background_color": { - HIGHLIGHTED: tokens.accent.a[4], - _OPEN: tokens.accent.a[3], - }, - }), - }, - "_contrast": {"true": {}, "false": {}}, + +# The content of a menu of UI SDK, which places it: no taller than the room +# it measures, which it says in `--available-height`. +_SDK_CONTENT_BASE: dict[str, Any] = { + **{ + key: value + for key, value in _CONTENT_BASE.items() + if key != "position_try_fallbacks" }, - "defaults": {"_variant": "solid", "_contrast": "false"}, - "compound": [ - { - "props": {"_variant": "solid", "_contrast": "true"}, - "style": unchecked({ - "background_color": { - HIGHLIGHTED: tokens.accent[12], - _OPEN: tokens.gray.a[3], - }, - "color": {HIGHLIGHTED: tokens.accent[1]}, - _CHEVRON: {"default": tokens.gray[12], HIGHLIGHTED: tokens.accent[1]}, - }), + **SDK_PLACED, + "max_height": "var(--available-height)", +} + +SDK_DROPDOWN_MENU_CONTENT = _content(_SDK_CONTENT_BASE, _SIZES, {}, []) +# Where UI SDK places the menu: props of the content, which no style reads. +# They are variants, so that `align` is not the one of a flex container. +SDK_DROPDOWN_MENU_CONTENT["variants"] = { + **SDK_DROPDOWN_MENU_CONTENT["variants"], + "side": {side: {} for side in ("top", "right", "bottom", "left")}, + "align": {align: {} for align in ("start", "center", "end")}, +} + +SDK_MENU_SUB_CONTENT = _content(_SDK_CONTENT_BASE, _RAISED, {}, []) + + +def _item(highlighted: str, open_: str) -> ComponentStyles: + """Make the look of an item, by what it has while highlighted or open. + + Args: + highlighted: What an item has while it is highlighted. + open_: What an item that opens a sub-menu has while it is open. + + Returns: + The look. + """ + open_beside = f":not({highlighted}){open_}" + return { + "base": unchecked({ + "display": "flex", + "align_items": "center", + "gap": tokens.space[2], + "height": f"var({_HEIGHT})", + "padding_left": f"var({_INDENT})", + "padding_right": f"var({_END})", + "box_sizing": "border-box", + "position": "relative", + "outline_style": "none", + "outline_width": "medium", + "outline_color": "currentColor", + "scroll_margin_top": f"var({_PADDING})", + "scroll_margin_bottom": f"var({_PADDING})", + # Fixes sticky text highlighting after a choice in Firefox. + "user_select": "none", + "cursor": {"default": tokens.cursor.menu_item, _DISABLED: "default"}, + # The pointer goes through a disabled item, which it cannot choose. + "pointer_events": {"default": "auto", _DISABLED: "none"}, + "font_size": f"var({_FONT_SIZE})", + "line_height": f"var({_LINE_HEIGHT})", + "letter_spacing": f"var({_LETTER_SPACING})", + "border_radius": f"var({_ITEM_RADIUS})", + "color": {_DISABLED: tokens.gray.a[8]}, + _SHORTCUT: { + "default": tokens.gray.a[11], + highlighted: "currentColor", + _DISABLED: "currentColor", + open_: "currentColor", + }, + _CHEVRON: tokens.gray[12], + _CHECK: {"default": "none", "[aria-checked='true']": "inline-flex"}, + }), + "variants": { + "color_scheme": { + "true": unchecked({ + "color": { + "default": tokens.accent.a[11], + _DISABLED: tokens.gray.a[8], + } + }) + }, + "_variant": { + "solid": unchecked({ + "background_color": { + highlighted: tokens.accent[9], + open_beside: tokens.gray.a[3], + }, + "color": {highlighted: tokens.accent.contrast}, + _CHEVRON: { + "default": tokens.gray[12], + highlighted: tokens.accent.contrast, + }, + }), + "soft": unchecked({ + "background_color": { + highlighted: tokens.accent.a[4], + open_beside: tokens.accent.a[3], + }, + }), + }, + "_contrast": {"true": {}, "false": {}}, }, - { - # An item of its own color keeps the highlight of a solid menu. - "props": {"_variant": "solid", "_contrast": "true", "color_scheme": "true"}, - "style": unchecked({ - "background_color": { - HIGHLIGHTED: tokens.accent[9], - _OPEN: tokens.gray.a[3], - }, - "color": {HIGHLIGHTED: tokens.accent.contrast}, - _CHEVRON: { - "default": tokens.gray[12], - HIGHLIGHTED: tokens.accent.contrast, + "defaults": {"_variant": "solid", "_contrast": "false"}, + "compound": [ + { + "props": {"_variant": "solid", "_contrast": "true"}, + "style": unchecked({ + "background_color": { + highlighted: tokens.accent[12], + open_beside: tokens.gray.a[3], + }, + "color": {highlighted: tokens.accent[1]}, + _CHEVRON: { + "default": tokens.gray[12], + highlighted: tokens.accent[1], + }, + }), + }, + { + # An item of its own color keeps the highlight of a solid menu. + "props": { + "_variant": "solid", + "_contrast": "true", + "color_scheme": "true", }, - }), - }, - ], - "parts": { - "shortcut": { - "base": unchecked({ - "display": "flex", - "align_items": "center", - "margin_left": "auto", - "padding_left": tokens.space[4], - "color": f"var({_SHORTCUT})", - }), - }, - "chevron": { - "base": unchecked({ - "color": f"var({_CHEVRON})", - "margin_right": f"calc(-2px * {tokens.scaling})", - "width": f"var({_ICON})", - "height": f"var({_ICON})", - }), - }, - "indicator": { - "base": unchecked({ - "position": "absolute", - "left": "0", - "width": f"var({_INDENT})", - "display": f"var({_CHECK})", - "align_items": "center", - "justify_content": "center", - }), - }, - "check": { - "base": unchecked({"width": f"var({_ICON})", "height": f"var({_ICON})"}), + "style": unchecked({ + "background_color": { + highlighted: tokens.accent[9], + open_beside: tokens.gray.a[3], + }, + "color": {highlighted: tokens.accent.contrast}, + _CHEVRON: { + "default": tokens.gray[12], + highlighted: tokens.accent.contrast, + }, + }), + }, + ], + "parts": { + "shortcut": { + "base": unchecked({ + "display": "flex", + "align_items": "center", + "margin_left": "auto", + "padding_left": tokens.space[4], + "color": f"var({_SHORTCUT})", + }), + }, + "chevron": { + "base": unchecked({ + "color": f"var({_CHEVRON})", + "margin_right": f"calc(-2px * {tokens.scaling})", + "width": f"var({_ICON})", + "height": f"var({_ICON})", + }), + }, + "indicator": { + "base": unchecked({ + "position": "absolute", + "left": "0", + "width": f"var({_INDENT})", + "display": f"var({_CHECK})", + "align_items": "center", + "justify_content": "center", + }), + }, + "check": { + "base": unchecked({ + "width": f"var({_ICON})", + "height": f"var({_ICON})", + }), + }, }, - }, -} + } + + +# The items of the menus whose script moves the focus, and those of UI SDK, +# which highlights an item, the one the focus is on or under the pointer. +MENU_ITEM = _item(HIGHLIGHTED, "[data-state='open']") +SDK_MENU_ITEM = _item("[data-highlighted]", "[data-open]") + MENU_LABEL: ComponentStyles = { "base": unchecked({ diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py index 8a3cff4bf8f..e578f7121b3 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py @@ -158,3 +158,27 @@ def placements(default_offset: str = "0px") -> list[CompoundStyle]: } for side, align in _AREAS ] + + +# What a popup of UI SDK has while it goes out: UI SDK keeps it open and in +# the page until its transitions end. +_ENDING = "[data-ending-style]" + +# A popup UI SDK places: it sets where, the side the popup ended up on and +# the point of its anchor the popup opens from. The popup comes in from +# that side, and goes out the way it came. +SDK_PLACED: dict[str, Any] = { + "transform_origin": "var(--transform-origin)", + _FROM: {f"[data-side='{side}']": entry for side, entry in _ENTRY.items()}, + "opacity": {"default": 1, "@starting-style": 0, _ENDING: 0}, + "transform": { + "default": "none", + "@starting-style": f"var({_FROM})", + _ENDING: f"var({_FROM})", + }, + "transition_property": "opacity, transform", + "transition_duration": { + "default": "0s", + _MOTION: {"default": "160ms", _ENDING: "100ms"}, + }, +} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py index 7f7429fdde1..2b0de3f1c22 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/tabs.py @@ -142,7 +142,7 @@ def _size( "font_style": "normal", "cursor": { "default": tokens.cursor.button, - ":disabled": tokens.cursor.disabled, + "[data-disabled]": tokens.cursor.disabled, }, # The whole outline, as the browser has one of its own for the focus. "outline_style": "none", diff --git a/pyi_hashes.json b/pyi_hashes.json index 7d345fa839a..6776084da01 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -125,6 +125,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "817a2b853123734c7e200bc54a55c47a", "packages/reflex-components-ui/src/reflex_components_ui/components/_menu.pyi": "c243405a64e5dd76eef6bef0492ac75a", "packages/reflex-components-ui/src/reflex_components_ui/components/_popup.pyi": "80f094441cee591fff2e06d6e315dcc0", + "packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.pyi": "2fab3b573275566745f45149bf62b695", "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "4abb8482e413aa9ee3d941ef12878c1a", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", @@ -139,9 +140,9 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.pyi": "b914252f1bc53816d7c5384faea6d2b5", "packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.pyi": "79193f172cbb6feb749a296f82af9814", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", - "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "28f5633fbda932ee598108e9d5a52e58", + "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "a144d0d2d518369359f11e4245634656", "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "cdaeaac954b4ff1100878d46b5649143", - "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "866b446d2bc8381230a6c0683c3a4209", + "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "fddd9e7a28b08d125f6577ee99f8839b", "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", "packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.pyi": "866327d09399a8a3f632f93a36014ebb", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", @@ -159,7 +160,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/spinner.pyi": "9e62e8634e1425a75302d24fb458e8a8", "packages/reflex-components-ui/src/reflex_components_ui/components/switch.pyi": "7ec957d0bc2dfb273b9f6b8e8be50746", "packages/reflex-components-ui/src/reflex_components_ui/components/table.pyi": "3d2683d69d98f3cd14da65831e89e5fe", - "packages/reflex-components-ui/src/reflex_components_ui/components/tabs.pyi": "37bd6cf7d23252f304647967c44f7693", + "packages/reflex-components-ui/src/reflex_components_ui/components/tabs.pyi": "bc587de2eb7fe5bdd4caf7deb8a9c0d8", "packages/reflex-components-ui/src/reflex_components_ui/components/text_area.pyi": "85e3d7d2cf756b3a67683d9724b1a68b", "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "0493db3f24247140307bd4387444aac4", "packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.pyi": "8415abf97f4c226acc2f721278dca20f", diff --git a/tests/units/reflex_components_ui/components/test_button.py b/tests/units/reflex_components_ui/components/test_button.py index 748573e4fda..9582518cef2 100644 --- a/tests/units/reflex_components_ui/components/test_button.py +++ b/tests/units/reflex_components_ui/components/test_button.py @@ -69,7 +69,7 @@ def test_button_plain( component = rx.ui.button("Save") assert component.render() == { "name": '"button"', - "props": ["className:sx_f2580dfc68_c"], + "props": ["className:sx_16addd9092_c"], "children": [{"contents": '"Save"'}], } assert declared_styles(component) == [ @@ -93,8 +93,8 @@ def test_button_plain( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, - "[data-state='open']": "var(--accent-10)", - ":active:not([data-state='open'])": "var(--accent-10)", + ":is([data-state='open'], [data-open])": "var(--accent-10)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, "backgroundImage": "none", @@ -117,7 +117,7 @@ def test_button_plain( "outlineStyle": { "default": "none", "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "solid" }, ":focus-visible:not([data-disabled])": "solid", }, @@ -142,26 +142,26 @@ def test_button_plain( "[data-disabled]": "var(--gray-a8)", }, "filter": { - ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + ":active:not(:is([data-state='open'], [data-open]))": "var(--rx-if-light, brightness(0.92) " "saturate(1.1)) var(--rx-if-dark, " "brightness(1.08))", "[data-disabled]": "none", }, "outlineWidth": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" }, ":focus-visible:not([data-disabled])": "2px", }, "outlineColor": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "var(--accent-a4)" }, ":focus-visible:not([data-disabled])": "var(--focus-8)", }, "outlineOffset": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0" }, ":focus-visible:not([data-disabled])": "2px", }, @@ -188,7 +188,7 @@ def test_button_soft_with_a_color_and_a_radius( "name": '"button"', "props": [ ( - 'className:sx_357e435970_c + " " + reflexUIClasses_e201574881 + " " + ' + 'className:sx_eb445af6ab_c + " " + reflexUIClasses_e201574881 + " " + ' "reflexUIClasses_4c7cd6a7ce" ) ], @@ -215,8 +215,8 @@ def test_button_soft_with_a_color_and_a_radius( "backgroundColor": { "default": "var(--accent-a3)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a4)"}, - "[data-state='open']": "var(--accent-a4)", - ":active:not([data-state='open'])": "var(--accent-a5)", + ":is([data-state='open'], [data-open])": "var(--accent-a4)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-a5)", "[data-disabled]": "var(--gray-a3)", }, "backgroundImage": "none", @@ -279,7 +279,7 @@ def test_button_ghost( component = rx.ui.button("Save", variant="ghost", size="3") assert component.render() == { "name": '"button"', - "props": ["className:sx_8db288804d_c"], + "props": ["className:sx_d9250aa972_c"], "children": [{"contents": '"Save"'}], } assert declared_styles(component) == [ @@ -303,8 +303,8 @@ def test_button_ghost( "backgroundColor": { "default": "transparent", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a3)"}, - "[data-state='open']": "var(--accent-a3)", - ":active:not([data-state='open'])": "var(--accent-a4)", + ":is([data-state='open'], [data-open])": "var(--accent-a3)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-a4)", "[data-disabled]": "transparent", }, "backgroundImage": "none", @@ -367,7 +367,7 @@ def test_button_classic_high_contrast( "marginLeft": "0", "paddingTop": { "default": "0", - ":active:not([data-state='open'], [data-disabled])": "var(--base-button-classic-active-padding-top)", + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "var(--base-button-classic-active-padding-top)", }, "paddingRight": "var(--space-3)", "paddingBottom": "0", @@ -387,11 +387,11 @@ def test_button_classic_high_contrast( "@media (hover: hover)": { ":hover:not(:active)": "var(--accent-12)" }, - "[data-state='open']": "var(--accent-12)", - ":active:not([data-state='open'], [data-disabled])": "inherit", + ":is([data-state='open'], [data-open])": "var(--accent-12)", + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "inherit", "[data-disabled]": "var(--gray-a2)", }, - ":active:not([data-state='open'], [data-disabled])": "var(--accent-12)", + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "var(--accent-12)", "[data-disabled]": "var(--gray-2)", }, "backgroundImage": { @@ -406,17 +406,17 @@ def test_button_classic_high_contrast( "transparent, " "var(--white-a2))" }, - "[data-state='open']": "linear-gradient(var(--black-a5), " + ":is([data-state='open'], [data-open])": "linear-gradient(var(--black-a5), " "transparent, " "var(--white-a2))", - ":active:not([data-state='open'], [data-disabled])": "linear-gradient(var(--black-a5), " + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "linear-gradient(var(--black-a5), " "transparent, " "var(--white-a3))", "[data-disabled]": "linear-gradient(var(--black-a1) " "-20%, transparent, " "var(--white-a1))", }, - ":active:not([data-state='open'], [data-disabled])": "linear-gradient(var(--black-a1), " + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "linear-gradient(var(--black-a1), " "transparent)", "[data-disabled]": "none", }, @@ -439,7 +439,7 @@ def test_button_classic_high_contrast( "outlineStyle": { "default": "none", "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "solid" }, ":focus-visible:not([data-disabled])": "solid", }, @@ -470,10 +470,10 @@ def test_button_classic_high_contrast( "0 transparent)", "::after": { "default": "inset 0 2px 3px -1px var(--white-a4)", - ":active:not([data-state='open'], [data-disabled])": "none", + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "none", "[data-disabled]": "none", }, - ":active:not([data-state='open'], [data-disabled])": "none", + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "none", "[data-disabled]": "var(--rx-if-light, inset 0 0 0 1px var(--gray-a4), " "inset 0 -2px 1px var(--gray-a3), inset 0 4px 2px " "-2px var(--white-a9), inset 0 2px 1px -1px " @@ -506,25 +506,25 @@ def test_button_classic_high_contrast( "backgroundClip": {"::after": "content-box"}, "outlineWidth": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" }, ":focus-visible:not([data-disabled])": "2px", }, "outlineColor": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "var(--accent-a4)" }, ":focus-visible:not([data-disabled])": "var(--focus-8)", }, "outlineOffset": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0" }, ":focus-visible:not([data-disabled])": "2px", }, "filter": { "[data-disabled]": "none", - ":active:not([data-state='open'], [data-disabled])": "var(--rx-if-light, " + ":active:not(:is([data-state='open'], [data-open]), [data-disabled])": "var(--rx-if-light, " "contrast(0.82) " "saturate(1.2) " "brightness(1.16)) " @@ -541,7 +541,7 @@ def test_button_classic_high_contrast( "saturate(1.3) " "brightness(1.14))" }, - "[data-state='open']": "var(--rx-if-light, " + ":is([data-state='open'], [data-open])": "var(--rx-if-light, " "contrast(0.88) " "saturate(1.1) " "brightness(1.1)) " @@ -591,8 +591,8 @@ def test_button_responsive_size( "backgroundColor": { "default": "transparent", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a2)"}, - "[data-state='open']": "var(--accent-a2)", - ":active:not([data-state='open'])": "var(--accent-a3)", + ":is([data-state='open'], [data-open])": "var(--accent-a2)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-a3)", "[data-disabled]": "transparent", }, "backgroundImage": "none", @@ -679,7 +679,7 @@ def test_button_disabled( assert component.render() == { "name": '"button"', "props": [ - "className:sx_f2580dfc68_c", + "className:sx_16addd9092_c", '"data-disabled":true', "disabled:true", 'type:"submit"', @@ -696,7 +696,7 @@ def test_button_loading( component = rx.ui.button("Save", loading=True, size="4") assert component.render() == { "name": '"button"', - "props": ["className:sx_33c6aced18_c", '"data-disabled":true', "disabled:true"], + "props": ["className:sx_b0c5b54627_c", '"data-disabled":true', "disabled:true"], "children": [ { "name": '"span"', @@ -783,8 +783,8 @@ def test_button_loading( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, - "[data-state='open']": "var(--accent-10)", - ":active:not([data-state='open'])": "var(--accent-10)", + ":is([data-state='open'], [data-open])": "var(--accent-10)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, "backgroundImage": "none", @@ -807,7 +807,7 @@ def test_button_loading( "outlineStyle": { "default": "none", "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "solid" }, ":focus-visible:not([data-disabled])": "solid", }, @@ -832,26 +832,26 @@ def test_button_loading( "[data-disabled]": "var(--gray-a8)", }, "filter": { - ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + ":active:not(:is([data-state='open'], [data-open]))": "var(--rx-if-light, brightness(0.92) " "saturate(1.1)) var(--rx-if-dark, " "brightness(1.08))", "[data-disabled]": "none", }, "outlineWidth": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" }, ":focus-visible:not([data-disabled])": "2px", }, "outlineColor": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "var(--accent-a4)" }, ":focus-visible:not([data-disabled])": "var(--focus-8)", }, "outlineOffset": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0" }, ":focus-visible:not([data-disabled])": "2px", }, @@ -928,8 +928,8 @@ def test_button_bound_to_state( "name": '"button"', "props": [ ( - 'className:sx_878a6e8128_c + " " + ' - "(sx_878a6e8128_0[reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_] " + 'className:sx_ee694bd455_c + " " + ' + "(sx_ee694bd455_0[reflex___state____state__tests___units___reflex_components_ui___components___test_button____button_state.busy_rx_state_] " '?? "")' ), ( @@ -1060,7 +1060,7 @@ def test_button_as_child( assert component.render() == { "name": "ReactRouterLink", "props": [ - "className:sx_f2580dfc68_c", + "className:sx_16addd9092_c", '"data-disabled":true', "disabled:true", 'to:"/docs"', diff --git a/tests/units/reflex_components_ui/components/test_card.py b/tests/units/reflex_components_ui/components/test_card.py index 74c08d9eacf..0a0ec24c517 100644 --- a/tests/units/reflex_components_ui/components/test_card.py +++ b/tests/units/reflex_components_ui/components/test_card.py @@ -18,7 +18,7 @@ def test_card_plain( component = rx.ui.card("Invoice") assert component.render() == { "name": '"div"', - "props": ["className:sx_8966fad991_c"], + "props": ["className:sx_a3eabfe8d9_c"], "children": [{"contents": '"Invoice"'}], } assert declared_styles(component) == [ @@ -42,10 +42,10 @@ def test_card_plain( "backgroundImage": { "default": "none", "::before": { - ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + ":focus-visible:active:not(:is([data-state='open'], [data-open]))": "linear-gradient(var(--focus-a2), " "var(--focus-a2))", "@media (pointer: coarse)": { - ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + ":is(:any-link, button, label):active:not(:focus-visible, :is([data-state='open'], [data-open]))": "linear-gradient(var(--gray-a4), " "var(--gray-a4))" }, }, @@ -142,14 +142,14 @@ def test_card_plain( "var(--gray-7) " "25%)" }, - ":is(:any-link, button, label)[data-state='open']": "0 0 0 " + ":is(:any-link, button, label):is([data-state='open'], [data-open])": "0 0 0 " "1px " "color-mix(in " "oklab, " "var(--gray-a7), " "var(--gray-7) " "25%)", - ":is(:any-link, button, label):active:not([data-state='open'])": "0 " + ":is(:any-link, button, label):active:not(:is([data-state='open'], [data-open]))": "0 " "0 " "0 " "1px " @@ -191,10 +191,10 @@ def test_card_classic( "backgroundImage": { "default": "none", "::before": { - ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + ":focus-visible:active:not(:is([data-state='open'], [data-open]))": "linear-gradient(var(--focus-a2), " "var(--focus-a2))", "@media (pointer: coarse)": { - ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + ":is(:any-link, button, label):active:not(:focus-visible, :is([data-state='open'], [data-open]))": "linear-gradient(var(--gray-a4), " "var(--gray-a4))" }, }, @@ -263,8 +263,8 @@ def test_card_classic( "@media (hover: hover)": { ":is(:any-link, button, label):hover:not(:active)": "40ms" }, - ":is(:any-link, button, label)[data-state='open']": "40ms", - ":is(:any-link, button, label):active:not([data-state='open'])": "40ms", + ":is(:any-link, button, label):is([data-state='open'], [data-open])": "40ms", + ":is(:any-link, button, label):active:not(:is([data-state='open'], [data-open]))": "40ms", "::before": "inherit", "::after": "inherit", }, @@ -370,7 +370,7 @@ def test_card_classic( "-9px " "var(--gray-a7))" }, - ":is(:any-link, button, label)[data-state='open']": "var(--rx-if-light, " + ":is(:any-link, button, label):is([data-state='open'], [data-open])": "var(--rx-if-light, " "0 0 0 0 " "color-mix(in " "oklab, " @@ -402,7 +402,7 @@ def test_card_classic( "var(--gray-a3), 0 " "0 16px -9px " "var(--gray-a7))", - ":is(:any-link, button, label):active:not([data-state='open'])": "var(--rx-if-light, " + ":is(:any-link, button, label):active:not(:is([data-state='open'], [data-open]))": "var(--rx-if-light, " "0 0 " "0 0 " "color-mix(in " @@ -545,7 +545,7 @@ def test_card_classic( "-8px " "var(--gray-a7))" }, - ":is(:any-link, button, label)[data-state='open']": "var(--rx-if-light, " + ":is(:any-link, button, label):is([data-state='open'], [data-open])": "var(--rx-if-light, " "0 0 0 " "1px " "color-mix(in " @@ -601,7 +601,7 @@ def test_card_classic( "16px " "-8px " "var(--gray-a7))", - ":is(:any-link, button, label):active:not([data-state='open'])": "var(--rx-if-light, " + ":is(:any-link, button, label):active:not(:is([data-state='open'], [data-open]))": "var(--rx-if-light, " "0 " "0 " "0 " @@ -702,17 +702,17 @@ def test_card_ghost_responsive( ":is(:any-link, button, label):hover:not(:active, :focus-visible)": "var(--gray-a3)", ":is(:any-link, button, label):hover:focus-visible": "var(--focus-a2)", }, - ":is(:any-link, button, label)[data-state='open']:not(:focus-visible)": "var(--gray-a3)", - ":is(:any-link, button, label):active:not([data-state='open'], :focus-visible)": "var(--gray-a4)", - ":is(:any-link, button, label):focus-visible:is(:active, [data-state='open'])": "var(--focus-a2)", + ":is(:any-link, button, label):is([data-state='open'], [data-open]):not(:focus-visible)": "var(--gray-a3)", + ":is(:any-link, button, label):active:not(:is([data-state='open'], [data-open]), :focus-visible)": "var(--gray-a4)", + ":is(:any-link, button, label):focus-visible:is(:active, :is([data-state='open'], [data-open]))": "var(--focus-a2)", }, "backgroundImage": { "default": "none", "::before": { - ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + ":focus-visible:active:not(:is([data-state='open'], [data-open]))": "linear-gradient(var(--focus-a2), " "var(--focus-a2))", "@media (pointer: coarse)": { - ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + ":is(:any-link, button, label):active:not(:focus-visible, :is([data-state='open'], [data-open]))": "linear-gradient(var(--gray-a4), " "var(--gray-a4))" }, }, @@ -810,7 +810,7 @@ def test_card_as_child( component = rx.ui.card(rx.el.a("Invoice", href="/invoice"), as_child=True) assert component.render() == { "name": "ReactRouterLink", - "props": ["className:sx_8966fad991_c", 'to:"/invoice"'], + "props": ["className:sx_a3eabfe8d9_c", 'to:"/invoice"'], "children": [{"contents": '"Invoice"'}], } @@ -842,10 +842,10 @@ def test_card_keeps_its_surface_under_a_background( "backgroundImage": { "default": "none", "::before": { - ":focus-visible:active:not([data-state='open'])": "linear-gradient(var(--focus-a2), " + ":focus-visible:active:not(:is([data-state='open'], [data-open]))": "linear-gradient(var(--focus-a2), " "var(--focus-a2))", "@media (pointer: coarse)": { - ":is(:any-link, button, label):active:not(:focus-visible, [data-state='open'])": "linear-gradient(var(--gray-a4), " + ":is(:any-link, button, label):active:not(:focus-visible, :is([data-state='open'], [data-open]))": "linear-gradient(var(--gray-a4), " "var(--gray-a4))" }, }, @@ -942,14 +942,14 @@ def test_card_keeps_its_surface_under_a_background( "var(--gray-7) " "25%)" }, - ":is(:any-link, button, label)[data-state='open']": "0 0 0 " + ":is(:any-link, button, label):is([data-state='open'], [data-open])": "0 0 0 " "1px " "color-mix(in " "oklab, " "var(--gray-a7), " "var(--gray-7) " "25%)", - ":is(:any-link, button, label):active:not([data-state='open'])": "0 " + ":is(:any-link, button, label):active:not(:is([data-state='open'], [data-open]))": "0 " "0 " "0 " "1px " diff --git a/tests/units/reflex_components_ui/components/test_color_mode.py b/tests/units/reflex_components_ui/components/test_color_mode.py index b8f278a0d3a..dcf7359a284 100644 --- a/tests/units/reflex_components_ui/components/test_color_mode.py +++ b/tests/units/reflex_components_ui/components/test_color_mode.py @@ -79,7 +79,7 @@ def test_button_toggles_the_color_mode( component = compiled(rx.ui.color_mode.button()) assert component.render() == { "name": '"button"', - "props": ["className:sx_4aef8418fd_c", TOGGLE], + "props": ["className:sx_7c9bd25a71_c", TOGGLE], "children": [ICON], } assert declared_styles(component) == [_icon_button_style(declared_styles, compiled)] @@ -155,21 +155,24 @@ def test_button_that_allows_the_system_mode_opens_a_menu( declared_styles: Callable[[Any], list[dict[str, Any]]], compiled: Callable[[Component], Component], ): - """The button opens a menu of the three modes, with the props on itself.""" + """The button opens a menu of the three modes, with the props on itself. + + The trigger of the menu renders as the button, which UI SDK gives the + attributes of a trigger. + """ component = compiled(rx.ui.color_mode.button(allow_system=True)) trigger, content = component.render()["children"] assert trigger == { - "name": '"button"', + "name": "MenuTrigger", "props": [ - '"aria-controls":"rx-dropdown-menu-1"', - '"aria-expanded":false', - '"aria-haspopup":"menu"', - "className:sx_4aef8418fd_c", - '"data-state":"closed"', - "onKeyDown:menuTrigger", - 'popoverTarget:"rx-dropdown-menu-1"', + ( + 'render:(jsx("button", ({className:sx_7c9bd25a71_c}), (jsx(Fragment, ' + '({}), ((resolvedColorMode?.valueOf?.() === "light"?.valueOf?.()) ? ' + "(jsx(Fragment, ({}), (jsx(LucideSun, ({}))))) : (jsx(Fragment, ({}), " + "(jsx(LucideMoon, ({}))))))))))" + ) ], - "children": [ICON], + "children": [], } items = content["children"][0]["children"][0]["children"] assert [(item["children"][0]["contents"], item["props"][1]) for item in items] == [ @@ -183,9 +186,8 @@ def test_button_that_allows_the_system_mode_opens_a_menu( ) for mode in ("light", "dark", "system") ] - assert declared_styles(component)[2] == _icon_button_style( - declared_styles, compiled - ) + button = component.children[0]._child # pyright: ignore[reportAttributeAccessIssue] + assert declared_styles(button) == [_icon_button_style(declared_styles, compiled)] def test_switch_is_on_in_dark_mode( @@ -224,9 +226,12 @@ def test_button_that_allows_the_system_mode_keeps_its_corner( component = compiled( rx.ui.color_mode.button(allow_system=True, position="top-right") ) - assert declared_styles(component)[2] == _icon_button_style( - declared_styles, compiled, position="fixed", top="2rem", right="2rem" - ) + button = component.children[0]._child # pyright: ignore[reportAttributeAccessIssue] + assert declared_styles(button) == [ + _icon_button_style( + declared_styles, compiled, position="fixed", top="2rem", right="2rem" + ) + ] def test_controls_name_themselves_in_errors(ui_plugin: UIPlugin): diff --git a/tests/units/reflex_components_ui/components/test_dialog.py b/tests/units/reflex_components_ui/components/test_dialog.py index 0972b526af1..5d0d5604ab9 100644 --- a/tests/units/reflex_components_ui/components/test_dialog.py +++ b/tests/units/reflex_components_ui/components/test_dialog.py @@ -1,554 +1,166 @@ """Tests for reflex_components_ui.components.dialog.""" -import itertools from collections.abc import Callable from typing import Any import pytest from reflex_base.utils.imports import ImportVar -from reflex_components_ui.components import _dialog from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import StyleError import reflex as rx +DIALOG = "@ui-sdk/react@0.1.0-beta.17/dialog" -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the dialogs of each test from one.""" - monkeypatch.setattr(_dialog, "_ids", itertools.count(1)) +class DialogState(rx.State): + """What a dialog is bound to.""" -def test_dialog( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A dialog is a native dialog over the page, around the panel an app styles; its trigger and its close button are their children, which command it; its title and its description name it.""" + open: bool = False + + @rx.event + def set_open(self, open: bool): + """Follow the dialog. + + Args: + open: Whether it is open. + """ + self.open = open + + +def test_dialog(ui_plugin: UIPlugin): + """A dialog is the parts of UI SDK: a backdrop over the page, and its content, the panel. + + The trigger and the close button render as their child, the title as a + heading of the first level, and the root renders no element. + """ component = rx.ui.dialog.root( - rx.ui.dialog.trigger(rx.el.button("Open", id="open")), + rx.ui.dialog.trigger(rx.el.button("Open")), rx.ui.dialog.content( rx.ui.dialog.title("Title"), - rx.ui.dialog.description("What it is about.", id="about"), + rx.ui.dialog.description("Text"), rx.ui.dialog.close(rx.el.button("Close")), size="2", - max_width="400px", - id="panel", ), default_open=True, ) assert component.render() == { - "name": '"div"', - "props": [ - "className:sx_71b84cd269_c", - '"data-rx-dialog-root":""', - "onClick:dialogClick", - ], + "name": "Dialog", + "props": ["defaultOpen:true"], "children": [ { - "name": '"button"', - "props": [ - '"aria-controls":"rx-dialog-1"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - 'command:"show-modal"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - 'id:"open"', - "ref:ref_open", - ], - "children": [{"contents": '"Open"'}], + "name": "DialogTrigger", + "props": ['render:(jsx("button", ({}), "Open"))'], + "children": [], }, { - "name": '"dialog"', - "props": [ - '"aria-describedby":"about"', - '"aria-labelledby":"rx-dialog-1-labelledby"', - "className:sx_826e1f6eca_c", - '"data-default-open":true', - '"data-rx-popup":""', - 'id:"rx-dialog-1"', - "onCancel:dialogEvent", - "onClose:dialogEvent", - "ref:((dialog) => dialogSync(dialog, null, null))", - ], + "name": "Fragment", + "props": [], "children": [ { - "name": '"div"', - "props": [ - "className:sx_18e4ad36e3_c", - '"data-rx-dialog-pad":""', - ], + "name": "DialogBackdrop", + "props": ["className:sx_dd9768c199_c"], + "children": [], + }, + { + "name": "DialogContent", + "props": ["className:sx_b7708e6de5_c"], "children": [ { - "name": '"div"', + "name": "DialogTitle", "props": [ - "className:sx_02cf547cd4_c", - 'id:"panel"', - "ref:ref_panel", + "className:sx_29271ef72f_c", + 'render:(jsx("h1", ({})))', ], - "children": [ - { - "name": '"h1"', - "props": [ - "className:sx_29271ef72f_c", - 'id:"rx-dialog-1-labelledby"', - ], - "children": [{"contents": '"Title"'}], - }, - { - "name": '"p"', - "props": [ - "className:sx_9b5373509f_c", - 'id:"about"', - "ref:ref_about", - ], - "children": [ - {"contents": '"What it is about."'} - ], - }, - { - "name": '"button"', - "props": [ - 'command:"close"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-close":""', - ], - "children": [{"contents": '"Close"'}], - }, - ], - } - ], - } - ], - }, - ], - } - assert declared_styles(component) == [ - {"display": "contents"}, - {}, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": { - "default": "transparent", - "::backdrop": "transparent", - "::before": "var(--color-overlay)", - }, - "color": "inherit", - "maxWidth": "none", - "maxHeight": "none", - "outlineStyle": "none", - "userSelect": "auto", - "transitionProperty": { - "default": "display, overlay", - "::before": "opacity", - }, - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", - "::before": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", - }, - }, - "--rx-dialog-shown": {"default": 0, "[open]": 1}, - "position": {"default": "fixed", "::before": "fixed"}, - "top": {"default": "0", "::before": "0"}, - "right": {"default": "0", "::before": "0"}, - "bottom": {"default": "0", "::before": "0"}, - "left": {"default": "0", "::before": "0"}, - "width": "100%", - "height": "100%", - "display": {"default": "none", "[open]": "flex"}, - "overflowX": "auto", - "overflowY": "auto", - "--rx-dialog-gone": { - "default": "translateY(5px) scale(0.99)", - "[open]": "none", - }, - "--rx-dialog-duration": {"default": "160ms", "[open]": "200ms"}, - "content": {"::before": "''"}, - "opacity": { - "::before": { - "default": 0, - "[open]": {"default": 1, "@starting-style": 0}, - } - }, - "transitionTimingFunction": {"::before": "cubic-bezier(0.16, 1, 0.3, 1)"}, - }, - { - "flexGrow": 1, - "marginTop": "auto", - "marginRight": "auto", - "marginBottom": "auto", - "marginLeft": "auto", - "paddingTop": "var(--space-6)", - "paddingBottom": "max(var(--space-6), 6vh)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - }, - { - "marginTop": "auto", - "marginRight": "auto", - "marginBottom": "auto", - "marginLeft": "auto", - "width": "100%", - "maxWidth": "400px", - "zIndex": 1, - "position": "relative", - "boxSizing": "border-box", - "overflowX": "auto", - "overflowY": "auto", - "--inset-padding-top": "var(--dialog-content-padding)", - "--inset-padding-right": "var(--dialog-content-padding)", - "--inset-padding-bottom": "var(--dialog-content-padding)", - "--inset-padding-left": "var(--dialog-content-padding)", - "padding": "var(--dialog-content-padding)", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-6)", - "outlineStyle": "none", - "opacity": {"default": "var(--rx-dialog-shown)", "@starting-style": 0}, - "transform": { - "default": "var(--rx-dialog-gone)", - "@starting-style": "translateY(5px) scale(0.97)", - }, - "transitionProperty": "opacity, transform", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": "calc(100ms + var(--rx-dialog-shown) * 100ms)", - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "--dialog-content-padding": "var(--space-4)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - }, - { - "--leading-trim-start": "var(--heading-leading-trim-start)", - "--leading-trim-end": "var(--heading-leading-trim-end)", - "fontFamily": "var(--heading-font-family)", - "fontStyle": "var(--heading-font-style)", - "fontWeight": "var(--font-weight-bold)", - "lineHeight": "var(--line-height)", - "marginTop": "0", - "marginRight": "0", - "marginBottom": { - "default": "var(--space-3)", - "::before": "calc(var(--leading-trim-start, var(--default-leading-trim-start)) - var(--line-height, calc(1em * var(--default-line-height))) / 2)", - }, - "marginLeft": "0", - "fontSize": "calc(var(--font-size-5) * var(--heading-font-size-adjust))", - "--line-height": "var(--heading-line-height-5)", - "letterSpacing": "calc(var(--letter-spacing-5) + var(--heading-letter-spacing))", - "content": {"::before": "''", "::after": "none"}, - "display": {"::before": "table"}, - }, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "lineHeight": "var(--line-height, var(--default-line-height))", - "letterSpacing": "var(--letter-spacing, inherit)", - "fontSize": "var(--font-size-3)", - "--line-height": "var(--line-height-3)", - "--letter-spacing": "var(--letter-spacing-3)", - }, - {}, - ] - - -def test_dialog_in_a_dialog(ui_plugin: UIPlugin): - """A dialog inside a dialog is its own: each trigger commands its dialog, and a child that hears a press itself is put in a flex container.""" - component = rx.ui.dialog.root( - rx.ui.dialog.trigger(rx.el.button("Open", on_click=rx.console_log("pressed"))), - rx.ui.dialog.content( - rx.ui.dialog.root( - rx.ui.dialog.trigger(rx.el.button("Inner")), - rx.ui.dialog.content("Inside"), - ), - ), - ) - assert component.render() == { - "name": '"div"', - "props": [ - "className:sx_71b84cd269_c", - '"data-rx-dialog-root":""', - "onClick:dialogClick", - ], - "children": [ - { - "name": '"div"', - "props": [ - '"aria-controls":"rx-dialog-2"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - "className:sx_78b49527aa_c", - 'command:"show-modal"', - 'commandfor:"rx-dialog-2"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - ], - "children": [ - { - "name": '"button"', - "props": [ - 'onClick:((_e) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("pressed"))), ["callback"] : null }), ({ })))], [_e], ({ }))))' - ], - "children": [{"contents": '"Open"'}], - } - ], - }, - { - "name": '"dialog"', - "props": [ - "className:sx_826e1f6eca_c", - '"data-rx-popup":""', - 'id:"rx-dialog-2"', - "onCancel:dialogEvent", - "onClose:dialogEvent", - "ref:((dialog) => dialogSync(dialog, null, null))", - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_18e4ad36e3_c", - '"data-rx-dialog-pad":""', - ], - "children": [ + "children": [{"contents": '"Title"'}], + }, { - "name": '"div"', - "props": ["className:sx_41c452192b_c"], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_71b84cd269_c", - '"data-rx-dialog-root":""', - "onClick:dialogClick", - ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-dialog-1"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - 'command:"show-modal"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - ], - "children": [{"contents": '"Inner"'}], - }, - { - "name": '"dialog"', - "props": [ - "className:sx_826e1f6eca_c", - '"data-rx-popup":""', - 'id:"rx-dialog-1"', - "onCancel:dialogEvent", - "onClose:dialogEvent", - "ref:((dialog) => dialogSync(dialog, null, null))", - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_18e4ad36e3_c", - '"data-rx-dialog-pad":""', - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_41c452192b_c" - ], - "children": [ - { - "contents": '"Inside"' - } - ], - } - ], - } - ], - }, - ], - } - ], - } - ], - } - ], - }, - ], - } - - -def test_dialog_parts_alone(ui_plugin: UIPlugin): - """The parts of a dialog outside one render without its name.""" - component = rx.el.div( - rx.ui.dialog.trigger(rx.el.button("Open")), - rx.ui.dialog.content( - rx.ui.dialog.title("Title"), rx.ui.dialog.description("About") - ), - rx.ui.dialog.close(rx.el.button("Close")), - ) - assert component.render() == { - "name": '"div"', - "props": [], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - ], - "children": [{"contents": '"Open"'}], - }, - { - "name": '"dialog"', - "props": [ - "className:sx_826e1f6eca_c", - '"data-rx-popup":""', - "onCancel:dialogEvent", - "onClose:dialogEvent", - "ref:((dialog) => dialogSync(dialog, null, null))", - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_18e4ad36e3_c", - '"data-rx-dialog-pad":""', - ], - "children": [ + "name": "DialogDescription", + "props": ["className:sx_9b5373509f_c"], + "children": [{"contents": '"Text"'}], + }, { - "name": '"div"', - "props": ["className:sx_41c452192b_c"], - "children": [ - { - "name": '"h1"', - "props": ["className:sx_29271ef72f_c"], - "children": [{"contents": '"Title"'}], - }, - { - "name": '"p"', - "props": ["className:sx_9b5373509f_c"], - "children": [{"contents": '"About"'}], - }, - ], - } + "name": "DialogClose", + "props": ['render:(jsx("button", ({}), "Close"))'], + "children": [], + }, ], - } + }, ], }, - { - "name": '"button"', - "props": ['"data-rx-dialog-close":""'], - "children": [{"contents": '"Close"'}], - }, ], } -class DialogState(rx.State): - """What a dialog is bound to.""" - - shown: bool = False - - @rx.event - def set_shown(self, shown: bool): - """Follow the dialog. - - Args: - shown: Whether it is open. - """ - self.shown = shown - - @rx.event - def note(self): - """Hear that something happened to the dialog.""" - - def test_dialog_bound_to_state(ui_plugin: UIPlugin): - """A dialog bound to state hands its script its state and what it does when it is asked to open or close, and its trigger commands nothing.""" - name = DialogState.get_full_name() + """A dialog bound to state takes whether it is open from it. + + The events Radix fires on the content are called by the reason UI SDK + gives for a change of the dialog. + """ component = rx.ui.dialog.root( - rx.ui.dialog.trigger(rx.el.button("Open")), rx.ui.dialog.content( "x", - on_escape_key_down=DialogState.note, - on_interact_outside=DialogState.note, + on_escape_key_down=DialogState.set_open(False), + on_open_auto_focus=rx.console_log("in"), ), - open=DialogState.shown, - on_open_change=DialogState.set_shown, + open=DialogState.open, + on_open_change=DialogState.set_open, ) - rendered = component.render() - assert rendered["props"] == [ - "className:sx_71b84cd269_c", - '"data-rx-dialog-root":""', - "onClick:dialogClick", - ] - trigger, dialog = rendered["children"] - assert trigger["props"] == [ - '"aria-controls":"rx-dialog-1"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - ] - note = ( - f'((...args) => (addEvents([(ReflexEvent("{name}.note", ({{ }}), ' - "({ })))], args, ({ }))))" + handler = ( + '"reflex___state____state.tests___units___reflex_components_ui___' + 'components___test_dialog____dialog_state.set_open"' ) - assert dialog["props"] == [ - "className:sx_826e1f6eca_c", - '"data-rx-popup":""', - 'id:"rx-dialog-1"', - "onCancel:dialogEvent", - "onClose:dialogEvent", + assert component.render()["props"] == [ ( - f"ref:((dialog) => dialogSync(dialog, {DialogState.shown!s}, ({{ open: " - f'((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' - '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))), ' - f"escape: {note}, interact: {note} }})))" + "onOpenChange:((value, details) => { const change = ((_ev_0) => " + f'(addEvents([(ReflexEvent({handler}, ({{ ["open"] : _ev_0 }}), ' + "({ })))], [_ev_0], ({ })))), openAutoFocus = ((...args) => " + '(addEvents([(ReflexEvent("_call_function", ({ ["function"] : ' + '(() => (console?.["log"]("in"))), ["callback"] : null }), ({ })))], ' + "args, ({ })))), closeAutoFocus = undefined, escape = ((...args) => " + f'(addEvents([(ReflexEvent({handler}, ({{ ["open"] : false }}), ' + "({ })))], args, ({ })))), outside = undefined, interact = undefined; " + 'if (details?.reason === "escape-key") escape?.(); ' + 'if (details?.reason === "outside-press") { outside?.(); interact?.(); } ' + "change?.(value); if (value) openAutoFocus?.(); else closeAutoFocus?.(); })" ), + ( + "open:reflex___state____state__tests___units___reflex_components_ui___" + "components___test_dialog____dialog_state.open_rx_state_" + ), + ] + + +def test_dialog_trigger_keeps_the_styles_of_its_child( + ui_plugin: UIPlugin, compiled: Callable[[Any], Any] +): + """The element a trigger renders as is styled by the page, as a child is.""" + trigger = compiled(rx.ui.dialog.trigger(rx.ui.button("Open"))) + (button,) = trigger._get_components_in_props() + assert trigger.render()["props"] == [ + f'render:(jsx("button", ({{className:{button._emit().classes}}}), "Open"))' ] + assert trigger._get_all_custom_code() == button._get_all_custom_code() -def test_dialog_imports_its_script(ui_plugin: UIPlugin): - """A page with a dialog loads the script of a dialog, and no other.""" +def test_dialog_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a dialog imports its parts from UI SDK, pinned, and no script.""" component = rx.ui.dialog.root( rx.ui.dialog.trigger(rx.el.button("Open")), rx.ui.dialog.content("x") ) imports = component._get_all_imports() assert { - module: names for module, names in imports.items() if "behaviors" in module + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module } == { - "$/reflex-ui/behaviors/dialog.js": [ - ImportVar(tag="dialogClick"), - ImportVar(tag="dialogSync"), - ImportVar(tag="dialogEvent"), + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + DIALOG: [ + ImportVar(tag="Dialog"), + ImportVar(tag="DialogTrigger"), + ImportVar(tag="DialogBackdrop"), + ImportVar(tag="DialogContent"), ], } diff --git a/tests/units/reflex_components_ui/components/test_dropdown_menu.py b/tests/units/reflex_components_ui/components/test_dropdown_menu.py index e4f3f865df4..da6496f08bb 100644 --- a/tests/units/reflex_components_ui/components/test_dropdown_menu.py +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -1,482 +1,328 @@ """Tests for reflex_components_ui.components.dropdown_menu.""" -import itertools from collections.abc import Callable from typing import Any import pytest from reflex_base.utils.imports import ImportVar -from reflex_components_ui.components import _popup -from reflex_components_ui.components._menu import _CHEVRON from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import StyleError import reflex as rx +MENU = "@ui-sdk/react@0.1.0-beta.17/menu" -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the popups of each test from one.""" - monkeypatch.setattr(_popup, "_ids", itertools.count(1)) + +def _tree(rendered: dict[str, Any]) -> Any: + """Project a render onto what a test reads: names, props and text. + + Args: + rendered: The render of a component. + + Returns: + The text of a text node, ``("svg",)`` for an icon, else the name, the + props and the projection of each child. + """ + if "contents" in rendered: + return rendered["contents"] + if rendered["name"] == '"svg"': + return ("svg",) + return ( + rendered["name"], + rendered["props"], + [_tree(child) for child in rendered["children"]], + ) + + +def _scrolled(*items: Any) -> tuple[str, list[str], list[Any]]: + """The elements that scroll the items of a menu, around them. + + Args: + *items: The projections of the items. + + Returns: + The projection. + """ + return ( + '"div"', + ["className:sx_b8ae355be2_c"], + [('"div"', ["className:sx_453162d43a_c"], list(items))], + ) + + +class MenuState(rx.State): + """What a menu is bound to.""" + + shown: bool = False + + @rx.event + def set_shown(self, shown: bool): + """Follow the menu. + + Args: + shown: Whether it is open. + """ + self.shown = shown def test_dropdown_menu(ui_plugin: UIPlugin): - """A dropdown menu is its trigger, then a popover of items whose look the content hands its items and its sub-menus, which a script moves through.""" + """A dropdown menu is the parts of UI SDK, in the look its content hands its items and sub-menus. + + The props of Radix take the names of UI SDK, those of the content that + are the menu's move to it, and the placement of Radix Themes is the + default: below and at the start of the trigger, 4px from it, 10px from + the edges, and a sub-menu as high as the padding of its menu. + """ menu = rx.ui.dropdown_menu component = menu.root( menu.trigger(rx.el.button("Options")), menu.content( - menu.item("Edit", shortcut="⌘ E", text_value="Change"), - menu.item("Delete", color_scheme="red", disabled=True), + menu.item("Edit", shortcut="⌘ E", text_value="edit"), menu.separator(), - menu.sub(menu.sub_trigger("More"), menu.sub_content(menu.item("Share"))), - variant="soft", + menu.sub( + menu.sub_trigger("More"), + menu.sub_content(menu.item("Archive", disabled=True)), + ), size="1", - high_contrast=True, + variant="soft", loop=True, - side_offset=6, + side="top", + side_offset=8, + avoid_collisions=False, ), - default_open=True, + modal=False, + dir="rtl", ) - assert component.render() == { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-dropdown-menu-2"', - '"aria-expanded":false', - '"aria-haspopup":"menu"', - '"data-state":"closed"', - "onKeyDown:menuTrigger", - 'popoverTarget:"rx-dropdown-menu-2"', - ], - "children": [{"contents": '"Options"'}], - }, - { - "name": '"div"', - "props": [ - "className:sx_47b417df9e_c", - '"data-default-open":true', - '"data-loop":true', - '"data-rx-popup":""', - 'id:"rx-dropdown-menu-2"', - "onBeforeToggle:((event) => { (menuEvent)(event); (popupBeforeToggle)(event); })", - "onBlur:menuEvent", - "onClick:menuEvent", - "onKeyDown:menuEvent", - "onPointerLeave:menuEvent", - "onPointerMove:menuEvent", - "onToggle:menuEvent", - 'popover:"auto"', - "ref:((popup) => menuSync(popup, null))", - 'role:"menu"', - "tabIndex:-1", + item = "className:sx_5c93cdaf19_c" + assert _tree(component.render()) == ( + "Menu", + ["loop:true", "modal:false"], + [ + ("MenuTrigger", ['render:(jsx("button", ({}), "Options"))'], []), + ( + "MenuContent", + [ + 'align:"start"', + "className:sx_c3f4b8c3e8_c", + "collisionPadding:10", + 'side:"top"', + "sideOffset:8", ], - "children": [ - { - "name": '"div"', - "props": ["className:sx_b8ae355be2_c"], - "children": [ - { - "name": '"div"', - "props": ["className:sx_453162d43a_c"], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_da4b1b2e3f_c", - '"data-text-value":"Change"', - 'role:"menuitem"', - "tabIndex:-1", - ], - "children": [ - {"contents": '"Edit"'}, - { - "name": '"div"', - "props": ["className:sx_da7de3c8ae_c"], - "children": [ - {"contents": '"\\u2318 E"'} - ], - }, - ], - }, - { - "name": '"div"', - "props": [ - '"aria-disabled":true', - 'className:sx_52d0500fbd_c + " " + reflexUIClasses_01ac7ed29f', - 'role:"menuitem"', - "tabIndex:-1", - ], - "children": [{"contents": '"Delete"'}], - }, - { - "name": '"div"', - "props": [ - '"aria-orientation":"horizontal"', - "className:sx_834f03d11d_c", - 'role:"separator"', - ], - "children": [], - }, - { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"div"', - "props": [ - '"aria-controls":"rx-menu-sub-1"', - '"aria-expanded":false', - '"aria-haspopup":"menu"', - "className:sx_da4b1b2e3f_c", - '"data-rx-opens":"rx-menu-sub-1"', - '"data-state":"closed"', - 'role:"menuitem"', - "tabIndex:-1", - ], - "children": [ - {"contents": '"More"'}, - { - "name": '"div"', - "props": [ - "className:sx_da7de3c8ae_c" - ], - "children": [ - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_ddf3393e61_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - f'd:"{_CHEVRON}"' - ], - "children": [], - } - ], - } - ], - }, - ], - }, - { - "name": '"div"', - "props": [ - "className:sx_f920401ab7_c", - '"data-rx-popup":""', - 'id:"rx-menu-sub-1"', - "onBeforeToggle:((event) => { (menuEvent)(event); (popupBeforeToggle)(event); })", - "onBlur:menuEvent", - "onClick:menuEvent", - "onKeyDown:menuEvent", - "onPointerLeave:menuEvent", - "onPointerMove:menuEvent", - "onToggle:menuEvent", - 'popover:"auto"', - "ref:((popup) => menuSync(popup, null))", - 'role:"menu"', - "tabIndex:-1", - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_b8ae355be2_c" - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_453162d43a_c" - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_da4b1b2e3f_c", - 'role:"menuitem"', - "tabIndex:-1", - ], - "children": [ - { - "contents": '"Share"' - } - ], - } - ], - } - ], - } - ], - }, - ], - }, - ], - } - ], - } + [ + _scrolled( + ( + "MenuItem", + [item, 'label:"edit"'], + [ + '"Edit"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + ['"\\u2318 E"'], + ), + ], + ), + ("MenuSeparator", ["className:sx_834f03d11d_c"], []), + ( + "MenuSub", + [], + [ + ( + "MenuSubTrigger", + [item], + [ + '"More"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + [("svg",)], + ), + ], + ), + ( + "MenuSubContent", + [ + "alignOffset:-4", + "className:sx_6df86afa34_c", + "collisionPadding:10", + "sideOffset:1", + ], + [ + _scrolled(( + "MenuItem", + [item, "disabled:true"], + ['"Archive"'], + )) + ], + ), + ], + ), + ) ], - }, + ), ], - } + ) def test_dropdown_menu_styles( ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] ): - """The menu has the look of the menu of Radix Themes, its items the one of its items, as the menu hands them down.""" + """UI SDK places the menu; it comes in from the side it ended up on, and its items highlight by UI SDK's state.""" menu = rx.ui.dropdown_menu component = menu.root( menu.trigger(rx.el.button("Options")), menu.content(menu.item("Edit")) ) - assert declared_styles(component) == [ - {}, - {}, - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-y, 0px))", - "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(10px - var(--rx-popup-snap-y, 0px))", - "marginLeft": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-x, 0px))", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "calc(100vw - 10px * 2)", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "100ms", - ":popover-open": "160ms", - }, + root, trigger, content, _, _, item = declared_styles(component) + placement = ( + "position", + "opacity", + "transform", + "transitionProperty", + "transitionDuration", + "maxHeight", + "transformOrigin", + "--rx-popup-from", + "display", + ) + assert (root, trigger) == ({}, {}) + assert {key: content.get(key) for key in placement} == { + "position": "fixed", + "opacity": {"default": 1, "@starting-style": 0, "[data-ending-style]": 0}, + "transform": { + "default": "none", + "@starting-style": "var(--rx-popup-from)", + "[data-ending-style]": "var(--rx-popup-from)", + }, + "transitionProperty": "opacity, transform", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "160ms", + "[data-ending-style]": "100ms", }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "var(--gray-12)", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "display": {"default": "none", ":popover-open": "flex"}, - "flexDirection": "column", - "overflowX": "hidden", - "overflowY": "hidden", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-5)", - "outlineStyle": "none", - "--base-menu-content-padding": "var(--space-2)", - "--base-menu-item-padding-right": "var(--space-3)", - "--base-menu-item-height": "var(--space-6)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "--rx-menu-font-size": "var(--font-size-2)", - "--rx-menu-line-height": "var(--line-height-2)", - "--rx-menu-letter-spacing": "var(--letter-spacing-2)", - "--rx-menu-item-radius": "var(--radius-2)", - "--rx-menu-icon-size": "calc(10px * var(--scaling))", - "--base-menu-item-padding-left": "var(--space-3)", - "positionArea": "bottom span-right", - "maxHeight": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", - "--rx-popup-from": "translateY(-4px) scale(0.97)", - "transformOrigin": "top left", }, - { - "flexGrow": "1", - "flexShrink": "1", - "flexBasis": "0%", - "minHeight": "0", - "overflowX": "auto", - "overflowY": "auto", - "scrollbarWidth": "thin", - "scrollbarColor": "var(--gray-a8) transparent", + "maxHeight": "var(--available-height)", + "transformOrigin": "var(--transform-origin)", + "--rx-popup-from": { + "[data-side='bottom']": "translateY(-4px) scale(0.97)", + "[data-side='top']": "translateY(4px) scale(0.97)", + "[data-side='left']": "translateX(4px) scale(0.97)", + "[data-side='right']": "translateX(-4px) scale(0.97)", }, - { - "flexGrow": "1", - "flexShrink": "1", - "flexBasis": "0%", - "minWidth": "0", - "minHeight": "0", - "display": "flex", - "flexDirection": "column", - "overflowX": "auto", - "overflowY": "auto", - "padding": "var(--base-menu-content-padding)", - "boxSizing": "border-box", + "display": {"default": "none", ":popover-open": "flex"}, + } + highlight = ( + "color", + "backgroundColor", + "--rx-menu-shortcut-color", + "--rx-menu-chevron-color", + ) + assert {key: item.get(key) for key in highlight} == { + "color": { + "[aria-disabled='true']": "var(--gray-a8)", + "[data-highlighted]": "var(--accent-contrast)", }, - { - "display": "flex", - "alignItems": "center", - "rowGap": "var(--space-2)", - "columnGap": "var(--space-2)", - "height": "var(--base-menu-item-height)", - "paddingLeft": "var(--base-menu-item-padding-left)", - "paddingRight": "var(--base-menu-item-padding-right)", - "boxSizing": "border-box", - "position": "relative", - "outlineStyle": "none", - "outlineWidth": "medium", - "outlineColor": "currentColor", - "scrollMarginTop": "var(--base-menu-content-padding)", - "scrollMarginBottom": "var(--base-menu-content-padding)", - "userSelect": "none", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, - "fontSize": "var(--rx-menu-font-size)", - "lineHeight": "var(--rx-menu-line-height)", - "letterSpacing": "var(--rx-menu-letter-spacing)", - "borderRadius": "var(--rx-menu-item-radius)", - "color": { - "[aria-disabled='true']": "var(--gray-a8)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-shortcut-color": { - "default": "var(--gray-a11)", - ":focus": "currentColor", - "[aria-disabled='true']": "currentColor", - "[data-state='open']": "currentColor", - }, - "--rx-menu-chevron-color": { - "default": "var(--gray-12)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-check": { - "default": "none", - "[aria-checked='true']": "inline-flex", - }, - "backgroundColor": { - ":focus": "var(--accent-9)", - ":not(:focus)[data-state='open']": "var(--gray-a3)", - }, + "backgroundColor": { + "[data-highlighted]": "var(--accent-9)", + ":not([data-highlighted])[data-open]": "var(--gray-a3)", }, - ] - - -class MenuState(rx.State): - """What a menu is bound to.""" - - shown: bool = False - - @rx.event - def set_shown(self, shown: bool): - """Follow the menu. - - Args: - shown: Whether it is open. - """ - self.shown = shown - - @rx.event - def escaped(self): - """Hear Escape.""" + "--rx-menu-shortcut-color": { + "default": "var(--gray-a11)", + "[data-highlighted]": "currentColor", + "[aria-disabled='true']": "currentColor", + "[data-open]": "currentColor", + }, + "--rx-menu-chevron-color": { + "default": "var(--gray-12)", + "[data-highlighted]": "var(--accent-contrast)", + }, + } def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): - """A menu bound to state hands its script its state, and what it does when it opens, closes or is dismissed; a choice is a press on the item.""" - name = MenuState.get_full_name() + """A menu bound to state takes whether it is open from it, and calls the events of Radix by the reason of a change.""" menu = rx.ui.dropdown_menu component = menu.root( - menu.trigger(rx.el.button("Options")), menu.content( - menu.item("Edit", on_select=MenuState.escaped), - on_escape_key_down=MenuState.escaped, + menu.item("Edit", on_select=MenuState.set_shown(False)), + on_escape_key_down=rx.console_log("esc"), ), open=MenuState.shown, on_open_change=MenuState.set_shown, ) - _, content = component.render()["children"] - on = ( - f'({{ open: ((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' - '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))), escape: ' - f'((...args) => (addEvents([(ReflexEvent("{name}.escaped", ({{ }}), ' - "({ })))], args, ({ })))) })" + handler = ( + '"reflex___state____state.tests___units___reflex_components_ui___' + 'components___test_dropdown_menu____menu_state.set_shown"' + ) + assert _tree(component.render()) == ( + "Menu", + [ + ( + "onOpenChange:((value, details) => { const change = ((_ev_0) => " + f'(addEvents([(ReflexEvent({handler}, ({{ ["shown"] : _ev_0 }}), ' + "({ })))], [_ev_0], ({ })))), closeAutoFocus = undefined, " + 'escape = ((...args) => (addEvents([(ReflexEvent("_call_function", ' + '({ ["function"] : (() => (console?.["log"]("esc"))), ' + '["callback"] : null }), ({ })))], args, ({ })))), ' + "outside = undefined, focusOutside = undefined, interact = undefined; " + 'if (details?.reason === "escape-key") escape?.(); ' + 'if (details?.reason === "outside-press") { outside?.(); interact?.(); } ' + 'if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); } ' + "change?.(value); if (!value) closeAutoFocus?.(); })" + ), + ( + "open:reflex___state____state__tests___units___reflex_components_ui___" + "components___test_dropdown_menu____menu_state.shown_rx_state_" + ), + ], + [ + ( + "MenuContent", + [ + 'align:"start"', + "className:sx_34247d117f_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:4", + ], + [ + _scrolled(( + "MenuItem", + [ + "className:sx_b9894c01e4_c", + ( + "onSelect:((...args) => (addEvents([(ReflexEvent(" + f'{handler}, ({{ ["shown"] : false }}), ({{ }})))], ' + "args, ({ }))))" + ), + ], + ['"Edit"'], + )) + ], + ) + ], ) - assert content["props"] == [ - "className:sx_2c641f6169_c", - '"data-rx-popup":""', - 'id:"rx-dropdown-menu-1"', - f"onBeforeToggle:((event) => {{ (((event) => menuEvent(event, {on})))(event); (popupBeforeToggle)(event); }})", - f"onBlur:((event) => menuEvent(event, {on}))", - f"onClick:((event) => menuEvent(event, {on}))", - f"onKeyDown:((event) => menuEvent(event, {on}))", - f"onPointerLeave:((event) => menuEvent(event, {on}))", - f"onPointerMove:((event) => menuEvent(event, {on}))", - f"onToggle:((event) => menuEvent(event, {on}))", - 'popover:"auto"', - f"ref:((popup) => menuSync(popup, {MenuState.shown!s}))", - 'role:"menu"', - "tabIndex:-1", - ] - item = content["children"][0]["children"][0]["children"][0] - assert item["props"] == [ - "className:sx_85bc40da55_c", - ( - f'onClick:((...args) => (addEvents([(ReflexEvent("{name}.escaped", ' - "({ }), ({ })))], args, ({ }))))" - ), - 'role:"menuitem"', - "tabIndex:-1", - ] -def test_dropdown_menu_imports_its_script(ui_plugin: UIPlugin): - """A page with a menu loads the script of the menus, and what puts a popup on whole pixels.""" +def test_dropdown_menu_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a menu imports its parts from UI SDK, pinned, and no script.""" menu = rx.ui.dropdown_menu component = menu.root( menu.trigger(rx.el.button("Options")), menu.content(menu.item("Edit")) ) imports = component._get_all_imports() assert { - module: names for module, names in imports.items() if "behaviors" in module + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module } == { - "$/reflex-ui/behaviors/menu.js": [ - ImportVar(tag="menuTrigger"), - ImportVar(tag="menuSync"), - ImportVar(tag="menuEvent"), + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + MENU: [ + ImportVar(tag="Menu"), + ImportVar(tag="MenuTrigger"), + ImportVar(tag="MenuContent"), + ImportVar(tag="MenuItem"), ], - "$/reflex-ui/behaviors/popup.js": [ImportVar(tag="popupBeforeToggle")], } @@ -490,6 +336,6 @@ def test_dropdown_menu_trigger_needs_an_element(ui_plugin: UIPlugin): with pytest.raises(StyleError) as error: rx.ui.dropdown_menu.trigger("Options") assert str(error.value) == ( - "rx.ui.dropdown_menu.trigger: it is rendered as its child, so it needs exactly " - "one child that is an element, such as a button." + "rx.ui.dropdown_menu.trigger: it is rendered as its child, so it needs " + "exactly one child that is an element, such as a button." ) diff --git a/tests/units/reflex_components_ui/components/test_form.py b/tests/units/reflex_components_ui/components/test_form.py index 7f9855d6c15..a4e0b23a1e9 100644 --- a/tests/units/reflex_components_ui/components/test_form.py +++ b/tests/units/reflex_components_ui/components/test_form.py @@ -452,7 +452,7 @@ def test_form_without_messages( {"name": '"span"', "props": [], "children": [{"contents": '"x"'}]}, { "name": '"button"', - "props": ["className:sx_f2580dfc68_c", 'type:"submit"'], + "props": ["className:sx_16addd9092_c", 'type:"submit"'], "children": [{"contents": '"Send"'}], }, ], diff --git a/tests/units/reflex_components_ui/components/test_icon_button.py b/tests/units/reflex_components_ui/components/test_icon_button.py index 6bb33f617a1..6994c034016 100644 --- a/tests/units/reflex_components_ui/components/test_icon_button.py +++ b/tests/units/reflex_components_ui/components/test_icon_button.py @@ -19,7 +19,7 @@ def test_icon_button_from_a_name( component = compiled(rx.ui.icon_button("plus")) assert component.render() == { "name": '"button"', - "props": ["className:sx_afda1d7c43_c"], + "props": ["className:sx_36db4f79fd_c"], "children": [{"name": "LucidePlus", "props": [], "children": []}], } assert declared_styles(component) == [ @@ -43,8 +43,8 @@ def test_icon_button_from_a_name( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, - "[data-state='open']": "var(--accent-10)", - ":active:not([data-state='open'])": "var(--accent-10)", + ":is([data-state='open'], [data-open])": "var(--accent-10)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, "backgroundImage": "none", @@ -67,7 +67,7 @@ def test_icon_button_from_a_name( "outlineStyle": { "default": "none", "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "solid" }, ":focus-visible:not([data-disabled])": "solid", }, @@ -90,26 +90,26 @@ def test_icon_button_from_a_name( "[data-disabled]": "var(--gray-a8)", }, "filter": { - ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + ":active:not(:is([data-state='open'], [data-open]))": "var(--rx-if-light, brightness(0.92) " "saturate(1.1)) var(--rx-if-dark, " "brightness(1.08))", "[data-disabled]": "none", }, "outlineWidth": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" }, ":focus-visible:not([data-disabled])": "2px", }, "outlineColor": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "var(--accent-a4)" }, ":focus-visible:not([data-disabled])": "var(--focus-8)", }, "outlineOffset": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0" }, ":focus-visible:not([data-disabled])": "2px", }, @@ -128,7 +128,7 @@ def test_icon_button_size_sizes_the_icon( component = compiled(rx.ui.icon_button(rx.icon("trash"), size="3", variant="soft")) assert component.render() == { "name": '"button"', - "props": ["className:sx_46971f9a00_c"], + "props": ["className:sx_f252cc983a_c"], "children": [{"name": "LucideTrash", "props": ["size:36"], "children": []}], } assert declared_styles(component) == [ @@ -152,8 +152,8 @@ def test_icon_button_size_sizes_the_icon( "backgroundColor": { "default": "var(--accent-a3)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a4)"}, - "[data-state='open']": "var(--accent-a4)", - ":active:not([data-state='open'])": "var(--accent-a5)", + ":is([data-state='open'], [data-open])": "var(--accent-a4)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-a5)", "[data-disabled]": "var(--gray-a3)", }, "backgroundImage": "none", @@ -229,8 +229,8 @@ def test_icon_button_ghost( "backgroundColor": { "default": "transparent", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-a3)"}, - "[data-state='open']": "var(--accent-a3)", - ":active:not([data-state='open'])": "var(--accent-a4)", + ":is([data-state='open'], [data-open])": "var(--accent-a3)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-a4)", "[data-disabled]": "transparent", }, "backgroundImage": "none", diff --git a/tests/units/reflex_components_ui/components/test_popup.py b/tests/units/reflex_components_ui/components/test_popup.py index 22c02f76ba8..95bbc3b6f34 100644 --- a/tests/units/reflex_components_ui/components/test_popup.py +++ b/tests/units/reflex_components_ui/components/test_popup.py @@ -10,26 +10,30 @@ @pytest.mark.parametrize( - "root", + ("root", "name"), [ - rx.ui.popover.root, - rx.ui.dropdown_menu.root, - rx.ui.dropdown_menu.sub, - rx.ui.context_menu.root, - rx.ui.hover_card.root, + (rx.ui.popover.root, "Fragment"), + (rx.ui.dropdown_menu.root, "Menu"), + (rx.ui.dropdown_menu.sub, "MenuSub"), + (rx.ui.context_menu.root, "Fragment"), + (rx.ui.hover_card.root, "Fragment"), ], ) def test_a_popup_in_a_list_keeps_its_key( - root: Callable[..., Component], ui_plugin: UIPlugin + root: Callable[..., Component], name: str, ui_plugin: UIPlugin ): - """The fragment of a popup carries its key: ``rx.foreach`` keys each item by it. + """The root of a popup carries its key: ``rx.foreach`` keys each item by it. + + A root of UI SDK is a component that renders no element; the others + render a fragment. Args: root: The root of a popup. + name: What the root renders as. ui_plugin: The configured plugin. """ component = root(rx.el.span("a"), key="a") assert (component.render()["name"], component.render()["props"]) == ( - "Fragment", + name, ['key:"a"'], ) diff --git a/tests/units/reflex_components_ui/components/test_skeleton.py b/tests/units/reflex_components_ui/components/test_skeleton.py index e2e15cedfa9..f429e67b894 100644 --- a/tests/units/reflex_components_ui/components/test_skeleton.py +++ b/tests/units/reflex_components_ui/components/test_skeleton.py @@ -152,7 +152,7 @@ def test_skeleton_as_its_child( "name": '"button"', "props": [ '"aria-hidden":true', - 'className:(sx_f2580dfc68_c) + " " + sx_596747f37d_c', + 'className:(sx_16addd9092_c) + " " + sx_596747f37d_c', '"data-rx-skeleton":""', 'id:"save"', "inert:true", @@ -218,8 +218,8 @@ def test_skeleton_as_its_child( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, - "[data-state='open']": "var(--accent-10)", - ":active:not([data-state='open'])": "var(--accent-10)", + ":is([data-state='open'], [data-open])": "var(--accent-10)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, "backgroundImage": "none", @@ -242,7 +242,7 @@ def test_skeleton_as_its_child( "outlineStyle": { "default": "none", "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "solid" }, ":focus-visible:not([data-disabled])": "solid", }, @@ -267,26 +267,26 @@ def test_skeleton_as_its_child( "[data-disabled]": "var(--gray-a8)", }, "filter": { - ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + ":active:not(:is([data-state='open'], [data-open]))": "var(--rx-if-light, brightness(0.92) " "saturate(1.1)) var(--rx-if-dark, " "brightness(1.08))", "[data-disabled]": "none", }, "outlineWidth": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" }, ":focus-visible:not([data-disabled])": "2px", }, "outlineColor": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "var(--accent-a4)" }, ":focus-visible:not([data-disabled])": "var(--focus-8)", }, "outlineOffset": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0" }, ":focus-visible:not([data-disabled])": "2px", }, @@ -308,7 +308,7 @@ def test_skeleton_not_loading( "children": [ { "name": '"button"', - "props": ["className:sx_f2580dfc68_c"], + "props": ["className:sx_16addd9092_c"], "children": [{"contents": '"Save"'}], } ], @@ -334,8 +334,8 @@ def test_skeleton_not_loading( "backgroundColor": { "default": "var(--accent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--accent-10)"}, - "[data-state='open']": "var(--accent-10)", - ":active:not([data-state='open'])": "var(--accent-10)", + ":is([data-state='open'], [data-open])": "var(--accent-10)", + ":active:not(:is([data-state='open'], [data-open]))": "var(--accent-10)", "[data-disabled]": "var(--gray-a3)", }, "backgroundImage": "none", @@ -358,7 +358,7 @@ def test_skeleton_not_loading( "outlineStyle": { "default": "none", "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "solid" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "solid" }, ":focus-visible:not([data-disabled])": "solid", }, @@ -383,26 +383,26 @@ def test_skeleton_not_loading( "[data-disabled]": "var(--gray-a8)", }, "filter": { - ":active:not([data-state='open'])": "var(--rx-if-light, brightness(0.92) " + ":active:not(:is([data-state='open'], [data-open]))": "var(--rx-if-light, brightness(0.92) " "saturate(1.1)) var(--rx-if-dark, " "brightness(1.08))", "[data-disabled]": "none", }, "outlineWidth": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0.5em" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" }, ":focus-visible:not([data-disabled])": "2px", }, "outlineColor": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "var(--accent-a4)" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "var(--accent-a4)" }, ":focus-visible:not([data-disabled])": "var(--focus-8)", }, "outlineOffset": { "@media (pointer: coarse)": { - ":active:not([data-state='open'], [data-disabled], :focus-visible)": "0" + ":active:not(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0" }, ":focus-visible:not([data-disabled])": "2px", }, diff --git a/tests/units/reflex_components_ui/components/test_tabs.py b/tests/units/reflex_components_ui/components/test_tabs.py index 5bdbdd2e5d1..c59d9739d3f 100644 --- a/tests/units/reflex_components_ui/components/test_tabs.py +++ b/tests/units/reflex_components_ui/components/test_tabs.py @@ -1,30 +1,22 @@ """Tests for reflex_components_ui.components.tabs.""" -import itertools from collections.abc import Callable -from typing import Any, Literal +from typing import Any import pytest from reflex_base.utils.imports import ImportVar -from reflex_components_ui.components import tabs as tabs_module from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import StyleError import reflex as rx - -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the tabs of each test from one.""" - monkeypatch.setattr(tabs_module, "_ids", itertools.count(1)) +TABS = "@ui-sdk/react@0.1.0-beta.17/tabs" class TabsState(rx.State): """What tabs are bound to.""" tab: str = "two" - names: list[str] = ["one", "two"] - upright: Literal["horizontal", "vertical"] = "vertical" @rx.event def set_tab(self, tab: str): @@ -36,10 +28,44 @@ def set_tab(self, tab: str): self.tab = tab +def _trigger(text: str, class_name: str, *props: str) -> dict[str, Any]: + """The render of a trigger: a tab of UI SDK around its text twice. + + Args: + text: The text of the trigger. + class_name: The expression of its class names. + *props: Its other props, in order. + + Returns: + The render. + """ + return { + "name": "TabsTab", + "props": [f"className:{class_name}", *props], + "children": [ + { + "name": '"span"', + "props": ["className:sx_dc646325ab_c"], + "children": [{"contents": f'"{text}"'}], + }, + { + "name": '"span"', + "props": ["className:sx_09d7e7be39_c"], + "children": [{"contents": f'"{text}"'}], + }, + ], + } + + def test_tabs( ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] ): - """The root gives each trigger and panel its id, its state and its orientation; a trigger is a button around its text twice.""" + """The parts are those of UI SDK, under its names for the props of Radix. + + The orientation reaches the parts as a variant of their look, and the + root as a prop. Whether the arrow keys go round moves from the list to + the root, and a panel kept mounted is ``keepMounted``. + """ component = rx.ui.tabs.root( rx.ui.tabs.list( rx.ui.tabs.trigger("One", value="one", color_scheme="ruby"), @@ -48,7 +74,7 @@ def test_tabs( loop=False, ), rx.ui.tabs.content("First", value="one", margin="1px"), - rx.ui.tabs.content("Second", value="two", id="panel"), + rx.ui.tabs.content("Second", value="two", id="panel", force_mount=True), default_value="one", orientation="vertical", dir="rtl", @@ -56,889 +82,116 @@ def test_tabs( id="tabs", ) assert component.render() == { - "name": '"div"', + "name": "Tabs", "props": [ + 'activation:"manual"', "className:sx_293eff2a48_c", - '"data-activation":"manual"', - '"data-rx-tabs":""', + 'defaultValue:"one"', 'dir:"rtl"', 'id:"tabs"', - "onBlur:tabsEvent", - "onClick:tabsEvent", - "onFocus:tabsEvent", + "loop:false", + 'orientation:"vertical"', "ref:ref_tabs", ], "children": [ { - "name": '"div"', - "props": [ - '"aria-orientation":"vertical"', - "className:sx_52bb344f95_c", - '"data-loop":false', - "onKeyDown:rovingKeyDown", - 'role:"tablist"', - ], + "name": "TabsList", + "props": ['"aria-orientation":"vertical"', "className:sx_52bb344f95_c"], "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-tabs-1-content-one"', - '"aria-selected":true', - 'className:sx_92e2216116_c + " " + reflexUIClasses_e201574881', - '"data-state":"active"', - '"data-value":"one"', - 'id:"rx-tabs-1-trigger-one"', - 'role:"tab"', - "tabIndex:0", - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_dc646325ab_c"], - "children": [{"contents": '"One"'}], - }, - { - "name": '"span"', - "props": ["className:sx_09d7e7be39_c"], - "children": [{"contents": '"One"'}], - }, - ], - }, - { - "name": '"button"', - "props": [ - '"aria-controls":"panel"', - '"aria-selected":false', - "className:sx_92e2216116_c", - '"data-state":"inactive"', - '"data-value":"two"', - "disabled:true", - 'id:"second"', - "ref:ref_second", - 'role:"tab"', - "tabIndex:-1", - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_dc646325ab_c"], - "children": [{"contents": '"Two"'}], - }, - { - "name": '"span"', - "props": ["className:sx_09d7e7be39_c"], - "children": [{"contents": '"Two"'}], - }, - ], - }, + _trigger( + "One", + 'sx_0aec0aad8f_c + " " + reflexUIClasses_e201574881', + 'value:"one"', + ), + _trigger( + "Two", + "sx_0aec0aad8f_c", + "disabled:true", + 'id:"second"', + "ref:ref_second", + 'value:"two"', + ), ], }, { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-tabs-1-trigger-one"', - "className:sx_f078fdbeec_c", - '"data-rx-tabs-content":""', - '"data-state":"active"', - '"data-value":"one"', - "hidden:false", - 'id:"rx-tabs-1-content-one"', - 'role:"tabpanel"', - "tabIndex:0", - ], + "name": "TabsPanel", + "props": ["className:sx_f078fdbeec_c", 'value:"one"'], "children": [{"contents": '"First"'}], }, { - "name": '"div"', + "name": "TabsPanel", "props": [ - '"aria-labelledby":"second"', "className:sx_dd03223cd1_c", - '"data-rx-tabs-content":""', - '"data-state":"inactive"', - '"data-value":"two"', - "hidden:true", 'id:"panel"', + "keepMounted:true", "ref:ref_panel", - 'role:"tabpanel"', - "tabIndex:0", + 'value:"two"', ], "children": [{"contents": '"Second"'}], }, ], } - assert declared_styles(component) == [ - {"display": "flex"}, - { - "display": {"default": "block", "::-webkit-scrollbar": "none"}, - "justifyContent": "flex-start", - "overflowX": "auto", - "whiteSpace": "nowrap", - "fontFamily": "var(--default-font-family)", - "fontStyle": "normal", - "scrollbarWidth": "none", - "boxShadow": "inset -1px 0 0 0 var(--gray-a5)", - "fontSize": "var(--font-size-1)", - "lineHeight": "var(--line-height-1)", - "letterSpacing": "var(--letter-spacing-1)", - "--tab-height": "var(--space-6)", - "--tab-padding-x": "var(--space-1)", - "--tab-inner-padding-x": "var(--space-1)", - "--tab-inner-padding-y": "calc(var(--space-1) * 0.5)", - "--tab-inner-border-radius": "var(--radius-1)", - }, - { - "appearance": "none", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingBottom": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": { - "default": "transparent", - "::before": {"[aria-selected='true']": "var(--accent-indicator)"}, - }, - "backgroundImage": "none", - "fontFamily": "inherit", - "fontSize": "inherit", - "lineHeight": "inherit", - "letterSpacing": "inherit", - "wordSpacing": "inherit", - "textTransform": "inherit", - "textAlign": "inherit", - "textIndent": "initial", - "fontWeight": "normal", - "fontStyle": "normal", - "cursor": { - "default": "var(--cursor-button)", - ":disabled": "var(--cursor-disabled)", - }, - "outlineStyle": "none", - "outlineWidth": "medium", - "outlineColor": "currentcolor", - "outlineOffset": "0", - "WebkitTapHighlightColor": "transparent", - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "flexShrink": 0, - "position": { - "default": "relative", - "::before": {"[aria-selected='true']": "absolute"}, - }, - "userSelect": "none", - "boxSizing": { - "default": "border-box", - "::before": {"[aria-selected='true']": "border-box"}, - }, - "height": { - "default": "var(--tab-height)", - "::before": {"[aria-selected='true']": "2px"}, - }, - "paddingLeft": "var(--tab-padding-x)", - "paddingRight": "var(--tab-padding-x)", - "color": { - "default": "var(--gray-a11)", - "@media (hover: hover)": {":hover": "var(--gray-12)"}, - "[aria-selected='true']": "var(--gray-12)", - }, - "--rx-tab-font-weight": { - "[aria-selected='true']": "var(--font-weight-medium)" - }, - "--rx-tab-letter-spacing": { - "default": "var(--tab-inactive-letter-spacing)", - "[aria-selected='true']": "var(--tab-active-letter-spacing)", - }, - "--rx-tab-word-spacing": { - "default": "var(--tab-inactive-word-spacing)", - "[aria-selected='true']": "var(--tab-active-word-spacing)", - }, - "--rx-tab-fill": { - "@media (hover: hover)": { - ":hover:not(:focus-visible)": "var(--gray-a3)", - ":hover:focus-visible": "var(--accent-a3)", - } - }, - "--rx-tab-ring": {":focus-visible": "solid"}, - "--rx-tab-ring-width": {":focus-visible": "2px"}, - "--rx-tab-ring-color": {":focus-visible": "var(--focus-8)"}, - "--rx-tab-ring-offset": {":focus-visible": "-2px"}, - "content": {"::before": {"[aria-selected='true']": "''"}}, - "bottom": {"::before": {"[aria-selected='true']": "0"}}, - "left": {"::before": {"[aria-selected='true']": "0"}}, - "right": {"::before": {"[aria-selected='true']": "0"}}, - "width": "100%", - }, - { - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "boxSizing": "border-box", - "padding": "var(--tab-inner-padding-y) var(--tab-inner-padding-x)", - "borderRadius": "var(--tab-inner-border-radius)", - "position": "absolute", - "fontWeight": "var(--rx-tab-font-weight, inherit)", - "letterSpacing": "var(--rx-tab-letter-spacing)", - "wordSpacing": "var(--rx-tab-word-spacing)", - "backgroundColor": "var(--rx-tab-fill, transparent)", - "outlineStyle": "var(--rx-tab-ring, none)", - "outlineWidth": "var(--rx-tab-ring-width, medium)", - "outlineColor": "var(--rx-tab-ring-color, currentcolor)", - "outlineOffset": "var(--rx-tab-ring-offset, 0)", - }, - { - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "boxSizing": "border-box", - "padding": "var(--tab-inner-padding-y) var(--tab-inner-padding-x)", - "borderRadius": "var(--tab-inner-border-radius)", - "visibility": "hidden", - "fontWeight": "var(--font-weight-medium)", - "letterSpacing": "var(--tab-active-letter-spacing)", - "wordSpacing": "var(--tab-active-word-spacing)", - }, - { - "appearance": "none", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingBottom": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": { - "default": "transparent", - "::before": {"[aria-selected='true']": "var(--accent-indicator)"}, - }, - "backgroundImage": "none", - "fontFamily": "inherit", - "fontSize": "inherit", - "lineHeight": "inherit", - "letterSpacing": "inherit", - "wordSpacing": "inherit", - "textTransform": "inherit", - "textAlign": "inherit", - "textIndent": "initial", - "fontWeight": "normal", - "fontStyle": "normal", - "cursor": { - "default": "var(--cursor-button)", - ":disabled": "var(--cursor-disabled)", - }, - "outlineStyle": "none", - "outlineWidth": "medium", - "outlineColor": "currentcolor", - "outlineOffset": "0", - "WebkitTapHighlightColor": "transparent", - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "flexShrink": 0, - "position": { - "default": "relative", - "::before": {"[aria-selected='true']": "absolute"}, - }, - "userSelect": "none", - "boxSizing": { - "default": "border-box", - "::before": {"[aria-selected='true']": "border-box"}, - }, - "height": { - "default": "var(--tab-height)", - "::before": {"[aria-selected='true']": "2px"}, - }, - "paddingLeft": "var(--tab-padding-x)", - "paddingRight": "var(--tab-padding-x)", - "color": { - "default": "var(--gray-a11)", - "@media (hover: hover)": {":hover": "var(--gray-12)"}, - "[aria-selected='true']": "var(--gray-12)", - }, - "--rx-tab-font-weight": { - "[aria-selected='true']": "var(--font-weight-medium)" - }, - "--rx-tab-letter-spacing": { - "default": "var(--tab-inactive-letter-spacing)", - "[aria-selected='true']": "var(--tab-active-letter-spacing)", - }, - "--rx-tab-word-spacing": { - "default": "var(--tab-inactive-word-spacing)", - "[aria-selected='true']": "var(--tab-active-word-spacing)", - }, - "--rx-tab-fill": { - "@media (hover: hover)": { - ":hover:not(:focus-visible)": "var(--gray-a3)", - ":hover:focus-visible": "var(--accent-a3)", - } - }, - "--rx-tab-ring": {":focus-visible": "solid"}, - "--rx-tab-ring-width": {":focus-visible": "2px"}, - "--rx-tab-ring-color": {":focus-visible": "var(--focus-8)"}, - "--rx-tab-ring-offset": {":focus-visible": "-2px"}, - "content": {"::before": {"[aria-selected='true']": "''"}}, - "bottom": {"::before": {"[aria-selected='true']": "0"}}, - "left": {"::before": {"[aria-selected='true']": "0"}}, - "right": {"::before": {"[aria-selected='true']": "0"}}, - "width": "100%", - }, - { - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "boxSizing": "border-box", - "padding": "var(--tab-inner-padding-y) var(--tab-inner-padding-x)", - "borderRadius": "var(--tab-inner-border-radius)", - "position": "absolute", - "fontWeight": "var(--rx-tab-font-weight, inherit)", - "letterSpacing": "var(--rx-tab-letter-spacing)", - "wordSpacing": "var(--rx-tab-word-spacing)", - "backgroundColor": "var(--rx-tab-fill, transparent)", - "outlineStyle": "var(--rx-tab-ring, none)", - "outlineWidth": "var(--rx-tab-ring-width, medium)", - "outlineColor": "var(--rx-tab-ring-color, currentcolor)", - "outlineOffset": "var(--rx-tab-ring-offset, 0)", - }, - { - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "boxSizing": "border-box", - "padding": "var(--tab-inner-padding-y) var(--tab-inner-padding-x)", - "borderRadius": "var(--tab-inner-border-radius)", - "visibility": "hidden", - "fontWeight": "var(--font-weight-medium)", - "letterSpacing": "var(--tab-active-letter-spacing)", - "wordSpacing": "var(--tab-active-word-spacing)", - }, - { - "position": "relative", - "outlineStyle": {"default": "none", ":focus-visible": "solid"}, - "outlineWidth": {"default": "0", ":focus-visible": "2px"}, - "outlineColor": {":focus-visible": "var(--focus-8)"}, - "width": "100%", - "marginTop": "1px", - "marginRight": "1px", - "marginBottom": "1px", - "marginLeft": "1px", - }, - { - "position": "relative", - "outlineStyle": {"default": "none", ":focus-visible": "solid"}, - "outlineWidth": {"default": "0", ":focus-visible": "2px"}, - "outlineColor": {":focus-visible": "var(--focus-8)"}, - "width": "100%", - }, - ] - - -def test_tabs_without_a_value(ui_plugin: UIPlugin): - """Tab stops on the first trigger that is not disabled, and tabs inside a panel are their own.""" - component = rx.ui.tabs.root( - rx.ui.tabs.list( - rx.ui.tabs.trigger("Off", value="off", disabled=True), - rx.ui.tabs.trigger("On", value="on"), - ), - rx.ui.tabs.content( - rx.ui.tabs( - rx.ui.tabs.list(rx.ui.tabs.trigger("In", value="in")), - rx.ui.tabs.content("Inner", value="in"), - default_value="in", - ), - value="on", - ), + styles = declared_styles(component) + assert (styles[0]["display"], styles[1]["display"], styles[2]["width"]) == ( + "flex", + {"default": "block", "::-webkit-scrollbar": "none"}, + "100%", ) - assert component.render() == { - "name": '"div"', - "props": [ - '"data-rx-tabs":""', - "onBlur:tabsEvent", - "onClick:tabsEvent", - "onFocus:tabsEvent", - ], - "children": [ - { - "name": '"div"', - "props": [ - '"aria-orientation":"horizontal"', - "className:sx_4f6024971d_c", - "onKeyDown:rovingKeyDown", - 'role:"tablist"', - ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-tabs-2-content-off"', - '"aria-selected":false', - "className:sx_585a0027e5_c", - '"data-state":"inactive"', - '"data-value":"off"', - "disabled:true", - 'id:"rx-tabs-2-trigger-off"', - 'role:"tab"', - "tabIndex:-1", - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_dc646325ab_c"], - "children": [{"contents": '"Off"'}], - }, - { - "name": '"span"', - "props": ["className:sx_09d7e7be39_c"], - "children": [{"contents": '"Off"'}], - }, - ], - }, - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-tabs-2-content-on"', - '"aria-selected":false', - "className:sx_585a0027e5_c", - '"data-state":"inactive"', - '"data-value":"on"', - 'id:"rx-tabs-2-trigger-on"', - 'role:"tab"', - "tabIndex:0", - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_dc646325ab_c"], - "children": [{"contents": '"On"'}], - }, - { - "name": '"span"', - "props": ["className:sx_09d7e7be39_c"], - "children": [{"contents": '"On"'}], - }, - ], - }, - ], - }, - { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-tabs-2-trigger-on"', - "className:sx_b59d991c6f_c", - '"data-rx-tabs-content":""', - '"data-state":"inactive"', - '"data-value":"on"', - "hidden:true", - 'id:"rx-tabs-2-content-on"', - 'role:"tabpanel"', - "tabIndex:0", - ], - "children": [ - { - "name": '"div"', - "props": [ - '"data-rx-tabs":""', - "onBlur:tabsEvent", - "onClick:tabsEvent", - "onFocus:tabsEvent", - ], - "children": [ - { - "name": '"div"', - "props": [ - '"aria-orientation":"horizontal"', - "className:sx_4f6024971d_c", - "onKeyDown:rovingKeyDown", - 'role:"tablist"', - ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-tabs-1-content-in"', - '"aria-selected":true', - "className:sx_585a0027e5_c", - '"data-state":"active"', - '"data-value":"in"', - 'id:"rx-tabs-1-trigger-in"', - 'role:"tab"', - "tabIndex:0", - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_dc646325ab_c"], - "children": [{"contents": '"In"'}], - }, - { - "name": '"span"', - "props": ["className:sx_09d7e7be39_c"], - "children": [{"contents": '"In"'}], - }, - ], - } - ], - }, - { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-tabs-1-trigger-in"', - "className:sx_b59d991c6f_c", - '"data-rx-tabs-content":""', - '"data-state":"active"', - '"data-value":"in"', - "hidden:false", - 'id:"rx-tabs-1-content-in"', - 'role:"tabpanel"', - "tabIndex:0", - ], - "children": [{"contents": '"Inner"'}], - }, - ], - } - ], - }, - ], - } -def test_tabs_trigger_alone( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A trigger outside tabs is one that is not selected.""" - component = rx.ui.tabs.trigger("Alone", value="alone") - assert component.render() == { - "name": '"button"', - "props": [ - '"aria-selected":false', - "className:sx_585a0027e5_c", - '"data-state":"inactive"', - '"data-value":"alone"', - 'role:"tab"', - "tabIndex:-1", - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_dc646325ab_c"], - "children": [{"contents": '"Alone"'}], - }, - { - "name": '"span"', - "props": ["className:sx_09d7e7be39_c"], - "children": [{"contents": '"Alone"'}], - }, - ], - } - assert declared_styles(component) == [ - { - "appearance": "none", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingBottom": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": { - "default": "transparent", - "::before": {"[aria-selected='true']": "var(--accent-indicator)"}, - }, - "backgroundImage": "none", - "fontFamily": "inherit", - "fontSize": "inherit", - "lineHeight": "inherit", - "letterSpacing": "inherit", - "wordSpacing": "inherit", - "textTransform": "inherit", - "textAlign": "inherit", - "textIndent": "initial", - "fontWeight": "normal", - "fontStyle": "normal", - "cursor": { - "default": "var(--cursor-button)", - ":disabled": "var(--cursor-disabled)", - }, - "outlineStyle": "none", - "outlineWidth": "medium", - "outlineColor": "currentcolor", - "outlineOffset": "0", - "WebkitTapHighlightColor": "transparent", - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "flexShrink": 0, - "position": { - "default": "relative", - "::before": {"[aria-selected='true']": "absolute"}, - }, - "userSelect": "none", - "boxSizing": { - "default": "border-box", - "::before": {"[aria-selected='true']": "border-box"}, - }, - "height": { - "default": "var(--tab-height)", - "::before": {"[aria-selected='true']": "2px"}, - }, - "paddingLeft": "var(--tab-padding-x)", - "paddingRight": "var(--tab-padding-x)", - "color": { - "default": "var(--gray-a11)", - "@media (hover: hover)": {":hover": "var(--gray-12)"}, - "[aria-selected='true']": "var(--gray-12)", - }, - "--rx-tab-font-weight": { - "[aria-selected='true']": "var(--font-weight-medium)" - }, - "--rx-tab-letter-spacing": { - "default": "var(--tab-inactive-letter-spacing)", - "[aria-selected='true']": "var(--tab-active-letter-spacing)", - }, - "--rx-tab-word-spacing": { - "default": "var(--tab-inactive-word-spacing)", - "[aria-selected='true']": "var(--tab-active-word-spacing)", - }, - "--rx-tab-fill": { - "@media (hover: hover)": { - ":hover:not(:focus-visible)": "var(--gray-a3)", - ":hover:focus-visible": "var(--accent-a3)", - } - }, - "--rx-tab-ring": {":focus-visible": "solid"}, - "--rx-tab-ring-width": {":focus-visible": "2px"}, - "--rx-tab-ring-color": {":focus-visible": "var(--focus-8)"}, - "--rx-tab-ring-offset": {":focus-visible": "-2px"}, - "content": {"::before": {"[aria-selected='true']": "''"}}, - "bottom": {"::before": {"[aria-selected='true']": "0"}}, - "left": {"::before": {"[aria-selected='true']": "0"}}, - "right": {"::before": {"[aria-selected='true']": "0"}}, - }, - { - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "boxSizing": "border-box", - "padding": "var(--tab-inner-padding-y) var(--tab-inner-padding-x)", - "borderRadius": "var(--tab-inner-border-radius)", - "position": "absolute", - "fontWeight": "var(--rx-tab-font-weight, inherit)", - "letterSpacing": "var(--rx-tab-letter-spacing)", - "wordSpacing": "var(--rx-tab-word-spacing)", - "backgroundColor": "var(--rx-tab-fill, transparent)", - "outlineStyle": "var(--rx-tab-ring, none)", - "outlineWidth": "var(--rx-tab-ring-width, medium)", - "outlineColor": "var(--rx-tab-ring-color, currentcolor)", - "outlineOffset": "var(--rx-tab-ring-offset, 0)", - }, - { - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "boxSizing": "border-box", - "padding": "var(--tab-inner-padding-y) var(--tab-inner-padding-x)", - "borderRadius": "var(--tab-inner-border-radius)", - "visibility": "hidden", - "fontWeight": "var(--font-weight-medium)", - "letterSpacing": "var(--tab-active-letter-spacing)", - "wordSpacing": "var(--tab-active-word-spacing)", - }, - ] +def test_tabs_list_says_its_orientation(ui_plugin: UIPlugin): + """The list says it is horizontal, as Radix does: UI SDK says only a vertical one. - -def test_tabs_content_alone( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A panel outside tabs is one that is not shown.""" - component = rx.ui.tabs.content("Alone", value="alone") - assert component.render() == { - "name": '"div"', - "props": [ - "className:sx_b59d991c6f_c", - '"data-rx-tabs-content":""', - '"data-state":"inactive"', - '"data-value":"alone"', - "hidden:true", - 'role:"tabpanel"', - "tabIndex:0", - ], - "children": [{"contents": '"Alone"'}], - } - assert declared_styles(component) == [ - { - "position": "relative", - "outlineStyle": {"default": "none", ":focus-visible": "solid"}, - "outlineWidth": {"default": "0", ":focus-visible": "2px"}, - "outlineColor": {":focus-visible": "var(--focus-8)"}, - } - ] - - -def test_tabs_list_alone( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A list outside tabs is horizontal.""" - component = rx.ui.tabs.list() - assert component.render() == { - "name": '"div"', - "props": [ - '"aria-orientation":"horizontal"', - "className:sx_4f6024971d_c", - "onKeyDown:rovingKeyDown", - 'role:"tablist"', - ], - "children": [], - } - assert declared_styles(component) == [ - { - "display": {"default": "flex", "::-webkit-scrollbar": "none"}, - "justifyContent": "flex-start", - "overflowX": "auto", - "whiteSpace": "nowrap", - "fontFamily": "var(--default-font-family)", - "fontStyle": "normal", - "scrollbarWidth": "none", - "boxShadow": "inset 0 -1px 0 0 var(--gray-a5)", - "fontSize": "var(--font-size-2)", - "lineHeight": "var(--line-height-2)", - "letterSpacing": "var(--letter-spacing-2)", - "--tab-height": "var(--space-7)", - "--tab-padding-x": "var(--space-2)", - "--tab-inner-padding-x": "var(--space-2)", - "--tab-inner-padding-y": "var(--space-1)", - "--tab-inner-border-radius": "var(--radius-2)", - } - ] + Horizontal tabs have no look of their own, and no class name. + """ + component = rx.ui.tabs.root(rx.ui.tabs.list(), rx.ui.tabs.content("x", value="a")) + rendered = component.render() + assert (rendered["props"], rendered["children"][0]["props"]) == ( + [], + ['"aria-orientation":"horizontal"', "className:sx_4f6024971d_c"], + ) def test_tabs_bound_to_state(ui_plugin: UIPlugin): - """Tabs bound to state render their state as expressions, hand the script what they do on a change, and keep a handler of their own for a press.""" - selected, upright = str(TabsState.tab), str(TabsState.upright) - on_change = ( - f'((_ev_0) => (addEvents([(ReflexEvent("{TabsState.get_full_name()}.set_tab", ' - '({ ["tab"] : _ev_0 }), ({ })))], [_ev_0], ({ }))))' - ) + """Tabs bound to state take its value, and hand a change to their handler.""" component = rx.ui.tabs.root( - rx.ui.tabs.list( - rx.foreach( - TabsState.names, lambda name: rx.ui.tabs.trigger(name, value=name) - ) - ), - rx.foreach(TabsState.names, lambda name: rx.ui.tabs.content(name, value=name)), + rx.ui.tabs.list(rx.ui.tabs.trigger("One", value="one")), value=TabsState.tab, on_change=TabsState.set_tab, - orientation=TabsState.upright, - on_click=rx.console_log("pressed"), ) - rendered = component.render() - assert rendered["props"] == [ - f'className:(sx_8b94b45675_0[{upright}] ?? "")', - '"data-rx-tabs":"bound"', - f"onBlur:((event) => tabsEvent(event, {on_change}))", + assert component.render()["props"] == [ ( - f"onClick:((event) => {{ (((event) => tabsEvent(event, {on_change})))(event); " - '(((_e) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : ' - '(() => (console?.["log"]("pressed"))), ["callback"] : null }), ({ })))], ' - "[_e], ({ })))))(event); })" + "onValueChange:((_ev_0) => (addEvents([(ReflexEvent(" + '"reflex___state____state.tests___units___reflex_components_ui___' + 'components___test_tabs____tabs_state.set_tab", ({ ["tab"] : _ev_0 }), ' + "({ })))], [_ev_0], ({ }))))" + ), + ( + "value:reflex___state____state__tests___units___reflex_components_ui___" + "components___test_tabs____tabs_state.tab_rx_state_" ), - f"onFocus:((event) => tabsEvent(event, {on_change}))", - ] - tab_list, panels = rendered["children"] - assert tab_list["props"] == [ - f'"aria-orientation":{upright}', - f'className:sx_e6dbf978a8_c + " " + (sx_e6dbf978a8_0[{upright}] ?? sx_e6dbf978a8_0d)', - "onKeyDown:rovingKeyDown", - 'role:"tablist"', - ] - index = tab_list["children"][0]["index_var_name"] - assert tab_list["children"][0]["children"] == [ - { - "name": '"button"', - "props": [ - '"aria-controls":("rx-tabs-1-content-" + name_rx_state_)', - f'"aria-selected":({selected} === name_rx_state_)', - f'className:sx_bbc606ee2b_c + " " + (sx_bbc606ee2b_0[{upright}] ?? "")', - f'"data-state":(({selected} === name_rx_state_) ? "active" : "inactive")', - '"data-value":name_rx_state_', - 'id:("rx-tabs-1-trigger-" + name_rx_state_)', - f"key:{index}", - 'role:"tab"', - f"tabIndex:(({selected} === name_rx_state_) ? 0 : -1)", - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_dc646325ab_c"], - "children": [{"contents": "name_rx_state_"}], - }, - { - "name": '"span"', - "props": ["className:sx_09d7e7be39_c"], - "children": [{"contents": "name_rx_state_"}], - }, - ], - } - ] - assert panels["children"] == [ - { - "name": '"div"', - "props": [ - '"aria-labelledby":("rx-tabs-1-trigger-" + name_rx_state_)', - f'className:sx_c229fddc7e_c + " " + (sx_c229fddc7e_0[{upright}] ?? "")', - '"data-rx-tabs-content":""', - f'"data-state":(({selected} === name_rx_state_) ? "active" : "inactive")', - '"data-value":name_rx_state_', - f"hidden:(({selected} === name_rx_state_) ? false : true)", - 'id:("rx-tabs-1-content-" + name_rx_state_)', - f"key:{panels['index_var_name']}", - 'role:"tabpanel"', - "tabIndex:0", - ], - "children": [{"contents": "name_rx_state_"}], - } ] -def test_tabs_import_their_scripts(ui_plugin: UIPlugin): - """A page with tabs loads the script that selects a tab and the one of the arrow keys, and nothing else of a script.""" +def test_tabs_import_ui_sdk(ui_plugin: UIPlugin): + """A page with tabs imports the parts it renders from UI SDK, pinned, and no script.""" component = rx.ui.tabs.root( rx.ui.tabs.list(rx.ui.tabs.trigger("One", value="one")), rx.ui.tabs.content("First", value="one"), ) imports = component._get_all_imports() assert { - module: names for module, names in imports.items() if "behaviors" in module + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module } == { - "$/reflex-ui/behaviors/tabs.js": [ImportVar(tag="tabsEvent")], - "$/reflex-ui/behaviors/roving-focus.js": [ImportVar(tag="rovingKeyDown")], + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + TABS: [ + ImportVar(tag="Tabs"), + ImportVar(tag="TabsList"), + ImportVar(tag="TabsTab"), + ImportVar(tag="TabsPanel"), + ], } diff --git a/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt index d9623243344..38bc5b8552b 100644 --- a/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt +++ b/tests/units/reflex_components_ui/migrate_fixtures/radix_kept/report.txt @@ -1,6 +1,6 @@ app/app.py:2:20: [kept] button stays imported from reflex for the use that stays on rx, and so do its other uses: name them rx.ui.button to migrate them. app/app.py:3:1: [kept] reflex_components_radix.themes.components.badge is imported from directly: its components are not migrated, and keep RadixThemesPlugin. -app/app.py:8:28: [state] rx.button is built in a state, and kept: rx.ui.button: the style "backgroundColor" has conditions ("default", "@media (hover: hover)", "[data-state='open']", ":active:not([data-state='open'])", "[data-disabled]"), 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. +app/app.py:8:28: [state] rx.button is built in a state, and kept: rx.ui.button: the style "backgroundColor" has conditions ("default", "@media (hover: hover)", ":is([data-state='open'], [data-open])", ":active:not(:is([data-state='open'], [data-open]))", "[data-disabled]"), 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. app/app.py:17:9: [kept] rx.radix.themes.components.badge is a Radix component by its own name: not migrated, and keeps RadixThemesPlugin. app/app.py:19:14: [unresolved] the module rx is passed on as a value: the components reached through it are not migrated. Pass rx.ui, or name them. rxconfig.py:3:45: [config] RadixThemesPlugin stays, for the Radix components that remain: app/app.py:3:1 (from reflex_components_radix.themes.components.badge import ...), app/app.py:8:28 (rx.button), app/app.py:17:9 (rx.radix.themes.components.badge), app/app.py:19:14 (rx). From 70c82a26ce90c7d817e6cea6516bb0d792863923 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 14:17:57 +0000 Subject: [PATCH 192/204] Regenerate the stubs of the dialog and the dropdown menu on UI SDK Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- pyi_hashes.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyi_hashes.json b/pyi_hashes.json index 6776084da01..23dc8d8878a 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -140,9 +140,9 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.pyi": "b914252f1bc53816d7c5384faea6d2b5", "packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.pyi": "79193f172cbb6feb749a296f82af9814", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", - "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "a144d0d2d518369359f11e4245634656", + "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "e3e684a6fd6424c43648acd2fafa39af", "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "cdaeaac954b4ff1100878d46b5649143", - "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "fddd9e7a28b08d125f6577ee99f8839b", + "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "bce2a2c1da692e84ed14f347dce2a69c", "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", "packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.pyi": "866327d09399a8a3f632f93a36014ebb", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", From bb251ffd7616d034520cc78e808ddbbe72f4377e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 14:23:52 +0000 Subject: [PATCH 193/204] Hold the shared rx.ui app to the tabs and the trigger looks on UI SDK An unselected panel of UI SDK's tabs is not in the page, as in Radix, and a button that opens a popup selects UI SDK's data-open beside Radix's data-state: the declarations of the app's memoized components follow. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- .../tests_playwright/test_ui_components.py | 231 +++++++++++------- 1 file changed, 139 insertions(+), 92 deletions(-) diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index bf0e21ede18..6ba9a7af8e1 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -127,8 +127,47 @@ # What the color mode button and switch of the panel page declare in the # module of the components the compile memoizes. PANEL_MEMO_DECLARATIONS = [ - 'const sx_27b6901346 = stylex.create({ s: {"marginTop": "0", "marginRight": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "6px", "paddingRight": "6px", "paddingBottom": "6px", "paddingLeft": "6px", "borderTopWidth": "0", "borderRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderRightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "none", "backgroundColor": "transparent", "backgroundImage": "none", "appearance": "none", "boxSizing": "border-box", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", "fontWeight": "normal", "textTransform": "inherit", "textIndent": "initial", "textShadow": "inherit", "wordSpacing": "inherit", "cursor": {"default": "inherit", ":where(button)": "var(--cursor-button)", ":any-link": "var(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)", ":hover": "pointer"}, "outlineStyle": {"default": "none", "@media (pointer: coarse)": {":active:not([data-state=\'open\'], [data-disabled], :focus-visible)": "solid"}, ":focus-visible:not([data-disabled])": "solid"}, "WebkitTapHighlightColor": "transparent", "display": "inline-flex", "alignItems": "center", "justifyContent": "center", "flexShrink": 0, "userSelect": "none", "verticalAlign": "top", "fontFamily": "var(--default-font-family)", "fontStyle": "normal", "textAlign": "center", "--spinner-opacity": {"[data-disabled]": "1"}, "--base-button-classic-active-padding-top": "2px", "--base-button-height": "var(--space-6)", "borderRadius": "max(var(--radius-2), var(--radius-full))", "color": "inherit", "filter": {":active:not([data-state=\'open\'])": "var(--rx-if-light, brightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08))", "[data-disabled]": "none"}, "outlineWidth": {"@media (pointer: coarse)": {":active:not([data-state=\'open\'], [data-disabled], :focus-visible)": "0.5em"}, ":focus-visible:not([data-disabled])": "2px"}, "outlineColor": {"@media (pointer: coarse)": {":active:not([data-state=\'open\'], [data-disabled], :focus-visible)": "var(--accent-a4)"}, ":focus-visible:not([data-disabled])": "var(--focus-8)"}, "outlineOffset": {"@media (pointer: coarse)": {":active:not([data-state=\'open\'], [data-disabled], :focus-visible)": "0"}, ":focus-visible:not([data-disabled])": "2px"}, "height": "var(--base-button-height)", "width": "var(--base-button-height)", "position": "fixed", "bottom": "2rem", "left": "2rem", "zIndex": "20"} });', - "const sx_27b6901346_c = stylex.props(sx_27b6901346.s).className;", + ( + 'const sx_ae10f35bc3 = stylex.create({ s: {"marginTop": "0", "marginR' + 'ight": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "6' + 'px", "paddingRight": "6px", "paddingBottom": "6px", "paddingLeft": "' + '6px", "borderTopWidth": "0", "borderRightWidth": "0", "borderBottomW' + 'idth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borde' + 'rRightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle"' + ': "none", "backgroundColor": "transparent", "backgroundImage": "none' + '", "appearance": "none", "boxSizing": "border-box", "fontSize": "inh' + 'erit", "lineHeight": "inherit", "letterSpacing": "inherit", "fontWei' + 'ght": "normal", "textTransform": "inherit", "textIndent": "initial",' + ' "textShadow": "inherit", "wordSpacing": "inherit", "cursor": {"defa' + 'ult": "inherit", ":where(button)": "var(--cursor-button)", ":any-lin' + 'k": "var(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)' + '", ":hover": "pointer"}, "outlineStyle": {"default": "none", "@media' + " (pointer: coarse)\": {\":active:not(:is([data-state='open'], [data-op" + 'en]), [data-disabled], :focus-visible)": "solid"}, ":focus-visible:n' + 'ot([data-disabled])": "solid"}, "WebkitTapHighlightColor": "transpar' + 'ent", "display": "inline-flex", "alignItems": "center", "justifyCont' + 'ent": "center", "flexShrink": 0, "userSelect": "none", "verticalAlig' + 'n": "top", "fontFamily": "var(--default-font-family)", "fontStyle": ' + '"normal", "textAlign": "center", "--spinner-opacity": {"[data-disabl' + 'ed]": "1"}, "--base-button-classic-active-padding-top": "2px", "--ba' + 'se-button-height": "var(--space-6)", "borderRadius": "max(var(--radi' + 'us-2), var(--radius-full))", "color": "inherit", "filter": {":active' + ":not(:is([data-state='open'], [data-open]))\": \"var(--rx-if-light, br" + 'ightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08))", ' + '"[data-disabled]": "none"}, "outlineWidth": {"@media (pointer: coars' + "e)\": {\":active:not(:is([data-state='open'], [data-open]), [data-disa" + 'bled], :focus-visible)": "0.5em"}, ":focus-visible:not([data-disable' + 'd])": "2px"}, "outlineColor": {"@media (pointer: coarse)": {":active' + ":not(:is([data-state='open'], [data-open]), [data-disabled], :focus-" + 'visible)": "var(--accent-a4)"}, ":focus-visible:not([data-disabled])' + '": "var(--focus-8)"}, "outlineOffset": {"@media (pointer: coarse)": ' + "{\":active:not(:is([data-state='open'], [data-open]), [data-disabled]" + ', :focus-visible)": "0"}, ":focus-visible:not([data-disabled])": "2p' + 'x"}, "height": "var(--base-button-height)", "width": "var(--base-but' + 'ton-height)", "position": "fixed", "bottom": "2rem", "left": "2rem",' + ' "zIndex": "20"} });' + ), + "const sx_ae10f35bc3_c = stylex.props(sx_ae10f35bc3.s).className;", 'const sx_fd86994bd3 = stylex.create({ s: {"appearance": "none", "marginTop": "0", "marginRight": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0", "paddingRight": "0", "paddingBottom": "0", "paddingLeft": "0", "borderTopWidth": "0", "borderRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderRightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "none", "backgroundColor": {"default": "transparent", "::before": {"default": "var(--gray-a3)", ":active:not(:disabled)": "var(--gray-a4)"}, "::after": {"default": "white", ":disabled": "var(--gray-2)"}}, "backgroundImage": {"default": "none", "::before": {"default": "linear-gradient(to right, var(--accent-track) 40%, transparent 60%)", ":disabled": "none"}}, "boxSizing": "border-box", "color": "inherit", "fontSize": "inherit", "lineHeight": "inherit", "letterSpacing": "inherit", "fontWeight": "normal", "fontStyle": "normal", "textIndent": "initial", "outlineStyle": {"default": "none", "::before": {":focus-visible": "solid"}}, "outlineWidth": {"default": "medium", "::before": {":focus-visible": "2px"}}, "outlineColor": {"default": "currentcolor", "::before": {":focus-visible": "var(--focus-8)"}}, "outlineOffset": {"default": "0", "::before": {":focus-visible": "2px"}}, "WebkitTapHighlightColor": "transparent", "position": {"default": "relative", "::after": "absolute"}, "display": {"default": "inline-flex", "::before": "block"}, "alignItems": "center", "verticalAlign": "top", "flexShrink": 0, "height": {"default": "var(--line-height, var(--switch-height))", "::before": "var(--switch-height)", "::after": "var(--switch-thumb-size)"}, "--switch-width": "calc(var(--switch-height) * 1.75)", "--switch-thumb-inset": "1px", "--switch-thumb-size": "calc(var(--switch-height) - var(--switch-thumb-inset) * 2)", "--switch-thumb-translate-x": "calc(var(--switch-width) - var(--switch-height))", "cursor": {":disabled": "var(--cursor-disabled)", "::before": {"default": "var(--cursor-switch)", ":disabled": "var(--cursor-disabled)"}}, "mixBlendMode": {":disabled": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)"}, "content": {"::before": "\'\'", "::after": "\'\'"}, "width": {"::before": "var(--switch-width)", "::after": "var(--switch-thumb-size)"}, "borderRadius": {"::before": "var(--switch-border-radius)", "::after": "calc(var(--switch-border-radius) - var(--switch-thumb-inset))"}, "transitionProperty": {"::before": "background-position, background-color, box-shadow, filter", "::after": {"default": "transform, box-shadow", ":disabled": "none"}}, "transitionTimingFunction": {"::before": "linear, ease-in-out, ease-in-out, ease-in-out", "::after": "cubic-bezier(0.45, 0.05, 0.55, 0.95), ease-in-out"}, "transitionDuration": {"::before": {"default": "120ms, 140ms, 140ms, 140ms", ":checked": "160ms, 140ms, 140ms, 140ms", ":active": "30ms"}, "::after": "140ms"}, "backgroundRepeat": {"::before": "no-repeat"}, "backgroundSize": {"::before": "calc(var(--switch-width) * 2 + var(--switch-height)) 100%"}, "backgroundPositionX": {"::before": {"default": "100%", ":checked": "0%"}}, "backgroundPositionY": {"::before": "50%"}, "left": {"::after": "var(--switch-thumb-inset)"}, "transform": {"::after": {":checked": "translateX(var(--switch-thumb-translate-x))"}}, "--switch-height": "calc(var(--space-5) * 5 / 6)", "--switch-border-radius": "max(var(--radius-2), var(--radius-thumb))", "boxShadow": {"::before": {"default": "inset 0 0 0 1px var(--gray-a5)", ":disabled": "inset 0 0 0 1px var(--gray-a3)"}, "::after": {"default": "0 0 1px 1px var(--black-a2), 0 1px 1px var(--black-a1), 0 2px 4px -1px var(--black-a1)", ":checked:not(:disabled)": "0 1px 3px var(--black-a2), 0 2px 4px -1px var(--black-a1), 0 0 0 1px var(--black-a1), 0 0 0 1px var(--accent-a4), -1px 0 1px var(--black-a2)", ":disabled": "0 0 0 1px var(--gray-a2), 0 1px 3px var(--black-a1)"}}, "filter": {"::before": {"default": "none", ":checked:active:not(:disabled)": "var(--rx-if-light, brightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08))"}}} });', "const sx_fd86994bd3_c = stylex.props(sx_fd86994bd3.s).className;", ] @@ -164,97 +203,105 @@ # each value, and the other is a plain solid button. ACTIONS_MEMO_DECLARATIONS = [ ( - 'const sx_e93db4cb5c = stylex.create({ s: {"marginTop": "0", "marginRight' - '": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0", "padd' - 'ingRight": "var(--space-3)", "paddingBottom": "0", "paddingLeft": "var(-' - '-space-3)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBotto' - 'mWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderR' - 'ightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "non' - 'e", "backgroundColor": {"default": "var(--accent-9)", "@media (hover: ho' - 'ver)": {":hover:not(:active)": "var(--accent-10)"}, "[data-state=\'open\']' - '": "var(--accent-10)", ":active:not([data-state=\'open\'])": "var(--accent' - '-10)", "[data-disabled]": "var(--gray-a3)"}' - ', "backgroundImage": "none", "appearance": "none", "boxSizing": "border-' - 'box", "fontSize": "var(--font-size-2)", "lineHeight": "var(--line-height' - '-2)", "letterSpacing": "var(--letter-spacing-2)", "fontWeight": "var(--f' - 'ont-weight-medium)", "textTransform": "inherit", "textIndent": "initial"' - ', "textShadow": "inherit", "wordSpacing": "inherit", "cursor": {"default' - '": "inherit", ":where(button)": "var(--cursor-button)", ":any-link": "va' - 'r(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)"}, "outlin' - 'eStyle": {"default": "none", "@media (pointer: coarse)": {":active:not([' - 'data-state=\'open\'], [data-disabled], :focus-visible)": "solid"}, ":focus' - '-visible:not([data-disabled])": "solid"}, "WebkitTapHighlightColor": "tr' - 'ansparent", "display": "inline-flex", "alignItems": "center", "justifyCo' - 'ntent": "center", "flexShrink": 0, "userSelect": "none", "verticalAlign"' - ': "top", "fontFamily": "var(--default-font-family)", "fontStyle": "norma' - 'l", "textAlign": "center", "--spinner-opacity": {"[data-disabled]": "1"}' - ', "--base-button-classic-active-padding-top": "2px", "--base-button-heig' - 'ht": "var(--space-6)", "borderRadius": "max(var(--radius-2), var(--radiu' - 's-full))", "rowGap": "var(--space-2)", "columnGap": "var(--space-2)", "c' - 'olor": {"default": "var(--accent-contrast)", "[data-disabled]": "var(--g' - 'ray-a8)"}, "filter": {":active:not([data-state=\'open\'])": "var(--rx-if-l' - "ight, brightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08)" - ')", "[data-disabled]": "none"}, "outlineWidth": {"@media (pointer: coars' - "e)\": {\":active:not([data-state='open'], [data-disabled], :focus-visible)" - '": "0.5em"}, ":focus-visible:not([data-disabled])": "2px"}, "outlineColo' - 'r": {"@media (pointer: coarse)": {":active:not([data-state=\'open\'], [dat' - 'a-disabled], :focus-visible)": "var(--accent-a4)"}, ":focus-visible:not(' - '[data-disabled])": "var(--focus-8)"}, "outlineOffset": {"@media (pointer' - ": coarse)\": {\":active:not([data-state='open'], [data-disabled], :focus-v" - 'isible)": "0"}, ":focus-visible:not([data-disabled])": "2px"}, "--rx-acc' - 'ent-text": "var(--accent-12)", "--rx-accent-link": "var(--accent-12)", "' - '--rx-accent-link-line": "underline", "--rx-accent-link-line-color": "col' - 'or-mix(in oklab, var(--accent-a6), var(--gray-a6))", "height": "var(--ba' - 'se-button-height)", "--rx-icon-opacity": "0.9"}, a0_0: {"position": "rel' - 'ative"} });' + 'const sx_046b512a21 = stylex.create({ s: {"marginTop": "0", "marginR' + 'ight": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0' + '", "paddingRight": "var(--space-3)", "paddingBottom": "0", "paddingL' + 'eft": "var(--space-3)", "borderTopWidth": "0", "borderRightWidth": "' + '0", "borderBottomWidth": "0", "borderLeftWidth": "0", "borderTopStyl' + 'e": "none", "borderRightStyle": "none", "borderBottomStyle": "none",' + ' "borderLeftStyle": "none", "backgroundColor": {"default": "var(--ac' + 'cent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--ac' + 'cent-10)"}, ":is([data-state=\'open\'], [data-open])": "var(--accent-1' + '0)", ":active:not(:is([data-state=\'open\'], [data-open]))": "var(--ac' + 'cent-10)", "[data-disabled]": "var(--gray-a3)"}, "backgroundImage": ' + '"none", "appearance": "none", "boxSizing": "border-box", "fontSize":' + ' "var(--font-size-2)", "lineHeight": "var(--line-height-2)", "letter' + 'Spacing": "var(--letter-spacing-2)", "fontWeight": "var(--font-weigh' + 't-medium)", "textTransform": "inherit", "textIndent": "initial", "te' + 'xtShadow": "inherit", "wordSpacing": "inherit", "cursor": {"default"' + ': "inherit", ":where(button)": "var(--cursor-button)", ":any-link": ' + '"var(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)"}, ' + '"outlineStyle": {"default": "none", "@media (pointer: coarse)": {":a' + "ctive:not(:is([data-state='open'], [data-open]), [data-disabled], :f" + 'ocus-visible)": "solid"}, ":focus-visible:not([data-disabled])": "so' + 'lid"}, "WebkitTapHighlightColor": "transparent", "display": "inline-' + 'flex", "alignItems": "center", "justifyContent": "center", "flexShri' + 'nk": 0, "userSelect": "none", "verticalAlign": "top", "fontFamily": ' + '"var(--default-font-family)", "fontStyle": "normal", "textAlign": "c' + 'enter", "--spinner-opacity": {"[data-disabled]": "1"}, "--base-butto' + 'n-classic-active-padding-top": "2px", "--base-button-height": "var(-' + '-space-6)", "borderRadius": "max(var(--radius-2), var(--radius-full)' + ')", "rowGap": "var(--space-2)", "columnGap": "var(--space-2)", "colo' + 'r": {"default": "var(--accent-contrast)", "[data-disabled]": "var(--' + 'gray-a8)"}, "filter": {":active:not(:is([data-state=\'open\'], [data-o' + 'pen]))": "var(--rx-if-light, brightness(0.92) saturate(1.1)) var(--r' + 'x-if-dark, brightness(1.08))", "[data-disabled]": "none"}, "outlineW' + 'idth": {"@media (pointer: coarse)": {":active:not(:is([data-state=\'o' + 'pen\'], [data-open]), [data-disabled], :focus-visible)": "0.5em"}, ":' + 'focus-visible:not([data-disabled])": "2px"}, "outlineColor": {"@medi' + "a (pointer: coarse)\": {\":active:not(:is([data-state='open'], [data-o" + 'pen]), [data-disabled], :focus-visible)": "var(--accent-a4)"}, ":foc' + 'us-visible:not([data-disabled])": "var(--focus-8)"}, "outlineOffset"' + ': {"@media (pointer: coarse)": {":active:not(:is([data-state=\'open\']' + ', [data-open]), [data-disabled], :focus-visible)": "0"}, ":focus-vis' + 'ible:not([data-disabled])": "2px"}, "--rx-accent-text": "var(--accen' + 't-12)", "--rx-accent-link": "var(--accent-12)", "--rx-accent-link-li' + 'ne": "underline", "--rx-accent-link-line-color": "color-mix(in oklab' + ', var(--accent-a6), var(--gray-a6))", "height": "var(--base-button-h' + 'eight)", "--rx-icon-opacity": "0.9"}, a0_0: {"position": "relative"}' + " });" ), - ("const sx_e93db4cb5c_c = stylex.props(sx_e93db4cb5c.s).className;"), + "const sx_046b512a21_c = stylex.props(sx_046b512a21.s).className;", ( - 'const sx_e93db4cb5c_0 = { __proto__: null, "true": stylex.props(sx_e93db' - "4cb5c.a0_0).className };" + 'const sx_046b512a21_0 = { __proto__: null, "true": stylex.props(sx_0' + "46b512a21.a0_0).className };" ), ( - 'const sx_f2580dfc68 = stylex.create({ s: {"marginTop": "0", "marginRight' - '": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0", "padd' - 'ingRight": "var(--space-3)", "paddingBottom": "0", "paddingLeft": "var(-' - '-space-3)", "borderTopWidth": "0", "borderRightWidth": "0", "borderBotto' - 'mWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none", "borderR' - 'ightStyle": "none", "borderBottomStyle": "none", "borderLeftStyle": "non' - 'e", "backgroundColor": {"default": "var(--accent-9)", "@media (hover: ho' - 'ver)": {":hover:not(:active)": "var(--accent-10)"}, "[data-state=\'open\']' - '": "var(--accent-10)", ":active:not([data-state=\'open\'])": "var(--accent' - '-10)", "[data-disabled]": "var(--gray-a3)"}' - ', "backgroundImage": "none", "appearance": "none", "boxSizing": "border-' - 'box", "fontSize": "var(--font-size-2)", "lineHeight": "var(--line-height' - '-2)", "letterSpacing": "var(--letter-spacing-2)", "fontWeight": "var(--f' - 'ont-weight-medium)", "textTransform": "inherit", "textIndent": "initial"' - ', "textShadow": "inherit", "wordSpacing": "inherit", "cursor": {"default' - '": "inherit", ":where(button)": "var(--cursor-button)", ":any-link": "va' - 'r(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)"}, "outlin' - 'eStyle": {"default": "none", "@media (pointer: coarse)": {":active:not([' - 'data-state=\'open\'], [data-disabled], :focus-visible)": "solid"}, ":focus' - '-visible:not([data-disabled])": "solid"}, "WebkitTapHighlightColor": "tr' - 'ansparent", "display": "inline-flex", "alignItems": "center", "justifyCo' - 'ntent": "center", "flexShrink": 0, "userSelect": "none", "verticalAlign"' - ': "top", "fontFamily": "var(--default-font-family)", "fontStyle": "norma' - 'l", "textAlign": "center", "--spinner-opacity": {"[data-disabled]": "1"}' - ', "--base-button-classic-active-padding-top": "2px", "--base-button-heig' - 'ht": "var(--space-6)", "borderRadius": "max(var(--radius-2), var(--radiu' - 's-full))", "rowGap": "var(--space-2)", "columnGap": "var(--space-2)", "c' - 'olor": {"default": "var(--accent-contrast)", "[data-disabled]": "var(--g' - 'ray-a8)"}, "filter": {":active:not([data-state=\'open\'])": "var(--rx-if-l' - "ight, brightness(0.92) saturate(1.1)) var(--rx-if-dark, brightness(1.08)" - ')", "[data-disabled]": "none"}, "outlineWidth": {"@media (pointer: coars' - "e)\": {\":active:not([data-state='open'], [data-disabled], :focus-visible)" - '": "0.5em"}, ":focus-visible:not([data-disabled])": "2px"}, "outlineColo' - 'r": {"@media (pointer: coarse)": {":active:not([data-state=\'open\'], [dat' - 'a-disabled], :focus-visible)": "var(--accent-a4)"}, ":focus-visible:not(' - '[data-disabled])": "var(--focus-8)"}, "outlineOffset": {"@media (pointer' - ": coarse)\": {\":active:not([data-state='open'], [data-disabled], :focus-v" - 'isible)": "0"}, ":focus-visible:not([data-disabled])": "2px"}, "height":' - ' "var(--base-button-height)", "--rx-icon-opacity": "0.9"} });' + 'const sx_16addd9092 = stylex.create({ s: {"marginTop": "0", "marginR' + 'ight": "0", "marginBottom": "0", "marginLeft": "0", "paddingTop": "0' + '", "paddingRight": "var(--space-3)", "paddingBottom": "0", "paddingL' + 'eft": "var(--space-3)", "borderTopWidth": "0", "borderRightWidth": "' + '0", "borderBottomWidth": "0", "borderLeftWidth": "0", "borderTopStyl' + 'e": "none", "borderRightStyle": "none", "borderBottomStyle": "none",' + ' "borderLeftStyle": "none", "backgroundColor": {"default": "var(--ac' + 'cent-9)", "@media (hover: hover)": {":hover:not(:active)": "var(--ac' + 'cent-10)"}, ":is([data-state=\'open\'], [data-open])": "var(--accent-1' + '0)", ":active:not(:is([data-state=\'open\'], [data-open]))": "var(--ac' + 'cent-10)", "[data-disabled]": "var(--gray-a3)"}, "backgroundImage": ' + '"none", "appearance": "none", "boxSizing": "border-box", "fontSize":' + ' "var(--font-size-2)", "lineHeight": "var(--line-height-2)", "letter' + 'Spacing": "var(--letter-spacing-2)", "fontWeight": "var(--font-weigh' + 't-medium)", "textTransform": "inherit", "textIndent": "initial", "te' + 'xtShadow": "inherit", "wordSpacing": "inherit", "cursor": {"default"' + ': "inherit", ":where(button)": "var(--cursor-button)", ":any-link": ' + '"var(--cursor-link)", "[data-disabled]": "var(--cursor-disabled)"}, ' + '"outlineStyle": {"default": "none", "@media (pointer: coarse)": {":a' + "ctive:not(:is([data-state='open'], [data-open]), [data-disabled], :f" + 'ocus-visible)": "solid"}, ":focus-visible:not([data-disabled])": "so' + 'lid"}, "WebkitTapHighlightColor": "transparent", "display": "inline-' + 'flex", "alignItems": "center", "justifyContent": "center", "flexShri' + 'nk": 0, "userSelect": "none", "verticalAlign": "top", "fontFamily": ' + '"var(--default-font-family)", "fontStyle": "normal", "textAlign": "c' + 'enter", "--spinner-opacity": {"[data-disabled]": "1"}, "--base-butto' + 'n-classic-active-padding-top": "2px", "--base-button-height": "var(-' + '-space-6)", "borderRadius": "max(var(--radius-2), var(--radius-full)' + ')", "rowGap": "var(--space-2)", "columnGap": "var(--space-2)", "colo' + 'r": {"default": "var(--accent-contrast)", "[data-disabled]": "var(--' + 'gray-a8)"}, "filter": {":active:not(:is([data-state=\'open\'], [data-o' + 'pen]))": "var(--rx-if-light, brightness(0.92) saturate(1.1)) var(--r' + 'x-if-dark, brightness(1.08))", "[data-disabled]": "none"}, "outlineW' + 'idth": {"@media (pointer: coarse)": {":active:not(:is([data-state=\'o' + 'pen\'], [data-open]), [data-disabled], :focus-visible)": "0.5em"}, ":' + 'focus-visible:not([data-disabled])": "2px"}, "outlineColor": {"@medi' + "a (pointer: coarse)\": {\":active:not(:is([data-state='open'], [data-o" + 'pen]), [data-disabled], :focus-visible)": "var(--accent-a4)"}, ":foc' + 'us-visible:not([data-disabled])": "var(--focus-8)"}, "outlineOffset"' + ': {"@media (pointer: coarse)": {":active:not(:is([data-state=\'open\']' + ', [data-open]), [data-disabled], :focus-visible)": "0"}, ":focus-vis' + 'ible:not([data-disabled])": "2px"}, "height": "var(--base-button-hei' + 'ght)", "--rx-icon-opacity": "0.9"} });' ), - ("const sx_f2580dfc68_c = stylex.props(sx_f2580dfc68.s).className;"), + "const sx_16addd9092_c = stylex.props(sx_16addd9092.s).className;", ( 'const sx_21e3781dc3 = stylex.create({ s: {"boxSizing": "border-box", "fo' 'ntFamily": "var(--default-font-family)", "fontWeight": "var(--font-weigh' @@ -2016,13 +2063,13 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): shown.get_by_role("button", name="Got it").click() expect(page.locator(":popover-open")).to_have_count(0) - # The panel of the selected tab alone is shown, whatever display an app - # gives the panels. + # The panel of the selected tab alone is in the page, with the display an + # app gives it: UI SDK unmounts the others, as Radix does. first, second = page.locator("#first-panel"), page.locator("#second-panel") expect(first).to_have_css("display", "flex") - expect(second).to_have_css("display", "none") + expect(second).to_have_count(0) page.get_by_role("tab", name="Second").click() - expect(first).to_have_css("display", "none") + expect(first).to_have_count(0) expect(second).to_have_css("display", "flex") page.keyboard.press("ArrowLeft") expect(first).to_be_visible() From 47a2f64af2c157aa8fab94b15778862e7d92fa28 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:09:13 +0000 Subject: [PATCH 194/204] rx.ui on UI SDK, wave A: popover, alert_dialog, drawer and select All four render UI SDK's parts in rx.ui's look, so no native popover or dialog is left under the dialog family and the select inside a dialog no longer closes it with Escape. - _sdk: one popup root that calls the Radix events of its content by the reason of a change, Radix defaults where UI SDK's differ (menus and the select stop at their ends), and placed content with Radix Themes' offsets; a trigger's child brings its hooks and is written to JSX only when it renders. - _dialog: the parts dialog, alert_dialog and drawer share. The cancel button of an alert dialog takes the focus; a drawer's edge is UI SDK's side and the end of its slide onOpenChangeComplete, and a drawer that is not modal draws no overlay. - select: UI SDK renders the chosen option and the form input; position="item-aligned" is alignItemWithTrigger. - Allowlist: the approved phase-1 entries, the same categories for the wave, entries for the differences found (Tab leaves an open select, a drawer's close button closes it when not dismissible, the drawer fades under reduced motion), stale entries removed, reasons rewritten for UI SDK. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- docs/styling/rx-ui-migration.md | 87 +- .../parity/allowlist.toml | 277 ++- .../parity/ui_parity/components/dialog.py | 8 +- .../parity/ui_parity/components/drawer.py | 24 +- .../parity/ui_parity/components/popover.py | 13 +- .../parity/ui_parity/components/select.py | 4 +- .../components/_dialog.py | 433 +---- .../reflex_components_ui/components/_sdk.py | 181 +- .../components/alert_dialog.py | 141 +- .../reflex_components_ui/components/dialog.py | 194 +- .../reflex_components_ui/components/drawer.py | 387 ++-- .../components/dropdown_menu.py | 171 +- .../components/popover.py | 76 +- .../reflex_components_ui/components/select.py | 663 ++----- .../src/reflex_components_ui/styles/drawer.py | 100 +- .../src/reflex_components_ui/styles/menu.py | 27 +- .../reflex_components_ui/styles/popover.py | 12 +- .../src/reflex_components_ui/styles/popup.py | 67 +- .../src/reflex_components_ui/styles/select.py | 35 +- pyi_hashes.json | 16 +- .../components/test_alert_dialog.py | 325 +--- .../components/test_dialog.py | 4 +- .../components/test_drawer.py | 467 +---- .../components/test_dropdown_menu.py | 15 +- .../components/test_popover.py | 326 +--- .../components/test_popup.py | 30 +- .../components/test_select.py | 1681 ++--------------- tests/units/reflex_components_ui/render.py | 31 + 28 files changed, 1553 insertions(+), 4242 deletions(-) create mode 100644 tests/units/reflex_components_ui/render.py diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index c1bf99e0168..9fd919a5a5f 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -149,10 +149,14 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### alert_dialog -- behaviour, `rx`, "what it holds is in the server render": rx.alert_dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.alert_dialog holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings. -- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.alert_dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger, the action and the cancel button of rx.ui.alert_dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript. -- behaviour, `rx.ui`, "Tab stays inside an open alert dialog": rx.ui.alert_dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.alert_dialog keeps the focus from leaving the dialog at all. -- style, `pointer-events`: While it is open rx.alert_dialog takes the pointer off the rest of the page with a style on the body. rx.ui.alert_dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style. +- behaviour, `rx`, "what it holds is in the server render": rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "what it holds is in the server render": rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "opens and closes with JavaScript disabled": rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "has the role, the name and the description of an alert dialog": The trigger of rx.ui.alert_dialog says that it opens a dialog (`aria-haspopup`) and names it while it is open (`aria-controls`), but not whether it is open: it has no `aria-expanded`, and says its state in `data-open` and `data-closed` rather than `data-state`. The trigger of rx.alert_dialog has `aria-expanded`. +- style, `pointer-events`: While it is open rx.alert_dialog takes the pointer off the rest of the page with a style on the body. rx.ui.alert_dialog makes the page behind it inert instead, which takes the pointer, the keyboard and assistive technology off it without a style. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`: The panel of rx.ui.alert_dialog is the dialog itself, in the top layer: fixed, centred by its margins in the room the overlay of Radix Themes leaves around it, and no taller than that room, so a tall panel scrolls inside itself. The panel of rx.alert_dialog sits in an overlay that scrolls. The panel is drawn on the same pixels. +- style, `height`: A panel of rx.ui.alert_dialog taller than the room the overlay of Radix Themes leaves around it is no taller than that room, and scrolls what it holds. rx.alert_dialog grows the panel and scrolls the overlay around it. ### avatar @@ -203,30 +207,45 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### dialog -- behaviour, `rx`, "what it holds is in the server render": rx.dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.dialog holds is in the page from the start, in a dialog that is closed, so it is there for a search engine and for the browser's find in page once the dialog is open, and it keeps its state between two openings. -- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript. +- behaviour, `rx`, "what it holds is in the server render": rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "what it holds is in the server render": rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "opens and closes with JavaScript disabled": rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "has the role, the name and the description of a dialog": The trigger of rx.ui.dialog says that it opens a dialog (`aria-haspopup`) and names the dialog while it is open (`aria-controls`), but not whether it is open: it has no `aria-expanded`, and says its state in `data-open` and `data-closed` rather than `data-state`. The trigger of rx.dialog has `aria-expanded`. +- behaviour, `rx.ui`, "the panel has the box of a dialog of the third size": The panel of rx.ui.dialog is the dialog itself, in the top layer: fixed, in the middle of the room the overlay of Radix Themes leaves around it, and no taller than that room, so a tall panel scrolls inside itself. The panel of rx.dialog sits in an overlay that scrolls. The panel is drawn on the same pixels. - behaviour, `rx`, "the dark appearance of a theme around a dialog reaches its panel": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a dialog included. rx.ui.theme does, and a dialog declared inside a dark rx.ui.theme is dark: its panel, what it holds and what is drawn over the page behind it. -- style, `pointer-events`: While it is open rx.dialog takes the pointer off the rest of the page with a style on the body. rx.ui.dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style. +- style, `pointer-events`: While it is open rx.dialog takes the pointer off the rest of the page with a style on the body. rx.ui.dialog makes the page behind it inert instead, which takes the pointer, the keyboard and assistive technology off it without a style. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`: The panel of rx.ui.dialog is the dialog itself, in the top layer: fixed, centred by its margins in the room the overlay of Radix Themes leaves around it, and no taller than that room, so a tall panel scrolls inside itself. The panel of rx.dialog sits in an overlay that scrolls. The panel is drawn on the same pixels. +- style, `height`: A panel of rx.ui.dialog taller than the room the overlay of Radix Themes leaves around it is no taller than that room, and scrolls what it holds. rx.dialog grows the panel and scrolls the overlay around it. ### drawer -- behaviour, `rx`, "what it holds is in the server render": rx.drawer renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.drawer holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings. -- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.drawer is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.drawer are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript. -- behaviour, `rx`, "the focus moves into the drawer, and back to its trigger": rx.drawer leaves the focus on its trigger while the drawer is open, so the keyboard and a screen reader start behind it. rx.ui.drawer is a native modal dialog: the focus moves to the first control inside it, and back to the trigger when it closes. -- behaviour, `rx`, "Tab does not reach the page behind an open drawer": With rx.drawer open, Tab goes on through the page behind it. rx.ui.drawer is a native modal dialog: the page behind it is inert, and Tab moves through the drawer and the browser's own controls. -- behaviour, `rx.ui`, "is dragged out of the page by its panel": rx.ui.drawer is not dragged: it is closed by Escape, by a press beside its panel and by its close button, and `snap_points`, `fade_from_index`, `handle_only`, `close_threshold`, `scroll_lock_timeout`, `prevent_scroll_restoration` and `should_scale_background`, which all describe the drag of rx.drawer, have nothing to say. The handle is drawn and does nothing. -- style, `pointer-events`: While it is open rx.drawer takes the pointer off the rest of the page with a style on the body. rx.ui.drawer is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style. +- behaviour, `rx`, "what it holds is in the server render": rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx`, "the focus moves into the drawer, and back to its trigger": rx.drawer leaves the focus on its trigger while the drawer is open, so the keyboard and a screen reader start behind it. rx.ui.drawer moves the focus to the first control inside it, and back to the trigger when it closes. +- behaviour, `rx`, "Tab does not reach the page behind an open drawer": With rx.drawer open, Tab goes on through the page behind it. rx.ui.drawer makes the page behind it inert while it is open, and Tab moves through the drawer alone. +- behaviour, `rx.ui`, "what it holds is in the server render": rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "opens and closes with JavaScript disabled": rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "has the role, the name and the description of a dialog": The trigger of rx.ui.drawer says that it opens a dialog (`aria-haspopup`) and names it while it is open (`aria-controls`), but not whether it is open: it has no `aria-expanded`, and says its state in `data-open` and `data-closed` rather than `data-state`. The trigger of rx.drawer has `aria-expanded`. +- behaviour, `rx.ui`, "a drawer that is not dismissible is closed by its state alone": A drawer of rx.ui that is not dismissible ignores Escape and a press outside, but its close button still closes it. The close button of rx.drawer does nothing either: only the state the drawer is bound to closes it. +- style, `pointer-events`: While it is open rx.drawer takes the pointer off the rest of the page with a style on the body. rx.ui.drawer makes the page behind it inert instead, which takes the pointer, the keyboard and assistive technology off it without a style. - style, `color`, `border-top-color`, `border-right-color`, `border-bottom-color`, `border-left-color`, `outline-color`: The overlay of rx.drawer declared inside its portal is rendered at the end of the page, outside the theme, and takes the text color of the page there; the one of rx.ui.drawer stays inside the theme. An overlay holds no text, so nothing is drawn in either color. +- style, `position`, `min-width`, `min-height`: The panel of rx.ui.drawer is laid out by UI SDK in a viewport of its own that covers the page, at the edge it comes from, and slid with `translate`. The panel of rx.drawer is itself fixed at that edge. It is drawn on the same pixels. +- style, `opacity`: Where reduced motion is asked for, rx.ui.drawer and what is drawn over the page behind it fade in and out, where they would slide: UI SDK respects the setting. rx.drawer slides whatever the setting. ### dropdown_menu -- behaviour, `rx`, "opens with JavaScript disabled": rx.dropdown_menu is opened by JavaScript: until it has run, a press on its trigger does nothing. The menu of rx.ui.dropdown_menu is a native popover of its trigger, which the browser opens, places and closes, on Escape and on a press outside, with or without JavaScript; moving through its items and choosing one wait for JavaScript. +- behaviour, `rx`, "opens with JavaScript disabled": rx.dropdown_menu and rx.ui.dropdown_menu are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing. - behaviour, `rx`, "the dark appearance of a theme around a menu reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a menu included. rx.ui.theme does, and a menu declared inside a dark rx.ui.theme is dark. -- behaviour, `rx`, "Escape closes only the sub-menu, and a choice in it closes both": Escape in a sub-menu of rx.dropdown_menu closes the whole menu. A sub-menu of rx.ui.dropdown_menu is a popover nested in its menu, and Escape closes only the topmost one, giving the focus back to the item that opened it, as the WAI-ARIA menu pattern describes; a second Escape closes the menu. -- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.dropdown_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. -- style, `pointer-events`: While it is open rx.dropdown_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.dropdown_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.dropdown_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.dropdown_menu hears the press and ignores it. +- behaviour, `rx`, "Escape closes only the sub-menu, and a choice in it closes both": Escape in a sub-menu of rx.dropdown_menu closes the whole menu. Escape in a sub-menu of rx.ui.dropdown_menu closes only that sub-menu, giving the focus back to the item that opened it, as the WAI-ARIA menu pattern describes; a second Escape closes the menu. +- behaviour, `rx.ui`, "the arrows, Home, End and typing move through the items, past a disabled one": A disabled item of rx.ui.dropdown_menu can take the focus, as the ARIA pattern of menus asks: the arrow keys stop on it without choosing it, so a screen reader can say it is there. The arrow keys of rx.dropdown_menu pass a disabled item by. +- behaviour, `rx.ui`, "Tab does not leave an open menu": Tab closes an open rx.ui.dropdown_menu and moves the focus on from its trigger, as from any button. rx.dropdown_menu keeps the focus in the menu until it closes. +- behaviour, `rx.ui`, "opens with JavaScript disabled": rx.dropdown_menu and rx.ui.dropdown_menu are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. The menu of rx.ui.dropdown_menu is placed itself, in the top layer: fixed, where UI SDK puts it beside what opens it, and no taller than the room UI SDK measures. It is drawn on the same pixels. +- style, `pointer-events`: While it is open rx.dropdown_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.dropdown_menu sets no such style: a press outside the menu closes it. And the pointer passes through a disabled item of rx.ui.dropdown_menu, which it does not highlight, where rx.dropdown_menu hears the press and ignores it. - pixels, long-true@open: A menu taller than the room the viewport leaves scrolls. rx.dropdown_menu draws a scrollbar of its own over the items, always shown, and widens the menu by the room it takes. The menu of rx.ui.dropdown_menu scrolls natively: the browser draws the scrollbar, in the colors of Radix, and decides its shape and when it shows. - style, `padding-right`, `width`: rx.dropdown_menu widens a menu that scrolls by the room its own scrollbar takes. The scrollbar of rx.ui.dropdown_menu is the browser's, which takes the room it needs itself. +- pixels in chromium, *side-left*: A menu of rx.ui.dropdown_menu on the left of its trigger is placed by its right edge on a whole pixel, so its text may fall between pixels, and is smoothed differently; rx.dropdown_menu places it by its left edge. The menu is in the same place, on the same pixels. ### hover_card @@ -237,12 +256,16 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### popover -- behaviour, `rx`, "what it holds is in the server render": rx.popover renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.popover holds is in the page from the start, in a popover that is closed, and it keeps its state between two openings. -- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.popover is opened by JavaScript: until it has run, a press on its trigger does nothing. rx.ui.popover is a native popover of its trigger, which the browser opens, places and closes, from its close button, on Escape and on a press outside, with or without JavaScript. -- behaviour, `rx`, "its trigger names the popover it opens by the id it is given": The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link, and it has none while the popover is closed. The trigger of rx.ui.popover names the popover by the id it was given. -- behaviour, `rx.ui`, "Tab stays inside an open popover": rx.ui.popover is a native popover, which is not modal: it comes right after its trigger in the order of the page, Tab moves through what it holds and on to what follows the trigger, and the popover closes when the focus leaves it. rx.popover keeps Tab going round inside it until Escape. `modal` has nothing to say: the page beside a native popover stays as it is. +- behaviour, `rx`, "what it holds is in the server render": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx`, "opens and closes with JavaScript disabled": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx`, "its trigger names the popover it opens by the id it is given": The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link. The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it. +- behaviour, `rx.ui`, "Tab stays inside an open popover": rx.ui.popover is not modal: Tab moves through what it holds and on to the page after its trigger, and the focus leaving it closes it. rx.popover keeps the focus inside until it closes. - behaviour, `rx`, "the dark appearance of a theme around a popover reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a popover included. rx.ui.theme does, and a popover declared inside a dark rx.ui.theme is dark. -- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a popover with a wrapper element it moves by a transform, and the popover inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.popover is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. +- behaviour, `rx.ui`, "what it holds is in the server render": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "opens and closes with JavaScript disabled": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. +- behaviour, `rx.ui`, "is a dialog its trigger says it opens": The trigger of rx.ui.popover says its state in `data-open` and `data-closed`, and the trigger of rx.popover in `data-state`; both say whether the popover is open in `aria-expanded`. +- behaviour, `rx.ui`, "its trigger names the popover it opens by the id it is given": The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it, whatever `id` the content is given. The trigger of rx.popover names it by an id rx.popover makes up. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a popover with a wrapper element it moves by a transform, and the popover inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.popover is placed itself, in the top layer: fixed, where UI SDK puts it beside its trigger, and no taller than the room UI SDK measures. It is drawn on the same pixels. - style, `height`: A popover taller than the page grows past the bottom of the page in rx.popover. rx.ui.popover is no taller than the room the viewport leaves, and scrolls what it holds. ### radio_cards @@ -275,10 +298,11 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### select -- behaviour, `rx`, "shows the chosen option in the server render": The trigger of rx.select is empty until JavaScript has found the text of the chosen option. rx.ui.select works the text out while compiling, where the options are known or show their values, so the page the server sends shows it. -- behaviour, `rx`, "opens and closes its list with JavaScript disabled": rx.select is opened by JavaScript: until it has run, a click on its trigger does nothing. The list of rx.ui.select is a native popover of its trigger, which the browser opens and closes with or without JavaScript; choosing an option waits for it. -- behaviour, `rx.ui`, "the page behind an open list takes no click": While its list is open rx.select takes the pointer off the rest of the page: a click outside closes the list and does nothing else. The list of rx.ui.select is a native popover: a click outside closes it and also reaches what is under the pointer, as with a native select, and the page behind it scrolls. -- style, `pointer-events`: While its list is open rx.select takes the pointer off the rest of the page: nothing else can be clicked or scrolled until the list closes. The list of rx.ui.select is a native popover, which leaves the page as it is: a click outside closes the list, and the page scrolls. +- behaviour, `rx`, "shows the chosen option in the server render": The trigger of rx.select is empty until JavaScript has found the text of the chosen option. UI SDK renders the text of the chosen option of rx.ui.select on the server, so the page the server sends shows it. +- behaviour, `rx`, "opens and closes its list with JavaScript disabled": rx.select and rx.ui.select are opened by JavaScript: until the page has hydrated, a click on the trigger does nothing. +- behaviour, `rx.ui`, "opens and closes its list with JavaScript disabled": rx.select and rx.ui.select are opened by JavaScript: until the page has hydrated, a click on the trigger does nothing. +- behaviour, `rx.ui`, "Tab stays in an open list": Tab closes the open list of rx.ui.select and moves the focus on from its trigger, as from any button. rx.select keeps the focus in the list until it closes. +- style, `pointer-events`: While its list is open rx.select takes the pointer off the rest of the page with a style on the body. rx.ui.select sets no such style: a click outside closes the list. - pixels, long-true*: A list of rx.ui.select too long for the room it has scrolls natively, with the scrollbar of the browser, which may lie over the options and show only while they scroll. rx.select draws a scrollbar of its own with JavaScript, and leaves room for it beside the options. - style, `width`, `height`: When the size of rx.select goes from "3" at one breakpoint to a smaller one at the next, Radix Themes keeps the larger icon size "3" has. The icon of rx.ui.select has the size of the select at each breakpoint, so the trigger is two pixels narrower there. - pixels, size-responsive: When the size of rx.select goes from "3" at one breakpoint to a smaller one at the next, Radix Themes keeps the larger icon size "3" has. The icon of rx.ui.select has the size of the select at each breakpoint, so the trigger is two pixels narrower there. @@ -301,6 +325,17 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### tabs - behaviour, `rx`, "a trigger and a panel given ids of their own name each other": A trigger of rx.tabs names its panel, and the panel its trigger, by an id rx.tabs makes up, so giving either an `id` breaks the link and a screen reader no longer says which tab a panel belongs to. rx.ui.tabs names each by the id it was given. +- behaviour, `rx.ui`, "the arrow keys, Home and End select the tabs that can be, around the ends": A disabled tab of rx.ui can take the focus, as the ARIA pattern of tabs asks: the arrow keys stop on it without selecting it, so a screen reader can say it is there. The arrow keys of rx.tabs pass a disabled tab by. +- behaviour, `rx.ui`, "tabs without a value show no panel until a tab is selected": Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed. +- behaviour, `rx.ui`, "shows the panel it starts with, with JavaScript disabled": Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel, in the page the server sends too. rx.tabs selects none until a tab is pressed. +- pixels, default-value-none: Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed. +- pixels, many-true*: Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed. +- style, `(element)`, `height`: Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed. +- style, `(element)`, `height`, `width`: Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed. +- a11y, default-value-none: Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed. +- a11y, many-true*: Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed. +- pixels, *@focus-visible: A tab of rx.ui is selected when it is pressed, or when the arrow keys move the focus to it: Tab or a script focusing it leaves the selection as it is. A tab of rx.tabs is selected whenever it takes the focus. +- style, `border-top-color`, `border-right-color`, `border-bottom-color`, `border-left-color`, `color`, `outline-color`, `width`, `font-weight`, `letter-spacing`: A tab of rx.ui is selected when it is pressed, or when the arrow keys move the focus to it: Tab or a script focusing it leaves the selection as it is. A tab of rx.tabs is selected whenever it takes the focus. ### text diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 8fa0a9d4485..55d4b414373 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -316,7 +316,7 @@ component = "select" check = "style" cells = "*@open" properties = ["pointer-events"] -reason = "While its list is open rx.select takes the pointer off the rest of the page: nothing else can be clicked or scrolled until the list closes. The list of rx.ui.select is a native popover, which leaves the page as it is: a click outside closes the list, and the page scrolls." +reason = "While its list is open rx.select takes the pointer off the rest of the page with a style on the body. rx.ui.select sets no such style: a click outside closes the list." [[look]] component = "select" @@ -341,19 +341,13 @@ reason = "When the size of rx.select goes from \"3\" at one breakpoint to a smal component = "select" step = "shows the chosen option in the server render" system = "rx" -reason = "The trigger of rx.select is empty until JavaScript has found the text of the chosen option. rx.ui.select works the text out while compiling, where the options are known or show their values, so the page the server sends shows it." +reason = "The trigger of rx.select is empty until JavaScript has found the text of the chosen option. UI SDK renders the text of the chosen option of rx.ui.select on the server, so the page the server sends shows it." [[contract]] component = "select" step = "opens and closes its list with JavaScript disabled" system = "rx" -reason = "rx.select is opened by JavaScript: until it has run, a click on its trigger does nothing. The list of rx.ui.select is a native popover of its trigger, which the browser opens and closes with or without JavaScript; choosing an option waits for it." - -[[contract]] -component = "select" -step = "the page behind an open list takes no click" -system = "rx.ui" -reason = "While its list is open rx.select takes the pointer off the rest of the page: a click outside closes the list and does nothing else. The list of rx.ui.select is a native popover: a click outside closes it and also reaches what is under the pointer, as with a native select, and the page behind it scrolls." +reason = "rx.select and rx.ui.select are opened by JavaScript: until the page has hydrated, a click on the trigger does nothing." [[look]] component = "checkbox" @@ -419,19 +413,46 @@ component = "dialog" check = "style" cells = "*@open" properties = ["pointer-events"] -reason = "While it is open rx.dialog takes the pointer off the rest of the page with a style on the body. rx.ui.dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style." +reason = "While it is open rx.dialog takes the pointer off the rest of the page with a style on the body. rx.ui.dialog makes the page behind it inert instead, which takes the pointer, the keyboard and assistive technology off it without a style." [[contract]] component = "dialog" step = "what it holds is in the server render" system = "rx" -reason = "rx.dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.dialog holds is in the page from the start, in a dialog that is closed, so it is there for a search engine and for the browser's find in page once the dialog is open, and it keeps its state between two openings." +reason = "rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "dialog" +step = "what it holds is in the server render" +reason = "rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger." [[contract]] component = "dialog" step = "opens and closes with JavaScript disabled" system = "rx" -reason = "rx.dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript." +reason = "rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "dialog" +step = "opens and closes with JavaScript disabled" +reason = "rx.dialog and rx.ui.dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what a dialog holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "dialog" +step = "has the role, the name and the description of a dialog" +reason = "The trigger of rx.ui.dialog says that it opens a dialog (`aria-haspopup`) and names the dialog while it is open (`aria-controls`), but not whether it is open: it has no `aria-expanded`, and says its state in `data-open` and `data-closed` rather than `data-state`. The trigger of rx.dialog has `aria-expanded`." + +[[contract]] +component = "dialog" +step = "the panel has the box of a dialog of the third size" +reason = "The panel of rx.ui.dialog is the dialog itself, in the top layer: fixed, in the middle of the room the overlay of Radix Themes leaves around it, and no taller than that room, so a tall panel scrolls inside itself. The panel of rx.dialog sits in an overlay that scrolls. The panel is drawn on the same pixels." + +[[look]] +component = "dialog" +check = "style" +cells = "*@open" +properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height"] +reason = "The panel of rx.ui.dialog is the dialog itself, in the top layer: fixed, centred by its margins in the room the overlay of Radix Themes leaves around it, and no taller than that room, so a tall panel scrolls inside itself. The panel of rx.dialog sits in an overlay that scrolls. The panel is drawn on the same pixels." [[contract]] component = "dialog" @@ -444,83 +465,73 @@ component = "alert_dialog" check = "style" cells = "*@open" properties = ["pointer-events"] -reason = "While it is open rx.alert_dialog takes the pointer off the rest of the page with a style on the body. rx.ui.alert_dialog is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style." +reason = "While it is open rx.alert_dialog takes the pointer off the rest of the page with a style on the body. rx.ui.alert_dialog makes the page behind it inert instead, which takes the pointer, the keyboard and assistive technology off it without a style." [[contract]] component = "alert_dialog" step = "what it holds is in the server render" system = "rx" -reason = "rx.alert_dialog renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.alert_dialog holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings." +reason = "rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger." [[contract]] component = "alert_dialog" step = "opens and closes with JavaScript disabled" system = "rx" -reason = "rx.alert_dialog is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger, the action and the cancel button of rx.ui.alert_dialog are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript." - -[[contract]] -component = "alert_dialog" -step = "Tab stays inside an open alert dialog" -reason = "rx.ui.alert_dialog is a native modal dialog: the page behind it is inert, and Tab goes from its last element to the browser's own controls and back to its first, as in every native dialog. rx.alert_dialog keeps the focus from leaving the dialog at all." +reason = "rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger." [[look]] component = "drawer" check = "style" cells = "*@open" properties = ["pointer-events"] -reason = "While it is open rx.drawer takes the pointer off the rest of the page with a style on the body. rx.ui.drawer is a native modal dialog: the browser makes the page behind it inert, which takes the pointer, the keyboard and assistive technology off it without a style." +reason = "While it is open rx.drawer takes the pointer off the rest of the page with a style on the body. rx.ui.drawer makes the page behind it inert instead, which takes the pointer, the keyboard and assistive technology off it without a style." [[contract]] component = "drawer" step = "what it holds is in the server render" system = "rx" -reason = "rx.drawer renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.drawer holds is in the page from the start, in a dialog that is closed, and it keeps its state between two openings." +reason = "rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger." [[contract]] component = "drawer" step = "opens and closes with JavaScript disabled" system = "rx" -reason = "rx.drawer is opened by JavaScript: until it has run, a press on its trigger does nothing. The trigger and the close button of rx.ui.drawer are buttons that command a native dialog, which a browser with invoker commands opens and closes with or without JavaScript." +reason = "rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger." [[contract]] component = "drawer" step = "the focus moves into the drawer, and back to its trigger" system = "rx" -reason = "rx.drawer leaves the focus on its trigger while the drawer is open, so the keyboard and a screen reader start behind it. rx.ui.drawer is a native modal dialog: the focus moves to the first control inside it, and back to the trigger when it closes." +reason = "rx.drawer leaves the focus on its trigger while the drawer is open, so the keyboard and a screen reader start behind it. rx.ui.drawer moves the focus to the first control inside it, and back to the trigger when it closes." [[contract]] component = "drawer" step = "Tab does not reach the page behind an open drawer" system = "rx" -reason = "With rx.drawer open, Tab goes on through the page behind it. rx.ui.drawer is a native modal dialog: the page behind it is inert, and Tab moves through the drawer and the browser's own controls." - -[[contract]] -component = "drawer" -step = "is dragged out of the page by its panel" -reason = "rx.ui.drawer is not dragged: it is closed by Escape, by a press beside its panel and by its close button, and `snap_points`, `fade_from_index`, `handle_only`, `close_threshold`, `scroll_lock_timeout`, `prevent_scroll_restoration` and `should_scale_background`, which all describe the drag of rx.drawer, have nothing to say. The handle is drawn and does nothing." +reason = "With rx.drawer open, Tab goes on through the page behind it. rx.ui.drawer makes the page behind it inert while it is open, and Tab moves through the drawer alone." [[contract]] component = "popover" step = "what it holds is in the server render" system = "rx" -reason = "rx.popover renders what it holds when it opens: the page the server sends has only its trigger. What rx.ui.popover holds is in the page from the start, in a popover that is closed, and it keeps its state between two openings." +reason = "rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger." [[contract]] component = "popover" step = "opens and closes with JavaScript disabled" system = "rx" -reason = "rx.popover is opened by JavaScript: until it has run, a press on its trigger does nothing. rx.ui.popover is a native popover of its trigger, which the browser opens, places and closes, from its close button, on Escape and on a press outside, with or without JavaScript." +reason = "rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger." [[contract]] component = "popover" step = "its trigger names the popover it opens by the id it is given" system = "rx" -reason = "The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link, and it has none while the popover is closed. The trigger of rx.ui.popover names the popover by the id it was given." +reason = "The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link. The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it." [[contract]] component = "popover" step = "Tab stays inside an open popover" -reason = "rx.ui.popover is a native popover, which is not modal: it comes right after its trigger in the order of the page, Tab moves through what it holds and on to what follows the trigger, and the popover closes when the focus leaves it. rx.popover keeps Tab going round inside it until Escape. `modal` has nothing to say: the page beside a native popover stays as it is." +reason = "rx.ui.popover is not modal: Tab moves through what it holds and on to the page after its trigger, and the focus leaving it closes it. rx.popover keeps the focus inside until it closes." [[contract]] component = "popover" @@ -550,7 +561,7 @@ component = "popover" check = "style" cells = "*@open" properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] -reason = "Radix places a popover with a wrapper element it moves by a transform, and the popover inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.popover is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." +reason = "Radix places a popover with a wrapper element it moves by a transform, and the popover inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.popover is placed itself, in the top layer: fixed, where UI SDK puts it beside its trigger, and no taller than the room UI SDK measures. It is drawn on the same pixels." [[look]] component = "popover" @@ -601,13 +612,13 @@ reason = "rx.theme around part of a page does not take an appearance of its own: component = "dropdown_menu" check = "style" properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] -reason = "Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.dropdown_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." +reason = "Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. The menu of rx.ui.dropdown_menu is placed itself, in the top layer: fixed, where UI SDK puts it beside what opens it, and no taller than the room UI SDK measures. It is drawn on the same pixels." [[look]] component = "dropdown_menu" check = "style" properties = ["pointer-events"] -reason = "While it is open rx.dropdown_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.dropdown_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.dropdown_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.dropdown_menu hears the press and ignores it." +reason = "While it is open rx.dropdown_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.dropdown_menu sets no such style: a press outside the menu closes it. And the pointer passes through a disabled item of rx.ui.dropdown_menu, which it does not highlight, where rx.dropdown_menu hears the press and ignores it." [[look]] component = "context_menu" @@ -625,7 +636,7 @@ reason = "While it is open rx.context_menu takes the pointer off the rest of the component = "dropdown_menu" step = "opens with JavaScript disabled" system = "rx" -reason = "rx.dropdown_menu is opened by JavaScript: until it has run, a press on its trigger does nothing. The menu of rx.ui.dropdown_menu is a native popover of its trigger, which the browser opens, places and closes, on Escape and on a press outside, with or without JavaScript; moving through its items and choosing one wait for JavaScript." +reason = "rx.dropdown_menu and rx.ui.dropdown_menu are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing." [[contract]] component = "dropdown_menu" @@ -650,7 +661,7 @@ reason = "rx.dropdown_menu widens a menu that scrolls by the room its own scroll component = "dropdown_menu" step = "Escape closes only the sub-menu, and a choice in it closes both" system = "rx" -reason = "Escape in a sub-menu of rx.dropdown_menu closes the whole menu. A sub-menu of rx.ui.dropdown_menu is a popover nested in its menu, and Escape closes only the topmost one, giving the focus back to the item that opened it, as the WAI-ARIA menu pattern describes; a second Escape closes the menu." +reason = "Escape in a sub-menu of rx.dropdown_menu closes the whole menu. Escape in a sub-menu of rx.ui.dropdown_menu closes only that sub-menu, giving the focus back to the item that opened it, as the WAI-ARIA menu pattern describes; a second Escape closes the menu." [[contract]] component = "text" @@ -688,3 +699,191 @@ component = "theme_panel" check = "a11y" cells = "base" reason = "Both panels name the radio buttons of the radius by labels that point at the fixed ids Radix Themes gives them, theme-panel-radius-none and so on. A page with several panels has those ids several times, and every label names the first radio button of the page with its id, so only the panel that comes first has names for them, whichever system it is of. In a page with one panel each radio button of the radius is named by its label in both." + +[[look]] +component = "tabs" +check = "pixels" +cells = "default-value-none" +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed." + +[[look]] +component = "tabs" +check = "pixels" +cells = "many-true*" +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed." + +[[look]] +component = "tabs" +check = "style" +cells = "default-value-none" +properties = ["(element)", "height"] +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed." + +[[look]] +component = "tabs" +check = "style" +cells = "many-true*" +properties = ["(element)", "height", "width"] +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed." + +[[look]] +component = "tabs" +check = "a11y" +cells = "default-value-none" +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed." + +[[look]] +component = "tabs" +check = "a11y" +cells = "many-true*" +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed." + +[[look]] +component = "tabs" +check = "pixels" +cells = "*@focus-visible" +reason = "A tab of rx.ui is selected when it is pressed, or when the arrow keys move the focus to it: Tab or a script focusing it leaves the selection as it is. A tab of rx.tabs is selected whenever it takes the focus." + +[[look]] +component = "tabs" +check = "style" +cells = "*@focus-visible" +properties = ["border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "color", "outline-color", "width", "font-weight", "letter-spacing"] +reason = "A tab of rx.ui is selected when it is pressed, or when the arrow keys move the focus to it: Tab or a script focusing it leaves the selection as it is. A tab of rx.tabs is selected whenever it takes the focus." + +[[contract]] +component = "tabs" +step = "the arrow keys, Home and End select the tabs that can be, around the ends" +reason = "A disabled tab of rx.ui can take the focus, as the ARIA pattern of tabs asks: the arrow keys stop on it without selecting it, so a screen reader can say it is there. The arrow keys of rx.tabs pass a disabled tab by." + +[[contract]] +component = "tabs" +step = "tabs without a value show no panel until a tab is selected" +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel. rx.tabs selects none until a tab is pressed." + +[[contract]] +component = "tabs" +step = "shows the panel it starts with, with JavaScript disabled" +reason = "Tabs of rx.ui with no value, or a value that names no tab, select their first tab that is not disabled and show its panel, in the page the server sends too. rx.tabs selects none until a tab is pressed." + +[[contract]] +component = "dropdown_menu" +step = "the arrows, Home, End and typing move through the items, past a disabled one" +reason = "A disabled item of rx.ui.dropdown_menu can take the focus, as the ARIA pattern of menus asks: the arrow keys stop on it without choosing it, so a screen reader can say it is there. The arrow keys of rx.dropdown_menu pass a disabled item by." + +[[contract]] +component = "dropdown_menu" +step = "Tab does not leave an open menu" +reason = "Tab closes an open rx.ui.dropdown_menu and moves the focus on from its trigger, as from any button. rx.dropdown_menu keeps the focus in the menu until it closes." + +[[contract]] +component = "dropdown_menu" +step = "opens with JavaScript disabled" +reason = "rx.dropdown_menu and rx.ui.dropdown_menu are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing." + +[[look]] +component = "dropdown_menu" +check = "pixels" +cells = "*side-left*" +engines = ["chromium"] +reason = "A menu of rx.ui.dropdown_menu on the left of its trigger is placed by its right edge on a whole pixel, so its text may fall between pixels, and is smoothed differently; rx.dropdown_menu places it by its left edge. The menu is in the same place, on the same pixels." + +[[contract]] +component = "alert_dialog" +step = "what it holds is in the server render" +reason = "rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "alert_dialog" +step = "opens and closes with JavaScript disabled" +reason = "rx.alert_dialog and rx.ui.alert_dialog are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the alert dialog holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "drawer" +step = "what it holds is in the server render" +reason = "rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "drawer" +step = "opens and closes with JavaScript disabled" +reason = "rx.drawer and rx.ui.drawer are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the drawer holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "popover" +step = "what it holds is in the server render" +reason = "rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "popover" +step = "opens and closes with JavaScript disabled" +reason = "rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger." + +[[contract]] +component = "select" +step = "opens and closes its list with JavaScript disabled" +reason = "rx.select and rx.ui.select are opened by JavaScript: until the page has hydrated, a click on the trigger does nothing." + +[[contract]] +component = "alert_dialog" +step = "has the role, the name and the description of an alert dialog" +reason = "The trigger of rx.ui.alert_dialog says that it opens a dialog (`aria-haspopup`) and names it while it is open (`aria-controls`), but not whether it is open: it has no `aria-expanded`, and says its state in `data-open` and `data-closed` rather than `data-state`. The trigger of rx.alert_dialog has `aria-expanded`." + +[[contract]] +component = "drawer" +step = "has the role, the name and the description of a dialog" +reason = "The trigger of rx.ui.drawer says that it opens a dialog (`aria-haspopup`) and names it while it is open (`aria-controls`), but not whether it is open: it has no `aria-expanded`, and says its state in `data-open` and `data-closed` rather than `data-state`. The trigger of rx.drawer has `aria-expanded`." + +[[contract]] +component = "popover" +step = "is a dialog its trigger says it opens" +reason = "The trigger of rx.ui.popover says its state in `data-open` and `data-closed`, and the trigger of rx.popover in `data-state`; both say whether the popover is open in `aria-expanded`." + +[[contract]] +component = "popover" +step = "its trigger names the popover it opens by the id it is given" +reason = "The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it, whatever `id` the content is given. The trigger of rx.popover names it by an id rx.popover makes up." + +[[contract]] +component = "drawer" +step = "a drawer that is not dismissible is closed by its state alone" +reason = "A drawer of rx.ui that is not dismissible ignores Escape and a press outside, but its close button still closes it. The close button of rx.drawer does nothing either: only the state the drawer is bound to closes it." + +[[contract]] +component = "select" +step = "Tab stays in an open list" +reason = "Tab closes the open list of rx.ui.select and moves the focus on from its trigger, as from any button. rx.select keeps the focus in the list until it closes." + +[[look]] +component = "dialog" +check = "style" +cells = "long-true*" +properties = ["height"] +reason = "A panel of rx.ui.dialog taller than the room the overlay of Radix Themes leaves around it is no taller than that room, and scrolls what it holds. rx.dialog grows the panel and scrolls the overlay around it." + +[[look]] +component = "alert_dialog" +check = "style" +cells = "*@open" +properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height"] +reason = "The panel of rx.ui.alert_dialog is the dialog itself, in the top layer: fixed, centred by its margins in the room the overlay of Radix Themes leaves around it, and no taller than that room, so a tall panel scrolls inside itself. The panel of rx.alert_dialog sits in an overlay that scrolls. The panel is drawn on the same pixels." + +[[look]] +component = "drawer" +check = "style" +cells = "*@open" +properties = ["position", "min-width", "min-height"] +reason = "The panel of rx.ui.drawer is laid out by UI SDK in a viewport of its own that covers the page, at the edge it comes from, and slid with `translate`. The panel of rx.drawer is itself fixed at that edge. It is drawn on the same pixels." + +[[look]] +component = "drawer" +check = "style" +cells = "*@open" +properties = ["opacity"] +reason = "Where reduced motion is asked for, rx.ui.drawer and what is drawn over the page behind it fade in and out, where they would slide: UI SDK respects the setting. rx.drawer slides whatever the setting." + +[[look]] +component = "alert_dialog" +check = "style" +cells = "long-true*" +properties = ["height"] +reason = "A panel of rx.ui.alert_dialog taller than the room the overlay of Radix Themes leaves around it is no taller than that room, and scrolls what it holds. rx.alert_dialog grows the panel and scrolls the overlay around it." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py index 66d2f74987b..be4d42082f0 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/dialog.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/dialog.py @@ -107,13 +107,13 @@ def close_dialog(page: Page, target: Locator, point: Point) -> None: # the page, an overlay around a panel; rx.ui renders a native dialog, which # draws the overlay with its ::before, around a panel. _RADIX = ".rt-BaseDialogContent" -# The parts of rx.ui.dialog are those of UI SDK: its content is the panel, -# and its backdrop what is drawn over the page. -_UI = "[data-slot=dialog-content][data-open]" +# The parts of rx.ui.dialog and rx.ui.alert_dialog are those of UI SDK: the +# content is the panel, and the backdrop what is drawn over the page. +_UI = "[data-slot$=dialog-content][data-open]" PARTS = { "overlay": ( in_page(".rt-BaseDialogOverlay::before"), - "[data-slot=dialog-backdrop]", + "[data-slot$=dialog-backdrop]", ), "content": (in_page(_RADIX), _UI), "title": (in_page(f"{_RADIX} h1"), f"{_UI} h1"), diff --git a/packages/reflex-components-ui/parity/ui_parity/components/drawer.py b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py index bfee8cd791d..2a7e8c0653a 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/drawer.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/drawer.py @@ -91,7 +91,7 @@ def _close(page: Page, target: Locator, point: Point) -> None: point: The middle of the trigger. """ close_dialog(page, target, point) - if not target.evaluate("trigger => trigger.hasAttribute('data-rx-dialog-trigger')"): + if target.get_attribute("data-slot") != "drawer-trigger": # The drawer of Radix gives the page its scroll position back some # time after it has closed, which would move the page under the # next cell. @@ -102,6 +102,9 @@ def _close(page: Page, target: Locator, point: Point) -> None: # milliseconds. SETTLED = 700 +# The panel of rx.ui.drawer is UI SDK's content. +_UI = "[data-slot=drawer-content][data-open]" + MATRIX = Matrix( component="drawer", render=_drawer, @@ -129,15 +132,22 @@ def _close(page: Page, target: Locator, point: Point) -> None: parts={ "overlay": ( in_page("[data-vaul-overlay]"), - "div[data-rx-popup]:has(+ dialog[open])", + "[data-slot=drawer-backdrop]", + ), + "content": (in_page("[data-vaul-drawer]"), _UI), + "title": (in_page("[data-vaul-drawer] h2"), f"{_UI} h2"), + "description": (in_page("[data-vaul-drawer] p"), f"{_UI} p"), + "close": ( + in_page("[data-vaul-drawer] button"), + f"{_UI} button:not([data-slot=drawer-handle])", ), - "content": (in_page("[data-vaul-drawer]"), "dialog[open] > div"), - "title": (in_page("[data-vaul-drawer] h2"), "dialog[open] h2"), - "description": (in_page("[data-vaul-drawer] p"), "dialog[open] p"), - "close": (in_page("[data-vaul-drawer] button"), "dialog[open] button"), }, states={ - OPEN: State(enter=open_dialog, leave=_close, matches="[data-state='open']") + OPEN: State( + enter=open_dialog, + leave=_close, + matches=":is([data-state='open'], [data-open])", + ) }, # Not held to zero. At a threshold of zero every cell but one is equal # pixel for pixel: the ring of the focus on the trigger, which the diff --git a/packages/reflex-components-ui/parity/ui_parity/components/popover.py b/packages/reflex-components-ui/parity/ui_parity/components/popover.py index e984c3d5552..74a7daf1354 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/popover.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/popover.py @@ -91,7 +91,9 @@ def close_popup(page: Page, target: Locator, point: Point) -> None: page.evaluate("document.activeElement.blur()") -OPENED = State(enter=open_popup, leave=close_popup, matches="[data-state='open']") +OPENED = State( + enter=open_popup, leave=close_popup, matches=":is([data-state='open'], [data-open])" +) MATRIX = Matrix( component="popover", @@ -118,14 +120,17 @@ def close_popup(page: Page, target: Locator, point: Point) -> None: crop="stage", target="button", parts={ - "content": (in_page(".rt-PopoverContent"), "[data-rx-popup]:popover-open"), + "content": ( + in_page(".rt-PopoverContent"), + "[data-slot=popover-content][data-open]", + ), "title": ( in_page(".rt-PopoverContent > span"), - "[data-rx-popup]:popover-open > span", + "[data-slot=popover-content][data-open] > span", ), "close": ( in_page(".rt-PopoverContent button"), - "[data-rx-popup]:popover-open button", + "[data-slot=popover-content][data-open] button", ), }, states={OPEN: OPENED}, diff --git a/packages/reflex-components-ui/parity/ui_parity/components/select.py b/packages/reflex-components-ui/parity/ui_parity/components/select.py index 481f95408de..44660e22c24 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/select.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/select.py @@ -192,7 +192,9 @@ def _close(page: Page, target: Locator, point: Point) -> None: target="button", parts={"shown": "button > span", "icon": "button > svg"}, states={ - OPEN: State(enter=_open, leave=_close, matches="[data-state='open']"), + OPEN: State( + enter=_open, leave=_close, matches=":is([data-state='open'], [data-open])" + ), }, # The trigger of Radix shows nothing until JavaScript has found the text # of the chosen option, some time after the page is hydrated. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py index 655af942cb5..a6b3e88fae7 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py @@ -1,430 +1,115 @@ -"""What a dialog and an alert dialog share: a native ``dialog`` and its parts.""" +"""What a dialog, an alert dialog and a drawer share: the parts of UI SDK's dialogs. + +Each component names its entry point of ``@ui-sdk/react`` in ``library`` and +the export of each part in ``tag``. UI SDK opens the content in the top +layer, makes the page behind it inert, keeps the focus inside, closes it on +Escape and on a press outside, and gives the focus back to its trigger. +""" from __future__ import annotations -import itertools -from collections.abc import Iterator +from collections.abc import Sequence from typing import Any, ClassVar -from reflex_base.components.component import Component +from reflex_base.components.component import BaseComponent, Component from reflex_base.components.tags import CommonTag -from reflex_base.vars.base import LiteralVar, Var, VarData - -from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.components._group import descendants -from reflex_components_ui.components._script import handlers, listen, script -from reflex_components_ui.components._slot import become_child, held +from reflex_components_core.base.fragment import Fragment +from reflex_components_core.el import elements + +from reflex_components_ui.components._sdk import ( + PopupContentPart, + PopupRootPart, + SDKPart, + element, +) from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.dialog import ( - DIALOG, DIALOG_DESCRIPTION, - DIALOG_ROOT, DIALOG_TITLE, + SDK_DIALOG_BACKDROP, + SDK_DIALOG_CONTENT, ) -# Numbers the dialogs of an app: a dialog is named by the id of its title. -_ids = itertools.count(1) - -# The events of a dialog as they are rendered, by the name the script calls -# each under. -_EVENTS = { - "onOpenChange": "open", - "onOpenAutoFocus": "openAutoFocus", - "onCloseAutoFocus": "closeAutoFocus", - "onEscapeKeyDown": "escape", - "onPointerDownOutside": "outside", - "onInteractOutside": "interact", -} - - -class DialogRootBase(UIComponent): - """The element around the parts of a dialog. +# The heading of the first level a title renders as, as in Radix Themes. +_H1 = elements.H1.create() - Radix hands the parts of a dialog its props through a context. Here the - root finds its parts while compiling, and gives them what they render. - """ - - tag = "div" - styles: ClassVar[ComponentStyles] = DIALOG_ROOT +class DialogRootBase(PopupRootPart): + """The root of a dialog: no element, the context of its parts.""" - def _post_init(self, *args, **kwargs): - """Initialize the dialog, and give its parts what they share. - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - name = f"rx-dialog-{next(_ids)}" - on_open_change = self.event_triggers.pop("on_open_change", None) - parts = list(descendants(self, DialogPart, DialogRootBase)) - named: dict[str, Any] = {} - for part in parts: - if part._names is not None: - if part.id is None: - part.id = LiteralVar.create(f"{name}-{part._names}") - named.setdefault(f"aria-{part._names}", part.id) - for part in parts: - part._join(self, name, named, on_open_change) - - def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the dialog off the element. +class DialogTriggerBase(SDKPart): + """What opens a dialog: its child, which UI SDK makes a trigger.""" - Returns: - The props read as styles, and whether the dialog is open. - """ - return [*super()._exclude_props(), "open", "default_open"] + _renders_child: ClassVar[bool] = True - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the dialog, the script that opens it 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 script("dialog", "dialogClick") - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the element around the dialog. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, which hears a press on what opens the dialog, on what - closes it and beside its panel. - """ - tag = super()._render(props).add_props(**{"data-rx-dialog-root": ""}) - return listen(tag, script("dialog", "dialogClick"), "onClick") +class DialogCloseBase(SDKPart): + """What closes a dialog: its child, which UI SDK makes a close button.""" + _renders_child: ClassVar[bool] = True -class DialogPart(UIComponent): - """A part of a dialog, which its root gives a name.""" - # What the part is to the dialog: ``labelledby`` for its title, - # ``describedby`` for its description. - _names: ClassVar[str | None] = None +class DialogBackdropBase(SDKPart): + """What is drawn over the page behind a dialog. - def _post_init(self, *args, **kwargs): - """Initialize the part, as one outside a dialog. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # The attributes the dialog gives the part. - self._dialog: dict[str, Any] = {} - super()._post_init(*args, **kwargs) - - def _join( - self, - root: DialogRootBase, - name: str, - named: dict[str, Any], - on_open_change: Any, - ) -> None: - """Take from a dialog what Radix hands its parts through a context. - - Args: - root: The dialog the part is in. - name: The id of the dialog. - named: What names and describes the dialog, by the attribute. - on_open_change: What the dialog does when it opens or closes. - """ - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the part, those its dialog gives it 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) - for value in self._dialog.values(): - if isinstance(value, Var): - yield value - - -class DialogSlot(DialogPart): - """A part of a dialog that is rendered as its child: what opens or closes it. - - These parts act on a press, and so does a child with a handler of its - own for one: such a child is put in a flex container, which is then the - part, as in the Radix components. + A press on it is a press outside the dialog. """ - # The child keeps its own styles. - _merges_slot: ClassVar[bool] = False + styles: ClassVar[ComponentStyles] = SDK_DIALOG_BACKDROP - # The command a button gives the dialog without a script, where the - # browser has commands. - _command: ClassVar[str] = "close" - # The attribute the script finds the part by. - _mark: ClassVar[str] = "data-rx-dialog-close" +class DialogContentBase(PopupContentPart): + """The content of a dialog: its panel, after what is drawn over the page.""" - # What the attribute says of the part. - _marked: ClassVar[str] = "" + styles: ClassVar[ComponentStyles] = SDK_DIALOG_CONTENT + + # The part drawn over the page behind the panel, or None for none. + _backdrop: ClassVar[type[SDKPart] | None] = None @classmethod def create(cls, *children: Any, **props: Any) -> Component: - """Create a part that is rendered as its child. + """Create the content, after what is drawn over the page behind it. Args: - *children: The child: one element. - **props: The properties of the component. + *children: What the dialog holds. + **props: The properties of the panel. Returns: - The component. + The backdrop, then the panel. """ - return super().create(*held(children), **props) + content = super().create(*children, **props) + if cls._backdrop is None: + return content + return Fragment.create(cls._backdrop.create(), content) - def _post_init(self, *args, **kwargs): - """Initialize the part, rendered as its only child. - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - if "as_child" in self.get_fields(): - # The part says itself whether it is its child, and is a button - # around its children otherwise. - if not self._as_child: # pyright: ignore[reportAttributeAccessIssue] - self.tag = "button" - return - become_child(self) - - def _join( - self, - root: DialogRootBase, - name: str, - named: dict[str, Any], - on_open_change: Any, - ) -> None: - """Take the id of the dialog, for a button that commands it. - - Args: - root: The dialog the part is in. - name: The id of the dialog. - named: What names and describes the dialog, by the attribute. - on_open_change: What the dialog does when it opens or closes. - """ - if getattr(root, "open", None) is None: - # A dialog bound to state opens and closes when its state says. - self._dialog = {"commandfor": name, "command": self._command} - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the part. +class DialogTitleBase(SDKPart): + """The title of a dialog, which names it: a heading of the first level.""" - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: its child, marked for the script of the dialog. - """ - return ( - super() - ._render(props) - .add_props(**{self._mark: self._marked, **self._dialog}) - ) - - -class DialogTriggerBase(DialogSlot): - """What opens a dialog: its child, which says so.""" - - _command: ClassVar[str] = "show-modal" - - _mark: ClassVar[str] = "data-rx-dialog-trigger" - - def _join( - self, - root: DialogRootBase, - name: str, - named: dict[str, Any], - on_open_change: Any, - ) -> None: - """Take the id of the dialog the trigger opens. - - Args: - root: The dialog the trigger is in. - name: The id of the dialog. - named: What names and describes the dialog, by the attribute. - on_open_change: What the dialog does when it opens or closes. - """ - super()._join(root, name, named, on_open_change) - self._dialog["aria-controls"] = name + styles: ClassVar[ComponentStyles] = DIALOG_TITLE - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. - - Args: - props: The props to render (if None, then use get_props). + def _get_components_in_props(self) -> Sequence[BaseComponent]: + """Get the components in the props, the heading the title renders as included. Returns: - The tag: its child, with the state Radix gives what opens a - dialog. - """ - return ( - super() - ._render(props) - .add_props(**{ - "aria-haspopup": "dialog", - "aria-expanded": False, - "data-state": "closed", - }) - ) - - -class DialogSurface(DialogPart): - """The native dialog: it covers the page, around the panel of the dialog.""" - - tag = "dialog" - - styles: ClassVar[ComponentStyles] = DIALOG - - # The role of the dialog, when it is not the one the element has. - _role: ClassVar[str | None] = None - - # What does not dismiss the dialog: ``outside`` for a press beside its - # panel, ``all`` for that and Escape. - _keeps: ClassVar[str | None] = None - - def _post_init(self, *args, **kwargs): - """Initialize the dialog, as one that is not bound to state. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # Whether the dialog is open, when its state says. - self._open: Var | None = None - super()._post_init(*args, **kwargs) - - def _join( - self, - root: DialogRootBase, - name: str, - named: dict[str, Any], - on_open_change: Any, - ) -> None: - """Take the name of the dialog, and whether it is open. - - Args: - root: The dialog the element is in. - name: The id of the dialog. - named: What names and describes the dialog, by the attribute. - on_open_change: What the dialog does when it opens or closes. - """ - self._dialog = {"id": name, **named} - self._open = getattr(root, "open", None) - default_open = getattr(root, "default_open", None) - if default_open is not None: - self._dialog["data-default-open"] = default_open - if on_open_change is not None: - self.event_triggers["on_open_change"] = on_open_change - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the dialog, its script included. - - Args: - include_children: Whether to include Vars from children. - ignore_ids: The ids to ignore. - - Yields: - Each var referenced by the component. + The components. """ - yield from super()._get_vars(include_children, ignore_ids) - yield script("dialog", "dialogSync") - yield script("dialog", "dialogEvent") - if self._open is not None: - yield self._open + return [*super()._get_components_in_props(), _H1] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the dialog. + """Render the title as a heading of the first level, as Radix Themes does. Args: props: The props to render (if None, then use get_props). Returns: - The tag: a ``dialog`` the script opens over the page, which - follows the state it is bound to and says what happens to it. + The tag. """ - tag, on = handlers(super()._render(props), _EVENTS) - bound = LiteralVar.create(self._open) - sync = script("dialog", "dialogSync") - tag = tag.add_props(**{ - "data-rx-popup": "", - "role": self._role, - "data-rx-keep": self._keeps, - **self._dialog, - # Called whenever the page renders: a dialog bound to state - # takes whether it is open from there. - "ref": Var( - f"((dialog) => dialogSync(dialog, {bound!s}, {'null' if on is None else on!s}))", - _var_data=VarData.merge( - sync._get_all_var_data(), - bound._get_all_var_data(), - None if on is None else on._get_all_var_data(), - ), - ), - }) - return listen(tag, script("dialog", "dialogEvent"), "onCancel", "onClose") - - -def surface( - kind: type[DialogSurface], content: Component, events: dict[str, Any] -) -> Component: - """Put the panel of a dialog in the native dialog that covers the page. - - Args: - kind: The class of the dialog. - content: The panel. - events: What the dialog does when it opens, closes or is dismissed. - - Returns: - The dialog: the room around the panel is what scrolls a tall one. - """ - return kind.create( - Part.create( - content, - part="pad", - tag="div", - custom_attrs={"data-rx-dialog-pad": ""}, - ), - **events, - ) + return super()._render(props).add_props(render=element(_H1)) -class DialogTitleBase(DialogPart): - """The title of a dialog, which names it.""" - - tag = "h1" - - styles: ClassVar[ComponentStyles] = DIALOG_TITLE - - _names: ClassVar[str | None] = "labelledby" - - -class DialogDescriptionBase(DialogPart): +class DialogDescriptionBase(SDKPart): """The description of a dialog, which a screen reader reads with its name.""" - tag = "p" - styles: ClassVar[ComponentStyles] = DIALOG_DESCRIPTION - - _names: ClassVar[str | None] = "describedby" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py index 1f2079e3865..25011e407ea 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py @@ -19,9 +19,11 @@ LiteralComponentVar, ) from reflex_base.components.tags import CommonTag +from reflex_base.utils import format from reflex_base.vars.base import LiteralVar, Var, VarData from reflex_components_ui.base import UIComponent +from reflex_components_ui.components._group import descendants, literal from reflex_components_ui.constants import UI_SDK_CORE, UI_SDK_REACT from reflex_components_ui.style import StyleError @@ -59,7 +61,8 @@ def create(cls, *children: Any, **props: Any) -> Component: StyleError: If a part that renders as its child is not given exactly one element. """ - if not cls._renders_child: + if not cls._renders_child or literal(props.get("as_child")) is False: + # A part told not to render as its child is an element of its own. return super().create(*children, **props) # Its props are checked first: an error about them is the more useful. part = super().create(**props) @@ -70,7 +73,6 @@ def create(cls, *children: Any, **props: Any) -> Component: ) raise StyleError(msg) part._child = children[0] # pyright: ignore[reportAttributeAccessIssue] - part._element = element(children[0]) # pyright: ignore[reportAttributeAccessIssue] return part def _post_init(self, *args, **kwargs): @@ -80,12 +82,13 @@ def _post_init(self, *args, **kwargs): *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ - # The element the part renders as, through the `render` prop, and - # the component it is made from. + # The element the part renders as, through the `render` prop. self._child: Component | None = None - self._element: Var | None = None super()._post_init(*args, **kwargs) + def _set_slot(self) -> None: + """Leave ``as_child`` to UI SDK, which renders a part as its child through ``render``.""" + def _get_components_in_props(self) -> Sequence[BaseComponent]: """Get the components in the props, the element the part renders as included. @@ -111,7 +114,6 @@ def _add_style_recursive(self, style: Any, theme: Component | None = None): result = super()._add_style_recursive(style, theme) if self._child is not None: self._child = self._child._add_style_recursive(style, theme) - self._element = element(self._child) return result def _get_vars( @@ -127,8 +129,12 @@ def _get_vars( Each var referenced by the component. """ yield from super()._get_vars(include_children, ignore_ids) - if self._element is not None: - yield self._element + if self._child is not None: + # Its own vars, and the element itself, whose hooks the page has + # as a child's: the element is written only when the part + # renders, once the app is configured. + yield from self._child._get_vars(include_children=True) + yield Var("", _var_data=VarData(components=(self._child,))) def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the part, its props under the names UI SDK gives them. @@ -147,8 +153,8 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: for name, value in tag.props.items() } ) - if self._element is not None: - tag = tag.add_props(render=self._element) + if self._child is not None: + tag = tag.add_props(render=element(self._child)) return tag @@ -209,3 +215,158 @@ def on_change(handlers: dict[str, Any], body: str) -> Var | None: *(literal._get_all_var_data() for literal in literals.values()) ), ) + + +# The events Radix fires on the content of a popup: the reason UI SDK gives +# for a change of the popup says which happened. +POPUP_EVENTS = ( + "on_open_auto_focus", + "on_close_auto_focus", + "on_escape_key_down", + "on_pointer_down_outside", + "on_focus_outside", + "on_interact_outside", +) + +# What a popup does when it opens or closes, by the reason: as in Radix, +# what dismissed it is said before it closes, and where the focus went after. +_ON_OPEN_CHANGE = ( + 'if (details?.reason === "escape-key") escape?.();' + ' if (details?.reason === "outside-press") { outside?.(); interact?.(); }' + ' if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); }' + " change?.(value);" + " if (value) openAutoFocus?.(); else closeAutoFocus?.();" +) + + +class PopupContentPart(SDKPart): + """The content of a popup of UI SDK, whose events its root calls. + + A prop of the content that UI SDK takes on the root, such as ``loop``, + is listed in ``_root_props`` and moves there. + """ + + # The props of Radix's content that UI SDK takes on the root. + _root_props: ClassVar[tuple[str, ...]] = () + + def _exclude_props(self) -> list[str]: + """Keep the props the root takes off the content. + + Returns: + The props read as styles, and those of the root. + """ + return [*super()._exclude_props(), *self._root_props] + + +class PopupRootPart(SDKPart): + """A popup of UI SDK: no element, the root of its parts. + + Radix fires the events of a dismissal on the content, UI SDK says on the + root why the popup opens or closes: the root takes them from its content + and calls them by the reason. + """ + + # What UI SDK is given where neither the root nor its content says, by the + # name of the prop of UI SDK: the defaults of Radix where UI SDK's differ. + _defaults: ClassVar[dict[str, Any]] = {} + + def _post_init(self, *args, **kwargs): + """Initialize the popup, and take what its content hands the root. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + self._from_content: dict[str, Var] = {} + events: dict[str, Any] = {} + content = next(descendants(self, PopupContentPart, PopupRootPart), None) + if content is not None: + for prop in content._root_props: + value = getattr(content, prop, None) + if value is not None: + self._from_content[format.to_camel_case(prop)] = value + own = content.event_triggers + events = {event: own.pop(event, None) for event in POPUP_EVENTS} + self._on_open_change = on_change( + { + "change": self.event_triggers.pop("on_open_change", None), + "openAutoFocus": events.get("on_open_auto_focus"), + "closeAutoFocus": events.get("on_close_auto_focus"), + "escape": events.get("on_escape_key_down"), + "outside": events.get("on_pointer_down_outside"), + "focusOutside": events.get("on_focus_outside"), + "interact": events.get("on_interact_outside"), + }, + _ON_OPEN_CHANGE, + ) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the popup, those it takes from its content 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._from_content.values() + if self._on_open_change is not None: + yield self._on_open_change + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the popup, which is no element. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with what it takes from its content. + """ + defaults = { + name: value + for name, value in self._defaults.items() + if name not in self._from_content + and getattr(self, format.to_snake_case(name), None) is None + } + tag = super()._render(props).add_props(**defaults, **self._from_content) + if self._on_open_change is None: + return tag + return tag.add_props(onOpenChange=self._on_open_change) + + +class PlacedContent(PopupContentPart): + """The content of a popup UI SDK places beside its trigger. + + ``side`` and ``align`` are variants of its style table, so that ``align`` + is not the one of a flex container, and are handed to UI SDK as they are. + """ + + # What UI SDK is given where the content is given nothing, by the name of + # the prop of UI SDK: the placement of Radix Themes. + _placement: ClassVar[dict[str, Any]] = {} + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the content, placed as Radix Themes places it. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, with the placement of Radix Themes for what the content + is not given. + """ + tag = super()._render(props) + placement = {} + for name, default in self._placement.items(): + value = getattr(self, format.to_snake_case(name), None) + if value is None: + placement[name] = default + elif name in ("side", "align"): + # Variants of the style table, so not rendered by it. + placement[name] = value + return tag.add_props(**placement) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py index f59ca7d692d..6358924b964 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.py @@ -1,34 +1,46 @@ -"""An alert dialog: a native modal ``dialog`` that waits for an answer.""" +"""An alert dialog: the parts of ``@ui-sdk/react/alert-dialog``, in the look of Radix Themes. + +A press outside does not dismiss it: it waits for an answer. +""" from __future__ import annotations from typing import Any, ClassVar, Literal -from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.el import elements -from reflex_components_ui.base import UIComponent from reflex_components_ui.components._dialog import ( + DialogBackdropBase, + DialogCloseBase, + DialogContentBase, DialogDescriptionBase, DialogRootBase, - DialogSlot, - DialogSurface, DialogTitleBase, DialogTriggerBase, - surface, ) -from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.dialog import DIALOG_CONTENT +from reflex_components_ui.components._group import descendants +from reflex_components_ui.components._sdk import entry LiteralContentSize = Literal["1", "2", "3", "4"] +_LIBRARY = entry("alert-dialog") + +# What marks the cancel button, which takes the focus when the dialog opens. +_CANCEL = "data-rx-cancel" + class AlertDialogRoot(DialogRootBase): """Contains all the parts of the dialog.""" + library = _LIBRARY + + tag = "AlertDialog" + open: Var[bool] = field(doc="The controlled open state of the dialog.") on_open_change: EventHandler[passthrough_event_spec(bool)] = field( @@ -43,41 +55,29 @@ class AlertDialogRoot(DialogRootBase): class AlertDialogTrigger(DialogTriggerBase): """Wraps the control that will open the dialog.""" + library = _LIBRARY -class AlertDialogOverlay(DialogSurface): - """The native dialog around the content of an alert dialog.""" - - _role: ClassVar[str | None] = "alertdialog" + tag = "AlertDialogTrigger" - # A press beside the panel of an alert dialog does not dismiss it. - _keeps: ClassVar[str | None] = "outside" - on_open_change: EventHandler[passthrough_event_spec(bool)] = field( - doc="Fired when the open state changes." - ) - - on_open_auto_focus: EventHandler[no_args_event_spec] = field( - doc="Fired when the dialog is opened." - ) +class AlertDialogOverlay(DialogBackdropBase): + """What is drawn over the page behind an alert dialog.""" - on_close_auto_focus: EventHandler[no_args_event_spec] = field( - doc="Fired when the dialog is closed." - ) + library = _LIBRARY - on_escape_key_down: EventHandler[no_args_event_spec] = field( - doc="Fired when the escape key is pressed." - ) + tag = "AlertDialogBackdrop" -_EVENTS = ("on_open_auto_focus", "on_close_auto_focus", "on_escape_key_down") +class AlertDialogContent(DialogContentBase, elements.Div): + """Contains the content of the dialog. This component is based on the div element.""" + library = _LIBRARY -class AlertDialogContent(UIComponent, elements.Div): - """Contains the content of the dialog. This component is based on the div element.""" + tag = "AlertDialogContent" - tag = "div" + _backdrop: ClassVar[type[DialogBackdropBase] | None] = AlertDialogOverlay - styles: ClassVar[ComponentStyles] = DIALOG_CONTENT + _sdk_names: ClassVar[dict[str, str]] = {"forceMount": "keepMounted"} size: Var[Responsive[LiteralContentSize]] = field(doc="The size of the content.") @@ -95,29 +95,31 @@ class AlertDialogContent(UIComponent, elements.Div): doc="Fired when the escape key is pressed." ) - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create an AlertDialogContent. + def _post_init(self, *args, **kwargs): + """Initialize the content, and find whether it holds a cancel button. Args: - *children: What the dialog holds. - **props: The properties of the component. Its styles are those - of the panel, and its events those of the dialog around it. - - Returns: - The native dialog, around the panel. + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. """ - events = {event: props.pop(event) for event in _EVENTS if event in props} - return surface(AlertDialogOverlay, super().create(*children, **props), events) + super()._post_init(*args, **kwargs) + self._cancels = next(descendants(self, AlertDialogCancel), None) is not None + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the content, which gives the focus to its cancel button. - def _exclude_props(self) -> list[str]: - """Keep the prop that is no attribute off the element. + Args: + props: The props to render (if None, then use get_props). Returns: - The props read as styles, and whether the content stays - mounted: it always is. + The tag: as in Radix, the cancel button takes the focus when the + dialog opens, where UI SDK gives it to the first button that + closes the dialog. """ - return [*super()._exclude_props(), "force_mount"] + tag = super()._render(props) + if not self._cancels: + return tag + return tag.add_props(initialFocus=f"[{_CANCEL}]") class AlertDialogTitle(DialogTitleBase): @@ -126,26 +128,61 @@ class AlertDialogTitle(DialogTitleBase): leading trim on top. """ + library = _LIBRARY + + tag = "AlertDialogTitle" + class AlertDialogDescription(DialogDescriptionBase): """An optional accessible description that is announced when the dialog is opened. This part is based on the Text component with a pre-defined font size. """ + library = _LIBRARY + + tag = "AlertDialogDescription" -class AlertDialogAction(DialogSlot): + +class AlertDialogAction(DialogCloseBase): """Wraps the control that will close the dialog. This should be distinguished visually from the Cancel control. """ + library = _LIBRARY + + tag = "AlertDialogClose" + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the action, which reports that it confirmed. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag, whose value says the dialog was confirmed. + """ + return super()._render(props).add_props(value="confirm") + -class AlertDialogCancel(DialogSlot): +class AlertDialogCancel(DialogCloseBase): """Wraps the control that will close the dialog. This should be distinguished visually from the Action control. """ - # The dialog gives the focus to what cancels it when it opens. - _marked: ClassVar[str] = "cancel" + library = _LIBRARY + + tag = "AlertDialogClose" + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the cancel button, marked for the focus the dialog gives it. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. + """ + return super()._render(props).add_props(**{_CANCEL: ""}) class AlertDialog(ComponentNamespace): diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py index 6e5bb98bd06..fbeceea334b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/dialog.py @@ -1,65 +1,30 @@ -"""A dialog: the parts of ``@ui-sdk/react/dialog``, in the look of Radix Themes. - -UI SDK opens the dialog in the top layer, makes the page behind it inert, -keeps the focus inside, closes it on Escape and on a press beside its panel, -and gives the focus back to its trigger. -""" +"""A dialog: the parts of ``@ui-sdk/react/dialog``, in the look of Radix Themes.""" from __future__ import annotations -from collections.abc import Iterator, Sequence -from typing import Any, ClassVar, Literal +from typing import ClassVar, Literal -from reflex_base.components.component import ( - BaseComponent, - Component, - ComponentNamespace, - field, -) -from reflex_base.components.tags import CommonTag +from reflex_base.components.component import ComponentNamespace, field from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex_base.vars.base import Var -from reflex_components_core.base.fragment import Fragment from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.el import elements -from reflex_components_ui.components._group import descendants -from reflex_components_ui.components._sdk import SDKPart, element, entry, on_change -from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.dialog import ( - DIALOG_DESCRIPTION, - DIALOG_TITLE, - SDK_DIALOG_BACKDROP, - SDK_DIALOG_CONTENT, +from reflex_components_ui.components._dialog import ( + DialogBackdropBase, + DialogCloseBase, + DialogContentBase, + DialogDescriptionBase, + DialogRootBase, + DialogTitleBase, + DialogTriggerBase, ) +from reflex_components_ui.components._sdk import entry _LIBRARY = entry("dialog") -# The events Radix fires on the content of a dialog, which UI SDK says as -# the reason of a change of the dialog. -_EVENTS = ( - "on_open_auto_focus", - "on_close_auto_focus", - "on_escape_key_down", - "on_pointer_down_outside", - "on_interact_outside", -) - -# What the dialog does when it opens or closes, by the reason: as in Radix, -# what dismissed it is said before it closes. -_ON_OPEN_CHANGE = ( - 'if (details?.reason === "escape-key") escape?.();' - ' if (details?.reason === "outside-press") { outside?.(); interact?.(); }' - " change?.(value);" - " if (value) openAutoFocus?.(); else closeAutoFocus?.();" -) - - -# The heading of the first level a title renders as, as in Radix Themes. -_H1 = elements.H1.create() - -class DialogRoot(SDKPart): +class DialogRoot(DialogRootBase): """Root component for Dialog.""" library = _LIBRARY @@ -76,135 +41,39 @@ class DialogRoot(SDKPart): doc="The open state of the dialog when it is initially rendered. Use when you do not need to control its open state." ) - def _post_init(self, *args, **kwargs): - """Initialize the dialog, and take the events of its content. - - Radix fires them on the content; UI SDK says on the dialog why it - opens or closes. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - triggers = self.event_triggers - events = {"change": triggers.pop("on_open_change", None)} - for content in descendants(self, DialogContent, DialogRoot): - own = content.event_triggers - for event in _EVENTS: - events[event] = own.pop(event, None) - self._on_open_change = on_change( - { - "change": events["change"], - "openAutoFocus": events.get("on_open_auto_focus"), - "closeAutoFocus": events.get("on_close_auto_focus"), - "escape": events.get("on_escape_key_down"), - "outside": events.get("on_pointer_down_outside"), - "interact": events.get("on_interact_outside"), - }, - _ON_OPEN_CHANGE, - ) - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the dialog, what it does on a change 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) - if self._on_open_change is not None: - yield self._on_open_change - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the dialog, which is no element. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, which calls the events of Radix by the reason of a change. - """ - tag = super()._render(props) - if self._on_open_change is None: - return tag - return tag.add_props(onOpenChange=self._on_open_change) - - -class DialogTrigger(SDKPart): + +class DialogTrigger(DialogTriggerBase): """Trigger an action or event, to open a Dialog modal.""" library = _LIBRARY tag = "DialogTrigger" - _renders_child: ClassVar[bool] = True - -class DialogTitle(SDKPart): +class DialogTitle(DialogTitleBase): """Title component to display inside a Dialog modal.""" library = _LIBRARY tag = "DialogTitle" - styles: ClassVar[ComponentStyles] = DIALOG_TITLE - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the title, a heading of the first level as in Radix Themes. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag. - """ - return super()._render(props).add_props(render=element(self._heading)) - def _get_components_in_props(self) -> Sequence[BaseComponent]: - """Get the components in the props, the heading the title renders as included. - - Returns: - The components. - """ - return [*super()._get_components_in_props(), self._heading] - - @property - def _heading(self) -> Component: - """The heading the title renders as. - - Returns: - An ``h1`` with nothing of its own. - """ - return _H1 - - -class DialogOverlay(SDKPart): - """The backdrop of UI SDK: what is drawn over the page behind a dialog. - - A press on it is a press outside the dialog, which closes it. - """ +class DialogOverlay(DialogBackdropBase): + """What is drawn over the page behind a Dialog modal.""" library = _LIBRARY tag = "DialogBackdrop" - styles: ClassVar[ComponentStyles] = SDK_DIALOG_BACKDROP - -class DialogContent(SDKPart, elements.Div): +class DialogContent(DialogContentBase, elements.Div): """Content component to display inside a Dialog modal.""" library = _LIBRARY tag = "DialogContent" - styles: ClassVar[ComponentStyles] = SDK_DIALOG_CONTENT + _backdrop: ClassVar[type[DialogBackdropBase] | None] = DialogOverlay size: Var[Responsive[Literal["1", "2", "3", "4"]]] = field( doc='DialogContent size "1" - "4"' @@ -230,41 +99,22 @@ class DialogContent(SDKPart, elements.Div): doc="Fired when the pointer interacts outside the dialog." ) - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a DialogContent, after what is drawn over the page behind it. - - Args: - *children: What the dialog holds. - **props: The properties of the panel. - - Returns: - The backdrop, then the panel. - """ - return Fragment.create( - DialogOverlay.create(), super().create(*children, **props) - ) - -class DialogDescription(SDKPart): +class DialogDescription(DialogDescriptionBase): """Description component to display inside a Dialog modal.""" library = _LIBRARY tag = "DialogDescription" - styles: ClassVar[ComponentStyles] = DIALOG_DESCRIPTION - -class DialogClose(SDKPart): +class DialogClose(DialogCloseBase): """Close button component to close an open Dialog modal.""" library = _LIBRARY tag = "DialogClose" - _renders_child: ClassVar[bool] = True - class Dialog(ComponentNamespace): """Dialog components namespace.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py index 8a80a3bb15b..f187560f691 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/drawer.py @@ -1,32 +1,37 @@ -"""A drawer: a native ``dialog`` whose panel slides in from an edge of the page.""" +"""A drawer: the parts of ``@ui-sdk/react/drawer``, a panel that slides in from an edge. + +UI SDK slides the panel in and out, lets a finger, a mouse or a pen drag it +away, and does what a dialog does: the page behind is inert, the focus is +kept inside, and Escape or a press outside closes it. +""" from __future__ import annotations -from collections.abc import Iterator, Sequence +from collections.abc import Sequence from typing import Any, ClassVar, Literal from reflex_base.components.component import Component, ComponentNamespace, field from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec -from reflex_base.vars.base import LiteralVar, Var +from reflex_base.vars.base import Var from reflex_components_core.base.fragment import Fragment -from reflex_components_ui.base import Part, UIComponent +from reflex_components_ui.base import Part from reflex_components_ui.components._dialog import ( - DialogPart, + DialogBackdropBase, + DialogCloseBase, + DialogContentBase, DialogRootBase, - DialogSlot, - DialogSurface, + DialogTriggerBase, ) from reflex_components_ui.components._group import choose, descendants, literal +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.drawer import ( - DRAWER, DRAWER_CONTENT, DRAWER_DESCRIPTION, DRAWER_HANDLE, DRAWER_OVERLAY, - DRAWER_ROOT, DRAWER_TITLE, ) @@ -34,6 +39,8 @@ _AS_CHILD_DOC = "Change the default rendered element for the one passed as a child." +_LIBRARY = entry("drawer") + def _is_off(flag: Var | None) -> Var | bool: """Say whether a flag that is on unless it says otherwise is off. @@ -57,7 +64,19 @@ def _is_off(flag: Var | None) -> Var | bool: class DrawerRoot(DialogRootBase): """The Root component of a Drawer, contains all parts of a drawer.""" - styles: ClassVar[ComponentStyles] = DRAWER_ROOT + library = _LIBRARY + + tag = "Drawer" + + # The edge the drawer comes from, which no style reads: a variant, so that + # it is not the direction of a flex container. + styles: ClassVar[ComponentStyles] = { + "variants": { + "direction": {side: {} for side in ("top", "bottom", "left", "right")} + } + } + + _sdk_names: ClassVar[dict[str, str]] = {"onAnimationEnd": "onOpenChangeComplete"} as_child: Var[bool] = field(doc=_AS_CHILD_DOC) @@ -116,33 +135,45 @@ class DrawerRoot(DialogRootBase): ) def _post_init(self, *args, **kwargs): - """Initialize the drawer, and give its parts what they share. + """Initialize the drawer, and give its panel the edge it comes from. Args: *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ super()._post_init(*args, **kwargs) - # Rendered by the dialog, which knows when its panel has moved. - on_animation_end = self.event_triggers.pop("on_animation_end", None) - if on_animation_end is not None: - for part in descendants(self, DrawerSurface, DialogRootBase): - part._on_animation_end = on_animation_end + for content in descendants(self, DrawerContent, DialogRootBase): + content._direction = self.direction + content._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + modeless = _is_off(self.modal) + for overlay in descendants(self, DrawerOverlay, DialogRootBase): + overlay._modal = choose(modeless, "false", "true") + overlay._merge_styles() # pyright: ignore[reportAttributeAccessIssue] + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the drawer, which hands UI SDK the edge it comes from. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag. + """ + tag = super()._render(props) + return tag if self.direction is None else tag.add_props(side=self.direction) def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the drawer off the element. + """Keep the props UI SDK has no use for off the drawer. Returns: - The props read as styles, and what the drawer hands its parts - or does without: it is not dragged, so it has no snap points. + The props read as styles, and those of vaul that UI SDK does + without: it drags the panel from anywhere, and moves it by its own + spring. """ return [ *super()._exclude_props(), - "modal", - "direction", - "dismissible", + "as_child", "handle_only", - "snap_points", "fade_from_index", "scroll_lock_timeout", "prevent_scroll_restoration", @@ -151,74 +182,42 @@ def _exclude_props(self) -> list[str]: ] -class DrawerPart(DialogPart): - """A part of a drawer.""" - - as_child: Var[bool] = field(doc=_AS_CHILD_DOC) +class _DrawerButton(SDKPart): + """What opens or closes a drawer: its child, or a button around its children.""" - -class DrawerTrigger(DialogSlot): - """The button that opens the dialog.""" + library = _LIBRARY as_child: Var[bool] = field( default=Var.create(True), doc="Defaults to true, if the first child acts as the trigger.", ) - # One declaration holds the styles of the trigger and of its child. - _merges_slot: ClassVar[bool] = True + def _exclude_props(self) -> list[str]: + """Keep ``as_child`` off the element. - _command: ClassVar[str] = "show-modal" + Returns: + The props read as styles, and ``as_child``. + """ + return [*super()._exclude_props(), "as_child"] - _mark: ClassVar[str] = "data-rx-dialog-trigger" - def _join( - self, - root: DialogRootBase, - name: str, - named: dict[str, Any], - on_open_change: Any, - ) -> None: - """Take the id of the drawer the trigger opens. +class DrawerTrigger(_DrawerButton, DialogTriggerBase): + """The button that opens the dialog.""" - Args: - root: The drawer the trigger is in. - name: The id of the drawer. - named: What names and describes the drawer, by the attribute. - on_open_change: What the drawer does when it opens or closes. - """ - super()._join(root, name, named, on_open_change) # pyright: ignore[reportAttributeAccessIssue] - if literal(getattr(root, "modal", None)) is not None: - # A drawer that may not be modal is opened by its script alone. - self._dialog = {} - if self._command != "close": - self._dialog["aria-controls"] = name + tag = "DrawerTrigger" - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. - Args: - props: The props to render (if None, then use get_props). +class DrawerClose(_DrawerButton, DialogCloseBase): + """A button that closes the drawer.""" - Returns: - The tag: its child, or a button around its children, with the - state Radix gives what opens a dialog. - """ - tag = super()._render(props) - if not self._as_child: # pyright: ignore[reportAttributeAccessIssue] - tag = tag.add_props(type="button") - if self._command == "close": - return tag - return tag.add_props(**{ - "aria-haspopup": "dialog", - "aria-expanded": False, - "data-state": "closed", - }) - - -class DrawerPortal(DrawerPart): + tag = "DrawerClose" + + +class DrawerPortal(SDKPart): """Portals your drawer into the body.""" + as_child: Var[bool] = field(doc=_AS_CHILD_DOC) + @classmethod def create(cls, *children: Any, **props: Any) -> Component: """Create a DrawerPortal. @@ -228,140 +227,49 @@ def create(cls, *children: Any, **props: Any) -> Component: **props: The properties of the component. Returns: - The children: a native dialog is over the page wherever it is. + The children: UI SDK puts the drawer in the top layer wherever it is. """ return Fragment.create(*children) -class DrawerSurface(DialogSurface): - """The native dialog around the content of a drawer.""" +class DrawerOverlay(DialogBackdropBase): + """What is drawn over the page behind the drawer: UI SDK fades it.""" - styles: ClassVar[ComponentStyles] = DRAWER + library = _LIBRARY - on_open_change: EventHandler[passthrough_event_spec(bool)] = field( - doc="Fires when the drawer is opened or closed." - ) - - on_open_auto_focus: EventHandler[no_args_event_spec] = field( - doc="Fired when the drawer content is opened." - ) - - on_close_auto_focus: EventHandler[no_args_event_spec] = field( - doc="Fired when the drawer content is closed." - ) - - on_escape_key_down: EventHandler[no_args_event_spec] = field( - doc="Fired when the escape key is pressed." - ) + tag = "DrawerBackdrop" - on_pointer_down_outside: EventHandler[no_args_event_spec] = field( - doc="Fired when the pointer is down outside the drawer content." - ) + styles: ClassVar[ComponentStyles] = DRAWER_OVERLAY - on_interact_outside: EventHandler[no_args_event_spec] = field( - doc="Fired when interacting outside the drawer content." - ) + as_child: Var[bool] = field(doc=_AS_CHILD_DOC) def _post_init(self, *args, **kwargs): - """Initialize the dialog, as the one of a drawer without props. + """Initialize the overlay, as the one of a modal drawer. Args: *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ - # What the style table reads as variants: the drawer sets them. - self._direction: Any = None + # What the style table reads as a variant: the drawer sets it. self._modal: Any = None - self._on_animation_end: Any = None super()._post_init(*args, **kwargs) - def _join( - self, - root: DialogRootBase, - name: str, - named: dict[str, Any], - on_open_change: Any, - ) -> None: - """Take from a drawer where it comes from and how it is dismissed. - - Args: - root: The drawer the dialog is in. - name: The id of the drawer. - named: What names and describes the drawer, by the attribute. - on_open_change: What the drawer does when it opens or closes. - """ - super()._join(root, name, named, on_open_change) # pyright: ignore[reportAttributeAccessIssue] - self._direction = getattr(root, "direction", None) - modeless = _is_off(getattr(root, "modal", None)) - self._modal = choose(modeless, "false", "true") - if modeless is not False: - self._dialog["data-modal"] = choose(modeless, "false", None) # pyright: ignore[reportAttributeAccessIssue] - kept = _is_off(getattr(root, "dismissible", None)) - if kept is not False: - self._dialog["data-rx-keep"] = choose(kept, "all", None) # pyright: ignore[reportAttributeAccessIssue] - for part in self.children: - if isinstance(part, DrawerContent): - part._direction = self._direction - part._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the dialog, what follows its panel 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) - if self._on_animation_end is not None: - yield LiteralVar.create(self._on_animation_end) - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the dialog. - - Args: - props: The props to render (if None, then use get_props). + def _exclude_props(self) -> list[str]: + """Keep ``as_child`` off the element. Returns: - The tag, out of the order of Tab, which says when its panel has - slid in or out. + The props read as styles, and ``as_child``. """ - # The dialog covers the page and is nothing to stop on: Safari makes - # it a stop of Tab, as a box its panel overflows, where Radix's - # drawer has no element around its panel. - tag = super()._render(props).add_props(tab_index=-1) - if self._on_animation_end is None: - return tag - handler = LiteralVar.create(self._on_animation_end) - return tag.add_props( - on_transition_end=Var( - '((event) => event.propertyName === "transform" && ' - "event.target.parentElement === event.currentTarget && " - f"({handler!s})(event.currentTarget.open))", - _var_data=handler._get_all_var_data(), - ) - ) - - -_EVENTS = ( - "on_open_auto_focus", - "on_close_auto_focus", - "on_escape_key_down", - "on_pointer_down_outside", - "on_interact_outside", -) + return [*super()._exclude_props(), "as_child"] # Based on https://www.radix-ui.com/primitives/docs/components/dialog#content -class DrawerContent(UIComponent): - """Content that should be rendered in the drawer.""" +class DrawerContent(DialogContentBase): + """The panel of the drawer, which UI SDK places at its edge and slides.""" + + library = _LIBRARY - tag = "div" + tag = "DrawerContent" styles: ClassVar[ComponentStyles] = DRAWER_CONTENT @@ -387,24 +295,8 @@ class DrawerContent(UIComponent): doc="Fired when interacting outside the drawer content." ) - @classmethod - def create(cls, *children, **props): - """Create a Drawer Content. - - Args: - *children: The list of children to use. - **props: Additional properties to apply to the drawer content. - Its styles are those of the panel, and its events those of - the dialog around it. - - Returns: - The native dialog, around the panel. - """ - events = {event: props.pop(event) for event in _EVENTS if event in props} - return DrawerSurface.create(super().create(*children, **props), **events) - def _post_init(self, *args, **kwargs): - """Initialize the panel, as the one of a drawer without props. + """Initialize the panel, as one that comes from the bottom. Args: *args: Args to initialize the component. @@ -414,87 +306,47 @@ def _post_init(self, *args, **kwargs): self._direction: Any = None super()._post_init(*args, **kwargs) - -class DrawerOverlay(DrawerPart): - """A layer that covers the inert portion of the view when the dialog is open.""" - - tag = "div" - - styles: ClassVar[ComponentStyles] = DRAWER_OVERLAY - - def _post_init(self, *args, **kwargs): - """Initialize the overlay, as the one of a modal drawer. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # What the style table reads as a variant: the drawer sets it. - self._modal: Any = None - super()._post_init(*args, **kwargs) - - def _join( - self, - root: DialogRootBase, - name: str, - named: dict[str, Any], - on_open_change: Any, - ) -> None: - """Take from a drawer whether it is modal: only then has it an overlay. - - Args: - root: The drawer the overlay is in. - name: The id of the drawer. - named: What names and describes the drawer, by the attribute. - on_open_change: What the drawer does when it opens or closes. - """ - self._modal = choose(_is_off(getattr(root, "modal", None)), "false", "true") - self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the overlay. - - Args: - props: The props to render (if None, then use get_props). + def _exclude_props(self) -> list[str]: + """Keep ``as_child`` off the element. Returns: - The tag, which stays until it has faded out. + The props read as styles, and ``as_child``. """ - return super()._render(props).add_props(**{"data-rx-popup": ""}) + return [*super()._exclude_props(), "as_child"] -class DrawerClose(DrawerTrigger): - """A button that closes the drawer.""" - - _command: ClassVar[str] = "close" +class DrawerTitle(SDKPart): + """A title for the drawer.""" - _mark: ClassVar[str] = "data-rx-dialog-close" + library = _LIBRARY + tag = "DrawerTitle" -class DrawerTitle(DrawerPart): - """A title for the drawer.""" + styles: ClassVar[ComponentStyles] = DRAWER_TITLE - tag = "h2" + as_child: Var[bool] = field(doc=_AS_CHILD_DOC) - styles: ClassVar[ComponentStyles] = DRAWER_TITLE + def _exclude_props(self) -> list[str]: + """Keep ``as_child`` off the element. - _names: ClassVar[str | None] = "labelledby" + Returns: + The props read as styles, and ``as_child``. + """ + return [*super()._exclude_props(), "as_child"] -class DrawerDescription(DrawerPart): +class DrawerDescription(DrawerTitle): """A description for the drawer.""" - tag = "p" + tag = "DrawerDescription" styles: ClassVar[ComponentStyles] = DRAWER_DESCRIPTION - _names: ClassVar[str | None] = "describedby" +class DrawerHandle(DrawerTitle): + """The handle of the drawer: a bar, which drags it.""" -class DrawerHandle(DrawerPart): - """A description for the drawer.""" - - tag = "div" + tag = "DrawerHandle" styles: ClassVar[ComponentStyles] = DRAWER_HANDLE @@ -519,17 +371,6 @@ def create(cls, *children: Any, **props: Any) -> Component: **props, ) - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the handle. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, which is nothing to assistive technology. - """ - return super()._render(props).add_props(**{"aria-hidden": True}) - class Drawer(ComponentNamespace): """A namespace for Drawer components.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py index 5946089ec37..8c5ae370971 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py @@ -7,7 +7,6 @@ from __future__ import annotations -from collections.abc import Iterator from typing import Any, ClassVar, Literal from reflex_base.components.component import Component, ComponentNamespace, field @@ -18,7 +17,12 @@ from reflex_components_ui.base import Part from reflex_components_ui.components._group import descendants, literal -from reflex_components_ui.components._sdk import SDKPart, entry, on_change +from reflex_components_ui.components._sdk import ( + PlacedContent, + PopupRootPart, + SDKPart, + entry, +) from reflex_components_ui.components.select import ( _icon, # pyright: ignore[reportAttributeAccessIssue] ) @@ -57,104 +61,18 @@ "L3.20171 1.26174C2.91909 0.958928 2.93545 0.484337 3.23826 0.201711Z" ) -# The events Radix fires on the content of a menu, which UI SDK says as the -# reason of a change of the menu. -_EVENTS = ( - "on_close_auto_focus", - "on_escape_key_down", - "on_pointer_down_outside", - "on_focus_outside", - "on_interact_outside", -) - -# What a menu does when it opens or closes, by the reason: as in Radix, what -# dismissed it is said before it closes. -_ON_OPEN_CHANGE = ( - 'if (details?.reason === "escape-key") escape?.();' - ' if (details?.reason === "outside-press") { outside?.(); interact?.(); }' - ' if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); }' - " change?.(value);" - " if (!value) closeAutoFocus?.();" -) - -# What Radix Themes gives the content of a dropdown menu: the room beside -# its trigger and the room it keeps from the edges of the viewport. -_SIDE_OFFSET = 4 +# What Radix Themes gives the content of a menu and of a sub-menu: the room +# beside what opens it and the room it keeps from the edges of the viewport. _COLLISION_PADDING = 10 -class MenuRootPart(SDKPart): - """A menu or a sub-menu, which takes from its content what Radix gives it. - - Whether the arrow keys go round is a prop of the content in Radix and of - the menu in UI SDK, and so are the events of a dismissal. - """ +class MenuRootPart(PopupRootPart): + """A menu or a sub-menu: no element, the root of its parts.""" library = _LIBRARY - def _post_init(self, *args, **kwargs): - """Initialize the menu, and take the props of its content. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - self._loop: Var | None = None - events: dict[str, Any] = { - "change": self.event_triggers.pop("on_open_change", None) - } - content = next(descendants(self, MenuContentPart, MenuRootPart), None) - if content is not None: - self._loop = getattr(content, "loop", None) - own = content.event_triggers - for event in _EVENTS: - events[event] = own.pop(event, None) - self._on_open_change = on_change( - { - "change": events["change"], - "closeAutoFocus": events.get("on_close_auto_focus"), - "escape": events.get("on_escape_key_down"), - "outside": events.get("on_pointer_down_outside"), - "focusOutside": events.get("on_focus_outside"), - "interact": events.get("on_interact_outside"), - }, - _ON_OPEN_CHANGE, - ) - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the menu, those it takes from its content 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) - if self._loop is not None: - yield self._loop - if self._on_open_change is not None: - yield self._on_open_change - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the menu, which is no element. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag. - """ - tag = super()._render(props) - if self._loop is not None: - tag = tag.add_props(loop=self._loop) - if self._on_open_change is not None: - tag = tag.add_props(onOpenChange=self._on_open_change) - return tag + # The arrow keys stop at the ends, as in Radix: UI SDK goes round. + _defaults: ClassVar[dict[str, Any]] = {"loop": False} class DropdownMenuRoot(MenuRootPart): @@ -206,13 +124,16 @@ class DropdownMenuTrigger(SDKPart): ) -class MenuContentPart(SDKPart): +class MenuContentPart(PlacedContent): """The content of a menu or a sub-menu, its items inside what scrolls them.""" library = _LIBRARY _sdk_names: ClassVar[dict[str, str]] = {"forceMount": "keepMounted"} + # Whether the arrow keys go round: a prop of the menu in UI SDK. + _root_props: ClassVar[tuple[str, ...]] = ("loop",) + @classmethod def create(cls, *children: Any, **props: Any) -> Component: """Create the content, its items inside the element that scrolls them. @@ -267,12 +188,11 @@ def _exclude_props(self) -> list[str]: """Keep the props UI SDK has no use for off the content. Returns: - The props read as styles, those the menu takes, and those of the - placement of Radix that UI SDK does not have. + The props read as styles, and those of the placement of Radix that + UI SDK does not have: it always keeps a menu in the viewport. """ return [ *super()._exclude_props(), - "loop", "as_child", "avoid_collisions", "sticky", @@ -285,6 +205,14 @@ class DropdownMenuContent(MenuContentPart): tag = "MenuContent" + # Where Radix Themes places a dropdown menu. + _placement: ClassVar[dict[str, Any]] = { + "side": "bottom", + "align": "start", + "sideOffset": 4, + "collisionPadding": _COLLISION_PADDING, + } + styles: ClassVar[ComponentStyles] = SDK_DROPDOWN_MENU_CONTENT size: Var[Responsive[LiteralSizeType]] = field( @@ -367,27 +295,6 @@ class DropdownMenuContent(MenuContentPart): doc="Fired when the pointer interacts outside the dialog." ) - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the content, placed as Radix Themes places it. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, with the side, the alignment, the offset and the padding - of Radix Themes where the content is given none. - """ - tag = super()._render(props) - placement: dict[str, Any] = { - "side": "bottom" if self.side is None else self.side, - "align": "start" if self.align is None else self.align, - } - if self.side_offset is None: - placement["sideOffset"] = _SIDE_OFFSET - if self.collision_padding is None: - placement["collisionPadding"] = _COLLISION_PADDING - return tag.add_props(**placement) - class MenuItemPart(SDKPart): """An item of a menu, which its menu gives its look.""" @@ -484,6 +391,12 @@ class DropdownMenuSubContent(MenuContentPart): tag = "MenuSubContent" + # Where Radix Themes places a sub-menu. + _placement: ClassVar[dict[str, Any]] = { + "sideOffset": 1, + "collisionPadding": _COLLISION_PADDING, + } + styles: ClassVar[ComponentStyles] = SDK_MENU_SUB_CONTENT as_child: Var[bool] = field( @@ -555,21 +468,15 @@ 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 the offset and the padding of Radix Themes where - the content is given none. + The tag: as far up as the padding of the menu, where it is given + no offset along its trigger, so that the text of its first item + is level with the item it opens from. """ tag = super()._render(props) - placement: dict[str, Any] = {} - if self.side_offset is None: - placement["sideOffset"] = 1 - if self.align_offset is None: - # As far up as the padding of the menu: the text of its first - # item is level with the item it opens from. - size = literal(getattr(self, "size", None)) - placement["alignOffset"] = -4 * int(size if size in ("1", "2") else 2) - if self.collision_padding is None: - placement["collisionPadding"] = _COLLISION_PADDING - return tag.add_props(**placement) + if self.align_offset is not None: + return tag + size = literal(getattr(self, "size", None)) + return tag.add_props(alignOffset=-4 * int(size if size in ("1", "2") else 2)) class DropdownMenuItem(MenuItemPart): diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py b/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py index e88d8c35406..5d3d3a136e0 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py @@ -1,8 +1,13 @@ -"""A popover: a native ``popover`` beside the button that opens it.""" +"""A popover: the parts of ``@ui-sdk/react/popover``, in the look of Radix Themes. + +UI SDK opens the popover in the top layer beside its trigger, places it, +moves the focus into it and back, and closes it on Escape and on a press +outside. +""" from __future__ import annotations -from typing import ClassVar, Literal +from typing import Any, ClassVar, Literal from reflex_base.components.component import ComponentNamespace, field from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec @@ -10,20 +15,24 @@ from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.el import elements -from reflex_components_ui.components._popup import ( - PopupClose, - PopupContent, - PopupRoot, - PopupTrigger, +from reflex_components_ui.components._sdk import ( + PlacedContent, + PopupRootPart, + SDKPart, + entry, ) from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.popover import POPOVER_CONTENT +from reflex_components_ui.styles.popover import SDK_POPOVER_CONTENT + +_LIBRARY = entry("popover") -class PopoverRoot(PopupRoot): +class PopoverRoot(PopupRootPart): """Floating element for displaying rich content, triggered by a button.""" - _prefix: ClassVar[str] = "rx-popover" + library = _LIBRARY + + tag = "Popover" open: Var[bool] = field(doc="The controlled open state of the popover.") @@ -40,14 +49,32 @@ class PopoverRoot(PopupRoot): ) -class PopoverTrigger(PopupTrigger): +class PopoverTrigger(SDKPart): """Wraps the control that will open the popover.""" + library = _LIBRARY + + tag = "PopoverTrigger" -class PopoverContent(PopupContent, elements.Div): + _renders_child: ClassVar[bool] = True + + +class PopoverContent(PlacedContent, elements.Div): """Contains content to be rendered in the open popover.""" - styles: ClassVar[ComponentStyles] = POPOVER_CONTENT + library = _LIBRARY + + tag = "PopoverContent" + + styles: ClassVar[ComponentStyles] = SDK_POPOVER_CONTENT + + # Where Radix Themes places a popover. + _placement: ClassVar[dict[str, Any]] = { + "side": "bottom", + "align": "start", + "sideOffset": 8, + "collisionPadding": 10, + } size: Var[Responsive[Literal["1", "2", "3", "4"]]] = field( doc='Size of the button: "1" | "2" | "3" | "4"' @@ -107,10 +134,31 @@ class PopoverContent(PopupContent, elements.Div): doc="Fired when the pointer interacts outside the dialog." ) + def _exclude_props(self) -> list[str]: + """Keep the props of Radix's placement that UI SDK does not have off the content. + + Returns: + The props read as styles, and ``avoid_collisions``, ``sticky`` + and ``hide_when_detached``: UI SDK always keeps a popover in the + viewport. + """ + return [ + *super()._exclude_props(), + "avoid_collisions", + "sticky", + "hide_when_detached", + ] + -class PopoverClose(PopupClose): +class PopoverClose(SDKPart): """Wraps the control that will close the popover.""" + library = _LIBRARY + + tag = "PopoverClose" + + _renders_child: ClassVar[bool] = True + class Popover(ComponentNamespace): """Floating element for displaying rich content, triggered by a button.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/select.py b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py index 1abdbc653bb..e11ff1fc8a0 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/select.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/select.py @@ -1,73 +1,43 @@ -"""A select: a button, and the popup of options it opens.""" +"""A select: the parts of ``@ui-sdk/react/select``, in the look of Radix Themes. + +UI SDK opens the list in the top layer beside its trigger, moves through +the options with the keys and by typing, shows the chosen option in the +trigger, in the page the server sends too, and keeps the value in an input +a form submits. +""" from __future__ import annotations -import functools -import itertools -from collections.abc import Iterator, Sequence +from collections.abc import Sequence from typing import Any, ClassVar, Literal from reflex_base.components.component import Component, ComponentNamespace, field from reflex_base.components.tags import CommonTag -from reflex_base.event import ( - EventHandler, - input_event, - no_args_event_spec, - passthrough_event_spec, -) -from reflex_base.utils.imports import ImportVar -from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec +from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.core.foreach import foreach from reflex_components_core.el import elements -from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.components._group import descendants, is_value, literal -from reflex_components_ui.components._script import listen -from reflex_components_ui.constants import WEB_DIR -from reflex_components_ui.props import style_before +from reflex_components_ui.base import Part +from reflex_components_ui.components._group import descendants, literal +from reflex_components_ui.components._sdk import ( + PlacedContent, + PopupRootPart, + SDKPart, + entry, +) from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.popup import OFFSET, SHIFT from reflex_components_ui.styles.select import ( - SELECT, SELECT_CONTENT, SELECT_ITEM, SELECT_LABEL, SELECT_SEPARATOR, SELECT_TRIGGER, - SELECT_VALUE, ) from reflex_components_ui.themes import LiteralAccentColor -_SCRIPT = f"$/{WEB_DIR}/behaviors/listbox.js" -_POPUP_SCRIPT = f"$/{WEB_DIR}/behaviors/popup.js" - - -@functools.cache -def _script(name: str, module: str = _SCRIPT) -> Var: - """Name a function of the script of a select, or of a popup. - - Args: - name: The name the script exports it under. - module: The script. - - Returns: - The function, with its import. - """ - return Var(name, _var_data=VarData(imports={module: [ImportVar(tag=name)]})) - - -# The events of the popup as they are rendered, by the name the script -# calls each under. -_POPUP_EVENTS = { - "onOpenChange": "open", - "onCloseAutoFocus": "close", - "onEscapeKeyDown": "escape", - "onPointerDownOutside": "outside", -} - -# Numbers the popups and the labels, which are found by their ids. -_ids = itertools.count(1) +_LIBRARY = entry("select") _CHEVRON = ( "M0.135232 3.15803C0.324102 2.95657 0.640521 2.94637 0.841971 3.13523" @@ -112,57 +82,17 @@ def _icon(part: str, path: str, **attributes: Any) -> Component: ) -def _pixels(amount: Any) -> Any: - """Write a number of pixels as a length. - - Args: - amount: The number, or a Var of it. - - Returns: - The length: a string when the number is known while compiling. - """ - amount = literal(amount) - if not isinstance(amount, Var): - return f"{amount}px" - return Var( - f'(({amount!s}) + "px")', _var_type=str, _var_data=amount._get_all_var_data() - ) - - -class SelectValue(UIComponent, elements.Input): - """The input that holds the value of a select, which a form submits.""" - - tag = "input" - - styles: ClassVar[ComponentStyles] = SELECT_VALUE - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the input. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: nothing to assistive technology, and not reached - with Tab. - """ - return ( - super() - ._render(props) - .add_props(**{ - "data-rx-select-value": "", - "aria-hidden": True, - "tabIndex": -1, - }) - ) +class SelectRoot(PopupRootPart): + """Displays a list of options for the user to pick from, triggered by a button.""" + library = _LIBRARY -class SelectRoot(UIComponent): - """Displays a list of options for the user to pick from, triggered by a button.""" + tag = "Select" - tag = "span" + _sdk_names: ClassVar[dict[str, str]] = {"onChange": "onValueChange"} - styles: ClassVar[ComponentStyles] = SELECT + # The arrow keys stop at the ends, as in Radix: UI SDK goes round. + _defaults: ClassVar[dict[str, Any]] = {"loop": False} size: Var[Responsive[Literal["1", "2", "3"]]] = field( doc=( @@ -248,7 +178,7 @@ class SelectRoot(UIComponent): ) ) - on_change: EventHandler[input_event] = field( + on_change: EventHandler[passthrough_event_spec(str)] = field( doc=( "Fires when the user selects a different option from the dropdown. " "The handler receives the new value as a string. Use this with " @@ -268,159 +198,44 @@ class SelectRoot(UIComponent): ) ) - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a SelectRoot. - - Radix hands the parts of a select its props through a context. Here - the root finds its parts while compiling, and gives them what they - render. The value is the one of an input after them, which is what - a form reads. - - Args: - *children: The trigger and the content of the select. - **props: The properties of the component. - - Returns: - The SelectRoot component. - """ - value, open_ = props.get("value"), props.get("open") - shown = value if value is not None else props.get("default_value") - arguments = [LiteralVar.create(argument) for argument in (value, open_)] - held: dict[str, Any] = { - key: props[key] for key in ("name", "required", "disabled") if key in props - } - if shown is not None: - held["default_value"] = shown - holder = SelectValue.create( - **held, - custom_attrs={ - # Called whenever the page renders: a select bound to state - # takes its value, and whether it is open, from there. - "ref": Var( - f"((holder) => syncSelect(holder, {arguments[0]!s}, " - f"{arguments[1]!s}))", - _var_data=VarData.merge( - _script("syncSelect")._get_all_var_data(), - *(argument._get_all_var_data() for argument in arguments), - ), - ), - "onFocus": _script("selectFocus"), - }, - ) - attributes = props.setdefault("custom_attrs", {}) - attributes.setdefault("onKeyDown", _script("selectKeyDown")) - attributes.setdefault("onClick", _script("selectClick")) - attributes.setdefault("onPointerMove", _script("selectPointerMove")) - return super().create(*children, holder, **props) - def _post_init(self, *args, **kwargs): - """Initialize the select, and give its parts what they share. + """Initialize the select, and give its trigger and its list its size. Args: *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ super()._post_init(*args, **kwargs) - selected = self.value if self.value is not None else self.default_value - items = list(descendants(self, SelectItem)) - for item in items: - item._join(selected) - popup = f"rx-select-{next(_ids)}" - on_open_change = self.event_triggers.pop("on_open_change", None) - for content in descendants(self, SelectContent): - popup = content._join(self, popup, on_open_change) - for trigger in descendants(self, SelectTrigger): - trigger._join(self, popup, selected, items) + for part in descendants(self, (SelectTrigger, SelectContent)): # pyright: ignore[reportArgumentType] + part._join(self) def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the parts off the element. + """Keep the size off the select, which is no element: its parts take it. Returns: - The props read as styles, and what the select hands its parts. + The props read as styles, and the size. """ - return [ - *super()._exclude_props(), - "size", - "value", - "default_value", - "default_open", - "open", - "name", - "disabled", - "required", - ] + return [*super()._exclude_props(), "size"] - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the element around the select. - Args: - props: The props to render (if None, then use get_props). +class _SelectShown(SDKPart, Part): + """What the trigger shows: the chosen option, or the placeholder.""" - Returns: - The tag, marked for the script of the select, which opens a - select that starts open. - """ - tag = super()._render(props).add_props(**{"data-rx-select": ""}) - if self.default_open is not None: - tag = tag.add_props(**{"data-default-open": self.default_open}) - return tag + library = _LIBRARY + tag = "SelectValue" -def _shown( - selected: Var | None, placeholder: Var | None, items: list[SelectItem] -) -> Any: - """Work out what the trigger of a select shows before any script runs. + _named_as: ClassVar[str | None] = "select.trigger" - Args: - selected: The value of the select, or None. - placeholder: What the trigger shows when nothing is chosen, or None. - items: The options of the select. - - Returns: - The text of the chosen option, where it is known while compiling or - can be read from the value, and the placeholder otherwise: the - script of the select shows the text when it runs. - """ - empty = "" if placeholder is None else placeholder - if selected is None: - return empty - texts = [(item.value, item._text) for item in items] - value = literal(selected) - if not isinstance(value, Var): - for item_value, text in texts: - if literal(item_value) == value and text is not None: - return text - return empty - fallback = LiteralVar.create(empty) - data = [selected._get_all_var_data(), fallback._get_all_var_data()] - if texts and all( - text is not None and str(text) == str(item_value) for item_value, text in texts - ): - # Each option shows its value: so does the trigger. - return Var( - f"({selected!s} || {fallback!s})", - _var_type=str, - _var_data=VarData.merge(*data), - ) - known = {literal(item_value): text for item_value, text in texts} - if texts and not any( - isinstance(item, Var) or item is None for pair in known.items() for item in pair - ): - # The text of each option is known: the one of the value is read - # from them. - return Var( - f"({LiteralVar.create(known)!s}[{selected!s}] ?? {fallback!s})", - _var_type=str, - _var_data=VarData.merge(*data), - ) - return empty + placeholder: Var[str] = field(doc="What the trigger shows while nothing is chosen.") -class SelectTrigger(UIComponent): +class SelectTrigger(SDKPart): """The button that toggles the select.""" - tag = "button" + library = _LIBRARY + + tag = "SelectTrigger" styles: ClassVar[ComponentStyles] = SELECT_TRIGGER @@ -473,11 +288,15 @@ def create(cls, *children: Any, **props: Any) -> Component: The SelectTrigger component: a button around what it shows and the icon of a select. """ - return super().create( - Part.create(*children, part="shown", tag="span"), - _icon("icon", _CHEVRON), - **props, - ) + if children: + shown = Part.create(*children, part="shown", tag="span") + else: + placeholder = props.get("placeholder") + shown = _SelectShown.create( + part="shown", + **({} if placeholder is None else {"placeholder": placeholder}), + ) + return super().create(shown, _icon("icon", _CHEVRON), **props) def _post_init(self, *args, **kwargs): """Initialize the trigger, with the look of a select without props. @@ -486,111 +305,48 @@ def _post_init(self, *args, **kwargs): *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ - # What the style table reads as a variant, and the attributes the - # select gives its trigger: both are set by the select around it. + # What the style table reads as a variant: the select sets it. self._size: Any = None - self._select: dict[str, Any] = {} super()._post_init(*args, **kwargs) - def _join( - self, - select: SelectRoot, - popup: Any, - selected: Var | None, - items: list[SelectItem], - ) -> None: - """Take from a select what Radix hands its trigger through a context. + def _join(self, select: SelectRoot) -> None: + """Take the size of the select the trigger is in. Args: - select: The select the trigger is in. - popup: The id of the popup it opens. - selected: The value of the select, or None. - items: The options of the select. + select: The select. """ self._size = select.size - attributes: dict[str, Any] = {"popoverTarget": popup, "aria-controls": popup} - if select.disabled is not None: - attributes["disabled"] = select.disabled - if not self.children[0].children: - mark: dict[str, Any] = {"data-rx-select-shown": ""} - if self.placeholder is not None: - mark["data-placeholder"] = self.placeholder - self.children[0] = Part.create( - _shown(selected, self.placeholder, items), - part="shown", - tag="span", - custom_attrs=mark, - ) - if selected is None: - attributes["data-placeholder"] = "" - elif isinstance(literal(selected), Var): - attributes["data-placeholder"] = Var( - f'({selected!s} ? undefined : "")', - _var_data=selected._get_all_var_data(), - ) - self._select = attributes # The parts take their styles again: the size is one of theirs. for part in descendants(self, Part): part._merged = None # pyright: ignore[reportAttributeAccessIssue] self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the trigger, those its select gives it 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) - for value in self._select.values(): - if isinstance(value, Var): - yield value - def _exclude_props(self) -> list[str]: - """Keep the placeholder off the button: the text inside it shows it. + """Keep the placeholder off the button: what it shows says it. Returns: The props read as styles, and the placeholder. """ return [*super()._exclude_props(), "placeholder"] - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: a button that opens its popup without a script, with - the role and the state Radix gives the trigger of a select. - """ - return ( - super() - ._render(props) - .add_props(**{ - "type": "button", - "role": "combobox", - "aria-expanded": "false", - "aria-haspopup": "listbox", - "aria-autocomplete": "none", - "data-state": "closed", - **self._select, - }) - ) - -class SelectContent(UIComponent): +class SelectContent(PlacedContent): """The component that pops out when the select is open.""" - tag = "div" + library = _LIBRARY + + tag = "SelectContent" styles: ClassVar[ComponentStyles] = SELECT_CONTENT + # Where Radix Themes places the list of a select. + _placement: ClassVar[dict[str, Any]] = { + "side": "bottom", + "align": "start", + "sideOffset": 4, + "collisionPadding": 10, + } + variant: Var[Literal["solid", "soft"]] = field( doc=( "The visual style of the dropdown menu surface. Defaults to " @@ -670,28 +426,8 @@ class SelectContent(UIComponent): doc="Fired when a pointer down event happens outside the select content." ) - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a SelectContent. - - Args: - *children: The options of the select. - **props: The properties of the component. - - Returns: - The SelectContent component. - """ - distances = { - name: _pixels(props[prop]) - for prop, name in (("side_offset", OFFSET), ("align_offset", SHIFT)) - if props.get(prop) is not None - } - if distances: - style_before(props, distances) - return super().create(*children, **props) - def _post_init(self, *args, **kwargs): - """Initialize the content, with the look of a select without props. + """Initialize the list, with the look of a select without props. Args: *args: Args to initialize the component. @@ -701,136 +437,75 @@ def _post_init(self, *args, **kwargs): self._size: Any = None super()._post_init(*args, **kwargs) - def _join(self, select: SelectRoot, popup: str, on_open_change: Any) -> Any: - """Take from a select what Radix hands its content through a context. + def _join(self, select: SelectRoot) -> None: + """Take the size of the select the list is in. Args: - select: The select the content is in. - popup: The id of a popup that is given none. - on_open_change: What the select does when it opens or closes. - - Returns: - The id of the popup. + select: The select. """ self._size = select.size - if self.id is None: - self.id = LiteralVar.create(popup) - if on_open_change is not None: - self.event_triggers["on_open_change"] = on_open_change self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - return self.id - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the popup, what follows its toggle 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 _script("selectToggle") - yield _script("popupBeforeToggle", _POPUP_SCRIPT) def _exclude_props(self) -> list[str]: - """Keep the props that say where the popup goes off the element. + """Keep the position off the list: UI SDK says it otherwise. Returns: - The props read as styles, and the ones a style is made from. - The position is one of them: the popup is beside its trigger - whatever it says. + The props read as styles, and the position. """ - return [*super()._exclude_props(), "position", "side_offset", "align_offset"] + return [*super()._exclude_props(), "position"] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the popup. + """Render the list, over its trigger where it is aligned with it. Args: props: The props to render (if None, then use get_props). Returns: - The tag: a popover the browser opens and closes, which says so - to the script of the select, and through it to the events. + The tag: a list of ``position="item-aligned"`` lies over its + trigger with the chosen option on it, as UI SDK's + ``alignItemWithTrigger`` does. """ tag = super()._render(props) - rendered = dict(tag.props) - handlers = { - name: LiteralVar.create(rendered.pop(event)) - for event, name in _POPUP_EVENTS.items() - if event in rendered - } - tag = tag.set(props=rendered) - toggle = _script("selectToggle") - if handlers: - called = ", ".join([ - f"{name}: {handler!s}" for name, handler in handlers.items() - ]) - toggle = Var( - f"((event) => selectToggle(event, ({{ {called} }})))", - _var_data=VarData.merge( - _script("selectToggle")._get_all_var_data(), - *(handler._get_all_var_data() for handler in handlers.values()), - ), + position = literal(self.position) + if position is None or position == "popper": + return tag + if isinstance(position, Var): + return tag.add_props( + alignItemWithTrigger=Var( + f'({position!s} === "item-aligned")', + _var_type=bool, + _var_data=position._get_all_var_data(), + ) ) - tag = tag.add_props(**{ - "popover": "auto", - "role": "listbox", - "tabIndex": -1, - "data-rx-popup": "", - # Before it is first drawn, the popup is put on whole pixels. - "onBeforeToggle": _script("popupBeforeToggle", _POPUP_SCRIPT), - "onToggle": toggle, - }) - # The select says it opens or closes as soon as it is about to. - return listen(tag, toggle, "onBeforeToggle") - - -class SelectGroup(UIComponent): + return tag.add_props(alignItemWithTrigger=True) + + +class SelectGroup(SDKPart): """Used to group multiple items.""" - tag = "div" + library = _LIBRARY - _valid_parents: ClassVar[list[str]] = ["SelectContent"] + tag = "SelectGroup" - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a SelectGroup. + _valid_parents: ClassVar[list[str]] = ["SelectContent"] - Args: - *children: The label and the options of the group. - **props: The properties of the component. - Returns: - The SelectGroup component, named by its label. - """ - for child in children: - if isinstance(child, SelectLabel): - if child.id is None: - child.id = LiteralVar.create(f"rx-select-label-{next(_ids)}") - props.setdefault("aria_labelledby", child.id) - break - return super().create(*children, **props) +class _SelectIndicator(SDKPart, Part): + """The check of the chosen option.""" - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the group. + library = _LIBRARY - Args: - props: The props to render (if None, then use get_props). + tag = "SelectItemIndicator" - Returns: - The tag, with the role of a group. - """ - return super()._render(props).add_props(role="group") + _named_as: ClassVar[str | None] = "select.item" -class SelectItem(UIComponent): +class SelectItem(SDKPart): """The component that contains the select items.""" - tag = "div" + library = _LIBRARY + + tag = "SelectItem" styles: ClassVar[ComponentStyles] = SELECT_ITEM @@ -869,141 +544,35 @@ def create(cls, *children: Any, **props: Any) -> Component: what the option shows. """ return super().create( - Part.create( + _SelectIndicator.create( _icon("check", _CHECK, fillRule="evenodd", clipRule="evenodd"), part="indicator", - tag="span", ), - elements.span(*children, custom_attrs={"data-rx-select-text": ""}), + elements.span(*children), **props, ) - def _post_init(self, *args, **kwargs): - """Initialize the option of a select that has no value. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # Whether the select around the option has chosen it. - self._selected: Any = False - super()._post_init(*args, **kwargs) - - @property - def _text(self) -> Any: - """What the option shows, when it is one string. - - Returns: - The text, or None for an option that shows anything else. - """ - shown = self.children[1].children - if len(shown) != 1: - return None - contents = getattr(shown[0], "contents", None) - if contents is None or not issubclass(contents._var_type, str): - return None - return literal(contents) - - def _join(self, selected: Var | None) -> None: - """Take from a select whether it has chosen the option. - - Args: - selected: The value of the select, or None. - """ - self._selected = False if selected is None else is_value(selected, self.value) - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the option, what its select gives it 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) - if isinstance(self._selected, Var): - yield self._selected - - def _exclude_props(self) -> list[str]: - """Keep the props of an option off the element: it is no input. - - Returns: - The props read as styles, the value and whether it is disabled. - """ - return [*super()._exclude_props(), "value", "disabled"] - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the option. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, with the role and the state of an option: it takes - the focus from the script of the select, not from Tab. - """ - selected = self._selected - attributes: dict[str, Any] = { - "role": "option", - "tabIndex": -1, - "data-value": self.value, - "aria-selected": ( - Var( - f'({selected!s} ? "true" : "false")', - _var_data=selected._get_all_var_data(), - ) - if isinstance(selected, Var) - else str(selected).lower() - ), - } - if self.disabled is not None: - attributes["aria-disabled"] = self.disabled - return super()._render(props).add_props(**attributes) - -class SelectLabel(UIComponent): +class SelectLabel(SDKPart): """Used to render the label of a group, it isn't focusable using arrow keys.""" - tag = "div" + library = _LIBRARY + + tag = "SelectGroupLabel" styles: ClassVar[ComponentStyles] = SELECT_LABEL _valid_parents: ClassVar[list[str]] = ["SelectGroup"] - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the label. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, marked for the rule that keeps it from the option - before it. - """ - return super()._render(props).add_props(**{"data-rx-select-label": ""}) - -class SelectSeparator(UIComponent): +class SelectSeparator(SDKPart): """Used to visually separate items in the Select.""" - tag = "div" - - styles: ClassVar[ComponentStyles] = SELECT_SEPARATOR + library = _LIBRARY - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the separator. + tag = "SelectSeparator" - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, which is nothing to assistive technology. - """ - return super()._render(props).add_props(**{"aria-hidden": True}) + styles: ClassVar[ComponentStyles] = SELECT_SEPARATOR class HighLevelSelect(SelectRoot): diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py index a1a985f53b7..44126d52e87 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/drawer.py @@ -1,31 +1,13 @@ -"""The look of a drawer: a native ``dialog`` whose panel slides in from an edge.""" +"""The look of a drawer: a panel UI SDK slides in from an edge of the page.""" from __future__ import annotations from typing import Any from reflex_components_ui.style import ComponentStyles, unchecked -from reflex_components_ui.styles.dialog import OPEN, SURFACE -_DURATION = "0.5s" -_EASING = "cubic-bezier(0.32, 0.72, 0, 1)" - -# What a drawer hands its panel: where it comes from and goes back to, and -# where it is now. -_AWAY = "--rx-drawer-away" -_PLACE = "--rx-drawer-place" - -# The overlay is the element before or after the drawer it belongs to. -_BESIDE_OPEN = ":is(:has(~ dialog[open]), dialog[open] ~ *)" - -# How far a panel is moved out of the page on each side, and where what -# continues it past its edge is. -_AWAYS = { - "bottom": "translate3d(0, 100%, 0)", - "top": "translate3d(0, -100%, 0)", - "left": "translate3d(-100%, 0, 0)", - "right": "translate3d(100%, 0, 0)", -} +# What continues a panel past the edge it comes from, on each side: when it +# is dragged further out than it rests, the page behind shows no gap. _BEYOND: dict[str, dict[str, Any]] = { "bottom": {"top": "100%", "left": "0", "right": "0", "height": "200%"}, "top": {"bottom": "100%", "left": "0", "right": "0", "height": "200%"}, @@ -33,57 +15,15 @@ "right": {"left": "100%", "top": "0", "bottom": "0", "width": "200%"}, } -# The element around the parts of a drawer, which is nothing to the layout. -# It reads the direction, which is the edge the drawer comes from and not -# the direction of a flex container. -DRAWER_ROOT: ComponentStyles = { - "base": {"display": "contents"}, - "variants": {"direction": {}}, -} - -# The dialog covers the page and is nothing to see: its panel is what an -# app styles. A drawer that is not modal lets the pointer through to the -# page beside its panel. -DRAWER: ComponentStyles = { - "base": unchecked({ - **SURFACE, - "position": "fixed", - "inset": "0", - "width": "100%", - "height": "100%", - "z_index": 50, - "display": {"default": "none", OPEN: "block"}, - # A moment longer than its panel, which says when it has slid out. - "transition_duration": "0.55s", - _PLACE: {"default": f"var({_AWAY})", OPEN: "none"}, - }), - "variants": { - "_direction": {side: unchecked({_AWAY: away}) for side, away in _AWAYS.items()}, - "_modal": {"false": {"pointer_events": "none"}}, - }, - "defaults": {"_direction": "bottom"}, -} - +# The panel, which UI SDK places at its edge and slides with `translate`: +# what an app styles is its size, its surface and its corners. DRAWER_CONTENT: ComponentStyles = { "base": unchecked({ - "left": "0", - "right": "0", - "bottom": "0", - "top": "0", - "position": "fixed", - "z_index": 50, + "position": "relative", "display": "flex", - "pointer_events": "auto", "touch_action": "none", - "will_change": "transform", + "outline_style": "none", "@media (hover: hover) and (pointer: fine)": {"user_select": "none"}, - "transform": { - "default": f"var({_PLACE})", - "@starting-style": f"var({_AWAY})", - }, - "transition_property": "transform", - "transition_duration": _DURATION, - "transition_timing_function": _EASING, # The panel goes on past the edge it came from, in its own color. "_after": { "content": "''", @@ -100,32 +40,16 @@ "defaults": {"_direction": "bottom"}, } +# What is drawn over the page behind a drawer: UI SDK fades it as the panel +# slides. DRAWER_OVERLAY: ComponentStyles = { "base": unchecked({ "position": "fixed", - "left": "0", - "right": "0", - "bottom": "0", - "top": "0", - "z_index": 50, + "inset": "0", "background_color": "rgba(0, 0, 0, 0.5)", - "transition_property": "opacity, display", - "transition_duration": _DURATION, - "transition_timing_function": _EASING, }), - "variants": { - "_modal": { - "true": { - "display": {"default": "none", _BESIDE_OPEN: "block"}, - "opacity": { - "default": 0, - _BESIDE_OPEN: {"default": 1, "@starting-style": 0}, - }, - }, - # A drawer that is not modal has no overlay. - "false": {"display": "none"}, - }, - }, + # A drawer that is not modal has no overlay, as in vaul. + "variants": {"_modal": {"true": {}, "false": {"display": "none"}}}, "defaults": {"_modal": "true"}, } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py index aebb3800c9f..e715c409442 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py @@ -6,7 +6,13 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked -from reflex_components_ui.styles.popup import POPUP, SDK_PLACED, placement, placements +from reflex_components_ui.styles.popup import ( + POPUP, + placed, + placement, + placements, + sdk_popup, +) from reflex_components_ui.tokens import Step9 # What the content of a menu hands its items, as Radix Themes names them. @@ -210,24 +216,9 @@ def _content( # The content of a menu of UI SDK, which places it: no taller than the room # it measures, which it says in `--available-height`. -_SDK_CONTENT_BASE: dict[str, Any] = { - **{ - key: value - for key, value in _CONTENT_BASE.items() - if key != "position_try_fallbacks" - }, - **SDK_PLACED, - "max_height": "var(--available-height)", -} +_SDK_CONTENT_BASE = sdk_popup(_CONTENT_BASE) -SDK_DROPDOWN_MENU_CONTENT = _content(_SDK_CONTENT_BASE, _SIZES, {}, []) -# Where UI SDK places the menu: props of the content, which no style reads. -# They are variants, so that `align` is not the one of a flex container. -SDK_DROPDOWN_MENU_CONTENT["variants"] = { - **SDK_DROPDOWN_MENU_CONTENT["variants"], - "side": {side: {} for side in ("top", "right", "bottom", "left")}, - "align": {align: {} for align in ("start", "center", "end")}, -} +SDK_DROPDOWN_MENU_CONTENT = placed(_content(_SDK_CONTENT_BASE, _SIZES, {}, [])) SDK_MENU_SUB_CONTENT = _content(_SDK_CONTENT_BASE, _RAISED, {}, []) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py index 857b486c93f..28a71c1bed9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py @@ -6,7 +6,7 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, unchecked -from reflex_components_ui.styles.popup import POPUP, placements +from reflex_components_ui.styles.popup import POPUP, placed, placements, sdk_popup _PADDING = "--popover-content-padding" @@ -55,3 +55,13 @@ def _size(padding: str, radius: str) -> dict[str, Any]: "defaults": {"size": "2", "side": "bottom", "align": "start"}, "compound": placements("8px"), } + +# A popover of UI SDK, which places it: at least as wide as its trigger. +SDK_POPOVER_CONTENT: ComponentStyles = placed({ + "base": unchecked({ + **sdk_popup(POPOVER_CONTENT["base"]), + "min_width": "var(--anchor-width)", + }), + "variants": POPOVER_CONTENT["variants"], + "defaults": {"size": "2"}, +}) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py index e578f7121b3..2f23186172a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py @@ -2,14 +2,15 @@ from __future__ import annotations +from collections.abc import Mapping from typing import Any -from reflex_components_ui.style import CompoundStyle, unchecked +from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked -# A popup that is open, and the element before it that opens it. A style -# of that element selects on the second: no script says that it is open. +# A popup that is open, and the element that opens it: the one before it, or +# a trigger of UI SDK, which says it has opened its popup. OPEN = ":popover-open" -OPENS = ":is([data-state='open'], :has(+ :popover-open))" +OPENS = ":is([data-state='open'], [data-open], :has(+ :popover-open))" # How far a popup stays from the edge of the viewport, as in Radix. _EDGE = "10px" @@ -182,3 +183,61 @@ def placements(default_offset: str = "0px") -> list[CompoundStyle]: _MOTION: {"default": "160ms", _ENDING: "100ms"}, }, } + +# A popup of UI SDK before a table draws it: what a native popover is not, +# placed by UI SDK where `placement` would put it. +SDK_POPUP: dict[str, Any] = { + **{ + key: value + for key, value in POPUP.items() + if key + not in ( + "position_try_fallbacks", + "opacity", + "transform", + "transition_property", + "transition_duration", + ) + }, + **SDK_PLACED, + "max_height": "var(--available-height)", +} + + +def sdk_popup(base: Mapping[str, Any]) -> dict[str, Any]: + """Make the base style of a popup of UI SDK from the one of a native popover. + + Args: + base: The base style of a native popover, made over ``POPUP``. + + Returns: + The same style over ``SDK_POPUP``: what it took from ``POPUP`` is + replaced, what it sets of its own stays. + """ + return { + **SDK_POPUP, + **{ + key: value + for key, value in base.items() + if key not in POPUP or POPUP[key] != value + }, + } + + +def placed(styles: ComponentStyles) -> ComponentStyles: + """Make the side and the alignment variants of a style table of placed content. + + Args: + styles: The style table. + + Returns: + The table, with ``side`` and ``align`` as variants without styles. + """ + return { + **styles, + "variants": { + **styles.get("variants", {}), + "side": {side: {} for side in ("top", "right", "bottom", "left")}, + "align": {align: {} for align in ("start", "center", "end")}, + }, + } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py index f11a2c24126..d4bb215a150 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py @@ -8,7 +8,7 @@ from reflex_components_ui.style import ComponentStyles, unchecked from reflex_components_ui.styles.appearance import by_appearance from reflex_components_ui.styles.button import _CLASSIC_DISABLED_SHADOW -from reflex_components_ui.styles.popup import OPENS, POPUP, placements +from reflex_components_ui.styles.popup import OPENS, SDK_POPUP from reflex_components_ui.tokens import Step9 accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black @@ -43,6 +43,8 @@ _DISABLED = ":disabled" _FOCUS = ":focus-visible" _EMPTY = "[data-placeholder]" +# The option UI SDK highlights: the one the keys or the pointer are on. +_HIGHLIGHTED = "[data-highlighted]" _OPEN = f"{OPENS}:not(:disabled)" _CLASSIC_SHADOW = by_appearance( @@ -353,7 +355,7 @@ def _content_size( SELECT_CONTENT: ComponentStyles = { "base": unchecked({ - **POPUP, + **SDK_POPUP, "color": gray[12], "font_family": tokens.default.font_family, "font_weight": tokens.font_weight.regular, @@ -361,7 +363,7 @@ def _content_size( "text_align": "start", "background_color": tokens.color.panel_solid, "box_shadow": tokens.shadow[5], - "min_width": "anchor-size(width)", + "min_width": "var(--anchor-width)", "outline_style": "none", "padding": f"var({_PADDING})", "overflow_y": "auto", @@ -393,12 +395,8 @@ def _content_size( "side": {"top": {}, "right": {}, "bottom": {}, "left": {}}, "align": {"start": {}, "center": {}, "end": {}}, }, - "defaults": {"_size": "2", "variant": "solid", "side": "bottom", "align": "start"}, + "defaults": {"_size": "2", "variant": "solid"}, "compound": [ - *( - {"props": place["props"], "style": unchecked(place["style"])} - for place in placements("4px") - ), { "props": {"variant": "solid", "high_contrast": "true"}, "style": unchecked({_MARK: accent[12], _MARK_COLOR: accent[1]}), @@ -421,10 +419,10 @@ def _content_size( }, "color": { "default": "inherit", - ":focus": f"var({_MARK_COLOR}, inherit)", + _HIGHLIGHTED: f"var({_MARK_COLOR}, inherit)", "[aria-disabled='true']": gray.a[8], }, - "background_color": {":focus": f"var({_MARK})"}, + "background_color": {_HIGHLIGHTED: f"var({_MARK})"}, "--rx-select-check": { "default": "none", "[aria-selected='true']": "inline-flex", @@ -471,20 +469,3 @@ def _content_size( "background_color": gray.a[6], }), } - -# The input that holds the value of a select, for a form: not seen, and not -# in the way of the pointer. -SELECT_VALUE: ComponentStyles = { - "base": { - "position": "absolute", - "width": "1px", - "height": "1px", - "margin": "0", - "padding": "0", - "border_width": "0", - "opacity": 0, - "pointer_events": "none", - }, -} - -SELECT: ComponentStyles = {"base": {"display": "contents"}} diff --git a/pyi_hashes.json b/pyi_hashes.json index 23dc8d8878a..86436ce7798 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -121,13 +121,13 @@ "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "7adaf4068a85572198f646ae8009e51b", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", - "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "0d7b27ab1cb51ac891a31ed97f2f5567", + "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "5233a0a9b63e556c33ee473db5fafdbe", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "817a2b853123734c7e200bc54a55c47a", "packages/reflex-components-ui/src/reflex_components_ui/components/_menu.pyi": "c243405a64e5dd76eef6bef0492ac75a", "packages/reflex-components-ui/src/reflex_components_ui/components/_popup.pyi": "80f094441cee591fff2e06d6e315dcc0", - "packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.pyi": "2fab3b573275566745f45149bf62b695", + "packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.pyi": "e5dbd83eb0448e016944c5937bee2b34", "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", - "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "4abb8482e413aa9ee3d941ef12878c1a", + "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "8116a4bc68a3d9607dfc44aa5f15dc22", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "296a02d4f7a276a0548ec473a6c761a9", "packages/reflex-components-ui/src/reflex_components_ui/components/badge.pyi": "f54c7d6d2a403389eb7424f7024bb847", @@ -140,20 +140,20 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.pyi": "b914252f1bc53816d7c5384faea6d2b5", "packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.pyi": "79193f172cbb6feb749a296f82af9814", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", - "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "e3e684a6fd6424c43648acd2fafa39af", - "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "cdaeaac954b4ff1100878d46b5649143", - "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "bce2a2c1da692e84ed14f347dce2a69c", + "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "841323f7bbdbc96b7646be3d89ef4dda", + "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "bb3fcfaae77fb8388155a6df7ba55cb4", + "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "bf39517cc33ac99186bfd946aa1e6e3a", "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", "packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.pyi": "866327d09399a8a3f632f93a36014ebb", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", - "packages/reflex-components-ui/src/reflex_components_ui/components/popover.pyi": "f50b0a5a30a0331f2a8e5dc28d8763cf", + "packages/reflex-components-ui/src/reflex_components_ui/components/popover.pyi": "aa73f98a1067248acfd40992795ec9ac", "packages/reflex-components-ui/src/reflex_components_ui/components/progress.pyi": "ba32f562c590556d634f16062120fa34", "packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.pyi": "0a0f621c1ceed962d86896ad1600e98f", "packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.pyi": "e7f9c6ffd5f3d882ebe2fa4c06c0bcd0", "packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.pyi": "0b9bb867b1ef68c0fd9b10d52867d2b8", "packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.pyi": "6c4bcbd1e1d2ee3effda901ad208fe56", - "packages/reflex-components-ui/src/reflex_components_ui/components/select.pyi": "7c9b56d6cbf55e8bed5ef1d262b115d0", + "packages/reflex-components-ui/src/reflex_components_ui/components/select.pyi": "eaab855301c61446950f54f84cf25e39", "packages/reflex-components-ui/src/reflex_components_ui/components/separator.pyi": "bd32f08f7c0ff2cb6733f964ea843440", "packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.pyi": "4bedd989efb5b095b943a04830bbd140", "packages/reflex-components-ui/src/reflex_components_ui/components/slider.pyi": "b5702134bebf0337effc41e3ddeffda8", diff --git a/tests/units/reflex_components_ui/components/test_alert_dialog.py b/tests/units/reflex_components_ui/components/test_alert_dialog.py index fe81f8e30f8..4c57e57a2b5 100644 --- a/tests/units/reflex_components_ui/components/test_alert_dialog.py +++ b/tests/units/reflex_components_ui/components/test_alert_dialog.py @@ -1,276 +1,87 @@ """Tests for reflex_components_ui.components.alert_dialog.""" -import itertools -from collections.abc import Callable -from typing import Any - -import pytest -from reflex_components_ui.components import _dialog from reflex_components_ui.plugin import UIPlugin import reflex as rx +from tests.units.reflex_components_ui.render import tree -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the dialogs of each test from one.""" - monkeypatch.setattr(_dialog, "_ids", itertools.count(1)) - +def test_alert_dialog(ui_plugin: UIPlugin): + """An alert dialog is the parts of UI SDK: its cancel button takes the focus, as in Radix. -def test_alert_dialog( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """An alert dialog is a native dialog with the role of one, which a press beside its panel does not dismiss; what cancels it is marked, and takes the focus when the dialog opens.""" + The action and the cancel button are UI SDK's close buttons; the action + reports that it confirmed. + """ component = rx.ui.alert_dialog.root( rx.ui.alert_dialog.trigger(rx.el.button("Delete")), rx.ui.alert_dialog.content( - rx.ui.alert_dialog.title("Delete the file"), - rx.ui.alert_dialog.description("It cannot be brought back."), - rx.ui.alert_dialog.action(rx.el.button("Delete it")), - rx.ui.alert_dialog.cancel(rx.el.button("Keep it")), - size="1", + rx.ui.alert_dialog.title("Sure?"), + rx.ui.alert_dialog.description("It goes."), + rx.ui.alert_dialog.cancel(rx.el.button("Keep")), + rx.ui.alert_dialog.action(rx.el.button("Delete")), + size="2", force_mount=True, - on_escape_key_down=rx.console_log("escape"), ), - on_open_change=rx.console_log("changed"), + default_open=True, ) - assert component.render() == { - "name": '"div"', - "props": [ - "className:sx_71b84cd269_c", - '"data-rx-dialog-root":""', - "onClick:dialogClick", - ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-dialog-1"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - 'command:"show-modal"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - ], - "children": [{"contents": '"Delete"'}], - }, - { - "name": '"dialog"', - "props": [ - '"aria-describedby":"rx-dialog-1-describedby"', - '"aria-labelledby":"rx-dialog-1-labelledby"', - "className:sx_826e1f6eca_c", - '"data-rx-keep":"outside"', - '"data-rx-popup":""', - 'id:"rx-dialog-1"', - "onCancel:dialogEvent", - "onClose:dialogEvent", - 'ref:((dialog) => dialogSync(dialog, null, ({ open: ((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("changed"))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))), escape: ((...args) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("escape"))), ["callback"] : null }), ({ })))], args, ({ })))) })))', - 'role:"alertdialog"', - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_18e4ad36e3_c", - '"data-rx-dialog-pad":""', + assert tree(component.render()) == ( + "AlertDialog", + ["defaultOpen:true"], + [ + ("AlertDialogTrigger", ['render:(jsx("button", ({}), "Delete"))'], []), + ( + "Fragment", + [], + [ + ("AlertDialogBackdrop", ["className:sx_dd9768c199_c"], []), + ( + "AlertDialogContent", + [ + "className:sx_b7708e6de5_c", + 'initialFocus:"[data-rx-cancel]"', + "keepMounted:true", ], - "children": [ - { - "name": '"div"', - "props": ["className:sx_849936ac28_c"], - "children": [ - { - "name": '"h1"', - "props": [ - "className:sx_29271ef72f_c", - 'id:"rx-dialog-1-labelledby"', - ], - "children": [{"contents": '"Delete the file"'}], - }, - { - "name": '"p"', - "props": [ - "className:sx_9b5373509f_c", - 'id:"rx-dialog-1-describedby"', - ], - "children": [ - {"contents": '"It cannot be brought back."'} - ], - }, - { - "name": '"button"', - "props": [ - 'command:"close"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-close":""', - ], - "children": [{"contents": '"Delete it"'}], - }, - { - "name": '"button"', - "props": [ - 'command:"close"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-close":"cancel"', - ], - "children": [{"contents": '"Keep it"'}], - }, + [ + ( + "AlertDialogTitle", + [ + "className:sx_29271ef72f_c", + 'render:(jsx("h1", ({})))', + ], + ['"Sure?"'], + ), + ( + "AlertDialogDescription", + ["className:sx_9b5373509f_c"], + ['"It goes."'], + ), + ( + "AlertDialogClose", + [ + '"data-rx-cancel":""', + 'render:(jsx("button", ({}), "Keep"))', ], - } + [], + ), + ( + "AlertDialogClose", + [ + 'render:(jsx("button", ({}), "Delete"))', + 'value:"confirm"', + ], + [], + ), ], - } + ), ], - }, + ), ], - } - assert declared_styles(component) == [ - {"display": "contents"}, - {}, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": { - "default": "transparent", - "::backdrop": "transparent", - "::before": "var(--color-overlay)", - }, - "color": "inherit", - "maxWidth": "none", - "maxHeight": "none", - "outlineStyle": "none", - "userSelect": "auto", - "transitionProperty": { - "default": "display, overlay", - "::before": "opacity", - }, - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", - "::before": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": "var(--rx-dialog-duration)", - }, - }, - "--rx-dialog-shown": {"default": 0, "[open]": 1}, - "position": {"default": "fixed", "::before": "fixed"}, - "top": {"default": "0", "::before": "0"}, - "right": {"default": "0", "::before": "0"}, - "bottom": {"default": "0", "::before": "0"}, - "left": {"default": "0", "::before": "0"}, - "width": "100%", - "height": "100%", - "display": {"default": "none", "[open]": "flex"}, - "overflowX": "auto", - "overflowY": "auto", - "--rx-dialog-gone": { - "default": "translateY(5px) scale(0.99)", - "[open]": "none", - }, - "--rx-dialog-duration": {"default": "160ms", "[open]": "200ms"}, - "content": {"::before": "''"}, - "opacity": { - "::before": { - "default": 0, - "[open]": {"default": 1, "@starting-style": 0}, - } - }, - "transitionTimingFunction": {"::before": "cubic-bezier(0.16, 1, 0.3, 1)"}, - }, - { - "flexGrow": 1, - "marginTop": "auto", - "marginRight": "auto", - "marginBottom": "auto", - "marginLeft": "auto", - "paddingTop": "var(--space-6)", - "paddingBottom": "max(var(--space-6), 6vh)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - }, - { - "marginTop": "auto", - "marginRight": "auto", - "marginBottom": "auto", - "marginLeft": "auto", - "width": "100%", - "maxWidth": "600px", - "zIndex": 1, - "position": "relative", - "boxSizing": "border-box", - "overflowX": "auto", - "overflowY": "auto", - "--inset-padding-top": "var(--dialog-content-padding)", - "--inset-padding-right": "var(--dialog-content-padding)", - "--inset-padding-bottom": "var(--dialog-content-padding)", - "--inset-padding-left": "var(--dialog-content-padding)", - "padding": "var(--dialog-content-padding)", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-6)", - "outlineStyle": "none", - "opacity": {"default": "var(--rx-dialog-shown)", "@starting-style": 0}, - "transform": { - "default": "var(--rx-dialog-gone)", - "@starting-style": "translateY(5px) scale(0.97)", - }, - "transitionProperty": "opacity, transform", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": "calc(100ms + var(--rx-dialog-shown) * 100ms)", - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "--dialog-content-padding": "var(--space-3)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - }, - { - "--leading-trim-start": "var(--heading-leading-trim-start)", - "--leading-trim-end": "var(--heading-leading-trim-end)", - "fontFamily": "var(--heading-font-family)", - "fontStyle": "var(--heading-font-style)", - "fontWeight": "var(--font-weight-bold)", - "lineHeight": "var(--line-height)", - "marginTop": "0", - "marginRight": "0", - "marginBottom": { - "default": "var(--space-3)", - "::before": "calc(var(--leading-trim-start, var(--default-leading-trim-start)) - var(--line-height, calc(1em * var(--default-line-height))) / 2)", - }, - "marginLeft": "0", - "fontSize": "calc(var(--font-size-5) * var(--heading-font-size-adjust))", - "--line-height": "var(--heading-line-height-5)", - "letterSpacing": "calc(var(--letter-spacing-5) + var(--heading-letter-spacing))", - "content": {"::before": "''", "::after": "none"}, - "display": {"::before": "table"}, - }, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "lineHeight": "var(--line-height, var(--default-line-height))", - "letterSpacing": "var(--letter-spacing, inherit)", - "fontSize": "var(--font-size-3)", - "--line-height": "var(--line-height-3)", - "--letter-spacing": "var(--letter-spacing-3)", - }, - {}, - {}, - ] + ) + + +def test_alert_dialog_without_a_cancel_button(ui_plugin: UIPlugin): + """Without a cancel button, UI SDK gives the focus to the first button that closes it.""" + component = rx.ui.alert_dialog.content( + rx.ui.alert_dialog.action(rx.el.button("Fine")) + ) + assert tree(component.render())[2][1][1] == ["className:sx_ee062dec20_c"] diff --git a/tests/units/reflex_components_ui/components/test_dialog.py b/tests/units/reflex_components_ui/components/test_dialog.py index 5d0d5604ab9..83e367a70d2 100644 --- a/tests/units/reflex_components_ui/components/test_dialog.py +++ b/tests/units/reflex_components_ui/components/test_dialog.py @@ -120,9 +120,11 @@ def test_dialog_bound_to_state(ui_plugin: UIPlugin): '(() => (console?.["log"]("in"))), ["callback"] : null }), ({ })))], ' "args, ({ })))), closeAutoFocus = undefined, escape = ((...args) => " f'(addEvents([(ReflexEvent({handler}, ({{ ["open"] : false }}), ' - "({ })))], args, ({ })))), outside = undefined, interact = undefined; " + "({ })))], args, ({ })))), outside = undefined, " + "focusOutside = undefined, interact = undefined; " 'if (details?.reason === "escape-key") escape?.(); ' 'if (details?.reason === "outside-press") { outside?.(); interact?.(); } ' + 'if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); } ' "change?.(value); if (value) openAutoFocus?.(); else closeAutoFocus?.(); })" ), ( diff --git a/tests/units/reflex_components_ui/components/test_drawer.py b/tests/units/reflex_components_ui/components/test_drawer.py index 75b9d881893..e0004c4613e 100644 --- a/tests/units/reflex_components_ui/components/test_drawer.py +++ b/tests/units/reflex_components_ui/components/test_drawer.py @@ -1,414 +1,103 @@ """Tests for reflex_components_ui.components.drawer.""" -import itertools -from collections.abc import Callable -from typing import Any - -import pytest -from reflex_components_ui.components import _dialog from reflex_components_ui.plugin import UIPlugin import reflex as rx +from tests.units.reflex_components_ui.render import tree + +STATE = ( + "tests___units___reflex_components_ui___components___test_drawer____drawer_state" +) + + +class DrawerState(rx.State): + """What a drawer reports to.""" + settled: bool = False -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the drawers of each test from one.""" - monkeypatch.setattr(_dialog, "_ids", itertools.count(1)) + @rx.event + def set_settled(self, settled: bool): + """Follow the drawer. + Args: + settled: Whether it is open, once it has slid. + """ + self.settled = settled -def test_drawer( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A drawer is a native dialog around the panel an app styles, which slides in from the edge the root names; its overlay is an element of its own beside it, and its portal is nothing.""" + +def test_drawer(ui_plugin: UIPlugin): + """A drawer is the parts of UI SDK: the edge it comes from is its side. + + The props of vaul UI SDK has no use for are left out, the end of its + slide is UI SDK's ``onOpenChangeComplete``, a portal is nothing, and a + close button told not to render as its child is a button of its own. + """ component = rx.ui.drawer.root( rx.ui.drawer.trigger(rx.el.button("Open")), - rx.ui.drawer.overlay(z_index="5"), rx.ui.drawer.portal( + rx.ui.drawer.overlay(), rx.ui.drawer.content( rx.ui.drawer.handle(), - rx.ui.drawer.title("Settings"), - rx.ui.drawer.description("What it is about."), - rx.ui.drawer.close(rx.el.button("Close")), - right="auto", - width="20em", - background_color="white", - ) + rx.ui.drawer.title("Files"), + rx.ui.drawer.description("Yours."), + rx.ui.drawer.close("Done", as_child=False), + ), ), direction="left", - on_animation_end=rx.console_log("moved"), + modal=False, + dismissible=False, + handle_only=True, + snap_points=[0.5, 1], + on_animation_end=DrawerState.set_settled, ) - assert component.render() == { - "name": '"div"', - "props": [ - "className:sx_71b84cd269_c", - '"data-rx-dialog-root":""', - "onClick:dialogClick", + assert tree(component.render()) == ( + "Drawer", + [ + "dismissible:false", + "modal:false", + ( + "onOpenChangeComplete:((_ev_0) => (addEvents([(ReflexEvent(" + f'"reflex___state____state.{STATE}.set_settled", ' + '({ ["settled"] : _ev_0 }), ({ })))], [_ev_0], ({ }))))' + ), + 'side:"left"', + "snapPoints:[0.5, 1]", ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-dialog-1"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - 'command:"show-modal"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - ], - "children": [{"contents": '"Open"'}], - }, - { - "name": '"div"', - "props": ["className:sx_92fd57a6ed_c", '"data-rx-popup":""'], - "children": [], - }, - { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"dialog"', - "props": [ - '"aria-describedby":"rx-dialog-1-describedby"', - '"aria-labelledby":"rx-dialog-1-labelledby"', - "className:sx_a309248e5f_c", - '"data-rx-popup":""', - 'id:"rx-dialog-1"', - "onCancel:dialogEvent", - "onClose:dialogEvent", - 'onTransitionEnd:((event) => event.propertyName === "transform" && event.target.parentElement === event.currentTarget && (((_ev_0) => (addEvents([(ReflexEvent("_call_function", ({ ["function"] : (() => (console?.["log"]("moved"))), ["callback"] : null }), ({ })))], [_ev_0], ({ })))))(event.currentTarget.open))', - "ref:((dialog) => dialogSync(dialog, null, null))", - "tabIndex:-1", - ], - "children": [ - { - "name": '"div"', - "props": ["className:sx_e8c44019a7_c"], - "children": [ - { - "name": '"div"', - "props": [ + [ + ("DrawerTrigger", ['render:(jsx("button", ({}), "Open"))'], []), + ( + "Fragment", + [], + [ + ("DrawerBackdrop", ["className:sx_165a6b083a_c"], []), + ( + "DrawerContent", + ["className:sx_e2d63de2b0_c"], + [ + ( + "DrawerHandle", + ["className:sx_c352e99684_c"], + [ + ( + '"span"', + [ '"aria-hidden":true', - "className:sx_c352e99684_c", - ], - "children": [ - { - "name": '"span"', - "props": [ - '"aria-hidden":true', - "className:sx_90a94c0153_c", - ], - "children": [], - } - ], - }, - { - "name": '"h2"', - "props": [ - "className:sx_0590ef4057_c", - 'id:"rx-dialog-1-labelledby"', - ], - "children": [{"contents": '"Settings"'}], - }, - { - "name": '"p"', - "props": [ - "className:sx_faadb9eee6_c", - 'id:"rx-dialog-1-describedby"', + "className:sx_90a94c0153_c", ], - "children": [ - {"contents": '"What it is about."'} - ], - }, - { - "name": '"button"', - "props": [ - 'command:"close"', - 'commandfor:"rx-dialog-1"', - '"data-rx-dialog-close":""', - ], - "children": [{"contents": '"Close"'}], - }, + [], + ) ], - } + ), + ("DrawerTitle", ["className:sx_0590ef4057_c"], ['"Files"']), + ( + "DrawerDescription", + ["className:sx_faadb9eee6_c"], + ['"Yours."'], + ), + ("DrawerClose", [], ['"Done"']), ], - } + ), ], - }, + ), ], - } - assert declared_styles(component) == [ - {"display": "contents"}, - {}, - { - "position": "fixed", - "left": "0", - "right": "0", - "bottom": "0", - "top": "0", - "zIndex": "5", - "backgroundColor": "rgba(0, 0, 0, 0.5)", - "transitionProperty": "opacity, display", - "transitionDuration": "0.5s", - "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", - "display": { - "default": "none", - ":is(:has(~ dialog[open]), dialog[open] ~ *)": "block", - }, - "opacity": { - "default": 0, - ":is(:has(~ dialog[open]), dialog[open] ~ *)": { - "default": 1, - "@starting-style": 0, - }, - }, - }, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": {"default": "transparent", "::backdrop": "transparent"}, - "color": "inherit", - "maxWidth": "none", - "maxHeight": "none", - "outlineStyle": "none", - "userSelect": "auto", - "transitionProperty": "display, overlay", - "transitionDuration": "0.55s", - "--rx-dialog-shown": {"default": 0, "[open]": 1}, - "position": "fixed", - "top": "0", - "right": "0", - "bottom": "0", - "left": "0", - "width": "100%", - "height": "100%", - "zIndex": 50, - "display": {"default": "none", "[open]": "block"}, - "--rx-drawer-place": {"default": "var(--rx-drawer-away)", "[open]": "none"}, - "--rx-drawer-away": "translate3d(-100%, 0, 0)", - }, - { - "left": "0", - "right": {"default": "auto", "::after": "100%"}, - "bottom": {"default": "0", "::after": "0"}, - "top": {"default": "0", "::after": "0"}, - "position": {"default": "fixed", "::after": "absolute"}, - "zIndex": 50, - "display": "flex", - "pointerEvents": "auto", - "touchAction": "none", - "willChange": "transform", - "userSelect": {"@media (hover: hover) and (pointer: fine)": "none"}, - "transform": { - "default": "var(--rx-drawer-place)", - "@starting-style": "var(--rx-drawer-away)", - }, - "transitionProperty": "transform", - "transitionDuration": "0.5s", - "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", - "content": {"::after": "''"}, - "backgroundColor": {"default": "white", "::after": "inherit"}, - "backgroundImage": {"::after": "inherit"}, - "width": {"default": "20em", "::after": "200%"}, - }, - { - "display": "block", - "position": "relative", - "opacity": {"default": 0.7, ":hover": 1, ":active": 1}, - "backgroundColor": "#e2e2e4", - "marginLeft": "auto", - "marginRight": "auto", - "height": "5px", - "width": "32px", - "borderTopLeftRadius": "1rem", - "borderTopRightRadius": "1rem", - "borderBottomRightRadius": "1rem", - "borderBottomLeftRadius": "1rem", - "touchAction": "pan-y", - }, - { - "position": "absolute", - "left": "50%", - "top": "50%", - "transform": "translate(-50%, -50%)", - "width": "max(100%, 2.75rem)", - "height": "max(100%, 2.75rem)", - "touchAction": "inherit", - }, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "fontSize": "1.125rem", - "fontWeight": "600", - "lineHeight": "1", - "letterSpacing": "-0.05em", - }, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "fontSize": "0.875rem", - }, - {}, - ] - - -def test_drawer_that_is_not_modal_nor_dismissible( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A drawer that is not modal lets the pointer through beside its panel and has no overlay, one that is not dismissible says so to its script, and a trigger that is not its child is a button.""" - component = rx.ui.drawer.root( - rx.ui.drawer.trigger("Open", as_child=False), - rx.ui.drawer.overlay(), - rx.ui.drawer.content("Inside"), - modal=False, - dismissible=False, - snap_points=["148px", 1], ) - assert component.render() == { - "name": '"div"', - "props": [ - "className:sx_71b84cd269_c", - '"data-rx-dialog-root":""', - "onClick:dialogClick", - ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-dialog-1"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - '"data-rx-dialog-trigger":""', - '"data-state":"closed"', - 'type:"button"', - ], - "children": [{"contents": '"Open"'}], - }, - { - "name": '"div"', - "props": ["className:sx_10d19d24da_c", '"data-rx-popup":""'], - "children": [], - }, - { - "name": '"dialog"', - "props": [ - "className:sx_26229be874_c", - '"data-modal":"false"', - '"data-rx-keep":"all"', - '"data-rx-popup":""', - 'id:"rx-dialog-1"', - "onCancel:dialogEvent", - "onClose:dialogEvent", - "ref:((dialog) => dialogSync(dialog, null, null))", - "tabIndex:-1", - ], - "children": [ - { - "name": '"div"', - "props": ["className:sx_b169a25bca_c"], - "children": [{"contents": '"Inside"'}], - } - ], - }, - ], - } - assert declared_styles(component) == [ - {"display": "contents"}, - {}, - { - "position": "fixed", - "left": "0", - "right": "0", - "bottom": "0", - "top": "0", - "zIndex": 50, - "backgroundColor": "rgba(0, 0, 0, 0.5)", - "transitionProperty": "opacity, display", - "transitionDuration": "0.5s", - "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", - "display": "none", - }, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": {"default": "transparent", "::backdrop": "transparent"}, - "color": "inherit", - "maxWidth": "none", - "maxHeight": "none", - "outlineStyle": "none", - "userSelect": "auto", - "transitionProperty": "display, overlay", - "transitionDuration": "0.55s", - "--rx-dialog-shown": {"default": 0, "[open]": 1}, - "position": "fixed", - "top": "0", - "right": "0", - "bottom": "0", - "left": "0", - "width": "100%", - "height": "100%", - "zIndex": 50, - "display": {"default": "none", "[open]": "block"}, - "--rx-drawer-place": {"default": "var(--rx-drawer-away)", "[open]": "none"}, - "--rx-drawer-away": "translate3d(0, 100%, 0)", - "pointerEvents": "none", - }, - { - "left": {"default": "0", "::after": "0"}, - "right": {"default": "0", "::after": "0"}, - "bottom": "0", - "top": {"default": "0", "::after": "100%"}, - "position": {"default": "fixed", "::after": "absolute"}, - "zIndex": 50, - "display": "flex", - "pointerEvents": "auto", - "touchAction": "none", - "willChange": "transform", - "userSelect": {"@media (hover: hover) and (pointer: fine)": "none"}, - "transform": { - "default": "var(--rx-drawer-place)", - "@starting-style": "var(--rx-drawer-away)", - }, - "transitionProperty": "transform", - "transitionDuration": "0.5s", - "transitionTimingFunction": "cubic-bezier(0.32, 0.72, 0, 1)", - "content": {"::after": "''"}, - "backgroundColor": {"::after": "inherit"}, - "backgroundImage": {"::after": "inherit"}, - "height": {"::after": "200%"}, - }, - ] diff --git a/tests/units/reflex_components_ui/components/test_dropdown_menu.py b/tests/units/reflex_components_ui/components/test_dropdown_menu.py index da6496f08bb..c8f6591d44c 100644 --- a/tests/units/reflex_components_ui/components/test_dropdown_menu.py +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -103,7 +103,7 @@ def test_dropdown_menu(ui_plugin: UIPlugin): "MenuContent", [ 'align:"start"', - "className:sx_c3f4b8c3e8_c", + "className:sx_8c7d332986_c", "collisionPadding:10", 'side:"top"', "sideOffset:8", @@ -125,7 +125,7 @@ def test_dropdown_menu(ui_plugin: UIPlugin): ("MenuSeparator", ["className:sx_834f03d11d_c"], []), ( "MenuSub", - [], + ["loop:false"], [ ( "MenuSubTrigger", @@ -143,7 +143,7 @@ def test_dropdown_menu(ui_plugin: UIPlugin): "MenuSubContent", [ "alignOffset:-4", - "className:sx_6df86afa34_c", + "className:sx_d3add7826b_c", "collisionPadding:10", "sideOffset:1", ], @@ -257,10 +257,12 @@ def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): assert _tree(component.render()) == ( "Menu", [ + "loop:false", ( "onOpenChange:((value, details) => { const change = ((_ev_0) => " f'(addEvents([(ReflexEvent({handler}, ({{ ["shown"] : _ev_0 }}), ' - "({ })))], [_ev_0], ({ })))), closeAutoFocus = undefined, " + "({ })))], [_ev_0], ({ })))), openAutoFocus = undefined, " + "closeAutoFocus = undefined, " 'escape = ((...args) => (addEvents([(ReflexEvent("_call_function", ' '({ ["function"] : (() => (console?.["log"]("esc"))), ' '["callback"] : null }), ({ })))], args, ({ })))), ' @@ -268,7 +270,8 @@ def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): 'if (details?.reason === "escape-key") escape?.(); ' 'if (details?.reason === "outside-press") { outside?.(); interact?.(); } ' 'if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); } ' - "change?.(value); if (!value) closeAutoFocus?.(); })" + "change?.(value); if (value) openAutoFocus?.(); else " + "closeAutoFocus?.(); })" ), ( "open:reflex___state____state__tests___units___reflex_components_ui___" @@ -280,7 +283,7 @@ def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): "MenuContent", [ 'align:"start"', - "className:sx_34247d117f_c", + "className:sx_ab8a2d3de6_c", "collisionPadding:10", 'side:"bottom"', "sideOffset:4", diff --git a/tests/units/reflex_components_ui/components/test_popover.py b/tests/units/reflex_components_ui/components/test_popover.py index 52c5be1d031..945429f6741 100644 --- a/tests/units/reflex_components_ui/components/test_popover.py +++ b/tests/units/reflex_components_ui/components/test_popover.py @@ -1,243 +1,26 @@ """Tests for reflex_components_ui.components.popover.""" -import itertools from collections.abc import Callable from typing import Any, get_args import pytest from reflex_base.utils.imports import ImportVar -from reflex_components_ui.components import _popup from reflex_components_ui.components.popover import PopoverContent from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree - -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the popups of each test from one.""" - monkeypatch.setattr(_popup, "_ids", itertools.count(1)) - - -def test_popover( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A popover is a native popover right after its trigger, which the browser opens it from; the root is nothing in the page, and the close button closes the popover without a script.""" - component = rx.ui.popover.root( - rx.ui.popover.trigger(rx.el.button("Open", id="open")), - rx.ui.popover.content( - "Inside", - rx.ui.popover.close(rx.el.button("Close")), - size="1", - side="top", - align="end", - side_offset=4, - align_offset=2, - collision_padding=20, - avoid_collisions=False, - max_width="300px", - ), - default_open=True, - modal=True, - ) - assert component.render() == { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"rx-popover-1"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - '"data-state":"closed"', - 'id:"open"', - 'popoverTarget:"rx-popover-1"', - "ref:ref_open", - ], - "children": [{"contents": '"Open"'}], - }, - { - "name": '"div"', - "props": [ - "className:sx_2fbab4a681_c", - '"data-default-open":true', - '"data-rx-popup":""', - 'id:"rx-popover-1"', - "onBeforeToggle:((event) => { (popupEvent)(event); (popupBeforeToggle)(event); })", - "onBlur:popupEvent", - "onClick:popupEvent", - "onKeyDown:popupEvent", - "onToggle:popupEvent", - 'popover:"auto"', - "ref:((popup) => popupSync(popup, null))", - 'role:"dialog"', - "tabIndex:-1", - ], - "children": [ - {"contents": '"Inside"'}, - { - "name": '"button"', - "props": [ - 'popoverTarget:"rx-popover-1"', - 'popoverTargetAction:"hide"', - ], - "children": [{"contents": '"Close"'}], - }, - ], - }, - ], - } - assert declared_styles(component) == [ - {}, - {}, - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "calc(10px + var(--rx-popup-snap-y, 0px))", - "marginRight": "calc(var(--rx-popup-shift, 0px) - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(var(--rx-popup-offset, 8px) - var(--rx-popup-snap-y, 0px))", - "marginLeft": "var(--rx-popup-snap-x, 0px)", - "padding": "var(--popover-content-padding)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "300px", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "100ms", - ":popover-open": "160ms", - }, - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "inherit", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-5)", - "minWidth": "anchor-size(width)", - "outlineStyle": "none", - "outlineWidth": "0", - "overflowX": "auto", - "overflowY": "auto", - "--inset-padding-top": "var(--popover-content-padding)", - "--inset-padding-right": "var(--popover-content-padding)", - "--inset-padding-bottom": "var(--popover-content-padding)", - "--inset-padding-left": "var(--popover-content-padding)", - "--popover-content-padding": "var(--space-3)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "positionArea": "top span-left", - "maxHeight": "calc(100% - var(--rx-popup-offset, 8px) - 10px)", - "--rx-popup-from": "translateY(4px) scale(0.97)", - "transformOrigin": "bottom right", - "--rx-popup-offset": "4px", - "--rx-popup-shift": "2px", - }, - {}, - ] - - -def test_popover_with_an_id(ui_plugin: UIPlugin): - """A popover that is given an id is named by it, and one outside a root is a popover nothing opens.""" - component = rx.el.div( - rx.ui.popover.root( - rx.ui.popover.trigger(rx.el.button("Open")), - rx.ui.popover.content("Inside", id="panel"), - ), - rx.ui.popover.content("Alone"), - ) - assert component.render() == { - "name": '"div"', - "props": [], - "children": [ - { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-controls":"panel"', - '"aria-expanded":false', - '"aria-haspopup":"dialog"', - '"data-state":"closed"', - 'popoverTarget:"panel"', - ], - "children": [{"contents": '"Open"'}], - }, - { - "name": '"div"', - "props": [ - "className:sx_8dd6075b6b_c", - '"data-rx-popup":""', - 'id:"panel"', - "onBeforeToggle:((event) => { (popupEvent)(event); (popupBeforeToggle)(event); })", - "onBlur:popupEvent", - "onClick:popupEvent", - "onKeyDown:popupEvent", - "onToggle:popupEvent", - 'popover:"auto"', - "ref:((popup) => popupSync(popup, null))", - 'role:"dialog"', - "tabIndex:-1", - ], - "children": [{"contents": '"Inside"'}], - }, - ], - }, - { - "name": '"div"', - "props": [ - "className:sx_8dd6075b6b_c", - '"data-rx-popup":""', - "onBeforeToggle:((event) => { (popupEvent)(event); (popupBeforeToggle)(event); })", - "onBlur:popupEvent", - "onClick:popupEvent", - "onKeyDown:popupEvent", - "onToggle:popupEvent", - 'popover:"auto"', - "ref:((popup) => popupSync(popup, null))", - 'role:"dialog"', - "tabIndex:-1", - ], - "children": [{"contents": '"Alone"'}], - }, - ], - } +STATE = ( + "tests___units___reflex_components_ui___components___test_popover____popover_state" +) class PopoverState(rx.State): """What a popover is bound to.""" shown: bool = False - gap: int = 6 @rx.event def set_shown(self, shown: bool): @@ -248,62 +31,85 @@ def set_shown(self, shown: bool): """ self.shown = shown - @rx.event - def note(self): - """Hear that something happened to the popover.""" +def test_popover(ui_plugin: UIPlugin): + """A popover is the parts of UI SDK, placed as Radix Themes places it. -def test_popover_bound_to_state(ui_plugin: UIPlugin): - """A popover bound to state hands its script its state and what it does when it opens, closes or is dismissed, and an offset bound to state is a custom property.""" - name = PopoverState.get_full_name() + The events of a dismissal are called by the reason UI SDK gives for a + change, and the props of Radix's placement that UI SDK does not have are + left out. + """ component = rx.ui.popover.root( rx.ui.popover.trigger(rx.el.button("Open")), rx.ui.popover.content( - "x", - side_offset=PopoverState.gap, - on_focus_outside=PopoverState.note, + "Hi", + rx.ui.popover.close(rx.el.button("Close")), + size="1", + side="top", + side_offset=12, + avoid_collisions=False, + on_escape_key_down=PopoverState.set_shown(False), ), open=PopoverState.shown, on_open_change=PopoverState.set_shown, + modal=True, ) - rendered = component.render() - assert (rendered["name"], rendered["props"]) == ("Fragment", []) - on = ( - f'({{ open: ((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' - '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))), focusOutside: ' - f'((...args) => (addEvents([(ReflexEvent("{name}.note", ({{ }}), ' - "({ })))], args, ({ })))) })" + handler = f'"reflex___state____state.{STATE}.set_shown"' + assert tree(component.render()) == ( + "Popover", + [ + "modal:true", + ( + "onOpenChange:((value, details) => { const change = ((_ev_0) => " + f'(addEvents([(ReflexEvent({handler}, ({{ ["shown"] : _ev_0 }}), ' + "({ })))], [_ev_0], ({ })))), openAutoFocus = undefined, " + "closeAutoFocus = undefined, escape = ((...args) => " + f'(addEvents([(ReflexEvent({handler}, ({{ ["shown"] : false }}), ' + "({ })))], args, ({ })))), outside = undefined, " + "focusOutside = undefined, interact = undefined; " + 'if (details?.reason === "escape-key") escape?.(); ' + 'if (details?.reason === "outside-press") { outside?.(); interact?.(); } ' + 'if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); } ' + "change?.(value); if (value) openAutoFocus?.(); else closeAutoFocus?.(); })" + ), + f"open:reflex___state____state__{STATE}.shown_rx_state_", + ], + [ + ("PopoverTrigger", ['render:(jsx("button", ({}), "Open"))'], []), + ( + "PopoverContent", + [ + 'align:"start"', + "className:sx_cdfecf0b21_c", + "collisionPadding:10", + 'side:"top"', + "sideOffset:12", + ], + [ + '"Hi"', + ("PopoverClose", ['render:(jsx("button", ({}), "Close"))'], []), + ], + ), + ], ) - assert rendered["children"][1]["props"] == [ - "className:sx_178ccdbf1d_c", - '"data-rx-popup":""', - 'id:"rx-popover-1"', - f"onBeforeToggle:((event) => {{ (((event) => popupEvent(event, {on})))(event); (popupBeforeToggle)(event); }})", - f"onBlur:((event) => popupEvent(event, {on}))", - f"onClick:((event) => popupEvent(event, {on}))", - f"onKeyDown:((event) => popupEvent(event, {on}))", - f"onToggle:((event) => popupEvent(event, {on}))", - 'popover:"auto"', - f"ref:((popup) => popupSync(popup, {PopoverState.shown!s}))", - 'role:"dialog"', - f'style:({{ "--v0": ((({PopoverState.gap!s}) + "px")) ?? "initial" }})', - "tabIndex:-1", - ] -def test_popover_imports_its_script(ui_plugin: UIPlugin): - """A page with a popover loads the script of a popup, and no other.""" +def test_popover_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a popover imports its parts from UI SDK, pinned, and no script.""" component = rx.ui.popover.root( - rx.ui.popover.trigger(rx.el.button("Open")), rx.ui.popover.content("x") + rx.ui.popover.trigger(rx.el.button("Open")), rx.ui.popover.content("Hi") ) imports = component._get_all_imports() assert { - module: names for module, names in imports.items() if "behaviors" in module + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module } == { - "$/reflex-ui/behaviors/popup.js": [ - ImportVar(tag="popupSync"), - ImportVar(tag="popupEvent"), - ImportVar(tag="popupBeforeToggle"), + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/popover": [ + ImportVar(tag="Popover"), + ImportVar(tag="PopoverTrigger"), + ImportVar(tag="PopoverContent"), ], } diff --git a/tests/units/reflex_components_ui/components/test_popup.py b/tests/units/reflex_components_ui/components/test_popup.py index 95bbc3b6f34..42338decb97 100644 --- a/tests/units/reflex_components_ui/components/test_popup.py +++ b/tests/units/reflex_components_ui/components/test_popup.py @@ -8,32 +8,36 @@ import reflex as rx +KEY = 'key:"a"' + @pytest.mark.parametrize( - ("root", "name"), + ("root", "name", "props"), [ - (rx.ui.popover.root, "Fragment"), - (rx.ui.dropdown_menu.root, "Menu"), - (rx.ui.dropdown_menu.sub, "MenuSub"), - (rx.ui.context_menu.root, "Fragment"), - (rx.ui.hover_card.root, "Fragment"), + (rx.ui.popover.root, "Popover", [KEY]), + (rx.ui.dropdown_menu.root, "Menu", [KEY, "loop:false"]), + (rx.ui.dropdown_menu.sub, "MenuSub", [KEY, "loop:false"]), + (rx.ui.context_menu.root, "Fragment", [KEY]), + (rx.ui.hover_card.root, "Fragment", [KEY]), ], ) def test_a_popup_in_a_list_keeps_its_key( - root: Callable[..., Component], name: str, ui_plugin: UIPlugin + root: Callable[..., Component], + name: str, + props: list[str], + ui_plugin: UIPlugin, ): """The root of a popup carries its key: ``rx.foreach`` keys each item by it. - A root of UI SDK is a component that renders no element; the others - render a fragment. + A root of UI SDK is a component that renders no element, and the arrow + keys of a menu stop at its ends, as in Radix; the others render a + fragment. Args: root: The root of a popup. name: What the root renders as. + props: The props it renders. ui_plugin: The configured plugin. """ component = root(rx.el.span("a"), key="a") - assert (component.render()["name"], component.render()["props"]) == ( - name, - ['key:"a"'], - ) + assert (component.render()["name"], component.render()["props"]) == (name, props) diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index cb163c3b334..6e81e785dfa 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -1,7 +1,5 @@ """Tests for reflex_components_ui.components.select.""" -import itertools -import re from collections.abc import Callable from typing import Any, get_args @@ -12,21 +10,18 @@ from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree - -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the popups and the labels of each test from one.""" - monkeypatch.setattr(select_module, "_ids", itertools.count(1)) +STATE = ( + "tests___units___reflex_components_ui___components___test_select____select_state" +) class SelectState(rx.State): """What a select is bound to.""" - fruit: str = "apple" - fruits: list[str] = ["apple", "pear"] - is_open: bool = False - offset: int = 6 + fruit: str = "a" + fruits: list[str] = ["a", "b"] @rx.event def set_fruit(self, fruit: str): @@ -37,1331 +32,200 @@ def set_fruit(self, fruit: str): """ self.fruit = fruit - @rx.event - def set_is_open(self, is_open: bool): - """Follow the list of the select. - Args: - is_open: Whether it is open. - """ - self.is_open = is_open +def _item(text: str, *props: str) -> tuple[str, list[str], list[Any]]: + """The projection of an option: UI SDK's check, then what it shows. - @rx.event - def closed(self): - """Hear that the list closed.""" + Args: + text: What the option shows, as rendered. + *props: Its props, after its class name. + Returns: + The projection. + """ + return ( + "SelectItem", + ["className:sx_354c170aac_c", *props], + [ + ("SelectItemIndicator", ["className:sx_9209c0ff85_c"], [("svg",)]), + ('"span"', [], [text]), + ], + ) -def test_select( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], -): - """A select is a button that opens a popover of options, and an input that holds its value; the root hands its size to both and its state to the input.""" + +def test_select(ui_plugin: UIPlugin): + """A select is the parts of UI SDK, in the look of Radix Themes. + + The select hands its size to its trigger and its list. The trigger shows + UI SDK's value, with the placeholder, the list is placed as Radix Themes + places it, and lies over its trigger where it is aligned with it. + """ component = rx.ui.select.root( - rx.ui.select.trigger( - placeholder="Pick", - variant="classic", - radius="full", - color_scheme="ruby", - id="pick", - margin="1px", - ), + rx.ui.select.trigger(placeholder="Pick", variant="soft"), rx.ui.select.content( rx.ui.select.group( - rx.ui.select.label("Fruits"), - rx.ui.select.item("Apple", value="apple"), - rx.ui.select.item("Pear", value="pear", disabled=True, id="pear"), + rx.ui.select.label("Fruit"), + rx.ui.select.item("Apple", value="a"), + rx.ui.select.item("Banana", value="b", disabled=True), ), rx.ui.select.separator(), - rx.ui.select.item(rx.el.b("None"), value="none"), + position="item-aligned", variant="soft", - high_contrast=True, - color_scheme="jade", - side="top", - align="end", - side_offset=8, - align_offset=2, - position="popper", - z_index="5", ), - default_value="pear", + size="1", name="fruit", required=True, - disabled=True, - size="3", - default_open=True, - id="fruit", + value=SelectState.fruit, + on_change=SelectState.set_fruit, ) - assert component.render() == { - "name": '"span"', - "props": [ - "className:sx_71b84cd269_c", - '"data-default-open":true', - '"data-rx-select":""', - 'id:"fruit"', - "onClick:selectClick", - "onKeyDown:selectKeyDown", - "onPointerMove:selectPointerMove", - "ref:ref_fruit", + assert tree(component.render()) == ( + "Select", + [ + "loop:false", + 'name:"fruit"', + ( + "onValueChange:((_ev_0) => (addEvents([(ReflexEvent(" + f'"reflex___state____state.{STATE}.set_fruit", ' + '({ ["fruit"] : _ev_0 }), ({ })))], [_ev_0], ({ }))))' + ), + "required:true", + f"value:reflex___state____state__{STATE}.fruit_rx_state_", ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-autocomplete":"none"', - '"aria-controls":"rx-select-2"', - '"aria-expanded":"false"', - '"aria-haspopup":"listbox"', - 'className:sx_0f680e2b85_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', - '"data-state":"closed"', - "disabled:true", - 'id:"pick"', - 'popoverTarget:"rx-select-2"', - "ref:ref_pick", - 'role:"combobox"', - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": [ - "className:sx_94480a599d_c", - '"data-placeholder":"Pick"', - '"data-rx-select-shown":""', - ], - "children": [{"contents": '"Pear"'}], - }, - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_9779d39f10_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'd:"M0.135232 3.15803C0.324102 2.95657 0.640521 2.94637 0.841971 3.13523L4.5 6.56464L8.158 3.13523C8.3595 2.94637 8.6759 2.95657 8.8648 3.15803C9.0536 3.35949 9.0434 3.67591 8.842 3.86477L4.84197 7.6148C4.64964 7.7951 4.35036 7.7951 4.15803 7.6148L0.158031 3.86477C-0.0434285 3.67591 -0.0536285 3.35949 0.135232 3.15803Z"' - ], - "children": [], - } - ], - }, + [ + ( + "SelectTrigger", + ["className:sx_5ea0b69884_c"], + [ + ( + "SelectValue", + ["className:sx_94480a599d_c", 'placeholder:"Pick"'], + [], + ), + ("svg",), ], - }, - { - "name": '"div"', - "props": [ - 'className:sx_a9c2b0afeb_c + " " + reflexUIClasses_f97593a337', - '"data-rx-popup":""', - 'id:"rx-select-2"', - "onBeforeToggle:((event) => { (selectToggle)(event); (popupBeforeToggle)(event); })", - "onToggle:selectToggle", - 'popover:"auto"', - 'role:"listbox"', - "tabIndex:-1", + ), + ( + "SelectContent", + [ + 'align:"start"', + "alignItemWithTrigger:true", + "className:sx_1a5dfc1f84_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:4", ], - "children": [ - { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-select-label-1"', - 'role:"group"', - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_4c825b9931_c", - '"data-rx-select-label":""', - 'id:"rx-select-label-1"', - ], - "children": [{"contents": '"Fruits"'}], - }, - { - "name": '"div"', - "props": [ - '"aria-selected":"false"', - "className:sx_afbb711e7e_c", - '"data-value":"apple"', - 'role:"option"', - "tabIndex:-1", - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_9209c0ff85_c"], - "children": [ - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_26fb6ce487_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'clipRule:"evenodd"', - 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', - 'fillRule:"evenodd"', - ], - "children": [], - } - ], - } - ], - }, - { - "name": '"span"', - "props": ['"data-rx-select-text":""'], - "children": [{"contents": '"Apple"'}], - }, - ], - }, - { - "name": '"div"', - "props": [ - '"aria-disabled":true', - '"aria-selected":"true"', - "className:sx_afbb711e7e_c", - '"data-value":"pear"', - 'id:"pear"', - "ref:ref_pear", - 'role:"option"', - "tabIndex:-1", - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_9209c0ff85_c"], - "children": [ - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_26fb6ce487_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'clipRule:"evenodd"', - 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', - 'fillRule:"evenodd"', - ], - "children": [], - } - ], - } - ], - }, - { - "name": '"span"', - "props": ['"data-rx-select-text":""'], - "children": [{"contents": '"Pear"'}], - }, - ], - }, - ], - }, - { - "name": '"div"', - "props": ['"aria-hidden":true', "className:sx_2d671c061b_c"], - "children": [], - }, - { - "name": '"div"', - "props": [ - '"aria-selected":"false"', - "className:sx_afbb711e7e_c", - '"data-value":"none"', - 'role:"option"', - "tabIndex:-1", - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_9209c0ff85_c"], - "children": [ - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_26fb6ce487_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'clipRule:"evenodd"', - 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', - 'fillRule:"evenodd"', - ], - "children": [], - } - ], - } - ], - }, - { - "name": '"span"', - "props": ['"data-rx-select-text":""'], - "children": [ - { - "name": '"b"', - "props": [], - "children": [{"contents": '"None"'}], - } - ], - }, + [ + ( + "SelectGroup", + [], + [ + ( + "SelectGroupLabel", + ["className:sx_4c825b9931_c"], + ['"Fruit"'], + ), + _item('"Apple"', 'value:"a"'), + _item('"Banana"', "disabled:true", 'value:"b"'), ], - }, + ), + ("SelectSeparator", ["className:sx_2d671c061b_c"], []), ], - }, - { - "name": '"input"', - "props": [ - '"aria-hidden":true', - "className:sx_b72d7382fd_c", - '"data-rx-select-value":""', - 'defaultValue:"pear"', - "disabled:true", - 'name:"fruit"', - "onFocus:selectFocus", - "ref:((holder) => syncSelect(holder, null, null))", - "required:true", - "tabIndex:-1", - ], - "children": [], - }, + ), ], - } - assert declared_styles(component) == [ - {"display": "contents"}, - { - "appearance": "none", - "marginTop": "1px", - "marginRight": "1px", - "marginBottom": "1px", - "marginLeft": "1px", - "paddingTop": "0", - "paddingRight": "var(--space-4)", - "paddingBottom": "0", - "paddingLeft": "var(--space-4)", - "borderTopWidth": {"default": "0", "::before": "2px"}, - "borderRightWidth": {"default": "0", "::before": "2px"}, - "borderBottomWidth": {"default": "0", "::before": "2px"}, - "borderLeftWidth": {"default": "0", "::before": "2px"}, - "borderTopStyle": {"default": "none", "::before": "solid"}, - "borderRightStyle": {"default": "none", "::before": "solid"}, - "borderBottomStyle": {"default": "none", "::before": "solid"}, - "borderLeftStyle": {"default": "none", "::before": "solid"}, - "backgroundColor": { - "default": "transparent", - ":disabled": "var(--gray-2)", - "::before": {":disabled": "var(--gray-a2)"}, - }, - "backgroundImage": { - "default": "linear-gradient(var(--gray-2), var(--gray-1))", - ":disabled": "none", - "::before": { - "default": "linear-gradient(var(--black-a1) -20%, transparent, var(--white-a1) 130%), linear-gradient(var(--color-surface), transparent)", - "@media (hover: hover)": { - ":hover:not(:disabled)": "linear-gradient(var(--black-a1) -15%, transparent, var(--white-a1) 120%), linear-gradient(var(--gray-2), var(--gray-1))" - }, - ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "linear-gradient(var(--black-a1) -15%, transparent, var(--white-a1) 120%), linear-gradient(var(--gray-2), var(--gray-1))", - ":disabled": "linear-gradient(var(--black-a1) -20%, transparent, var(--white-a1))", - }, - }, - "textTransform": "inherit", - "textIndent": "initial", - "wordSpacing": "inherit", - "cursor": { - "default": "var(--cursor-button)", - ":disabled": "var(--cursor-disabled)", - }, - "WebkitTapHighlightColor": "transparent", - "display": "inline-flex", - "alignItems": "center", - "justifyContent": "space-between", - "flexShrink": 0, - "userSelect": "none", - "verticalAlign": "top", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "outlineStyle": {"default": "none", ":focus-visible": "solid"}, - "outlineWidth": {"default": "medium", ":focus-visible": "2px"}, - "outlineColor": { - "default": "currentcolor", - ":focus-visible": "var(--focus-8)", - }, - "outlineOffset": {"default": "0", ":focus-visible": "-1px"}, - "--rx-select-icon-color": {":disabled": "var(--gray-a9)"}, - "--select-trigger-height": "var(--space-7)", - "rowGap": "var(--space-2)", - "columnGap": "var(--space-2)", - "fontSize": "var(--font-size-3)", - "lineHeight": "var(--line-height-3)", - "letterSpacing": "var(--letter-spacing-3)", - "borderRadius": "max(var(--radius-3), var(--radius-full))", - "boxSizing": "border-box", - "height": "var(--select-trigger-height)", - "--rx-select-shown-color": {"[data-placeholder]": "var(--gray-a10)"}, - "color": {"default": "var(--gray-12)", ":disabled": "var(--gray-a11)"}, - "boxShadow": { - "default": "var(--rx-if-light, inset 0 0 0 1px var(--gray-a5), inset 0 2px 1px var(--white-a11), inset 0 -2px 1px var(--gray-a4)) var(--rx-if-dark, inset 0 0 0 1px var(--white-a4), inset 0 1px 1px var(--white-a4), inset 0 -1px 1px var(--black-a9))", - "@media (hover: hover)": { - ":hover:not(:disabled)": "inset 0 0 0 1px var(--gray-a3), var(--rx-if-light, inset 0 0 0 1px var(--gray-a5), inset 0 2px 1px var(--white-a11), inset 0 -2px 1px var(--gray-a4)) var(--rx-if-dark, inset 0 0 0 1px var(--white-a4), inset 0 1px 1px var(--white-a4), inset 0 -1px 1px var(--black-a9))" - }, - ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "inset 0 0 0 1px var(--gray-a3), var(--rx-if-light, inset 0 0 0 1px var(--gray-a5), inset 0 2px 1px var(--white-a11), inset 0 -2px 1px var(--gray-a4)) var(--rx-if-dark, inset 0 0 0 1px var(--white-a4), inset 0 1px 1px var(--white-a4), inset 0 -1px 1px var(--black-a9))", - ":disabled": "var(--rx-if-light, inset 0 0 0 1px var(--gray-a4), inset 0 -2px 1px var(--gray-a3), inset 0 4px 2px -2px var(--white-a9), inset 0 2px 1px -1px var(--white-a9)) var(--rx-if-dark, inset 0 0 0 1px var(--gray-a5), inset 0 4px 2px -2px var(--gray-a2), inset 0 1px 1px var(--gray-a5), inset 0 -1px 1px var(--black-a3), inset 0 0 0 1px var(--gray-a2))", - }, - "position": {"default": "relative", "::before": "absolute"}, - "zIndex": {"default": 0, "::before": -1}, - "content": {"::before": "''"}, - "top": {"::before": "0"}, - "right": {"::before": "0"}, - "bottom": {"::before": "0"}, - "left": {"::before": "0"}, - "borderTopColor": {"::before": "transparent"}, - "borderRightColor": {"::before": "transparent"}, - "borderBottomColor": {"::before": "transparent"}, - "borderLeftColor": {"::before": "transparent"}, - "backgroundClip": {"::before": "content-box"}, - "borderTopLeftRadius": {"::before": "inherit"}, - "borderTopRightRadius": {"::before": "inherit"}, - "borderBottomRightRadius": {"::before": "inherit"}, - "borderBottomLeftRadius": {"::before": "inherit"}, - "pointerEvents": {"::before": "none"}, - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "textOverflow": "ellipsis", - "whiteSpace": "nowrap", - "color": "var(--rx-select-shown-color, inherit)", - "opacity": "var(--rx-select-shown-opacity, 1)", - }, - { - "flexShrink": 0, - "color": "var(--rx-select-icon-color, inherit)", - "opacity": 0.9, - "width": "11px", - "height": "11px", - }, - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "calc(10px + var(--rx-popup-snap-y, 0px))", - "marginRight": "calc(var(--rx-popup-shift, 0px) - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-y, 0px))", - "marginLeft": "var(--rx-popup-snap-x, 0px)", - "padding": "var(--select-content-padding)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "calc(100vw - 10px * 2)", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "100ms", - ":popover-open": "160ms", - }, - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "var(--gray-12)", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-5)", - "minWidth": "anchor-size(width)", - "outlineStyle": "none", - "overflowY": "auto", - "scrollbarWidth": "thin", - "scrollbarColor": "var(--gray-a8) transparent", - "--select-content-padding": "var(--space-2)", - "--select-item-height": "var(--space-6)", - "--select-item-indicator-width": "var(--space-5)", - "--select-separator-margin-right": "var(--space-3)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "--rx-select-font-size": "var(--font-size-3)", - "--rx-select-line-height": "var(--line-height-2)", - "--rx-select-letter-spacing": "var(--letter-spacing-3)", - "--rx-select-label-font-size": "var(--font-size-2)", - "--rx-select-label-letter-spacing": "var(--letter-spacing-2)", - "--rx-select-item-radius": "var(--radius-2)", - "--rx-select-check-size": "calc(10px * var(--scaling))", - "--rx-select-highlight": "var(--accent-a4)", - "positionArea": "top span-left", - "maxHeight": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", - "--rx-popup-from": "translateY(4px) scale(0.97)", - "transformOrigin": "bottom right", - "--rx-popup-offset": "8px", - "--rx-popup-shift": "2px", - "zIndex": "5", - }, - {}, - { - "display": "flex", - "alignItems": "center", - "height": "var(--select-item-height)", - "paddingLeft": "var(--select-item-indicator-width)", - "paddingRight": "var(--select-item-indicator-width)", - "userSelect": "none", - "fontSize": "var(--rx-select-label-font-size)", - "lineHeight": "var(--rx-select-line-height)", - "letterSpacing": "var(--rx-select-label-letter-spacing)", - "color": "var(--gray-a10)", - "cursor": "default", - }, - { - "display": "flex", - "alignItems": "center", - "height": "var(--select-item-height)", - "paddingLeft": "var(--select-item-indicator-width)", - "paddingRight": "var(--select-item-indicator-width)", - "userSelect": "none", - "fontSize": "var(--rx-select-font-size)", - "lineHeight": "var(--rx-select-line-height)", - "letterSpacing": "var(--rx-select-letter-spacing)", - "position": "relative", - "boxSizing": "border-box", - "outlineStyle": "none", - "scrollMarginTop": "var(--select-content-padding)", - "scrollMarginBottom": "var(--select-content-padding)", - "borderRadius": "var(--rx-select-item-radius)", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "color": { - "default": "inherit", - ":focus": "var(--rx-select-highlight-color, inherit)", - "[aria-disabled='true']": "var(--gray-a8)", - }, - "backgroundColor": {":focus": "var(--rx-select-highlight)"}, - "--rx-select-check": { - "default": "none", - "[aria-selected='true']": "inline-flex", - }, - }, - { - "position": "absolute", - "left": "0", - "width": "var(--select-item-indicator-width)", - "display": "var(--rx-select-check)", - "alignItems": "center", - "justifyContent": "center", - }, - { - "width": "var(--rx-select-check-size)", - "height": "var(--rx-select-check-size)", - }, - { - "display": "flex", - "alignItems": "center", - "height": "var(--select-item-height)", - "paddingLeft": "var(--select-item-indicator-width)", - "paddingRight": "var(--select-item-indicator-width)", - "userSelect": "none", - "fontSize": "var(--rx-select-font-size)", - "lineHeight": "var(--rx-select-line-height)", - "letterSpacing": "var(--rx-select-letter-spacing)", - "position": "relative", - "boxSizing": "border-box", - "outlineStyle": "none", - "scrollMarginTop": "var(--select-content-padding)", - "scrollMarginBottom": "var(--select-content-padding)", - "borderRadius": "var(--rx-select-item-radius)", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "color": { - "default": "inherit", - ":focus": "var(--rx-select-highlight-color, inherit)", - "[aria-disabled='true']": "var(--gray-a8)", - }, - "backgroundColor": {":focus": "var(--rx-select-highlight)"}, - "--rx-select-check": { - "default": "none", - "[aria-selected='true']": "inline-flex", - }, - }, - { - "position": "absolute", - "left": "0", - "width": "var(--select-item-indicator-width)", - "display": "var(--rx-select-check)", - "alignItems": "center", - "justifyContent": "center", - }, - { - "width": "var(--rx-select-check-size)", - "height": "var(--rx-select-check-size)", - }, - { - "height": "1px", - "marginTop": "var(--space-2)", - "marginBottom": "var(--space-2)", - "marginLeft": "var(--select-item-indicator-width)", - "marginRight": "var(--select-separator-margin-right)", - "backgroundColor": "var(--gray-a6)", - }, - { - "display": "flex", - "alignItems": "center", - "height": "var(--select-item-height)", - "paddingLeft": "var(--select-item-indicator-width)", - "paddingRight": "var(--select-item-indicator-width)", - "userSelect": "none", - "fontSize": "var(--rx-select-font-size)", - "lineHeight": "var(--rx-select-line-height)", - "letterSpacing": "var(--rx-select-letter-spacing)", - "position": "relative", - "boxSizing": "border-box", - "outlineStyle": "none", - "scrollMarginTop": "var(--select-content-padding)", - "scrollMarginBottom": "var(--select-content-padding)", - "borderRadius": "var(--rx-select-item-radius)", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "color": { - "default": "inherit", - ":focus": "var(--rx-select-highlight-color, inherit)", - "[aria-disabled='true']": "var(--gray-a8)", - }, - "backgroundColor": {":focus": "var(--rx-select-highlight)"}, - "--rx-select-check": { - "default": "none", - "[aria-selected='true']": "inline-flex", - }, - }, - { - "position": "absolute", - "left": "0", - "width": "var(--select-item-indicator-width)", - "display": "var(--rx-select-check)", - "alignItems": "center", - "justifyContent": "center", - }, - { - "width": "var(--rx-select-check-size)", - "height": "var(--rx-select-check-size)", - }, - { - "position": "absolute", - "width": "1px", - "height": "1px", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "opacity": 0, - "pointerEvents": "none", - }, - ] + ) -def test_select_of_a_list( - ui_plugin: UIPlugin, -): - """The select of a list of words has an option for each, in a group named by its label, and gives its trigger and its list what is theirs.""" - component = rx.ui.select( - ["One", "Two"], - label="Numbers", - placeholder="Count", - default_value="Two", - variant="soft", - radius="small", - color_scheme="ruby", - high_contrast=True, - width="120px", - id="count", - name="count", - position="item-aligned", - ) - assert component.render() == { - "name": '"span"', - "props": [ - "className:sx_71b84cd269_c", - '"data-rx-select":""', - "onClick:selectClick", - "onKeyDown:selectKeyDown", - "onPointerMove:selectPointerMove", - ], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-autocomplete":"none"', - '"aria-controls":"rx-select-2"', - '"aria-expanded":"false"', - '"aria-haspopup":"listbox"', - 'className:sx_476d055388_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', - '"data-state":"closed"', - 'id:"count"', - 'popoverTarget:"rx-select-2"', - "ref:ref_count", - 'role:"combobox"', - 'type:"button"', - ], - "children": [ - { - "name": '"span"', - "props": [ - "className:sx_94480a599d_c", - '"data-placeholder":"Count"', - '"data-rx-select-shown":""', - ], - "children": [{"contents": '"Two"'}], - }, - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_3c2399b961_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'd:"M0.135232 3.15803C0.324102 2.95657 0.640521 2.94637 0.841971 3.13523L4.5 6.56464L8.158 3.13523C8.3595 2.94637 8.6759 2.95657 8.8648 3.15803C9.0536 3.35949 9.0434 3.67591 8.842 3.86477L4.84197 7.6148C4.64964 7.7951 4.35036 7.7951 4.15803 7.6148L0.158031 3.86477C-0.0434285 3.67591 -0.0536285 3.35949 0.135232 3.15803Z"' - ], - "children": [], - } - ], - }, - ], - }, - { - "name": '"div"', - "props": [ - 'className:sx_070d48041b_c + " " + reflexUIClasses_e201574881', - '"data-rx-popup":""', - 'id:"rx-select-2"', - "onBeforeToggle:((event) => { (selectToggle)(event); (popupBeforeToggle)(event); })", - "onToggle:selectToggle", - 'popover:"auto"', - 'role:"listbox"', - "tabIndex:-1", +def test_select_of_a_list(ui_plugin: UIPlugin): + """The select of a list of words is a group of an option for each, under its label.""" + component = rx.ui.select(["a", "b"], label="Letters", position="popper") + assert tree(component.render()) == ( + "Select", + ["loop:false"], + [ + ( + "SelectTrigger", + ["className:sx_d728ce29c0_c"], + [("SelectValue", ["className:sx_94480a599d_c"], []), ("svg",)], + ), + ( + "SelectContent", + [ + 'align:"start"', + "className:sx_1f65a63af7_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:4", ], - "children": [ - { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-select-label-1"', - 'role:"group"', - ], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_4c825b9931_c", - '"data-rx-select-label":""', - 'id:"rx-select-label-1"', - ], - "children": [{"contents": '"Numbers"'}], - }, - { - "name": '"div"', - "props": [ - '"aria-selected":"false"', - "className:sx_afbb711e7e_c", - '"data-value":"One"', - 'role:"option"', - "tabIndex:-1", - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_9209c0ff85_c"], - "children": [ - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_26fb6ce487_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'clipRule:"evenodd"', - 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', - 'fillRule:"evenodd"', - ], - "children": [], - } - ], - } - ], - }, - { - "name": '"span"', - "props": ['"data-rx-select-text":""'], - "children": [{"contents": '"One"'}], - }, - ], - }, - { - "name": '"div"', - "props": [ - '"aria-selected":"true"', - "className:sx_afbb711e7e_c", - '"data-value":"Two"', - 'role:"option"', - "tabIndex:-1", - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_9209c0ff85_c"], - "children": [ - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_26fb6ce487_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'clipRule:"evenodd"', - 'd:"M8.53547 0.62293C8.88226 0.849446 8.97976 1.3142 8.75325 1.66099L4.5083 8.1599C4.38833 8.34356 4.19397 8.4655 3.9764 8.49358C3.75883 8.52167 3.53987 8.45309 3.3772 8.30591L0.616113 5.80777C0.308959 5.52987 0.285246 5.05559 0.563148 4.74844C0.84105 4.44128 1.31533 4.41757 1.62249 4.69547L3.73256 6.60459L7.49741 0.840706C7.72393 0.493916 8.18868 0.396414 8.53547 0.62293Z"', - 'fillRule:"evenodd"', - ], - "children": [], - } - ], - } - ], - }, - { - "name": '"span"', - "props": ['"data-rx-select-text":""'], - "children": [{"contents": '"Two"'}], - }, - ], - }, + [ + ( + "SelectGroup", + [], + [ + ( + "SelectGroupLabel", + ["className:sx_4c825b9931_c"], + ['"Letters"'], + ), + _item('"a"', 'value:"a"'), + _item('"b"', 'value:"b"'), ], - } + ), ], - }, - { - "name": '"input"', - "props": [ - '"aria-hidden":true', - "className:sx_b72d7382fd_c", - '"data-rx-select-value":""', - 'defaultValue:"Two"', - 'name:"count"', - "onFocus:selectFocus", - "ref:((holder) => syncSelect(holder, null, null))", - "tabIndex:-1", - ], - "children": [], - }, + ), ], - } + ) -def test_select_default_styles( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], -): - """The styles of a select that is given no props, whose first option is in no group.""" - component = rx.ui.select.root( - rx.ui.select.trigger(), rx.ui.select.content(rx.ui.select.item("A", value="a")) +def test_select_trigger_shows_what_it_is_given(ui_plugin: UIPlugin): + """A trigger given children shows them in place of UI SDK's value.""" + trigger = rx.ui.select.trigger("Custom") + assert tree(trigger.render())[2][0] == ( + '"span"', + ["className:sx_94480a599d_c"], + ['"Custom"'], ) - assert declared_styles(component) == [ - {"display": "contents"}, - { - "appearance": "none", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "var(--space-3)", - "paddingBottom": "0", - "paddingLeft": "var(--space-3)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": { - "default": "var(--color-surface)", - ":disabled": "var(--gray-a2)", - }, - "backgroundImage": "none", - "textTransform": "inherit", - "textIndent": "initial", - "wordSpacing": "inherit", - "cursor": { - "default": "var(--cursor-button)", - ":disabled": "var(--cursor-disabled)", - }, - "WebkitTapHighlightColor": "transparent", - "display": "inline-flex", - "alignItems": "center", - "justifyContent": "space-between", - "flexShrink": 0, - "userSelect": "none", - "verticalAlign": "top", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "outlineStyle": {"default": "none", ":focus-visible": "solid"}, - "outlineWidth": {"default": "medium", ":focus-visible": "2px"}, - "outlineColor": { - "default": "currentcolor", - ":focus-visible": "var(--focus-8)", - }, - "outlineOffset": {"default": "0", ":focus-visible": "-1px"}, - "--rx-select-icon-color": {":disabled": "var(--gray-a9)"}, - "--select-trigger-height": "var(--space-6)", - "gap": "calc(var(--space-1) * 1.5)", - "fontSize": "var(--font-size-2)", - "lineHeight": "var(--line-height-2)", - "letterSpacing": "var(--letter-spacing-2)", - "borderRadius": "max(var(--radius-2), var(--radius-full))", - "boxSizing": "border-box", - "height": "var(--select-trigger-height)", - "--rx-select-shown-color": {"[data-placeholder]": "var(--gray-a10)"}, - "color": {"default": "var(--gray-12)", ":disabled": "var(--gray-a11)"}, - "boxShadow": { - "default": "inset 0 0 0 1px var(--gray-a7)", - "@media (hover: hover)": { - ":hover:not(:disabled)": "inset 0 0 0 1px var(--gray-a8)" - }, - ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "inset 0 0 0 1px var(--gray-a8)", - ":disabled": "inset 0 0 0 1px var(--gray-a6)", - }, - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "textOverflow": "ellipsis", - "whiteSpace": "nowrap", - "color": "var(--rx-select-shown-color, inherit)", - "opacity": "var(--rx-select-shown-opacity, 1)", - }, - { - "flexShrink": 0, - "color": "var(--rx-select-icon-color, inherit)", - "opacity": 0.9, - }, - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "calc(var(--rx-popup-offset, 4px) + var(--rx-popup-snap-y, 0px))", - "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(10px - var(--rx-popup-snap-y, 0px))", - "marginLeft": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-x, 0px))", - "padding": "var(--select-content-padding)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "calc(100vw - 10px * 2)", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "100ms", - ":popover-open": "160ms", - }, - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "var(--gray-12)", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-5)", - "minWidth": "anchor-size(width)", - "outlineStyle": "none", - "overflowY": "auto", - "scrollbarWidth": "thin", - "scrollbarColor": "var(--gray-a8) transparent", - "--select-content-padding": "var(--space-2)", - "--select-item-height": "var(--space-6)", - "--select-item-indicator-width": "var(--space-5)", - "--select-separator-margin-right": "var(--space-3)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "--rx-select-font-size": "var(--font-size-2)", - "--rx-select-line-height": "var(--line-height-2)", - "--rx-select-letter-spacing": "var(--letter-spacing-2)", - "--rx-select-label-font-size": "var(--font-size-2)", - "--rx-select-label-letter-spacing": "var(--letter-spacing-2)", - "--rx-select-item-radius": "var(--radius-2)", - "--rx-select-check-size": "calc(10px * var(--scaling))", - "--rx-select-highlight": "var(--accent-9)", - "--rx-select-highlight-color": "var(--accent-contrast)", - "positionArea": "bottom span-right", - "maxHeight": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", - "--rx-popup-from": "translateY(-4px) scale(0.97)", - "transformOrigin": "top left", - }, - { - "display": "flex", - "alignItems": "center", - "height": "var(--select-item-height)", - "paddingLeft": "var(--select-item-indicator-width)", - "paddingRight": "var(--select-item-indicator-width)", - "userSelect": "none", - "fontSize": "var(--rx-select-font-size)", - "lineHeight": "var(--rx-select-line-height)", - "letterSpacing": "var(--rx-select-letter-spacing)", - "position": "relative", - "boxSizing": "border-box", - "outlineStyle": "none", - "scrollMarginTop": "var(--select-content-padding)", - "scrollMarginBottom": "var(--select-content-padding)", - "borderRadius": "var(--rx-select-item-radius)", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "color": { - "default": "inherit", - ":focus": "var(--rx-select-highlight-color, inherit)", - "[aria-disabled='true']": "var(--gray-a8)", - }, - "backgroundColor": {":focus": "var(--rx-select-highlight)"}, - "--rx-select-check": { - "default": "none", - "[aria-selected='true']": "inline-flex", - }, - }, - { - "position": "absolute", - "left": "0", - "width": "var(--select-item-indicator-width)", - "display": "var(--rx-select-check)", - "alignItems": "center", - "justifyContent": "center", - }, - { - "width": "var(--rx-select-check-size)", - "height": "var(--rx-select-check-size)", - }, - { - "position": "absolute", - "width": "1px", - "height": "1px", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "opacity": 0, - "pointerEvents": "none", - }, - ] -def test_select_ghost_styles( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], +def test_select_highlights_by_ui_sdk( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] ): - """The ghost trigger, and a list beside its trigger and centered on it.""" - component = rx.ui.select.root( - rx.ui.select.trigger(variant="ghost"), - rx.ui.select.content(side="left", align="center"), - size="1", - ) - assert declared_styles(component) == [ - {"display": "contents"}, - { - "appearance": "none", - "marginTop": "calc(0px - var(--select-trigger-ghost-padding-y))", - "marginRight": "calc(0px - var(--select-trigger-ghost-padding-x))", - "marginBottom": "calc(0px - var(--select-trigger-ghost-padding-y))", - "marginLeft": "calc(0px - var(--select-trigger-ghost-padding-x))", - "paddingTop": "var(--select-trigger-ghost-padding-y)", - "paddingRight": "var(--select-trigger-ghost-padding-x)", - "paddingBottom": "var(--select-trigger-ghost-padding-y)", - "paddingLeft": "var(--select-trigger-ghost-padding-x)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "backgroundColor": { - "default": "transparent", - "@media (hover: hover)": {":hover:not(:disabled)": "var(--accent-a3)"}, - ":is([data-state='open'], :has(+ :popover-open)):not(:disabled)": "var(--accent-a3)", - ":disabled": "transparent", - }, - "backgroundImage": "none", - "textTransform": "inherit", - "textIndent": "initial", - "wordSpacing": "inherit", - "cursor": { - "default": "var(--cursor-button)", - ":disabled": "var(--cursor-disabled)", - }, - "WebkitTapHighlightColor": "transparent", - "display": "inline-flex", - "alignItems": "center", - "justifyContent": "space-between", - "flexShrink": 0, - "userSelect": "none", - "verticalAlign": "top", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "outlineStyle": {"default": "none", ":focus-visible": "solid"}, - "outlineWidth": {"default": "medium", ":focus-visible": "2px"}, - "outlineColor": { - "default": "currentcolor", - ":focus-visible": "var(--focus-8)", - }, - "outlineOffset": {"default": "0", ":focus-visible": "-1px"}, - "--rx-select-icon-color": {":disabled": "var(--gray-a9)"}, - "--select-trigger-height": "var(--space-5)", - "rowGap": "var(--space-1)", - "columnGap": "var(--space-1)", - "fontSize": "var(--font-size-1)", - "lineHeight": "var(--line-height-1)", - "letterSpacing": "var(--letter-spacing-1)", - "borderRadius": "max(var(--radius-1), var(--radius-full))", - "--rx-select-shown-color": {"[data-placeholder]": "var(--accent-12)"}, - "--rx-select-shown-opacity": {"[data-placeholder]": 0.6}, - "boxSizing": "content-box", - "height": "fit-content", - "color": {"default": "var(--accent-12)", ":disabled": "var(--gray-a11)"}, - "--select-trigger-ghost-padding-x": "var(--space-2)", - "--select-trigger-ghost-padding-y": "var(--space-1)", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "textOverflow": "ellipsis", - "whiteSpace": "nowrap", - "color": "var(--rx-select-shown-color, inherit)", - "opacity": "var(--rx-select-shown-opacity, 1)", - }, - {"flexShrink": 0, "color": "var(--rx-select-icon-color, inherit)"}, - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "var(--rx-popup-snap-y, 0px)", - "marginRight": "calc(var(--rx-popup-offset, 4px) - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(0px - var(--rx-popup-snap-y, 0px))", - "marginLeft": "calc(10px + var(--rx-popup-snap-x, 0px))", - "padding": "var(--select-content-padding)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "calc(100% - var(--rx-popup-offset, 4px) - 10px)", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "100ms", - ":popover-open": "160ms", - }, - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "var(--gray-12)", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-5)", - "minWidth": "anchor-size(width)", - "outlineStyle": "none", - "overflowY": "auto", - "scrollbarWidth": "thin", - "scrollbarColor": "var(--gray-a8) transparent", - "--select-content-padding": "var(--space-1)", - "--select-item-height": "var(--space-5)", - "--select-item-indicator-width": "calc(var(--space-5) / 1.2)", - "--select-separator-margin-right": "var(--space-2)", - "borderTopLeftRadius": "var(--radius-3)", - "borderTopRightRadius": "var(--radius-3)", - "borderBottomRightRadius": "var(--radius-3)", - "borderBottomLeftRadius": "var(--radius-3)", - "--rx-select-font-size": "var(--font-size-1)", - "--rx-select-line-height": "var(--line-height-1)", - "--rx-select-letter-spacing": "var(--letter-spacing-1)", - "--rx-select-label-font-size": "var(--font-size-1)", - "--rx-select-label-letter-spacing": "var(--letter-spacing-1)", - "--rx-select-item-radius": "var(--radius-1)", - "--rx-select-check-size": "calc(8px * var(--scaling))", - "--rx-select-highlight": "var(--accent-9)", - "--rx-select-highlight-color": "var(--accent-contrast)", - "positionArea": "left span-all", - "--rx-popup-from": "translateX(4px) scale(0.97)", - "transformOrigin": "right center", - "alignSelf": "anchor-center", + """An option highlights where UI SDK says it is highlighted, and is checked where it is selected.""" + item, _, _ = declared_styles(rx.ui.select.item("A", value="a")) + assert { + key: item[key] for key in ("color", "backgroundColor", "--rx-select-check") + } == { + "color": { + "default": "inherit", + "[data-highlighted]": "var(--rx-select-highlight-color, inherit)", + "[aria-disabled='true']": "var(--gray-a8)", }, - { - "position": "absolute", - "width": "1px", - "height": "1px", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "opacity": 0, - "pointerEvents": "none", + "backgroundColor": {"[data-highlighted]": "var(--rx-select-highlight)"}, + "--rx-select-check": { + "default": "none", + "[aria-selected='true']": "inline-flex", }, - ] + } + + +def test_select_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a select imports its parts from UI SDK, pinned, and no script.""" + imports = rx.ui.select(["a"])._get_all_imports() + assert { + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/select": [ + ImportVar(tag="Select"), + ImportVar(tag="SelectTrigger"), + ImportVar(tag="SelectValue"), + ImportVar(tag="SelectContent"), + ImportVar(tag="SelectGroup"), + ImportVar(tag="SelectItem"), + ImportVar(tag="SelectItemIndicator"), + ], + } def test_select_unknown_variant(ui_plugin: UIPlugin): @@ -1400,216 +264,3 @@ def test_select_of_a_list_unknown_variant(ui_plugin: UIPlugin): str(error.value) == 'rx.ui.select.trigger: unknown variant "outline". The values are "classic", "surface", "soft", "ghost".' ) - - -STATE = ( - "reflex___state____state__tests___units___reflex_components_ui" - "___components___test_select____select_state" -) -HANDLER = ( - "reflex___state____state.tests___units___reflex_components_ui" - "___components___test_select____select_state" -) - - -def _event(handler: str, argument: str) -> str: - """Write the function an event handler with one argument renders as. - - Args: - handler: The name of the handler. - argument: The name of its argument. - - Returns: - The function. - """ - return ( - f'((_ev_0) => (addEvents([(ReflexEvent("{HANDLER}.{handler}", ' - f'({{ ["{argument}"] : _ev_0 }}), ({{ }})))], [_ev_0], ({{ }}))))' - ) - - -def test_select_bound_to_state(ui_plugin: UIPlugin): - """A select bound to state hands its value and whether it is open to its script, and its events to the input and the popover.""" - select = rx.ui.select.root( - rx.ui.select.trigger(placeholder="Pick"), - rx.ui.select.content( - rx.ui.select.item("Apple", value="apple"), - rx.ui.select.item("Pear", value="pear"), - side_offset=SelectState.offset, - on_close_auto_focus=SelectState.closed, - on_escape_key_down=SelectState.closed, - on_pointer_down_outside=SelectState.closed, - ), - value=SelectState.fruit, - open=SelectState.is_open, - on_change=SelectState.set_fruit, - on_open_change=SelectState.set_is_open, - ) - fruit = f"{STATE}.fruit_rx_state_" - closed = ( - f'((...args) => (addEvents([(ReflexEvent("{HANDLER}.closed", ({{ }}), ' - "({ })))], args, ({ }))))" - ) - trigger, content, holder = select.children - assert select.render()["props"] == [ - "className:sx_71b84cd269_c", - '"data-rx-select":""', - ( - f'onChange:((_e) => (addEvents([(ReflexEvent("{HANDLER}.set_fruit", ' - '({ ["fruit"] : _e?.["target"]?.["value"] }), ({ })))], [_e], ({ }))))' - ), - "onClick:selectClick", - "onKeyDown:selectKeyDown", - "onPointerMove:selectPointerMove", - ] - assert trigger.render()["props"] == [ - '"aria-autocomplete":"none"', - '"aria-controls":"rx-select-1"', - '"aria-expanded":"false"', - '"aria-haspopup":"listbox"', - "className:sx_872142009a_c", - f'"data-placeholder":({fruit} ? undefined : "")', - '"data-state":"closed"', - 'popoverTarget:"rx-select-1"', - 'role:"combobox"', - 'type:"button"', - ] - assert trigger.children[0].render() == { - "name": '"span"', - "props": [ - "className:sx_94480a599d_c", - '"data-placeholder":"Pick"', - '"data-rx-select-shown":""', - ], - "children": [ - { - "contents": ( - '(({ ["apple"] : "Apple", ["pear"] : "Pear" })' - f'[{fruit}] ?? "Pick")' - ) - } - ], - } - assert content.render()["props"] == [ - "className:sx_eeb5a9fe4b_c", - '"data-rx-popup":""', - 'id:"rx-select-1"', - ( - "onBeforeToggle:((event) => { (((event) => selectToggle(event, ({ " - f"open: {_event('set_is_open', 'is_open')}, " - f"close: {closed}, escape: {closed}, outside: {closed} }}))))(event); " - "(popupBeforeToggle)(event); })" - ), - ( - "onToggle:((event) => selectToggle(event, ({ " - f"open: {_event('set_is_open', 'is_open')}, " - f"close: {closed}, escape: {closed}, outside: {closed} }})))" - ), - 'popover:"auto"', - 'role:"listbox"', - (f'style:({{ "--v0": ((({STATE}.offset_rx_state_) + "px")) ?? "initial" }})'), - "tabIndex:-1", - ] - assert str(content._element_styles().style.style["--rx-popup-offset"]) == ( # pyright: ignore[reportAttributeAccessIssue] - f'(({STATE}.offset_rx_state_) + "px")' - ) - assert [item.render()["props"] for item in content.children] == [ - [ - f'"aria-selected":(({fruit} === "{value}") ? "true" : "false")', - "className:sx_afbb711e7e_c", - f'"data-value":"{value}"', - 'role:"option"', - "tabIndex:-1", - ] - for value in ("apple", "pear") - ] - assert holder.render()["props"] == [ - '"aria-hidden":true', - "className:sx_b72d7382fd_c", - '"data-rx-select-value":""', - f"defaultValue:{fruit}", - "onFocus:selectFocus", - (f"ref:((holder) => syncSelect(holder, {fruit}, {STATE}.is_open_rx_state_))"), - "tabIndex:-1", - ] - - -def test_select_of_a_list_in_state(ui_plugin: UIPlugin): - """Options a foreach renders show their values, so the trigger shows the value of the select.""" - select = rx.ui.select(SelectState.fruits, value=SelectState.fruit) - trigger, content, _ = select.children - assert trigger.children[0].render()["children"] == [ - {"contents": f'({STATE}.fruit_rx_state_ || "")'} - ] - (group,) = content.children - (options,) = group.children - item = options.children[0] - # Named after the bytecode of the function that renders an option, which - # differs from one Python version to the next. - index = options.render()["index_var_name"] - assert re.fullmatch(r"index_[0-9a-f]{32}", index) - assert item.render()["props"] == [ - ( - f'"aria-selected":(({STATE}.fruit_rx_state_ === item_rx_state_) ' - '? "true" : "false")' - ), - "className:sx_afbb711e7e_c", - '"data-value":item_rx_state_', - f"key:{index}", - 'role:"option"', - "tabIndex:-1", - ] - - -def test_select_shows_what_it_knows(ui_plugin: UIPlugin): - """The trigger shows the placeholder for a value no option has, for options that hold more than text, and what it is given in place of either.""" - item, trigger, content = ( - rx.ui.select.item, - rx.ui.select.trigger, - rx.ui.select.content, - ) - - def shown(*options: Any, trigger_children: tuple[Any, ...] = (), **props: Any): - root = rx.ui.select.root( - trigger(*trigger_children, placeholder="Pick"), content(*options), **props - ) - rendered = root.children[0].children[0].render() - return rendered["props"], rendered["children"] - - mark = [ - "className:sx_94480a599d_c", - '"data-placeholder":"Pick"', - '"data-rx-select-shown":""', - ] - assert shown(item("A", value="a")) == (mark, [{"contents": '"Pick"'}]) - assert shown(item("A", value="a"), default_value="b") == ( - mark, - [{"contents": '"Pick"'}], - ) - assert shown(item(rx.el.b("A"), value="a"), default_value="a") == ( - mark, - [{"contents": '"Pick"'}], - ) - assert shown(item(rx.el.b("A"), value="a"), value=SelectState.fruit) == ( - mark, - [{"contents": '"Pick"'}], - ) - assert shown( - item("A", value="a"), trigger_children=("Custom",), default_value="a" - ) == (["className:sx_94480a599d_c"], [{"contents": '"Custom"'}]) - - -def test_select_script(ui_plugin: UIPlugin): - """The script of a select is imported by the parts that call it.""" - select = rx.ui.select(["a"]) - assert select._get_all_imports()["$/reflex-ui/behaviors/listbox.js"] == [ - ImportVar(tag="selectKeyDown"), - ImportVar(tag="selectClick"), - ImportVar(tag="selectPointerMove"), - ImportVar(tag="selectToggle"), - ImportVar(tag="syncSelect"), - ImportVar(tag="selectFocus"), - ] - assert select._get_all_imports()["$/reflex-ui/behaviors/popup.js"] == [ - ImportVar(tag="popupBeforeToggle") - ] diff --git a/tests/units/reflex_components_ui/render.py b/tests/units/reflex_components_ui/render.py new file mode 100644 index 00000000000..ecc06d70368 --- /dev/null +++ b/tests/units/reflex_components_ui/render.py @@ -0,0 +1,31 @@ +"""A projection of a rendered component that a test compares in full.""" + +from typing import Any + + +def tree(rendered: dict[str, Any]) -> Any: + """Project a render onto what a test reads: names, props and text. + + Args: + rendered: The render of a component. + + Returns: + The text of a text node, ``("svg",)`` for an icon, the branches of a + condition, else the name, the props and the projection of each child. + """ + if "contents" in rendered: + return rendered["contents"] + if "cond_state" in rendered: + return ( + "cond", + rendered["cond_state"], + tree(rendered["true_value"]), + tree(rendered["false_value"]), + ) + if rendered.get("name") == '"svg"': + return ("svg",) + return ( + rendered["name"], + rendered["props"], + [tree(child) for child in rendered["children"]], + ) From aef7e3df8c80cffdaf0b0476b5c953a00fcd4313 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:23:52 +0000 Subject: [PATCH 195/204] rx.ui on UI SDK, wave B: context_menu, hover_card and tooltip The menus share the parts of @ui-sdk/react/menu: the context menu opens from MenuContextTrigger, and a checkbox item closes its menu and keeps its own state, as in Radix. The hover card and the tooltip are the parts of UI SDK, with the delays and placement of Radix Themes; a tooltip describes its child. The popup behaviour scripts and the native-popover style tables are gone. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- .../js/src/behaviors/dialog.js | 192 ----- .../js/src/behaviors/hover.js | 176 ----- .../js/src/behaviors/keys.js | 65 -- .../js/src/behaviors/listbox.js | 279 ------- .../js/src/behaviors/menu.js | 378 ---------- .../js/src/behaviors/popup-position.js | 48 -- .../js/src/behaviors/popup.js | 286 -------- .../js/tests/behaviors/dialog.test.js | 357 --------- .../js/tests/behaviors/hover.test.js | 277 ------- .../js/tests/behaviors/listbox.test.js | 566 --------------- .../js/tests/behaviors/menu.test.js | 470 ------------ .../js/tests/behaviors/popover.js | 68 -- .../js/tests/behaviors/popup-position.test.js | 107 --- .../js/tests/behaviors/popup.test.js | 471 ------------ .../ui_parity/components/context_menu.py | 8 +- .../parity/ui_parity/components/hover_card.py | 8 +- .../parity/ui_parity/components/tooltip.py | 15 +- .../components/_dialog.py | 8 +- .../reflex_components_ui/components/_menu.py | 669 +++++++---------- .../reflex_components_ui/components/_popup.py | 481 ------------- .../reflex_components_ui/components/_sdk.py | 10 +- .../components/context_menu.py | 67 +- .../components/dropdown_menu.py | 289 +------- .../components/hover_card.py | 78 +- .../components/popover.py | 4 +- .../components/tooltip.py | 178 +++-- .../src/reflex_components_ui/styles/dialog.py | 190 ++--- .../reflex_components_ui/styles/hover_card.py | 11 +- .../src/reflex_components_ui/styles/menu.py | 46 +- .../reflex_components_ui/styles/popover.py | 19 +- .../src/reflex_components_ui/styles/popup.py | 198 +---- .../src/reflex_components_ui/styles/select.py | 4 +- .../reflex_components_ui/styles/tooltip.py | 11 +- .../components/test_context_menu.py | 681 ++++++------------ .../components/test_dropdown_menu.py | 6 +- .../components/test_hover_card.py | 227 ++---- .../components/test_popover.py | 2 +- .../components/test_popup.py | 11 +- .../components/test_select.py | 8 +- .../components/test_theme_panel.py | 6 + .../components/test_tooltip.py | 266 +++---- 41 files changed, 1009 insertions(+), 6232 deletions(-) delete mode 100644 packages/reflex-components-ui/js/src/behaviors/dialog.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/hover.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/keys.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/listbox.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/menu.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/popup-position.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/popup.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/dialog.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/hover.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/listbox.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/menu.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/popover.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/popup.test.js delete mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py diff --git a/packages/reflex-components-ui/js/src/behaviors/dialog.js b/packages/reflex-components-ui/js/src/behaviors/dialog.js deleted file mode 100644 index 70d13dbebe5..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/dialog.js +++ /dev/null @@ -1,192 +0,0 @@ -// What a dialog does that the browser leaves to a script. -// -// The dialog is a native `dialog` opened with `showModal`: the browser puts -// it over everything else, makes the page behind it inert, moves the focus -// in and gives it back, and closes the topmost one on Escape. Left for a -// script: opening it from its trigger and closing it from a button or -// beside its panel where the browser has no commands, saying on the trigger -// that it is open, the events of the dialog, and a dialog bound to state, -// which shows what its state holds. - -const ROOT = "[data-rx-dialog-root]"; - -/** - * @typedef {{ open?: (open: boolean) => void, openAutoFocus?: () => void, closeAutoFocus?: () => void, escape?: () => void, outside?: () => void, interact?: () => void }} Handlers - */ - -/** @type {WeakMap} */ -const dialogs = new WeakMap(); - -/** - * Show on what opens a dialog whether it is open. - * - * @param {HTMLDialogElement} dialog The dialog. - * @param {boolean} open Whether it is open. - * @returns {void} - */ -function mark(dialog, open) { - const root = dialog.closest(ROOT); - for (const trigger of root?.querySelectorAll("[data-rx-dialog-trigger]") ?? - []) { - if (trigger.closest(ROOT) !== root) continue; - trigger.setAttribute("aria-expanded", String(open)); - trigger.setAttribute("data-state", open ? "open" : "closed"); - } -} - -/** - * Open a dialog over the page. - * - * @param {HTMLDialogElement} dialog The dialog. - * @returns {void} - */ -function show(dialog) { - // A drawer that is not modal leaves the page as it is. - if (dialog.dataset.modal === "false") dialog.show(); - else dialog.showModal(); - // The browser scrolls to what it gives the focus: a tall dialog starts - // at its top, as in Radix. - dialog.scrollTop = 0; - // An alert dialog starts on what cancels it, wherever that is in it. - /** @type {HTMLElement | null} */ ( - dialog.querySelector("[data-rx-dialog-close=cancel]") - )?.focus({ preventScroll: true }); - mark(dialog, true); - dialogs.get(dialog)?.on?.openAutoFocus?.(); -} - -/** - * Open or close a dialog as its user asks: a dialog bound to state says so - * to its state instead, and shows what the state then holds. - * - * @param {HTMLDialogElement} dialog The dialog. - * @param {boolean} open Whether to open it. - * @param {...("close" | "escape" | "outside" | "interact")} why What asked - * to close it: its button, Escape, or a press beside its panel. - * @returns {void} - */ -function ask(dialog, open, ...why) { - const { on, bound } = dialogs.get(dialog) ?? {}; - // An alert dialog keeps a press beside its panel from closing it, and - // a drawer that is not dismissible everything but its state. - const { rxKeep } = dialog.dataset; - if (why[0] && (rxKeep === "all" || rxKeep === why[0])) return; - for (const name of why) if (name !== "close") on?.[name]?.(); - if (bound || open) on?.open?.(open); - if (bound) return; - if (open) show(dialog); - else dialog.close(); -} - -/** - * Keep a dialog as its state says: the `ref` of the dialog, called again - * whenever the page renders. - * - * @param {HTMLDialogElement | null} dialog The dialog. - * @param {boolean | null} [open] Whether a dialog bound to state is open. - * @param {Handlers | null} [on] What the dialog does when it opens, closes - * or is dismissed. - * @returns {void} - */ -export function dialogSync(dialog, open, on) { - if (!dialog) return; - const first = !dialogs.has(dialog); - dialogs.set(dialog, { on: on ?? undefined, bound: open != null }); - const wanted = - open ?? (first && dialog.dataset.defaultOpen === "true" ? true : null); - if (wanted === null || wanted === dialog.open) return; - if (wanted) show(dialog); - else dialog.close(); -} - -/** - * Follow a press on what opens a dialog, on what closes it and beside its - * panel: the `onClick` of the element around the dialog. - * - * @param {{ target: EventTarget | null, currentTarget: Element, preventDefault: () => void }} event - * The press. - * @returns {void} - */ -export function dialogClick(event) { - const root = event.currentTarget; - const dialog = root.querySelector("dialog"); - const { target } = event; - if (!dialog || !(target instanceof Element)) return; - const part = target.closest( - "[data-rx-dialog-trigger], [data-rx-dialog-close]", - ); - if (part?.closest(ROOT) === root) { - // The script does what the command of a button asks the browser for. - event.preventDefault(); - if (part.hasAttribute("data-rx-dialog-trigger")) ask(dialog, true); - else ask(dialog, false, "close"); - } else if ( - target === dialog || - (target.parentElement === dialog && - target.hasAttribute("data-rx-dialog-pad")) - ) - ask(dialog, false, "outside", "interact"); -} - -/** - * Follow a dialog that is asked to close and one that has closed: the - * `onCancel` and the `onClose` of the dialog. - * - * Escape asks, as a press beside the panel does. Once closed, by whatever - * closed it, the dialog says so. - * - * @param {{ type: string, target: EventTarget | null, currentTarget: HTMLDialogElement, preventDefault: () => void }} event - * The request or the closing. - * @returns {void} - */ -export function dialogEvent(event) { - const dialog = event.currentTarget; - // React hands a dialog the events of the dialogs inside it too. - if (event.target !== dialog) return; - if (event.type === "cancel") { - event.preventDefault(); - ask(dialog, false, "escape"); - return; - } - const { on, bound } = dialogs.get(dialog) ?? {}; - mark(dialog, false); - if (!bound) on?.open?.(false); - on?.closeAutoFocus?.(); - slidOut(dialog); -} - -/** - * Say that the panels of a closed dialog have slid out where they do not. - * - * Without the `overlay` property of CSS, Firefox and Safari take a modal - * dialog out of the top layer as it closes, so a panel that slides out as - * the dialog closes runs no transition and says nothing. Such a panel is - * given the `transitionend` the browsers that run it send. - * - * @param {HTMLDialogElement} dialog The dialog that has closed. - * @returns {void} - */ -function slidOut(dialog) { - for (const panel of dialog.children) { - if ( - !(panel instanceof HTMLElement) || - !getComputedStyle(panel) - .transitionProperty.split(",") - .some((name) => name.trim() === "transform") || - panel - .getAnimations() - .some( - (animation) => - /** @type {CSSTransition} */ (animation).transitionProperty === - "transform" && animation.playState === "running", - ) - ) - continue; - panel.dispatchEvent( - new TransitionEvent("transitionend", { - bubbles: true, - propertyName: "transform", - }), - ); - } -} diff --git a/packages/reflex-components-ui/js/src/behaviors/hover.js b/packages/reflex-components-ui/js/src/behaviors/hover.js deleted file mode 100644 index f83590e4add..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/hover.js +++ /dev/null @@ -1,176 +0,0 @@ -// A popup that opens under the pointer and with the focus of the keyboard: -// a tooltip, a hover card. -// -// The popup is a native popover the browser puts over everything else and -// CSS places against what opens it. Nothing in a browser opens one on -// hover in every engine, so a script does: after a delay under the pointer, -// at once with the focus of the keyboard, and it closes the popup when -// both have left, on Escape and on a press outside it. Without this the -// popup never shows; a tooltip still describes what it is on. - -/** Whether the browser places a popover beside its anchor by itself. */ -const ANCHORED = globalThis.CSS?.supports?.("position-area: bottom") ?? false; - -let ids = 0; - -/** - * @typedef {{ open?: (open: boolean) => void, escape?: () => void, outside?: () => void }} Handlers - * @typedef {{ on?: Handlers | null, bound?: boolean, timer?: number, off?: () => void }} State - */ - -/** @type {WeakMap} */ -const popups = new WeakMap(); - -/** - * Find what a popup opens under. - * - * @param {HTMLElement} popup The popover. - * @returns {HTMLElement | null} The element that names it. - */ -function triggerOf(popup) { - return document.querySelector(`[data-rx-hover="${popup.id}"]`); -} - -/** - * Open or close a popup, and say so on what it opens under. - * - * While it is open, Escape and a press outside it close it, wherever the - * focus is. - * - * @param {HTMLElement} popup The popover. - * @param {boolean} open Whether to open it. - * @returns {void} - */ -function set(popup, open) { - const state = popups.get(popup); - if (!state || open === popup.matches(":popover-open")) return; - popup.togglePopover(open); - const trigger = triggerOf(popup); - if (trigger) { - const shown = popup.role === "tooltip" ? "delayed-open" : "open"; - trigger.dataset.state = open ? shown : "closed"; - if (!ANCHORED) - import("./popup-position.js").then(({ place }) => - place(popup, trigger, open), - ); - } - state.off?.(); - delete state.off; - if (!open) return; - const dismiss = (/** @type {Event} */ event) => { - if (event.type !== "keydown") { - if (!popup.contains(/** @type {Node} */ (event.target))) - ask(popup, false, "outside"); - } else if (/** @type {KeyboardEvent} */ (event).key === "Escape") { - // Spent on the popup, as the topmost layer: without this, Firefox and - // WebKit also hand the key to a modal dialog the popup is in, which - // closes with it. - event.preventDefault(); - ask(popup, false, "escape"); - } - }; - addEventListener("keydown", dismiss, true); - addEventListener("pointerdown", dismiss, true); - state.off = () => { - removeEventListener("keydown", dismiss, true); - removeEventListener("pointerdown", dismiss, true); - }; -} - -/** - * Open or close a popup as its user asks: a popup bound to state says so - * to its state instead, and shows what the state then holds. - * - * @param {HTMLElement} popup The popover. - * @param {boolean} open Whether to open it. - * @param {"escape" | "outside"} [why] What dismissed it. - * @returns {void} - */ -function ask(popup, open, why) { - const state = popups.get(popup); - if (!state) return; - clearTimeout(state.timer); - if (open === popup.matches(":popover-open")) return; - if (why) state.on?.[why]?.(); - state.on?.open?.(open); - if (!state.bound) set(popup, open); -} - -/** - * Keep a popup as its state says: the `ref` of the popover, called again - * whenever the page renders. - * - * The first time, the popup and what it opens under are given a name no - * other pair of the page has, which CSS places the popup by: the popups a - * loop renders share the id they are rendered with. - * - * @param {HTMLElement | null} popup The popover. - * @param {boolean | null} [open] Whether a popup bound to state is open. - * @param {Handlers | null} [on] What the popup does when it opens, closes - * or is dismissed. - * @returns {void} - */ -export function hoverSync(popup, open, on) { - if (!popup) return; - let state = popups.get(popup); - let wanted = open ?? null; - if (!state) { - popups.set(popup, (state = {})); - const trigger = triggerOf(popup); - if (trigger) { - const id = popup.id.startsWith("rx-") ? `${popup.id}-${++ids}` : popup.id; - if (trigger.getAttribute("aria-describedby") === popup.id) - trigger.setAttribute("aria-describedby", id); - trigger.dataset.rxHover = popup.id = id; - trigger.style.setProperty("anchor-name", `--${id}`); - popup.style.setProperty("position-anchor", `--${id}`); - } - if (popup.dataset.defaultOpen === "true") wanted ??= true; - } - state.on = on; - state.bound = open != null; - if (wanted !== null) set(popup, wanted); -} - -/** - * Follow the pointer and the focus on a popup and on what it opens under: - * the `onPointerEnter`, `onPointerLeave`, `onFocus`, `onBlur` and - * `onPointerDown` of either. - * - * The pointer opens the popup and closes it after the delays the popup - * says, so it can go from one to the other. The focus of the keyboard - * opens a tooltip at once, and a hover card after the same delays, and - * closes it when it leaves both. A press on what a tooltip is on closes - * the tooltip. - * - * @param {{ type: string, currentTarget: HTMLElement, pointerType?: string, relatedTarget?: EventTarget | null }} event - * The pointer or the focus coming or going. - * @returns {void} - */ -export function hoverEvent(event) { - const element = event.currentTarget; - const popup = element.hasAttribute("popover") - ? element - : document.getElementById(element.dataset.rxHover ?? ""); - const state = popup && popups.get(popup); - const { type } = event; - const to = /** @type {Node | null} */ (event.relatedTarget ?? null); - if ( - !state || - event.pointerType === "touch" || - (type === "focus" && !element.matches(":focus-visible")) || - (type === "blur" && (popup.contains(to) || triggerOf(popup)?.contains(to))) - ) - return; - const open = type === "pointerenter" || type === "focus"; - const data = popup.dataset; - // A tooltip follows the focus at once, a hover card after its delays. - const delayed = - type === "pointerenter" || - type === "pointerleave" || - (type !== "pointerdown" && popup.role !== "tooltip"); - const delay = delayed ? Number(open ? data.openDelay : data.closeDelay) : 0; - clearTimeout(state.timer); - if (delay) state.timer = Number(setTimeout(() => ask(popup, open), delay)); - else ask(popup, open); -} diff --git a/packages/reflex-components-ui/js/src/behaviors/keys.js b/packages/reflex-components-ui/js/src/behaviors/keys.js deleted file mode 100644 index 5cf6d8c9405..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/keys.js +++ /dev/null @@ -1,65 +0,0 @@ -// What a list of options and a menu share: the keys that move through -// their items, and typing to find one. - -/** What was typed to find an item, and when it is forgotten. */ -let typed = ""; -let forgetting = 0; - -/** - * Say whether a search is being typed, during which Space is a letter. - * - * @returns {boolean} Whether something was typed less than a second ago. - */ -export function typing() { - return typed !== ""; -} - -/** Forget what was typed: a list that opens or closes starts afresh. */ -export function forget() { - typed = ""; -} - -/** - * Find the item that what was typed leads to. - * - * Typing one letter again goes through the items that start with it. - * - * @param {HTMLElement[]} items The items that can be reached. - * @param {string} key The letter typed. - * @param {Element | null} from The item to start after. - * @param {(item: Element) => string} textOf The text an item is found by. - * @returns {HTMLElement | undefined} The item found. - */ -export function find(items, key, from, textOf) { - clearTimeout(forgetting); - typed += key.toLowerCase(); - forgetting = Number(setTimeout(forget, 1000)); - const repeated = [...typed].every((letter) => letter === typed[0]); - const search = repeated ? typed[0] : typed; - const starts = (/** @type {Element} */ item) => - textOf(item).trim().toLowerCase().startsWith(search); - if (!repeated && from && starts(from)) - return /** @type {HTMLElement} */ (from); - const start = items.indexOf(/** @type {HTMLElement} */ (from)); - return [...items.slice(start + 1), ...items.slice(0, start + 1)].find(starts); -} - -/** - * Find the item an arrow key, Home or End goes to. - * - * @param {HTMLElement[]} items The items that can be reached. - * @param {string} key The key. - * @param {number} at The place of the item that has the focus, or -1. - * @param {boolean} [loop] Whether the arrows go round from one end to the other. - * @returns {HTMLElement | undefined | null} The item, or null for a key - * that moves nowhere. - */ -export function move(items, key, at, loop = false) { - const last = items.length - 1; - if (key === "Home") return items[0]; - if (key === "End") return items[last]; - if (key === "ArrowDown") return items[at < last ? at + 1 : loop ? 0 : last]; - if (key === "ArrowUp") - return items[at > 0 ? at - 1 : loop || at < 0 ? last : 0]; - return null; -} diff --git a/packages/reflex-components-ui/js/src/behaviors/listbox.js b/packages/reflex-components-ui/js/src/behaviors/listbox.js deleted file mode 100644 index c2f2bd77f04..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/listbox.js +++ /dev/null @@ -1,279 +0,0 @@ -// What a select does that the browser leaves to a script: the keys that -// move through its options, typing to find one, and the value it keeps. -// -// The list is a popup the browser opens, closes and places. The value is -// the one of a text input no one sees, so a form submits it, a required -// select holds its form back, and React hears of a change as it does of -// any input. Without this the select opens and closes, and chooses nothing. - -import { find, forget, move, typing } from "./keys.js"; -import { closedBy, opener, pair, popupPlace, popupToggle } from "./popup.js"; - -const OPTION = "[role=option]"; -const ENABLED = `${OPTION}:not([aria-disabled=true])`; - -/** - * Find the parts of a select. - * - * @param {Element} select The element around the select. - * @returns {{ trigger: HTMLElement | null, popup: HTMLElement | null, holder: HTMLInputElement | null }} - * What opens the list, the list, and the input that holds the value. - */ -function parts(select) { - return { - trigger: select.querySelector("[role=combobox]"), - popup: select.querySelector("[popover]"), - holder: select.querySelector("input[data-rx-select-value]"), - }; -} - -/** - * Read the text an option shows. - * - * @param {Element} option The option. - * @returns {string} Its text, without what marks it as chosen. - */ -function textOf(option) { - return ( - (option.querySelector("[data-rx-select-text]") ?? option).textContent ?? "" - ); -} - -/** - * Show the value of a select on its options and on what opens it: the - * `ref` of the input that holds the value, called again whenever the page - * renders. - * - * The chosen option says so, and its text is the text of the trigger, or - * the placeholder when nothing is chosen. A select bound to state takes its - * value, and whether it is open, from there. - * - * @param {Element | null} holder The input that holds the value. - * @param {string | null} [value] The value of a select bound to state. - * @param {boolean | null} [open] Whether a select bound to state is open. - * @returns {void} - */ -export function syncSelect(holder, value, open) { - const select = /** @type {HTMLElement | null | undefined} */ ( - holder?.closest("[data-rx-select]") - ); - if (!select) return; - const { trigger, popup } = parts(select); - if (!trigger || !popup || !(holder instanceof HTMLInputElement)) return; - pair(popup, trigger); - if (value !== undefined && value !== null) { - // What the select goes back to when a choice changes nothing in state. - select.dataset.rxValue = value; - if (holder.value !== value) holder.value = value; - } - show(select, trigger, holder.value); - const starts = select.getAttribute("data-default-open") === "true"; - select.removeAttribute("data-default-open"); - const wanted = open ?? (starts ? true : null); - if (wanted !== null && wanted !== popup.matches(":popover-open")) { - popup.dataset.rxClosedBy = "state"; - popup.togglePopover(wanted); - } -} - -/** - * Show a value on the options of a select and on what opens it. - * - * @param {Element} select The element around the select. - * @param {Element} trigger What opens the list. - * @param {string} current The value. - * @returns {void} - */ -function show(select, trigger, current) { - let chosen = null; - for (const option of select.querySelectorAll(OPTION)) { - const on = current !== "" && option.getAttribute("data-value") === current; - option.setAttribute("aria-selected", String(on)); - option.setAttribute("data-state", on ? "checked" : "unchecked"); - if (on) chosen ??= option; - } - const shown = trigger.querySelector("[data-rx-select-shown]"); - if (shown instanceof HTMLElement) { - const text = chosen ? textOf(chosen) : (shown.dataset.placeholder ?? ""); - // The node React rendered keeps its place: React may write to it again. - if (shown.firstChild) shown.firstChild.nodeValue = text; - else shown.textContent = text; - trigger.toggleAttribute("data-placeholder", !chosen); - } -} - -/** - * Choose an option: the list closes, and the value changes if it differs. - * - * @param {Element} select The element around the select. - * @param {Element} option The option. - * @returns {void} - */ -function choose(select, option) { - const { trigger, popup, holder } = parts(select); - const value = option.getAttribute("data-value") ?? ""; - if (popup?.matches(":popover-open")) { - popup.dataset.rxClosedBy = "choice"; - popup.hidePopover(); - } - if (!trigger || !holder || holder.value === value) return; - const setter = - /** @type {(this: HTMLInputElement, value: string) => void} */ ( - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set - ); - setter.call(holder, value); - // As a user types it, so that React hears of it. - holder.dispatchEvent(new Event("input", { bubbles: true })); - // A select bound to state shows the value of the state, which follows or - // does not. - const bound = /** @type {HTMLElement} */ (select).dataset.rxValue; - if (bound !== undefined) holder.value = bound; - show(select, trigger, holder.value); -} - -/** - * The keys of a select: the `onKeyDown` of the element around it. - * - * On the trigger the arrow keys open the list, and a letter chooses the - * next option that starts with what is typed. In the list the arrow keys, - * Home and End move through the options, a letter goes to one, Enter and - * Space choose, and Tab stays. - * - * @param {{ key: string, target: EventTarget | null, currentTarget: Element, preventDefault: () => void, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean }} event - * The key going down inside the select. - * @returns {void} - */ -export function selectKeyDown(event) { - const select = event.currentTarget; - const { trigger, popup, holder } = parts(select); - if (!trigger || !popup || !holder) return; - const { key } = event; - const options = /** @type {HTMLElement[]} */ ([ - ...select.querySelectorAll(ENABLED), - ]); - const letter = - key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey; - if (!popup.matches(":popover-open")) { - if (event.target !== trigger || trigger.matches(":disabled")) return; - if (key === "ArrowDown" || key === "ArrowUp") { - event.preventDefault(); - trigger.click(); - } else if (letter && (key !== " " || typing())) { - event.preventDefault(); - const current = options.find( - (option) => option.dataset.value === holder.value, - ); - const found = find(options, key, current ?? null, textOf); - if (found) choose(select, found); - } - return; - } - // The browser closes the list: its toggle says that the key did. - if (key === "Escape") popup.dataset.rxClosedBy = "escape"; - const at = options.indexOf( - /** @type {HTMLElement} */ (document.activeElement), - ); - let next = move(options, key, at); - if (key === "Enter" || (key === " " && !typing())) { - event.preventDefault(); - if (at >= 0) choose(select, options[at]); - return; - } else if (key === "Tab") { - event.preventDefault(); - return; - } else if (next === null) { - if (!letter) return; - next = find(options, key, options[at] ?? null, textOf); - } - event.preventDefault(); - next?.focus(); -} - -/** - * Choose the option under the pointer: the `onClick` of the element around - * a select. - * - * @param {{ target: EventTarget | null, currentTarget: Element }} event The click. - * @returns {void} - */ -export function selectClick(event) { - const option = - event.target instanceof Element ? event.target.closest(ENABLED) : null; - if (option) choose(event.currentTarget, option); -} - -/** - * Give the option under the pointer the focus, which is what marks it: the - * `onPointerMove` of the element around a select. - * - * @param {{ target: EventTarget | null, currentTarget: Element }} event The pointer moving. - * @returns {void} - */ -export function selectPointerMove(event) { - const target = event.target instanceof Element ? event.target : null; - const option = target?.closest(ENABLED); - if (option instanceof HTMLElement) { - if (option !== document.activeElement) - option.focus({ preventScroll: true }); - } else if (target?.closest("[popover]")) { - parts(event.currentTarget).popup?.focus({ preventScroll: true }); - } -} - -/** - * Follow the list of a select that opens or closes: the `onBeforeToggle` and - * the `onToggle` of its popover. - * - * The select says it opens or closes as soon as it is about to. The chosen - * option takes the focus once the list is shown, or the first one, and the - * trigger has it back when the list closes. - * - * @param {{ type?: string, currentTarget: HTMLElement, newState?: string }} event - * The toggle to come or done. - * @param {{ open?: (open: boolean) => void, close?: () => void, escape?: () => void, outside?: () => void }} [on] - * What the select does when its list opens or closes, when it has closed, - * and when Escape or a pointer outside the list closed it. - * @returns {void} - */ -export function selectToggle(event, on) { - const popup = event.currentTarget; - if (event.type === "toggle") { - popupPlace(popup); - if (!popup.matches(":popover-open")) return; - const options = /** @type {HTMLElement[]} */ ([ - ...popup.querySelectorAll(ENABLED), - ]); - ( - options.find( - (option) => option.getAttribute("aria-selected") === "true", - ) ?? - options[0] ?? - popup - ).focus(); - return; - } - const open = popupToggle(event); - const by = open ? popup.dataset.rxClosedBy : closedBy(popup); - delete popup.dataset.rxClosedBy; - forget(); - on?.open?.(open); - if (open) return; - if (popup.contains(document.activeElement)) - /** @type {HTMLElement | null} */ (opener(popup))?.focus(); - if (by === "escape") on?.escape?.(); - else if (!by) on?.outside?.(); - on?.close?.(); -} - -/** - * Hand the focus the input of the value is given to the trigger: the - * `onFocus` of the input, which a form gives the focus when it is required - * and empty. - * - * @param {{ currentTarget: Element }} event The focus. - * @returns {void} - */ -export function selectFocus(event) { - const select = event.currentTarget.closest("[data-rx-select]"); - if (select) parts(select).trigger?.focus(); -} diff --git a/packages/reflex-components-ui/js/src/behaviors/menu.js b/packages/reflex-components-ui/js/src/behaviors/menu.js deleted file mode 100644 index 57a79674d1c..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/menu.js +++ /dev/null @@ -1,378 +0,0 @@ -// A menu: a native popover of items beside the button that opens it, at -// the pointer for a context menu, or beside an item for a sub-menu. -// -// The browser opens the menu of a dropdown from its trigger, puts it over -// everything else, and closes it on Escape and on a press outside, the -// topmost menu first. What is left for a script: the keys that move through -// the items, typing to find one, choosing one, the sub-menus, the checkbox -// items, and the context menu, which opens where the pointer is. Without -// this a dropdown menu opens and closes, and its items do nothing. - -import { find, forget, move, typing } from "./keys.js"; -import { - closedBy, - opener, - popupPlace, - popupSync, - popupToggle, -} from "./popup.js"; - -const MENU = "[role=menu]"; -const ITEM = "[role^=menuitem]"; -const ENABLED = `${ITEM}:not([aria-disabled="true"])`; - -/** How long the pointer rests on an item before its sub-menu opens, in ms. */ -const SUB_DELAY = 100; - -let anchors = 0; -let opening = 0; - -/** - * Find the menu an element is in. - * - * @param {Element} element The element. - * @returns {HTMLElement | null} The innermost menu around it, itself included. - */ -function menuOf(element) { - return element.closest(MENU); -} - -/** - * Find the items of a menu that can be reached, not those of its sub-menus. - * - * @param {Element} menu The menu. - * @returns {HTMLElement[]} The items that are not disabled, in order. - */ -function itemsOf(menu) { - return /** @type {HTMLElement[]} */ ([ - ...menu.querySelectorAll(ENABLED), - ]).filter((item) => menuOf(item) === menu); -} - -/** - * Find the sub-menu an item opens. - * - * @param {Element} item The item. - * @returns {HTMLElement | null} The sub-menu, or null for another item. - */ -function subOf(item) { - const id = item.getAttribute("data-rx-opens"); - return id ? document.getElementById(id) : null; -} - -/** - * Find the outermost menu around one: the one a choice closes. - * - * @param {HTMLElement} menu The menu. - * @returns {HTMLElement} The menu that holds it, or itself. - */ -function rootOf(menu) { - const outer = menu.parentElement && menuOf(menu.parentElement); - return outer ? rootOf(outer) : menu; -} - -/** - * Find the sub-menus open inside a menu. - * - * @param {Element} menu The menu. - * @returns {HTMLElement[]} Each open sub-menu, outermost first. - */ -function openSubs(menu) { - return /** @type {HTMLElement[]} */ ([...menu.querySelectorAll(MENU)]).filter( - (sub) => sub.matches(":popover-open"), - ); -} - -/** - * Close a menu, and say why to what follows its toggle. - * - * @param {HTMLElement} menu The menu. - * @param {string} why What closed it. - * @returns {void} - */ -function close(menu, why) { - if (!menu.matches(":popover-open")) return; - menu.dataset.rxClosedBy = why; - menu.hidePopover(); -} - -/** - * Close the sub-menus a menu has open, but the one of an item. - * - * @param {HTMLElement} menu The menu. - * @param {Element | null} [kept] The item whose sub-menu stays open. - * @returns {void} - */ -function closeSubs(menu, kept) { - clearTimeout(opening); - for (const item of itemsOf(menu)) { - const sub = item !== kept && subOf(item); - if (sub) close(sub, "pointer"); - } -} - -/** - * Open the sub-menu of an item. - * - * @param {Element} item The item. - * @param {boolean} keyboard Whether a key opens it, which moves the focus - * to its first item. - * @returns {void} - */ -function openSub(item, keyboard) { - clearTimeout(opening); - const sub = subOf(item); - if (!sub) return; - if (sub.matches(":popover-open")) { - if (keyboard) itemsOf(sub)[0]?.focus(); - return; - } - if (keyboard) sub.dataset.rxKeyboard = "true"; - sub.showPopover(); -} - -/** - * Keep a menu as its state says: the `ref` of the popover, called again - * whenever the page renders. - * - * A menu that nothing opens with `popovertarget`, a sub-menu or a context - * menu, is placed against the element rendered right before it: the item - * that opens it, or the point a context menu opens at. - * - * @param {HTMLElement | null} menu The popover. - * @param {boolean | null} [open] Whether a menu bound to state is open. - * @returns {void} - */ -export function menuSync(menu, open) { - if (!menu) return; - const anchor = menu.previousElementSibling; - if ( - anchor instanceof HTMLElement && - !anchor.hasAttribute("popovertarget") && - !menu.style.getPropertyValue("position-anchor") - ) { - const name = `--rx-menu-${++anchors}`; - anchor.style.setProperty("anchor-name", name); - menu.style.setProperty("position-anchor", name); - } - popupSync(menu, open); -} - -/** - * Follow the keys on what opens a dropdown menu: its `onKeyDown`. - * - * Enter, Space and the down arrow open the menu with the focus on its - * first item; the down arrow does what a press does. - * - * @param {{ type: string, key?: string, currentTarget: Element, preventDefault: () => void }} event - * The key going down. - * @returns {void} - */ -export function menuTrigger(event) { - const trigger = event.currentTarget; - const menu = document.getElementById( - trigger.getAttribute("popovertarget") ?? "", - ); - if (!menu) return; - const { key } = event; - if (key !== "Enter" && key !== " " && key !== "ArrowDown") { - delete menu.dataset.rxKeyboard; - return; - } - menu.dataset.rxKeyboard = "true"; - if (key === "ArrowDown") { - event.preventDefault(); - if (!menu.matches(":popover-open")) - /** @type {HTMLElement} */ (trigger).click(); - } -} - -/** - * Open a context menu where it is asked for: the `onContextMenu` of the - * element it is on. - * - * It opens at the pointer, or for the context-menu key and Shift+F10 where - * the browser says, with the focus on its first item. - * - * @param {{ currentTarget: Element, clientX: number, clientY: number, button: number, preventDefault: () => void }} event - * The context menu asked for. - * @returns {void} - */ -export function menuContext(event) { - const area = event.currentTarget; - const menu = document.getElementById( - area.getAttribute("data-rx-opens") ?? "", - ); - const point = menu?.previousElementSibling; - if ( - !menu || - !(point instanceof HTMLElement) || - area.hasAttribute("data-disabled") - ) - return; - event.preventDefault(); - point.style.left = `${event.clientX}px`; - point.style.top = `${event.clientY}px`; - close(menu, "state"); - if (event.button !== 2) menu.dataset.rxKeyboard = "true"; - menu.showPopover(); -} - -/** - * Check or uncheck a checkbox item: its `onClick`. - * - * @param {{ currentTarget: Element }} event The press. - * @param {((checked: boolean) => void) | null} [change] What the item does - * when it changes. - * @param {boolean} [bound] Whether the item shows the state it is bound to - * rather than its own. - * @returns {void} - */ -export function menuCheck(event, change, bound) { - const item = event.currentTarget; - if (item.getAttribute("aria-disabled") === "true") return; - const checked = item.getAttribute("aria-checked") !== "true"; - if (!bound) { - item.setAttribute("aria-checked", String(checked)); - item.setAttribute("data-state", checked ? "checked" : "unchecked"); - } - change?.(checked); -} - -/** - * Follow what happens in a menu: the `onBeforeToggle`, `onToggle`, - * `onKeyDown`, `onClick`, `onPointerMove`, `onPointerLeave` and `onBlur` of - * its popover. - * - * The arrow keys, Home and End move through the items, a letter goes to - * one, Enter and Space choose, and Tab stays. A choice closes every menu - * and gives the focus back to the trigger. The right arrow and the pointer - * open a sub-menu, and the left arrow closes it. The menu says when it - * opens and closes, and what closed it. - * - * @param {{ type: string, target: EventTarget | null, currentTarget: HTMLElement, newState?: string, key?: string, relatedTarget?: EventTarget | null, pointerType?: string, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean, preventDefault: () => void }} event - * What happened. - * @param {{ open?: (open: boolean) => void, closeAutoFocus?: () => void, escape?: () => void, outside?: () => void, focusOutside?: () => void, interact?: () => void } | null} [on] - * What the menu does when it opens, closes or is dismissed. - * @returns {void} - */ -export function menuEvent(event, on) { - const menu = event.currentTarget; - const { type } = event; - const target = event.target instanceof Element ? event.target : null; - const data = menu.dataset; - if (type === "toggle") { - // The menu takes the focus once it is shown. - if (target !== menu) return; - const keyboard = data.rxKeyboard; - delete data.rxKeyboard; - popupPlace(menu); - if (!menu.matches(":popover-open")) return; - if (keyboard) (itemsOf(menu)[0] ?? menu).focus(); - else if (rootOf(menu) === menu) menu.focus(); - return; - } - if (type === "beforetoggle") { - if (target !== menu) return; - const open = popupToggle(event); - const by = open ? data.rxClosedBy : closedBy(menu); - delete data.rxClosedBy; - forget(); - if (open) { - if (by !== "state") on?.open?.(true); - return; - } - if (by === "escape" || by === "choice" || by === "left") - /** @type {HTMLElement | null} */ (opener(menu))?.focus(); - if (by === "escape") on?.escape?.(); - if (by === "focus") on?.focusOutside?.(); - if (!by) on?.outside?.(); - if (!by || by === "focus") on?.interact?.(); - if (by !== "state") on?.open?.(false); - on?.closeAutoFocus?.(); - return; - } - if (!target || menuOf(target) !== menu) return; - const items = itemsOf(menu); - const item = /** @type {HTMLElement | null} */ (target.closest(ENABLED)); - if (type === "blur") { - const to = event.relatedTarget; - // A press outside the menu is the browser's to close it by. - if ( - to instanceof Element && - !menu.contains(to) && - to !== opener(menu) && - !to.matches(":active") - ) - close(menu, "focus"); - } else if (type === "click") { - if (!item) return; - if (subOf(item)) return openSub(item, false); - const root = rootOf(menu); - for (const sub of openSubs(root)) sub.dataset.rxClosedBy = "state"; - close(root, "choice"); - } else if (type === "pointermove") { - if (event.pointerType !== "mouse") return; - if (!item) { - if (!openSubs(menu).length) menu.focus({ preventScroll: true }); - return; - } - if (item !== document.activeElement) item.focus({ preventScroll: true }); - closeSubs(menu, item); - if (subOf(item) && !subOf(item)?.matches(":popover-open")) - opening = Number(setTimeout(() => openSub(item, false), SUB_DELAY)); - } else if (type === "pointerleave") { - clearTimeout(opening); - const at = /** @type {Element} */ (document.activeElement); - if (items.includes(/** @type {HTMLElement} */ (at)) && !subOf(at)) - menu.focus({ preventScroll: true }); - } else if (type === "keydown") { - const { key = "" } = event; - if (key === "Escape") { - // The browser closes the topmost menu: a sub-menu the pointer opened. - (openSubs(menu).pop() ?? menu).dataset.rxClosedBy = "escape"; - return; - } - const at = items.indexOf( - /** @type {HTMLElement} */ (document.activeElement), - ); - const focused = items[at]; - const letter = - key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey; - if (key === "Tab") { - event.preventDefault(); - return; - } - if (focused && (key === "Enter" || (key === " " && !typing()))) { - event.preventDefault(); - if (subOf(focused)) openSub(focused, true); - else focused.click(); - return; - } - if (key === "ArrowRight" && focused && subOf(focused)) { - event.preventDefault(); - openSub(focused, true); - return; - } - if (key === "ArrowLeft" && rootOf(menu) !== menu) { - event.preventDefault(); - close(menu, "left"); - return; - } - let next = move(items, key, at, menu.dataset.loop === "true"); - if (next === null) { - if (!letter) return; - next = find( - items, - key, - focused ?? null, - (one) => one.getAttribute("data-text-value") ?? one.textContent ?? "", - ); - } - event.preventDefault(); - if (next) { - closeSubs(menu, next); - next.focus(); - } - } -} diff --git a/packages/reflex-components-ui/js/src/behaviors/popup-position.js b/packages/reflex-components-ui/js/src/behaviors/popup-position.js deleted file mode 100644 index 0551bf0e69e..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/popup-position.js +++ /dev/null @@ -1,48 +0,0 @@ -// Where a popup goes in a browser without CSS anchor positioning: loaded on -// demand, only there. -// -// The popup is placed below what opens it, at its start, at least as wide, -// and above it where there is more room and it would leave the viewport. - -/** @type {WeakMap void>} */ -const following = new WeakMap(); - -/** The room kept between a popup and the edge of the viewport, in pixels. */ -const EDGE = 10; - -/** - * Place a popup beside its anchor, and keep it there while it is open. - * - * @param {HTMLElement} popup The popover. - * @param {Element} anchor What opens it. - * @param {boolean} open Whether the popup is open. - * @returns {void} - */ -export function place(popup, anchor, open) { - following.get(popup)?.(); - following.delete(popup); - if (!open) return; - const gap = Number.parseFloat(getComputedStyle(popup).marginTop) || 0; - const update = () => { - const box = anchor.getBoundingClientRect(); - const below = innerHeight - box.bottom - gap - EDGE; - const above = box.top - gap - EDGE; - const height = popup.offsetHeight; - const over = height > below && above > below; - const style = popup.style; - style.position = "fixed"; - style.inset = "auto"; - style.minWidth = `${box.width}px`; - style.maxHeight = `${Math.max(over ? above : below, 0)}px`; - // On whole pixels, as Radix puts the popups it places. - style.left = `${Math.round(Math.max(Math.min(box.left, innerWidth - popup.offsetWidth - EDGE), EDGE))}px`; - style.top = `${Math.round(over ? box.top - Math.min(height, above) - gap * 2 : box.bottom)}px`; - }; - update(); - addEventListener("scroll", update, true); - addEventListener("resize", update); - following.set(popup, () => { - removeEventListener("scroll", update, true); - removeEventListener("resize", update); - }); -} diff --git a/packages/reflex-components-ui/js/src/behaviors/popup.js b/packages/reflex-components-ui/js/src/behaviors/popup.js deleted file mode 100644 index a65a65ab029..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/popup.js +++ /dev/null @@ -1,286 +0,0 @@ -// A popup: a native popover placed beside the element that opens it. -// -// The browser opens it from its `popovertarget`, puts it over everything -// else, closes it on Escape and on a pointer outside it, and gives the -// focus back. CSS places it against its anchor and turns it over where it -// would leave the viewport. What is left for a script is to say on the -// element that opens it that it is open, and to place it where the browser -// has no anchor positioning: that part is loaded only there. - -/** Whether the browser places a popover beside its anchor by itself. */ -const ANCHORED = globalThis.CSS?.supports?.("position-area: bottom") ?? false; - -let ids = 0; - -// Whether an Escape is being handled: the browser closes the popovers it -// dismisses in the task of the key, wherever the focus is. -let escaping = false; -globalThis.addEventListener?.( - "keydown", - (event) => { - if (event.key !== "Escape" || escaping) return; - escaping = true; - setTimeout(() => { - escaping = false; - }); - }, - true, -); - -/** - * Take what closed a popup that is closing: what a script said, or Escape - * when the popup closes in the task of the key. The key closes one popup: - * the first that closes after it. - * - * @param {HTMLElement} popup The popover. - * @returns {string | undefined} What closed it, if anything said. - */ -export function closedBy(popup) { - const by = popup.dataset.rxClosedBy ?? (escaping ? "escape" : undefined); - delete popup.dataset.rxClosedBy; - escaping = false; - return by; -} - -/** - * Find what opens a popup. - * - * @param {Element} popup The popover. - * @returns {Element | null} The first element whose `popovertarget` it is, - * or that a script opens it from: an item of a menu that opens a - * sub-menu, the element a context menu is on. - */ -export function opener(popup) { - return popup.id - ? document.querySelector( - `[popovertarget="${popup.id}"], [data-rx-opens="${popup.id}"]`, - ) - : null; -} - -/** - * Give a popup and what opens it an id no other popup of the page has. - * - * A page renders one id for each popup written, so the popups a loop - * renders share one: the first sync of each makes them distinct. - * - * @param {Element} popup The popover. - * @param {Element | null} trigger What opens it. - * @returns {void} - */ -export function pair(popup, trigger) { - // An id an app gave a popup is its own to keep. - if ( - !trigger || - !popup.id.startsWith("rx-") || - popup.hasAttribute("data-rx-popup-paired") - ) - return; - // What closes the popup from inside it names it too. - const named = [ - trigger, - ...popup.querySelectorAll(`[popovertarget="${popup.id}"]`), - ]; - popup.id = `${popup.id || "rx-popup"}-${++ids}`; - popup.setAttribute("data-rx-popup-paired", ""); - for (const element of named) - element.setAttribute( - element.hasAttribute("data-rx-opens") ? "data-rx-opens" : "popovertarget", - popup.id, - ); - trigger.setAttribute("aria-controls", popup.id); -} - -/** What says how far a popup is from whole pixels, across and down. */ -const SNAP = ["--rx-popup-snap-x", "--rx-popup-snap-y"]; - -/** - * Say how far a popup is laid out from whole pixels. - * - * Where it is laid out is read from where it is drawn, less the transform - * it comes in with. - * - * @param {HTMLElement} popup The popover. - * @returns {number[]} What brings it to whole pixels, across and down. - */ -function off(popup) { - const { transform, transformOrigin } = getComputedStyle(popup); - const [a = 1, , , d = 1, e = 0, f = 0] = ( - transform.match(/-?[\d.]+(e-?\d+)?/g) ?? [] - ).map(Number); - const [x = 0, y = 0] = transformOrigin - .split(" ") - .map((length) => Number.parseFloat(length) || 0); - const box = popup.getBoundingClientRect(); - const ratio = globalThis.devicePixelRatio || 1; - return [box.x - x * (1 - a) - e, box.y - y * (1 - d) - f].map((at) => { - // In the units a browser lays out in: a sixty-fourth of a pixel, or - // close to it, and what is left of one is nothing. - const by = Math.round((Math.round(at * ratio) / ratio - at) * 64) / 64; - return Math.abs(by) < 0.02 ? 0 : by; - }); -} - -/** - * Put an open popup on whole pixels, as Radix puts the ones it places. - * - * A popup that ends at the end of its anchor, or is centered on it, starts - * on a fraction of a pixel when its width has one. Its styles move it by - * what is written here, in its margins: it is laid out there, not drawn - * there by a transform, which would blur it. - * - * @param {HTMLElement} popup The popover. - * @returns {void} - */ -function snap(popup) { - const { style } = popup; - for (const name of SNAP) style.removeProperty(name); - const wanted = off(popup); - wanted.forEach((by, axis) => by && style.setProperty(SNAP[axis], `${by}px`)); - // A popup the browser turned over has its margins turned over with it. - off(popup).forEach( - (left, axis) => left && style.setProperty(SNAP[axis], `${-wanted[axis]}px`), - ); -} - -/** - * Follow a popup that is about to open or close: its `onBeforeToggle`. - * - * What opens it says so in `aria-expanded` and `data-state`, for styles and - * for assistive technology, at once: the browser sends the `toggle` that - * follows in a task of its own, one for every change made before it runs, - * so a popup opened and closed in between is never said to be open by it. - * - * @param {{ currentTarget: HTMLElement, newState?: string }} event The toggle to come. - * @returns {boolean} Whether the popup is opening. - */ -export function popupToggle(event) { - const popup = event.currentTarget; - const open = event.newState === "open"; - const trigger = opener(popup); - if (trigger) { - trigger.setAttribute("aria-expanded", String(open)); - trigger.setAttribute("data-state", open ? "open" : "closed"); - } - return open; -} - -/** - * Place a popup that is shown, or no longer, where the browser has no anchor - * positioning: once it is laid out, on its `onToggle`. - * - * @param {HTMLElement} popup The popover. - * @returns {void} - */ -export function popupPlace(popup) { - const trigger = opener(popup); - if (!ANCHORED && trigger) { - import("./popup-position.js").then(({ place }) => - place(popup, trigger, popup.matches(":popover-open")), - ); - } -} - -/** - * Keep a popup as its state says: the `ref` of the popover, called again - * whenever the page renders. - * - * @param {HTMLElement | null} popup The popover. - * @param {boolean | null} [open] Whether a popup bound to state is open. - * @returns {void} - */ -export function popupSync(popup, open) { - if (!popup) return; - pair(popup, opener(popup)); - // The browser opens a popup from its trigger before the page is hydrated. - if (popup.matches(":popover-open")) - popupToggle({ currentTarget: popup, newState: "open" }); - const starts = popup.dataset.defaultOpen === "true"; - delete popup.dataset.defaultOpen; - const wanted = open ?? (starts || null); - if (wanted !== null && wanted !== popup.matches(":popover-open")) { - popup.dataset.rxClosedBy = "state"; - popup.togglePopover(wanted); - } -} - -/** - * Follow a popup that holds controls of its own, as a popover does: its - * `onBeforeToggle`, `onToggle`, `onKeyDown`, `onClick` and `onBlur`. - * - * The popup takes the focus when it opens, and closes when the focus - * leaves it for anything but what opens it, as in Radix. It says when it - * opens and closes, and what closed it: Escape, the focus, or a pointer - * outside it. - * - * @param {{ type: string, target: EventTarget | null, currentTarget: HTMLElement, newState?: string, key?: string, relatedTarget?: EventTarget | null }} event - * The toggle to come or done, the key going down, the press or the focus - * leaving. - * @param {{ open?: (open: boolean) => void, openAutoFocus?: () => void, closeAutoFocus?: () => void, escape?: () => void, outside?: () => void, focusOutside?: () => void, interact?: () => void } | null} [on] - * What the popup does when it opens, closes or is dismissed. - * @returns {void} - */ -export function popupEvent(event, on) { - const popup = event.currentTarget; - const { type, target } = event; - const data = popup.dataset; - if (type === "keydown") { - if (event.key === "Escape") data.rxClosedBy = "escape"; - } else if (type === "click") { - if ( - target instanceof Element && - target.closest("[popovertargetaction=hide]") - ) - data.rxClosedBy = "close"; - } else if (type === "blur") { - const to = event.relatedTarget; - // A press outside the popup is the browser's to close it by. - if ( - to instanceof Element && - !popup.contains(to) && - to !== opener(popup) && - !to.matches(":active") - ) { - data.rxClosedBy = "focus"; - popup.hidePopover(); - } - } else if (target === popup && type === "toggle") { - popupPlace(popup); - if (popup.matches(":popover-open")) { - popup.focus(); - on?.openAutoFocus?.(); - } - } else if (target === popup) { - const open = popupToggle(event); - const by = open ? popup.dataset.rxClosedBy : closedBy(popup); - delete data.rxClosedBy; - if (open) { - if (by !== "state") on?.open?.(open); - return; - } - if (by === "escape") on?.escape?.(); - if (by === "focus") on?.focusOutside?.(); - if (!by) on?.outside?.(); - if (!by || by === "focus") on?.interact?.(); - if (by !== "state") on?.open?.(open); - on?.closeAutoFocus?.(); - } -} - -/** - * Put a popup that is about to open on whole pixels before it is first - * drawn: the `onBeforeToggle` of the popover. - * - * The browser keeps the fraction of a pixel a popover is first drawn at, in - * the edges of its letters, so moving it once it has been seen is too late: - * it is moved in the frame that shows it. - * - * @param {{ currentTarget: HTMLElement, newState?: string }} event The toggle to come. - * @returns {void} - */ -export function popupBeforeToggle(event) { - const popup = event.currentTarget; - if (ANCHORED && event.newState === "open") { - requestAnimationFrame(() => snap(popup)); - } -} diff --git a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js b/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js deleted file mode 100644 index b2a0a8d0776..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/dialog.test.js +++ /dev/null @@ -1,357 +0,0 @@ -// What a dialog does with a press on its trigger, on a button that closes -// it and beside its panel, with Escape, and with the state it is bound to. -import { beforeEach, expect, test } from "vitest"; - -import { - dialogClick, - dialogEvent, - dialogSync, -} from "$/reflex-ui/behaviors/dialog.js"; - -// What jsdom has of a modal dialog: the attribute. These open and close -// one as a browser does, and send the event a browser sends. -HTMLDialogElement.prototype.showModal = function () { - this.open = true; -}; -HTMLDialogElement.prototype.close = function () { - if (!this.open) return; - this.open = false; - dialogEvent({ - type: "close", - target: this, - currentTarget: this, - preventDefault: () => {}, - }); -}; - -/** @type {HTMLElement} */ -let root; -/** @type {HTMLDialogElement} */ -let dialog; - -/** - * Render a dialog with a dialog of its own inside its panel. - * - * @param {string} [attributes] The attributes of the dialog. - * @returns {void} - */ -function render(attributes = "") { - document.body.innerHTML = ` -
- - -
-
- -
- -
-
-
-
-
-
- `; - root = /** @type {HTMLElement} */ (document.getElementById("root")); - dialog = /** @type {HTMLDialogElement} */ (document.getElementById("dialog")); -} - -beforeEach(() => render()); - -/** - * Make the handlers of a dialog, which keep what they are called with. - * - * @returns {{ on: Record void>, seen: string[] }} - * The handlers, and what was called, in order. - */ -function handlers() { - /** @type {string[]} */ - const seen = []; - const on = Object.fromEntries( - [ - "open", - "openAutoFocus", - "closeAutoFocus", - "escape", - "outside", - "interact", - ].map((name) => [ - name, - (/** @type {boolean | undefined} */ open) => - seen.push(open === undefined ? name : `${name}:${open}`), - ]), - ); - return { on, seen }; -} - -/** - * Press an element, as the element around the dialog hears it. - * - * @param {string | null} id The id of the element, or null for no element. - * @param {HTMLElement} [around] The element that hears the press. - * @returns {boolean} Whether the dialog kept the press from the browser. - */ -function press(id, around = root) { - let prevented = false; - dialogClick({ - target: id ? document.getElementById(id) : null, - currentTarget: around, - preventDefault: () => { - prevented = true; - }, - }); - return prevented; -} - -/** - * Press Escape in a dialog, as the dialog hears it. - * - * @param {HTMLDialogElement} [target] The dialog the key is pressed in. - * @returns {boolean} Whether the dialog kept the browser from closing it. - */ -function escape(target = dialog) { - let prevented = false; - dialogEvent({ - type: "cancel", - target, - currentTarget: dialog, - preventDefault: () => { - prevented = true; - }, - }); - return prevented; -} - -/** - * Read what the trigger says of its dialog. - * - * @returns {string} Whether the dialog is open, to assistive technology - * and to styles. - */ -function said() { - const trigger = /** @type {HTMLElement} */ (document.getElementById("open")); - return `${trigger.getAttribute("aria-expanded")}:${trigger.dataset.state}`; -} - -test("a press on the trigger opens the dialog, and one on its button closes it", () => { - const { on, seen } = handlers(); - dialogSync(dialog, null, on); - dialog.scrollTop = 40; - expect(press("open-text")).toBe(true); - expect([dialog.open, dialog.scrollTop, said()]).toEqual([ - true, - 0, - "true:open", - ]); - expect( - document.getElementById("inner-open")?.getAttribute("aria-expanded"), - ).toBe("false"); - expect(press("close")).toBe(true); - expect([dialog.open, said()]).toEqual([false, "false:closed"]); - expect(seen).toEqual([ - "open:true", - "openAutoFocus", - "open:false", - "closeAutoFocus", - ]); -}); - -test("a dialog without handlers opens and closes all the same", () => { - press("open"); - expect(dialog.open).toBe(true); - expect(escape()).toBe(true); - expect(dialog.open).toBe(false); - dialogSync(dialog); - press("open"); - expect(dialog.open).toBe(true); -}); - -test("a press beside the panel and Escape dismiss the dialog, and say what did", () => { - const { on, seen } = handlers(); - dialogSync(dialog, null, on); - press("open"); - expect(press("panel")).toBe(false); - expect(dialog.open).toBe(true); - expect(press("pad")).toBe(false); - expect(dialog.open).toBe(false); - press("open"); - press("dialog"); - expect(dialog.open).toBe(false); - press("open"); - expect(escape()).toBe(true); - expect(dialog.open).toBe(false); - expect(seen).toEqual([ - "open:true", - "openAutoFocus", - "outside", - "interact", - "open:false", - "closeAutoFocus", - "open:true", - "openAutoFocus", - "outside", - "interact", - "open:false", - "closeAutoFocus", - "open:true", - "openAutoFocus", - "escape", - "open:false", - "closeAutoFocus", - ]); -}); - -test("a press beside the panel of an alert dialog does not dismiss it", () => { - render('role="alertdialog" data-rx-keep="outside"'); - const cancel = /** @type {HTMLElement} */ (document.getElementById("close")); - cancel.setAttribute("data-rx-dialog-close", "cancel"); - press("open"); - expect(document.activeElement).toBe(cancel); - press("pad"); - press("dialog"); - expect(dialog.open).toBe(true); - expect(escape()).toBe(true); - expect(dialog.open).toBe(false); -}); - -test("a dialog bound to state says what is asked of it, and shows its state", () => { - const { on, seen } = handlers(); - dialogSync(dialog, false, on); - expect(press("open")).toBe(true); - expect(dialog.open).toBe(false); - dialogSync(dialog, true, on); - expect([dialog.open, said()]).toEqual([true, "true:open"]); - dialogSync(dialog, true, on); - expect(escape()).toBe(true); - press("close"); - press("pad"); - expect(dialog.open).toBe(true); - dialogSync(dialog, false, on); - expect([dialog.open, said()]).toEqual([false, "false:closed"]); - expect(seen).toEqual([ - "open:true", - "openAutoFocus", - "escape", - "open:false", - "open:false", - "outside", - "interact", - "open:false", - "closeAutoFocus", - ]); -}); - -test("a drawer that is not dismissible stays until its state says, and one that is not modal is shown beside the page", () => { - /** @type {string[]} */ - const shown = []; - HTMLDialogElement.prototype.show = function () { - shown.push(this.id); - this.open = true; - }; - render('data-rx-keep="all" data-modal="false"'); - const { on, seen } = handlers(); - dialogSync(dialog, null, on); - press("open"); - expect(shown).toEqual(["dialog"]); - expect(escape()).toBe(true); - press("dialog"); - press("close"); - expect(dialog.open).toBe(true); - expect(seen).toEqual(["open:true", "openAutoFocus"]); -}); - -test("a dialog that starts open opens once", () => { - render('data-default-open="true"'); - const { on, seen } = handlers(); - dialogSync(dialog, null, on); - expect(dialog.open).toBe(true); - press("close"); - dialogSync(dialog, null, on); - expect(dialog.open).toBe(false); - expect(seen).toEqual(["openAutoFocus", "open:false", "closeAutoFocus"]); - dialogSync(null); -}); - -test("the dialog inside a dialog is its own", () => { - const inner = /** @type {HTMLDialogElement} */ ( - document.getElementById("inner") - ); - const innerRoot = /** @type {HTMLElement} */ ( - document.getElementById("inner-root") - ); - press("open"); - // The press on what opens the inner dialog reaches both elements. - press("inner-open", innerRoot); - press("inner-open"); - expect([dialog.open, inner.open]).toEqual([true, true]); - expect(escape(inner)).toBe(false); - press("inner-pad"); - press("inner-close"); - expect([dialog.open, inner.open]).toEqual([true, true]); - press("inner-close", innerRoot); - expect([dialog.open, inner.open, said()]).toEqual([true, false, "true:open"]); -}); - -test("a press on anything else is left alone", () => { - expect(press(null)).toBe(false); - expect(press("elsewhere")).toBe(false); - dialog.remove(); - expect(press("open")).toBe(false); -}); - -test("a panel that does not slide out says it has, as one that slides out does", () => { - // What jsdom lacks of a transition: its event, and the animations of an element. - globalThis.TransitionEvent ??= /** @type {typeof TransitionEvent} */ ( - /** @type {unknown} */ ( - class extends Event { - /** - * @param {string} type The type. - * @param {TransitionEventInit} init What the event says. - */ - constructor(type, init) { - super(type, init); - this.propertyName = init.propertyName ?? ""; - } - } - ) - ); - const pad = /** @type {HTMLElement} */ (document.getElementById("pad")); - pad.style.transitionProperty = "opacity, transform"; - /** @type {{ transitionProperty: string, playState: string }[]} */ - let running = []; - Object.assign(pad, { getAnimations: () => running }); - const { on, seen: ended } = handlers(); - dialogSync(dialog, null, on); - dialog.addEventListener("transitionend", (event) => - ended.push( - `${/** @type {HTMLElement} */ (event.target).id}:${ - /** @type {TransitionEvent} */ (event).propertyName - }`, - ), - ); - press("open"); - press("close"); - // An engine that takes the dialog out of the top layer at once runs no - // transition as it closes: the panel is said to have slid out, after the - // dialog has said it closed, as a transition that runs ends after it. - const once = [ - "open:true", - "openAutoFocus", - "open:false", - "closeAutoFocus", - "pad:transform", - ]; - expect(ended).toEqual(once); - // Where the panel slides out, the browser says so when it has. - running = [{ transitionProperty: "transform", playState: "running" }]; - press("open"); - press("close"); - const unsaid = ["open:true", "openAutoFocus", "open:false", "closeAutoFocus"]; - expect(ended).toEqual([...once, ...unsaid]); - // A panel without a transition of its transform says nothing. - running = []; - pad.style.transitionProperty = "opacity"; - press("open"); - press("close"); - expect(ended).toEqual([...once, ...unsaid, ...unsaid]); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js b/packages/reflex-components-ui/js/tests/behaviors/hover.test.js deleted file mode 100644 index 6391f069f57..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/hover.test.js +++ /dev/null @@ -1,277 +0,0 @@ -// A popup that opens under the pointer and with the focus of the keyboard: -// when it opens and closes, what it says, and the state it follows. -import { afterEach, beforeEach, expect, test, vi } from "vitest"; - -import { installPopover } from "./popover.js"; - -/** @type {typeof import("$/reflex-ui/behaviors/hover.js")} */ -let api; -/** @type {HTMLElement} */ -let trigger; -/** @type {HTMLElement} */ -let popup; -/** @type {string[]} */ -let seen; - -/** - * Render a button and the popup that opens under it, and a second pair - * rendered with the same id, as a loop renders them. - * - * @param {string} [attributes] The attributes of the first popup. - * @returns {void} - */ -function render(attributes = 'role="tooltip"') { - document.body.innerHTML = ` - - - -
- `; - trigger = /** @type {HTMLElement} */ (document.getElementById("save")); - popup = /** @type {HTMLElement} */ (trigger.nextElementSibling); -} - -const on = { - open: (/** @type {boolean} */ open) => seen.push(`open:${open}`), - escape: () => seen.push("escape"), - outside: () => seen.push("outside"), -}; - -beforeEach(async () => { - vi.resetModules(); - vi.useFakeTimers(); - vi.stubGlobal("CSS", { supports: () => true }); - installPopover(); - api = await import("$/reflex-ui/behaviors/hover.js"); - seen = []; - render(); -}); - -afterEach(() => { - vi.useRealTimers(); - vi.unstubAllGlobals(); -}); - -/** - * Send what happens on a button or on its popup. - * - * @param {string} type The type of the event. - * @param {HTMLElement} [element] The element that hears it. - * @param {{ pointerType?: string, to?: HTMLElement | null }} [details] The - * kind of pointer, and where the focus goes. - * @returns {void} - */ -function send(type, element = trigger, { pointerType, to } = {}) { - api.hoverEvent({ - type, - currentTarget: element, - pointerType, - relatedTarget: to, - }); -} - -/** - * Say whether the popup is shown. - * - * @returns {boolean} Whether it is open. - */ -function shown() { - return popup.matches(":popover-open"); -} - -test("the first sync names each pair of a loop apart, for the browser to place the popup by", () => { - const second = /** @type {HTMLElement} */ ( - document.getElementById("copy")?.nextElementSibling - ); - api.hoverSync(popup, null, on); - api.hoverSync(second); - api.hoverSync(popup, null, on); - api.hoverSync(null); - expect([ - popup.id, - trigger.dataset.rxHover, - trigger.getAttribute("aria-describedby"), - trigger.style.getPropertyValue("anchor-name"), - popup.style.getPropertyValue("position-anchor"), - ]).toEqual(["rx-tip-1", "rx-tip-1", "rx-tip-1", "--rx-tip-1", "--rx-tip-1"]); - expect([ - second.id, - document.getElementById("copy")?.dataset.rxHover, - document.getElementById("copy")?.hasAttribute("aria-describedby"), - ]).toEqual(["rx-tip-2", "rx-tip-2", false]); -}); - -test("a popup an app named keeps its name, and one nothing opens is left alone", () => { - document.body.innerHTML = `
`; - const [mine, alone] = /** @type {HTMLElement[]} */ ([ - ...document.querySelectorAll("[popover]"), - ]); - api.hoverSync(mine); - api.hoverSync(alone); - expect([mine.id, alone.id]).toEqual(["mine", "rx-alone"]); -}); - -test("the pointer opens the popup after its delay, and closes it after the other", () => { - api.hoverSync(popup, null, on); - send("pointerenter"); - vi.advanceTimersByTime(199); - expect(shown()).toBe(false); - vi.advanceTimersByTime(1); - expect([shown(), trigger.dataset.state]).toEqual([true, "delayed-open"]); - send("pointerleave"); - vi.advanceTimersByTime(99); - expect(shown()).toBe(true); - // The pointer reached the popup in time. - send("pointerenter", popup); - vi.advanceTimersByTime(500); - expect(shown()).toBe(true); - send("pointerleave", popup); - vi.advanceTimersByTime(100); - expect([shown(), trigger.dataset.state]).toEqual([false, "closed"]); - expect(seen).toEqual(["open:true", "open:false"]); -}); - -test("a pointer that leaves before the delay opens nothing, and a finger opens nothing", () => { - api.hoverSync(popup, null, on); - send("pointerenter"); - vi.advanceTimersByTime(100); - send("pointerleave"); - vi.advanceTimersByTime(1000); - send("pointerenter", trigger, { pointerType: "touch" }); - vi.advanceTimersByTime(1000); - expect(shown()).toBe(false); - expect(seen).toEqual([]); -}); - -test("the focus of the keyboard opens the popup at once, and closes it when it leaves both", () => { - api.hoverSync(popup, null, on); - send("focus"); - vi.advanceTimersByTime(0); - expect(shown()).toBe(false); - const matches = trigger.matches.bind(trigger); - trigger.matches = (selector) => - selector === ":focus-visible" || matches(selector); - send("focus"); - vi.advanceTimersByTime(0); - expect(shown()).toBe(true); - send("blur", trigger, { to: document.getElementById("link") }); - send("blur", popup, { to: document.getElementById("save-text") }); - vi.advanceTimersByTime(0); - expect(shown()).toBe(true); - send("blur", popup, { to: document.getElementById("elsewhere") }); - vi.advanceTimersByTime(0); - expect(shown()).toBe(false); -}); - -test("the focus of the keyboard opens a hover card after its delay, and closes it after the other", () => { - render(""); - api.hoverSync(popup, null, on); - const matches = trigger.matches.bind(trigger); - trigger.matches = (selector) => - selector === ":focus-visible" || matches(selector); - send("focus"); - vi.advanceTimersByTime(199); - expect(shown()).toBe(false); - vi.advanceTimersByTime(1); - expect([shown(), trigger.dataset.state]).toEqual([true, "open"]); - send("blur", trigger, { to: document.getElementById("elsewhere") }); - vi.advanceTimersByTime(99); - expect(shown()).toBe(true); - vi.advanceTimersByTime(1); - expect([shown(), trigger.dataset.state]).toEqual([false, "closed"]); - expect(seen).toEqual(["open:true", "open:false"]); -}); - -test("Escape, a press outside and a press on the button of a tooltip close it", () => { - api.hoverSync(popup, null, on); - const open = () => { - send("pointerenter"); - vi.advanceTimersByTime(200); - }; - open(); - dispatchEvent(new KeyboardEvent("keydown", { key: "a" })); - expect(shown()).toBe(true); - // The Escape that closes it is spent: a dialog the popup is in stays open. - const escape = () => { - const event = new KeyboardEvent("keydown", { - key: "Escape", - cancelable: true, - }); - dispatchEvent(event); - return event.defaultPrevented; - }; - expect([escape(), shown()]).toEqual([true, false]); - // Once closed, the popup hears nothing of the page. - expect(escape()).toBe(false); - open(); - document - .getElementById("link") - ?.dispatchEvent(new Event("pointerdown", { bubbles: true })); - expect(shown()).toBe(true); - document - .getElementById("elsewhere") - ?.dispatchEvent(new Event("pointerdown", { bubbles: true })); - expect(shown()).toBe(false); - open(); - send("pointerdown"); - vi.advanceTimersByTime(0); - expect(shown()).toBe(false); - expect(seen).toEqual([ - "open:true", - "escape", - "open:false", - "open:true", - "outside", - "open:false", - "open:true", - "open:false", - ]); -}); - -test("a popup bound to state says what is asked of it, and shows its state", () => { - render(""); - api.hoverSync(popup, false, on); - send("pointerenter"); - vi.advanceTimersByTime(200); - expect(shown()).toBe(false); - api.hoverSync(popup, true, on); - expect([shown(), trigger.dataset.state]).toEqual([true, "open"]); - api.hoverSync(popup, true, on); - dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); - expect(shown()).toBe(true); - api.hoverSync(popup, false, on); - expect(shown()).toBe(false); - expect(seen).toEqual(["open:true", "escape", "open:false"]); -}); - -test("a popup that starts open opens once, and one that is unknown is left alone", () => { - render('data-default-open="true"'); - send("pointerenter"); - vi.advanceTimersByTime(1000); - expect(shown()).toBe(false); - api.hoverSync(popup); - expect(shown()).toBe(true); - send("pointerleave"); - vi.advanceTimersByTime(100); - api.hoverSync(popup); - expect(shown()).toBe(false); - trigger.dataset.rxHover = "gone"; - send("pointerenter"); - delete trigger.dataset.rxHover; - send("pointerenter"); -}); - -test("a browser without anchor positioning has the popup placed by a script", async () => { - vi.resetModules(); - vi.stubGlobal("CSS", { supports: () => false }); - const place = vi.fn(); - vi.doMock("$/reflex-ui/behaviors/popup-position.js", () => ({ place })); - api = await import("$/reflex-ui/behaviors/hover.js"); - api.hoverSync(popup); - send("pointerenter"); - vi.advanceTimersByTime(200); - await vi.waitFor(() => - expect(place.mock.calls).toEqual([[popup, trigger, true]]), - ); - vi.doUnmock("$/reflex-ui/behaviors/popup-position.js"); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js b/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js deleted file mode 100644 index 330bdfd2cec..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/listbox.test.js +++ /dev/null @@ -1,566 +0,0 @@ -// What a select does with its options: the value it keeps and shows, the -// keys that move through the list, and what it says when the list closes. -import { beforeAll, beforeEach, expect, test, vi } from "vitest"; - -import { - selectClick, - selectFocus, - selectKeyDown, - selectPointerMove, - selectToggle, - syncSelect, -} from "$/reflex-ui/behaviors/listbox.js"; - -import { installPopover } from "./popover.js"; - -const OPTIONS = [ - ["apple", "Apple"], - ["apricot", "Apricot"], - ["banana", "Banana"], - ["cherry", "Cherry"], -]; - -/** @type {HTMLElement} */ -let select; -/** @type {HTMLElement} */ -let trigger; -/** @type {HTMLElement} */ -let popup; -/** @type {HTMLInputElement} */ -let holder; -/** @type {string[]} */ -let heard; - -/** - * Build a select, wired as a page wires it. - * - * @param {{ value?: string, disabled?: string, attributes?: string, id?: string }} [options] - * The value it starts with, the value of a disabled option, further - * attributes of the element around it, and the id of its popup. - * @returns {void} - */ -function build({ - value = "", - disabled = "", - attributes = "", - id = "rx-list", -} = {}) { - const container = document.createElement("div"); - container.innerHTML = ` - -
-
Fruits
- ${OPTIONS.map( - ([option, text]) => - `
✓${text}
`, - ).join("")} -
- -
`; - document.body.append(container); - select = /** @type {HTMLElement} */ ( - container.querySelector("[data-rx-select]") - ); - trigger = /** @type {HTMLElement} */ (select.querySelector("button")); - popup = /** @type {HTMLElement} */ (select.querySelector("[popover]")); - holder = /** @type {HTMLInputElement} */ (select.querySelector("input")); - heard = []; - // What the browser does of a button with a `popovertarget`. - trigger.addEventListener("click", () => { - if (!trigger.matches(":disabled")) popup.togglePopover(); - }); - for (const type of ["beforetoggle", "toggle"]) - popup.addEventListener(type, (event) => - selectToggle(/** @type {any} */ (event), { - open: (open) => heard.push(`open ${open}`), - close: () => heard.push("close"), - escape: () => heard.push("escape"), - outside: () => heard.push("outside"), - }), - ); - holder.addEventListener("input", () => heard.push(`change ${holder.value}`)); - syncSelect(holder); -} - -/** - * Press a key inside the select. - * - * @param {string} key The key. - * @param {Partial<{ target: Element, altKey: boolean, ctrlKey: boolean, metaKey: boolean }>} [more] - * Where, when not on what has the focus, and the modifiers held. - * @returns {boolean} Whether the select kept the key from the browser. - */ -function press(key, more = {}) { - let prevented = false; - selectKeyDown({ - key, - target: document.activeElement, - currentTarget: select, - preventDefault: () => (prevented = true), - ...more, - }); - return prevented; -} - -/** - * Find an option. - * - * @param {string} value Its value. - * @returns {HTMLElement} The option. - */ -function option(value) { - return /** @type {HTMLElement} */ ( - select.querySelector(`[data-value="${value}"]`) - ); -} - -/** - * Read what the select shows. - * - * @returns {{ value: string, shown: string | null, empty: boolean, chosen: string[], open: boolean }} - * Its value, the text and the placeholder mark of its trigger, the - * options that say they are chosen, and whether the list is open. - */ -function state() { - return { - value: holder.value, - shown: trigger.textContent, - empty: trigger.hasAttribute("data-placeholder"), - chosen: [ - ...select.querySelectorAll( - '[aria-selected="true"][data-state="checked"]', - ), - ].map((element) => element.getAttribute("data-value") ?? ""), - open: popup.matches(":popover-open"), - }; -} - -/** - * Read the value of the option that has the focus. - * - * @returns {string | null | undefined} Its value, or null for anything else. - */ -function focused() { - return document.activeElement?.getAttribute("data-value"); -} - -beforeAll(() => installPopover()); - -beforeEach(() => { - document.body.innerHTML = ""; - vi.useRealTimers(); -}); - -test("a select without a value shows its placeholder, and every option unchosen", () => { - build(); - - expect(state()).toEqual({ - value: "", - shown: "Pick", - empty: true, - chosen: [], - open: false, - }); - expect( - [...select.querySelectorAll("[role=option]")].map((element) => [ - element.getAttribute("aria-selected"), - element.getAttribute("data-state"), - ]), - ).toEqual(OPTIONS.map(() => ["false", "unchecked"])); -}); - -test("a select with a value shows the text of its option", () => { - build({ value: "banana" }); - - expect(state()).toEqual({ - value: "banana", - shown: "Banana", - empty: false, - chosen: ["banana"], - open: false, - }); -}); - -test("a value no option has shows the placeholder", () => { - build({ value: "kiwi" }); - - expect(state()).toEqual({ - value: "kiwi", - shown: "Pick", - empty: true, - chosen: [], - open: false, - }); -}); - -test("a trigger without the element that shows the value is left as it is", () => { - build({ value: "banana" }); - trigger.innerHTML = "Custom"; - syncSelect(holder); - - expect(trigger.outerHTML).toBe( - ``, - ); -}); - -test("an empty element that shows the value is given the text", () => { - build(); - /** @type {HTMLElement} */ (trigger.firstElementChild).textContent = ""; - holder.value = "cherry"; - syncSelect(holder); - - expect(trigger.textContent).toBe("Cherry"); -}); - -test("nothing is done for what is not a select", () => { - build(); - const before = document.body.innerHTML; - syncSelect(null); - syncSelect(document.body); - trigger.remove(); - syncSelect(holder); - press("ArrowDown"); - - expect(document.body.innerHTML).toBe( - before.replace(//, ""), - ); -}); - -test("opening gives the focus to the chosen option, or to the first", () => { - build({ value: "banana" }); - trigger.click(); - expect([state().open, focused(), heard]).toEqual([ - true, - "banana", - ["open true"], - ]); - expect([ - trigger.getAttribute("aria-expanded"), - trigger.getAttribute("data-state"), - ]).toEqual(["true", "open"]); - - build({ disabled: "apple" }); - trigger.click(); - expect(focused()).toBe("apricot"); -}); - -test("a list without options takes the focus itself", () => { - build(); - for (const element of select.querySelectorAll("[role=option]")) - element.remove(); - trigger.click(); - - expect(document.activeElement).toBe(popup); -}); - -test("the arrow keys open the list from the trigger", () => { - build(); - trigger.focus(); - expect([press("ArrowDown"), state().open, focused()]).toEqual([ - true, - true, - "apple", - ]); - popup.hidePopover(); - expect([press("ArrowUp"), state().open]).toEqual([true, true]); -}); - -test("a key on anything but the trigger of a closed select is left alone", () => { - build(); - expect([press("ArrowDown", { target: holder }), state().open]).toEqual([ - false, - false, - ]); - trigger.setAttribute("disabled", ""); - expect([press("ArrowDown", { target: trigger }), state().open]).toEqual([ - false, - false, - ]); - expect([press("Enter", { target: trigger }), state().open]).toEqual([ - false, - false, - ]); -}); - -test("the arrow keys, Home and End move through the options that can be chosen", () => { - build({ disabled: "apricot" }); - trigger.click(); - const moves = [ - "ArrowDown", - "ArrowDown", - "ArrowDown", - "ArrowUp", - "Home", - "ArrowUp", - "End", - ].map((key) => [key, press(key), focused()]); - - expect(moves).toEqual([ - ["ArrowDown", true, "banana"], - ["ArrowDown", true, "cherry"], - ["ArrowDown", true, "cherry"], - ["ArrowUp", true, "banana"], - ["Home", true, "apple"], - ["ArrowUp", true, "apple"], - ["End", true, "cherry"], - ]); -}); - -test("Tab stays in an open list, and other keys are left to the browser", () => { - build(); - trigger.click(); - - expect([press("Tab"), focused(), state().open]).toEqual([ - true, - "apple", - true, - ]); - expect([press("Shift"), press("a", { ctrlKey: true }), focused()]).toEqual([ - false, - false, - "apple", - ]); -}); - -test("Enter and Space choose the option that has the focus", () => { - build(); - trigger.click(); - press("ArrowDown"); - expect(press("Enter")).toBe(true); - expect(state()).toEqual({ - value: "apricot", - shown: "Apricot", - empty: false, - chosen: ["apricot"], - open: false, - }); - expect(heard).toEqual(["open true", "open false", "close", "change apricot"]); - expect(document.activeElement).toBe(trigger); - - trigger.click(); - press("End"); - expect(press(" ")).toBe(true); - expect([state().value, heard.slice(4)]).toEqual([ - "cherry", - ["open true", "open false", "close", "change cherry"], - ]); -}); - -test("Enter with the focus on the list itself chooses nothing", () => { - build(); - trigger.click(); - popup.focus(); - - expect([press("Enter"), state().value, state().open]).toEqual([ - true, - "", - true, - ]); -}); - -test("choosing the chosen option closes the list and changes nothing", () => { - build({ value: "banana" }); - trigger.click(); - selectClick({ - target: option("banana").lastElementChild, - currentTarget: select, - }); - - expect([state().value, state().open, heard]).toEqual([ - "banana", - false, - ["open true", "open false", "close"], - ]); -}); - -test("a click chooses an option, and nothing anywhere else or on a disabled one", () => { - build({ disabled: "banana" }); - trigger.click(); - selectClick({ target: option("banana"), currentTarget: select }); - selectClick({ target: popup, currentTarget: select }); - selectClick({ target: null, currentTarget: select }); - expect([state().value, state().open]).toEqual(["", true]); - - selectClick({ - target: option("cherry").lastElementChild, - currentTarget: select, - }); - expect([state().value, state().shown, state().open]).toEqual([ - "cherry", - "Cherry", - false, - ]); -}); - -test("typing in the list goes to the option that starts with it", () => { - vi.useFakeTimers(); - build(); - trigger.click(); - - expect([press("b"), focused()]).toEqual([true, "banana"]); - vi.advanceTimersByTime(1000); - // One letter again goes through the options that start with it. - expect([press("a"), focused()]).toEqual([true, "apple"]); - expect([press("a"), focused()]).toEqual([true, "apricot"]); - expect([press("a"), focused()]).toEqual([true, "apple"]); - vi.advanceTimersByTime(1000); - // Several letters are a search, which stays where it matches. - expect([press("a"), press("p"), press("r"), focused()]).toEqual([ - true, - true, - true, - "apricot", - ]); - // A space is part of what is typed, and chooses nothing. - expect([press(" "), state().open, state().value]).toEqual([true, true, ""]); - vi.advanceTimersByTime(1000); - expect([press("z"), focused()]).toEqual([true, "apricot"]); - vi.advanceTimersByTime(1000); -}); - -test("typing on the trigger chooses the next option that starts with it", () => { - vi.useFakeTimers(); - build({ value: "apple" }); - trigger.focus(); - - expect([press("a"), state().value, state().open]).toEqual([ - true, - "apricot", - false, - ]); - vi.advanceTimersByTime(1000); - expect([press("c"), state().value]).toEqual([true, "cherry"]); - vi.advanceTimersByTime(1000); - expect([press("z"), state().value]).toEqual([true, "cherry"]); - vi.advanceTimersByTime(1000); - // Space is left to the button, which it opens. - expect(press(" ")).toBe(false); - expect(heard).toEqual(["change apricot", "change cherry"]); -}); - -test("the pointer gives the option under it the focus, and the list between options", () => { - build({ disabled: "banana" }); - trigger.click(); - selectPointerMove({ - target: option("cherry").lastElementChild, - currentTarget: select, - }); - expect(focused()).toBe("cherry"); - selectPointerMove({ target: option("cherry"), currentTarget: select }); - expect(focused()).toBe("cherry"); - - selectPointerMove({ target: option("banana"), currentTarget: select }); - expect(document.activeElement).toBe(popup); - selectPointerMove({ target: trigger, currentTarget: select }); - selectPointerMove({ target: null, currentTarget: select }); - expect(document.activeElement).toBe(popup); -}); - -test("a list says what closed it", () => { - build(); - // Escape on a closed select closes nothing, and is not remembered. - trigger.focus(); - expect(press("Escape")).toBe(false); - trigger.click(); - /** @type {HTMLElement} */ (document.activeElement).blur(); - popup.hidePopover(); - expect(heard).toEqual(["open true", "open false", "outside", "close"]); - - heard.length = 0; - trigger.click(); - press("Escape"); - popup.hidePopover(); - expect(heard).toEqual(["open true", "open false", "escape", "close"]); - expect(document.activeElement).toBe(trigger); - - heard.length = 0; - trigger.click(); - /** @type {HTMLElement} */ (document.activeElement).blur(); - popup.hidePopover(); - expect(heard).toEqual(["open true", "open false", "outside", "close"]); - expect(document.activeElement).toBe(document.body); -}); - -test("a list without anything to call is followed all the same", () => { - build(); - selectToggle({ - type: "beforetoggle", - currentTarget: popup, - newState: "open", - }); - popup.showPopover(); - selectToggle({ type: "toggle", currentTarget: popup, newState: "open" }); - expect([focused(), trigger.getAttribute("aria-expanded")]).toEqual([ - "apple", - "true", - ]); - selectToggle({ - type: "beforetoggle", - currentTarget: popup, - newState: "closed", - }); - expect(document.activeElement).toBe(trigger); -}); - -test("a select bound to state takes its value and whether it is open from there", () => { - build(); - syncSelect(holder, "banana", true); - expect(state()).toEqual({ - value: "banana", - shown: "Banana", - empty: false, - chosen: ["banana"], - open: true, - }); - - syncSelect(holder, "banana", true); - syncSelect(holder, "cherry", false); - expect([state().value, state().open, heard]).toEqual([ - "cherry", - false, - ["open true", "open false", "close"], - ]); -}); - -test("a choice the state does not follow leaves the select as it was", () => { - build(); - syncSelect(holder, "banana", null); - trigger.click(); - selectClick({ target: option("cherry"), currentTarget: select }); - expect([state().value, state().shown, state().chosen, heard]).toEqual([ - "banana", - "Banana", - ["banana"], - ["open true", "open false", "close", "change cherry"], - ]); - - syncSelect(holder, "cherry", null); - expect([state().value, state().shown]).toEqual(["cherry", "Cherry"]); -}); - -test("a select that starts open opens once", () => { - build({ attributes: 'data-default-open="true"' }); - expect([state().open, select.hasAttribute("data-default-open")]).toEqual([ - true, - false, - ]); - - popup.hidePopover(); - syncSelect(holder); - expect(state().open).toBe(false); - - build({ attributes: 'data-default-open="false"' }); - expect(state().open).toBe(false); -}); - -test("the input of the value hands the focus it is given to the trigger", () => { - build(); - holder.focus(); - selectFocus({ currentTarget: holder }); - expect(document.activeElement).toBe(trigger); - - document.body.append(holder); - holder.focus(); - selectFocus({ currentTarget: holder }); - expect(document.activeElement).toBe(holder); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/menu.test.js b/packages/reflex-components-ui/js/tests/behaviors/menu.test.js deleted file mode 100644 index 244095c3a09..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/menu.test.js +++ /dev/null @@ -1,470 +0,0 @@ -// A menu: the keys, the pointer and the choices of its items, its -// sub-menus, its checkbox items, and the context menu at the pointer. -import { afterEach, beforeEach, expect, test, vi } from "vitest"; - -import { installPopover } from "./popover.js"; - -/** @type {typeof import("$/reflex-ui/behaviors/menu.js")} */ -let api; -/** @type {string[]} */ -let seen; - -const on = { - open: (/** @type {boolean} */ open) => seen.push(`open:${open}`), - escape: () => seen.push("escape"), - outside: () => seen.push("outside"), - focusOutside: () => seen.push("focus-outside"), - interact: () => seen.push("interact"), - closeAutoFocus: () => seen.push("close-focus"), -}; - -/** - * Render a dropdown menu with a sub-menu, and a context menu. - * - * @returns {void} - */ -function render() { - document.body.innerHTML = ` - - -
Area
- - - `; -} - -/** - * Find an element of the page. - * - * @param {string} id Its id. - * @returns {HTMLElement} The element. - */ -function $(id) { - return /** @type {HTMLElement} */ (document.getElementById(id)); -} - -/** - * Have the script of a menu hear its events, as React does. - * - * @param {string} id The id of the menu. - * @param {typeof on | null} [handlers] What the menu does. - * @returns {void} - */ -function listen(id, handlers = null) { - const menu = $(id); - for (const type of [ - "beforetoggle", - "toggle", - "keydown", - "click", - "pointermove", - "pointerleave", - "focusout", - ]) { - menu.addEventListener(type, (event) => - api.menuEvent( - /** @type {any} */ ({ - type: type === "focusout" ? "blur" : type, - target: event.target, - currentTarget: menu, - newState: /** @type {any} */ (event).newState, - key: /** @type {any} */ (event).key, - relatedTarget: /** @type {any} */ (event).relatedTarget, - pointerType: /** @type {any} */ (event).pointerType, - preventDefault: () => event.preventDefault(), - }), - handlers, - ), - ); - } -} - -/** - * Press a key on the element that has the focus. - * - * @param {string} key The key. - * @returns {boolean} Whether the script took the key for itself. - */ -function press(key) { - const event = new KeyboardEvent("keydown", { - key, - bubbles: true, - cancelable: true, - }); - /** @type {HTMLElement} */ (document.activeElement).dispatchEvent(event); - return event.defaultPrevented; -} - -/** - * Move a mouse over an element. - * - * @param {string} id The id of the element. - * @param {string} [type] The event. - * @returns {void} - */ -function point(id, type = "pointermove") { - const event = new Event(type, { bubbles: type === "pointermove" }); - Object.assign(event, { pointerType: "mouse" }); - $(id).dispatchEvent(event); -} - -/** - * Say which element has the focus. - * - * @returns {string} Its id. - */ -function focused() { - return document.activeElement?.id ?? ""; -} - -beforeEach(async () => { - vi.resetModules(); - vi.useFakeTimers(); - installPopover(); - api = await import("$/reflex-ui/behaviors/menu.js"); - seen = []; - render(); - listen("opts", on); - listen("sub"); - listen("ctx"); -}); - -afterEach(() => { - vi.useRealTimers(); -}); - -test("a menu nothing opens by popovertarget is placed against the element before it", () => { - api.menuSync($("opts")); - api.menuSync($("sub")); - api.menuSync($("sub")); - api.menuSync($("ctx")); - api.menuSync(null); - expect([ - $("trigger").style.getPropertyValue("anchor-name"), - $("opts").style.getPropertyValue("position-anchor"), - $("more").style.getPropertyValue("anchor-name"), - $("sub").style.getPropertyValue("position-anchor"), - $("point").style.getPropertyValue("anchor-name"), - $("ctx").style.getPropertyValue("position-anchor"), - ]).toEqual([ - "", - "", - "--rx-menu-1", - "--rx-menu-1", - "--rx-menu-2", - "--rx-menu-2", - ]); -}); - -test("a press opens the menu on itself, and the keys of the trigger on its first item", () => { - $("opts").showPopover(); - expect([focused(), $("trigger").getAttribute("aria-expanded")]).toEqual([ - "opts", - "true", - ]); - $("opts").hidePopover(); - for (const key of ["Enter", " "]) { - api.menuTrigger( - /** @type {any} */ ({ - key, - currentTarget: $("trigger"), - preventDefault() {}, - }), - ); - $("opts").showPopover(); - expect(focused()).toBe("edit"); - $("opts").hidePopover(); - } - const click = vi.spyOn($("trigger"), "click"); - let prevented = false; - api.menuTrigger( - /** @type {any} */ ({ - key: "ArrowDown", - currentTarget: $("trigger"), - preventDefault: () => (prevented = true), - }), - ); - expect([click.mock.calls.length, prevented]).toEqual([1, true]); - // A key that opens nothing forgets the one before. - api.menuTrigger( - /** @type {any} */ ({ - key: "Tab", - currentTarget: $("trigger"), - preventDefault() {}, - }), - ); - $("opts").showPopover(); - expect(focused()).toBe("opts"); - api.menuTrigger( - /** @type {any} */ ({ - key: "Enter", - currentTarget: $("elsewhere"), - preventDefault() {}, - }), - ); -}); - -test("the arrows, Home, End and typing move through the items past a disabled one, and Tab stays", () => { - $("opts").showPopover(); - $("edit").focus(); - const moves = [ - ["ArrowDown", "archive"], - ["ArrowDown", "more"], - ["ArrowDown", "share"], - ["ArrowDown", "share"], - ["ArrowUp", "more"], - ["Home", "edit"], - ["ArrowUp", "edit"], - ["End", "share"], - ["m", "more"], - ["b", "archive"], - ]; - for (const [key, item] of moves) { - // What was typed is forgotten after a second. - vi.advanceTimersByTime(1000); - expect(press(key)).toBe(true); - expect(focused()).toBe(item); - } - expect(press("Tab")).toBe(true); - expect(press("Shift")).toBe(false); - $("opts").dataset.loop = "true"; - $("share").focus(); - press("ArrowDown"); - expect(focused()).toBe("edit"); -}); - -test("a choice closes every menu, gives the focus back, and says so", () => { - $("opts").showPopover(); - $("edit").focus(); - const chosen = vi.fn(); - $("edit").addEventListener("click", chosen); - press("Enter"); - expect([ - chosen.mock.calls.length, - $("opts").matches(":popover-open"), - focused(), - ]).toEqual([1, false, "trigger"]); - expect(seen).toEqual(["open:true", "open:false", "close-focus"]); - // A press on a disabled item, or beside the items, chooses nothing. - $("opts").showPopover(); - $("delete").click(); - $("opts").click(); - expect($("opts").matches(":popover-open")).toBe(true); -}); - -test("Escape, the focus leaving and a press outside close the menu and say why", () => { - $("opts").showPopover(); - $("edit").focus(); - press("Escape"); - $("opts").hidePopover(); - expect(focused()).toBe("trigger"); - $("opts").showPopover(); - $("edit").focus(); - $("elsewhere").focus(); - $("opts").showPopover(); - $("opts").hidePopover(); - expect(seen).toEqual([ - "open:true", - "escape", - "open:false", - "close-focus", - "open:true", - "focus-outside", - "interact", - "open:false", - "close-focus", - "open:true", - "outside", - "interact", - "open:false", - "close-focus", - ]); -}); - -test("the right arrow and Enter open a sub-menu on its first item, and the left arrow closes it", () => { - $("opts").showPopover(); - $("more").focus(); - press("ArrowRight"); - expect([ - $("sub").matches(":popover-open"), - focused(), - $("more").getAttribute("aria-expanded"), - ]).toEqual([true, "move", "true"]); - press("ArrowDown"); - expect(focused()).toBe("copy"); - press("ArrowLeft"); - expect([$("sub").matches(":popover-open"), focused()]).toEqual([ - false, - "more", - ]); - press("Enter"); - expect(focused()).toBe("move"); - // Escape is for the topmost menu. - press("Escape"); - expect([$("sub").dataset.rxClosedBy, $("opts").dataset.rxClosedBy]).toEqual([ - "escape", - undefined, - ]); - $("sub").hidePopover(); - expect(focused()).toBe("more"); - press("ArrowLeft"); - expect($("opts").matches(":popover-open")).toBe(true); - // A key on an item with an open sub-menu goes to it. - $("sub").showPopover(); - press(" "); - expect(focused()).toBe("move"); - // A choice in a sub-menu closes both. - press("Enter"); - expect([ - $("sub").matches(":popover-open"), - $("opts").matches(":popover-open"), - focused(), - ]).toEqual([false, false, "trigger"]); -}); - -test("the pointer highlights an item and opens a sub-menu after a rest, and leaves it for another item", () => { - $("opts").showPopover(); - point("edit"); - expect(focused()).toBe("edit"); - point("more"); - vi.advanceTimersByTime(99); - expect($("sub").matches(":popover-open")).toBe(false); - vi.advanceTimersByTime(1); - expect([$("sub").matches(":popover-open"), focused()]).toEqual([ - true, - "more", - ]); - point("move"); - expect(focused()).toBe("move"); - point("sub", "pointerleave"); - expect(focused()).toBe("sub"); - // Beside the items, with a sub-menu open, the highlight stays. - point("opts"); - expect(focused()).toBe("sub"); - point("share"); - expect([$("sub").matches(":popover-open"), focused()]).toEqual([ - false, - "share", - ]); - point("opts"); - expect(focused()).toBe("opts"); - point("share"); - point("opts", "pointerleave"); - expect(focused()).toBe("opts"); - // A press on an item that opens a sub-menu opens it, a finger moves nothing. - $("more").click(); - expect($("sub").matches(":popover-open")).toBe(true); - $("opts").dispatchEvent(new Event("pointermove", { bubbles: true })); -}); - -test("a checkbox item checks itself, or says so to the state it is bound to", () => { - const changes = /** @type {boolean[]} */ ([]); - const event = /** @type {any} */ ({ currentTarget: $("check") }); - api.menuCheck(event, (checked) => changes.push(checked)); - expect([ - $("check").getAttribute("aria-checked"), - $("check").dataset.state, - ]).toEqual(["true", "checked"]); - api.menuCheck(event, (checked) => changes.push(checked), true); - expect($("check").getAttribute("aria-checked")).toBe("true"); - api.menuCheck(event); - $("check").setAttribute("aria-disabled", "true"); - api.menuCheck(event, (checked) => changes.push(checked)); - expect([changes, $("check").getAttribute("aria-checked")]).toEqual([ - [true, false], - "false", - ]); -}); - -test("a context menu opens at the pointer, or on its first item from the keyboard", () => { - api.menuSync($("ctx")); - const ask = ( - /** @type {number} */ button, - /** @type {string} */ id = "area", - ) => { - let prevented = false; - api.menuContext( - /** @type {any} */ ({ - currentTarget: $(id), - clientX: 30, - clientY: 40, - button, - preventDefault: () => (prevented = true), - }), - ); - return prevented; - }; - expect(ask(2)).toBe(true); - expect([$("point").style.left, $("point").style.top, focused()]).toEqual([ - "30px", - "40px", - "ctx", - ]); - expect($("ctx").matches(":popover-open")).toBe(true); - ask(0); - expect([$("ctx").matches(":popover-open"), focused()]).toEqual([ - true, - "check", - ]); - $("area").setAttribute("data-disabled", ""); - $("ctx").hidePopover(); - expect(ask(2)).toBe(false); - expect(ask(2, "elsewhere")).toBe(false); - expect($("ctx").matches(":popover-open")).toBe(false); -}); - -test("a menu says it opened, and its trigger says so at once, though the browser sends its toggle later or never", () => { - installPopover({ deferred: true }); - api.menuSync($("opts")); - $("opts").showPopover(); - expect([ - $("trigger").getAttribute("aria-expanded"), - $("trigger").dataset.state, - seen, - ]).toEqual(["true", "open", ["open:true"]]); - // Closed by a press outside before the toggle of the opening was sent: - // the browser sends one toggle, which says closed. - $("opts").hidePopover(); - expect([$("trigger").getAttribute("aria-expanded"), seen]).toEqual([ - "false", - ["open:true", "outside", "interact", "open:false", "close-focus"], - ]); - vi.runAllTimers(); - expect(seen).toEqual([ - "open:true", - "outside", - "interact", - "open:false", - "close-focus", - ]); - // Opened by the keyboard, the menu takes the focus once it is shown. - $("opts").dataset.rxKeyboard = "true"; - $("opts").showPopover(); - expect(focused()).toBe(""); - vi.runAllTimers(); - expect(focused()).toBe("edit"); -}); - -test("a menu the browser opened before the page was hydrated says so on its trigger", () => { - $("opts").showPopover(); - $("trigger").setAttribute("aria-expanded", "false"); - $("trigger").dataset.state = "closed"; - api.menuSync($("opts")); - expect([ - $("trigger").getAttribute("aria-expanded"), - $("trigger").dataset.state, - ]).toEqual(["true", "open"]); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/popover.js b/packages/reflex-components-ui/js/tests/behaviors/popover.js deleted file mode 100644 index b0081595556..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/popover.js +++ /dev/null @@ -1,68 +0,0 @@ -// What jsdom has of a popover: nothing. This gives an element the methods -// the scripts call and the pseudo-class they ask for, the beforetoggle event -// the browser sends at once, and the toggle event: sent at once, or, as a -// browser sends it, in a task of its own, one for the changes made before it -// runs. - -/** @type {WeakSet} */ -const open = new WeakSet(); - -const matches = Element.prototype.matches; - -/** @type {WeakMap} */ -const pending = new WeakMap(); - -/** - * Give every element the popover methods, as a browser has them. - * - * @param {{ deferred?: boolean }} [options] Whether the toggle event waits - * for a task of its own, as in a browser, rather than coming at once. - * @returns {void} - */ -export function installPopover(options = {}) { - const deferred = options.deferred ?? false; - Element.prototype.matches = function (/** @type {string} */ selector) { - return selector === ":popover-open" - ? open.has(this) - : matches.call(this, selector); - }; - HTMLElement.prototype.togglePopover = function ( - /** @type {unknown} */ force, - ) { - const next = typeof force === "boolean" ? force : !open.has(this); - if (next === open.has(this)) return next; - const newState = next ? "open" : "closed"; - const before = new Event("beforetoggle"); - Object.assign(before, { newState }); - this.dispatchEvent(before); - if (next) open.add(this); - else open.delete(this); - const send = (/** @type {string} */ state) => { - const event = new Event("toggle"); - Object.assign(event, { newState: state }); - this.dispatchEvent(event); - }; - if (!deferred) { - send(newState); - return next; - } - const queued = pending.get(this); - if (queued) { - queued.newState = newState; - return next; - } - const change = { oldState: next ? "closed" : "open", newState }; - pending.set(this, change); - setTimeout(() => { - pending.delete(this); - send(change.newState); - }); - return next; - }; - HTMLElement.prototype.showPopover = function () { - this.togglePopover(true); - }; - HTMLElement.prototype.hidePopover = function () { - this.togglePopover(false); - }; -} diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js deleted file mode 100644 index 890f1b5931f..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/popup-position.test.js +++ /dev/null @@ -1,107 +0,0 @@ -// Where a popup goes in a browser without CSS anchor positioning. -import { afterEach, beforeEach, expect, test, vi } from "vitest"; - -import { place } from "$/reflex-ui/behaviors/popup-position.js"; - -/** @type {HTMLElement} */ -let popup; -/** @type {HTMLElement} */ -let anchor; -/** @type {{ left: number, top: number, bottom: number, width: number }} */ -let box; - -/** - * Read where the popup was put. - * - * @returns {string[]} Its left, top, least width and greatest height. - */ -function placed() { - const { left, top, minWidth, maxHeight } = popup.style; - return [left, top, minWidth, maxHeight]; -} - -beforeEach(() => { - document.body.innerHTML = `
`; - anchor = /** @type {HTMLElement} */ (document.querySelector("button")); - popup = /** @type {HTMLElement} */ (document.querySelector("[popover]")); - box = { left: 40, top: 100, bottom: 132, width: 120 }; - anchor.getBoundingClientRect = () => /** @type {DOMRect} */ (box); - Object.defineProperty(popup, "offsetHeight", { - value: 200, - configurable: true, - }); - Object.defineProperty(popup, "offsetWidth", { - value: 160, - configurable: true, - }); - vi.stubGlobal("innerWidth", 800); - vi.stubGlobal("innerHeight", 600); -}); - -afterEach(() => { - place(popup, anchor, false); - vi.unstubAllGlobals(); -}); - -test("the popup goes below its anchor, at its start and at least as wide", () => { - place(popup, anchor, true); - - expect(placed()).toEqual(["40px", "132px", "120px", "454px"]); - expect([popup.style.position, popup.style.inset]).toEqual(["fixed", "auto"]); -}); - -test("it goes above where there is more room and it would leave the viewport", () => { - box = { left: 40, top: 460, bottom: 492, width: 120 }; - place(popup, anchor, true); - - expect(placed()).toEqual(["40px", "252px", "120px", "446px"]); -}); - -test("a popup taller than the room above is as tall as the room", () => { - box = { left: 40, top: 300, bottom: 532, width: 120 }; - Object.defineProperty(popup, "offsetHeight", { value: 400 }); - place(popup, anchor, true); - - expect(placed()).toEqual(["40px", "6px", "120px", "286px"]); -}); - -test("it stays inside the viewport at both ends", () => { - box = { left: 700, top: 100, bottom: 132, width: 120 }; - place(popup, anchor, true); - expect(placed()).toEqual(["630px", "132px", "120px", "454px"]); - - box = { left: -30, top: 100, bottom: 132, width: 120 }; - place(popup, anchor, true); - expect(placed()).toEqual(["10px", "132px", "120px", "454px"]); -}); - -test("it follows its anchor while it is open, and no longer", () => { - place(popup, anchor, true); - box = { left: 60, top: 80, bottom: 112, width: 120 }; - window.dispatchEvent(new Event("scroll")); - expect(placed()).toEqual(["60px", "112px", "120px", "474px"]); - - box = { left: 80, top: 80, bottom: 112, width: 140 }; - window.dispatchEvent(new Event("resize")); - expect(placed()).toEqual(["80px", "112px", "140px", "474px"]); - - place(popup, anchor, false); - box = { left: 0, top: 0, bottom: 32, width: 10 }; - window.dispatchEvent(new Event("scroll")); - window.dispatchEvent(new Event("resize")); - expect(placed()).toEqual(["80px", "112px", "140px", "474px"]); -}); - -test("it is put on whole pixels", () => { - box = { left: 40.4, top: 100.2, bottom: 132.6, width: 120.5 }; - place(popup, anchor, true); - - expect(placed()).toEqual(["40px", "133px", "120.5px", "453.4px"]); -}); - -test("a popup without a margin has no gap", () => { - popup.style.marginTop = ""; - place(popup, anchor, true); - - expect(placed()).toEqual(["40px", "132px", "120px", "458px"]); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js b/packages/reflex-components-ui/js/tests/behaviors/popup.test.js deleted file mode 100644 index 5a3893634c9..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/popup.test.js +++ /dev/null @@ -1,471 +0,0 @@ -// What a popup says on the element that opens it, and where it goes in a -// browser that does not place it. -import { afterEach, beforeEach, expect, test, vi } from "vitest"; - -import { installPopover } from "./popover.js"; - -/** - * Build a button and the popup it opens. - * - * @param {string} [id] The id of the popup. - * @returns {{ trigger: HTMLElement, popup: HTMLElement }} The two. - */ -function build(id = "list") { - document.body.innerHTML = `
`; - return { - trigger: /** @type {HTMLElement} */ (document.querySelector("button")), - popup: /** @type {HTMLElement} */ (document.querySelector("[popover]")), - }; -} - -/** - * Send a popup the toggle the browser sends. - * - * @template T - * @param {(event: { currentTarget: HTMLElement, newState?: string }) => T} popupToggle The script. - * @param {HTMLElement} popup The popup. - * @param {string} newState What it is now, or is about to be. - * @returns {T} What the script answers. - */ -function toggle(popupToggle, popup, newState) { - return popupToggle({ currentTarget: popup, newState }); -} - -/** - * Read what a trigger says of its popup. - * - * @param {HTMLElement} trigger The trigger. - * @returns {(string | null)[]} Its `aria-expanded` and its `data-state`. - */ -function said(trigger) { - return [ - trigger.getAttribute("aria-expanded"), - trigger.getAttribute("data-state"), - ]; -} - -beforeEach(() => { - vi.resetModules(); - // The frame a popup is first drawn in comes at once. - vi.stubGlobal("requestAnimationFrame", (/** @type {() => void} */ frame) => - frame(), - ); -}); - -afterEach(() => { - vi.unstubAllGlobals(); -}); - -test("the trigger says whether its popup is open, and the browser places it", async () => { - vi.stubGlobal("CSS", { - supports: (/** @type {string} */ rule) => rule === "position-area: bottom", - }); - const { popupToggle } = await import("$/reflex-ui/behaviors/popup.js"); - const { trigger, popup } = build(); - - expect(toggle(popupToggle, popup, "open")).toBe(true); - expect(said(trigger)).toEqual(["true", "open"]); - expect(toggle(popupToggle, popup, "closed")).toBe(false); - expect(said(trigger)).toEqual(["false", "closed"]); - await new Promise((resolve) => setTimeout(resolve, 0)); - expect(popup.getAttribute("style")).toBe(null); -}); - -/** - * Lay a popup out as a browser does: where it is told, moved by what its - * script found it off whole pixels. - * - * @param {HTMLElement} popup The popover. - * @param {{ x: number, y: number }} laid Where it is laid out, unmoved. - * @param {{ drawn?: { x: number, y: number }, turned?: boolean }} [how] - * How far its transform draws it from there, and whether the browser - * turned it over, its margins with it. - * @returns {void} - */ -function layOut(popup, laid, { drawn = { x: 0, y: 0 }, turned = false } = {}) { - const moved = (/** @type {string} */ axis) => - (Number.parseFloat( - popup.style.getPropertyValue(`--rx-popup-snap-${axis}`), - ) || 0) * (turned ? -1 : 1); - popup.getBoundingClientRect = () => - /** @type {DOMRect} */ ({ - x: laid.x + moved("x") + drawn.x, - y: laid.y + moved("y") + drawn.y, - }); -} - -test("a popup that opens is laid out on whole pixels before it is drawn", async () => { - vi.stubGlobal("CSS", { supports: () => true }); - const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); - const { popup } = build(); - - layOut(popup, { x: 34.640625, y: 52 }); - toggle(popupBeforeToggle, popup, "open"); - expect(popup.getAttribute("style")).toBe("--rx-popup-snap-x: 0.359375px;"); - - // What it was moved by before is forgotten when it opens again. - layOut(popup, { x: 60.3125, y: 51.75 }); - toggle(popupBeforeToggle, popup, "open"); - expect(popup.getAttribute("style")).toBe( - "--rx-popup-snap-x: -0.3125px; --rx-popup-snap-y: 0.25px;", - ); - - // A popup on whole pixels is left where it is, and one that closes too. - layOut(popup, { x: 40, y: 50 }); - toggle(popupBeforeToggle, popup, "open"); - expect(popup.getAttribute("style")).toBe(""); - layOut(popup, { x: 40.5, y: 50 }); - toggle(popupBeforeToggle, popup, "closed"); - expect(popup.getAttribute("style")).toBe(""); -}); - -test("a popup is laid out on whole pixels whatever it comes in with", async () => { - vi.stubGlobal("CSS", { supports: () => true }); - const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); - const { popup } = build(); - // Halfway in: half its size about a point inside it, and four pixels up. - popup.style.transform = "matrix(0.5, 0, 0, 0.5, 0, -4)"; - popup.style.transformOrigin = "10px 20px"; - layOut(popup, { x: 35.25, y: 44.5 }, { drawn: { x: 5, y: 6 } }); - - toggle(popupBeforeToggle, popup, "open"); - expect([ - popup.style.getPropertyValue("--rx-popup-snap-x"), - popup.style.getPropertyValue("--rx-popup-snap-y"), - ]).toEqual(["-0.25px", "0.5px"]); -}); - -test("a popup the browser turned over is moved the other way", async () => { - vi.stubGlobal("CSS", { supports: () => true }); - const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); - const { popup } = build(); - layOut(popup, { x: 34.640625, y: 52.25 }, { turned: true }); - - toggle(popupBeforeToggle, popup, "open"); - expect(popup.getAttribute("style")).toBe( - "--rx-popup-snap-x: -0.359375px; --rx-popup-snap-y: 0.25px;", - ); -}); - -test("a screen with more pixels has the popup on its pixels", async () => { - vi.stubGlobal("CSS", { supports: () => true }); - vi.stubGlobal("devicePixelRatio", 2); - const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); - const { popup } = build(); - layOut(popup, { x: 10.3, y: 20.5 }); - - toggle(popupBeforeToggle, popup, "open"); - expect(popup.getAttribute("style")).toBe("--rx-popup-snap-x: 0.203125px;"); -}); - -test("a browser that does not place popups moves none before it is drawn", async () => { - const { popupBeforeToggle } = await import("$/reflex-ui/behaviors/popup.js"); - const { popup } = build(); - layOut(popup, { x: 34.640625, y: 52 }); - - toggle(popupBeforeToggle, popup, "open"); - expect(popup.getAttribute("style")).toBe(null); -}); - -test("a popup nothing opens is followed without a trigger", async () => { - const { popupToggle, opener } = await import( - "$/reflex-ui/behaviors/popup.js" - ); - document.body.innerHTML = `
`; - const [alone, unnamed] = /** @type {HTMLElement[]} */ ([ - ...document.querySelectorAll("[popover]"), - ]); - - expect(opener(alone)).toBe(null); - expect(opener(unnamed)).toBe(null); - expect(toggle(popupToggle, alone, "open")).toBe(true); -}); - -test("the popups a loop renders with one id are told apart", async () => { - const { opener, pair } = await import("$/reflex-ui/behaviors/popup.js"); - document.body.innerHTML = [1, 2] - .map( - () => - `
`, - ) - .join(""); - const spans = [...document.querySelectorAll("span")]; - for (const span of spans) { - pair( - /** @type {Element} */ (span.querySelector("[popover]")), - span.querySelector("button"), - ); - } - // A second sync of the first changes nothing. - pair( - /** @type {Element} */ (spans[0].querySelector("[popover]")), - spans[0].querySelector("button"), - ); - pair(/** @type {Element} */ (spans[1].querySelector("[popover]")), null); - - expect( - spans.map((span) => [ - span.querySelector("[popover]")?.id, - span.querySelector("button")?.getAttribute("popovertarget"), - span.querySelector("button")?.getAttribute("aria-controls"), - ]), - ).toEqual([ - ["rx-list-1", "rx-list-1", "rx-list-1"], - ["rx-list-2", "rx-list-2", "rx-list-2"], - ]); - expect( - opener(/** @type {Element} */ (spans[1].querySelector("[popover]"))), - ).toBe(spans[1].querySelector("button")); -}); - -test("a browser without anchor positioning has the popup placed by a script", async () => { - installPopover(); - const { popupPlace } = await import("$/reflex-ui/behaviors/popup.js"); - const { trigger, popup } = build(); - vi.stubGlobal("innerWidth", 800); - vi.stubGlobal("innerHeight", 600); - trigger.getBoundingClientRect = () => - /** @type {DOMRect} */ ({ left: 40, top: 100, bottom: 132, width: 120 }); - Object.defineProperty(popup, "offsetHeight", { value: 200 }); - Object.defineProperty(popup, "offsetWidth", { value: 160 }); - popup.style.marginTop = "4px"; - - popup.showPopover(); - popupPlace(popup); - await vi.waitFor(() => expect(popup.style.top).toBe("132px")); - expect(popup.getAttribute("style")).toBe( - "margin-top: 4px; position: fixed; inset: auto; min-width: 120px; max-height: 454px; left: 40px; top: 132px;", - ); -}); - -/** - * Build a popover with a control and a button that closes it, after the - * button that opens it. - * - * @param {string} [attributes] The attributes of the popover. - * @returns {Promise<{ api: typeof import("$/reflex-ui/behaviors/popup.js"), trigger: HTMLElement, popup: HTMLElement, seen: string[], on: Record void> }>} - * The script, the two elements, and handlers that keep what they are - * called with. - */ -async function popover(attributes = "") { - installPopover(); - const api = await import("$/reflex-ui/behaviors/popup.js"); - document.body.innerHTML = ` - -
- - -
- `; - const popup = /** @type {HTMLElement} */ ( - document.querySelector("[popover]") - ); - /** @type {string[]} */ - const seen = []; - const on = Object.fromEntries( - [ - "open", - "openAutoFocus", - "closeAutoFocus", - "escape", - "outside", - "focusOutside", - "interact", - ].map((name) => [ - name, - (/** @type {boolean | undefined} */ open) => - seen.push(open === undefined ? name : `${name}:${open}`), - ]), - ); - for (const type of ["beforetoggle", "toggle"]) - popup.addEventListener(type, (event) => - api.popupEvent( - /** @type {{ type: string, target: EventTarget | null, currentTarget: HTMLElement }} */ ( - /** @type {unknown} */ (event) - ), - on, - ), - ); - return { - api, - trigger: /** @type {HTMLElement} */ (document.getElementById("open")), - popup, - seen, - on, - }; -} - -/** - * Send a popover something that happens inside it. - * - * @param {typeof import("$/reflex-ui/behaviors/popup.js")} api The script. - * @param {HTMLElement} popup The popover. - * @param {string} type The type of the event. - * @param {{ target?: string, key?: string, to?: string }} [details] The id - * of the element it happens on, the key, and where the focus goes. - * @returns {void} - */ -function inside(api, popup, type, { target, key, to } = {}) { - api.popupEvent({ - type, - target: target ? document.getElementById(target) : popup, - currentTarget: popup, - key, - relatedTarget: to ? document.getElementById(to) : null, - }); -} - -test("a popover takes the focus when it opens, and says what closed it", async () => { - const { api, popup, trigger, seen } = await popover(); - api.popupSync(popup); - api.popupSync(null); - expect([popup.id, trigger.getAttribute("popovertarget")]).toEqual([ - "rx-panel-1", - "rx-panel-1", - ]); - expect(document.getElementById("close")?.getAttribute("popovertarget")).toBe( - "rx-panel-1", - ); - - popup.showPopover(); - expect(document.activeElement).toBe(popup); - expect(said(trigger)).toEqual(["true", "open"]); - inside(api, popup, "keydown", { target: "field", key: "a" }); - inside(api, popup, "keydown", { target: "field", key: "Escape" }); - popup.hidePopover(); - - popup.showPopover(); - inside(api, popup, "click", { target: "field" }); - inside(api, popup, "click", { target: "close-text" }); - popup.hidePopover(); - - popup.showPopover(); - popup.hidePopover(); - - expect(seen).toEqual([ - "open:true", - "openAutoFocus", - "escape", - "open:false", - "closeAutoFocus", - "open:true", - "openAutoFocus", - "open:false", - "closeAutoFocus", - "open:true", - "openAutoFocus", - "outside", - "interact", - "open:false", - "closeAutoFocus", - ]); -}); - -test("Escape closes a popover as Escape wherever the focus is", async () => { - const { api, popup, seen } = await popover(); - api.popupSync(popup); - popup.showPopover(); - // The focus is not in the popover yet: the browser closes it on the - // Escape all the same, in the task of the key. - document.body.dispatchEvent( - new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), - ); - popup.hidePopover(); - // What closes it in a later task is not the key. - popup.showPopover(); - await new Promise((resolve) => setTimeout(resolve)); - popup.hidePopover(); - expect(seen).toEqual([ - "open:true", - "openAutoFocus", - "escape", - "open:false", - "closeAutoFocus", - "open:true", - "openAutoFocus", - "outside", - "interact", - "open:false", - "closeAutoFocus", - ]); -}); - -test("a popover closes when the focus leaves it for the page", async () => { - const { api, popup, seen } = await popover(); - popup.showPopover(); - inside(api, popup, "blur", { target: "field", to: "close" }); - inside(api, popup, "blur", { target: "field", to: "open" }); - inside(api, popup, "blur", { target: "field" }); - expect(popup.matches(":popover-open")).toBe(true); - // A press outside is left to the browser. - const beside = /** @type {HTMLElement} */ (document.getElementById("beside")); - const matches = beside.matches.bind(beside); - beside.matches = (selector) => selector === ":active" || matches(selector); - inside(api, popup, "blur", { target: "field", to: "beside" }); - expect(popup.matches(":popover-open")).toBe(true); - beside.matches = matches; - inside(api, popup, "blur", { target: "field", to: "beside" }); - expect(popup.matches(":popover-open")).toBe(false); - expect(seen).toEqual([ - "open:true", - "openAutoFocus", - "focusOutside", - "interact", - "open:false", - "closeAutoFocus", - ]); -}); - -test("a popover bound to state shows its state, and one that starts open opens once", async () => { - const { api, popup, seen } = await popover('data-default-open="true"'); - api.popupSync(popup); - expect(popup.matches(":popover-open")).toBe(true); - expect(popup.hasAttribute("data-default-open")).toBe(false); - api.popupSync(popup, false); - api.popupSync(popup, false); - expect(popup.matches(":popover-open")).toBe(false); - api.popupSync(popup); - expect(popup.matches(":popover-open")).toBe(false); - api.popupSync(popup, true); - expect(popup.matches(":popover-open")).toBe(true); - expect(seen).toEqual(["openAutoFocus", "closeAutoFocus", "openAutoFocus"]); -}); - -test("a popover without handlers, and the toggle of a popup inside it, change nothing", async () => { - installPopover(); - const api = await import("$/reflex-ui/behaviors/popup.js"); - document.body.innerHTML = `
`; - const popup = /** @type {HTMLElement} */ (document.getElementById("mine")); - api.popupSync(popup); - expect(popup.id).toBe("mine"); - api.popupEvent({ - type: "beforetoggle", - target: popup, - currentTarget: popup, - newState: "open", - }); - popup.showPopover(); - api.popupEvent({ - type: "toggle", - target: popup, - currentTarget: popup, - newState: "open", - }); - expect(document.activeElement).toBe(popup); - api.popupEvent({ - type: "toggle", - target: document.getElementById("inner"), - currentTarget: popup, - newState: "closed", - }); - expect( - said(/** @type {HTMLElement} */ (document.getElementById("open"))), - ).toEqual(["true", "open"]); - api.popupEvent({ - type: "beforetoggle", - target: popup, - currentTarget: popup, - newState: "closed", - }); - api.popupEvent({ type: "click", target: null, currentTarget: popup }); -}); diff --git a/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py index 07a540c7251..e53f68f207f 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py @@ -21,7 +21,7 @@ OPEN = "open" KEYS = "keys" # What the area matches while its menu is open. -KEYS_STATE = "[data-state='open']" +KEYS_STATE = ":is([data-state='open'], [data-open])" SUB = "sub" _RADIX = ".rt-BaseMenuContent:not(.rt-BaseMenuSubContent)" _UI = "[role=menu]:popover-open:not([role=menu] *)" @@ -198,11 +198,9 @@ def _open_sub(page: Page, target: Locator, point: Point) -> None: ), }, states={ - OPEN: State( - enter=_right_click, leave=close_menu, matches="[data-state='open']" - ), + OPEN: State(enter=_right_click, leave=close_menu, matches=KEYS_STATE), KEYS: State(enter=_keys, leave=close_menu, matches=KEYS_STATE), - SUB: State(enter=_open_sub, leave=close_menu, matches="[data-state='open']"), + SUB: State(enter=_open_sub, leave=close_menu, matches=KEYS_STATE), }, # Not held to a threshold of zero. At zero 18 of the 39 cells are equal # pixel for pixel. In the 9 with a sub-menu open, the shadows of the two diff --git a/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py index fde44bf1c20..1a3494cbff4 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py @@ -19,10 +19,10 @@ ALIGNS = ["start", "center", "end"] OPEN = "open" # A hover card that is shown, in either system. -SHOWN = ".rt-HoverCardContent, [data-rx-popup]:popover-open" +SHOWN = ".rt-HoverCardContent, [data-slot=hover-card-content][data-open]" # The card that is open, in each system: Radix renders it at the end of the # page, rx.ui right after its trigger. -CARD = (in_page(".rt-HoverCardContent"), "[data-rx-popup]:popover-open") +CARD = (in_page(".rt-HoverCardContent"), "[data-slot=hover-card-content][data-open]") def _card(namespace: Any) -> list[Any]: @@ -158,7 +158,9 @@ def _blur_card(page: Page, target: Locator, point: Point) -> None: "link": (f"{CARD[0]} a", f"{CARD[1]} a"), }, states={ - OPEN: State(enter=_show, leave=_hide, matches="[data-state='open']"), + OPEN: State( + enter=_show, leave=_hide, matches=":is([data-state='open'], [data-open])" + ), FOCUS_VISIBLE: State( enter=_focus_card, leave=_blur_card, matches=":focus-visible" ), diff --git a/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py b/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py index 311289e5de8..a48f4f073cb 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/tooltip.py @@ -17,7 +17,7 @@ ALIGNS = ["start", "center", "end"] OPEN = "open" # A tooltip that is shown, in either system. -SHOWN = ".rt-TooltipContent, [role=tooltip]:popover-open" +SHOWN = ".rt-TooltipContent, [role=tooltip][data-open]" LONG = ( "A tooltip with more to say than one line holds, which wraps where a " "tooltip is as wide as it may be." @@ -108,14 +108,19 @@ def _hide(page: Page, target: Locator, point: Point) -> None: crop="stage", target="button", parts={ - "content": (in_page(".rt-TooltipContent"), "[role=tooltip]:popover-open"), - "text": (in_page(".rt-TooltipText"), "[role=tooltip]:popover-open > p"), + "content": (in_page(".rt-TooltipContent"), "[role=tooltip][data-open]"), + "text": (in_page(".rt-TooltipText"), "[role=tooltip][data-open] > p"), }, states={ OPEN: State( enter=_show, leave=_hide, - matches=":is([data-state='delayed-open'], [data-state='instant-open'])", + # The trigger of UI SDK says nothing of its tooltip, which comes + # right after it. + matches=( + ":is([data-state='delayed-open'], [data-state='instant-open']," + " :has(+ [role=tooltip][data-open]))" + ), ) }, # Held to a threshold of zero, and to the arrow: the tooltip of Radix has @@ -222,7 +227,7 @@ def _contract(namespace: Any) -> Any: # The text of each tooltip that is shown. SHOWING = ( - "[...document.querySelectorAll('.rt-TooltipContent, [role=tooltip]:popover-open')]" + "[...document.querySelectorAll('.rt-TooltipContent, [role=tooltip][data-open]')]" ".map(tooltip => tooltip.querySelector('p').textContent)" ) # What describes an element to assistive technology, by its id. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py index a6b3e88fae7..beedaa36a36 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.py @@ -24,10 +24,10 @@ ) from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.dialog import ( + DIALOG_BACKDROP, + DIALOG_CONTENT, DIALOG_DESCRIPTION, DIALOG_TITLE, - SDK_DIALOG_BACKDROP, - SDK_DIALOG_CONTENT, ) # The heading of the first level a title renders as, as in Radix Themes. @@ -56,13 +56,13 @@ class DialogBackdropBase(SDKPart): A press on it is a press outside the dialog. """ - styles: ClassVar[ComponentStyles] = SDK_DIALOG_BACKDROP + styles: ClassVar[ComponentStyles] = DIALOG_BACKDROP class DialogContentBase(PopupContentPart): """The content of a dialog: its panel, after what is drawn over the page.""" - styles: ClassVar[ComponentStyles] = SDK_DIALOG_CONTENT + styles: ClassVar[ComponentStyles] = DIALOG_CONTENT # The part drawn over the page behind the panel, or None for none. _backdrop: ClassVar[type[SDKPart] | None] = None diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py index e2bd96030fb..024e616cd1c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py @@ -1,24 +1,29 @@ -"""What the menus share: a popover of items, its sub-menus, and its script.""" +"""What the menus share: the parts of ``@ui-sdk/react/menu``, in the look of Radix Themes. + +UI SDK opens a menu in the top layer, beside its trigger or at the pointer, +moves through its items with the keys and by typing, opens its sub-menus, +checks its checkbox items and closes it on Escape, on a press outside and +on a choice. The content hands its look to its items and its sub-menus, +as Radix does through a context. +""" from __future__ import annotations -from collections.abc import Iterator from typing import Any, ClassVar from reflex_base.components.component import Component from reflex_base.components.tags import CommonTag -from reflex_base.vars.base import LiteralVar, Var -from reflex_components_core.base.fragment import Fragment - -from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.components._group import descendants -from reflex_components_ui.components._popup import ( - PopupContent, - PopupPart, - PopupRoot, - PopupTrigger, +from reflex_base.vars.base import get_unique_variable_name + +from reflex_components_ui.base import Part +from reflex_components_ui.components._group import descendants, literal +from reflex_components_ui.components._sdk import ( + COLLISION_PADDING, + PlacedContent, + PopupRootPart, + SDKPart, + entry, ) -from reflex_components_ui.components._script import listen, script from reflex_components_ui.components.select import ( _CHECK, _icon, # pyright: ignore[reportAttributeAccessIssue] @@ -32,6 +37,8 @@ MENU_SUB_CONTENT, ) +LIBRARY = entry("menu") + # The chevron of an item that opens a sub-menu, as Radix Themes draws it. _CHEVRON = ( "M3.23826 0.201711C3.54108 -0.0809141 4.01567 -0.0645489 4.29829 0.238264" @@ -42,148 +49,165 @@ ) -class MenuTrigger(PopupTrigger): - """What opens a menu: its child, a button the browser opens the menu from.""" +def raised(size: Any) -> int: + """Get how far up a menu goes for the text of its first item to be level. + + A sub-menu, and a context menu, are as far up as the padding of the menu, + so that the text of their first item is level with what opens them. + + Args: + size: The size of the menu. + + Returns: + The offset along what opens the menu, in pixels. + """ + size = literal(size) + return -4 * int(size if size in ("1", "2") else 2) + + +class MenuRoot(PopupRootPart): + """A menu or a sub-menu: no element, the root of its parts.""" + + library = LIBRARY - _haspopup: ClassVar[str] = "menu" + # The arrow keys stop at the ends, as in Radix: UI SDK goes round. + _defaults: ClassVar[dict[str, Any]] = {"loop": False} def _exclude_props(self) -> list[str]: - """Keep ``as_child`` off the element: the trigger is always its child. + """Keep the direction off the menu, which is no element. Returns: - The props read as styles, and ``as_child``. + The props read as styles, and ``dir``: UI SDK reads the direction + of the page around the menu. """ - return [*super()._exclude_props(), "as_child"] + return [*super()._exclude_props(), "dir"] - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the trigger, its script included. - Args: - include_children: Whether to include Vars from children. - ignore_ids: The ids to ignore. +class MenuContent(PlacedContent): + """The content of a menu or a sub-menu, its items inside what scrolls them.""" - Yields: - Each var referenced by the component. - """ - yield from super()._get_vars(include_children, ignore_ids) - yield script("menu", "menuTrigger") + library = LIBRARY - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. + _sdk_names: ClassVar[dict[str, str]] = {"forceMount": "keepMounted"} + + # Whether the arrow keys go round: a prop of the menu in UI SDK. + _root_props: ClassVar[tuple[str, ...]] = ("loop",) + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create the content, its items inside the element that scrolls them. Args: - props: The props to render (if None, then use get_props). + *children: The items. + **props: The properties of the content. Returns: - The tag: its child, which opens its menu with a press, and with - Enter, Space and the down arrow on the first item. + The content. """ - return listen( - super()._render(props), script("menu", "menuTrigger"), "onKeyDown" + return super().create( + Part.create( + Part.create(*children, part="viewport", tag="div"), + part="scroll", + tag="div", + ), + **props, ) - -class MenuArea(PopupTrigger): - """What a context menu opens on: its child, where the pointer asks for it.""" - - def _join(self, root: Any, name: Any, on_open_change: Any) -> None: - """Take the id of the menu the element opens. + def _post_init(self, *args, **kwargs): + """Initialize the content, and give its items its look. Args: - root: The context menu. - name: The id of the menu. - on_open_change: What the menu does when it opens or closes. + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. """ - self._popup = {"data-rx-opens": name} + # Whether the menu has checkbox items, which leave room for a check. + self._indented: Any = None + super()._post_init(*args, **kwargs) + self._look: tuple[Any, Any] = ( + getattr(self, "variant", None), + getattr(self, "high_contrast", None), + ) + self._join_items() + + def _join_items(self) -> None: + """Give the items of the menu its look, those of its sub-menus too.""" + indented = False + for member in descendants( + self, + (MenuItemPart, MenuContent), # pyright: ignore[reportArgumentType] + MenuContent, + ): + if isinstance(member, MenuSubContent): + member._inherit(self) + else: + member._join(self) + indented = indented or isinstance(member, MenuCheckboxItem) + self._indented = indented + self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] def _exclude_props(self) -> list[str]: - """Keep ``disabled`` off the element, which says it otherwise. + """Keep the props UI SDK has no use for off the content. Returns: - The props read as styles, and ``disabled``. + The props read as styles, and those of the placement of Radix that + UI SDK does not have: it always keeps a menu in the viewport. """ - return [*super()._exclude_props(), "disabled"] + return [ + *super()._exclude_props(), + "as_child", + "avoid_collisions", + "sticky", + "hide_when_detached", + ] - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the element, its script included. - Args: - include_children: Whether to include Vars from children. - ignore_ids: The ids to ignore. +class MenuSubContent(MenuContent): + """The content of a sub-menu, which takes the look of the menu it opens from.""" + + tag = "MenuSubContent" + + styles: ClassVar[ComponentStyles] = MENU_SUB_CONTENT + + # Where Radix Themes places a sub-menu. + _placement: ClassVar[dict[str, Any]] = { + "sideOffset": 1, + "collisionPadding": COLLISION_PADDING, + } - Yields: - Each var referenced by the component. + def _inherit(self, menu: MenuContent) -> None: + """Take the look of the menu the sub-menu opens from, as in Radix. + + Args: + menu: The content of that menu. """ - yield from super()._get_vars(include_children, ignore_ids) - yield script("menu", "menuContext") + self._look = menu._look + self.size = getattr(menu, "size", None) + self._join_items() def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the element. + """Render the content, placed as Radix Themes places a sub-menu. Args: props: The props to render (if None, then use get_props). Returns: - The tag: its child, which opens its menu where the pointer or - the keyboard asks for one, unless it is disabled. + The tag, as far up as the padding of the menu where it is given no + offset along its trigger. """ - tag = UIComponent._render(self, props).add_props(**{ - "data-state": "closed", - **self._popup, - }) - disabled = getattr(self, "disabled", None) - if disabled is not None: - disabled = LiteralVar.create(disabled) - tag = tag.add_props(**{ - "data-disabled": Var( - f'({disabled!s} ? "" : undefined)', - _var_data=disabled._get_all_var_data(), - ) - }) - return listen(tag, script("menu", "menuContext"), "onContextMenu") - - -class MenuItem(UIComponent): - """An item of a menu, which its menu gives its look.""" - - tag = "div" - - styles: ClassVar[ComponentStyles] = MENU_ITEM - - # What the item is to assistive technology. - _role: ClassVar[str] = "menuitem" - - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create an item, with its shortcut after what it shows. + tag = super()._render(props) + if getattr(self, "align_offset", None) is not None: + return tag + return tag.add_props(alignOffset=raised(getattr(self, "size", None))) - Args: - *children: What the item shows. - **props: The properties of the item. - Returns: - The item. - """ - shortcut = props.get("shortcut") - return super().create(*children, *cls._after(shortcut), **props) +class MenuItemPart(SDKPart): + """An item of a menu, which its menu gives its look.""" - @classmethod - def _after(cls, shortcut: Any) -> list[Component]: - """Create what comes after what the item shows. + library = LIBRARY - Args: - shortcut: The shortcut the item names, or None. + styles: ClassVar[ComponentStyles] = MENU_ITEM - Returns: - The shortcut, when it has one. - """ - if shortcut is None: - return [] - return [Part.create(shortcut, part="shortcut", tag="div")] + _sdk_names: ClassVar[dict[str, str]] = {"textValue": "label"} def _post_init(self, *args, **kwargs): """Initialize the item, as one outside a menu. @@ -207,187 +231,174 @@ def _join(self, menu: MenuContent) -> None: self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] def _exclude_props(self) -> list[str]: - """Keep the props that are no attributes off the element. + """Keep the props UI SDK has no use for off the item. Returns: - The props read as styles, and the ones the item renders itself. + The props read as styles, ``as_child`` and the shortcut, which is + shown: a shortcut of UI SDK is a key it binds. """ - return [ - *super()._exclude_props(), - "shortcut", - "text_value", - "disabled", - "as_child", - ] + return [*super()._exclude_props(), "as_child", "shortcut"] - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the item. + +def _shortcut(shortcut: Any) -> list[Component]: + """Create the shortcut an item shows after what it shows. + + Args: + shortcut: The shortcut the item names, or None. + + Returns: + The shortcut, when it has one. + """ + if shortcut is None: + return [] + return [Part.create(shortcut, part="shortcut", tag="div")] + + +class MenuItem(MenuItemPart): + """An item of a menu, which runs when it is chosen.""" + + tag = "MenuItem" + + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create an item, with its shortcut after what it shows. Args: - props: The props to render (if None, then use get_props). + *children: What the item shows. + **props: The properties of the item. Returns: - The tag: an item its menu moves the focus to, which says when it - is disabled and what it is found by. + The item. """ - disabled = getattr(self, "disabled", None) - text = getattr(self, "text_value", None) - attributes: dict[str, Any] = {"role": self._role, "tabIndex": -1} - if disabled is not None: - attributes["aria-disabled"] = disabled - if text is not None: - attributes["data-text-value"] = text - tag = super()._render(props) - rendered = dict(tag.props) - # A choice is a press on the item, or Enter or Space on it. - if "onSelect" in rendered: - rendered["onClick"] = rendered.pop("onSelect") - return tag.set(props=rendered).add_props(**attributes) + return super().create(*children, *_shortcut(props.get("shortcut")), **props) -class MenuCheckboxItem(MenuItem): +class MenuCheckboxItem(MenuItemPart): """An item of a menu that is checked or not.""" - _role: ClassVar[str] = "menuitemcheckbox" + tag = "MenuCheckboxItem" + + _sdk_names: ClassVar[dict[str, str]] = { + "textValue": "label", + "onChange": "onCheckedChange", + } @classmethod - def _after(cls, shortcut: Any) -> list[Component]: - """Create what comes after what the item shows. + def create(cls, *children: Any, **props: Any) -> Component: + """Create a checkbox item: the check, what it shows and its shortcut. Args: - shortcut: The shortcut the item names, or None. + *children: What the item shows. + **props: The properties of the item. Returns: - The check, shown while the item is checked, and the shortcut. + The item. """ - return [ + return super().create( Part.create( _icon("check", _CHECK, fillRule="evenodd", clipRule="evenodd"), part="indicator", tag="span", ), - *super()._after(shortcut), - ] + *children, + *_shortcut(props.get("shortcut")), + **props, + ) + + def _post_init(self, *args, **kwargs): + """Initialize the item, with the value UI SDK keeps its state under. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + # UI SDK keeps whether an item is checked under its value: one of its + # own where it is given none, as each item of Radix is checked alone. + self._key = get_unique_variable_name() + + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the item, which closes its menu when it is chosen, as in Radix. + + Args: + props: The props to render (if None, then use get_props). + + Returns: + The tag: UI SDK keeps a menu open on a checkbox item by default. + """ + tag = super()._render(props).add_props(closeOnSelect=True) + if getattr(self, "value", None) is not None: + return tag + return tag.add_props(value=self._key) def _exclude_props(self) -> list[str]: - """Keep the state of the item off the element, which says it otherwise. + """Keep the props of a checkbox that an item has no use for off it. Returns: - The props read as styles, and the ones the item renders itself. + The props read as styles, and those of a form control. """ return [ *super()._exclude_props(), - "checked", - "default_checked", "size", "variant", "high_contrast", "required", "name", - "value", ] - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the item. - Args: - props: The props to render (if None, then use get_props). +class MenuSubTrigger(MenuItemPart): + """An item that opens a sub-menu, with the chevron that says so.""" - Returns: - The tag: an item that says whether it is checked, and that its - script checks and unchecks. - """ - checked = getattr(self, "checked", None) - if checked is None: - checked = getattr(self, "default_checked", None) - if checked is None: - checked = LiteralVar.create(False) - checked = LiteralVar.create(checked) - tag = super()._render(props) - rendered = dict(tag.props) - change = rendered.pop("onChange", None) - tag = tag.set(props=rendered).add_props(**{ - "aria-checked": checked, - "data-state": Var(f'({checked!s} ? "checked" : "unchecked")'), - }) - return listen( - tag, - script("menu", "menuCheck"), - "onClick", - arguments=(change, getattr(self, "checked", None) is not None), - ) + tag = "MenuSubTrigger" - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the item, its script included. + @classmethod + def create(cls, *children: Any, **props: Any) -> Component: + """Create the item, with the chevron that says it opens a sub-menu. Args: - include_children: Whether to include Vars from children. - ignore_ids: The ids to ignore. + *children: What the item shows. + **props: The properties of the item. - Yields: - Each var referenced by the component. + Returns: + The item. """ - yield from super()._get_vars(include_children, ignore_ids) - yield script("menu", "menuCheck") - - -class MenuSubTrigger(PopupPart, MenuItem): - """An item that opens a sub-menu.""" - - @classmethod - def _after(cls, shortcut: Any) -> list[Component]: - """Create what comes after what the item shows. + return super().create( + *children, + Part.create(_icon("chevron", _CHEVRON), part="shortcut", tag="div"), + **props, + ) - Args: - shortcut: Nothing: the item has none. + def _exclude_props(self) -> list[str]: + """Keep ``text_value`` off the item: UI SDK finds it by its text. Returns: - The chevron that says it opens a sub-menu. + The props read as styles, and ``text_value``. """ - return [Part.create(_icon("chevron", _CHEVRON), part="shortcut", tag="div")] + return [*super()._exclude_props(), "text_value"] - def _join(self, root: Any, name: Any = None, on_open_change: Any = None) -> None: - """Take the look of its menu, or the id of the sub-menu it opens. - Args: - root: The content of the menu the item is in, or its sub-menu. - name: The id of the sub-menu. - on_open_change: What the sub-menu does when it opens or closes. - """ - if isinstance(root, MenuContent): - MenuItem._join(self, root) - return - self._popup = { - "data-rx-opens": name, - "aria-controls": name, - "aria-haspopup": "menu", - "aria-expanded": False, - "data-state": "closed", - } +class MenuSeparator(SDKPart): + """A line between items.""" - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the item. + library = LIBRARY - Args: - props: The props to render (if None, then use get_props). + tag = "MenuSeparator" - Returns: - The tag: an item that says which sub-menu it opens. - """ - return super()._render(props).add_props(**self._popup) + styles: ClassVar[ComponentStyles] = MENU_SEPARATOR -class MenuLabel(UIComponent): +class MenuLabel(SDKPart): """A label of a group of items, which cannot be chosen.""" - tag = "div" + library = LIBRARY + + tag = "MenuGroupLabel" styles: ClassVar[ComponentStyles] = MENU_LABEL def _exclude_props(self) -> list[str]: - """Keep the props that are no attributes off the element. + """Keep ``as_child`` off the label. Returns: The props read as styles, and ``as_child``. @@ -395,18 +406,20 @@ def _exclude_props(self) -> list[str]: return [*super()._exclude_props(), "as_child"] -class MenuGroup(UIComponent): - """A group of items.""" +class MenuGroup(SDKPart): + """A group of items, named by its label.""" + + library = LIBRARY - tag = "div" + tag = "MenuGroup" styles: ClassVar[ComponentStyles] = MENU_GROUP def _exclude_props(self) -> list[str]: - """Keep the props that are no attributes off the element. + """Keep ``as_child`` and a value off the group. Returns: - The props read as styles, ``as_child`` and a value. + The props read as styles, ``as_child`` and ``value``. """ return [*super()._exclude_props(), "as_child", "value"] @@ -417,184 +430,12 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: props: The props to render (if None, then use get_props). Returns: - The tag: a group, to assistive technology. A value it changes is - the business of its items, so a change inside it says nothing. + The tag. A value it changes is the business of its items, so a + change inside it says nothing. """ tag = super()._render(props) - rendered = { - name: value for name, value in tag.props.items() if name != "onChange" - } - return tag.set(props=rendered).add_props(role="group") - - -class MenuSeparator(UIComponent): - """A line between items.""" - - tag = "div" - - styles: ClassVar[ComponentStyles] = MENU_SEPARATOR - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the separator. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: a separator, to assistive technology. - """ - return ( - super() - ._render(props) - .add_props(role="separator", **{"aria-orientation": "horizontal"}) - ) - - -class MenuContent(PopupContent): - """A native popover of items, whose script moves through them.""" - - _role: ClassVar[str | None] = "menu" - - _script: ClassVar[tuple[str, ...]] = ( - "menu", - "menuSync", - "menuEvent", - "onBeforeToggle", - "onToggle", - "onKeyDown", - "onClick", - "onPointerMove", - "onPointerLeave", - "onBlur", - ) - - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a menu, its items inside the element that scrolls them. - - Args: - *children: The items. - **props: The properties of the menu. - - Returns: - The menu. - """ - return super().create( - Part.create( - Part.create(*children, part="viewport", tag="div"), - part="scroll", - tag="div", - ), - **props, - ) - - def _post_init(self, *args, **kwargs): - """Initialize the menu, and give its items its look. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # Whether the menu has checkbox items, which leave room for a check. - self._indented: Any = None - super()._post_init(*args, **kwargs) - # The look the items of the menu take: its variant and its contrast. - self._look: tuple[Any, Any] = ( - getattr(self, "variant", None), - getattr(self, "high_contrast", None), + return tag.set( + props={ + name: value for name, value in tag.props.items() if name != "onChange" + } ) - self._join_items() - - def _join_items(self) -> None: - """Give the items of the menu its look, those of its sub-menus too.""" - indented = False - for member in descendants(self, (MenuItem, MenuContent), MenuContent): # pyright: ignore[reportArgumentType] - if isinstance(member, MenuSubContent): - member._inherit(self) - elif isinstance(member, MenuItem): - member._join(self) - indented = indented or isinstance(member, MenuCheckboxItem) - self._indented = indented - self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - - def _exclude_props(self) -> list[str]: - """Keep the props that are no attributes off the element. - - Returns: - The props read as styles, and the ones the menu renders itself. - """ - return [*super()._exclude_props(), "loop", "as_child"] - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the menu. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: a popover with the role of a menu, which says whether - its arrows go round. - """ - tag = super()._render(props) - loop = getattr(self, "loop", None) - return tag if loop is None else tag.add_props(**{"data-loop": loop}) - - -class MenuSub(PopupRoot): - """Contains all the parts of a submenu.""" - - _prefix: ClassVar[str] = "rx-menu-sub" - - -class MenuSubContent(MenuContent): - """The component that pops out when a submenu is open.""" - - styles: ClassVar[ComponentStyles] = MENU_SUB_CONTENT - - def _inherit(self, menu: MenuContent) -> None: - """Take the look of the menu the sub-menu opens from, as in Radix. - - Args: - menu: The content of that menu. - """ - self._look = menu._look - self.size = getattr(menu, "size", None) - self._join_items() - - -class MenuPoint(UIComponent): - """Where a context menu opens: an element of no size its script moves to the pointer.""" - - tag = "span" - - styles: ClassVar[ComponentStyles] = { - "base": { - "position": "fixed", - "width": "0", - "height": "0", - "pointer_events": "none", - } - } - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the point. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: nothing to assistive technology. - """ - return super()._render(props).add_props(**{"aria-hidden": True}) - - -def at_point(content: Component) -> Component: - """Put a menu after the point it opens at. - - Args: - content: The menu. - - Returns: - The point, then the menu. - """ - return Fragment.create(MenuPoint.create(), content) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py deleted file mode 100644 index ec6febb79cf..00000000000 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_popup.py +++ /dev/null @@ -1,481 +0,0 @@ -"""What the popups share: a native popover, and what opens and closes it.""" - -from __future__ import annotations - -import itertools -from collections.abc import Iterator -from typing import Any, ClassVar - -from reflex_base.components.component import Component -from reflex_base.components.tags import CommonTag -from reflex_base.vars.base import LiteralVar, Var, VarData - -from reflex_components_ui.base import UIComponent -from reflex_components_ui.components._group import descendants, literal -from reflex_components_ui.components._script import handlers, listen, script -from reflex_components_ui.components._slot import become_child, held -from reflex_components_ui.props import style_before -from reflex_components_ui.styles.popup import OFFSET, SHIFT - -# Numbers the popups of an app: what opens a popup names it by its id. -_ids = itertools.count(1) - -# The events of a popup as they are rendered, by the name the script calls -# each under. -_EVENTS = { - "onOpenChange": "open", - "onOpenAutoFocus": "openAutoFocus", - "onCloseAutoFocus": "closeAutoFocus", - "onEscapeKeyDown": "escape", - "onPointerDownOutside": "outside", - "onFocusOutside": "focusOutside", - "onInteractOutside": "interact", -} - - -def pixels(amount: Any) -> Any: - """Write a number of pixels as a length. - - Args: - amount: The number, or a Var of it. - - Returns: - The length: a string when the number is known while compiling. - """ - amount = literal(amount) - if not isinstance(amount, Var): - return f"{amount}px" - return Var( - f'(({amount!s}) + "px")', _var_type=str, _var_data=amount._get_all_var_data() - ) - - -def offsets(props: dict[str, Any], gap: int = 0) -> None: - """Put how far a popup is from its anchor before its other styles. - - Args: - props: The props a popup is created with, changed in place: its - ``side_offset`` and its ``align_offset`` become custom - properties the placement of the popup reads. - gap: The room, in pixels, the popup leaves beside its anchor on top - of the distance it is asked to keep. - """ - distances = { - name: pixels( - literal(LiteralVar.create(props[prop])) + extra if extra else props[prop] - ) - for prop, name, extra in ( - ("side_offset", OFFSET, gap), - ("align_offset", SHIFT, 0), - ) - if props.get(prop) is not None - } - if distances: - style_before(props, distances) - - -class PopupRoot(UIComponent): - """The root of a popup, which renders nothing of its own. - - Radix hands the parts of a popup its props through a context. Here the - root finds its parts while compiling, and gives them what they render. - """ - - library = "react" - - tag = "Fragment" - - _is_tag_in_global_scope: ClassVar[bool] = False - - # What the ids of the popups of the component start with. - _prefix: ClassVar[str] = "rx-popup" - - def _post_init(self, *args, **kwargs): - """Initialize the popup, and give its parts what they share. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - name: Any = f"{self._prefix}-{next(_ids)}" - on_open_change = self.event_triggers.pop("on_open_change", None) - parts = list(descendants(self, PopupPart, PopupRoot)) - for part in parts: - if isinstance(part, PopupContent) and part.id is not None: - name = part.id - for part in parts: - part._join(self, name, on_open_change) - - def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the popup off the root. - - Returns: - Every prop but the key, which a fragment takes: the root renders - no element. - """ - return [ - *super()._exclude_props(), - *(name for name in self.get_fields() if name != "key"), - ] - - -class PopupPart(UIComponent): - """A part of a popup, which its root gives a name.""" - - def _post_init(self, *args, **kwargs): - """Initialize the part, as one outside a popup. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # The attributes the popup gives the part. - self._popup: dict[str, Any] = {} - super()._post_init(*args, **kwargs) - - def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: - """Take from a popup what Radix hands its parts through a context. - - Args: - root: The popup the part is in. - name: The id of the popup. - on_open_change: What the popup does when it opens or closes. - """ - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the part, those its popup gives it 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) - for value in self._popup.values(): - if isinstance(value, Var): - yield value - - -class PopupTrigger(PopupPart): - """What opens a popup: its child, a button the browser opens the popup from.""" - - # The child keeps its own styles. - _merges_slot: ClassVar[bool] = False - - # What the trigger says it opens, to assistive technology. - _haspopup: ClassVar[str] = "dialog" - - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a part that is rendered as its child. - - Args: - *children: The child: one element. - **props: The properties of the component. - - Returns: - The component. - """ - return super().create(*held(children), **props) - - def _post_init(self, *args, **kwargs): - """Initialize the part, rendered as its only child. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - become_child(self) - - def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: - """Take the id of the popup the trigger opens. - - Args: - root: The popup the trigger is in. - name: The id of the popup. - on_open_change: What the popup does when it opens or closes. - """ - self._popup = {"popoverTarget": name, "aria-controls": name} - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: its child, which opens its popup without a script, - with the state Radix gives what opens a popup. - """ - return ( - super() - ._render(props) - .add_props(**{ - "aria-haspopup": self._haspopup, - "aria-expanded": False, - "data-state": "closed", - **self._popup, - }) - ) - - -class PopupClose(PopupTrigger): - """What closes a popup from inside it: its child, a button.""" - - def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: - """Take the id of the popup the button closes. - - Args: - root: The popup the button is in. - name: The id of the popup. - on_open_change: What the popup does when it opens or closes. - """ - self._popup = {"popoverTarget": name, "popoverTargetAction": "hide"} - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the button. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: its child, which closes the popup without a script. - """ - return UIComponent._render(self, props).add_props(**self._popup) - - -class PopupContent(PopupPart): - """A native popover placed beside what opens it.""" - - tag = "div" - - # The role of the popup. - _role: ClassVar[str | None] = "dialog" - - # The room the popup leaves beside its anchor on top of its offset. - _gap: ClassVar[int] = 0 - - # Whether the browser closes the popup on Escape and on a press outside - # it (``auto``), or its script does (``manual``). - _popover: ClassVar[str] = "auto" - - # Whether the popup takes the focus from its script. - _tab_index: ClassVar[int | None] = -1 - - # The script of the popup: its name, what keeps the popup as its state - # says, and what hears the events named after them. - _script: ClassVar[tuple[str, ...]] = ( - "popup", - "popupSync", - "popupEvent", - "onBeforeToggle", - "onToggle", - "onKeyDown", - "onClick", - "onBlur", - ) - - # Whether what the popup does is handed to what keeps it as its state - # says, rather than to what hears its events. - _synced: ClassVar[bool] = False - - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a popup. - - Args: - *children: What the popup holds. - **props: The properties of the component. - - Returns: - The popup, as far from its anchor as it is asked to be. - """ - offsets(props, cls._gap) - return super().create(*children, **props) - - def _post_init(self, *args, **kwargs): - """Initialize the popup, as one that is not bound to state. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # Whether the popup is open, when its state says. - self._open: Var | None = None - super()._post_init(*args, **kwargs) - - def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: - """Take the name of the popup, and whether it is open. - - Args: - root: The popup the element is in. - name: The id of the popup. - on_open_change: What the popup does when it opens or closes. - """ - if self.id is None: - self._popup["id"] = name - self._open = getattr(root, "open", None) - default_open = getattr(root, "default_open", None) - if default_open is not None: - self._popup["data-default-open"] = default_open - if on_open_change is not None: - self.event_triggers["on_open_change"] = on_open_change - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the popup, its script 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) - module, sync, heard = self._script[:3] - yield script(module, sync) - yield script(module, heard) - yield script("popup", "popupBeforeToggle") - if self._open is not None: - yield self._open - - def _exclude_props(self) -> list[str]: - """Keep the props that say where the popup goes off the element. - - Returns: - The props read as styles, the ones a style is made from, and - the ones the placement of the browser has no use for. - """ - return [ - *super()._exclude_props(), - "side_offset", - "align_offset", - "avoid_collisions", - "collision_padding", - "sticky", - "hide_when_detached", - "force_mount", - ] - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the popup. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: a popover the browser opens and closes, which says so - to its script, and through it to the events. - """ - tag, on = handlers(super()._render(props), _EVENTS) - module, sync_name, heard, *events = self._script - bound = LiteralVar.create(self._open) - sync = script(module, sync_name) - handed = f", {on!s}" if self._synced and on is not None else "" - tag = tag.add_props(**{ - "popover": self._popover, - "role": self._role, - "tabIndex": self._tab_index, - "data-rx-popup": "", - # Before it is first drawn, the popup is put on whole pixels. - "onBeforeToggle": script("popup", "popupBeforeToggle"), - **self._popup, - # Called whenever the page renders: a popup bound to state takes - # whether it is open from there. - "ref": Var( - f"((popup) => {sync_name}(popup, {bound!s}{handed}))", - _var_data=VarData.merge( - sync._get_all_var_data(), - bound._get_all_var_data(), - on._get_all_var_data() if handed and on is not None else None, - ), - ), - }) - return listen( - tag, - script(module, heard), - *events, - arguments=() if on is None or self._synced else (on,), - ) - - -class HoverTrigger(PopupTrigger): - """What a popup opens under: its child, which hears the pointer and the focus.""" - - # What the trigger hears of. - _heard: ClassVar[tuple[str, ...]] = ( - "onPointerEnter", - "onPointerLeave", - "onFocus", - "onBlur", - ) - - def _join(self, root: PopupRoot | None, name: Any, on_open_change: Any) -> None: - """Take the id of the popup that opens under the trigger. - - Args: - root: The popup the trigger is in. - name: The id of the popup. - on_open_change: What the popup does when it opens or closes. - """ - self._popup = {"data-rx-hover": name} - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the trigger, its script 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 script("hover", "hoverEvent") - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: its child, which opens its popup under the pointer - and with the focus of the keyboard. - """ - tag = UIComponent._render(self, props).add_props(**{ - "data-state": "closed", - **self._popup, - }) - return listen(tag, script("hover", "hoverEvent"), *self._heard) - - -class HoverContent(PopupContent): - """A popup that opens under the pointer and with the focus of the keyboard.""" - - _role: ClassVar[str | None] = None - - _popover: ClassVar[str] = "manual" - - _tab_index: ClassVar[int | None] = None - - _script: ClassVar[tuple[str, ...]] = ( - "hover", - "hoverSync", - "hoverEvent", - "onPointerEnter", - "onPointerLeave", - "onBlur", - ) - - _synced: ClassVar[bool] = True diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py index 25011e407ea..846cc315733 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.py @@ -217,6 +217,10 @@ def on_change(handlers: dict[str, Any], body: str) -> Var | None: ) +# The room Radix Themes keeps between a popup and the edges of the viewport. +COLLISION_PADDING = 10 + + # The events Radix fires on the content of a popup: the reason UI SDK gives # for a change of the popup says which happened. POPUP_EVENTS = ( @@ -327,13 +331,13 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: Returns: The tag, with what it takes from its content. """ + tag = super()._render(props) defaults = { name: value for name, value in self._defaults.items() - if name not in self._from_content - and getattr(self, format.to_snake_case(name), None) is None + if name not in self._from_content and name not in tag.props } - tag = super()._render(props).add_props(**defaults, **self._from_content) + tag = tag.add_props(**defaults, **self._from_content) if self._on_open_change is None: return tag return tag.add_props(onOpenChange=self._on_open_change) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py index 39bc8fac426..ae181e8dd8a 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.py @@ -1,31 +1,37 @@ -"""A context menu: a native ``popover`` of items, at the pointer that asks for it.""" +"""A context menu: the parts of ``@ui-sdk/react/menu``, at the pointer that asks for it. + +UI SDK opens the menu on a right click, a long press, Shift+F10 or the +context-menu key over its area, beside the pointer, and does the rest of +what a dropdown menu does. +""" from __future__ import annotations from typing import Any, ClassVar, Literal -from reflex_base.components.component import Component, ComponentNamespace, field +from reflex_base.components.component import ComponentNamespace, field +from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive from reflex_components_ui.components._menu import ( - MenuArea, + LIBRARY, MenuCheckboxItem, MenuContent, MenuGroup, MenuItem, MenuLabel, + MenuRoot, MenuSeparator, - MenuSub, MenuSubContent, MenuSubTrigger, - at_point, + raised, ) -from reflex_components_ui.components._popup import PopupRoot +from reflex_components_ui.components._sdk import COLLISION_PADDING, SDKPart from reflex_components_ui.components.radio_group import HighLevelRadioGroup from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.menu import CONTEXT_MENU_CONTENT +from reflex_components_ui.styles.menu import MENU_CONTENT from reflex_components_ui.themes import LiteralAccentColor LiteralDirType = Literal["ltr", "rtl"] @@ -48,10 +54,10 @@ LiteralCheckboxVariant = Literal["classic", "surface", "soft"] -class ContextMenuRoot(PopupRoot): +class ContextMenuRoot(MenuRoot): """Menu representing a set of actions, displayed at the origin of a pointer right-click or long-press.""" - _prefix: ClassVar[str] = "rx-context-menu" + tag = "Menu" modal: Var[bool] = field( doc="The modality of the context menu. When set to true, interaction with outside elements will be disabled and only menu content will be visible to screen readers." @@ -66,8 +72,14 @@ class ContextMenuRoot(PopupRoot): ) -class ContextMenuTrigger(MenuArea): - """Wraps the element that will open the context menu.""" +class ContextMenuTrigger(SDKPart): + """Wraps the element that will open the context menu: it is rendered as it.""" + + library = LIBRARY + + tag = "MenuContextTrigger" + + _renders_child: ClassVar[bool] = True disabled: Var[bool] = field(doc="Whether the trigger is disabled") @@ -75,7 +87,17 @@ class ContextMenuTrigger(MenuArea): class ContextMenuContent(MenuContent): """The component that pops out when the context menu is open.""" - styles: ClassVar[ComponentStyles] = CONTEXT_MENU_CONTENT + tag = "MenuContent" + + styles: ClassVar[ComponentStyles] = MENU_CONTENT + + # Where Radix Themes places a context menu: beside the pointer. + _placement: ClassVar[dict[str, Any]] = { + "side": "right", + "align": "start", + "sideOffset": 2, + "collisionPadding": COLLISION_PADDING, + } size: Var[Responsive[LiteralSizeType]] = field( doc='Dropdown Menu Content size "1" - "2"' @@ -157,23 +179,28 @@ class ContextMenuContent(MenuContent): doc="Fired when the pointer interacts outside the context menu." ) - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create a context menu, after the point it opens at. + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the menu, placed as Radix Themes places a context menu. Args: - *children: The items. - **props: The properties of the menu. + props: The props to render (if None, then use get_props). Returns: - The point, then the menu. + The tag, as far up as the padding of the menu where it is given no + offset along the pointer, so that the text of its first item is at + the pointer. """ - return at_point(super().create(*children, **props)) + tag = super()._render(props) + if self.align_offset is not None: + return tag + return tag.add_props(alignOffset=raised(self.size)) -class ContextMenuSub(MenuSub): +class ContextMenuSub(MenuRoot): """Contains all the parts of a submenu.""" + tag = "MenuSub" + open: Var[bool] = field( doc="The controlled open state of the submenu. Must be used in conjunction with `on_open_change`." ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py index 8c5ae370971..87e4173d633 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.py @@ -9,30 +9,23 @@ from typing import Any, ClassVar, Literal -from reflex_base.components.component import Component, ComponentNamespace, field -from reflex_base.components.tags import CommonTag +from reflex_base.components.component import ComponentNamespace, field from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive -from reflex_components_ui.base import Part -from reflex_components_ui.components._group import descendants, literal -from reflex_components_ui.components._sdk import ( - PlacedContent, - PopupRootPart, - SDKPart, - entry, -) -from reflex_components_ui.components.select import ( - _icon, # pyright: ignore[reportAttributeAccessIssue] +from reflex_components_ui.components._menu import ( + LIBRARY, + MenuContent, + MenuItem, + MenuRoot, + MenuSeparator, + MenuSubContent, + MenuSubTrigger, ) +from reflex_components_ui.components._sdk import COLLISION_PADDING, SDKPart from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.menu import ( - MENU_SEPARATOR, - SDK_DROPDOWN_MENU_CONTENT, - SDK_MENU_ITEM, - SDK_MENU_SUB_CONTENT, -) +from reflex_components_ui.styles.menu import MENU_CONTENT from reflex_components_ui.themes import LiteralAccentColor LiteralDirType = Literal["ltr", "rtl"] @@ -50,32 +43,8 @@ "always", ] -_LIBRARY = entry("menu") - -# The chevron of an item that opens a sub-menu, as Radix Themes draws it. -_CHEVRON = ( - "M3.23826 0.201711C3.54108 -0.0809141 4.01567 -0.0645489 4.29829 0.238264" - "L7.79829 3.98826C8.06724 4.27642 8.06724 4.72359 7.79829 5.01174" - "L4.29829 8.76174C4.01567 9.06455 3.54108 9.08092 3.23826 8.79829" - "C2.93545 8.51567 2.91909 8.04108 3.20171 7.73826L6.22409 4.5" - "L3.20171 1.26174C2.91909 0.958928 2.93545 0.484337 3.23826 0.201711Z" -) - -# What Radix Themes gives the content of a menu and of a sub-menu: the room -# beside what opens it and the room it keeps from the edges of the viewport. -_COLLISION_PADDING = 10 - -class MenuRootPart(PopupRootPart): - """A menu or a sub-menu: no element, the root of its parts.""" - - library = _LIBRARY - - # The arrow keys stop at the ends, as in Radix: UI SDK goes round. - _defaults: ClassVar[dict[str, Any]] = {"loop": False} - - -class DropdownMenuRoot(MenuRootPart): +class DropdownMenuRoot(MenuRoot): """The Dropdown Menu Root Component.""" tag = "Menu" @@ -100,20 +69,11 @@ class DropdownMenuRoot(MenuRootPart): doc="Fired when the open state changes." ) - def _exclude_props(self) -> list[str]: - """Keep the direction off the menu, which is no element. - - Returns: - The props read as styles, and ``dir``: UI SDK reads the direction - of the page around the menu. - """ - return [*super()._exclude_props(), "dir"] - class DropdownMenuTrigger(SDKPart): """The button that toggles the dropdown menu.""" - library = _LIBRARY + library = LIBRARY tag = "MenuTrigger" @@ -124,83 +84,7 @@ class DropdownMenuTrigger(SDKPart): ) -class MenuContentPart(PlacedContent): - """The content of a menu or a sub-menu, its items inside what scrolls them.""" - - library = _LIBRARY - - _sdk_names: ClassVar[dict[str, str]] = {"forceMount": "keepMounted"} - - # Whether the arrow keys go round: a prop of the menu in UI SDK. - _root_props: ClassVar[tuple[str, ...]] = ("loop",) - - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create the content, its items inside the element that scrolls them. - - Args: - *children: The items. - **props: The properties of the content. - - Returns: - The content. - """ - return super().create( - Part.create( - Part.create(*children, part="viewport", tag="div"), - part="scroll", - tag="div", - ), - **props, - ) - - def _post_init(self, *args, **kwargs): - """Initialize the content, and give its items its look. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # Whether the menu has checkbox items, which leave room for a check. - self._indented: Any = None - super()._post_init(*args, **kwargs) - self._look: tuple[Any, Any] = ( - getattr(self, "variant", None), - getattr(self, "high_contrast", None), - ) - self._join_items() - - def _join_items(self) -> None: - """Give the items of the menu its look, those of its sub-menus too.""" - for member in descendants( - self, - (MenuItemPart, MenuContentPart), # pyright: ignore[reportArgumentType] - MenuContentPart, - ): - if isinstance(member, DropdownMenuSubContent): - member._inherit(self) - else: - member._join(self) - self._indented = False - self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - - def _exclude_props(self) -> list[str]: - """Keep the props UI SDK has no use for off the content. - - Returns: - The props read as styles, and those of the placement of Radix that - UI SDK does not have: it always keeps a menu in the viewport. - """ - return [ - *super()._exclude_props(), - "as_child", - "avoid_collisions", - "sticky", - "hide_when_detached", - ] - - -class DropdownMenuContent(MenuContentPart): +class DropdownMenuContent(MenuContent): """The Dropdown Menu Content component that pops out when the dropdown menu is open.""" tag = "MenuContent" @@ -210,10 +94,10 @@ class DropdownMenuContent(MenuContentPart): "side": "bottom", "align": "start", "sideOffset": 4, - "collisionPadding": _COLLISION_PADDING, + "collisionPadding": COLLISION_PADDING, } - styles: ClassVar[ComponentStyles] = SDK_DROPDOWN_MENU_CONTENT + styles: ClassVar[ComponentStyles] = MENU_CONTENT size: Var[Responsive[LiteralSizeType]] = field( doc='Dropdown Menu Content size "1" - "2"' @@ -296,40 +180,9 @@ class DropdownMenuContent(MenuContentPart): ) -class MenuItemPart(SDKPart): - """An item of a menu, which its menu gives its look.""" - - library = _LIBRARY - - styles: ClassVar[ComponentStyles] = SDK_MENU_ITEM - - def _post_init(self, *args, **kwargs): - """Initialize the item, as one outside a menu. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - # The look of the menu the item is in, which Radix hands down. - self._variant: Any = None - self._contrast: Any = None - super()._post_init(*args, **kwargs) - - def _join(self, menu: MenuContentPart) -> None: - """Take the look of the menu the item is in. - - Args: - menu: The content of the menu. - """ - self._variant, self._contrast = menu._look - self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - - -class DropdownMenuSubTrigger(MenuItemPart): +class DropdownMenuSubTrigger(MenuSubTrigger): """An item that opens a submenu.""" - tag = "MenuSubTrigger" - as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." ) @@ -342,33 +195,8 @@ class DropdownMenuSubTrigger(MenuItemPart): doc="Optional text used for typeahead purposes. By default the typeahead behavior will use the .textContent of the item. Use this when the content is complex, or you have non-textual content inside." ) - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create the item, with the chevron that says it opens a sub-menu. - - Args: - *children: What the item shows. - **props: The properties of the item. - - Returns: - The item. - """ - return super().create( - *children, - Part.create(_icon("chevron", _CHEVRON), part="shortcut", tag="div"), - **props, - ) - def _exclude_props(self) -> list[str]: - """Keep the props UI SDK has no use for off the item. - - Returns: - The props read as styles, ``as_child`` and ``text_value``. - """ - return [*super()._exclude_props(), "as_child", "text_value"] - - -class DropdownMenuSub(MenuRootPart): +class DropdownMenuSub(MenuRoot): """Contains all the parts of a submenu.""" tag = "MenuSub" @@ -386,19 +214,9 @@ class DropdownMenuSub(MenuRootPart): ) -class DropdownMenuSubContent(MenuContentPart): +class DropdownMenuSubContent(MenuSubContent): """The component that pops out when a submenu is open. Must be rendered inside DropdownMenuSub.""" - tag = "MenuSubContent" - - # Where Radix Themes places a sub-menu. - _placement: ClassVar[dict[str, Any]] = { - "sideOffset": 1, - "collisionPadding": _COLLISION_PADDING, - } - - styles: ClassVar[ComponentStyles] = SDK_MENU_SUB_CONTENT - as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False." ) @@ -451,41 +269,10 @@ class DropdownMenuSubContent(MenuContentPart): doc="Fired when the pointer interacts outside the dialog." ) - def _inherit(self, menu: MenuContentPart) -> None: - """Take the look of the menu the sub-menu opens from, as in Radix. - - Args: - menu: The content of that menu. - """ - self._look = menu._look - self.size = getattr(menu, "size", None) - self._join_items() - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the content, placed as Radix Themes places a sub-menu. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag: as far up as the padding of the menu, where it is given - no offset along its trigger, so that the text of its first item - is level with the item it opens from. - """ - tag = super()._render(props) - if self.align_offset is not None: - return tag - size = literal(getattr(self, "size", None)) - return tag.add_props(alignOffset=-4 * int(size if size in ("1", "2") else 2)) - -class DropdownMenuItem(MenuItemPart): +class DropdownMenuItem(MenuItem): """The Dropdown Menu Item Component.""" - tag = "MenuItem" - - _sdk_names: ClassVar[dict[str, str]] = {"textValue": "label"} - color_scheme: Var[LiteralAccentColor] = field( doc="Override theme color for Dropdown Menu Item" ) @@ -508,44 +295,10 @@ class DropdownMenuItem(MenuItemPart): doc="Fired when the item is selected." ) - @classmethod - def create(cls, *children: Any, **props: Any) -> Component: - """Create an item, with its shortcut after what it shows. - - Args: - *children: What the item shows. - **props: The properties of the item. - - Returns: - The item. - """ - shortcut = props.get("shortcut") - after = ( - [] - if shortcut is None - else [Part.create(shortcut, part="shortcut", tag="div")] - ) - return super().create(*children, *after, **props) - - def _exclude_props(self) -> list[str]: - """Keep the props UI SDK has no use for off the item. - Returns: - The props read as styles, ``as_child`` and the shortcut, which is - shown: a shortcut of UI SDK is a key it binds. - """ - return [*super()._exclude_props(), "as_child", "shortcut"] - - -class DropdownMenuSeparator(SDKPart): +class DropdownMenuSeparator(MenuSeparator): """Dropdown Menu Separator Component. Used to visually separate items in the dropdown menu.""" - library = _LIBRARY - - tag = "MenuSeparator" - - styles: ClassVar[ComponentStyles] = MENU_SEPARATOR - class DropdownMenu(ComponentNamespace): """DropdownMenu components namespace.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py b/packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py index 76ef20f8e71..e29f91bb4d9 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.py @@ -1,4 +1,9 @@ -"""A hover card: a native ``popover`` that opens under the pointer and with the focus.""" +"""A hover card: the parts of ``@ui-sdk/react/hover-card``, in the look of Radix Themes. + +UI SDK opens the card when the pointer rests on its trigger or the focus +reaches it, keeps it open while the pointer is on its way to the card, and +places it beside the trigger. +""" from __future__ import annotations @@ -10,7 +15,13 @@ from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.el import elements -from reflex_components_ui.components._popup import HoverContent, HoverTrigger, PopupRoot +from reflex_components_ui.components._sdk import ( + COLLISION_PADDING, + PlacedContent, + PopupRootPart, + SDKPart, + entry, +) from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.hover_card import HOVER_CARD_CONTENT @@ -20,11 +31,22 @@ _OPEN_DELAY = 200 _CLOSE_DELAY = 150 +_LIBRARY = entry("hover-card") + -class HoverCardRoot(PopupRoot): +class HoverCardRoot(PopupRootPart): """For sighted users to preview content available behind a link.""" - _prefix: ClassVar[str] = "rx-hover-card" + library = _LIBRARY + + tag = "HoverCard" + + _sdk_names: ClassVar[dict[str, str]] = {"openDelay": "delay"} + + _defaults: ClassVar[dict[str, Any]] = { + "delay": _OPEN_DELAY, + "closeDelay": _CLOSE_DELAY, + } default_open: Var[bool] = field( doc="The open state of the hover card when it is initially rendered. Use when you do not need to control its open state." @@ -47,15 +69,33 @@ class HoverCardRoot(PopupRoot): ) -class HoverCardTrigger(HoverTrigger): - """Wraps the link that will open the hover card.""" +class HoverCardTrigger(SDKPart): + """Wraps the link that will open the hover card: it is rendered as it.""" + + library = _LIBRARY + tag = "HoverCardTrigger" -class HoverCardContent(HoverContent, elements.Div): + _renders_child: ClassVar[bool] = True + + +class HoverCardContent(PlacedContent, elements.Div): """Contains the content of the open hover card.""" + library = _LIBRARY + + tag = "HoverCardContent" + styles: ClassVar[ComponentStyles] = HOVER_CARD_CONTENT + # Where Radix Themes places a hover card. + _placement: ClassVar[dict[str, Any]] = { + "side": "bottom", + "align": "start", + "sideOffset": 8, + "collisionPadding": COLLISION_PADDING, + } + side: Var[Responsive[Literal["top", "right", "bottom", "left"]]] = field( doc="The preferred side of the trigger to render against when open. Will be reversed when collisions occur and avoidCollisions is enabled." ) @@ -90,21 +130,19 @@ class HoverCardContent(HoverContent, elements.Div): doc='Hovercard size "1" - "3"' ) - def _join(self, root: PopupRoot, name: Any, on_open_change: Any) -> None: - """Take the name of the card, whether it is open, and its delays. + def _exclude_props(self) -> list[str]: + """Keep the props of the placement of Radix that UI SDK does not have off. - Args: - root: The hover card the content is in. - name: The id of the card. - on_open_change: What the card does when it opens or closes. + Returns: + The props read as styles, and those UI SDK does without: it always + keeps a card in the viewport. """ - super()._join(root, name, on_open_change) # pyright: ignore[reportAttributeAccessIssue] - for attribute, prop, default in ( - ("data-open-delay", "open_delay", _OPEN_DELAY), - ("data-close-delay", "close_delay", _CLOSE_DELAY), - ): - delay = getattr(root, prop, None) - self._popup[attribute] = default if delay is None else delay # pyright: ignore[reportAttributeAccessIssue] + return [ + *super()._exclude_props(), + "avoid_collisions", + "sticky", + "hide_when_detached", + ] class HoverCard(ComponentNamespace): diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py b/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py index 5d3d3a136e0..c6b9d6c30bf 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/popover.py @@ -22,7 +22,7 @@ entry, ) from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.popover import SDK_POPOVER_CONTENT +from reflex_components_ui.styles.popover import POPOVER_CONTENT _LIBRARY = entry("popover") @@ -66,7 +66,7 @@ class PopoverContent(PlacedContent, elements.Div): tag = "PopoverContent" - styles: ClassVar[ComponentStyles] = SDK_POPOVER_CONTENT + styles: ClassVar[ComponentStyles] = POPOVER_CONTENT # Where Radix Themes places a popover. _placement: ClassVar[dict[str, Any]] = { diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py index 767dfb33b09..214d540a285 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.py @@ -1,4 +1,9 @@ -"""A tooltip: a native ``popover`` that opens under the pointer and with the focus.""" +"""A tooltip: the parts of ``@ui-sdk/react/tooltip``, in the look of Radix Themes. + +UI SDK opens the tooltip when the pointer rests on what it describes or the +focus reaches it, closes it on a press, on Escape and when the pointer or +the focus leaves, and places it beside what it describes. +""" from __future__ import annotations @@ -8,14 +13,18 @@ from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex_base.vars.base import Var -from reflex_components_core.base.fragment import Fragment from reflex_components_ui.base import Part -from reflex_components_ui.components import _popup from reflex_components_ui.components._group import choose, literal -from reflex_components_ui.components._popup import HoverContent, HoverTrigger +from reflex_components_ui.components._sdk import ( + COLLISION_PADDING, + PlacedContent, + PopupRootPart, + SDKPart, + entry, +) from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.tooltip import ARROW, TOOLTIP +from reflex_components_ui.styles.tooltip import ARROW, OFFSET_DEFAULT, TOOLTIP LiteralSideType = Literal[ "top", @@ -43,43 +52,109 @@ _OPEN_DELAY = 200 _CLOSE_DELAY = 100 +_LIBRARY = entry("tooltip") -class TooltipTrigger(HoverTrigger): - """What a tooltip describes: the child of the tooltip.""" +# The props of rx.ui.tooltip that its root takes: whether it is open, and when. +_ROOT_PROPS = ( + "open", + "default_open", + "on_open_change", + "delay_duration", + "disable_hoverable_content", +) - # Created by rx.ui.tooltip from its child, which its errors are about. - _named_as: ClassVar[str | None] = "tooltip" - # A press on what a tooltip is on closes the tooltip. - _heard: ClassVar[tuple[str, ...]] = (*HoverTrigger._heard, "onPointerDown") # pyright: ignore[reportAttributeAccessIssue] +class TooltipRoot(PopupRootPart): + """A tooltip: no element, what it describes and its popup.""" + + library = _LIBRARY + + tag = "Tooltip" + + _sdk_names: ClassVar[dict[str, str]] = {"delayDuration": "delay"} + + # The tooltip describes what it is on, as in Radix: UI SDK names what has + # no name of its own. + _defaults: ClassVar[dict[str, Any]] = { + "delay": _OPEN_DELAY, + "type": "description", + } + + default_open: Var[bool] = field(doc="Whether the tooltip is open at first.") + + open: Var[bool] = field(doc="Whether the tooltip is open.") + + delay_duration: Var[float | int] = field( + doc="How long the pointer rests on the trigger before the tooltip opens." + ) + + disable_hoverable_content: Var[bool] = field( + doc="Whether the tooltip closes as soon as the pointer leaves the trigger." + ) + + on_open_change: EventHandler[passthrough_event_spec(bool)] = field( + doc="Fired when the open state changes." + ) + + def _exclude_props(self) -> list[str]: + """Keep what the root turns into a delay off it. + + Returns: + The props read as styles, and ``disable_hoverable_content``. + """ + return [*super()._exclude_props(), "disable_hoverable_content"] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the trigger. + """Render the root, which waits for the pointer to reach the tooltip. Args: props: The props to render (if None, then use get_props). Returns: - The tag: the child, which its tooltip describes whether it is - shown or not. + The tag, with how long the tooltip waits before it closes: not at + all when the pointer cannot rest on it. """ + still = self.disable_hoverable_content return ( super() ._render(props) - .add_props(**{"aria-describedby": self._popup.get("data-rx-hover")}) # pyright: ignore[reportAttributeAccessIssue] + .add_props( + closeDelay=_CLOSE_DELAY + if still is None + else choose(literal(still), 0, _CLOSE_DELAY) + ) ) -class Tooltip(HoverContent): +class TooltipTrigger(SDKPart): + """What a tooltip describes: the child of the tooltip, rendered as it.""" + + library = _LIBRARY + + tag = "TooltipTrigger" + + _renders_child: ClassVar[bool] = True + + # Created by rx.ui.tooltip from its child, which its errors are about. + _named_as: ClassVar[str | None] = "tooltip" + + +class Tooltip(PlacedContent): """Floating element that provides a control with contextual information via pointer or focus.""" - styles: ClassVar[ComponentStyles] = TOOLTIP + library = _LIBRARY - _role: ClassVar[str | None] = "tooltip" + tag = "TooltipContent" - # A tooltip is as far from what it describes as the one of Radix, which - # has an arrow between the two. - _gap: ClassVar[int] = ARROW + styles: ClassVar[ComponentStyles] = TOOLTIP + + # Where Radix Themes places a tooltip: as far from what it describes as + # its arrow, which this one does not draw, takes it. + _placement: ClassVar[dict[str, Any]] = { + "side": "top", + "align": "center", + "collisionPadding": COLLISION_PADDING, + } content: Var[str] = field(doc="The content of the tooltip.") @@ -162,60 +237,65 @@ def create(cls, *children, **props) -> Component: Run some additional handling on the props. Args: - *children: The positional arguments + *children: What the tooltip describes: one element. **props: The keyword arguments Returns: - The created component: what the tooltip describes, then the - tooltip, a popup that holds its text. + The tooltip: its root, around what it describes and its popup, + which holds its text. """ label = props.pop(ARIA_LABEL_KEY, None) if label is not None: props.setdefault("custom_attrs", {})["aria-label"] = label + root = {name: props.pop(name) for name in _ROOT_PROPS if name in props} + if "disable_hoverable_content" in root: + props["disable_hoverable_content"] = root["disable_hoverable_content"] popup = super().create( Part.create(props.get("content"), part="text", tag="p"), **props ) - trigger = TooltipTrigger.create(*children) - name = popup.id if popup.id is not None else f"rx-tooltip-{next(_popup._ids)}" - popup._join(None, name, None) # pyright: ignore[reportAttributeAccessIssue] - trigger._join(None, name, None) # pyright: ignore[reportAttributeAccessIssue] - return Fragment.create(trigger, popup) + return TooltipRoot.create(TooltipTrigger.create(*children), popup, **root) - def _join(self, root: Any, name: Any, on_open_change: Any) -> None: - """Take the name of the tooltip, and what its script reads. + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the popup, as far from what it describes as the one of Radix. Args: - root: Nothing: a tooltip has no root. - name: The id of the tooltip. - on_open_change: Nothing: the tooltip has the event itself. + props: The props to render (if None, then use get_props). + + Returns: + The tag, its offset from what it describes widened by the arrow of + Radix Themes. """ - if self.id is None: - self._popup["id"] = name # pyright: ignore[reportAttributeAccessIssue] - self._open = self.open - if self.default_open is not None: - self._popup["data-default-open"] = self.default_open # pyright: ignore[reportAttributeAccessIssue] - delay = self.delay_duration - self._popup["data-open-delay"] = _OPEN_DELAY if delay is None else delay # pyright: ignore[reportAttributeAccessIssue] - still = self.disable_hoverable_content - self._popup["data-close-delay"] = ( # pyright: ignore[reportAttributeAccessIssue] - _CLOSE_DELAY if still is None else choose(literal(still), 0, _CLOSE_DELAY) - ) + offset = self.side_offset + if offset is None: + gap: Any = OFFSET_DEFAULT + ARROW + elif isinstance(known := literal(offset), Var): + gap = Var( + f"({known!s} + {ARROW})", + _var_type=float, + _var_data=known._get_all_var_data(), + ) + else: + gap = known + ARROW + return super()._render(props).add_props(sideOffset=gap) def _exclude_props(self) -> list[str]: """Keep the props that are no attributes off the element. Returns: The props read as styles, and what the tooltip hands its text - and its script. + and its root, or UI SDK does without. """ return [ *super()._exclude_props(), "content", - "default_open", - "open", + "side_offset", "arrow_padding", - "delay_duration", + "force_mount", + "avoid_collisions", + "sticky", + "hide_when_detached", "aria_label", + *_ROOT_PROPS, ] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py index 93a53f08e74..8b63f03a37f 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/dialog.py @@ -1,4 +1,4 @@ -"""The look of a dialog: a native ``dialog`` over the page, and the panel in it.""" +"""The look of a dialog: an overlay over the page, and the panel over it.""" from __future__ import annotations @@ -7,79 +7,19 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, unchecked from reflex_components_ui.styles.heading import HEADING +from reflex_components_ui.styles.popup import ENDING from reflex_components_ui.styles.text import TEXT _PADDING = "--dialog-content-padding" MOTION = "@media (prefers-reduced-motion: no-preference)" -OPEN = "[open]" _EASING = "cubic-bezier(0.16, 1, 0.3, 1)" -# What a dialog hands its panel, which comes in when the dialog opens and -# goes out before it closes: where it goes, and how long it takes. -SHOWN = "--rx-dialog-shown" -GONE = "--rx-dialog-gone" -DURATION = "--rx-dialog-duration" - -# The element around the parts of a dialog, which is nothing to the layout. -DIALOG_ROOT: ComponentStyles = {"base": {"display": "contents"}} - -# What a `dialog` is before a table draws it: nothing of the box the browser -# gives one. It stays in the top layer until what is inside has gone out. -SURFACE: dict[str, Any] = { - "margin": "0", - "padding": "0", - "border_width": "0", - "border_style": "none", - "background_color": "transparent", - "color": "inherit", - "max_width": "none", - "max_height": "none", - "outline_style": "none", - # Not the selection the browser gives the text of a modal dialog. - "user_select": "auto", - "::backdrop": {"background_color": "transparent"}, - "transition_property": "display, overlay", - "transition_duration": {"default": "0s", MOTION: f"var({DURATION})"}, - SHOWN: {"default": 0, OPEN: 1}, -} - -# The dialog itself covers the page, and scrolls a panel taller than it. -DIALOG: ComponentStyles = { - "base": unchecked({ - **SURFACE, - "position": "fixed", - "inset": "0", - "width": "100%", - "height": "100%", - "display": {"default": "none", OPEN: "flex"}, - "overflow": "auto", - GONE: {"default": "translateY(5px) scale(0.99)", OPEN: "none"}, - DURATION: {"default": "160ms", OPEN: "200ms"}, - "_before": { - "position": "fixed", - "content": "''", - "inset": "0", - "background_color": tokens.color.overlay, - "opacity": {"default": 0, OPEN: {"default": 1, "@starting-style": 0}}, - "transition_property": "opacity", - "transition_duration": {"default": "0s", MOTION: f"var({DURATION})"}, - "transition_timing_function": _EASING, - }, - }), - "parts": { - "pad": { - "base": { - "flex_grow": 1, - "margin": "auto", - "padding_top": tokens.space[6], - "padding_bottom": f"max({tokens.space[6]}, 6vh)", - "padding_left": tokens.space[4], - "padding_right": tokens.space[4], - }, - }, - }, -} +# The room a dialog leaves around its panel, as the padding of the overlay of +# Radix Themes around it. +_ROOM_TOP = tokens.space[6] +_ROOM_BOTTOM = f"max({tokens.space[6]}, 6vh)" +_ROOM_SIDE = tokens.space[4] def _size(padding: str, radius: str) -> dict[str, Any]: @@ -95,13 +35,29 @@ def _size(padding: str, radius: str) -> dict[str, Any]: return {_PADDING: padding, "border_radius": radius} +# What is drawn over the page behind a dialog. +DIALOG_BACKDROP: ComponentStyles = { + "base": unchecked({ + "position": "fixed", + "inset": "0", + "background_color": tokens.color.overlay, + "opacity": {"default": 1, "@starting-style": 0, ENDING: 0}, + "transition_property": "opacity", + "transition_duration": { + "default": "0s", + MOTION: {"default": "200ms", ENDING: "160ms"}, + }, + "transition_timing_function": _EASING, + }), +} + +# The panel of a dialog: a popover in the top layer, in the middle of the +# room the overlay of Radix Themes leaves. A panel taller than that room +# scrolls. DIALOG_CONTENT: ComponentStyles = { "base": unchecked({ "margin": "auto", - "width": "100%", "max_width": "600px", - "z_index": 1, - "position": "relative", "box_sizing": "border-box", "overflow": "auto", "--inset-padding-top": f"var({_PADDING})", @@ -112,20 +68,32 @@ def _size(padding: str, radius: str) -> dict[str, Any]: "background_color": tokens.color.panel_solid, "box_shadow": tokens.shadow[6], "outline_style": "none", - "opacity": { - "default": f"var({SHOWN})", - "@starting-style": 0, - }, - "transform": { - "default": f"var({GONE})", - "@starting-style": "translateY(5px) scale(0.97)", - }, "transition_property": "opacity, transform", "transition_duration": { "default": "0s", - MOTION: f"calc(100ms + var({SHOWN}) * 100ms)", + MOTION: {"default": "200ms", ENDING: "100ms"}, }, "transition_timing_function": _EASING, + "position": "fixed", + "top": _ROOM_TOP, + "bottom": _ROOM_BOTTOM, + "left": "0", + "right": "0", + "width": f"calc(100% - {_ROOM_SIDE} * 2)", + "height": "fit-content", + "max_height": f"calc(100% - {_ROOM_TOP} - {_ROOM_BOTTOM})", + # No border, of the style of the panel of Radix Themes. + "border_width": "0", + "border_style": "solid", + "color": "inherit", + "user_select": "auto", + "::backdrop": {"background_color": "transparent"}, + "opacity": {"default": 1, "@starting-style": 0, ENDING: 0}, + "transform": { + "default": "none", + "@starting-style": "translateY(5px) scale(0.97)", + ENDING: "translateY(5px) scale(0.99)", + }, }), "variants": { "size": { @@ -147,67 +115,3 @@ def _size(padding: str, radius: str) -> dict[str, Any]: } DIALOG_DESCRIPTION: ComponentStyles = {**TEXT, "defaults": {"size": "3"}} - -# What UI SDK's parts of a dialog have while they go out: UI SDK keeps them -# in the page until their transitions end. -_SDK_ENDING = "[data-ending-style]" - -# The room a dialog of UI SDK leaves around its panel, as the padding of the -# overlay of Radix Themes around it. -_ROOM_TOP = tokens.space[6] -_ROOM_BOTTOM = f"max({tokens.space[6]}, 6vh)" -_ROOM_SIDE = tokens.space[4] - -# What is drawn over the page behind a dialog of UI SDK. -SDK_DIALOG_BACKDROP: ComponentStyles = { - "base": unchecked({ - "position": "fixed", - "inset": "0", - "background_color": tokens.color.overlay, - "opacity": {"default": 1, "@starting-style": 0, _SDK_ENDING: 0}, - "transition_property": "opacity", - "transition_duration": { - "default": "0s", - MOTION: {"default": "200ms", _SDK_ENDING: "160ms"}, - }, - "transition_timing_function": _EASING, - }), -} - -# The panel of a dialog of UI SDK, its content: a popover in the top layer, -# in the middle of the room the overlay of Radix Themes leaves. A panel -# taller than that room scrolls. -SDK_DIALOG_CONTENT: ComponentStyles = { - **DIALOG_CONTENT, - "base": unchecked({ - **{ - key: value - for key, value in DIALOG_CONTENT["base"].items() - if key not in ("width", "z_index", "position", "opacity", "transform") - }, - "position": "fixed", - "top": _ROOM_TOP, - "bottom": _ROOM_BOTTOM, - "left": "0", - "right": "0", - "width": f"calc(100% - {_ROOM_SIDE} * 2)", - "height": "fit-content", - "max_height": f"calc(100% - {_ROOM_TOP} - {_ROOM_BOTTOM})", - # No border, of the style of the panel of Radix Themes. - "border_width": "0", - "border_style": "solid", - "color": "inherit", - "user_select": "auto", - "::backdrop": {"background_color": "transparent"}, - "opacity": {"default": 1, "@starting-style": 0, _SDK_ENDING: 0}, - "transform": { - "default": "none", - "@starting-style": "translateY(5px) scale(0.97)", - _SDK_ENDING: "translateY(5px) scale(0.99)", - }, - "transition_duration": { - "default": "0s", - MOTION: {"default": "200ms", _SDK_ENDING: "100ms"}, - }, - }), -} diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py index 3146984b37b..d4b8cb71c46 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/hover_card.py @@ -6,7 +6,7 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, unchecked -from reflex_components_ui.styles.popup import POPUP, placements +from reflex_components_ui.styles.popup import POPUP, placed _PADDING = "--hover-card-content-padding" @@ -24,10 +24,10 @@ def _size(padding: str, radius: str) -> dict[str, Any]: return {_PADDING: padding, "border_radius": radius} -HOVER_CARD_CONTENT: ComponentStyles = { +# A hover card, which UI SDK places beside its trigger. +HOVER_CARD_CONTENT: ComponentStyles = placed({ "base": unchecked({ **POPUP, - # The text of the page around it, not the one of a native popover. "color": "inherit", "background_color": tokens.color.panel_solid, "box_shadow": tokens.shadow[4], @@ -48,6 +48,5 @@ def _size(padding: str, radius: str) -> dict[str, Any]: "3": unchecked(_size(tokens.space[5], tokens.radius[5])), }, }, - "defaults": {"size": "2", "side": "bottom", "align": "start"}, - "compound": placements("8px"), -} + "defaults": {"size": "2"}, +}) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py index e715c409442..c2506d05665 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/menu.py @@ -6,13 +6,7 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked -from reflex_components_ui.styles.popup import ( - POPUP, - placed, - placement, - placements, - sdk_popup, -) +from reflex_components_ui.styles.popup import POPUP, placed from reflex_components_ui.tokens import Step9 # What the content of a menu hands its items, as Radix Themes names them. @@ -32,9 +26,6 @@ _CHEVRON = "--rx-menu-chevron-color" _CHECK = "--rx-menu-check" -# An item the focus is on is the one Radix highlights: the pointer moves the -# focus to the item under it. -HIGHLIGHTED = ":focus" _DISABLED = "[aria-disabled='true']" # A label right after an item. _AFTER_ITEM = ":is(:is([role=menuitem], [role=menuitemcheckbox]) + *)" @@ -132,13 +123,6 @@ def _size( "outline_style": "none", } -# As far up as the padding of an item, for its text to be at the pointer or -# at the item it opens from. -_RAISED = { - size: unchecked({**style, "--rx-popup-shift": f"-{4 * int(size)}px"}) - for size, style in _SIZES.items() -} - def _content( base: dict[str, Any], @@ -201,26 +185,10 @@ def _content( } -DROPDOWN_MENU_CONTENT = _content( - _CONTENT_BASE, _SIZES, {"side": "bottom", "align": "start"}, placements("4px") -) - -CONTEXT_MENU_CONTENT = _content( - _CONTENT_BASE, _RAISED, {"side": "right", "align": "start"}, placements("2px") -) - -MENU_SUB_CONTENT = _content( - {**_CONTENT_BASE, **placement("right", "start", "1px")}, _RAISED, {}, [] -) - - -# The content of a menu of UI SDK, which places it: no taller than the room -# it measures, which it says in `--available-height`. -_SDK_CONTENT_BASE = sdk_popup(_CONTENT_BASE) - -SDK_DROPDOWN_MENU_CONTENT = placed(_content(_SDK_CONTENT_BASE, _SIZES, {}, [])) +# A dropdown menu and a context menu, which UI SDK places, and a sub-menu. +MENU_CONTENT = placed(_content(_CONTENT_BASE, _SIZES, {}, [])) -SDK_MENU_SUB_CONTENT = _content(_SDK_CONTENT_BASE, _RAISED, {}, []) +MENU_SUB_CONTENT = _content(_CONTENT_BASE, _SIZES, {}, []) def _item(highlighted: str, open_: str) -> ComponentStyles: @@ -372,10 +340,8 @@ def _item(highlighted: str, open_: str) -> ComponentStyles: } -# The items of the menus whose script moves the focus, and those of UI SDK, -# which highlights an item, the one the focus is on or under the pointer. -MENU_ITEM = _item(HIGHLIGHTED, "[data-state='open']") -SDK_MENU_ITEM = _item("[data-highlighted]", "[data-open]") +# An item UI SDK highlights: the one the focus is on, or under the pointer. +MENU_ITEM = _item("[data-highlighted]", "[data-open]") MENU_LABEL: ComponentStyles = { diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py index 28a71c1bed9..75736cbe00b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popover.py @@ -6,7 +6,7 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, unchecked -from reflex_components_ui.styles.popup import POPUP, placed, placements, sdk_popup +from reflex_components_ui.styles.popup import POPUP, placed _PADDING = "--popover-content-padding" @@ -24,15 +24,15 @@ def _size(padding: str, radius: str) -> dict[str, Any]: return {_PADDING: padding, "border_radius": radius} -POPOVER_CONTENT: ComponentStyles = { +# A popover, which UI SDK places beside its trigger. +POPOVER_CONTENT: ComponentStyles = placed({ "base": unchecked({ **POPUP, - # The text of the page around it, not the one of a native popover. "color": "inherit", "background_color": tokens.color.panel_solid, "box_shadow": tokens.shadow[5], # At least as wide as what opens it, and no wider than the page. - "min_width": "anchor-size(width)", + "min_width": "var(--anchor-width)", "max_width": "min(480px, calc(100vw - 20px))", "outline_style": "none", "outline_width": "0", @@ -52,16 +52,5 @@ def _size(padding: str, radius: str) -> dict[str, Any]: "4": unchecked(_size(tokens.space[6], tokens.radius[5])), }, }, - "defaults": {"size": "2", "side": "bottom", "align": "start"}, - "compound": placements("8px"), -} - -# A popover of UI SDK, which places it: at least as wide as its trigger. -SDK_POPOVER_CONTENT: ComponentStyles = placed({ - "base": unchecked({ - **sdk_popup(POPOVER_CONTENT["base"]), - "min_width": "var(--anchor-width)", - }), - "variants": POPOVER_CONTENT["variants"], "defaults": {"size": "2"}, }) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py index 2f23186172a..0bbf3f2411c 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/popup.py @@ -1,46 +1,19 @@ -"""The look of a popup: a native popover, placed beside what opens it.""" +"""The look of a popup of UI SDK, which places it beside what opens it.""" from __future__ import annotations -from collections.abc import Mapping from typing import Any -from reflex_components_ui.style import ComponentStyles, CompoundStyle, unchecked +from reflex_components_ui.style import ComponentStyles -# A popup that is open, and the element that opens it: the one before it, or -# a trigger of UI SDK, which says it has opened its popup. -OPEN = ":popover-open" -OPENS = ":is([data-state='open'], [data-open], :has(+ :popover-open))" +# The element that opens a popup, which says it has opened it. +OPENS = ":is([data-state='open'], [data-open])" # How far a popup stays from the edge of the viewport, as in Radix. _EDGE = "10px" -# Where a popup goes for each side of its anchor and each alignment along -# that side: the part of the page the browser lays it out in. -_AREAS = { - ("bottom", "start"): "bottom span-right", - ("bottom", "center"): "bottom span-all", - ("bottom", "end"): "bottom span-left", - ("top", "start"): "top span-right", - ("top", "center"): "top span-all", - ("top", "end"): "top span-left", - ("left", "start"): "left span-bottom", - ("left", "center"): "left span-all", - ("left", "end"): "left span-top", - ("right", "start"): "right span-bottom", - ("right", "center"): "right span-all", - ("right", "end"): "right span-top", -} - -# What a table sets on a popup: how far it is from its anchor, how far -# along it, and where it comes from when it opens. -OFFSET = "--rx-popup-offset" -SHIFT = "--rx-popup-shift" +# Where a popup comes from when it opens, as in Radix Themes. _FROM = "--rx-popup-from" -# What the script of a popup sets on it once it is open: how far it is from -# whole pixels, across and down. Radix puts what it places on whole pixels. -_SNAP_X = "var(--rx-popup-snap-x, 0px)" -_SNAP_Y = "var(--rx-popup-snap-y, 0px)" _MOTION = "@media (prefers-reduced-motion: no-preference)" @@ -51,10 +24,15 @@ "left": "translateX(4px) scale(0.97)", "right": "translateX(-4px) scale(0.97)", } -_OPPOSITE = {"bottom": "top", "top": "bottom", "left": "right", "right": "left"} -# What a popover is before a table draws it: nothing of the box the browser -# gives one, and placed by its anchor instead of in the middle of the page. +# What a popup of UI SDK has while it goes out: UI SDK keeps it open and in +# the page until its transitions end. +ENDING = "[data-ending-style]" + +# A popup before a table draws it: nothing of the box the browser gives a +# popover, placed where UI SDK puts it, no taller than the room it measures. +# UI SDK says the side the popup ended up on and the point of its anchor it +# opens from: the popup comes in from that side, and goes out the way it came. POPUP: dict[str, Any] = { "position": "fixed", "inset": "auto", @@ -66,164 +44,24 @@ "width": "max-content", "height": "auto", "max_width": f"calc(100vw - {_EDGE} * 2)", - # It turns over where it would leave the viewport. - "position_try_fallbacks": "flip-block, flip-inline", - # It comes in when it opens, and goes out before it leaves the top - # layer, for whoever has not asked for less motion. - "opacity": {"default": 0, OPEN: {"default": 1, "@starting-style": 0}}, - "transform": { - "default": f"var({_FROM})", - OPEN: {"default": "none", "@starting-style": f"var({_FROM})"}, - }, - "transition_property": "opacity, transform, display, overlay", - "transition_duration": { - "default": "0s", - _MOTION: {"default": "100ms", OPEN: "160ms"}, - }, - "transition_timing_function": "cubic-bezier(0.16, 1, 0.3, 1)", -} - - -def placement(side: str, align: str, default_offset: str = "0px") -> dict[str, Any]: - """Make the styles that place a popup beside its anchor. - - Args: - side: The side of the anchor the popup is on. - align: Where along that side: at its start, its center or its end. - default_offset: How far from the anchor, for a popup that does not say. - - Returns: - The styles: the popup is no taller, or no wider, than the room the - viewport leaves on that side. - """ - vertical = side in ("top", "bottom") - offset = f"var({OFFSET}, {default_offset})" - shift = f"var({SHIFT}, 0px)" - # The room between the popup and each side: the offset on the side that - # faces the anchor, the room Radix keeps from the edge of the viewport on - # the side opposite it, where the popup turns over only when it would - # come closer, and the shift on the side the popup is aligned to. A - # margin and the one opposite it move the popup together, by what its - # script found it off whole pixels. - across = { - "start": (f"calc({shift} + {_SNAP_X})", f"calc(0px - {_SNAP_X})"), - "center": (_SNAP_X, f"calc(0px - {_SNAP_X})"), - "end": (_SNAP_X, f"calc({shift} - {_SNAP_X})"), - } - down = { - "start": (f"calc({shift} + {_SNAP_Y})", f"calc(0px - {_SNAP_Y})"), - "center": (_SNAP_Y, f"calc(0px - {_SNAP_Y})"), - "end": (_SNAP_Y, f"calc({shift} - {_SNAP_Y})"), - } - before, after = (offset, _EDGE) if side in ("bottom", "right") else (_EDGE, offset) - if vertical: - left, right = across[align] - top, bottom = f"calc({before} + {_SNAP_Y})", f"calc({after} - {_SNAP_Y})" - else: - top, bottom = down[align] - left, right = f"calc({before} + {_SNAP_X})", f"calc({after} - {_SNAP_X})" - start, end = ("left", "right") if vertical else ("top", "bottom") - style: dict[str, Any] = { - "position_area": _AREAS[side, align], - "margin_top": top, - "margin_right": right, - "margin_bottom": bottom, - "margin_left": left, - ("max_height" if vertical else "max_width"): ( - f"calc(100% - {offset} - {_EDGE})" - ), - _FROM: _ENTRY[side], - "transform_origin": ( - f"{_OPPOSITE[side]} " - f"{'center' if align == 'center' else start if align == 'start' else end}" - ), - } - if align == "center": - style["justify_self" if vertical else "align_self"] = "anchor-center" - return style - - -def placements(default_offset: str = "0px") -> list[CompoundStyle]: - """Make the compound variants that place a popup by its side and alignment. - - Args: - default_offset: How far from the anchor, for a popup that does not say. - - Returns: - One compound variant for each side and each alignment along it. - """ - return [ - { - "props": {"side": side, "align": align}, - "style": unchecked(placement(side, align, default_offset)), - } - for side, align in _AREAS - ] - - -# What a popup of UI SDK has while it goes out: UI SDK keeps it open and in -# the page until its transitions end. -_ENDING = "[data-ending-style]" - -# A popup UI SDK places: it sets where, the side the popup ended up on and -# the point of its anchor the popup opens from. The popup comes in from -# that side, and goes out the way it came. -SDK_PLACED: dict[str, Any] = { + "max_height": "var(--available-height)", "transform_origin": "var(--transform-origin)", _FROM: {f"[data-side='{side}']": entry for side, entry in _ENTRY.items()}, - "opacity": {"default": 1, "@starting-style": 0, _ENDING: 0}, + "opacity": {"default": 1, "@starting-style": 0, ENDING: 0}, "transform": { "default": "none", "@starting-style": f"var({_FROM})", - _ENDING: f"var({_FROM})", + ENDING: f"var({_FROM})", }, "transition_property": "opacity, transform", "transition_duration": { "default": "0s", - _MOTION: {"default": "160ms", _ENDING: "100ms"}, - }, -} - -# A popup of UI SDK before a table draws it: what a native popover is not, -# placed by UI SDK where `placement` would put it. -SDK_POPUP: dict[str, Any] = { - **{ - key: value - for key, value in POPUP.items() - if key - not in ( - "position_try_fallbacks", - "opacity", - "transform", - "transition_property", - "transition_duration", - ) + _MOTION: {"default": "160ms", ENDING: "100ms"}, }, - **SDK_PLACED, - "max_height": "var(--available-height)", + "transition_timing_function": "cubic-bezier(0.16, 1, 0.3, 1)", } -def sdk_popup(base: Mapping[str, Any]) -> dict[str, Any]: - """Make the base style of a popup of UI SDK from the one of a native popover. - - Args: - base: The base style of a native popover, made over ``POPUP``. - - Returns: - The same style over ``SDK_POPUP``: what it took from ``POPUP`` is - replaced, what it sets of its own stays. - """ - return { - **SDK_POPUP, - **{ - key: value - for key, value in base.items() - if key not in POPUP or POPUP[key] != value - }, - } - - def placed(styles: ComponentStyles) -> ComponentStyles: """Make the side and the alignment variants of a style table of placed content. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py index d4bb215a150..cabd66b0e92 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/select.py @@ -8,7 +8,7 @@ from reflex_components_ui.style import ComponentStyles, unchecked from reflex_components_ui.styles.appearance import by_appearance from reflex_components_ui.styles.button import _CLASSIC_DISABLED_SHADOW -from reflex_components_ui.styles.popup import OPENS, SDK_POPUP +from reflex_components_ui.styles.popup import OPENS, POPUP from reflex_components_ui.tokens import Step9 accent, gray, white, black = tokens.accent, tokens.gray, tokens.white, tokens.black @@ -355,7 +355,7 @@ def _content_size( SELECT_CONTENT: ComponentStyles = { "base": unchecked({ - **SDK_POPUP, + **POPUP, "color": gray[12], "font_family": tokens.default.font_family, "font_weight": tokens.font_weight.regular, diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py index a5757dafa89..12759863a0b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/tooltip.py @@ -4,7 +4,7 @@ from reflex_components_ui import tokens from reflex_components_ui.style import ComponentStyles, unchecked -from reflex_components_ui.styles.popup import OPEN, POPUP, placements +from reflex_components_ui.styles.popup import ENDING, POPUP, placed from reflex_components_ui.styles.typography import SIZE _MOTION = "@media (prefers-reduced-motion: no-preference)" @@ -15,10 +15,9 @@ OFFSET_DEFAULT = 4 ARROW = 5 -TOOLTIP: ComponentStyles = { +TOOLTIP: ComponentStyles = placed({ "base": unchecked({ **POPUP, - # The text of the page around it, not the one of a native popover. "color": "inherit", "overflow": "visible", "box_sizing": "border-box", @@ -29,15 +28,13 @@ # It comes in, and is gone at once. "transition_duration": { "default": "0s", - _MOTION: {"default": "0s", OPEN: "140ms"}, + _MOTION: {"default": "140ms", ENDING: "0s"}, }, }), "variants": { # A tooltip the pointer cannot rest on lets it through. "disable_hoverable_content": {"true": {"pointer_events": "none"}}, }, - "defaults": {"side": "top", "align": "center"}, - "compound": placements(f"{OFFSET_DEFAULT + ARROW}px"), "parts": { "text": { "base": unchecked({ @@ -51,4 +48,4 @@ }), }, }, -} +}) diff --git a/tests/units/reflex_components_ui/components/test_context_menu.py b/tests/units/reflex_components_ui/components/test_context_menu.py index 362d536b6ab..0231563766e 100644 --- a/tests/units/reflex_components_ui/components/test_context_menu.py +++ b/tests/units/reflex_components_ui/components/test_context_menu.py @@ -1,28 +1,43 @@ """Tests for reflex_components_ui.components.context_menu.""" -import itertools -from collections.abc import Callable from typing import Any import pytest -from reflex_components_ui.components import _popup +from reflex_base.utils.imports import ImportVar from reflex_components_ui.components.radio_group import RadioGroupRoot -from reflex_components_ui.components.select import _CHECK from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree +MENU = "@ui-sdk/react@0.1.0-beta.17/menu" -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the popups of each test from one.""" - monkeypatch.setattr(_popup, "_ids", itertools.count(1)) +def _scrolled(*items: Any) -> tuple[str, list[str], list[Any]]: + """The elements that scroll the items of a menu, around them. -def test_context_menu( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A context menu is the element it is on, the point it opens at, then a popover of items; a checkbox item says whether it is checked, and the menu leaves room for its check.""" + Args: + *items: The projections of the items. + + Returns: + The projection. + """ + return ( + '"div"', + ["className:sx_b8ae355be2_c"], + [('"div"', ["className:sx_453162d43a_c"], list(items))], + ) + + +def test_context_menu(ui_plugin: UIPlugin): + """A context menu is the parts of UI SDK: its area is the element it is on, and the menu opens beside the pointer. + + The placement of Radix Themes is the default: right of the pointer, 2px + from it and as far up as the padding of the menu, 10px from the edges. A + checkbox item closes the menu when it is chosen, as in Radix, and keeps + its state under a value of its own. The direction is the page's. + """ menu = rx.ui.context_menu component = menu.root( menu.trigger(rx.el.div("Area"), disabled=True), @@ -32,506 +47,228 @@ def test_context_menu( menu.label("View"), menu.group(menu.item("Zoom")), menu.separator(), + menu.sub( + menu.sub_trigger("Share"), + menu.sub_content(menu.item("Email")), + ), + size="1", + variant="soft", + sticky="always", ), + modal=False, + dir="rtl", ) - assert component.render() == { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"div"', - "props": [ - '"data-disabled":(true ? "" : undefined)', - '"data-rx-opens":"rx-context-menu-1"', - '"data-state":"closed"', - "onContextMenu:menuContext", + item = "className:sx_5c93cdaf19_c" + value = component.children[1].children[0].children[0].children[1]._key + assert tree(component.render()) == ( + "Menu", + ["loop:false", "modal:false"], + [ + ( + "MenuContextTrigger", + ["disabled:true", 'render:(jsx("div", ({}), "Area"))'], + [], + ), + ( + "MenuContent", + [ + 'align:"start"', + "alignOffset:-4", + "className:sx_1555e4b025_c", + "collisionPadding:10", + 'side:"right"', + "sideOffset:2", ], - "children": [{"contents": '"Area"'}], - }, - { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"span"', - "props": ['"aria-hidden":true', "className:sx_7e3d745d7a_c"], - "children": [], - }, - { - "name": '"div"', - "props": [ - "className:sx_5dd7216c67_c", - '"data-rx-popup":""', - 'id:"rx-context-menu-1"', - "onBeforeToggle:((event) => { (menuEvent)(event); (popupBeforeToggle)(event); })", - "onBlur:menuEvent", - "onClick:menuEvent", - "onKeyDown:menuEvent", - "onPointerLeave:menuEvent", - "onPointerMove:menuEvent", - "onToggle:menuEvent", - 'popover:"auto"', - "ref:((popup) => menuSync(popup, null))", - 'role:"menu"', - "tabIndex:-1", - ], - "children": [ - { - "name": '"div"', - "props": ["className:sx_b8ae355be2_c"], - "children": [ - { - "name": '"div"', - "props": ["className:sx_453162d43a_c"], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_85bc40da55_c", - 'role:"menuitem"', - "tabIndex:-1", - ], - "children": [{"contents": '"Copy"'}], - }, - { - "name": '"div"', - "props": [ - '"aria-checked":true', - "className:sx_85bc40da55_c", - '"data-state":(true ? "checked" : "unchecked")', - "onClick:((event) => menuCheck(event, null, false))", - 'role:"menuitemcheckbox"', - "tabIndex:-1", - ], - "children": [ - {"contents": '"Grid"'}, - { - "name": '"span"', - "props": [ - "className:sx_0796999dae_c" - ], - "children": [ - { - "name": '"svg"', - "props": [ - '"aria-hidden":true', - "className:sx_2f40c68fbd_c", - 'fill:"currentcolor"', - 'height:"9"', - 'viewBox:"0 0 9 9"', - 'width:"9"', - 'xmlns:"http://www.w3.org/2000/svg"', - ], - "children": [ - { - "name": '"path"', - "props": [ - 'clipRule:"evenodd"', - f'd:"{_CHECK}"', - 'fillRule:"evenodd"', - ], - "children": [], - } - ], - } - ], - }, - { - "name": '"div"', - "props": [ - "className:sx_da7de3c8ae_c" - ], - "children": [ - {"contents": '"\\u2318 G"'} - ], - }, - ], - }, - { - "name": '"div"', - "props": ["className:sx_b13742d240_c"], - "children": [{"contents": '"View"'}], - }, - { - "name": '"div"', - "props": ['role:"group"'], - "children": [ - { - "name": '"div"', - "props": [ - "className:sx_85bc40da55_c", - 'role:"menuitem"', - "tabIndex:-1", - ], - "children": [ - {"contents": '"Zoom"'} - ], - } - ], - }, - { - "name": '"div"', - "props": [ - '"aria-orientation":"horizontal"', - "className:sx_834f03d11d_c", - 'role:"separator"', - ], - "children": [], - }, - ], - } - ], - } - ], - }, + [ + _scrolled( + ("MenuItem", [item], ['"Copy"']), + ( + "MenuCheckboxItem", + [ + item, + "closeOnSelect:true", + "defaultChecked:true", + f'value:"{value}"', + ], + [ + ('"span"', ["className:sx_0796999dae_c"], [("svg",)]), + '"Grid"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + ['"\\u2318 G"'], + ), + ], + ), + ("MenuGroupLabel", ["className:sx_b13742d240_c"], ['"View"']), + ("MenuGroup", [], [("MenuItem", [item], ['"Zoom"'])]), + ("MenuSeparator", ["className:sx_834f03d11d_c"], []), + ( + "MenuSub", + ["loop:false"], + [ + ( + "MenuSubTrigger", + [item], + [ + '"Share"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + [("svg",)], + ), + ], + ), + ( + "MenuSubContent", + [ + "alignOffset:-4", + "className:sx_94fcdb63b8_c", + "collisionPadding:10", + "sideOffset:1", + ], + [_scrolled(("MenuItem", [item], ['"Email"']))], + ), + ], + ), + ) ], - }, + ), ], - } - # The items, the check, the shortcut, the label and the separator. - assert declared_styles(component)[3:] == [ - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-y, 0px))", - "marginRight": "calc(10px - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(0px - var(--rx-popup-snap-y, 0px))", - "marginLeft": "calc(var(--rx-popup-offset, 2px) + var(--rx-popup-snap-x, 0px))", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "calc(100% - var(--rx-popup-offset, 2px) - 10px)", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "100ms", - ":popover-open": "160ms", - }, - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "var(--gray-12)", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-regular)", - "fontStyle": "normal", - "textAlign": "start", - "display": {"default": "none", ":popover-open": "flex"}, - "flexDirection": "column", - "overflowX": "hidden", - "overflowY": "hidden", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-5)", - "outlineStyle": "none", - "--base-menu-content-padding": "var(--space-2)", - "--base-menu-item-padding-right": "var(--space-3)", - "--base-menu-item-height": "var(--space-6)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "--rx-menu-font-size": "var(--font-size-2)", - "--rx-menu-line-height": "var(--line-height-2)", - "--rx-menu-letter-spacing": "var(--letter-spacing-2)", - "--rx-menu-item-radius": "var(--radius-2)", - "--rx-menu-icon-size": "calc(10px * var(--scaling))", - "--rx-popup-shift": "-8px", - "--base-menu-item-padding-left": "var(--space-5)", - "positionArea": "right span-bottom", - "--rx-popup-from": "translateX(-4px) scale(0.97)", - "transformOrigin": "left top", - }, - { - "flexGrow": "1", - "flexShrink": "1", - "flexBasis": "0%", - "minHeight": "0", - "overflowX": "auto", - "overflowY": "auto", - "scrollbarWidth": "thin", - "scrollbarColor": "var(--gray-a8) transparent", - }, - { - "flexGrow": "1", - "flexShrink": "1", - "flexBasis": "0%", - "minWidth": "0", - "minHeight": "0", - "display": "flex", - "flexDirection": "column", - "overflowX": "auto", - "overflowY": "auto", - "padding": "var(--base-menu-content-padding)", - "boxSizing": "border-box", - }, - { - "display": "flex", - "alignItems": "center", - "rowGap": "var(--space-2)", - "columnGap": "var(--space-2)", - "height": "var(--base-menu-item-height)", - "paddingLeft": "var(--base-menu-item-padding-left)", - "paddingRight": "var(--base-menu-item-padding-right)", - "boxSizing": "border-box", - "position": "relative", - "outlineStyle": "none", - "outlineWidth": "medium", - "outlineColor": "currentColor", - "scrollMarginTop": "var(--base-menu-content-padding)", - "scrollMarginBottom": "var(--base-menu-content-padding)", - "userSelect": "none", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, - "fontSize": "var(--rx-menu-font-size)", - "lineHeight": "var(--rx-menu-line-height)", - "letterSpacing": "var(--rx-menu-letter-spacing)", - "borderRadius": "var(--rx-menu-item-radius)", - "color": { - "[aria-disabled='true']": "var(--gray-a8)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-shortcut-color": { - "default": "var(--gray-a11)", - ":focus": "currentColor", - "[aria-disabled='true']": "currentColor", - "[data-state='open']": "currentColor", - }, - "--rx-menu-chevron-color": { - "default": "var(--gray-12)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-check": { - "default": "none", - "[aria-checked='true']": "inline-flex", - }, - "backgroundColor": { - ":focus": "var(--accent-9)", - ":not(:focus)[data-state='open']": "var(--gray-a3)", - }, - }, - { - "display": "flex", - "alignItems": "center", - "rowGap": "var(--space-2)", - "columnGap": "var(--space-2)", - "height": "var(--base-menu-item-height)", - "paddingLeft": "var(--base-menu-item-padding-left)", - "paddingRight": "var(--base-menu-item-padding-right)", - "boxSizing": "border-box", - "position": "relative", - "outlineStyle": "none", - "outlineWidth": "medium", - "outlineColor": "currentColor", - "scrollMarginTop": "var(--base-menu-content-padding)", - "scrollMarginBottom": "var(--base-menu-content-padding)", - "userSelect": "none", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, - "fontSize": "var(--rx-menu-font-size)", - "lineHeight": "var(--rx-menu-line-height)", - "letterSpacing": "var(--rx-menu-letter-spacing)", - "borderRadius": "var(--rx-menu-item-radius)", - "color": { - "[aria-disabled='true']": "var(--gray-a8)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-shortcut-color": { - "default": "var(--gray-a11)", - ":focus": "currentColor", - "[aria-disabled='true']": "currentColor", - "[data-state='open']": "currentColor", - }, - "--rx-menu-chevron-color": { - "default": "var(--gray-12)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-check": { - "default": "none", - "[aria-checked='true']": "inline-flex", - }, - "backgroundColor": { - ":focus": "var(--accent-9)", - ":not(:focus)[data-state='open']": "var(--gray-a3)", - }, - }, - { - "position": "absolute", - "left": "0", - "width": "var(--base-menu-item-padding-left)", - "display": "var(--rx-menu-check)", - "alignItems": "center", - "justifyContent": "center", - }, - {"width": "var(--rx-menu-icon-size)", "height": "var(--rx-menu-icon-size)"}, - { - "display": "flex", - "alignItems": "center", - "marginLeft": "auto", - "paddingLeft": "var(--space-4)", - "color": "var(--rx-menu-shortcut-color)", - }, - { - "display": "flex", - "alignItems": "center", - "height": "var(--base-menu-item-height)", - "paddingLeft": "var(--base-menu-item-padding-left)", - "paddingRight": "var(--base-menu-item-padding-right)", - "boxSizing": "border-box", - "color": "var(--gray-a10)", - "userSelect": "none", - "cursor": "default", - "fontSize": "var(--rx-menu-font-size)", - "lineHeight": "var(--rx-menu-line-height)", - "letterSpacing": "var(--rx-menu-letter-spacing)", - "marginTop": { - ":is(:is([role=menuitem], [role=menuitemcheckbox]) + *)": "var(--space-2)" - }, - }, - {}, - { - "display": "flex", - "alignItems": "center", - "rowGap": "var(--space-2)", - "columnGap": "var(--space-2)", - "height": "var(--base-menu-item-height)", - "paddingLeft": "var(--base-menu-item-padding-left)", - "paddingRight": "var(--base-menu-item-padding-right)", - "boxSizing": "border-box", - "position": "relative", - "outlineStyle": "none", - "outlineWidth": "medium", - "outlineColor": "currentColor", - "scrollMarginTop": "var(--base-menu-content-padding)", - "scrollMarginBottom": "var(--base-menu-content-padding)", - "userSelect": "none", - "cursor": { - "default": "var(--cursor-menu-item)", - "[aria-disabled='true']": "default", - }, - "pointerEvents": {"default": "auto", "[aria-disabled='true']": "none"}, - "fontSize": "var(--rx-menu-font-size)", - "lineHeight": "var(--rx-menu-line-height)", - "letterSpacing": "var(--rx-menu-letter-spacing)", - "borderRadius": "var(--rx-menu-item-radius)", - "color": { - "[aria-disabled='true']": "var(--gray-a8)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-shortcut-color": { - "default": "var(--gray-a11)", - ":focus": "currentColor", - "[aria-disabled='true']": "currentColor", - "[data-state='open']": "currentColor", - }, - "--rx-menu-chevron-color": { - "default": "var(--gray-12)", - ":focus": "var(--accent-contrast)", - }, - "--rx-menu-check": { - "default": "none", - "[aria-checked='true']": "inline-flex", - }, - "backgroundColor": { - ":focus": "var(--accent-9)", - ":not(:focus)[data-state='open']": "var(--gray-a3)", - }, - }, - { - "height": "1px", - "marginTop": "var(--space-2)", - "marginBottom": "var(--space-2)", - "marginLeft": "var(--base-menu-item-padding-left)", - "marginRight": "var(--base-menu-item-padding-right)", - "backgroundColor": "var(--gray-a6)", - }, + ) + + +def test_context_menu_keeps_an_offset_it_is_given(ui_plugin: UIPlugin): + """A menu given an offset along the pointer is placed by it, not by its padding.""" + menu = rx.ui.context_menu + content = menu.content(menu.item("Copy"), align_offset=3) + assert tree(content.render())[1] == [ + 'align:"start"', + "alignOffset:3", + "className:sx_cf3c9fe7e2_c", + "collisionPadding:10", + 'side:"right"', + "sideOffset:2", ] +@pytest.mark.parametrize( + ("items", "indent"), + [ + ([rx.ui.context_menu.item("Copy")], "var(--space-3)"), + ( + [rx.ui.context_menu.item("Copy"), rx.ui.context_menu.checkbox("Grid")], + "var(--space-5)", + ), + ], +) +def test_context_menu_leaves_room_for_a_check( + items: list[Any], indent: str, ui_plugin: UIPlugin +): + """A menu with a checkbox item leaves room before the text of its items for the check. + + Args: + items: The items of the menu. + indent: The room before the text of an item. + ui_plugin: The configured plugin. + """ + content = rx.ui.context_menu.content(*items) + style = content._element_styles().style.style # pyright: ignore[reportAttributeAccessIssue] + assert style["--base-menu-item-padding-left"] == indent + + class GridState(rx.State): - """What a checkbox item and a radio group are bound to.""" + """What a checkbox item is bound to.""" grid: bool = True - unit: str = "a" + unit: str = "px" @rx.event - def set_unit(self, unit: str): - """Follow the group. + def set_grid(self, grid: bool): + """Follow the checkbox item. Args: - unit: The value of the group. + grid: Whether it is checked. """ - self.unit = unit + self.grid = grid @rx.event - def set_grid(self, grid: bool): - """Follow the item. + def set_unit(self, unit: str): + """Follow the radio group. Args: - grid: Whether it is checked. + unit: The unit. """ - self.grid = grid + self.unit = unit def test_context_menu_checkbox_bound_to_state(ui_plugin: UIPlugin): - """A checkbox item bound to state shows the state, and hands its script what it does when it changes.""" + """A checkbox item bound to state shows the state, hands over the new state, and keeps the value it is given.""" name = GridState.get_full_name() item = rx.ui.context_menu.checkbox( - "Grid", checked=GridState.grid, on_change=GridState.set_grid + "Grid", checked=GridState.grid, on_change=GridState.set_grid, value="grid" ) assert item.render()["props"] == [ - f'"aria-checked":{GridState.grid!s}', - "className:sx_85bc40da55_c", - f'"data-state":({GridState.grid!s} ? "checked" : "unchecked")', + f"checked:{GridState.grid!s}", + "className:sx_b9894c01e4_c", + "closeOnSelect:true", ( - "onClick:((event) => menuCheck(event, ((_ev_0) => (addEvents(" + "onCheckedChange:((_ev_0) => (addEvents(" f'[(ReflexEvent("{name}.set_grid", ({{ ["grid"] : _ev_0 }}), ({{ }})))], ' - "[_ev_0], ({ })))), true))" + "[_ev_0], ({ }))))" ), - 'role:"menuitemcheckbox"', - "tabIndex:-1", + 'value:"grid"', ] +def test_context_menu_checkbox_items_keep_their_own_state(ui_plugin: UIPlugin): + """Each checkbox item given no value has one of its own: UI SDK keeps an item's state under its value.""" + first, second = (rx.ui.context_menu.checkbox(text) for text in ("Grid", "Rulers")) + assert first._key != second._key # pyright: ignore[reportAttributeAccessIssue] + + def test_context_menu_radio_is_a_radio_group(ui_plugin: UIPlugin): """rx.ui.context_menu.radio is a group of radio buttons from its items, as rx.context_menu.radio is.""" assert isinstance(rx.ui.context_menu.radio(["a", "b"]), RadioGroupRoot) def test_context_menu_radio_group_hears_no_change_of_its_own(ui_plugin: UIPlugin): - """A radio group of a menu is a group to assistive technology, and its change is the business of its items, as in Radix.""" + """A radio group of a menu is a group of UI SDK, and its change is the business of its items, as in Radix.""" group = rx.ui.context_menu.radio_group( rx.el.input(type="checkbox"), value=GridState.unit, on_change=GridState.set_unit ) - assert group.render()["props"] == ['role:"group"'] + assert (group.render()["name"], group.render()["props"]) == ("MenuGroup", []) + + +def test_context_menu_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a context menu imports its parts from UI SDK, pinned, and no script.""" + menu = rx.ui.context_menu + component = menu.root( + menu.trigger(rx.el.div("Area")), + menu.content(menu.item("Copy"), menu.checkbox("Grid")), + ) + imports = component._get_all_imports() + assert { + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + MENU: [ + ImportVar(tag="Menu"), + ImportVar(tag="MenuContextTrigger"), + ImportVar(tag="MenuContent"), + ImportVar(tag="MenuItem"), + ImportVar(tag="MenuCheckboxItem"), + ], + } + + +def test_context_menu_trigger_needs_an_element(ui_plugin: UIPlugin): + """An area of anything but one element fails with the name of the component.""" + with pytest.raises(StyleError) as error: + rx.ui.context_menu.trigger("Area") + assert str(error.value) == ( + "rx.ui.context_menu.trigger: it is rendered as its child, so it needs " + "exactly one child that is an element, such as a button." + ) diff --git a/tests/units/reflex_components_ui/components/test_dropdown_menu.py b/tests/units/reflex_components_ui/components/test_dropdown_menu.py index c8f6591d44c..e559cf01a93 100644 --- a/tests/units/reflex_components_ui/components/test_dropdown_menu.py +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -103,7 +103,7 @@ def test_dropdown_menu(ui_plugin: UIPlugin): "MenuContent", [ 'align:"start"', - "className:sx_8c7d332986_c", + "className:sx_94fcdb63b8_c", "collisionPadding:10", 'side:"top"', "sideOffset:8", @@ -143,7 +143,7 @@ def test_dropdown_menu(ui_plugin: UIPlugin): "MenuSubContent", [ "alignOffset:-4", - "className:sx_d3add7826b_c", + "className:sx_94fcdb63b8_c", "collisionPadding:10", "sideOffset:1", ], @@ -283,7 +283,7 @@ def test_dropdown_menu_bound_to_state(ui_plugin: UIPlugin): "MenuContent", [ 'align:"start"', - "className:sx_ab8a2d3de6_c", + "className:sx_cf3c9fe7e2_c", "collisionPadding:10", 'side:"bottom"', "sideOffset:4", diff --git a/tests/units/reflex_components_ui/components/test_hover_card.py b/tests/units/reflex_components_ui/components/test_hover_card.py index 6f3ca20434a..c7c4c85951f 100644 --- a/tests/units/reflex_components_ui/components/test_hover_card.py +++ b/tests/units/reflex_components_ui/components/test_hover_card.py @@ -1,149 +1,54 @@ """Tests for reflex_components_ui.components.hover_card.""" -import itertools -from collections.abc import Callable -from typing import Any - import pytest from reflex_base.utils.imports import ImportVar -from reflex_components_ui.components import _popup from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the popups of each test from one.""" - monkeypatch.setattr(_popup, "_ids", itertools.count(1)) - +def test_hover_card(ui_plugin: UIPlugin): + """A hover card is the parts of UI SDK: its trigger is its child, and the card opens beside it after the delays of Radix Themes. -def test_hover_card( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A hover card is its trigger, then a popover a script opens under the pointer and with the focus, after the delays of its root.""" - component = rx.ui.hover_card.root( - rx.ui.hover_card.trigger(rx.el.button("Radix")), - rx.ui.hover_card.content( - rx.el.p("Inside"), size="1", side="top", align="center", side_offset=4 + The placement of Radix Themes is the default: below and at the start of + the trigger, 8px from it, 10px from the edges. The props of the + placement of Radix that UI SDK does not have are left out. + """ + card = rx.ui.hover_card + component = card.root( + card.trigger(rx.el.a("Radix", href="https://radix-ui.com")), + card.content( + "Inside", size="1", side="right", side_offset=4, avoid_collisions=False ), - open_delay=100, - close_delay=50, default_open=True, + close_delay=50, ) - assert component.render() == { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"button"', - "props": [ - '"data-rx-hover":"rx-hover-card-1"', - '"data-state":"closed"', - "onBlur:hoverEvent", - "onFocus:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", + assert tree(component.render()) == ( + "HoverCard", + ["closeDelay:50", "defaultOpen:true", "delay:200"], + [ + ( + "HoverCardTrigger", + [ + 'render:(jsx(ReactRouterLink, ({to:"https://radix-ui.com"}), "Radix"))' ], - "children": [{"contents": '"Radix"'}], - }, - { - "name": '"div"', - "props": [ - "className:sx_a4491172ba_c", - '"data-close-delay":50', - '"data-default-open":true', - '"data-open-delay":100', - '"data-rx-popup":""', - 'id:"rx-hover-card-1"', - "onBeforeToggle:popupBeforeToggle", - "onBlur:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", - 'popover:"manual"', - "ref:((popup) => hoverSync(popup, null))", + [], + ), + ( + "HoverCardContent", + [ + 'align:"start"', + "className:sx_b74f469818_c", + "collisionPadding:10", + 'side:"right"', + "sideOffset:4", ], - "children": [ - { - "name": '"p"', - "props": [], - "children": [{"contents": '"Inside"'}], - } - ], - }, + ['"Inside"'], + ), ], - } - assert declared_styles(component) == [ - {}, - {}, - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "calc(10px + var(--rx-popup-snap-y, 0px))", - "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(var(--rx-popup-offset, 8px) - var(--rx-popup-snap-y, 0px))", - "marginLeft": "var(--rx-popup-snap-x, 0px)", - "padding": "var(--hover-card-content-padding)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "min(480px, calc(100vw - 20px))", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "100ms", - ":popover-open": "160ms", - }, - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "inherit", - "backgroundColor": "var(--color-panel-solid)", - "boxShadow": "var(--shadow-4)", - "outlineStyle": "none", - "overflowX": "auto", - "overflowY": "auto", - "--inset-padding-top": "var(--hover-card-content-padding)", - "--inset-padding-right": "var(--hover-card-content-padding)", - "--inset-padding-bottom": "var(--hover-card-content-padding)", - "--inset-padding-left": "var(--hover-card-content-padding)", - "--hover-card-content-padding": "var(--space-3)", - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "positionArea": "top span-all", - "maxHeight": "calc(100% - var(--rx-popup-offset, 8px) - 10px)", - "--rx-popup-from": "translateY(4px) scale(0.97)", - "transformOrigin": "bottom center", - "justifySelf": "anchor-center", - "--rx-popup-offset": "4px", - }, - ] + ) class HoverCardState(rx.State): @@ -154,7 +59,7 @@ class HoverCardState(rx.State): @rx.event def set_shown(self, shown: bool): - """Follow the hover card. + """Follow the card. Args: shown: Whether it is open. @@ -163,59 +68,51 @@ def set_shown(self, shown: bool): def test_hover_card_bound_to_state(ui_plugin: UIPlugin): - """A hover card bound to state hands its script its state, its delays and what it does when it is asked to open or close; the defaults are the delays of Radix Themes.""" + """A hover card bound to state takes whether it is open and how long it waits from it; it closes after the delay of Radix Themes.""" name = HoverCardState.get_full_name() component = rx.ui.hover_card( - rx.ui.hover_card.trigger(rx.el.a("Radix", id="radix")), - rx.ui.hover_card.content("Inside", id="card"), + rx.ui.hover_card.trigger(rx.el.a("Radix")), + rx.ui.hover_card.content("Inside"), open=HoverCardState.shown, on_open_change=HoverCardState.set_shown, open_delay=HoverCardState.wait, ) - trigger, popup = component.render()["children"] - assert trigger["props"] == [ - '"data-rx-hover":"card"', - '"data-state":"closed"', - 'id:"radix"', - "onBlur:hoverEvent", - "onFocus:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", - "ref:ref_radix", - ] - assert popup["props"] == [ - "className:sx_2cb8c9a2a4_c", - '"data-close-delay":150', - f'"data-open-delay":{HoverCardState.wait!s}', - '"data-rx-popup":""', - 'id:"card"', - "onBeforeToggle:popupBeforeToggle", - "onBlur:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", - 'popover:"manual"', + assert component.render()["props"] == [ + "closeDelay:150", + f"delay:{HoverCardState.wait!s}", ( - f"ref:((popup) => hoverSync(popup, {HoverCardState.shown!s}, ({{ open: " - f'((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' - '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))) })))' + "onOpenChange:((value, details) => { const change = ((_ev_0) => " + f'(addEvents([(ReflexEvent("{name}.set_shown", ({{ ["shown"] : _ev_0 }}), ' + "({ })))], [_ev_0], ({ })))), openAutoFocus = undefined, " + "closeAutoFocus = undefined, escape = undefined, outside = undefined, " + "focusOutside = undefined, interact = undefined; " + 'if (details?.reason === "escape-key") escape?.(); ' + 'if (details?.reason === "outside-press") { outside?.(); interact?.(); } ' + 'if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); } ' + "change?.(value); if (value) openAutoFocus?.(); else " + "closeAutoFocus?.(); })" ), + f"open:{HoverCardState.shown!s}", ] -def test_hover_card_imports_its_script(ui_plugin: UIPlugin): - """A page with a hover card loads the script of the popups that open under the pointer, and what puts a popup on whole pixels.""" +def test_hover_card_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a hover card imports its parts from UI SDK, pinned, and no script.""" component = rx.ui.hover_card.root( rx.ui.hover_card.trigger(rx.el.a("Radix")), rx.ui.hover_card.content("x") ) imports = component._get_all_imports() assert { - module: names for module, names in imports.items() if "behaviors" in module + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module } == { - "$/reflex-ui/behaviors/hover.js": [ - ImportVar(tag="hoverEvent"), - ImportVar(tag="hoverSync"), + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/hover-card": [ + ImportVar(tag="HoverCard"), + ImportVar(tag="HoverCardTrigger"), + ImportVar(tag="HoverCardContent"), ], - "$/reflex-ui/behaviors/popup.js": [ImportVar(tag="popupBeforeToggle")], } diff --git a/tests/units/reflex_components_ui/components/test_popover.py b/tests/units/reflex_components_ui/components/test_popover.py index 945429f6741..5ce079baa68 100644 --- a/tests/units/reflex_components_ui/components/test_popover.py +++ b/tests/units/reflex_components_ui/components/test_popover.py @@ -80,7 +80,7 @@ def test_popover(ui_plugin: UIPlugin): "PopoverContent", [ 'align:"start"', - "className:sx_cdfecf0b21_c", + "className:sx_85c95c6603_c", "collisionPadding:10", 'side:"top"', "sideOffset:12", diff --git a/tests/units/reflex_components_ui/components/test_popup.py b/tests/units/reflex_components_ui/components/test_popup.py index 42338decb97..137d88b896f 100644 --- a/tests/units/reflex_components_ui/components/test_popup.py +++ b/tests/units/reflex_components_ui/components/test_popup.py @@ -17,8 +17,9 @@ (rx.ui.popover.root, "Popover", [KEY]), (rx.ui.dropdown_menu.root, "Menu", [KEY, "loop:false"]), (rx.ui.dropdown_menu.sub, "MenuSub", [KEY, "loop:false"]), - (rx.ui.context_menu.root, "Fragment", [KEY]), - (rx.ui.hover_card.root, "Fragment", [KEY]), + (rx.ui.context_menu.root, "Menu", [KEY, "loop:false"]), + (rx.ui.context_menu.sub, "MenuSub", [KEY, "loop:false"]), + (rx.ui.hover_card.root, "HoverCard", ["closeDelay:150", "delay:200", KEY]), ], ) def test_a_popup_in_a_list_keeps_its_key( @@ -29,9 +30,9 @@ def test_a_popup_in_a_list_keeps_its_key( ): """The root of a popup carries its key: ``rx.foreach`` keys each item by it. - A root of UI SDK is a component that renders no element, and the arrow - keys of a menu stop at its ends, as in Radix; the others render a - fragment. + A root of UI SDK is a component that renders no element. The arrow keys + of a menu stop at its ends, and a hover card waits as long as in Radix + Themes. Args: root: The root of a popup. diff --git a/tests/units/reflex_components_ui/components/test_select.py b/tests/units/reflex_components_ui/components/test_select.py index 6e81e785dfa..7a0fe530c06 100644 --- a/tests/units/reflex_components_ui/components/test_select.py +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -94,7 +94,7 @@ def test_select(ui_plugin: UIPlugin): [ ( "SelectTrigger", - ["className:sx_5ea0b69884_c"], + ["className:sx_590c531cfc_c"], [ ( "SelectValue", @@ -109,7 +109,7 @@ def test_select(ui_plugin: UIPlugin): [ 'align:"start"', "alignItemWithTrigger:true", - "className:sx_1a5dfc1f84_c", + "className:sx_16a9d4ef9b_c", "collisionPadding:10", 'side:"bottom"', "sideOffset:4", @@ -144,14 +144,14 @@ def test_select_of_a_list(ui_plugin: UIPlugin): [ ( "SelectTrigger", - ["className:sx_d728ce29c0_c"], + ["className:sx_812cedac46_c"], [("SelectValue", ["className:sx_94480a599d_c"], []), ("svg",)], ), ( "SelectContent", [ 'align:"start"', - "className:sx_1f65a63af7_c", + "className:sx_42734c738f_c", "collisionPadding:10", 'side:"bottom"', "sideOffset:4", diff --git a/tests/units/reflex_components_ui/components/test_theme_panel.py b/tests/units/reflex_components_ui/components/test_theme_panel.py index 3e5290865a8..3c0f4a0fe1b 100644 --- a/tests/units/reflex_components_ui/components/test_theme_panel.py +++ b/tests/units/reflex_components_ui/components/test_theme_panel.py @@ -46,6 +46,9 @@ def _walk(component: Any) -> Iterator[Any]: """Walk a tree of components, parents before children. + A part of UI SDK rendered as its child, such as the trigger of a + tooltip, holds that child apart from its children. + Args: component: The root. @@ -53,6 +56,9 @@ def _walk(component: Any) -> Iterator[Any]: Each component of the tree. """ yield component + rendered_as = getattr(component, "_child", None) + if rendered_as is not None: + yield from _walk(rendered_as) for child in getattr(component, "children", ()): yield from _walk(child) diff --git a/tests/units/reflex_components_ui/components/test_tooltip.py b/tests/units/reflex_components_ui/components/test_tooltip.py index 1e15d30196e..e9e13e754a5 100644 --- a/tests/units/reflex_components_ui/components/test_tooltip.py +++ b/tests/units/reflex_components_ui/components/test_tooltip.py @@ -1,167 +1,75 @@ """Tests for reflex_components_ui.components.tooltip.""" -import itertools from collections.abc import Callable from typing import Any import pytest from reflex_base.utils.imports import ImportVar -from reflex_components_ui.components import _popup from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree -@pytest.fixture(autouse=True) -def ids(monkeypatch: pytest.MonkeyPatch): - """Number the popups of each test from one.""" - monkeypatch.setattr(_popup, "_ids", itertools.count(1)) +def test_tooltip(ui_plugin: UIPlugin): + """A tooltip is the parts of UI SDK: what it describes is its child, and its popup holds its text. - -def test_tooltip( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """A tooltip is its child, which it describes, then a popover with its text, which a script opens under the pointer and with the focus.""" + It describes its child, as in Radix, and opens after the delay of Radix + Themes, given here. It is placed as the one of Radix Themes, whose arrow + it does not draw: the room of the arrow widens its offset. + """ component = rx.ui.tooltip( - rx.el.button("Save", id="save"), + rx.el.button("Save"), content="Saves the file", side="bottom", align="start", - side_offset=6, - delay_duration=0, - disable_hoverable_content=True, - default_open=True, - aria_label="Save", - max_width="200px", + side_offset=2, + aria_label="Save it", + delay_duration=500, + force_mount=True, ) - assert component.render() == { - "name": "Fragment", - "props": [], - "children": [ - { - "name": '"button"', - "props": [ - '"aria-describedby":"rx-tooltip-1"', - '"data-rx-hover":"rx-tooltip-1"', - '"data-state":"closed"', - 'id:"save"', - "onBlur:hoverEvent", - "onFocus:hoverEvent", - "onPointerDown:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", - "ref:ref_save", - ], - "children": [{"contents": '"Save"'}], - }, - { - "name": '"div"', - "props": [ - '"aria-label":"Save"', - "className:sx_dfdb3d8a01_c", - '"data-close-delay":0', - '"data-default-open":true', - '"data-open-delay":0', - '"data-rx-popup":""', - 'id:"rx-tooltip-1"', - "onBeforeToggle:popupBeforeToggle", - "onBlur:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", - 'popover:"manual"', - "ref:((popup) => hoverSync(popup, null))", - 'role:"tooltip"', + assert tree(component.render()) == ( + "Tooltip", + ["closeDelay:100", "delay:500", 'type:"description"'], + [ + ("TooltipTrigger", ['render:(jsx("button", ({}), "Save"))'], []), + ( + "TooltipContent", + [ + 'align:"start"', + '"aria-label":"Save it"', + "className:sx_1b0391f864_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:7", ], - "children": [ - { - "name": '"p"', - "props": ["className:sx_7f6c9bc5c4_c"], - "children": [{"contents": '"Saves the file"'}], - } - ], - }, + [('"p"', ["className:sx_7f6c9bc5c4_c"], ['"Saves the file"'])], + ), ], - } - assert declared_styles(component) == [ - {}, - { - "position": "fixed", - "top": "auto", - "right": "auto", - "bottom": "auto", - "left": "auto", - "marginTop": "calc(var(--rx-popup-offset, 9px) + var(--rx-popup-snap-y, 0px))", - "marginRight": "calc(0px - var(--rx-popup-snap-x, 0px))", - "marginBottom": "calc(10px - var(--rx-popup-snap-y, 0px))", - "marginLeft": "calc(var(--rx-popup-shift, 0px) + var(--rx-popup-snap-x, 0px))", - "paddingTop": "var(--space-1)", - "paddingRight": "var(--space-2)", - "paddingBottom": "var(--space-1)", - "paddingLeft": "var(--space-2)", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "boxSizing": "border-box", - "width": "max-content", - "height": "auto", - "maxWidth": "200px", - "positionTryFallbacks": "flip-block, flip-inline", - "opacity": { - "default": 0, - ":popover-open": {"default": 1, "@starting-style": 0}, - }, - "transform": { - "default": "var(--rx-popup-from)", - ":popover-open": { - "default": "none", - "@starting-style": "var(--rx-popup-from)", - }, - }, - "transitionProperty": "opacity, transform, display, overlay", - "transitionDuration": { - "default": "0s", - "@media (prefers-reduced-motion: no-preference)": { - "default": "0s", - ":popover-open": "140ms", - }, - }, - "transitionTimingFunction": "cubic-bezier(0.16, 1, 0.3, 1)", - "color": "inherit", - "overflowX": "visible", - "overflowY": "visible", - "backgroundColor": "var(--gray-12)", - "borderTopLeftRadius": "var(--radius-2)", - "borderTopRightRadius": "var(--radius-2)", - "borderBottomRightRadius": "var(--radius-2)", - "borderBottomLeftRadius": "var(--radius-2)", - "pointerEvents": "none", - "positionArea": "bottom span-right", - "maxHeight": "calc(100% - var(--rx-popup-offset, 9px) - 10px)", - "--rx-popup-from": "translateY(-4px) scale(0.97)", - "transformOrigin": "top left", - "--rx-popup-offset": "11px", - }, - { - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "lineHeight": "var(--line-height, var(--default-line-height))", - "letterSpacing": "var(--letter-spacing, inherit)", - "fontSize": "var(--font-size-1)", - "--line-height": "var(--line-height-1)", - "--letter-spacing": "var(--letter-spacing-1)", - "color": "var(--gray-1)", - "userSelect": "none", - "cursor": "default", - }, + ) + + +def test_tooltip_styles( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """A tooltip is placed above what it describes by default; it comes in, and is gone at once.""" + component = rx.ui.tooltip(rx.el.button("Save"), content="Saves the file") + assert tree(component.render())[2][1][1] == [ + 'align:"center"', + "className:sx_1b0391f864_c", + "collisionPadding:10", + 'side:"top"', + "sideOffset:9", ] + _, _, popup, _ = declared_styles(component) + assert popup["transitionDuration"] == { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": { + "default": "140ms", + "[data-ending-style]": "0s", + }, + } class TooltipState(rx.State): @@ -169,6 +77,7 @@ class TooltipState(rx.State): shown: bool = False still: bool = False + gap: int = 4 @rx.event def set_shown(self, shown: bool): @@ -181,58 +90,65 @@ def set_shown(self, shown: bool): def test_tooltip_bound_to_state(ui_plugin: UIPlugin): - """A tooltip bound to state hands its script its state and what it does when it is asked to open or close.""" + """A tooltip bound to state takes whether it is open, how long it waits and its offset from it, and calls the events of Radix by the reason of a change.""" name = TooltipState.get_full_name() component = rx.ui.tooltip( rx.el.button("Save"), content="Saves the file", open=TooltipState.shown, on_open_change=TooltipState.set_shown, + on_escape_key_down=rx.console_log("esc"), disable_hoverable_content=TooltipState.still, + side_offset=TooltipState.gap, ) - trigger, popup = component.render()["children"] - assert trigger["props"] == [ - '"aria-describedby":"rx-tooltip-1"', - '"data-rx-hover":"rx-tooltip-1"', - '"data-state":"closed"', - "onBlur:hoverEvent", - "onFocus:hoverEvent", - "onPointerDown:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", + root = tree(component.render()) + assert root[1] == [ + f"closeDelay:({TooltipState.still!s} ? 0 : 100)", + "delay:200", + ( + "onOpenChange:((value, details) => { const change = ((_ev_0) => " + f'(addEvents([(ReflexEvent("{name}.set_shown", ({{ ["shown"] : _ev_0 }}), ' + "({ })))], [_ev_0], ({ })))), openAutoFocus = undefined, " + "closeAutoFocus = undefined, " + 'escape = ((...args) => (addEvents([(ReflexEvent("_call_function", ' + '({ ["function"] : (() => (console?.["log"]("esc"))), ' + '["callback"] : null }), ({ })))], args, ({ })))), ' + "outside = undefined, focusOutside = undefined, interact = undefined; " + 'if (details?.reason === "escape-key") escape?.(); ' + 'if (details?.reason === "outside-press") { outside?.(); interact?.(); } ' + 'if (details?.reason === "focus-out") { focusOutside?.(); interact?.(); } ' + "change?.(value); if (value) openAutoFocus?.(); else " + "closeAutoFocus?.(); })" + ), + f"open:{TooltipState.shown!s}", + 'type:"description"', ] - assert popup["props"] == [ - f'className:sx_35d14492e9_c + " " + (sx_35d14492e9_0[{TooltipState.still!s}] ?? "")', - f'"data-close-delay":({TooltipState.still!s} ? 0 : 100)', - '"data-open-delay":200', - '"data-rx-popup":""', - 'id:"rx-tooltip-1"', - "onBeforeToggle:popupBeforeToggle", - "onBlur:hoverEvent", - "onPointerEnter:hoverEvent", - "onPointerLeave:hoverEvent", - 'popover:"manual"', + assert root[2][1][1] == [ + 'align:"center"', ( - f"ref:((popup) => hoverSync(popup, {TooltipState.shown!s}, ({{ open: " - f'((_ev_0) => (addEvents([(ReflexEvent("{name}.set_shown", ' - '({ ["shown"] : _ev_0 }), ({ })))], [_ev_0], ({ })))) })))' + f'className:sx_c0ec531d30_c + " " + (sx_c0ec531d30_0[{TooltipState.still!s}] ?? "")' ), - 'role:"tooltip"', + "collisionPadding:10", + 'side:"top"', + f"sideOffset:({TooltipState.gap!s} + 5)", ] -def test_tooltip_imports_its_script(ui_plugin: UIPlugin): - """A page with a tooltip loads the script of the popups that open under the pointer, and what puts a popup on whole pixels.""" +def test_tooltip_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a tooltip imports its parts from UI SDK, pinned, and no script.""" component = rx.ui.tooltip(rx.el.button("Save"), content="Saves the file") imports = component._get_all_imports() assert { - module: names for module, names in imports.items() if "behaviors" in module + module: names + for module, names in imports.items() + if "ui-sdk" in module or "behaviors" in module } == { - "$/reflex-ui/behaviors/hover.js": [ - ImportVar(tag="hoverEvent"), - ImportVar(tag="hoverSync"), + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/tooltip": [ + ImportVar(tag="Tooltip"), + ImportVar(tag="TooltipTrigger"), + ImportVar(tag="TooltipContent"), ], - "$/reflex-ui/behaviors/popup.js": [ImportVar(tag="popupBeforeToggle")], } From 1c9d4db0c5eb330adce184dd5f151f2953940185 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:32:28 +0000 Subject: [PATCH 196/204] Keep a menu label anywhere in its menu, and allow the UI SDK differences of wave B A label of a menu is an element of its own, as in Radix: UI SDK's label must be inside a group. The arrow keys of a context menu stop on a disabled item, a tooltip closes when a press ends, and one the pointer cannot rest on stays open while the pointer is over it. The trigger of a popover names it by the id its content is given, while it is open. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- .../parity/allowlist.toml | 29 ++++++++++++++----- .../parity/ui_parity/components/hover_card.py | 5 +++- .../reflex_components_ui/components/_menu.py | 12 ++++---- .../components/test_context_menu.py | 2 +- 4 files changed, 34 insertions(+), 14 deletions(-) diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index 55d4b414373..a47ecae6cba 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -526,7 +526,7 @@ reason = "rx.popover and rx.ui.popover are opened by JavaScript: until the page component = "popover" step = "its trigger names the popover it opens by the id it is given" system = "rx" -reason = "The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link. The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it." +reason = "The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link. The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the `id` the content is given." [[contract]] component = "popover" @@ -548,7 +548,7 @@ reason = "rx.tooltip renders its text when it opens, and names it as the descrip [[contract]] component = "tooltip" step = "points at its button with an arrow" -reason = "rx.ui.tooltip has no arrow. It is where the tooltip of rx.tooltip is, the room of the arrow included, and is placed by the browser, which turns it over where it would leave the page: an arrow drawn by its styles could not follow it. `arrow_padding` has nothing to say." +reason = "rx.ui.tooltip has no arrow. It is where the tooltip of rx.tooltip is, the room of the arrow included, and UI SDK places it and turns it over where it would leave the page; Radix Themes draws the arrow with an element of Radix that rx.ui does not render. `arrow_padding` has nothing to say." [[contract]] component = "tooltip" @@ -574,13 +574,13 @@ reason = "A popover taller than the page grows past the bottom of the page in rx component = "tooltip" check = "style" properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] -reason = "Radix places a tooltip with a wrapper element it moves by a transform, and the tooltip inside it has no position, margins or bounds of its own. rx.ui.tooltip is placed itself, a native popover in the top layer: fixed, at a margin from what it describes by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." +reason = "Radix places a tooltip with a wrapper element it moves by a transform, and the tooltip inside it has no position, margins or bounds of its own. rx.ui.tooltip is placed itself, in the top layer: fixed, where UI SDK puts it beside what it describes, and no larger than the room UI SDK measures. It is drawn on the same pixels." [[look]] component = "hover_card" check = "style" properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] -reason = "Radix places a hover card with a wrapper element it moves by a transform, and the card inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.hover_card is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." +reason = "Radix places a hover card with a wrapper element it moves by a transform, and the card inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.hover_card is placed itself, in the top layer: fixed, where UI SDK puts it beside its trigger, and no larger than the room UI SDK measures. It is drawn on the same pixels." [[look]] component = "hover_card" @@ -624,13 +624,13 @@ reason = "While it is open rx.dropdown_menu takes the pointer off the rest of th component = "context_menu" check = "style" properties = ["position", "margin-top", "margin-right", "margin-bottom", "margin-left", "max-height", "max-width"] -reason = "Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.context_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels." +reason = "Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.context_menu is placed itself, in the top layer: fixed, where UI SDK puts it beside the pointer, and no taller than the room UI SDK measures. It is drawn on the same pixels." [[look]] component = "context_menu" check = "style" properties = ["pointer-events"] -reason = "While it is open rx.context_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.context_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.context_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.context_menu hears the press and ignores it." +reason = "While it is open rx.context_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.context_menu sets no such style: a press outside the menu closes it. And the pointer passes through a disabled item of rx.ui.context_menu, which it does not highlight, where rx.context_menu hears the press and ignores it." [[contract]] component = "dropdown_menu" @@ -841,7 +841,7 @@ reason = "The trigger of rx.ui.popover says its state in `data-open` and `data-c [[contract]] component = "popover" step = "its trigger names the popover it opens by the id it is given" -reason = "The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it, whatever `id` the content is given. The trigger of rx.popover names it by an id rx.popover makes up." +reason = "The trigger of rx.ui.popover names its popover only while it is open: UI SDK sets its `aria-controls` when the popover opens, and then it is the `id` the content is given. The trigger of rx.popover names it while it is closed too, by an id rx.popover makes up." [[contract]] component = "drawer" @@ -887,3 +887,18 @@ check = "style" cells = "long-true*" properties = ["height"] reason = "A panel of rx.ui.alert_dialog taller than the room the overlay of Radix Themes leaves around it is no taller than that room, and scrolls what it holds. rx.alert_dialog grows the panel and scrolls the overlay around it." + +[[contract]] +component = "context_menu" +step = "opens from the keyboard on its first item" +reason = "The arrow keys of rx.ui.context_menu stop on a disabled item, as the menu pattern of ARIA asks: UI SDK keeps it focusable, so that it is announced, and a choice of it does nothing. The arrow keys of rx.context_menu skip it." + +[[contract]] +component = "tooltip" +step = "a press on its button closes it" +reason = "rx.ui.tooltip closes when a press on its button ends, where UI SDK hears the press. rx.tooltip closes as soon as the pointer goes down." + +[[contract]] +component = "tooltip" +step = "a tooltip the pointer cannot rest on closes when it leaves the button" +reason = "A tooltip of rx.ui.tooltip with `disable_hoverable_content` lets the pointer through, but UI SDK keeps it open while the pointer is over it, and closes it when the pointer leaves it. rx.tooltip closes it as soon as the pointer leaves the button." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py index 1a3494cbff4..57f18abb9d6 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/hover_card.py @@ -328,7 +328,10 @@ def _hover(run: Run) -> None: page.wait_for_timeout(100) assert _shown(run) == [] _wait_for_shown(run, "A profile") - assert page.locator("#profile").get_attribute("data-state") == "open" + # Radix says the trigger is open in `data-state`, UI SDK in `data-open`. + assert page.locator("#profile").evaluate( + "trigger => trigger.matches(\":is([data-state='open'], [data-open])\")" + ) leave(page) page.wait_for_timeout(50) assert _shown(run) == ["A profile"] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py index 024e616cd1c..5cb79863793 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/_menu.py @@ -15,7 +15,7 @@ from reflex_base.components.tags import CommonTag from reflex_base.vars.base import get_unique_variable_name -from reflex_components_ui.base import Part +from reflex_components_ui.base import Part, UIComponent from reflex_components_ui.components._group import descendants, literal from reflex_components_ui.components._sdk import ( COLLISION_PADDING, @@ -388,12 +388,14 @@ class MenuSeparator(SDKPart): styles: ClassVar[ComponentStyles] = MENU_SEPARATOR -class MenuLabel(SDKPart): - """A label of a group of items, which cannot be chosen.""" +class MenuLabel(UIComponent): + """A label of a group of items, which cannot be chosen. - library = LIBRARY + It is an element of its own, as in Radix, and may be anywhere in a menu: + UI SDK's label names a group, and must be inside it. + """ - tag = "MenuGroupLabel" + tag = "div" styles: ClassVar[ComponentStyles] = MENU_LABEL diff --git a/tests/units/reflex_components_ui/components/test_context_menu.py b/tests/units/reflex_components_ui/components/test_context_menu.py index 0231563766e..8a085d7aa15 100644 --- a/tests/units/reflex_components_ui/components/test_context_menu.py +++ b/tests/units/reflex_components_ui/components/test_context_menu.py @@ -100,7 +100,7 @@ def test_context_menu(ui_plugin: UIPlugin): ), ], ), - ("MenuGroupLabel", ["className:sx_b13742d240_c"], ['"View"']), + ('"div"', ["className:sx_b13742d240_c"], ['"View"']), ("MenuGroup", [], [("MenuItem", [item], ['"Zoom"'])]), ("MenuSeparator", ["className:sx_834f03d11d_c"], []), ( From 7971d9a4084e671b3871fb81e65581659ac878ed Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:49:56 +0000 Subject: [PATCH 197/204] Finish wave B: the keyboard place of a context menu, stubs, guide and shared app A context menu asked for from the keyboard opens beside its area, where UI SDK puts it. Regenerate the stubs and the differences of the migration guide, and hold the shared rx.ui app to the select trigger, the context menu and the hover card on UI SDK. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- docs/styling/rx-ui-migration.md | 18 +++-- .../parity/allowlist.toml | 6 ++ pyi_hashes.json | 16 ++-- .../tests_playwright/test_ui_components.py | 76 +++---------------- .../components/test_context_menu.py | 2 +- 5 files changed, 35 insertions(+), 83 deletions(-) diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index 9fd919a5a5f..1b555464723 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -198,8 +198,10 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### context_menu -- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.context_menu is placed itself, a native popover in the top layer: fixed, at a margin from what opens it by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. -- style, `pointer-events`: While it is open rx.context_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.context_menu is not modal: the page beside it keeps the pointer, and a press outside the menu closes it. And a disabled item of rx.ui.context_menu lets the pointer through, so a press on it chooses nothing without a script, where rx.context_menu hears the press and ignores it. +- behaviour, `rx.ui`, "opens from the keyboard on its first item": The arrow keys of rx.ui.context_menu stop on a disabled item, as the menu pattern of ARIA asks: UI SDK keeps it focusable, so that it is announced, and a choice of it does nothing. The arrow keys of rx.context_menu skip it. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a menu with a wrapper element it moves by a transform, and the menu inside it has no position, margins or bounds of its own; it is as tall as the room Radix measures. rx.ui.context_menu is placed itself, in the top layer: fixed, where UI SDK puts it beside the pointer, and no taller than the room UI SDK measures. It is drawn on the same pixels. +- style, `pointer-events`: While it is open rx.context_menu takes the pointer off the rest of the page with a style on the body, which what opens it inherits. rx.ui.context_menu sets no such style: a press outside the menu closes it. And the pointer passes through a disabled item of rx.ui.context_menu, which it does not highlight, where rx.context_menu hears the press and ignores it. +- pixels, *@keys: A context menu asked for from the keyboard, with Shift+F10 or the context-menu key, opens where rx.context_menu takes the browser's point for the key to be, the middle of the area. UI SDK opens the menu of rx.ui.context_menu beside the area instead, at its end and level with its top: the same menu, in another place. ### data_list @@ -251,20 +253,20 @@ counterpart, kept in sync with the parity checks of `rx.ui`: - behaviour, `rx.ui`, "Tab does not reach the links inside it": rx.hover_card takes what is inside the card out of the order of Tab: a keyboard user sees the card and cannot reach its links. The card of rx.ui.hover_card comes right after its trigger, so Tab moves into it and through its links, and the card stays open while the focus is inside it. - behaviour, `rx`, "the dark appearance of a theme around a hover card reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a hover card included. rx.ui.theme does, and a hover card declared inside a dark rx.ui.theme is dark. -- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a hover card with a wrapper element it moves by a transform, and the card inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.hover_card is placed itself, a native popover in the top layer: fixed, at a margin from its trigger by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a hover card with a wrapper element it moves by a transform, and the card inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.hover_card is placed itself, in the top layer: fixed, where UI SDK puts it beside its trigger, and no larger than the room UI SDK measures. It is drawn on the same pixels. - style, `height`: A hover card taller than the page grows past the bottom of the page in rx.hover_card. rx.ui.hover_card is no taller than the room the viewport leaves, and scrolls what it holds. ### popover - behaviour, `rx`, "what it holds is in the server render": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. - behaviour, `rx`, "opens and closes with JavaScript disabled": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. -- behaviour, `rx`, "its trigger names the popover it opens by the id it is given": The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link. The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it. +- behaviour, `rx`, "its trigger names the popover it opens by the id it is given": The trigger of rx.popover names its popover by an id rx.popover makes up, so giving the content an `id` breaks the link. The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the `id` the content is given. - behaviour, `rx.ui`, "Tab stays inside an open popover": rx.ui.popover is not modal: Tab moves through what it holds and on to the page after its trigger, and the focus leaving it closes it. rx.popover keeps the focus inside until it closes. - behaviour, `rx`, "the dark appearance of a theme around a popover reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a popover included. rx.ui.theme does, and a popover declared inside a dark rx.ui.theme is dark. - behaviour, `rx.ui`, "what it holds is in the server render": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. - behaviour, `rx.ui`, "opens and closes with JavaScript disabled": rx.popover and rx.ui.popover are opened by JavaScript: until the page has hydrated, a press on the trigger does nothing, and what the popover holds is rendered when it opens, so the page the server sends has only its trigger. - behaviour, `rx.ui`, "is a dialog its trigger says it opens": The trigger of rx.ui.popover says its state in `data-open` and `data-closed`, and the trigger of rx.popover in `data-state`; both say whether the popover is open in `aria-expanded`. -- behaviour, `rx.ui`, "its trigger names the popover it opens by the id it is given": The trigger of rx.ui.popover names its popover only while it is open (`aria-controls`), by the id UI SDK gives it, whatever `id` the content is given. The trigger of rx.popover names it by an id rx.popover makes up. +- behaviour, `rx.ui`, "its trigger names the popover it opens by the id it is given": The trigger of rx.ui.popover names its popover only while it is open: UI SDK sets its `aria-controls` when the popover opens, and then it is the `id` the content is given. The trigger of rx.popover names it while it is closed too, by an id rx.popover makes up. - style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a popover with a wrapper element it moves by a transform, and the popover inside it is positioned relatively, with no margins and no bounds of its own. rx.ui.popover is placed itself, in the top layer: fixed, where UI SDK puts it beside its trigger, and no taller than the room UI SDK measures. It is drawn on the same pixels. - style, `height`: A popover taller than the page grows past the bottom of the page in rx.popover. rx.ui.popover is no taller than the room the viewport leaves, and scrolls what it holds. @@ -357,8 +359,10 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### tooltip - behaviour, `rx`, "describes its button with JavaScript disabled": rx.tooltip renders its text when it opens, and names it as the description of its child only then. The text of rx.ui.tooltip is in the page from the start and always describes its child, so a screen reader reads it whether the tooltip is shown or not, with or without JavaScript; showing it under the pointer waits for JavaScript. -- behaviour, `rx.ui`, "points at its button with an arrow": rx.ui.tooltip has no arrow. It is where the tooltip of rx.tooltip is, the room of the arrow included, and is placed by the browser, which turns it over where it would leave the page: an arrow drawn by its styles could not follow it. `arrow_padding` has nothing to say. +- behaviour, `rx.ui`, "points at its button with an arrow": rx.ui.tooltip has no arrow. It is where the tooltip of rx.tooltip is, the room of the arrow included, and UI SDK places it and turns it over where it would leave the page; Radix Themes draws the arrow with an element of Radix that rx.ui does not render. `arrow_padding` has nothing to say. - behaviour, `rx`, "the dark appearance of a theme around a tooltip reaches it": rx.theme around part of a page does not take an appearance of its own: what is inside follows the color mode of the app, a tooltip included. rx.ui.theme does, and a tooltip declared inside a dark rx.ui.theme has the colors of the dark appearance. -- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a tooltip with a wrapper element it moves by a transform, and the tooltip inside it has no position, margins or bounds of its own. rx.ui.tooltip is placed itself, a native popover in the top layer: fixed, at a margin from what it describes by CSS anchor positioning, and no larger than the room the viewport leaves. It is drawn on the same pixels. +- behaviour, `rx.ui`, "a press on its button closes it": rx.ui.tooltip closes when a press on its button ends, where UI SDK hears the press. rx.tooltip closes as soon as the pointer goes down. +- behaviour, `rx.ui`, "a tooltip the pointer cannot rest on closes when it leaves the button": A tooltip of rx.ui.tooltip with `disable_hoverable_content` lets the pointer through, but UI SDK keeps it open while the pointer is over it, and closes it when the pointer leaves it. rx.tooltip closes it as soon as the pointer leaves the button. +- style, `position`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `max-height`, `max-width`: Radix places a tooltip with a wrapper element it moves by a transform, and the tooltip inside it has no position, margins or bounds of its own. rx.ui.tooltip is placed itself, in the top layer: fixed, where UI SDK puts it beside what it describes, and no larger than the room UI SDK measures. It is drawn on the same pixels. diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index a47ecae6cba..e320b746e16 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -902,3 +902,9 @@ reason = "rx.ui.tooltip closes when a press on its button ends, where UI SDK hea component = "tooltip" step = "a tooltip the pointer cannot rest on closes when it leaves the button" reason = "A tooltip of rx.ui.tooltip with `disable_hoverable_content` lets the pointer through, but UI SDK keeps it open while the pointer is over it, and closes it when the pointer leaves it. rx.tooltip closes it as soon as the pointer leaves the button." + +[[look]] +component = "context_menu" +check = "pixels" +cells = "*@keys" +reason = "A context menu asked for from the keyboard, with Shift+F10 or the context-menu key, opens where rx.context_menu takes the browser's point for the key to be, the middle of the area. UI SDK opens the menu of rx.ui.context_menu beside the area instead, at its end and level with its top: the same menu, in another place." diff --git a/pyi_hashes.json b/pyi_hashes.json index 86436ce7798..bdae421259d 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -121,11 +121,11 @@ "packages/reflex-components-ui/src/reflex_components_ui/__init__.pyi": "7adaf4068a85572198f646ae8009e51b", "packages/reflex-components-ui/src/reflex_components_ui/base.pyi": "80d9f33c5a73df61e18ee58f80b9f0e7", "packages/reflex-components-ui/src/reflex_components_ui/components/_cards.pyi": "2e639571eea0f8788a8186355444332a", - "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "5233a0a9b63e556c33ee473db5fafdbe", + "packages/reflex-components-ui/src/reflex_components_ui/components/_dialog.pyi": "c3dfb4f69cf5cb12eb5320fd788c23a4", "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "817a2b853123734c7e200bc54a55c47a", - "packages/reflex-components-ui/src/reflex_components_ui/components/_menu.pyi": "c243405a64e5dd76eef6bef0492ac75a", + "packages/reflex-components-ui/src/reflex_components_ui/components/_menu.pyi": "e15ed1f9c79ae63f275581338463ffd9", "packages/reflex-components-ui/src/reflex_components_ui/components/_popup.pyi": "80f094441cee591fff2e06d6e315dcc0", - "packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.pyi": "e5dbd83eb0448e016944c5937bee2b34", + "packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.pyi": "555998b790703a343fa967893b0f775f", "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "8116a4bc68a3d9607dfc44aa5f15dc22", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", @@ -138,16 +138,16 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_cards.pyi": "55446eddd45d81355eea0ada7370a6c3", "packages/reflex-components-ui/src/reflex_components_ui/components/checkbox_group.pyi": "63dc6c987c53e017e217e60f4686c4b9", "packages/reflex-components-ui/src/reflex_components_ui/components/color_mode.pyi": "b914252f1bc53816d7c5384faea6d2b5", - "packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.pyi": "79193f172cbb6feb749a296f82af9814", + "packages/reflex-components-ui/src/reflex_components_ui/components/context_menu.pyi": "17d3ab634dfca3802f30ab9adfac5218", "packages/reflex-components-ui/src/reflex_components_ui/components/data_list.pyi": "73ebbb9dcbe8630ef177e7a7de2565be", "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "841323f7bbdbc96b7646be3d89ef4dda", "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "bb3fcfaae77fb8388155a6df7ba55cb4", - "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "bf39517cc33ac99186bfd946aa1e6e3a", + "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "388ab56522100c0300a380b8d87fa07a", "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", - "packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.pyi": "866327d09399a8a3f632f93a36014ebb", + "packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.pyi": "3eb07ede3ba9e134d30b1ca0cf4f7ea8", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", - "packages/reflex-components-ui/src/reflex_components_ui/components/popover.pyi": "aa73f98a1067248acfd40992795ec9ac", + "packages/reflex-components-ui/src/reflex_components_ui/components/popover.pyi": "2e9fe5ee21528be9e4dbec77aabb1abb", "packages/reflex-components-ui/src/reflex_components_ui/components/progress.pyi": "ba32f562c590556d634f16062120fa34", "packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.pyi": "0a0f621c1ceed962d86896ad1600e98f", "packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.pyi": "e7f9c6ffd5f3d882ebe2fa4c06c0bcd0", @@ -164,7 +164,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/text_area.pyi": "85e3d7d2cf756b3a67683d9724b1a68b", "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "0493db3f24247140307bd4387444aac4", "packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.pyi": "8415abf97f4c226acc2f721278dca20f", - "packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.pyi": "e40ab12c01c4c79dd540aa7872596cd3", + "packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.pyi": "082353523ccccf169c362ed6cd684e65", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", "packages/reflex-components-ui/src/reflex_components_ui/layout/center.pyi": "a38424cf14313b5358c9ad198a7880f9", "packages/reflex-components-ui/src/reflex_components_ui/layout/container.pyi": "ecfbd513a1a12bbfc11a6d30e91987c6", diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index 6ba9a7af8e1..c6ad979c5fa 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -437,67 +437,6 @@ 'ault": 1, ":is(:disabled, :read-only)": 0.5}}} });' ), "const sx_345c25de08_c = stylex.props(sx_345c25de08.s).className;", - ( - 'const sx_872142009a = stylex.create({ s: {"appearance": "none", "marginT' - 'op": "0", "marginRight": "0", "marginBottom": "0", "marginLeft": "0", "p' - 'addingTop": "0", "paddingRight": "var(--space-3)", "paddingBottom": "0",' - ' "paddingLeft": "var(--space-3)", "borderTopWidth": "0", "borderRightWid' - 'th": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", "borderTopSt' - 'yle": "none", "borderRightStyle": "none", "borderBottomStyle": "none", "' - 'borderLeftStyle": "none", "backgroundColor": {"default": "var(--color-su' - 'rface)", ":disabled": "var(--gray-a2)"}, "backgroundImage": "none", "tex' - 'tTransform": "inherit", "textIndent": "initial", "wordSpacing": "inherit' - '", "cursor": {"default": "var(--cursor-button)", ":disabled": "var(--cur' - 'sor-disabled)"}, "WebkitTapHighlightColor": "transparent", "display": "i' - 'nline-flex", "alignItems": "center", "justifyContent": "space-between", ' - '"flexShrink": 0, "userSelect": "none", "verticalAlign": "top", "fontFami' - 'ly": "var(--default-font-family)", "fontWeight": "var(--font-weight-regu' - 'lar)", "fontStyle": "normal", "textAlign": "start", "outlineStyle": {"de' - 'fault": "none", ":focus-visible": "solid"}, "outlineWidth": {"default": ' - '"medium", ":focus-visible": "2px"}, "outlineColor": {"default": "current' - 'color", ":focus-visible": "var(--focus-8)"}, "outlineOffset": {"default"' - ': "0", ":focus-visible": "-1px"}, "--rx-select-icon-color": {":disabled"' - ': "var(--gray-a9)"}, "--select-trigger-height": "var(--space-6)", "gap":' - ' "calc(var(--space-1) * 1.5)", "fontSize": "var(--font-size-2)", "lineHe' - 'ight": "var(--line-height-2)", "letterSpacing": "var(--letter-spacing-2)' - '", "borderRadius": "max(var(--radius-2), var(--radius-full))", "boxSizin' - 'g": "border-box", "height": "var(--select-trigger-height)", "--rx-select' - '-shown-color": {"[data-placeholder]": "var(--gray-a10)"}, "color": {"def' - 'ault": "var(--gray-12)", ":disabled": "var(--gray-a11)"}, "boxShadow": {' - '"default": "inset 0 0 0 1px var(--gray-a7)", "@media (hover: hover)": {"' - ':hover:not(:disabled)": "inset 0 0 0 1px var(--gray-a8)"}, ":is([data-st' - "ate='open'], :has(+ :popover-open)):not(:disabled)\": \"inset 0 0 0 1px va" - 'r(--gray-a8)", ":disabled": "inset 0 0 0 1px var(--gray-a6)"}} });' - ), - "const sx_872142009a_c = stylex.props(sx_872142009a.s).className;", - ( - 'const sx_afbb711e7e = stylex.create({ s: {"display": "flex", "alignItems' - '": "center", "height": "var(--select-item-height)", "paddingLeft": "var(' - '--select-item-indicator-width)", "paddingRight": "var(--select-item-indi' - 'cator-width)", "userSelect": "none", "fontSize": "var(--rx-select-font-s' - 'ize)", "lineHeight": "var(--rx-select-line-height)", "letterSpacing": "v' - 'ar(--rx-select-letter-spacing)", "position": "relative", "boxSizing": "b' - 'order-box", "outlineStyle": "none", "scrollMarginTop": "var(--select-con' - 'tent-padding)", "scrollMarginBottom": "var(--select-content-padding)", "' - 'borderRadius": "var(--rx-select-item-radius)", "cursor": {"default": "va' - 'r(--cursor-menu-item)", "[aria-disabled=\'true\']": "default"}, "color": {' - '"default": "inherit", ":focus": "var(--rx-select-highlight-color, inheri' - 't)", "[aria-disabled=\'true\']": "var(--gray-a8)"}, "backgroundColor": {":' - 'focus": "var(--rx-select-highlight)"}, "--rx-select-check": {"default": ' - '"none", "[aria-selected=\'true\']": "inline-flex"}} });' - ), - "const sx_afbb711e7e_c = stylex.props(sx_afbb711e7e.s).className;", - ( - 'const sx_b72d7382fd = stylex.create({ s: {"position": "absolute", "width' - '": "1px", "height": "1px", "marginTop": "0", "marginRight": "0", "margin' - 'Bottom": "0", "marginLeft": "0", "paddingTop": "0", "paddingRight": "0",' - ' "paddingBottom": "0", "paddingLeft": "0", "borderTopWidth": "0", "borde' - 'rRightWidth": "0", "borderBottomWidth": "0", "borderLeftWidth": "0", "op' - 'acity": 0, "pointerEvents": "none"} });' - ), - "const sx_b72d7382fd_c = stylex.props(sx_b72d7382fd.s).className;", - 'const sx_71b84cd269 = stylex.create({ s: {"display": "contents"} });', - "const sx_71b84cd269_c = stylex.props(sx_71b84cd269.s).className;", 'const sx_5073704993 = stylex.create({ s: {"width": "100%"} });', "const sx_5073704993_c = stylex.props(sx_5073704993.s).className;", ] @@ -2055,8 +1994,8 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): expect(page.get_by_role("dialog")).to_have_count(0) expect(page.get_by_role("button", name="bob")).to_be_focused() - # The popovers of a list share the id they are rendered with: the script - # of a popup tells them apart, and each close button closes its own. + # The popovers of a list share the id they are rendered with: UI SDK tells + # them apart, and each close button closes its own. page.get_by_role("button", name="About dye").click() shown = page.locator(":popover-open") expect(shown).to_have_text("All about dyeGot it") @@ -2088,8 +2027,8 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): expect(account.get_by_text("Five.")).to_be_visible() expect(account.locator("details[open]")).to_have_count(1) - # The menus of a list share the ids they are rendered with: the script of - # a menu tells them apart, and places each sub-menu beside its item. + # The menus of a list share the ids they are rendered with: UI SDK tells + # them apart, and places each sub-menu beside its item. page.get_by_role("button", name="Menu jet").click() menu = page.get_by_role("menu") expect(menu).to_have_count(1) @@ -2101,7 +2040,8 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): page.keyboard.press("Escape") expect(page.get_by_role("menu")).to_have_count(0) - # A context menu opens at the pointer, and its checkbox item is checked. + # A context menu opens at the pointer, and its checkbox item is checked; + # choosing it closes the menu, as in Radix. page.locator("#canvas").click(button="right") snap = page.get_by_role("menuitemcheckbox", name="Snap") expect(snap).to_have_attribute("aria-checked", "true") @@ -2113,7 +2053,9 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): # A hover card opens under the pointer. page.get_by_role("link", name="Author").hover() - expect(page.locator(":popover-open")).to_have_text("Writes things") + expect(page.locator("[data-slot=hover-card-content][data-open]")).to_have_text( + "Writes things" + ) def _panel_probe(page: Page) -> list[str]: diff --git a/tests/units/reflex_components_ui/components/test_context_menu.py b/tests/units/reflex_components_ui/components/test_context_menu.py index 8a085d7aa15..57f0b676caa 100644 --- a/tests/units/reflex_components_ui/components/test_context_menu.py +++ b/tests/units/reflex_components_ui/components/test_context_menu.py @@ -59,7 +59,7 @@ def test_context_menu(ui_plugin: UIPlugin): dir="rtl", ) item = "className:sx_5c93cdaf19_c" - value = component.children[1].children[0].children[0].children[1]._key + value = component.children[1].children[0].children[0].children[1]._key # pyright: ignore[reportAttributeAccessIssue] assert tree(component.render()) == ( "Menu", ["loop:false", "modal:false"], From b130e333f0dd6b16eca1f347043e6c956b0e8399 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 17:57:18 +0000 Subject: [PATCH 198/204] rx.ui on UI SDK, wave C: accordion, slider and segmented_control The accordion is the parts of @ui-sdk/react/accordion: a heading around a button, a panel UI SDK mounts while it is open; a single accordion keeps its open item open unless it is collapsible, and Tab passes the trigger of a disabled item, as in Radix. The slider is UI SDK's, its thumbs travelling as far as Radix Themes'. The segmented control is UI SDK's, its arrow keys moving the focus without choosing and Enter, Home and End doing what they do in Radix; what marks the chosen item is placed by CSS before the page hydrates. The accordion, slider and roving-focus scripts are gone; the radio group and radio cards stay native. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- docs/styling/rx-ui-migration.md | 16 +- packages/reflex-components-ui/js/src/base.css | 27 +- .../js/src/behaviors/accordion.js | 46 - .../js/src/behaviors/roving-focus.js | 59 - .../js/src/behaviors/slider.js | 121 -- .../js/tests/behaviors/accordion.test.js | 103 -- .../js/tests/behaviors/roving-focus.test.js | 180 --- .../js/tests/behaviors/slider.test.js | 181 --- .../parity/allowlist.toml | 78 +- .../parity/ui_parity/components/accordion.py | 25 +- .../ui_parity/components/context_menu.py | 6 +- .../ui_parity/components/segmented_control.py | 33 +- .../parity/ui_parity/components/slider.py | 17 +- .../components/accordion.py | 394 ++---- .../components/segmented_control.py | 172 ++- .../reflex_components_ui/components/slider.py | 267 ++-- .../reflex_components_ui/styles/accordion.py | 37 +- .../styles/segmented_control.py | 53 +- .../src/reflex_components_ui/styles/slider.py | 150 +-- pyi_hashes.json | 6 +- .../tests_playwright/test_ui_components.py | 15 +- .../components/test_accordion.py | 866 +++---------- .../components/test_segmented_control.py | 608 +++------ .../components/test_slider.py | 1121 +++-------------- 24 files changed, 983 insertions(+), 3598 deletions(-) delete mode 100644 packages/reflex-components-ui/js/src/behaviors/accordion.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/roving-focus.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/slider.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/accordion.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/slider.test.js diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index 1b555464723..53ce736926d 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -140,12 +140,9 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### accordion -- behaviour, `rx`, "opens and closes an item with JavaScript disabled": rx.accordion is opened by JavaScript: until it has run, a press on a header does nothing. An item of rx.ui.accordion is a native `details`, which the browser opens and closes with or without JavaScript, one at a time when the accordion is `type="single"`; only an open item of an accordion that is not `collapsible` needs JavaScript to stay open when it is pressed. +- behaviour, `rx.ui`, "opens and closes an item with JavaScript disabled": rx.accordion and rx.ui.accordion are opened by JavaScript: until the page has hydrated, a press on a header does nothing. - behaviour, `rx.ui`, "the arrow keys, Home and End move between the headers": The headers of rx.ui.accordion are native `summary` elements: Tab and Shift+Tab move between them, as between the headers of any `details`, and Enter and Space open and close an item. rx.accordion also moves between its headers with the arrow keys, Home and End, and `orientation` says which arrow keys do. -- behaviour, `rx.ui`, "hands over the open items in the order they were opened in": `on_value_change` of an rx.ui.accordion of `type="multiple"` hands over the values of the open items in the order of the items, whatever the order they were opened in: the accordion keeps no state of its own and reads its items. rx.accordion appends each value as it is opened. -- a11y, *: An item of rx.ui.accordion is a native `details`: its header is the `summary`, which holds the heading and says by itself whether the item is open, where the header of rx.accordion is a heading that holds a button with `aria-expanded`. A screen reader announces both as a heading that expands and collapses. -- style, `outline-style`, `outline-width`, `outline-color`: The ring of the keyboard's focus is drawn by the browser around the `summary` of the item, which is what takes the focus in rx.ui.accordion, and around the button inside the heading in rx.accordion. It is the same ring in the same place. -- style, `pointer-events`: The header of a disabled item of rx.ui.accordion lets the pointer through, so the item cannot be opened with or without JavaScript. rx.accordion disables the button of the header. +- behaviour, `rx`, "opens and closes an item with JavaScript disabled": rx.accordion and rx.ui.accordion are opened by JavaScript: until the page has hydrated, a press on a header does nothing. ### alert_dialog @@ -295,8 +292,8 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### segmented_control -- behaviour, `rx`, "chooses an item with JavaScript disabled": The items of rx.segmented_control are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. An item of rx.ui.segmented_control is a label around a native radio button, which the browser checks with or without JavaScript. -- a11y, *: An item of rx.ui.segmented_control is a label around a native radio button: what the item holds names the radio button, as in rx.segmented_control, and is also text of the page, as the text of any label is. An item of rx.segmented_control is one button that holds its text. +- behaviour, `rx.ui`, "chooses an item with JavaScript disabled": The items of rx.segmented_control and rx.ui.segmented_control are buttons that JavaScript makes radio buttons: until the page has hydrated, a click does nothing. +- behaviour, `rx`, "chooses an item with JavaScript disabled": The items of rx.segmented_control and rx.ui.segmented_control are buttons that JavaScript makes radio buttons: until the page has hydrated, a click does nothing. ### select @@ -313,9 +310,12 @@ counterpart, kept in sync with the parity checks of `rx.ui`: - behaviour, `rx`, "moves with the keyboard with JavaScript disabled": rx.slider is drawn and moved by JavaScript: until it has run, its thumb takes no focus and no key. The thumbs of rx.ui.slider are native range inputs, which the keyboard and the pointer move with or without JavaScript; only the filled part of the track waits for it. - behaviour, `rx`, "the thumb of a slider has the name the slider is given": An `aria_label` of rx.slider names the element around its thumb, so the thumb, which is what a screen reader lands on, has no name. rx.ui.slider gives the label to the thumb. -- behaviour, `rx.ui`, "Shift and an arrow key move a thumb by ten steps": The thumbs of rx.ui.slider are native range inputs: the browser moves one by one step for an arrow key, with or without Shift, and by ten for Page Up and Page Down, as rx.slider does for those. - behaviour, `rx.ui`, "a thumb can be moved past the one after it": A thumb of rx.ui.slider stops at the thumbs beside it, where a thumb of rx.slider passes them and the two change places. Home and End move the thumb that has the focus, where rx.slider moves the first and the last whichever has it. - a11y, *: A thumb of rx.ui.slider is a native range input, which says its value to the accessibility tree as every such input does. A thumb of rx.slider has its value in `aria-valuenow` alone. +- style, `width`: UI SDK gives the filled part of the track of rx.ui.slider a width, a share of the track, where rx.slider sets where it ends; the browser rounds the two to a 64th of a pixel apart, so the fill of rx.ui.slider may end a 64th of a pixel sooner. +- pixels, *size-1*: UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. A thumb of size 1 is drawn 13 pixels wide, an odd number, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise. +- pixels, *size-3*: UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. A thumb of size 3 is drawn 19 pixels wide, an odd number, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise. +- pixels, size-responsive*: UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. The responsive slider is of size 1 or 3 at these widths, whose thumbs are an odd number of pixels wide, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise. ### switch diff --git a/packages/reflex-components-ui/js/src/base.css b/packages/reflex-components-ui/js/src/base.css index 0851a6ad885..9fb15f54212 100644 --- a/packages/reflex-components-ui/js/src/base.css +++ b/packages/reflex-components-ui/js/src/base.css @@ -106,10 +106,12 @@ html.dark { * The line before an item of a segmented control is not shown before the * first item, nor on either side of the chosen one or of the one the * keyboard is on: the item before another is no state of that other. + * UI SDK puts the radio button of a form after each item. */ - [data-rx-segmented-item]:first-child, - [data-rx-segmented-item]:is(:has(> input:checked), :has(> input:focus-visible)), - [data-rx-segmented-item]:is(:has(> input:checked), :has(> input:focus-visible)) + [data-rx-segmented-item]:first-of-type, + [data-rx-segmented-item]:is([data-checked], :focus-visible), + [data-rx-segmented-item]:is([data-checked], :focus-visible) + + input + [data-rx-segmented-item] { --rx-segmented-separator-opacity: 0; --rx-segmented-separator-easing: ease-in; @@ -140,29 +142,12 @@ html.dark { /* * The icon of an item of an accordion is turned over while the item is - * open, and its panel grows and shrinks where the browser can animate the - * height of what a `details` holds, for whoever has not asked for less - * motion. The accordion says how long it takes. + * open. The accordion says how long it takes. */ [data-rx-accordion-icon] { transform: var(--rx-accordion-turn, none); transition: transform var(--animation-duration) var(--animation-easing); } - @media (prefers-reduced-motion: no-preference) { - [data-rx-accordion-item] { - interpolate-size: allow-keywords; - } - [data-rx-accordion-item]::details-content { - height: 0; - overflow: hidden; - transition: - height var(--animation-duration) var(--animation-easing), - content-visibility var(--animation-duration) allow-discrete; - } - [data-rx-accordion-item][open]::details-content { - height: auto; - } - } /* The thumb of the scrollbar of a text area, under the pointer. */ @media (hover: hover) { diff --git a/packages/reflex-components-ui/js/src/behaviors/accordion.js b/packages/reflex-components-ui/js/src/behaviors/accordion.js deleted file mode 100644 index c8c1fc52bf2..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/accordion.js +++ /dev/null @@ -1,46 +0,0 @@ -// What an accordion does that the browser leaves to a script. -// -// An item is a native `details`: the browser opens and closes it with a -// press, Enter and Space, and closes the others of its name. Left for a -// script: an open item that stays open when it is pressed, as in Radix -// unless the accordion is collapsible, saying which items are open, and an -// accordion bound to state, which shows what its state holds. Without this -// every item opens and closes. - -/** - * Follow a press on the header of an item: the `onClick` of the element - * around an accordion. - * - * @param {{ target: EventTarget | null, currentTarget: HTMLElement, preventDefault: () => void }} event - * The press, before the browser opens or closes the item. - * @param {(value: string | string[]) => void} [onValueChange] What the - * accordion does when its open items change. - * @returns {void} - */ -export function accordionClick(event, onValueChange) { - const root = event.currentTarget; - const item = - event.target instanceof Element - ? event.target.closest("summary")?.parentElement - : null; - if (!(item instanceof HTMLDetailsElement) || item.parentElement !== root) - return; - const { rxAccordion, collapsible, bound } = root.dataset; - const single = rxAccordion === "single"; - if (single && item.open && collapsible !== "true") { - event.preventDefault(); - return; - } - if (bound !== undefined) event.preventDefault(); - if (!onValueChange) return; - const value = item.dataset.value ?? ""; - onValueChange( - single - ? item.open - ? "" - : value - : /** @type {HTMLDetailsElement[]} */ ([...root.children]) - .filter((other) => other.open !== (other === item)) - .map((other) => other.dataset.value ?? ""), - ); -} diff --git a/packages/reflex-components-ui/js/src/behaviors/roving-focus.js b/packages/reflex-components-ui/js/src/behaviors/roving-focus.js deleted file mode 100644 index e7f79de8d30..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/roving-focus.js +++ /dev/null @@ -1,59 +0,0 @@ -// The arrow keys of a group that is one stop for Tab: they move the focus -// between its items, as in Radix, without choosing one. -// -// The items are the native radio buttons of a group, which the browser -// moves between with the arrow keys by itself, choosing each one it passes: -// without this the group works that way. Or they are the triggers of tabs, -// which are buttons the browser does not move between. - -const RADIO = "input[type=radio]"; - -/** - * Move the focus through the items of a group: the `onKeyDown` of the group. - * - * The arrow keys go to the item before and after, around the ends unless - * the group says `data-loop="false"`, Home and End to the first and the - * last, and Enter chooses the radio button the focus is on, as Space does - * by itself. The direction of the text turns left and right, and a group - * with an `aria-orientation` only hears the arrow keys along it. - * - * @param {{ key: string, target: EventTarget | null, currentTarget: HTMLElement, preventDefault: () => void, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean, shiftKey?: boolean }} event - * The key going down on an item. - * @returns {void} - */ -export function rovingKeyDown(event) { - const { key, target, currentTarget } = event; - if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; - if (!(target instanceof HTMLElement)) return; - const item = [RADIO, "[role=tab]"].find((kind) => target.matches(kind)); - if (!item) return; - if (key === "Enter") { - if (item === RADIO) { - event.preventDefault(); - target.click(); - } - return; - } - const items = /** @type {HTMLElement[]} */ ([ - ...currentTarget.querySelectorAll(`${item}:not(:disabled)`), - ]); - const count = items.length; - let index = items.indexOf(target); - if (key === "Home") index = 0; - else if (key === "End") index = count - 1; - else if (key.startsWith("Arrow")) { - const across = /Up|Down/.test(key); - const orientation = currentTarget.ariaOrientation; - if (orientation && across === (orientation === "horizontal")) return; - const back = - /Up|Left/.test(key) !== - (!across && getComputedStyle(currentTarget).direction === "rtl"); - index += back ? -1 : 1; - index = - currentTarget.dataset.loop === "false" - ? Math.max(0, Math.min(index, count - 1)) - : (index + count) % count; - } else return; - event.preventDefault(); - items[index]?.focus(); -} diff --git a/packages/reflex-components-ui/js/src/behaviors/slider.js b/packages/reflex-components-ui/js/src/behaviors/slider.js deleted file mode 100644 index 02edf44ee14..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/slider.js +++ /dev/null @@ -1,121 +0,0 @@ -// What a slider draws of the values of its native range inputs: the part -// of its track between them, and for a slider with several thumbs the order -// they keep and the thumb a pointer on the track moves. -// -// The thumbs are the ones of the inputs, which the browser moves, reads to -// the accessibility tree and submits with a form by itself. Without this -// the filled part of the track stays where the server drew it. - -/** - * Find the inputs of a slider. - * - * @param {Element} slider The slider. - * @returns {HTMLInputElement[]} Its range inputs, in the order of its thumbs. - */ -function thumbs(slider) { - return /** @type {HTMLInputElement[]} */ ([ - ...slider.querySelectorAll("input"), - ]); -} - -/** - * Say how far along its track the value of an input is. - * - * @param {HTMLInputElement} input A range input. - * @returns {string} The share of the track, as a percentage. - */ -function share(input) { - const min = Number(input.min || 0); - const max = Number(input.max || 100); - return `${max > min ? ((input.valueAsNumber - min) / (max - min)) * 100 : 0}%`; -} - -/** - * Give an input a value as a user does, so that React hears of it. - * - * @param {HTMLInputElement} input The input. - * @param {number} value The value. - * @returns {void} - */ -function assign(input, value) { - const setter = - /** @type {(this: HTMLInputElement, value: string) => void} */ ( - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set - ); - setter.call(input, String(value)); - input.dispatchEvent(new Event("input", { bubbles: true })); -} - -/** - * Follow a thumb that moves: the `onInput` of a slider. - * - * A thumb stops at the ones beside it, and the filled part of the track is - * drawn from the first thumb to the last, or from the start of the track to - * the only one. - * - * @param {{ target: EventTarget | null, currentTarget: HTMLElement }} event - * The input of one of the thumbs. - * @returns {void} - */ -export function slide(event) { - const slider = event.currentTarget; - const inputs = thumbs(slider); - const index = inputs.indexOf(/** @type {HTMLInputElement} */ (event.target)); - if (index < 0) return; - const moved = inputs[index]; - const low = inputs[index - 1]?.valueAsNumber ?? -Infinity; - const high = inputs[index + 1]?.valueAsNumber ?? Infinity; - const kept = Math.min(Math.max(moved.valueAsNumber, low), high); - if (kept !== moved.valueAsNumber) moved.value = String(kept); - slider.style.setProperty( - "--rx-slider-start", - inputs.length > 1 ? share(inputs[0]) : "0%", - ); - slider.style.setProperty("--rx-slider-end", share(inputs[inputs.length - 1])); -} - -/** - * Move the nearest thumb of a slider with several to a pointer on its - * track: the `onMouseDown` of such a slider. - * - * The browser does it for a slider with one thumb. With several, each - * input lets the pointer through to the ones below it, but for its thumb. - * The thumb that moves takes the focus, which the pointer leaves it. - * - * @param {{ target: EventTarget | null, currentTarget: HTMLElement, clientX: number, clientY: number, preventDefault: () => void }} event - * The pointer going down on the slider. - * @returns {void} - */ -export function press(event) { - const slider = event.currentTarget; - const inputs = thumbs(slider); - const first = inputs[0]; - if ( - inputs.length < 2 || - event.target instanceof HTMLInputElement || - first.disabled - ) - return; - const box = slider.getBoundingClientRect(); - const vertical = slider.dataset.orientation === "vertical"; - const along = vertical - ? (box.bottom - event.clientY) / box.height - : (event.clientX - box.left) / box.width; - const min = Number(first.min || 0); - const max = Number(first.max || 100); - const step = Number(first.step || 1); - const reached = min + Math.min(Math.max(along, 0), 1) * (max - min); - const value = Math.min(max, min + Math.round((reached - min) / step) * step); - let nearest = first; - for (const input of inputs) { - if ( - Math.abs(input.valueAsNumber - value) < - Math.abs(nearest.valueAsNumber - value) - ) { - nearest = input; - } - } - event.preventDefault(); - nearest.focus(); - assign(nearest, value); -} diff --git a/packages/reflex-components-ui/js/tests/behaviors/accordion.test.js b/packages/reflex-components-ui/js/tests/behaviors/accordion.test.js deleted file mode 100644 index 7f2d58514cc..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/accordion.test.js +++ /dev/null @@ -1,103 +0,0 @@ -// What an accordion does with a press on a header that the browser does -// not: an open item stays open, a change is said, and an accordion bound to -// state waits for its state. -import { beforeEach, expect, test, vi } from "vitest"; - -import { accordionClick } from "$/reflex-ui/behaviors/accordion.js"; - -/** @type {HTMLElement} */ -let root; - -/** - * Render an accordion of three items, the first of them open, with an - * accordion of its own in its panel. - * - * @param {string} attributes The attributes of the element around it. - * @returns {void} - */ -function render(attributes) { - document.body.innerHTML = ` -
-
-

A

-
-
-
Inner
-
- -
-
-
B
-
C
-
`; - root = /** @type {HTMLElement} */ (document.getElementById("root")); -} - -beforeEach(() => render('data-rx-accordion="single"')); - -/** - * Press an element of the accordion. - * - * @param {string | null} id The id of the element, or null for no element. - * @param {(value: string | string[]) => void} [onValueChange] What the - * accordion does when its open items change. - * @returns {boolean} Whether the accordion kept the press from the browser. - */ -function press(id, onValueChange) { - let prevented = false; - accordionClick( - { - target: id ? document.getElementById(id) : null, - currentTarget: root, - preventDefault: () => { - prevented = true; - }, - }, - onValueChange, - ); - return prevented; -} - -test("the open item of an accordion that does not collapse stays open", () => { - const onValueChange = vi.fn(); - expect(press("a", onValueChange)).toBe(true); - expect(press("a-text", onValueChange)).toBe(true); - expect(onValueChange.mock.calls).toEqual([]); - expect(press("b", onValueChange)).toBe(false); - expect(onValueChange.mock.calls).toEqual([["b"]]); -}); - -test("a collapsible accordion closes its open item, and says that none is open", () => { - render('data-rx-accordion="single" data-collapsible="true"'); - const onValueChange = vi.fn(); - expect(press("a", onValueChange)).toBe(false); - expect(press("c", onValueChange)).toBe(false); - expect(press("b")).toBe(false); - expect(onValueChange.mock.calls).toEqual([[""], [""]]); -}); - -test("an accordion of several says which items are open after the press", () => { - render('data-rx-accordion="multiple"'); - const onValueChange = vi.fn(); - expect(press("b", onValueChange)).toBe(false); - expect(press("a", onValueChange)).toBe(false); - expect(press("c", onValueChange)).toBe(false); - expect(onValueChange.mock.calls).toEqual([[["a", "b"]], [[]], [["a", ""]]]); -}); - -test("an accordion bound to state leaves its items to its state", () => { - render('data-rx-accordion="multiple" data-bound=""'); - const onValueChange = vi.fn(); - expect(press("b", onValueChange)).toBe(true); - expect(press("b")).toBe(true); - expect(onValueChange.mock.calls).toEqual([[["a", "b"]]]); -}); - -test("a press on anything but a header of the accordion is left alone", () => { - const onValueChange = vi.fn(); - expect(press("inside", onValueChange)).toBe(false); - expect(press("inner", onValueChange)).toBe(false); - expect(press("root", onValueChange)).toBe(false); - expect(press(null, onValueChange)).toBe(false); - expect(onValueChange.mock.calls).toEqual([]); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js b/packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js deleted file mode 100644 index 37c98b1e5a1..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/roving-focus.test.js +++ /dev/null @@ -1,180 +0,0 @@ -// The keys of a group that is one stop for Tab: the arrow keys, Home and End -// move the focus between its radio buttons without choosing one, and Enter -// chooses. The triggers of tabs move the same way, along their list. -import { beforeEach, expect, test } from "vitest"; - -import { rovingKeyDown } from "$/reflex-ui/behaviors/roving-focus.js"; - -/** @type {HTMLElement} */ -let group; - -beforeEach(() => { - document.body.innerHTML = ` -
- - - - - -
`; - group = /** @type {HTMLElement} */ (document.getElementById("group")); -}); - -/** - * Find a radio button of the group. - * - * @param {string} value Its value. - * @returns {HTMLInputElement} The radio button. - */ -function radio(value) { - return /** @type {HTMLInputElement} */ ( - group.querySelector(`[value=${value}]`) - ); -} - -/** - * Press a key on whatever has the focus. - * - * @param {string} key The key. - * @param {Record} [modifiers] The modifiers held with it. - * @returns {boolean} Whether the group kept the key from the browser. - */ -function press(key, modifiers = {}) { - let prevented = false; - rovingKeyDown({ - key, - target: document.activeElement, - currentTarget: group, - preventDefault: () => { - prevented = true; - }, - ...modifiers, - }); - return prevented; -} - -/** - * Read which radio button has the focus. - * - * @returns {string} Its value. - */ -function focused() { - return /** @type {HTMLInputElement} */ (document.activeElement).value; -} - -test("the arrow keys move the focus past a disabled item and around the ends", () => { - radio("a").focus(); - const visited = []; - for (const key of [ - "ArrowRight", - "ArrowDown", - "ArrowRight", - "ArrowLeft", - "ArrowUp", - ]) { - expect(press(key)).toBe(true); - visited.push(focused()); - } - expect(visited).toEqual(["c", "d", "a", "d", "c"]); - expect(group.querySelectorAll(":checked").length).toBe(0); -}); - -test("Home and End go to the first and the last item", () => { - radio("c").focus(); - expect(press("End")).toBe(true); - expect(focused()).toBe("d"); - expect(press("Home")).toBe(true); - expect(focused()).toBe("a"); -}); - -test("Enter chooses the item the focus is on", () => { - radio("c").focus(); - expect(press("Enter")).toBe(true); - expect(radio("c").checked).toBe(true); - expect(focused()).toBe("c"); -}); - -test("left and right are turned where the text runs from the right", () => { - group.style.direction = "rtl"; - radio("c").focus(); - press("ArrowRight"); - expect(focused()).toBe("a"); - press("ArrowLeft"); - expect(focused()).toBe("c"); - press("ArrowDown"); - expect(focused()).toBe("d"); -}); - -test("other keys, keys with a modifier and other controls are left to the browser", () => { - radio("a").focus(); - expect(press("a")).toBe(false); - expect(press(" ")).toBe(false); - expect(press("Tab")).toBe(false); - for (const modifier of ["altKey", "ctrlKey", "metaKey", "shiftKey"]) { - expect(press("ArrowRight", { [modifier]: true })).toBe(false); - } - expect(focused()).toBe("a"); - /** @type {HTMLElement} */ (document.getElementById("text")).focus(); - expect(press("ArrowRight")).toBe(false); - expect(press("Enter")).toBe(false); - expect(document.activeElement?.id).toBe("text"); -}); - -/** - * Render a list of tabs in place of the group. - * - * @param {string} [attributes] The attributes of the list. - * @returns {void} - */ -function tabs(attributes = "") { - document.body.innerHTML = ` -
- - - - -
`; - group = /** @type {HTMLElement} */ (document.getElementById("group")); -} - -test("the triggers of tabs move along a horizontal list, and Enter is theirs", () => { - tabs('aria-orientation="horizontal"'); - radio("a").focus(); - expect(press("ArrowDown")).toBe(false); - expect(press("ArrowUp")).toBe(false); - expect(press("Enter")).toBe(false); - expect(focused()).toBe("a"); - expect(press("ArrowRight")).toBe(true); - expect(focused()).toBe("c"); - expect(press("ArrowRight")).toBe(true); - expect(focused()).toBe("a"); - expect(press("End")).toBe(true); - expect(focused()).toBe("c"); - /** @type {HTMLElement} */ (document.getElementById("other")).focus(); - expect(press("ArrowRight")).toBe(false); - expect(document.activeElement?.id).toBe("other"); -}); - -test("the triggers of vertical tabs move with up and down alone", () => { - tabs('aria-orientation="vertical" dir="rtl" style="direction: rtl"'); - radio("a").focus(); - expect(press("ArrowRight")).toBe(false); - expect(press("ArrowLeft")).toBe(false); - expect(focused()).toBe("a"); - expect(press("ArrowDown")).toBe(true); - expect(focused()).toBe("c"); - expect(press("ArrowUp")).toBe(true); - expect(focused()).toBe("a"); -}); - -test("a list that does not loop stops at its ends", () => { - tabs('data-loop="false"'); - radio("a").focus(); - expect(press("ArrowLeft")).toBe(true); - expect(focused()).toBe("a"); - expect(press("ArrowUp")).toBe(true); - expect(focused()).toBe("a"); - expect(press("ArrowRight")).toBe(true); - expect(press("ArrowDown")).toBe(true); - expect(focused()).toBe("c"); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/slider.test.js b/packages/reflex-components-ui/js/tests/behaviors/slider.test.js deleted file mode 100644 index e11c0ada11f..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/slider.test.js +++ /dev/null @@ -1,181 +0,0 @@ -// What a slider draws of its range inputs: the filled part of its track, -// the order of several thumbs, and the thumb a pointer on the track moves. -import { beforeEach, expect, test } from "vitest"; - -import { press, slide } from "$/reflex-ui/behaviors/slider.js"; - -/** - * Build a slider. - * - * @param {number[]} values The value of each thumb. - * @param {string} [attributes] Further attributes of each input. - * @returns {HTMLElement} The slider. - */ -function slider(values, attributes = "") { - document.body.innerHTML = `${values - .map((value) => ``) - .join("")}`; - const element = /** @type {HTMLElement} */ ( - document.getElementById("slider") - ); - // jsdom lays nothing out: the track is 200 pixels long, from 100. - element.getBoundingClientRect = () => - /** @type {DOMRect} */ ({ - left: 100, - width: 200, - bottom: 300, - height: 200, - }); - return element; -} - -/** - * Read where the filled part of the track of a slider starts and ends. - * - * @param {HTMLElement} element The slider. - * @returns {string[]} The two custom properties. - */ -function filled(element) { - return ["--rx-slider-start", "--rx-slider-end"].map((name) => - element.style.getPropertyValue(name), - ); -} - -/** - * Read the values of the thumbs of a slider. - * - * @param {HTMLElement} element The slider. - * @returns {number[]} The value of each thumb. - */ -function values(element) { - return [...element.querySelectorAll("input")].map( - (input) => input.valueAsNumber, - ); -} - -/** - * Move a thumb as a user does. - * - * @param {HTMLElement} element The slider. - * @param {number} index Which thumb. - * @param {number} value Where to. - * @returns {void} - */ -function move(element, index, value) { - const input = element.querySelectorAll("input")[index]; - input.value = String(value); - slide({ target: input, currentTarget: element }); -} - -/** - * Put the pointer down on the track of a slider. - * - * @param {HTMLElement} element The slider. - * @param {{ clientX?: number, clientY?: number, target?: EventTarget }} at Where. - * @returns {boolean} Whether the slider kept the pointer from the browser. - */ -function pointer(element, at) { - let prevented = false; - press({ - target: element, - currentTarget: element, - clientX: 0, - clientY: 0, - preventDefault: () => { - prevented = true; - }, - ...at, - }); - return prevented; -} - -beforeEach(() => { - document.body.innerHTML = ""; -}); - -test("the track is filled from its start to the only thumb", () => { - const element = slider([30]); - move(element, 0, 45); - expect(filled(element)).toEqual(["0%", "45%"]); -}); - -test("the share of the track follows the range of the slider", () => { - const element = slider([20], 'min="10" max="50"'); - move(element, 0, 30); - expect(filled(element)).toEqual(["0%", "50%"]); - const flat = slider([5], 'min="5" max="5"'); - move(flat, 0, 5); - expect(filled(flat)).toEqual(["0%", "0%"]); -}); - -test("with several thumbs the track is filled from the first to the last", () => { - const element = slider([20, 60, 90]); - move(element, 1, 70); - expect(filled(element)).toEqual(["20%", "90%"]); - move(element, 0, 10); - expect(filled(element)).toEqual(["10%", "90%"]); -}); - -test("a thumb stops at the thumbs beside it", () => { - const element = slider([20, 60, 90]); - move(element, 0, 75); - expect(values(element)).toEqual([60, 60, 90]); - move(element, 2, 10); - expect(values(element)).toEqual([60, 60, 60]); - move(element, 1, 100); - expect(values(element)).toEqual([60, 60, 60]); - expect(filled(element)).toEqual(["60%", "60%"]); -}); - -test("what is no thumb of the slider moves nothing", () => { - const element = slider([20, 60]); - slide({ target: document.body, currentTarget: element }); - expect(filled(element)).toEqual(["", ""]); -}); - -test("a pointer on the track moves the nearest thumb there and gives it the focus", () => { - const element = slider([20, 60]); - /** @type {number[][]} */ - const heard = []; - element.addEventListener("input", () => heard.push(values(element))); - expect(pointer(element, { clientX: 250 })).toBe(true); - expect(values(element)).toEqual([20, 75]); - expect(document.activeElement).toBe(element.querySelectorAll("input")[1]); - expect(pointer(element, { clientX: 110 })).toBe(true); - expect(values(element)).toEqual([5, 75]); - expect(heard).toEqual([ - [20, 75], - [5, 75], - ]); -}); - -test("a pointer past the ends of the track goes to its ends, by the step", () => { - const element = slider([2, 6], 'min="0" max="10" step="4"'); - pointer(element, { clientX: 1000 }); - expect(values(element)).toEqual([2, 10]); - const stepped = slider([0, 8], 'min="0" max="10" step="4"'); - pointer(stepped, { clientX: 100 + 200 * 0.45 }); - expect(values(stepped)).toEqual([4, 8]); - pointer(stepped, { clientX: -50 }); - expect(values(stepped)).toEqual([0, 8]); -}); - -test("a vertical slider is read from the bottom up", () => { - const element = slider([20, 60]); - element.dataset.orientation = "vertical"; - pointer(element, { clientY: 300 - 200 * 0.9 }); - expect(values(element)).toEqual([20, 90]); -}); - -test("one thumb, a thumb under the pointer and a disabled slider are left to the browser", () => { - const one = slider([20]); - expect(pointer(one, { clientX: 250 })).toBe(false); - expect(values(one)).toEqual([20]); - const two = slider([20, 60]); - expect( - pointer(two, { clientX: 250, target: two.querySelector("input") ?? two }), - ).toBe(false); - const off = slider([20, 60], "disabled"); - expect(pointer(off, { clientX: 250 })).toBe(false); - expect(values(off)).toEqual([20, 60]); -}); diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index e320b746e16..febec7643e3 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -273,17 +273,10 @@ component = "checkbox_cards" step = "hands over the checked values in the order they were checked in" reason = "`on_value_change` of rx.ui.checkbox_cards hands over the values of the checked cards in the order of the cards, whatever the order they were checked in: the group keeps no state of its own and reads its checkboxes. rx.checkbox_cards appends each value as it is checked." -[[look]] -component = "segmented_control" -check = "a11y" -reason = "An item of rx.ui.segmented_control is a label around a native radio button: what the item holds names the radio button, as in rx.segmented_control, and is also text of the page, as the text of any label is. An item of rx.segmented_control is one button that holds its text." - [[contract]] component = "segmented_control" step = "chooses an item with JavaScript disabled" -system = "rx" -reason = "The items of rx.segmented_control are buttons that JavaScript turns into radio buttons: until it has run, a click does nothing. An item of rx.ui.segmented_control is a label around a native radio button, which the browser checks with or without JavaScript." - +reason = "The items of rx.segmented_control and rx.ui.segmented_control are buttons that JavaScript makes radio buttons: until the page has hydrated, a click does nothing." [[look]] component = "slider" check = "a11y" @@ -301,11 +294,6 @@ step = "the thumb of a slider has the name the slider is given" system = "rx" reason = "An `aria_label` of rx.slider names the element around its thumb, so the thumb, which is what a screen reader lands on, has no name. rx.ui.slider gives the label to the thumb." -[[contract]] -component = "slider" -step = "Shift and an arrow key move a thumb by ten steps" -reason = "The thumbs of rx.ui.slider are native range inputs: the browser moves one by one step for an arrow key, with or without Shift, and by ten for Page Up and Page Down, as rx.slider does for those." - [[contract]] component = "slider" step = "a thumb can be moved past the one after it" @@ -373,41 +361,15 @@ step = "a trigger and a panel given ids of their own name each other" system = "rx" reason = "A trigger of rx.tabs names its panel, and the panel its trigger, by an id rx.tabs makes up, so giving either an `id` breaks the link and a screen reader no longer says which tab a panel belongs to. rx.ui.tabs names each by the id it was given." -[[look]] -component = "accordion" -check = "a11y" -reason = "An item of rx.ui.accordion is a native `details`: its header is the `summary`, which holds the heading and says by itself whether the item is open, where the header of rx.accordion is a heading that holds a button with `aria-expanded`. A screen reader announces both as a heading that expands and collapses." - -[[look]] -component = "accordion" -check = "style" -cells = "*@focus-visible" -properties = ["outline-style", "outline-width", "outline-color"] -reason = "The ring of the keyboard's focus is drawn by the browser around the `summary` of the item, which is what takes the focus in rx.ui.accordion, and around the button inside the heading in rx.accordion. It is the same ring in the same place." - -[[look]] -component = "accordion" -check = "style" -cells = "disabled-true*" -properties = ["pointer-events"] -reason = "The header of a disabled item of rx.ui.accordion lets the pointer through, so the item cannot be opened with or without JavaScript. rx.accordion disables the button of the header." - [[contract]] component = "accordion" step = "opens and closes an item with JavaScript disabled" -system = "rx" -reason = "rx.accordion is opened by JavaScript: until it has run, a press on a header does nothing. An item of rx.ui.accordion is a native `details`, which the browser opens and closes with or without JavaScript, one at a time when the accordion is `type=\"single\"`; only an open item of an accordion that is not `collapsible` needs JavaScript to stay open when it is pressed." - +reason = "rx.accordion and rx.ui.accordion are opened by JavaScript: until the page has hydrated, a press on a header does nothing." [[contract]] component = "accordion" step = "the arrow keys, Home and End move between the headers" reason = "The headers of rx.ui.accordion are native `summary` elements: Tab and Shift+Tab move between them, as between the headers of any `details`, and Enter and Space open and close an item. rx.accordion also moves between its headers with the arrow keys, Home and End, and `orientation` says which arrow keys do." -[[contract]] -component = "accordion" -step = "hands over the open items in the order they were opened in" -reason = "`on_value_change` of an rx.ui.accordion of `type=\"multiple\"` hands over the values of the open items in the order of the items, whatever the order they were opened in: the accordion keeps no state of its own and reads its items. rx.accordion appends each value as it is opened." - [[look]] component = "dialog" check = "style" @@ -908,3 +870,39 @@ component = "context_menu" check = "pixels" cells = "*@keys" reason = "A context menu asked for from the keyboard, with Shift+F10 or the context-menu key, opens where rx.context_menu takes the browser's point for the key to be, the middle of the area. UI SDK opens the menu of rx.ui.context_menu beside the area instead, at its end and level with its top: the same menu, in another place." + +[[contract]] +component = "accordion" +step = "opens and closes an item with JavaScript disabled" +system = "rx" +reason = "rx.accordion and rx.ui.accordion are opened by JavaScript: until the page has hydrated, a press on a header does nothing." + +[[contract]] +component = "segmented_control" +step = "chooses an item with JavaScript disabled" +system = "rx" +reason = "The items of rx.segmented_control and rx.ui.segmented_control are buttons that JavaScript makes radio buttons: until the page has hydrated, a click does nothing." + +[[look]] +component = "slider" +check = "style" +properties = ["width"] +reason = "UI SDK gives the filled part of the track of rx.ui.slider a width, a share of the track, where rx.slider sets where it ends; the browser rounds the two to a 64th of a pixel apart, so the fill of rx.ui.slider may end a 64th of a pixel sooner." + +[[look]] +component = "slider" +check = "pixels" +cells = "*size-1*" +reason = "UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. A thumb of size 1 is drawn 13 pixels wide, an odd number, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise." + +[[look]] +component = "slider" +check = "pixels" +cells = "*size-3*" +reason = "UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. A thumb of size 3 is drawn 19 pixels wide, an odd number, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise." + +[[look]] +component = "slider" +check = "pixels" +cells = "size-responsive*" +reason = "UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. The responsive slider is of size 1 or 3 at these widths, whose thumbs are an odd number of pixels wide, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/accordion.py b/packages/reflex-components-ui/parity/ui_parity/components/accordion.py index 77b92a0695c..4bf8099dfc2 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/accordion.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/accordion.py @@ -74,11 +74,11 @@ def _focus(page: Page, target: Locator, point: Point) -> None: Args: page: The page. - target: The trigger: a button of Radix, the heading in a summary here. + target: The trigger: a button in either system. point: The middle of the trigger. """ page.keyboard.press("Tab") - target.evaluate("element => (element.closest('summary') ?? element).focus()") + target.focus() def _blur(page: Page, target: Locator, point: Point) -> None: @@ -136,15 +136,8 @@ def _blur(page: Page, target: Locator, point: Point) -> None: "second": ".AccordionItem:nth-of-type(2) .AccordionTrigger", "third": ".AccordionItem:nth-of-type(3) .AccordionTrigger", }, - # The focus is on the button of Radix, and on the summary around the - # heading here. - states={ - FOCUS_VISIBLE: State( - enter=_focus, - leave=_blur, - matches=":is(:focus-visible, summary:focus-visible *)", - ) - }, + # The focus is on the button of the trigger in either system. + states={FOCUS_VISIBLE: State(enter=_focus, leave=_blur, matches=":focus-visible")}, # Not held to zero. At a threshold of zero 87 of the 106 cells are equal # pixel for pixel, and the others differ by at most 5 pixels of 108000 # on a rounded corner, which the browser anti-aliases by where the @@ -267,11 +260,11 @@ def _letters(namespace: Any, name: str, off: str = "", **props: Any) -> Any: ) # How long a panel takes to open or close, and some more, in milliseconds. STILL = 400 -# What takes the focus in a header: the button of Radix, the summary here. -HEADER = "button.AccordionTrigger, summary" +# What takes the focus in a header: its button, in either system. +HEADER = "button.AccordionTrigger" # The text of the header that has the focus, or the id of anything else. FOCUSED = ( - "document.activeElement.matches('button.AccordionTrigger, summary')" + "document.activeElement.matches('button.AccordionTrigger')" " ? document.activeElement.textContent : document.activeElement.id" ) @@ -345,8 +338,8 @@ def _role(run: Run) -> None: "Header b", "Header c", ] - # An open item says so on its button in Radix, and as a `details` here. - said = plain.locator("button[aria-expanded=true], details[open] > summary") + # An open item says so on its button. + said = plain.locator("button[aria-expanded=true]") assert said.all_text_contents() == ["Header a"] assert plain.get_by_role("region", name="Header a").text_content() == "Panel a" diff --git a/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py index e53f68f207f..0a20e421758 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/context_menu.py @@ -121,7 +121,9 @@ def open_from_keyboard(page: Page, area: Locator) -> None: page.keyboard.press("Shift+F10") shown = f"document.querySelectorAll('{SHOWN}').length" try: - page.wait_for_function(f"{shown} > 0", timeout=1000) + # Long enough for a page under load to open the menu: a second key + # would ask for another one. + page.wait_for_function(f"{shown} > 0", timeout=2000) except PlaywrightTimeoutError: page.keyboard.press("ContextMenu") @@ -134,6 +136,8 @@ def _keys(page: Page, target: Locator, point: Point) -> None: target: The area. point: The middle of the area. """ + # Nothing of the menu is under the pointer the cell before left. + page.mouse.move(1, 1) open_from_keyboard(page, target) _wait(page, 1) wait_for_value(page, "document.activeElement.textContent.startsWith('Copy')", True) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py index b0f4f23cc7b..c5c9cc5b28a 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/segmented_control.py @@ -17,7 +17,7 @@ RADII = ["none", "small", "medium", "large", "full"] STATES = ["rest", HOVER, FOCUS_VISIBLE, ACTIVE] # The second item: a button of Radix, a label around a radio button here. -TARGET = ("button:nth-child(2)", "label:nth-child(2)") +TARGET = "button:nth-of-type(2)" MANY = [str(number) for number in range(1, 13)] # Three items of a whole number of pixels each. WIDTH = "240px" @@ -89,30 +89,17 @@ def _control(namespace: Any, props: Mapping[str, Any]) -> Any: stage=(420, 80), crop="stage", target=TARGET, - # What is inside an item, which has a radio button before it here. + # What is inside an item. parts={ "root": "[role=radiogroup]", "indicator": "[role=radiogroup] > div", "pill": "[role=radiogroup] > div::before", - "separator": ( - f"{TARGET[0]} > span:nth-of-type(1)", - f"{TARGET[1]} > span:nth-of-type(1)", - ), - "label": ( - f"{TARGET[0]} > span:nth-of-type(2)", - f"{TARGET[1]} > span:nth-of-type(2)", - ), - "active": ( - f"{TARGET[0]} > span > span:nth-of-type(1)", - f"{TARGET[1]} > span > span:nth-of-type(1)", - ), - "inactive": ( - f"{TARGET[0]} > span > span:nth-of-type(2)", - f"{TARGET[1]} > span > span:nth-of-type(2)", - ), + "separator": f"{TARGET} > span:nth-of-type(1)", + "label": f"{TARGET} > span:nth-of-type(2)", + "active": f"{TARGET} > span > span:nth-of-type(1)", + "inactive": f"{TARGET} > span > span:nth-of-type(2)", }, - # The focus is on the item of Radix and on the radio button in the item - # here. + # The focus is on the item, in either system. states={FOCUS_VISIBLE: FOCUS_WITHIN}, # Not held to zero. At a threshold of zero most cells are equal pixel # for pixel, and the others differ by where they are on the page: the @@ -223,12 +210,12 @@ def _items(namespace: Any, *values: str) -> list[Any]: ), ) -# An item is a button of Radix and a label around a radio button here. -ITEMS = "button[role=radio], label" +# An item is a button with the role of a radio button, in either system. +ITEMS = "button[role=radio]" # The text of the chosen items of a control, by the id of its frame. CHOSEN = ( f"id => [...document.getElementById(id).querySelectorAll('{ITEMS}')]" - ".filter(item => item.matches('[aria-checked=true], :has(:checked)'))" + ".filter(item => item.matches('[aria-checked=true]'))" ".map(item => item.querySelector('span > span').textContent)" ) # The text of the item that has the focus. diff --git a/packages/reflex-components-ui/parity/ui_parity/components/slider.py b/packages/reflex-components-ui/parity/ui_parity/components/slider.py index de3c2c27abf..82500af66ae 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/slider.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/slider.py @@ -66,10 +66,11 @@ stage=(240, 140), crop="stage", parts={ - "track": "span > span", - "range": "span > span > span", + "track": ("span > span", "[data-slot=slider-track]"), + "range": ("span > span > span", "[data-slot=slider-indicator]"), }, - # The focus is on the first thumb: an element of Radix, an input here. + # The focus is on the first thumb: an element of Radix, the range input + # inside the thumb here. states={FOCUS_VISIBLE: FOCUS_WITHIN}, # Not held to zero. At a threshold of zero 102 of the 147 cells are # equal pixel for pixel, and the others differ by where they are on the @@ -199,9 +200,11 @@ def submit(self, data: dict[str, Any]): ".map(thumb => Number(thumb.getAttribute('aria-valuenow') ?? thumb.value))" ) # The slider whose thumb has the focus, and which of its thumbs it is. +# The frame is the element with an id around the slider, not a part of the +# slider of UI SDK, which has ids of its own. FOCUSED_THUMB = ( - "(thumb => thumb.closest('div[id]')?.id + ':' + " - f"[...thumb.closest('div[id]')?.querySelectorAll('{THUMBS}') ?? []].indexOf(thumb))" + "(thumb => thumb.closest('div[id]:not([data-slot])')?.id + ':' + " + f"[...thumb.closest('div[id]:not([data-slot])')?.querySelectorAll('{THUMBS}') ?? []].indexOf(thumb))" "(document.activeElement)" ) @@ -282,7 +285,9 @@ def _tab(run: Run) -> None: stops = [] for _ in range(6): page.keyboard.press("Tab") - stops.append(focused(page) or page.evaluate(FOCUSED_THUMB)) + # A thumb is named by its slider and its place, whatever id it has. + on_thumb = page.evaluate(f"document.activeElement.matches('{THUMBS}')") + stops.append(page.evaluate(FOCUSED_THUMB) if on_thumb else focused(page)) assert stops == ["volume:0", "bound:0", "high", "span:0", "span:1", "steps:0"] diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/accordion.py b/packages/reflex-components-ui/src/reflex_components_ui/components/accordion.py index 37357a060fb..f026cbfd989 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/accordion.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/accordion.py @@ -1,4 +1,9 @@ -"""An accordion: items that are native ``details``, opened by their summary.""" +"""An accordion: the parts of ``@ui-sdk/react/accordion``, drawn as the Radix wrapper draws them. + +UI SDK opens and closes the items, keeps an open item open when the +accordion is not collapsible, moves between the triggers with the arrow +keys, and mounts the panel of an item while it is open, as Radix does. +""" from __future__ import annotations @@ -12,16 +17,8 @@ from reflex_base.vars.base import LiteralVar, Var, VarData from reflex_components_lucide.icon import Icon -from reflex_components_ui.base import UIComponent -from reflex_components_ui.components._group import ( - choose, - descendants, - either, - has_value, - is_value, - literal, -) -from reflex_components_ui.components._script import listen, script +from reflex_components_ui.components._group import choose, descendants, either, literal +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.props import style_before from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.accordion import ( @@ -36,6 +33,8 @@ ) from reflex_components_ui.themes import LiteralAccentColor +_LIBRARY = entry("accordion") + LiteralAccordionType = Literal["single", "multiple"] LiteralAccordionDir = Literal["ltr", "rtl"] LiteralAccordionOrientation = Literal["vertical", "horizontal"] @@ -45,7 +44,7 @@ DEFAULT_ANIMATION_DURATION = 250 DEFAULT_ANIMATION_EASING = "cubic-bezier(0.87, 0, 0.13, 1)" -# Numbers the accordions of an app, and the items that are given no value. +# Numbers the items of an app that are given no value. _ids = itertools.count(1) @@ -76,29 +75,11 @@ def _is_one_of(values: Sequence[Var | None], wanted: tuple[str, ...]) -> Var | b ) -def _joined(prefix: str, value: Var) -> Any: - """Make an id from a prefix and the value of an item. - - Args: - prefix: What the id starts with. - value: The value of the item. - - Returns: - The id: a string when the value is known while compiling. - """ - known = literal(value) - if not isinstance(known, Var): - return f"{prefix}{known}" - return Var( - f"({LiteralVar.create(prefix)!s} + {known!s})", - _var_type=str, - _var_data=known._get_all_var_data(), - ) - - -class AccordionComponent(UIComponent): +class AccordionComponent(SDKPart): """Base class for the components of an accordion.""" + library = _LIBRARY + as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child." ) @@ -110,12 +91,13 @@ class AccordionComponent(UIComponent): variant: Var[LiteralAccordionVariant] = field(doc="The variant of the component.") def _exclude_props(self) -> list[str]: - """Keep the variant off the element: it selects styles. + """Keep the variant and ``as_child`` off the element. Returns: - The props read as styles, and the variant. + The props read as styles, the variant, which selects styles, and + ``as_child``. """ - return [*super()._exclude_props(), "variant"] + return [*super()._exclude_props(), "variant", "as_child"] def on_value_change_handler(value: Var[str | list[str]]) -> tuple[Var[str | list[str]]]: @@ -133,7 +115,7 @@ def on_value_change_handler(value: Var[str | list[str]]) -> tuple[Var[str | list class AccordionRoot(AccordionComponent): """An accordion component.""" - tag = "div" + tag = "Accordion" styles: ClassVar[ComponentStyles] = ACCORDION @@ -224,12 +206,26 @@ def _post_init(self, *args, **kwargs): **kwargs: Kwargs to initialize the component. """ super()._post_init(*args, **kwargs) - self._name = f"rx-accordion-{next(_ids)}" # The line between two items is as thick as the accordion says, and # it says so when asked to, or drawn with an outline. self._divided: Var | bool = self.show_dividers is not None or _is_one_of( [self.variant], ("outline", "surface") ) + multiple = self._multiple + # The open item of a single accordion stays open unless it is + # collapsible, as in Radix: UI SDK lets it close by default. + self._sdk: dict[str, Any] = ( + {} if self.collapsible is not None else {"collapsible": False} + ) + if multiple is not False: + self._sdk["multiple"] = multiple + for prop, name in (("value", "value"), ("default_value", "defaultValue")): + given = getattr(self, prop) + if given is not None: + self._sdk[name] = _listed(given) + change = self.event_triggers.pop("on_value_change", None) + if change is not None: + self._sdk["onValueChange"] = _said(LiteralVar.create(change), multiple) for item in descendants(self, AccordionItem, AccordionRoot): item._join(self) @@ -243,43 +239,27 @@ def _multiple(self) -> Var | bool: return _is_one_of([self.type], ("multiple",)) def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the items off the element. + """Keep the props UI SDK is given otherwise off the accordion. Returns: - The props read as styles, and what the accordion hands its - items or its script. + The props read as styles, and those the accordion hands UI SDK + in its own shape, its items, or its styles. """ return [ *super()._exclude_props(), "type", "value", "default_value", - "collapsible", - "disabled", "orientation", "duration", "easing", "show_dividers", ] - @property - def _scripted(self) -> bool: - """Whether the accordion does something the browser does not. - - Returns: - Whether an item that is open stays open when it is pressed, - the accordion is bound to state, or says what is open. - """ - return ( - self.value is not None - or "on_value_change" in self.event_triggers - or not (self._multiple is True or literal(self.collapsible) is True) - ) - def _get_vars( self, include_children: bool = False, ignore_ids: set[int] | None = None ) -> Iterator[Var]: - """Walk all Vars used in the accordion, its script included. + """Walk all Vars used in the accordion, those it hands UI SDK included. Args: include_children: Whether to include Vars from children. @@ -289,42 +269,72 @@ def _get_vars( Each var referenced by the component. """ yield from super()._get_vars(include_children, ignore_ids) - if self._scripted: - yield script("accordion", "accordionClick") + for value in self._sdk.values(): + if isinstance(value, Var): + yield value def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the element around the accordion. + """Render the accordion. Args: props: The props to render (if None, then use get_props). Returns: - The tag. The browser opens and closes the items; a script - hears a press on a header only for what the browser does not - do. + The tag, with whether several items open, which are open, and + what to do when they change, in the shape UI SDK takes. """ - tag = super()._render(props) - if not self._scripted: - return tag - rendered = dict(tag.props) - on_value_change = rendered.pop("onValueChange", None) - tag = tag.set(props=rendered).add_props(**{ - "data-rx-accordion": choose(self._multiple, "multiple", "single"), - "data-collapsible": self.collapsible, - "data-bound": None if self.value is None else "", - }) - return listen( - tag, - script("accordion", "accordionClick"), - "onClick", - arguments=() if on_value_change is None else (on_value_change,), - ) + return super()._render(props).add_props(**self._sdk) + + +def _said(handler: Var, multiple: Var | bool) -> Var: + """Hand a handler of a change of an accordion what Radix says changed. + + Args: + handler: The handler of ``on_value_change``. + multiple: Whether several items of the accordion open. + + Returns: + What UI SDK calls with the list of the open items: a single + accordion of Radix says the value of its open item, or "". + """ + if multiple is True: + return handler + first = f'({handler!s})(value[0] ?? "")' + if multiple is False: + return Var(f"((value) => {first})", _var_data=handler._get_all_var_data()) + return Var( + f"((value) => ({multiple!s}) ? ({handler!s})(value) : {first})", + _var_data=VarData.merge( + handler._get_all_var_data(), multiple._get_all_var_data() + ), + ) + + +def _listed(value: Var | str | Sequence[str]) -> Any: + """Put the value of an accordion in the list UI SDK takes. + + Args: + value: The value of a single accordion, or the values of a multiple + one. + + Returns: + The list: a list when the value is known while compiling. + """ + known = literal(LiteralVar.create(value)) + if not isinstance(known, Var): + if isinstance(known, str): + return [known] if known else [] + return list(known) + return Var( + f"(Array.isArray({known!s}) ? {known!s} : ({known!s} ? [{known!s}] : []))", + _var_data=known._get_all_var_data(), + ) class AccordionItem(AccordionComponent): """An accordion component.""" - tag = "details" + tag = "AccordionItem" styles: ClassVar[ComponentStyles] = ACCORDION_ITEM @@ -402,8 +412,8 @@ def create( ), ] else: - # The summary of a `details` is its child: a trigger without a - # header is given one. + # A trigger is inside a header, as in Radix: one without a header + # is given one. children = [ AccordionHeader.create(child) if isinstance(child, AccordionTrigger) @@ -420,11 +430,9 @@ def _post_init(self, *args, **kwargs): *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ - # What the style table reads as variants, and the attributes the - # accordion gives the item: both are set by the root around it. + # What the style table reads as variants: the root around it sets them. self._ghost: Any = None self._divided: Any = None - self._accordion: dict[str, Any] = {} super()._post_init(*args, **kwargs) def _join(self, accordion: AccordionRoot) -> None: @@ -437,49 +445,9 @@ def _join(self, accordion: AccordionRoot) -> None: _is_one_of([self.variant, accordion.variant], ("ghost",)), "true", "false" ) self._divided = choose(accordion._divided, "true", "false") - multiple = accordion._multiple - selected = ( - accordion.value if accordion.value is not None else accordion.default_value - ) - attributes: dict[str, Any] = { - # The browser closes the other items of a name when one opens. - "name": choose(multiple, None, accordion._name), - } - if selected is not None: - several, one = ( - has_value(selected, self.value), - is_value(selected, self.value), - ) - attributes["open"] = ( - several - if multiple is True - else one - if multiple is False - else choose(multiple, several, one) - ) - self._accordion = attributes self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - disabled = either(accordion.disabled, self.disabled) - prefix = f"{accordion._name}-" for part in descendants(self, AccordionPart, AccordionRoot): - part._join(accordion, self, disabled, prefix) - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the item, those its accordion gives it 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) - for value in self._accordion.values(): - if isinstance(value, Var): - yield value + part._join(accordion, self) def _exclude_props(self) -> list[str]: """Keep the props of an item off the element. @@ -487,7 +455,7 @@ def _exclude_props(self) -> list[str]: Returns: The props read as styles, and the ones its parts render. """ - return [*super()._exclude_props(), "header", "content", "value", "disabled"] + return [*super()._exclude_props(), "header", "content"] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the item. @@ -496,21 +464,13 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: props: The props to render (if None, then use get_props). Returns: - The tag: a ``details`` the browser opens and closes. + The tag, marked for the rule that turns its icon over. """ - return ( - super() - ._render(props) - .add_props(**{ - "data-rx-accordion-item": "", - "data-value": self.value, - **self._accordion, - }) - ) + return super()._render(props).add_props(**{"data-rx-accordion-item": ""}) class AccordionPart(AccordionComponent): - """A part of an item, which the accordion gives a look and a name.""" + """A part of an item, which the accordion gives a look.""" def _post_init(self, *args, **kwargs): """Initialize the part, as one of an accordion without props. @@ -519,27 +479,17 @@ def _post_init(self, *args, **kwargs): *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ - # What the style table reads as variants, and the attributes the - # accordion gives the part: both are set by the root around it. + # What the style table reads as variants: the root around it sets them. self._classic: Any = None self._divided: Any = None - self._accordion: dict[str, Any] = {} super()._post_init(*args, **kwargs) - def _join( - self, - accordion: AccordionRoot, - item: AccordionItem, - disabled: Var | None, - prefix: str, - ) -> None: + def _join(self, accordion: AccordionRoot, item: AccordionItem) -> None: """Take from an accordion what Radix hands its parts through a context. Args: accordion: The accordion the part is in. item: The item the part is in. - disabled: Whether the item is disabled. - prefix: What the ids of the parts of the accordion start with. """ # A part is classic when it, its item or its accordion is, and an # accordion is unless it says otherwise. @@ -552,57 +502,13 @@ def _join( "false", ) self._divided = choose(accordion._divided, "true", "false") - self._accordion = self._attributes(item, disabled, prefix) self._merge_styles() # pyright: ignore[reportAttributeAccessIssue] - def _attributes( - self, item: AccordionItem, disabled: Var | None, prefix: str - ) -> dict[str, Any]: - """Work out the attributes the accordion gives the part. - - Args: - item: The item the part is in. - disabled: Whether the item is disabled. - prefix: What the ids of the parts of the accordion start with. - - Returns: - The attributes. - """ - return {} - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the part, those its accordion gives it 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) - for value in self._accordion.values(): - if isinstance(value, Var): - yield value - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the part. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, with what its accordion gives it. - """ - return super()._render(props).add_props(**self._accordion) - class AccordionHeader(AccordionPart): """An accordion component.""" - tag = "summary" + tag = "AccordionHeader" styles: ClassVar[ComponentStyles] = ACCORDION_HEADER @@ -624,29 +530,39 @@ def create(cls, *children, **props) -> Component: return super().create(*children, class_name=cls_name, **props) - def _attributes( - self, item: AccordionItem, disabled: Var | None, prefix: str - ) -> dict[str, Any]: - """Say that the header of a disabled item opens nothing. - Args: - item: The item the header is in. - disabled: Whether the item is disabled. - prefix: What the ids of the parts of the accordion start with. +class AccordionTrigger(AccordionPart): + """An accordion component.""" - Returns: - The attributes: a disabled header says so, and Tab passes it. + tag = "AccordionTrigger" + + def _join(self, accordion: AccordionRoot, item: AccordionItem) -> None: + """Take the look of the accordion, and whether the item is disabled. + + Args: + accordion: The accordion the trigger is in. + item: The item the trigger is in. """ - if disabled is None: - return {} - off = literal(disabled) - return {"aria-disabled": off, "tabIndex": choose(off, -1, None)} + super()._join(accordion, item) + # Tab passes the trigger of a disabled item, as in Radix: UI SDK + # keeps it focusable. + disabled = either(accordion.disabled, item.disabled) + self._skipped: Any = ( + None if disabled is None else choose(literal(disabled), -1, None) + ) + def _render(self, props: dict[str, Any] | None = None) -> CommonTag: + """Render the trigger. -class AccordionTrigger(AccordionPart): - """An accordion component.""" + Args: + props: The props to render (if None, then use get_props). - tag = "h3" + Returns: + The tag, out of the order of Tab when its item is disabled. + """ + tag = super()._render(props) + skipped = getattr(self, "_skipped", None) + return tag if skipped is None else tag.add_props(tabIndex=skipped) styles: ClassVar[ComponentStyles] = ACCORDION_TRIGGER @@ -668,23 +584,6 @@ def create(cls, *children, **props) -> Component: return super().create(*children, class_name=cls_name, **props) - def _attributes( - self, item: AccordionItem, disabled: Var | None, prefix: str - ) -> dict[str, Any]: - """Take the id the panel of the item is named by. - - Args: - item: The item the trigger is in. - disabled: Whether the item is disabled. - prefix: What the ids of the parts of the accordion start with. - - Returns: - The attributes. - """ - if self.id is not None: - return {} - return {"id": _joined(f"{prefix}trigger-", item.value)} - class AccordionIcon(Icon): """An accordion icon component.""" @@ -713,7 +612,7 @@ def create(cls, *children, **props) -> Component: class AccordionContent(AccordionPart): """An accordion component.""" - tag = "div" + tag = "AccordionPanel" styles: ClassVar[ComponentStyles] = ACCORDION_CONTENT @@ -735,39 +634,6 @@ def create(cls, *children, **props) -> Component: return super().create(*children, class_name=cls_name, **props) - def _attributes( - self, item: AccordionItem, disabled: Var | None, prefix: str - ) -> dict[str, Any]: - """Name the panel by the trigger of its item. - - Args: - item: The item the panel is in. - disabled: Whether the item is disabled. - prefix: What the ids of the parts of the accordion start with. - - Returns: - The attributes. - """ - trigger = next(iter(descendants(item, AccordionTrigger, AccordionRoot)), None) - return { - "aria-labelledby": ( - _joined(f"{prefix}trigger-", item.value) - if trigger is None or trigger.id is None - else trigger.id - ) - } - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the panel. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, with the role of a region of the page. - """ - return super()._render(props).add_props(role="region") - class Accordion(ComponentNamespace): """Accordion component.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py b/packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py index 54a8d3a8618..f2dd66b959b 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.py @@ -1,27 +1,26 @@ -"""A segmented control: a row of native radio buttons, drawn as one control.""" +"""A segmented control: the parts of ``@ui-sdk/react/segmented-control``, drawn as one control. + +UI SDK makes its items a group of radio buttons that Tab stops at once and +the arrow keys move through. What marks the chosen item is placed by the +styles of the control, from where the chosen item is among its items, so +that it is in place before the page hydrates. +""" from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Iterator, Sequence from typing import Any, ClassVar, Literal, cast from reflex_base.components.component import Component, ComponentNamespace, field from reflex_base.components.tags import CommonTag -from reflex_base.event import EventHandler, input_event -from reflex_base.utils.imports import ImportVar -from reflex_base.vars.base import Var, VarData +from reflex_base.event import EventHandler, passthrough_event_spec +from reflex_base.vars.base import LiteralVar, Var, VarData from reflex_base.vars.sequence import ArrayVar from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.core.foreach import Foreach -from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.components._group import ( - GroupInput, - GroupRoot, - group_name, - is_value, -) -from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.base import Part +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.props import style_before from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.segmented_control import ( @@ -35,42 +34,28 @@ ) from reflex_components_ui.themes import LiteralAccentColor -# The `onKeyDown` of the control: the arrow keys move the focus between the -# items without choosing one, as in Radix, which is all its JavaScript. -_ROVING_KEY_DOWN = Var( - "rovingKeyDown", - _var_data=VarData( - imports={ - f"$/{WEB_DIR}/behaviors/roving-focus.js": [ImportVar(tag="rovingKeyDown")] - } - ), +_LIBRARY = entry("segmented-control") + +# The keys of an item of Radix that UI SDK, whose items are radio buttons, +# does not have: Enter chooses the item, as Space does, and Home and End go +# to the first and the last one. The arrow keys are UI SDK's. +_KEYS = Var( + "((event) => { const item = event.target.closest('[role=radio]');" + " if (!item || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;" + ' if (event.key === "Enter") { event.preventDefault(); item.click(); return; }' + ' if (event.key !== "Home" && event.key !== "End") return;' + " const items = event.currentTarget.querySelectorAll('[role=radio]:not(:disabled)');" + " event.preventDefault();" + ' items[event.key === "Home" ? 0 : items.length - 1]?.focus(); })' ) -class SegmentedControlInput(GroupInput, Part): - """The radio button of an item, which is not seen.""" - - _type: ClassVar[str] = "radio" - - value: Var[str] = field(doc="The value of the item.") - - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the radio button. - - Args: - props: The props to render (if None, then use get_props). - - Returns: - The tag, of no form: a segmented control has no name, and the - name that groups its radio buttons is not for a form to submit. - """ - return super()._render(props).add_props(form="") - - -class SegmentedControlRoot(GroupRoot): +class SegmentedControlRoot(SDKPart): """Root element for a SegmentedControl component.""" - tag = "div" + library = _LIBRARY + + tag = "SegmentedControl" styles: ClassVar[ComponentStyles] = SEGMENTED_CONTROL @@ -100,17 +85,10 @@ class SegmentedControlRoot(GroupRoot): doc="The current value of the segmented control." ) - on_change: EventHandler[input_event] = field( + on_change: EventHandler[passthrough_event_spec(str)] = field( doc="Handles the `onChange` event for the SegmentedControl component." ) - # What a group hands its items, and a segmented control does not have. - high_contrast: ClassVar[None] = None - disabled: ClassVar[None] = None - required: ClassVar[None] = None - - _holds = staticmethod(is_value) - @classmethod def create(cls, *children: Any, **props: Any) -> Component: """Create a SegmentedControlRoot. @@ -150,32 +128,53 @@ def create(cls, *children: Any, **props: Any) -> Component: chosen(position): position - 1 for position in range(PLACED + 1, len(children) + 1) } - props.setdefault("custom_attrs", {}).setdefault("onKeyDown", _ROVING_KEY_DOWN) style_before(props, placement) return super().create( *children, Part.create(part="indicator", tag="div"), **props ) - def _bind(self) -> None: - """Name the items: the browser takes radio buttons for a group by it.""" - self._name = group_name(None, "segmented") + def _post_init(self, *args, **kwargs): + """Initialize the control, and take its handler of a change from it. + + Args: + *args: Args to initialize the component. + **kwargs: Kwargs to initialize the component. + """ + super()._post_init(*args, **kwargs) + change = self.event_triggers.pop("on_change", None) + handler = None if change is None else LiteralVar.create(change) + # The arrow keys move the focus without choosing, as in Radix: UI SDK + # chooses the item they reach, which the control refuses. + then = "" if handler is None else f" ({handler!s})(value);" + self._on_value_change = Var( + f'((value, details) => {{ if (details?.reason === "list-navigation")' + f" {{ details.cancel(); return; }}{then} }})", + _var_data=None if handler is None else handler._get_all_var_data(), + ) + + def _get_vars( + self, include_children: bool = False, ignore_ids: set[int] | None = None + ) -> Iterator[Var]: + """Walk all Vars used in the control, its handler of a change 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 self._on_value_change def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the items off the element. + """Keep the props that are styles off the control. Returns: - The props read as styles, and what the control hands its items. - The type is one of them: as in Radix Themes, one item is chosen - whatever it says. + The props read as styles, and the type: as in Radix Themes, one + item is chosen whatever it says. """ - return [ - *super()._exclude_props(), - "size", - "variant", - "type", - "value", - "default_value", - ] + return [*super()._exclude_props(), "size", "variant", "type"] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the control. @@ -184,9 +183,13 @@ 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 the role of a group of radio buttons. + The tag, which hears a change of its value and the keys of Radix. """ - return super()._render(props).add_props(role="radiogroup") + return ( + super() + ._render(props) + .add_props(onValueChange=self._on_value_change, onKeyDown=_KEYS) + ) def _value_of(foreach: Foreach, element: Var) -> Var: @@ -199,13 +202,15 @@ def _value_of(foreach: Foreach, element: Var) -> Var: Returns: The value of the item. """ - return cast("SegmentedControlItem", foreach.render_fn(element)).children[0].value # pyright: ignore[reportAttributeAccessIssue] + return cast("SegmentedControlItem", foreach.render_fn(element)).value -class SegmentedControlItem(UIComponent): +class SegmentedControlItem(SDKPart): """An item in the SegmentedControl component.""" - tag = "label" + library = _LIBRARY + + tag = "SegmentedControlItem" styles: ClassVar[ComponentStyles] = SEGMENTED_CONTROL_ITEM @@ -215,23 +220,16 @@ class SegmentedControlItem(UIComponent): @classmethod def create(cls, *children, **props) -> Component: - """Create an item: a label around its radio button and its text. + """Create an item: the line before it, and its text. Args: *children: What the item shows. - **props: The props of the item. Its styles are those of the - label, and everything else is given to the radio button. + **props: The props of the item. Returns: - The label. + The item. """ - own = { - key: props.pop(key) - for key in list(props) - if key in ("value", "id") or key.startswith(("on_", "aria_", "data_")) - } return super().create( - SegmentedControlInput.create(part="input", **own), Part.create(part="separator", tag="span"), Part.create( Part.create(*children, part="active", tag="span"), @@ -247,14 +245,6 @@ def create(cls, *children, **props) -> Component: **props, ) - def _exclude_props(self) -> list[str]: - """Keep the value off the label: it is the one of the radio button. - - Returns: - The props read as styles, and the value. - """ - return [*super()._exclude_props(), "value"] - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the item. diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/slider.py b/packages/reflex-components-ui/src/reflex_components_ui/components/slider.py index c80d5708191..fa917cc6c13 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/slider.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/slider.py @@ -1,4 +1,9 @@ -"""A slider: native range inputs over a track that Radix Themes draws.""" +"""A slider: the parts of ``@ui-sdk/react/slider``, drawn as Radix Themes draws a slider. + +UI SDK moves a thumb with the pointer and the keys, a native range input +inside each thumb taking the focus, keeps several thumbs in order, and +places the thumbs and the filled part of the track. +""" from __future__ import annotations @@ -8,111 +13,50 @@ from reflex_base.components.component import Component, field from reflex_base.components.tags import CommonTag -from reflex_base.event import EventHandler, JavascriptInputEvent -from reflex_base.utils.imports import ImportVar +from reflex_base.event import EventHandler from reflex_base.utils.types import typehint_issubclass -from reflex_base.vars.base import LiteralVar, Var, VarData -from reflex_base.vars.object import ObjectVar +from reflex_base.vars.base import Var from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.core.foreach import foreach -from reflex_components_core.el import elements -from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.components._group import literal -from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.base import Part +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.props import style_before from reflex_components_ui.style import ComponentStyles -from reflex_components_ui.styles.slider import END, SLIDER, START +from reflex_components_ui.styles.slider import SLIDER from reflex_components_ui.themes import LiteralAccentColor -_SCRIPT = f"$/{WEB_DIR}/behaviors/slider.js" - -# What follows the thumbs of a slider: its `onInputCapture` draws the filled -# part of the track and keeps several thumbs in order, and the -# `onMouseDown` of a slider with several moves the nearest one. -_SLIDE = Var("slide", _var_data=VarData(imports={_SCRIPT: [ImportVar(tag="slide")]})) -_PRESS = Var("press", _var_data=VarData(imports={_SCRIPT: [ImportVar(tag="press")]})) - -# The keys that move a thumb: a thumb is released when one of them is. -_KEYS = ( - '["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", ' - '"Home", "End", "PageUp", "PageDown"]' -) - - -def _values(event: Var, kind: type) -> Var: - """Read the values of the thumbs of a slider from an event inside it. - - Args: - event: The event, as it reaches the slider. - kind: The type of the list of values. - - Returns: - The value of each thumb, in the order of the thumbs. - """ - return Var( - f'Array.from({event!s}.currentTarget.querySelectorAll("input"), ' - "(input) => input.valueAsNumber)", - _var_type=kind, - ) +_LIBRARY = entry("slider") -def float_values_event( - e: ObjectVar[JavascriptInputEvent], -) -> tuple[Var[list[float]]]: +def float_values_event(value: Var[list[float]]) -> tuple[Var[list[float]]]: """Get the values of a slider from a change of one of its thumbs. Args: - e: The change, as it reaches the slider. + value: The value of each thumb, as UI SDK says it. Returns: The value of each thumb. """ - return (_values(e, list[float]),) + return (value,) -def int_values_event(e: ObjectVar[JavascriptInputEvent]) -> tuple[Var[list[int]]]: +def int_values_event(value: Var[list[int]]) -> tuple[Var[list[int]]]: """Get the whole values of a slider from a change of one of its thumbs. Args: - e: The change, as it reaches the slider. + value: The value of each thumb, as UI SDK says it. Returns: The value of each thumb. """ - return (_values(e, list[int]),) + return (value,) on_value_event_spec = (float_values_event, int_values_event) -def _share(value: Any, low: Any, high: Any) -> Any: - """Say how far along the track of a slider a value is. - - Args: - value: The value. - low: The minimum of the slider, or None for 0. - high: Its maximum, or None for 100. - - Returns: - The share of the track as a percentage: a string when everything is - known while compiling. - """ - low = 0 if low is None else literal(low) - high = 100 if high is None else literal(high) - value = literal(value) - if not any(isinstance(item, Var) for item in (value, low, high)): - return f"{(value - low) / (high - low) * 100:g}%" if high > low else "0%" - parts = [LiteralVar.create(item) for item in (value, low, high)] - amount, start, end = (str(part) for part in parts) - return Var( - f'(((({amount}) - ({start})) / (({end}) - ({start})) * 100) + "%")', - _var_type=str, - _var_data=VarData.merge(*(part._get_all_var_data() for part in parts)), - ) - - -def _label(index: int, count: int) -> dict[str, str]: +def _label(index: int, count: int) -> dict[str, Any]: """Name a thumb of a slider with several, as Radix does. Args: @@ -130,30 +74,33 @@ def _label(index: int, count: int) -> dict[str, str]: return {"aria_label": f"Value {index + 1} of {count}"} -class SliderThumb(Part, elements.Input): - """A thumb of a slider: a native range input.""" +class SliderThumb(SDKPart, Part): + """A thumb of a slider, around the range input that takes the focus.""" - tag = "input" + library = _LIBRARY - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the input. + tag = "SliderThumb" - Args: - props: The props to render (if None, then use get_props). + index: Var[int] = field(doc="Which thumb it is, from 0.") - Returns: - The tag, with the type of a range. - """ - return super()._render(props).add_props(type="range") +class _SliderPart(SDKPart, Part): + """A part of a slider that UI SDK places: the control, the track, its fill.""" -class Slider(UIComponent): + library = _LIBRARY + + +class Slider(SDKPart): """Provides user selection from a range of values.""" - tag = "span" + library = _LIBRARY + + tag = "Slider" styles: ClassVar[ComponentStyles] = SLIDER + _sdk_names: ClassVar[dict[str, str]] = {"onChange": "onValueChange"} + as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child, merging their props and behavior." ) @@ -230,8 +177,7 @@ def create( ) -> Component: """Create a Slider component. - A slider has a thumb for each of its values: a native range input, - which takes the ``id`` and the name of the slider. The ``aria_*`` + A slider has a thumb for each of its values. The ``aria_*`` attributes of a slider with one thumb are the ones of its thumb; with several, they are the ones of the group the thumbs are. @@ -249,135 +195,84 @@ def create( default_value = [default_value] elif isinstance(default_value, (int, float)): default_value = [default_value] - value = props.get("value") values = default_value if value is None else value - low, high = props.get("min"), props.get("max") - shared = { - key: props[key] - for key in ("min", "max", "step", "disabled") - if props.get(key) is not None - } - named = {key: props[key] for key in props if key.startswith("aria_")} - attribute = "default_value" if value is None else "value" - name = props.get("name") + if value is None: + props["default_value"] = default_value thumbs: list[Any] - if isinstance(values, Var) or len(values) > 1: - # Several thumbs are a group with the name of the slider, each - # with a name of its own. - if named: - props.setdefault("custom_attrs", {}).setdefault("role", "group") - else: - # The only thumb has the name of the slider. - shared.update({key: props.pop(key) for key in named}) if isinstance(values, Var): # The thumbs of a list in state are counted in the browser. - several: Any = True thumbs = [ foreach( values, - lambda item: SliderThumb.create( - part="thumb", **shared, **{attribute: item} - ), + lambda _, index: SliderThumb.create(part="thumb", index=index), ) ] - first = values[0] # pyright: ignore[reportIndexIssue] - start, end = _share(first, low, high), _share(values[-1], low, high) # pyright: ignore[reportIndexIssue] else: several = len(values) > 1 - if name is not None and several: - # As Radix names the inputs of a slider with several values. - name = Var.create(name) + "[]" # pyright: ignore[reportOperatorIssue] - if name is not None: - shared["name"] = name + named: dict[str, Any] = { + key: props.pop(key) for key in list(props) if key.startswith("aria_") + } + if several and named: + props.setdefault("custom_attrs", {}).update({ + key.replace("_", "-"): value for key, value in named.items() + }) thumbs = [ SliderThumb.create( part="thumb", - **{**_label(index, len(values)), **shared, attribute: item}, + index=index, + **(_label(index, len(values)) if several else named), ) - for index, item in enumerate(values) + for index in range(len(values)) ] - if thumbs and "id" in props: - thumbs[0].id = Var.create(props.pop("id")) - start = _share(values[0], low, high) if several else "0%" - end = _share(values[-1], low, high) if values else "0%" - handlers = props.setdefault("custom_attrs", {}) - handlers.setdefault("onInputCapture", _SLIDE) - if several: - handlers.setdefault("onMouseDown", _PRESS) - placement = {"width": width, START: start, END: end} - style_before(props, placement) + style_before(props, {"width": width}) return super().create( - Part.create( - Part.create(part="range", tag="span"), part="track", tag="span" + _SliderPart.create( + _SliderPart.create( + _SliderPart.create(part="range", tag="SliderIndicator"), + part="track", + tag="SliderTrack", + ), + # Where the thumbs travel: as far as the ones of Radix Themes, + # which stay on the track at either end. + Part.create(*thumbs, part="thumbs", tag="span"), + part="control", + tag="SliderControl", ), - *thumbs, *children, - _several=several, **props, ) - def _post_init(self, *args, **kwargs): - """Initialize the slider. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. ``_several`` says - whether the slider has more than one thumb. - """ - # What the style table reads as a variant. - self._several = kwargs.pop("_several", False) - super()._post_init(*args, **kwargs) - def _set_slot(self) -> None: """Render the slider itself: it has no child to be rendered as.""" - def _exclude_props(self) -> list[str]: - """Keep the props that are the ones of the thumbs off the element. - - Returns: - The props read as styles, and what the slider hands its inputs. - """ - return [ - *super()._exclude_props(), - "disabled", - "default_value", - "value", - "name", - "min", - "max", - "step", - "width", - ] - def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the slider. + """Render the slider, which hands UI SDK what also selects its styles. Args: props: The props to render (if None, then use get_props). Returns: - The tag. A thumb is released when the pointer or a key that - moves it is: Radix says so with ``on_value_commit``. + The tag, with whether it is disabled and its orientation, which + are variants of its style table and so not rendered by it. """ - tag = super()._render(props) - orientation = self.orientation - tag = tag.add_props(**{ - "data-orientation": "horizontal" if orientation is None else orientation - }) - commit = tag.props.get("onValueCommit") - if commit is None: - return tag - commit = LiteralVar.create(commit) - var_data = commit._get_all_var_data() - return tag.remove_props("onValueCommit").add_props( - on_pointer_up=commit, - on_key_up=Var( - f"((event) => {{ if ({_KEYS}.includes(event.key)) " - f"({commit!s})(event); }})", - _var_data=var_data, - ), - ) + given = { + name: value + for name, value in ( + ("disabled", self.disabled), + ("orientation", self.orientation), + ) + if value is not None + } + return super()._render(props).add_props(**given) + + def _exclude_props(self) -> list[str]: + """Keep the props that are styles off the slider. + + Returns: + The props read as styles, ``as_child`` and the width. + """ + return [*super()._exclude_props(), "as_child", "width"] slider = Slider.create diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py index 8a0172db8fb..a8afdcb5e5e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/accordion.py @@ -16,6 +16,8 @@ # turns it over. _TURN = "--rx-accordion-turn" +_MOTION = "@media (prefers-reduced-motion: no-preference)" + _RADIUS = tokens.radius[4] _LINE = gray.a[6] _FIRST = ":first-of-type" @@ -60,7 +62,7 @@ "width": "100%", "margin_top": {"default": "1px", _FIRST: "0"}, ":focus-within": {"position": "relative", "z_index": 1}, - _TURN: {"default": "none", "[open]": "rotate(180deg)"}, + _TURN: {"default": "none", "[data-open]": "rotate(180deg)"}, }), "variants": { "_ghost": { @@ -108,17 +110,9 @@ "defaults": {"_ghost": "false", "_divided": "false"}, } -# The summary of the item: what opens it, with nothing of the look the -# browser gives one. +# The heading of the item, around what opens it. ACCORDION_HEADER: ComponentStyles = { - "base": unchecked({ - "display": "flex", - "margin": "0", - "list_style_type": "none", - "::-webkit-details-marker": {"display": "none"}, - # A disabled item does not open: the pointer goes through its header. - "pointer_events": {"[aria-disabled='true']": "none"}, - }), + "base": {"display": "flex", "margin": "0"}, } ACCORDION_TRIGGER: ComponentStyles = { @@ -143,7 +137,8 @@ "padding_left": tokens.space[4], "padding_right": tokens.space[4], "width": "100%", - "background_color": {":hover": accent[4]}, + # A button, with none of the background the browser gives one. + "background_color": {"default": "transparent", ":hover": accent[4]}, }, "variants": { "_classic": { @@ -165,14 +160,28 @@ } ACCORDION_CONTENT: ComponentStyles = { - "base": { + "base": unchecked({ "overflow": "hidden", + # As tall as UI SDK measures what it holds, from nothing as it opens + # and to nothing as it closes, for whoever has not asked for less + # motion. The accordion says how long it takes. + "height": { + "default": "var(--accordion-panel-height, auto)", + "[data-starting-style]": "0", + "[data-ending-style]": "0", + }, + "transition_property": "height", + "transition_duration": { + "default": "0s", + _MOTION: f"var({DURATION})", + }, + "transition_timing_function": f"var({EASING})", "color": accent[11], "padding_left": tokens.space[4], "padding_right": tokens.space[4], # Room above and below what the panel holds, which opens with it. "_before": _PAD, "_after": _PAD, - }, + }), "variants": {"_classic": {"true": {"color": accent.contrast}}}, } diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py index 11491c688c7..687dcb96709 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/segmented_control.py @@ -35,9 +35,9 @@ _INACTIVE_EASING = "--rx-segmented-inactive-easing" _HOVER = "--rx-segmented-hover" -# The state of an item is the one of the radio button inside it. -_ON = ":has(> input:checked)" -_FOCUSED = ":has(> input:focus-visible)" +# The state of an item, which UI SDK says. +_ON = "[data-checked]" +_FOCUSED = ":focus-visible" # How many items the table places the indicator for. A control with more # literal items is given the further conditions as its own style. @@ -53,7 +53,7 @@ def chosen(position: int) -> str: Returns: The condition. """ - return f":has(> :nth-child({position}) > input:checked)" + return f":has(> button:nth-of-type({position})[data-checked])" def _size( @@ -100,7 +100,7 @@ def _size( # A stacking context: the indicator is behind the items, inside it. "isolation": "isolate", "border_radius": f"var({_RADIUS})", - _SHOWN: {"default": "none", ":has(> label > input:checked)": "block"}, + _SHOWN: {"default": "none", ":has(> [data-checked])": "block"}, INDEX: { "default": f"var({INDEX_OF_VALUE}, 0)", **{chosen(position): position - 1 for position in range(1, PLACED + 1)}, @@ -177,7 +177,7 @@ def _size( }, } -# An item: a label around its radio button, which is not seen. +# An item: a button, of none of the look the browser gives one. SEGMENTED_CONTROL_ITEM: ComponentStyles = { "base": unchecked({ "display": "flex", @@ -188,25 +188,32 @@ def _size( # As the button an item of Radix Themes is has none. "border_width": "0", "border_style": "none", + "background_color": "transparent", + "color": "inherit", + "font_family": "inherit", + "font_size": "inherit", + "font_weight": "inherit", + "line_height": "inherit", + "letter_spacing": "inherit", + "text_align": "inherit", + "outline_style": {"default": "none", _FOCUSED: "solid"}, "cursor": tokens.cursor.button, "WebkitTapHighlightColor": "transparent", - "border_top_left_radius": {":first-child": "inherit", _FOCUSED: "inherit"}, - "border_bottom_left_radius": {":first-child": "inherit", _FOCUSED: "inherit"}, - # The last item, before the indicator. - "border_top_right_radius": { - ":nth-last-child(2)": "inherit", + # The items are the buttons of the control: UI SDK puts the radio + # button of a form after each. + "border_top_left_radius": {":first-of-type": "inherit", _FOCUSED: "inherit"}, + "border_bottom_left_radius": { + ":first-of-type": "inherit", _FOCUSED: "inherit", }, + "border_top_right_radius": {":last-of-type": "inherit", _FOCUSED: "inherit"}, "border_bottom_right_radius": { - ":nth-last-child(2)": "inherit", + ":last-of-type": "inherit", _FOCUSED: "inherit", }, - _FOCUSED: { - "outline_width": "2px", - "outline_style": "solid", - "outline_color": focus[8], - "outline_offset": "-1px", - }, + "outline_width": {_FOCUSED: "2px"}, + "outline_color": {_FOCUSED: focus[8]}, + "outline_offset": {_FOCUSED: "-1px"}, _ACTIVE: {"default": 0, _ON: 1}, _INACTIVE: {"default": 1, _ON: 0}, _ACTIVE_EASING: {"default": "ease-in", _ON: "ease-out"}, @@ -216,16 +223,6 @@ def _size( }, }), "parts": { - "input": { - "base": { - "appearance": "none", - "position": "absolute", - "inset": "0", - "margin": "0", - "opacity": 0, - "pointer_events": "none", - }, - }, # The line between two items, behind the indicator. A rule of # base.css hides it beside the chosen item. "separator": { diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py index ecf6faffd17..12460152262 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/slider.py @@ -12,16 +12,14 @@ _TRACK = "--slider-track-size" _THUMB = "--slider-thumb-size" -# Where the filled part of the track starts and ends, which the slider sets -# from its values and its script moves with its thumbs. -START = "--rx-slider-start" -END = "--rx-slider-end" - -_DISABLED = ":has(:disabled)" +# What UI SDK sets on a disabled slider and each of its parts. +_DISABLED = "[data-disabled]" # The side of the thumb that is drawn: larger than the one that says how far # a thumb travels, so that it reaches a little past the filled part. _DRAWN = f"calc(var({_THUMB}) + var({_TRACK}) * 0.5)" -_PAST = f"calc(var({_TRACK}) * -0.25)" +# Where the middle of a thumb travels: half a thumb in from either end of the +# track, as in Radix Themes. +_TRAVEL = f"calc(var({_THUMB}) / 2)" _THUMB_SHADOWS = { "surface": f"0 0 0 1px {black.a[4]}", @@ -40,58 +38,26 @@ def _thumb(variant: str) -> dict[str, Any]: - """Make the thumb the browser draws for a range input, in one variant. + """Make the shadow of a thumb, in one variant. Args: variant: The variant. Returns: - The styles of the thumb, for every state of the input. + The shadow of the thumb, for every state of its range input. """ shadow = _THUMB_SHADOWS[variant] return { - "appearance": "none", - "box_sizing": "border-box", - "width": _DRAWN, - "height": _DRAWN, - "border_width": "0", - "border_style": "none", - "pointer_events": "auto", - "background_color": {"default": "white", ":disabled": gray[1]}, - "border_radius": f"max({tokens.radius[1]}, {tokens.radius.thumb})", "box_shadow": { "default": shadow, - ":focus-visible": ( + ":has(:focus-visible)": ( f"{shadow}, 0 0 0 3px {accent[3]}, 0 0 0 5px {tokens.focus[8]}" ), - ":disabled": f"0 0 0 1px {_THUMB_DISABLED[variant]}", - }, - "cursor": { - "default": tokens.cursor.slider_thumb, - ":active": tokens.cursor.slider_thumb_active, - ":disabled": tokens.cursor.disabled, + _DISABLED: f"0 0 0 1px {_THUMB_DISABLED[variant]}", }, } -def _input(variant: str) -> dict[str, Any]: - """Make the range input of a thumb, in one variant. - - Args: - variant: The variant. - - Returns: - The styles of the input: only its thumb is drawn, in each engine. - """ - clear = {"background_color": "transparent", "height": "100%"} - return { - "::-webkit-slider-runnable-track": clear, - "::-webkit-slider-thumb": _thumb(variant), - "::-moz-range-track": clear, - "::-moz-range-thumb": _thumb(variant), - } - - def _range(fill: dict[str, Any], disabled: bool) -> dict[str, Any]: """Make the filled part of a track. @@ -211,6 +177,20 @@ def _fill(variant: str, high_contrast: bool) -> dict[str, Any]: }, "defaults": {"size": "2", "variant": "surface", "orientation": "horizontal"}, "parts": { + # What UI SDK hears the pointer on: the track, and the thumbs over it. + "control": { + "base": { + "position": "relative", + "display": "flex", + "align_items": "center", + "flex_grow": 1, + "align_self": "stretch", + "border_radius": "inherit", + }, + "variants": { + "orientation": {"vertical": {"flex_direction": "column"}}, + }, + }, "track": { "base": { "overflow": "hidden", @@ -239,20 +219,8 @@ def _fill(variant: str, high_contrast: bool) -> dict[str, Any]: # The filled part: between the first thumb and the last, or from the # start of the track to the only one. "range": { - "base": {"position": "absolute", "border_radius": "inherit"}, + "base": {"border_radius": "inherit"}, "variants": { - "orientation": { - "horizontal": unchecked({ - "height": "100%", - "left": f"var({START})", - "right": f"calc(100% - var({END}))", - }), - "vertical": unchecked({ - "width": "100%", - "bottom": f"var({START})", - "top": f"calc(100% - var({END}))", - }), - }, "variant": { variant: unchecked(_fill(variant, False)) for variant in _VARIANTS }, @@ -272,47 +240,49 @@ def _fill(variant: str, high_contrast: bool) -> dict[str, Any]: }, ], }, - # A thumb: a range input of which only the thumb is drawn. It is - # wider than the track by what the drawn thumb reaches past it, so - # that the thumb travels as far as the one of Radix Themes. + # Where the thumbs travel, which the pointer goes through. + "thumbs": { + "base": {"position": "absolute", "pointer_events": "none"}, + "variants": { + "orientation": { + "horizontal": unchecked({ + "top": "0", + "bottom": "0", + "left": _TRAVEL, + "right": _TRAVEL, + }), + "vertical": unchecked({ + "left": "0", + "right": "0", + "top": _TRAVEL, + "bottom": _TRAVEL, + }), + }, + }, + "defaults": {"orientation": "horizontal"}, + }, + # A thumb, which UI SDK places, around the range input that takes the + # focus. "thumb": { "base": unchecked({ - "appearance": "none", - "position": "absolute", - "margin": "0", - "padding": "0", - "border_width": "0", - "border_style": "none", - "background_color": "transparent", - "outline_style": "none", - "cursor": "inherit", + "box_sizing": "border-box", + "width": _DRAWN, + "height": _DRAWN, + "pointer_events": "auto", + "background_color": {"default": "white", _DISABLED: gray[1]}, + "border_radius": f"max({tokens.radius[1]}, {tokens.radius.thumb})", + "cursor": { + "default": tokens.cursor.slider_thumb, + ":active": tokens.cursor.slider_thumb_active, + _DISABLED: tokens.cursor.disabled, + }, }), "variants": { - "orientation": { - "horizontal": { - "width": f"calc(100% + var({_TRACK}) * 0.5)", - "height": _DRAWN, - "left": _PAST, - "top": f"calc(50% - {_DRAWN} / 2)", - }, - "vertical": { - "height": f"calc(100% + var({_TRACK}) * 0.5)", - "width": _DRAWN, - "top": _PAST, - "left": f"calc(50% - {_DRAWN} / 2)", - # From the bottom up. - "writing_mode": "vertical-lr", - "direction": "rtl", - }, - }, "variant": { - variant: unchecked(_input(variant)) for variant in _VARIANTS + variant: unchecked(_thumb(variant)) for variant in _VARIANTS }, - # With several thumbs a pointer goes through an input to the - # ones below it, but for its thumb. - "_several": {"true": {"pointer_events": "none"}}, }, - "defaults": {"variant": "surface", "orientation": "horizontal"}, + "defaults": {"variant": "surface"}, }, }, } diff --git a/pyi_hashes.json b/pyi_hashes.json index bdae421259d..614e9c1282b 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -126,7 +126,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/_menu.pyi": "e15ed1f9c79ae63f275581338463ffd9", "packages/reflex-components-ui/src/reflex_components_ui/components/_popup.pyi": "80f094441cee591fff2e06d6e315dcc0", "packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.pyi": "555998b790703a343fa967893b0f775f", - "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "4cc79be854600aa47acc3899e4d7f12c", + "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "c899c6feec8ef54c7e6f5b772b58ee2f", "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "8116a4bc68a3d9607dfc44aa5f15dc22", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "296a02d4f7a276a0548ec473a6c761a9", @@ -152,11 +152,11 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/radio_cards.pyi": "0a0f621c1ceed962d86896ad1600e98f", "packages/reflex-components-ui/src/reflex_components_ui/components/radio_group.pyi": "e7f9c6ffd5f3d882ebe2fa4c06c0bcd0", "packages/reflex-components-ui/src/reflex_components_ui/components/scroll_area.pyi": "0b9bb867b1ef68c0fd9b10d52867d2b8", - "packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.pyi": "6c4bcbd1e1d2ee3effda901ad208fe56", + "packages/reflex-components-ui/src/reflex_components_ui/components/segmented_control.pyi": "e303501ce15ba7303e347b671dd04ca4", "packages/reflex-components-ui/src/reflex_components_ui/components/select.pyi": "eaab855301c61446950f54f84cf25e39", "packages/reflex-components-ui/src/reflex_components_ui/components/separator.pyi": "bd32f08f7c0ff2cb6733f964ea843440", "packages/reflex-components-ui/src/reflex_components_ui/components/skeleton.pyi": "4bedd989efb5b095b943a04830bbd140", - "packages/reflex-components-ui/src/reflex_components_ui/components/slider.pyi": "b5702134bebf0337effc41e3ddeffda8", + "packages/reflex-components-ui/src/reflex_components_ui/components/slider.pyi": "c7d786bf58459d00b765496176a5bae0", "packages/reflex-components-ui/src/reflex_components_ui/components/spinner.pyi": "9e62e8634e1425a75302d24fb458e8a8", "packages/reflex-components-ui/src/reflex_components_ui/components/switch.pyi": "7ec957d0bc2dfb273b9f6b8e8be50746", "packages/reflex-components-ui/src/reflex_components_ui/components/table.pyi": "3d2683d69d98f3cd14da65831e89e5fe", diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index c6ad979c5fa..a1d9848af23 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -869,7 +869,7 @@ def overlays(): tabs.content("Two", value="second", display="flex", id="second-panel"), default_value="first", ), - # An accordion left to the browser, and one whose open item stays. + # An accordion of several open items, and one whose open item stays. rx.ui.accordion.root( rx.ui.accordion.item(header="Shipping", content="Two days."), rx.ui.accordion.item(header="Returns", content="Thirty days."), @@ -1967,7 +1967,7 @@ def test_form_controls_work_in_an_app(ui_app: AppHarness, page: Page): page.get_by_text("Gift").click() # An item draws its text twice, one over the other. page.locator("#view").get_by_text("List").first.click(force=True) - page.locator("#volume").press("ArrowRight") + page.locator("#volume").get_by_role("slider").press("ArrowRight") # The form hands over the value of every control that has a name. page.locator("#send").click() @@ -2014,18 +2014,19 @@ def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): expect(first).to_be_visible() expect(page.get_by_role("tab", name="First")).to_be_focused() - # Items are native: the browser opens them, and the script of an - # accordion that does not collapse keeps its open item open. + # UI SDK opens the items, and keeps the open item of an accordion that + # does not collapse open. faq, account = page.locator("#faq"), page.locator("#account") faq.get_by_text("Shipping").click() faq.get_by_text("Returns").click() - expect(faq.locator("details[open]")).to_have_count(2) + expect(faq.locator("[aria-expanded=true]")).to_have_count(2) expect(faq.get_by_text("Two days.")).to_be_visible() - account.get_by_text("Plan").click() + # The open item says it cannot be pressed, as in Radix: pressed, it stays. + account.get_by_text("Plan").click(force=True) expect(account.get_by_text("Free.")).to_be_visible() account.get_by_text("Seats").click() expect(account.get_by_text("Five.")).to_be_visible() - expect(account.locator("details[open]")).to_have_count(1) + expect(account.locator("[aria-expanded=true]")).to_have_count(1) # The menus of a list share the ids they are rendered with: UI SDK tells # them apart, and places each sub-menu beside its item. diff --git a/tests/units/reflex_components_ui/components/test_accordion.py b/tests/units/reflex_components_ui/components/test_accordion.py index 1510291bc56..195e375302d 100644 --- a/tests/units/reflex_components_ui/components/test_accordion.py +++ b/tests/units/reflex_components_ui/components/test_accordion.py @@ -2,7 +2,7 @@ import itertools from collections.abc import Callable -from typing import Any, Literal +from typing import Any import pytest from reflex_base.utils.imports import ImportVar @@ -11,756 +11,220 @@ from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree @pytest.fixture(autouse=True) def ids(monkeypatch: pytest.MonkeyPatch): - """Number the accordions and the items of each test from one.""" + """Number the items of each test that are given no value from one.""" monkeypatch.setattr(accordion_module, "_ids", itertools.count(1)) -def test_accordion( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """An item is a native details: its header is the summary around a heading, and its panel a region the heading names. The root says how the panels move and gives the items their name and their look.""" - component = rx.ui.accordion.root( - rx.ui.accordion.item(header="One", content="First", value="one"), - rx.ui.accordion.item(header="Two", content="Second", disabled=True), - default_value="one", - variant="outline", - color_scheme="ruby", - radius="full", - duration=100, - easing="linear", - dir="rtl", - id="faq", +def _chevron() -> tuple[str, list[str], list[Any]]: + """The icon of the header of an item made from its ``header``. + + Returns: + The projection. + """ + return ( + "LucideChevronDown", + ['className:"AccordionChevron"', '"data-rx-accordion-icon":""'], + [], ) - assert component.render() == { - "name": '"div"', - "props": [ - 'className:sx_6a0d053193_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', - '"data-rx-accordion":"single"', - 'dir:"rtl"', - 'id:"faq"', - "onClick:accordionClick", - "ref:ref_faq", - ], - "children": [ - { - "name": '"details"', - "props": [ - 'className:"AccordionItem " + sx_563dab9fe8_c', - '"data-rx-accordion-item":""', - '"data-value":"one"', - 'name:"rx-accordion-2"', - "open:true", - ], - "children": [ - { - "name": '"summary"', - "props": ['className:"AccordionHeader " + sx_00d40261d7_c'], - "children": [ - { - "name": '"h3"', - "props": [ - 'className:"AccordionTrigger " + sx_90f62bd3b2_c', - 'id:"rx-accordion-2-trigger-one"', - ], - "children": [ - {"contents": '"One"'}, - { - "name": "LucideChevronDown", - "props": [ - 'className:"AccordionChevron"', - '"data-rx-accordion-icon":""', - ], - "children": [], - }, - ], - } - ], - }, - { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-accordion-2-trigger-one"', - 'className:"AccordionContent " + sx_b8a96ba61b_c', - 'role:"region"', - ], - "children": [{"contents": '"First"'}], - }, - ], - }, - { - "name": '"details"', - "props": [ - 'className:"AccordionItem " + sx_563dab9fe8_c', - '"data-rx-accordion-item":""', - '"data-value":"rx-accordion-item-1"', - 'name:"rx-accordion-2"', - "open:false", - ], - "children": [ - { - "name": '"summary"', - "props": [ - '"aria-disabled":true', - 'className:"AccordionHeader " + sx_00d40261d7_c', - "tabIndex:-1", - ], - "children": [ - { - "name": '"h3"', - "props": [ - 'className:"AccordionTrigger " + sx_90f62bd3b2_c', - 'id:"rx-accordion-2-trigger-rx-accordion-item-1"', - ], - "children": [ - {"contents": '"Two"'}, - { - "name": "LucideChevronDown", - "props": [ - 'className:"AccordionChevron"', - '"data-rx-accordion-icon":""', - ], - "children": [], - }, - ], - } - ], - }, - { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-accordion-2-trigger-rx-accordion-item-1"', - 'className:"AccordionContent " + sx_b8a96ba61b_c', - 'role:"region"', - ], - "children": [{"contents": '"Second"'}], - }, - ], - }, - ], - } - assert declared_styles(component) == [ - { - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "boxShadow": "0 2px 10px var(--black-a1)", - "borderTopWidth": "1px", - "borderRightWidth": "1px", - "borderBottomWidth": "1px", - "borderLeftWidth": "1px", - "borderTopStyle": "solid", - "borderRightStyle": "solid", - "borderBottomStyle": "solid", - "borderLeftStyle": "solid", - "borderTopColor": "var(--accent-6)", - "borderRightColor": "var(--accent-6)", - "borderBottomColor": "var(--accent-6)", - "borderLeftColor": "var(--accent-6)", - "--divider-px": "1px", - "--animation-duration": "100ms", - "--animation-easing": "linear", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "width": "100%", - "marginTop": {"default": "1px", ":first-of-type": "0"}, - "position": {":focus-within": "relative"}, - "zIndex": {":focus-within": 1}, - "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, - "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, - "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, - "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, - "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, - "borderTopWidth": {"default": "var(--divider-px)", ":first-of-type": "0"}, - "borderTopStyle": {"default": "solid", ":first-of-type": "none"}, - "borderTopColor": { - "default": "var(--gray-a6)", - ":first-of-type": "currentcolor", - }, - }, - { - "display": {"default": "flex", "::-webkit-details-marker": "none"}, - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "listStyleType": "none", - "pointerEvents": {"[aria-disabled='true']": "none"}, - }, - { - "boxSizing": "border-box", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "cursor": "default", - "fontSize": "1.1em", - "fontWeight": "inherit", - "lineHeight": 1, - "textAlign": "center", - "color": "var(--accent-11)", - "display": "flex", - "justifyContent": "space-between", - "alignItems": "center", - "flexGrow": 1, - "flexShrink": 1, - "flexBasis": "0%", - "paddingTop": "var(--space-3)", - "paddingBottom": "var(--space-3)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "width": "100%", - "backgroundColor": {":hover": "var(--accent-4)"}, - "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "color": "var(--accent-11)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "content": {"::before": "' '", "::after": "' '"}, - "display": {"::before": "block", "::after": "block"}, - "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "width": "100%", - "marginTop": {"default": "1px", ":first-of-type": "0"}, - "position": {":focus-within": "relative"}, - "zIndex": {":focus-within": 1}, - "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, - "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, - "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, - "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, - "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, - "borderTopWidth": {"default": "var(--divider-px)", ":first-of-type": "0"}, - "borderTopStyle": {"default": "solid", ":first-of-type": "none"}, - "borderTopColor": { - "default": "var(--gray-a6)", - ":first-of-type": "currentcolor", - }, - }, - { - "display": {"default": "flex", "::-webkit-details-marker": "none"}, - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "listStyleType": "none", - "pointerEvents": {"[aria-disabled='true']": "none"}, - }, - { - "boxSizing": "border-box", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "cursor": "default", - "fontSize": "1.1em", - "fontWeight": "inherit", - "lineHeight": 1, - "textAlign": "center", - "color": "var(--accent-11)", - "display": "flex", - "justifyContent": "space-between", - "alignItems": "center", - "flexGrow": 1, - "flexShrink": 1, - "flexBasis": "0%", - "paddingTop": "var(--space-3)", - "paddingBottom": "var(--space-3)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "width": "100%", - "backgroundColor": {":hover": "var(--accent-4)"}, - "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "color": "var(--accent-11)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "content": {"::before": "' '", "::after": "' '"}, - "display": {"::before": "block", "::after": "block"}, - "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, - }, - ] -def test_accordion_of_several_needs_no_script( - ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] -): - """An accordion of several items open at once is left to the browser: its items share no name, and nothing hears a press.""" - component = rx.ui.accordion.root( - rx.ui.accordion.item( - rx.ui.accordion.trigger("One", id="one"), - rx.ui.accordion.content("First"), - value="one", - variant="ghost", +def test_accordion(ui_plugin: UIPlugin): + """An accordion is the parts of UI SDK: an item, its heading, the button in it and its panel. + + A single accordion hands UI SDK the value of its open item in a list, + and its open item stays open unless it is collapsible, as in Radix. A + trigger without a header is given one, and Tab passes the trigger of a + disabled item. + """ + accordion = rx.ui.accordion + component = accordion.root( + accordion.item(header="One", content="1", value="a"), + accordion.item( + accordion.trigger("Two"), accordion.content("2"), value="b", disabled=True ), - rx.ui.accordion.item(header="Two", content="Second", value="two"), - type="multiple", - default_value=["two"], + type="single", + default_value="a", variant="soft", show_dividers=True, - disabled=True, + duration=300, ) - assert component.render() == { - "name": '"div"', - "props": ["className:sx_9bef01ebc0_c"], - "children": [ - { - "name": '"details"', - "props": [ - 'className:"AccordionItem " + sx_efc06f4e34_c', - '"data-rx-accordion-item":""', - '"data-value":"one"', - "open:false", - ], - "children": [ - { - "name": '"summary"', - "props": [ - '"aria-disabled":true', - 'className:"AccordionHeader " + sx_00d40261d7_c', - "tabIndex:-1", - ], - "children": [ - { - "name": '"h3"', - "props": [ - 'className:"AccordionTrigger " + sx_90f62bd3b2_c', - 'id:"one"', - "ref:ref_one", - ], - "children": [{"contents": '"One"'}], - } - ], - }, - { - "name": '"div"', - "props": [ - '"aria-labelledby":"one"', - 'className:"AccordionContent " + sx_b8a96ba61b_c', - 'role:"region"', - ], - "children": [{"contents": '"First"'}], - }, + item = 'className:"AccordionItem " + sx_d4628081b9_c' + header = 'className:"AccordionHeader " + sx_31eb8acee3_c' + trigger = 'className:"AccordionTrigger " + sx_670a53a6b1_c' + panel = 'className:"AccordionContent " + sx_b87df07e92_c' + assert tree(component.render()) == ( + "Accordion", + ["className:sx_07523392e3_c", "collapsible:false", 'defaultValue:["a"]'], + [ + ( + "AccordionItem", + [item, '"data-rx-accordion-item":""', 'value:"a"'], + [ + ( + "AccordionHeader", + [header], + [("AccordionTrigger", [trigger], ['"One"', _chevron()])], + ), + ("AccordionPanel", [panel], ['"1"']), ], - }, - { - "name": '"details"', - "props": [ - 'className:"AccordionItem " + sx_563dab9fe8_c', - '"data-rx-accordion-item":""', - '"data-value":"two"', - "open:true", + ), + ( + "AccordionItem", + [item, '"data-rx-accordion-item":""', "disabled:true", 'value:"b"'], + [ + ( + "AccordionHeader", + [header], + [("AccordionTrigger", [trigger, "tabIndex:-1"], ['"Two"'])], + ), + ("AccordionPanel", [panel], ['"2"']), ], - "children": [ - { - "name": '"summary"', - "props": [ - '"aria-disabled":true', - 'className:"AccordionHeader " + sx_00d40261d7_c', - "tabIndex:-1", - ], - "children": [ - { - "name": '"h3"', - "props": [ - 'className:"AccordionTrigger " + sx_90f62bd3b2_c', - 'id:"rx-accordion-1-trigger-two"', - ], - "children": [ - {"contents": '"Two"'}, - { - "name": "LucideChevronDown", - "props": [ - 'className:"AccordionChevron"', - '"data-rx-accordion-icon":""', - ], - "children": [], - }, - ], - } - ], - }, - { - "name": '"div"', - "props": [ - '"aria-labelledby":"rx-accordion-1-trigger-two"', - 'className:"AccordionContent " + sx_b8a96ba61b_c', - 'role:"region"', - ], - "children": [{"contents": '"Second"'}], - }, - ], - }, + ), ], - } - assert declared_styles(component) == [ - { - "borderTopLeftRadius": "var(--radius-4)", - "borderTopRightRadius": "var(--radius-4)", - "borderBottomRightRadius": "var(--radius-4)", - "borderBottomLeftRadius": "var(--radius-4)", - "boxShadow": "0 2px 10px var(--black-a1)", - "backgroundColor": "var(--accent-3)", - "--animation-duration": "250ms", - "--animation-easing": "cubic-bezier(0.87, 0, 0.13, 1)", - "--divider-px": "1px", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "width": "100%", - "marginTop": {"default": "1px", ":first-of-type": "0"}, - "position": {":focus-within": "relative"}, - "zIndex": {":focus-within": 1}, - "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, - "borderTopWidth": "var(--divider-px)", - "borderTopStyle": "solid", - "borderTopColor": "var(--gray-a6)", - "borderBottomWidth": {":last-child": "var(--divider-px)"}, - "borderBottomStyle": {":last-child": "solid"}, - "borderBottomColor": {":last-child": "var(--gray-a6)"}, - }, - { - "display": {"default": "flex", "::-webkit-details-marker": "none"}, - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "listStyleType": "none", - "pointerEvents": {"[aria-disabled='true']": "none"}, - }, - { - "boxSizing": "border-box", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "cursor": "default", - "fontSize": "1.1em", - "fontWeight": "inherit", - "lineHeight": 1, - "textAlign": "center", - "color": "var(--accent-11)", - "display": "flex", - "justifyContent": "space-between", - "alignItems": "center", - "flexGrow": 1, - "flexShrink": 1, - "flexBasis": "0%", - "paddingTop": "var(--space-3)", - "paddingBottom": "var(--space-3)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "width": "100%", - "backgroundColor": {":hover": "var(--accent-4)"}, - "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "color": "var(--accent-11)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "content": {"::before": "' '", "::after": "' '"}, - "display": {"::before": "block", "::after": "block"}, - "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "width": "100%", - "marginTop": {"default": "1px", ":first-of-type": "0"}, - "position": {":focus-within": "relative"}, - "zIndex": {":focus-within": 1}, - "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, - "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, - "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, - "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, - "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, - "borderTopWidth": {"default": "var(--divider-px)", ":first-of-type": "0"}, - "borderTopStyle": {"default": "solid", ":first-of-type": "none"}, - "borderTopColor": { - "default": "var(--gray-a6)", - ":first-of-type": "currentcolor", - }, - }, - { - "display": {"default": "flex", "::-webkit-details-marker": "none"}, - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "listStyleType": "none", - "pointerEvents": {"[aria-disabled='true']": "none"}, - }, - { - "boxSizing": "border-box", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "cursor": "default", - "fontSize": "1.1em", - "fontWeight": "inherit", - "lineHeight": 1, - "textAlign": "center", - "color": "var(--accent-11)", - "display": "flex", - "justifyContent": "space-between", - "alignItems": "center", - "flexGrow": 1, - "flexShrink": 1, - "flexBasis": "0%", - "paddingTop": "var(--space-3)", - "paddingBottom": "var(--space-3)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "width": "100%", - "backgroundColor": {":hover": "var(--accent-4)"}, - "boxShadow": "0 var(--divider-px) 0 var(--gray-a6)", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "color": "var(--accent-11)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "content": {"::before": "' '", "::after": "' '"}, - "display": {"::before": "block", "::after": "block"}, - "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, - }, - ] + ) -def test_accordion_item_alone( +def test_accordion_styles( ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] ): - """An item outside an accordion is one of an accordion without props.""" - component = rx.ui.accordion.item(header="Alone", content="Panel") - assert component.render() == { - "name": '"details"', - "props": [ - 'className:"AccordionItem " + sx_aad5443040_c', - '"data-rx-accordion-item":""', - '"data-value":"rx-accordion-item-1"', - ], - "children": [ - { - "name": '"summary"', - "props": ['className:"AccordionHeader " + sx_00d40261d7_c'], - "children": [ - { - "name": '"h3"', - "props": ['className:"AccordionTrigger " + sx_b2de2d1617_c'], - "children": [ - {"contents": '"Alone"'}, - { - "name": "LucideChevronDown", - "props": [ - 'className:"AccordionChevron"', - '"data-rx-accordion-icon":""', - ], - "children": [], - }, - ], - } - ], - }, - { - "name": '"div"', - "props": [ - 'className:"AccordionContent " + sx_b8a96ba61b_c', - 'role:"region"', - ], - "children": [{"contents": '"Panel"'}], - }, - ], + """An open item turns its icon over, the trigger is a button of no background but its hover, and a panel grows to the height UI SDK measures.""" + accordion = rx.ui.accordion + component = accordion.root(accordion.item(header="One", content="1", value="a")) + _, item, _, trigger, panel = declared_styles(component) + assert item["--rx-accordion-turn"] == { + "default": "none", + "[data-open]": "rotate(180deg)", + } + assert trigger["backgroundColor"] == { + "default": "transparent", + ":hover": "var(--accent-10)", + } + assert { + key: panel[key] + for key in ( + "height", + "transitionProperty", + "transitionDuration", + "transitionTimingFunction", + ) + } == { + # The room above and below what the panel holds is as tall as in Radix. + "height": { + "default": "var(--accordion-panel-height, auto)", + "[data-starting-style]": "0", + "[data-ending-style]": "0", + "::before": "var(--space-3)", + "::after": "var(--space-3)", + }, + "transitionProperty": "height", + "transitionDuration": { + "default": "0s", + "@media (prefers-reduced-motion: no-preference)": "var(--animation-duration)", + }, + "transitionTimingFunction": "var(--animation-easing)", } - assert declared_styles(component) == [ - { - "overflowX": "hidden", - "overflowY": "hidden", - "width": "100%", - "marginTop": {"default": "1px", ":first-of-type": "0"}, - "position": {":focus-within": "relative"}, - "zIndex": {":focus-within": 1}, - "--rx-accordion-turn": {"default": "none", "[open]": "rotate(180deg)"}, - "borderTopLeftRadius": {":first-of-type": "var(--radius-4)"}, - "borderTopRightRadius": {":first-of-type": "var(--radius-4)"}, - "borderBottomLeftRadius": {":last-child": "var(--radius-4)"}, - "borderBottomRightRadius": {":last-child": "var(--radius-4)"}, - "borderTopStyle": "none", - }, - { - "display": {"default": "flex", "::-webkit-details-marker": "none"}, - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "listStyleType": "none", - "pointerEvents": {"[aria-disabled='true']": "none"}, - }, - { - "boxSizing": "border-box", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "cursor": "default", - "fontSize": "1.1em", - "fontWeight": "inherit", - "lineHeight": 1, - "textAlign": "center", - "color": "var(--accent-11)", - "display": "flex", - "justifyContent": "space-between", - "alignItems": "center", - "flexGrow": 1, - "flexShrink": 1, - "flexBasis": "0%", - "paddingTop": "var(--space-3)", - "paddingBottom": "var(--space-3)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "width": "100%", - "backgroundColor": {":hover": "var(--accent-4)"}, - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "color": "var(--accent-11)", - "paddingLeft": "var(--space-4)", - "paddingRight": "var(--space-4)", - "content": {"::before": "' '", "::after": "' '"}, - "display": {"::before": "block", "::after": "block"}, - "height": {"::before": "var(--space-3)", "::after": "var(--space-3)"}, - }, - ] class AccordionState(rx.State): """What an accordion is bound to.""" - open_item: str = "b" - kind: Literal["classic", "soft", "surface", "outline", "ghost"] = "soft" - shown: bool = True + open: list[str] = ["a"] + off: bool = False @rx.event def set_open(self, value: str | list[str]): """Follow the accordion. Args: - value: The value of the open item. + value: The values of the open items. """ - self.open_item = str(value) + self.open = value if isinstance(value, list) else [value] def test_accordion_bound_to_state(ui_plugin: UIPlugin): - """An accordion bound to state renders its state as expressions, and hands the script what it does on a change.""" - open_item, kind, shown = ( - str(AccordionState.open_item), - str(AccordionState.kind), - str(AccordionState.shown), - ) - component = rx.ui.accordion.root( - rx.ui.accordion.item(header="A", content="x", value="a"), - value=AccordionState.open_item, + """A multiple accordion bound to state hands UI SDK its list, and hands over the list UI SDK says; a disabled one takes its triggers out of the order of Tab.""" + name = AccordionState.get_full_name() + accordion = rx.ui.accordion + component = accordion.root( + accordion.item(header="One", content="1", value="a"), + type="multiple", + value=AccordionState.open, on_value_change=AccordionState.set_open, - variant=AccordionState.kind, - show_dividers=AccordionState.shown, collapsible=True, + disabled=AccordionState.off, ) - rendered = component.render() - assert rendered["props"] == [ - f'className:sx_c35f0e8dde_c + " " + (sx_c35f0e8dde_0[{kind}] ?? sx_c35f0e8dde_0d)', - '"data-bound":""', - '"data-collapsible":true', - '"data-rx-accordion":"single"', + open_ = f"{AccordionState.open!s}" + rendered = tree(component.render()) + assert rendered[1] == [ + "className:sx_5d094c6338_c", + "collapsible:true", + f"disabled:{AccordionState.off!s}", + "multiple:true", ( - "onClick:((event) => accordionClick(event, ((_value) => (addEvents([(ReflexEvent(" - f'"{AccordionState.get_full_name()}.set_open", ({{ ["value"] : _value }}), ' - "({ })))], [_value], ({ }))))))" + "onValueChange:((_value) => (addEvents([(ReflexEvent(" + f'"{name}.set_open", ({{ ["value"] : _value }}), ({{ }})))], [_value], ' + "({ }))))" ), - f'style:({{ "--v0": (({shown} ? "1px" : "0")) ?? "initial" }})', + f"value:(Array.isArray({open_}) ? {open_} : ({open_} ? [{open_}] : []))", ] - item = rendered["children"][0] - assert item["props"] == [ - ( - 'className:"AccordionItem " + sx_33774f392f_c + " " + (sx_33774f392f_0[' - f'((["ghost"].includes({kind})) ? "true" : "false")] ?? sx_33774f392f_0d)' - ), - '"data-rx-accordion-item":""', - '"data-value":"a"', - 'name:"rx-accordion-1"', - f'open:({open_item} === "a")', + assert rendered[2][0][2][0][2][0][1] == [ + 'className:"AccordionTrigger " + sx_4a120e8568_c', + f"tabIndex:({AccordionState.off!s} ? -1 : null)", ] - assert item["children"][0]["children"][0]["props"] == [ + + +def test_accordion_single_hands_over_the_value_of_its_open_item(ui_plugin: UIPlugin): + """A single accordion hands over the value of its open item, or "", as Radix does.""" + accordion = rx.ui.accordion + component = accordion.root( + accordion.item(header="One", content="1", value="a"), + on_value_change=rx.console_log("x"), + ) + assert tree(component.render())[1] == [ + "className:sx_5d094c6338_c", + "collapsible:false", ( - 'className:"AccordionTrigger " + sx_631c017a79_c + " " + (sx_631c017a79_0[' - f'((["classic"].includes({kind})) ? "true" : "false")] ?? sx_631c017a79_0d)' + 'onValueChange:((value) => (((_value) => (addEvents([(ReflexEvent("_call_function", ' + '({ ["function"] : (() => (console?.["log"]("x"))), ["callback"] : null }), ' + '({ })))], [_value], ({ })))))(value[0] ?? ""))' ), - 'id:"rx-accordion-1-trigger-a"', ] -@pytest.mark.parametrize( - ("props", "scripts"), - [ - ({}, [ImportVar(tag="accordionClick")]), - ({"collapsible": True}, None), - ({"type": "multiple"}, None), - ({"type": "multiple", "value": ["a"]}, [ImportVar(tag="accordionClick")]), - ( - {"type": "multiple", "on_value_change": rx.console_log}, - [ImportVar(tag="accordionClick")], - ), - ], -) -def test_accordion_loads_its_script_only_for_what_the_browser_does_not_do( - ui_plugin: UIPlugin, props: dict[str, Any], scripts: list[ImportVar] | None -): - """A page loads the script of an accordion whose open item stays open, that is bound to state or that says what is open.""" - component = rx.ui.accordion.root( - rx.ui.accordion.item(header="A", content="x", value="a"), **props - ) - assert ( - component._get_all_imports().get("$/reflex-ui/behaviors/accordion.js") - == scripts +def test_accordion_item_without_a_value_is_given_one(ui_plugin: UIPlugin): + """An item given no value has one no other item of the app has: UI SDK tells the items apart by it.""" + first, second = ( + rx.ui.accordion.item(header=text, content=text) for text in ("One", "Two") ) + assert [first.render()["props"][-1], second.render()["props"][-1]] == [ + 'value:"rx-accordion-item-1"', + 'value:"rx-accordion-item-2"', + ] + + +def test_accordion_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with an accordion imports its parts from UI SDK, pinned, and no script.""" + accordion = rx.ui.accordion + component = accordion.root(accordion.item(header="One", content="1", value="a")) + assert { + module: names + for module, names in component._get_all_imports().items() + if "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/accordion": [ + ImportVar(tag="Accordion"), + ImportVar(tag="AccordionItem"), + ImportVar(tag="AccordionHeader"), + ImportVar(tag="AccordionTrigger"), + ImportVar(tag="AccordionPanel"), + ], + } def test_accordion_refuses_a_variant_it_does_not_have(ui_plugin: UIPlugin): diff --git a/tests/units/reflex_components_ui/components/test_segmented_control.py b/tests/units/reflex_components_ui/components/test_segmented_control.py index 3650bf98707..88b580b92d7 100644 --- a/tests/units/reflex_components_ui/components/test_segmented_control.py +++ b/tests/units/reflex_components_ui/components/test_segmented_control.py @@ -1,23 +1,60 @@ """Tests for reflex_components_ui.components.segmented_control.""" -import itertools import re from collections.abc import Callable from typing import Any import pytest from reflex_base.utils.imports import ImportVar -from reflex_components_ui.components import _group from reflex_components_ui.plugin import UIPlugin from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree + +# The keys of Radix the control adds to UI SDK's: Enter, Home and End. +KEYS = ( + "onKeyDown:((event) => { const item = event.target.closest('[role=radio]'); if " + "(!item || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; " + 'if (event.key === "Enter") { event.preventDefault(); item.click(); return; } if ' + '(event.key !== "Home" && event.key !== "End") return; const items = ' + "event.currentTarget.querySelectorAll('[role=radio]:not(:disabled)'); " + 'event.preventDefault(); items[event.key === "Home" ? 0 : items.length - ' + "1]?.focus(); })" +) + +# What the control does with a change UI SDK asks for when nothing hears it: +# it refuses the one of the arrow keys. +REFUSES = ( + 'onValueChange:((value, details) => { if (details?.reason === "list-navigation") ' + "{ details.cancel(); return; } })" +) + + +def _text(text: str) -> tuple[str, list[str], list[Any]]: + """The text of an item, twice: medium while chosen, regular otherwise. + + Args: + text: The text. + + Returns: + The projection of the label of the item. + """ + return ( + '"span"', + ["className:sx_f91740a5b0_c"], + [ + ('"span"', ["className:sx_48fb0dc076_c"], [f'"{text}"']), + ( + '"span"', + ['"aria-hidden":true', "className:sx_d60de3577e_c"], + [f'"{text}"'], + ), + ], + ) -@pytest.fixture(autouse=True) -def names(monkeypatch: pytest.MonkeyPatch): - """Number the controls of each test from one: the name groups their items.""" - monkeypatch.setattr(_group, "_names", itertools.count(1)) +SEPARATOR = ('"span"', ["className:sx_f0662e97c2_c"], []) class SegmentedState(rx.State): @@ -36,11 +73,12 @@ def set_view(self, view: str): self.view = view -def test_segmented_control( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], -): - """An item is a label around a native radio button and its text, twice; the control counts its items for what marks the chosen one.""" +def test_segmented_control(ui_plugin: UIPlugin): + """A segmented control is the parts of UI SDK, its items a button each with the line before it and its text twice. + + The control counts its items for what marks the chosen one, whatever + its type: as in Radix Themes, one item is chosen. + """ component = rx.ui.segmented_control.root( rx.ui.segmented_control.item("One", value="1", id="one"), rx.ui.segmented_control.item("Two", value="2", margin="1px"), @@ -52,423 +90,98 @@ def test_segmented_control( type="multiple", id="views", ) - assert component.render() == { - "name": '"div"', - "props": [ - 'className:sx_66f6ec5e0a_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', + assert tree(component.render()) == ( + "SegmentedControl", + [ + ( + 'className:sx_bf2c61f2b5_c + " " + reflexUIClasses_e201574881 + " " + ' + "reflexUIClasses_4c7cd6a7ce" + ), + 'defaultValue:"2"', 'id:"views"', - "onKeyDown:rovingKeyDown", + KEYS, + REFUSES, "ref:ref_views", - 'role:"radiogroup"', ], - "children": [ - { - "name": '"label"', - "props": ["className:sx_7f4c9c997f_c", '"data-rx-segmented-item":""'], - "children": [ - { - "name": '"input"', - "props": [ - "className:sx_8e51139181_c", - 'form:""', - 'id:"one"', - 'name:"rx-segmented-1"', - "ref:ref_one", - 'type:"radio"', - 'value:"1"', - ], - "children": [], - }, - { - "name": '"span"', - "props": ["className:sx_f0662e97c2_c"], - "children": [], - }, - { - "name": '"span"', - "props": ["className:sx_f91740a5b0_c"], - "children": [ - { - "name": '"span"', - "props": ["className:sx_48fb0dc076_c"], - "children": [{"contents": '"One"'}], - }, - { - "name": '"span"', - "props": [ - '"aria-hidden":true', - "className:sx_d60de3577e_c", - ], - "children": [{"contents": '"One"'}], - }, - ], - }, + [ + ( + "SegmentedControlItem", + [ + "className:sx_c3ab422107_c", + '"data-rx-segmented-item":""', + 'id:"one"', + "ref:ref_one", + 'value:"1"', ], - }, - { - "name": '"label"', - "props": ["className:sx_c43e9e9803_c", '"data-rx-segmented-item":""'], - "children": [ - { - "name": '"input"', - "props": [ - "className:sx_8e51139181_c", - "defaultChecked:true", - 'form:""', - 'name:"rx-segmented-1"', - 'type:"radio"', - 'value:"2"', - ], - "children": [], - }, - { - "name": '"span"', - "props": ["className:sx_f0662e97c2_c"], - "children": [], - }, - { - "name": '"span"', - "props": ["className:sx_f91740a5b0_c"], - "children": [ - { - "name": '"span"', - "props": ["className:sx_48fb0dc076_c"], - "children": [{"contents": '"Two"'}], - }, - { - "name": '"span"', - "props": [ - '"aria-hidden":true', - "className:sx_d60de3577e_c", - ], - "children": [{"contents": '"Two"'}], - }, - ], - }, + [SEPARATOR, _text("One")], + ), + ( + "SegmentedControlItem", + [ + "className:sx_f1f474e393_c", + '"data-rx-segmented-item":""', + 'value:"2"', ], - }, - {"name": '"div"', "props": ["className:sx_3a340e571a_c"], "children": []}, + [SEPARATOR, _text("Two")], + ), + ('"div"', ["className:sx_3a340e571a_c"], []), ], + ) + + +def test_segmented_control_styles( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """An item is chosen and focused by UI SDK's state, and the corners of the first and the last button are the control's.""" + item = rx.ui.segmented_control.item + component = rx.ui.segmented_control.root( + item("One", value="1"), item("Two", value="2") + ) + root, first, *_ = declared_styles(component) + assert root["--rx-segmented-indicator"] == { + "default": "none", + ":has(> [data-checked])": "block", } - assert declared_styles(component) == [ - { - "boxSizing": "border-box", - "display": "inline-grid", - "verticalAlign": "top", - "gridAutoFlow": "column", - "gridAutoColumns": "1fr", - "alignItems": "stretch", - "color": "var(--gray-12)", - "backgroundColor": "var(--color-surface)", - "backgroundImage": "linear-gradient(var(--gray-a3), var(--gray-a3))", - "position": "relative", - "minWidth": "max-content", - "fontFamily": "var(--default-font-family)", - "fontStyle": "normal", - "textAlign": "center", - "isolation": "isolate", - "borderRadius": "var(--segmented-control-border-radius)", - "--rx-segmented-indicator": { - "default": "none", - ":has(> label > input:checked)": "block", - }, - "--rx-segmented-index": { - "default": "var(--rx-segmented-index-of-value, 0)", - ":has(> :nth-child(1) > input:checked)": 0, - ":has(> :nth-child(2) > input:checked)": 1, - ":has(> :nth-child(3) > input:checked)": 2, - ":has(> :nth-child(4) > input:checked)": 3, - ":has(> :nth-child(5) > input:checked)": 4, - ":has(> :nth-child(6) > input:checked)": 5, - ":has(> :nth-child(7) > input:checked)": 6, - ":has(> :nth-child(8) > input:checked)": 7, - ":has(> :nth-child(9) > input:checked)": 8, - ":has(> :nth-child(10) > input:checked)": 9, - }, - "--rx-segmented-separator-duration": { - "default": "80ms", - ":has(:focus-visible)": "0ms", - }, - "--segmented-control-border-radius": "max(var(--radius-3), var(--radius-full))", - "height": "var(--space-7)", - "--rx-segmented-font-size": "var(--font-size-3)", - "--rx-segmented-letter-spacing": "var(--letter-spacing-3)", - "--rx-segmented-padding": "var(--space-4)", - "--rx-segmented-gap": "var(--space-3)", - "--rx-segmented-count": 2, - }, - { - "display": "flex", - "alignItems": "stretch", - "userSelect": "none", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "cursor": "var(--cursor-button)", - "WebkitTapHighlightColor": "transparent", - "borderTopLeftRadius": { - ":first-child": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "borderBottomLeftRadius": { - ":first-child": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "borderTopRightRadius": { - ":nth-last-child(2)": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "borderBottomRightRadius": { - ":nth-last-child(2)": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "outlineWidth": {":has(> input:focus-visible)": "2px"}, - "outlineStyle": {":has(> input:focus-visible)": "solid"}, - "outlineColor": {":has(> input:focus-visible)": "var(--focus-8)"}, - "outlineOffset": {":has(> input:focus-visible)": "-1px"}, - "--rx-segmented-active-opacity": {"default": 0, ":has(> input:checked)": 1}, - "--rx-segmented-inactive-opacity": { - "default": 1, - ":has(> input:checked)": 0, - }, - "--rx-segmented-active-easing": { - "default": "ease-in", - ":has(> input:checked)": "ease-out", - }, - "--rx-segmented-inactive-easing": { - "default": "ease-out", - ":has(> input:checked)": "ease-in", - }, - "--rx-segmented-hover": { - "@media (hover: hover)": { - ":hover:not(:has(> input:checked))": "var(--gray-a2)" - } - }, - }, - { - "appearance": "none", - "position": "absolute", - "top": "0", - "right": "0", - "bottom": "0", - "left": "0", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "opacity": 0, - "pointerEvents": "none", - }, - { - "zIndex": -1, - "marginTop": "3px", - "marginBottom": "3px", - "marginLeft": "-0.5px", - "marginRight": "-0.5px", - "width": "1px", - "backgroundColor": "var(--gray-a4)", - "opacity": "var(--rx-segmented-separator-opacity, 1)", - "transitionProperty": "opacity", - "transitionDuration": "var(--rx-segmented-separator-duration)", - "transitionTimingFunction": "var(--rx-segmented-separator-easing, ease-out)", - }, - { - "boxSizing": "border-box", - "display": "flex", - "flexGrow": 1, - "alignItems": "center", - "justifyContent": "center", - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "fontSize": "var(--rx-segmented-font-size)", - "letterSpacing": "var(--rx-segmented-letter-spacing)", - "paddingLeft": "var(--rx-segmented-padding)", - "paddingRight": "var(--rx-segmented-padding)", - "gap": "var(--rx-segmented-gap)", - "backgroundColor": "var(--rx-segmented-hover, transparent)", - }, - { - "transitionProperty": "opacity", - "transitionDuration": "80ms", - "transitionTimingFunction": "var(--rx-segmented-active-easing)", - "fontWeight": "var(--font-weight-medium)", - "letterSpacing": "var(--tab-active-letter-spacing)", - "wordSpacing": "var(--tab-active-word-spacing)", - "opacity": "var(--rx-segmented-active-opacity)", - }, - { - "position": "absolute", - "transitionProperty": "opacity", - "transitionDuration": "80ms", - "transitionTimingFunction": "var(--rx-segmented-inactive-easing)", - "fontWeight": "var(--font-weight-regular)", - "letterSpacing": "var(--tab-inactive-letter-spacing)", - "wordSpacing": "var(--tab-inactive-word-spacing)", - "opacity": "var(--rx-segmented-inactive-opacity)", - }, - { - "display": "flex", - "alignItems": "stretch", - "userSelect": "none", - "marginTop": "1px", - "marginRight": "1px", - "marginBottom": "1px", - "marginLeft": "1px", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": "0", - "borderRightWidth": "0", - "borderBottomWidth": "0", - "borderLeftWidth": "0", - "borderTopStyle": "none", - "borderRightStyle": "none", - "borderBottomStyle": "none", - "borderLeftStyle": "none", - "cursor": "var(--cursor-button)", - "WebkitTapHighlightColor": "transparent", - "borderTopLeftRadius": { - ":first-child": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "borderBottomLeftRadius": { - ":first-child": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "borderTopRightRadius": { - ":nth-last-child(2)": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "borderBottomRightRadius": { - ":nth-last-child(2)": "inherit", - ":has(> input:focus-visible)": "inherit", - }, - "outlineWidth": {":has(> input:focus-visible)": "2px"}, - "outlineStyle": {":has(> input:focus-visible)": "solid"}, - "outlineColor": {":has(> input:focus-visible)": "var(--focus-8)"}, - "outlineOffset": {":has(> input:focus-visible)": "-1px"}, - "--rx-segmented-active-opacity": {"default": 0, ":has(> input:checked)": 1}, - "--rx-segmented-inactive-opacity": { - "default": 1, - ":has(> input:checked)": 0, - }, - "--rx-segmented-active-easing": { - "default": "ease-in", - ":has(> input:checked)": "ease-out", - }, - "--rx-segmented-inactive-easing": { - "default": "ease-out", - ":has(> input:checked)": "ease-in", - }, - "--rx-segmented-hover": { - "@media (hover: hover)": { - ":hover:not(:has(> input:checked))": "var(--gray-a2)" - } - }, - }, - { - "appearance": "none", - "position": "absolute", - "top": "0", - "right": "0", - "bottom": "0", - "left": "0", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "opacity": 0, - "pointerEvents": "none", - }, - { - "zIndex": -1, - "marginTop": "3px", - "marginBottom": "3px", - "marginLeft": "-0.5px", - "marginRight": "-0.5px", - "width": "1px", - "backgroundColor": "var(--gray-a4)", - "opacity": "var(--rx-segmented-separator-opacity, 1)", - "transitionProperty": "opacity", - "transitionDuration": "var(--rx-segmented-separator-duration)", - "transitionTimingFunction": "var(--rx-segmented-separator-easing, ease-out)", + assert { + key: first[key] + for key in ( + "borderTopLeftRadius", + "borderTopRightRadius", + "outlineStyle", + "--rx-segmented-active-opacity", + ) + } == { + "borderTopLeftRadius": { + ":first-of-type": "inherit", + ":focus-visible": "inherit", }, - { - "boxSizing": "border-box", - "display": "flex", - "flexGrow": 1, - "alignItems": "center", - "justifyContent": "center", - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "fontSize": "var(--rx-segmented-font-size)", - "letterSpacing": "var(--rx-segmented-letter-spacing)", - "paddingLeft": "var(--rx-segmented-padding)", - "paddingRight": "var(--rx-segmented-padding)", - "gap": "var(--rx-segmented-gap)", - "backgroundColor": "var(--rx-segmented-hover, transparent)", - }, - { - "transitionProperty": "opacity", - "transitionDuration": "80ms", - "transitionTimingFunction": "var(--rx-segmented-active-easing)", - "fontWeight": "var(--font-weight-medium)", - "letterSpacing": "var(--tab-active-letter-spacing)", - "wordSpacing": "var(--tab-active-word-spacing)", - "opacity": "var(--rx-segmented-active-opacity)", - }, - { - "position": "absolute", - "transitionProperty": "opacity", - "transitionDuration": "80ms", - "transitionTimingFunction": "var(--rx-segmented-inactive-easing)", - "fontWeight": "var(--font-weight-regular)", - "letterSpacing": "var(--tab-inactive-letter-spacing)", - "wordSpacing": "var(--tab-inactive-word-spacing)", - "opacity": "var(--rx-segmented-inactive-opacity)", - }, - { - "display": "var(--rx-segmented-indicator)", - "position": {"default": "absolute", "::before": "absolute"}, - "zIndex": -1, - "top": {"default": "0", "::before": "1px"}, - "left": {"default": "0", "::before": "1px"}, - "height": "100%", - "width": "calc(100% / var(--rx-segmented-count))", - "transform": "translateX(calc(var(--rx-segmented-index) * 100%))", - "pointerEvents": "none", - "transitionProperty": "transform", - "transitionTimingFunction": "cubic-bezier(0.445, 0.05, 0.55, 0.95)", - "transitionDuration": "100ms", - "right": {"::before": "1px"}, - "bottom": {"::before": "1px"}, - "borderRadius": { - "::before": "max(0.5px, calc(var(--segmented-control-border-radius) - 1px))" - }, - "backgroundColor": { - "::before": "light-dark(var(--color-background), var(--gray-a3))" - }, - "content": {"::before": "''"}, - "boxShadow": {"::before": "var(--shadow-2)"}, + "borderTopRightRadius": { + ":last-of-type": "inherit", + ":focus-visible": "inherit", }, + "outlineStyle": {"default": "none", ":focus-visible": "solid"}, + "--rx-segmented-active-opacity": {"default": 0, "[data-checked]": 1}, + } + + +def test_segmented_control_bound_to_state(ui_plugin: UIPlugin): + """A control bound to state takes its value from it, and hands over the value of an item that is chosen, not one the arrow keys reach.""" + name = SegmentedState.get_full_name() + control = rx.ui.segmented_control.root( + rx.ui.segmented_control.item("One", value="1"), + value=SegmentedState.view, + on_change=SegmentedState.set_view, + ) + assert control.render()["props"] == [ + "className:sx_ee26394550_c", + KEYS, + ( + 'onValueChange:((value, details) => { if (details?.reason === "list-navigation") ' + "{ details.cancel(); return; } (((_ev_0) => (addEvents([(ReflexEvent(" + f'"{name}.set_view", ({{ ["view"] : _ev_0 }}), ({{ }})))], [_ev_0], ' + "({ })))))(value); })" + ), + f"value:{SegmentedState.view!s}", ] @@ -483,7 +196,7 @@ def test_segmented_control_unknown_variant(ui_plugin: UIPlugin): def test_segmented_control_from_a_foreach(ui_plugin: UIPlugin): - """Items a foreach renders are counted in the browser, and a bound control checks the item of its value.""" + """Items a foreach renders are counted in the browser, and the indicator is placed at the item of the value.""" control = rx.ui.segmented_control.root( rx.foreach( SegmentedState.views, @@ -492,59 +205,46 @@ def test_segmented_control_from_a_foreach(ui_plugin: UIPlugin): value=SegmentedState.view, on_change=SegmentedState.set_view, ) - state = ( - "reflex___state____state__tests___units___reflex_components_ui" - "___components___test_segmented_control____segmented_state" - ) + views, view = f"{SegmentedState.views!s}", f"{SegmentedState.view!s}" style = control._element_styles().style.style # pyright: ignore[reportAttributeAccessIssue] - assert str(style["--rx-segmented-count"]) == f"{state}.views_rx_state_.length" + assert str(style["--rx-segmented-count"]) == f"{views}.length" # The name of the argument of the function is made up anew each run. index = re.sub( r"\(\((\w+)\) => \1\)", "((item) => item)", str(style["--rx-segmented-index-of-value"]), ) - assert index == ( - f"({state}.views_rx_state_.map(((item) => item))" - f".indexOf({state}.view_rx_state_))" - ) - item = control.children[0].children[0] - assert item.children[0].render()["props"] == [ - f"checked:({state}.view_rx_state_ === view_rx_state_)", - "className:sx_8e51139181_c", - 'form:""', - 'name:"rx-segmented-1"', - "readOnly:true", - 'type:"radio"', - "value:view_rx_state_", - ] + assert index == f"({views}.map(((item) => item)).indexOf({view}))" def test_segmented_control_places_every_item(ui_plugin: UIPlugin): - """The style table places the indicator for ten items, and a control with more adds the rest.""" + """The style table places the indicator for ten items, and a control with more adds the rest; items are counted among the buttons.""" item = rx.ui.segmented_control.item twelve = rx.ui.segmented_control.root(*[ item(str(number), value=str(number)) for number in range(12) ]) - index = twelve._element_styles().style.style["--rx-segmented-index"] # pyright: ignore[reportAttributeAccessIssue] - assert index == { + style = twelve._element_styles().style.style # pyright: ignore[reportAttributeAccessIssue] + assert style["--rx-segmented-index"] == { "default": "var(--rx-segmented-index-of-value, 0)", **{ - f":has(> :nth-child({position}) > input:checked)": position - 1 + f":has(> button:nth-of-type({position})[data-checked])": position - 1 for position in range(1, 13) }, } - assert twelve._element_styles().style.style["--rx-segmented-count"] == 12 # pyright: ignore[reportAttributeAccessIssue] + assert style["--rx-segmented-count"] == 12 -def test_segmented_control_script(ui_plugin: UIPlugin): - """The one script of a segmented control is the keys that move through it.""" +def test_segmented_control_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a segmented control imports its parts from UI SDK, pinned, and no script.""" control = rx.ui.segmented_control.root(rx.ui.segmented_control.item("a", value="a")) - assert control._get_all_imports()["$/reflex-ui/behaviors/roving-focus.js"] == [ - ImportVar(tag="rovingKeyDown") - ] - assert control.render()["props"] == [ - "className:sx_1b6d0f2eb5_c", - "onKeyDown:rovingKeyDown", - 'role:"radiogroup"', - ] + assert { + module: names + for module, names in control._get_all_imports().items() + if "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/segmented-control": [ + ImportVar(tag="SegmentedControl"), + ImportVar(tag="SegmentedControlItem"), + ], + } diff --git a/tests/units/reflex_components_ui/components/test_slider.py b/tests/units/reflex_components_ui/components/test_slider.py index a0d623742e5..db94d0ccdca 100644 --- a/tests/units/reflex_components_ui/components/test_slider.py +++ b/tests/units/reflex_components_ui/components/test_slider.py @@ -1,6 +1,5 @@ """Tests for reflex_components_ui.components.slider.""" -import re from collections.abc import Callable from typing import Any @@ -10,932 +9,149 @@ from reflex_components_ui.style import StyleError import reflex as rx +from tests.units.reflex_components_ui.render import tree -class SliderState(rx.State): - """What a slider is bound to.""" +def _parts(control: str, track: str, fill: str, area: str, *thumbs: Any) -> Any: + """The parts of a slider inside its root. - span: list[float] = [20, 60] - low: int = 10 + Args: + control: The class of the control. + track: The class of the track. + fill: The class of the filled part of the track. + area: The class of where the thumbs travel. + *thumbs: The projection of each thumb. - @rx.event - def set_span(self, span: list[float]): - """Follow the slider. - - Args: - span: Its values. - """ - self.span = span + Returns: + The projection of the control. + """ + return [ + ( + "SliderControl", + [f"className:{control}"], + [ + ( + "SliderTrack", + [f"className:{track}"], + [("SliderIndicator", [f"className:{fill}"], [])], + ), + ('"span"', [f"className:{area}"], list(thumbs)), + ], + ) + ] -def test_slider( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], -): - """A slider is a track, its filled part and a native range input for its thumb, which has the id, the name and the label of the slider.""" - component = rx.ui.slider( - default_value=30, - id="volume", - name="volume", +def test_slider(ui_plugin: UIPlugin): + """A slider is the parts of UI SDK, with a thumb for its value: the ``aria_*`` of a slider with one thumb are its thumb's.""" + slider = rx.ui.slider( + default_value=40, + aria_label="Volume", + name="vol", + id="vol", + size="1", + variant="classic", min=0, max=200, step=5, - aria_label="Volume", - width="50%", - margin="1px", ) - assert component.render() == { - "name": '"span"', - "props": [ - "className:sx_2e50c10c69_c", - '"data-orientation":"horizontal"', - "onInputCapture:slide", - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_9a52612950_c"], - "children": [ - { - "name": '"span"', - "props": ["className:sx_3462dcdb83_c"], - "children": [], - } - ], - }, - { - "name": '"input"', - "props": [ - '"aria-label":"Volume"', - "className:sx_2ed6fd010a_c", - "defaultValue:30", - 'id:"volume"', - "max:200", - "min:0", - 'name:"volume"', - "step:5", - 'type:"range"', - ], - "children": [], - }, + assert tree(slider.render()) == ( + "Slider", + [ + "className:sx_cf9e3f467c_c", + "defaultValue:[40]", + 'id:"vol"', + "max:200", + "min:0", + 'name:"vol"', + "ref:ref_vol", + "step:5", ], - } - assert declared_styles(component) == [ - { - "boxSizing": "border-box", - "--slider-thumb-size": "calc(var(--slider-track-size) + var(--space-1))", - "position": "relative", - "display": "flex", - "alignItems": "center", - "flexGrow": 1, - "borderRadius": "max(calc(var(--radius-factor) * var(--slider-track-size) / 3), calc(var(--radius-factor) * var(--radius-thumb)))", - "userSelect": "none", - "touchAction": "none", - "cursor": {":has(:disabled)": "var(--cursor-disabled)"}, - "mixBlendMode": { - ":has(:disabled)": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" - }, - "--slider-track-size": "var(--space-2)", - "width": "50%", - "height": "var(--slider-track-size)", - "--rx-slider-start": "0%", - "--rx-slider-end": "15%", - "marginTop": "1px", - "marginRight": "1px", - "marginBottom": "1px", - "marginLeft": "1px", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "position": "relative", - "flexGrow": 1, - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "height": "var(--slider-track-size)", - "backgroundColor": "var(--gray-a3)", - "boxShadow": "inset 0 0 0 1px var(--gray-a5)", - }, - { - "position": "absolute", - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "height": "100%", - "left": "var(--rx-slider-start)", - "right": "calc(100% - var(--rx-slider-end))", - "backgroundColor": "var(--accent-track)", - "backgroundImage": "none", - "boxShadow": "inset 0 0 0 1px var(--gray-a5)", - }, - { - "appearance": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "position": "absolute", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderRightWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderBottomWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderLeftWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderTopStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderRightStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderBottomStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderLeftStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "backgroundColor": { - "default": "transparent", - "::-webkit-slider-runnable-track": "transparent", - "::-webkit-slider-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - "::-moz-range-track": "transparent", - "::-moz-range-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - }, - "outlineStyle": "none", - "cursor": { - "default": "inherit", - "::-webkit-slider-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - "::-moz-range-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - }, - "width": { - "default": "calc(100% + var(--slider-track-size) * 0.5)", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "height": { - "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-webkit-slider-runnable-track": "100%", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-track": "100%", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "left": "calc(var(--slider-track-size) * -0.25)", - "top": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", - "boxSizing": { - "::-webkit-slider-thumb": "border-box", - "::-moz-range-thumb": "border-box", - }, - "pointerEvents": { - "::-webkit-slider-thumb": "auto", - "::-moz-range-thumb": "auto", - }, - "borderRadius": { - "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", - "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", - }, - "boxShadow": { - "::-webkit-slider-thumb": { - "default": "0 0 0 1px var(--black-a4)", - ":focus-visible": "0 0 0 1px var(--black-a4), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - "::-moz-range-thumb": { - "default": "0 0 0 1px var(--black-a4)", - ":focus-visible": "0 0 0 1px var(--black-a4), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - }, - }, - ] + _parts( + "sx_9d6c9b96ec_c", + "sx_ba51ac2911_c", + "sx_cb84de2a22_c", + "sx_303e2c1e35_c", + ( + "SliderThumb", + ['"aria-label":"Volume"', "className:sx_3ebcf889ae_c", "index:0"], + [], + ), + ), + ) -def test_slider_with_several_thumbs( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], -): - """A slider with several values has a thumb for each, named as Radix names them in a group with the name of the slider, and its script moves the nearest.""" - component = rx.ui.slider( - default_value=[20, 60, 90], - name="span", - aria_label="Span", - disabled=True, - size="3", - variant="classic", - high_contrast=True, - color_scheme="ruby", - radius="small", - orientation="vertical", - as_child=True, +def test_slider_with_several_thumbs(ui_plugin: UIPlugin): + """The thumbs of a slider with several are named as Radix names them, and the ``aria_*`` are the group's; disabled and vertical reach UI SDK.""" + slider = rx.ui.slider( + default_value=[20, 60], aria_label="Span", disabled=True, orientation="vertical" ) - assert component.render() == { - "name": '"span"', - "props": [ + thumb = "className:sx_fb79566a6a_c" + assert tree(slider.render()) == ( + "Slider", + [ '"aria-label":"Span"', - 'className:sx_2a31e8da62_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_6d1e87c3d8', - '"data-orientation":"vertical"', - "onInputCapture:slide", - "onMouseDown:press", - 'role:"group"', + "className:sx_7a1da8ae44_c", + "defaultValue:[20, 60]", + "disabled:true", + 'orientation:"vertical"', ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_c5bed6bb3f_c"], - "children": [ - { - "name": '"span"', - "props": ["className:sx_fff88394c2_c"], - "children": [], - } - ], - }, - { - "name": '"input"', - "props": [ - '"aria-label":"Value 1 of 3"', - "className:sx_1c26558511_c", - "defaultValue:20", - "disabled:true", - 'name:"span[]"', - 'type:"range"', - ], - "children": [], - }, - { - "name": '"input"', - "props": [ - '"aria-label":"Value 2 of 3"', - "className:sx_1c26558511_c", - "defaultValue:60", - "disabled:true", - 'name:"span[]"', - 'type:"range"', - ], - "children": [], - }, - { - "name": '"input"', - "props": [ - '"aria-label":"Value 3 of 3"', - "className:sx_1c26558511_c", - "defaultValue:90", - "disabled:true", - 'name:"span[]"', - 'type:"range"', - ], - "children": [], - }, - ], - } - assert declared_styles(component) == [ - { - "boxSizing": "border-box", - "--slider-thumb-size": "calc(var(--slider-track-size) + var(--space-1))", - "position": "relative", - "display": "flex", - "alignItems": "center", - "flexGrow": 1, - "borderRadius": "max(calc(var(--radius-factor) * var(--slider-track-size) / 3), calc(var(--radius-factor) * var(--radius-thumb)))", - "userSelect": "none", - "touchAction": "none", - "cursor": {":has(:disabled)": "var(--cursor-disabled)"}, - "mixBlendMode": { - ":has(:disabled)": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" - }, - "--slider-track-size": "calc(var(--space-2) * 1.25)", - "height": "stretch", - "flexDirection": "column", - "width": "100%", - "--rx-slider-start": "20%", - "--rx-slider-end": "90%", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "position": {"default": "relative", "::before": "absolute"}, - "flexGrow": 1, - "borderTopLeftRadius": {"default": "inherit", "::before": "inherit"}, - "borderTopRightRadius": {"default": "inherit", "::before": "inherit"}, - "borderBottomRightRadius": {"default": "inherit", "::before": "inherit"}, - "borderBottomLeftRadius": {"default": "inherit", "::before": "inherit"}, - "width": "var(--slider-track-size)", - "backgroundColor": "var(--gray-a3)", - "content": {"::before": "''"}, - "top": {"::before": "0"}, - "right": {"::before": "0"}, - "bottom": {"::before": "0"}, - "left": {"::before": "0"}, - "boxShadow": {"::before": "var(--shadow-1)"}, - "opacity": {"::before": 0.5}, - }, - { - "position": "absolute", - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "width": "100%", - "bottom": "var(--rx-slider-start)", - "top": "calc(100% - var(--rx-slider-end))", - "backgroundColor": "transparent", - "backgroundImage": "none", - "boxShadow": "none", - }, - { - "appearance": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "position": "absolute", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderRightWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderBottomWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderLeftWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderTopStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderRightStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderBottomStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderLeftStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "backgroundColor": { - "default": "transparent", - "::-webkit-slider-runnable-track": "transparent", - "::-webkit-slider-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - "::-moz-range-track": "transparent", - "::-moz-range-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - }, - "outlineStyle": "none", - "cursor": { - "default": "inherit", - "::-webkit-slider-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - "::-moz-range-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - }, - "height": { - "default": "calc(100% + var(--slider-track-size) * 0.5)", - "::-webkit-slider-runnable-track": "100%", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-track": "100%", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "width": { - "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "top": "calc(var(--slider-track-size) * -0.25)", - "left": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", - "writingMode": "vertical-lr", - "direction": "rtl", - "boxSizing": { - "::-webkit-slider-thumb": "border-box", - "::-moz-range-thumb": "border-box", - }, - "pointerEvents": { - "default": "none", - "::-webkit-slider-thumb": "auto", - "::-moz-range-thumb": "auto", - }, - "borderRadius": { - "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", - "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", - }, - "boxShadow": { - "::-webkit-slider-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - "::-moz-range-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - }, - }, - { - "appearance": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "position": "absolute", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderRightWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderBottomWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderLeftWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderTopStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderRightStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderBottomStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderLeftStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "backgroundColor": { - "default": "transparent", - "::-webkit-slider-runnable-track": "transparent", - "::-webkit-slider-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - "::-moz-range-track": "transparent", - "::-moz-range-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - }, - "outlineStyle": "none", - "cursor": { - "default": "inherit", - "::-webkit-slider-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - "::-moz-range-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - }, - "height": { - "default": "calc(100% + var(--slider-track-size) * 0.5)", - "::-webkit-slider-runnable-track": "100%", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-track": "100%", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "width": { - "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "top": "calc(var(--slider-track-size) * -0.25)", - "left": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", - "writingMode": "vertical-lr", - "direction": "rtl", - "boxSizing": { - "::-webkit-slider-thumb": "border-box", - "::-moz-range-thumb": "border-box", - }, - "pointerEvents": { - "default": "none", - "::-webkit-slider-thumb": "auto", - "::-moz-range-thumb": "auto", - }, - "borderRadius": { - "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", - "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", - }, - "boxShadow": { - "::-webkit-slider-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - "::-moz-range-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - }, - }, - { - "appearance": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "position": "absolute", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderRightWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderBottomWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderLeftWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderTopStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderRightStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderBottomStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderLeftStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "backgroundColor": { - "default": "transparent", - "::-webkit-slider-runnable-track": "transparent", - "::-webkit-slider-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - "::-moz-range-track": "transparent", - "::-moz-range-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - }, - "outlineStyle": "none", - "cursor": { - "default": "inherit", - "::-webkit-slider-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - "::-moz-range-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - }, - "height": { - "default": "calc(100% + var(--slider-track-size) * 0.5)", - "::-webkit-slider-runnable-track": "100%", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-track": "100%", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "width": { - "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "top": "calc(var(--slider-track-size) * -0.25)", - "left": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", - "writingMode": "vertical-lr", - "direction": "rtl", - "boxSizing": { - "::-webkit-slider-thumb": "border-box", - "::-moz-range-thumb": "border-box", - }, - "pointerEvents": { - "default": "none", - "::-webkit-slider-thumb": "auto", - "::-moz-range-thumb": "auto", - }, - "borderRadius": { - "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", - "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", - }, - "boxShadow": { - "::-webkit-slider-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - "::-moz-range-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 1px 3px var(--black-a1), 0 2px 4px -1px var(--black-a1), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-6)", - }, - }, - }, + _parts( + "sx_c3c3faff51_c", + "sx_1b5891cf0a_c", + "sx_71e44b49d0_c", + "sx_ec96b33674_c", + ("SliderThumb", ['"aria-label":"Minimum"', thumb, "index:0"], []), + ("SliderThumb", ['"aria-label":"Maximum"', thumb, "index:1"], []), + ), + ) + three = rx.ui.slider(default_value=[1, 2, 3]) + assert [ + thumb.render()["props"][0] for thumb in three.children[0].children[1].children + ] == [ + '"aria-label":"Value 1 of 3"', + '"aria-label":"Value 2 of 3"', + '"aria-label":"Value 3 of 3"', ] -def test_slider_soft( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], +def test_slider_styles( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] ): - """The soft variant, and the default value of a slider.""" - component = rx.ui.slider(variant="soft") - assert declared_styles(component) == [ - { - "boxSizing": "border-box", - "--slider-thumb-size": "calc(var(--slider-track-size) + var(--space-1))", - "position": "relative", - "display": "flex", - "alignItems": "center", - "flexGrow": 1, - "borderRadius": "max(calc(var(--radius-factor) * var(--slider-track-size) / 3), calc(var(--radius-factor) * var(--radius-thumb)))", - "userSelect": "none", - "touchAction": "none", - "cursor": {":has(:disabled)": "var(--cursor-disabled)"}, - "mixBlendMode": { - ":has(:disabled)": "var(--rx-if-light, multiply) var(--rx-if-dark, screen)" - }, - "--slider-track-size": "var(--space-2)", - "width": "100%", - "height": "var(--slider-track-size)", - "--rx-slider-start": "0%", - "--rx-slider-end": "50%", - }, - { - "overflowX": "hidden", - "overflowY": "hidden", - "position": "relative", - "flexGrow": 1, - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "height": "var(--slider-track-size)", - "backgroundColor": "var(--gray-a4)", - "backgroundImage": "linear-gradient(var(--white-a1), var(--white-a1))", - }, - { - "position": "absolute", - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "height": "100%", - "left": "var(--rx-slider-start)", - "right": "calc(100% - var(--rx-slider-end))", - "backgroundColor": "var(--accent-6)", - "backgroundImage": "linear-gradient(var(--accent-a5), var(--accent-a5)), none", + """The thumbs travel half a thumb in from either end of the track, as in Radix Themes, and a thumb is drawn by UI SDK's state.""" + _, _, _, _, area, thumb = declared_styles(rx.ui.slider(variant="soft")) + assert area == { + "position": "absolute", + "pointerEvents": "none", + "top": "0", + "bottom": "0", + "left": "calc(var(--slider-thumb-size) / 2)", + "right": "calc(var(--slider-thumb-size) / 2)", + } + assert { + key: thumb[key] for key in ("width", "backgroundColor", "cursor", "boxShadow") + } == { + "width": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", + "backgroundColor": {"default": "white", "[data-disabled]": "var(--gray-1)"}, + "cursor": { + "default": "var(--cursor-slider-thumb)", + ":active": "var(--cursor-slider-thumb-active)", + "[data-disabled]": "var(--cursor-disabled)", }, - { - "appearance": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "position": "absolute", - "marginTop": "0", - "marginRight": "0", - "marginBottom": "0", - "marginLeft": "0", - "paddingTop": "0", - "paddingRight": "0", - "paddingBottom": "0", - "paddingLeft": "0", - "borderTopWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderRightWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderBottomWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderLeftWidth": { - "default": "0", - "::-webkit-slider-thumb": "0", - "::-moz-range-thumb": "0", - }, - "borderTopStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderRightStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderBottomStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "borderLeftStyle": { - "default": "none", - "::-webkit-slider-thumb": "none", - "::-moz-range-thumb": "none", - }, - "backgroundColor": { - "default": "transparent", - "::-webkit-slider-runnable-track": "transparent", - "::-webkit-slider-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - "::-moz-range-track": "transparent", - "::-moz-range-thumb": { - "default": "white", - ":disabled": "var(--gray-1)", - }, - }, - "outlineStyle": "none", - "cursor": { - "default": "inherit", - "::-webkit-slider-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - "::-moz-range-thumb": { - "default": "var(--cursor-slider-thumb)", - ":active": "var(--cursor-slider-thumb-active)", - ":disabled": "var(--cursor-disabled)", - }, - }, - "width": { - "default": "calc(100% + var(--slider-track-size) * 0.5)", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "height": { - "default": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-webkit-slider-runnable-track": "100%", - "::-webkit-slider-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - "::-moz-range-track": "100%", - "::-moz-range-thumb": "calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5)", - }, - "left": "calc(var(--slider-track-size) * -0.25)", - "top": "calc(50% - calc(var(--slider-thumb-size) + var(--slider-track-size) * 0.5) / 2)", - "boxSizing": { - "::-webkit-slider-thumb": "border-box", - "::-moz-range-thumb": "border-box", - }, - "pointerEvents": { - "::-webkit-slider-thumb": "auto", - "::-moz-range-thumb": "auto", - }, - "borderRadius": { - "::-webkit-slider-thumb": "max(var(--radius-1), var(--radius-thumb))", - "::-moz-range-thumb": "max(var(--radius-1), var(--radius-thumb))", - }, - "boxShadow": { - "::-webkit-slider-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-5)", - }, - "::-moz-range-thumb": { - "default": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3)", - ":focus-visible": "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), 0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), 0 1px 3px -0.5px var(--gray-a3), 0 0 0 3px var(--accent-3), 0 0 0 5px var(--focus-8)", - ":disabled": "0 0 0 1px var(--gray-5)", - }, - }, + "boxShadow": { + "default": ( + "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), " + "0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), " + "0 1px 3px -0.5px var(--gray-a3)" + ), + ":has(:focus-visible)": ( + "0 0 0 1px var(--black-a3), 0 0 0 1px var(--gray-a2), " + "0 0 0 1px var(--accent-a2), 0 1px 2px var(--gray-a4), " + "0 1px 3px -0.5px var(--gray-a3), 0 0 0 3px var(--accent-3), " + "0 0 0 5px var(--focus-8)" + ), + "[data-disabled]": "0 0 0 1px var(--gray-5)", }, - ] + } def test_slider_unknown_radius(ui_plugin: UIPlugin): @@ -948,66 +164,61 @@ def test_slider_unknown_radius(ui_plugin: UIPlugin): ) +class SliderState(rx.State): + """What a slider is bound to.""" + + span: list[float] = [20, 60] + + @rx.event + def set_span(self, span: list[float]): + """Follow the slider. + + Args: + span: Its values. + """ + self.span = span + + def test_slider_bound_to_state(ui_plugin: UIPlugin): - """A slider bound to a list has a thumb for each value, counted in the browser, and hands the values over.""" + """A slider bound to a list has a thumb for each value, counted in the browser, and hands over the values UI SDK says.""" + name = SliderState.get_full_name() slider = rx.ui.slider( value=SliderState.span, - min=SliderState.low, on_change=SliderState.set_span, on_value_commit=SliderState.set_span, ) - state = ( - "tests___units___reflex_components_ui___components___test_slider" - "____slider_state" - ) - span = f"reflex___state____state__{state}.span_rx_state_" - low = f"reflex___state____state__{state}.low_rx_state_" - values = ( - 'Array.from(_e.currentTarget.querySelectorAll("input"), ' - "(input) => input.valueAsNumber)" - ) handler = ( - '((_e) => (addEvents([(ReflexEvent("reflex___state____state.' - f'{state}.set_span", ({{ ["span"] : {values} }}), ({{ }})))], [_e], ' - "({ }))))" - ) - keys = ( - '["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", ' - '"PageUp", "PageDown"]' + f'((_value) => (addEvents([(ReflexEvent("{name}.set_span", ' + '({ ["span"] : _value }), ({ })))], [_value], ({ }))))' ) assert slider.render()["props"] == [ - "className:sx_d6dc3ba3e7_c", - '"data-orientation":"horizontal"', - f"onChange:{handler}", - "onInputCapture:slide", - f"onKeyUp:((event) => {{ if ({keys}.includes(event.key)) ({handler})(event); }})", - "onMouseDown:press", - f"onPointerUp:{handler}", - ( - f'style:({{ "--v0": ((((({span}?.at?.(0)) - ({low})) / ((100) - ({low})) ' - f'* 100) + "%")) ?? "initial", "--v1": ((((({span}?.at?.(-1)) - ({low})) ' - f'/ ((100) - ({low})) * 100) + "%")) ?? "initial" }})' - ), + "className:sx_9d165cc942_c", + f"onValueChange:{handler}", + f"onValueCommit:{handler}", + f"value:{SliderState.span!s}", ] - thumb = slider.children[1].children[0] - # Named after the bytecode of the function that renders a thumb, which - # differs from one Python version to the next. - index = slider.children[1].render()["index_var_name"] - assert re.fullmatch(r"index_[0-9a-f]{32}", index) - assert thumb.render()["props"] == [ - "className:sx_04c810abee_c", - f"key:{index}", - f"min:{low}", - 'type:"range"', - 'value:(isNotNullOrUndefined(item_rx_state_) ? item_rx_state_ : "")', + thumbs = slider.children[0].children[1].children[0] + assert thumbs.render()["index_var_name"] == "index_rx_state_" + assert thumbs.children[0].render()["props"] == [ + "className:sx_fb79566a6a_c", + "index:index_rx_state_", + "key:index_rx_state_", ] -def test_slider_script(ui_plugin: UIPlugin): - """The script of a slider follows its thumbs, and moves the nearest of several.""" - script = "$/reflex-ui/behaviors/slider.js" - assert rx.ui.slider()._get_all_imports()[script] == [ImportVar(tag="slide")] - assert rx.ui.slider(default_value=[1, 2])._get_all_imports()[script] == [ - ImportVar(tag="slide"), - ImportVar(tag="press"), - ] +def test_slider_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with a slider imports its parts from UI SDK, pinned, and no script.""" + assert { + module: names + for module, names in rx.ui.slider()._get_all_imports().items() + if "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/slider": [ + ImportVar(tag="Slider"), + ImportVar(tag="SliderControl"), + ImportVar(tag="SliderTrack"), + ImportVar(tag="SliderIndicator"), + ImportVar(tag="SliderThumb"), + ], + } From 3e006961840dab9860ff07ace9b394a3d33f880a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 18:23:53 +0000 Subject: [PATCH 199/204] rx.ui on UI SDK, wave D: avatar, form, text field slots and theme panel The avatar is the parts of @ui-sdk/react/avatar, which shows the fallback until the image has loaded. A form field is UI SDK's field: a message with a condition is its error, one without is always shown, and a label points at its control in the page the server sends. A text field with slots is UI SDK's input group. The theme panel keeps its class swap as an app script, its tooltips UI SDK's. The form-validity, image-status and text-field scripts are gone. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- docs/styling/rx-ui-migration.md | 14 +- .../js/src/behaviors/form-validity.js | 173 ---------- .../js/src/behaviors/image-status.js | 35 -- .../js/src/behaviors/text-field.js | 34 -- .../js/tests/behaviors/form-validity.test.js | 193 ----------- .../js/tests/behaviors/image-status.test.js | 108 ------ .../js/tests/behaviors/text-field.test.js | 89 ----- .../parity/allowlist.toml | 24 +- .../parity/ui_parity/components/avatar.py | 5 +- .../parity/ui_parity/components/form.py | 29 +- .../reflex_components_ui/components/_slot.py | 61 ---- .../reflex_components_ui/components/avatar.py | 54 +-- .../reflex_components_ui/components/form.py | 269 +++++++-------- .../components/text_field.py | 37 ++- .../components/theme_panel.py | 11 +- .../src/reflex_components_ui/styles/avatar.py | 12 +- pyi_hashes.json | 6 +- .../tests_playwright/test_ui_components.py | 19 +- .../components/test_avatar.py | 311 ++++-------------- .../components/test_form.py | 284 ++++++++-------- .../components/test_text_field.py | 27 +- 21 files changed, 466 insertions(+), 1329 deletions(-) delete mode 100644 packages/reflex-components-ui/js/src/behaviors/form-validity.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/image-status.js delete mode 100644 packages/reflex-components-ui/js/src/behaviors/text-field.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/image-status.test.js delete mode 100644 packages/reflex-components-ui/js/tests/behaviors/text-field.test.js delete mode 100644 packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index 53ce736926d..c2fc6150489 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -157,8 +157,9 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### avatar -- behaviour, `rx`, "the fallback is in the server render": rx.avatar renders its fallback and its image once JavaScript has run: the server sends an empty placeholder. rx.ui.avatar sends both, so the page shows the avatar before it is hydrated. -- behaviour, `rx`, "shows a loaded image and the fallback without JavaScript": rx.avatar shows neither its image nor its fallback with JavaScript disabled. rx.ui.avatar shows the fallback, and the image over it once it has loaded; only an image that fails needs JavaScript to give way to the fallback. +- behaviour, `rx`, "the fallback is in the server render": rx.avatar renders its fallback and its image once JavaScript has run: the server sends an empty placeholder. rx.ui.avatar sends its fallback, so the page shows the avatar before it is hydrated. +- behaviour, `rx`, "shows a loaded image and the fallback without JavaScript": rx.avatar shows neither its image nor its fallback with JavaScript disabled. rx.ui.avatar shows its fallback; UI SDK shows the image in its place once the page has hydrated. +- behaviour, `rx.ui`, "shows a loaded image and the fallback without JavaScript": UI SDK keeps the image of rx.ui.avatar hidden until it has loaded, which it learns once the page has hydrated: with JavaScript disabled the avatar shows its fallback. rx.avatar shows neither. - pixels, size-responsive-large@800: When the size of rx.avatar grows at a breakpoint from one of the four small sizes to a larger one, Radix Themes keeps the smaller letters the small size has for a fallback of two letters. rx.ui.avatar gives the two letters the size they have in an avatar of the larger size alone. - style, `font-size`, `line-height`: When the size of rx.avatar grows at a breakpoint from one of the four small sizes to a larger one, Radix Themes keeps the smaller letters the small size has for a fallback of two letters. rx.ui.avatar gives the two letters the size they have in an avatar of the larger size alone. @@ -246,6 +247,11 @@ counterpart, kept in sync with the parity checks of `rx.ui`: - style, `padding-right`, `width`: rx.dropdown_menu widens a menu that scrolls by the room its own scrollbar takes. The scrollbar of rx.ui.dropdown_menu is the browser's, which takes the room it needs itself. - pixels in chromium, *side-left*: A menu of rx.ui.dropdown_menu on the left of its trigger is placed by its right edge on a whole pixel, so its text may fall between pixels, and is smoothed differently; rx.dropdown_menu places it by its left edge. The menu is in the same place, on the same pixels. +### form + +- behaviour, `rx.ui`, "a message outside its field shows for the field it names": A message of rx.ui.form is an error of the field it is in, as UI SDK has it: one given a `name` outside the fields shows only when it is forced, with `force_match`. rx.form shows it with the reasons of the field it names. +- behaviour, `rx.ui`, "a change forgets the reason, and leaving the control reads it again": Once a submit finds a control of rx.ui.form invalid, UI SDK reads its validity again as its value changes, so its messages follow what is typed: typing into an empty email field says at once that it is not an email. rx.form hides the messages while the value changes, and reads the reason again when the control is left. + ### hover_card - behaviour, `rx.ui`, "Tab does not reach the links inside it": rx.hover_card takes what is inside the card out of the order of Tab: a keyboard user sees the card and cannot reach its links. The card of rx.ui.hover_card comes right after its trigger, so Tab moves into it and through its links, and the card stays open while the focus is inside it. @@ -348,6 +354,10 @@ counterpart, kept in sync with the parity checks of `rx.ui`: - prop `form`, `html_for`: As for rx.ui.text: rx.text.span passes html_for and form on as CSS keys, which the browser ignores; rx.ui.text.span renders them as attributes when it is a label. +### text_field + +- behaviour, `rx.ui`, "a pointer on a slot gives the input the focus, at that end of its text": UI SDK gives the input of rx.ui.text_field the focus from a press on a slot, and leaves the caret where the browser puts it when an input takes the focus. rx.text_field puts the caret at the end of the text the slot is on. + ### theme_panel - behaviour, `rx`, "copies the theme as the code of an rx.ui.Theme": rx.theme_panel copies the theme as the JSX of a Radix Themes Theme, such as , which a Reflex app cannot use as it is. rx.ui.theme_panel copies the Python of the rx.ui.Theme it shows, such as rx.ui.Theme(accent_color="red", radius="large"), leaving out what is the default of rx.ui.Theme. diff --git a/packages/reflex-components-ui/js/src/behaviors/form-validity.js b/packages/reflex-components-ui/js/src/behaviors/form-validity.js deleted file mode 100644 index 002d8489551..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/form-validity.js +++ /dev/null @@ -1,173 +0,0 @@ -// What the messages of a form show of the validity of its controls. -// -// The browser knows why a control is not valid: nothing typed, a pattern -// that does not match, a number out of its range. A message names one of -// those reasons and is hidden until it holds, as Radix has it: reasons are -// read when a form is submitted or a control is left after a change, and -// forgotten while its value changes. -// -// Without it the browser reports an invalid control itself, as it does for -// any form. - -/** - * @typedef {HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement} Control - */ - -let ids = 0; - -/** - * Tell the element of an event apart from anything that is no form control. - * - * @param {EventTarget | null} target The target of an event. - * @returns {Control | null} The control, or null. - */ -function controlOf(target) { - return target instanceof HTMLInputElement || - target instanceof HTMLSelectElement || - target instanceof HTMLTextAreaElement - ? target - : null; -} - -/** - * Show the messages of a control whose reason holds, and hide the others. - * - * The field of the control, its labels and the control say whether it is - * valid in `data-valid` and `data-invalid`, and the control is described by - * the messages that show. - * - * @param {Element} form The form. - * @param {Control} control The control. - * @param {boolean} known Whether the validity of the control is read, or - * forgotten. - * @returns {void} - */ -function report(form, control, known) { - const field = control.closest("[data-rx-form-field]"); - const validity = control.validity; - const invalid = known && !validity.valid; - const marked = [ - control, - ...(field ? [field, ...field.querySelectorAll("label")] : []), - ]; - for (const element of marked) { - if (element !== field || !field.hasAttribute("data-server-invalid")) { - element.toggleAttribute("data-invalid", invalid); - } - element.toggleAttribute("data-valid", known && validity.valid); - } - const shown = []; - for (const message of form.querySelectorAll("[data-rx-form-message]")) { - if (!(message instanceof HTMLElement)) continue; - const name = message.dataset.name; - const own = name - ? name === control.name - : field !== null && field.contains(message); - if (!own) continue; - const match = message.dataset.match; - if (match && !("force" in message.dataset)) { - message.hidden = !( - known && /** @type {Record} */ (validity)[match] - ); - } - if (!message.hidden) { - message.id ||= `rx-form-message-${++ids}`; - shown.push(message.id); - } - } - if (shown.length) control.setAttribute("aria-describedby", shown.join(" ")); - else control.removeAttribute("aria-describedby"); -} - -/** - * Read the validity of a control the browser found invalid: the `onInvalid` - * of a form. - * - * The messages stand in for the report of the browser, and the first - * invalid control of the form takes the focus. - * - * @param {{ target: EventTarget | null, currentTarget: HTMLFormElement, preventDefault: () => void }} event - * The control found invalid. - * @returns {void} - */ -export function invalid(event) { - const control = controlOf(event.target); - if (!control) return; - const form = event.currentTarget; - if (form.querySelector(":invalid") === control) control.focus(); - event.preventDefault(); - report(form, control, true); -} - -/** - * Forget the validity of a control whose value changes: the - * `onChangeCapture` of a form. - * - * @param {{ target: EventTarget | null, currentTarget: HTMLFormElement }} event - * The change. - * @returns {void} - */ -export function changed(event) { - const control = controlOf(event.target); - if (!control) return; - control.dataset.rxChanged = ""; - report(event.currentTarget, control, false); -} - -/** - * Read the validity of a control that is left after a change: the - * `onBlurCapture` of a form. - * - * @param {{ target: EventTarget | null, currentTarget: HTMLFormElement }} event - * The control losing the focus. - * @returns {void} - */ -export function left(event) { - const control = controlOf(event.target); - if (!control || !("rxChanged" in control.dataset)) return; - delete control.dataset.rxChanged; - report(event.currentTarget, control, true); -} - -/** - * Forget the validity of every control of a form that is reset: its - * `onReset`. - * - * @param {{ currentTarget: HTMLFormElement }} event The reset. - * @returns {void} - */ -export function cleared(event) { - const form = event.currentTarget; - for (const element of form.elements) { - const control = controlOf(element); - if (control) { - delete control.dataset.rxChanged; - report(form, control, false); - } - } -} - -/** - * Give the focus to the first control of a form that is not valid, when - * the server finds a field invalid: the `ref` of the field while it is. - * - * It is the first one of the whole form, as in Radix: a form with several - * such fields, or with one the browser finds invalid too, starts at the top. - * - * @param {Element | null} field The field, or null when it stops being invalid. - * @returns {void} - */ -export function focusInvalid(field) { - const form = field?.closest("form"); - if (!form) return; - for (const element of form.elements) { - const control = controlOf(element); - if ( - control && - (control.ariaInvalid === "true" || !control.validity.valid) - ) { - control.focus(); - return; - } - } -} diff --git a/packages/reflex-components-ui/js/src/behaviors/image-status.js b/packages/reflex-components-ui/js/src/behaviors/image-status.js deleted file mode 100644 index 58bae36d55f..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/image-status.js +++ /dev/null @@ -1,35 +0,0 @@ -// How the load of an image ended, said on the image and on what stands in -// for it, so that their styles show one of the two. -// -// The server renders both: the image lies over its stand-in, so a page shows -// a loaded image before this runs, and without JavaScript. An image may have -// loaded, or failed, before React attaches: its events are gone by then, and -// the image itself says how it ended. - -/** - * Follow the load of an image: the `ref` of the `img` element. - * - * `data-status` is `loaded` or `error`, on the image and on the element - * before it. Nothing is rendered again. - * - * @param {HTMLImageElement | null} image The image, or null when it leaves. - * @returns {(() => void) | undefined} What stops following it. - */ -export function watchImage(image) { - if (!image) return undefined; - const settle = () => { - const status = image.naturalWidth > 0 ? "loaded" : "error"; - image.dataset.status = status; - const standIn = image.previousElementSibling; - if (standIn instanceof HTMLElement) standIn.dataset.status = status; - }; - // Already over, before or without an event: an image the browser had - // loaded or given up on before hydration, or one without an address. - if (image.complete) settle(); - image.addEventListener("load", settle); - image.addEventListener("error", settle); - return () => { - image.removeEventListener("load", settle); - image.removeEventListener("error", settle); - }; -} diff --git a/packages/reflex-components-ui/js/src/behaviors/text-field.js b/packages/reflex-components-ui/js/src/behaviors/text-field.js deleted file mode 100644 index b4dcc50ed84..00000000000 --- a/packages/reflex-components-ui/js/src/behaviors/text-field.js +++ /dev/null @@ -1,34 +0,0 @@ -// What a pointer on the box of a text field does when it is not on the -// input: on a slot that holds an icon, or on the edge of the box. -// -// Without it the input still takes the focus from a pointer on the input -// itself, from the keyboard and from its label. - -/** - * Give the input of a text field the focus: the `onPointerDown` of its box. - * - * The caret goes to the end of the value from a slot on the right and to - * its start from anywhere else. A button or a link in a slot keeps the - * pointer for itself. - * - * @param {{ target: EventTarget | null, currentTarget: Element }} event The - * pointer going down inside the box. - * @returns {void} - */ -export function focusField(event) { - const target = event.target; - if (!(target instanceof Element) || target.closest("input, button, a")) - return; - const input = event.currentTarget.querySelector("input"); - if (!input) return; - const caret = target.closest("[data-side='right']") ? input.value.length : 0; - requestAnimationFrame(() => { - try { - // An input without text, such as a date, has no caret to place. - input.setSelectionRange(caret, caret); - } catch { - // The focus is all it takes then. - } - input.focus(); - }); -} diff --git a/packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js b/packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js deleted file mode 100644 index f003a91c199..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/form-validity.test.js +++ /dev/null @@ -1,193 +0,0 @@ -// What the messages of a form show of the validity of its controls: read -// on a submit and when a control is left after a change, forgotten while -// its value changes and on a reset. -import { beforeEach, expect, test } from "vitest"; - -import { - changed, - cleared, - focusInvalid, - invalid, - left, -} from "$/reflex-ui/behaviors/form-validity.js"; - -/** @type {HTMLFormElement} */ -let form; - -beforeEach(() => { - document.body.innerHTML = ` -
-
- - - - - always - forced -
-
- - -
- - - -
`; - form = /** @type {HTMLFormElement} */ (document.querySelector("form")); -}); - -/** - * Find a control of the form. - * - * @param {string} name The name of the control. - * @returns {HTMLInputElement} The control. - */ -function control(name) { - return /** @type {HTMLInputElement} */ (form.elements.namedItem(name)); -} - -/** - * Read which messages of the form show. - * - * @returns {(string | null)[]} The text of each one, in the order of the form. - */ -function shown() { - return [...form.querySelectorAll("span")] - .filter((message) => !message.hidden) - .map((message) => message.textContent); -} - -/** - * Read which of the marks of validity an element has. - * - * @param {string} id The id of the element. - * @returns {string[]} The names of the attributes. - */ -function marks(id) { - const element = /** @type {HTMLElement} */ (document.getElementById(id)); - return ["data-valid", "data-invalid"].filter((mark) => - element.hasAttribute(mark), - ); -} - -/** - * Make the event of a control, as React hands it to the form. - * - * @param {EventTarget | null} target The control. - * @returns {{ target: EventTarget | null, currentTarget: HTMLFormElement, preventDefault: () => void, prevented: boolean }} - * The event. - */ -function eventOf(target) { - const event = { - target, - currentTarget: form, - prevented: false, - preventDefault: () => { - event.prevented = true; - }, - }; - return event; -} - -test("a control found invalid shows its reasons, is described by them and takes the focus", () => { - const email = control("email"); - const event = eventOf(email); - invalid(event); - expect(shown()).toEqual(["needed", "always", "forced", "outside"]); - expect(event.prevented).toBe(true); - expect(document.activeElement).toBe(email); - expect(marks("email-field")).toEqual(["data-invalid"]); - expect(marks("email-label")).toEqual(["data-invalid"]); - expect(email.hasAttribute("data-invalid")).toBe(true); - const described = (email.getAttribute("aria-describedby") ?? "").split(" "); - expect( - described.map((id) => document.getElementById(id)?.textContent), - ).toEqual(["needed", "always", "forced", "outside"]); -}); - -test("only the first invalid control of the form takes the focus", () => { - const code = control("code"); - code.value = "abc"; - invalid(eventOf(code)); - expect(shown()).toEqual(["always", "forced", "digits"]); - expect(document.activeElement).toBe(document.body); -}); - -test("a change forgets the reasons, and leaving the control reads them again", () => { - const email = control("email"); - invalid(eventOf(email)); - email.value = "ada"; - changed(eventOf(email)); - expect(shown()).toEqual(["always", "forced"]); - expect(marks("email-field")).toEqual([]); - left(eventOf(email)); - expect(shown()).toEqual(["not an email", "always", "forced"]); - expect(email.getAttribute("aria-describedby")?.split(" ")[0]).toBe("mine"); - email.value = "ada@example.com"; - changed(eventOf(email)); - left(eventOf(email)); - expect(shown()).toEqual(["always", "forced"]); - expect(marks("email-field")).toEqual(["data-valid"]); -}); - -test("a control that is left without a change keeps what it shows", () => { - left(eventOf(control("email"))); - expect(shown()).toEqual(["always", "forced"]); - expect(marks("email-field")).toEqual([]); -}); - -test("a field the server finds invalid stays marked whatever the browser says", () => { - const code = control("code"); - code.value = "12"; - changed(eventOf(code)); - left(eventOf(code)); - expect(marks("code-field")).toEqual(["data-valid", "data-invalid"]); - expect(code.hasAttribute("aria-describedby")).toBe(false); -}); - -test("a reset forgets the reasons of every control", () => { - invalid(eventOf(control("email"))); - control("code").value = "abc"; - invalid(eventOf(control("code"))); - cleared({ currentTarget: form }); - expect(shown()).toEqual(["always", "forced"]); - expect(marks("email-field")).toEqual([]); - left(eventOf(control("code"))); - expect(shown()).toEqual(["always", "forced"]); -}); - -test("a control outside a field has the messages that name it", () => { - const free = control("free"); - free.required = true; - form.insertAdjacentHTML( - "beforeend", - '', - ); - invalid(eventOf(free)); - expect(shown()).toEqual(["always", "forced", "free"]); -}); - -test("what is no form control is left alone", () => { - for (const handler of [invalid, changed, left]) { - handler(eventOf(form.querySelector("button"))); - handler(eventOf(null)); - } - expect(shown()).toEqual(["always", "forced"]); -}); - -test("a field the server finds invalid gives the first invalid control the focus", () => { - focusInvalid(document.getElementById("code-field")); - expect(document.activeElement).toBe(control("email")); - control("email").value = "ada@example.com"; - control("code").setAttribute("aria-invalid", "true"); - focusInvalid(document.getElementById("code-field")); - expect(document.activeElement).toBe(control("code")); -}); - -test("a field that stops being invalid, or is in no form, moves no focus", () => { - focusInvalid(null); - focusInvalid(document.body); - control("email").value = "ada@example.com"; - focusInvalid(document.getElementById("email-field")); - expect(document.activeElement).toBe(document.body); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/image-status.test.js b/packages/reflex-components-ui/js/tests/behaviors/image-status.test.js deleted file mode 100644 index 918766c7ec5..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/image-status.test.js +++ /dev/null @@ -1,108 +0,0 @@ -// What an avatar follows the load of its image with: the image and what -// stands in for it are both in the page, and each is told how the load ended. -import { afterEach, beforeEach, expect, test, vi } from "vitest"; - -import { watchImage } from "$/reflex-ui/behaviors/image-status.js"; - -// jsdom loads no image: a test says how the load of each address stands. -/** @type {Record} */ -let images; - -/** @type {HTMLElement} */ -let standIn; -/** @type {HTMLImageElement} */ -let image; - -/** - * Put an avatar in the page: a stand-in, then its image. - * - * @param {string} src The address of the image. - */ -function render(src) { - document.body.innerHTML = `AB`; - standIn = /** @type {HTMLElement} */ (document.querySelector("span > span")); - image = /** @type {HTMLImageElement} */ (document.querySelector("img")); -} - -/** - * Read what the image and its stand-in were told. - * - * @returns {(string | undefined)[]} The status of the stand-in, then of the image. - */ -function statuses() { - return [standIn.dataset.status, image.dataset.status]; -} - -beforeEach(() => { - images = { - "/loading.png": { complete: false, naturalWidth: 0 }, - "/loaded.png": { complete: true, naturalWidth: 32 }, - "/broken.png": { complete: true, naturalWidth: 0 }, - }; - for (const property of /** @type {const} */ (["complete", "naturalWidth"])) { - vi.spyOn(HTMLImageElement.prototype, property, "get").mockImplementation( - /** @this {HTMLImageElement} */ - function () { - return images[this.getAttribute("src") ?? ""]?.[property]; - }, - ); - } -}); - -afterEach(() => { - vi.restoreAllMocks(); - document.body.innerHTML = ""; -}); - -test("an image that loaded before it was followed is loaded at once", () => { - render("/loaded.png"); - watchImage(image); - expect(statuses()).toEqual(["loaded", "loaded"]); -}); - -test("an image that failed before it was followed is an error at once", () => { - render("/broken.png"); - watchImage(image); - expect(statuses()).toEqual(["error", "error"]); -}); - -test("an image that is loading says nothing until its event", () => { - render("/loading.png"); - watchImage(image); - expect(statuses()).toEqual([undefined, undefined]); - images["/loading.png"] = { complete: true, naturalWidth: 32 }; - image.dispatchEvent(new Event("load")); - expect(statuses()).toEqual(["loaded", "loaded"]); -}); - -test("an image that fails while it is followed is an error", () => { - render("/loading.png"); - watchImage(image); - image.dispatchEvent(new Event("error")); - expect(statuses()).toEqual(["error", "error"]); -}); - -test("a new address is followed on the same image", () => { - render("/broken.png"); - watchImage(image); - image.setAttribute("src", "/loaded.png"); - image.dispatchEvent(new Event("load")); - expect(statuses()).toEqual(["loaded", "loaded"]); -}); - -test("an image that left is no longer followed", () => { - render("/loading.png"); - const stop = watchImage(image); - expect(typeof stop).toBe("function"); - stop?.(); - image.dispatchEvent(new Event("error")); - expect(statuses()).toEqual([undefined, undefined]); - expect(watchImage(null)).toBeUndefined(); -}); - -test("an image alone is told, with nothing before it", () => { - document.body.innerHTML = ``; - image = /** @type {HTMLImageElement} */ (document.querySelector("img")); - watchImage(image); - expect(image.dataset.status).toBe("error"); -}); diff --git a/packages/reflex-components-ui/js/tests/behaviors/text-field.test.js b/packages/reflex-components-ui/js/tests/behaviors/text-field.test.js deleted file mode 100644 index 3f28e9ce656..00000000000 --- a/packages/reflex-components-ui/js/tests/behaviors/text-field.test.js +++ /dev/null @@ -1,89 +0,0 @@ -// What a pointer on the box of a text field does: the input takes the focus, -// with its caret at the end the pointer is nearest to. -import { afterEach, beforeEach, expect, test, vi } from "vitest"; - -import { focusField } from "$/reflex-ui/behaviors/text-field.js"; - -/** @type {HTMLElement} */ -let box; -/** @type {HTMLInputElement} */ -let input; - -beforeEach(() => { - document.body.innerHTML = ` -
- -
- -
x
-
-
`; - box = /** @type {HTMLElement} */ (document.getElementById("box")); - input = /** @type {HTMLInputElement} */ (box.querySelector("input")); - // The focus waits for a frame, as the pointer is still going down. - vi.stubGlobal( - "requestAnimationFrame", - (/** @type {FrameRequestCallback} */ callback) => { - callback(0); - return 0; - }, - ); -}); - -afterEach(() => { - vi.unstubAllGlobals(); -}); - -/** - * Put the pointer down on an element of a box. - * - * @param {string} id The id of the element. - * @param {Element} [currentTarget] The box, when it is not the first one. - * @returns {void} - */ -function pointerDown(id, currentTarget = box) { - focusField({ target: document.getElementById(id), currentTarget }); -} - -test("a pointer on a left slot focuses the input at the start of its text", () => { - pointerDown("icon"); - expect(document.activeElement).toBe(input); - expect([input.selectionStart, input.selectionEnd]).toEqual([0, 0]); -}); - -test("a pointer on a right slot focuses the input at the end of its text", () => { - pointerDown("right"); - expect(document.activeElement).toBe(input); - expect([input.selectionStart, input.selectionEnd]).toEqual([6, 6]); -}); - -test("a pointer on the box itself focuses the input at the start", () => { - pointerDown("box"); - expect(document.activeElement).toBe(input); - expect([input.selectionStart, input.selectionEnd]).toEqual([0, 0]); -}); - -test("a button, a link and the input keep the pointer for themselves", () => { - input.setSelectionRange(3, 3); - for (const id of ["clear", "link"]) { - pointerDown(id); - expect(document.activeElement).toBe(document.body); - } - focusField({ target: input, currentTarget: box }); - expect(document.activeElement).toBe(document.body); - expect(input.selectionStart).toBe(3); -}); - -test("an input without a caret, such as a date, still takes the focus", () => { - input.type = "date"; - pointerDown("right"); - expect(document.activeElement).toBe(input); -}); - -test("a box without an input and a target that is no element do nothing", () => { - const empty = /** @type {HTMLElement} */ (document.getElementById("empty")); - pointerDown("alone", empty); - focusField({ target: null, currentTarget: box }); - focusField({ target: document, currentTarget: box }); - expect(document.activeElement).toBe(document.body); -}); diff --git a/packages/reflex-components-ui/parity/allowlist.toml b/packages/reflex-components-ui/parity/allowlist.toml index febec7643e3..1c65ecd863b 100644 --- a/packages/reflex-components-ui/parity/allowlist.toml +++ b/packages/reflex-components-ui/parity/allowlist.toml @@ -72,13 +72,13 @@ reason = "When the orientation of rx.data_list changes at a breakpoint, Radix Th component = "avatar" step = "the fallback is in the server render" system = "rx" -reason = "rx.avatar renders its fallback and its image once JavaScript has run: the server sends an empty placeholder. rx.ui.avatar sends both, so the page shows the avatar before it is hydrated." +reason = "rx.avatar renders its fallback and its image once JavaScript has run: the server sends an empty placeholder. rx.ui.avatar sends its fallback, so the page shows the avatar before it is hydrated." [[contract]] component = "avatar" step = "shows a loaded image and the fallback without JavaScript" system = "rx" -reason = "rx.avatar shows neither its image nor its fallback with JavaScript disabled. rx.ui.avatar shows the fallback, and the image over it once it has loaded; only an image that fails needs JavaScript to give way to the fallback." +reason = "rx.avatar shows neither its image nor its fallback with JavaScript disabled. rx.ui.avatar shows its fallback; UI SDK shows the image in its place once the page has hydrated." [[look]] component = "avatar" @@ -906,3 +906,23 @@ component = "slider" check = "pixels" cells = "size-responsive*" reason = "UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. The responsive slider is of size 1 or 3 at these widths, whose thumbs are an odd number of pixels wide, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise." + +[[contract]] +component = "avatar" +step = "shows a loaded image and the fallback without JavaScript" +reason = "UI SDK keeps the image of rx.ui.avatar hidden until it has loaded, which it learns once the page has hydrated: with JavaScript disabled the avatar shows its fallback. rx.avatar shows neither." + +[[contract]] +component = "form" +step = "a message outside its field shows for the field it names" +reason = "A message of rx.ui.form is an error of the field it is in, as UI SDK has it: one given a `name` outside the fields shows only when it is forced, with `force_match`. rx.form shows it with the reasons of the field it names." + +[[contract]] +component = "form" +step = "a change forgets the reason, and leaving the control reads it again" +reason = "Once a submit finds a control of rx.ui.form invalid, UI SDK reads its validity again as its value changes, so its messages follow what is typed: typing into an empty email field says at once that it is not an email. rx.form hides the messages while the value changes, and reads the reason again when the control is left." + +[[contract]] +component = "text_field" +step = "a pointer on a slot gives the input the focus, at that end of its text" +reason = "UI SDK gives the input of rx.ui.text_field the focus from a press on a slot, and leaves the caret where the browser puts it when an input takes the focus. rx.text_field puts the caret at the end of the text the slot is on." diff --git a/packages/reflex-components-ui/parity/ui_parity/components/avatar.py b/packages/reflex-components-ui/parity/ui_parity/components/avatar.py index 80c2c5fdd95..4dea016ef06 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/avatar.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/avatar.py @@ -94,9 +94,12 @@ def _broken(run: Run) -> None: box = fallback.bounding_box() assert box is not None assert (box["width"], box["height"]) == (40, 40) + # The image is not seen: Radix leaves it out, UI SDK keeps it in the page + # with no opacity. run.page.wait_for_function( "!document.querySelector('#broken img')" - " || getComputedStyle(document.querySelector('#broken img')).display === 'none'" + " || !document.querySelector('#broken img')" + ".checkVisibility({opacityProperty: true})" ) diff --git a/packages/reflex-components-ui/parity/ui_parity/components/form.py b/packages/reflex-components-ui/parity/ui_parity/components/form.py index edc94c85ce2..1665929ae12 100644 --- a/packages/reflex-components-ui/parity/ui_parity/components/form.py +++ b/packages/reflex-components-ui/parity/ui_parity/components/form.py @@ -60,7 +60,11 @@ def _form(namespace: Any, props: Mapping[str, Any]) -> Any: "label": "label", "control": "form > div > :is(input, textarea)", "message": "form > div > span", - "forced": "form > div > span:nth-of-type(2)", + # A message of Radix is a span, an error of UI SDK a div. + "forced": ( + "form > div > span:nth-of-type(2)", + "form > div > [data-slot=field-error]", + ), "submit": "form > button", }, # A field the server finds invalid gives its control the focus, which @@ -149,13 +153,17 @@ def _contract_form(namespace: Any) -> Any: CONTRACT = Contract(component="form", render=_contract_form) -# The messages that show, in the order of the page. +# The messages that show, in the order of the page: a message of Radix is a +# span, an error of UI SDK a div. SHOWN = ( - "[...document.querySelectorAll('#form span')]" + "[...document.querySelectorAll('#form :is(span, [data-slot=field-error])')]" ".filter(message => message.checkVisibility()).map(message => message.textContent)" ) # The name of the control that has the focus. FOCUSED = "document.activeElement.name" +# The message outside the fields, which names the field of the email: rx.ui +# shows it never, which a step of its own holds it to. +OUTSIDE = {"rx": ["Outside"], "rx.ui": []} def _wait_for_messages(run: Run, messages: list[str]) -> None: @@ -221,7 +229,7 @@ def _invalid(run: Run) -> None: page = run.page _control(run, "age").focus() page.locator("#send").click() - _wait_for_messages(run, ["Email is needed", "Outside"]) + _wait_for_messages(run, ["Email is needed", *OUTSIDE[run.system.name]]) assert page.evaluate(FOCUSED) == "email" assert page.locator("#submissions").text_content() == "0" assert page.locator("#email-field").get_attribute("data-invalid") is not None @@ -230,15 +238,22 @@ def _invalid(run: Run) -> None: "expected => (document.querySelector(\"#form [name='email']\")" ".getAttribute('aria-describedby') ?? '').split(' ').filter(Boolean)" ".map(id => document.getElementById(id)?.textContent).join('|') === expected", - arg="Email is needed|Outside", + arg="|".join(["Email is needed", *OUTSIDE[run.system.name]]), ) +@CONTRACT.step("a message outside its field shows for the field it names") +def _outside(run: Run) -> None: + page = run.page + page.locator("#send").click() + _wait_for_messages(run, ["Email is needed", "Outside"]) + + @CONTRACT.step("a change forgets the reason, and leaving the control reads it again") def _change(run: Run) -> None: page = run.page page.locator("#send").click() - _wait_for_messages(run, ["Email is needed", "Outside"]) + _wait_for_messages(run, ["Email is needed", *OUTSIDE[run.system.name]]) page.keyboard.type("ada") _wait_for_messages(run, []) assert page.locator("#email-field").get_attribute("data-invalid") is None @@ -265,7 +280,7 @@ def _pattern(run: Run) -> None: def _reset(run: Run) -> None: page = run.page page.locator("#send").click() - _wait_for_messages(run, ["Email is needed", "Outside"]) + _wait_for_messages(run, ["Email is needed", *OUTSIDE[run.system.name]]) page.locator("#reset").click() _wait_for_messages(run, []) assert page.locator("#email-field").get_attribute("data-invalid") is None diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py b/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py deleted file mode 100644 index 0558386ee1c..00000000000 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/_slot.py +++ /dev/null @@ -1,61 +0,0 @@ -"""What the parts that are rendered as their child share: a trigger, a close button.""" - -from __future__ import annotations - -import dataclasses -from typing import Any - -from reflex_base.components.component import Component - -from reflex_components_ui.base import UIComponent -from reflex_components_ui.layout.flex import Flex -from reflex_components_ui.style import StyleError - - -def held(children: tuple[Any, ...]) -> tuple[Any, ...]: - """Get the children a part that acts on a press is created with. - - Such a part acts on a press, and so does a child with a handler of its - own for one: that child is put in a flex container, which is then the - part, as in the Radix components. - - Args: - children: The children the part is given. - - Returns: - The children, or the flex container around them. - """ - for child in children: - if "on_click" in getattr(child, "event_triggers", {}): - return (Flex.create(*children),) - return children - - -def become_child(part: UIComponent) -> None: - """Have a part render as its only child. - - Args: - part: The part, once it is initialized. - - Raises: - StyleError: If the part does not have exactly one child that is an - element. - """ - children = part.children - if ( - len(children) != 1 - or not isinstance(children[0], Component) - or type(children[0]).render not in (Component.render, UIComponent.render) - ): - name = part._display_name() # pyright: ignore[reportAttributeAccessIssue] - msg = ( - f"{name}: it is rendered as its child, so it needs exactly one " - "child that is an element, such as a button." - ) - raise StyleError(msg) - part._as_child = True # pyright: ignore[reportAttributeAccessIssue] - # The child has to stay the child: a compile would otherwise move one - # that is bound to state into a component of its own. - part._memoization_mode = dataclasses.replace( - part._memoization_mode, recursive=False - ) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py b/packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py index dbbb83325be..f8144780625 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/avatar.py @@ -1,48 +1,54 @@ -"""An avatar: an image of a user, and what stands in for it.""" +"""An avatar: the parts of ``@ui-sdk/react/avatar``, an image of a user and what stands in for it. + +UI SDK shows what stands in for the image until the image has loaded, and +when it fails, as Radix does. +""" from __future__ import annotations from typing import Any, ClassVar, Literal from reflex_base.components.component import Component, field -from reflex_base.utils.imports import ImportVar -from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.vars.base import LiteralVar, Var from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.el import elements -from reflex_components_ui.base import Part, UIComponent -from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.base import Part +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.avatar import AVATAR from reflex_components_ui.themes import LiteralAccentColor, LiteralRadius LiteralSize = Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"] -# The ref of the image: it tells the image and the fallback how the load -# ended, which is all the JavaScript of an avatar. -_WATCH_IMAGE = Var( - "watchImage", - _var_data=VarData( - imports={ - f"$/{WEB_DIR}/behaviors/image-status.js": [ImportVar(tag="watchImage")] - } - ), -) +_LIBRARY = entry("avatar") # The part that holds the fallback, by the number of its letters. _FALLBACK_PARTS = {1: "fallback_one", 2: "fallback_two"} -class AvatarImage(Part, elements.Img): - """The image of an avatar.""" +class AvatarImage(SDKPart, Part, elements.Img): + """The image of an avatar, which UI SDK shows once it has loaded.""" + + library = _LIBRARY + + tag = "AvatarImage" + - tag = "img" +class AvatarFallback(SDKPart, Part): + """What stands in for the image of an avatar until it has loaded.""" + library = _LIBRARY -class Avatar(UIComponent): + tag = "AvatarFallback" + + +class Avatar(SDKPart): """An image element with a fallback for representing the user.""" - tag = "span" + library = _LIBRARY + + tag = "Avatar" styles: ClassVar[ComponentStyles] = AVATAR @@ -81,8 +87,7 @@ def _exclude_props(self) -> list[str]: def create(cls, *children, **props) -> Component: """Create an avatar: the fallback, and the image over it when it has one. - The fallback shows until the image has loaded, and when it fails. An - avatar without a ``src`` is its fallback alone, and has no JavaScript. + The fallback shows until the image has loaded, and when it fails. Args: *children: The children of the component. @@ -103,16 +108,15 @@ def create(cls, *children, **props) -> Component: part = "fallback_bound" counted = {"custom_attrs": {"data-letters": letters.to(str).length()}} parts = [ - Part.create( + AvatarFallback.create( *([] if fallback is None else [fallback]), part=part or "fallback", - tag="span", **counted, ) ] src = props.get("src") if src is not None: - image_props = {"src": src, "custom_attrs": {"ref": _WATCH_IMAGE}} + image_props = {"src": src} if "alt" in props: image_props["alt"] = props["alt"] parts.append(AvatarImage.create(part="image", **image_props)) diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/form.py b/packages/reflex-components-ui/src/reflex_components_ui/components/form.py index a98f425cc24..80bdb06b3ee 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/form.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/form.py @@ -1,4 +1,9 @@ -"""A form: the native element, its fields, and messages for what is not valid.""" +"""A form: the native element, and its fields: the parts of ``@ui-sdk/react/field``. + +UI SDK links a field's label and messages to its control, and shows the +messages of what is not valid once a submit finds the control invalid, +as Radix does. +""" from __future__ import annotations @@ -15,15 +20,14 @@ from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, no_args_event_spec from reflex_base.utils.form import FormData as _FormData -from reflex_base.utils.imports import ImportVar -from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.vars.base import LiteralVar, Var from reflex_components_core.core.debounce import DebounceInput from reflex_components_core.el.elements.forms import BaseInput, Select, Textarea from reflex_components_core.el.elements.forms import Form as HTMLForm from reflex_components_ui.base import UIComponent from reflex_components_ui.components._group import literal -from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.form import FORM, FORM_FIELD, FORM_LABEL, FORM_MESSAGE @@ -31,32 +35,21 @@ # or textarea, or a component rendering one. _FORM_CONTROL_CHILD_TYPES = (BaseInput, Select, Textarea, DebounceInput) -_SCRIPT = f"$/{WEB_DIR}/behaviors/form-validity.js" - - -def _handler(name: str) -> Var: - """Get one of the functions that show the validity of a form's controls. - - Args: - name: The name of the function. - - Returns: - The function, with its import. - """ - return Var(name, _var_data=VarData(imports={_SCRIPT: [ImportVar(tag=name)]})) - - -# What reads the validity of the controls of a form, all the JavaScript of -# one: a form without a message has none. -_INVALID = _handler("invalid") -_CHANGED = _handler("changed") -_LEFT = _handler("left") -_CLEARED = _handler("cleared") -_FOCUS_INVALID = _handler("focusInvalid") +_LIBRARY = entry("field") # Numbers the fields whose control is given no id of its own. _ids = itertools.count(1) +# The ref of a field the server finds invalid: the first control of the form +# that is not valid takes the focus, as in Radix. +_FOCUS_INVALID = ( + "((field) => { const form = field?.closest('form'); if (!form) return;" + " const control = [...form.elements].find((element) =>" + " element.matches?.('input, select, textarea') &&" + " (element.ariaInvalid === 'true' || !element.validity.valid));" + " control?.focus(); })" +) + def _find(component: BaseComponent, kind: type | tuple[type, ...]) -> Iterator[Any]: """Find the components of a kind below another, at any depth. @@ -83,7 +76,7 @@ def _native(control: Component) -> Component: Returns: The component that renders the input, the select or the textarea. """ - if isinstance(control, UIComponent) and control.tag == "div": + if isinstance(control, UIComponent) and control.tag in ("div", "InputGroup"): return control.children[0] # pyright: ignore[reportReturnType] return control @@ -130,72 +123,32 @@ class FormRoot(HTMLForm, UIComponent): def _set_slot(self) -> None: """Render the form itself: it is the element that submits.""" - def _post_init(self, *args, **kwargs): - """Initialize the form, and see whether it has validity to show. - - Args: - *args: Args to initialize the component. - **kwargs: Kwargs to initialize the component. - """ - super()._post_init(*args, **kwargs) - self._has_messages = next(_find(self, FormMessage), None) is not None - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the form, its script 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) - if self._has_messages: - yield _INVALID - yield _CHANGED - yield _LEFT - yield _CLEARED - def _render(self) -> CommonTag: """Render the form. Returns: - The tag. A form with messages reads the validity of its controls - where it changes, and server errors are cleared where Radix - clears them: on a submit and on a reset. + The tag. Server errors are cleared where Radix clears them: on a + submit and on a reset. """ tag = super()._render() clear = tag.props.get("onClearServerErrors") tag = tag.remove_props("onClearServerErrors") - handlers: dict[str, list[str]] = {} - if self._has_messages: - handlers = { - "onInvalid": [str(_INVALID)], - "onChangeCapture": [str(_CHANGED)], - "onBlurCapture": [str(_LEFT)], - "onReset": [str(_CLEARED)], - } - var_data = None - if clear is not None: - clear = LiteralVar.create(clear) - var_data = clear._get_all_var_data() - for prop in ("onReset", "onSubmitCapture"): - handlers.setdefault(prop, []).append(f"({clear!s})") - for prop, functions in handlers.items(): - calls = "; ".join(f"{function}(event)" for function in functions) - tag = tag.add_props(**{ - prop: Var(f"((event) => {{ {calls}; }})", _var_data=var_data) - }) - return tag - - -class FormField(UIComponent): + if clear is None: + return tag + clear = LiteralVar.create(clear) + handler = Var( + f"((event) => {{ ({clear!s})(event); }})", + _var_data=clear._get_all_var_data(), + ) + return tag.add_props(onReset=handler, onSubmitCapture=handler) + + +class FormField(SDKPart): """A form field component.""" - tag = "div" + library = _LIBRARY + + tag = "Field" styles: ClassVar[ComponentStyles] = FORM_FIELD @@ -211,15 +164,11 @@ class FormField(UIComponent): doc="Flag to mark the form field as invalid, for server side validation." ) - def _set_slot(self) -> None: - """Render the field itself.""" - def _post_init(self, *args, **kwargs): """Initialize the field: name its control, and point its labels at it. - Radix hands the name and an id through a context. Here the field - finds its control and its labels while compiling, below it at any - depth. + The link is in the page the server sends, so that a label gives its + control the focus without JavaScript, as in Radix. Args: *args: Args to initialize the component. @@ -251,31 +200,12 @@ def _post_init(self, *args, **kwargs): label.custom_attrs.setdefault("htmlFor", control_id) def _exclude_props(self) -> list[str]: - """Keep the props that are not attributes off the element. + """Keep what UI SDK is given otherwise off the field. Returns: - The props read as styles, and the ones the field hands down. + The props read as styles, ``as_child`` and ``server_invalid``. """ - return [*super()._exclude_props(), "name", "server_invalid"] - - def _get_vars( - self, include_children: bool = False, ignore_ids: set[int] | None = None - ) -> Iterator[Var]: - """Walk all Vars used in the field, its script 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) - if ( - self.server_invalid is not None - and literal(self.server_invalid) is not False - ): - yield _FOCUS_INVALID + return [*super()._exclude_props(), "as_child", "server_invalid"] def _render(self, props: dict[str, Any] | None = None) -> CommonTag: """Render the field. @@ -284,40 +214,34 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: props: The props to render (if None, then use get_props). Returns: - The tag, marked as the field of the messages inside it, and as - invalid when the server says so. + The tag: invalid while the server says so, and the browser's + validity otherwise. The control takes the focus when the server + finds the field invalid, as in Radix. """ - tag = super()._render(props).add_props(**{"data-rx-form-field": ""}) + tag = super()._render(props) invalid = self.server_invalid if invalid is None or literal(invalid) is False: return tag - flag = ( - "" - if literal(invalid) is True - else Var( - f'({invalid!s} ? "" : undefined)', - _var_data=invalid._get_all_var_data(), - ) - ) - # A ref that is new when the server finds the field invalid, so that - # React calls it then: the control takes the focus, as in Radix. - focus = ( - _FOCUS_INVALID - if literal(invalid) is True - else Var( - f"({invalid!s} ? {_FOCUS_INVALID!s} : undefined)", - _var_data=VarData.merge( - invalid._get_all_var_data(), _FOCUS_INVALID._get_all_var_data() - ), - ) - ) + if literal(invalid) is True: + return tag.add_props(invalid=True, ref=Var(_FOCUS_INVALID)) + var_data = invalid._get_all_var_data() return tag.add_props( - ref=focus, **{"data-invalid": flag, "data-server-invalid": flag} + invalid=Var(f"({invalid!s} || undefined)", _var_data=var_data), + # A ref that is new when the server finds the field invalid, so + # that React calls it then. + ref=Var( + f"({invalid!s} ? {_FOCUS_INVALID} : undefined)", _var_data=var_data + ), ) class FormLabel(UIComponent): - """A form label component.""" + """A form label component. + + A native label, which the field points at its control in the page the + server sends: UI SDK's label points at an id of its own until the page + hydrates. + """ tag = "label" @@ -331,10 +255,12 @@ def _set_slot(self) -> None: """Render the label itself.""" -class FormControl(UIComponent): +class FormControl(SDKPart): """A form control component.""" - tag = "input" + library = _LIBRARY + + tag = "FieldControl" as_child: Var[bool] = field( doc="Change the default rendered element for the one passed as a child." @@ -390,8 +316,13 @@ def create(cls, *children, **props): return child return super().create(**props) - def _set_slot(self) -> None: - """Render the input itself: a child is returned in its place.""" + def _exclude_props(self) -> list[str]: + """Keep ``as_child`` off the input. + + Returns: + The props read as styles, and ``as_child``. + """ + return [*super()._exclude_props(), "as_child"] LiteralMatcher = Literal[ @@ -431,42 +362,62 @@ class FormMessage(UIComponent): doc="Forces the message to be shown. This is useful when using server-side validation." ) + @classmethod + def create(cls, *children, **props) -> Component: + """Create a message: one shown always, or the error of a condition. + + Args: + *children: What the message says. + **props: The properties of the message. + + Returns: + The message. One with a condition is an error of UI SDK, which + shows it when the condition holds, or when it is forced to. + """ + if cls is FormMessage and props.get("match") is not None: + return _FormError.create(*children, **props) + return super().create(*children, **props) + def _set_slot(self) -> None: """Render the message itself.""" def _exclude_props(self) -> list[str]: - """Keep the props that are rendered as data off the element. + """Keep the props of the condition off the element. Returns: The props read as styles, and the ones of the message. """ - return [*super()._exclude_props(), "name", "match", "force_match"] + return [*super()._exclude_props(), "name", "match", "force_match", "as_child"] + + +class _FormError(SDKPart, FormMessage): + """A message that shows when a condition holds: an error of UI SDK.""" + + library = _LIBRARY + + tag = "FieldError" def _render(self, props: dict[str, Any] | None = None) -> CommonTag: - """Render the message. + """Render the error, which shows when its condition holds or is forced. Args: props: The props to render (if None, then use get_props). Returns: - The tag. A message with a condition is hidden until its script - finds that the condition holds, or it is forced to show. + The tag, with what UI SDK matches: the condition, or true while + the message is forced to show. """ - tag = super()._render(props).add_props(**{"data-rx-form-message": ""}) - if self.name is not None: - tag = tag.add_props(**{"data-name": self.name}) - if self.match is None: - return tag - tag = tag.add_props(**{"data-match": self.match}) - force = self.force_match + tag = super()._render(props) + match, force = self.match, self.force_match if force is None or literal(force) is False: - return tag.add_props(hidden=True) + return tag.add_props(match=match) if literal(force) is True: - return tag.add_props(**{"data-force": ""}) - var_data = force._get_all_var_data() + return tag.add_props(match=True) return tag.add_props( - hidden=Var(f"!({force!s})", _var_type=bool, _var_data=var_data), - **{"data-force": Var(f'({force!s} ? "" : undefined)', _var_data=var_data)}, + match=Var( + f"({force!s} ? true : {match!s})", + _var_data=force._get_all_var_data(), + ) ) @@ -506,6 +457,10 @@ def _render(self, props: dict[str, Any] | None = None) -> CommonTag: # This class is created mainly for reflex-web docs. +# Its errors name what an app calls: a prop of the message it created. +_FormError.__name__ = _FormError.__qualname__ = "FormMessage" + + class Form(FormRoot): """The Form component.""" diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py index 729bd57c828..d5b5a6f872e 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/text_field.py @@ -1,4 +1,8 @@ -"""A text field: a box around a native input, with slots for icons and buttons.""" +"""A text field: a box around a native input, with slots for icons and buttons. + +A box with slots is the input group of ``@ui-sdk/react/input``: a press on +a slot, or on the edge of the box, gives the input the focus. +""" from __future__ import annotations @@ -7,9 +11,8 @@ from reflex_base.components.component import Component, ComponentNamespace, field from reflex_base.components.tags import CommonTag from reflex_base.event import EventHandler, input_event, key_event -from reflex_base.utils.imports import ImportVar from reflex_base.utils.types import is_optional, safe_issubclass, value_inside_optional -from reflex_base.vars.base import Var, VarData +from reflex_base.vars.base import Var from reflex_base.vars.number import ternary_operation from reflex_components_core.core.breakpoints import Responsive from reflex_components_core.core.debounce import DebounceInput @@ -17,7 +20,7 @@ from reflex_components_ui.base import UIComponent from reflex_components_ui.components._group import literal -from reflex_components_ui.constants import WEB_DIR +from reflex_components_ui.components._sdk import SDKPart, entry from reflex_components_ui.style import ComponentStyles from reflex_components_ui.styles.text_field import ( TEXT_FIELD, @@ -29,16 +32,6 @@ LiteralTextFieldSize = Literal["1", "2", "3"] LiteralTextFieldVariant = Literal["classic", "surface", "soft"] -# The `onPointerDown` of a box with slots: a pointer on a slot or on the edge -# of the box gives the input the focus, which is all the JavaScript of a text -# field. -_FOCUS_FIELD = Var( - "focusField", - _var_data=VarData( - imports={f"$/{WEB_DIR}/behaviors/text-field.js": [ImportVar(tag="focusField")]} - ), -) - # The props of the box of a text field or a text area. Every other one is a # prop of the control inside it. _BOX_PROPS = frozenset(( @@ -278,10 +271,18 @@ def create(cls, *children, **props) -> Component: if own.get("value") is not None and own.get("on_change") is not None: # create a debounced input if the user requests full control to avoid typing jank control = DebouncedControl.create(control, **wrapper) # pyright: ignore[reportArgumentType] - if children: - _place_slots(children) - props.setdefault("custom_attrs", {})["onPointerDown"] = _FOCUS_FIELD - return super().create(control, *children, **props) + if not children: + return super().create(control, **props) + _place_slots(children) + return super(TextFieldRoot, _TextFieldGroup).create(control, *children, **props) + + +class _TextFieldGroup(SDKPart, TextFieldRoot): + """A text field with slots: UI SDK gives its input the focus from them.""" + + library = entry("input") + + tag = "InputGroup" def _place_slots(children: tuple[Any, ...]) -> None: diff --git a/packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.py b/packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.py index 3c26d377846..a7ce83d06ca 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.py @@ -8,6 +8,7 @@ from __future__ import annotations +import dataclasses import json from typing import Any, ClassVar, get_args @@ -22,7 +23,6 @@ from reflex_components_ui import _radix_tokens, tokens from reflex_components_ui.base import UIComponent from reflex_components_ui.components._script import listen, script -from reflex_components_ui.components._slot import become_child from reflex_components_ui.components.button import button from reflex_components_ui.components.icon_button import IconButton from reflex_components_ui.components.popover import popover @@ -344,14 +344,19 @@ class _Shortcut(Kbd): """The key that shows and hides the panel, rendered as the button inside it.""" def _post_init(self, *args, **kwargs): - """Initialize the key, rendered as its only child. + """Initialize the key, rendered as its only child, the button. Args: *args: Args to initialize the component. **kwargs: Kwargs to initialize the component. """ super()._post_init(*args, **kwargs) - become_child(self) + self._as_child = True + # The button has to stay the child: a compile would otherwise move + # one bound to state into a component of its own. + self._memoization_mode = dataclasses.replace( + self._memoization_mode, recursive=False + ) class _InfoButton(IconButton): diff --git a/packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py b/packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py index d67ab646cad..301e3629169 100644 --- a/packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py +++ b/packages/reflex-components-ui/src/reflex_components_ui/styles/avatar.py @@ -1,4 +1,4 @@ -"""The look of an avatar: an image over what stands in for it.""" +"""The look of an avatar: an image, or what stands in for it.""" from __future__ import annotations @@ -133,11 +133,6 @@ def _fallback(font_size: str | dict[str, str] | None) -> ComponentStyles: "line_height": 1, "border_radius": "inherit", "text_transform": "uppercase", - # Under the image, which is as large: neither gives way to the - # other. Alone it is the fallback of Radix Themes, which may shrink. - "flex_shrink": {":not(:only-child)": 0}, - # An image that loaded is all there is to see, see-through or not. - "visibility": {"[data-status='loaded']": "hidden"}, } if font_size is not None: base["font_size"] = font_size @@ -196,15 +191,12 @@ def _fallback(font_size: str | dict[str, str] | None) -> ComponentStyles: "image": { "base": unchecked({ "box_sizing": "border-box", - "display": {"default": "block", "[data-status='error']": "none"}, + "display": "block", "max_width": "100%", "width": "100%", "height": "100%", "object_fit": "cover", "border_radius": "inherit", - # Over what stands in for it, which comes first. - "flex_shrink": 0, - "margin_left": "-100%", }), }, }, diff --git a/pyi_hashes.json b/pyi_hashes.json index 614e9c1282b..5472cf6581a 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -129,7 +129,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/accordion.pyi": "c899c6feec8ef54c7e6f5b772b58ee2f", "packages/reflex-components-ui/src/reflex_components_ui/components/alert_dialog.pyi": "8116a4bc68a3d9607dfc44aa5f15dc22", "packages/reflex-components-ui/src/reflex_components_ui/components/aspect_ratio.pyi": "19678f0d00dd9133d7fabeb086d9cd72", - "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "296a02d4f7a276a0548ec473a6c761a9", + "packages/reflex-components-ui/src/reflex_components_ui/components/avatar.pyi": "484c66746c5df97d6cae253608998f20", "packages/reflex-components-ui/src/reflex_components_ui/components/badge.pyi": "f54c7d6d2a403389eb7424f7024bb847", "packages/reflex-components-ui/src/reflex_components_ui/components/button.pyi": "9e3f6fccbe30356fdbbe576471d6222e", "packages/reflex-components-ui/src/reflex_components_ui/components/callout.pyi": "b878e3859317f6cf7e452eaa9683654f", @@ -143,7 +143,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/dialog.pyi": "841323f7bbdbc96b7646be3d89ef4dda", "packages/reflex-components-ui/src/reflex_components_ui/components/drawer.pyi": "bb3fcfaae77fb8388155a6df7ba55cb4", "packages/reflex-components-ui/src/reflex_components_ui/components/dropdown_menu.pyi": "388ab56522100c0300a380b8d87fa07a", - "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "6470600db545ad02437ec8b2aafe3694", + "packages/reflex-components-ui/src/reflex_components_ui/components/form.pyi": "2f23bdc76054177968b890c4c86eeb42", "packages/reflex-components-ui/src/reflex_components_ui/components/hover_card.pyi": "3eb07ede3ba9e134d30b1ca0cf4f7ea8", "packages/reflex-components-ui/src/reflex_components_ui/components/icon_button.pyi": "ff38238be8b0b1efa006048e8d7c093b", "packages/reflex-components-ui/src/reflex_components_ui/components/inset.pyi": "e7845d0ca8291ca3d4990c7f91eca734", @@ -162,7 +162,7 @@ "packages/reflex-components-ui/src/reflex_components_ui/components/table.pyi": "3d2683d69d98f3cd14da65831e89e5fe", "packages/reflex-components-ui/src/reflex_components_ui/components/tabs.pyi": "bc587de2eb7fe5bdd4caf7deb8a9c0d8", "packages/reflex-components-ui/src/reflex_components_ui/components/text_area.pyi": "85e3d7d2cf756b3a67683d9724b1a68b", - "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "0493db3f24247140307bd4387444aac4", + "packages/reflex-components-ui/src/reflex_components_ui/components/text_field.pyi": "aa05942bd728f72b9cfb02222ae25cbf", "packages/reflex-components-ui/src/reflex_components_ui/components/theme_panel.pyi": "8415abf97f4c226acc2f721278dca20f", "packages/reflex-components-ui/src/reflex_components_ui/components/tooltip.pyi": "082353523ccccf169c362ed6cd684e65", "packages/reflex-components-ui/src/reflex_components_ui/layout/box.pyi": "063c5d816f7340a5348288ac9aec58dd", diff --git a/tests/integration/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py index a1d9848af23..3aadabd70d0 100644 --- a/tests/integration/tests_playwright/test_ui_components.py +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -303,20 +303,19 @@ ), "const sx_16addd9092_c = stylex.props(sx_16addd9092.s).className;", ( - 'const sx_21e3781dc3 = stylex.create({ s: {"boxSizing": "border-box", "fo' + 'const sx_cc3b8d15e3 = stylex.create({ s: {"boxSizing": "border-box", "fo' 'ntFamily": "var(--default-font-family)", "fontWeight": "var(--font-weigh' 't-medium)", "fontStyle": "normal", "zIndex": 0, "width": "100%", "height' '": "100%", "display": "flex", "alignItems": "center", "justifyContent": ' '"center", "lineHeight": 1, "borderTopLeftRadius": "inherit", "borderTopR' 'ightRadius": "inherit", "borderBottomRightRadius": "inherit", "borderBot' - 'tomLeftRadius": "inherit", "textTransform": "uppercase", "flexShrink": {' - '":not(:only-child)": 0}, "visibility": {"[data-status=\'loaded\']": "hidde' - 'n"}, "fontSize": {"[data-letters=\'1\']": "var(--avatar-fallback-one-lette' - 'r-font-size)", "[data-letters=\'2\']": "var(--avatar-fallback-two-letters-' - 'font-size, var(--avatar-fallback-one-letter-font-size))"}, "backgroundCo' - 'lor": "var(--accent-a3)", "color": "var(--accent-a11)"} });' + 'tomLeftRadius": "inherit", "textTransform": "uppercase", "fontSize": {"[' + 'data-letters=\'1\']": "var(--avatar-fallback-one-letter-font-size)", "[dat' + "a-letters='2']\": \"var(--avatar-fallback-two-letters-font-size, var(--ava" + 'tar-fallback-one-letter-font-size))"}, "backgroundColor": "var(--accent-' + 'a3)", "color": "var(--accent-a11)"} });' ), - ("const sx_21e3781dc3_c = stylex.props(sx_21e3781dc3.s).className;"), + ("const sx_cc3b8d15e3_c = stylex.props(sx_cc3b8d15e3.s).className;"), ( 'const sx_8df01e863a = stylex.create({ s: {"boxSizing": "border-box", "di' 'splay": "inline-flex", "alignItems": "center", "justifyContent": "center' @@ -1905,8 +1904,8 @@ def test_display_and_action_components_work_in_an_app(ui_app: AppHarness, page: })""" ) == [["running", 800], ["running", 1000]] - # The one script of the wave: a broken image gives way to its fallback. - expect(page.locator("#broken img")).to_have_css("display", "none") + # A broken image gives way to its fallback: UI SDK keeps it unseen. + expect(page.locator("#broken img")).to_have_css("opacity", "0") expect(page.locator("#broken").get_by_text("CD")).to_be_visible() # Loading follows the state: the button is disabled under a spinner. diff --git a/tests/units/reflex_components_ui/components/test_avatar.py b/tests/units/reflex_components_ui/components/test_avatar.py index 3ab3b0fd4ad..a4c5da2c81c 100644 --- a/tests/units/reflex_components_ui/components/test_avatar.py +++ b/tests/units/reflex_components_ui/components/test_avatar.py @@ -7,6 +7,7 @@ from reflex_components_ui.plugin import UIPlugin import reflex as rx +from tests.units.reflex_components_ui.render import tree class AvatarState(rx.State): @@ -15,258 +16,80 @@ class AvatarState(rx.State): initials: str = "AB" -def test_avatar_fallback_alone( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], -): - """Without a src an avatar is its fallback, sized by its two letters.""" - component = rx.ui.avatar(fallback="AB") - assert component.render() == { - "name": '"span"', - "props": ["className:sx_eecdbf58c4_c"], - "children": [ - { - "name": '"span"', - "props": ["className:sx_2cb4e09027_c"], - "children": [{"contents": '"AB"'}], - } - ], - } - assert declared_styles(component) == [ - { - "boxSizing": "border-box", - "display": "inline-flex", - "alignItems": "center", - "justifyContent": "center", - "verticalAlign": "middle", - "userSelect": "none", - "width": "var(--avatar-size)", - "height": "var(--avatar-size)", - "flexShrink": 0, - "--avatar-size": "var(--space-7)", - "--avatar-fallback-one-letter-font-size": "var(--font-size-4)", - "borderRadius": "max(var(--radius-3), var(--radius-full))", - "letterSpacing": "var(--letter-spacing-3)", - "--avatar-fallback-two-letters-font-size": "var(--font-size-3)", - }, - { - "boxSizing": "border-box", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-medium)", - "fontStyle": "normal", - "zIndex": 0, - "width": "100%", - "height": "100%", - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "lineHeight": 1, - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "textTransform": "uppercase", - "flexShrink": {":not(:only-child)": 0}, - "visibility": {"[data-status='loaded']": "hidden"}, - "fontSize": "var(--avatar-fallback-two-letters-font-size, " - "var(--avatar-fallback-one-letter-font-size))", - "backgroundColor": "var(--accent-a3)", - "color": "var(--accent-a11)", - }, - ] +def test_avatar_fallback_alone(ui_plugin: UIPlugin): + """An avatar without an image is the parts of UI SDK, and its fallback alone.""" + component = rx.ui.avatar(fallback="R", size="5", variant="solid") + assert tree(component.render()) == ( + "Avatar", + ["className:sx_119fa60175_c"], + [("AvatarFallback", ["className:sx_9cf1bef94d_c"], ['"R"'])], + ) -def test_avatar_image_over_the_fallback( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], +def test_avatar_image_and_its_fallback( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] ): - """The image lies over the fallback, and its ref says how its load ended.""" - component = rx.ui.avatar( - src="/ada.png", - alt="Ada", - fallback="A", - size="5", - variant="solid", - high_contrast=True, - radius="full", - id="ada", - ) - assert component.render() == { - "name": '"span"', - "props": [ - 'className:sx_119fa60175_c + " " + reflexUIClasses_4c7cd6a7ce', - 'id:"ada"', - "ref:ref_ada", - ], - "children": [ - { - "name": '"span"', - "props": ["className:sx_3102976db3_c"], - "children": [{"contents": '"A"'}], - }, - { - "name": '"img"', - "props": [ - 'alt:"Ada"', - "className:sx_b22e24c3d6_c", - "ref:watchImage", - 'src:"/ada.png"', - ], - "children": [], - }, + """An avatar with an image has its fallback, which UI SDK shows until the image has loaded, then the image, which is all there is once it has.""" + component = rx.ui.avatar(src="/me.png", fallback="RX", alt="Me", radius="full") + assert tree(component.render()) == ( + "Avatar", + ['className:sx_eecdbf58c4_c + " " + reflexUIClasses_4c7cd6a7ce'], + [ + ("AvatarFallback", ["className:sx_46859d4f4b_c"], ['"RX"']), + ( + "AvatarImage", + ['alt:"Me"', "className:sx_9b569d2d23_c", 'src:"/me.png"'], + [], + ), ], + ) + *_, image = declared_styles(component) + assert image == { + "boxSizing": "border-box", + "display": "block", + "maxWidth": "100%", + "width": "100%", + "height": "100%", + "objectFit": "cover", + "borderTopLeftRadius": "inherit", + "borderTopRightRadius": "inherit", + "borderBottomRightRadius": "inherit", + "borderBottomLeftRadius": "inherit", } - assert declared_styles(component) == [ - { - "boxSizing": "border-box", - "display": "inline-flex", - "alignItems": "center", - "justifyContent": "center", - "verticalAlign": "middle", - "userSelect": "none", - "width": "var(--avatar-size)", - "height": "var(--avatar-size)", - "flexShrink": 0, - "--avatar-size": "var(--space-9)", - "--avatar-fallback-one-letter-font-size": "var(--font-size-6)", - "borderRadius": "max(var(--radius-4), var(--radius-full))", - "letterSpacing": "var(--letter-spacing-6)", - }, - { - "boxSizing": "border-box", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-medium)", - "fontStyle": "normal", - "zIndex": 0, - "width": "100%", - "height": "100%", - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "lineHeight": 1, - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "textTransform": "uppercase", - "flexShrink": {":not(:only-child)": 0}, - "visibility": {"[data-status='loaded']": "hidden"}, - "fontSize": "var(--avatar-fallback-one-letter-font-size)", - "backgroundColor": "var(--accent-12)", - "color": "var(--accent-1)", - }, - { - "boxSizing": "border-box", - "display": {"default": "block", "[data-status='error']": "none"}, - "maxWidth": "100%", - "width": "100%", - "height": "100%", - "objectFit": "cover", - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "flexShrink": 0, - "marginLeft": "-100%", - }, - ] -def test_avatar_fallback_bound_to_state( - ui_plugin: UIPlugin, - declared_styles: Callable[[Any], list[dict[str, Any]]], -): - """The letters of a fallback bound to state are counted by the page.""" - component = rx.ui.avatar( - fallback=AvatarState.initials, size=rx.breakpoints(initial="1", md="4") - ) - assert component.render() == { - "name": '"span"', - "props": ["className:sx_0c15401e7f_c"], - "children": [ - { - "name": '"span"', - "props": [ - "className:sx_21e3781dc3_c", - f'"data-letters":pyStrLength({AvatarState.initials!s})', +def test_avatar_fallback_bound_to_state(ui_plugin: UIPlugin): + """The letters of a fallback bound to state are counted by the page, which sizes them by their number.""" + component = rx.ui.avatar(fallback=AvatarState.initials) + initials = f"{AvatarState.initials!s}" + assert tree(component.render()) == ( + "Avatar", + ["className:sx_eecdbf58c4_c"], + [ + ( + "AvatarFallback", + [ + "className:sx_cc3b8d15e3_c", + f'"data-letters":pyStrLength({initials})', ], - "children": [ - { - "contents": "reflex___state____state__tests___units___reflex_components_ui___components___test_avatar____avatar_state.initials_rx_state_" - } - ], - } + [initials], + ) ], - } - assert declared_styles(component) == [ - { - "boxSizing": "border-box", - "display": "inline-flex", - "alignItems": "center", - "justifyContent": "center", - "verticalAlign": "middle", - "userSelect": "none", - "width": "var(--avatar-size)", - "height": "var(--avatar-size)", - "flexShrink": 0, - "--avatar-size": { - "default": "var(--space-5)", - "@media (min-width: 1024px)": "var(--space-8)", - }, - "--avatar-fallback-one-letter-font-size": { - "default": "var(--font-size-2)", - "@media (min-width: 1024px)": "var(--font-size-5)", - }, - "borderRadius": { - "default": "max(var(--radius-2), var(--radius-full))", - "@media (min-width: 1024px)": "max(var(--radius-3), " - "var(--radius-full))", - }, - "letterSpacing": { - "default": "var(--letter-spacing-1)", - "@media (min-width: 1024px)": "var(--letter-spacing-4)", - }, - "--avatar-fallback-two-letters-font-size": { - "default": "var(--font-size-1)", - "@media (min-width: 1024px)": "var(--font-size-4)", - }, - }, - { - "boxSizing": "border-box", - "fontFamily": "var(--default-font-family)", - "fontWeight": "var(--font-weight-medium)", - "fontStyle": "normal", - "zIndex": 0, - "width": "100%", - "height": "100%", - "display": "flex", - "alignItems": "center", - "justifyContent": "center", - "lineHeight": 1, - "borderTopLeftRadius": "inherit", - "borderTopRightRadius": "inherit", - "borderBottomRightRadius": "inherit", - "borderBottomLeftRadius": "inherit", - "textTransform": "uppercase", - "flexShrink": {":not(:only-child)": 0}, - "fontSize": { - "[data-letters='1']": "var(--avatar-fallback-one-letter-font-size)", - "[data-letters='2']": ( - "var(--avatar-fallback-two-letters-font-size, " - "var(--avatar-fallback-one-letter-font-size))" - ), - }, - "visibility": {"[data-status='loaded']": "hidden"}, - "backgroundColor": "var(--accent-a3)", - "color": "var(--accent-a11)", - }, - ] + ) -def test_avatar_imports_its_script_only_with_an_image(ui_plugin: UIPlugin): - """The one script of an avatar follows the load of an image.""" - script = "$/reflex-ui/behaviors/image-status.js" - assert script not in rx.ui.avatar(fallback="AB")._get_all_imports() - assert rx.ui.avatar(src="/ada.png", fallback="AB")._get_all_imports()[script] == [ - ImportVar(tag="watchImage") - ] +def test_avatar_imports_ui_sdk(ui_plugin: UIPlugin): + """A page with an avatar imports its parts from UI SDK, pinned, and no script.""" + component = rx.ui.avatar(src="/me.png", fallback="RX") + assert { + module: names + for module, names in component._get_all_imports().items() + if "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/avatar": [ + ImportVar(tag="Avatar"), + ImportVar(tag="AvatarFallback"), + ImportVar(tag="AvatarImage"), + ], + } diff --git a/tests/units/reflex_components_ui/components/test_form.py b/tests/units/reflex_components_ui/components/test_form.py index a4e0b23a1e9..8429cb4df2a 100644 --- a/tests/units/reflex_components_ui/components/test_form.py +++ b/tests/units/reflex_components_ui/components/test_form.py @@ -10,6 +10,20 @@ from reflex_components_ui.plugin import UIPlugin import reflex as rx +from tests.units.reflex_components_ui.render import tree + +# The class of a message. +MESSAGE = "className:sx_71d77c9098_c" + +# The ref of a field the server finds invalid: the first control of the form +# that is not valid takes the focus. +FOCUS_INVALID = ( + "((field) => { const form = field?.closest('form'); if (!form) return;" + " const control = [...form.elements].find((element) =>" + " element.matches?.('input, select, textarea') &&" + " (element.ariaInvalid === 'true' || !element.validity.valid));" + " control?.focus(); })" +) class FormState(rx.State): @@ -35,7 +49,7 @@ def test_form_parts( ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]], ): - """A field names its control and points its label at it; a message with a condition is hidden until it holds, and the form reads the validity of its controls.""" + """A field is UI SDK's, which names its control and points its label at it; a message with a condition is an error of UI SDK, shown when it holds, and one without is always shown.""" component = rx.ui.form( rx.ui.form.field( rx.ui.form.label("Email"), @@ -49,35 +63,31 @@ def test_form_parts( rx.ui.form.submit("Send"), id="signup", ) - assert component.render() == { - "name": '"form"', - "props": [ + assert tree(component.render()) == ( + '"form"', + [ "className:sx_5073704993_c", 'id:"signup"', - "onBlurCapture:((event) => { left(event); })", - "onChangeCapture:((event) => { changed(event); })", - "onInvalid:((event) => { invalid(event); })", - "onReset:((event) => { cleared(event); })", "onSubmit:handleSubmit_ff7a0ed8ca0437fd853c637504ba1398", "ref:ref_signup", ], - "children": [ - { - "name": '"div"', - "props": ["className:sx_7fb5ccb001_c", '"data-rx-form-field":""'], - "children": [ - { - "name": '"label"', - "props": ["className:sx_3f1c4be050_c", 'htmlFor:"email"'], - "children": [{"contents": '"Email"'}], - }, - { - "name": '"div"', - "props": ["className:sx_ff3fb9d45c_c"], - "children": [ - { - "name": '"input"', - "props": [ + [ + ( + "Field", + ["className:sx_7fb5ccb001_c", 'name:"email"'], + [ + ( + '"label"', + ["className:sx_3f1c4be050_c", 'htmlFor:"email"'], + ['"Email"'], + ), + ( + '"div"', + ["className:sx_ff3fb9d45c_c"], + [ + ( + '"input"', + [ "className:sx_345c25de08_c", '"data-rx-text-field-input":""', 'id:"email"', @@ -87,58 +97,24 @@ def test_form_parts( "spellCheck:false", 'type:"email"', ], - "children": [], - } - ], - }, - { - "name": '"span"', - "props": [ - "className:sx_71d77c9098_c", - '"data-match":"valueMissing"', - '"data-rx-form-message":""', - "hidden:true", - ], - "children": [{"contents": '"Needed"'}], - }, - { - "name": '"span"', - "props": [ - "className:sx_71d77c9098_c", - '"data-rx-form-message":""', - ], - "children": [{"contents": '"Always"'}], - }, - { - "name": '"span"', - "props": [ - "className:sx_71d77c9098_c", - '"data-force":""', - '"data-match":"typeMismatch"', - '"data-rx-form-message":""', + [], + ) ], - "children": [{"contents": '"Forced"'}], - }, - ], - }, - { - "name": '"span"', - "props": [ - "className:sx_71d77c9098_c", - '"data-match":"valueMissing"', - '"data-name":"email"', - '"data-rx-form-message":""', - "hidden:true", + ), + ( + "FieldError", + [MESSAGE, 'match:"valueMissing"'], + ['"Needed"'], + ), + ('"span"', [MESSAGE], ['"Always"']), + ("FieldError", [MESSAGE, "match:true"], ['"Forced"']), ], - "children": [{"contents": '"Outside"'}], - }, - { - "name": '"button"', - "props": ['type:"submit"'], - "children": [{"contents": '"Send"'}], - }, + ), + # UI SDK shows an error outside a field only when it is forced. + ("FieldError", [MESSAGE, 'match:"valueMissing"'], ['"Outside"']), + ('"button"', ['type:"submit"'], ['"Send"']), ], - } + ) assert declared_styles(component) == [ {"width": "100%"}, {"display": "grid", "marginBottom": "10px"}, @@ -341,7 +317,7 @@ def test_form_parts( def test_form_server_errors( ui_plugin: UIPlugin, ): - """A field the server finds invalid says so on itself and on its control, shows the messages it forces, and its errors are cleared on a submit and on a reset.""" + """A field the server finds invalid says so to UI SDK and on its control, gives the focus to it, shows the messages it forces, and its errors are cleared on a submit and on a reset.""" component = rx.ui.form.root( rx.ui.form.field( rx.ui.form.control(rx.el.input(name="mine", id="code")), @@ -352,59 +328,55 @@ def test_form_server_errors( on_submit=FormState.submit, on_clear_server_errors=FormState.clear, ) - assert component.render() == { - "name": '"form"', - "props": [ + name = FormState.get_full_name() + taken = f"{FormState.taken!s}" + clear = ( + "((event) => { (((...args) => (addEvents([(ReflexEvent(" + f'"{name}.clear", ({{ }}), ({{ }})))], args, ({{ }})))))(event); }})' + ) + assert tree(component.render()) == ( + '"form"', + [ "className:sx_5073704993_c", - "onBlurCapture:((event) => { left(event); })", - "onChangeCapture:((event) => { changed(event); })", - "onInvalid:((event) => { invalid(event); })", - 'onReset:((event) => { cleared(event); (((...args) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_form____form_state.clear", ({ }), ({ })))], args, ({ })))))(event); })', - "onSubmit:handleSubmit_21b393bf90a9dc94271acff60be1dacc", - 'onSubmitCapture:((event) => { (((...args) => (addEvents([(ReflexEvent("reflex___state____state.tests___units___reflex_components_ui___components___test_form____form_state.clear", ({ }), ({ })))], args, ({ })))))(event); })', + f"onReset:{clear}", + "onSubmit:handleSubmit_d0cc17a26357c93f98ce435bb75ef574", + f"onSubmitCapture:{clear}", ], - "children": [ - { - "name": '"div"', - "props": [ + [ + ( + "Field", + [ "className:sx_7fb5ccb001_c", - '"data-invalid":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? "" : undefined)', - '"data-rx-form-field":""', - '"data-server-invalid":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? "" : undefined)', - "ref:(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? focusInvalid : undefined)", + f"invalid:({taken} || undefined)", + 'name:"code"', + f"ref:({taken} ? {FOCUS_INVALID} : undefined)", ], - "children": [ - { - "name": '"input"', - "props": [ - '"aria-invalid":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ || undefined)', + [ + ( + '"input"', + [ + f'"aria-invalid":({taken} || undefined)', 'id:"code"', 'name:"mine"', "ref:ref_code", ], - "children": [], - }, - { - "name": '"span"', - "props": [ - "className:sx_71d77c9098_c", - '"data-force":(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_ ? "" : undefined)', - '"data-match":"valid"', - '"data-rx-form-message":""', - "hidden:!(reflex___state____state__tests___units___reflex_components_ui___components___test_form____form_state.taken_rx_state_)", - ], - "children": [{"contents": '"Taken"'}], - }, + [], + ), + ( + "FieldError", + [MESSAGE, f'match:({taken} ? true : "valid")'], + ['"Taken"'], + ), ], - } + ) ], - } + ) def test_form_without_messages( ui_plugin: UIPlugin, ): - """A form without a message is the form element of Reflex, with no script of its own.""" + """A form is the form element of Reflex, and its fields UI SDK's.""" component = rx.ui.form( rx.ui.form.field( rx.ui.form.label("Notes"), @@ -422,8 +394,8 @@ def test_form_without_messages( ], "children": [ { - "name": '"div"', - "props": ["className:sx_7fb5ccb001_c", '"data-rx-form-field":""'], + "name": "Field", + "props": ["className:sx_7fb5ccb001_c", 'name:"notes"'], "children": [ { "name": '"label"', @@ -489,39 +461,63 @@ def test_form_message_unknown_match(ui_plugin: UIPlugin): ) -def test_form_field_gives_its_control_an_id( +def test_form_field_names_its_control( ui_plugin: UIPlugin, monkeypatch: pytest.MonkeyPatch ): - """A control without an id is given one for the label of its field.""" + """A field names its control unless the control has a name, gives it an id its label points at in the page the server sends, and a field the server finds invalid is invalid to UI SDK.""" monkeypatch.setattr(form_module, "_ids", itertools.count(4)) field = rx.ui.form.field( - rx.ui.form.label("Age"), rx.ui.form.control(name="years"), name="age" + rx.ui.form.label("Age"), + rx.ui.form.control(name="years"), + name="age", + server_invalid=True, + ) + assert tree(field.render()) == ( + "Field", + [ + "className:sx_7fb5ccb001_c", + "invalid:true", + 'name:"age"', + f"ref:{FOCUS_INVALID}", + ], + [ + ( + '"label"', + ["className:sx_3f1c4be050_c", 'htmlFor:"rx-form-field-4"'], + ['"Age"'], + ), + ( + "FieldControl", + [ + '"aria-invalid":(true || undefined)', + 'id:"rx-form-field-4"', + 'name:"years"', + ], + [], + ), + ], ) - assert field.render()["children"] == [ - { - "name": '"label"', - "props": ["className:sx_3f1c4be050_c", 'htmlFor:"rx-form-field-4"'], - "children": [{"contents": '"Age"'}], - }, - { - "name": '"input"', - "props": ['id:"rx-form-field-4"', 'name:"years"'], - "children": [], - }, - ] -def test_form_script_is_only_for_messages(ui_plugin: UIPlugin): - """The script of a form reads validity for its messages, and nothing else.""" - script = "$/reflex-ui/behaviors/form-validity.js" - plain = rx.ui.form(rx.ui.form.field(rx.ui.form.control(), name="a")) - assert script not in plain._get_all_imports() - with_message = rx.ui.form(rx.ui.form.message("x", match="valueMissing")) - assert with_message._get_all_imports()[script] == [ - ImportVar(tag="invalid"), - ImportVar(tag="changed"), - ImportVar(tag="left"), - ImportVar(tag="cleared"), - ] - invalid = rx.ui.form.field(rx.ui.form.control(), server_invalid=True) - assert invalid._get_all_imports()[script] == [ImportVar(tag="focusInvalid")] +def test_form_imports_ui_sdk(ui_plugin: UIPlugin): + """A form with fields imports their parts from UI SDK, pinned, and no script.""" + form = rx.ui.form( + rx.ui.form.field( + rx.ui.form.label("A"), + rx.ui.form.control(), + rx.ui.form.message("x", match="valueMissing"), + name="a", + ) + ) + assert { + module: names + for module, names in form._get_all_imports().items() + if "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/field": [ + ImportVar(tag="Field"), + ImportVar(tag="FieldControl"), + ImportVar(tag="FieldError"), + ], + } diff --git a/tests/units/reflex_components_ui/components/test_text_field.py b/tests/units/reflex_components_ui/components/test_text_field.py index f89cc3d38d1..c1b67dea926 100644 --- a/tests/units/reflex_components_ui/components/test_text_field.py +++ b/tests/units/reflex_components_ui/components/test_text_field.py @@ -267,7 +267,7 @@ def test_text_field_with_slots( ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]], ): - """A slot is on the side it names; the first without one is on the left and the next on the right, and a pointer on either gives the input the focus.""" + """A slot is on the side it names; the first without one is on the left and the next on the right, and the box is UI SDK's input group, which gives the input the focus from them.""" component = rx.ui.input( rx.ui.input.slot("a"), rx.ui.input.slot("b"), @@ -279,10 +279,9 @@ def test_text_field_with_slots( type="date", ) assert component.render() == { - "name": '"div"', + "name": "InputGroup", "props": [ 'className:sx_59632c79fd_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', - "onPointerDown:focusField", ], "children": [ { @@ -625,13 +624,21 @@ def test_text_field_unknown_slot_side(ui_plugin: UIPlugin): ) -def test_text_field_script_is_only_for_slots(ui_plugin: UIPlugin): - """The one script of a text field gives its input the focus from a slot.""" - script = "$/reflex-ui/behaviors/text-field.js" - assert script not in rx.ui.input(placeholder="a")._get_all_imports() - assert rx.ui.input(rx.ui.input.slot("a"))._get_all_imports()[script] == [ - ImportVar(tag="focusField") - ] +def test_text_field_imports_ui_sdk_only_for_slots(ui_plugin: UIPlugin): + """A text field with slots imports the input group of UI SDK, pinned; one without has no JavaScript of its own.""" + + def ui_sdk(component: Any) -> dict[str, Any]: + return { + module: names + for module, names in component._get_all_imports().items() + if "ui-sdk" in module or "behaviors" in module + } + + assert ui_sdk(rx.ui.input(placeholder="a")) == {} + assert ui_sdk(rx.ui.input(rx.ui.input.slot("a"))) == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + "@ui-sdk/react@0.1.0-beta.17/input": [ImportVar(tag="InputGroup")], + } assert "react-debounce-input@3.3.0" not in rx.ui.input()._get_all_imports() From 851ac2596e735b7e198af9d12ed943ecf74ecbc9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 18:32:04 +0000 Subject: [PATCH 200/204] rx.ui on UI SDK: docs, news, README and budgets The README says how a component is made of the parts of UI SDK; the docs and the migration guide say what renders what, with the sizes of the kitchen sink measured again. One breaking news fragment says behaviour comes from UI SDK pinned at 0.1.0-beta.17 and what a user may notice, and the fragments of the waves no longer describe the scripts it replaced. The size budgets of the kitchen sink are the measured values + 5 %. The reasons of the allowlist that still described native elements say what UI SDK does. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v --- docs/library/data-display/avatar-ui.md | 3 +- docs/library/disclosure/accordion-ui.md | 10 +- docs/library/forms/form-ui.md | 2 +- docs/library/forms/select-ui.md | 8 +- docs/library/forms/slider-ui.md | 4 +- docs/library/overlay/alert_dialog-ui.md | 2 +- docs/library/overlay/context_menu-ui.md | 2 +- docs/library/overlay/dialog-ui.md | 7 +- docs/library/overlay/drawer-ui.md | 2 +- docs/library/overlay/dropdown_menu-ui.md | 2 +- docs/library/overlay/hover_card-ui.md | 2 +- docs/library/overlay/popover-ui.md | 2 +- docs/library/overlay/tooltip-ui.md | 2 +- docs/rx_ui/overview.md | 17 +- docs/styling/rx-ui-migration.md | 29 +- packages/reflex-bench/budgets.json | 12 +- packages/reflex-components-ui/README.md | 264 ++++++------------ .../reflex-components-ui/js/src/README.md | 7 +- .../news/+drawer-firefox-safari.bugfix.md | 2 +- .../news/+react-warnings.bugfix.md | 2 +- .../news/+ui-sdk-pilot.feature.md | 1 - .../news/+ui-sdk.breaking.md | 3 + .../news/+wave3-form-controls.feature.md | 4 +- .../news/+wave4-overlays.feature.md | 14 +- .../parity/allowlist.toml | 6 +- 25 files changed, 158 insertions(+), 251 deletions(-) delete mode 100644 packages/reflex-components-ui/news/+ui-sdk-pilot.feature.md create mode 100644 packages/reflex-components-ui/news/+ui-sdk.breaking.md diff --git a/docs/library/data-display/avatar-ui.md b/docs/library/data-display/avatar-ui.md index 8083a748bbe..2e0da6c0db6 100644 --- a/docs/library/data-display/avatar-ui.md +++ b/docs/library/data-display/avatar-ui.md @@ -26,8 +26,7 @@ rx.ui.flex( ``` The fallback is in the page the server sends and shows until the image has -loaded, with or without JavaScript. `rx.avatar` renders both once JavaScript -has run. +loaded. `rx.avatar` renders both once JavaScript has run. ## Sizes diff --git a/docs/library/disclosure/accordion-ui.md b/docs/library/disclosure/accordion-ui.md index d608f9c1a5f..7b0549a068b 100644 --- a/docs/library/disclosure/accordion-ui.md +++ b/docs/library/disclosure/accordion-ui.md @@ -9,12 +9,12 @@ import reflex as rx # Accordion -`rx.ui.accordion` takes the props of `rx.accordion` and renders native `details` elements, one per item, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.accordion` takes the props of `rx.accordion` and renders the parts of a UI SDK accordion, one item per value, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example -Each item is a native `details` element, so it opens and closes with or -without JavaScript. +Each header is a heading around a button that opens and closes its item; +the panel of an item is in the page while it is open. ```python demo rx.ui.accordion.root( @@ -79,5 +79,5 @@ def ui_controlled_accordion(): ) ``` -Tab and Shift+Tab move between the headers, as between any `details` -elements; the arrow keys do not. +Tab and Shift+Tab move between the headers, and Tab passes the header of a +disabled item; the arrow keys do not move between them. diff --git a/docs/library/forms/form-ui.md b/docs/library/forms/form-ui.md index c5777ac4092..1f7c32cb05a 100644 --- a/docs/library/forms/form-ui.md +++ b/docs/library/forms/form-ui.md @@ -14,7 +14,7 @@ import reflex as rx # Form -`rx.ui.form` takes the props of `rx.form` and renders a `form` element whose fields validate natively whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.form` takes the props of `rx.form` and renders a `form` element whose fields are UI SDK's, which show the validity the browser computes, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example diff --git a/docs/library/forms/select-ui.md b/docs/library/forms/select-ui.md index b4a8ac98b25..5d9a2a4ec34 100644 --- a/docs/library/forms/select-ui.md +++ b/docs/library/forms/select-ui.md @@ -15,7 +15,7 @@ import reflex as rx # Select -`rx.ui.select` takes the props of `rx.select` and renders a button and a list of options in a native popover whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.select` takes the props of `rx.select` and renders the parts of a UI SDK select, a button and a list of options, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example @@ -64,6 +64,6 @@ rx.ui.select.root( ) ``` -The list is a native popover, so the page behind it stays interactive, and a -long list scrolls natively. `position="item-aligned"` places it as -`"popper"` does, and the trigger shows the chosen option's text. +The page behind an open list stays interactive, a long list scrolls, and +the trigger shows the chosen option's text. `position="item-aligned"` puts +the chosen option over the trigger. diff --git a/docs/library/forms/slider-ui.md b/docs/library/forms/slider-ui.md index 89c2cc3a6b5..5af1a3fda88 100644 --- a/docs/library/forms/slider-ui.md +++ b/docs/library/forms/slider-ui.md @@ -8,7 +8,7 @@ import reflex as rx # Slider -`rx.ui.slider` takes the props of `rx.slider` and renders native range `input`s, one per thumb whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.slider` takes the props of `rx.slider` and renders the parts of a UI SDK slider, a thumb per value, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example @@ -41,7 +41,7 @@ rx.ui.slider(default_value=[25, 75], style={"width": "100%"}) ``` The thumbs of a range stop at their neighbours, and Shift with an arrow key -moves a thumb by one step. +moves a thumb by ten steps. ## Sizes and Variants diff --git a/docs/library/overlay/alert_dialog-ui.md b/docs/library/overlay/alert_dialog-ui.md index b2fa6274891..d4a0ac3f75f 100644 --- a/docs/library/overlay/alert_dialog-ui.md +++ b/docs/library/overlay/alert_dialog-ui.md @@ -14,7 +14,7 @@ import reflex as rx # Alert Dialog -`rx.ui.alert_dialog` takes the props of `rx.alert_dialog` and renders a native modal `dialog` that asks for a decision whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.alert_dialog` takes the props of `rx.alert_dialog` and renders the parts of a UI SDK alert dialog, which asks for a decision, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example diff --git a/docs/library/overlay/context_menu-ui.md b/docs/library/overlay/context_menu-ui.md index ee4ab3b3a01..8aadcea4ec0 100644 --- a/docs/library/overlay/context_menu-ui.md +++ b/docs/library/overlay/context_menu-ui.md @@ -20,7 +20,7 @@ import reflex as rx # Context Menu -`rx.ui.context_menu` takes the props of `rx.context_menu` and renders a menu in a native popover that opens at the pointer on a right click whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.context_menu` takes the props of `rx.context_menu` and renders the parts of a UI SDK menu, which opens at the pointer on a right click, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example diff --git a/docs/library/overlay/dialog-ui.md b/docs/library/overlay/dialog-ui.md index b5d2649b797..69ffebac9d1 100644 --- a/docs/library/overlay/dialog-ui.md +++ b/docs/library/overlay/dialog-ui.md @@ -13,7 +13,7 @@ import reflex as rx # Dialog -`rx.ui.dialog` takes the props of `rx.dialog` and renders a native modal `dialog` element whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.dialog` takes the props of `rx.dialog` and renders the parts of a UI SDK dialog whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example @@ -36,9 +36,8 @@ rx.ui.dialog.root( ) ``` -The trigger and close buttons command the native dialog, so a browser with -invoker commands opens and closes it with or without JavaScript. The browser -makes the page behind an open dialog inert. +An open dialog makes the page behind it inert and keeps the focus inside; +Escape and a press outside close it. ## Controlled diff --git a/docs/library/overlay/drawer-ui.md b/docs/library/overlay/drawer-ui.md index 94a07078386..35ec995a543 100644 --- a/docs/library/overlay/drawer-ui.md +++ b/docs/library/overlay/drawer-ui.md @@ -16,7 +16,7 @@ import reflex as rx # Drawer -`rx.ui.drawer` takes the props of `rx.drawer` and renders a native modal `dialog` that slides in from an edge whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.drawer` takes the props of `rx.drawer` and renders the parts of a UI SDK drawer, which slides in from an edge, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example diff --git a/docs/library/overlay/dropdown_menu-ui.md b/docs/library/overlay/dropdown_menu-ui.md index 43bbe673b36..0e1a419745a 100644 --- a/docs/library/overlay/dropdown_menu-ui.md +++ b/docs/library/overlay/dropdown_menu-ui.md @@ -15,7 +15,7 @@ import reflex as rx # Dropdown Menu -`rx.ui.dropdown_menu` takes the props of `rx.dropdown_menu` and renders a menu in a native popover whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. `rx.ui.menu` is the same namespace. +`rx.ui.dropdown_menu` takes the props of `rx.dropdown_menu` and renders the parts of a UI SDK menu whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. `rx.ui.menu` is the same namespace. ## Basic Example diff --git a/docs/library/overlay/hover_card-ui.md b/docs/library/overlay/hover_card-ui.md index 6a7f0bd0dc2..ad7383c8aea 100644 --- a/docs/library/overlay/hover_card-ui.md +++ b/docs/library/overlay/hover_card-ui.md @@ -10,7 +10,7 @@ import reflex as rx # Hover Card -`rx.ui.hover_card` takes the props of `rx.hover_card` and renders a native popover that opens while its trigger is hovered or focused whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.hover_card` takes the props of `rx.hover_card` and renders the parts of a UI SDK hover card, which opens while its trigger is hovered or focused, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example diff --git a/docs/library/overlay/popover-ui.md b/docs/library/overlay/popover-ui.md index 36a65833445..9c0495ca5a8 100644 --- a/docs/library/overlay/popover-ui.md +++ b/docs/library/overlay/popover-ui.md @@ -11,7 +11,7 @@ import reflex as rx # Popover -`rx.ui.popover` takes the props of `rx.popover` and renders a native popover anchored to its trigger whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.popover` takes the props of `rx.popover` and renders the parts of a UI SDK popover, placed beside its trigger, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example diff --git a/docs/library/overlay/tooltip-ui.md b/docs/library/overlay/tooltip-ui.md index 7b350992d53..a39296099fd 100644 --- a/docs/library/overlay/tooltip-ui.md +++ b/docs/library/overlay/tooltip-ui.md @@ -8,7 +8,7 @@ import reflex as rx # Tooltip -`rx.ui.tooltip` takes the props of `rx.tooltip` and renders a native popover that names its trigger while it is hovered or focused whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. +`rx.ui.tooltip` takes the props of `rx.tooltip` and renders the parts of a UI SDK tooltip, which describes its trigger and shows while it is hovered or focused, whose styles are compiled at build time. The **rx** tab documents the props in depth; [rx.ui](/rx-ui/overview/) covers installing the package. ## Basic Example diff --git a/docs/rx_ui/overview.md b/docs/rx_ui/overview.md index bdf5c5684f2..f29135c5bf7 100644 --- a/docs/rx_ui/overview.md +++ b/docs/rx_ui/overview.md @@ -1,6 +1,6 @@ --- title: "rx.ui: Compiled Components" -meta_description: "rx.ui components take the props of the Radix-backed rx components and compile to plain HTML elements with static CSS. Install the ui extra and add UIPlugin." +meta_description: "rx.ui components take the props of the Radix-backed rx components and compile their styles to static CSS, with behaviour from UI SDK. Install the ui extra and add UIPlugin." --- ```python exec @@ -11,10 +11,11 @@ from reflex_docs.pages.docs import ui_library_pages # rx.ui `rx.ui` is a set of components that take the same props as the Radix-backed -`rx` components and render plain HTML elements. Their styles are compiled to -static CSS by [StyleX](https://stylexjs.com) in your app's own build, and their -behaviour comes from the browser and a few small scripts, so no component -library is shipped to the browser. +`rx` components. Their styles are compiled to static CSS by +[StyleX](https://stylexjs.com) in your app's own build. A component with +behaviour, such as a menu, a dialog or a select, renders the parts of +[UI SDK](https://ui-sdk.dev), pinned to one version; the others render plain +HTML elements with no JavaScript of their own. Moving a component is an import change: @@ -80,9 +81,9 @@ ModuleNotFoundError: `rx.ui` requires the reflex-components-ui package, which is gzipped CSS for the theme's accent and gray, and 0.6 kB of gzipped JavaScript in the chunk every page already loads. StyleX and its Vite plugin run only during the build. -- **Each component** adds only its own compiled classes. A component that - needs a script, such as a select or a dialog, adds a small one to the pages - that use it, and a page without it does not load it. +- **Each component** adds only its own compiled classes. A component with + behaviour adds the parts of UI SDK it renders to the pages that use it, and + a page without one does not load UI SDK. ## Using Both diff --git a/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md index c2fc6150489..8c414e2ad5b 100644 --- a/docs/styling/rx-ui-migration.md +++ b/docs/styling/rx-ui-migration.md @@ -1,10 +1,11 @@ # Migrating to rx.ui `rx.ui` has the components of `rx` that are built on Radix Themes, with the -same props, compiled to plain HTML elements and a static stylesheet. No -component library ships to the browser, and most controls work before -JavaScript has run. Moving an app is one command, plus the short list of items -the command reports. +same props and a static stylesheet compiled in the app's own build. A +component with behaviour, such as a menu, a dialog or a select, renders the +parts of [UI SDK](https://ui-sdk.dev); the others are plain HTML elements, and +the form controls among them work before JavaScript has run. Moving an app is +one command, plus the short list of items the command reports. ## What changes @@ -100,9 +101,9 @@ app and of its state. | | `rx` | `rx.ui` | | --- | --- | --- | -| JavaScript, gzipped | 240.7 kB | 171.1 kB | -| CSS, gzipped | 82.4 kB | 24.1 kB | -| Everything the page loads, gzipped | 335.6 kB | 216.7 kB | +| JavaScript, gzipped | 240.7 kB | 269.2 kB | +| CSS, gzipped | 82.4 kB | 22.7 kB | +| Everything the page loads, gzipped | 335.6 kB | 308.5 kB | | Scripts that contain Emotion | 4 | 0 | | Lighthouse mobile score, simulated throttling | 0.97 | 1.00 | | Largest contentful paint, simulated | 1.21 s | 0.91 s | @@ -112,8 +113,12 @@ app and of its state. | Total blocking time, DevTools | 487 ms | 64 ms | | Layout shift | 0 | 0 | -The sizes are of one production build each, the Lighthouse figures the median -of five audits on a shared 4-core virtual machine. +The sizes are of one production build each. The page of `rx.ui` loads more +JavaScript than the one of `rx`, the parts of UI SDK its menus, dialogs, +select and other components with behaviour render, and far less CSS. The +Lighthouse figures, the median of five audits on a shared 4-core virtual +machine, were taken before the behaviour of `rx.ui` moved to UI SDK, when its +page loaded 171.1 kB of JavaScript. The page looks the same except where the `rx` page does not do what its code asks, which `rx.ui` does: @@ -141,7 +146,7 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### accordion - behaviour, `rx.ui`, "opens and closes an item with JavaScript disabled": rx.accordion and rx.ui.accordion are opened by JavaScript: until the page has hydrated, a press on a header does nothing. -- behaviour, `rx.ui`, "the arrow keys, Home and End move between the headers": The headers of rx.ui.accordion are native `summary` elements: Tab and Shift+Tab move between them, as between the headers of any `details`, and Enter and Space open and close an item. rx.accordion also moves between its headers with the arrow keys, Home and End, and `orientation` says which arrow keys do. +- behaviour, `rx.ui`, "the arrow keys, Home and End move between the headers": Tab and Shift+Tab move between the headers of rx.ui.accordion, and Enter and Space open and close an item: UI SDK gives the headers no arrow keys, which the accordion pattern of ARIA leaves optional. rx.accordion also moves between its headers with the arrow keys, Home and End, and `orientation` says which arrow keys do. - behaviour, `rx`, "opens and closes an item with JavaScript disabled": rx.accordion and rx.ui.accordion are opened by JavaScript: until the page has hydrated, a press on a header does nothing. ### alert_dialog @@ -314,10 +319,10 @@ counterpart, kept in sync with the parity checks of `rx.ui`: ### slider -- behaviour, `rx`, "moves with the keyboard with JavaScript disabled": rx.slider is drawn and moved by JavaScript: until it has run, its thumb takes no focus and no key. The thumbs of rx.ui.slider are native range inputs, which the keyboard and the pointer move with or without JavaScript; only the filled part of the track waits for it. +- behaviour, `rx`, "moves with the keyboard with JavaScript disabled": rx.slider is drawn and moved by JavaScript: until it has run, its thumb takes no focus and no key. A thumb of rx.ui.slider holds a native range input, which the keyboard moves with or without JavaScript; the thumb and the filled part of the track follow it once the page has hydrated. - behaviour, `rx`, "the thumb of a slider has the name the slider is given": An `aria_label` of rx.slider names the element around its thumb, so the thumb, which is what a screen reader lands on, has no name. rx.ui.slider gives the label to the thumb. - behaviour, `rx.ui`, "a thumb can be moved past the one after it": A thumb of rx.ui.slider stops at the thumbs beside it, where a thumb of rx.slider passes them and the two change places. Home and End move the thumb that has the focus, where rx.slider moves the first and the last whichever has it. -- a11y, *: A thumb of rx.ui.slider is a native range input, which says its value to the accessibility tree as every such input does. A thumb of rx.slider has its value in `aria-valuenow` alone. +- a11y, *: A thumb of rx.ui.slider holds a native range input, which says its value to the accessibility tree as every such input does. A thumb of rx.slider has its value in `aria-valuenow` alone. - style, `width`: UI SDK gives the filled part of the track of rx.ui.slider a width, a share of the track, where rx.slider sets where it ends; the browser rounds the two to a 64th of a pixel apart, so the fill of rx.ui.slider may end a 64th of a pixel sooner. - pixels, *size-1*: UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. A thumb of size 1 is drawn 13 pixels wide, an odd number, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise. - pixels, *size-3*: UI SDK centers a thumb of rx.ui.slider on its value with margins, where rx.slider moves its thumb by half its width. A thumb of size 3 is drawn 19 pixels wide, an odd number, and the two land half a pixel apart: the edge of the thumb is anti-aliased otherwise. diff --git a/packages/reflex-bench/budgets.json b/packages/reflex-bench/budgets.json index a7360a7b713..4f1f7708983 100644 --- a/packages/reflex-bench/budgets.json +++ b/packages/reflex-bench/budgets.json @@ -74,14 +74,14 @@ }, "size.export[app=kitchen_sink_ui]": { "css_gzip": { - "max": 25300, - "measured": 24094, - "note": "Missed the 20,000 of the plan for 54 components in one accent: the theme with the accent and its gray is about 5 kB, the components' rules the rest. Corrected to the measured value + 5 %." + "max": 23800, + "measured": 22649, + "note": "rx.ui on UI SDK, PR #8037: the measured value + 5 %." }, "js_gzip": { - "max": 179600, - "measured": 171008, - "note": "The measured value + 5 %." + "max": 282700, + "measured": 269221, + "note": "rx.ui on UI SDK, PR #8037: the measured value + 5 %. The parts of @ui-sdk/react and @ui-sdk/core its components with behaviour render; it was 171,008 with the scripts they replaced." }, "emotion_files": { "max": 0, diff --git a/packages/reflex-components-ui/README.md b/packages/reflex-components-ui/README.md index 9570783cc69..3655ea11bbf 100644 --- a/packages/reflex-components-ui/README.md +++ b/packages/reflex-components-ui/README.md @@ -43,7 +43,7 @@ js/ the javascript package, with its own tooling 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 - behaviors/ the little a component needs a script for + behaviors/ the theme panel's app script colors/ generated: one module for each Radix color scale tokens/ generated: space, radius, typography, shadow, ... themes/ generated: accent/, gray/, radius, scaling, ... @@ -378,7 +378,9 @@ What a wave does for each component, in this order. `flex` (a layout), `text` class deriving from `UIComponent` and the element class the Radix wrapper derives from, with `tag`, `styles` and the same fields, copied with their `field(doc=...)` so that the documentation and the stubs stay complete. - Keep `create` as it is there. A second element is a `Part`. + Keep `create` as it is there. A second element is a `Part`. A component + with behaviour is made of the parts of UI SDK, each an `SDKPart` (see + [Behaviour: the parts of UI SDK](#behaviour-the-parts-of-ui-sdk)). 4. **The name**: an entry of `_SUBMOD_ATTRS` in `__init__.py`, a namespace (`rx.ui.text`, `rx.ui.list`) under the name `rx` has it. 5. **Unit tests**, `tests/units/reflex_components_ui//test_.py`: @@ -433,14 +435,11 @@ What the display and action wave settled, for the waves after it: progress bar rather than a ``: a plain element costs no script either, and the pseudo-elements a native bar is drawn with differ by engine, of which only Chromium could be looked at when it was written. -- **A script is the last resort, and is a function, not a component.** - `js/src/behaviors/.js` exports plain functions with JSDoc types and a - vitest file under `js/tests/behaviors/`. A component reaches one through a - `Var` that carries its import, such as the `ref` of the image of an - avatar: no hook, no state, nothing rendered again, and a page without the - component does not load it. Render both states on the server and let the - script say which one holds (`data-status`), so that the page is right - before it runs, and say in the contract what shows with JavaScript off. +- **Behaviour is UI SDK's.** A component with behaviour is made of the + parts of UI SDK (see + [Behaviour: the parts of UI SDK](#behaviour-the-parts-of-ui-sdk)); the + page sends what UI SDK renders on the server, and the contract says what + shows with JavaScript off. - **What a class cannot say of the children of an element** is a rule of `base.css`, on an attribute the wrapper renders: `[data-rx-callout] > *` puts everything in a callout in its last column, `[data-rx-skeleton] > *` @@ -461,186 +460,84 @@ What the display and action wave settled, for the waves after it: styles in the order they are written, and a whole shorthand written after its longhands cancels them. Write each side out, as the ghost button does. -### Behaviour: the browser first, a script for the gap - -What a component does is the contract of its Radix counterpart, kept with -as little JavaScript as the browser allows. In this order: - -1. **An element that already does it.** A checkbox, a radio button, a - switch and a thumb of a slider are native inputs, drawn by their table - with `appearance: none` and their `::before` and `::after`; an item with - text is a `