diff --git a/docs/api-reference/browser_javascript.md b/docs/api-reference/browser_javascript.md index daa87f3c907..2c802f8afc1 100644 --- a/docs/api-reference/browser_javascript.md +++ b/docs/api-reference/browser_javascript.md @@ -141,6 +141,154 @@ The `callback` parameter may be an `EventHandler` with one argument, or a lambda 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 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, 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. | + +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. + +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`: + +```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( + "Read", + on_click=rx.call_script( + "reflex.ref('reflex_api_search').current.value", + 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}"), + ) +``` + +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 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 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 = search_saver_path.importable_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 +`rx.run_script` runs whether an event trigger uses it or an event handler +returns it: + +```python +class SearchState(rx.State): + query: str = "" + + @rx.event + def set_query(self, query: str): + self.query = query + + @rx.event + 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.text(SearchState.query), + ) +``` + +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. + ## 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 new file mode 100644 index 00000000000..e450e4fa248 --- /dev/null +++ b/news/+reflex-js.feature.md @@ -0,0 +1 @@ +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/+eval-minified-shared-chunk.performance.md b/packages/reflex-base/news/+eval-minified-shared-chunk.performance.md index 50aaf67b1cd..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` 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), `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-base/news/+reflex-js.feature.md b/packages/reflex-base/news/+reflex-js.feature.md new file mode 100644 index 00000000000..b8eb0601251 --- /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)` 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/constants/base.py b/packages/reflex-base/src/reflex_base/constants/base.py index 5add4115098..272b2a5cb98 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 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..094d86f0235 --- /dev/null +++ b/packages/reflex-base/src/reflex_base/js.py @@ -0,0 +1,55 @@ +"""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 + +from reflex_base.constants.base import Dirs +from reflex_base.utils.imports import ImportVar +from reflex_base.vars.base import Var, VarData +from reflex_base.vars.function import FunctionVar +from reflex_base.vars.object import ObjectVar + +__all__ = ["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 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 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/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..85b2e24b3bc --- /dev/null +++ b/packages/reflex-frontend/src/utils/reflex.js @@ -0,0 +1,46 @@ +// `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 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)], + + /** + * 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, 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. + */ + event: (name, payload = {}) => ReflexEvent(name, payload), +}); diff --git a/packages/reflex-frontend/src/utils/state.js b/packages/reflex-frontend/src/utils/state.js index afce90ccda9..cf1fe6b60a1 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 { reflex } from "$/utils/reflex"; import { CLIENT_STATE_REF, getClientState, @@ -584,11 +585,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 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 @@ -610,6 +614,8 @@ const runScript = (code, addEvents, socket, navigate, params) => { "navigate", "params", "token", + "env", + "reflex", "code", '"use strict"; return eval(code);', ); @@ -620,6 +626,8 @@ const runScript = (code, addEvents, socket, navigate, params) => { navigate, params, token, + env, + reflex, code, ); }; diff --git a/packages/reflex-frontend/tests/public_api.test.js b/packages/reflex-frontend/tests/public_api.test.js index 64c4e883575..7955cbe1252 100644 --- a/packages/reflex-frontend/tests/public_api.test.js +++ b/packages/reflex-frontend/tests/public_api.test.js @@ -85,6 +85,7 @@ const PUBLIC_API = { "useStateContext", ], "$/utils/react-theme": ["ThemeProvider", "useTheme"], + "$/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..0f351bbb586 --- /dev/null +++ b/packages/reflex-frontend/tests/reflex.test.js @@ -0,0 +1,66 @@ +/** + * `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"; + +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", + "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", () => { + // 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(save)).toEqual({ name: save }); +}); + +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"]); +}); + +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 407ceafebe9..6b8c51d4864 100644 --- a/packages/reflex-frontend/tests/run_script.test.js +++ b/packages/reflex-frontend/tests/run_script.test.js @@ -8,6 +8,7 @@ import { describe, expect, test, vi } from "vitest"; import { getClientState } from "$/utils/client_state"; import { eventLoop } from "$/utils/context-registry"; +import { reflex } from "$/utils/reflex"; import { applyEvent, getToken } from "$/utils/state"; const callScript = (code, callback, socket = null) => @@ -64,6 +65,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/pyi_hashes.json b/pyi_hashes.json index fec0b8f2474..1d9667fc003 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": "b195e3845260389ced026d2f5c4adb93", - "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..c0cdabf7a45 100644 --- a/reflex/__init__.py +++ b/reflex/__init__.py @@ -245,6 +245,7 @@ "config", "compiler", "plugins", + "js", } _SUBMOD_ATTRS: lazy_loader.SubmodAttrsType = _MAPPING _EXTRA_MAPPINGS: dict[str, str] = _COMPONENT_NAME_TO_PATH diff --git a/reflex/js.py b/reflex/js.py new file mode 100644 index 00000000000..05ac215bf88 --- /dev/null +++ b/reflex/js.py @@ -0,0 +1,4 @@ +# pyright: reportWildcardImportFromLibrary=false +"""Build calls on ``reflex``, the API browser code reaches Reflex through.""" + +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 56ae7a1a3ce..c215e519662 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 from tests.integration.utils import CLIENT_TOKEN_JS @@ -45,6 +46,7 @@ class CallScriptState(rx.State): external_counter: rx.Field[int] = rx.field(0) value: str = "Initial" last_result: rx.Field[int] = rx.field(0) + reflex_result: str = "" @rx.event def call_script_callback(self, result): @@ -196,6 +198,23 @@ def set_last_result(self, value: str): def set_value(self, value: str): self.value = value + @rx.event + def set_reflex_result(self, value: str): + self.reflex_result = value + + @rx.event + def ref_from_backend(self): + return rx.run_script( + 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 def reset_(self): yield rx.call_script("inline_counter = 0; external_counter = 0") @@ -355,6 +374,37 @@ def index(): ), id="call_with_var_str_cast_wrapped_inline", ), + rx.input(id="reflex_target", default_value="from the ref"), + rx.input( + value=CallScriptState.reflex_result, id="reflex_result", read_only=True + ), + rx.button( + "ref_from_string", + on_click=rx.call_script( + "reflex.ref('reflex_target').current.value", + callback=CallScriptState.set_reflex_result, + ), + id="ref_from_string", + ), + rx.button( + "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_string", + ), + 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", + ), ) @@ -526,3 +576,26 @@ 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_reflex_api(call_script_page: Page): + """Scripts reach Reflex through `reflex`, from strings and from `rx.js`. + + Args: + call_script_page: Playwright page. + """ + result = call_script_page.locator("#reflex_result") + + call_script_page.locator("#ref_from_string").click() + expect(result).to_have_value("from the ref") + + 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() + expect(result).to_have_value("typed, read by the 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") diff --git a/tests/units/compiler/state_js.test.mjs b/tests/units/compiler/state_js.test.mjs index 2b4fdd40757..5a1ba8ad2af 100644 --- a/tests/units/compiler/state_js.test.mjs +++ b/tests/units/compiler/state_js.test.mjs @@ -238,6 +238,7 @@ async function setup({ "$/utils/helpers/debounce": { default() {} }, "$/utils/helpers/throttle": { default() {} }, "$/utils/helpers/upload": { uploadFiles() {} }, + "$/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 a2970bfe6d7..b96afd972ca 100644 --- a/tests/units/reflex_base/client_event_queue_runtime.mjs +++ b/tests/units/reflex_base/client_event_queue_runtime.mjs @@ -76,6 +76,7 @@ export async function createQueueRuntime( "$/utils/helpers/upload": { uploadFiles: uploadFiles ?? unused, }, + "$/utils/reflex": { reflex: {} }, ...dependencyOverrides, }; // Let Node parse the unchanged module; only expose private state to tests. diff --git a/tests/units/reflex_base/test_js.py b/tests/units/reflex_base/test_js.py new file mode 100644 index 00000000000..2653e504bbb --- /dev/null +++ b/tests/units/reflex_base/test_js.py @@ -0,0 +1,49 @@ +"""Tests for the Vars that call ``reflex``, the API browser code reaches Reflex through.""" + +from typing import cast + +from reflex_base import js +from reflex_base.event import run_script +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 var the Vars are built with.""" + + target: str = "search" + + +def test_rx_js_is_reflex_base_js(): + """rx.js exposes exactly the public functions of reflex_base.js.""" + assert js.__all__ == ["ref"] + assert rx.js.ref is 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_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