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/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/integration_tests.yml b/.github/workflows/integration_tests.yml index 23ddd7ef686..741f49f9dd7 100644 --- a/.github/workflows/integration_tests.yml +++ b/.github/workflows/integration_tests.yml @@ -349,7 +349,125 @@ 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. 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 + 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 + 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 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, shard $UI_PARITY_SHARD" + echo '```json' + cat "$UI_PARITY_REPORT/timings.json" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + fi + - name: Upload the shard's report + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + 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: + 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 +531,9 @@ jobs: reflex-docs-macos, app-harness, app-harness-playwright, + ui-parity, + ui-parity-report, + ui-contracts, bun-only-startup, ] if: always() 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/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 27e27303b6a..004885ccfad 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -191,6 +191,34 @@ 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 + # 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: timeout-minutes: 30 if: github.event_name == 'push' && github.ref == 'refs/heads/main' @@ -224,7 +252,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..31c877ef4e6 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ examples/* !examples/README.md !examples/ruff.toml !examples/playground/ +!examples/pages/ .web .states .idea @@ -32,8 +33,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/.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/AGENTS.md b/AGENTS.md index 9bc22def8d8..2dbd53f2dca 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 +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/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/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/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.lock/package.json b/docs/app/reflex.lock/package.json index 13c11a45d4e..2fd72da0b12 100644 --- a/docs/app/reflex.lock/package.json +++ b/docs/app/reflex.lock/package.json @@ -93,4 +93,4 @@ "vite": "8.3.4" }, "overrides": {} -} \ No newline at end of file +} diff --git a/docs/app/reflex_docs/pages/docs/__init__.py b/docs/app/reflex_docs/pages/docs/__init__.py index 8f716489682..8b7b810638b 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) @@ -427,10 +464,23 @@ 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_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 prose of its own; a Low Level page shares the + # 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) else: @@ -457,6 +507,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 +520,8 @@ def handle_library_doc( previews=previews, component_list=clist, title=display_title, - ll_component_list=ll_clist, + variant_component_lists=variant_component_lists, + variant_descriptions=variant_descriptions, description=description, image=image, source=source, @@ -543,15 +600,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..bc650acbd96 100644 --- a/docs/app/reflex_docs/pages/docs/component.py +++ b/docs/app/reflex_docs/pages/docs/component.py @@ -21,7 +21,11 @@ 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, @@ -33,6 +37,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 +82,10 @@ 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. The +# rx.ui components share the props of these and list them in a compact table. +INTERACTIVE_BASES = (RadixThemesComponent, RadixPrimitiveComponent) + EXCLUDED_COMPONENTS = [ "Theme", "ThemePanel", @@ -150,7 +159,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 +549,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 @@ -1054,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. @@ -1076,121 +1162,186 @@ def api_reference_toc(names: Sequence[str], has_shared: bool) -> list[tuple[int, ] -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, - ll_component_list: list | None = None, - source: str | None = None, -): - 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:] - ] +# 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 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" +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" - 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"), +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.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", + rx.text(label), + class_name=active_class_name + if segment == current + else non_active_class_name, ), - 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", + underline="none", + class_name=link_class_name, + **( + {"aria_current": "page"} + if segment == current + else {"href": f"{path}/{segment + '/' if segment else ''}"} ), - class_name="flex mb-2", ) - return rx.fragment() + 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", + ) - @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:]]), + +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), ) - def out(): + + +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, + 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``. + """ + 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) - # 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 +1355,113 @@ 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 - @docpage( - set_path=path.rstrip("/") + "/low/", - t=title + " (Low Level)", - description=ll_description, + +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_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. + + 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_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_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, + 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..dfadfac83c2 --- /dev/null +++ b/docs/app/reflex_docs/pages/docs/ui_differences.py @@ -0,0 +1,163 @@ +"""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 = "*" + +# The harness's names of components that a page documents under another name. +DOCUMENTED_AS = {"text_field": "input"} + + +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 separated by commas, each in backticks unless it is a + description such as "length without a unit". + """ + return ", ".join(name if " " in name else 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. A component a page + documents under another name is filed under that name. + """ + 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, ()): + component = entry["component"] + items[DOCUMENTED_AS.get(component, 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..2eb54923c45 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, @@ -93,6 +94,15 @@ def get_sidebar_items_frontend(): styling.layout, styling.common_props, styling.tailwind, + styling.rx_ui_migration, + ], + ), + create_item( + "rx.ui", + children=[ + rx_ui.overview, + rx_ui.styling, + rx_ui.theming, ], ), create_item( 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/frontend_quality.test.mjs b/docs/app/tests/frontend_quality.test.mjs index 97adad37035..077df1d7b83 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", "utils_refs", "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); 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..408c37af95f --- /dev/null +++ b/docs/app/tests/test_ui_pages.py @@ -0,0 +1,296 @@ +"""The rx.ui pages of the component library and the differences they list.""" + +import importlib +from pathlib import Path +from typing import Literal + +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 ( + EVERY_COMPONENT, + differences_by_component, + 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 = "*" +kind = "style" +names = ["length without a unit"] +reason = "Units." + +[[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." + +[[contract]] +component = "text_field" +step = "focuses from a slot" +reason = "Caret." +""" + + +@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_of_a_component_reach_the_page_of_its_other_name(allowlist): + """The harness's ``text_field`` is documented on the page of ``rx.ui.input``.""" + assert differences_markdown(["rx.ui.input", "rx.ui.input.slot"], allowlist) == ( + "- **Behaviour**, *focuses from a slot*: `rx.ui` does not. Caret." + ) + + +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.\n" + "- **Style keywords** length without a unit: Units." + ) + + +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 = set(differences_by_component()) - {EVERY_COMPONENT} + assert { + component + for component in components + if not any( + name == component or name.startswith(component + ".") for name in documented + ) + } == 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 + + 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 + } + 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 - set(UI_ALIASES) == { + "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 + + +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 new file mode 100644 index 00000000000..2e0da6c0db6 --- /dev/null +++ b/docs/library/data-display/avatar-ui.md @@ -0,0 +1,39 @@ +--- +components: + - rx.ui.avatar +--- +```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"), + spacing="3", +) +``` + +The fallback is in the page the server sends and shows until the image has +loaded. `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)], + spacing="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..548c06832e2 --- /dev/null +++ b/docs/library/data-display/badge-ui.md @@ -0,0 +1,32 @@ +--- +components: + - rx.ui.badge +--- +```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), + spacing="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..84c47b23f22 --- /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 +--- +```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", + spacing="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..0579e516588 --- /dev/null +++ b/docs/library/data-display/data_list-ui.md @@ -0,0 +1,53 @@ +--- +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..5631c095b03 --- /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"), + ), + spacing="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..377dae2308d --- /dev/null +++ b/docs/library/data-display/progress-ui.md @@ -0,0 +1,38 @@ +--- +components: + - rx.ui.progress +--- +```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", + spacing="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..883f426d2e7 --- /dev/null +++ b/docs/library/data-display/scroll_area-ui.md @@ -0,0 +1,35 @@ +--- +components: + - rx.ui.scroll_area +--- +```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", + spacing="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..6ac3fa01519 --- /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"), + spacing="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), + spacing="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..7b0549a068b --- /dev/null +++ b/docs/library/disclosure/accordion-ui.md @@ -0,0 +1,83 @@ +--- +components: + - rx.ui.accordion.root + - rx.ui.accordion.item +--- +```python exec +import reflex as rx +``` + +# Accordion + +`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 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( + 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", + spacing="3", + ) +``` + +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/disclosure/segmented_control-ui.md b/docs/library/disclosure/segmented_control-ui.md new file mode 100644 index 00000000000..9b086a5bbf6 --- /dev/null +++ b/docs/library/disclosure/segmented_control-ui.md @@ -0,0 +1,63 @@ +--- +components: + - rx.ui.segmented_control.root + - rx.ui.segmented_control.item +--- +```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", + spacing="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", + spacing="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..ea1b9a5192d --- /dev/null +++ b/docs/library/disclosure/tabs-ui.md @@ -0,0 +1,90 @@ +--- +components: + - rx.ui.tabs.root + - rx.ui.tabs.list + - rx.ui.tabs.trigger + - rx.ui.tabs.content +--- +```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", + spacing="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", +) +``` diff --git a/docs/library/forms/button-ui.md b/docs/library/forms/button-ui.md new file mode 100644 index 00000000000..89f02fb514d --- /dev/null +++ b/docs/library/forms/button-ui.md @@ -0,0 +1,99 @@ +--- +components: + - rx.ui.button + - rx.ui.icon_button +--- + +```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 + ), + spacing="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"), + spacing="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"), + spacing="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), + spacing="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" + ), + spacing="3", +) +``` diff --git a/docs/library/forms/checkbox-ui.md b/docs/library/forms/checkbox-ui.md new file mode 100644 index 00000000000..0da6d908848 --- /dev/null +++ b/docs/library/forms/checkbox-ui.md @@ -0,0 +1,98 @@ +--- +components: + - rx.ui.checkbox + - rx.ui.checkbox_group.root + - rx.ui.checkbox_group.item + - rx.ui.checkbox_cards.root + - rx.ui.checkbox_cards.item +--- +```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")), + spacing="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", + spacing="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", + spacing="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..1f7c32cb05a --- /dev/null +++ b/docs/library/forms/form-ui.md @@ -0,0 +1,79 @@ +--- +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 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 + +`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.text(rx.ui.switch(name="switch"), " Switched", as_="label"), + ), + 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", + spacing="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..455068eaa52 --- /dev/null +++ b/docs/library/forms/input-ui.md @@ -0,0 +1,55 @@ +--- +components: + - rx.ui.input + - rx.ui.input.slot +--- +```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", + spacing="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", + spacing="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..2f57b8586b2 --- /dev/null +++ b/docs/library/forms/radio_group-ui.md @@ -0,0 +1,81 @@ +--- +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 +--- +```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), + spacing="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", 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", + spacing="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..5d9a2a4ec34 --- /dev/null +++ b/docs/library/forms/select-ui.md @@ -0,0 +1,69 @@ +--- +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 +--- +```python exec +import reflex as rx +``` + +# Select + +`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 + +```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), + spacing="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 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 new file mode 100644 index 00000000000..5af1a3fda88 --- /dev/null +++ b/docs/library/forms/slider-ui.md @@ -0,0 +1,57 @@ +--- +components: + - rx.ui.slider +--- +```python exec +import reflex as rx +``` + +# Slider + +`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 + +`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", + spacing="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 ten steps. + +## 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", + spacing="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..2d886e6b7ac --- /dev/null +++ b/docs/library/forms/switch-ui.md @@ -0,0 +1,46 @@ +--- +components: + - rx.ui.switch +--- +```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")), + spacing="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), + spacing="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..15680b27118 --- /dev/null +++ b/docs/library/forms/text_area-ui.md @@ -0,0 +1,43 @@ +--- +components: + - rx.ui.text_area +--- +```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", + spacing="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", + spacing="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..6c586d1155a --- /dev/null +++ b/docs/library/layout/card-ui.md @@ -0,0 +1,64 @@ +--- +components: + - rx.ui.card +--- +```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" + ), + ), + spacing="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"), + spacing="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"), + spacing="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..d409301c8f1 --- /dev/null +++ b/docs/library/layout/center-ui.md @@ -0,0 +1,24 @@ +--- +components: + - rx.ui.center +--- +```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..84d0be47f17 --- /dev/null +++ b/docs/library/layout/flex-ui.md @@ -0,0 +1,49 @@ +--- +components: + - rx.ui.flex +--- +```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"), + spacing="2", +) +``` + +## Direction, Alignment and Wrapping + +`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( + rx.ui.card("Card 1"), + rx.ui.card("Card 2"), + rx.ui.card("Card 3"), + direction=rx.breakpoints(initial="column", sm="row"), + justify="between", + spacing="3", +) +``` + +```python demo +rx.ui.flex( + *[rx.ui.badge(f"Item {i}") for i in range(1, 13)], + wrap="wrap", + spacing="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..c6c4bd76c55 --- /dev/null +++ b/docs/library/layout/grid-ui.md @@ -0,0 +1,44 @@ +--- +components: + - rx.ui.grid +--- +```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", + spacing="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"), + spacing="3", +) +``` + +## Flow + +```python demo +rx.ui.grid( + *[rx.ui.card(f"Card {i}") for i in range(1, 7)], + rows="2", + flow="column", + spacing="3", +) +``` diff --git a/docs/library/layout/inset-ui.md b/docs/library/layout/inset-ui.md new file mode 100644 index 00000000000..b79988d7166 --- /dev/null +++ b/docs/library/layout/inset-ui.md @@ -0,0 +1,36 @@ +--- +components: + - rx.ui.inset +--- +```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..d99bbcc72c8 --- /dev/null +++ b/docs/library/layout/section-ui.md @@ -0,0 +1,29 @@ +--- +components: + - rx.ui.section +--- +```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..fa0f02901f0 --- /dev/null +++ b/docs/library/layout/separator-ui.md @@ -0,0 +1,37 @@ +--- +components: + - rx.ui.separator +--- +```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", + spacing="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"), + spacing="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..9f670abf5e6 --- /dev/null +++ b/docs/library/layout/stack-ui.md @@ -0,0 +1,41 @@ +--- +components: + - rx.ui.stack + - rx.ui.hstack + - rx.ui.vstack +--- +```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"), + spacing="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/other/skeleton-ui.md b/docs/library/other/skeleton-ui.md new file mode 100644 index 00000000000..03e754b6323 --- /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"}), + spacing="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..626f8276fcc --- /dev/null +++ b/docs/library/other/theme-ui.md @@ -0,0 +1,61 @@ +--- +components: + - rx.ui.theme + - rx.ui.theme_panel + - rx.ui.color_mode.button + - rx.ui.color_mode.switch +--- +```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", + ), + spacing="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(), + spacing="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..d4a0ac3f75f --- /dev/null +++ b/docs/library/overlay/alert_dialog-ui.md @@ -0,0 +1,45 @@ +--- +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 +--- +```python exec +import reflex as rx +``` + +# Alert Dialog + +`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 + +```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") + ), + spacing="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..8aadcea4ec0 --- /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 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 + +```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..69ffebac9d1 --- /dev/null +++ b/docs/library/overlay/dialog-ui.md @@ -0,0 +1,72 @@ +--- +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 +--- +```python exec +import reflex as rx +``` + +# Dialog + +`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 + +```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"}, + ), + ), +) +``` + +An open dialog makes the page behind it inert and keeps the focus inside; +Escape and a press outside close it. + +## 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, + ), + spacing="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..35ec995a543 --- /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 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 + +```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", + spacing="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..0e1a419745a --- /dev/null +++ b/docs/library/overlay/dropdown_menu-ui.md @@ -0,0 +1,67 @@ +--- +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 +--- +```python exec +import reflex as rx +``` + +# Dropdown Menu + +`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 + +```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)), + spacing="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..ad7383c8aea --- /dev/null +++ b/docs/library/overlay/hover_card-ui.md @@ -0,0 +1,40 @@ +--- +components: + - rx.ui.hover_card.root + - rx.ui.hover_card.trigger + - rx.ui.hover_card.content +--- +```python exec +import reflex as rx +``` + +# Hover Card + +`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 + +```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"), + ), + spacing="3", + ), + ), + ), + spacing="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..9c0495ca5a8 --- /dev/null +++ b/docs/library/overlay/popover-ui.md @@ -0,0 +1,49 @@ +--- +components: + - rx.ui.popover.root + - rx.ui.popover.trigger + - rx.ui.popover.content + - rx.ui.popover.close +--- +```python exec +import reflex as rx +``` + +# Popover + +`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 + +```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", + spacing="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"] + ], + spacing="3", +) +``` 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/docs/library/overlay/tooltip-ui.md b/docs/library/overlay/tooltip-ui.md new file mode 100644 index 00000000000..a39296099fd --- /dev/null +++ b/docs/library/overlay/tooltip-ui.md @@ -0,0 +1,34 @@ +--- +components: + - rx.ui.tooltip +--- +```python exec +import reflex as rx +``` + +# Tooltip + +`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 + +```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"] + ], + spacing="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..14d0f377dd3 --- /dev/null +++ b/docs/library/tables-and-data-grids/table-ui.md @@ -0,0 +1,79 @@ +--- +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 +--- +```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. diff --git a/docs/library/typography/blockquote-ui.md b/docs/library/typography/blockquote-ui.md new file mode 100644 index 00000000000..43548eeada0 --- /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", + spacing="3", +) +``` diff --git a/docs/library/typography/code-ui.md b/docs/library/typography/code-ui.md new file mode 100644 index 00000000000..38fa47dd02e --- /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"), + spacing="3", +) +``` diff --git a/docs/library/typography/heading-ui.md b/docs/library/typography/heading-ui.md new file mode 100644 index 00000000000..14fd1c3ddfb --- /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", + spacing="2", +) +``` diff --git a/docs/library/typography/link-ui.md b/docs/library/typography/link-ui.md new file mode 100644 index 00000000000..17b3bc5ea07 --- /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), + spacing="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"), + spacing="4", +) +``` diff --git a/docs/library/typography/text-ui.md b/docs/library/typography/text-ui.md new file mode 100644 index 00000000000..a822a527d32 --- /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", + spacing="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", + spacing="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..f29135c5bf7 --- /dev/null +++ b/docs/rx_ui/overview.md @@ -0,0 +1,141 @@ +--- +title: "rx.ui: Compiled Components" +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 +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. 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: + +```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 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 + +`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..86b89738c32 --- /dev/null +++ b/docs/rx_ui/styling.md @@ -0,0 +1,309 @@ +--- +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 `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 +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, + ), + spacing="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`, ... + +# 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, +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..b2a9d8ac64a --- /dev/null +++ b/docs/rx_ui/theming.md @@ -0,0 +1,208 @@ +--- +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", + ), + spacing="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"), + spacing="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"), + spacing="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", + spacing="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/docs/styling/rx-ui-migration.md b/docs/styling/rx-ui-migration.md new file mode 100644 index 00000000000..fd86cad4f02 --- /dev/null +++ b/docs/styling/rx-ui-migration.md @@ -0,0 +1,387 @@ +# Migrating to rx.ui + +`rx.ui` has the components of `rx` that are built on Radix Themes, with the +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 + +- `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 | 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 | +| 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 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: + +- `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. +- 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 + +- 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": 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. +- behaviour, `rx.ui`, "Tab stops on every header, and not on a disabled one": UI SDK keeps the header of a disabled item of rx.ui.accordion focusable, and says it is disabled with `aria-disabled`, so that a screen reader finds it: Tab stops on it, and pressing it opens nothing. rx.accordion disables the button of the header, which Tab passes. + +### alert_dialog + +- 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 + +- 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. + +### 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. + +### 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 + +- 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 + +- 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 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 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 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 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. 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. + +### 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. +- 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, 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` 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: 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. + +### 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.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. +- behaviour, `rx.ui`, "the arrow keys, Home and End move the focus without choosing": The items of rx.ui.segmented_control are a group of radio buttons of UI SDK, which the arrow keys move through; Home and End do nothing there. rx.segmented_control, a group of toggle buttons, goes to the first and the last item with Home and End. +- behaviour, `rx.ui`, "Space, Enter and a click choose an item, and say so": Space and a click choose an item of rx.ui.segmented_control, a radio button of UI SDK, and Enter does not, as the radio pattern of ARIA has it. rx.segmented_control, a group of toggle buttons, chooses an item with Enter too. + +### 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. 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. + +### 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. 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 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. +- 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 + +- 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. + +### 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. +- behaviour, `rx` in firefox, "Tab stops on the selected trigger, then on its panel": In Firefox, Shift+Tab from the selected tab of rx.tabs leaves the focus on that tab, where the roving focus of Radix gives it back; in Chromium and WebKit it goes back to the panel before. rx.ui.tabs goes back to the panel before in every engine. +- 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 + +- 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. + +### 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. +- 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 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. +- 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/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/examples/pages/.content-hash b/examples/pages/.content-hash new file mode 100644 index 00000000000..15c18583f3f --- /dev/null +++ b/examples/pages/.content-hash @@ -0,0 +1 @@ +sha256:0ec61190fef10b2a30d691dae893d64cfb343c180907ae013abf6e8ee5c057a2 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..967466326f3 --- /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(enable_state=False) +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..e24dedc75cd --- /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")), + spacing="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"), + spacing="6", + ), + ns.center( + ns.blockquote("Settings are saved per project."), + ns.code("acme.reflex.run"), + padding="16px", + ), + 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 41393b91a35..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] @@ -31,6 +33,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/+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/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/news/+lazy-dynamic-libraries.performance.md b/news/+lazy-dynamic-libraries.performance.md new file mode 100644 index 00000000000..6a3699cf8af --- /dev/null +++ b/news/+lazy-dynamic-libraries.performance.md @@ -0,0 +1 @@ +Apps that render no dynamic component (a component held in state) no longer build or ship the libraries registered for them, and apps that do fetch each library on first use instead of on every page. Libraries an app registers itself with `rx.bundle_library` always stay loadable through `window.__reflex_load`. 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/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/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/news/+stateless-root-without-event-runtime.performance.md b/news/+stateless-root-without-event-runtime.performance.md new file mode 100644 index 00000000000..cdd9733d90c --- /dev/null +++ b/news/+stateless-root-without-event-runtime.performance.md @@ -0,0 +1 @@ +An app with `enable_state=False` no longer ships the event runtime on every page: its root, its context module and its error boundary run without `utils/state.js`, which a page loads only when it has an event handler, or when the app renders a dynamic component. 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/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/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/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/+emotion-free-pages.performance.md b/packages/reflex-base/news/+emotion-free-pages.performance.md new file mode 100644 index 00000000000..043332ee1ed --- /dev/null +++ b/packages/reflex-base/news/+emotion-free-pages.performance.md @@ -0,0 +1 @@ +The templates of generated modules import React's `createElement` as `jsx` when the code of the module has no `css` prop, and Emotion's `jsx` otherwise. Code that generates a module of its own from `Component._get_all_imports()` is unchanged and keeps importing Emotion. diff --git a/packages/reflex-base/news/+lazy-dynamic-libraries.breaking.md b/packages/reflex-base/news/+lazy-dynamic-libraries.breaking.md new file mode 100644 index 00000000000..024d40cde62 --- /dev/null +++ b/packages/reflex-base/news/+lazy-dynamic-libraries.breaking.md @@ -0,0 +1 @@ +`frontend_lazy_bundled_libraries` now defaults to `True`: `window.__reflex` holds React and the Reflex runtime, and gains each other registered library only once it has been loaded. Custom scripts that read a library from `window.__reflex` must first `await window.__reflex_load([""])`, or the app can set `frontend_lazy_bundled_libraries=False` to keep importing every registered library up front. Dynamic components and `rx.bundle_library` need no change. diff --git a/packages/reflex-base/news/+lazy-dynamic-libraries.performance.md b/packages/reflex-base/news/+lazy-dynamic-libraries.performance.md new file mode 100644 index 00000000000..64fdeb41bfc --- /dev/null +++ b/packages/reflex-base/news/+lazy-dynamic-libraries.performance.md @@ -0,0 +1 @@ +Stop shipping whole libraries to every page for dynamic components. A library registered for dynamic components (such as `@radix-ui/themes`, or one passed to `rx.bundle_library`) is now built as a chunk of its own and fetched the first time a dynamic component needs it, so pages only load the parts of it they use. A blank app's JavaScript drops from about 240 KB to 171 KB gzipped. 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/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/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/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-base/news/+scripts-after-first-paint.performance.md b/packages/reflex-base/news/+scripts-after-first-paint.performance.md new file mode 100644 index 00000000000..e698cafd17a --- /dev/null +++ b/packages/reflex-base/news/+scripts-after-first-paint.performance.md @@ -0,0 +1 @@ +Prerendered pages show up sooner: a production page no longer preloads its scripts ahead of the stylesheet it needs to paint, and starts them once it has painted. On a blank app, mobile Lighthouse LCP drops from about 2.9 s to 1.2 s (simulated slow 4G). Hydration starts later by the same design, and the window `load` event no longer waits for it. A click that comes before the page is hydrated starts the scripts right away and is dispatched again once its handler is attached; so does a hidden tab or a browser without paint timing, and a page that paints nothing starts them after one second. Dev mode and pages rendered in the browser are unchanged. 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/news/+stateless-root-without-event-runtime.performance.md b/packages/reflex-base/news/+stateless-root-without-event-runtime.performance.md new file mode 100644 index 00000000000..2d64d7ef3ab --- /dev/null +++ b/packages/reflex-base/news/+stateless-root-without-event-runtime.performance.md @@ -0,0 +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. A dynamic component reads the registry of refs from `window.__reflex["$/utils/refs"]`. 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/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/client_state.py b/packages/reflex-base/src/reflex_base/client_state.py index 0962f49a231..a8877522e3f 100644 --- a/packages/reflex-base/src/reflex_base/client_state.py +++ b/packages/reflex-base/src/reflex_base/client_state.py @@ -246,7 +246,7 @@ def _collect_declarations() -> Iterator[None]: # and devtools can inspect. _client_state_store_set = FunctionStringVar.create( f"refs[{json.dumps(CLIENT_STATE_REF)}].set", - _var_data=VarData(imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]}), + _var_data=VarData(imports={f"$/{Dirs.REFS_PATH}": [ImportVar(tag="refs")]}), ) diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 77f28862881..af623d6dd46 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( @@ -67,6 +68,63 @@ 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]: + """Settle which element factory a module calls ``jsx``. + + The imports of a module name Emotion's, the only one that applies a + ``css`` prop. A module whose code has no ``css`` key has no such prop to + apply, so it gets React's ``createElement`` under that name instead, and + stops depending on Emotion. The code is what decides, since it exists by + now: no component is asked, and whatever reached the module is seen. + + Args: + imports: The imports of the module. + *code: The rest of the module. + + Returns: + The imports the module should have. + """ + if any(map(_CSS_KEY.search, code)): + return list(imports) + resolved: list[_ImportDict] = [] + react: int | None = None + swap = False + for module in imports: + if module["lib"] == "@emotion/react" and "jsx" in module["rest"]: + swap = True + rest = [name for name in module["rest"] if name != "jsx"] + if not rest and not module["default"]: + continue + module: _ImportDict = { + "lib": "@emotion/react", + "default": module["default"], + "rest": rest, + } + elif module["lib"] == "react": + react = len(resolved) + resolved.append(module) + if not swap: + return resolved + if react is None: + resolved.append({"lib": "react", "default": "", "rest": [_REACT_JSX]}) + else: + module = resolved[react] + resolved[react] = { + "lib": "react", + "default": module["default"], + "rest": sorted([*module["rest"], _REACT_JSX]), + } + return resolved + + class _RenderUtils: @staticmethod def render(component: Mapping[str, Any] | str) -> str: @@ -138,6 +196,21 @@ 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: Iterable[_ImportDict], *code: str) -> str: + """Render the imports of a module, settling what it calls ``jsx``. + + Args: + imports: The imports of the module. + *code: The rest of the module. + + Returns: + The import statements, one per line. + """ + return "\n".join([ + _RenderUtils.get_import(module) for module in resolve_jsx(imports, *code) + ]) + def rxconfig_template(app_name: str): """Template for the Reflex config file. @@ -170,12 +243,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} ) }}""" @@ -201,12 +274,11 @@ def app_root_template( render: The dictionary of render functions. dynamic_imports: The set of dynamic imports. hydrate_fallback_export: The exported name of the hydrate-fallback memo module to re-export as ``HydrateFallback``, or None for no fallback. - lazy_window_libraries: Optional libraries loaded before evaluating a dynamic component. + lazy_window_libraries: Optional libraries loaded before evaluating a dynamic component, each from the module `dynamic_library_template` renders for it. 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 = "" @@ -236,11 +308,15 @@ def app_root_template( lazy_imports_setup = "" if lazy_window_libraries: loaders = "\n".join( - f" {json.dumps(lib_path)}: () => import({json.dumps(lib_path)})," - for _, lib_path in lazy_window_libraries + f" {json.dumps(lib_path)}: () => " + f'import("$/{constants.Dirs.DYNAMIC_LIBRARIES_PATH}/{lib_alias}")' + ".then((module) => module.default)," + for lib_alias, lib_path in lazy_window_libraries ) # Register before child effects run, including an initially mounted - # dynamic component. Optional namespaces stay out of the initial graph. + # dynamic component. Each namespace is imported through a module of its + # own: importing the library here would pull every export into the + # chunks pages load, a separate module becomes a chunk fetched on demand. window_imports_effect = "" lazy_imports_setup = f""" if (typeof window !== "undefined") {{ @@ -267,6 +343,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} @@ -289,8 +371,8 @@ def app_root_template( function AppWrap({{children}}) {{ -{_render_hooks(hooks)} -return ({_RenderUtils.render(render)}) +{hooks_str} +return ({rendered}) }} export function Layout({{children}}) {{ @@ -311,6 +393,20 @@ def app_root_template( """ +def dynamic_library_template(lib_path: str) -> str: + """Template for the module that exposes a library to dynamic components. + + Args: + lib_path: The module path of the library. + + Returns: + Rendered module code as string. + """ + return f"""import * as library from {json.dumps(lib_path)}; +export default library; +""" + + def theme_template(theme: str): """Template for the theme file. @@ -323,6 +419,108 @@ def theme_template(theme: str): return f"""export default {theme}""" +# The state store of the compiled context module of an app with state. +_STATEFUL_STORE = """// Dispatch updates happen outside render; useSyncExternalStore keeps reads +// consistent while notifying only consumers of the changed substate. +function createStateStore(initialState) { + const state = {}; + const listeners = new Map(); + const dispatchers = {}; + const notify = (substateName) => + listeners.get(substateName)?.forEach((listener) => listener()); + // Hot reload passes the recompiled initial state: new substates are added, + // and existing substates gain new fields at their defaults while keeping + // their live values. + const mergeInitialState = (nextInitialState) => { + for (const [substateName, value] of Object.entries(nextInitialState)) { + const liveState = state[substateName]; + if (liveState !== undefined) { + if (Object.keys(value).some((key) => !Object.hasOwn(liveState, key))) { + state[substateName] = { ...value, ...liveState }; + notify(substateName); + } + continue; + } + state[substateName] = value; + dispatchers[substateName] = (delta) => { + const currentState = state[substateName]; + const nextState = applyDelta(currentState, delta); + if (nextState === currentState) return; + state[substateName] = nextState; + notify(substateName); + }; + notify(substateName); + } + }; + mergeInitialState(initialState); + + return { + dispatchers, + mergeInitialState, + getSnapshot: (substateName) => state[substateName], + subscribe: (substateName, listener) => { + let substateListeners = listeners.get(substateName); + if (!substateListeners) { + substateListeners = new Set(); + listeners.set(substateName, substateListeners); + } + substateListeners.add(listener); + return () => substateListeners.delete(listener); + }, + }; +} + +function StateStoreProviders({ children, store }) { + return createElement( + StateStoreContext, + { value: store }, + createElement(DispatchContext, { value: store.dispatchers }, children), + ); +} + +function ClientStateProvider({ children }) { + const [store] = useState(() => createStateStore(initialState)); + useEffect(() => store.mergeInitialState(initialState), [store, initialState]); + return createElement(StateStoreProviders, { children, store }); +} + +// The server renders once and never applies a delta, so it only reads the +// initial state. +const serverStateStore = { + dispatchers: {}, + getSnapshot: (substateName) => initialState[substateName], + subscribe: () => () => {}, +}; + +function ServerStateProvider({ children }) { + return createElement(StateStoreProviders, { children, store: serverStateStore }); +} + +export const StateProvider = + typeof document === "undefined" ? ServerStateProvider : ClientStateProvider;""" + +# The state store of the compiled context module of an app without state. +_STATELESS_STORE = """// An app without state applies no delta: its pages read the initial state, +// in the browser as on the server. +const stateStore = { + dispatchers: {}, + getSnapshot: (substateName) => initialState[substateName], + subscribe: () => () => {}, +}; + +function StateStoreProviders({ children, store }) { + return createElement( + StateStoreContext, + { value: store }, + createElement(DispatchContext, { value: store.dispatchers }, children), + ); +} + +export function StateProvider({ children }) { + return createElement(StateStoreProviders, { children, store: stateStore }); +}""" + + def context_template( *, is_dev_mode: bool, @@ -429,6 +627,23 @@ 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. + # Nor the event runtime: its event loop is the one of utils/event_loop.js, + # which loads utils/state.js with the first page that has an event handler. + state_imports_str = ( + 'import { applyDelta, ReflexEvent } from "$/utils/state"\n' + 'import { refs } from "$/utils/refs"\n' + 'import { hydrateClientStorage, useEventLoop } from "$/utils/socket"' + if state_name + else 'import { refs } from "$/utils/refs"\n' + 'import { useLocalEventLoop as useEventLoop } from "$/utils/event_loop"' + ) + + # The store of the state of the app: one that applies the deltas of the + # backend, or, without state, one that never changes. + state_store_str = _STATEFUL_STORE if state_name else _STATELESS_STORE + disable_owner_stacks_str = ( r""" // Disable React dev-build owner-stack capture: the per-element Error() @@ -458,9 +673,8 @@ 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} export {{ ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext }}; export const initialState = {initial_state_json} @@ -525,7 +739,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; @@ -553,84 +767,7 @@ def context_template( ); }} -// Dispatch updates happen outside render; useSyncExternalStore keeps reads -// consistent while notifying only consumers of the changed substate. -function createStateStore(initialState) {{ - const state = {{}}; - const listeners = new Map(); - const dispatchers = {{}}; - const notify = (substateName) => - listeners.get(substateName)?.forEach((listener) => listener()); - // Hot reload passes the recompiled initial state: new substates are added, - // and existing substates gain new fields at their defaults while keeping - // their live values. - const mergeInitialState = (nextInitialState) => {{ - for (const [substateName, value] of Object.entries(nextInitialState)) {{ - const liveState = state[substateName]; - if (liveState !== undefined) {{ - if (Object.keys(value).some((key) => !Object.hasOwn(liveState, key))) {{ - state[substateName] = {{ ...value, ...liveState }}; - notify(substateName); - }} - continue; - }} - state[substateName] = value; - dispatchers[substateName] = (delta) => {{ - const currentState = state[substateName]; - const nextState = applyDelta(currentState, delta); - if (nextState === currentState) return; - state[substateName] = nextState; - notify(substateName); - }}; - notify(substateName); - }} - }}; - mergeInitialState(initialState); - - return {{ - dispatchers, - mergeInitialState, - getSnapshot: (substateName) => state[substateName], - subscribe: (substateName, listener) => {{ - let substateListeners = listeners.get(substateName); - if (!substateListeners) {{ - substateListeners = new Set(); - listeners.set(substateName, substateListeners); - }} - substateListeners.add(listener); - return () => substateListeners.delete(listener); - }}, - }}; -}} - -function StateStoreProviders({{ children, store }}) {{ - return createElement( - StateStoreContext, - {{ value: store }}, - createElement(DispatchContext, {{ value: store.dispatchers }}, children), - ); -}} - -function ClientStateProvider({{ children }}) {{ - const [store] = useState(() => createStateStore(initialState)); - useEffect(() => store.mergeInitialState(initialState), [store, initialState]); - return createElement(StateStoreProviders, {{ children, store }}); -}} - -// The server renders once and never applies a delta, so it only reads the -// initial state. -const serverStateStore = {{ - dispatchers: {{}}, - getSnapshot: (substateName) => initialState[substateName], - subscribe: () => () => {{}}, -}}; - -function ServerStateProvider({{ children }}) {{ - return createElement(StateStoreProviders, {{ children, store: serverStateStore }}); -}} - -export const StateProvider = - typeof document === "undefined" ? ServerStateProvider : ClientStateProvider;""" +{state_store_str}""" def component_template(component: Component): @@ -688,11 +825,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 @@ -713,7 +853,7 @@ def page_template( {hooks_str} return ( - {_RenderUtils.render(render)} + {rendered} ) }} {display_name_str} @@ -772,6 +912,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 +929,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 +1034,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 +1116,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 "[]"}), @@ -1155,7 +1310,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) @@ -1167,6 +1321,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} @@ -1196,11 +1354,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} @@ -1225,11 +1383,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/packages/reflex-base/src/reflex_base/components/component.py b/packages/reflex-base/src/reflex_base/components/component.py index b9005fdd3bf..fb2142ae4f3 100644 --- a/packages/reflex-base/src/reflex_base/components/component.py +++ b/packages/reflex-base/src/reflex_base/components/component.py @@ -1528,6 +1528,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 @@ -1847,7 +1852,7 @@ def _get_hooks_imports(self) -> ParsedImportDict: if self._get_ref_hook() is not None: # Handle hooks needed for attaching react refs to DOM nodes. - imports_.setdefault(f"$/{Dirs.STATE_PATH}", set()).add( + imports_.setdefault(f"$/{Dirs.REFS_PATH}", set()).add( ImportVar(tag="useRegisteredRef") ) @@ -2459,17 +2464,18 @@ def _cached_get_all_var_data(self) -> VarData | None: VarData( imports=self._var_value._get_all_imports(), ), - VarData( - # Rendering rx.match in the code above produces conditional expressions - # of the form (pattern1 == element || pattern2 == element || ...), which - # introduce the OR operator and get compiled to a pyOr function call. Since - # the component itself might not otherwise require pyOr, and since we ignore - # the imports of the rendered Var above, we add the pyOr import here to - # ensure it is available. An alternative would be to have `render_dict_to_var` - # return a Var carrying all the required VarData, so this call could just - # retrieve it from there. - imports=_PY_OR_IMPORT - ), + # Rendering rx.match in the code above produces conditional expressions + # of the form (pattern1 == element || pattern2 == element || ...), which + # introduce the OR operator and get compiled to a pyOr function call. Since + # the component itself might not otherwise require pyOr, and since we ignore + # the imports of the rendered Var above, we add the pyOr import here when + # the rendered code calls it: an import of the event runtime it does not + # use would load it into the page of an app without state. An alternative + # would be to have `render_dict_to_var` return a Var carrying all the + # required VarData, so this call could just retrieve it from there. + VarData(imports=_PY_OR_IMPORT) + if "pyOr(" in self._cached_var_name + else None, ) def __hash__(self) -> int: diff --git a/packages/reflex-base/src/reflex_base/components/dynamic.py b/packages/reflex-base/src/reflex_base/components/dynamic.py index a32e4cddff1..9cf3b8591d0 100644 --- a/packages/reflex-base/src/reflex_base/components/dynamic.py +++ b/packages/reflex-base/src/reflex_base/components/dynamic.py @@ -1,11 +1,18 @@ """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 -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 @@ -17,6 +24,41 @@ 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() + + +@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`. @@ -166,6 +208,18 @@ 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 + """ + with rendering_dynamic_component(): + return generate_component_code(component) + + def generate_component_code(component: Component) -> str: + """Generate the module a dynamic component is evaluated from. + Args: component: The component to generate code for. @@ -224,7 +278,10 @@ def make_component(component: Component) -> str: module_imports = [] bundled_declarations = [] bundled_library_paths = set() - for module in utils.compile_imports(imports): + # Emotion is only loaded for code with a ``css`` prop to apply. + for module in templates.resolve_jsx( + utils.compile_imports(imports), *rendered_components + ): if module["lib"] not in libs_in_window and not module["lib"].startswith(( "$/", "/", @@ -268,9 +325,9 @@ def make_component(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/config.py b/packages/reflex-base/src/reflex_base/config.py index cb23d019170..2a71a28f84e 100644 --- a/packages/reflex-base/src/reflex_base/config.py +++ b/packages/reflex-base/src/reflex_base/config.py @@ -186,7 +186,7 @@ class BaseConfig: auto_memoize: Wrap stateful page components in generated memo components. Disable only together with react_compiler, which then memoizes whole pages; without it, every state change re-renders the whole page. Defaults to True. frontend_compression_formats: Pre-compressed frontend asset formats to generate for production builds. Supported values are "gzip", "brotli", and "zstd". Use an empty list to disable build-time pre-compression. frontend_packages: Additional frontend packages to install. - frontend_lazy_bundled_libraries: Load optional dynamic-component libraries when a dynamic component is first evaluated, rather than importing their full namespaces on every page. Defaults to False for compatibility with scripts that read window.__reflex directly. + frontend_lazy_bundled_libraries: Load optional dynamic-component libraries when a dynamic component is first evaluated, rather than importing their full namespaces on every page. Set to False for scripts that read these libraries from window.__reflex without awaiting window.__reflex_load(). state_manager_mode: Indicate which type of state manager to use. redis_lock_expiration: Maximum expiration lock time for redis state manager. redis_lock_warning_threshold: Maximum lock time before warning for redis state manager. @@ -264,7 +264,7 @@ class BaseConfig: frontend_packages: list[str] = dataclasses.field(default_factory=list) - frontend_lazy_bundled_libraries: bool = False + frontend_lazy_bundled_libraries: bool = True state_manager_mode: constants.StateManagerMode = constants.StateManagerMode.DISK diff --git a/packages/reflex-base/src/reflex_base/constants/base.py b/packages/reflex-base/src/reflex_base/constants/base.py index 5add4115098..adc8970396c 100644 --- a/packages/reflex-base/src/reflex_base/constants/base.py +++ b/packages/reflex-base/src/reflex_base/constants/base.py @@ -33,6 +33,10 @@ class Dirs(SimpleNamespace): UTILS = "utils" # The name of the state file. STATE_PATH = UTILS + "/state" + # The name of the refs file: the registry of the refs of elements with an + # id, apart from the state file so that registering one bundles no event + # runtime. + REFS_PATH = UTILS + "/refs" # The name of the components file, where memos that can't be mirrored to a # user module (``__main__``, unsafe names) get one file per memo. COMPONENTS_PATH = UTILS + "/components" @@ -40,6 +44,8 @@ class Dirs(SimpleNamespace): CONTEXTS_PATH = UTILS + "/context" # The name of the client state file. CLIENT_STATE_PATH = UTILS + "/client_state" + # The directory of the modules that expose a library to dynamic components. + DYNAMIC_LIBRARIES_PATH = UTILS + "/dynamic_libraries" # The name of the output directory. BUILD_DIR = "build" # The name of the static files directory. 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/registry.py b/packages/reflex-base/src/reflex_base/registry.py index 05fb5c694da..0c49b54980c 100644 --- a/packages/reflex-base/src/reflex_base/registry.py +++ b/packages/reflex-base/src/reflex_base/registry.py @@ -34,6 +34,23 @@ 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}", + ] + + +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" ] 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/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/packages/reflex-base/src/reflex_base/utils/pyi_generator.py b/packages/reflex-base/src/reflex_base/utils/pyi_generator.py index 06280c42e84..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 [] @@ -1500,6 +1530,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-base/src/reflex_base/vars/base.py b/packages/reflex-base/src/reflex_base/vars/base.py index 1f34176ff31..b55ae1d4b25 100644 --- a/packages/reflex-base/src/reflex_base/vars/base.py +++ b/packages/reflex-base/src/reflex_base/vars/base.py @@ -1567,7 +1567,7 @@ def _as_ref(self) -> Var: _js_expr=f"refs[{Var.create(str(self))}]", _var_data=VarData( imports={ - f"$/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")] + f"$/{constants.Dirs.REFS_PATH}": [imports.ImportVar(tag="refs")] } ), ).to(str) diff --git a/packages/reflex-bench/README.md b/packages/reflex-bench/README.md index ddcf95d6880..bef19f1cfbc 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,27 @@ 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 ` + + 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/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("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(); + 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.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(); + click(target); + target.remove(); + await hydrate(); + expect(clicks.length).toBe(1); + }); + + 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"); + 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); + 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); + }); + }); +}); 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..357d4e7f291 --- /dev/null +++ b/packages/reflex-frontend/tests/state_without_backend.test.js @@ -0,0 +1,271 @@ +/** + * `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(); +}); + +test("the event loop of a root without utils/state.js queues through what it registers", async () => { + // The root of an app without state imports utils/event_loop.js alone; a + // page imports utils/state.js with its first event handler. + vi.resetModules(); + const eventLoop = await import("$/utils/event_loop"); + const registry = await import("$/utils/context-registry"); + registry.registerApp({ + initialState: {}, + clientStorage: {}, + initialEvents: () => [], + onLoadInternalEvent: () => [], + isDevMode: false, + }); + expect(eventLoop.runtime).toEqual({}); + const mounted = {}; + const Probe = () => { + [mounted.addEvents, mounted.connectErrors] = eventLoop.useLocalEventLoop(); + mounted.location = useLocation(); + return null; + }; + const root = createRoot( + document.body.appendChild(document.createElement("div")), + ); + await act(async () => { + root.render(createElement(MemoryRouter, null, createElement(Probe))); + }); + expect(() => + mounted.addEvents([{ name: "_redirect", payload: { path: "/early" } }]), + ).toThrow(TypeError); + + const page = await import("$/utils/state"); + expect(Object.keys(eventLoop.runtime)).toEqual(["addLocalEvents"]); + await act(async () => + mounted.addEvents([page.ReflexEvent("_redirect", { path: "/later" })]), + ); + + expect(mounted.location.pathname).toBe("/later"); + expect(mounted.connectErrors).toEqual([]); + expect(loaded).toEqual([]); + await act(async () => root.unmount()); +}); 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/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/pyi_hashes.json b/pyi_hashes.json index fec0b8f2474..e6607f4b987 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -5,8 +5,8 @@ "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/error_boundary.pyi": "2bec3beeafea96787d10838d73e47bdc", + "packages/reflex-components-core/src/reflex_components_core/base/document.pyi": "04d20bcfba980db936b2e88974e0b02c", + "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": "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", @@ -117,8 +117,69 @@ "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", - "reflex/__init__.pyi": "067a60e22fb825072f2f0b690662da5a", + "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "f753e71635ca82297fadda6574b9760e", + "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": "c3dfb4f69cf5cb12eb5320fd788c23a4", + "packages/reflex-components-ui/src/reflex_components_ui/components/_group.pyi": "817a2b853123734c7e200bc54a55c47a", + "packages/reflex-components-ui/src/reflex_components_ui/components/_menu.pyi": "e15ed1f9c79ae63f275581338463ffd9", + "packages/reflex-components-ui/src/reflex_components_ui/components/_sdk.pyi": "555998b790703a343fa967893b0f775f", + "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": "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", + "packages/reflex-components-ui/src/reflex_components_ui/components/card.pyi": "f3a2ccfa6dc14e579c0d9f0974c32e3e", + "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": "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": "388ab56522100c0300a380b8d87fa07a", + "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", + "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", + "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": "0a2118625a2234bea7a57a25da5fcc15", + "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": "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", + "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": "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", + "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": "ceedbdf66b3090ead0cad353d6a4eb1a", + "reflex/__init__.pyi": "540ab90bd8a7a89647f0bdd0a2fa3590", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" } diff --git a/pyproject.toml b/pyproject.toml index 43f486a5a9c..ea5dfb9e479 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", ] @@ -79,6 +79,9 @@ testing = [ "selenium >=4.0.0,<5.0", "uvicorn >=0.34.0,<1.0", ] +# `rx.ui`: components compiled to plain HTML and static CSS. Optional while +# the package is pre-release. +ui = ["reflex-components-ui"] [project.urls] homepage = "https://reflex.dev" @@ -121,6 +124,7 @@ dev = [ "python-dotenv", "pyyaml", "reflex-bench", + "reflex-components-ui", "reflex-docgen", "reflex-otel", "reflex-release", @@ -186,6 +190,9 @@ extraPaths = [ "packages/reflex-react-router/src", "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", @@ -312,7 +319,12 @@ preview = true "docs/package/scripts/*.py" = ["INP001"] "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/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"] @@ -324,13 +336,15 @@ 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", ] [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] @@ -348,6 +362,7 @@ source = [ "reflex_components_react_player", "reflex_components_recharts", "reflex_components_sonner", + "reflex_components_ui", "reflex_base", "reflex_docgen", "reflex_otel", @@ -409,8 +424,9 @@ root-package = "reflex" root-source-dirs = ["reflex"] packages-dir = "packages" package-source-subdirs = ["src"] -# reflex-base embeds the frontend javascript package as its web template. -extra-source-dirs = { reflex-base = ["packages/reflex-frontend/src"] } +# reflex-base embeds the frontend javascript package as its web template, and +# reflex-components-ui the javascript its components are compiled against. +extra-source-dirs = { reflex-base = ["packages/reflex-frontend/src"], reflex-components-ui = ["packages/reflex-components-ui/js/src"] } # Changelog dates and r/pre- branch names are stamped in the project's # home timezone, so an evening release is not dated tomorrow by a UTC runner. release-timezone = "America/Los_Angeles" @@ -553,6 +569,7 @@ reflex-components-radix = false reflex-components-react-player = false reflex-components-recharts = false reflex-components-sonner = false +reflex-components-ui = false reflex-enterprise = false reflex-hosting-cli = false pillow = "2026-10-21T00:00:00Z" @@ -575,6 +592,7 @@ reflex-components-radix.workspace = true reflex-components-react-player.workspace = true reflex-components-recharts.workspace = true reflex-components-sonner.workspace = true +reflex-components-ui.workspace = true reflex-docgen.workspace = true reflex-release.workspace = true reflex-hosting-cli.workspace = true diff --git a/reflex/__init__.py b/reflex/__init__.py index 75cb5a1328b..52da2115eea 100644 --- a/reflex/__init__.py +++ b/reflex/__init__.py @@ -84,6 +84,8 @@ from __future__ import annotations +import importlib + from reflex_base.utils import lazy_loader from reflex_components_radix.mappings import RADIX_MAPPING @@ -247,14 +249,59 @@ "plugins", } _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = _MAPPING -_EXTRA_MAPPINGS: dict[str, str] = _COMPONENT_NAME_TO_PATH -getattr, __dir__, __all__ = lazy_loader.attach( - __name__, - submodules=_SUBMODULES, - submod_attrs=_SUBMOD_ATTRS, - **_EXTRA_MAPPINGS, -) +# `rx.ui` comes from the `ui` extra, which may not be installed. It stays out of +# `attach` so that resolving it goes through `_import_ui`, whose error says what +# to install: a native lazy import (Python 3.15) would raise its own instead. +_EXTRA_MAPPINGS: dict[str, str] = { + **_COMPONENT_NAME_TO_PATH, + "ui": "reflex_components_ui", +} + + +def _attach(): + """Attach the lazy names of the package, and list `ui` beside them. + + Returns: + The lazy ``__getattr__``, and the ``__dir__`` and ``__all__`` of the package. + """ + lazy_getattr, _, names = lazy_loader.attach( + __name__, + submodules=_SUBMODULES, + submod_attrs=_SUBMOD_ATTRS, + **_COMPONENT_NAME_TO_PATH, + ) + names.append("ui") + return lazy_getattr, lambda: names, names + + +getattr, __dir__, __all__ = _attach() + + +def _import_ui(): + """Import the `rx.ui` namespace and cache it on this module. + + Returns: + The reflex_components_ui package. + + Raises: + ModuleNotFoundError: If the `ui` extra is not installed. + """ + package = _EXTRA_MAPPINGS["ui"] + try: + ui = importlib.import_module(package) + except ModuleNotFoundError as err: + if err.name != package: + raise + msg = ( + "`rx.ui` 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()["ui"] = ui + return ui def __getattr__(name: str): + if name == "ui": + return _import_ui() return getattr(name) diff --git a/reflex/app.py b/reflex/app.py index 0800bcf2b10..cd3b8b48570 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -49,7 +49,6 @@ IndividualEventType, _check_not_undecorated_state_method, event_sequence, - noop, ) from reflex_base.event.context import EventContext from reflex_base.event.processor import BaseStateEventProcessor, EventProcessor @@ -78,7 +77,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 +263,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. @@ -489,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} @@ -931,7 +920,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. """ @@ -947,8 +936,12 @@ class App(MiddlewareMixin, LifespanMixin): dataclasses.field( default_factory=lambda: { (55, "ErrorBoundary"): ( - lambda stateful: default_error_boundary( - **({"on_error": noop()} if not stateful else {}) + lambda stateful: ( + default_error_boundary() + if stateful + # No event of Reflex, so the root loads no event runtime. + # The stub of the component leaves its private members out. + else ErrorBoundary._create_without_state() # pyright: ignore[reportAttributeAccessIssue] ) ), (5, "Overlay"): ( @@ -1034,7 +1027,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 @@ -2154,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}" @@ -2168,7 +2171,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..c9dc01f6c49 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,8 +34,9 @@ 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.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 @@ -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" @@ -165,8 +175,54 @@ def _get_window_libraries() -> list[tuple[str, str]]: return window_libraries +def _split_window_libraries( + dynamic_components: bool, + stateful: bool = True, +) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]: + """Split the bundled libraries into those root.jsx imports and those it defers. + + 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. Emotion is deferred like any + other: a dynamic component loads it when it renders a ``css`` prop. The + event runtime is left out of the root of an app without state, unless it + renders a dynamic component: a page loads it with its event handlers. + + Args: + dynamic_components: Whether the app renders a dynamic component. + stateful: Whether the app has state. + + Returns: + The eagerly imported libraries and the lazily loaded libraries, each + as aliases paired with module paths. + """ + window_libraries = _get_window_libraries() + if not (stateful or dynamic_components): + state = f"$/{constants.Dirs.STATE_PATH}" + window_libraries = [ + library for library in window_libraries if library[1] != state + ] + if not get_config().frontend_lazy_bundled_libraries: + return window_libraries, [] + core_libraries = set(_eager_bundled_libraries()) + explicit_libraries = ( + RegistrationContext.ensure_context()._explicit_bundled_libraries + ) + eager: list[tuple[str, str]] = [] + lazy: list[tuple[str, str]] = [] + for library in window_libraries: + if library[1] in core_libraries: + eager.append(library) + elif dynamic_components or library[1] in explicit_libraries: + lazy.append(library) + return eager, lazy + + def _compile_app( - app_root: Component, hydrate_fallback_export: str | None = None + app_root: Component, + hydrate_fallback_export: str | None = None, + dynamic_components: bool = True, + stateful: bool = True, ) -> str: """Compile the app template component. @@ -174,20 +230,15 @@ def _compile_app( app_root: The app root to compile. hydrate_fallback_export: The exported name of the hydrate-fallback memo component to re-export as ``HydrateFallback``, or None for no fallback. + dynamic_components: Whether the app renders a dynamic component. + stateful: Whether the app has state. Returns: The compiled app. """ - window_libraries = _get_window_libraries() - lazy_window_libraries = [] - if get_config().frontend_lazy_bundled_libraries: - core_libraries = set(_default_bundled_libraries()) - lazy_window_libraries = [ - library for library in window_libraries if library[1] not in core_libraries - ] - window_libraries = [ - library for library in window_libraries if library[1] in core_libraries - ] + window_libraries, lazy_window_libraries = _split_window_libraries( + dynamic_components, stateful + ) app_root_imports = app_root._get_all_imports() _apply_common_imports(app_root_imports) @@ -220,8 +271,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. @@ -229,6 +281,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) @@ -237,7 +290,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( @@ -515,16 +578,44 @@ def add_function( _extend_imports_in_place(self.imports, memo_imports) -# Imports every memo module needs regardless of its body: ``isTrue`` for prop -# coercion. The component wrapper import (``memo`` from React by default) -# rides on each definition's ``wrapper`` var data instead, so a module whose -# memos swap or drop the default wrapper doesn't import it. Shared by the -# grouped and un-mirrored compile paths so they can't drift apart. +# Imports a memo module needs whatever its body: ``isTrue`` for prop +# coercion, when the module calls it. The component wrapper import (``memo`` +# from React by default) rides on each definition's ``wrapper`` var data +# instead, so a module whose memos swap or drop the default wrapper doesn't +# import it. Shared by the grouped and un-mirrored compile paths so they can't +# drift apart. _MEMO_BASE_IMPORTS: dict[str, list[ImportVar]] = { f"$/{constants.Dirs.STATE_PATH}": [ImportVar(tag="isTrue")], } +def _render_memo_module( + render: Callable[[dict[str, list[ImportVar]]], str], + imports: dict[str, list[ImportVar]], +) -> tuple[str, dict[str, list[ImportVar]]]: + """Render a memo module, importing ``isTrue`` only when it calls it. + + An import of the event runtime the module does not use would load it into + the pages of an app without state, so it is added only when the code calls + it without the var data of its body having imported it already. + + Args: + render: Renders the module from its imports. + imports: The imports of its body, with the common imports applied. + + Returns: + The code of the module and the imports it was rendered with. + """ + code = render(imports) + state = f"$/{constants.Dirs.STATE_PATH}" + if "isTrue(" in code and not any( + imported.tag == "isTrue" for imported in imports.get(state, ()) + ): + imports = utils.merge_imports(_MEMO_BASE_IMPORTS, imports) + code = render(imports) + return code, imports + + def _compile_memo_components( memos: Iterable[MemoDefinition] = (), ) -> tuple[list[tuple[str, str]], dict[str, list[ImportVar]]]: @@ -609,14 +700,17 @@ def _emit_unmirrored( # Importing from the same file would shadow the module's own exports. self_specifier = memo_paths.mirrored_library_specifier(segments) group.imports.pop(self_specifier, None) - merged_imports = utils.merge_imports(_MEMO_BASE_IMPORTS, group.imports) + merged_imports = utils.merge_imports(group.imports) _apply_common_imports(merged_imports) - code = templates.memo_components_template( - imports=utils.compile_imports(merged_imports), - components=group.components, - functions=group.functions, - dynamic_imports=sorted(set(group.dynamic_imports)), - custom_codes=list(dict.fromkeys(group.custom_code)), + code, _ = _render_memo_module( + lambda imports, group=group: templates.memo_components_template( + imports=utils.compile_imports(imports), + components=group.components, + functions=group.functions, + dynamic_imports=sorted(set(group.dynamic_imports)), + custom_codes=list(dict.fromkeys(group.custom_code)), + ), + merged_imports, ) output_files.append((module_path, code)) _extend_imports_in_place(aggregate_imports, group.imports) @@ -638,15 +732,17 @@ def _compile_single_memo_component( Returns: The file contents and the full import dict used to compile it. """ - imports = utils.merge_imports(_MEMO_BASE_IMPORTS, component_imports) + imports = utils.merge_imports(component_imports) _apply_common_imports(imports) - code = templates.memo_single_component_template( - imports=utils.compile_imports(imports), - component=component_render, - dynamic_imports=sorted(component_render.get("dynamic_imports", []) or []), - custom_codes=component_render.get("custom_code", []) or [], + return _render_memo_module( + lambda imports: templates.memo_single_component_template( + imports=utils.compile_imports(imports), + component=component_render, + dynamic_imports=sorted(component_render.get("dynamic_imports", []) or []), + custom_codes=component_render.get("custom_code", []) or [], + ), + imports, ) - return code, imports def _compile_single_memo_function( @@ -720,7 +816,11 @@ def compile_document_root( def compile_app_root( - app_root: Component, hydrate_fallback_export: str | None = None + app_root: Component, + hydrate_fallback_export: str | None = None, + *, + dynamic_components: bool = True, + stateful: bool = True, ) -> tuple[str, str]: """Compile the app root. @@ -728,6 +828,11 @@ def compile_app_root( app_root: The app root component to compile. hydrate_fallback_export: The exported name of the hydrate-fallback memo component to re-export as ``HydrateFallback``, or None for no fallback. + dynamic_components: Whether the app renders a dynamic component. Without + one, only the libraries the app registered itself are made available + to load. + stateful: Whether the app has state. Without it, and without a dynamic + component, the root does not load the event runtime. Returns: The path and code of the compiled app wrapper. @@ -738,10 +843,31 @@ def compile_app_root( ) # Compile the document root. - code = _compile_app(app_root, hydrate_fallback_export) + code = _compile_app(app_root, hydrate_fallback_export, dynamic_components, stateful) return output_path, code +def compile_dynamic_libraries( + *, dynamic_components: bool = True +) -> list[tuple[str, str]]: + """Compile the modules the app root loads dynamic-component libraries from. + + Args: + dynamic_components: Whether the app renders a dynamic component. + + Returns: + The path and code of the module of each lazily loaded library. + """ + output_dir = get_web_dir() / constants.Dirs.DYNAMIC_LIBRARIES_PATH + return [ + ( + str(output_dir / (alias + constants.Ext.JS)), + templates.dynamic_library_template(library), + ) + for alias, library in _split_window_libraries(dynamic_components)[1] + ] + + def compile_theme(style: ComponentStyle) -> tuple[str, str]: """Compile the theme. @@ -862,6 +988,8 @@ def purge_web_pages_dir(): if TYPE_CHECKING: + from reflex_components_ui.plugin import UIPlugin + from reflex.app import App, ComponentCallable, UnevaluatedPage @@ -1071,6 +1199,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.REFS_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 +1437,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 +1447,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 @@ -1592,7 +1931,22 @@ def add_save_task( ]) progress.advance(task) - compile_results.append(compile_app_root(app_root, hydrate_fallback_export)) + # A dynamic component is evaluated by evalReactComponent, wherever it renders. + dynamic_components = any( + field.tag == "evalReactComponent" + for field in all_imports.get(f"$/{constants.Dirs.STATE_PATH}", ()) + ) + compile_results.extend( + compile_dynamic_libraries(dynamic_components=dynamic_components) + ) + compile_results.append( + compile_app_root( + app_root, + hydrate_fallback_export, + dynamic_components=dynamic_components, + stateful=app._state is not None, + ) + ) progress.advance(task) progress.stop() diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index e0b490938b3..7b1a5825be1 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, @@ -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(): @@ -277,7 +313,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/reflex/plugins/__init__.py b/reflex/plugins/__init__.py index ba9c0775f54..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, @@ -14,6 +16,7 @@ SitemapPlugin, TailwindV3Plugin, TailwindV4Plugin, + VitePluginEntry, _ScreenshotPlugin, embed, get_plugin, @@ -23,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", @@ -38,6 +47,7 @@ "SitemapPlugin", "TailwindV3Plugin", "TailwindV4Plugin", + "VitePluginEntry", "_ScreenshotPlugin", "embed", "get_plugin", @@ -45,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/reflex/utils/frontend_skeleton.py b/reflex/utils/frontend_skeleton.py index c32e1f0e893..fd7990806be 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 Iterable, 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,72 @@ 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" + ) + if not isinstance(entry.imports, Iterable): + return ( + f"has imports={entry.imports!r}, which must be a sequence of import " + "statements" + ) + 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 +718,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/scripts/hash_examples.py b/scripts/hash_examples.py index f9f5ac56d04..2599665609e 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,15 @@ 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") +PLAYGROUND_DIR = EXAMPLES_DIR / "playground" 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 +80,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 +89,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/scripts/make_pyi.py b/scripts/make_pyi.py index 4d1c00b9830..8ca89a16671 100644 --- a/scripts/make_pyi.py +++ b/scripts/make_pyi.py @@ -30,6 +30,7 @@ "packages/reflex-components-react-player/src/reflex_components_react_player", "packages/reflex-components-recharts/src/reflex_components_recharts", "packages/reflex-components-sonner/src/reflex_components_sonner", + "packages/reflex-components-ui/src/reflex_components_ui", ] diff --git a/scripts/ui_parity.py b/scripts/ui_parity.py new file mode 100644 index 00000000000..b625f6cd2d9 --- /dev/null +++ b/scripts/ui_parity.py @@ -0,0 +1,165 @@ +"""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 + uv run python scripts/ui_parity.py --fonts "Liberation Sans" "Liberation Mono" + the look in other fonts than the theme's + uv run python scripts/ui_parity.py --shard 2/3 one of three shards, as a CI job runs it + uv run python scripts/ui_parity.py --save-seconds every component, then record the + seconds the shards are balanced by + uv run python scripts/ui_parity.py --merge A B C --report OUT + one report from the shards' reports + +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 json +import os +import subprocess +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).parents[1] +PARITY = REPO_ROOT / "packages" / "reflex-components-ui" / "parity" +DEFAULT_REPORT = PARITY / "report" +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, 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(["test_run_time", *selected])] + return command + extra + + +def main(argv: list[str] | None = None) -> int: + """Run the harness, print the intended differences, or merge shards' reports. + + Args: + argv: The command line, without the program name. + + Returns: + The exit code: that of pytest, or 0 when nothing ran. + """ + parser = argparse.ArgumentParser( + prog=Path(__file__).name, 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: {DEFAULT_REPORT})", + ) + parser.add_argument( + "--fonts", + nargs=2, + metavar=("TEXT", "CODE"), + help="installed font families both systems render text and code in", + ) + parser.add_argument( + "--shard", + metavar="INDEX/COUNT", + help="check one shard of the components, e.g. 2/3 (default: all of them)", + ) + parser.add_argument( + "--save-seconds", + action="store_true", + help="after a run of every component in Chromium, record its seconds for the shards", + ) + parser.add_argument( + "--merge", + nargs="+", + type=Path, + metavar="DIR", + help="assemble the report from the reports of shards, and run nothing", + ) + args, extra = parser.parse_known_args(argv) + sys.path.insert(0, str(PARITY)) + from ui_parity import allowlist, report, shards + + report_dir = (args.report or DEFAULT_REPORT).resolve() + if args.merge: + print(report.merge(args.merge, report_dir)) + return 0 + if args.components == [DIFFERENCES]: + print(allowlist.differences_markdown(allowlist.load())) + return 0 + engines: list[str] = ( + list(ENGINES) if args.all_engines else args.engine or [ENGINES[0]] + ) + if args.shard is not None: + if args.components: + parser.error("--shard checks a shard of every component: name none") + try: + shards.parse(args.shard) + except ValueError as exc: + parser.error(str(exc)) + if args.save_seconds and (args.components or args.shard or engines != ["chromium"]): + parser.error( + "--save-seconds records a run of every component in Chromium alone" + ) + env = dict(os.environ) + if args.report is not None: + env["UI_PARITY_REPORT"] = str(report_dir) + if args.fonts is not None: + env["UI_PARITY_FONTS"] = "|".join(args.fonts) + env.pop(shards.ENV, None) + if args.shard is not None: + env[shards.ENV] = args.shard + code = subprocess.run( + pytest_command(args.components, engines, extra), + cwd=REPO_ROOT, + env=env, + check=False, + ).returncode + timings = report_dir / report.TIMINGS + if args.save_seconds and timings.exists(): + seconds = json.loads(timings.read_text())["seconds"] + print( + f"recorded the seconds of the run in {shards.save(shards.from_timings(seconds))}" + ) + return code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/integration/tests_playwright/test_dynamic_components.py b/tests/integration/tests_playwright/test_dynamic_components.py index bf7e55a3c9f..64c026265f2 100644 --- a/tests/integration/tests_playwright/test_dynamic_components.py +++ b/tests/integration/tests_playwright/test_dynamic_components.py @@ -55,7 +55,7 @@ def client_token_component(self) -> rx.Component: rx.el.input( custom_attrs={"id": "token"}, value=self.router.session.client_token, - is_read_only=True, + read_only=True, ), rx.button( "Update", @@ -171,13 +171,16 @@ def lazy_bundled_libraries(request: pytest.FixtureRequest) -> bool: @pytest.fixture(scope="module") def dynamic_components( - tmp_path_factory, lazy_bundled_libraries: bool + tmp_path_factory, + lazy_bundled_libraries: bool, + app_harness_env: type[AppHarness], ) -> Generator[AppHarness, None, None]: """Start VarOperations app at tmp_path via AppHarness. Args: tmp_path_factory: pytest tmp_path_factory fixture lazy_bundled_libraries: whether optional libraries load on demand + app_harness_env: the harness class, for a dev or a production frontend Yields: The running app harness. @@ -186,7 +189,7 @@ def dynamic_components( monkeypatch.setenv( "REFLEX_FRONTEND_LAZY_BUNDLED_LIBRARIES", str(lazy_bundled_libraries) ) - with AppHarness.create( + with app_harness_env.create( root=tmp_path_factory.mktemp("dynamic_components"), app_source=DynamicComponents, ) as harness: @@ -211,6 +214,23 @@ def test_dynamic_components( lazy_bundled_libraries: whether lazy loading of bundled libraries is enabled. """ banana = "lucide-react/dist/esm/icons/banana.mjs" + errors: list[str] = [] + radix_requests: list[str] = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.on( + "console", + lambda message: ( + errors.append(message.text) if message.type == "error" else None + ), + ) + page.on( + "request", + lambda request: ( + radix_requests.append(request.url) + if "/radix_ui_themes" in request.url + else None + ), + ) assert dynamic_components.frontend_url is not None page.goto(dynamic_components.frontend_url) expect(page.locator("#token")).not_to_have_value("", timeout=15_000) @@ -258,3 +278,8 @@ def test_dynamic_components( expect(page.locator("#initial-icon")).to_be_attached() page.locator("#activate").click() expect(page.locator("#delayed-icon")).to_be_attached() + # Every dynamic component on the page shares one fetch of the Radix module + # (in production, the chunk built from it), + # however many mount at once or are evaluated again later. + assert len(radix_requests) == (1 if lazy_bundled_libraries else 0) + assert errors == [] 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/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..39622fd720e --- /dev/null +++ b/tests/integration/tests_playwright/test_scripts_after_first_paint.py @@ -0,0 +1,240 @@ +"""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 +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 +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), + rx.el.button("Toggle", id="toggle", on_click=rx.toggle_color_mode), + *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" + # 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" + '' + 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") + + +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") diff --git a/tests/integration/tests_playwright/test_stateless_app.py b/tests/integration/tests_playwright/test_stateless_app.py index ef566819f48..455ad7adc49 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,91 @@ 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, + holds_event_runtime, + 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("/")), + ) + + def quiet(): + """A page with no event handler: an element with an id, and a link. + + Returns: + The page. + """ + return rx.el.div( + rx.heading("A quiet page"), + rx.el.section("Docs", id="docs"), + rx.el.a("Home", href="/", id="home"), + ) app = rx.App(enable_state=False) app.add_page(index) + app.add_page(other, route="/other") + app.add_page(quiet, route="/quiet") @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 +120,129 @@ 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_a_page_without_event_handlers_loads_no_event_runtime( + stateless_app: AppHarness, page: Page +): + """A page with no event handler loads no event runtime; the next page does. + + Its link leads, without a reload, to a page whose client-side handlers + load the runtime and run. + + Args: + stateless_app: A harness for testing the stateless app. + page: A Playwright page. + """ + assert stateless_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(stateless_app.frontend_url.rstrip("/") + "/quiet") + expect(page.get_by_role("heading")).to_have_text("A quiet page") + page.wait_for_load_state("networkidle") + assert scripts + assert holds_event_runtime(scripts) is False + + page.locator("#home").click() + expect(page.get_by_role("heading")).to_have_text("This is a stateless app") + expect(page.locator("#count")).to_have_text("0") + page.locator("#count").click() + expect(page.locator("#count")).to_have_text("1") + page.locator("#fill").click() + expect(page.locator("#field")).to_have_value("filled in") + assert holds_event_runtime(scripts) is True + assert page_errors == [] + + +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/tests_playwright/test_ui_components.py b/tests/integration/tests_playwright/test_ui_components.py new file mode 100644 index 00000000000..3aadabd70d0 --- /dev/null +++ b/tests/integration/tests_playwright/test_ui_components.py @@ -0,0 +1,2230 @@ +"""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. 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, 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 + +# 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 = '"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. + "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 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;", +] + +# 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_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;", +] + +# 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;", +] + + +# 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_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_046b512a21_c = stylex.props(sx_046b512a21.s).className;", + ( + 'const sx_046b512a21_0 = { __proto__: null, "true": stylex.props(sx_0' + "46b512a21.a0_0).className };" + ), + ( + '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_16addd9092_c = stylex.props(sx_16addd9092.s).className;", + ( + '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", "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_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' + '", "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. +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__/" + + +# What the page of the form controls declares for the components bound to +# state: a text field, and the parts of a select. +CONTROLS_MEMO_DECLARATIONS = [ + ( + 'const sx_ff3fb9d45c = stylex.create({ s: {"display": {"default": "flex",' + ' ":has(> input:is([hidden], [type=\'hidden\' i]))": "none"}, "alignItems":' + ' "stretch", "fontFamily": "var(--default-font-family)", "fontWeight": "v' + 'ar(--font-weight-regular)", "fontStyle": "normal", "textAlign": "start",' + ' "boxSizing": "border-box", "height": "var(--text-field-height)", "paddi' + 'ng": "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-fie' + 'ld-focus-color)"}, "outlineOffset": {":has(> :is(input, textarea):focus)' + '": "-1px"}, "backgroundColor": {"default": "var(--color-surface)", "::se' + 'lection": "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-pad' + 'ding)", ":has(> [data-side=\'left\'])": "0"}, "--rx-text-field-padding-rig' + 'ht": {"default": "var(--text-field-padding)", ":has(> [data-side=\'right\'' + '])": "0"}, "--rx-text-field-radius-left": {"default": "calc(var(--text-f' + 'ield-border-radius) - var(--text-field-border-width))", ":has(> [data-si' + 'de=\'left\'])": "0"}, "--rx-text-field-radius-right": {"default": "calc(va' + 'r(--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):placeho' + 'lder-shown)": "var(--cursor-disabled)"}, "--text-field-height": "var(--s' + 'pace-6)", "--text-field-padding": "calc(var(--space-2) - var(--text-fiel' + 'd-border-width))", "--text-field-border-radius": "max(var(--radius-2), v' + 'ar(--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-slo' + 't-padding": "var(--space-2)", "--text-field-selection-color": {"default"' + ': "var(--focus-a5)", ":has(> :is(input, textarea):is(:disabled, :read-on' + 'ly))": "var(--gray-a5)"}, "--text-field-focus-color": {"default": "var(-' + '-focus-8)", ":has(> :is(input, textarea):is(:disabled, :read-only))": "v' + 'ar(--gray-8)"}, "--text-field-border-width": "1px", "color": "var(--gray' + '-12)", "--rx-text-field-slot-color": "var(--gray-a11)", "boxShadow": {"d' + 'efault": "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(--foc' + 'us-a5), inset 0 0 0 1px var(--gray-a5)"}, "backgroundImage": {":has(> :i' + 's(input, textarea):is(:disabled, :read-only))": "linear-gradient(var(--g' + 'ray-a2), var(--gray-a2))", ":has(> :is(input, textarea):autofill:not(:is' + '(:disabled, :read-only)))": "linear-gradient(var(--focus-a2), var(--focu' + 's-a2))"}, "backgroundClip": "content-box"} });' + ), + "const sx_ff3fb9d45c_c = stylex.props(sx_ff3fb9d45c.s).className;", + ( + 'const sx_345c25de08 = stylex.create({ s: {"appearance": {"default": "non' + 'e", "[type=\'number\']": "textfield", "::-webkit-inner-spin-button": "none' + '", "::-webkit-search-cancel-button": "none"}, "marginTop": "0", "marginR' + 'ight": {"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", "b' + 'orderBottomWidth": "0", "borderLeftWidth": "0", "borderTopStyle": "none"' + ', "borderRightStyle": "none", "borderBottomStyle": "none", "borderLeftSt' + 'yle": "none", "backgroundColor": {"default": "transparent", "::selection' + '": "var(--text-field-selection-color)"}, "backgroundImage": "none", "box' + 'Sizing": {"default": "border-box", "::-webkit-calendar-picker-indicator"' + ': "content-box"}, "color": {"default": "inherit", ":is(:disabled, :read-' + 'only)": "var(--gray-a11)", "::placeholder": "var(--gray-a10)"}, "fontFam' + 'ily": "inherit", "fontSize": "inherit", "fontWeight": "normal", "fontSty' + 'le": "normal", "lineHeight": "inherit", "letterSpacing": "inherit", "tex' + 'tTransform": "inherit", "wordSpacing": "inherit", "outlineStyle": "none"' + ', "outlineWidth": "medium", "outlineColor": "currentcolor", "outlineOffs' + 'et": "0", "whiteSpace": "pre-wrap", "WebkitTapHighlightColor": "transpar' + 'ent", "cursor": {"default": "text", ":is(:disabled, :read-only):placehol' + 'der-shown": "var(--cursor-disabled)"}, "WebkitTextFillColor": {":is(:dis' + 'abled, :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": "cen' + 'ter", "textAlign": "inherit", "borderRadius": {"::-webkit-calendar-picke' + 'r-indicator": "calc(var(--text-field-border-radius) - 2px)"}, "borderTop' + 'LeftRadius": "var(--rx-text-field-radius-left)", "borderBottomLeftRadius' + '": "var(--rx-text-field-radius-left)", "borderTopRightRadius": "var(--rx' + '-text-field-radius-right)", "borderBottomRightRadius": "var(--rx-text-fi' + 'eld-radius-right)", "textIndent": {"default": "var(--rx-text-field-inden' + "t)\", \":is([type='date'], [type='datetime-local'], [type='time'], [type='" + 'week\'], [type=\'month\'])": "0"}, "paddingTop": {"default": "0", "::-webki' + 't-calendar-picker-indicator": "var(--space-1)"}, "paddingLeft": {"defaul' + "t\": \"0\", \":is([type='date'], [type='datetime-local'], [type='time'], [ty" + "pe='week'], [type='month'])\": \"var(--rx-text-field-padding-left)\", \"::-w" + 'ebkit-calendar-picker-indicator": "var(--space-1)"}, "paddingRight": {"d' + "efault\": \"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-ind' + 'icator": "var(--space-1)"}, "backgroundClip": {":autofill": "text"}, "us' + 'erSelect": {"::placeholder": "none"}, "opacity": {"::placeholder": {"def' + 'ault": 1, ":is(:disabled, :read-only)": 0.5}}} });' + ), + "const sx_345c25de08_c = stylex.props(sx_345c25de08.s).className;", + 'const sx_5073704993 = stylex.create({ s: {"width": "100%"} });', + "const sx_5073704993_c = stylex.props(sx_5073704993.s).className;", +] + + +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 typing import Any, ClassVar, Literal + + from reflex_components_ui import _radix_tokens + from reflex_components_ui.base import UIComponent + from reflex_components_ui.style import ComponentStyles + + import reflex as rx + + tokens = rx.ui.tokens + + 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"]] + + 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"), + 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"}) + + 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"), + 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), + ) + + # 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: list[dict[str, Any]] = [ + {**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: 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( + rx.theme(id=f"radix-{index}", custom_attrs=label, **options) + ) + # 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( + 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", + ), + ) + + 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 }") + + 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", + ), + # The child is bound to state, and stays the element all the same. + rx.ui.flex( + rx.ui.text(StyleState.tone, size="5", id="slot"), + as_child=True, + direction="column", + ), + 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) + initials: rx.Field[str] = rx.field("A") + + @rx.event + def start(self): + """Start loading.""" + self.busy = True + self.initials = "AB" + + @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.ui.avatar(fallback=ActionState.initials, size="4", id="bound"), + 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"), + ), + ), + ) + + class ControlState(rx.State): + """What the form controls are bound to.""" + + name: rx.Field[str] = rx.field("Ada") + plan: rx.Field[str] = rx.field("Free") + submitted: rx.Field[dict[str, Any]] = rx.field(default_factory=dict) + + @rx.event + def set_name(self, name: str): + """Follow the text field. + + Args: + name: What it holds. + """ + self.name = name + + @rx.event + def set_plan(self, plan: str): + """Follow the select. + + Args: + plan: The chosen option. + """ + self.plan = plan + + @rx.event + def submit(self, data: dict[str, Any]): + """Keep what the form submitted. + + Args: + data: The values of the form. + """ + self.submitted = data + + def controls(): + cards, boxes = rx.ui.radio_cards, rx.ui.checkbox_cards + return rx.el.main( + rx.ui.form.root( + # A text field and a select bound to state. + rx.ui.input( + name="name", + value=ControlState.name, + on_change=ControlState.set_name, + id="name", + ), + rx.ui.select( + ["Free", "Pro"], + name="plan", + value=ControlState.plan, + on_change=ControlState.set_plan, + id="plan", + ), + rx.ui.text_area(name="notes", default_value="None", id="notes"), + rx.ui.checkbox("Agree", name="agree", default_checked=True, id="agree"), + # 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"), + rx.ui.checkbox_group.item("Egg", value="egg"), + name="toppings", + default_value=["egg"], + ), + cards.root( + cards.item("S", value="s"), + cards.item("M", value="m"), + name="size", + default_value="m", + ), + boxes.root(boxes.item("Gift", value="gift"), name="extras"), + rx.ui.segmented_control.root( + rx.ui.segmented_control.item("List", value="list"), + rx.ui.segmented_control.item("Grid", value="grid"), + default_value="grid", + id="view", + ), + rx.ui.slider(name="volume", default_value=[30], id="volume"), + rx.el.button("Send", id="send"), + on_submit=ControlState.submit, + id="form", + ), + # Typing waits for the page to be hydrated. + rx.el.span(rx.cond(rx.State.is_hydrated, "ready", "loading"), id="ready"), + rx.el.span(ControlState.name, id="name-value"), + rx.el.span(ControlState.submitted.to_string(), id="submitted"), + ) + + def overlays(): + tabs = rx.ui.tabs + return rx.el.main( + # Panels an app lays out: the one that is not selected stays hidden. + tabs.root( + tabs.list( + tabs.trigger("First", value="first"), + tabs.trigger("Second", value="second"), + ), + tabs.content("One", value="first", display="flex", id="first-panel"), + tabs.content("Two", value="second", display="flex", id="second-panel"), + default_value="first", + ), + # 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."), + 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", + ), + # 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")), + ), + ), + ), + # 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")), + ), + ), + ), + # 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"), + ) + + def panel(): + return rx.el.main( + rx.ui.theme_panel(), + rx.ui.box( + id="panel-probe", + background_color=tokens.accent[9], + color=tokens.gray[11], + border_top_left_radius=tokens.radius[3], + width=tokens.space[5], + height=tokens.space[5], + ), + rx.ui.color_mode.button(id="mode-button", position="bottom-left"), + rx.ui.color_mode.switch(id="mode-switch"), + rx.el.span(rx.cond(rx.State.is_hydrated, "ready", "loading"), id="ready"), + ) + + # 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(actions, route="/actions") + app.add_page(controls, route="/controls") + app.add_page(overlays, route="/overlays") + app.add_page(panel, route="/panel") + app.add_page(literal, route="/literal") + app.add_page(styled, route="/styled") + 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" + 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, # pyright: ignore [reportArgumentType] + gray_color="slate", + 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), + ) + + app.add_page(bound, route="/bound") + + config = rx.config.get_config() + 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()) + + +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_{'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=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. + + 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, elements: dict[str, dict[str, str]] +) -> dict[str, dict[str, str]]: + """Read the computed style of elements of the page. + + Args: + page: A page of the app. + elements: The properties to read, as the keys of a dict, by element id. + + Returns: + The properties as the browser computed them, by element id. + """ + return page.evaluate( + """(elements) => Object.fromEntries( + Object.entries(elements).map(([id, properties]) => { + const style = getComputedStyle(document.getElementById(id)); + return [ + id, + Object.fromEntries( + Object.keys(properties).map((name) => [ + name, + style.getPropertyValue(name), + ]), + ), + ]; + }), + )""", + elements, + ) + + +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) == 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) == 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 _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") == [ + *WAVE_MEMO_DECLARATIONS, + *ACTIONS_MEMO_DECLARATIONS, + *CONTROLS_MEMO_DECLARATIONS, + *PANEL_MEMO_DECLARATIONS, + *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 + 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 + # 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 = _scripts(prod_app) + literal_chunks = [name for name in scripts if name.startswith("assets/_literal_")] + assert len(literal_chunks) == 1, sorted(scripts) + # 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 + ] + + +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: 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 name.startswith(("assets/_literal_", "assets/_styled_", "assets/_index")) + and "$$css" in code + ] == [] + # The table of the variant, in the chunk that renders the element: the + # 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\}", + table, + ), 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. + + 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 + + +# 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, + ]; + })""" + ) + # 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 == [ + # 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") +] + +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) == [] + assert _sweep_differences(radix, alone) == [] + + +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") + + +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", + ] + # 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)"], + } + + +# 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 + 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}) + 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 + + +# 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]] + + # 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. + # So do the letters of an avatar, sized by how many they are. + bound = page.locator("#bound > span") + expect(bound).to_have_text("A") + expect(bound).to_have_css("font-size", "20px") + assert save.is_enabled() + save.click() + expect(bound).to_have_text("AB") + expect(bound).to_have_css("font-size", "18px") + 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") + + +# What the page of the form controls computes to, by id. +CONTROLS = { + "name": {"height": "30px", "font-size": "14px"}, + "plan": {"height": "32px", "padding-left": "12px"}, + "notes": {"padding-top": "5px", "resize": "none"}, + "agree": {"width": "16px", "height": "20px"}, + "alerts": {"width": "35px", "height": "20px"}, + "view": {"height": "32px", "display": "inline-grid"}, +} + + +def test_form_controls_work_in_an_app(ui_app: AppHarness, page: Page): + """The form controls work in a real app, in dev and prod.""" + assert ui_app.frontend_url is not None + page.goto(ui_app.frontend_url.rstrip("/") + "/controls") + expect(page.locator("#ready")).to_have_text("ready") + name = page.locator("#name") + expect(name).to_have_value("Ada") + assert _computed_styles(page, CONTROLS) == CONTROLS + + # A text field bound to state follows what is typed, and the state it. + name.press("End") + name.press_sequentially(" L") + expect(page.locator("#name-value")).to_have_text("Ada L") + expect(name).to_have_value("Ada L") + + # The select opens a native popover, and its script chooses an option. + plan = page.locator("#plan") + expect(plan).to_have_text("Free") + plan.click() + page.get_by_role("option", name="Pro").click() + expect(plan).to_have_text("Pro") + expect(page.get_by_role("listbox")).to_be_hidden() + + # Native inputs: a click, and the keys of the browser. + 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. + page.locator("#view").get_by_text("List").first.click(force=True) + 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() + expect(page.locator("#submitted")).to_have_text( + '{"name":"Ada L","plan":"Pro","notes":"None","agree":true,"alerts":true,' + '"letter":"b","toppings":"egg","size":"s","extras":"gift","volume":"31"}' + ) + + +def test_overlays_and_disclosure_work_in_an_app(ui_app: AppHarness, page: Page): + """The overlays, the tabs and the accordion work in a real app, in dev and prod.""" + assert ui_app.frontend_url is not None + 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 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") + 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 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_count(0) + page.get_by_role("tab", name="Second").click() + expect(first).to_have_count(0) + expect(second).to_have_css("display", "flex") + page.keyboard.press("ArrowLeft") + expect(first).to_be_visible() + expect(page.get_by_role("tab", name="First")).to_be_focused() + + # 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("[aria-expanded=true]")).to_have_count(2) + expect(faq.get_by_text("Two days.")).to_be_visible() + # 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("[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. + 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; + # 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") + 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("[data-slot=hover-card-content][data-open]")).to_have_text( + "Writes things" + ) + + +def _panel_probe(page: Page) -> list[str]: + """Read what the probe of the panel page takes from the theme of the app. + + Args: + page: A page showing the panel page. + + Returns: + The accent, the gray, the radius and the scaling, as computed values. + """ + return page.locator("#panel-probe").evaluate( + """(probe) => { + const style = getComputedStyle(probe); + return [style.backgroundColor, style.color, style.borderTopLeftRadius, + style.width]; + }""" + ) + + +def test_theme_panel_and_color_mode_controls_work_in_an_app( + ui_app: AppHarness, page: Page +): + """The color mode controls drive the app, and the panel its theme, in dev and prod.""" + assert ui_app.frontend_url is not None + page.goto(ui_app.frontend_url.rstrip("/") + "/panel") + expect(page.locator("#ready")).to_have_text("ready") + html = page.locator("html") + + # The button toggles the color mode, the switch follows it, and the mode + # outlives a reload. + expect(html).to_have_class("light") + expect(page.locator("#mode-switch")).not_to_be_checked() + page.locator("#mode-button").click() + expect(html).to_have_class("dark") + expect(page.locator("#mode-switch")).to_be_checked() + page.reload() + expect(page.locator("#ready")).to_have_text("ready") + expect(html).to_have_class("dark") + page.locator("#mode-switch").click() + expect(html).to_have_class("light") + + # The panel shows the theme of the app, and changes it. + panel = page.locator("[data-rx-theme-panel=panel]") + expect(panel.locator("input[name=accentColor][value=indigo]")).to_be_checked() + expect(panel.locator("input[name=radius][value=large]")).to_be_checked() + assert _panel_probe(page) == [ + "rgb(62, 99, 221)", + "rgb(96, 100, 108)", + "9px", + "24px", + ] + panel.locator("input[name=accentColor][value=red]").click() + panel.locator("input[name=radius][value=none]").click() + panel.locator("input[name=scaling][value='90%']").click() + assert _panel_probe(page) == [ + "rgb(229, 72, 77)", + "rgb(101, 99, 109)", + "0px", + "21.5938px", + ] + panel.locator("input[name=appearance][value=dark]").click() + expect(html).to_have_class("dark") + assert _panel_probe(page)[:2] == ["rgb(229, 72, 77)", "rgb(181, 178, 188)"] + + # T shows and hides the panel. + page.keyboard.press("t") + 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/integration/tests_playwright/test_ui_parity.py b/tests/integration/tests_playwright/test_ui_parity.py new file mode 100644 index 00000000000..689613dd610 --- /dev/null +++ b/tests/integration/tests_playwright/test_ui_parity.py @@ -0,0 +1,540 @@ +"""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. + +``UI_PARITY_SHARD=/`` checks one shard of the components +(``ui_parity.shards``): the app has their pages alone, and the run time budget +holds for what the shard runs. +""" + +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, shards # 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.hydration import ATTRIBUTE # noqa: E402 +from ui_parity.look import ( # noqa: E402 + READ_SCRIPT, + READY_SCRIPT, + SETTLED_SCRIPT, + StyleDifference, + run_matrix, + use_fonts, +) +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")) +# The fonts the matrices render in instead of the theme's, as "text|code". +FONTS = os.environ.get("UI_PARITY_FONTS") +TIMINGS = report.TIMINGS +# Every component with a matrix or a contract, and those this run checks. +COMPONENTS = list(dict.fromkeys([*MATRICES, *CONTRACTS])) +SELECTED = shards.selected(COMPONENTS) +SHARD = os.environ.get(shards.ENV) or None + +# 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, of the shard.""" + from ui_parity import shards + from ui_parity.app import create_app + from ui_parity.components import CONTRACTS, MATRICES + + import reflex as rx + + every = list(dict.fromkeys([*MATRICES, *CONTRACTS])) + app = create_app(shards.built(shards.selected(every), every)) # 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", [component for component in MATRICES if component in SELECTED] +) +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")), + prepare=use_fonts(*FONTS.split("|")) if FONTS else None, + ) + 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'" + ) + ] + + +# 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)", + "notRendered": "style,script,link,template", + "shapeKey": "(shape)", + } + 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"}, + "(shape)": {"": "0 div"}, + }, + "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 + + +NESTED = """ + + + + + +""" + + +def test_read_reaches_the_elements_inside_the_compared_one(page: Page): + """Each element inside is read by its place, a named part under its name.""" + page.set_content(NESTED) + request = { + "properties": ["display", "isolation"], + "targets": {"reference": None, "candidate": None}, + "parts": {"icon": {"reference": ".icon", "candidate": ".icon"}}, + "only": None, + "matches": None, + "first": ":scope > :not(style):not(script):not(link):not(template)", + "notRendered": "style,script,link,template", + "shapeKey": "(shape)", + } + [frame] = page.evaluate(READ_SCRIPT, request) + assert frame["styles"] == { + "": {"display": "block", "isolation": "auto"}, + "icon": {"display": "inline-block", "isolation": "auto"}, + "> 1": {"display": "inline", "isolation": "isolate"}, + "> 1 > 1": {"display": "inline", "isolation": "auto"}, + "> 2 > 1": {"display": "inline", "isolation": "auto"}, + "> 2 > 2": {"display": "inline", "isolation": "auto"}, + "(shape)": { + "": "2 a", + "> 1": "1 code", + "> 1 > 1": "0 b", + "> 2": "2 span", + "> 2 > 1": "0 i", + "> 2 > 2": "0 i", + }, + } + # The page is still: nothing changes it after it has loaded. + 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() + if component in SELECTED + 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, or of its shard, fit the budget.""" + total = sum(_seconds.values()) + (report_dir / TIMINGS).write_text( + json.dumps( + { + "shard": SHARD, + "budget": BUDGET, + "total": round(total, 3), + "seconds": {name: round(value, 3) for name, value in _seconds.items()}, + }, + indent=2, + ) + + "\n" + ) + run = f"Shard {SHARD} of the parity run" if SHARD else "The parity run" + assert total <= BUDGET, ( + f"{run} took {total:.0f} s, over its budget of {BUDGET:.0f} s: " + f"{_seconds}. Cross fewer dimensions and sweep the rest, or record the " + "times with `scripts/ui_parity.py --save-seconds` to rebalance the shards." + ) diff --git a/tests/integration/utils.py b/tests/integration/utils.py index b4db8a96ce0..7d1ac2ecbed 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,78 @@ 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() + } + + +# A string of utils/state.js that minifying keeps and no other module holds. +EVENT_RUNTIME_MARKER = "//__reflex_evaluate:" + + +def holds_event_runtime(scripts: Mapping[str, str]) -> bool: + """Find whether scripts hold the event runtime, utils/state.js. + + Args: + scripts: The source of each script, by its name or URL. + + Returns: + Whether any script contains it. + """ + return any(EVENT_RUNTIME_MARKER in body for body in scripts.values()) + + +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..ac3a36560cd 100644 --- a/tests/units/compiler/state_js.test.mjs +++ b/tests/units/compiler/state_js.test.mjs @@ -3,13 +3,19 @@ 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, and that +// the registry of refs in utils/refs.js. +const sources = {}; +for (const name of ["state", "event_loop", "socket", "refs"]) { + 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 +245,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 +275,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..e96a4bf1d22 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -5,20 +5,28 @@ import re import shutil import sys +from collections.abc import Sequence from pathlib import Path, PureWindowsPath +from typing import Any, Literal 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.dynamic import ( + _bundle_library, + bundle_library, + reset_bundled_libraries, +) from reflex_base.components.memo import MEMOS 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 from reflex_base.utils.console import PoorProgress from reflex_base.utils.exceptions import ( DynamicRouteArgShadowsStateVarError, @@ -26,18 +34,25 @@ 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 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 from reflex.compiler import compiler, utils 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 +from tests.units.compiler.test_dynamic_components_codegen import ( + app_root_loaders, + loader, +) @pytest.mark.parametrize("with_plugin", [False, True]) @@ -252,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]): @@ -627,8 +652,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 'import * as d3_format from "d3-format";' in code - assert '"d3-format": d3_format' in code + 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 @@ -704,8 +733,14 @@ def test_compile_app_root_uses_unique_window_library_aliases( _, code = compiler.compile_app_root(rx.el.div("hello")) if lazy: - assert '"foo.bar": () => import("foo.bar")' in code - assert '"foo/bar.mjs": () => import("foo/bar.mjs")' in code + loader = ( + ' "{}": () => import("$/utils/dynamic_libraries/{}")' + ".then((module) => module.default)," + ) + lines = code.splitlines() + assert loader.format("foo.bar", "foo_bar") in lines + assert loader.format("foo_bar", "foo_bar_2") in lines + assert loader.format("foo/bar.mjs", "foo_bar_mjs") in lines else: assert 'import * as foo_bar from "foo.bar";' in code assert 'import * as foo_bar_2 from "foo_bar";' in code @@ -737,7 +772,9 @@ def test_compile_app_root_includes_radix_window_library_when_bundled(mocker): """Bundled Radix libraries should be exposed to window.__reflex.""" mocker.patch( "reflex.compiler.compiler.get_config", - return_value=rx.Config(app_name="eager_libraries"), + return_value=rx.Config( + app_name="eager_libraries", frontend_lazy_bundled_libraries=False + ), ) reset_bundled_libraries() try: @@ -751,28 +788,285 @@ def test_compile_app_root_includes_radix_window_library_when_bundled(mocker): reset_bundled_libraries() -def test_compile_app_root_can_defer_optional_window_libraries(mocker): - """Dynamic libraries need not force their entire exports into every page.""" +_APP_ROOT_HEAD = """ +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 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 = """ + return jsx(ThemeProvider, {defaultTheme: defaultColorMode, attribute: "class"}, + jsx(AppWrap, {}, children) + ); +} + + +function AppWrap({children}) { + +return (jsx("div",{},"hello")) +} + +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, {}); +} + +""" + +_APP_ROOT_WITHOUT_LOADERS = ( + _APP_ROOT_HEAD + + """ + + + +function ReflexProviders({children}) { + useEffect(() => { + // Make contexts and state objects available globally for dynamic eval'd components + window.__reflex = { + "react": React, + "$/utils/context": utils_context, + "$/utils/context-registry": utils_context_registry, + "$/utils/state": utils_state, + "$/utils/refs": utils_refs, + }; + }, []); +""" + + _APP_ROOT_TAIL +) + + +def _app_root_with_loaders(*loaders: str) -> str: + """Build the root.jsx that loads optional libraries on demand. + + Args: + *loaders: The loader entry of each optional library, in order. + + Returns: + The complete expected module. + """ + return ( + _APP_ROOT_HEAD + + """ +if (typeof window !== "undefined") { + window.__reflex = { ...window.__reflex, + "react": React, + "$/utils/context": utils_context, + "$/utils/context-registry": utils_context_registry, + "$/utils/state": utils_state, + "$/utils/refs": utils_refs, + }; + const loaders = { +""" + + "".join(f" {loader}\n" for loader in loaders) + + """ }; + const pending = Object.create(null); + window.__reflex_load = (libraries = Object.keys(loaders)) => { + return Promise.all(libraries.filter((name) => Object.hasOwn(loaders, name) && !Object.hasOwn(window.__reflex, name)).map((name) => { + if (!pending[name]) { + pending[name] = loaders[name]().then((module) => { + window.__reflex[name] = module; + }).catch((error) => { + delete pending[name]; + throw error; + }); + } + return pending[name]; + })); + }; +} + + + + +function ReflexProviders({children}) { + \n""" + + _APP_ROOT_TAIL + ) + + +_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', +) +_D3_MODULE = ( + "d3_format.js", + 'import * as library from "d3-format";\nexport default library;\n', +) + + +@pytest.mark.parametrize( + ("app_libraries", "dynamic_components", "expected_root", "expected_modules"), + [ + pytest.param( + (), + True, + _app_root_with_loaders(_EMOTION_LOADER, _RADIX_LOADER), + [_EMOTION_MODULE, _RADIX_MODULE], + id="dynamic_components", + ), + pytest.param( + (), False, _APP_ROOT_WITHOUT_LOADERS, [], id="no_dynamic_components" + ), + pytest.param( + ("d3-format@3.1.0",), + True, + _app_root_with_loaders(_EMOTION_LOADER, _RADIX_LOADER, _D3_LOADER), + [_EMOTION_MODULE, _RADIX_MODULE, _D3_MODULE], + id="dynamic_components_and_app_library", + ), + pytest.param( + ("d3-format@3.1.0",), + False, + _app_root_with_loaders(_D3_LOADER), + [_D3_MODULE], + id="app_library_only", + ), + ], +) +def test_compile_app_root_loads_optional_libraries_on_demand( + app_libraries: tuple[str, ...], + dynamic_components: bool, + expected_root: str, + expected_modules: list[tuple[str, str]], + mocker: MockerFixture, +): + """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. 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. + dynamic_components: Whether the app renders a dynamic component. + expected_root: The complete expected root.jsx. + expected_modules: The expected file name and code of each library module. + mocker: Fixture for configuring the app. + """ mocker.patch( - "reflex.compiler.compiler.get_config", + "reflex_base.config._get_config", + return_value=rx.Config(app_name="lazy_libraries"), + ) + with RegistrationContext(): + _bundle_library("@radix-ui/themes") + for library in app_libraries: + bundle_library(library) + root_path, code = compiler.compile_app_root( + rx.el.div("hello"), dynamic_components=dynamic_components + ) + modules = compiler.compile_dynamic_libraries( + dynamic_components=dynamic_components + ) + + assert root_path == str(prerequisites.get_web_dir() / "app" / "root.jsx") + assert code == expected_root + assert modules == [ + ( + str(prerequisites.get_web_dir() / "utils" / "dynamic_libraries" / name), + module_code, + ) + for name, module_code in expected_modules + ] + + +def test_compile_dynamic_libraries_is_empty_for_eager_libraries(mocker: MockerFixture): + """Write no library modules when root.jsx imports the namespaces itself. + + Args: + mocker: Fixture for configuring the app. + """ + mocker.patch( + "reflex_base.config._get_config", return_value=rx.Config( - app_name="lazy_libraries", frontend_lazy_bundled_libraries=True + app_name="eager_libraries", frontend_lazy_bundled_libraries=False ), ) with RegistrationContext(): - bundle_library("@radix-ui/themes@3.3.0") - bundle_library("constructor") - _, code = compiler.compile_app_root(rx.el.div("hello")) + bundle_library("d3-format@3.1.0") + assert compiler.compile_dynamic_libraries() == [] + + +@pytest.mark.parametrize("dynamic", [False, True]) +def test_compile_detects_dynamic_components( + dynamic: bool, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +): + """Tell the app root whether any page renders a dynamic component. + + Args: + dynamic: Whether the page renders a component held in state. + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + """ + monkeypatch.chdir(tmp_path) + with RegistrationContext(): + mocker.patch( + "reflex_base.config._get_config", + return_value=rx.Config(app_name="dynamic_detection", plugins=[]), + ) + + class DynamicDetectionState(rx.State): + """A state holding a component and a plain value.""" + + component: rx.Component = rx.el.div("dynamic") + text: str = "static" + + def index() -> rx.Component: + """Render the component or the plain value from state. + + Returns: + The page. + """ + return rx.el.div( + DynamicDetectionState.component + if dynamic + else DynamicDetectionState.text + ) + + app = rx.App() + app.add_page(index) + compile_root = mocker.spy(compiler, "compile_app_root") + compile_libraries = mocker.spy(compiler, "compile_dynamic_libraries") + compiler.compile_app(app, dry_run=True, use_rich=False) - assert 'import * as radix_ui_themes from "@radix-ui/themes"' not in code - assert '() => import("@radix-ui/themes")' in code - assert '"constructor": () => import("constructor")' in code - assert 'import * as React from "react"' in code - assert 'import * as utils_context from "$/utils/context"' in code - assert "window.__reflex_load" in code + assert compile_root.call_args.kwargs == { + "dynamic_components": dynamic, + "stateful": True, + } + 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 @@ -781,10 +1075,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) @@ -868,6 +1164,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.""" @@ -893,6 +1219,39 @@ 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 {{Fragment,createElement as jsx,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. @@ -2402,3 +2761,685 @@ 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" + + +# 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 {Fragment,useEffect} from "react"', + 'import {jsx} from "@emotion/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, + [ + THIRD_PARTY_PLAIN, + 'import {jsx} from "@emotion/react"', + 'import {Fragment,useEffect} from "react"', + ], + id="style_in_a_component_prop", + ), + pytest.param( + lambda: ThirdPartyPlain.create(fallback=rx.el.span("a")), + None, + [THIRD_PARTY_PLAIN, REACT_JSX], + 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=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")) + ), + [ + 'import {Fragment,useEffect} from "react"', + 'import {Cond_comp_} from "$/utils/components/Cond_comp_"', + 'import {jsx} from "@emotion/react"', + ], + [ + 'import {useStateContext} from "$/utils/context-registry"', + 'import {isTrue} from "$/utils/state"', + 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 {useStateContext} from "$/utils/context-registry"', + 'import {isTrue} from "$/utils/state"', + 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 {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 {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 {useStateContext} from "$/utils/context-registry"', + *EMOTION_JSX_MEMO, + 'import {mergeSlotProps} from "$/utils/state"', + ], + 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") == [*EMOTION_JSX_MEMO] + assert memo_imports("jsx_plain_memo") == [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", + [ + pytest.param(lambda: rx.el.div("x"), id="no_style"), + pytest.param(lambda: rx.el.div("x", style=_RED), id="style"), + ], +) +def test_module_built_from_the_imports_of_a_component_ships_emotion(component): + """A plugin that writes a module of its own keeps the ``jsx`` that applies ``css``. + + It collects the imports of the components it renders and adds the common + ones. Only a template of the compiler, which sees the code of the module, + can tell that Emotion is not needed: imports alone always name it. + """ + imports = component()._get_all_imports() + compiler._apply_common_imports(imports) + assert utils.compile_imports(imports) == [ + {"lib": "@emotion/react", "default": "", "rest": ["jsx"]}, + {"lib": "react", "default": "", "rest": ["Fragment", "useEffect"]}, + ] + + +def test_a_memo_module_imports_is_true_only_when_it_calls_it(): + """The event runtime is imported for isTrue only by a module that calls it.""" + + def render(imports: dict[str, list[ImportVar]]) -> str: + lines = [ + f"import {{{','.join(sorted(str(i.tag) for i in v))}}} from {k!r}" + for k, v in imports.items() + ] + return "\n".join([*lines, body]) + + body = "export const x = 1;" + assert compiler._render_memo_module(render, {"react": [ImportVar(tag="memo")]}) == ( + "import {memo} from 'react'\nexport const x = 1;", + {"react": [ImportVar(tag="memo")]}, + ) + body = "export const x = isTrue(y);" + assert compiler._render_memo_module(render, {"react": [ImportVar(tag="memo")]}) == ( + ( + "import {isTrue} from '$/utils/state'\n" + "import {memo} from 'react'\n" + "export const x = isTrue(y);" + ), + {"$/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_context_js_template.py b/tests/units/compiler/test_context_js_template.py index 2e1b6b82468..a5cec69a7f8 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,14 @@ "$/utils/state": """ export const applyDelta = () => {}; export const ReflexEvent = () => ({}); -export const hydrateClientStorage = () => ({}); -export const useEventLoop = () => []; +""", + "$/utils/refs": """ export const refs = {}; """, + "$/utils/event_loop": """ +export const useLocalEventLoop = () => [() => {}, []]; +""", + "$/utils/socket": _SOCKET_STUB, "$/utils/context-registry": """ export const ColorModeContext = {}; export const UploadFilesContext = {}; @@ -61,7 +72,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. @@ -111,6 +121,51 @@ 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 } from "$/utils/state"', + 'import { refs } from "$/utils/refs"', + 'import { hydrateClientStorage, useEventLoop } from "$/utils/socket"', + 'import { ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext, registerApp, eventLoop } from "$/utils/context-registry"', + ] + + +def test_stateless_context_does_not_import_the_backend_connection() -> None: + """An app without state bundles no socket, nor the event runtime. + + Its event loop is the one of utils/event_loop.js, which loads + utils/state.js with the first page that has an event handler. + """ + rendered = context_template(is_dev_mode=False, default_color_mode='"light"') + assert _imports(rendered) == [ + 'import { useContext, useMemo, useState, createElement, useEffect } from "react"', + 'import { refs } from "$/utils/refs"', + 'import { useLocalEventLoop as useEventLoop } from "$/utils/event_loop"', + 'import { ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext, registerApp, eventLoop } from "$/utils/context-registry"', + ] + assert "utils/socket" not in rendered + + def test_event_loop_provider_memoizes_its_element() -> None: """``EventLoopProvider`` must return a memoized provider element. @@ -247,9 +302,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" registry_source = registry_path.read_text().replace( @@ -258,8 +310,9 @@ def test_client_state_store_notifies_only_substate_subscribers(tmp_path: Path): for specifier, source in ( ("react", react_stub), ("$/utils/state", state_stub), + ("$/utils/refs", "export const refs = {};\n"), + ("$/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 f000349e225..1c959c1a771 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,10 +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 ( - "import * as lucide_react_dist_esm_icons_apple_mjs " - 'from "lucide-react/dist/esm/icons/apple.mjs";' - ) in app_root_code + 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: @@ -70,7 +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("unused-library")' in app_root_code + 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]) @@ -113,8 +156,8 @@ class ComponentWithSlot(rx.Component): with context.fork(): _reset_bundled_libraries_for_compile() _, app_root_code = compiler.compile_app_root(rx.el.div()) - assert f'from "{subpath}";' in app_root_code - assert 'from "lucide-react";' not in app_root_code + assert f' "{subpath}": () => ' in app_root_code + assert ' "lucide-react": () => ' not in app_root_code assert RegistrationContext.get().bundled_libraries.count(subpath) == 1 code = serializers.serialize(prototype) assert isinstance(code, str) @@ -141,7 +184,7 @@ def test_explicit_subpath_registration_does_not_require_package_root(reactive: b _, app_root_code = compiler.compile_app_root(rx.el.div()) code = serializers.serialize(icon) assert "lucide-react" not in context.bundled_libraries - assert f'from "{subpath}";' in app_root_code + assert f' "{subpath}": () => ' in app_root_code assert isinstance(code, str) assert f"window.__reflex['{subpath}']" in code assert "cdn.jsdelivr.net/npm/lucide-react" not in code @@ -212,7 +255,7 @@ async def nested_components(self) -> list[rx.Component]: assert subpath in context.bundled_libraries assert f"window.__reflex['{subpath}'].default" in context_code assert ( - f'() => import("{subpath}")' if lazy else f'from "{subpath}";' + f' "{subpath}": () => ' if lazy else f'from "{subpath}";' ) in root_code assert subpath not in context._explicit_bundled_libraries assert any( @@ -326,8 +369,8 @@ def import_var(self) -> ImportVar: with context.fork() as forked: _reset_bundled_libraries_for_compile() _, app_root_code = compiler.compile_app_root(rx.el.div()) - assert f'from "{root}";' not in app_root_code - assert f'from "{subpath}";' in app_root_code + assert f' "{root}": () => ' not in app_root_code + assert f' "{subpath}": () => ' in app_root_code assert root not in forked.bundled_libraries code = serializers.serialize(component) assert root not in forked.bundled_libraries @@ -463,12 +506,12 @@ 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 assert ( - "const {ReflexEvent,applyEventActions,pyOr} = window.__reflex['$/utils/state']" + "const {ReflexEvent,applyEventActions} = window.__reflex['$/utils/state']" in code ) assert "useContext(EventLoopContext)" not in code @@ -531,10 +574,10 @@ 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']" + "const {ReflexEvent,applyEventActions} = window.__reflex['$/utils/state']" in code ) assert "useContext(EventLoopContext)" not in code @@ -545,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/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..1e326b457a5 100644 --- a/tests/units/components/core/test_banner.py +++ b/tests/units/components/core/test_banner.py @@ -1,9 +1,11 @@ +from reflex_base.components.app_wraps import collect_subtree_app_wraps from reflex_components_core.core.banner import ( ConnectionBanner, ConnectionModal, ConnectionPulser, ConnectionToaster, WebsocketTargetURL, + WifiOffPulse, ) from reflex_components_radix.themes.typography.text import Text @@ -63,3 +65,98 @@ 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) == {} + + +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 icon.render() == { + "name": "LucideWifiOff", + "props": [ + 'className:"rx-connection-pulse mine"', + 'css:({ ["color"] : "red" })', + "size:32", + ], + "children": [], + } diff --git a/tests/units/components/core/test_upload.py b/tests/units/components/core/test_upload.py index d9817cea4a8..d79bc63859c 100644 --- a/tests/units/components/core/test_upload.py +++ b/tests/units/components/core/test_upload.py @@ -415,7 +415,7 @@ def test_upload_files_event_uses_shared_selection( data = files._get_all_var_data() assert data is not None assert not data.hooks - assert any(imp.tag == "refs" for imp in dict(data.imports)["$/utils/state"]) + assert any(imp.tag == "refs" for imp in dict(data.imports)["$/utils/refs"]) def test_upload_files_preserves_dynamic_id_metadata(): diff --git a/tests/units/components/test_component.py b/tests/units/components/test_component.py index 99b612c3da1..726d581b659 100644 --- a/tests/units/components/test_component.py +++ b/tests/units/components/test_component.py @@ -2665,14 +2665,19 @@ class DefaultedProps(Component): assert "first" not in vars(component) -def test_ref_hook_registers_through_state_helper(): - """Id refs register through a hook instead of writing ``refs`` during render.""" +def test_ref_hook_registers_through_the_refs_module(): + """Id refs register through a hook of the refs module, not of the state one. + + An element with an id is all a page of a stateless app needs to register a + ref: importing the hook from the state module bundled the event runtime + into a page with no event. + """ component = Box.create(id="my-box") hook = component._get_ref_hook() assert hook is not None assert str(hook) == 'const ref_my_box = useRegisteredRef("ref_my_box");' - hook_imports = component._get_hooks_imports() - assert list(hook_imports["$/utils/state"]) == [ImportVar(tag="useRegisteredRef")] - assert "react" not in hook_imports + assert dict(component._get_hooks_imports()) == { + "$/utils/refs": [ImportVar(tag="useRegisteredRef")] + } diff --git a/tests/units/conftest.py b/tests/units/conftest.py index 2e88acca651..f7f6d6a9a48 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, Plugin 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,43 @@ 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, the plugins of the app to run beside the ones + of every compile, 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], + *plugins: Plugin, + style: ComponentStyle | None = None, + ) -> CompileContext: + ctx = CompileContext( + pages=[_Page(route="/", component=page)], + hooks=CompilerHooks(plugins=(*default_page_plugins(style=style), *plugins)), + ) + with ctx: + ctx.compile() + return ctx + + return compile_page 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/client_event_queue_runtime.mjs b/tests/units/reflex_base/client_event_queue_runtime.mjs index a2970bfe6d7..97793ca113c 100644 --- a/tests/units/reflex_base/client_event_queue_runtime.mjs +++ b/tests/units/reflex_base/client_event_queue_runtime.mjs @@ -1,6 +1,13 @@ +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, what the two share, and the registry +// of refs. +const SIBLINGS = ["event_loop", "socket", "refs"]; + +/** Evaluate the complete frontend runtime with isolated dependency stubs. */ export async function createQueueRuntime( source, { @@ -78,17 +85,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 +117,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_base/compiler/test_templates.py b/tests/units/reflex_base/compiler/test_templates.py index 196a30a218a..5c25d35fecf 100644 --- a/tests/units/reflex_base/compiler/test_templates.py +++ b/tests/units/reflex_base/compiler/test_templates.py @@ -1,7 +1,14 @@ """Tests for reflex_base.compiler.templates.""" -from reflex_base.compiler.templates import _merge_state_hooks, _render_hooks +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 +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 +85,183 @@ 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, + ) + + +# What a module is given before its code is looked at: Emotion's ``jsx``. +EMOTION_IMPORTS: list = [ + {"lib": "react", "default": "", "rest": ["useEffect", "Fragment"]}, + {"lib": "@emotion/react", "default": "", "rest": ["jsx"]}, +] +EMOTION_JSX = ( + 'import {Fragment,useEffect} from "react"\nimport {jsx} from "@emotion/react"' +) +REACT_JSX = 'import {Fragment,createElement as jsx,useEffect} from "react"' + + +@pytest.mark.parametrize( + ("imports", "code", "expected"), + [ + pytest.param( + EMOTION_IMPORTS, + 'jsx("div",{className:"css",style:{"--css":1}},"scss")', + REACT_JSX, + id="no_css_key", + ), + pytest.param( + EMOTION_IMPORTS, + 'jsx("div",{css:({ ["color"] : "red" })},)', + EMOTION_JSX, + id="css_prop", + ), + pytest.param( + EMOTION_IMPORTS, 'const props = {"css": style};', EMOTION_JSX, id="quoted" + ), + pytest.param( + EMOTION_IMPORTS, + 'const props = {["css"] : style};', + EMOTION_JSX, + id="computed", + ), + pytest.param( + # Text that reads like the key is taken for one: Emotion renders + # the element as React would. + EMOTION_IMPORTS, + 'jsx("p",{},"css: the language of style")', + EMOTION_JSX, + id="css_key_in_text", + ), + pytest.param( + [ + {"lib": "@emotion/react", "default": "", "rest": ["jsx", "keyframes"]}, + {"lib": "react", "default": "", "rest": ["memo"]}, + ], + "jsx(Icon,{className:name},)", + 'import {keyframes} from "@emotion/react"\n' + 'import {createElement as jsx,memo} from "react"', + id="another_emotion_import_stays", + ), + pytest.param( + [{"lib": "@emotion/react", "default": "", "rest": ["jsx"]}], + "jsx(Icon,{},)", + 'import {createElement as jsx} from "react"', + id="module_without_react", + ), + pytest.param( + [{"lib": "react", "default": "", "rest": ["memo"]}], + "const style = {};", + 'import {memo} from "react"', + id="module_without_jsx", + ), + ], +) +def test_module_calls_emotion_only_for_a_css_key( + imports: list, code: str, expected: str +): + """A module with no ``css`` key gets React's ``createElement`` as ``jsx``.""" + 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 5f05159f213..42c0bea1a5b 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 @@ -165,3 +167,60 @@ 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] + + +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. + """ + code = serialize(component) + assert isinstance(code, str) + lines = code.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']", + ] + assert _dynamic_module_head(rx.el.div("x", style={"color": "red"})) == [ + '//__reflex_evaluate:["@emotion/react"]', + "const React = window.__reflex.react;", + "const {jsx} = window.__reflex['@emotion/react']", + "const {Fragment,useEffect} = window.__reflex['react']", + ] 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/reflex_base/test_client_state.py b/tests/units/reflex_base/test_client_state.py index a3d35d78c10..e42443d96a6 100644 --- a/tests/units/reflex_base/test_client_state.py +++ b/tests/units/reflex_base/test_client_state.py @@ -651,7 +651,7 @@ def test_push_var_is_evaluated_on_the_client() -> None: } (_, function), _ = spec.args assert function._get_all_var_data() == VarData.merge( - VarData(imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]}), + VarData(imports={f"$/{Dirs.REFS_PATH}": [ImportVar(tag="refs")]}), other.global_value._get_all_var_data(), ) 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_base/utils/pyi_generator/test_unit.py b/tests/units/reflex_base/utils/pyi_generator/test_unit.py index b862f15a5c9..7faffccc42d 100644 --- a/tests/units/reflex_base/utils/pyi_generator/test_unit.py +++ b/tests/units/reflex_base/utils/pyi_generator/test_unit.py @@ -23,6 +23,7 @@ _is_literal, _is_optional, _is_union, + _rewrite_component_import, _safe_issubclass, type_to_ast, ) @@ -516,3 +517,24 @@ class CreateComp(Component): assert "**props" in result # Return type should reference the class. assert "CreateComp" in result + + +@pytest.mark.parametrize( + ("module", "is_reflex_package", "expected"), + [ + ("components", True, "reflex_components_core"), + ("components.radix.themes.base", True, "reflex_components_radix.themes.base"), + ("components.datadisplay.code", True, "reflex_components_code.code"), + ("components.ui", True, "reflex_components_ui"), + ( + "components.ui.components.button", + True, + "reflex_components_ui.components.button", + ), + ("components.component", True, ".components.component"), + ("components.ui", False, ".components.ui"), + ("event", True, ".event"), + ], +) +def test_rewrite_component_import(module: str, is_reflex_package: bool, expected: str): + assert _rewrite_component_import(module, is_reflex_package) == expected 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/drivers/test_lighthouse.py b/tests/units/reflex_bench/drivers/test_lighthouse.py new file mode 100644 index 00000000000..6ef4a6f591e --- /dev/null +++ b/tests/units/reflex_bench/drivers/test_lighthouse.py @@ -0,0 +1,119 @@ +"""Tests for reflex_bench.drivers.lighthouse.""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path +from typing import Any + +import pytest +from reflex_bench.drivers import lighthouse + + +def _report(score: float | None, warnings: list[str] | None = None) -> dict[str, Any]: + return { + "categories": {"performance": {"score": score}}, + "audits": { + "largest-contentful-paint": {"numericValue": 1254.5}, + "total-blocking-time": {"numericValue": 30.0}, + "cumulative-layout-shift": {"numericValue": 0.012}, + "first-contentful-paint": {"numericValue": 900.0}, + }, + "runWarnings": warnings or [], + } + + +def test_read_takes_seconds_and_the_score(): + assert lighthouse.read(_report(0.98)) == { + "score": 0.98, + "lcp": 1.2545, + "tbt": 0.03, + "cls": 0.012, + "fcp": 0.9, + } + + +def test_a_report_without_a_score_fails_with_its_warnings(): + with pytest.raises(RuntimeError) as error: + lighthouse.read(_report(None, ["The page did not paint", "Timed out"])) + assert str(error.value) == ( + "Lighthouse gave no performance score: The page did not paint; Timed out" + ) + + +def test_command_prefers_the_variable_then_lighthouse_then_npx( + monkeypatch: pytest.MonkeyPatch, +): + found: set[str] = set() + monkeypatch.setattr(lighthouse.shutil, "which", lambda name: name in found or None) + monkeypatch.delenv(lighthouse.COMMAND_ENV, raising=False) + with pytest.raises(FileNotFoundError) as error: + lighthouse.command() + assert str(error.value) == ( + "Lighthouse is unavailable: install `lighthouse`, Node's `npx`, or set" + " REFLEX_LIGHTHOUSE_COMMAND" + ) + found.add("npx") + assert lighthouse.command() == ["npx", "--yes", "lighthouse@13.1.0"] + found.add("lighthouse") + assert lighthouse.command() == ["lighthouse"] + monkeypatch.setenv(lighthouse.COMMAND_ENV, "node '/opt/my lh/cli.js'") + assert lighthouse.command() == ["node", "/opt/my lh/cli.js"] + + +def test_run_audits_a_mobile_page(monkeypatch: pytest.MonkeyPatch, tmp_path: Path): + calls = [] + out = tmp_path / "report.json" + + def run(args, **kwargs): + calls.append(args) + out.write_text(json.dumps(_report(1.0)), encoding="utf-8") + return subprocess.CompletedProcess(args, 0, "", "") + + monkeypatch.setattr(lighthouse.subprocess, "run", run) + values = lighthouse.run( + ["lighthouse"], + "http://localhost:3000/", + throttling="devtools", + chrome="/bin/chrome", + out=out, + env={}, + ) + assert values == lighthouse.read(_report(1.0)) + assert calls == [ + [ + "lighthouse", + "http://localhost:3000/", + "--only-categories=performance", + "--form-factor=mobile", + "--throttling-method=devtools", + "--output=json", + f"--output-path={out}", + "--chrome-path=/bin/chrome", + "--chrome-flags=--headless=new --no-sandbox --disable-dev-shm-usage", + "--quiet", + ] + ] + + +def test_a_failed_run_says_how_it_ended( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +): + output = "\n".join(f"line {n}" for n in range(30)) + monkeypatch.setattr( + lighthouse.subprocess, + "run", + lambda args, **kwargs: subprocess.CompletedProcess(args, 1, output, "boom\n"), + ) + with pytest.raises(RuntimeError) as error: + lighthouse.run( + ["lighthouse"], + "http://localhost:3000/", + throttling="simulate", + chrome="/bin/chrome", + out=tmp_path / "report.json", + env={}, + ) + tail = "\n".join(f"line {n}" for n in range(11, 30)) + assert str(error.value) == f"lighthouse exited with code 1:\n{tail}\nboom" diff --git a/tests/units/reflex_bench/report/test_pages.py b/tests/units/reflex_bench/report/test_pages.py new file mode 100644 index 00000000000..c41ca93f5d0 --- /dev/null +++ b/tests/units/reflex_bench/report/test_pages.py @@ -0,0 +1,62 @@ +"""Tests for reflex_bench.report.pages.""" + +from __future__ import annotations + +from reflex_bench.registry import Metric +from reflex_bench.report import pages +from reflex_bench.schema import BenchmarkDoc + +from tests.units.reflex_bench.factories import make_doc, make_entry + +EXACT_B = Metric(unit="B", direction="lower", assume="exact") +EXACT_1 = Metric(unit="1", direction="lower", assume="exact") +SECONDS = Metric(unit="s", direction="lower") +SCORE = Metric(unit="1", direction="higher") + + +def _size(app: str, js: int, status: str = "ok") -> BenchmarkDoc: + return make_entry( + "size.export", + { + "js_gzip": (EXACT_B, [js]), + "css_gzip": (EXACT_B, [7712]), + "js_files": (EXACT_1, [8]), + "emotion_files": (EXACT_1, [0]), + "build_time": (SECONDS, [4.107]), + }, + params={"app": app}, + status=status, + error=None if status == "ok" else "RuntimeError: export failed", + ) + + +def _audit(app: str) -> BenchmarkDoc: + metrics = {} + for throttling, lcp in ( + ("simulate", [0.75, 0.76, 0.8]), + ("devtools", [1.3, 1.2, 1.29]), + ): + metrics[f"{throttling}_score"] = (SCORE, [1.0, 0.99, 1.0]) + metrics[f"{throttling}_lcp"] = (SECONDS, lcp) + metrics[f"{throttling}_tbt"] = (SECONDS, [0.0, 0.0, 0.01]) + metrics[f"{throttling}_cls"] = (EXACT_1, [0.0, 0.0, 0.0]) + return make_entry("lighthouse.mobile", metrics, params={"app": app}) + + +def test_a_row_per_app_with_the_medians(): + doc = make_doc([ + _audit("ui_button"), + _size("ui_button", 146699), + _size("blank", 163900, status="failed"), + ]) + assert pages.render(doc) == ( + "| app | JS gzip (B) | CSS gzip (B) | JS files | Emotion files | build" + " | simulated score | simulated LCP | simulated TBT | simulated CLS" + " | real score | real LCP | real TBT | real CLS |\n" + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |" + " ---: | ---: | ---: | ---: |\n" + "| ui_button | 146,699 | 7,712 | 8 | 0 | 4.11 s | 100 | 0.76 s | 0.00 s" + " | 0.000 | 100 | 1.29 s | 0.00 s | 0.000 |\n" + "| blank | failed | failed | failed | failed | failed | - | - | - | -" + " | - | - | - | - |\n" + ) diff --git a/tests/units/reflex_bench/suites/test_size.py b/tests/units/reflex_bench/suites/test_size.py index 8a9cf6c43db..e41a185bbf7 100644 --- a/tests/units/reflex_bench/suites/test_size.py +++ b/tests/units/reflex_bench/suites/test_size.py @@ -33,8 +33,40 @@ '' "" ) +# 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,36 @@ 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): + app = _export(tmp_path) + client = app / ".web" / "build" / "client" + extra_files = { + # Outside assets: a script, but not a chunk. + "public/widget.js": b"console.log('widget');" * 10, + "assets/emotion-react.browser.esm-Ab12Cd34.js": b"export const jsx=1;" * 30, + "assets/styled-Xy12Zw34.js": b"/* @EMOTION/cache */ export {};" * 5, + } + _write(client, extra_files) + values = size.measure_export(app, reflex_version="0.9.12").values + files = {**INITIAL, **OTHER, **extra_files} + scripts = [data for name, data in files.items() if name.endswith(".js")] + sheets = [data for name, data in files.items() if name.endswith(".css")] + assert ( + values["js_gzip"], + values["css_gzip"], + values["js_files"], + values["chunks"], + values["emotion_files"], + ) == ( + sum(map(_gzip_size, scripts)), + sum(map(_gzip_size, sheets)), + 9, + 8, + 2, + ) def test_web_dir_and_node_modules_are_disjoint(tmp_path: Path): @@ -154,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"] == { @@ -266,15 +365,25 @@ def test_real_first_pages(fixture: str, count: int, first: str, last: str): def test_the_benchmark_declares_what_sample_returns(tmp_path: Path): bench = registry.discover()["size.export"] - assert bench.exact + # Every metric but the build time is exact, and one run measures them all. + assert [ + name for name, metric in bench.metrics.items() if metric.assume != "exact" + ] == ["build_time"] + assert bench.default_runs == 1 assert bench.kind == "track" - assert bench.suites == ("pr", "daily") - assert bench.params == {"app": ("playground",)} + assert bench.suites == ("pr", "daily", "pages") + assert bench.params == {"app": ("playground", *size.PAGE_APPS)} + assert bench.suite_params == { + "pr": {"app": ("playground",)}, + "daily": {"app": ("playground",)}, + } assert {metric.direction for metric in bench.metrics.values()} == {"lower"} _export(tmp_path) ctx = make_context(tmp_path, {"app": "playground"}) - result = bench.normalize(size.ExportSize().sample(ctx)) - assert result.values["chunks"] == 4 + export = size.ExportSize() + export.build_time = 12.5 + result = bench.normalize(export.sample(ctx)) + 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 @@ -320,7 +429,8 @@ def _fake_export(monkeypatch: pytest.MonkeyPatch) -> list[tuple[Path, Any, Any]] def fake_run_cli(python: Path, args: Any, **kwargs: Any) -> SimpleNamespace: calls.append((python, args, kwargs)) _write(kwargs["cwd"] / ".web" / "build" / "client", {"index.html": b""}) - return SimpleNamespace(check=lambda: None) + done = SimpleNamespace(wall_s=7.25) + return SimpleNamespace(check=lambda: done) monkeypatch.setattr(size, "run_cli", fake_run_cli) return calls @@ -332,12 +442,15 @@ def test_setup_exports_into_the_work_directory( calls = _fake_export(monkeypatch) work, cache = tmp_path / "work", tmp_path / "cache" ctx = make_context(work, {"app": "demo"}, cache_dir=cache) - size.ExportSize().setup(ctx) + export = size.ExportSize() + export.setup(ctx) + assert export.build_time == pytest.approx(7.25) ((python, args, kwargs),) = calls assert python == ctx.subject.python assert list(args) == ["export", "--frontend-only", "--no-zip", "--env", "prod"] assert kwargs["cwd"] == work / "app" assert kwargs["env"]["REFLEX_DIR"] == str(cache / "reflex") + assert "PAGES_APP" not in kwargs["env"] assert (work / "app" / "rxconfig.py").read_text() == "config = 1\n" assert not (cache / "app").exists() assert ctx.fixture == { @@ -362,3 +475,22 @@ def test_each_session_exports_its_own_copy( tmp_path / "B" / "app", ] assert all((ctx.workdir / "app" / ".web" / "build").is_dir() for ctx in arms) + + +def test_a_page_app_is_the_pages_example_with_its_name( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + pages = repo / "examples" / "pages" + _write(pages, {"rxconfig.py": b"config = 2\n", ".content-hash": b"sha256:def456\n"}) + _git(repo, "add", ".") + calls = _fake_export(monkeypatch) + ctx = make_context(tmp_path / "work", {"app": "kitchen_sink_ui"}) + size.ExportSize().setup(ctx) + ((_, _, kwargs),) = calls + assert kwargs["env"]["PAGES_APP"] == "kitchen_sink_ui" + assert (tmp_path / "work" / "app" / "rxconfig.py").read_text() == "config = 2\n" + assert ctx.fixture == { + "name": "kitchen_sink_ui", + "content_hash": "sha256:def456", + "params": {}, + } diff --git a/tests/units/reflex_bench/test_budgets.py b/tests/units/reflex_bench/test_budgets.py index 785f497698f..0efacd7f43c 100644 --- a/tests/units/reflex_bench/test_budgets.py +++ b/tests/units/reflex_bench/test_budgets.py @@ -4,6 +4,7 @@ import json from pathlib import Path +from typing import Any import pytest from click.testing import CliRunner, Result @@ -16,216 +17,316 @@ SIZE = Metric(unit="B", direction="lower", assume="exact") COUNT = Metric(unit="1", direction="lower", assume="exact") -NAME = "size.export[app=playground]" -BUDGETS = {NAME: {"initial_gzip": 260_000, "chunks": 40}} - - -def _doc(status: str = "ok", error: str | None = None, warmup: int = 0) -> ResultDoc: +SECONDS = Metric(unit="s", direction="lower") +SCORE = Metric(unit="1", direction="higher") +NAME = "size.export[app=blank]" +AUDIT = "lighthouse.mobile[app=blank]" +LIMITS = { + NAME: { + "js_gzip": {"max": 260_000, "measured": 250_000}, + "js_files": {"max": 40, "measured": 30}, + } +} +HEADER = "benchmark metric value budget delta verdict" + + +def _doc(status: str = "ok", error: str | None = None) -> ResultDoc: entry = make_entry( "size.export", { - "initial_gzip": (SIZE, [250_000]), + "js_gzip": (SIZE, [250_000]), "total_gzip": (SIZE, [900_000]), - "chunks": (COUNT, [30]), + "js_files": (COUNT, [30]), }, - params={"app": "playground"}, - warmup=warmup, + params={"app": "blank"}, status=status, error=error, ) return make_doc([entry]) -def _files( - tmp_path: Path, doc: ResultDoc, limits: dict[str, dict[str, int]] -) -> tuple[Path, Path]: - result = tmp_path / "result.json" - dump(doc, result) - path = tmp_path / "budgets.json" - path.write_text(json.dumps({"schema": budgets.SCHEMA_ID, "budgets": limits})) - return result, path +def _audit(lcp: list[float], score: list[float]) -> Any: + return make_entry( + "lighthouse.mobile", + {"simulate_lcp": (SECONDS, lcp), "simulate_score": (SCORE, score)}, + params={"app": "blank"}, + ) -def _check(tmp_path: Path, doc: ResultDoc, limits: dict[str, dict[str, int]]) -> Result: - result, path = _files(tmp_path, doc, limits) - return CliRunner().invoke( - cli.cli, ["budgets", "check", str(result), "--budgets", str(path)] +def _check( + tmp_path: Path, doc: ResultDoc, limits: dict[str, Any], *args: str +) -> Result: + """Check a result against budgets through the command line. + + Args: + tmp_path: Where to write the files. + doc: The result. + limits: The budgets of the file. + *args: More arguments of ``budgets check``. + + Returns: + The run, from the directory of the files, so paths print relative. + """ + dump(doc, tmp_path / "result.json") + (tmp_path / "budgets.json").write_text( + json.dumps({"schema": budgets.SCHEMA_ID, "budgets": limits}) ) + with pytest.MonkeyPatch.context() as patch: + patch.chdir(tmp_path) + return CliRunner().invoke( + cli.cli, + ["budgets", "check", "result.json", "--budgets", "budgets.json", *args], + ) def test_within_budget_exits_0_and_shows_the_headroom(tmp_path: Path): - result = _check(tmp_path, _doc(), BUDGETS) + result = _check(tmp_path, _doc(), LIMITS) assert result.exit_code == 0, result.output - lines = result.output.splitlines() - assert lines[0].split() == [ - "benchmark", - "metric", - "value", - "budget", - "delta", - "verdict", - ] - assert lines[1].split() == [ - NAME, - "initial_gzip", - "250000", - "260000", - "-10,000", - "B", - "(-3.8", - "%)", - "ok", - ] - assert lines[2].split() == [ - NAME, - "chunks", - "30", - "40", - "-10", - "(-25", - "%)", - "ok", - ] - assert "2 within budget" in result.output + assert result.output == ( + f"{HEADER}\n" + f"{NAME} js_gzip 250000 <= 260000 -10,000 B (-3.8 %) ok\n" + f"{NAME} js_files 30 <= 40 -10 (-25 %) ok\n" + "\n" + "2 within budget · 0 over budget · 0 over budget, reported only · 0 not checked\n" + ) -def test_a_metric_over_budget_exits_2_with_the_delta(tmp_path: Path): - limits = {NAME: {"initial_gzip": 240_000, "chunks": 40}} +def test_a_metric_over_budget_fails_naming_it_its_value_and_its_limit( + tmp_path: Path, +): + limits = {NAME: {"js_gzip": {"max": 240_000, "measured": 230_000}}} result = _check(tmp_path, _doc(), limits) assert result.exit_code == 2, result.output - row = next(line for line in result.output.splitlines() if "initial_gzip" in line) - assert row.split()[2:] == [ - "250000", - "240000", - "+10,000", - "B", - "(+4.2", - "%)", - "over", - "budget", + assert result.output == ( + "benchmark metric value budget delta verdict\n" + f"{NAME} js_gzip 250000 <= 240000 +10,000 B (+4.2 %) over budget\n" + "\n" + f"{NAME} js_gzip is 250,000 B, over its limit of 240,000 B\n" + "0 within budget · 1 over budget · 0 over budget, reported only · 0 not checked\n" + "to accept a new value, change its budget in budgets.json in the same pull request\n" + ) + + +def test_a_reported_budget_never_fails(tmp_path: Path): + limits = { + AUDIT: { + "simulate_lcp": {"max": 1.5, "measured": 1.2, "enforce": False}, + "simulate_score": {"min": 0.95, "measured": 1, "enforce": False}, + } + } + doc = make_doc([_audit(lcp=[1.4, 2.0, 1.8], score=[0.9, 0.97, 0.92])]) + result = _check(tmp_path, doc, limits) + assert result.exit_code == 0, result.output + # A noisy metric is checked at its median. + assert result.output.splitlines()[1:] == [ + ( + f"{AUDIT} simulate_lcp 1.800 <= 1.500 +0.300 s (+20 %)" + " over budget (reported)" + ), + ( + f"{AUDIT} simulate_score 0.920 >= 0.950 -0.030 (-3.2 %)" + " under budget (reported)" + ), + "", + f"reported, not enforced: {AUDIT} simulate_lcp is 1.800 s, over its limit of 1.500 s", + f"reported, not enforced: {AUDIT} simulate_score is 0.920, under its limit of 0.950", + "0 within budget · 0 over budget · 2 over budget, reported only · 0 not checked", ] - assert "1 over budget" in result.output -def test_a_fractional_value_keeps_its_fraction(tmp_path: Path): - entry = make_entry( - "size.export", - {"initial_gzip": (SIZE, [250_000.5])}, - params={"app": "playground"}, - ) - result = _check(tmp_path, make_doc([entry]), {NAME: {"initial_gzip": 250_000}}) +def test_an_enforced_minimum_fails_below_it(tmp_path: Path): + limits = {AUDIT: {"simulate_score": {"min": 0.95, "measured": 1}}} + result = _check(tmp_path, make_doc([_audit([1.0], [0.9])]), limits) assert result.exit_code == 2, result.output - row = next(line for line in result.output.splitlines() if "initial_gzip" in line) - assert row.split()[2:] == [ - "250000.500", - "250000", - "+0.500", - "B", - "(+0.0", - "%)", - "over", - "budget", - ] + assert result.output.splitlines()[3] == ( + f"{AUDIT} simulate_score is 0.900, under its limit of 0.950" + ) @pytest.mark.parametrize( - ("doc", "limits", "error"), + ("doc", "limits", "row"), [ - (_doc(), {"size.export[app=other]": {"chunks": 40}}, "not in the result"), ( - _doc(status="failed", error="RuntimeError: reflex export exited with 1"), - BUDGETS, - "failed: RuntimeError: reflex export exited with 1", + _doc(), + {"size.export[app=other]": {"js_files": {"max": 40, "measured": 30}}}, + "size.export[app=other] js_files - <= 40 error: not in the result", + ), + ( + _doc(), + {NAME: {"node_modules": {"max": 1, "measured": 1}}}, + f"{NAME} node_modules - <= 1 error: metric not in the result", ), - (_doc(), {NAME: {"node_modules": 1}}, "metric not in the result"), ], ) -def test_a_budget_that_cannot_be_checked_exits_1( - tmp_path: Path, doc: ResultDoc, limits: dict[str, dict[str, int]], error: str +def test_a_missing_benchmark_or_metric_exits_1( + tmp_path: Path, doc: ResultDoc, limits: dict[str, Any], row: str ): result = _check(tmp_path, doc, limits) assert result.exit_code == 1, result.output - assert error in result.output + assert result.output.splitlines()[1:] == [ + row, + "", + "0 within budget · 0 over budget · 0 over budget, reported only · 1 not checked", + ] def test_a_failed_benchmark_prints_its_error_once(tmp_path: Path): error = "RuntimeError: reflex export exited with 1" - result = _check(tmp_path, _doc(status="failed", error=error), BUDGETS) + result = _check(tmp_path, _doc(status="failed", error=error), LIMITS) assert result.exit_code == 1, result.output - assert result.output.count(error) == 1 - rows = [line for line in result.output.splitlines() if line.startswith(NAME)] - assert [row.split()[-2:] for row in rows] == [["error:", "failed"]] * 2 + assert result.output.splitlines()[1:4] == [ + f"{NAME} js_gzip - <= 260000 error: failed", + f"✗ {NAME}: failed: {error}", + f"{NAME} js_files - <= 40 error: failed", + ] def test_an_unchecked_budget_wins_over_one_exceeded(tmp_path: Path): - limits = {NAME: {"initial_gzip": 1, "node_modules": 1}} + limits = { + NAME: { + "js_gzip": {"max": 1, "measured": 1}, + "node_modules": {"max": 1, "measured": 1}, + } + } assert _check(tmp_path, _doc(), limits).exit_code == 1 -def test_only_budgeted_metrics_are_checked(): - rows = budgets.check(_doc(), BUDGETS) - assert [(row.benchmark, row.metric) for row in rows] == [ - (NAME, "initial_gzip"), - (NAME, "chunks"), - ] - assert [(row.value, row.unit, row.exceeded) for row in rows] == [ - (250_000, "B", False), - (30, "1", False), - ] +def test_only_checks_the_instances_it_matches(tmp_path: Path): + limits = { + **LIMITS, + AUDIT: {"simulate_lcp": {"max": 1.5, "measured": 1.2, "enforce": False}}, + } + result = _check(tmp_path, _doc(), limits, "--only", "size.*") + assert result.exit_code == 0, result.output + assert [line.split()[0] for line in result.output.splitlines()[1:3]] == [NAME] * 2 + + +def test_only_that_matches_nothing_is_a_usage_error(tmp_path: Path): + result = _check(tmp_path, _doc(), LIMITS, "--only", "memory.*") + assert result.exit_code == 1 + assert result.output.splitlines()[-1] == ( + "Error: --only memory.* matches no budget of budgets.json" + ) -def test_the_largest_timed_sample_is_checked(): +def test_check_reads_exact_metrics_at_their_largest_sample(): entry = make_entry( "size.export", - {"chunks": (COUNT, [99, 30, 41])}, - params={"app": "playground"}, + {"js_files": (COUNT, [99, 30, 41])}, + params={"app": "blank"}, warmup=1, ) - (row,) = budgets.check(make_doc([entry]), {NAME: {"chunks": 40}}) - assert (row.value, row.exceeded) == (41, True) + budget = budgets.Budget(limit=40, bound="max", measured=30) + (row,) = budgets.check(make_doc([entry]), {NAME: {"js_files": budget}}) + assert row == budgets.BudgetRow(NAME, "js_files", budget, value=41, unit="1") + assert row.exceeded + assert row.failed + + +def test_load_reads_every_field(tmp_path: Path): + path = tmp_path / "budgets.json" + path.write_text( + json.dumps({ + "schema": budgets.SCHEMA_ID, + "budgets": { + NAME: { + "js_gzip": {"max": 180000, "measured": 170812, "note": "step 1"} + }, + AUDIT: { + "simulate_score": {"min": 0.9, "measured": 1, "enforce": False} + }, + }, + }) + ) + assert budgets.load(path) == { + NAME: {"js_gzip": budgets.Budget(180000, "max", 170812, True, "step 1")}, + AUDIT: {"simulate_score": budgets.Budget(0.9, "min", 1, False, None)}, + } @pytest.mark.parametrize( - ("content", "message"), + ("budgets_doc", "message"), [ - ("not json", "is not valid JSON"), - ('{"schema": "other/1", "budgets": {}}', "schema"), - ('{"schema": "reflex-bench-budgets/1"}', "budgets"), - ('{"schema": "reflex-bench-budgets/1", "budgets": {"x": 1}}', "budgets"), ( - '{"schema": "reflex-bench-budgets/1", "budgets": {"x": {"m": 1.5}}}', - "budgets", + "not json", + "{path} is not valid JSON: Expecting value: line 1 column 1 (char 0)", + ), + ( + {"schema": "other/1", "budgets": {}}, + "{path}: schema must be 'reflex-bench-budgets/2'", ), ( - '{"schema": "reflex-bench-budgets/1", "budgets": {"x": {"m": -1}}}', - "budgets", + {"schema": "reflex-bench-budgets/2"}, + "{path}: budgets must map instance names to objects of metric budgets", ), ( - '{"schema": "reflex-bench-budgets/1", "budgets": {"x": {"m": true}}}', - "budgets", + {"schema": "reflex-bench-budgets/2", "budgets": {"x": 1}}, + "{path}: budgets must map instance names to objects of metric budgets", + ), + ( + {"schema": "reflex-bench-budgets/2", "budgets": {"x": {"m": 1}}}, + "{path}: budget x m must be an object", + ), + ( + {"schema": "reflex-bench-budgets/2", "budgets": {"x": {"m": {"max": 1}}}}, + "{path}: budget x m: max and measured must be numbers >= 0", + ), + ( + { + "schema": "reflex-bench-budgets/2", + "budgets": {"x": {"m": {"max": 1, "min": 0, "measured": 1}}}, + }, + "{path}: budget x m needs exactly one of max and min", + ), + ( + { + "schema": "reflex-bench-budgets/2", + "budgets": {"x": {"m": {"max": -1, "measured": 1}}}, + }, + "{path}: budget x m: max and measured must be numbers >= 0", + ), + ( + { + "schema": "reflex-bench-budgets/2", + "budgets": {"x": {"m": {"max": True, "measured": 1}}}, + }, + "{path}: budget x m: max and measured must be numbers >= 0", + ), + ( + { + "schema": "reflex-bench-budgets/2", + "budgets": {"x": {"m": {"max": 1, "measured": 1, "enforce": "no"}}}, + }, + "{path}: budget x m: enforce must be a boolean and note a string", + ), + ( + { + "schema": "reflex-bench-budgets/2", + "budgets": {"x": {"m": {"max": 1, "measured": 1, "limit": 2}}}, + }, + "{path}: budget x m has unknown keys ['limit']", ), ], ) -def test_invalid_budget_files(tmp_path: Path, content: str, message: str): +def test_invalid_budget_files(tmp_path: Path, budgets_doc: Any, message: str): path = tmp_path / "budgets.json" - path.write_text(content) - with pytest.raises(budgets.BudgetsError, match=message): - budgets.load(path) - result = tmp_path / "result.json" - dump(_doc(), result) - invoked = CliRunner().invoke( - cli.cli, ["budgets", "check", str(result), "--budgets", str(path)] + path.write_text( + budgets_doc if isinstance(budgets_doc, str) else json.dumps(budgets_doc) ) - assert invoked.exit_code == 1 - assert message in invoked.output + with pytest.raises(budgets.BudgetsError) as error: + budgets.load(path) + assert str(error.value) == message.format(path=path) def test_an_invalid_result_exits_1(tmp_path: Path): - _, path = _files(tmp_path, _doc(), BUDGETS) + (tmp_path / "budgets.json").write_text( + json.dumps({"schema": budgets.SCHEMA_ID, "budgets": LIMITS}) + ) bad = tmp_path / "bad.json" bad.write_text("{}") result = CliRunner().invoke( - cli.cli, ["budgets", "check", str(bad), "--budgets", str(path)] + cli.cli, + ["budgets", "check", str(bad), "--budgets", str(tmp_path / "budgets.json")], ) assert result.exit_code == 1 assert "is not a valid reflex-bench/1 document" in result.output @@ -238,3 +339,7 @@ def test_the_repo_budgets_name_declared_metrics(): for name, limits in loaded.items(): assert name in instances assert limits.keys() <= instances[name].metrics.keys() + for metric, budget in limits.items(): + # A limit bounds a metric on the side it gets worse. + direction = instances[name].metrics[metric].direction + assert budget.bound == ("max" if direction == "lower" else "min"), metric diff --git a/tests/units/reflex_bench/test_registry.py b/tests/units/reflex_bench/test_registry.py index fc313dd45c0..d4f7fd2e61e 100644 --- a/tests/units/reflex_bench/test_registry.py +++ b/tests/units/reflex_bench/test_registry.py @@ -117,6 +117,7 @@ class Other(_Sampler): ({"suites": ("nightly",)}, "unknown suites"), ({"suites": ("all",)}, "unknown suites"), ({"timeout": 0}, "timeouts > 0"), + ({"runs": 0}, "runs must be >= 1"), ({"min_version": "not a version"}, "is not a version"), ( {"params": {"n": [1, 2]}, "suite_params": {"smoke": {"n": [1]}}}, @@ -231,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 @@ -437,3 +457,15 @@ def sample(self, ctx): instance.conclude() instance.cleanup() assert calls == ["setup:3", "sample"] + + +def test_default_runs_are_declared_or_follow_exactness(): + exact = Metric(unit="B", direction="lower", assume="exact") + declared = Benchmark.define(_Sampler, id="t.x", metrics={"wall": WALL}, runs=5) + noisy = Benchmark.define(_Sampler, id="t.x", metrics={"wall": WALL}) + sizes = Benchmark.define(_Sampler, id="t.x", metrics={"size": exact}) + assert (declared.default_runs, noisy.default_runs, sizes.default_runs) == ( + 5, + None, + 1, + ) diff --git a/tests/units/reflex_bench/test_scheduler.py b/tests/units/reflex_bench/test_scheduler.py index c2b6ca792f7..8aeb26fb3ce 100644 --- a/tests/units/reflex_bench/test_scheduler.py +++ b/tests/units/reflex_bench/test_scheduler.py @@ -121,6 +121,16 @@ def test_run_count_rule_applies_after_the_first_timed_sample( assert entry["metrics"]["wall"]["summary"]["A"]["n"] == 4 +def test_declared_runs_replace_the_rule_and_yield_to_the_policy( + tmp_path: Path, fixed_timer +): + declared: list[str] = [] + _run(_recorder(declared, runs=3), tmp_path, min_runs=10, max_runs=30) + fixed: list[str] = [] + _run(_recorder(fixed, runs=3), tmp_path, runs=2) + assert (declared.count("sample"), fixed.count("sample")) == (3, 2) + + def test_exact_benchmarks_default_to_one_run(tmp_path: Path): exact = {"bytes": Metric(unit="B", direction="lower", assume="exact")} planned = _recorder([], sample=lambda ctx: {"bytes": 5}, metrics=exact) 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() 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..4408de2a9b4 --- /dev/null +++ b/tests/units/reflex_components_core/base/test_error_boundary.py @@ -0,0 +1,75 @@ +"""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 has no ``css`` prop.""" + boundary = ErrorBoundary.create(rx.el.div("page")) + assert sorted(boundary._get_all_imports(collapse=True)) == [ + "$/utils/context", + "$/utils/state", + "@emotion/react", + "react", + "react-error-boundary@6.1.6", + "react-router", + ] + fallback, _on_error = boundary.render()["props"] + assert fallback == f"fallbackRender:{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..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: @@ -42,3 +43,153 @@ 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"', + 'fill:"#6E56CF"', + 'height:"16"', + 'rx:"2"', + 'width:"16"', + ], + "children": [], + }, + { + "name": '"path"', + "props": [ + 'className:"rx-sticky-logo-letter"', + 'd:"M10 9V13H12V9H10Z"', + 'fill:"white"', + ], + "children": [], + }, + { + "name": '"path"', + "props": [ + 'className:"rx-sticky-logo-letter"', + 'd:"M4 3V13H6V9H10V7H6V5H10V7H12V3H4Z"', + 'fill:"white"', + ], + "children": [], + }, + ], + }, + { + "name": '"div"', + "props": ['className:"rx-sticky-desktop-only"'], + "children": [ + { + "name": '"span"', + "props": ['className:"rx-sticky-label"'], + "children": [{"contents": '"Built with Reflex"'}], + } + ], + }, + ], + } + + +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)")}"' + } + ], + } diff --git a/tests/units/reflex_components_sonner/test_toast.py b/tests/units/reflex_components_sonner/test_toast.py index bca21a536ed..fdf4b040b89 100644 --- a/tests/units/reflex_components_sonner/test_toast.py +++ b/tests/units/reflex_components_sonner/test_toast.py @@ -1,9 +1,11 @@ """Sonner toast component tests.""" import json +import subprocess +import sys 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 +27,46 @@ 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,{},)" + + +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", + "", + ) diff --git a/tests/units/reflex_components_ui/__init__.py b/tests/units/reflex_components_ui/__init__.py new file mode 100644 index 00000000000..e69de29bb2d 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_accordion.py b/tests/units/reflex_components_ui/components/test_accordion.py new file mode 100644 index 00000000000..0f5364799fc --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_accordion.py @@ -0,0 +1,232 @@ +"""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 +from tests.units.reflex_components_ui.render import tree + + +@pytest.fixture(autouse=True) +def ids(monkeypatch: pytest.MonkeyPatch): + """Number the items of each test that are given no value from one.""" + monkeypatch.setattr(accordion_module, "_ids", itertools.count(1)) + + +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":""'], + [], + ) + + +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. + """ + 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 + ), + type="single", + default_value="a", + variant="soft", + show_dividers=True, + duration=300, + ) + 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()) == ( + "UISDKAccordion", + ["className:sx_07523392e3_c", "collapsible:false", 'defaultValue:["a"]'], + [ + ( + "UISDKAccordionItem", + [item, '"data-rx-accordion-item":""', 'value:"a"'], + [ + ( + "UISDKAccordionHeader", + [header], + [("UISDKAccordionTrigger", [trigger], ['"One"', _chevron()])], + ), + ("UISDKAccordionPanel", [panel], ['"1"']), + ], + ), + ( + "UISDKAccordionItem", + [item, '"data-rx-accordion-item":""', "disabled:true", 'value:"b"'], + [ + ( + "UISDKAccordionHeader", + [header], + [("UISDKAccordionTrigger", [trigger], ['"Two"'])], + ), + ("UISDKAccordionPanel", [panel], ['"2"']), + ], + ), + ], + ) + + +def test_accordion_styles( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """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)", + } + + +class AccordionState(rx.State): + """What an accordion is bound to.""" + + open: list[str] = ["a"] + off: bool = False + + @rx.event + def set_open(self, value: str | list[str]): + """Follow the accordion. + + Args: + value: The values of the open items. + """ + self.open = value if isinstance(value, list) else [value] + + +def test_accordion_bound_to_state(ui_plugin: UIPlugin): + """A multiple accordion bound to state hands UI SDK its list, and hands over the list UI SDK says.""" + 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, + collapsible=True, + disabled=AccordionState.off, + ) + 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", + ( + "onValueChange:((_value) => (addEvents([(ReflexEvent(" + f'"{name}.set_open", ({{ ["value"] : _value }}), ({{ }})))], [_value], ' + "({ }))))" + ), + f"value:(Array.isArray({open_}) ? {open_} : ({open_} ? [{open_}] : []))", + ] + + +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", + ( + 'onValueChange:((value) => (((_value) => (addEvents([(ReflexEvent("_call_function", ' + '({ ["function"] : (() => (console?.["log"]("x"))), ["callback"] : null }), ' + '({ })))], [_value], ({ })))))(value[0] ?? ""))' + ), + ] + + +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", alias="UISDKAccordion"), + ImportVar(tag="AccordionItem", alias="UISDKAccordionItem"), + ImportVar(tag="AccordionHeader", alias="UISDKAccordionHeader"), + ImportVar(tag="AccordionTrigger", alias="UISDKAccordionTrigger"), + ImportVar(tag="AccordionPanel", alias="UISDKAccordionPanel"), + ], + } + + +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") # pyright: ignore[reportArgumentType] + 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_alert_dialog.py b/tests/units/reflex_components_ui/components/test_alert_dialog.py new file mode 100644 index 00000000000..854052502f4 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_alert_dialog.py @@ -0,0 +1,87 @@ +"""Tests for reflex_components_ui.components.alert_dialog.""" + +from reflex_components_ui.plugin import UIPlugin + +import reflex as rx +from tests.units.reflex_components_ui.render import tree + + +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. + + 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("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, + ), + default_open=True, + ) + assert tree(component.render()) == ( + "UISDKAlertDialog", + ["defaultOpen:true"], + [ + ("UISDKAlertDialogTrigger", ['render:(jsx("button", ({}), "Delete"))'], []), + ( + "Fragment", + [], + [ + ("UISDKAlertDialogBackdrop", ["className:sx_dd9768c199_c"], []), + ( + "UISDKAlertDialogContent", + [ + "className:sx_b7708e6de5_c", + 'initialFocus:"[data-rx-cancel]"', + "keepMounted:true", + ], + [ + ( + "UISDKAlertDialogTitle", + [ + "className:sx_29271ef72f_c", + 'render:(jsx("h1", ({})))', + ], + ['"Sure?"'], + ), + ( + "UISDKAlertDialogDescription", + ["className:sx_9b5373509f_c"], + ['"It goes."'], + ), + ( + "UISDKAlertDialogClose", + [ + '"data-rx-cancel":""', + 'render:(jsx("button", ({}), "Keep"))', + ], + [], + ), + ( + "UISDKAlertDialogClose", + [ + 'render:(jsx("button", ({}), "Delete"))', + 'value:"confirm"', + ], + [], + ), + ], + ), + ], + ), + ], + ) + + +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_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_avatar.py b/tests/units/reflex_components_ui/components/test_avatar.py new file mode 100644 index 00000000000..b94c089cb0a --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_avatar.py @@ -0,0 +1,95 @@ +"""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 +from tests.units.reflex_components_ui.render import tree + + +class AvatarState(rx.State): + """What an avatar is bound to.""" + + initials: str = "AB" + + +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()) == ( + "UISDKAvatar", + ["className:sx_119fa60175_c"], + [("UISDKAvatarFallback", ["className:sx_9cf1bef94d_c"], ['"R"'])], + ) + + +def test_avatar_image_and_its_fallback( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """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()) == ( + "UISDKAvatar", + ['className:sx_eecdbf58c4_c + " " + reflexUIClasses_4c7cd6a7ce'], + [ + ("UISDKAvatarFallback", ["className:sx_46859d4f4b_c"], ['"RX"']), + ( + "UISDKAvatarImage", + ['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", + } + + +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()) == ( + "UISDKAvatar", + ["className:sx_eecdbf58c4_c"], + [ + ( + "UISDKAvatarFallback", + [ + "className:sx_cc3b8d15e3_c", + f'"data-letters":pyStrLength({initials})', + ], + [initials], + ) + ], + ) + + +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", alias="UISDKAvatar"), + ImportVar(tag="AvatarFallback", alias="UISDKAvatarFallback"), + ImportVar(tag="AvatarImage", alias="UISDKAvatarImage"), + ], + } 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/components/test_button.py b/tests/units/reflex_components_ui/components/test_button.py new file mode 100644 index 00000000000..9582518cef2 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_button.py @@ -0,0 +1,1145 @@ +"""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_16addd9092_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)"}, + ":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", + "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(:is([data-state='open'], [data-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(: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(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "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])": "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_eb445af6ab_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)"}, + ":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", + "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_d9250aa972_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)"}, + ":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", + "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(:is([data-state='open'], [data-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)" + }, + ":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(:is([data-state='open'], [data-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))" + }, + ":is([data-state='open'], [data-open])": "linear-gradient(var(--black-a5), " + "transparent, " + "var(--white-a2))", + ":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(:is([data-state='open'], [data-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(:is([data-state='open'], [data-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(:is([data-state='open'], [data-open]), [data-disabled])": "none", + "[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 " + "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(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "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])": "2px", + }, + "filter": { + "[data-disabled]": "none", + ":active:not(:is([data-state='open'], [data-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))" + }, + ":is([data-state='open'], [data-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", + } + ] + + +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)"}, + ":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", + "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_16addd9092_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_b0c5b54627_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_fcdd32a514_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)"}, + ":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", + "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(:is([data-state='open'], [data-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(: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(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "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])": "2px", + }, + "position": "relative", + "height": "var(--base-button-height)", + "--rx-icon-opacity": "0.9", + }, + {"display": "contents", "visibility": "hidden"}, + { + "position": "absolute", + "borderTopWidth": "0", + "borderTopStyle": "none", + "borderTopColor": "currentcolor", + "borderRightWidth": "0", + "borderRightStyle": "none", + "borderRightColor": "currentcolor", + "borderBottomWidth": "0", + "borderBottomStyle": "none", + "borderBottomColor": "currentcolor", + "borderLeftWidth": "0", + "borderLeftStyle": "none", + "borderLeftColor": "currentcolor", + "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_ee694bd455_c + " " + ' + "(sx_ee694bd455_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_fcdd32a514_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_16addd9092_c", + '"data-disabled":true', + "disabled:true", + 'to:"/docs"', + ], + "children": [{"contents": '"Docs"'}], + } + + +def test_button_as_child_literal_var(ui_plugin: UIPlugin): + """A literal Var for as_child is read as its value, loading or not.""" + child = rx.el.a("Docs", href="/docs") + expected = rx.ui.button(child, as_child=True, loading=False).render() + assert expected["name"] == "ReactRouterLink" + assert ( + rx.ui.button(child, as_child=rx.Var.create(True), loading=False).render() + == expected + ) + assert ( + rx.ui.button("Save", as_child=rx.Var.create(False), loading=False).render() + == rx.ui.button("Save", loading=False).render() + ) + + +@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) # pyright: ignore[reportArgumentType] + 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_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/components/test_card.py b/tests/units/reflex_components_ui/components/test_card.py new file mode 100644 index 00000000000..0a0ec24c517 --- /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_a3eabfe8d9_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(: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, :is([data-state='open'], [data-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):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(:is([data-state='open'], [data-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(: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, :is([data-state='open'], [data-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):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", + }, + "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):is([data-state='open'], [data-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(:is([data-state='open'], [data-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):is([data-state='open'], [data-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(:is([data-state='open'], [data-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):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(: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, :is([data-state='open'], [data-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_a3eabfe8d9_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(: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, :is([data-state='open'], [data-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):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(:is([data-state='open'], [data-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/components/test_checkbox.py b/tests/units/reflex_components_ui/components/test_checkbox.py new file mode 100644 index 00000000000..00ee01570dd --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_checkbox.py @@ -0,0 +1,487 @@ +"""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_b87bd44530_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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "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_6ac964b510_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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "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": "currentcolor", + }, + "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": { + "default": "inherit", + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "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_846aafb601_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") # pyright: ignore[reportArgumentType] + 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") # pyright: ignore[reportArgumentType] + assert ( + str(error.value) + == 'rx.ui.checkbox: unknown size "4". The values are "1", "2", "3".' + ) 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..04d39d58b84 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_checkbox_cards.py @@ -0,0 +1,799 @@ +"""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_6eb5dc6fb4_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_6eb5dc6fb4_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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "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_4f13f0900c_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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-1)", + ":disabled": "var(--gray-a8)", + }, + }, + "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_6eb5dc6fb4_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") # pyright: ignore[reportArgumentType] + 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_checkbox_group.py b/tests/units/reflex_components_ui/components/test_checkbox_group.py new file mode 100644 index 00000000000..0bdac87d6cf --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_checkbox_group.py @@ -0,0 +1,728 @@ +"""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_8b52e7930c_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_8b52e7930c_c", + "defaultChecked:true", + "disabled:true", + 'name:"pick"', + 'type:"checkbox"', + 'value:"2"', + ], + "children": [], + }, + { + "name": '"div"', + "props": [], + "children": [ + { + "name": '"input"', + "props": [ + "className:sx_8b52e7930c_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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-12)", + ":disabled": "var(--gray-a8)", + }, + }, + "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_b87bd44530_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_b87bd44530_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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "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": "currentcolor", + }, + "backgroundImage": "none", + "boxSizing": "border-box", + "color": { + "default": "inherit", + "::after": { + "default": "var(--accent-contrast)", + ":disabled": "var(--gray-a8)", + }, + }, + "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") # pyright: ignore[reportArgumentType] + 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/components/test_color_mode.py b/tests/units/reflex_components_ui/components/test_color_mode.py new file mode 100644 index 00000000000..96e21d73273 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_color_mode.py @@ -0,0 +1,243 @@ +"""Tests for reflex_components_ui.components.color_mode.""" + +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 + +# What the icon of the color mode renders: a sun in light mode, a moon in dark. +ICON = { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": '(resolvedColorMode?.valueOf?.() === "light"?.valueOf?.())', + "true_value": { + "name": "Fragment", + "props": [], + "children": [{"name": "LucideSun", "props": [], "children": []}], + }, + "false_value": { + "name": "Fragment", + "props": [], + "children": [{"name": "LucideMoon", "props": [], "children": []}], + }, + } + ], +} + +TOGGLE = "onClick:((_e) => (toggleColorMode(_e)))" + + +def _icon_button_style( + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], + **overrides: Any, +) -> dict[str, Any]: + """Get the style of an icon button, with what a color mode button sets. + + Args: + declared_styles: The fixture that reads what an element declares. + compiled: The fixture that adds the styles a compile adds. + **overrides: The properties the color mode button sets beside. + + Returns: + The whole declared style. + """ + (style,) = declared_styles(compiled(rx.ui.icon_button("sun"))) + return { + **style, + "backgroundColor": "transparent", + "color": "inherit", + "cursor": {**style["cursor"], ":hover": "pointer"}, + "zIndex": "20", + **overrides, + } + + +def test_icon_follows_the_color_mode(): + assert rx.ui.color_mode.icon().render() == ICON + + +def test_icon_takes_components_of_its_own(): + rendered = rx.ui.color_mode.icon(rx.text("light"), rx.text("dark")).render() + assert rendered == rx.color_mode.icon(rx.text("light"), rx.text("dark")).render() + + +def test_button_toggles_the_color_mode( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """A transparent icon button in the flow of the page.""" + component = compiled(rx.ui.color_mode.button()) + assert component.render() == { + "name": '"button"', + "props": ["className:sx_7c9bd25a71_c", TOGGLE], + "children": [ICON], + } + assert declared_styles(component) == [_icon_button_style(declared_styles, compiled)] + + +def test_button_in_a_corner_is_fixed_there( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + corners: dict[LiteralPosition, dict[str, str]] = { + "top-left": {"top": "2rem", "left": "2rem"}, + "top-right": {"top": "2rem", "right": "2rem"}, + "bottom-left": {"bottom": "2rem", "left": "2rem"}, + "bottom-right": {"bottom": "2rem", "right": "2rem"}, + } + for position, edges in corners.items(): + component = compiled(rx.ui.color_mode.button(position=position)) + assert declared_styles(component) == [ + _icon_button_style(declared_styles, compiled, position="fixed", **edges) + ] + + +def test_button_keeps_what_its_props_set( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """A CSS position is the position, and a prop wins over the placement.""" + component = compiled( + rx.ui.color_mode.button(position="top-left", top="10px", color="red") + ) + assert declared_styles(component) == [ + _icon_button_style( + declared_styles, + compiled, + position="fixed", + top="10px", + left="2rem", + color="red", + ) + ] + # A CSS position, which the Radix button takes too, though its type does not. + component = compiled(rx.ui.color_mode.button(position="sticky")) # pyright: ignore[reportArgumentType] + assert declared_styles(component) == [ + _icon_button_style(declared_styles, compiled, position="sticky") + ] + + +def test_button_placed_by_state( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """Each edge is a custom property the browser chooses a value of.""" + position = rx.Var("corner", _var_type=str) + component = compiled(rx.ui.color_mode.button(position=position)) + styles = component.render()["props"][2] + assert styles == ( + 'style:({ "--v0": ((["top-left", "top-right", "bottom-left", ' + '"bottom-right"].includes(corner) ? "fixed" : corner)) ?? "initial", ' + '"--v1": ((["top-left", "top-right"].includes(corner) ? "2rem" : "")) ' + '?? "initial", "--v2": ((["bottom-left", "bottom-right"].includes(corner) ' + '? "2rem" : "")) ?? "initial", "--v3": ((["top-left", ' + '"bottom-left"].includes(corner) ? "2rem" : "")) ?? "initial", ' + '"--v4": ((["top-right", "bottom-right"].includes(corner) ? "2rem" : "")) ' + '?? "initial" })' + ) + + +def test_button_that_allows_the_system_mode_opens_a_menu( + ui_plugin: UIPlugin, + 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 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": "UISDKMenuTrigger", + "props": [ + ( + 'render:(jsx("button", ({className:sx_7c9bd25a71_c}), (jsx(Fragment, ' + '({}), ((resolvedColorMode?.valueOf?.() === "light"?.valueOf?.()) ? ' + "(jsx(Fragment, ({}), (jsx(LucideSun, ({}))))) : (jsx(Fragment, ({}), " + "(jsx(LucideMoon, ({}))))))))))" + ) + ], + "children": [], + } + items = content["children"][0]["children"][0]["children"] + assert [(item["children"][0]["contents"], item["props"][1]) for item in items] == [ + ( + f'"{mode.title()}"', + ( + 'onClick:((_e) => (addEvents([(ReflexEvent("_call_function", ' + f'({{ ["function"] : (() => (setColorMode("{mode}"))), ' + '["callback"] : null }), ({ })))], [_e], ({ }))))' + ), + ) + for mode in ("light", "dark", "system") + ] + 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( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + component = compiled(rx.ui.color_mode.switch(size="3")) + assert component.render() == { + "name": '"input"', + "props": [ + 'checked:!((resolvedColorMode?.valueOf?.() === "light"?.valueOf?.()))', + "className:sx_31b0c2f6a1_c", + "onChange:((_e) => (toggleColorMode(_e)))", + 'role:"switch"', + 'type:"checkbox"', + ], + "children": [], + } + assert declared_styles(component) == declared_styles( + compiled(rx.ui.switch(size="3")) + ) + + +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") + ) + 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): + 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/components/test_context_menu.py b/tests/units/reflex_components_ui/components/test_context_menu.py new file mode 100644 index 00000000000..bc8dffa5c72 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_context_menu.py @@ -0,0 +1,274 @@ +"""Tests for reflex_components_ui.components.context_menu.""" + +from typing import Any + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_ui.components.radio_group import RadioGroupRoot +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" + + +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))], + ) + + +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), + menu.content( + menu.item("Copy"), + menu.checkbox("Grid", default_checked=True, shortcut="⌘ G"), + 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", + ) + item = "className:sx_5c93cdaf19_c" + value = component.children[1].children[0].children[0].children[1]._key # pyright: ignore[reportAttributeAccessIssue] + assert tree(component.render()) == ( + "UISDKMenu", + ["loop:false", "modal:false"], + [ + ( + "UISDKMenuContextTrigger", + ["disabled:true", 'render:(jsx("div", ({}), "Area"))'], + [], + ), + ( + "UISDKMenuContent", + [ + 'align:"start"', + "alignOffset:-4", + "className:sx_1555e4b025_c", + "collisionPadding:10", + 'side:"right"', + "sideOffset:2", + ], + [ + _scrolled( + ("UISDKMenuItem", [item], ['"Copy"']), + ( + "UISDKMenuCheckboxItem", + [ + item, + "closeOnSelect:true", + "defaultChecked:true", + f'value:"{value}"', + ], + [ + ('"span"', ["className:sx_0796999dae_c"], [("svg",)]), + '"Grid"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + ['"\\u2318 G"'], + ), + ], + ), + ('"div"', ["className:sx_b13742d240_c"], ['"View"']), + ("UISDKMenuGroup", [], [("UISDKMenuItem", [item], ['"Zoom"'])]), + ("UISDKMenuSeparator", ["className:sx_834f03d11d_c"], []), + ( + "UISDKMenuSub", + ["loop:false"], + [ + ( + "UISDKMenuSubTrigger", + [item], + [ + '"Share"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + [("svg",)], + ), + ], + ), + ( + "UISDKMenuSubContent", + [ + "alignOffset:-4", + "className:sx_94fcdb63b8_c", + "collisionPadding:10", + "sideOffset:1", + ], + [_scrolled(("UISDKMenuItem", [item], ['"Email"']))], + ), + ], + ), + ) + ], + ), + ], + ) + + +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 is bound to.""" + + grid: bool = True + unit: str = "px" + + @rx.event + def set_grid(self, grid: bool): + """Follow the checkbox item. + + Args: + grid: Whether it is checked. + """ + self.grid = grid + + @rx.event + def set_unit(self, unit: str): + """Follow the radio group. + + Args: + unit: The unit. + """ + self.unit = unit + + +def test_context_menu_checkbox_bound_to_state(ui_plugin: UIPlugin): + """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, value="grid" + ) + assert item.render()["props"] == [ + f"checked:{GridState.grid!s}", + "className:sx_b9894c01e4_c", + "closeOnSelect:true", + ( + "onCheckedChange:((_ev_0) => (addEvents(" + f'[(ReflexEvent("{name}.set_grid", ({{ ["grid"] : _ev_0 }}), ({{ }})))], ' + "[_ev_0], ({ }))))" + ), + '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 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()["name"], group.render()["props"]) == ("UISDKMenuGroup", []) + + +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", alias="UISDKMenu"), + ImportVar(tag="MenuContextTrigger", alias="UISDKMenuContextTrigger"), + ImportVar(tag="MenuContent", alias="UISDKMenuContent"), + ImportVar(tag="MenuItem", alias="UISDKMenuItem"), + ImportVar(tag="MenuCheckboxItem", alias="UISDKMenuCheckboxItem"), + ], + } + + +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_data_list.py b/tests/units/reflex_components_ui/components/test_data_list.py new file mode 100644 index 00000000000..45e87f0b2d2 --- /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/components/test_dialog.py b/tests/units/reflex_components_ui/components/test_dialog.py new file mode 100644 index 00000000000..7b538eea5ce --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_dialog.py @@ -0,0 +1,199 @@ +"""Tests for reflex_components_ui.components.dialog.""" + +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 + +DIALOG = "@ui-sdk/react@0.1.0-beta.17/dialog" + + +class DialogState(rx.State): + """What a dialog is bound to.""" + + 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")), + rx.ui.dialog.content( + rx.ui.dialog.title("Title"), + rx.ui.dialog.description("Text"), + rx.ui.dialog.close(rx.el.button("Close")), + size="2", + ), + default_open=True, + ) + assert component.render() == { + "name": "UISDKDialog", + "props": ["defaultOpen:true"], + "children": [ + { + "name": "UISDKDialogTrigger", + "props": ['render:(jsx("button", ({}), "Open"))'], + "children": [], + }, + { + "name": "Fragment", + "props": [], + "children": [ + { + "name": "UISDKDialogBackdrop", + "props": ["className:sx_dd9768c199_c"], + "children": [], + }, + { + "name": "UISDKDialogContent", + "props": ["className:sx_b7708e6de5_c"], + "children": [ + { + "name": "UISDKDialogTitle", + "props": [ + "className:sx_29271ef72f_c", + 'render:(jsx("h1", ({})))', + ], + "children": [{"contents": '"Title"'}], + }, + { + "name": "UISDKDialogDescription", + "props": ["className:sx_9b5373509f_c"], + "children": [{"contents": '"Text"'}], + }, + { + "name": "UISDKDialogClose", + "props": ['render:(jsx("button", ({}), "Close"))'], + "children": [], + }, + ], + }, + ], + }, + ], + } + + +def test_dialog_bound_to_state(ui_plugin: UIPlugin): + """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.content( + "x", + on_escape_key_down=DialogState.set_open(False), + on_open_auto_focus=rx.console_log("in"), + ), + open=DialogState.open, + on_open_change=DialogState.set_open, + ) + handler = ( + '"reflex___state____state.tests___units___reflex_components_ui___' + 'components___test_dialog____dialog_state.set_open"' + ) + assert component.render()["props"] == [ + ( + "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, " + "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?.(); })" + ), + ( + "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_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 "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + DIALOG: [ + ImportVar(tag="Dialog", alias="UISDKDialog"), + ImportVar(tag="DialogTrigger", alias="UISDKDialogTrigger"), + ImportVar(tag="DialogBackdrop", alias="UISDKDialogBackdrop"), + ImportVar(tag="DialogContent", alias="UISDKDialogContent"), + ], + } + + +@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_drawer.py b/tests/units/reflex_components_ui/components/test_drawer.py new file mode 100644 index 00000000000..8f63fcf4b33 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_drawer.py @@ -0,0 +1,107 @@ +"""Tests for reflex_components_ui.components.drawer.""" + +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 + + @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): + """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.portal( + rx.ui.drawer.overlay(), + rx.ui.drawer.content( + rx.ui.drawer.handle(), + rx.ui.drawer.title("Files"), + rx.ui.drawer.description("Yours."), + rx.ui.drawer.close("Done", as_child=False), + ), + ), + direction="left", + modal=False, + dismissible=False, + handle_only=True, + snap_points=[0.5, 1], + on_animation_end=DrawerState.set_settled, + ) + assert tree(component.render()) == ( + "UISDKDrawer", + [ + "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]", + ], + [ + ("UISDKDrawerTrigger", ['render:(jsx("button", ({}), "Open"))'], []), + ( + "Fragment", + [], + [ + ("UISDKDrawerBackdrop", ["className:sx_165a6b083a_c"], []), + ( + "UISDKDrawerContent", + ["className:sx_e2d63de2b0_c"], + [ + ( + "UISDKDrawerHandle", + ["className:sx_c352e99684_c"], + [ + ( + '"span"', + [ + '"aria-hidden":true', + "className:sx_90a94c0153_c", + ], + [], + ) + ], + ), + ( + "UISDKDrawerTitle", + ["className:sx_0590ef4057_c"], + ['"Files"'], + ), + ( + "UISDKDrawerDescription", + ["className:sx_faadb9eee6_c"], + ['"Yours."'], + ), + ("UISDKDrawerClose", [], ['"Done"']), + ], + ), + ], + ), + ], + ) 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..ef3122937f4 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_dropdown_menu.py @@ -0,0 +1,344 @@ +"""Tests for reflex_components_ui.components.dropdown_menu.""" + +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 + +MENU = "@ui-sdk/react@0.1.0-beta.17/menu" + + +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 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="edit"), + menu.separator(), + menu.sub( + menu.sub_trigger("More"), + menu.sub_content(menu.item("Archive", disabled=True)), + ), + size="1", + variant="soft", + loop=True, + side="top", + side_offset=8, + avoid_collisions=False, + ), + modal=False, + dir="rtl", + ) + item = "className:sx_5c93cdaf19_c" + assert _tree(component.render()) == ( + "UISDKMenu", + ["loop:true", "modal:false"], + [ + ("UISDKMenuTrigger", ['render:(jsx("button", ({}), "Options"))'], []), + ( + "UISDKMenuContent", + [ + 'align:"start"', + "className:sx_94fcdb63b8_c", + "collisionPadding:10", + 'side:"top"', + "sideOffset:8", + ], + [ + _scrolled( + ( + "UISDKMenuItem", + [item, 'label:"edit"'], + [ + '"Edit"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + ['"\\u2318 E"'], + ), + ], + ), + ("UISDKMenuSeparator", ["className:sx_834f03d11d_c"], []), + ( + "UISDKMenuSub", + ["loop:false"], + [ + ( + "UISDKMenuSubTrigger", + [item], + [ + '"More"', + ( + '"div"', + ["className:sx_da7de3c8ae_c"], + [("svg",)], + ), + ], + ), + ( + "UISDKMenuSubContent", + [ + "alignOffset:-4", + "className:sx_94fcdb63b8_c", + "collisionPadding:10", + "sideOffset:1", + ], + [ + _scrolled(( + "UISDKMenuItem", + [item, "disabled:true"], + ['"Archive"'], + )) + ], + ), + ], + ), + ) + ], + ), + ], + ) + + +def test_dropdown_menu_styles( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """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")) + ) + 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", + }, + }, + "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)", + }, + "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)", + }, + "backgroundColor": { + "[data-highlighted]": "var(--accent-9)", + ":not([data-highlighted])[data-open]": "var(--gray-a3)", + }, + "--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 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.content( + 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, + ) + handler = ( + '"reflex___state____state.tests___units___reflex_components_ui___' + 'components___test_dropdown_menu____menu_state.set_shown"' + ) + assert _tree(component.render()) == ( + "UISDKMenu", + [ + "loop:false", + ( + "onOpenChange:((value, details) => { const change = ((_ev_0) => " + f'(addEvents([(ReflexEvent({handler}, ({{ ["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?.(); })" + ), + ( + "open:reflex___state____state__tests___units___reflex_components_ui___" + "components___test_dropdown_menu____menu_state.shown_rx_state_" + ), + ], + [ + ( + "UISDKMenuContent", + [ + 'align:"start"', + "className:sx_cf3c9fe7e2_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:4", + ], + [ + _scrolled(( + "UISDKMenuItem", + [ + "className:sx_b9894c01e4_c", + ( + "onSelect:((...args) => (addEvents([(ReflexEvent(" + f'{handler}, ({{ ["shown"] : false }}), ({{ }})))], ' + "args, ({ }))))" + ), + ], + ['"Edit"'], + )) + ], + ) + ], + ) + + +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 "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", alias="UISDKMenu"), + ImportVar(tag="MenuTrigger", alias="UISDKMenuTrigger"), + ImportVar(tag="MenuContent", alias="UISDKMenuContent"), + ImportVar(tag="MenuItem", alias="UISDKMenuItem"), + ], + } + + +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_form.py b/tests/units/reflex_components_ui/components/test_form.py new file mode 100644 index 00000000000..024540118df --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_form.py @@ -0,0 +1,523 @@ +"""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 +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): + """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 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"), + 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 tree(component.render()) == ( + '"form"', + [ + "className:sx_5073704993_c", + 'id:"signup"', + "onSubmit:handleSubmit_ff7a0ed8ca0437fd853c637504ba1398", + "ref:ref_signup", + ], + [ + ( + "UISDKField", + ["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"', + 'name:"email"', + "ref:ref_email", + "required:true", + "spellCheck:false", + 'type:"email"', + ], + [], + ) + ], + ), + ( + "UISDKFieldError", + [MESSAGE, 'match:"valueMissing"'], + ['"Needed"'], + ), + ('"span"', [MESSAGE], ['"Always"']), + ("UISDKFieldError", [MESSAGE, "match:true"], ['"Forced"']), + ], + ), + # UI SDK shows an error outside a field only when it is forced. + ("UISDKFieldError", [MESSAGE, 'match:"valueMissing"'], ['"Outside"']), + ('"button"', ['type:"submit"'], ['"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 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")), + 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, + ) + 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", + f"onReset:{clear}", + "onSubmit:handleSubmit_d0cc17a26357c93f98ce435bb75ef574", + f"onSubmitCapture:{clear}", + ], + [ + ( + "UISDKField", + [ + "className:sx_7fb5ccb001_c", + f"invalid:({taken} || undefined)", + 'name:"code"', + f"ref:({taken} ? {FOCUS_INVALID} : undefined)", + ], + [ + ( + '"input"', + [ + f'"aria-invalid":({taken} || undefined)', + 'id:"code"', + 'name:"mine"', + "ref:ref_code", + ], + [], + ), + ( + "UISDKFieldError", + [MESSAGE, f'match:({taken} ? true : "valid")'], + ['"Taken"'], + ), + ], + ) + ], + ) + + +def test_form_without_messages( + ui_plugin: UIPlugin, +): + """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"), + 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": "UISDKField", + "props": ["className:sx_7fb5ccb001_c", 'name:"notes"'], + "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_16addd9092_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") # pyright: ignore[reportArgumentType] + 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_names_its_control( + ui_plugin: UIPlugin, monkeypatch: pytest.MonkeyPatch +): + """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", + server_invalid=True, + ) + assert tree(field.render()) == ( + "UISDKField", + [ + "className:sx_7fb5ccb001_c", + "invalid:true", + 'name:"age"', + f"ref:{FOCUS_INVALID}", + ], + [ + ( + '"label"', + ["className:sx_3f1c4be050_c", 'htmlFor:"rx-form-field-4"'], + ['"Age"'], + ), + ( + "UISDKFieldControl", + [ + '"aria-invalid":(true || undefined)', + 'id:"rx-form-field-4"', + 'name:"years"', + ], + [], + ), + ], + ) + + +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", alias="UISDKField"), + ImportVar(tag="FieldControl", alias="UISDKFieldControl"), + ImportVar(tag="FieldError", alias="UISDKFieldError"), + ], + } 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..b898d209e85 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_hover_card.py @@ -0,0 +1,126 @@ +"""Tests for reflex_components_ui.components.hover_card.""" + +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 +from tests.units.reflex_components_ui.render import tree + + +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. + + 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 + ), + default_open=True, + close_delay=50, + ) + assert tree(component.render()) == ( + "UISDKHoverCard", + ["closeDelay:50", "defaultOpen:true", "delay:200"], + [ + ( + "UISDKHoverCardTrigger", + [ + 'render:(jsx(ReactRouterLink, ({to:"https://radix-ui.com"}), "Radix"))' + ], + [], + ), + ( + "UISDKHoverCardContent", + [ + 'align:"start"', + "className:sx_b74f469818_c", + "collisionPadding:10", + 'side:"right"', + "sideOffset:4", + ], + ['"Inside"'], + ), + ], + ) + + +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 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 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")), + rx.ui.hover_card.content("Inside"), + open=HoverCardState.shown, + on_open_change=HoverCardState.set_shown, + open_delay=HoverCardState.wait, + ) + assert component.render()["props"] == [ + "closeDelay:150", + f"delay:{HoverCardState.wait!s}", + ( + "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_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 "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/hover-card": [ + ImportVar(tag="HoverCard", alias="UISDKHoverCard"), + ImportVar(tag="HoverCardTrigger", alias="UISDKHoverCardTrigger"), + ImportVar(tag="HoverCardContent", alias="UISDKHoverCardContent"), + ], + } + + +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_icon_button.py b/tests/units/reflex_components_ui/components/test_icon_button.py new file mode 100644 index 00000000000..6994c034016 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_icon_button.py @@ -0,0 +1,287 @@ +"""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_36db4f79fd_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)"}, + ":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", + "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(:is([data-state='open'], [data-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(: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(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "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])": "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_f252cc983a_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)"}, + ":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", + "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)"}, + ":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", + "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_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_popover.py b/tests/units/reflex_components_ui/components/test_popover.py new file mode 100644 index 00000000000..cc2568c5b0f --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_popover.py @@ -0,0 +1,183 @@ +"""Tests for reflex_components_ui.components.popover.""" + +from collections.abc import Callable +from typing import Any, get_args + +import pytest +from reflex_base.utils.imports import ImportVar +from reflex_components_internal.components.base.popover import PopoverRoot +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 reflex.compiler.utils import compile_imports +from tests.units.reflex_components_ui.render import tree + +STATE = ( + "tests___units___reflex_components_ui___components___test_popover____popover_state" +) + + +class PopoverState(rx.State): + """What a popover is bound to.""" + + shown: bool = False + + @rx.event + def set_shown(self, shown: bool): + """Follow the popover. + + Args: + shown: Whether it is open. + """ + self.shown = shown + + +def test_popover(ui_plugin: UIPlugin): + """A popover is the parts of UI SDK, placed as Radix Themes places it. + + 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( + "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, + ) + handler = f'"reflex___state____state.{STATE}.set_shown"' + assert tree(component.render()) == ( + "UISDKPopover", + [ + "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_", + ], + [ + ("UISDKPopoverTrigger", ['render:(jsx("button", ({}), "Open"))'], []), + ( + "UISDKPopoverContent", + [ + 'align:"start"', + "className:sx_85c95c6603_c", + "collisionPadding:10", + 'side:"top"', + "sideOffset:12", + ], + [ + '"Hi"', + ( + "UISDKPopoverClose", + ['render:(jsx("button", ({}), "Close"))'], + [], + ), + ], + ), + ], + ) + + +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("Hi") + ) + 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)], + "@ui-sdk/react@0.1.0-beta.17/popover": [ + ImportVar(tag="Popover", alias="UISDKPopover"), + ImportVar(tag="PopoverTrigger", alias="UISDKPopoverTrigger"), + ImportVar(tag="PopoverContent", alias="UISDKPopoverContent"), + ], + } + + +def test_popover_beside_a_base_ui_popover_compiles(ui_plugin: UIPlugin): + """A page with a popover of Base UI and rx.ui.popover imports both: UI SDK's parts under names of their own.""" + component = rx.fragment( + PopoverRoot.create(), + rx.ui.popover.root( + rx.ui.popover.trigger(rx.el.button("B")), rx.ui.popover.content("b") + ), + ) + assert [ + imports + for imports in compile_imports(component._get_all_imports()) + if imports["lib"].endswith("popover") + ] == [ + {"lib": "@base-ui/react/popover", "default": "", "rest": ["Popover"]}, + { + "lib": "@ui-sdk/react/popover", + "default": "", + "rest": [ + "Popover as UISDKPopover", + "PopoverContent as UISDKPopoverContent", + "PopoverTrigger as UISDKPopoverTrigger", + ], + }, + ] + + +# The sides of a popover, in the order of the Literal its 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. +SIDES = get_args(get_args(PopoverContent.get_fields()["side"].annotated_type)[0]) + + +def test_popover_has_four_sides(): + assert sorted(SIDES) == ["bottom", "left", "right", "top"] + + +@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 ' + + ", ".join(f'"{side}"' for side in SIDES) + + ".", + ), + ], +) +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/components/test_popup.py b/tests/units/reflex_components_ui/components/test_popup.py new file mode 100644 index 00000000000..18bb6558b1e --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_popup.py @@ -0,0 +1,44 @@ +"""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 + +KEY = 'key:"a"' + + +@pytest.mark.parametrize( + ("root", "name", "props"), + [ + (rx.ui.popover.root, "UISDKPopover", [KEY]), + (rx.ui.dropdown_menu.root, "UISDKMenu", [KEY, "loop:false"]), + (rx.ui.dropdown_menu.sub, "UISDKMenuSub", [KEY, "loop:false"]), + (rx.ui.context_menu.root, "UISDKMenu", [KEY, "loop:false"]), + (rx.ui.context_menu.sub, "UISDKMenuSub", [KEY, "loop:false"]), + (rx.ui.hover_card.root, "UISDKHoverCard", ["closeDelay:150", "delay:200", KEY]), + ], +) +def test_a_popup_in_a_list_keeps_its_key( + 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 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. + 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, props) 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..2d8ade2b556 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_progress.py @@ -0,0 +1,365 @@ +"""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": ({limit}) ?? "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": limit}) + 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_9b58edc65a_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) == [ + # The maximum the bar is read out with, not the one given. + track(**{"--progress-value": "150", "--progress-max": "100"}), + indicator(), + ] + # A value that is one of the checked maximum is a share of it. + [root, _] = declared_styles(rx.ui.progress(value=25, max=-1)) + assert root == track(**{"--progress-value": "25", "--progress-max": "100"}) + 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_radio_cards.py b/tests/units/reflex_components_ui/components/test_radio_cards.py new file mode 100644 index 00000000000..48b018cb2c3 --- /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") # pyright: ignore[reportArgumentType] + 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/components/test_radio_group.py b/tests/units/reflex_components_ui/components/test_radio_group.py new file mode 100644 index 00000000000..2330558ff65 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_radio_group.py @@ -0,0 +1,695 @@ +"""Tests for reflex_components_ui.components.radio_group.""" + +import itertools +import re +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") # pyright: ignore[reportArgumentType] + 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()] == [ # pyright: ignore[reportAttributeAccessIssue] + '"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"] 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 == [ + [ + [ + "className:sx_8f60d95144_c", + f'name:"rx-radio-{number}"', + 'type:"radio"', + f'value:"{value}"', + ] + for value in values + ] + for number, values in ((7, "12"), (8, "1")) + ] + + +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} # pyright: ignore[reportAttributeAccessIssue] + assert item._element_styles().style.style["--radio-size"] == ( # pyright: ignore[reportAttributeAccessIssue] + "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_)))" + ) + # 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"'], + "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_scroll_area.py b/tests/units/reflex_components_ui/components/test_scroll_area.py new file mode 100644 index 00000000000..2ac1f14fcb5 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_scroll_area.py @@ -0,0 +1,160 @@ +"""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", + "tabIndex:0", + ], + "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", "tabIndex:0"], + "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, + }, + ] + + +def test_scroll_area_tab_stop_can_be_overridden(ui_plugin: UIPlugin): + """The area is a tab stop unless the caller gives it another tab index.""" + assert rx.ui.scroll_area("Text").render()["props"] == [ + "className:sx_d0de57eb68_c", + "tabIndex:0", + ] + assert rx.ui.scroll_area( + "Text", custom_attrs={"tabIndex": -1, "data-kind": "log"} + ).render()["props"] == [ + "className:sx_d0de57eb68_c", + '"data-kind":"log"', + "tabIndex:-1", + ] 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..b510b37bacd --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_segmented_control.py @@ -0,0 +1,237 @@ +"""Tests for reflex_components_ui.components.segmented_control.""" + +import re +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 +from tests.units.reflex_components_ui.render import tree + +# 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}"'], + ), + ], + ) + + +SEPARATOR = ('"span"', ["className:sx_f0662e97c2_c"], []) + + +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): + """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"), + default_value="2", + size="3", + variant="classic", + radius="full", + color_scheme="ruby", + type="multiple", + id="views", + ) + assert tree(component.render()) == ( + "UISDKSegmentedControl", + [ + ( + 'className:sx_bf2c61f2b5_c + " " + reflexUIClasses_e201574881 + " " + ' + "reflexUIClasses_4c7cd6a7ce" + ), + 'defaultValue:"2"', + 'id:"views"', + REFUSES, + "ref:ref_views", + ], + [ + ( + "UISDKSegmentedControlItem", + [ + "className:sx_c3ab422107_c", + '"data-rx-segmented-item":""', + 'id:"one"', + "ref:ref_one", + 'value:"1"', + ], + [SEPARATOR, _text("One")], + ), + ( + "UISDKSegmentedControlItem", + [ + "className:sx_f1f474e393_c", + '"data-rx-segmented-item":""', + 'value:"2"', + ], + [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 { + key: first[key] + for key in ( + "borderTopLeftRadius", + "borderTopRightRadius", + "outlineStyle", + "--rx-segmented-active-opacity", + ) + } == { + "borderTopLeftRadius": { + ":first-of-type": "inherit", + ":focus-visible": "inherit", + }, + "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", + ( + '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}", + ] + + +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") # pyright: ignore[reportArgumentType] + 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 the indicator is placed at the item of the 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, + ) + 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"{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"({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; 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) + ]) + style = twelve._element_styles().style.style # pyright: ignore[reportAttributeAccessIssue] + assert style["--rx-segmented-index"] == { + "default": "var(--rx-segmented-index-of-value, 0)", + **{ + f":has(> button:nth-of-type({position})[data-checked])": position - 1 + for position in range(1, 13) + }, + } + assert style["--rx-segmented-count"] == 12 + + +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 { + 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", alias="UISDKSegmentedControl"), + ImportVar(tag="SegmentedControlItem", alias="UISDKSegmentedControlItem"), + ], + } 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..86c90329122 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_select.py @@ -0,0 +1,266 @@ +"""Tests for reflex_components_ui.components.select.""" + +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 select as select_module +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 + +STATE = ( + "tests___units___reflex_components_ui___components___test_select____select_state" +) + + +class SelectState(rx.State): + """What a select is bound to.""" + + fruit: str = "a" + fruits: list[str] = ["a", "b"] + + @rx.event + def set_fruit(self, fruit: str): + """Follow the select. + + Args: + fruit: The chosen value. + """ + self.fruit = fruit + + +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. + + Args: + text: What the option shows, as rendered. + *props: Its props, after its class name. + + Returns: + The projection. + """ + return ( + "UISDKSelectItem", + ["className:sx_354c170aac_c", *props], + [ + ("UISDKSelectItemIndicator", ["className:sx_9209c0ff85_c"], [("svg",)]), + ('"span"', [], [text]), + ], + ) + + +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="soft"), + rx.ui.select.content( + rx.ui.select.group( + 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(), + position="item-aligned", + variant="soft", + ), + size="1", + name="fruit", + required=True, + value=SelectState.fruit, + on_change=SelectState.set_fruit, + ) + assert tree(component.render()) == ( + "UISDKSelect", + [ + "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_", + ], + [ + ( + "UISDKSelectTrigger", + ["className:sx_590c531cfc_c"], + [ + ( + "UISDKSelectValue", + ["className:sx_94480a599d_c", 'placeholder:"Pick"'], + [], + ), + ("svg",), + ], + ), + ( + "UISDKSelectContent", + [ + 'align:"start"', + "alignItemWithTrigger:true", + "className:sx_16a9d4ef9b_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:4", + ], + [ + ( + "UISDKSelectGroup", + [], + [ + ( + "UISDKSelectGroupLabel", + ["className:sx_4c825b9931_c"], + ['"Fruit"'], + ), + _item('"Apple"', 'value:"a"'), + _item('"Banana"', "disabled:true", 'value:"b"'), + ], + ), + ("UISDKSelectSeparator", ["className:sx_2d671c061b_c"], []), + ], + ), + ], + ) + + +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()) == ( + "UISDKSelect", + ["loop:false"], + [ + ( + "UISDKSelectTrigger", + ["className:sx_812cedac46_c"], + [("UISDKSelectValue", ["className:sx_94480a599d_c"], []), ("svg",)], + ), + ( + "UISDKSelectContent", + [ + 'align:"start"', + "className:sx_42734c738f_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:4", + ], + [ + ( + "UISDKSelectGroup", + [], + [ + ( + "UISDKSelectGroupLabel", + ["className:sx_4c825b9931_c"], + ['"Letters"'], + ), + _item('"a"', 'value:"a"'), + _item('"b"', 'value:"b"'), + ], + ), + ], + ), + ], + ) + + +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"'], + ) + + +def test_select_highlights_by_ui_sdk( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """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)", + }, + "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", alias="UISDKSelect"), + ImportVar(tag="SelectTrigger", alias="UISDKSelectTrigger"), + ImportVar(tag="SelectValue", alias="UISDKSelectValue"), + ImportVar(tag="SelectContent", alias="UISDKSelectContent"), + ImportVar(tag="SelectGroup", alias="UISDKSelectGroup"), + ImportVar(tag="SelectItem", alias="UISDKSelectItem"), + ImportVar(tag="SelectItemIndicator", alias="UISDKSelectItemIndicator"), + ], + } + + +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") # pyright: ignore[reportArgumentType] + 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") # pyright: ignore[reportArgumentType] + # 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}.' + ) + + +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") # pyright: ignore[reportArgumentType] + assert ( + str(error.value) + == 'rx.ui.select.trigger: unknown variant "outline". The values are "classic", "surface", "soft", "ghost".' + ) 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/components/test_skeleton.py b/tests/units/reflex_components_ui/components/test_skeleton.py new file mode 100644 index 00000000000..f429e67b894 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_skeleton.py @@ -0,0 +1,462 @@ +"""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 + + +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) == [ + { + "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( + 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) == [ + { + "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( + 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_16addd9092_c) + " " + sx_596747f37d_c', + '"data-rx-skeleton":""', + 'id:"save"', + "inert:true", + "ref:ref_save", + "tabIndex:-1", + ], + "children": [{"contents": '"Save"'}], + } + 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)"}, + "width": "120px !important", + }, + { + "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)"}, + ":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", + "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(:is([data-state='open'], [data-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(: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(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "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])": "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_16addd9092_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)"}, + ":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", + "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(:is([data-state='open'], [data-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(: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(:is([data-state='open'], [data-open]), [data-disabled], :focus-visible)": "0.5em" + }, + ":focus-visible:not([data-disabled])": "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])": "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/components/test_slider.py b/tests/units/reflex_components_ui/components/test_slider.py new file mode 100644 index 00000000000..737a5723585 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_slider.py @@ -0,0 +1,224 @@ +"""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 +from tests.units.reflex_components_ui.render import tree + + +def _parts(control: str, track: str, fill: str, area: str, *thumbs: Any) -> Any: + """The parts of a slider inside its root. + + 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. + + Returns: + The projection of the control. + """ + return [ + ( + "UISDKSliderControl", + [f"className:{control}"], + [ + ( + "UISDKSliderTrack", + [f"className:{track}"], + [("UISDKSliderIndicator", [f"className:{fill}"], [])], + ), + ('"span"', [f"className:{area}"], list(thumbs)), + ], + ) + ] + + +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, + ) + assert tree(slider.render()) == ( + "UISDKSlider", + [ + "className:sx_cf9e3f467c_c", + "defaultValue:[40]", + 'id:"vol"', + "max:200", + "min:0", + 'name:"vol"', + "ref:ref_vol", + "step:5", + ], + _parts( + "sx_9d6c9b96ec_c", + "sx_ba51ac2911_c", + "sx_cb84de2a22_c", + "sx_303e2c1e35_c", + ( + "UISDKSliderThumb", + ['"aria-label":"Volume"', "className:sx_3ebcf889ae_c", "index:0"], + [], + ), + ), + ) + + +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" + ) + thumb = "className:sx_fb79566a6a_c" + assert tree(slider.render()) == ( + "UISDKSlider", + [ + '"aria-label":"Span"', + "className:sx_7a1da8ae44_c", + "defaultValue:[20, 60]", + "disabled:true", + 'orientation:"vertical"', + ], + _parts( + "sx_c3c3faff51_c", + "sx_1b5891cf0a_c", + "sx_71e44b49d0_c", + "sx_ec96b33674_c", + ("UISDKSliderThumb", ['"aria-label":"Minimum"', thumb, "index:0"], []), + ("UISDKSliderThumb", ['"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_styles( + ui_plugin: UIPlugin, declared_styles: Callable[[Any], list[dict[str, Any]]] +): + """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)", + }, + "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): + """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") # pyright: ignore[reportArgumentType] + assert ( + str(error.value) + == 'rx.ui.slider: unknown radius "large". The values are "none", "small", "full".' + ) + + +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 over the values UI SDK says.""" + name = SliderState.get_full_name() + slider = rx.ui.slider( + value=SliderState.span, + on_change=SliderState.set_span, + on_value_commit=SliderState.set_span, + ) + handler = ( + f'((_value) => (addEvents([(ReflexEvent("{name}.set_span", ' + '({ ["span"] : _value }), ({ })))], [_value], ({ }))))' + ) + assert slider.render()["props"] == [ + "className:sx_9d165cc942_c", + f"onValueChange:{handler}", + f"onValueCommit:{handler}", + f"value:{SliderState.span!s}", + ] + 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_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", alias="UISDKSlider"), + ImportVar(tag="SliderControl", alias="UISDKSliderControl"), + ImportVar(tag="SliderTrack", alias="UISDKSliderTrack"), + ImportVar(tag="SliderIndicator", alias="UISDKSliderIndicator"), + ImportVar(tag="SliderThumb", alias="UISDKSliderThumb"), + ], + } 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..91514df1cc8 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_spinner.py @@ -0,0 +1,361 @@ +"""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/components/test_switch.py b/tests/units/reflex_components_ui/components/test_switch.py new file mode 100644 index 00000000000..2f2334fe4d0 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_switch.py @@ -0,0 +1,522 @@ +"""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_fd86994bd3_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))"} + }, + "--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_c196716516_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))"} + }, + "--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))"} + }, + "--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") # pyright: ignore[reportArgumentType] + 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") # pyright: ignore[reportArgumentType] + assert ( + 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/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/components/test_tabs.py b/tests/units/reflex_components_ui/components/test_tabs.py new file mode 100644 index 00000000000..b71e25469ec --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_tabs.py @@ -0,0 +1,204 @@ +"""Tests for reflex_components_ui.components.tabs.""" + +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 + +TABS = "@ui-sdk/react@0.1.0-beta.17/tabs" + + +class TabsState(rx.State): + """What tabs are bound to.""" + + tab: str = "two" + + @rx.event + def set_tab(self, tab: str): + """Follow the tabs. + + Args: + tab: The value of the selected tab. + """ + 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": "UISDKTabsTab", + "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 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"), + rx.ui.tabs.trigger("Two", value="two", disabled=True, id="second"), + size="1", + loop=False, + ), + rx.ui.tabs.content("First", value="one", margin="1px"), + rx.ui.tabs.content("Second", value="two", id="panel", force_mount=True), + default_value="one", + orientation="vertical", + dir="rtl", + activation_mode="manual", + id="tabs", + ) + assert component.render() == { + "name": "UISDKTabs", + "props": [ + 'activation:"manual"', + "className:sx_293eff2a48_c", + 'defaultValue:"one"', + 'dir:"rtl"', + 'id:"tabs"', + "loop:false", + 'orientation:"vertical"', + "ref:ref_tabs", + ], + "children": [ + { + "name": "UISDKTabsList", + "props": ['"aria-orientation":"vertical"', "className:sx_52bb344f95_c"], + "children": [ + _trigger( + "One", + 'sx_0aec0aad8f_c + " " + reflexUIClasses_e201574881', + 'value:"one"', + ), + _trigger( + "Two", + "sx_0aec0aad8f_c", + "disabled:true", + 'id:"second"', + "ref:ref_second", + 'value:"two"', + ), + ], + }, + { + "name": "UISDKTabsPanel", + "props": ["className:sx_f078fdbeec_c", 'value:"one"'], + "children": [{"contents": '"First"'}], + }, + { + "name": "UISDKTabsPanel", + "props": [ + "className:sx_dd03223cd1_c", + 'id:"panel"', + "keepMounted:true", + "ref:ref_panel", + 'value:"two"', + ], + "children": [{"contents": '"Second"'}], + }, + ], + } + styles = declared_styles(component) + assert (styles[0]["display"], styles[1]["display"], styles[2]["width"]) == ( + "flex", + {"default": "block", "::-webkit-scrollbar": "none"}, + "100%", + ) + + +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. + + 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 take its value, and hand a change to their handler.""" + component = rx.ui.tabs.root( + rx.ui.tabs.list(rx.ui.tabs.trigger("One", value="one")), + value=TabsState.tab, + on_change=TabsState.set_tab, + ) + assert component.render()["props"] == [ + ( + "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_" + ), + ] + + +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 "ui-sdk" in module or "behaviors" in module + } == { + "@ui-sdk/core@0.1.0-beta.17": [ImportVar(tag=None, render=False)], + TABS: [ + ImportVar(tag="Tabs", alias="UISDKTabs"), + ImportVar(tag="TabsList", alias="UISDKTabsList"), + ImportVar(tag="TabsTab", alias="UISDKTabsTab"), + ImportVar(tag="TabsPanel", alias="UISDKTabsPanel"), + ], + } + + +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") # pyright: ignore[reportArgumentType] + assert str(error.value) == ( + 'rx.ui.tabs.list: unknown size "3". The values are "1", "2".' + ) 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..dc9889877d3 --- /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") # pyright: ignore[reportArgumentType] + 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..a9289b89b80 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_text_field.py @@ -0,0 +1,677 @@ +"""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, # pyright: ignore[reportArgumentType] + 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 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"), + 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": "UISDKInputGroup", + "props": [ + 'className:sx_59632c79fd_c + " " + reflexUIClasses_e201574881 + " " + reflexUIClasses_4c7cd6a7ce', + ], + "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"), # pyright: ignore[reportArgumentType] + 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, # pyright: ignore[reportArgumentType] + 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") # pyright: ignore[reportArgumentType] + assert ( + str(error.value) + == 'rx.ui.input: 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") # pyright: ignore[reportArgumentType] + 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_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", alias="UISDKInputGroup") + ], + } + 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/components/test_theme_panel.py b/tests/units/reflex_components_ui/components/test_theme_panel.py new file mode 100644 index 00000000000..3c0f4a0fe1b --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_theme_panel.py @@ -0,0 +1,223 @@ +"""Tests for reflex_components_ui.components.theme_panel.""" + +import json +from collections.abc import Callable, Iterator +from typing import Any + +import pytest +from reflex_base.components.component import Component +from reflex_base.config import get_config +from reflex_components_ui.components.theme_panel import _Radio +from reflex_components_ui.components.tooltip import Tooltip +from reflex_components_ui.plugin import UIPlugin +from reflex_components_ui.themes import OPTIONS, Theme, theme_panel_tables + +import reflex as rx + +# The style of the card of the panel. +PANEL_STYLE = { + "boxSizing": "border-box", + "display": "flex", + "justifyContent": "flex-start", + "flexDirection": "column", + "position": "fixed", + "top": "0", + "right": "0", + "marginRight": "var(--space-4)", + "marginTop": "var(--space-4)", + "zIndex": 9999, + "overflowX": "hidden", + "overflowY": "hidden", + "maxHeight": "calc(100vh - var(--space-4) - var(--space-4))", + "borderTopLeftRadius": "var(--radius-4)", + "borderTopRightRadius": "var(--radius-4)", + "borderBottomRightRadius": "var(--radius-4)", + "borderBottomLeftRadius": "var(--radius-4)", + "backgroundColor": "var(--color-panel-solid)", + "transformOrigin": "top center", + "transitionProperty": "transform, box-shadow", + "transitionDuration": "200ms", + "transitionTimingFunction": {"default": "ease-out", "[inert]": "ease-in"}, + "transform": {"default": "none", "[inert]": "translateX(105%)"}, + "boxShadow": {"default": "var(--shadow-5)", "[inert]": "var(--shadow-2)"}, +} + + +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. + + Yields: + 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) + + +def _checked(panel: Component) -> list[tuple[str, str]]: + """List the radio buttons the server renders checked. + + Args: + panel: The panel. + + Returns: + The option and the value of each. + """ + radios: list[Any] = [radio for radio in _walk(panel) if isinstance(radio, _Radio)] + return [ + (radio.name._var_value, radio.custom_attrs["value"]) + for radio in radios + if radio.default_checked is not None + ] + + +def _tooltips(panel: Component) -> list[str]: + """List the text of every tooltip of the panel. + + Args: + panel: The panel. + + Returns: + The texts, in the order of the page. + """ + tooltips: list[Any] = [ + tooltip for tooltip in _walk(panel) if isinstance(tooltip, Tooltip) + ] + return [tooltip.content._var_value for tooltip in tooltips] + + +def test_panel_is_a_theme_fixed_to_the_viewport( + ui_plugin: UIPlugin, + declared_styles: Callable[[Any], list[dict[str, Any]]], + compiled: Callable[[Component], Component], +): + """An open panel, a theme of the medium radius at the scaling of 100%.""" + panel = compiled(rx.ui.theme_panel()) + rendered = panel.render() + assert rendered["name"] == '"div"' + assert rendered["props"] == [ + "className:reflexUIClasses_671aaa73d7", + '"data-rx-theme-panel":"panel"', + "inert:false", + "onChange:themePanelEvent", + "onClick:themePanelEvent", + 'ref:((panel) => themePanel(panel, reflexUIThemePanel, "auto"))', + ] + assert declared_styles(panel)[0] == PANEL_STYLE + style = ( + f"const sx_66c1029ab2 = stylex.create({{ s: {json.dumps(PANEL_STYLE)} }});\n" + "const sx_66c1029ab2_c = stylex.props(sx_66c1029ab2.s).className;" + ) + assert panel.add_custom_code() == [ + style, + "const sx_66c1029ab2_o = sx_66c1029ab2.s;", + ( + 'const reflexUIClasses_671aaa73d7 = "reflex-ui-theme " + ' + "reflexUIClassName(spaceScope, radiusScope, typographyScope, shadowScope, " + "colorScope, focusScope, radiusMedium, scaling100, reflexUITheme.root, " + "sx_66c1029ab2_o);" + ), + *theme_panel_tables().declarations, + ] + + +def test_panel_imports_every_theme(ui_plugin: UIPlugin): + """What the panel can apply is what a page with it loads: every theme.""" + imports = rx.ui.theme_panel().add_imports() + assert isinstance(imports, list) + modules = sorted({module for each in imports for module in each}) + accents = [ + f"$/reflex-ui/themes/accent/{accent}.js" + for accent in sorted(OPTIONS["accent_color"]) + ] + grays = [ + f"$/reflex-ui/themes/gray/{gray}.js" + for gray in ("gray", "mauve", "olive", "sage", "sand", "slate") + ] + assert modules == [ + "$/reflex-ui/class-name.js", + *accents, + "$/reflex-ui/themes/focus.js", + *grays, + "$/reflex-ui/themes/panel.js", + "$/reflex-ui/themes/radius.js", + "$/reflex-ui/themes/scaling.js", + "$/reflex-ui/themes/scope.js", + "$/reflex-ui/themes/theme.js", + ] + + +@pytest.mark.parametrize( + ("default_open", "inert"), + [ + (False, "inert:true"), + (True, "inert:false"), + (rx.Var("open", _var_type=bool), "inert:!(isTrue(open))"), + ], +) +def test_panel_is_inert_while_it_is_closed( + ui_plugin: UIPlugin, default_open: Any, inert: str +): + props = rx.ui.theme_panel(default_open=default_open).render()["props"] + assert props[2] == inert + + +def test_server_render_checks_the_theme_of_the_app(monkeypatch: pytest.MonkeyPatch): + """The theme of the app is what the server shows chosen, by Radix's order.""" + theme = Theme( + accent_color="gray", + gray_color="sand", + radius="large", + scaling="90%", + appearance="dark", + panel_background="solid", + ) + monkeypatch.setattr(get_config(), "plugins", [UIPlugin(theme=theme)]) + panel = rx.ui.theme_panel() + assert _checked(panel) == [ + ("accentColor", "gray"), + ("grayColor", "sand"), + ("appearance", "dark"), + ("radius", "large"), + ("scaling", "90%"), + ("panelBackground", "solid"), + ] + # Every accent names the gray while the accent is gray, as in Radix. + tooltips = _tooltips(panel) + assert tooltips[:3] == [ + "Press T to show/hide the Theme Panel", + "Gray (Sand)", + "Gold (Sand)", + ] + assert tooltips[-7:] == [ + "Auto (Gray)", + "Gray", + "Mauve", + "Slate", + "Sage", + "Olive", + "Sand", + ] + + +def test_server_render_without_an_appearance_checks_none(ui_plugin: UIPlugin): + """An app that follows its color mode shows no appearance chosen until it runs.""" + panel = rx.ui.theme_panel() + assert _checked(panel) == [ + ("accentColor", "blue"), + ("grayColor", "auto"), + ("radius", "medium"), + ("scaling", "100%"), + ("panelBackground", "translucent"), + ] + tooltips = _tooltips(panel) + assert [tooltips[1], tooltips[-7]] == ["Gray", "Auto (Slate)"] 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..b7aa08623b0 --- /dev/null +++ b/tests/units/reflex_components_ui/components/test_tooltip.py @@ -0,0 +1,162 @@ +"""Tests for reflex_components_ui.components.tooltip.""" + +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 +from tests.units.reflex_components_ui.render import tree + + +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. + + 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"), + content="Saves the file", + side="bottom", + align="start", + side_offset=2, + aria_label="Save it", + delay_duration=500, + force_mount=True, + ) + assert tree(component.render()) == ( + "UISDKTooltip", + ["closeDelay:100", "delay:500", 'type:"description"'], + [ + ("UISDKTooltipTrigger", ['render:(jsx("button", ({}), "Save"))'], []), + ( + "UISDKTooltipContent", + [ + 'align:"start"', + '"aria-label":"Save it"', + "className:sx_1b0391f864_c", + "collisionPadding:10", + 'side:"bottom"', + "sideOffset:7", + ], + [('"p"', ["className:sx_7f6c9bc5c4_c"], ['"Saves the file"'])], + ), + ], + ) + + +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): + """What a tooltip is bound to.""" + + shown: bool = False + still: bool = False + gap: int = 4 + + @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 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, + ) + 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 root[2][1][1] == [ + 'align:"center"', + ( + f'className:sx_c0ec531d30_c + " " + (sx_c0ec531d30_0[{TooltipState.still!s}] ?? "")' + ), + "collisionPadding:10", + 'side:"top"', + f"sideOffset:({TooltipState.gap!s} + 5)", + ] + + +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 "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/tooltip": [ + ImportVar(tag="Tooltip", alias="UISDKTooltip"), + ImportVar(tag="TooltipTrigger", alias="UISDKTooltipTrigger"), + ImportVar(tag="TooltipContent", alias="UISDKTooltipContent"), + ], + } + + +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: 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/conftest.py b/tests/units/reflex_components_ui/conftest.py new file mode 100644 index 00000000000..f48dec469bd --- /dev/null +++ b/tests/units/reflex_components_ui/conftest.py @@ -0,0 +1,118 @@ +"""Fixtures for the tests of reflex-components-ui.""" + +import json +import os +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_components_ui.plugin import UIPlugin + +# Code for a type checker, kept as text so that no other tool checks it. +FIXTURES = Path(__file__).parent / "style" / "fixtures" + + +@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 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, + # Pyright writes UTF-8 whatever the encoding of the system is. + encoding="utf-8", + cwd=tmp_path, + check=False, + ) + diagnostics = json.loads(result.stdout)["generalDiagnostics"] + # Pyright names a Windows drive in lower case. + assert {os.path.normcase(diagnostic["file"]) for diagnostic in diagnostics} <= { + os.path.normcase(target) + } + return [ + ( + diagnostic["range"]["start"]["line"] + 1, + diagnostic["rule"], + diagnostic["message"], + ) + for diagnostic in diagnostics + ] + + 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/__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..a8997605ad0 --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_box.py @@ -0,0 +1,216 @@ +"""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 + +import reflex as rx + +BOX_PAGE = """import * as stylex from "@stylexjs/stylex" +import {Fragment,createElement as jsx,useEffect} from "react" + + + +const sx_b26ac4fb71 = stylex.create({ s: {"boxSizing": "border-box", "display": "block"} }); +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",{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(/)"; + +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) + + +@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 | None]"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0Type parameter "_T_co@Sequence" is covariant, but "str" is ' + 'not a subtype of "_Display | _StrVar | None"\n' + '\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"\n' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"str" is not assignable to type "Literal[\'-webkit-box\']"' + ), + ), + ( + 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/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/layout/test_theme.py b/tests/units/reflex_components_ui/layout/test_theme.py new file mode 100644 index 00000000000..bc710e57ece --- /dev/null +++ b/tests/units/reflex_components_ui/layout/test_theme.py @@ -0,0 +1,443 @@ +"""Tests for reflex_components_ui.layout.theme.""" + +from collections.abc import Callable + +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 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 = ( + """ +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" +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,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'; + + + +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(() => { + // 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"}, + jsx(AppWrap, {}, children) + ); +} + + +function AppWrap({children}) { + +return (jsx("div",{className:reflexUIClasses_48dbd5f3d5},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 "$/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" +import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" +import {useRegisteredRef} from "$/utils/refs" +import {radiusFull} from "$/reflex-ui/themes/radius.js" +import {Fragment,createElement as jsx,useEffect} from "react" + + + +const sx_e0e666cdfc = stylex.create({ s: {"boxSizing": "border-box", "display": "block", "color": "var(--accent-9)"} }); +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",{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(/)"; + +export default Component; +""" + +BOUND_PAGE = """import {Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5} from "$/utils/components/Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5" +import {Themeelement_div_110e113e071e5dc30028d2a466586629} from "$/utils/components/Themeelement_div_110e113e071e5dc30028d2a466586629" +import {Fragment,createElement as jsx,useEffect} from "react" + + + + + +function Component() { + + + return ( + 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(/)"; + +export default Component; +""" + +BOUND_ACCENT_THEME = """ +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" +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 {colorScope,radiusScope,shadowScope,spaceScope,typographyScope} from "$/reflex-ui/themes/scope.js" +import {theme as reflexUITheme} from "$/reflex-ui/themes/theme.js" +import {Fragment,createElement as jsx,memo,useEffect} from "react" +import {mergeSlotProps} from "$/utils/state" + + + +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_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, ({ 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_45c9f04fbd77a86b901df8ec7c9186f5.displayName = "ThemeElement"; +return Themeelement_div_45c9f04fbd77a86b901df8ec7c9186f5; +})(); +""" + +BOUND_NAMES_THEME = """ +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" +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 {Fragment,createElement as jsx,memo,useEffect} from "react" +import {mergeSlotProps} from "$/utils/state" + + + +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_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_) + " " + "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_110e113e071e5dc30028d2a466586629.displayName = "ThemeElement"; +return Themeelement_div_110e113e071e5dc30028d2a466586629; +})(); +""" + + +class ThemeState(rx.State): + """State whose fields are bound to a theme.""" + + accent: str = "red" + names: str = "wide" + appearance: str = "dark" + + +@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_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": ['className:"dark " + sx_71b84cd269_c'], + "children": [], + } + theme = wraps[15, "ReflexUITheme"] + assert theme.render() == { + "name": '"div"', + "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( + 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}) + " " + 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}])" + ) + ] + + +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, # pyright: ignore [reportArgumentType] + ), + rx.ui.theme( + "names", + accent_color=ThemeState.accent, # pyright: ignore [reportArgumentType] + 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)) + + +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/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..38bc5b8552b --- /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)", ":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). 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..d28e90e17fc --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/after/app/app.py.txt @@ -0,0 +1,56 @@ +import reflex as rx + +from .style import card_style + +local_style = {"animation": "spin 1s"} + + +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 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"}), + 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.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"), + ) + + +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..16c757689be --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/before/app/app.py.txt @@ -0,0 +1,56 @@ +import reflex as rx + +from .style import card_style + +local_style = {"animation": "spin 1s"} + + +class State(rx.State): + bg: str = "red" + gap: str = "2" + + +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"}), + 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.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"), + ) + + +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/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/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..5e8640512c6 --- /dev/null +++ b/tests/units/reflex_components_ui/migrate_fixtures/styles/report.txt @@ -0,0 +1,31 @@ +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: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. +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. 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..1762449f918 --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_allowlist.py @@ -0,0 +1,235 @@ +"""Tests for the allowlist of the parity harness.""" + +import pytest +import reflex_components_ui +from reflex_base.components.component import ComponentNamespace +from ui_parity import allowlist +from ui_parity.allowlist import ( + Allowlist, + AllowlistError, + ApiEntry, + ContractEntry, + 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": [ + { + "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', 'style', 'children'].", + ), + ( + { + "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(): + # "*" is every component, which an [[api]] entry of a style keyword names. + components = {"*", *reflex_components_ui.__all__} + # A member of a namespace is listed by its own name, "kbd" for text.kbd, or + # by its dotted name, as the API test compares it: "text.span". + for name in reflex_components_ui.__all__: + value = getattr(reflex_components_ui, name) + if isinstance(value, ComponentNamespace): + 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) + } + 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..57e6bd27877 --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_look.py @@ -0,0 +1,294 @@ +"""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 ( + SHAPE, + CellResult, + MatrixResult, + StyleDifference, + _crop, + _Excuses, + _style_differences, + _unmatched, + split_a11y, + use_fonts, +) +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 test_style_differences_reach_the_elements_inside_that_correspond(): + """An element inside is compared while both systems build it alike.""" + reference = { + "": {"color": "red"}, + "> 1": {"isolation": "isolate"}, + "> 1 > 1": {"color": "red"}, + "> 2": {"color": "red"}, + "> 2 > 1": {"color": "red"}, + "> 2 > 2": {"color": "red"}, + "> 3": {"color": "red"}, + SHAPE: { + "": "3 a", + "> 1": "1 code", + "> 1 > 1": "0 b", + "> 2": "2 span", + "> 2 > 1": "0 i", + "> 2 > 2": "0 i", + "> 3": "0 svg", + }, + } + candidate = { + "": {"color": "red"}, + "> 1": {"isolation": "auto"}, + "> 1 > 1": {"color": "blue"}, + "> 2": {"color": "green"}, + # Built differently: what is inside is not compared. + "> 2 > 1": {"color": "blue"}, + # Named as a part in this system, and compared as one. + "icon": {"color": "red"}, + SHAPE: { + "": "3 a", + "> 1": "1 code", + "> 1 > 1": "0 span", + "> 2": "1 span", + "> 2 > 1": "0 i", + "> 3": "0 svg", + }, + } + assert _style_differences(reference, candidate) == [ + StyleDifference("> 1 ", "isolation", "isolate", "auto"), + StyleDifference("> 1 > 1 ", "color", "red", "blue"), + StyleDifference("icon", "(element)", None, "present"), + ] + assert _unmatched(reference, candidate) == { + # 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( + {**reference, SHAPE: {**reference[SHAPE], "": "4 a"}}, candidate + ) == [StyleDifference("icon", "(element)", None, "present")] + assert _unmatched( + {**reference, SHAPE: {**reference[SHAPE], "": "4 a"}}, candidate + ) == {"": "inside : rx has 4 element children, rx.ui 3"} + assert _unmatched(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], + ) + # The images are named as the system names a path. + images = ( + Path("/report") / "chromium/button/size-1@hover.{reference,candidate,diff}.png" + ) + 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" + f" images: {images}" + ), + ( + "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] + + +def test_use_fonts_sets_the_fonts_of_both_systems_and_waits_for_them(): + """The fonts are forced on every element, code apart, before a read.""" + calls = [] + + class FakePage: + def add_style_tag(self, *, content: str) -> None: + calls.append(("style", content)) + + def evaluate(self, expression: str) -> None: + calls.append(("evaluate", expression)) + + use_fonts("DejaVu Sans", "Liberation Mono")(FakePage()) # pyright: ignore[reportArgumentType] + css = ( + '* { font-family: "DejaVu Sans" !important; }\n' + "code, code *, kbd, kbd *, pre, pre * " + '{ font-family: "Liberation Mono" !important; }' + ) + assert calls == [ + ("style", css), + ("evaluate", "document.fonts.ready"), + ] 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..968368a435a --- /dev/null +++ b/tests/units/reflex_components_ui/parity/test_report.py @@ -0,0 +1,195 @@ +"""Tests for the report of a parity run.""" + +import json +from pathlib import Path + +import pytest +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") + }, + skipped=["inside