From 83fd0808169278f7bbb5ee1bbcc2243fae234656 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 20 Nov 2026 20:50:56 +0000 Subject: [PATCH 01/15] Add env, the API scripts reach Reflex through Code run by rx.call_script sees every export of utils/state.js, so apps and Reflex itself depend on frontend internals by accident, and none of them can move. This adds one defined object instead, utils/script_env.js: env.ref(id) the ref of a component, named as format_ref names it env.refs the ref registry env.addEvents(...) dispatch through the event loop mounted at call time env.event(...) build an event for addEvents env.library(name) a bundled library, loaded first when loading is lazy Script code sees it as `env`. On the Python side rx.js.env (reflex_base.js) builds the same calls as vars; it renders under the alias __reflexEnv, which runScript also passes in, so one expression works compiled into a page and sent from the backend, and cannot collide with the `env` pages import from env.json. Every member reads the runtime at call time, so the module loads in either order despite its import cycle with utils/state.js. Nothing existing changes: scripts keep every name they saw before. Part of ENG-9127. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- docs/api-reference/browser_javascript.md | 35 ++++++ news/+script-env.feature.md | 1 + .../reflex-base/news/+script-env.feature.md | 1 + .../src/reflex_base/constants/base.py | 2 + .../src/reflex_base/js/__init__.py | 5 + .../reflex-base/src/reflex_base/js/env.py | 101 ++++++++++++++++ .../reflex-frontend/src/utils/script_env.js | 70 +++++++++++ packages/reflex-frontend/src/utils/state.js | 8 +- .../reflex-frontend/tests/public_api.test.js | 1 + .../reflex-frontend/tests/script_env.test.js | 109 ++++++++++++++++++ pyi_hashes.json | 2 +- reflex/__init__.py | 1 + reflex/js.py | 4 + .../tests_playwright/test_call_script.py | 53 +++++++++ tests/units/compiler/state_js.test.mjs | 1 + .../client_event_queue_runtime.mjs | 1 + tests/units/reflex_base/js/__init__.py | 0 tests/units/reflex_base/js/test_env.py | 75 ++++++++++++ 18 files changed, 468 insertions(+), 2 deletions(-) create mode 100644 news/+script-env.feature.md create mode 100644 packages/reflex-base/news/+script-env.feature.md create mode 100644 packages/reflex-base/src/reflex_base/js/__init__.py create mode 100644 packages/reflex-base/src/reflex_base/js/env.py create mode 100644 packages/reflex-frontend/src/utils/script_env.js create mode 100644 packages/reflex-frontend/tests/script_env.test.js create mode 100644 reflex/js.py create mode 100644 tests/units/reflex_base/js/__init__.py create mode 100644 tests/units/reflex_base/js/test_env.py diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index daa87f3c907..1490f3bbf4b 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -141,6 +141,41 @@ The `callback` parameter may be an `EventHandler` with one argument, or a lambda If the callback is None, then no event is triggered. ``` +## The Script Environment + +Code run by `rx.call_script` reaches Reflex through `env`, a small API that +stays stable as the rest of the frontend changes: + +| Member | What it does | +| --- | --- | +| `env.ref(id)` | The ref of the component with that `id`; its `current` is the element. | +| `env.refs` | Every registered component ref. | +| `env.addEvents(events)` | Dispatch events, as event triggers do. | +| `env.event(name, payload)` | Build an event for `env.addEvents`. | +| `env.library(name)` | A promise of a library bundled for dynamic components, such as `"react"`. | + +```python +(rx.input(id="search"),) +(rx.button("Focus", on_click=rx.call_script("env.ref('search').current.focus()")),) +``` + +To build the same calls from Python vars, use `rx.js.env`. It works in an event +trigger and when an event handler returns it: + +```python +class SearchState(rx.State): + @rx.event + def clear_later(self): + return rx.run_script(rx.js.env.add_events(SearchState.clear)) + + @rx.event + def clear(self): ... +``` + +Prefer `env` over the other names a script can see, such as `refs` or +`ReflexEvent`: those are internals of the frontend and may change between +Reflex versions. + ## Using React Hooks To use React Hooks directly in a Reflex app, you must subclass `rx.Component`, diff --git a/news/+script-env.feature.md b/news/+script-env.feature.md new file mode 100644 index 00000000000..87e4ca884d8 --- /dev/null +++ b/news/+script-env.feature.md @@ -0,0 +1 @@ +Add `rx.js.env`, a var for the script environment, so `rx.run_script(rx.js.env.add_events(State.handler))` and `rx.js.env.ref("my_id")` work both in event triggers and when returned from an event handler. See [Browser Javascript](https://reflex.dev/docs/api-reference/browser-javascript/#the-script-environment). diff --git a/packages/reflex-base/news/+script-env.feature.md b/packages/reflex-base/news/+script-env.feature.md new file mode 100644 index 00000000000..f2a39481cdd --- /dev/null +++ b/packages/reflex-base/news/+script-env.feature.md @@ -0,0 +1 @@ +Add `env`, the API browser code reaches Reflex through: `rx.call_script` code can call `env.ref(id)`, `env.refs`, `env.addEvents(...)`, `env.event(...)` and `env.library(name)` instead of frontend internals, and `reflex_base.js.env` builds the same calls from Python vars. diff --git a/packages/reflex-base/src/reflex_base/constants/base.py b/packages/reflex-base/src/reflex_base/constants/base.py index 5add4115098..d8f8eebdb4f 100644 --- a/packages/reflex-base/src/reflex_base/constants/base.py +++ b/packages/reflex-base/src/reflex_base/constants/base.py @@ -40,6 +40,8 @@ class Dirs(SimpleNamespace): CONTEXTS_PATH = UTILS + "/context" # The name of the client state file. CLIENT_STATE_PATH = UTILS + "/client_state" + # The name of the script environment file. + SCRIPT_ENV_PATH = UTILS + "/script_env" # 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/js/__init__.py b/packages/reflex-base/src/reflex_base/js/__init__.py new file mode 100644 index 00000000000..040549e7c6a --- /dev/null +++ b/packages/reflex-base/src/reflex_base/js/__init__.py @@ -0,0 +1,5 @@ +"""Run JavaScript in the browser through a defined API.""" + +from reflex_base.js.env import ScriptEnvVar, env + +__all__ = ["ScriptEnvVar", "env"] diff --git a/packages/reflex-base/src/reflex_base/js/env.py b/packages/reflex-base/src/reflex_base/js/env.py new file mode 100644 index 00000000000..a9ff5101908 --- /dev/null +++ b/packages/reflex-base/src/reflex_base/js/env.py @@ -0,0 +1,101 @@ +"""The script environment as a Var: the API browser code reaches Reflex through. + +The frontend defines it in ``utils/script_env.js``. ``rx.call_script`` code +sees it as ``env``, a JavaScript module imports it as ``env``, and Python +builds expressions on it through ``rx.js.env``. A Var renders under the alias +``__reflexEnv``, which ``rx.call_script`` code also sees, so one expression +works compiled into a page and sent from the backend, and cannot collide with +the ``env`` a page imports from ``env.json``. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from reflex_base.constants.base import Dirs +from reflex_base.event import EventCallback, EventHandler, EventSpec +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.vars.function import FunctionVar +from reflex_base.vars.object import ObjectVar + +# The name a Var renders the environment under. +_ALIAS = "__reflexEnv" + + +class ScriptEnvVar(ObjectVar[Mapping[str, Any]]): + """The script environment, for building browser code in Python.""" + + def _function(self, name: str) -> FunctionVar: + """Get one of the environment's functions. + + Args: + name: The member name. + + Returns: + The function. + """ + return Var( + _js_expr=f"{self._js_expr}.{name}", + _var_data=self._get_all_var_data(), + ).to(FunctionVar) + + @property + def refs(self) -> ObjectVar[Mapping[str, Any]]: + """Every registered component ref, by registry key (``ref_``). + + Returns: + The ref registry. + """ + return Var( + _js_expr=f"{self._js_expr}.refs", + _var_data=self._get_all_var_data(), + ).to(dict) + + def ref(self, id: str | Var[str]) -> ObjectVar[Mapping[str, Any]]: + """Get the ref of a component by its id. + + Args: + id: The component id. + + Returns: + The ref, whose ``current`` is the mounted element, or undefined if + no component with that id has mounted. + """ + return self._function("ref").call(id).to(dict) + + def add_events(self, *events: EventSpec | EventHandler | EventCallback[()]) -> Var: + """Dispatch events through the event loop, as event triggers do. + + Args: + *events: The events, or handlers that take no arguments. + + Returns: + The dispatch call. + """ + return self._function("addEvents").call( + LiteralVar.create([ + event if isinstance(event, EventSpec) else event() for event in events + ]) + ) + + def library(self, name: str | Var[str]) -> Var: + """Get a library bundled for dynamic components. + + Args: + name: The library's import name, e.g. ``"react"``. + + Returns: + A promise of the library's module namespace. + """ + return self._function("library").call(name) + + +env = ScriptEnvVar( + _js_expr=_ALIAS, + _var_type=Mapping[str, Any], + _var_data=VarData( + imports={f"$/{Dirs.SCRIPT_ENV_PATH}": [ImportVar(tag="env", alias=_ALIAS)]} + ), +) diff --git a/packages/reflex-frontend/src/utils/script_env.js b/packages/reflex-frontend/src/utils/script_env.js new file mode 100644 index 00000000000..9f1087846c2 --- /dev/null +++ b/packages/reflex-frontend/src/utils/script_env.js @@ -0,0 +1,70 @@ +// The script environment: the API JavaScript run by an app reaches Reflex +// through, in place of the internals of utils/state.js. It is passed to +// `rx.call_script` code as `env`, a module imports it as `env`, and +// `rx.js.env` builds expressions on it from Python. Its members read the +// runtime at call time, so it is safe to import before the event loop mounts +// and from a module utils/state.js imports. +import { eventLoop } from "$/utils/context-registry"; +import { ReflexEvent, refs } from "$/utils/state"; + +/** + * Get the name a component id is registered under in `refs`. + * + * Mirrors `format_ref` in reflex_base.utils.format: every run of characters + * that are not letters, digits or underscores becomes one underscore. + * @param {string} id The component id. + * @returns {string} The registry key. + */ +const refName = (id) => + `ref_${String(id).replace(/[^\p{L}\p{N}_]+/gu, "_")}`; + +export const env = Object.freeze({ + /** + * Every registered component ref, by registry key (`ref_`). + * @returns {Record} The ref registry. + */ + get refs() { + return refs; + }, + + /** + * Get the ref of a component by its id. + * @param {string} id The component id. + * @returns {{current: any} | undefined} The ref, or undefined if no + * component with that id has mounted. + */ + ref: (id) => refs[refName(id)], + + /** + * Dispatch events through the mounted event loop, as event triggers do. + * @param {any[]} events The events, built with `env.event`. + * @param {any[]} [args] The arguments of the triggering call. + * @param {object} [eventActions] Event actions such as preventDefault. + * @returns {any} Whatever the event loop's addEvents returns. + */ + addEvents: (events, args = [], eventActions = {}) => + eventLoop.addEvents(events, args, eventActions), + + /** + * Build an event for `addEvents`. + * @param {string} name The full name of the event handler. + * @param {object} [payload] The handler's arguments, by name. + * @returns {any} The event. + */ + event: (name, payload = {}) => ReflexEvent(name, payload), + + /** + * Get a library bundled for dynamic components, loading it first when the + * app loads optional libraries lazily. + * @param {string} name The library's import name, e.g. "react". + * @returns {Promise} The library's module namespace. + */ + library: async (name) => { + await window.__reflex_load?.([name]); + const module = window.__reflex?.[name]; + if (module === undefined) { + throw new Error(`${name} is not a bundled library of this app.`); + } + return module; + }, +}); diff --git a/packages/reflex-frontend/src/utils/state.js b/packages/reflex-frontend/src/utils/state.js index 7486b1dac04..ce6c9be6d27 100644 --- a/packages/reflex-frontend/src/utils/state.js +++ b/packages/reflex-frontend/src/utils/state.js @@ -13,6 +13,7 @@ import { import { app, eventLoop } from "$/utils/context-registry"; // This module's own exports, passed to server-provided scripts by runScript. import * as stateExports from "$/utils/state"; +import { env as scriptEnv } from "$/utils/script_env"; import { CLIENT_STATE_REF, getClientState, @@ -519,7 +520,8 @@ function urlFrom(string) { * `params` and `token`. A direct eval would see them, but it also stops the * minifier from mangling every name in the chunk that holds it, so the code * is compiled with the Function constructor and those names are passed in as - * parameters. The eval inside the body still runs the code as a strict + * parameters. The script environment is passed twice: as `env`, the name + * scripts use, and as `__reflexEnv`, the name `rx.js.env` compiles to. The eval inside the body still runs the code as a strict * script, so statements keep their completion value. * * Compiled on first use: a Content Security Policy without `unsafe-eval` @@ -542,6 +544,8 @@ const runScript = (code, addEvents, socket, navigate, params) => { "navigate", "params", "token", + "env", + "__reflexEnv", "code", '"use strict"; return eval(code);', ); @@ -552,6 +556,8 @@ const runScript = (code, addEvents, socket, navigate, params) => { navigate, params, token, + scriptEnv, + scriptEnv, code, ); }; diff --git a/packages/reflex-frontend/tests/public_api.test.js b/packages/reflex-frontend/tests/public_api.test.js index 5d34496f53b..40838591a03 100644 --- a/packages/reflex-frontend/tests/public_api.test.js +++ b/packages/reflex-frontend/tests/public_api.test.js @@ -82,6 +82,7 @@ const PUBLIC_API = { "useStateContext", ], "$/utils/react-theme": ["ThemeProvider", "useTheme"], + "$/utils/script_env": ["env"], "$/utils/helpers/array": ["default"], "$/utils/helpers/datetime": ["default"], "$/utils/helpers/debounce": ["default"], diff --git a/packages/reflex-frontend/tests/script_env.test.js b/packages/reflex-frontend/tests/script_env.test.js new file mode 100644 index 00000000000..23fff1dfbe0 --- /dev/null +++ b/packages/reflex-frontend/tests/script_env.test.js @@ -0,0 +1,109 @@ +/** + * The script environment is the API scripts reach Reflex through. These pin + * each member, that it reads the runtime at call time, and that + * `rx.call_script` code sees it under both of its names. + */ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { eventLoop } from "$/utils/context-registry"; +import { env } from "$/utils/script_env"; +import { applyEvent, refs } from "$/utils/state"; + +afterEach(() => { + delete window.__reflex; + delete window.__reflex_load; +}); + +describe("env", () => { + test("ref finds a component by id, named as format_ref names it", () => { + const cases = { + search: "ref_search", + "my-input": "ref_my_input", + "a b..c": "ref_a_b_c", + "naïve-x": "ref_naïve_x", + }; + for (const [id, key] of Object.entries(cases)) { + const ref = { current: id }; + refs[key] = ref; + expect(env.ref(id)).toBe(ref); + delete refs[key]; + } + expect(env.ref("never-mounted")).toBe(undefined); + }); + + test("refs is the registry itself", () => { + expect(env.refs).toBe(refs); + }); + + test("addEvents dispatches through the event loop mounted at call time", () => { + const first = vi.fn(); + const second = vi.fn(); + eventLoop.addEvents = first; + env.addEvents(["a"]); + eventLoop.addEvents = second; + env.addEvents(["b"], [1], { preventDefault: true }); + expect(first.mock.calls).toEqual([[["a"], [], {}]]); + expect(second.mock.calls).toEqual([[["b"], [1], { preventDefault: true }]]); + }); + + test("event builds the event addEvents takes", () => { + expect(env.event("state.my_state.save", { value: 3 })).toEqual({ + name: "state.my_state.save", + payload: { value: 3 }, + }); + expect(env.event("state.my_state.reset")).toEqual({ + name: "state.my_state.reset", + }); + }); + + test("library loads a lazy library first and returns its module", async () => { + const confetti = { default: () => "boom" }; + window.__reflex = { react: { version: "19" } }; + window.__reflex_load = vi.fn(async (names) => { + for (const name of names) { + window.__reflex[name] ??= confetti; + } + }); + await expect(env.library("canvas-confetti")).resolves.toBe(confetti); + expect(window.__reflex_load.mock.calls).toEqual([[["canvas-confetti"]]]); + await expect(env.library("react")).resolves.toEqual({ version: "19" }); + }); + + test("library rejects a library the app does not bundle", async () => { + window.__reflex = {}; + await expect(env.library("left-pad")).rejects.toThrow( + new Error("left-pad is not a bundled library of this app."), + ); + }); + + test("is frozen, so a script cannot replace a member for everyone", () => { + expect(() => { + env.addEvents = () => {}; + }).toThrow(TypeError); + }); +}); + +test("rx.call_script code sees env as env and as __reflexEnv", async () => { + const seen = []; + await applyEvent( + { + name: "_call_script", + payload: { + javascript_code: "[env === __reflexEnv, env.refs === refs]", + callback: (result) => seen.push(result), + }, + }, + null, + null, + null, + ); + expect(seen).toEqual([[true, true]]); +}); + +test("loads first, before utils/state, despite the import cycle", async () => { + vi.resetModules(); + const { env: fresh } = await import("$/utils/script_env"); + const state = await import("$/utils/state"); + state.refs.ref_first = { current: 1 }; + expect(fresh.ref("first")).toBe(state.refs.ref_first); +}); diff --git a/pyi_hashes.json b/pyi_hashes.json index 8f2b4c8aa7a..3538f32191a 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,7 +118,7 @@ "packages/reflex-components-recharts/src/reflex_components_recharts/polar.pyi": "adc4db1a3ca7cd292b099ec4d97a4346", "packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "f2a9cf6db58d169289fbc76de6813300", "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "f170ac685b6ba5892370166c80684db3", - "reflex/__init__.pyi": "067a60e22fb825072f2f0b690662da5a", + "reflex/__init__.pyi": "9e15759df6266f047709e2a1325c2cb4", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" } diff --git a/reflex/__init__.py b/reflex/__init__.py index 75cb5a1328b..035dda21e53 100644 --- a/reflex/__init__.py +++ b/reflex/__init__.py @@ -242,6 +242,7 @@ "testing", "utils", "vars", + "js", "config", "compiler", "plugins", diff --git a/reflex/js.py b/reflex/js.py new file mode 100644 index 00000000000..8c3ff01626e --- /dev/null +++ b/reflex/js.py @@ -0,0 +1,4 @@ +# pyright: reportWildcardImportFromLibrary=false +"""Run JavaScript in the browser through a defined API.""" + +from reflex_base.js import * # pragma: no cover diff --git a/tests/integration/tests_playwright/test_call_script.py b/tests/integration/tests_playwright/test_call_script.py index e9fa0d84444..7c7995bb9dc 100644 --- a/tests/integration/tests_playwright/test_call_script.py +++ b/tests/integration/tests_playwright/test_call_script.py @@ -44,6 +44,7 @@ class CallScriptState(rx.State): external_counter: rx.Field[int] = rx.field(0) value: str = "Initial" last_result: rx.Field[int] = rx.field(0) + env_result: str = "" @rx.event def call_script_callback(self, result): @@ -195,6 +196,16 @@ def set_last_result(self, value: str): def set_value(self, value: str): self.value = value + @rx.event + def set_env_result(self, value: str): + self.env_result = value + + @rx.event + def env_var_backend(self): + return rx.run_script( + rx.js.env.add_events(CallScriptState.set_env_result("env var backend")) + ) + @rx.event def reset_(self): yield rx.call_script("inline_counter = 0; external_counter = 0") @@ -354,6 +365,30 @@ def index(): ), id="call_with_var_str_cast_wrapped_inline", ), + rx.input(id="env_target", default_value="from the ref"), + rx.input(value=CallScriptState.env_result, id="env_result", read_only=True), + rx.button( + "env_string", + on_click=rx.call_script( + "env.ref('env_target').current.value", + callback=CallScriptState.set_env_result, + ), + id="env_string", + ), + rx.button( + "env_var_frontend", + on_click=rx.run_script( + rx.js.env.add_events( + CallScriptState.set_env_result("env var frontend") + ) + ), + id="env_var_frontend", + ), + rx.button( + "env_var_backend", + on_click=CallScriptState.env_var_backend, + id="env_var_backend", + ), ) @@ -525,3 +560,21 @@ def test_call_script_w_var( inline_return_button.click() call_with_var_str_cast_wrapped_inline_button.click() expect(last_result).to_have_value("8") + + +def test_script_env(call_script_page: Page): + """Scripts reach the script environment as `env` and through `rx.js.env`. + + Args: + call_script_page: Playwright page. + """ + env_result = call_script_page.locator("#env_result") + + call_script_page.locator("#env_string").click() + expect(env_result).to_have_value("from the ref") + + call_script_page.locator("#env_var_frontend").click() + expect(env_result).to_have_value("env var frontend") + + call_script_page.locator("#env_var_backend").click() + expect(env_result).to_have_value("env var backend") diff --git a/tests/units/compiler/state_js.test.mjs b/tests/units/compiler/state_js.test.mjs index b5eba0f1dee..610aacbff88 100644 --- a/tests/units/compiler/state_js.test.mjs +++ b/tests/units/compiler/state_js.test.mjs @@ -227,6 +227,7 @@ async function setup({ "$/utils/helpers/debounce": { default() {} }, "$/utils/helpers/throttle": { default() {} }, "$/utils/helpers/upload": { uploadFiles() {} }, + "$/utils/script_env": { env: {} }, }; const module = new vm.SourceTextModule(source, { context, diff --git a/tests/units/reflex_base/client_event_queue_runtime.mjs b/tests/units/reflex_base/client_event_queue_runtime.mjs index f13cb974094..ab666047987 100644 --- a/tests/units/reflex_base/client_event_queue_runtime.mjs +++ b/tests/units/reflex_base/client_event_queue_runtime.mjs @@ -62,6 +62,7 @@ export async function createQueueRuntime( "$/utils/helpers/upload": { uploadFiles: uploadFiles ?? unused, }, + "$/utils/script_env": { env: {} }, ...dependencyOverrides, }; // Let Node parse the unchanged module; only expose private state to tests. diff --git a/tests/units/reflex_base/js/__init__.py b/tests/units/reflex_base/js/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/units/reflex_base/js/test_env.py b/tests/units/reflex_base/js/test_env.py new file mode 100644 index 00000000000..9cc3e9e2af9 --- /dev/null +++ b/tests/units/reflex_base/js/test_env.py @@ -0,0 +1,75 @@ +"""Tests for the script environment Var.""" + +from typing import cast + +from reflex_base.event import EventSpec, run_script +from reflex_base.js import env +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData + +import reflex as rx + +ENV_VAR_DATA = VarData( + imports={"$/utils/script_env": [ImportVar(tag="env", alias="__reflexEnv")]} +) + + +class EnvState(rx.State): + """A state whose handlers and vars the env Var is built with.""" + + target: str = "search" + + @rx.event + def save(self, value: int): + """Take an argument. + + Args: + value: The value. + """ + + @rx.event + def reset_all(self): + """Take no arguments.""" + + +def test_env_renders_under_its_alias_with_its_import(): + assert str(env) == "__reflexEnv" + assert env._get_all_var_data() == ENV_VAR_DATA + assert rx.js.env is env + + +def test_refs_and_ref(): + assert str(env.refs) == "__reflexEnv.refs" + assert env.refs._get_all_var_data() == ENV_VAR_DATA + assert str(env.ref("search")) == '(__reflexEnv.ref("search"))' + target = cast(Var[str], EnvState.target) + ref = env.ref(target) + assert str(ref) == f"(__reflexEnv.ref({target!s}))" + assert ref._get_all_var_data() == VarData.merge( + ENV_VAR_DATA, target._get_all_var_data() + ) + + +def test_add_events_takes_specs_and_argless_handlers(): + name = EnvState.get_full_name() + assert str(env.add_events(EnvState.save(3), EnvState.reset_all)) == ( + "(__reflexEnv.addEvents([" + f'(ReflexEvent("{name}.save", ({{ ["value"] : 3 }}), ({{ }}))), ' + f'(ReflexEvent("{name}.reset_all", ({{ }}), ({{ }})))' + "]))" + ) + + +def test_library(): + assert str(env.library("react")) == '(__reflexEnv.library("react"))' + + +def test_run_script_carries_the_import_into_the_page(): + spec = run_script(env.ref("search")) + assert isinstance(spec, EventSpec) + literal = LiteralVar.create(spec) + assert str(literal) == ( + '(ReflexEvent("_call_function", ({ ["function"] : ' + '(() => (__reflexEnv.ref("search"))), ["callback"] : null }), ({ })))' + ) + assert literal._get_all_var_data() == ENV_VAR_DATA From 5dd96975fbaf1af1f08a615f1a0a9a34795dcd04 Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 20 Nov 2026 21:04:24 +0000 Subject: [PATCH 02/15] Format script_env.js with biome Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- packages/reflex-frontend/src/utils/script_env.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/reflex-frontend/src/utils/script_env.js b/packages/reflex-frontend/src/utils/script_env.js index 9f1087846c2..1a85ec15bef 100644 --- a/packages/reflex-frontend/src/utils/script_env.js +++ b/packages/reflex-frontend/src/utils/script_env.js @@ -15,8 +15,7 @@ import { ReflexEvent, refs } from "$/utils/state"; * @param {string} id The component id. * @returns {string} The registry key. */ -const refName = (id) => - `ref_${String(id).replace(/[^\p{L}\p{N}_]+/gu, "_")}`; +const refName = (id) => `ref_${String(id).replace(/[^\p{L}\p{N}_]+/gu, "_")}`; export const env = Object.freeze({ /** From 20fc39d949f7b3646a4976aae271b6793c12800f Mon Sep 17 00:00:00 2001 From: Farhan Date: Fri, 20 Nov 2026 21:41:23 +0000 Subject: [PATCH 03/15] Add docstrings to the script env tests Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- tests/units/reflex_base/js/test_env.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/units/reflex_base/js/test_env.py b/tests/units/reflex_base/js/test_env.py index 9cc3e9e2af9..9d854b0d7bf 100644 --- a/tests/units/reflex_base/js/test_env.py +++ b/tests/units/reflex_base/js/test_env.py @@ -33,12 +33,14 @@ def reset_all(self): def test_env_renders_under_its_alias_with_its_import(): + """The env Var renders under its alias and imports it from script_env.""" assert str(env) == "__reflexEnv" assert env._get_all_var_data() == ENV_VAR_DATA assert rx.js.env is env def test_refs_and_ref(): + """Refs and ref() render on the alias and keep the var data of their arguments.""" assert str(env.refs) == "__reflexEnv.refs" assert env.refs._get_all_var_data() == ENV_VAR_DATA assert str(env.ref("search")) == '(__reflexEnv.ref("search"))' @@ -51,6 +53,7 @@ def test_refs_and_ref(): def test_add_events_takes_specs_and_argless_handlers(): + """add_events compiles event specs, and handlers without arguments, to events.""" name = EnvState.get_full_name() assert str(env.add_events(EnvState.save(3), EnvState.reset_all)) == ( "(__reflexEnv.addEvents([" @@ -61,10 +64,12 @@ def test_add_events_takes_specs_and_argless_handlers(): def test_library(): + """library() renders a call on the alias.""" assert str(env.library("react")) == '(__reflexEnv.library("react"))' def test_run_script_carries_the_import_into_the_page(): + """A script built on env carries the env import into the page that uses it.""" spec = run_script(env.ref("search")) assert isinstance(spec, EventSpec) literal = LiteralVar.create(spec) From 2c92b0544eccc6099e14e7228009036b5474f735 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 21 Nov 2026 21:18:29 +0000 Subject: [PATCH 04/15] Rename the script API to reflex and keep env.json in scripts `env` inside scripts shadowed the `env` that `rx.get_upload_url` compiles to (`getBackendURL(env.UPLOAD)`), so a backend script linking to an upload opened `.../ping/a.png`; since the Function-constructor runScript it was a ReferenceError. The API is now `reflex`, exported from utils/reflex.js, and runScript passes `env` (the app's env.json) as the direct eval did in 0.11.0. The API is narrowed to what is documented: `refs` is gone (`ref(id)` covers it and keeps the registry key format private), `addEvents` takes only the events, and `library` rejects `$/` frontend modules. Each `library` error names the library, the cause and the fix, including a call made before the app root registered its libraries. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- packages/reflex-frontend/README.md | 10 +- packages/reflex-frontend/src/utils/reflex.js | 71 ++++++++++++ .../reflex-frontend/src/utils/script_env.js | 69 ----------- packages/reflex-frontend/src/utils/state.js | 22 ++-- .../reflex-frontend/tests/public_api.test.js | 2 +- packages/reflex-frontend/tests/reflex.test.js | 105 +++++++++++++++++ .../reflex-frontend/tests/run_script.test.js | 13 +++ .../reflex-frontend/tests/script_env.test.js | 109 ------------------ tests/units/compiler/state_js.test.mjs | 2 +- .../client_event_queue_runtime.mjs | 2 +- 10 files changed, 210 insertions(+), 195 deletions(-) create mode 100644 packages/reflex-frontend/src/utils/reflex.js delete mode 100644 packages/reflex-frontend/src/utils/script_env.js create mode 100644 packages/reflex-frontend/tests/reflex.test.js delete mode 100644 packages/reflex-frontend/tests/script_env.test.js diff --git a/packages/reflex-frontend/README.md b/packages/reflex-frontend/README.md index 712a67f3c6d..336929639ba 100644 --- a/packages/reflex-frontend/README.md +++ b/packages/reflex-frontend/README.md @@ -61,10 +61,12 @@ without it appearing in its arguments. What there is, and where it is pinned: callbacks) runs through `runScript` in `utils/state.js`, which compiles it with the Function constructor and passes in every export of that module, the late-bound `addEvents`, the `socket`, `navigate` and `params` of the event - being applied, and the session `token`. A direct `eval` would see every - module local, but it stops the minifier from mangling the chunk that holds - it. So a script sees those names and the globals, and nothing else. Renaming - an export changes what compiled callbacks can call. + being applied, the session `token`, `env` (the app's `$/env.json`, which + `rx.get_upload_url` compiles to) and `reflex` (the API in `utils/reflex.js`, + which `rx.js` compiles to). A direct `eval` would see every module local, but + it stops the minifier from mangling the chunk that holds it. So a script sees + those names and the globals, and nothing else. Renaming an export changes + what compiled callbacks can call. - **Globals the runtime reads**: hooks other code installs on `window` (`__reflex_otel`, `__reflex`, `__reflex_load`) and the per-app `$/env.json`. Each is declared in `types/globals.d.ts`; reading one that is not fails the diff --git a/packages/reflex-frontend/src/utils/reflex.js b/packages/reflex-frontend/src/utils/reflex.js new file mode 100644 index 00000000000..9b478bc9aa3 --- /dev/null +++ b/packages/reflex-frontend/src/utils/reflex.js @@ -0,0 +1,71 @@ +// `reflex`: the API JavaScript run by an app reaches Reflex through, in place +// of the internals of utils/state.js. `rx.call_script` code sees it as +// `reflex`, a module imports it from here, and `rx.js` builds calls on it from +// Python. Its members read the runtime at call time, so it is safe to import +// before the event loop mounts and from a module utils/state.js imports. +import { eventLoop } from "$/utils/context-registry"; +import { ReflexEvent, refs } from "$/utils/state"; + +/** + * Get the name a component id is registered under in `refs`. + * + * Mirrors `format_ref` in reflex_base.utils.format: every run of characters + * that are not letters, digits or underscores becomes one underscore. + * @param {string} id The component id. + * @returns {string} The registry key. + */ +const refName = (id) => `ref_${String(id).replace(/[^\p{L}\p{N}_]+/gu, "_")}`; + +export const reflex = Object.freeze({ + /** + * Get the ref of a component by its id. + * @param {string} id The component id. + * @returns {{current: any} | undefined} The ref, or undefined if no + * component with that id has mounted. + */ + ref: (id) => refs[refName(id)], + + /** + * Dispatch events through the mounted event loop, as event triggers do. + * @param {any[]} events The events, built with `reflex.event`. + */ + addEvents: (events) => { + eventLoop.addEvents(events); + }, + + /** + * Build an event for `addEvents`. + * @param {string} name The full name of the event handler. + * @param {object} [payload] The handler's arguments, by name. + * @returns {any} The event. + */ + event: (name, payload = {}) => ReflexEvent(name, payload), + + /** + * Get an npm library bundled for dynamic components, loading it first when + * the app loads optional libraries lazily. + * @param {string} name The library's import name, e.g. "react". + * @returns {Promise} The library's module namespace. + */ + library: async (name) => { + if (name.startsWith("$/")) { + throw new Error( + `reflex.library("${name}") cannot load "${name}": a name starting with "$/" is a module of the app's frontend, not a bundled npm library. Use reflex.ref, reflex.addEvents and reflex.event instead of Reflex internals, and import your own modules from a JavaScript module.`, + ); + } + await window.__reflex_load?.([name]); + // Without lazy loading, the app root registers the libraries in an effect. + if (window.__reflex === undefined) { + throw new Error( + `reflex.library("${name}") cannot load "${name}" yet: the app registers its bundled libraries when it first mounts, and it has not mounted. Call reflex.library from an event, such as on_mount or on_click, rather than while a module loads.`, + ); + } + const module = window.__reflex[name]; + if (module === undefined) { + throw new Error( + `reflex.library("${name}") cannot load "${name}": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("${name}") from reflex.components.dynamic in your app's Python code.`, + ); + } + return module; + }, +}); diff --git a/packages/reflex-frontend/src/utils/script_env.js b/packages/reflex-frontend/src/utils/script_env.js deleted file mode 100644 index 1a85ec15bef..00000000000 --- a/packages/reflex-frontend/src/utils/script_env.js +++ /dev/null @@ -1,69 +0,0 @@ -// The script environment: the API JavaScript run by an app reaches Reflex -// through, in place of the internals of utils/state.js. It is passed to -// `rx.call_script` code as `env`, a module imports it as `env`, and -// `rx.js.env` builds expressions on it from Python. Its members read the -// runtime at call time, so it is safe to import before the event loop mounts -// and from a module utils/state.js imports. -import { eventLoop } from "$/utils/context-registry"; -import { ReflexEvent, refs } from "$/utils/state"; - -/** - * Get the name a component id is registered under in `refs`. - * - * Mirrors `format_ref` in reflex_base.utils.format: every run of characters - * that are not letters, digits or underscores becomes one underscore. - * @param {string} id The component id. - * @returns {string} The registry key. - */ -const refName = (id) => `ref_${String(id).replace(/[^\p{L}\p{N}_]+/gu, "_")}`; - -export const env = Object.freeze({ - /** - * Every registered component ref, by registry key (`ref_`). - * @returns {Record} The ref registry. - */ - get refs() { - return refs; - }, - - /** - * Get the ref of a component by its id. - * @param {string} id The component id. - * @returns {{current: any} | undefined} The ref, or undefined if no - * component with that id has mounted. - */ - ref: (id) => refs[refName(id)], - - /** - * Dispatch events through the mounted event loop, as event triggers do. - * @param {any[]} events The events, built with `env.event`. - * @param {any[]} [args] The arguments of the triggering call. - * @param {object} [eventActions] Event actions such as preventDefault. - * @returns {any} Whatever the event loop's addEvents returns. - */ - addEvents: (events, args = [], eventActions = {}) => - eventLoop.addEvents(events, args, eventActions), - - /** - * Build an event for `addEvents`. - * @param {string} name The full name of the event handler. - * @param {object} [payload] The handler's arguments, by name. - * @returns {any} The event. - */ - event: (name, payload = {}) => ReflexEvent(name, payload), - - /** - * Get a library bundled for dynamic components, loading it first when the - * app loads optional libraries lazily. - * @param {string} name The library's import name, e.g. "react". - * @returns {Promise} The library's module namespace. - */ - library: async (name) => { - await window.__reflex_load?.([name]); - const module = window.__reflex?.[name]; - if (module === undefined) { - throw new Error(`${name} is not a bundled library of this app.`); - } - return module; - }, -}); diff --git a/packages/reflex-frontend/src/utils/state.js b/packages/reflex-frontend/src/utils/state.js index ce6c9be6d27..0eaf9507476 100644 --- a/packages/reflex-frontend/src/utils/state.js +++ b/packages/reflex-frontend/src/utils/state.js @@ -13,7 +13,7 @@ import { import { app, eventLoop } from "$/utils/context-registry"; // This module's own exports, passed to server-provided scripts by runScript. import * as stateExports from "$/utils/state"; -import { env as scriptEnv } from "$/utils/script_env"; +import { reflex } from "$/utils/reflex"; import { CLIENT_STATE_REF, getClientState, @@ -517,12 +517,14 @@ function urlFrom(string) { * Callback strings and `rx.call_script` code reference helpers compiled * pages import from here (`ReflexEvent`, `pyMod`, `isTrue`, ...), and apps * written against the former direct eval also use `socket`, `navigate`, - * `params` and `token`. A direct eval would see them, but it also stops the - * minifier from mangling every name in the chunk that holds it, so the code - * is compiled with the Function constructor and those names are passed in as - * parameters. The script environment is passed twice: as `env`, the name - * scripts use, and as `__reflexEnv`, the name `rx.js.env` compiles to. The eval inside the body still runs the code as a strict - * script, so statements keep their completion value. + * `params` and `token`. Scripts reach Reflex through `reflex`, and + * `rx.get_upload_url` compiles to `getBackendURL(env.UPLOAD)`, which reads + * `env` from `$/env.json` as the former direct eval did. A direct eval would + * see these names, but it also stops the minifier from mangling every name in + * the chunk that holds it, so the code is compiled with the Function + * constructor and the names are passed in as parameters. The eval inside the + * body still runs the code as a strict script, so statements keep their + * completion value. * * Compiled on first use: a Content Security Policy without `unsafe-eval` * rejects the Function constructor, and apps that never send scripts must @@ -545,7 +547,7 @@ const runScript = (code, addEvents, socket, navigate, params) => { "params", "token", "env", - "__reflexEnv", + "reflex", "code", '"use strict"; return eval(code);', ); @@ -556,8 +558,8 @@ const runScript = (code, addEvents, socket, navigate, params) => { navigate, params, token, - scriptEnv, - scriptEnv, + env, + reflex, code, ); }; diff --git a/packages/reflex-frontend/tests/public_api.test.js b/packages/reflex-frontend/tests/public_api.test.js index 40838591a03..d337d89e0f6 100644 --- a/packages/reflex-frontend/tests/public_api.test.js +++ b/packages/reflex-frontend/tests/public_api.test.js @@ -82,7 +82,7 @@ const PUBLIC_API = { "useStateContext", ], "$/utils/react-theme": ["ThemeProvider", "useTheme"], - "$/utils/script_env": ["env"], + "$/utils/reflex": ["reflex"], "$/utils/helpers/array": ["default"], "$/utils/helpers/datetime": ["default"], "$/utils/helpers/debounce": ["default"], diff --git a/packages/reflex-frontend/tests/reflex.test.js b/packages/reflex-frontend/tests/reflex.test.js new file mode 100644 index 00000000000..72a157b5be5 --- /dev/null +++ b/packages/reflex-frontend/tests/reflex.test.js @@ -0,0 +1,105 @@ +/** + * `reflex` is the API scripts reach Reflex through. These pin each member and + * that it reads the runtime at call time. + */ +import { afterEach, expect, test, vi } from "vitest"; + +import { eventLoop } from "$/utils/context-registry"; +import { reflex } from "$/utils/reflex"; +import { refs } from "$/utils/state"; + +afterEach(() => { + delete window.__reflex; + delete window.__reflex_load; +}); + +test("ref finds a component by id, named as format_ref names it", () => { + const cases = { + search: "ref_search", + "my-input": "ref_my_input", + "a b..c": "ref_a_b_c", + "naïve-x": "ref_naïve_x", + }; + for (const [id, key] of Object.entries(cases)) { + const ref = { current: id }; + refs[key] = ref; + expect(reflex.ref(id)).toBe(ref); + delete refs[key]; + } + expect(reflex.ref("never-mounted")).toBe(undefined); +}); + +test("addEvents dispatches through the event loop mounted at call time", () => { + const first = vi.fn(); + const second = vi.fn(); + eventLoop.addEvents = first; + expect(reflex.addEvents(["a"])).toBe(undefined); + eventLoop.addEvents = second; + reflex.addEvents(["b"]); + expect(first.mock.calls).toEqual([[["a"]]]); + expect(second.mock.calls).toEqual([[["b"]]]); +}); + +test("event builds the event addEvents takes", () => { + expect(reflex.event("state.my_state.save", { value: 3 })).toEqual({ + name: "state.my_state.save", + payload: { value: 3 }, + }); + expect(reflex.event("state.my_state.reset")).toEqual({ + name: "state.my_state.reset", + }); +}); + +test("library loads a lazy library first and returns its module", async () => { + const confetti = { default: () => "boom" }; + window.__reflex = { react: { version: "19" } }; + window.__reflex_load = vi.fn(async (names) => { + for (const name of names) { + window.__reflex[name] ??= confetti; + } + }); + await expect(reflex.library("canvas-confetti")).resolves.toBe(confetti); + expect(window.__reflex_load.mock.calls).toEqual([[["canvas-confetti"]]]); + await expect(reflex.library("react")).resolves.toEqual({ version: "19" }); +}); + +test("library rejects a module of the app's frontend", async () => { + window.__reflex = { "$/utils/state": {} }; + window.__reflex_load = vi.fn(); + await expect(reflex.library("$/utils/state")).rejects.toThrow( + new Error( + 'reflex.library("$/utils/state") cannot load "$/utils/state": a name starting with "$/" is a module of the app\'s frontend, not a bundled npm library. Use reflex.ref, reflex.addEvents and reflex.event instead of Reflex internals, and import your own modules from a JavaScript module.', + ), + ); + expect(window.__reflex_load.mock.calls).toEqual([]); +}); + +test("library called before the app registers its libraries says so", async () => { + await expect(reflex.library("react")).rejects.toThrow( + new Error( + 'reflex.library("react") cannot load "react" yet: the app registers its bundled libraries when it first mounts, and it has not mounted. Call reflex.library from an event, such as on_mount or on_click, rather than while a module loads.', + ), + ); +}); + +test("library rejects a library the app does not bundle", async () => { + window.__reflex = {}; + await expect(reflex.library("left-pad")).rejects.toThrow( + new Error( + 'reflex.library("left-pad") cannot load "left-pad": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("left-pad") from reflex.components.dynamic in your app\'s Python code.', + ), + ); +}); + +test("is frozen, so a script cannot replace a member for everyone", () => { + expect(Object.isFrozen(reflex)).toBe(true); + expect(Object.keys(reflex)).toEqual(["ref", "addEvents", "event", "library"]); +}); + +test("loads first, before utils/state, despite the import cycle", async () => { + vi.resetModules(); + const { reflex: fresh } = await import("$/utils/reflex"); + const state = await import("$/utils/state"); + state.refs.ref_first = { current: 1 }; + expect(fresh.ref("first")).toBe(state.refs.ref_first); +}); diff --git a/packages/reflex-frontend/tests/run_script.test.js b/packages/reflex-frontend/tests/run_script.test.js index f561ee2f7ca..cfcc0f29cbf 100644 --- a/packages/reflex-frontend/tests/run_script.test.js +++ b/packages/reflex-frontend/tests/run_script.test.js @@ -7,6 +7,7 @@ import { describe, expect, test, vi } from "vitest"; import { eventLoop } from "$/utils/context-registry"; +import { reflex } from "$/utils/reflex"; import { applyEvent, getToken } from "$/utils/state"; const callScript = (code, callback, socket = null) => @@ -63,6 +64,18 @@ describe("_call_script", () => { expect(seen).toEqual([["object", "object", token]]); }); + test("scripts see reflex, and env as the app's env.json", async () => { + // rx.get_upload_url compiles to getBackendURL(env.UPLOAD), so a script + // from the backend that links to an uploaded file reads env.json's env. + const seen = []; + await callScript( + '[reflex, (getBackendURL(env.UPLOAD)+"/a.png")]', + (result) => seen.push(result), + ); + expect(seen).toEqual([[reflex, "http://localhost:8000/_upload/a.png"]]); + expect(seen[0][0]).toBe(reflex); + }); + test("callback strings can use every helper this module exports", async () => { // Var operations inside a callback compile to helpers such as pyMod, // isTrue or pyStrLength, which compiled pages import but a string cannot. diff --git a/packages/reflex-frontend/tests/script_env.test.js b/packages/reflex-frontend/tests/script_env.test.js deleted file mode 100644 index 23fff1dfbe0..00000000000 --- a/packages/reflex-frontend/tests/script_env.test.js +++ /dev/null @@ -1,109 +0,0 @@ -/** - * The script environment is the API scripts reach Reflex through. These pin - * each member, that it reads the runtime at call time, and that - * `rx.call_script` code sees it under both of its names. - */ -import { afterEach, describe, expect, test, vi } from "vitest"; - -import { eventLoop } from "$/utils/context-registry"; -import { env } from "$/utils/script_env"; -import { applyEvent, refs } from "$/utils/state"; - -afterEach(() => { - delete window.__reflex; - delete window.__reflex_load; -}); - -describe("env", () => { - test("ref finds a component by id, named as format_ref names it", () => { - const cases = { - search: "ref_search", - "my-input": "ref_my_input", - "a b..c": "ref_a_b_c", - "naïve-x": "ref_naïve_x", - }; - for (const [id, key] of Object.entries(cases)) { - const ref = { current: id }; - refs[key] = ref; - expect(env.ref(id)).toBe(ref); - delete refs[key]; - } - expect(env.ref("never-mounted")).toBe(undefined); - }); - - test("refs is the registry itself", () => { - expect(env.refs).toBe(refs); - }); - - test("addEvents dispatches through the event loop mounted at call time", () => { - const first = vi.fn(); - const second = vi.fn(); - eventLoop.addEvents = first; - env.addEvents(["a"]); - eventLoop.addEvents = second; - env.addEvents(["b"], [1], { preventDefault: true }); - expect(first.mock.calls).toEqual([[["a"], [], {}]]); - expect(second.mock.calls).toEqual([[["b"], [1], { preventDefault: true }]]); - }); - - test("event builds the event addEvents takes", () => { - expect(env.event("state.my_state.save", { value: 3 })).toEqual({ - name: "state.my_state.save", - payload: { value: 3 }, - }); - expect(env.event("state.my_state.reset")).toEqual({ - name: "state.my_state.reset", - }); - }); - - test("library loads a lazy library first and returns its module", async () => { - const confetti = { default: () => "boom" }; - window.__reflex = { react: { version: "19" } }; - window.__reflex_load = vi.fn(async (names) => { - for (const name of names) { - window.__reflex[name] ??= confetti; - } - }); - await expect(env.library("canvas-confetti")).resolves.toBe(confetti); - expect(window.__reflex_load.mock.calls).toEqual([[["canvas-confetti"]]]); - await expect(env.library("react")).resolves.toEqual({ version: "19" }); - }); - - test("library rejects a library the app does not bundle", async () => { - window.__reflex = {}; - await expect(env.library("left-pad")).rejects.toThrow( - new Error("left-pad is not a bundled library of this app."), - ); - }); - - test("is frozen, so a script cannot replace a member for everyone", () => { - expect(() => { - env.addEvents = () => {}; - }).toThrow(TypeError); - }); -}); - -test("rx.call_script code sees env as env and as __reflexEnv", async () => { - const seen = []; - await applyEvent( - { - name: "_call_script", - payload: { - javascript_code: "[env === __reflexEnv, env.refs === refs]", - callback: (result) => seen.push(result), - }, - }, - null, - null, - null, - ); - expect(seen).toEqual([[true, true]]); -}); - -test("loads first, before utils/state, despite the import cycle", async () => { - vi.resetModules(); - const { env: fresh } = await import("$/utils/script_env"); - const state = await import("$/utils/state"); - state.refs.ref_first = { current: 1 }; - expect(fresh.ref("first")).toBe(state.refs.ref_first); -}); diff --git a/tests/units/compiler/state_js.test.mjs b/tests/units/compiler/state_js.test.mjs index 610aacbff88..90c1990d017 100644 --- a/tests/units/compiler/state_js.test.mjs +++ b/tests/units/compiler/state_js.test.mjs @@ -227,7 +227,7 @@ async function setup({ "$/utils/helpers/debounce": { default() {} }, "$/utils/helpers/throttle": { default() {} }, "$/utils/helpers/upload": { uploadFiles() {} }, - "$/utils/script_env": { env: {} }, + "$/utils/reflex": { reflex: {} }, }; const module = new vm.SourceTextModule(source, { context, diff --git a/tests/units/reflex_base/client_event_queue_runtime.mjs b/tests/units/reflex_base/client_event_queue_runtime.mjs index ab666047987..b0080357475 100644 --- a/tests/units/reflex_base/client_event_queue_runtime.mjs +++ b/tests/units/reflex_base/client_event_queue_runtime.mjs @@ -62,7 +62,7 @@ export async function createQueueRuntime( "$/utils/helpers/upload": { uploadFiles: uploadFiles ?? unused, }, - "$/utils/script_env": { env: {} }, + "$/utils/reflex": { reflex: {} }, ...dependencyOverrides, }; // Let Node parse the unchanged module; only expose private state to tests. From e95f417661341f5433d5910f2324ae03eeed8b2c Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 21 Nov 2026 21:18:44 +0000 Subject: [PATCH 05/15] Put ref, add_events and library directly on rx.js `rx.js.env.ref(...)` becomes `rx.js.ref(...)`, and likewise for `add_events` and `library`; each renders as a call on `reflex`, which a page imports from `$/utils/reflex` and runScript passes to backend scripts, so the `__reflexEnv` alias and the public `ScriptEnvVar` class are gone, as is `refs`. `rx.js.ref(id).current` is typed, so `rx.js.ref("search").current.value` reads the element's value. `add_events` now builds each event through `call_event_handler`, so a handler that still needs arguments fails when the var is built, with a message naming the handler and the fix, instead of dispatching an empty payload at runtime. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- .../src/reflex_base/constants/base.py | 4 +- packages/reflex-base/src/reflex_base/js.py | 115 ++++++++++++++++ .../src/reflex_base/js/__init__.py | 5 - .../reflex-base/src/reflex_base/js/env.py | 101 -------------- reflex/js.py | 2 +- tests/units/reflex_base/js/__init__.py | 0 tests/units/reflex_base/js/test_env.py | 80 ----------- tests/units/reflex_base/test_js.py | 125 ++++++++++++++++++ 8 files changed, 243 insertions(+), 189 deletions(-) create mode 100644 packages/reflex-base/src/reflex_base/js.py delete mode 100644 packages/reflex-base/src/reflex_base/js/__init__.py delete mode 100644 packages/reflex-base/src/reflex_base/js/env.py delete mode 100644 tests/units/reflex_base/js/__init__.py delete mode 100644 tests/units/reflex_base/js/test_env.py create mode 100644 tests/units/reflex_base/test_js.py diff --git a/packages/reflex-base/src/reflex_base/constants/base.py b/packages/reflex-base/src/reflex_base/constants/base.py index d8f8eebdb4f..272b2a5cb98 100644 --- a/packages/reflex-base/src/reflex_base/constants/base.py +++ b/packages/reflex-base/src/reflex_base/constants/base.py @@ -40,8 +40,8 @@ class Dirs(SimpleNamespace): CONTEXTS_PATH = UTILS + "/context" # The name of the client state file. CLIENT_STATE_PATH = UTILS + "/client_state" - # The name of the script environment file. - SCRIPT_ENV_PATH = UTILS + "/script_env" + # The module defining `reflex`, the API JavaScript reaches Reflex through. + REFLEX_API_PATH = UTILS + "/reflex" # 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/js.py b/packages/reflex-base/src/reflex_base/js.py new file mode 100644 index 00000000000..012c2213275 --- /dev/null +++ b/packages/reflex-base/src/reflex_base/js.py @@ -0,0 +1,115 @@ +"""Build calls on ``reflex``, the API browser code reaches Reflex through. + +The frontend defines ``reflex`` in ``utils/reflex.js``. Each function here +returns a Var that renders as a call on it, such as ``reflex.ref("search")``. +A page that uses one imports ``reflex``, and code ``rx.run_script`` sends from +the backend has ``reflex`` in scope, so the same Var works in both. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, cast + +from reflex_base.constants.base import Dirs +from reflex_base.event import ( + EventCallback, + EventHandler, + EventSpec, + call_event_handler, + no_args_event_spec, +) +from reflex_base.utils.exceptions import EventFnArgMismatchError +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.vars.function import FunctionVar +from reflex_base.vars.object import ObjectVar + +__all__ = ["add_events", "library", "ref"] + +_REFLEX_VAR_DATA = VarData( + imports={f"$/{Dirs.REFLEX_API_PATH}": [ImportVar(tag="reflex")]} +) + + +def _call(member: str, *args: Any) -> Var: + """Call a member of ``reflex``. + + Args: + member: The member's name. + *args: The arguments to call it with. + + Returns: + The call. + """ + return ( + Var(_js_expr=f"reflex.{member}", _var_data=_REFLEX_VAR_DATA) + .to(FunctionVar) + .call(*args) + ) + + +def _event_spec(event: EventSpec | EventHandler | EventCallback[()]) -> EventSpec: + """Build the event ``add_events`` dispatches for a handler or an event. + + Args: + event: The event, or a handler that takes no arguments. + + Returns: + The event. + + Raises: + EventFnArgMismatchError: If the handler needs arguments it was not given. + """ + try: + return call_event_handler( + cast("EventSpec | EventHandler", event), no_args_event_spec + ) + except EventFnArgMismatchError as err: + handler = event.handler if isinstance(event, EventSpec) else event + name = handler.fn.__qualname__ + msg = ( + f"rx.js.add_events cannot dispatch {name}: the handler needs " + "arguments, and add_events has none to pass it. Pass them where you " + f"add it, as in rx.js.add_events({name}(...))." + ) + raise EventFnArgMismatchError(msg) from err + + +def ref(id: str | Var[str]) -> ObjectVar[Mapping[str, Mapping[str, Any]]]: + """Get the ref of a component by its id. + + Args: + id: The component's id. + + Returns: + The ref, whose ``current`` is the mounted element, or undefined if no + component with that id has mounted. + """ + return _call("ref", id).to(ObjectVar, Mapping[str, Mapping[str, Any]]) + + +def add_events(*events: EventSpec | EventHandler | EventCallback[()]) -> Var: + """Dispatch events through the event loop, as event triggers do. + + Args: + *events: The events, or handlers that take no arguments. + + Returns: + The dispatch call. + """ + return _call( + "addEvents", LiteralVar.create([_event_spec(event) for event in events]) + ) + + +def library(name: str | Var[str]) -> Var: + """Get an npm library bundled for dynamic components. + + Args: + name: The library's import name, e.g. ``"react"``. + + Returns: + A promise of the library's module namespace. + """ + return _call("library", name) diff --git a/packages/reflex-base/src/reflex_base/js/__init__.py b/packages/reflex-base/src/reflex_base/js/__init__.py deleted file mode 100644 index 040549e7c6a..00000000000 --- a/packages/reflex-base/src/reflex_base/js/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Run JavaScript in the browser through a defined API.""" - -from reflex_base.js.env import ScriptEnvVar, env - -__all__ = ["ScriptEnvVar", "env"] diff --git a/packages/reflex-base/src/reflex_base/js/env.py b/packages/reflex-base/src/reflex_base/js/env.py deleted file mode 100644 index a9ff5101908..00000000000 --- a/packages/reflex-base/src/reflex_base/js/env.py +++ /dev/null @@ -1,101 +0,0 @@ -"""The script environment as a Var: the API browser code reaches Reflex through. - -The frontend defines it in ``utils/script_env.js``. ``rx.call_script`` code -sees it as ``env``, a JavaScript module imports it as ``env``, and Python -builds expressions on it through ``rx.js.env``. A Var renders under the alias -``__reflexEnv``, which ``rx.call_script`` code also sees, so one expression -works compiled into a page and sent from the backend, and cannot collide with -the ``env`` a page imports from ``env.json``. -""" - -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any - -from reflex_base.constants.base import Dirs -from reflex_base.event import EventCallback, EventHandler, EventSpec -from reflex_base.utils.imports import ImportVar -from reflex_base.vars.base import LiteralVar, Var, VarData -from reflex_base.vars.function import FunctionVar -from reflex_base.vars.object import ObjectVar - -# The name a Var renders the environment under. -_ALIAS = "__reflexEnv" - - -class ScriptEnvVar(ObjectVar[Mapping[str, Any]]): - """The script environment, for building browser code in Python.""" - - def _function(self, name: str) -> FunctionVar: - """Get one of the environment's functions. - - Args: - name: The member name. - - Returns: - The function. - """ - return Var( - _js_expr=f"{self._js_expr}.{name}", - _var_data=self._get_all_var_data(), - ).to(FunctionVar) - - @property - def refs(self) -> ObjectVar[Mapping[str, Any]]: - """Every registered component ref, by registry key (``ref_``). - - Returns: - The ref registry. - """ - return Var( - _js_expr=f"{self._js_expr}.refs", - _var_data=self._get_all_var_data(), - ).to(dict) - - def ref(self, id: str | Var[str]) -> ObjectVar[Mapping[str, Any]]: - """Get the ref of a component by its id. - - Args: - id: The component id. - - Returns: - The ref, whose ``current`` is the mounted element, or undefined if - no component with that id has mounted. - """ - return self._function("ref").call(id).to(dict) - - def add_events(self, *events: EventSpec | EventHandler | EventCallback[()]) -> Var: - """Dispatch events through the event loop, as event triggers do. - - Args: - *events: The events, or handlers that take no arguments. - - Returns: - The dispatch call. - """ - return self._function("addEvents").call( - LiteralVar.create([ - event if isinstance(event, EventSpec) else event() for event in events - ]) - ) - - def library(self, name: str | Var[str]) -> Var: - """Get a library bundled for dynamic components. - - Args: - name: The library's import name, e.g. ``"react"``. - - Returns: - A promise of the library's module namespace. - """ - return self._function("library").call(name) - - -env = ScriptEnvVar( - _js_expr=_ALIAS, - _var_type=Mapping[str, Any], - _var_data=VarData( - imports={f"$/{Dirs.SCRIPT_ENV_PATH}": [ImportVar(tag="env", alias=_ALIAS)]} - ), -) diff --git a/reflex/js.py b/reflex/js.py index 8c3ff01626e..05ac215bf88 100644 --- a/reflex/js.py +++ b/reflex/js.py @@ -1,4 +1,4 @@ # pyright: reportWildcardImportFromLibrary=false -"""Run JavaScript in the browser through a defined API.""" +"""Build calls on ``reflex``, the API browser code reaches Reflex through.""" from reflex_base.js import * # pragma: no cover diff --git a/tests/units/reflex_base/js/__init__.py b/tests/units/reflex_base/js/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/units/reflex_base/js/test_env.py b/tests/units/reflex_base/js/test_env.py deleted file mode 100644 index 9d854b0d7bf..00000000000 --- a/tests/units/reflex_base/js/test_env.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Tests for the script environment Var.""" - -from typing import cast - -from reflex_base.event import EventSpec, run_script -from reflex_base.js import env -from reflex_base.utils.imports import ImportVar -from reflex_base.vars.base import LiteralVar, Var, VarData - -import reflex as rx - -ENV_VAR_DATA = VarData( - imports={"$/utils/script_env": [ImportVar(tag="env", alias="__reflexEnv")]} -) - - -class EnvState(rx.State): - """A state whose handlers and vars the env Var is built with.""" - - target: str = "search" - - @rx.event - def save(self, value: int): - """Take an argument. - - Args: - value: The value. - """ - - @rx.event - def reset_all(self): - """Take no arguments.""" - - -def test_env_renders_under_its_alias_with_its_import(): - """The env Var renders under its alias and imports it from script_env.""" - assert str(env) == "__reflexEnv" - assert env._get_all_var_data() == ENV_VAR_DATA - assert rx.js.env is env - - -def test_refs_and_ref(): - """Refs and ref() render on the alias and keep the var data of their arguments.""" - assert str(env.refs) == "__reflexEnv.refs" - assert env.refs._get_all_var_data() == ENV_VAR_DATA - assert str(env.ref("search")) == '(__reflexEnv.ref("search"))' - target = cast(Var[str], EnvState.target) - ref = env.ref(target) - assert str(ref) == f"(__reflexEnv.ref({target!s}))" - assert ref._get_all_var_data() == VarData.merge( - ENV_VAR_DATA, target._get_all_var_data() - ) - - -def test_add_events_takes_specs_and_argless_handlers(): - """add_events compiles event specs, and handlers without arguments, to events.""" - name = EnvState.get_full_name() - assert str(env.add_events(EnvState.save(3), EnvState.reset_all)) == ( - "(__reflexEnv.addEvents([" - f'(ReflexEvent("{name}.save", ({{ ["value"] : 3 }}), ({{ }}))), ' - f'(ReflexEvent("{name}.reset_all", ({{ }}), ({{ }})))' - "]))" - ) - - -def test_library(): - """library() renders a call on the alias.""" - assert str(env.library("react")) == '(__reflexEnv.library("react"))' - - -def test_run_script_carries_the_import_into_the_page(): - """A script built on env carries the env import into the page that uses it.""" - spec = run_script(env.ref("search")) - assert isinstance(spec, EventSpec) - literal = LiteralVar.create(spec) - assert str(literal) == ( - '(ReflexEvent("_call_function", ({ ["function"] : ' - '(() => (__reflexEnv.ref("search"))), ["callback"] : null }), ({ })))' - ) - assert literal._get_all_var_data() == ENV_VAR_DATA diff --git a/tests/units/reflex_base/test_js.py b/tests/units/reflex_base/test_js.py new file mode 100644 index 00000000000..bac869c86f3 --- /dev/null +++ b/tests/units/reflex_base/test_js.py @@ -0,0 +1,125 @@ +"""Tests for the Vars that call ``reflex``, the API browser code reaches Reflex through.""" + +from typing import cast + +import pytest +from reflex_base import js +from reflex_base.event import run_script +from reflex_base.utils.exceptions import EventFnArgMismatchError +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import LiteralVar, Var, VarData + +import reflex as rx + +REFLEX_VAR_DATA = VarData(imports={"$/utils/reflex": [ImportVar(tag="reflex")]}) + + +class JsState(rx.State): + """A state whose handlers and vars the Vars are built with.""" + + target: str = "search" + + @rx.event + def save(self, value: int): + """Take an argument. + + Args: + value: The value. + """ + + @rx.event + def save_pair(self, first: int, second: int): + """Take two arguments. + + Args: + first: The first value. + second: The second value. + """ + + @rx.event + def reset_all(self): + """Take no arguments.""" + + +def test_rx_js_is_reflex_base_js(): + """rx.js exposes exactly the public functions of reflex_base.js.""" + assert js.__all__ == ["add_events", "library", "ref"] + assert [getattr(rx.js, name) for name in js.__all__] == [ + js.add_events, + js.library, + js.ref, + ] + + +def test_ref(): + """ref() calls reflex.ref, keeps its argument's var data, and reads current.""" + search = js.ref("search") + assert str(search) == '(reflex.ref("search"))' + assert search._get_all_var_data() == REFLEX_VAR_DATA + assert str(search.current.value) == '(reflex.ref("search"))?.["current"]?.["value"]' + + target = cast(Var[str], JsState.target) + ref = js.ref(target) + assert str(ref) == f"(reflex.ref({target!s}))" + assert ref._get_all_var_data() == VarData.merge( + REFLEX_VAR_DATA, target._get_all_var_data() + ) + + +def test_add_events(): + """add_events compiles events, and handlers without arguments, to one dispatch.""" + name = JsState.get_full_name() + dispatch = js.add_events( + JsState.save(3), JsState.save_pair(1, 2), JsState.reset_all, rx.redirect("/x") + ) + assert str(dispatch) == ( + "(reflex.addEvents([" + f'(ReflexEvent("{name}.save", ({{ ["value"] : 3 }}), ({{ }}))), ' + f'(ReflexEvent("{name}.save_pair", ({{ ["first"] : 1, ["second"] : 2 }}), ({{ }}))), ' + f'(ReflexEvent("{name}.reset_all", ({{ }}), ({{ }}))), ' + '(ReflexEvent("_redirect", ({ ["path"] : "/x", ["external"] : false, ' + '["popup"] : false, ["replace"] : false }), ({ })))' + "]))" + ) + assert dispatch._get_all_var_data() == REFLEX_VAR_DATA + assert str(js.add_events()) == "(reflex.addEvents([]))" + + +@pytest.mark.parametrize( + ("event", "name"), + [ + (JsState.save, "JsState.save"), + (JsState.save_pair(1), "JsState.save_pair"), + ], +) +def test_add_events_rejects_a_handler_missing_arguments(event, name: str): + """A handler still missing arguments fails when add_events is built. + + Args: + event: The handler or partial event. + name: The handler's qualified name. + """ + with pytest.raises(EventFnArgMismatchError) as error: + js.add_events(JsState.reset_all, event) + assert str(error.value) == ( + f"rx.js.add_events cannot dispatch {name}: the handler needs arguments, " + "and add_events has none to pass it. Pass them where you add it, as in " + f"rx.js.add_events({name}(...))." + ) + + +def test_library(): + """library() calls reflex.library.""" + react = js.library("react") + assert str(react) == '(reflex.library("react"))' + assert react._get_all_var_data() == REFLEX_VAR_DATA + + +def test_run_script_carries_the_import_into_the_page(): + """A script built on reflex carries the reflex import into the page that uses it.""" + literal = LiteralVar.create(run_script(js.ref("search"))) + assert str(literal) == ( + '(ReflexEvent("_call_function", ({ ["function"] : ' + '(() => (reflex.ref("search"))), ["callback"] : null }), ({ })))' + ) + assert literal._get_all_var_data() == REFLEX_VAR_DATA From 4ae5dbcc5c3002ae05f9fa8d1d83d63f009b4b31 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 21 Nov 2026 21:18:45 +0000 Subject: [PATCH 06/15] Test reflex and rx.js end to end in the call_script app Covers `reflex.ref` from a string script, `rx.js.add_events` from a trigger and from the backend, `rx.js.ref` read by the backend, `reflex.library` from on_mount, and an `rx.get_upload_url` script sent from the backend resolving to the upload endpoint. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- .../tests_playwright/test_call_script.py | 110 +++++++++++++----- 1 file changed, 83 insertions(+), 27 deletions(-) diff --git a/tests/integration/tests_playwright/test_call_script.py b/tests/integration/tests_playwright/test_call_script.py index 7c7995bb9dc..1c906368e9a 100644 --- a/tests/integration/tests_playwright/test_call_script.py +++ b/tests/integration/tests_playwright/test_call_script.py @@ -7,6 +7,7 @@ import pytest from playwright.sync_api import Page, expect +from reflex.config import get_config from reflex.testing import AppHarness @@ -44,7 +45,8 @@ class CallScriptState(rx.State): external_counter: rx.Field[int] = rx.field(0) value: str = "Initial" last_result: rx.Field[int] = rx.field(0) - env_result: str = "" + reflex_result: str = "" + mounted_library: str = "" @rx.event def call_script_callback(self, result): @@ -197,13 +199,32 @@ def set_value(self, value: str): self.value = value @rx.event - def set_env_result(self, value: str): - self.env_result = value + def set_reflex_result(self, value: str): + self.reflex_result = value @rx.event - def env_var_backend(self): + def set_mounted_library(self, value: str): + self.mounted_library = value + + @rx.event + def add_events_from_backend(self): + return rx.run_script( + rx.js.add_events( + CallScriptState.set_reflex_result("add_events from the backend") + ) + ) + + @rx.event + def ref_from_backend(self): return rx.run_script( - rx.js.env.add_events(CallScriptState.set_env_result("env var backend")) + rx.js.ref("reflex_target").current.value, + callback=CallScriptState.set_reflex_result, + ) + + @rx.event + def upload_url_from_backend(self): + return rx.call_script( + rx.get_upload_url("a.png"), callback=CallScriptState.set_reflex_result ) @rx.event @@ -365,29 +386,55 @@ def index(): ), id="call_with_var_str_cast_wrapped_inline", ), - rx.input(id="env_target", default_value="from the ref"), - rx.input(value=CallScriptState.env_result, id="env_result", read_only=True), + rx.input( + id="reflex_target", + default_value="from the ref", + on_mount=rx.call_script( + "reflex.library('react').then((react) => typeof react.useState)", + callback=CallScriptState.set_mounted_library, + ), + ), + rx.input( + value=CallScriptState.reflex_result, id="reflex_result", read_only=True + ), + rx.input( + value=CallScriptState.mounted_library, + id="mounted_library", + read_only=True, + ), rx.button( - "env_string", + "ref_from_string", on_click=rx.call_script( - "env.ref('env_target').current.value", - callback=CallScriptState.set_env_result, + "reflex.ref('reflex_target').current.value", + callback=CallScriptState.set_reflex_result, ), - id="env_string", + id="ref_from_string", ), rx.button( - "env_var_frontend", + "add_events_from_frontend", on_click=rx.run_script( - rx.js.env.add_events( - CallScriptState.set_env_result("env var frontend") + rx.js.add_events( + CallScriptState.set_reflex_result( + "add_events from the frontend" + ) ) ), - id="env_var_frontend", + id="add_events_from_frontend", ), rx.button( - "env_var_backend", - on_click=CallScriptState.env_var_backend, - id="env_var_backend", + "add_events_from_backend", + on_click=CallScriptState.add_events_from_backend, + id="add_events_from_backend", + ), + rx.button( + "ref_from_backend", + on_click=CallScriptState.ref_from_backend, + id="ref_from_backend", + ), + rx.button( + "upload_url_from_backend", + on_click=CallScriptState.upload_url_from_backend, + id="upload_url_from_backend", ), ) @@ -562,19 +609,28 @@ def test_call_script_w_var( expect(last_result).to_have_value("8") -def test_script_env(call_script_page: Page): - """Scripts reach the script environment as `env` and through `rx.js.env`. +def test_reflex_api(call_script_page: Page): + """Scripts reach Reflex through `reflex`, from strings and from `rx.js`. Args: call_script_page: Playwright page. """ - env_result = call_script_page.locator("#env_result") + result = call_script_page.locator("#reflex_result") + expect(call_script_page.locator("#mounted_library")).to_have_value("function") + + call_script_page.locator("#ref_from_string").click() + expect(result).to_have_value("from the ref") + + call_script_page.locator("#add_events_from_frontend").click() + expect(result).to_have_value("add_events from the frontend") - call_script_page.locator("#env_string").click() - expect(env_result).to_have_value("from the ref") + call_script_page.locator("#add_events_from_backend").click() + expect(result).to_have_value("add_events from the backend") - call_script_page.locator("#env_var_frontend").click() - expect(env_result).to_have_value("env var frontend") + call_script_page.locator("#reflex_target").fill("typed, read by the backend") + call_script_page.locator("#ref_from_backend").click() + expect(result).to_have_value("typed, read by the backend") - call_script_page.locator("#env_var_backend").click() - expect(env_result).to_have_value("env var backend") + # A script from the backend still reads `env` from env.json. + call_script_page.locator("#upload_url_from_backend").click() + expect(result).to_have_value(f"{get_config().api_url}/_upload/a.png") From 2557adf0cfd6d39750d13b891159df46120a4891 Mon Sep 17 00:00:00 2001 From: Farhan Date: Sat, 21 Nov 2026 21:18:45 +0000 Subject: [PATCH 07/15] Document reflex and rx.js usage-first Rename "The Script Environment" to "Reaching Reflex from JavaScript": a runnable demo from a script, a JavaScript module, rx.js from Python, the rule to prefer `reflex` over other names in scope, and each error with its fix. News fragments follow the rename, and the unreleased script scope fragment lists `env` again. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- docs/api-reference/browser_javascript.md | 136 +++++++++++++++--- news/+reflex-js.feature.md | 1 + news/+script-env.feature.md | 1 - ...+eval-minified-shared-chunk.performance.md | 2 +- .../reflex-base/news/+reflex-js.feature.md | 1 + .../reflex-base/news/+script-env.feature.md | 1 - 6 files changed, 120 insertions(+), 22 deletions(-) create mode 100644 news/+reflex-js.feature.md delete mode 100644 news/+script-env.feature.md create mode 100644 packages/reflex-base/news/+reflex-js.feature.md delete mode 100644 packages/reflex-base/news/+script-env.feature.md diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index 1490f3bbf4b..30c8e1e6701 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -141,40 +141,138 @@ The `callback` parameter may be an `EventHandler` with one argument, or a lambda If the callback is None, then no event is triggered. ``` -## The Script Environment +## Reaching Reflex from JavaScript -Code run by `rx.call_script` reaches Reflex through `env`, a small API that -stays stable as the rest of the frontend changes: +JavaScript you run in the browser reaches Reflex through `reflex`, an object +whose members stay the same as the rest of the frontend changes: | Member | What it does | | --- | --- | -| `env.ref(id)` | The ref of the component with that `id`; its `current` is the element. | -| `env.refs` | Every registered component ref. | -| `env.addEvents(events)` | Dispatch events, as event triggers do. | -| `env.event(name, payload)` | Build an event for `env.addEvents`. | -| `env.library(name)` | A promise of a library bundled for dynamic components, such as `"react"`. | +| `reflex.ref(id)` | The ref of the component with that `id`; its `current` is the element. `undefined` until a component with that `id` mounts. | +| `reflex.addEvents(events)` | Dispatch events, as an event trigger does. | +| `reflex.event(name, payload)` | Build an event for `reflex.addEvents`: `name` is the event handler's full name, `payload` its arguments by name. | +| `reflex.library(name)` | A promise of an npm library bundled for dynamic components, such as `"react"`. | -```python -(rx.input(id="search"),) -(rx.button("Focus", on_click=rx.call_script("env.ref('search').current.focus()")),) +Prefer `reflex` over the other names a script can see, such as `refs`, +`ReflexEvent` or `addEvents`: those are internals of the frontend and may change +between Reflex versions. + +### From a Script + +Code run by `rx.call_script` sees `reflex`: + +```python demo exec +class ReflexApiState(rx.State): + result: str = "" + + @rx.event + def set_result(self, result: str): + self.result = result + + +def reflex_api_demo(): + return rx.vstack( + rx.input(id="reflex_api_search", placeholder="Type something"), + rx.hstack( + rx.button( + "Focus", + on_click=rx.call_script( + "reflex.ref('reflex_api_search').current.focus()" + ), + ), + rx.button( + "Read", + on_click=rx.call_script( + "reflex.ref('reflex_api_search').current.value", + callback=ReflexApiState.set_result, + ), + ), + rx.button( + "React version", + on_click=rx.call_script( + "reflex.library('react').then((react) => react.version)", + callback=ReflexApiState.set_result, + ), + ), + ), + rx.text(f"Result: {ReflexApiState.result}"), + ) ``` -To build the same calls from Python vars, use `rx.js.env`. It works in an event -trigger and when an event handler returns it: +### From a JavaScript Module + +A JavaScript module, such as one a [wrapped component](/docs/wrapping-react/overview/) +imports, imports `reflex` from `$/utils/reflex`: + +```javascript +import { reflex } from "$/utils/reflex"; + +export function saveSearch(handlerName) { + const value = reflex.ref("reflex_api_search").current.value; + reflex.addEvents([reflex.event(handlerName, { value })]); +} +``` + +### From Python + +`rx.js` builds the same calls from Python, filling in the event handler's full +name for you. Each function returns a var, which `rx.run_script` runs whether an +event trigger uses it or an event handler returns it: + +| Python | JavaScript | +| --- | --- | +| `rx.js.ref(id)` | `reflex.ref(id)` | +| `rx.js.add_events(*events)` | `reflex.addEvents([...])` | +| `rx.js.library(name)` | `reflex.library(name)` | ```python class SearchState(rx.State): + query: str = "" + + @rx.event + def set_query(self, query: str): + self.query = query + @rx.event - def clear_later(self): - return rx.run_script(rx.js.env.add_events(SearchState.clear)) + def clear(self): + self.query = "" @rx.event - def clear(self): ... + def read_search(self): + # Read the input's current value from the browser. + return rx.run_script( + rx.js.ref("search").current.value, callback=SearchState.set_query + ) + + +def search(): + return rx.vstack( + rx.input(id="search"), + rx.button("Read", on_click=SearchState.read_search), + rx.button("Clear", on_click=rx.run_script(rx.js.add_events(SearchState.clear))), + rx.text(SearchState.query), + ) ``` -Prefer `env` over the other names a script can see, such as `refs` or -`ReflexEvent`: those are internals of the frontend and may change between -Reflex versions. +`rx.js.add_events` takes events, such as `SearchState.set_query("x")`, and +event handlers that take no arguments, such as `SearchState.clear`. + +### Errors + +- `rx.js.add_events cannot dispatch SearchState.set_query: the handler needs + arguments, and add_events has none to pass it.` Pass the arguments in Python: + `rx.js.add_events(SearchState.set_query("x"))`. +- `reflex.library("left-pad") cannot load "left-pad": the app does not bundle it + for dynamic components.` Bundle it in your app's Python code with + `bundle_library("left-pad")` from `reflex.components.dynamic`. +- `reflex.library("react") cannot load "react" yet: the app registers its + bundled libraries when it first mounts, and it has not mounted.` Call + `reflex.library` from an event, such as `on_mount` or `on_click`, rather than + while a module loads. +- `reflex.library("$/utils/state") cannot load "$/utils/state": a name starting + with "$/" is a module of the app's frontend, not a bundled npm library.` Use + the members of `reflex` instead of Reflex internals, and import your own + modules from a JavaScript module. ## Using React Hooks diff --git a/news/+reflex-js.feature.md b/news/+reflex-js.feature.md new file mode 100644 index 00000000000..1d0381e010e --- /dev/null +++ b/news/+reflex-js.feature.md @@ -0,0 +1 @@ +Add `rx.js.ref(id)`, `rx.js.add_events(*events)` and `rx.js.library(name)`, vars that call the browser's `reflex` API from Python and work both in an event trigger and returned from an event handler, e.g. `rx.run_script(rx.js.add_events(State.handler))`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). diff --git a/news/+script-env.feature.md b/news/+script-env.feature.md deleted file mode 100644 index 87e4ca884d8..00000000000 --- a/news/+script-env.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `rx.js.env`, a var for the script environment, so `rx.run_script(rx.js.env.add_events(State.handler))` and `rx.js.env.ref("my_id")` work both in event triggers and when returned from an event handler. See [Browser Javascript](https://reflex.dev/docs/api-reference/browser-javascript/#the-script-environment). diff --git a/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md b/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md index 50aaf67b1cd..d9077ae83b4 100644 --- a/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md +++ b/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md @@ -1 +1 @@ -Shrink the shared JavaScript chunk by about 88 KB (11 KB gzipped) when `frontend_lazy_bundled_libraries` is on: server-provided scripts and callbacks no longer use a direct `eval`, so the minifier can shorten every name in that chunk. Scripts passed to `rx.call_script` and `rx.call_function` still see every export of `utils/state.js` (such as `ReflexEvent`, `refs` and `queueEvents`), plus `addEvents`, `socket`, `navigate`, `params`, `token` and the globals; names the module does not export, such as its imports, are no longer in scope. +Shrink the shared JavaScript chunk by about 88 KB (11 KB gzipped) when `frontend_lazy_bundled_libraries` is on: server-provided scripts and callbacks no longer use a direct `eval`, so the minifier can shorten every name in that chunk. Scripts passed to `rx.call_script` and `rx.call_function` still see every export of `utils/state.js` (such as `ReflexEvent`, `refs` and `queueEvents`), plus `addEvents`, `socket`, `navigate`, `params`, `token`, `env` (which `rx.get_upload_url` reads) and the globals; names the module does not export, such as its other imports, are no longer in scope. diff --git a/packages/reflex-base/news/+reflex-js.feature.md b/packages/reflex-base/news/+reflex-js.feature.md new file mode 100644 index 00000000000..f43c8778cbd --- /dev/null +++ b/packages/reflex-base/news/+reflex-js.feature.md @@ -0,0 +1 @@ +Add `reflex`, the API browser JavaScript reaches Reflex through: `rx.call_script` code, and JavaScript modules through `import { reflex } from "$/utils/reflex"`, can call `reflex.ref(id)`, `reflex.addEvents(events)`, `reflex.event(name, payload)` and `reflex.library(name)` instead of frontend internals, e.g. `rx.call_script("reflex.ref('search').current.focus()")`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). diff --git a/packages/reflex-base/news/+script-env.feature.md b/packages/reflex-base/news/+script-env.feature.md deleted file mode 100644 index f2a39481cdd..00000000000 --- a/packages/reflex-base/news/+script-env.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `env`, the API browser code reaches Reflex through: `rx.call_script` code can call `env.ref(id)`, `env.refs`, `env.addEvents(...)`, `env.event(...)` and `env.library(name)` instead of frontend internals, and `reflex_base.js.env` builds the same calls from Python vars. From b35a13e955be45508bef6ce8c707b3cb4057ac4e Mon Sep 17 00:00:00 2001 From: Farhan Date: Sun, 22 Nov 2026 22:02:04 +0000 Subject: [PATCH 08/15] Reject library names the registry only inherits, and correct the reflex docs `window.__reflex` is an object literal, so `reflex.library("constructor")` returned Object instead of saying the app does not bundle it. The docs now quote each error in full, say a ref's `current` is null until React attaches the element, and the news lists `reflex` among the names a script sees. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- docs/api-reference/browser_javascript.md | 36 ++++++++++--------- ...+eval-minified-shared-chunk.performance.md | 2 +- packages/reflex-frontend/src/utils/reflex.js | 9 +++-- packages/reflex-frontend/tests/reflex.test.js | 9 +++++ 4 files changed, 37 insertions(+), 19 deletions(-) diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index 30c8e1e6701..55336ff8bb2 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -144,11 +144,11 @@ If the callback is None, then no event is triggered. ## Reaching Reflex from JavaScript JavaScript you run in the browser reaches Reflex through `reflex`, an object -whose members stay the same as the rest of the frontend changes: +whose members stay the same across Reflex versions: | Member | What it does | | --- | --- | -| `reflex.ref(id)` | The ref of the component with that `id`; its `current` is the element. `undefined` until a component with that `id` mounts. | +| `reflex.ref(id)` | The ref of the component with that `id`. `undefined` until a component with that `id` renders; its `current` is `null` until React attaches the element, then the element. | | `reflex.addEvents(events)` | Dispatch events, as an event trigger does. | | `reflex.event(name, payload)` | Build an event for `reflex.addEvents`: `name` is the event handler's full name, `payload` its arguments by name. | | `reflex.library(name)` | A promise of an npm library bundled for dynamic components, such as `"react"`. | @@ -259,20 +259,24 @@ event handlers that take no arguments, such as `SearchState.clear`. ### Errors -- `rx.js.add_events cannot dispatch SearchState.set_query: the handler needs - arguments, and add_events has none to pass it.` Pass the arguments in Python: - `rx.js.add_events(SearchState.set_query("x"))`. -- `reflex.library("left-pad") cannot load "left-pad": the app does not bundle it - for dynamic components.` Bundle it in your app's Python code with - `bundle_library("left-pad")` from `reflex.components.dynamic`. -- `reflex.library("react") cannot load "react" yet: the app registers its - bundled libraries when it first mounts, and it has not mounted.` Call - `reflex.library` from an event, such as `on_mount` or `on_click`, rather than - while a module loads. -- `reflex.library("$/utils/state") cannot load "$/utils/state": a name starting - with "$/" is a module of the app's frontend, not a bundled npm library.` Use - the members of `reflex` instead of Reflex internals, and import your own - modules from a JavaScript module. +Each error says what went wrong and how to fix it. The messages, with example +names: + +```text +rx.js.add_events cannot dispatch SearchState.set_query: the handler needs arguments, and add_events has none to pass it. Pass them where you add it, as in rx.js.add_events(SearchState.set_query(...)). +``` + +```text +reflex.library("left-pad") cannot load "left-pad": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("left-pad") from reflex.components.dynamic in your app's Python code. +``` + +```text +reflex.library("react") cannot load "react" yet: the app registers its bundled libraries when it first mounts, and it has not mounted. Call reflex.library from an event, such as on_mount or on_click, rather than while a module loads. +``` + +```text +reflex.library("$/utils/state") cannot load "$/utils/state": a name starting with "$/" is a module of the app's frontend, not a bundled npm library. Use reflex.ref, reflex.addEvents and reflex.event instead of Reflex internals, and import your own modules from a JavaScript module. +``` ## Using React Hooks diff --git a/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md b/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md index d9077ae83b4..47ff3c53b7f 100644 --- a/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md +++ b/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md @@ -1 +1 @@ -Shrink the shared JavaScript chunk by about 88 KB (11 KB gzipped) when `frontend_lazy_bundled_libraries` is on: server-provided scripts and callbacks no longer use a direct `eval`, so the minifier can shorten every name in that chunk. Scripts passed to `rx.call_script` and `rx.call_function` still see every export of `utils/state.js` (such as `ReflexEvent`, `refs` and `queueEvents`), plus `addEvents`, `socket`, `navigate`, `params`, `token`, `env` (which `rx.get_upload_url` reads) and the globals; names the module does not export, such as its other imports, are no longer in scope. +Shrink the shared JavaScript chunk by about 88 KB (11 KB gzipped) when `frontend_lazy_bundled_libraries` is on: server-provided scripts and callbacks no longer use a direct `eval`, so the minifier can shorten every name in that chunk. Scripts passed to `rx.call_script` and `rx.call_function` still see every export of `utils/state.js` (such as `ReflexEvent`, `refs` and `queueEvents`), plus `addEvents`, `socket`, `navigate`, `params`, `token`, `env` (which `rx.get_upload_url` reads), `reflex` and the globals; names the module does not export, such as its other imports, are no longer in scope. diff --git a/packages/reflex-frontend/src/utils/reflex.js b/packages/reflex-frontend/src/utils/reflex.js index 9b478bc9aa3..ac0f72b6132 100644 --- a/packages/reflex-frontend/src/utils/reflex.js +++ b/packages/reflex-frontend/src/utils/reflex.js @@ -21,7 +21,8 @@ export const reflex = Object.freeze({ * Get the ref of a component by its id. * @param {string} id The component id. * @returns {{current: any} | undefined} The ref, or undefined if no - * component with that id has mounted. + * component with that id has rendered. Its `current` is null until React + * attaches the element. */ ref: (id) => refs[refName(id)], @@ -60,7 +61,11 @@ export const reflex = Object.freeze({ `reflex.library("${name}") cannot load "${name}" yet: the app registers its bundled libraries when it first mounts, and it has not mounted. Call reflex.library from an event, such as on_mount or on_click, rather than while a module loads.`, ); } - const module = window.__reflex[name]; + // The registry is an object literal: `constructor` and the like are + // inherited, not bundled libraries. + const module = Object.hasOwn(window.__reflex, name) + ? window.__reflex[name] + : undefined; if (module === undefined) { throw new Error( `reflex.library("${name}") cannot load "${name}": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("${name}") from reflex.components.dynamic in your app's Python code.`, diff --git a/packages/reflex-frontend/tests/reflex.test.js b/packages/reflex-frontend/tests/reflex.test.js index 72a157b5be5..046f675b599 100644 --- a/packages/reflex-frontend/tests/reflex.test.js +++ b/packages/reflex-frontend/tests/reflex.test.js @@ -91,6 +91,15 @@ test("library rejects a library the app does not bundle", async () => { ); }); +test("library rejects a name the registry only inherits", async () => { + window.__reflex = {}; + await expect(reflex.library("constructor")).rejects.toThrow( + new Error( + 'reflex.library("constructor") cannot load "constructor": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("constructor") from reflex.components.dynamic in your app\'s Python code.', + ), + ); +}); + test("is frozen, so a script cannot replace a member for everyone", () => { expect(Object.isFrozen(reflex)).toBe(true); expect(Object.keys(reflex)).toEqual(["ref", "addEvents", "event", "library"]); From 8901c28199c711258f0802e705e879ddc0daf7ed Mon Sep 17 00:00:00 2001 From: Farhan Date: Mon, 23 Nov 2026 23:34:51 +0500 Subject: [PATCH 09/15] Drop rx.js.add_events, which only repeats an event trigger rx.run_script(rx.js.add_events(State.handler)) does what on_click=State.handler and return State.handler already do, with an extra round trip through the browser. Keep reflex.addEvents and reflex.event for JavaScript, which has no other way to send a value it computed back to Python. --- docs/api-reference/browser_javascript.md | 21 ++---- news/+reflex-js.feature.md | 2 +- packages/reflex-base/src/reflex_base/js.py | 55 +------------- .../tests_playwright/test_call_script.py | 34 ++------- tests/units/reflex_base/test_js.py | 75 +------------------ 5 files changed, 21 insertions(+), 166 deletions(-) diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index 55336ff8bb2..fe72e54409b 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -215,14 +215,13 @@ export function saveSearch(handlerName) { ### From Python -`rx.js` builds the same calls from Python, filling in the event handler's full -name for you. Each function returns a var, which `rx.run_script` runs whether an -event trigger uses it or an event handler returns it: +`rx.js` builds the same calls from Python. Each function returns a var, which +`rx.run_script` runs whether an event trigger uses it or an event handler +returns it: | Python | JavaScript | | --- | --- | | `rx.js.ref(id)` | `reflex.ref(id)` | -| `rx.js.add_events(*events)` | `reflex.addEvents([...])` | | `rx.js.library(name)` | `reflex.library(name)` | ```python @@ -233,10 +232,6 @@ class SearchState(rx.State): def set_query(self, query: str): self.query = query - @rx.event - def clear(self): - self.query = "" - @rx.event def read_search(self): # Read the input's current value from the browser. @@ -249,23 +244,19 @@ def search(): return rx.vstack( rx.input(id="search"), rx.button("Read", on_click=SearchState.read_search), - rx.button("Clear", on_click=rx.run_script(rx.js.add_events(SearchState.clear))), rx.text(SearchState.query), ) ``` -`rx.js.add_events` takes events, such as `SearchState.set_query("x")`, and -event handlers that take no arguments, such as `SearchState.clear`. +Python has no `reflex.addEvents`: dispatch events from Python as usual, with an +event trigger or by returning them from an event handler. `reflex.addEvents` is +for JavaScript that sends a value it computed back to Python. ### Errors Each error says what went wrong and how to fix it. The messages, with example names: -```text -rx.js.add_events cannot dispatch SearchState.set_query: the handler needs arguments, and add_events has none to pass it. Pass them where you add it, as in rx.js.add_events(SearchState.set_query(...)). -``` - ```text reflex.library("left-pad") cannot load "left-pad": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("left-pad") from reflex.components.dynamic in your app's Python code. ``` diff --git a/news/+reflex-js.feature.md b/news/+reflex-js.feature.md index 1d0381e010e..56c10e26c42 100644 --- a/news/+reflex-js.feature.md +++ b/news/+reflex-js.feature.md @@ -1 +1 @@ -Add `rx.js.ref(id)`, `rx.js.add_events(*events)` and `rx.js.library(name)`, vars that call the browser's `reflex` API from Python and work both in an event trigger and returned from an event handler, e.g. `rx.run_script(rx.js.add_events(State.handler))`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). +Add `rx.js.ref(id)` and `rx.js.library(name)`, vars that call the browser's `reflex` API from Python and work both in an event trigger and returned from an event handler, e.g. `rx.run_script(rx.js.ref("search").current.value, callback=State.set_query)`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). diff --git a/packages/reflex-base/src/reflex_base/js.py b/packages/reflex-base/src/reflex_base/js.py index 012c2213275..526a6fc3271 100644 --- a/packages/reflex-base/src/reflex_base/js.py +++ b/packages/reflex-base/src/reflex_base/js.py @@ -9,23 +9,15 @@ from __future__ import annotations from collections.abc import Mapping -from typing import Any, cast +from typing import Any from reflex_base.constants.base import Dirs -from reflex_base.event import ( - EventCallback, - EventHandler, - EventSpec, - call_event_handler, - no_args_event_spec, -) -from reflex_base.utils.exceptions import EventFnArgMismatchError from reflex_base.utils.imports import ImportVar -from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.vars.base import Var, VarData from reflex_base.vars.function import FunctionVar from reflex_base.vars.object import ObjectVar -__all__ = ["add_events", "library", "ref"] +__all__ = ["library", "ref"] _REFLEX_VAR_DATA = VarData( imports={f"$/{Dirs.REFLEX_API_PATH}": [ImportVar(tag="reflex")]} @@ -49,33 +41,6 @@ def _call(member: str, *args: Any) -> Var: ) -def _event_spec(event: EventSpec | EventHandler | EventCallback[()]) -> EventSpec: - """Build the event ``add_events`` dispatches for a handler or an event. - - Args: - event: The event, or a handler that takes no arguments. - - Returns: - The event. - - Raises: - EventFnArgMismatchError: If the handler needs arguments it was not given. - """ - try: - return call_event_handler( - cast("EventSpec | EventHandler", event), no_args_event_spec - ) - except EventFnArgMismatchError as err: - handler = event.handler if isinstance(event, EventSpec) else event - name = handler.fn.__qualname__ - msg = ( - f"rx.js.add_events cannot dispatch {name}: the handler needs " - "arguments, and add_events has none to pass it. Pass them where you " - f"add it, as in rx.js.add_events({name}(...))." - ) - raise EventFnArgMismatchError(msg) from err - - def ref(id: str | Var[str]) -> ObjectVar[Mapping[str, Mapping[str, Any]]]: """Get the ref of a component by its id. @@ -89,20 +54,6 @@ def ref(id: str | Var[str]) -> ObjectVar[Mapping[str, Mapping[str, Any]]]: return _call("ref", id).to(ObjectVar, Mapping[str, Mapping[str, Any]]) -def add_events(*events: EventSpec | EventHandler | EventCallback[()]) -> Var: - """Dispatch events through the event loop, as event triggers do. - - Args: - *events: The events, or handlers that take no arguments. - - Returns: - The dispatch call. - """ - return _call( - "addEvents", LiteralVar.create([_event_spec(event) for event in events]) - ) - - def library(name: str | Var[str]) -> Var: """Get an npm library bundled for dynamic components. diff --git a/tests/integration/tests_playwright/test_call_script.py b/tests/integration/tests_playwright/test_call_script.py index 1c906368e9a..7cd26b183e3 100644 --- a/tests/integration/tests_playwright/test_call_script.py +++ b/tests/integration/tests_playwright/test_call_script.py @@ -206,14 +206,6 @@ def set_reflex_result(self, value: str): def set_mounted_library(self, value: str): self.mounted_library = value - @rx.event - def add_events_from_backend(self): - return rx.run_script( - rx.js.add_events( - CallScriptState.set_reflex_result("add_events from the backend") - ) - ) - @rx.event def ref_from_backend(self): return rx.run_script( @@ -411,20 +403,13 @@ def index(): id="ref_from_string", ), rx.button( - "add_events_from_frontend", - on_click=rx.run_script( - rx.js.add_events( - CallScriptState.set_reflex_result( - "add_events from the frontend" - ) - ) + "add_events_from_string", + on_click=rx.call_script( + "reflex.addEvents([reflex.event(" + f"'{CallScriptState.get_full_name()}.set_reflex_result', " + "{value: 'addEvents from a script'})])" ), - id="add_events_from_frontend", - ), - rx.button( - "add_events_from_backend", - on_click=CallScriptState.add_events_from_backend, - id="add_events_from_backend", + id="add_events_from_string", ), rx.button( "ref_from_backend", @@ -621,11 +606,8 @@ def test_reflex_api(call_script_page: Page): call_script_page.locator("#ref_from_string").click() expect(result).to_have_value("from the ref") - call_script_page.locator("#add_events_from_frontend").click() - expect(result).to_have_value("add_events from the frontend") - - call_script_page.locator("#add_events_from_backend").click() - expect(result).to_have_value("add_events from the backend") + call_script_page.locator("#add_events_from_string").click() + expect(result).to_have_value("addEvents from a script") call_script_page.locator("#reflex_target").fill("typed, read by the backend") call_script_page.locator("#ref_from_backend").click() diff --git a/tests/units/reflex_base/test_js.py b/tests/units/reflex_base/test_js.py index bac869c86f3..5686f866d03 100644 --- a/tests/units/reflex_base/test_js.py +++ b/tests/units/reflex_base/test_js.py @@ -2,10 +2,8 @@ from typing import cast -import pytest from reflex_base import js from reflex_base.event import run_script -from reflex_base.utils.exceptions import EventFnArgMismatchError from reflex_base.utils.imports import ImportVar from reflex_base.vars.base import LiteralVar, Var, VarData @@ -15,40 +13,15 @@ class JsState(rx.State): - """A state whose handlers and vars the Vars are built with.""" + """A state whose var the Vars are built with.""" target: str = "search" - @rx.event - def save(self, value: int): - """Take an argument. - - Args: - value: The value. - """ - - @rx.event - def save_pair(self, first: int, second: int): - """Take two arguments. - - Args: - first: The first value. - second: The second value. - """ - - @rx.event - def reset_all(self): - """Take no arguments.""" - def test_rx_js_is_reflex_base_js(): """rx.js exposes exactly the public functions of reflex_base.js.""" - assert js.__all__ == ["add_events", "library", "ref"] - assert [getattr(rx.js, name) for name in js.__all__] == [ - js.add_events, - js.library, - js.ref, - ] + assert js.__all__ == ["library", "ref"] + assert [getattr(rx.js, name) for name in js.__all__] == [js.library, js.ref] def test_ref(): @@ -66,48 +39,6 @@ def test_ref(): ) -def test_add_events(): - """add_events compiles events, and handlers without arguments, to one dispatch.""" - name = JsState.get_full_name() - dispatch = js.add_events( - JsState.save(3), JsState.save_pair(1, 2), JsState.reset_all, rx.redirect("/x") - ) - assert str(dispatch) == ( - "(reflex.addEvents([" - f'(ReflexEvent("{name}.save", ({{ ["value"] : 3 }}), ({{ }}))), ' - f'(ReflexEvent("{name}.save_pair", ({{ ["first"] : 1, ["second"] : 2 }}), ({{ }}))), ' - f'(ReflexEvent("{name}.reset_all", ({{ }}), ({{ }}))), ' - '(ReflexEvent("_redirect", ({ ["path"] : "/x", ["external"] : false, ' - '["popup"] : false, ["replace"] : false }), ({ })))' - "]))" - ) - assert dispatch._get_all_var_data() == REFLEX_VAR_DATA - assert str(js.add_events()) == "(reflex.addEvents([]))" - - -@pytest.mark.parametrize( - ("event", "name"), - [ - (JsState.save, "JsState.save"), - (JsState.save_pair(1), "JsState.save_pair"), - ], -) -def test_add_events_rejects_a_handler_missing_arguments(event, name: str): - """A handler still missing arguments fails when add_events is built. - - Args: - event: The handler or partial event. - name: The handler's qualified name. - """ - with pytest.raises(EventFnArgMismatchError) as error: - js.add_events(JsState.reset_all, event) - assert str(error.value) == ( - f"rx.js.add_events cannot dispatch {name}: the handler needs arguments, " - "and add_events has none to pass it. Pass them where you add it, as in " - f"rx.js.add_events({name}(...))." - ) - - def test_library(): """library() calls reflex.library.""" react = js.library("react") From f2e95f364937574a30f64b736b8053df8881b67e Mon Sep 17 00:00:00 2001 From: Farhan Date: Tue, 24 Nov 2026 19:18:27 +0500 Subject: [PATCH 10/15] Drop reflex.library and rx.js.library, which nothing needs A JavaScript module imports npm packages directly, and no app or Reflex code calls reflex.library. Point focus, blur, set and scroll at the events that already do them, and say that a script's reflex and env hide page globals of those names. --- docs/api-reference/browser_javascript.md | 46 +++------------ news/+reflex-js.feature.md | 2 +- .../reflex-base/news/+reflex-js.feature.md | 2 +- packages/reflex-base/src/reflex_base/js.py | 14 +---- packages/reflex-frontend/src/utils/reflex.js | 32 ---------- packages/reflex-frontend/tests/reflex.test.js | 59 +------------------ .../tests_playwright/test_call_script.py | 20 +------ tests/units/reflex_base/test_js.py | 11 +--- 8 files changed, 17 insertions(+), 169 deletions(-) diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index fe72e54409b..bf08db81fc5 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -151,12 +151,15 @@ whose members stay the same across Reflex versions: | `reflex.ref(id)` | The ref of the component with that `id`. `undefined` until a component with that `id` renders; its `current` is `null` until React attaches the element, then the element. | | `reflex.addEvents(events)` | Dispatch events, as an event trigger does. | | `reflex.event(name, payload)` | Build an event for `reflex.addEvents`: `name` is the event handler's full name, `payload` its arguments by name. | -| `reflex.library(name)` | A promise of an npm library bundled for dynamic components, such as `"react"`. | Prefer `reflex` over the other names a script can see, such as `refs`, `ReflexEvent` or `addEvents`: those are internals of the frontend and may change between Reflex versions. +In a script, `reflex` and `env` (the app's config, which `rx.get_upload_url` +reads) name these values, so a global of the same name on your page is +reachable only as `window.reflex` or `window.env`. + ### From a Script Code run by `rx.call_script` sees `reflex`: @@ -174,12 +177,6 @@ def reflex_api_demo(): return rx.vstack( rx.input(id="reflex_api_search", placeholder="Type something"), rx.hstack( - rx.button( - "Focus", - on_click=rx.call_script( - "reflex.ref('reflex_api_search').current.focus()" - ), - ), rx.button( "Read", on_click=rx.call_script( @@ -187,18 +184,15 @@ def reflex_api_demo(): callback=ReflexApiState.set_result, ), ), - rx.button( - "React version", - on_click=rx.call_script( - "reflex.library('react').then((react) => react.version)", - callback=ReflexApiState.set_result, - ), - ), ), rx.text(f"Result: {ReflexApiState.result}"), ) ``` +To focus, blur, set or scroll to a component, use the events that already do +it: `rx.set_focus(id)`, `rx.blur_focus(id)`, `rx.set_value(id, value)` and +`rx.scroll_to(id)`. + ### From a JavaScript Module A JavaScript module, such as one a [wrapped component](/docs/wrapping-react/overview/) @@ -215,15 +209,10 @@ export function saveSearch(handlerName) { ### From Python -`rx.js` builds the same calls from Python. Each function returns a var, which +`rx.js.ref(id)` builds `reflex.ref(id)` from Python. It returns a var, which `rx.run_script` runs whether an event trigger uses it or an event handler returns it: -| Python | JavaScript | -| --- | --- | -| `rx.js.ref(id)` | `reflex.ref(id)` | -| `rx.js.library(name)` | `reflex.library(name)` | - ```python class SearchState(rx.State): query: str = "" @@ -252,23 +241,6 @@ Python has no `reflex.addEvents`: dispatch events from Python as usual, with an event trigger or by returning them from an event handler. `reflex.addEvents` is for JavaScript that sends a value it computed back to Python. -### Errors - -Each error says what went wrong and how to fix it. The messages, with example -names: - -```text -reflex.library("left-pad") cannot load "left-pad": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("left-pad") from reflex.components.dynamic in your app's Python code. -``` - -```text -reflex.library("react") cannot load "react" yet: the app registers its bundled libraries when it first mounts, and it has not mounted. Call reflex.library from an event, such as on_mount or on_click, rather than while a module loads. -``` - -```text -reflex.library("$/utils/state") cannot load "$/utils/state": a name starting with "$/" is a module of the app's frontend, not a bundled npm library. Use reflex.ref, reflex.addEvents and reflex.event instead of Reflex internals, and import your own modules from a JavaScript module. -``` - ## Using React Hooks To use React Hooks directly in a Reflex app, you must subclass `rx.Component`, diff --git a/news/+reflex-js.feature.md b/news/+reflex-js.feature.md index 56c10e26c42..e450e4fa248 100644 --- a/news/+reflex-js.feature.md +++ b/news/+reflex-js.feature.md @@ -1 +1 @@ -Add `rx.js.ref(id)` and `rx.js.library(name)`, vars that call the browser's `reflex` API from Python and work both in an event trigger and returned from an event handler, e.g. `rx.run_script(rx.js.ref("search").current.value, callback=State.set_query)`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). +Add `rx.js.ref(id)`, a var that reads a component's ref through the browser's `reflex` API from Python, e.g. `rx.run_script(rx.js.ref("search").current.value, callback=State.set_query)`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). diff --git a/packages/reflex-base/news/+reflex-js.feature.md b/packages/reflex-base/news/+reflex-js.feature.md index f43c8778cbd..b8eb0601251 100644 --- a/packages/reflex-base/news/+reflex-js.feature.md +++ b/packages/reflex-base/news/+reflex-js.feature.md @@ -1 +1 @@ -Add `reflex`, the API browser JavaScript reaches Reflex through: `rx.call_script` code, and JavaScript modules through `import { reflex } from "$/utils/reflex"`, can call `reflex.ref(id)`, `reflex.addEvents(events)`, `reflex.event(name, payload)` and `reflex.library(name)` instead of frontend internals, e.g. `rx.call_script("reflex.ref('search').current.focus()")`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). +Add `reflex`, the API browser JavaScript reaches Reflex through: `rx.call_script` code, and JavaScript modules through `import { reflex } from "$/utils/reflex"`, can call `reflex.ref(id)`, `reflex.addEvents(events)` and `reflex.event(name, payload)` instead of frontend internals, e.g. `rx.call_script("reflex.ref('search').current.value", callback=State.set_query)`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript). diff --git a/packages/reflex-base/src/reflex_base/js.py b/packages/reflex-base/src/reflex_base/js.py index 526a6fc3271..c6d0876e337 100644 --- a/packages/reflex-base/src/reflex_base/js.py +++ b/packages/reflex-base/src/reflex_base/js.py @@ -17,7 +17,7 @@ from reflex_base.vars.function import FunctionVar from reflex_base.vars.object import ObjectVar -__all__ = ["library", "ref"] +__all__ = ["ref"] _REFLEX_VAR_DATA = VarData( imports={f"$/{Dirs.REFLEX_API_PATH}": [ImportVar(tag="reflex")]} @@ -52,15 +52,3 @@ def ref(id: str | Var[str]) -> ObjectVar[Mapping[str, Mapping[str, Any]]]: component with that id has mounted. """ return _call("ref", id).to(ObjectVar, Mapping[str, Mapping[str, Any]]) - - -def library(name: str | Var[str]) -> Var: - """Get an npm library bundled for dynamic components. - - Args: - name: The library's import name, e.g. ``"react"``. - - Returns: - A promise of the library's module namespace. - """ - return _call("library", name) diff --git a/packages/reflex-frontend/src/utils/reflex.js b/packages/reflex-frontend/src/utils/reflex.js index ac0f72b6132..4fd3b16507d 100644 --- a/packages/reflex-frontend/src/utils/reflex.js +++ b/packages/reflex-frontend/src/utils/reflex.js @@ -41,36 +41,4 @@ export const reflex = Object.freeze({ * @returns {any} The event. */ event: (name, payload = {}) => ReflexEvent(name, payload), - - /** - * Get an npm library bundled for dynamic components, loading it first when - * the app loads optional libraries lazily. - * @param {string} name The library's import name, e.g. "react". - * @returns {Promise} The library's module namespace. - */ - library: async (name) => { - if (name.startsWith("$/")) { - throw new Error( - `reflex.library("${name}") cannot load "${name}": a name starting with "$/" is a module of the app's frontend, not a bundled npm library. Use reflex.ref, reflex.addEvents and reflex.event instead of Reflex internals, and import your own modules from a JavaScript module.`, - ); - } - await window.__reflex_load?.([name]); - // Without lazy loading, the app root registers the libraries in an effect. - if (window.__reflex === undefined) { - throw new Error( - `reflex.library("${name}") cannot load "${name}" yet: the app registers its bundled libraries when it first mounts, and it has not mounted. Call reflex.library from an event, such as on_mount or on_click, rather than while a module loads.`, - ); - } - // The registry is an object literal: `constructor` and the like are - // inherited, not bundled libraries. - const module = Object.hasOwn(window.__reflex, name) - ? window.__reflex[name] - : undefined; - if (module === undefined) { - throw new Error( - `reflex.library("${name}") cannot load "${name}": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("${name}") from reflex.components.dynamic in your app's Python code.`, - ); - } - return module; - }, }); diff --git a/packages/reflex-frontend/tests/reflex.test.js b/packages/reflex-frontend/tests/reflex.test.js index 046f675b599..5f524052af3 100644 --- a/packages/reflex-frontend/tests/reflex.test.js +++ b/packages/reflex-frontend/tests/reflex.test.js @@ -2,17 +2,12 @@ * `reflex` is the API scripts reach Reflex through. These pin each member and * that it reads the runtime at call time. */ -import { afterEach, expect, test, vi } from "vitest"; +import { expect, test, vi } from "vitest"; import { eventLoop } from "$/utils/context-registry"; import { reflex } from "$/utils/reflex"; import { refs } from "$/utils/state"; -afterEach(() => { - delete window.__reflex; - delete window.__reflex_load; -}); - test("ref finds a component by id, named as format_ref names it", () => { const cases = { search: "ref_search", @@ -50,59 +45,9 @@ test("event builds the event addEvents takes", () => { }); }); -test("library loads a lazy library first and returns its module", async () => { - const confetti = { default: () => "boom" }; - window.__reflex = { react: { version: "19" } }; - window.__reflex_load = vi.fn(async (names) => { - for (const name of names) { - window.__reflex[name] ??= confetti; - } - }); - await expect(reflex.library("canvas-confetti")).resolves.toBe(confetti); - expect(window.__reflex_load.mock.calls).toEqual([[["canvas-confetti"]]]); - await expect(reflex.library("react")).resolves.toEqual({ version: "19" }); -}); - -test("library rejects a module of the app's frontend", async () => { - window.__reflex = { "$/utils/state": {} }; - window.__reflex_load = vi.fn(); - await expect(reflex.library("$/utils/state")).rejects.toThrow( - new Error( - 'reflex.library("$/utils/state") cannot load "$/utils/state": a name starting with "$/" is a module of the app\'s frontend, not a bundled npm library. Use reflex.ref, reflex.addEvents and reflex.event instead of Reflex internals, and import your own modules from a JavaScript module.', - ), - ); - expect(window.__reflex_load.mock.calls).toEqual([]); -}); - -test("library called before the app registers its libraries says so", async () => { - await expect(reflex.library("react")).rejects.toThrow( - new Error( - 'reflex.library("react") cannot load "react" yet: the app registers its bundled libraries when it first mounts, and it has not mounted. Call reflex.library from an event, such as on_mount or on_click, rather than while a module loads.', - ), - ); -}); - -test("library rejects a library the app does not bundle", async () => { - window.__reflex = {}; - await expect(reflex.library("left-pad")).rejects.toThrow( - new Error( - 'reflex.library("left-pad") cannot load "left-pad": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("left-pad") from reflex.components.dynamic in your app\'s Python code.', - ), - ); -}); - -test("library rejects a name the registry only inherits", async () => { - window.__reflex = {}; - await expect(reflex.library("constructor")).rejects.toThrow( - new Error( - 'reflex.library("constructor") cannot load "constructor": the app does not bundle it for dynamic components. Bundle it by calling bundle_library("constructor") from reflex.components.dynamic in your app\'s Python code.', - ), - ); -}); - test("is frozen, so a script cannot replace a member for everyone", () => { expect(Object.isFrozen(reflex)).toBe(true); - expect(Object.keys(reflex)).toEqual(["ref", "addEvents", "event", "library"]); + expect(Object.keys(reflex)).toEqual(["ref", "addEvents", "event"]); }); test("loads first, before utils/state, despite the import cycle", async () => { diff --git a/tests/integration/tests_playwright/test_call_script.py b/tests/integration/tests_playwright/test_call_script.py index 7cd26b183e3..bbc9a62b58f 100644 --- a/tests/integration/tests_playwright/test_call_script.py +++ b/tests/integration/tests_playwright/test_call_script.py @@ -46,7 +46,6 @@ class CallScriptState(rx.State): value: str = "Initial" last_result: rx.Field[int] = rx.field(0) reflex_result: str = "" - mounted_library: str = "" @rx.event def call_script_callback(self, result): @@ -202,10 +201,6 @@ def set_value(self, value: str): def set_reflex_result(self, value: str): self.reflex_result = value - @rx.event - def set_mounted_library(self, value: str): - self.mounted_library = value - @rx.event def ref_from_backend(self): return rx.run_script( @@ -378,22 +373,10 @@ def index(): ), id="call_with_var_str_cast_wrapped_inline", ), - rx.input( - id="reflex_target", - default_value="from the ref", - on_mount=rx.call_script( - "reflex.library('react').then((react) => typeof react.useState)", - callback=CallScriptState.set_mounted_library, - ), - ), + rx.input(id="reflex_target", default_value="from the ref"), rx.input( value=CallScriptState.reflex_result, id="reflex_result", read_only=True ), - rx.input( - value=CallScriptState.mounted_library, - id="mounted_library", - read_only=True, - ), rx.button( "ref_from_string", on_click=rx.call_script( @@ -601,7 +584,6 @@ def test_reflex_api(call_script_page: Page): call_script_page: Playwright page. """ result = call_script_page.locator("#reflex_result") - expect(call_script_page.locator("#mounted_library")).to_have_value("function") call_script_page.locator("#ref_from_string").click() expect(result).to_have_value("from the ref") diff --git a/tests/units/reflex_base/test_js.py b/tests/units/reflex_base/test_js.py index 5686f866d03..2653e504bbb 100644 --- a/tests/units/reflex_base/test_js.py +++ b/tests/units/reflex_base/test_js.py @@ -20,8 +20,8 @@ class JsState(rx.State): def test_rx_js_is_reflex_base_js(): """rx.js exposes exactly the public functions of reflex_base.js.""" - assert js.__all__ == ["library", "ref"] - assert [getattr(rx.js, name) for name in js.__all__] == [js.library, js.ref] + assert js.__all__ == ["ref"] + assert rx.js.ref is js.ref def test_ref(): @@ -39,13 +39,6 @@ def test_ref(): ) -def test_library(): - """library() calls reflex.library.""" - react = js.library("react") - assert str(react) == '(reflex.library("react"))' - assert react._get_all_var_data() == REFLEX_VAR_DATA - - def test_run_script_carries_the_import_into_the_page(): """A script built on reflex carries the reflex import into the page that uses it.""" literal = LiteralVar.create(run_script(js.ref("search"))) From c4c7a5ecab1cb2bc6f561d1344edc5d2c30311db Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 26 Nov 2026 20:56:09 +0000 Subject: [PATCH 11/15] docs: show how to get an event handler's full name for reflex.event reflex.event(name, payload) needs the handler's full name, which encodes the state's module and class. The docs now build it in Python with f"{State.get_full_name()}.handler_name" and pass it into the JavaScript, in both the rx.call_script demo and a local component example, instead of leaving readers to hardcode the mangled naming scheme. The unit test uses a name of the real shape rather than "state.my_state.save". Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- docs/api-reference/browser_javascript.md | 58 +++++++++++++++++-- packages/reflex-frontend/src/utils/reflex.js | 3 +- packages/reflex-frontend/tests/reflex.test.js | 11 ++-- 3 files changed, 61 insertions(+), 11 deletions(-) diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index bf08db81fc5..bea5c598690 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -152,6 +152,11 @@ whose members stay the same across Reflex versions: | `reflex.addEvents(events)` | Dispatch events, as an event trigger does. | | `reflex.event(name, payload)` | Build an event for `reflex.addEvents`: `name` is the event handler's full name, `payload` its arguments by name. | +An event handler's full name encodes the module and class of its state, and how +it does may change between Reflex versions, so never write one out by hand. +Build it in Python, as `f"{State.get_full_name()}.handler_name"`, and pass it +into the JavaScript. + Prefer `reflex` over the other names a script can see, such as `refs`, `ReflexEvent` or `addEvents`: those are internals of the frontend and may change between Reflex versions. @@ -184,6 +189,14 @@ def reflex_api_demo(): callback=ReflexApiState.set_result, ), ), + rx.button( + "Send", + on_click=rx.call_script( + "reflex.addEvents([reflex.event(" + f"'{ReflexApiState.get_full_name()}.set_result', " + "{result: reflex.ref('reflex_api_search').current.value})])" + ), + ), ), rx.text(f"Result: {ReflexApiState.result}"), ) @@ -195,18 +208,53 @@ it: `rx.set_focus(id)`, `rx.blur_focus(id)`, `rx.set_value(id, value)` and ### From a JavaScript Module -A JavaScript module, such as one a [wrapped component](/docs/wrapping-react/overview/) -imports, imports `reflex` from `$/utils/reflex`: +A JavaScript module, such as a [local component](/docs/wrapping-react/local-packages/), +imports `reflex` from `$/utils/reflex`. This one sends the value of the input +with `id="search"` to the event handler named by its `handlerName` prop: ```javascript +// search_saver.jsx import { reflex } from "$/utils/reflex"; -export function saveSearch(handlerName) { - const value = reflex.ref("reflex_api_search").current.value; - reflex.addEvents([reflex.event(handlerName, { value })]); +export function SearchSaver({ handlerName }) { + const save = () => { + const value = reflex.ref("search").current.value; + reflex.addEvents([reflex.event(handlerName, { value })]); + }; + return ; } ``` +The Python side passes the handler's full name as that prop: + +```python +search_saver_path = rx.asset("./search_saver.jsx", shared=True) + + +class SearchSaver(rx.Component): + library = f"$/public{search_saver_path}" + tag = "SearchSaver" + + # The full name of the event handler to send the value to. + handler_name: rx.Var[str] + + +class SavedState(rx.State): + saved: str = "" + + @rx.event + def save(self, value: str): + self.saved = value + + +def saved_search(): + return rx.vstack( + rx.input(id="search"), + SearchSaver.create(handler_name=f"{SavedState.get_full_name()}.save"), + rx.text(SavedState.saved), + ) +``` + ### From Python `rx.js.ref(id)` builds `reflex.ref(id)` from Python. It returns a var, which diff --git a/packages/reflex-frontend/src/utils/reflex.js b/packages/reflex-frontend/src/utils/reflex.js index 4fd3b16507d..34fda621382 100644 --- a/packages/reflex-frontend/src/utils/reflex.js +++ b/packages/reflex-frontend/src/utils/reflex.js @@ -36,7 +36,8 @@ export const reflex = Object.freeze({ /** * Build an event for `addEvents`. - * @param {string} name The full name of the event handler. + * @param {string} name The full name of the event handler, built in Python + * as `f"{State.get_full_name()}.handler_name"` and passed in. * @param {object} [payload] The handler's arguments, by name. * @returns {any} The event. */ diff --git a/packages/reflex-frontend/tests/reflex.test.js b/packages/reflex-frontend/tests/reflex.test.js index 5f524052af3..e058d822779 100644 --- a/packages/reflex-frontend/tests/reflex.test.js +++ b/packages/reflex-frontend/tests/reflex.test.js @@ -36,13 +36,14 @@ test("addEvents dispatches through the event loop mounted at call time", () => { }); test("event builds the event addEvents takes", () => { - expect(reflex.event("state.my_state.save", { value: 3 })).toEqual({ - name: "state.my_state.save", + // A script gets the name from Python, here as + // f"{SearchState.get_full_name()}.save" builds it for a state in __main__. + const save = "reflex___state____state.__main______search_state.save"; + expect(reflex.event(save, { value: 3 })).toEqual({ + name: save, payload: { value: 3 }, }); - expect(reflex.event("state.my_state.reset")).toEqual({ - name: "state.my_state.reset", - }); + expect(reflex.event(save)).toEqual({ name: save }); }); test("is frozen, so a script cannot replace a member for everyone", () => { From e77106295413d92c3b961cf5a2ddec49cf181e7e Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 26 Nov 2026 20:56:10 +0000 Subject: [PATCH 12/15] docs: note reflex.ref is undefined for a component with a Var id Component.get_ref() returns None when a component's id is a Var, so no ref is registered and reflex.ref (and rx.js.ref) never finds it. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- docs/api-reference/browser_javascript.md | 2 +- packages/reflex-base/src/reflex_base/js.py | 3 ++- packages/reflex-frontend/src/utils/reflex.js | 5 +++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index bea5c598690..27ecae5d541 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -148,7 +148,7 @@ whose members stay the same across Reflex versions: | Member | What it does | | --- | --- | -| `reflex.ref(id)` | The ref of the component with that `id`. `undefined` until a component with that `id` renders; its `current` is `null` until React attaches the element, then the element. | +| `reflex.ref(id)` | The ref of the component with that `id`. `undefined` until a component with that `id` renders, and always for a component whose `id` is a var, which registers no ref; its `current` is `null` until React attaches the element, then the element. | | `reflex.addEvents(events)` | Dispatch events, as an event trigger does. | | `reflex.event(name, payload)` | Build an event for `reflex.addEvents`: `name` is the event handler's full name, `payload` its arguments by name. | diff --git a/packages/reflex-base/src/reflex_base/js.py b/packages/reflex-base/src/reflex_base/js.py index c6d0876e337..094d86f0235 100644 --- a/packages/reflex-base/src/reflex_base/js.py +++ b/packages/reflex-base/src/reflex_base/js.py @@ -49,6 +49,7 @@ def ref(id: str | Var[str]) -> ObjectVar[Mapping[str, Mapping[str, Any]]]: Returns: The ref, whose ``current`` is the mounted element, or undefined if no - component with that id has mounted. + component with that id has mounted or the component's id is a Var, + which registers no ref. """ return _call("ref", id).to(ObjectVar, Mapping[str, Mapping[str, Any]]) diff --git a/packages/reflex-frontend/src/utils/reflex.js b/packages/reflex-frontend/src/utils/reflex.js index 34fda621382..85b2e24b3bc 100644 --- a/packages/reflex-frontend/src/utils/reflex.js +++ b/packages/reflex-frontend/src/utils/reflex.js @@ -21,8 +21,9 @@ export const reflex = Object.freeze({ * Get the ref of a component by its id. * @param {string} id The component id. * @returns {{current: any} | undefined} The ref, or undefined if no - * component with that id has rendered. Its `current` is null until React - * attaches the element. + * component with that id has rendered or the component's id is a Var, + * which registers no ref. Its `current` is null until React attaches the + * element. */ ref: (id) => refs[refName(id)], From 46b44621a53c9f6b24c13992d357d372ff418a7d Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 26 Nov 2026 20:56:10 +0000 Subject: [PATCH 13/15] Restore eventLoop.addEvents after reflex tests; list js last in _SUBMODULES reflex.test.js replaced eventLoop.addEvents without putting it back, so the stub leaked into later tests in the file. "js" now joins the end of reflex's _SUBMODULES, as other late additions did, instead of sitting between "vars" and "config". Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- packages/reflex-frontend/tests/reflex.test.js | 8 +++++++- reflex/__init__.py | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/reflex-frontend/tests/reflex.test.js b/packages/reflex-frontend/tests/reflex.test.js index e058d822779..0f351bbb586 100644 --- a/packages/reflex-frontend/tests/reflex.test.js +++ b/packages/reflex-frontend/tests/reflex.test.js @@ -2,12 +2,18 @@ * `reflex` is the API scripts reach Reflex through. These pin each member and * that it reads the runtime at call time. */ -import { expect, test, vi } from "vitest"; +import { afterEach, expect, test, vi } from "vitest"; import { eventLoop } from "$/utils/context-registry"; import { reflex } from "$/utils/reflex"; import { refs } from "$/utils/state"; +const unmountedAddEvents = eventLoop.addEvents; + +afterEach(() => { + eventLoop.addEvents = unmountedAddEvents; +}); + test("ref finds a component by id, named as format_ref names it", () => { const cases = { search: "ref_search", diff --git a/reflex/__init__.py b/reflex/__init__.py index 035dda21e53..c0cdabf7a45 100644 --- a/reflex/__init__.py +++ b/reflex/__init__.py @@ -242,10 +242,10 @@ "testing", "utils", "vars", - "js", "config", "compiler", "plugins", + "js", } _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = _MAPPING _EXTRA_MAPPINGS: dict[str, str] = _COMPONENT_NAME_TO_PATH From c35664358059e28ade29040e90fdbb620175edd9 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 26 Nov 2026 20:58:58 +0000 Subject: [PATCH 14/15] docs: fix the wording of the handler full name warning Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- docs/api-reference/browser_javascript.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index 27ecae5d541..101170b0857 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -152,8 +152,8 @@ whose members stay the same across Reflex versions: | `reflex.addEvents(events)` | Dispatch events, as an event trigger does. | | `reflex.event(name, payload)` | Build an event for `reflex.addEvents`: `name` is the event handler's full name, `payload` its arguments by name. | -An event handler's full name encodes the module and class of its state, and how -it does may change between Reflex versions, so never write one out by hand. +An event handler's full name encodes the module and class of its state, and its +format may change between Reflex versions, so never write one out by hand. Build it in Python, as `f"{State.get_full_name()}.handler_name"`, and pass it into the JavaScript. From 348213733f238632dc729dc3d49b86e72ac2a24c Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 26 Nov 2026 21:01:42 +0000 Subject: [PATCH 15/15] docs: import the local component example by its importable path Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf --- docs/api-reference/browser_javascript.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index 101170b0857..2c802f8afc1 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -232,7 +232,7 @@ search_saver_path = rx.asset("./search_saver.jsx", shared=True) class SearchSaver(rx.Component): - library = f"$/public{search_saver_path}" + library = search_saver_path.importable_path tag = "SearchSaver" # The full name of the event handler to send the value to.