Merge remote-tracking branch 'origin/main' into elijah/redirect-external-prop
This commit is contained in:
commit
9ed4ba2ead
19
.github/ISSUE_TEMPLATE/enhancement_request.md
vendored
Normal file
19
.github/ISSUE_TEMPLATE/enhancement_request.md
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
---
|
||||
name: Enhancement Request
|
||||
about: Suggest an enhancement for an existing Reflex feature.
|
||||
title: ''
|
||||
labels: 'enhancement'
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
**Describe the Enhancement you want**
|
||||
A clear and concise description of what the improvement does.
|
||||
|
||||
- Which feature do you want to improve? (and what problem does it have)
|
||||
|
||||
- What is the benefit of the enhancement?
|
||||
|
||||
- Show an example/usecase were the improvement are needed.
|
||||
|
||||
**Additional context**
|
||||
Add any other context here.
|
18
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
18
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@ -0,0 +1,18 @@
|
||||
---
|
||||
name: Feature Request
|
||||
about: Suggest a new feature for Reflex
|
||||
title: ''
|
||||
labels: 'feature request'
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the Features**
|
||||
A clear and concise description of what the features does.
|
||||
|
||||
- What is the purpose of the feature?
|
||||
|
||||
- Show an example / use cases for the new feature.
|
||||
|
||||
**Additional context**
|
||||
Add any other context here.
|
6
.github/workflows/benchmarks.yml
vendored
6
.github/workflows/benchmarks.yml
vendored
@ -80,7 +80,7 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Show OS combos first in GUI
|
||||
os: [ubuntu-latest, windows-latest, macos-12]
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
python-version: ['3.9.18', '3.10.13', '3.11.5', '3.12.0']
|
||||
exclude:
|
||||
- os: windows-latest
|
||||
@ -92,7 +92,7 @@ jobs:
|
||||
python-version: '3.9.18'
|
||||
- os: macos-latest
|
||||
python-version: '3.10.13'
|
||||
- os: macos-12
|
||||
- os: macos-latest
|
||||
python-version: '3.12.0'
|
||||
include:
|
||||
- os: windows-latest
|
||||
@ -155,7 +155,7 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Show OS combos first in GUI
|
||||
os: [ubuntu-latest, windows-latest, macos-12]
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
python-version: ['3.11.5']
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
@ -58,7 +58,7 @@ jobs:
|
||||
working-directory: ./reflex-web
|
||||
run: poetry run uv pip install -r requirements.txt
|
||||
- name: Install additional dependencies for DB access
|
||||
run: poetry run uv pip install psycopg2-binary
|
||||
run: poetry run uv pip install psycopg
|
||||
- name: Init Website for reflex-web
|
||||
working-directory: ./reflex-web
|
||||
run: poetry run reflex init
|
||||
|
@ -22,9 +22,9 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
state_manager: ["redis", "memory"]
|
||||
state_manager: ['redis', 'memory']
|
||||
python-version: ['3.11.5', '3.12.0', '3.13.0']
|
||||
split_index: [1, 2]
|
||||
python-version: ["3.11.5", "3.12.0"]
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-22.04
|
||||
services:
|
||||
|
39
.github/workflows/integration_tests.yml
vendored
39
.github/workflows/integration_tests.yml
vendored
@ -43,7 +43,7 @@ jobs:
|
||||
matrix:
|
||||
# Show OS combos first in GUI
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
python-version: ['3.9.18', '3.10.13', '3.11.5', '3.12.0']
|
||||
python-version: ['3.9.18', '3.10.13', '3.11.5', '3.12.0', '3.13.0']
|
||||
exclude:
|
||||
- os: windows-latest
|
||||
python-version: '3.10.13'
|
||||
@ -73,7 +73,7 @@ jobs:
|
||||
run: |
|
||||
poetry run uv pip install -r requirements.txt
|
||||
- name: Install additional dependencies for DB access
|
||||
run: poetry run uv pip install psycopg2-binary
|
||||
run: poetry run uv pip install psycopg
|
||||
- name: Check export --backend-only before init for counter example
|
||||
working-directory: ./reflex-examples/counter
|
||||
run: |
|
||||
@ -147,7 +147,7 @@ jobs:
|
||||
working-directory: ./reflex-web
|
||||
run: poetry run uv pip install $(grep -ivE "reflex " requirements.txt)
|
||||
- name: Install additional dependencies for DB access
|
||||
run: poetry run uv pip install psycopg2-binary
|
||||
run: poetry run uv pip install psycopg
|
||||
- name: Init Website for reflex-web
|
||||
working-directory: ./reflex-web
|
||||
run: poetry run reflex init
|
||||
@ -163,13 +163,42 @@ jobs:
|
||||
--pr-id "${{ github.event.pull_request.id }}" --branch-name "${{ github.head_ref || github.ref_name }}"
|
||||
--app-name "reflex-web" --path ./reflex-web/.web
|
||||
|
||||
rx-shout-from-template:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: ./.github/actions/setup_build_env
|
||||
with:
|
||||
python-version: '3.11.4'
|
||||
run-poetry-install: true
|
||||
create-venv-at-path: .venv
|
||||
- name: Create app directory
|
||||
run: mkdir rx-shout-from-template
|
||||
- name: Init reflex-web from template
|
||||
run: poetry run reflex init --template https://github.com/masenf/rx_shout
|
||||
working-directory: ./rx-shout-from-template
|
||||
- name: ignore reflex pin in requirements
|
||||
run: sed -i -e '/reflex==/d' requirements.txt
|
||||
working-directory: ./rx-shout-from-template
|
||||
- name: Install additional dependencies
|
||||
run: poetry run uv pip install -r requirements.txt
|
||||
working-directory: ./rx-shout-from-template
|
||||
- name: Run Website and Check for errors
|
||||
run: |
|
||||
# Check that npm is home
|
||||
npm -v
|
||||
poetry run bash scripts/integration.sh ./rx-shout-from-template prod
|
||||
|
||||
|
||||
reflex-web-macos:
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ['3.11.5', '3.12.0']
|
||||
runs-on: macos-12
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: ./.github/actions/setup_build_env
|
||||
@ -187,7 +216,7 @@ jobs:
|
||||
working-directory: ./reflex-web
|
||||
run: poetry run uv pip install -r requirements.txt
|
||||
- name: Install additional dependencies for DB access
|
||||
run: poetry run uv pip install psycopg2-binary
|
||||
run: poetry run uv pip install psycopg
|
||||
- name: Init Website for reflex-web
|
||||
working-directory: ./reflex-web
|
||||
run: poetry run reflex init
|
||||
|
7
.github/workflows/unit_tests.yml
vendored
7
.github/workflows/unit_tests.yml
vendored
@ -28,7 +28,7 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
python-version: ['3.9.18', '3.10.13', '3.11.5', '3.12.0']
|
||||
python-version: ['3.9.18', '3.10.13', '3.11.5', '3.12.0', '3.13.0']
|
||||
# Windows is a bit behind on Python version availability in Github
|
||||
exclude:
|
||||
- os: windows-latest
|
||||
@ -88,8 +88,9 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ['3.9.18', '3.10.13', '3.11.5', '3.12.0']
|
||||
runs-on: macos-12
|
||||
# Note: py39, py310 versions chosen due to available arm64 darwin builds.
|
||||
python-version: ['3.9.13', '3.10.11', '3.11.5', '3.12.0', '3.13.0']
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: ./.github/actions/setup_build_env
|
||||
|
@ -3,7 +3,7 @@ fail_fast: true
|
||||
repos:
|
||||
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.7.2
|
||||
rev: v0.8.2
|
||||
hooks:
|
||||
- id: ruff-format
|
||||
args: [reflex, tests]
|
||||
|
@ -23,7 +23,7 @@
|
||||
# for example, pass `docker build --platform=linux/amd64 ...`
|
||||
|
||||
# Stage 1: init
|
||||
FROM python:3.11 as init
|
||||
FROM python:3.13 as init
|
||||
|
||||
ARG uv=/root/.local/bin/uv
|
||||
|
||||
@ -48,11 +48,11 @@ RUN $uv pip install -r requirements.txt
|
||||
RUN reflex init
|
||||
|
||||
# Stage 2: copy artifacts into slim image
|
||||
FROM python:3.11-slim
|
||||
FROM python:3.13-slim
|
||||
WORKDIR /app
|
||||
RUN adduser --disabled-password --home /app reflex
|
||||
COPY --chown=reflex --from=init /app /app
|
||||
# Install libpq-dev for psycopg2 (skip if not using postgres).
|
||||
# Install libpq-dev for psycopg (skip if not using postgres).
|
||||
RUN apt-get update -y && apt-get install -y libpq-dev && rm -rf /var/lib/apt/lists/*
|
||||
USER reflex
|
||||
ENV PATH="/app/.venv/bin:$PATH" PYTHONUNBUFFERED=1
|
||||
|
@ -2,7 +2,7 @@
|
||||
# instance of a Reflex app.
|
||||
|
||||
# Stage 1: init
|
||||
FROM python:3.11 as init
|
||||
FROM python:3.13 as init
|
||||
|
||||
ARG uv=/root/.local/bin/uv
|
||||
|
||||
@ -35,11 +35,11 @@ RUN rm -rf .web && mkdir .web
|
||||
RUN mv /tmp/_static .web/_static
|
||||
|
||||
# Stage 2: copy artifacts into slim image
|
||||
FROM python:3.11-slim
|
||||
FROM python:3.13-slim
|
||||
WORKDIR /app
|
||||
RUN adduser --disabled-password --home /app reflex
|
||||
COPY --chown=reflex --from=init /app /app
|
||||
# Install libpq-dev for psycopg2 (skip if not using postgres).
|
||||
# Install libpq-dev for psycopg (skip if not using postgres).
|
||||
RUN apt-get update -y && apt-get install -y libpq-dev && rm -rf /var/lib/apt/lists/*
|
||||
USER reflex
|
||||
ENV PATH="/app/.venv/bin:$PATH" PYTHONUNBUFFERED=1
|
||||
|
@ -15,7 +15,7 @@ services:
|
||||
|
||||
app:
|
||||
environment:
|
||||
DB_URL: postgresql+psycopg2://postgres:secret@db/postgres
|
||||
DB_URL: postgresql+psycopg://postgres:secret@db/postgres
|
||||
REDIS_URL: redis://redis:6379
|
||||
depends_on:
|
||||
- db
|
||||
|
3
docker-example/production-one-port/.dockerignore
Normal file
3
docker-example/production-one-port/.dockerignore
Normal file
@ -0,0 +1,3 @@
|
||||
.web
|
||||
!.web/bun.lockb
|
||||
!.web/package.json
|
14
docker-example/production-one-port/Caddyfile
Normal file
14
docker-example/production-one-port/Caddyfile
Normal file
@ -0,0 +1,14 @@
|
||||
:{$PORT}
|
||||
|
||||
encode gzip
|
||||
|
||||
@backend_routes path /_event/* /ping /_upload /_upload/*
|
||||
handle @backend_routes {
|
||||
reverse_proxy localhost:8000
|
||||
}
|
||||
|
||||
root * /srv
|
||||
route {
|
||||
try_files {path} {path}/ /404.html
|
||||
file_server
|
||||
}
|
62
docker-example/production-one-port/Dockerfile
Normal file
62
docker-example/production-one-port/Dockerfile
Normal file
@ -0,0 +1,62 @@
|
||||
# This Dockerfile is used to deploy a single-container Reflex app instance
|
||||
# to services like Render, Railway, Heroku, GCP, and others.
|
||||
|
||||
# If the service expects a different port, provide it here (f.e Render expects port 10000)
|
||||
ARG PORT=8080
|
||||
# Only set for local/direct access. When TLS is used, the API_URL is assumed to be the same as the frontend.
|
||||
ARG API_URL
|
||||
|
||||
# It uses a reverse proxy to serve the frontend statically and proxy to backend
|
||||
# from a single exposed port, expecting TLS termination to be handled at the
|
||||
# edge by the given platform.
|
||||
FROM python:3.13 as builder
|
||||
|
||||
RUN mkdir -p /app/.web
|
||||
RUN python -m venv /app/.venv
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install python app requirements and reflex in the container
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
# Install reflex helper utilities like bun/fnm/node
|
||||
COPY rxconfig.py ./
|
||||
RUN reflex init
|
||||
|
||||
# Install pre-cached frontend dependencies (if exist)
|
||||
COPY *.web/bun.lockb *.web/package.json .web/
|
||||
RUN if [ -f .web/bun.lockb ]; then cd .web && ~/.local/share/reflex/bun/bin/bun install --frozen-lockfile; fi
|
||||
|
||||
# Copy local context to `/app` inside container (see .dockerignore)
|
||||
COPY . .
|
||||
|
||||
ARG PORT API_URL
|
||||
# Download other npm dependencies and compile frontend
|
||||
RUN API_URL=${API_URL:-http://localhost:$PORT} reflex export --loglevel debug --frontend-only --no-zip && mv .web/_static/* /srv/ && rm -rf .web
|
||||
|
||||
|
||||
# Final image with only necessary files
|
||||
FROM python:3.13-slim
|
||||
|
||||
# Install Caddy and redis server inside image
|
||||
RUN apt-get update -y && apt-get install -y caddy redis-server && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG PORT API_URL
|
||||
ENV PATH="/app/.venv/bin:$PATH" PORT=$PORT API_URL=${API_URL:-http://localhost:$PORT} REDIS_URL=redis://localhost PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app /app
|
||||
COPY --from=builder /srv /srv
|
||||
|
||||
# Needed until Reflex properly passes SIGTERM on backend.
|
||||
STOPSIGNAL SIGKILL
|
||||
|
||||
EXPOSE $PORT
|
||||
|
||||
# Apply migrations before starting the backend.
|
||||
CMD [ -d alembic ] && reflex db migrate; \
|
||||
caddy start && \
|
||||
redis-server --daemonize yes && \
|
||||
exec reflex run --env prod --backend-only
|
37
docker-example/production-one-port/README.md
Normal file
37
docker-example/production-one-port/README.md
Normal file
@ -0,0 +1,37 @@
|
||||
# production-one-port
|
||||
|
||||
This docker deployment runs Reflex in prod mode, exposing a single HTTP port:
|
||||
* `8080` (`$PORT`) - Caddy server hosting the frontend statically and proxying requests to the backend.
|
||||
|
||||
The deployment also runs a local Redis server to store state for each user.
|
||||
|
||||
Conceptually it is similar to the `simple-one-port` example except it:
|
||||
* has layer caching for python, reflex, and node dependencies
|
||||
* uses multi-stage build to reduce the size of the final image
|
||||
|
||||
Using this method may be preferable for deploying in memory constrained
|
||||
environments, because it serves a static frontend export, rather than running
|
||||
the NextJS server via node.
|
||||
|
||||
## Build
|
||||
|
||||
```console
|
||||
docker build -t reflex-production-one-port .
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```console
|
||||
docker run -p 8080:8080 reflex-production-one-port
|
||||
```
|
||||
|
||||
Note that this container has _no persistence_ and will lose all data when
|
||||
stopped. You can use bind mounts or named volumes to persist the database and
|
||||
uploaded_files directories as needed.
|
||||
|
||||
## Usage
|
||||
|
||||
This container should be used with an existing load balancer or reverse proxy to
|
||||
terminate TLS.
|
||||
|
||||
It is also useful for deploying to simple app platforms, such as Render or Heroku.
|
@ -4,7 +4,7 @@
|
||||
# It uses a reverse proxy to serve the frontend statically and proxy to backend
|
||||
# from a single exposed port, expecting TLS termination to be handled at the
|
||||
# edge by the given platform.
|
||||
FROM python:3.11
|
||||
FROM python:3.13
|
||||
|
||||
# If the service expects a different port, provide it here (f.e Render expects port 10000)
|
||||
ARG PORT=8080
|
||||
|
@ -1,5 +1,5 @@
|
||||
# This Dockerfile is used to deploy a simple single-container Reflex app instance.
|
||||
FROM python:3.12
|
||||
FROM python:3.13
|
||||
|
||||
RUN apt-get update && apt-get install -y redis-server && rm -rf /var/lib/apt/lists/*
|
||||
ENV REDIS_URL=redis://localhost PYTHONUNBUFFERED=1
|
||||
|
1054
poetry.lock
generated
1054
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "reflex"
|
||||
version = "0.6.6dev1"
|
||||
version = "0.6.7dev1"
|
||||
description = "Web apps in pure Python."
|
||||
license = "Apache-2.0"
|
||||
authors = [
|
||||
@ -49,16 +49,17 @@ wrapt = [
|
||||
{version = ">=1.11.0,<2.0", python = "<3.11"},
|
||||
]
|
||||
packaging = ">=23.1,<25.0"
|
||||
reflex-hosting-cli = ">=0.1.15,<2.0"
|
||||
reflex-hosting-cli = ">=0.1.29,<2.0"
|
||||
charset-normalizer = ">=3.3.2,<4.0"
|
||||
wheel = ">=0.42.0,<1.0"
|
||||
build = ">=1.0.3,<2.0"
|
||||
setuptools = ">=75.0"
|
||||
httpx = ">=0.25.1,<1.0"
|
||||
twine = ">=4.0.0,<6.0"
|
||||
twine = ">=4.0.0,<7.0"
|
||||
tomlkit = ">=0.12.4,<1.0"
|
||||
lazy_loader = ">=0.4"
|
||||
reflex-chakra = ">=0.6.0"
|
||||
typing_extensions = ">=4.6.0"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
pytest = ">=7.1.2,<9.0"
|
||||
@ -69,7 +70,7 @@ dill = ">=0.3.8"
|
||||
toml = ">=0.10.2,<1.0"
|
||||
pytest-asyncio = ">=0.24.0"
|
||||
pytest-cov = ">=4.0.0,<7.0"
|
||||
ruff = "0.7.2"
|
||||
ruff = "0.8.2"
|
||||
pandas = ">=2.1.1,<3.0"
|
||||
pillow = ">=10.0.0,<12.0"
|
||||
plotly = ">=5.13.0,<6.0"
|
||||
@ -92,8 +93,8 @@ build-backend = "poetry.core.masonry.api"
|
||||
[tool.ruff]
|
||||
target-version = "py39"
|
||||
lint.isort.split-on-trailing-comma = false
|
||||
lint.select = ["B", "D", "E", "F", "I", "SIM", "W"]
|
||||
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115"]
|
||||
lint.select = ["B", "D", "E", "F", "I", "SIM", "W", "RUF", "FURB", "ERA"]
|
||||
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"]
|
||||
lint.pydocstyle.convention = "google"
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
|
@ -40,9 +40,6 @@ let event_processing = false;
|
||||
// Array holding pending events to be processed.
|
||||
const event_queue = [];
|
||||
|
||||
// Pending upload promises, by id
|
||||
const upload_controllers = {};
|
||||
|
||||
/**
|
||||
* Generate a UUID (Used for session tokens).
|
||||
* Taken from: https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid
|
||||
@ -300,7 +297,7 @@ export const applyEvent = async (event, socket) => {
|
||||
if (socket) {
|
||||
socket.emit(
|
||||
"event",
|
||||
JSON.stringify(event, (k, v) => (v === undefined ? null : v))
|
||||
event,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@ -407,6 +404,8 @@ export const connect = async (
|
||||
transports: transports,
|
||||
autoUnref: false,
|
||||
});
|
||||
// Ensure undefined fields in events are sent as null instead of removed
|
||||
socket.current.io.encoder.replacer = (k, v) => (v === undefined ? null : v)
|
||||
|
||||
function checkVisibility() {
|
||||
if (document.visibilityState === "visible") {
|
||||
@ -443,8 +442,7 @@ export const connect = async (
|
||||
});
|
||||
|
||||
// On each received message, queue the updates and events.
|
||||
socket.current.on("event", async (message) => {
|
||||
const update = JSON5.parse(message);
|
||||
socket.current.on("event", async (update) => {
|
||||
for (const substate in update.delta) {
|
||||
dispatch[substate](update.delta[substate]);
|
||||
}
|
||||
@ -454,6 +452,10 @@ export const connect = async (
|
||||
queueEvents(update.events, socket);
|
||||
}
|
||||
});
|
||||
socket.current.on("reload", async (event) => {
|
||||
event_processing = false;
|
||||
queueEvents([...initialEvents(), event], socket);
|
||||
});
|
||||
|
||||
document.addEventListener("visibilitychange", checkVisibility);
|
||||
};
|
||||
@ -481,25 +483,42 @@ export const uploadFiles = async (
|
||||
return false;
|
||||
}
|
||||
|
||||
if (upload_controllers[upload_id]) {
|
||||
const upload_ref_name = `__upload_controllers_${upload_id}`
|
||||
|
||||
if (refs[upload_ref_name]) {
|
||||
console.log("Upload already in progress for ", upload_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Track how many partial updates have been processed for this upload.
|
||||
let resp_idx = 0;
|
||||
const eventHandler = (progressEvent) => {
|
||||
// handle any delta / event streamed from the upload event handler
|
||||
const event_callbacks = socket._callbacks.$event;
|
||||
// Whenever called, responseText will contain the entire response so far.
|
||||
const chunks = progressEvent.event.target.responseText.trim().split("\n");
|
||||
chunks.slice(resp_idx).map((chunk) => {
|
||||
// So only process _new_ chunks beyond resp_idx.
|
||||
chunks.slice(resp_idx).map((chunk_json) => {
|
||||
try {
|
||||
socket._callbacks.$event.map((f) => {
|
||||
f(chunk);
|
||||
});
|
||||
const chunk = JSON5.parse(chunk_json);
|
||||
event_callbacks.map((f, ix) => {
|
||||
f(chunk)
|
||||
.then(() => {
|
||||
if (ix === event_callbacks.length - 1) {
|
||||
// Mark this chunk as processed.
|
||||
resp_idx += 1;
|
||||
} catch (e) {
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (progressEvent.progress === 1) {
|
||||
// Chunk may be incomplete, so only report errors when full response is available.
|
||||
console.log("Error parsing chunk", chunk, e);
|
||||
console.log("Error processing chunk", chunk, e);
|
||||
}
|
||||
return;
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
if (progressEvent.progress === 1) {
|
||||
console.log("Error parsing chunk", chunk_json, e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@ -526,7 +545,7 @@ export const uploadFiles = async (
|
||||
});
|
||||
|
||||
// Send the file to the server.
|
||||
upload_controllers[upload_id] = controller;
|
||||
refs[upload_ref_name] = controller;
|
||||
|
||||
try {
|
||||
return await axios.post(getBackendURL(UPLOADURL), formdata, config);
|
||||
@ -546,7 +565,7 @@ export const uploadFiles = async (
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
delete upload_controllers[upload_id];
|
||||
delete refs[upload_ref_name];
|
||||
}
|
||||
};
|
||||
|
||||
@ -705,6 +724,11 @@ export const useEventLoop = (
|
||||
_e.stopPropagation();
|
||||
}
|
||||
const combined_name = events.map((e) => e.name).join("+++");
|
||||
if (event_actions?.temporal) {
|
||||
if (!socket.current || !socket.current.connected) {
|
||||
return; // don't queue when the backend is not connected
|
||||
}
|
||||
}
|
||||
if (event_actions?.throttle) {
|
||||
// If throttle returns false, the events are not added to the queue.
|
||||
if (!throttle(combined_name, event_actions.throttle)) {
|
||||
@ -762,7 +786,7 @@ export const useEventLoop = (
|
||||
window.onunhandledrejection = function (event) {
|
||||
addEvents([
|
||||
Event(`${exception_state_name}.handle_frontend_exception`, {
|
||||
stack: event.reason.stack,
|
||||
stack: event.reason?.stack,
|
||||
component_stack: "",
|
||||
}),
|
||||
]);
|
||||
@ -783,7 +807,7 @@ export const useEventLoop = (
|
||||
connect(
|
||||
socket,
|
||||
dispatch,
|
||||
["websocket", "polling"],
|
||||
["websocket"],
|
||||
setConnectErrors,
|
||||
client_storage
|
||||
);
|
||||
@ -837,11 +861,20 @@ export const useEventLoop = (
|
||||
}
|
||||
};
|
||||
const change_complete = () => addEvents(onLoadInternalEvent());
|
||||
const change_error = () => {
|
||||
// Remove cached error state from router for this page, otherwise the
|
||||
// page will never send on_load events again.
|
||||
if (router.components[router.pathname].error) {
|
||||
delete router.components[router.pathname].error;
|
||||
}
|
||||
};
|
||||
router.events.on("routeChangeStart", change_start);
|
||||
router.events.on("routeChangeComplete", change_complete);
|
||||
router.events.on("routeChangeError", change_error);
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", change_start);
|
||||
router.events.off("routeChangeComplete", change_complete);
|
||||
router.events.off("routeChangeError", change_error);
|
||||
};
|
||||
}, [router]);
|
||||
|
||||
|
@ -264,6 +264,7 @@ _MAPPING: dict = {
|
||||
"experimental": ["_x"],
|
||||
"admin": ["AdminDash"],
|
||||
"app": ["App", "UploadFile"],
|
||||
"assets": ["asset"],
|
||||
"base": ["Base"],
|
||||
"components.component": [
|
||||
"Component",
|
||||
@ -330,7 +331,7 @@ _MAPPING: dict = {
|
||||
"SessionStorage",
|
||||
],
|
||||
"middleware": ["middleware", "Middleware"],
|
||||
"model": ["session", "Model"],
|
||||
"model": ["asession", "session", "Model"],
|
||||
"state": [
|
||||
"var",
|
||||
"ComponentState",
|
||||
|
@ -19,6 +19,7 @@ from . import vars as vars
|
||||
from .admin import AdminDash as AdminDash
|
||||
from .app import App as App
|
||||
from .app import UploadFile as UploadFile
|
||||
from .assets import asset as asset
|
||||
from .base import Base as Base
|
||||
from .components import el as el
|
||||
from .components import lucide as lucide
|
||||
@ -185,6 +186,7 @@ from .istate.wrappers import get_state as get_state
|
||||
from .middleware import Middleware as Middleware
|
||||
from .middleware import middleware as middleware
|
||||
from .model import Model as Model
|
||||
from .model import asession as asession
|
||||
from .model import session as session
|
||||
from .page import page as page
|
||||
from .state import ComponentState as ComponentState
|
||||
|
@ -17,6 +17,7 @@ import sys
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
@ -73,6 +74,7 @@ from reflex.event import (
|
||||
EventSpec,
|
||||
EventType,
|
||||
IndividualEventType,
|
||||
get_hydrate_event,
|
||||
window_alert,
|
||||
)
|
||||
from reflex.model import Model, get_db_status
|
||||
@ -362,6 +364,11 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
max_http_buffer_size=constants.POLLING_MAX_HTTP_BUFFER_SIZE,
|
||||
ping_interval=constants.Ping.INTERVAL,
|
||||
ping_timeout=constants.Ping.TIMEOUT,
|
||||
json=SimpleNamespace(
|
||||
dumps=staticmethod(format.json_dumps),
|
||||
loads=staticmethod(json.loads),
|
||||
),
|
||||
transports=["websocket"],
|
||||
)
|
||||
elif getattr(self.sio, "async_mode", "") != "asgi":
|
||||
raise RuntimeError(
|
||||
@ -429,7 +436,7 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
allow_origins=["*"],
|
||||
allow_origins=get_config().cors_allowed_origins,
|
||||
)
|
||||
|
||||
@property
|
||||
@ -466,7 +473,7 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
|
||||
def add_page(
|
||||
self,
|
||||
component: Component | ComponentCallable,
|
||||
component: Component | ComponentCallable | None = None,
|
||||
route: str | None = None,
|
||||
title: str | Var | None = None,
|
||||
description: str | Var | None = None,
|
||||
@ -489,17 +496,33 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
meta: The metadata of the page.
|
||||
|
||||
Raises:
|
||||
ValueError: When the specified route name already exists.
|
||||
PageValueError: When the component is not set for a non-404 page.
|
||||
RouteValueError: When the specified route name already exists.
|
||||
"""
|
||||
# If the route is not set, get it from the callable.
|
||||
if route is None:
|
||||
if not isinstance(component, Callable):
|
||||
raise ValueError("Route must be set if component is not a callable.")
|
||||
raise exceptions.RouteValueError(
|
||||
"Route must be set if component is not a callable."
|
||||
)
|
||||
# Format the route.
|
||||
route = format.format_route(component.__name__)
|
||||
else:
|
||||
route = format.format_route(route, format_case=False)
|
||||
|
||||
if route == constants.Page404.SLUG:
|
||||
if component is None:
|
||||
component = Default404Page.create()
|
||||
component = wait_for_client_redirect(self._generate_component(component))
|
||||
title = title or constants.Page404.TITLE
|
||||
description = description or constants.Page404.DESCRIPTION
|
||||
image = image or constants.Page404.IMAGE
|
||||
else:
|
||||
if component is None:
|
||||
raise exceptions.PageValueError(
|
||||
"Component must be set for a non-404 page."
|
||||
)
|
||||
|
||||
# Check if the route given is valid
|
||||
verify_route_validity(route)
|
||||
|
||||
@ -515,7 +538,7 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
if route == constants.PageNames.INDEX_ROUTE
|
||||
else f"`{route}`"
|
||||
)
|
||||
raise ValueError(
|
||||
raise exceptions.RouteValueError(
|
||||
f"Duplicate page route {route_name} already exists. Make sure you do not have two"
|
||||
f" pages with the same route"
|
||||
)
|
||||
@ -632,10 +655,14 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
on_load: The event handler(s) that will be called each time the page load.
|
||||
meta: The metadata of the page.
|
||||
"""
|
||||
if component is None:
|
||||
component = Default404Page.create()
|
||||
console.deprecate(
|
||||
feature_name="App.add_custom_404_page",
|
||||
reason=f"Use app.add_page(component, route='/{constants.Page404.SLUG}') instead.",
|
||||
deprecation_version="0.6.7",
|
||||
removal_version="0.8.0",
|
||||
)
|
||||
self.add_page(
|
||||
component=wait_for_client_redirect(self._generate_component(component)),
|
||||
component=component,
|
||||
route=constants.Page404.SLUG,
|
||||
title=title or constants.Page404.TITLE,
|
||||
image=image or constants.Page404.IMAGE,
|
||||
@ -836,7 +863,7 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
|
||||
# Render a default 404 page if the user didn't supply one
|
||||
if constants.Page404.SLUG not in self.unevaluated_pages:
|
||||
self.add_custom_404_page()
|
||||
self.add_page(route=constants.Page404.SLUG)
|
||||
|
||||
# Fix up the style.
|
||||
self.style = evaluate_style_namespaces(self.style)
|
||||
@ -850,10 +877,9 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
if self.theme is not None:
|
||||
# If a theme component was provided, wrap the app with it
|
||||
app_wrappers[(20, "Theme")] = self.theme
|
||||
# Fix #2992 by removing the top-level appearance prop
|
||||
self.theme.appearance = None
|
||||
|
||||
for route in self.unevaluated_pages:
|
||||
console.debug(f"Evaluating page: {route}")
|
||||
self._compile_page(route)
|
||||
|
||||
# Add the optional endpoints (_upload)
|
||||
@ -947,12 +973,12 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
is not None
|
||||
):
|
||||
executor = concurrent.futures.ProcessPoolExecutor(
|
||||
max_workers=number_of_processes,
|
||||
max_workers=number_of_processes or None,
|
||||
mp_context=multiprocessing.get_context("fork"),
|
||||
)
|
||||
else:
|
||||
executor = concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=environment.REFLEX_COMPILE_THREADS.get()
|
||||
max_workers=environment.REFLEX_COMPILE_THREADS.get() or None
|
||||
)
|
||||
|
||||
for route, component in zip(self.pages, page_components):
|
||||
@ -965,7 +991,6 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
|
||||
def _submit_work(fn, *args, **kwargs):
|
||||
f = executor.submit(fn, *args, **kwargs)
|
||||
# f = executor.apipe(fn, *args, **kwargs)
|
||||
result_futures.append(f)
|
||||
|
||||
# Compile the pre-compiled pages.
|
||||
@ -1006,6 +1031,9 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
compile_results.append(
|
||||
compiler.compile_contexts(self.state, self.theme),
|
||||
)
|
||||
if self.theme is not None:
|
||||
# Fix #2992 by removing the top-level appearance prop
|
||||
self.theme.appearance = None
|
||||
progress.advance(task)
|
||||
|
||||
# Compile the app root.
|
||||
@ -1154,7 +1182,7 @@ class App(MiddlewareMixin, LifespanMixin):
|
||||
if hasattr(handler_fn, "__name__"):
|
||||
_fn_name = handler_fn.__name__
|
||||
else:
|
||||
_fn_name = handler_fn.__class__.__name__
|
||||
_fn_name = type(handler_fn).__name__
|
||||
|
||||
if isinstance(handler_fn, functools.partial):
|
||||
raise ValueError(
|
||||
@ -1257,6 +1285,21 @@ async def process(
|
||||
)
|
||||
# Get the state for the session exclusively.
|
||||
async with app.state_manager.modify_state(event.substate_token) as state:
|
||||
# When this is a brand new instance of the state, signal the
|
||||
# frontend to reload before processing it.
|
||||
if (
|
||||
not state.router_data
|
||||
and event.name != get_hydrate_event(state)
|
||||
and app.event_namespace is not None
|
||||
):
|
||||
await asyncio.create_task(
|
||||
app.event_namespace.emit(
|
||||
"reload",
|
||||
data=event,
|
||||
to=sid,
|
||||
)
|
||||
)
|
||||
return
|
||||
# re-assign only when the value is different
|
||||
if state.router_data != router_data:
|
||||
# assignment will recurse into substates and force recalculation of
|
||||
@ -1460,10 +1503,10 @@ class EventNamespace(AsyncNamespace):
|
||||
app: App
|
||||
|
||||
# Keep a mapping between socket ID and client token.
|
||||
token_to_sid: dict[str, str] = {}
|
||||
token_to_sid: dict[str, str]
|
||||
|
||||
# Keep a mapping between client token and socket ID.
|
||||
sid_to_token: dict[str, str] = {}
|
||||
sid_to_token: dict[str, str]
|
||||
|
||||
def __init__(self, namespace: str, app: App):
|
||||
"""Initialize the event namespace.
|
||||
@ -1473,6 +1516,8 @@ class EventNamespace(AsyncNamespace):
|
||||
app: The application object.
|
||||
"""
|
||||
super().__init__(namespace)
|
||||
self.token_to_sid = {}
|
||||
self.sid_to_token = {}
|
||||
self.app = app
|
||||
|
||||
def on_connect(self, sid, environ):
|
||||
@ -1503,7 +1548,7 @@ class EventNamespace(AsyncNamespace):
|
||||
"""
|
||||
# Creating a task prevents the update from being blocked behind other coroutines.
|
||||
await asyncio.create_task(
|
||||
self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
|
||||
self.emit(str(constants.SocketEvent.EVENT), update, to=sid)
|
||||
)
|
||||
|
||||
async def on_event(self, sid, data):
|
||||
@ -1516,7 +1561,7 @@ class EventNamespace(AsyncNamespace):
|
||||
sid: The Socket.IO session id.
|
||||
data: The event data.
|
||||
"""
|
||||
fields = json.loads(data)
|
||||
fields = data
|
||||
# Get the event.
|
||||
event = Event(
|
||||
**{k: v for k, v in fields.items() if k not in ("handler", "event_actions")}
|
||||
|
95
reflex/assets.py
Normal file
95
reflex/assets.py
Normal file
@ -0,0 +1,95 @@
|
||||
"""Helper functions for adding assets to the app."""
|
||||
|
||||
import inspect
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from reflex import constants
|
||||
from reflex.config import EnvironmentVariables
|
||||
|
||||
|
||||
def asset(
|
||||
path: str,
|
||||
shared: bool = False,
|
||||
subfolder: Optional[str] = None,
|
||||
_stack_level: int = 1,
|
||||
) -> str:
|
||||
"""Add an asset to the app, either shared as a symlink or local.
|
||||
|
||||
Shared/External/Library assets:
|
||||
Place the file next to your including python file.
|
||||
Links the file to the app's external assets directory.
|
||||
|
||||
Example:
|
||||
```python
|
||||
# my_custom_javascript.js is a shared asset located next to the including python file.
|
||||
rx.script(src=rx.asset(path="my_custom_javascript.js", shared=True))
|
||||
rx.image(src=rx.asset(path="test_image.png", shared=True, subfolder="subfolder"))
|
||||
```
|
||||
|
||||
Local/Internal assets:
|
||||
Place the file in the app's assets/ directory.
|
||||
|
||||
Example:
|
||||
```python
|
||||
# local_image.png is an asset located in the app's assets/ directory. It cannot be shared when developing a library.
|
||||
rx.image(src=rx.asset(path="local_image.png"))
|
||||
```
|
||||
|
||||
Args:
|
||||
path: The relative path of the asset.
|
||||
subfolder: The directory to place the shared asset in.
|
||||
shared: Whether to expose the asset to other apps.
|
||||
_stack_level: The stack level to determine the calling file, defaults to
|
||||
the immediate caller 1. When using rx.asset via a helper function,
|
||||
increase this number for each helper function in the stack.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the file does not exist.
|
||||
ValueError: If subfolder is provided for local assets.
|
||||
|
||||
Returns:
|
||||
The relative URL to the asset.
|
||||
"""
|
||||
assets = constants.Dirs.APP_ASSETS
|
||||
backend_only = EnvironmentVariables.REFLEX_BACKEND_ONLY.get()
|
||||
|
||||
# Local asset handling
|
||||
if not shared:
|
||||
cwd = Path.cwd()
|
||||
src_file_local = cwd / assets / path
|
||||
if subfolder is not None:
|
||||
raise ValueError("Subfolder is not supported for local assets.")
|
||||
if not backend_only and not src_file_local.exists():
|
||||
raise FileNotFoundError(f"File not found: {src_file_local}")
|
||||
return f"/{path}"
|
||||
|
||||
# Shared asset handling
|
||||
# Determine the file by which the asset is exposed.
|
||||
frame = inspect.stack()[_stack_level]
|
||||
calling_file = frame.filename
|
||||
module = inspect.getmodule(frame[0])
|
||||
assert module is not None
|
||||
|
||||
external = constants.Dirs.EXTERNAL_APP_ASSETS
|
||||
src_file_shared = Path(calling_file).parent / path
|
||||
if not src_file_shared.exists():
|
||||
raise FileNotFoundError(f"File not found: {src_file_shared}")
|
||||
|
||||
caller_module_path = module.__name__.replace(".", "/")
|
||||
subfolder = f"{caller_module_path}/{subfolder}" if subfolder else caller_module_path
|
||||
|
||||
# Symlink the asset to the app's external assets directory if running frontend.
|
||||
if not backend_only:
|
||||
# Create the asset folder in the currently compiling app.
|
||||
asset_folder = Path.cwd() / assets / external / subfolder
|
||||
asset_folder.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
dst_file = asset_folder / path
|
||||
|
||||
if not dst_file.exists() and (
|
||||
not dst_file.is_symlink() or dst_file.resolve() != src_file_shared.resolve()
|
||||
):
|
||||
dst_file.symlink_to(src_file_shared)
|
||||
|
||||
return f"/{external}/{subfolder}/{path}"
|
@ -103,8 +103,8 @@ class Bare(Component):
|
||||
def _render(self) -> Tag:
|
||||
if isinstance(self.contents, Var):
|
||||
if isinstance(self.contents, (BooleanVar, ObjectVar)):
|
||||
return Tagless(contents=f"{{{str(self.contents.to_string())}}}")
|
||||
return Tagless(contents=f"{{{str(self.contents)}}}")
|
||||
return Tagless(contents=f"{{{self.contents.to_string()!s}}}")
|
||||
return Tagless(contents=f"{{{self.contents!s}}}")
|
||||
return Tagless(contents=str(self.contents))
|
||||
|
||||
def _get_vars(self, include_children: bool = False) -> Iterator[Var]:
|
||||
|
@ -161,7 +161,7 @@ class ComponentNamespace(SimpleNamespace):
|
||||
Returns:
|
||||
The hash of the namespace.
|
||||
"""
|
||||
return hash(self.__class__.__name__)
|
||||
return hash(type(self).__name__)
|
||||
|
||||
|
||||
def evaluate_style_namespaces(style: ComponentStyle) -> dict:
|
||||
@ -186,6 +186,23 @@ ComponentStyle = Dict[
|
||||
ComponentChild = Union[types.PrimitiveType, Var, BaseComponent]
|
||||
|
||||
|
||||
def satisfies_type_hint(obj: Any, type_hint: Any) -> bool:
|
||||
"""Check if an object satisfies a type hint.
|
||||
|
||||
Args:
|
||||
obj: The object to check.
|
||||
type_hint: The type hint to check against.
|
||||
|
||||
Returns:
|
||||
Whether the object satisfies the type hint.
|
||||
"""
|
||||
if isinstance(obj, LiteralVar):
|
||||
return types._isinstance(obj._var_value, type_hint)
|
||||
if isinstance(obj, Var):
|
||||
return types._issubclass(obj._var_type, type_hint)
|
||||
return types._isinstance(obj, type_hint)
|
||||
|
||||
|
||||
class Component(BaseComponent, ABC):
|
||||
"""A component with style, event trigger and other props."""
|
||||
|
||||
@ -460,8 +477,7 @@ class Component(BaseComponent, ABC):
|
||||
)
|
||||
) or (
|
||||
# Else just check if the passed var type is valid.
|
||||
not passed_types
|
||||
and not types._issubclass(passed_type, expected_type, value)
|
||||
not passed_types and not satisfies_type_hint(value, expected_type)
|
||||
):
|
||||
value_name = value._js_expr if isinstance(value, Var) else value
|
||||
|
||||
@ -567,7 +583,7 @@ class Component(BaseComponent, ABC):
|
||||
return self._create_event_chain(args_spec, value.guess_type(), key=key)
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Invalid event chain: {str(value)} of type {value._var_type}"
|
||||
f"Invalid event chain: {value!s} of type {value._var_type}"
|
||||
)
|
||||
elif isinstance(value, EventChain):
|
||||
# Trust that the caller knows what they're doing passing an EventChain directly
|
||||
@ -637,7 +653,6 @@ class Component(BaseComponent, ABC):
|
||||
|
||||
Returns:
|
||||
The event triggers.
|
||||
|
||||
"""
|
||||
default_triggers: Dict[str, types.ArgsSpec | Sequence[types.ArgsSpec]] = {
|
||||
EventTriggers.ON_FOCUS: no_args_event_spec,
|
||||
@ -1095,7 +1110,7 @@ class Component(BaseComponent, ABC):
|
||||
vars.append(prop_var)
|
||||
|
||||
# Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
|
||||
if isinstance(self.style, dict) and self.style or isinstance(self.style, Var):
|
||||
if (isinstance(self.style, dict) and self.style) or isinstance(self.style, Var):
|
||||
vars.append(
|
||||
Var(
|
||||
_js_expr="style",
|
||||
@ -1450,7 +1465,9 @@ class Component(BaseComponent, ABC):
|
||||
"""
|
||||
ref = self.get_ref()
|
||||
if ref is not None:
|
||||
return f"const {ref} = useRef(null); {str(Var(_js_expr=ref)._as_ref())} = {ref};"
|
||||
return (
|
||||
f"const {ref} = useRef(null); {Var(_js_expr=ref)._as_ref()!s} = {ref};"
|
||||
)
|
||||
|
||||
def _get_vars_hooks(self) -> dict[str, None]:
|
||||
"""Get the hooks required by vars referenced in this component.
|
||||
@ -2547,7 +2564,7 @@ class LiteralComponentVar(CachedVarOperation, LiteralVar, ComponentVar):
|
||||
Returns:
|
||||
The hash of the var.
|
||||
"""
|
||||
return hash((self.__class__.__name__, self._js_expr))
|
||||
return hash((type(self).__name__, self._js_expr))
|
||||
|
||||
@classmethod
|
||||
def create(
|
||||
|
@ -109,7 +109,7 @@ class ConnectionToaster(Toaster):
|
||||
)
|
||||
|
||||
individual_hooks = [
|
||||
f"const toast_props = {str(LiteralVar.create(props))};",
|
||||
f"const toast_props = {LiteralVar.create(props)!s};",
|
||||
"const [userDismissed, setUserDismissed] = useState(false);",
|
||||
FunctionStringVar(
|
||||
"useEffect",
|
||||
@ -124,7 +124,7 @@ class ConnectionToaster(Toaster):
|
||||
Var(
|
||||
_js_expr=f"""
|
||||
() => {{
|
||||
if ({str(has_too_many_connection_errors)}) {{
|
||||
if ({has_too_many_connection_errors!s}) {{
|
||||
if (!userDismissed) {{
|
||||
toast.error(
|
||||
`Cannot connect to server: ${{{connection_error}}}.`,
|
||||
|
@ -24,7 +24,7 @@ class ClientSideRouting(Component):
|
||||
library = "$/utils/client_side_routing"
|
||||
tag = "useClientSideRouting"
|
||||
|
||||
def add_hooks(self) -> list[str]:
|
||||
def add_hooks(self) -> list[str | Var]:
|
||||
"""Get the hooks to render.
|
||||
|
||||
Returns:
|
||||
@ -66,4 +66,4 @@ class Default404Page(Component):
|
||||
tag = "Error"
|
||||
is_default = True
|
||||
|
||||
status_code: Var[int] = 404 # type: ignore
|
||||
status_code: Var[int] = Var.create(404)
|
||||
|
@ -13,7 +13,7 @@ from reflex.vars.base import Var
|
||||
route_not_found: Var
|
||||
|
||||
class ClientSideRouting(Component):
|
||||
def add_hooks(self) -> list[str]: ...
|
||||
def add_hooks(self) -> list[str | Var]: ...
|
||||
def render(self) -> str: ...
|
||||
@overload
|
||||
@classmethod
|
||||
|
@ -51,7 +51,7 @@ class Clipboard(Fragment):
|
||||
return super().create(*children, **props)
|
||||
|
||||
def _exclude_props(self) -> list[str]:
|
||||
return super()._exclude_props() + ["on_paste", "on_paste_event_actions"]
|
||||
return [*super()._exclude_props(), "on_paste", "on_paste_event_actions"]
|
||||
|
||||
def _render(self) -> Tag:
|
||||
tag = super()._render()
|
||||
|
@ -49,9 +49,9 @@ class Cond(MemoizationLeaf):
|
||||
The conditional component.
|
||||
"""
|
||||
# Wrap everything in fragments.
|
||||
if comp1.__class__.__name__ != "Fragment":
|
||||
if type(comp1).__name__ != "Fragment":
|
||||
comp1 = Fragment.create(comp1)
|
||||
if comp2 is None or comp2.__class__.__name__ != "Fragment":
|
||||
if comp2 is None or type(comp2).__name__ != "Fragment":
|
||||
comp2 = Fragment.create(comp2) if comp2 else Fragment.create()
|
||||
return Fragment.create(
|
||||
cls(
|
||||
@ -94,7 +94,7 @@ class Cond(MemoizationLeaf):
|
||||
).set(
|
||||
props=tag.format_props(),
|
||||
),
|
||||
cond_state=f"isTrue({str(self.cond)})",
|
||||
cond_state=f"isTrue({self.cond!s})",
|
||||
)
|
||||
|
||||
def add_imports(self) -> ImportDict:
|
||||
|
@ -54,7 +54,7 @@ class Foreach(Component):
|
||||
iterable = LiteralVar.create(iterable)
|
||||
if iterable._var_type == Any:
|
||||
raise ForeachVarError(
|
||||
f"Could not foreach over var `{str(iterable)}` of type Any. "
|
||||
f"Could not foreach over var `{iterable!s}` of type Any. "
|
||||
"(If you are trying to foreach over a state var, add a type annotation to the var). "
|
||||
"See https://reflex.dev/docs/library/dynamic-rendering/foreach/"
|
||||
)
|
||||
|
@ -29,7 +29,7 @@ from reflex.event import (
|
||||
from reflex.utils import format
|
||||
from reflex.utils.imports import ImportVar
|
||||
from reflex.vars import VarData
|
||||
from reflex.vars.base import CallableVar, LiteralVar, Var, get_unique_variable_name
|
||||
from reflex.vars.base import CallableVar, Var, get_unique_variable_name
|
||||
from reflex.vars.sequence import LiteralStringVar
|
||||
|
||||
DEFAULT_UPLOAD_ID: str = "default"
|
||||
@ -61,7 +61,7 @@ def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> Var:
|
||||
id_var = LiteralStringVar.create(id_)
|
||||
var_name = f"""e => setFilesById(filesById => {{
|
||||
const updatedFilesById = Object.assign({{}}, filesById);
|
||||
updatedFilesById[{str(id_var)}] = e;
|
||||
updatedFilesById[{id_var!s}] = e;
|
||||
return updatedFilesById;
|
||||
}})
|
||||
"""
|
||||
@ -87,7 +87,7 @@ def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> Var:
|
||||
"""
|
||||
id_var = LiteralStringVar.create(id_)
|
||||
return Var(
|
||||
_js_expr=f"(filesById[{str(id_var)}] ? filesById[{str(id_var)}].map((f) => (f.path || f.name)) : [])",
|
||||
_js_expr=f"(filesById[{id_var!s}] ? filesById[{id_var!s}].map((f) => (f.path || f.name)) : [])",
|
||||
_var_type=List[str],
|
||||
_var_data=VarData.merge(
|
||||
upload_files_context_var_data, id_var._get_all_var_data()
|
||||
@ -108,7 +108,8 @@ def clear_selected_files(id_: str = DEFAULT_UPLOAD_ID) -> EventSpec:
|
||||
# UploadFilesProvider assigns a special function to clear selected files
|
||||
# into the shared global refs object to make it accessible outside a React
|
||||
# component via `run_script` (otherwise backend could never clear files).
|
||||
return run_script(f"refs['__clear_selected_files']({id_!r})")
|
||||
func = Var("__clear_selected_files")._as_ref()
|
||||
return run_script(f"{func}({id_!r})")
|
||||
|
||||
|
||||
def cancel_upload(upload_id: str) -> EventSpec:
|
||||
@ -120,9 +121,8 @@ def cancel_upload(upload_id: str) -> EventSpec:
|
||||
Returns:
|
||||
An event spec that cancels the upload when triggered.
|
||||
"""
|
||||
return run_script(
|
||||
f"upload_controllers[{str(LiteralVar.create(upload_id))}]?.abort()"
|
||||
)
|
||||
controller = Var(f"__upload_controllers_{upload_id}")._as_ref()
|
||||
return run_script(f"{controller}?.abort()")
|
||||
|
||||
|
||||
def get_upload_dir() -> Path:
|
||||
@ -293,13 +293,15 @@ class Upload(MemoizationLeaf):
|
||||
format.to_camel_case(key): value for key, value in upload_props.items()
|
||||
}
|
||||
|
||||
use_dropzone_arguments = {
|
||||
use_dropzone_arguments = Var.create(
|
||||
{
|
||||
"onDrop": event_var,
|
||||
**upload_props,
|
||||
}
|
||||
)
|
||||
|
||||
left_side = f"const {{getRootProps: {root_props_unique_name}, getInputProps: {input_props_unique_name}}} "
|
||||
right_side = f"useDropzone({str(Var.create(use_dropzone_arguments))})"
|
||||
right_side = f"useDropzone({use_dropzone_arguments!s})"
|
||||
|
||||
var_data = VarData.merge(
|
||||
VarData(
|
||||
@ -307,6 +309,7 @@ class Upload(MemoizationLeaf):
|
||||
hooks={Hooks.EVENTS: None},
|
||||
),
|
||||
event_var._get_all_var_data(),
|
||||
use_dropzone_arguments._get_all_var_data(),
|
||||
VarData(
|
||||
hooks={
|
||||
callback_str: None,
|
||||
|
@ -382,7 +382,7 @@ for theme_name in dir(Theme):
|
||||
class CodeBlock(Component, MarkdownComponentMap):
|
||||
"""A code block."""
|
||||
|
||||
library = "react-syntax-highlighter@15.6.1"
|
||||
library = "react-syntax-highlighter@15.6.0"
|
||||
|
||||
tag = "PrismAsyncLight"
|
||||
|
||||
@ -519,13 +519,13 @@ class CodeBlock(Component, MarkdownComponentMap):
|
||||
The hook to register the language.
|
||||
"""
|
||||
return f"""
|
||||
if ({str(_LANGUAGE)}) {{
|
||||
if ({_LANGUAGE!s}) {{
|
||||
(async () => {{
|
||||
try {{
|
||||
const module = await import(`react-syntax-highlighter/dist/cjs/languages/prism/${{{str(_LANGUAGE)}}}`);
|
||||
SyntaxHighlighter.registerLanguage({str(_LANGUAGE)}, module.default);
|
||||
const module = await import(`react-syntax-highlighter/dist/cjs/languages/prism/${{{_LANGUAGE!s}}}`);
|
||||
SyntaxHighlighter.registerLanguage({_LANGUAGE!s}, module.default);
|
||||
}} catch (error) {{
|
||||
console.error(`Error importing language module for ${{{str(_LANGUAGE)}}}:`, error);
|
||||
console.error(`Error importing language module for ${{{_LANGUAGE!s}}}:`, error);
|
||||
}}
|
||||
}})();
|
||||
}}
|
||||
@ -547,7 +547,7 @@ class CodeBlock(Component, MarkdownComponentMap):
|
||||
The hooks for the component.
|
||||
"""
|
||||
return [
|
||||
f"const {str(_LANGUAGE)} = {str(self.language)}",
|
||||
f"const {_LANGUAGE!s} = {self.language!s}",
|
||||
self._get_language_registration_hook(),
|
||||
]
|
||||
|
||||
|
@ -51,27 +51,6 @@ class GridColumnIcons(Enum):
|
||||
VideoUri = "video_uri"
|
||||
|
||||
|
||||
# @serializer
|
||||
# def serialize_gridcolumn_icon(icon: GridColumnIcons) -> str:
|
||||
# """Serialize grid column icon.
|
||||
|
||||
# Args:
|
||||
# icon: the Icon to serialize.
|
||||
|
||||
# Returns:
|
||||
# The serialized value.
|
||||
# """
|
||||
# return "prefix" + str(icon)
|
||||
|
||||
|
||||
# class DataEditorColumn(Base):
|
||||
# """Column."""
|
||||
|
||||
# title: str
|
||||
# id: Optional[str] = None
|
||||
# type_: str = "str"
|
||||
|
||||
|
||||
class DataEditorTheme(Base):
|
||||
"""The theme for the DataEditor component."""
|
||||
|
||||
@ -229,7 +208,7 @@ class DataEditor(NoSSRComponent):
|
||||
header_height: Var[int]
|
||||
|
||||
# Additional header icons:
|
||||
# header_icons: Var[Any] # (TODO: must be a map of name: svg)
|
||||
# header_icons: Var[Any] # (TODO: must be a map of name: svg) #noqa: ERA001
|
||||
|
||||
# The maximum width a column can be automatically sized to.
|
||||
max_column_auto_width: Var[int]
|
||||
@ -406,10 +385,8 @@ class DataEditor(NoSSRComponent):
|
||||
props["rows"] = data.length() if isinstance(data, Var) else len(data)
|
||||
|
||||
if not isinstance(columns, Var) and len(columns):
|
||||
if (
|
||||
types.is_dataframe(type(data))
|
||||
or isinstance(data, Var)
|
||||
and types.is_dataframe(data._var_type)
|
||||
if types.is_dataframe(type(data)) or (
|
||||
isinstance(data, Var) and types.is_dataframe(data._var_type)
|
||||
):
|
||||
raise ValueError(
|
||||
"Cannot pass in both a pandas dataframe and columns to the data_editor component."
|
||||
|
@ -288,7 +288,7 @@ class DataEditor(NoSSRComponent):
|
||||
freeze_columns: The number of columns which should remain in place when scrolling horizontally. Doesn't include rowMarkers.
|
||||
group_header_height: Controls the header of the group header row.
|
||||
header_height: Controls the height of the header row.
|
||||
max_column_auto_width: Additional header icons: header_icons: Var[Any] # (TODO: must be a map of name: svg) The maximum width a column can be automatically sized to.
|
||||
max_column_auto_width: The maximum width a column can be automatically sized to.
|
||||
max_column_width: The maximum width a column can be resized to.
|
||||
min_column_width: The minimum width a column can be resized to.
|
||||
row_height: Determins the height of each row.
|
||||
|
@ -490,17 +490,17 @@ class ShikiJsTransformer(ShikiBaseTransformers):
|
||||
},
|
||||
# White Space
|
||||
# ".tab, .space": {
|
||||
# "position": "relative",
|
||||
# "position": "relative", # noqa: ERA001
|
||||
# },
|
||||
# ".tab::before": {
|
||||
# "content": "'⇥'",
|
||||
# "position": "absolute",
|
||||
# "opacity": "0.3",
|
||||
# "content": "'⇥'", # noqa: ERA001
|
||||
# "position": "absolute", # noqa: ERA001
|
||||
# "opacity": "0.3",# noqa: ERA001
|
||||
# },
|
||||
# ".space::before": {
|
||||
# "content": "'·'",
|
||||
# "position": "absolute",
|
||||
# "opacity": "0.3",
|
||||
# "content": "'·'", # noqa: ERA001
|
||||
# "position": "absolute", # noqa: ERA001
|
||||
# "opacity": "0.3", # noqa: ERA001
|
||||
# },
|
||||
}
|
||||
)
|
||||
|
@ -173,7 +173,7 @@ def load_dynamic_serializer():
|
||||
f"const [{unique_var_name}, set_{unique_var_name}] = useState(null);": None,
|
||||
"useEffect(() => {"
|
||||
"let isMounted = true;"
|
||||
f"evalReactComponent({str(js_string)})"
|
||||
f"evalReactComponent({js_string!s})"
|
||||
".then((component) => {"
|
||||
"if (isMounted) {"
|
||||
f"set_{unique_var_name}(component);"
|
||||
@ -183,7 +183,7 @@ def load_dynamic_serializer():
|
||||
"isMounted = false;"
|
||||
"};"
|
||||
"}"
|
||||
f", [{str(js_string)}]);": None,
|
||||
f", [{js_string!s}]);": None,
|
||||
},
|
||||
),
|
||||
),
|
||||
|
@ -5,6 +5,7 @@
|
||||
|
||||
from . import elements as elements
|
||||
from .elements.forms import Button as Button
|
||||
from .elements.forms import Datalist as Datalist
|
||||
from .elements.forms import Fieldset as Fieldset
|
||||
from .elements.forms import Form as Form
|
||||
from .elements.forms import Input as Input
|
||||
@ -18,6 +19,7 @@ from .elements.forms import Progress as Progress
|
||||
from .elements.forms import Select as Select
|
||||
from .elements.forms import Textarea as Textarea
|
||||
from .elements.forms import button as button
|
||||
from .elements.forms import datalist as datalist
|
||||
from .elements.forms import fieldset as fieldset
|
||||
from .elements.forms import form as form
|
||||
from .elements.forms import input as input
|
||||
|
@ -7,6 +7,7 @@ from reflex.utils import lazy_loader
|
||||
_MAPPING = {
|
||||
"forms": [
|
||||
"button",
|
||||
"datalist",
|
||||
"fieldset",
|
||||
"form",
|
||||
"input",
|
||||
|
@ -4,6 +4,7 @@
|
||||
# ------------------------------------------------------
|
||||
|
||||
from .forms import Button as Button
|
||||
from .forms import Datalist as Datalist
|
||||
from .forms import Fieldset as Fieldset
|
||||
from .forms import Form as Form
|
||||
from .forms import Input as Input
|
||||
@ -17,6 +18,7 @@ from .forms import Progress as Progress
|
||||
from .forms import Select as Select
|
||||
from .forms import Textarea as Textarea
|
||||
from .forms import button as button
|
||||
from .forms import datalist as datalist
|
||||
from .forms import fieldset as fieldset
|
||||
from .forms import form as form
|
||||
from .forms import input as input
|
||||
@ -226,6 +228,7 @@ from .typography import ul as ul
|
||||
_MAPPING = {
|
||||
"forms": [
|
||||
"button",
|
||||
"datalist",
|
||||
"fieldset",
|
||||
"form",
|
||||
"input",
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Base classes."""
|
||||
|
||||
from typing import Union
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Forms classes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -18,6 +18,7 @@ from reflex.event import (
|
||||
prevent_default,
|
||||
)
|
||||
from reflex.utils.imports import ImportDict
|
||||
from reflex.utils.types import is_optional
|
||||
from reflex.vars import VarData
|
||||
from reflex.vars.base import LiteralVar, Var
|
||||
|
||||
@ -84,7 +85,6 @@ class Datalist(BaseHTML):
|
||||
"""Display the datalist element."""
|
||||
|
||||
tag = "datalist"
|
||||
# No unique attributes, only common ones are inherited
|
||||
|
||||
|
||||
class Fieldset(Element):
|
||||
@ -241,16 +241,15 @@ class Form(BaseHTML):
|
||||
if ref.startswith("refs_"):
|
||||
ref_var = Var(_js_expr=ref[:-3])._as_ref()
|
||||
form_refs[ref[len("refs_") : -3]] = Var(
|
||||
_js_expr=f"getRefValues({str(ref_var)})",
|
||||
_js_expr=f"getRefValues({ref_var!s})",
|
||||
_var_data=VarData.merge(ref_var._get_all_var_data()),
|
||||
)
|
||||
else:
|
||||
ref_var = Var(_js_expr=ref)._as_ref()
|
||||
form_refs[ref[4:]] = Var(
|
||||
_js_expr=f"getRefValue({str(ref_var)})",
|
||||
_js_expr=f"getRefValue({ref_var!s})",
|
||||
_var_data=VarData.merge(ref_var._get_all_var_data()),
|
||||
)
|
||||
# print(repr(form_refs))
|
||||
return form_refs
|
||||
|
||||
def _get_vars(self, include_children: bool = True) -> Iterator[Var]:
|
||||
@ -258,7 +257,8 @@ class Form(BaseHTML):
|
||||
yield from self._get_form_refs().values()
|
||||
|
||||
def _exclude_props(self) -> list[str]:
|
||||
return super()._exclude_props() + [
|
||||
return [
|
||||
*super()._exclude_props(),
|
||||
"reset_on_submit",
|
||||
"handle_submit_unique_name",
|
||||
]
|
||||
@ -383,6 +383,33 @@ class Input(BaseHTML):
|
||||
# Fired when a key is released
|
||||
on_key_up: EventHandler[key_event]
|
||||
|
||||
@classmethod
|
||||
def create(cls, *children, **props):
|
||||
"""Create an Input component.
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
**props: The properties of the component.
|
||||
|
||||
Returns:
|
||||
The component.
|
||||
"""
|
||||
from reflex.vars.number import ternary_operation
|
||||
|
||||
value = props.get("value")
|
||||
|
||||
# React expects an empty string(instead of null) for controlled inputs.
|
||||
if value is not None and is_optional(
|
||||
(value_var := Var.create(value))._var_type
|
||||
):
|
||||
props["value"] = ternary_operation(
|
||||
(value_var != Var.create(None)) # pyright: ignore [reportGeneralTypeIssues]
|
||||
& (value_var != Var(_js_expr="undefined")),
|
||||
value,
|
||||
Var.create(""),
|
||||
)
|
||||
return super().create(*children, **props)
|
||||
|
||||
|
||||
class Label(BaseHTML):
|
||||
"""Display the label element."""
|
||||
@ -400,7 +427,6 @@ class Legend(BaseHTML):
|
||||
"""Display the legend element."""
|
||||
|
||||
tag = "legend"
|
||||
# No unique attributes, only common ones are inherited
|
||||
|
||||
|
||||
class Meter(BaseHTML):
|
||||
@ -570,6 +596,9 @@ class Textarea(BaseHTML):
|
||||
# Visible width of the text control, in average character widths
|
||||
cols: Var[Union[str, int, bool]]
|
||||
|
||||
# The default value of the textarea when initially rendered
|
||||
default_value: Var[str]
|
||||
|
||||
# Name part of the textarea to submit in 'dir' and 'name' pair when form is submitted
|
||||
dirname: Var[Union[str, int, bool]]
|
||||
|
||||
@ -649,19 +678,20 @@ class Textarea(BaseHTML):
|
||||
"Cannot combine `enter_key_submit` with `on_key_down`.",
|
||||
)
|
||||
custom_attrs["on_key_down"] = Var(
|
||||
_js_expr=f"(e) => enterKeySubmitOnKeyDown(e, {str(enter_key_submit)})",
|
||||
_js_expr=f"(e) => enterKeySubmitOnKeyDown(e, {enter_key_submit!s})",
|
||||
_var_data=VarData.merge(enter_key_submit._get_all_var_data()),
|
||||
)
|
||||
if auto_height is not None:
|
||||
auto_height = Var.create(auto_height)
|
||||
custom_attrs["on_input"] = Var(
|
||||
_js_expr=f"(e) => autoHeightOnInput(e, {str(auto_height)})",
|
||||
_js_expr=f"(e) => autoHeightOnInput(e, {auto_height!s})",
|
||||
_var_data=VarData.merge(auto_height._get_all_var_data()),
|
||||
)
|
||||
return super().create(*children, **props)
|
||||
|
||||
def _exclude_props(self) -> list[str]:
|
||||
return super()._exclude_props() + [
|
||||
return [
|
||||
*super()._exclude_props(),
|
||||
"auto_height",
|
||||
"enter_key_submit",
|
||||
]
|
||||
@ -681,6 +711,7 @@ class Textarea(BaseHTML):
|
||||
|
||||
|
||||
button = Button.create
|
||||
datalist = Datalist.create
|
||||
fieldset = Fieldset.create
|
||||
form = Form.create
|
||||
input = Input.create
|
||||
|
@ -189,7 +189,7 @@ class Datalist(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
@ -512,7 +512,7 @@ class Input(BaseHTML):
|
||||
on_unmount: Optional[EventType[[], BASE_STATE]] = None,
|
||||
**props,
|
||||
) -> "Input":
|
||||
"""Create the component.
|
||||
"""Create an Input component.
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
@ -576,7 +576,7 @@ class Input(BaseHTML):
|
||||
class_name: The class name for the component.
|
||||
autofocus: Whether the component should take the focus once the page is loaded
|
||||
custom_attrs: custom attribute
|
||||
**props: The props of the component.
|
||||
**props: The properties of the component.
|
||||
|
||||
Returns:
|
||||
The component.
|
||||
@ -730,7 +730,7 @@ class Legend(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
@ -1350,6 +1350,7 @@ class Textarea(BaseHTML):
|
||||
auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
auto_height: Optional[Union[Var[bool], bool]] = None,
|
||||
cols: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
default_value: Optional[Union[Var[str], str]] = None,
|
||||
dirname: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
disabled: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
enter_key_submit: Optional[Union[Var[bool], bool]] = None,
|
||||
@ -1439,6 +1440,7 @@ class Textarea(BaseHTML):
|
||||
auto_focus: Automatically focuses the textarea when the page loads
|
||||
auto_height: Automatically fit the content height to the text (use min-height with this prop)
|
||||
cols: Visible width of the text control, in average character widths
|
||||
default_value: The default value of the textarea when initially rendered
|
||||
dirname: Name part of the textarea to submit in 'dir' and 'name' pair when form is submitted
|
||||
disabled: Disables the textarea
|
||||
enter_key_submit: Enter key submits form (shift-enter adds new line)
|
||||
@ -1490,6 +1492,7 @@ class Textarea(BaseHTML):
|
||||
...
|
||||
|
||||
button = Button.create
|
||||
datalist = Datalist.create
|
||||
fieldset = Fieldset.create
|
||||
form = Form.create
|
||||
input = Input.create
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Inline classes."""
|
||||
|
||||
from typing import Union
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Media classes."""
|
||||
|
||||
from typing import Any, Union
|
||||
|
||||
@ -129,7 +129,6 @@ class Img(BaseHTML):
|
||||
|
||||
Returns:
|
||||
The component.
|
||||
|
||||
"""
|
||||
return (
|
||||
super().create(src=children[0], **props)
|
||||
@ -274,14 +273,12 @@ class Picture(BaseHTML):
|
||||
"""Display the picture element."""
|
||||
|
||||
tag = "picture"
|
||||
# No unique attributes, only common ones are inherited
|
||||
|
||||
|
||||
class Portal(BaseHTML):
|
||||
"""Display the portal element."""
|
||||
|
||||
tag = "portal"
|
||||
# No unique attributes, only common ones are inherited
|
||||
|
||||
|
||||
class Source(BaseHTML):
|
||||
|
@ -340,7 +340,6 @@ class Img(BaseHTML):
|
||||
|
||||
Returns:
|
||||
The component.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@ -987,7 +986,7 @@ class Picture(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
@ -1073,7 +1072,7 @@ class Portal(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Metadata classes."""
|
||||
|
||||
from typing import List, Union
|
||||
|
||||
@ -8,7 +8,7 @@ from reflex.vars.base import Var
|
||||
from .base import BaseHTML
|
||||
|
||||
|
||||
class Base(BaseHTML): # noqa: E742
|
||||
class Base(BaseHTML):
|
||||
"""Display the base element."""
|
||||
|
||||
tag = "base"
|
||||
@ -18,13 +18,13 @@ class Base(BaseHTML): # noqa: E742
|
||||
target: Var[Union[str, int, bool]]
|
||||
|
||||
|
||||
class Head(BaseHTML): # noqa: E742
|
||||
class Head(BaseHTML):
|
||||
"""Display the head element."""
|
||||
|
||||
tag = "head"
|
||||
|
||||
|
||||
class Link(BaseHTML): # noqa: E742
|
||||
class Link(BaseHTML):
|
||||
"""Display the link element."""
|
||||
|
||||
tag = "link"
|
||||
@ -75,14 +75,14 @@ class Meta(BaseHTML): # Inherits common attributes from BaseHTML
|
||||
name: Var[Union[str, int, bool]]
|
||||
|
||||
|
||||
class Title(Element): # noqa: E742
|
||||
class Title(Element):
|
||||
"""Display the title element."""
|
||||
|
||||
tag = "title"
|
||||
|
||||
|
||||
# Had to be named with an underscore so it doesnt conflict with reflex.style Style in pyi
|
||||
class StyleEl(Element): # noqa: E742
|
||||
class StyleEl(Element):
|
||||
"""Display the style element."""
|
||||
|
||||
tag = "style"
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Other classes."""
|
||||
|
||||
from typing import Union
|
||||
|
||||
@ -26,31 +26,39 @@ class Dialog(BaseHTML):
|
||||
|
||||
|
||||
class Summary(BaseHTML):
|
||||
"""Display the summary element."""
|
||||
"""Display the summary element.
|
||||
|
||||
Used as a summary or caption for a <details> element.
|
||||
"""
|
||||
|
||||
tag = "summary"
|
||||
# No unique attributes, only common ones are inherited; used as a summary or caption for a <details> element
|
||||
|
||||
|
||||
class Slot(BaseHTML):
|
||||
"""Display the slot element."""
|
||||
"""Display the slot element.
|
||||
|
||||
Used as a placeholder inside a web component.
|
||||
"""
|
||||
|
||||
tag = "slot"
|
||||
# No unique attributes, only common ones are inherited; used as a placeholder inside a web component
|
||||
|
||||
|
||||
class Template(BaseHTML):
|
||||
"""Display the template element."""
|
||||
"""Display the template element.
|
||||
|
||||
Used for declaring fragments of HTML that can be cloned and inserted in the document.
|
||||
"""
|
||||
|
||||
tag = "template"
|
||||
# No unique attributes, only common ones are inherited; used for declaring fragments of HTML that can be cloned and inserted in the document
|
||||
|
||||
|
||||
class Math(BaseHTML):
|
||||
"""Display the math element."""
|
||||
"""Display the math element.
|
||||
|
||||
Represents a mathematical expression.
|
||||
"""
|
||||
|
||||
tag = "math"
|
||||
# No unique attributes, only common ones are inherited; used for displaying mathematical expressions
|
||||
|
||||
|
||||
class Html(BaseHTML):
|
||||
|
@ -244,7 +244,7 @@ class Summary(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited; used as a summary or caption for a <details> element Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
@ -330,7 +330,7 @@ class Slot(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited; used as a placeholder inside a web component Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
@ -416,7 +416,7 @@ class Template(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited; used for declaring fragments of HTML that can be cloned and inserted in the document Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
@ -502,7 +502,7 @@ class Math(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited; used for displaying mathematical expressions Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Scripts classes."""
|
||||
|
||||
from typing import Union
|
||||
|
||||
@ -17,7 +17,6 @@ class Noscript(BaseHTML):
|
||||
"""Display the noscript element."""
|
||||
|
||||
tag = "noscript"
|
||||
# No unique attributes, only common ones are inherited
|
||||
|
||||
|
||||
class Script(BaseHTML):
|
||||
|
@ -154,7 +154,7 @@ class Noscript(BaseHTML):
|
||||
|
||||
Args:
|
||||
*children: The children of the component.
|
||||
access_key: No unique attributes, only common ones are inherited Provides a hint for generating a keyboard shortcut for the current element.
|
||||
access_key: Provides a hint for generating a keyboard shortcut for the current element.
|
||||
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
|
||||
content_editable: Indicates whether the element's content is editable.
|
||||
context_menu: Defines the ID of a <menu> element which will serve as the element's context menu.
|
||||
|
@ -1,93 +1,93 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Sectioning classes."""
|
||||
|
||||
from .base import BaseHTML
|
||||
|
||||
|
||||
class Body(BaseHTML): # noqa: E742
|
||||
class Body(BaseHTML):
|
||||
"""Display the body element."""
|
||||
|
||||
tag = "body"
|
||||
|
||||
|
||||
class Address(BaseHTML): # noqa: E742
|
||||
class Address(BaseHTML):
|
||||
"""Display the address element."""
|
||||
|
||||
tag = "address"
|
||||
|
||||
|
||||
class Article(BaseHTML): # noqa: E742
|
||||
class Article(BaseHTML):
|
||||
"""Display the article element."""
|
||||
|
||||
tag = "article"
|
||||
|
||||
|
||||
class Aside(BaseHTML): # noqa: E742
|
||||
class Aside(BaseHTML):
|
||||
"""Display the aside element."""
|
||||
|
||||
tag = "aside"
|
||||
|
||||
|
||||
class Footer(BaseHTML): # noqa: E742
|
||||
class Footer(BaseHTML):
|
||||
"""Display the footer element."""
|
||||
|
||||
tag = "footer"
|
||||
|
||||
|
||||
class Header(BaseHTML): # noqa: E742
|
||||
class Header(BaseHTML):
|
||||
"""Display the header element."""
|
||||
|
||||
tag = "header"
|
||||
|
||||
|
||||
class H1(BaseHTML): # noqa: E742
|
||||
class H1(BaseHTML):
|
||||
"""Display the h1 element."""
|
||||
|
||||
tag = "h1"
|
||||
|
||||
|
||||
class H2(BaseHTML): # noqa: E742
|
||||
class H2(BaseHTML):
|
||||
"""Display the h1 element."""
|
||||
|
||||
tag = "h2"
|
||||
|
||||
|
||||
class H3(BaseHTML): # noqa: E742
|
||||
class H3(BaseHTML):
|
||||
"""Display the h1 element."""
|
||||
|
||||
tag = "h3"
|
||||
|
||||
|
||||
class H4(BaseHTML): # noqa: E742
|
||||
class H4(BaseHTML):
|
||||
"""Display the h1 element."""
|
||||
|
||||
tag = "h4"
|
||||
|
||||
|
||||
class H5(BaseHTML): # noqa: E742
|
||||
class H5(BaseHTML):
|
||||
"""Display the h1 element."""
|
||||
|
||||
tag = "h5"
|
||||
|
||||
|
||||
class H6(BaseHTML): # noqa: E742
|
||||
class H6(BaseHTML):
|
||||
"""Display the h1 element."""
|
||||
|
||||
tag = "h6"
|
||||
|
||||
|
||||
class Main(BaseHTML): # noqa: E742
|
||||
class Main(BaseHTML):
|
||||
"""Display the main element."""
|
||||
|
||||
tag = "main"
|
||||
|
||||
|
||||
class Nav(BaseHTML): # noqa: E742
|
||||
class Nav(BaseHTML):
|
||||
"""Display the nav element."""
|
||||
|
||||
tag = "nav"
|
||||
|
||||
|
||||
class Section(BaseHTML): # noqa: E742
|
||||
class Section(BaseHTML):
|
||||
"""Display the section element."""
|
||||
|
||||
tag = "section"
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Tables classes."""
|
||||
|
||||
from typing import Union
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
|
||||
"""Typography classes."""
|
||||
|
||||
from typing import Union
|
||||
|
||||
|
@ -283,7 +283,7 @@ class Markdown(Component):
|
||||
# Format the code to handle inline and block code.
|
||||
formatted_code = f"""
|
||||
const match = (className || '').match(/language-(?<lang>.*)/);
|
||||
const {str(_LANGUAGE)} = match ? match[1] : '';
|
||||
const {_LANGUAGE!s} = match ? match[1] : '';
|
||||
{codeblock_custom_code};
|
||||
return inline ? (
|
||||
{self.format_component("code")}
|
||||
@ -340,7 +340,7 @@ const {str(_LANGUAGE)} = match ? match[1] : '';
|
||||
# If the children are set as a prop, don't pass them as children.
|
||||
children_prop = props.pop("children", None)
|
||||
if children_prop is not None:
|
||||
special_props.append(Var(_js_expr=f"children={{{str(children_prop)}}}"))
|
||||
special_props.append(Var(_js_expr=f"children={{{children_prop!s}}}"))
|
||||
children = []
|
||||
# Get the component.
|
||||
component = self.component_map[tag](*children, **props).set(
|
||||
@ -429,7 +429,7 @@ const {str(_LANGUAGE)} = match ? match[1] : '';
|
||||
function {self._get_component_map_name()} () {{
|
||||
{formatted_hooks}
|
||||
return (
|
||||
{str(LiteralVar.create(self.format_component_map()))}
|
||||
{LiteralVar.create(self.format_component_map())!s}
|
||||
)
|
||||
}}
|
||||
"""
|
||||
|
@ -1,7 +1,8 @@
|
||||
"""Moment component for humanized date rendering."""
|
||||
|
||||
import dataclasses
|
||||
from typing import List, Optional
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from reflex.components.component import NoSSRComponent
|
||||
from reflex.event import EventHandler, passthrough_event_spec
|
||||
@ -19,7 +20,7 @@ class MomentDelta:
|
||||
weeks: Optional[int] = dataclasses.field(default=None)
|
||||
days: Optional[int] = dataclasses.field(default=None)
|
||||
hours: Optional[int] = dataclasses.field(default=None)
|
||||
minutess: Optional[int] = dataclasses.field(default=None)
|
||||
minutes: Optional[int] = dataclasses.field(default=None)
|
||||
seconds: Optional[int] = dataclasses.field(default=None)
|
||||
milliseconds: Optional[int] = dataclasses.field(default=None)
|
||||
|
||||
@ -78,7 +79,7 @@ class Moment(NoSSRComponent):
|
||||
duration: Var[str]
|
||||
|
||||
# The date to display (also work if passed as children).
|
||||
date: Var[str]
|
||||
date: Var[Union[str, datetime, date, time, timedelta]]
|
||||
|
||||
# Shows the duration (elapsed time) between now and the provided datetime.
|
||||
duration_from_now: Var[bool]
|
||||
|
@ -4,6 +4,7 @@
|
||||
# This file was generated by `reflex/utils/pyi_generator.py`!
|
||||
# ------------------------------------------------------
|
||||
import dataclasses
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Any, Dict, Optional, Union, overload
|
||||
|
||||
from reflex.components.component import NoSSRComponent
|
||||
@ -20,7 +21,7 @@ class MomentDelta:
|
||||
weeks: Optional[int]
|
||||
days: Optional[int]
|
||||
hours: Optional[int]
|
||||
minutess: Optional[int]
|
||||
minutes: Optional[int]
|
||||
seconds: Optional[int]
|
||||
milliseconds: Optional[int]
|
||||
|
||||
@ -46,7 +47,16 @@ class Moment(NoSSRComponent):
|
||||
decimal: Optional[Union[Var[bool], bool]] = None,
|
||||
unit: Optional[Union[Var[str], str]] = None,
|
||||
duration: Optional[Union[Var[str], str]] = None,
|
||||
date: Optional[Union[Var[str], str]] = None,
|
||||
date: Optional[
|
||||
Union[
|
||||
Var[Union[date, datetime, str, time, timedelta]],
|
||||
date,
|
||||
datetime,
|
||||
str,
|
||||
time,
|
||||
timedelta,
|
||||
]
|
||||
] = None,
|
||||
duration_from_now: Optional[Union[Var[bool], bool]] = None,
|
||||
unix: Optional[Union[Var[bool], bool]] = None,
|
||||
local: Optional[Union[Var[bool], bool]] = None,
|
||||
|
@ -47,7 +47,7 @@ class Image(NextComponent):
|
||||
placeholder: Var[str]
|
||||
|
||||
# Allows passing CSS styles to the underlying image element.
|
||||
# style: Var[Any]
|
||||
# style: Var[Any] #noqa: ERA001
|
||||
|
||||
# The loading behavior of the image. Defaults to lazy. Can hurt performance, recommended to use `priority` instead.
|
||||
loading: Var[Literal["lazy", "eager"]]
|
||||
|
@ -70,7 +70,7 @@ class Image(NextComponent):
|
||||
quality: The quality of the optimized image, an integer between 1 and 100, where 100 is the best quality and therefore largest file size. Defaults to 75.
|
||||
priority: When true, the image will be considered high priority and preload. Lazy loading is automatically disabled for images using priority.
|
||||
placeholder: A placeholder to use while the image is loading. Possible values are blur, empty, or data:image/.... Defaults to empty.
|
||||
loading: Allows passing CSS styles to the underlying image element. style: Var[Any] The loading behavior of the image. Defaults to lazy. Can hurt performance, recommended to use `priority` instead.
|
||||
loading: The loading behavior of the image. Defaults to lazy. Can hurt performance, recommended to use `priority` instead.
|
||||
blurDataURL: A Data URL to be used as a placeholder image before the src image successfully loads. Only takes effect when combined with placeholder="blur".
|
||||
on_load: Fires when the image has loaded.
|
||||
on_error: Fires when the image has an error.
|
||||
|
@ -255,7 +255,7 @@ const extractPoints = (points) => {
|
||||
|
||||
def _render(self):
|
||||
tag = super()._render()
|
||||
figure = self.data.to(dict)
|
||||
figure = self.data.to(dict) if self.data is not None else Var.create({})
|
||||
merge_dicts = [] # Data will be merged and spread from these dict Vars
|
||||
if self.layout is not None:
|
||||
# Why is this not a literal dict? Great question... it didn't work
|
||||
@ -270,11 +270,11 @@ const extractPoints = (points) => {
|
||||
tag.special_props.append(
|
||||
# Merge all dictionaries and spread the result over props.
|
||||
Var(
|
||||
_js_expr=f"{{...mergician({str(figure)},"
|
||||
_js_expr=f"{{...mergician({figure!s},"
|
||||
f"{','.join(str(md) for md in merge_dicts)})}}",
|
||||
),
|
||||
)
|
||||
else:
|
||||
# Spread the figure dict over props, nothing to merge.
|
||||
tag.special_props.append(Var(_js_expr=f"{{...{str(figure)}}}"))
|
||||
tag.special_props.append(Var(_js_expr=f"{{...{figure!s}}}"))
|
||||
return tag
|
||||
|
@ -129,7 +129,8 @@ class AccordionRoot(AccordionComponent):
|
||||
on_value_change: EventHandler[on_value_change]
|
||||
|
||||
def _exclude_props(self) -> list[str]:
|
||||
return super()._exclude_props() + [
|
||||
return [
|
||||
*super()._exclude_props(),
|
||||
"radius",
|
||||
"duration",
|
||||
"easing",
|
||||
|
@ -11,7 +11,6 @@ from reflex.components.radix.primitives.base import RadixPrimitiveComponent
|
||||
from reflex.components.radix.themes.base import Theme
|
||||
from reflex.components.radix.themes.layout.flex import Flex
|
||||
from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec
|
||||
from reflex.utils import console
|
||||
from reflex.vars.base import Var
|
||||
|
||||
|
||||
@ -140,19 +139,19 @@ class DrawerContent(DrawerComponent):
|
||||
base_style.update(style)
|
||||
return {"css": base_style}
|
||||
|
||||
# Fired when the drawer content is opened. Deprecated.
|
||||
# Fired when the drawer content is opened.
|
||||
on_open_auto_focus: EventHandler[no_args_event_spec]
|
||||
|
||||
# Fired when the drawer content is closed. Deprecated.
|
||||
# Fired when the drawer content is closed.
|
||||
on_close_auto_focus: EventHandler[no_args_event_spec]
|
||||
|
||||
# Fired when the escape key is pressed. Deprecated.
|
||||
# Fired when the escape key is pressed.
|
||||
on_escape_key_down: EventHandler[no_args_event_spec]
|
||||
|
||||
# Fired when the pointer is down outside the drawer content. Deprecated.
|
||||
# Fired when the pointer is down outside the drawer content.
|
||||
on_pointer_down_outside: EventHandler[no_args_event_spec]
|
||||
|
||||
# Fired when interacting outside the drawer content. Deprecated.
|
||||
# Fired when interacting outside the drawer content.
|
||||
on_interact_outside: EventHandler[no_args_event_spec]
|
||||
|
||||
@classmethod
|
||||
@ -170,23 +169,6 @@ class DrawerContent(DrawerComponent):
|
||||
Returns:
|
||||
The drawer content.
|
||||
"""
|
||||
deprecated_properties = [
|
||||
"on_open_auto_focus",
|
||||
"on_close_auto_focus",
|
||||
"on_escape_key_down",
|
||||
"on_pointer_down_outside",
|
||||
"on_interact_outside",
|
||||
]
|
||||
|
||||
for prop in deprecated_properties:
|
||||
if prop in props:
|
||||
console.deprecate(
|
||||
feature_name="drawer content events",
|
||||
reason=f"The `{prop}` event is deprecated and will be removed in 0.7.0.",
|
||||
deprecation_version="0.6.3",
|
||||
removal_version="0.7.0",
|
||||
)
|
||||
|
||||
comp = super().create(*children, **props)
|
||||
|
||||
return Theme.create(comp)
|
||||
|
@ -188,7 +188,7 @@ class Slider(ComponentNamespace):
|
||||
else:
|
||||
children = [
|
||||
track,
|
||||
# Foreach.create(props.get("value"), lambda e: SliderThumb.create()), # foreach doesn't render Thumbs properly
|
||||
# Foreach.create(props.get("value"), lambda e: SliderThumb.create()), # foreach doesn't render Thumbs properly # noqa: ERA001
|
||||
]
|
||||
|
||||
return SliderRoot.create(*children, **props)
|
||||
|
@ -53,7 +53,7 @@ LiteralAccentColor = Literal[
|
||||
class CommonMarginProps(Component):
|
||||
"""Many radix-themes elements accept shorthand margin props."""
|
||||
|
||||
# Margin: "0" - "9"
|
||||
# Margin: "0" - "9" # noqa: ERA001
|
||||
m: Var[LiteralSpacing]
|
||||
|
||||
# Margin horizontal: "0" - "9"
|
||||
@ -78,7 +78,7 @@ class CommonMarginProps(Component):
|
||||
class CommonPaddingProps(Component):
|
||||
"""Many radix-themes elements accept shorthand padding props."""
|
||||
|
||||
# Padding: "0" - "9"
|
||||
# Padding: "0" - "9" # noqa: ERA001
|
||||
p: Var[Responsive[LiteralSpacing]]
|
||||
|
||||
# Padding horizontal: "0" - "9"
|
||||
@ -139,14 +139,7 @@ class RadixThemesComponent(Component):
|
||||
component = super().create(*children, **props)
|
||||
if component.library is None:
|
||||
component.library = RadixThemesComponent.__fields__["library"].default
|
||||
component.alias = "RadixThemes" + (
|
||||
component.tag or component.__class__.__name__
|
||||
)
|
||||
# value = props.get("value")
|
||||
# if value is not None and component.alias == "RadixThemesSelect.Root":
|
||||
# lv = LiteralVar.create(value)
|
||||
# print(repr(lv))
|
||||
# print(f"Warning: Value {value} is not used in {component.alias}.")
|
||||
component.alias = "RadixThemes" + (component.tag or type(component).__name__)
|
||||
return component
|
||||
|
||||
@staticmethod
|
||||
@ -268,6 +261,7 @@ class Theme(RadixThemesComponent):
|
||||
_js_expr="{...theme.styles.global[':root'], ...theme.styles.global.body}"
|
||||
),
|
||||
)
|
||||
tag.remove_props("appearance")
|
||||
return tag
|
||||
|
||||
|
||||
|
@ -427,7 +427,7 @@ class ColorModeSwitch(Switch):
|
||||
color_scheme: Override theme color for switch
|
||||
high_contrast: Whether to render the switch with higher contrast color against background
|
||||
radius: Override theme radius for switch: "none" | "small" | "full"
|
||||
on_change: Props to rename Fired when the value of the switch changes
|
||||
on_change: Fired when the value of the switch changes
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
|
@ -153,7 +153,7 @@ class Checkbox(RadixThemesComponent):
|
||||
required: Whether the checkbox is required
|
||||
name: The name of the checkbox control when submitting the form.
|
||||
value: The value of the checkbox control when submitting the form.
|
||||
on_change: Props to rename Fired when the checkbox is checked or unchecked.
|
||||
on_change: Fired when the checkbox is checked or unchecked.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
@ -302,7 +302,7 @@ class HighLevelCheckbox(RadixThemesComponent):
|
||||
required: Whether the checkbox is required
|
||||
name: The name of the checkbox control when submitting the form.
|
||||
value: The value of the checkbox control when submitting the form.
|
||||
on_change: Props to rename Fired when the checkbox is checked or unchecked.
|
||||
on_change: Fired when the checkbox is checked or unchecked.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
@ -449,7 +449,7 @@ class CheckboxNamespace(ComponentNamespace):
|
||||
required: Whether the checkbox is required
|
||||
name: The name of the checkbox control when submitting the form.
|
||||
value: The value of the checkbox control when submitting the form.
|
||||
on_change: Props to rename Fired when the checkbox is checked or unchecked.
|
||||
on_change: Fired when the checkbox is checked or unchecked.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
|
@ -8,6 +8,7 @@ from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spe
|
||||
from reflex.vars.base import Var
|
||||
|
||||
from ..base import LiteralAccentColor, RadixThemesComponent
|
||||
from .checkbox import Checkbox
|
||||
|
||||
LiteralDirType = Literal["ltr", "rtl"]
|
||||
|
||||
@ -232,6 +233,15 @@ class ContextMenuSeparator(RadixThemesComponent):
|
||||
tag = "ContextMenu.Separator"
|
||||
|
||||
|
||||
class ContextMenuCheckbox(Checkbox):
|
||||
"""The component that contains the checkbox."""
|
||||
|
||||
tag = "ContextMenu.CheckboxItem"
|
||||
|
||||
# Text to render as shortcut.
|
||||
shortcut: Var[str]
|
||||
|
||||
|
||||
class ContextMenu(ComponentNamespace):
|
||||
"""Menu representing a set of actions, displayed at the origin of a pointer right-click or long-press."""
|
||||
|
||||
@ -243,6 +253,7 @@ class ContextMenu(ComponentNamespace):
|
||||
sub_content = staticmethod(ContextMenuSubContent.create)
|
||||
item = staticmethod(ContextMenuItem.create)
|
||||
separator = staticmethod(ContextMenuSeparator.create)
|
||||
checkbox = staticmethod(ContextMenuCheckbox.create)
|
||||
|
||||
|
||||
context_menu = ContextMenu()
|
||||
|
@ -12,6 +12,7 @@ from reflex.style import Style
|
||||
from reflex.vars.base import Var
|
||||
|
||||
from ..base import RadixThemesComponent
|
||||
from .checkbox import Checkbox
|
||||
|
||||
LiteralDirType = Literal["ltr", "rtl"]
|
||||
LiteralSizeType = Literal["1", "2"]
|
||||
@ -672,6 +673,159 @@ class ContextMenuSeparator(RadixThemesComponent):
|
||||
"""
|
||||
...
|
||||
|
||||
class ContextMenuCheckbox(Checkbox):
|
||||
@overload
|
||||
@classmethod
|
||||
def create( # type: ignore
|
||||
cls,
|
||||
*children,
|
||||
shortcut: Optional[Union[Var[str], str]] = None,
|
||||
as_child: Optional[Union[Var[bool], bool]] = None,
|
||||
size: Optional[
|
||||
Union[
|
||||
Breakpoints[str, Literal["1", "2", "3"]],
|
||||
Literal["1", "2", "3"],
|
||||
Var[
|
||||
Union[
|
||||
Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
|
||||
]
|
||||
],
|
||||
]
|
||||
] = None,
|
||||
variant: Optional[
|
||||
Union[
|
||||
Literal["classic", "soft", "surface"],
|
||||
Var[Literal["classic", "soft", "surface"]],
|
||||
]
|
||||
] = None,
|
||||
color_scheme: Optional[
|
||||
Union[
|
||||
Literal[
|
||||
"amber",
|
||||
"blue",
|
||||
"bronze",
|
||||
"brown",
|
||||
"crimson",
|
||||
"cyan",
|
||||
"gold",
|
||||
"grass",
|
||||
"gray",
|
||||
"green",
|
||||
"indigo",
|
||||
"iris",
|
||||
"jade",
|
||||
"lime",
|
||||
"mint",
|
||||
"orange",
|
||||
"pink",
|
||||
"plum",
|
||||
"purple",
|
||||
"red",
|
||||
"ruby",
|
||||
"sky",
|
||||
"teal",
|
||||
"tomato",
|
||||
"violet",
|
||||
"yellow",
|
||||
],
|
||||
Var[
|
||||
Literal[
|
||||
"amber",
|
||||
"blue",
|
||||
"bronze",
|
||||
"brown",
|
||||
"crimson",
|
||||
"cyan",
|
||||
"gold",
|
||||
"grass",
|
||||
"gray",
|
||||
"green",
|
||||
"indigo",
|
||||
"iris",
|
||||
"jade",
|
||||
"lime",
|
||||
"mint",
|
||||
"orange",
|
||||
"pink",
|
||||
"plum",
|
||||
"purple",
|
||||
"red",
|
||||
"ruby",
|
||||
"sky",
|
||||
"teal",
|
||||
"tomato",
|
||||
"violet",
|
||||
"yellow",
|
||||
]
|
||||
],
|
||||
]
|
||||
] = None,
|
||||
high_contrast: Optional[Union[Var[bool], bool]] = None,
|
||||
default_checked: Optional[Union[Var[bool], bool]] = None,
|
||||
checked: Optional[Union[Var[bool], bool]] = None,
|
||||
disabled: Optional[Union[Var[bool], bool]] = None,
|
||||
required: Optional[Union[Var[bool], bool]] = None,
|
||||
name: Optional[Union[Var[str], str]] = None,
|
||||
value: Optional[Union[Var[str], str]] = None,
|
||||
style: Optional[Style] = None,
|
||||
key: Optional[Any] = None,
|
||||
id: Optional[Any] = None,
|
||||
class_name: Optional[Any] = None,
|
||||
autofocus: Optional[bool] = None,
|
||||
custom_attrs: Optional[Dict[str, Union[Var, Any]]] = None,
|
||||
on_blur: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_change: Optional[
|
||||
Union[EventType[[], BASE_STATE], EventType[[bool], BASE_STATE]]
|
||||
] = None,
|
||||
on_click: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_context_menu: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_double_click: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_focus: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mount: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mouse_down: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mouse_enter: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mouse_leave: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mouse_move: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mouse_out: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mouse_over: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_mouse_up: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_scroll: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_unmount: Optional[EventType[[], BASE_STATE]] = None,
|
||||
**props,
|
||||
) -> "ContextMenuCheckbox":
|
||||
"""Create a new component instance.
|
||||
|
||||
Will prepend "RadixThemes" to the component tag to avoid conflicts with
|
||||
other UI libraries for common names, like Text and Button.
|
||||
|
||||
Args:
|
||||
*children: Child components.
|
||||
shortcut: Text to render as shortcut.
|
||||
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
|
||||
size: Checkbox size "1" - "3"
|
||||
variant: Variant of checkbox: "classic" | "surface" | "soft"
|
||||
color_scheme: Override theme color for checkbox
|
||||
high_contrast: Whether to render the checkbox with higher contrast color against background
|
||||
default_checked: Whether the checkbox is checked by default
|
||||
checked: Whether the checkbox is checked
|
||||
disabled: Whether the checkbox is disabled
|
||||
required: Whether the checkbox is required
|
||||
name: The name of the checkbox control when submitting the form.
|
||||
value: The value of the checkbox control when submitting the form.
|
||||
on_change: Fired when the checkbox is checked or unchecked.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
class_name: The class name for the component.
|
||||
autofocus: Whether the component should take the focus once the page is loaded
|
||||
custom_attrs: custom attribute
|
||||
**props: Component properties.
|
||||
|
||||
Returns:
|
||||
A new component instance.
|
||||
"""
|
||||
...
|
||||
|
||||
class ContextMenu(ComponentNamespace):
|
||||
root = staticmethod(ContextMenuRoot.create)
|
||||
trigger = staticmethod(ContextMenuTrigger.create)
|
||||
@ -681,5 +835,6 @@ class ContextMenu(ComponentNamespace):
|
||||
sub_content = staticmethod(ContextMenuSubContent.create)
|
||||
item = staticmethod(ContextMenuItem.create)
|
||||
separator = staticmethod(ContextMenuSeparator.create)
|
||||
checkbox = staticmethod(ContextMenuCheckbox.create)
|
||||
|
||||
context_menu = ContextMenu()
|
||||
|
@ -140,10 +140,8 @@ class HighLevelRadioGroup(RadixThemesComponent):
|
||||
color_scheme = props.pop("color_scheme", None)
|
||||
default_value = props.pop("default_value", "")
|
||||
|
||||
if (
|
||||
not isinstance(items, (list, Var))
|
||||
or isinstance(items, Var)
|
||||
and not types._issubclass(items._var_type, list)
|
||||
if not isinstance(items, (list, Var)) or (
|
||||
isinstance(items, Var) and not types._issubclass(items._var_type, list)
|
||||
):
|
||||
items_type = type(items) if not isinstance(items, Var) else items._var_type
|
||||
raise TypeError(
|
||||
|
@ -148,7 +148,7 @@ class RadioGroupRoot(RadixThemesComponent):
|
||||
disabled: Whether the radio group is disabled
|
||||
name: The name of the group. Submitted with its owning form as part of a name/value pair.
|
||||
required: Whether the radio group is required
|
||||
on_change: Props to rename Fired when the value of the radio group changes.
|
||||
on_change: Fired when the value of the radio group changes.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
|
@ -12,7 +12,9 @@ from reflex.vars.base import Var
|
||||
from ..base import LiteralAccentColor, RadixThemesComponent
|
||||
|
||||
|
||||
def on_value_change(value: Var[str | List[str]]) -> Tuple[Var[str | List[str]]]:
|
||||
def on_value_change(
|
||||
value: Var[Union[str, List[str]]],
|
||||
) -> Tuple[Var[Union[str, List[str]]]]:
|
||||
"""Handle the on_value_change event.
|
||||
|
||||
Args:
|
||||
|
@ -13,7 +13,9 @@ from reflex.vars.base import Var
|
||||
|
||||
from ..base import RadixThemesComponent
|
||||
|
||||
def on_value_change(value: Var[str | List[str]]) -> Tuple[Var[str | List[str]]]: ...
|
||||
def on_value_change(
|
||||
value: Var[Union[str, List[str]]],
|
||||
) -> Tuple[Var[Union[str, List[str]]]]: ...
|
||||
|
||||
class SegmentedControlRoot(RadixThemesComponent):
|
||||
@overload
|
||||
@ -118,7 +120,10 @@ class SegmentedControlRoot(RadixThemesComponent):
|
||||
custom_attrs: Optional[Dict[str, Union[Var, Any]]] = None,
|
||||
on_blur: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_change: Optional[
|
||||
Union[EventType[[], BASE_STATE], EventType[[str | List[str]], BASE_STATE]]
|
||||
Union[
|
||||
EventType[[], BASE_STATE],
|
||||
EventType[[Union[str, List[str]]], BASE_STATE],
|
||||
]
|
||||
] = None,
|
||||
on_click: Optional[EventType[[], BASE_STATE]] = None,
|
||||
on_context_menu: Optional[EventType[[], BASE_STATE]] = None,
|
||||
|
@ -81,7 +81,7 @@ class SelectRoot(RadixThemesComponent):
|
||||
name: The name of the select control when submitting the form.
|
||||
disabled: When True, prevents the user from interacting with select.
|
||||
required: When True, indicates that the user must select a value before the owning form can be submitted.
|
||||
on_change: Props to rename Fired when the value of the select changes.
|
||||
on_change: Fired when the value of the select changes.
|
||||
on_open_change: Fired when the select is opened or closed.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
@ -732,7 +732,7 @@ class HighLevelSelect(SelectRoot):
|
||||
name: The name of the select control when submitting the form.
|
||||
disabled: When True, prevents the user from interacting with select.
|
||||
required: When True, indicates that the user must select a value before the owning form can be submitted.
|
||||
on_change: Props to rename Fired when the value of the select changes.
|
||||
on_change: Fired when the value of the select changes.
|
||||
on_open_change: Fired when the select is opened or closed.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
@ -912,7 +912,7 @@ class Select(ComponentNamespace):
|
||||
name: The name of the select control when submitting the form.
|
||||
disabled: When True, prevents the user from interacting with select.
|
||||
required: When True, indicates that the user must select a value before the owning form can be submitted.
|
||||
on_change: Props to rename Fired when the value of the select changes.
|
||||
on_change: Fired when the value of the select changes.
|
||||
on_open_change: Fired when the select is opened or closed.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
|
@ -195,7 +195,7 @@ class Slider(RadixThemesComponent):
|
||||
step: The step value of the slider.
|
||||
disabled: Whether the slider is disabled
|
||||
orientation: The orientation of the slider.
|
||||
on_change: Props to rename Fired when the value of the slider changes.
|
||||
on_change: Fired when the value of the slider changes.
|
||||
on_value_commit: Fired when a thumb is released after being dragged.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
|
@ -157,7 +157,7 @@ class Switch(RadixThemesComponent):
|
||||
color_scheme: Override theme color for switch
|
||||
high_contrast: Whether to render the switch with higher contrast color against background
|
||||
radius: Override theme radius for switch: "none" | "small" | "full"
|
||||
on_change: Props to rename Fired when the value of the switch changes
|
||||
on_change: Fired when the value of the switch changes
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
|
@ -72,7 +72,7 @@ class TabsRoot(RadixThemesComponent):
|
||||
orientation: The orientation of the tabs.
|
||||
dir: Reading direction of the tabs.
|
||||
activation_mode: The mode of activation for the tabs. "automatic" will activate the tab when focused. "manual" will activate the tab when clicked.
|
||||
on_change: Props to rename Fired when the value of the tabs changes.
|
||||
on_change: Fired when the value of the tabs changes.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
@ -374,7 +374,7 @@ class Tabs(ComponentNamespace):
|
||||
orientation: The orientation of the tabs.
|
||||
dir: Reading direction of the tabs.
|
||||
activation_mode: The mode of activation for the tabs. "automatic" will activate the tab when focused. "manual" will activate the tab when clicked.
|
||||
on_change: Props to rename Fired when the value of the tabs changes.
|
||||
on_change: Fired when the value of the tabs changes.
|
||||
style: The style of the component.
|
||||
key: A unique key for the component.
|
||||
id: The id for the component.
|
||||
|
@ -41,6 +41,9 @@ class TextArea(RadixThemesComponent, elements.Textarea):
|
||||
# Automatically focuses the textarea when the page loads
|
||||
auto_focus: Var[bool]
|
||||
|
||||
# The default value of the textarea when initially rendered
|
||||
default_value: Var[str]
|
||||
|
||||
# Name part of the textarea to submit in 'dir' and 'name' pair when form is submitted
|
||||
dirname: Var[str]
|
||||
|
||||
|
@ -123,6 +123,7 @@ class TextArea(RadixThemesComponent, elements.Textarea):
|
||||
] = None,
|
||||
auto_complete: Optional[Union[Var[bool], bool]] = None,
|
||||
auto_focus: Optional[Union[Var[bool], bool]] = None,
|
||||
default_value: Optional[Union[Var[str], str]] = None,
|
||||
dirname: Optional[Union[Var[str], str]] = None,
|
||||
disabled: Optional[Union[Var[bool], bool]] = None,
|
||||
form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
@ -217,6 +218,7 @@ class TextArea(RadixThemesComponent, elements.Textarea):
|
||||
radius: The radius of the text area: "none" | "small" | "medium" | "large" | "full"
|
||||
auto_complete: Whether the form control should have autocomplete enabled
|
||||
auto_focus: Automatically focuses the textarea when the page loads
|
||||
default_value: The default value of the textarea when initially rendered
|
||||
dirname: Name part of the textarea to submit in 'dir' and 'name' pair when form is submitted
|
||||
disabled: Disables the textarea
|
||||
form: Associates the textarea with a form (by id)
|
||||
|
@ -9,7 +9,9 @@ from reflex.components.core.breakpoints import Responsive
|
||||
from reflex.components.core.debounce import DebounceInput
|
||||
from reflex.components.el import elements
|
||||
from reflex.event import EventHandler, input_event, key_event
|
||||
from reflex.utils.types import is_optional
|
||||
from reflex.vars.base import Var
|
||||
from reflex.vars.number import ternary_operation
|
||||
|
||||
from ..base import LiteralAccentColor, LiteralRadius, RadixThemesComponent
|
||||
|
||||
@ -67,6 +69,9 @@ class TextFieldRoot(elements.Div, RadixThemesComponent):
|
||||
# Value of the input
|
||||
value: Var[Union[str, int, float]]
|
||||
|
||||
# References a datalist for suggested options
|
||||
list: Var[Union[str, int, bool]]
|
||||
|
||||
# Fired when the value of the textarea changes.
|
||||
on_change: EventHandler[input_event]
|
||||
|
||||
@ -93,6 +98,19 @@ class TextFieldRoot(elements.Div, RadixThemesComponent):
|
||||
Returns:
|
||||
The component.
|
||||
"""
|
||||
value = props.get("value")
|
||||
|
||||
# React expects an empty string(instead of null) for controlled inputs.
|
||||
if value is not None and is_optional(
|
||||
(value_var := Var.create(value))._var_type
|
||||
):
|
||||
props["value"] = ternary_operation(
|
||||
(value_var != Var.create(None)) # pyright: ignore [reportGeneralTypeIssues]
|
||||
& (value_var != Var(_js_expr="undefined")),
|
||||
value,
|
||||
Var.create(""),
|
||||
)
|
||||
|
||||
component = super().create(*children, **props)
|
||||
if props.get("value") is not None and props.get("on_change") is not None:
|
||||
# create a debounced input if the user requests full control to avoid typing jank
|
||||
|
@ -119,6 +119,7 @@ class TextFieldRoot(elements.Div, RadixThemesComponent):
|
||||
required: Optional[Union[Var[bool], bool]] = None,
|
||||
type: Optional[Union[Var[str], str]] = None,
|
||||
value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
|
||||
list: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
auto_capitalize: Optional[
|
||||
Union[Var[Union[bool, int, str]], bool, int, str]
|
||||
@ -206,6 +207,7 @@ class TextFieldRoot(elements.Div, RadixThemesComponent):
|
||||
required: Indicates that the input is required
|
||||
type: Specifies the type of input
|
||||
value: Value of the input
|
||||
list: References a datalist for suggested options
|
||||
on_change: Fired when the value of the textarea changes.
|
||||
on_focus: Fired when the textarea is focused.
|
||||
on_blur: Fired when the textarea is blurred.
|
||||
@ -454,6 +456,7 @@ class TextField(ComponentNamespace):
|
||||
required: Optional[Union[Var[bool], bool]] = None,
|
||||
type: Optional[Union[Var[str], str]] = None,
|
||||
value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
|
||||
list: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
|
||||
auto_capitalize: Optional[
|
||||
Union[Var[Union[bool, int, str]], bool, int, str]
|
||||
@ -541,6 +544,7 @@ class TextField(ComponentNamespace):
|
||||
required: Indicates that the input is required
|
||||
type: Specifies the type of input
|
||||
value: Value of the input
|
||||
list: References a datalist for suggested options
|
||||
on_change: Fired when the value of the textarea changes.
|
||||
on_focus: Fired when the textarea is focused.
|
||||
on_blur: Fired when the textarea is blurred.
|
||||
|
@ -64,7 +64,6 @@ class BaseList(Component, MarkdownComponentMap):
|
||||
|
||||
Returns:
|
||||
The list component.
|
||||
|
||||
"""
|
||||
items = props.pop("items", None)
|
||||
list_style_type = props.pop("list_style_type", "none")
|
||||
@ -114,7 +113,6 @@ class UnorderedList(BaseList, Ul):
|
||||
|
||||
Returns:
|
||||
The list component.
|
||||
|
||||
"""
|
||||
items = props.pop("items", None)
|
||||
list_style_type = props.pop("list_style_type", "disc")
|
||||
@ -144,7 +142,6 @@ class OrderedList(BaseList, Ol):
|
||||
|
||||
Returns:
|
||||
The list component.
|
||||
|
||||
"""
|
||||
items = props.pop("items", None)
|
||||
list_style_type = props.pop("list_style_type", "decimal")
|
||||
@ -168,7 +165,6 @@ class ListItem(Li, MarkdownComponentMap):
|
||||
|
||||
Returns:
|
||||
The list item component.
|
||||
|
||||
"""
|
||||
for child in children:
|
||||
if isinstance(child, Text):
|
||||
|
@ -118,7 +118,6 @@ class BaseList(Component, MarkdownComponentMap):
|
||||
|
||||
Returns:
|
||||
The list component.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@ -252,7 +251,6 @@ class UnorderedList(BaseList, Ul):
|
||||
|
||||
Returns:
|
||||
The list component.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@ -390,7 +388,6 @@ class OrderedList(BaseList, Ol):
|
||||
|
||||
Returns:
|
||||
The list component.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@ -477,7 +474,6 @@ class ListItem(Li, MarkdownComponentMap):
|
||||
|
||||
Returns:
|
||||
The list item component.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@ -571,7 +567,6 @@ class List(ComponentNamespace):
|
||||
|
||||
Returns:
|
||||
The list component.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
|
@ -77,13 +77,14 @@ class Link(RadixThemesComponent, A, MemoizationLeaf, MarkdownComponentMap):
|
||||
Component: The link component
|
||||
"""
|
||||
props.setdefault(":hover", {"color": color("accent", 8)})
|
||||
href = props.get("href")
|
||||
|
||||
is_external = props.pop("is_external", None)
|
||||
|
||||
if is_external is not None:
|
||||
props["target"] = cond(is_external, "_blank", "")
|
||||
|
||||
if props.get("href") is not None:
|
||||
if href is not None:
|
||||
if not len(children):
|
||||
raise ValueError("Link without a child will not display")
|
||||
|
||||
@ -101,6 +102,9 @@ class Link(RadixThemesComponent, A, MemoizationLeaf, MarkdownComponentMap):
|
||||
as_child=True,
|
||||
**props,
|
||||
)
|
||||
else:
|
||||
props["href"] = "#"
|
||||
|
||||
return super().create(*children, **props)
|
||||
|
||||
|
||||
|
@ -416,7 +416,7 @@ class Bar(Cartesian):
|
||||
radius: Var[Union[int, List[int]]]
|
||||
|
||||
# The active bar is shown when a user enters a bar chart and this chart has tooltip. If set to false, no active bar will be drawn. If set to true, active bar will be drawn with the props calculated internally. If passed an object, active bar will be drawn, and the internally calculated props will be merged with the key value pairs of the passed object.
|
||||
# active_bar: Var[Union[bool, Dict[str, Any]]]
|
||||
# active_bar: Var[Union[bool, Dict[str, Any]]] #noqa: ERA001
|
||||
|
||||
# Valid children components
|
||||
_valid_children: List[str] = ["Cell", "LabelList", "ErrorBar"]
|
||||
|
@ -136,7 +136,7 @@ class Radar(Recharts):
|
||||
# Fill color. Default: rx.color("accent", 3)
|
||||
fill: Var[str] = LiteralVar.create(Color("accent", 3))
|
||||
|
||||
# opacity. Default: 0.6
|
||||
# The opacity to fill the chart. Default: 0.6
|
||||
fill_opacity: Var[float] = LiteralVar.create(0.6)
|
||||
|
||||
# The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
|
||||
|
@ -204,7 +204,7 @@ class Radar(Recharts):
|
||||
dot: If false set, dots will not be drawn. Default: True
|
||||
stroke: Stoke color. Default: rx.color("accent", 9)
|
||||
fill: Fill color. Default: rx.color("accent", 3)
|
||||
fill_opacity: opacity. Default: 0.6
|
||||
fill_opacity: The opacity to fill the chart. Default: 0.6
|
||||
legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
|
||||
label: If false set, labels will not be drawn. Default: True
|
||||
is_animation_active: If set false, animation of polygon will be disabled. Default: True in CSR, and False in SSR
|
||||
|
@ -3,7 +3,6 @@
|
||||
from typing import Dict, Literal
|
||||
|
||||
from reflex.components.component import Component, MemoizationLeaf, NoSSRComponent
|
||||
from reflex.utils import console
|
||||
|
||||
|
||||
class Recharts(Component):
|
||||
@ -11,19 +10,8 @@ class Recharts(Component):
|
||||
|
||||
library = "recharts@2.13.0"
|
||||
|
||||
def render(self) -> Dict:
|
||||
"""Render the tag.
|
||||
|
||||
Returns:
|
||||
The rendered tag.
|
||||
"""
|
||||
tag = super().render()
|
||||
if any(p.startswith("css") for p in tag["props"]):
|
||||
console.warn(
|
||||
f"CSS props do not work for {self.__class__.__name__}. Consult docs to style it with its own prop."
|
||||
)
|
||||
tag["props"] = [p for p in tag["props"] if not p.startswith("css")]
|
||||
return tag
|
||||
def _get_style(self) -> Dict:
|
||||
return {"wrapperStyle": self.style}
|
||||
|
||||
|
||||
class RechartsCharts(NoSSRComponent, MemoizationLeaf):
|
||||
|
@ -11,7 +11,6 @@ from reflex.style import Style
|
||||
from reflex.vars.base import Var
|
||||
|
||||
class Recharts(Component):
|
||||
def render(self) -> Dict: ...
|
||||
@overload
|
||||
@classmethod
|
||||
def create( # type: ignore
|
||||
|
@ -15,6 +15,8 @@ from reflex.utils.imports import ImportVar
|
||||
from reflex.utils.serializers import serializer
|
||||
from reflex.vars import VarData
|
||||
from reflex.vars.base import LiteralVar, Var
|
||||
from reflex.vars.function import FunctionVar
|
||||
from reflex.vars.object import ObjectVar
|
||||
|
||||
LiteralPosition = Literal[
|
||||
"top-left",
|
||||
@ -62,7 +64,7 @@ def _toast_callback_signature(toast: Var) -> list[Var]:
|
||||
"""
|
||||
return [
|
||||
Var(
|
||||
_js_expr=f"(() => {{let {{action, cancel, onDismiss, onAutoClose, ...rest}} = {str(toast)}; return rest}})()"
|
||||
_js_expr=f"(() => {{let {{action, cancel, onDismiss, onAutoClose, ...rest}} = {toast!s}; return rest}})()"
|
||||
)
|
||||
]
|
||||
|
||||
@ -96,7 +98,7 @@ class ToastProps(PropsBase, NoExtrasAllowedProps):
|
||||
|
||||
# TODO: fix serialization of icons for toast? (might not be possible yet)
|
||||
# Icon displayed in front of toast's text, aligned vertically.
|
||||
# icon: Optional[Icon] = None
|
||||
# icon: Optional[Icon] = None # noqa: ERA001
|
||||
|
||||
# TODO: fix implementation for action / cancel buttons
|
||||
# Renders a primary button, clicking it will close the toast.
|
||||
@ -232,7 +234,9 @@ class Toaster(Component):
|
||||
return [hook]
|
||||
|
||||
@staticmethod
|
||||
def send_toast(message: str = "", level: str | None = None, **props) -> EventSpec:
|
||||
def send_toast(
|
||||
message: str | Var = "", level: str | None = None, **props
|
||||
) -> EventSpec:
|
||||
"""Send a toast message.
|
||||
|
||||
Args:
|
||||
@ -250,20 +254,27 @@ class Toaster(Component):
|
||||
raise ValueError(
|
||||
"Toaster component must be created before sending a toast. (use `rx.toast.provider()`)"
|
||||
)
|
||||
toast_command = f"{toast_ref}.{level}" if level is not None else toast_ref
|
||||
if message == "" and ("title" not in props or "description" not in props):
|
||||
raise ValueError("Toast message or title or description must be provided.")
|
||||
if props:
|
||||
args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # type: ignore
|
||||
toast = f"{toast_command}(`{message}`, {str(args)})"
|
||||
else:
|
||||
toast = f"{toast_command}(`{message}`)"
|
||||
|
||||
toast_action = Var(_js_expr=toast)
|
||||
return run_script(toast_action)
|
||||
toast_command = (
|
||||
ObjectVar.__getattr__(toast_ref.to(dict), level) if level else toast_ref
|
||||
).to(FunctionVar)
|
||||
|
||||
if isinstance(message, Var):
|
||||
props.setdefault("title", message)
|
||||
message = ""
|
||||
elif message == "" and "title" not in props and "description" not in props:
|
||||
raise ValueError("Toast message or title or description must be provided.")
|
||||
|
||||
if props:
|
||||
args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # pyright: ignore [reportCallIssue, reportGeneralTypeIssues]
|
||||
toast = toast_command.call(message, args)
|
||||
else:
|
||||
toast = toast_command.call(message)
|
||||
|
||||
return run_script(toast)
|
||||
|
||||
@staticmethod
|
||||
def toast_info(message: str = "", **kwargs):
|
||||
def toast_info(message: str | Var = "", **kwargs):
|
||||
"""Display an info toast message.
|
||||
|
||||
Args:
|
||||
@ -276,7 +287,7 @@ class Toaster(Component):
|
||||
return Toaster.send_toast(message, level="info", **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def toast_warning(message: str = "", **kwargs):
|
||||
def toast_warning(message: str | Var = "", **kwargs):
|
||||
"""Display a warning toast message.
|
||||
|
||||
Args:
|
||||
@ -289,7 +300,7 @@ class Toaster(Component):
|
||||
return Toaster.send_toast(message, level="warning", **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def toast_error(message: str = "", **kwargs):
|
||||
def toast_error(message: str | Var = "", **kwargs):
|
||||
"""Display an error toast message.
|
||||
|
||||
Args:
|
||||
@ -302,7 +313,7 @@ class Toaster(Component):
|
||||
return Toaster.send_toast(message, level="error", **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def toast_success(message: str = "", **kwargs):
|
||||
def toast_success(message: str | Var = "", **kwargs):
|
||||
"""Display a success toast message.
|
||||
|
||||
Args:
|
||||
@ -327,7 +338,7 @@ class Toaster(Component):
|
||||
dismiss_var_data = None
|
||||
|
||||
if isinstance(id, Var):
|
||||
dismiss = f"{toast_ref}.dismiss({str(id)})"
|
||||
dismiss = f"{toast_ref}.dismiss({id!s})"
|
||||
dismiss_var_data = id._get_all_var_data()
|
||||
elif isinstance(id, str):
|
||||
dismiss = f"{toast_ref}.dismiss('{id}')"
|
||||
@ -353,9 +364,7 @@ class Toaster(Component):
|
||||
return super().create(*children, **props)
|
||||
|
||||
|
||||
# TODO: figure out why loading toast stay open forever
|
||||
# def toast_loading(message: str, **kwargs):
|
||||
# return _toast(message, level="loading", **kwargs)
|
||||
# TODO: figure out why loading toast stay open forever when using level="loading" in toast()
|
||||
|
||||
|
||||
class ToastNamespace(ComponentNamespace):
|
||||
@ -368,7 +377,6 @@ class ToastNamespace(ComponentNamespace):
|
||||
error = staticmethod(Toaster.toast_error)
|
||||
success = staticmethod(Toaster.toast_success)
|
||||
dismiss = staticmethod(Toaster.toast_dismiss)
|
||||
# loading = staticmethod(toast_loading)
|
||||
__call__ = staticmethod(Toaster.send_toast)
|
||||
|
||||
|
||||
|
@ -59,16 +59,16 @@ class Toaster(Component):
|
||||
def add_hooks(self) -> list[Var | str]: ...
|
||||
@staticmethod
|
||||
def send_toast(
|
||||
message: str = "", level: str | None = None, **props
|
||||
message: str | Var = "", level: str | None = None, **props
|
||||
) -> EventSpec: ...
|
||||
@staticmethod
|
||||
def toast_info(message: str = "", **kwargs): ...
|
||||
def toast_info(message: str | Var = "", **kwargs): ...
|
||||
@staticmethod
|
||||
def toast_warning(message: str = "", **kwargs): ...
|
||||
def toast_warning(message: str | Var = "", **kwargs): ...
|
||||
@staticmethod
|
||||
def toast_error(message: str = "", **kwargs): ...
|
||||
def toast_error(message: str | Var = "", **kwargs): ...
|
||||
@staticmethod
|
||||
def toast_success(message: str = "", **kwargs): ...
|
||||
def toast_success(message: str | Var = "", **kwargs): ...
|
||||
@staticmethod
|
||||
def toast_dismiss(id: Var | str | None = None): ...
|
||||
@overload
|
||||
@ -176,7 +176,7 @@ class ToastNamespace(ComponentNamespace):
|
||||
|
||||
@staticmethod
|
||||
def __call__(
|
||||
message: str = "", level: Optional[str] = None, **props
|
||||
message: Union[str, Var] = "", level: Optional[str] = None, **props
|
||||
) -> "Optional[EventSpec]":
|
||||
"""Send a toast message.
|
||||
|
||||
|
@ -116,7 +116,7 @@ class Editor(NoSSRComponent):
|
||||
# Please refer to the library docs for this.
|
||||
# options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" |
|
||||
# "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it"
|
||||
# default : "en"
|
||||
# default: "en".
|
||||
lang: Var[
|
||||
Union[
|
||||
Literal[
|
||||
@ -172,7 +172,7 @@ class Editor(NoSSRComponent):
|
||||
set_options: Var[Dict]
|
||||
|
||||
# Whether all SunEditor plugins should be loaded.
|
||||
# default: True
|
||||
# default: True.
|
||||
set_all_plugins: Var[bool]
|
||||
|
||||
# Set the content of the editor.
|
||||
@ -191,19 +191,19 @@ class Editor(NoSSRComponent):
|
||||
set_default_style: Var[str]
|
||||
|
||||
# Disable the editor
|
||||
# default: False
|
||||
# default: False.
|
||||
disable: Var[bool]
|
||||
|
||||
# Hide the editor
|
||||
# default: False
|
||||
# default: False.
|
||||
hide: Var[bool]
|
||||
|
||||
# Hide the editor toolbar
|
||||
# default: False
|
||||
# default: False.
|
||||
hide_toolbar: Var[bool]
|
||||
|
||||
# Disable the editor toolbar
|
||||
# default: False
|
||||
# default: False.
|
||||
disable_toolbar: Var[bool]
|
||||
|
||||
# Fired when the editor content changes.
|
||||
|
@ -172,7 +172,7 @@ class Editor(NoSSRComponent):
|
||||
|
||||
Args:
|
||||
set_options(Optional[EditorOptions]): Configuration object to further configure the instance.
|
||||
lang: Language of the editor. Alternatively to a string, a dict of your language can be passed to this prop. Please refer to the library docs for this. options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" | "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it" default : "en"
|
||||
lang: Language of the editor. Alternatively to a string, a dict of your language can be passed to this prop. Please refer to the library docs for this. options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" | "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it" default: "en".
|
||||
name: This is used to set the HTML form name of the editor. This means on HTML form submission, it will be submitted together with contents of the editor by the name provided.
|
||||
default_value: Sets the default value of the editor. This is useful if you don't want the on_change method to be called on render. If you want the on_change method to be called on render please use the set_contents prop
|
||||
width: Sets the width of the editor. px and percentage values are accepted, eg width="100%" or width="500px" default: 100%
|
||||
@ -180,14 +180,14 @@ class Editor(NoSSRComponent):
|
||||
placeholder: Sets the placeholder of the editor.
|
||||
auto_focus: Should the editor receive focus when initialized?
|
||||
set_options: Pass an EditorOptions instance to modify the behaviour of Editor even more.
|
||||
set_all_plugins: Whether all SunEditor plugins should be loaded. default: True
|
||||
set_all_plugins: Whether all SunEditor plugins should be loaded. default: True.
|
||||
set_contents: Set the content of the editor. Note: To set the initial contents of the editor without calling the on_change event, please use the default_value prop. set_contents is used to set the contents of the editor programmatically. You must be aware that, when the set_contents's prop changes, the on_change event is triggered.
|
||||
append_contents: Append editor content
|
||||
set_default_style: Sets the default style of the editor's edit area
|
||||
disable: Disable the editor default: False
|
||||
hide: Hide the editor default: False
|
||||
hide_toolbar: Hide the editor toolbar default: False
|
||||
disable_toolbar: Disable the editor toolbar default: False
|
||||
disable: Disable the editor default: False.
|
||||
hide: Hide the editor default: False.
|
||||
hide_toolbar: Hide the editor toolbar default: False.
|
||||
disable_toolbar: Disable the editor toolbar default: False.
|
||||
on_change: Fired when the editor content changes.
|
||||
on_input: Fired when the something is inputted in the editor.
|
||||
on_blur: Fired when the editor loses focus.
|
||||
|
110
reflex/config.py
110
reflex/config.py
@ -8,7 +8,9 @@ import importlib
|
||||
import inspect
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import urllib.parse
|
||||
from importlib.util import find_spec
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
@ -80,7 +82,7 @@ class DBConfig(Base):
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def postgresql_psycopg2(
|
||||
def postgresql_psycopg(
|
||||
cls,
|
||||
database: str,
|
||||
username: str,
|
||||
@ -88,7 +90,7 @@ class DBConfig(Base):
|
||||
host: str | None = None,
|
||||
port: int | None = 5432,
|
||||
) -> DBConfig:
|
||||
"""Create an instance with postgresql+psycopg2 engine.
|
||||
"""Create an instance with postgresql+psycopg engine.
|
||||
|
||||
Args:
|
||||
database: Database name.
|
||||
@ -101,7 +103,7 @@ class DBConfig(Base):
|
||||
DBConfig instance.
|
||||
"""
|
||||
return cls(
|
||||
engine="postgresql+psycopg2",
|
||||
engine="postgresql+psycopg",
|
||||
username=username,
|
||||
password=password,
|
||||
host=host,
|
||||
@ -452,6 +454,14 @@ class PathExistsFlag:
|
||||
ExistingPath = Annotated[Path, PathExistsFlag]
|
||||
|
||||
|
||||
class PerformanceMode(enum.Enum):
|
||||
"""Performance mode for the app."""
|
||||
|
||||
WARN = "warn"
|
||||
RAISE = "raise"
|
||||
OFF = "off"
|
||||
|
||||
|
||||
class EnvironmentVariables:
|
||||
"""Environment variables class to instantiate environment variables."""
|
||||
|
||||
@ -502,6 +512,9 @@ class EnvironmentVariables:
|
||||
# Whether to print the SQL queries if the log level is INFO or lower.
|
||||
SQLALCHEMY_ECHO: EnvVar[bool] = env_var(False)
|
||||
|
||||
# Whether to check db connections before using them.
|
||||
SQLALCHEMY_POOL_PRE_PING: EnvVar[bool] = env_var(True)
|
||||
|
||||
# Whether to ignore the redis config error. Some redis servers only allow out-of-band configuration.
|
||||
REFLEX_IGNORE_REDIS_CONFIG_ERROR: EnvVar[bool] = env_var(False)
|
||||
|
||||
@ -545,10 +558,23 @@ class EnvironmentVariables:
|
||||
# Where to save screenshots when tests fail.
|
||||
SCREENSHOT_DIR: EnvVar[Optional[Path]] = env_var(None)
|
||||
|
||||
# Whether to check for outdated package versions.
|
||||
REFLEX_CHECK_LATEST_VERSION: EnvVar[bool] = env_var(True)
|
||||
|
||||
# In which performance mode to run the app.
|
||||
REFLEX_PERF_MODE: EnvVar[Optional[PerformanceMode]] = env_var(PerformanceMode.WARN)
|
||||
|
||||
# The maximum size of the reflex state in kilobytes.
|
||||
REFLEX_STATE_SIZE_LIMIT: EnvVar[int] = env_var(1000)
|
||||
|
||||
|
||||
environment = EnvironmentVariables()
|
||||
|
||||
|
||||
# These vars are not logged because they may contain sensitive information.
|
||||
_sensitive_env_vars = {"DB_URL", "ASYNC_DB_URL", "REDIS_URL"}
|
||||
|
||||
|
||||
class Config(Base):
|
||||
"""The config defines runtime settings for the app.
|
||||
|
||||
@ -602,6 +628,9 @@ class Config(Base):
|
||||
# The database url used by rx.Model.
|
||||
db_url: Optional[str] = "sqlite:///reflex.db"
|
||||
|
||||
# The async database url used by rx.Model.
|
||||
async_db_url: Optional[str] = None
|
||||
|
||||
# The redis url
|
||||
redis_url: Optional[str] = None
|
||||
|
||||
@ -633,9 +662,9 @@ class Config(Base):
|
||||
frontend_packages: List[str] = []
|
||||
|
||||
# The hosting service backend URL.
|
||||
cp_backend_url: str = Hosting.CP_BACKEND_URL
|
||||
cp_backend_url: str = Hosting.HOSTING_SERVICE
|
||||
# The hosting service frontend URL.
|
||||
cp_web_url: str = Hosting.CP_WEB_URL
|
||||
cp_web_url: str = Hosting.HOSTING_SERVICE_UI
|
||||
|
||||
# The worker class used in production mode
|
||||
gunicorn_worker_class: str = "uvicorn.workers.UvicornH11Worker"
|
||||
@ -655,6 +684,9 @@ class Config(Base):
|
||||
# Maximum expiration lock time for redis state manager
|
||||
redis_lock_expiration: int = constants.Expiration.LOCK
|
||||
|
||||
# Maximum lock time before warning for redis state manager.
|
||||
redis_lock_warning_threshold: int = constants.Expiration.LOCK_WARNING_THRESHOLD
|
||||
|
||||
# Token expiration time for redis state manager
|
||||
redis_token_expiration: int = constants.Expiration.TOKEN
|
||||
|
||||
@ -729,18 +761,20 @@ class Config(Base):
|
||||
|
||||
# If the env var is set, override the config value.
|
||||
if env_var is not None:
|
||||
if key.upper() != "DB_URL":
|
||||
console.info(
|
||||
f"Overriding config value {key} with env var {key.upper()}={env_var}",
|
||||
dedupe=True,
|
||||
)
|
||||
|
||||
# Interpret the value.
|
||||
value = interpret_env_var_value(env_var, field.outer_type_, field.name)
|
||||
|
||||
# Set the value.
|
||||
updated_values[key] = value
|
||||
|
||||
if key.upper() in _sensitive_env_vars:
|
||||
env_var = "***"
|
||||
|
||||
console.info(
|
||||
f"Overriding config value {key} with env var {key.upper()}={env_var}",
|
||||
dedupe=True,
|
||||
)
|
||||
|
||||
return updated_values
|
||||
|
||||
def get_event_namespace(self) -> str:
|
||||
@ -798,6 +832,27 @@ class Config(Base):
|
||||
self._replace_defaults(**kwargs)
|
||||
|
||||
|
||||
def _get_config() -> Config:
|
||||
"""Get the app config.
|
||||
|
||||
Returns:
|
||||
The app config.
|
||||
"""
|
||||
# only import the module if it exists. If a module spec exists then
|
||||
# the module exists.
|
||||
spec = find_spec(constants.Config.MODULE)
|
||||
if not spec:
|
||||
# we need this condition to ensure that a ModuleNotFound error is not thrown when
|
||||
# running unit/integration tests or during `reflex init`.
|
||||
return Config(app_name="")
|
||||
rxconfig = importlib.import_module(constants.Config.MODULE)
|
||||
return rxconfig.config
|
||||
|
||||
|
||||
# Protect sys.path from concurrent modification
|
||||
_config_lock = threading.RLock()
|
||||
|
||||
|
||||
def get_config(reload: bool = False) -> Config:
|
||||
"""Get the app config.
|
||||
|
||||
@ -807,15 +862,26 @@ def get_config(reload: bool = False) -> Config:
|
||||
Returns:
|
||||
The app config.
|
||||
"""
|
||||
sys.path.insert(0, os.getcwd())
|
||||
# only import the module if it exists. If a module spec exists then
|
||||
# the module exists.
|
||||
spec = importlib.util.find_spec(constants.Config.MODULE) # type: ignore
|
||||
if not spec:
|
||||
# we need this condition to ensure that a ModuleNotFound error is not thrown when
|
||||
# running unit/integration tests.
|
||||
return Config(app_name="")
|
||||
rxconfig = importlib.import_module(constants.Config.MODULE)
|
||||
cached_rxconfig = sys.modules.get(constants.Config.MODULE, None)
|
||||
if cached_rxconfig is not None:
|
||||
if reload:
|
||||
importlib.reload(rxconfig)
|
||||
return rxconfig.config
|
||||
# Remove any cached module when `reload` is requested.
|
||||
del sys.modules[constants.Config.MODULE]
|
||||
else:
|
||||
return cached_rxconfig.config
|
||||
|
||||
with _config_lock:
|
||||
sys_path = sys.path.copy()
|
||||
sys.path.clear()
|
||||
sys.path.append(os.getcwd())
|
||||
try:
|
||||
# Try to import the module with only the current directory in the path.
|
||||
return _get_config()
|
||||
except Exception:
|
||||
# If the module import fails, try to import with the original sys.path.
|
||||
sys.path.extend(sys_path)
|
||||
return _get_config()
|
||||
finally:
|
||||
# Restore the original sys.path.
|
||||
sys.path.clear()
|
||||
sys.path.extend(sys_path)
|
||||
|
@ -97,6 +97,18 @@ class Templates(SimpleNamespace):
|
||||
# The default template
|
||||
DEFAULT = "blank"
|
||||
|
||||
# The AI template
|
||||
AI = "ai"
|
||||
|
||||
# The option for the user to choose a remote template.
|
||||
CHOOSE_TEMPLATES = "choose-templates"
|
||||
|
||||
# The URL to find reflex templates.
|
||||
REFLEX_TEMPLATES_URL = "https://reflex.dev/templates"
|
||||
|
||||
# Demo url for the default template.
|
||||
DEFAULT_TEMPLATE_URL = "https://blank-template.reflex.run"
|
||||
|
||||
# The reflex.build frontend host
|
||||
REFLEX_BUILD_FRONTEND = "https://flexgen.reflex.run"
|
||||
|
||||
|
@ -29,6 +29,8 @@ class Expiration(SimpleNamespace):
|
||||
LOCK = 10000
|
||||
# The PING timeout
|
||||
PING = 120
|
||||
# The maximum time in milliseconds to hold a lock before throwing a warning.
|
||||
LOCK_WARNING_THRESHOLD = 1000
|
||||
|
||||
|
||||
class GitIgnore(SimpleNamespace):
|
||||
|
@ -184,15 +184,15 @@ class PackageJson(SimpleNamespace):
|
||||
"json5": "2.2.3",
|
||||
"next": "14.2.16",
|
||||
"next-sitemap": "4.2.3",
|
||||
"next-themes": "0.3.0",
|
||||
"next-themes": "0.4.3",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1",
|
||||
"react-focus-lock": "2.13.2",
|
||||
"socket.io-client": "4.8.1",
|
||||
"universal-cookie": "7.2.1",
|
||||
"universal-cookie": "7.2.2",
|
||||
}
|
||||
DEV_DEPENDENCIES = {
|
||||
"autoprefixer": "10.4.20",
|
||||
"postcss": "8.4.47",
|
||||
"postcss": "8.4.49",
|
||||
"postcss-import": "16.1.0",
|
||||
}
|
||||
|
@ -7,7 +7,7 @@ class Tailwind(SimpleNamespace):
|
||||
"""Tailwind constants."""
|
||||
|
||||
# The Tailwindcss version
|
||||
VERSION = "tailwindcss@3.4.14"
|
||||
VERSION = "tailwindcss@3.4.15"
|
||||
# The Tailwind config.
|
||||
CONFIG = "tailwind.config.js"
|
||||
# Default Tailwind content paths
|
||||
|
@ -827,11 +827,11 @@ def _collect_details_for_gallery():
|
||||
Raises:
|
||||
Exit: If pyproject.toml file is ill-formed or the request to the backend services fails.
|
||||
"""
|
||||
from reflex.reflex import _login
|
||||
from reflex_cli.utils import hosting
|
||||
|
||||
console.rule("[bold]Authentication with Reflex Services")
|
||||
console.print("First let's log in to Reflex backend services.")
|
||||
access_token = _login()
|
||||
access_token, _ = hosting.authenticated_token()
|
||||
|
||||
console.rule("[bold]Custom Component Information")
|
||||
params = {}
|
||||
|
@ -181,6 +181,18 @@ class EventActionsMixin:
|
||||
event_actions={"debounce": delay_ms, **self.event_actions},
|
||||
)
|
||||
|
||||
@property
|
||||
def temporal(self):
|
||||
"""Do not queue the event if the backend is down.
|
||||
|
||||
Returns:
|
||||
New EventHandler-like with temporal set to True.
|
||||
"""
|
||||
return dataclasses.replace(
|
||||
self,
|
||||
event_actions={"temporal": True, **self.event_actions},
|
||||
)
|
||||
|
||||
|
||||
@dataclasses.dataclass(
|
||||
init=True,
|
||||
@ -435,7 +447,7 @@ class JavascriptHTMLInputElement:
|
||||
class JavascriptInputEvent:
|
||||
"""Interface for a Javascript InputEvent https://developer.mozilla.org/en-US/docs/Web/API/InputEvent."""
|
||||
|
||||
target: JavascriptHTMLInputElement = JavascriptHTMLInputElement()
|
||||
target: JavascriptHTMLInputElement = JavascriptHTMLInputElement() # noqa: RUF009
|
||||
|
||||
|
||||
@dataclasses.dataclass(
|
||||
@ -1243,7 +1255,7 @@ def call_event_handler(
|
||||
except TypeError:
|
||||
# TODO: In 0.7.0, remove this block and raise the exception
|
||||
# raise TypeError(
|
||||
# f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_handler.fn.__qualname__} provided for {key}."
|
||||
# f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_handler.fn.__qualname__} provided for {key}." # noqa: ERA001
|
||||
# ) from e
|
||||
console.warn(
|
||||
f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_callback.fn.__qualname__} provided for {key}."
|
||||
@ -1379,6 +1391,10 @@ def check_fn_match_arg_spec(
|
||||
EventFnArgMismatch: Raised if the number of mandatory arguments do not match
|
||||
"""
|
||||
user_args = inspect.getfullargspec(user_func).args
|
||||
# Drop the first argument if it's a bound method
|
||||
if inspect.ismethod(user_func) and user_func.__self__ is not None:
|
||||
user_args = user_args[1:]
|
||||
|
||||
user_default_args = inspect.getfullargspec(user_func).defaults
|
||||
number_of_user_args = len(user_args) - number_of_bound_args
|
||||
number_of_user_default_args = len(user_default_args) if user_default_args else 0
|
||||
@ -1573,7 +1589,7 @@ class LiteralEventVar(VarOperationCall, LiteralVar, EventVar):
|
||||
Returns:
|
||||
The hash of the var.
|
||||
"""
|
||||
return hash((self.__class__.__name__, self._js_expr))
|
||||
return hash((type(self).__name__, self._js_expr))
|
||||
|
||||
@classmethod
|
||||
def create(
|
||||
@ -1637,7 +1653,7 @@ class LiteralEventChainVar(ArgsFunctionOperationBuilder, LiteralVar, EventChainV
|
||||
Returns:
|
||||
The hash of the var.
|
||||
"""
|
||||
return hash((self.__class__.__name__, self._js_expr))
|
||||
return hash((type(self).__name__, self._js_expr))
|
||||
|
||||
@classmethod
|
||||
def create(
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user