Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions docs/api-reference/browser_javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,139 @@ 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 as the rest of the frontend changes:

| 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.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.

### 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}"),
)
```

### 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(self):
self.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.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`.

### 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

To use React Hooks directly in a Reflex app, you must subclass `rx.Component`,
Expand Down
1 change: 1 addition & 0 deletions news/+reflex-js.feature.md
Original file line number Diff line number Diff line change
@@ -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).
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions packages/reflex-base/news/+reflex-js.feature.md
Original file line number Diff line number Diff line change
@@ -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).
2 changes: 2 additions & 0 deletions packages/reflex-base/src/reflex_base/constants/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
115 changes: 115 additions & 0 deletions packages/reflex-base/src/reflex_base/js.py
Original file line number Diff line number Diff line change
@@ -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)
10 changes: 6 additions & 4 deletions packages/reflex-frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
71 changes: 71 additions & 0 deletions packages/reflex-frontend/src/utils/reflex.js
Original file line number Diff line number Diff line change
@@ -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({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Dependent apps cannot build

PRs #7950 and #7951 still write a page_script.js that imports env from $/utils/script_env and calls env.addEvents. This rename removes that module, so their test app cannot bundle.

Both PRs also retain environment.py, which reads the removed Dirs.SCRIPT_ENV_PATH and builds calls to __reflexEnv, which runScript no longer provides. Update those dependent callers and exports to the new API before merging the stack.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. #7950 and #7951 are being rebased onto this change now: page_script.js will import { reflex } from $/utils/reflex, and environment.py, Dirs.SCRIPT_ENV_PATH and __reflexEnv are being removed from them. I'll resolve this thread once both PRs are pushed with the new API.


Generated by Claude Code

/**
* 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<any>} 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;
},
});
Loading
Loading