Merge remote-tracking branch 'origin/main' into masenf/proxy

This commit is contained in:
Masen Furer 2024-12-12 10:19:38 -08:00
commit 67b673523c
No known key found for this signature in database
GPG Key ID: B0008AD22B3B3A95
206 changed files with 4410 additions and 1952 deletions

View File

@ -2,7 +2,6 @@
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---

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

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

View File

@ -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 }}

View File

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

View File

@ -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:
@ -50,7 +50,7 @@ jobs:
- run: poetry run uv pip install pyvirtualdisplay pillow pytest-split
- name: Run app harness tests
env:
SCREENSHOT_DIR: /tmp/screenshots
SCREENSHOT_DIR: /tmp/screenshots/${{ matrix.state_manager }}/${{ matrix.python-version }}/${{ matrix.split_index }}
REDIS_URL: ${{ matrix.state_manager == 'redis' && 'redis://localhost:6379' || '' }}
run: |
poetry run playwright install --with-deps

View File

@ -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
@ -162,14 +162,43 @@ jobs:
--python-version "${{ matrix.python-version }}" --commit-sha "${{ github.sha }}"
--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

View File

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

View File

@ -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]

View File

@ -23,9 +23,9 @@
# 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/.cargo/bin/uv
ARG uv=/root/.local/bin/uv
# Install `uv` for faster package boostrapping
ADD --chmod=755 https://astral.sh/uv/install.sh /install.sh
@ -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

View File

@ -2,9 +2,9 @@
# instance of a Reflex app.
# Stage 1: init
FROM python:3.11 as init
FROM python:3.13 as init
ARG uv=/root/.cargo/bin/uv
ARG uv=/root/.local/bin/uv
# Install `uv` for faster package boostrapping
ADD --chmod=755 https://astral.sh/uv/install.sh /install.sh
@ -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

View File

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

View File

@ -0,0 +1,3 @@
.web
!.web/bun.lockb
!.web/package.json

View 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
}

View 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

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

View File

@ -11,4 +11,4 @@ root * /srv
route {
try_files {path} {path}/ /404.html
file_server
}
}

View File

@ -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
@ -38,4 +38,4 @@ EXPOSE $PORT
CMD [ -d alembic ] && reflex db migrate; \
caddy start && \
redis-server --daemonize yes && \
exec reflex run --env prod --backend-only
exec reflex run --env prod --backend-only

View File

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

1055
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[tool.poetry]
name = "reflex"
version = "0.6.5dev1"
version = "0.6.7dev1"
description = "Web apps in pure Python."
license = "Apache-2.0"
authors = [
@ -49,17 +49,18 @@ wrapt = [
{version = ">=1.11.0,<2.0", python = "<3.11"},
]
packaging = ">=23.1,<25.0"
reflex-hosting-cli = ">=0.1.4,<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"
asgiproxy = { version = "==0.1.1", optional = true }
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"
@ -70,7 +71,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"
@ -97,8 +98,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]

View File

@ -8,20 +8,6 @@
{% endfor %}
export const {{component.name}} = memo(({ {{-component.props|join(", ")-}} }) => {
{% if component.name == "CodeBlock" and "language" in component.props %}
if (language) {
(async () => {
try {
const module = await import(`react-syntax-highlighter/dist/cjs/languages/prism/${language}`);
SyntaxHighlighter.registerLanguage(language, module.default);
} catch (error) {
console.error(`Error importing language module for ${language}:`, error);
}
})();
}
{% endif %}
{% for hook in component.hooks %}
{{ hook }}
{% endfor %}

View File

@ -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) => {
if (progressEvent.progress === 1) {
// Chunk may be incomplete, so only report errors when full response is available.
console.log("Error processing chunk", chunk, e);
}
return;
});
});
resp_idx += 1;
} 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 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]);

View File

@ -264,6 +264,7 @@ _MAPPING: dict = {
"experimental": ["_x"],
"admin": ["AdminDash"],
"app": ["App", "UploadFile"],
"assets": ["asset"],
"base": ["Base"],
"components.component": [
"Component",
@ -298,6 +299,7 @@ _MAPPING: dict = {
"components.moment": ["MomentDelta", "moment"],
"config": ["Config", "DBConfig"],
"constants": ["Env"],
"constants.colors": ["Color"],
"event": [
"EventChain",
"EventHandler",
@ -329,7 +331,7 @@ _MAPPING: dict = {
"SessionStorage",
],
"middleware": ["middleware", "Middleware"],
"model": ["session", "Model"],
"model": ["asession", "session", "Model"],
"state": [
"var",
"ComponentState",
@ -338,7 +340,7 @@ _MAPPING: dict = {
],
"istate.wrappers": ["get_state"],
"style": ["Style", "toggle_color_mode"],
"utils.imports": ["ImportVar"],
"utils.imports": ["ImportDict", "ImportVar"],
"utils.serializers": ["serializer"],
"vars": ["Var", "field", "Field"],
}

View File

@ -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
@ -152,6 +153,7 @@ from .components.suneditor import editor as editor
from .config import Config as Config
from .config import DBConfig as DBConfig
from .constants import Env as Env
from .constants.colors import Color as Color
from .event import EventChain as EventChain
from .event import EventHandler as EventHandler
from .event import background as background
@ -184,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
@ -192,6 +195,7 @@ from .state import dynamic as dynamic
from .state import var as var
from .style import Style as Style
from .style import toggle_color_mode as toggle_color_mode
from .utils.imports import ImportDict as ImportDict
from .utils.imports import ImportVar as ImportVar
from .utils.serializers import serializer as serializer
from .vars import Field as Field

View File

@ -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
@ -368,6 +370,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(
@ -472,7 +479,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,
@ -495,17 +502,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)
@ -521,7 +544,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"
)
@ -638,10 +661,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,
@ -842,7 +869,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)
@ -856,10 +883,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)
@ -953,12 +979,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):
@ -971,7 +997,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.
@ -1012,6 +1037,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.
@ -1160,7 +1188,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(
@ -1263,6 +1291,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=format.json_dumps(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
@ -1466,10 +1509,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.
@ -1479,6 +1522,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):
@ -1509,7 +1554,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):
@ -1522,7 +1567,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
View 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}"

View File

@ -130,8 +130,8 @@ class Base(BaseModel): # pyright: ignore [reportUnboundVariable]
Returns:
The value of the field.
"""
if isinstance(key, str) and key in self.__fields__:
if isinstance(key, str):
# Seems like this function signature was wrong all along?
# If the user wants a field that we know of, get it and pass it off to _get_value
key = getattr(self, key)
return getattr(self, key, key)
return key

View File

@ -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]:

View File

@ -2,14 +2,15 @@
from __future__ import annotations
from typing import Dict, List, Tuple
from typing import Dict, Tuple
from reflex.compiler.compiler import _compile_component
from reflex.components.component import Component
from reflex.components.el import div, p
from reflex.event import EventHandler
from reflex.components.datadisplay.logo import svg_logo
from reflex.components.el import a, button, details, div, h2, hr, p, pre, summary
from reflex.event import EventHandler, set_clipboard
from reflex.state import FrontendEventExceptionState
from reflex.vars.base import Var
from reflex.vars.function import ArgsFunctionOperation
def on_error_spec(
@ -40,38 +41,7 @@ class ErrorBoundary(Component):
on_error: EventHandler[on_error_spec]
# Rendered instead of the children when an error is caught.
Fallback_component: Var[Component] = Var(_js_expr="Fallback")._replace(
_var_type=Component
)
def add_custom_code(self) -> List[str]:
"""Add custom Javascript code into the page that contains this component.
Custom code is inserted at module level, after any imports.
Returns:
The custom code to add.
"""
fallback_container = div(
p("Ooops...Unknown Reflex error has occured:"),
p(
Var(_js_expr="error.message"),
color="red",
),
p("Please contact the support."),
)
compiled_fallback = _compile_component(fallback_container)
return [
f"""
function Fallback({{ error, resetErrorBoundary }}) {{
return (
{compiled_fallback}
);
}}
"""
]
fallback_render: Var[Component]
@classmethod
def create(cls, *children, **props):
@ -86,6 +56,99 @@ class ErrorBoundary(Component):
"""
if "on_error" not in props:
props["on_error"] = FrontendEventExceptionState.handle_frontend_exception
if "fallback_render" not in props:
props["fallback_render"] = ArgsFunctionOperation.create(
("event_args",),
Var.create(
div(
div(
div(
h2(
"An error occurred while rendering this page.",
font_size="1.25rem",
font_weight="bold",
),
p(
"This is an error with the application itself.",
opacity="0.75",
),
details(
summary("Error message", padding="0.5rem"),
div(
div(
pre(
Var(
_js_expr="event_args.error.stack",
),
),
padding="0.5rem",
width="fit-content",
),
width="100%",
max_height="50vh",
overflow="auto",
background="#000",
color="#fff",
border_radius="0.25rem",
),
button(
"Copy",
on_click=set_clipboard(
Var(_js_expr="event_args.error.stack"),
),
padding="0.35rem 0.75rem",
margin="0.5rem",
background="#fff",
color="#000",
border="1px solid #000",
border_radius="0.25rem",
font_weight="bold",
),
),
display="flex",
flex_direction="column",
gap="1rem",
max_width="50ch",
border="1px solid #888888",
border_radius="0.25rem",
padding="1rem",
),
hr(
border_color="currentColor",
opacity="0.25",
),
a(
div(
"Built with ",
svg_logo("currentColor"),
display="flex",
align_items="baseline",
justify_content="center",
font_family="monospace",
gap="0.5rem",
),
href="https://reflex.dev",
),
display="flex",
flex_direction="column",
gap="1rem",
),
height="100%",
width="100%",
position="absolute",
display="flex",
align_items="center",
justify_content="center",
)
),
_var_type=Component,
)
else:
props["fallback_render"] = ArgsFunctionOperation.create(
("event_args",),
props["fallback_render"],
_var_type=Component,
)
return super().create(*children, **props)

View File

@ -3,7 +3,7 @@
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
from typing import Any, Dict, List, Optional, Tuple, Union, overload
from typing import Any, Dict, Optional, Tuple, Union, overload
from reflex.components.component import Component
from reflex.event import BASE_STATE, EventType
@ -15,13 +15,12 @@ def on_error_spec(
) -> Tuple[Var[str], Var[str]]: ...
class ErrorBoundary(Component):
def add_custom_code(self) -> List[str]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
Fallback_component: Optional[Union[Component, Var[Component]]] = None,
fallback_render: Optional[Union[Component, Var[Component]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
@ -57,7 +56,7 @@ class ErrorBoundary(Component):
Args:
*children: The children of the component.
on_error: Fired when the boundary catches an error.
Fallback_component: Rendered instead of the children when an error is caught.
fallback_render: Rendered instead of the children when an error is caught.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.

View File

@ -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.
@ -1904,6 +1921,11 @@ memo = custom_component
class NoSSRComponent(Component):
"""A dynamic component that is not rendered on the server."""
def _get_import_name(self) -> None | str:
if not self.library:
return None
return f"${self.library}" if self.library.startswith("/") else self.library
def _get_imports(self) -> ParsedImportDict:
"""Get the imports for the component.
@ -1917,8 +1939,9 @@ class NoSSRComponent(Component):
_imports = super()._get_imports()
# Do NOT import the main library/tag statically.
if self.library is not None:
_imports[self.library] = [
import_name = self._get_import_name()
if import_name is not None:
_imports[import_name] = [
imports.ImportVar(
tag=None,
render=False,
@ -1936,10 +1959,10 @@ class NoSSRComponent(Component):
opts_fragment = ", { ssr: false });"
# extract the correct import name from library name
if self.library is None:
base_import_name = self._get_import_name()
if base_import_name is None:
raise ValueError("Undefined library for NoSSRComponent")
import_name = format.format_library_name(self.library)
import_name = format.format_library_name(base_import_name)
library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
mod_import = (
@ -2541,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(

View File

@ -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}}}.`,

View File

@ -321,7 +321,7 @@ class ConnectionPulser(Div):
"""Create a connection pulser component.
Args:
access_key: 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.

View File

@ -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)

View File

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

View File

@ -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()

View File

@ -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:
@ -171,6 +171,14 @@ def cond(condition: Any, c1: Any, c2: Any = None) -> Component | Var:
)
@overload
def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... # type: ignore
@overload
def color_mode_cond(light: Any, dark: Any = None) -> Var: ...
def color_mode_cond(light: Any, dark: Any = None) -> Var | Component:
"""Create a component or Prop based on color_mode.

View File

@ -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/"
)

View File

@ -71,7 +71,7 @@ class Html(Div):
Args:
*children: The children of the component.
dangerouslySetInnerHTML: The HTML to render.
access_key: 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.

View File

@ -5,6 +5,7 @@ from __future__ import annotations
from pathlib import Path
from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple
from reflex.components.base.fragment import Fragment
from reflex.components.component import (
Component,
ComponentNamespace,
@ -28,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"
@ -60,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;
}})
"""
@ -86,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()
@ -107,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:
@ -119,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:
@ -181,6 +182,13 @@ class UploadFilesProvider(Component):
tag = "UploadFilesProvider"
class GhostUpload(Fragment):
"""A ghost upload component."""
# Fired when files are dropped.
on_drop: EventHandler[_on_drop_spec]
class Upload(MemoizationLeaf):
"""A file upload component."""
@ -276,8 +284,8 @@ class Upload(MemoizationLeaf):
root_props_unique_name = get_unique_variable_name()
event_var, callback_str = StatefulComponent._get_memoized_event_triggers(
Box.create(on_click=upload_props["on_drop"]) # type: ignore
)["on_click"]
GhostUpload.create(on_drop=upload_props["on_drop"])
)["on_drop"]
upload_props["on_drop"] = event_var
@ -285,13 +293,15 @@ class Upload(MemoizationLeaf):
format.to_camel_case(key): value for key, value in upload_props.items()
}
use_dropzone_arguments = {
"onDrop": event_var,
**upload_props,
}
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(
@ -299,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,

View File

@ -6,6 +6,7 @@
from pathlib import Path
from typing import Any, ClassVar, Dict, List, Optional, Union, overload
from reflex.components.base.fragment import Fragment
from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
from reflex.constants import Dirs
from reflex.event import BASE_STATE, CallableEventSpec, EventSpec, EventType
@ -84,6 +85,56 @@ class UploadFilesProvider(Component):
"""
...
class GhostUpload(Fragment):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
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_click: Optional[EventType[[], BASE_STATE]] = None,
on_context_menu: Optional[EventType[[], BASE_STATE]] = None,
on_double_click: Optional[EventType[[], BASE_STATE]] = None,
on_drop: Optional[
Union[EventType[[], BASE_STATE], EventType[[Any], 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,
) -> "GhostUpload":
"""Create the component.
Args:
*children: The children of the component.
on_drop: Fired when files are dropped.
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: The props of the component.
Returns:
The component.
"""
...
class Upload(MemoizationLeaf):
is_used: ClassVar[bool] = False

View File

@ -8,13 +8,14 @@ from typing import ClassVar, Dict, Literal, Optional, Union
from reflex.components.component import Component, ComponentNamespace
from reflex.components.core.cond import color_mode_cond
from reflex.components.lucide.icon import Icon
from reflex.components.markdown.markdown import _LANGUAGE, MarkdownComponentMap
from reflex.components.radix.themes.components.button import Button
from reflex.components.radix.themes.layout.box import Box
from reflex.constants.colors import Color
from reflex.event import set_clipboard
from reflex.style import Style
from reflex.utils import console, format
from reflex.utils.imports import ImportDict, ImportVar
from reflex.utils.imports import ImportVar
from reflex.vars.base import LiteralVar, Var, VarData
LiteralCodeLanguage = Literal[
@ -378,10 +379,10 @@ for theme_name in dir(Theme):
setattr(Theme, theme_name, getattr(Theme, theme_name)._replace(_var_type=Theme))
class CodeBlock(Component):
class CodeBlock(Component, MarkdownComponentMap):
"""A code block."""
library = "react-syntax-highlighter@15.6.1"
library = "react-syntax-highlighter@15.6.0"
tag = "PrismAsyncLight"
@ -417,39 +418,6 @@ class CodeBlock(Component):
# A custom copy button to override the default one.
copy_button: Optional[Union[bool, Component]] = None
def add_imports(self) -> ImportDict:
"""Add imports for the CodeBlock component.
Returns:
The import dict.
"""
imports_: ImportDict = {}
if (
self.language is not None
and (language_without_quotes := str(self.language).replace('"', ""))
in LiteralCodeLanguage.__args__ # type: ignore
):
imports_[
f"react-syntax-highlighter/dist/cjs/languages/prism/{language_without_quotes}"
] = [
ImportVar(
tag=format.to_camel_case(language_without_quotes),
is_default=True,
install=False,
)
]
return imports_
def _get_custom_code(self) -> Optional[str]:
if (
self.language is not None
and (language_without_quotes := str(self.language).replace('"', ""))
in LiteralCodeLanguage.__args__ # type: ignore
):
return f"{self.alias}.registerLanguage('{language_without_quotes}', {format.to_camel_case(language_without_quotes)})"
@classmethod
def create(
cls,
@ -534,8 +502,8 @@ class CodeBlock(Component):
theme = self.theme
out.add_props(style=theme).remove_props("theme", "code").add_props(
children=self.code
out.add_props(style=theme).remove_props("theme", "code", "language").add_props(
children=self.code, language=_LANGUAGE
)
return out
@ -543,6 +511,46 @@ class CodeBlock(Component):
def _exclude_props(self) -> list[str]:
return ["can_copy", "copy_button"]
@classmethod
def _get_language_registration_hook(cls) -> str:
"""Get the hook to register the language.
Returns:
The hook to register the language.
"""
return f"""
if ({_LANGUAGE!s}) {{
(async () => {{
try {{
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 ${{{_LANGUAGE!s}}}:`, error);
}}
}})();
}}
"""
@classmethod
def get_component_map_custom_code(cls) -> str:
"""Get the custom code for the component.
Returns:
The custom code for the component.
"""
return cls._get_language_registration_hook()
def add_hooks(self) -> list[str | Var]:
"""Add hooks for the component.
Returns:
The hooks for the component.
"""
return [
f"const {_LANGUAGE!s} = {self.language!s}",
self._get_language_registration_hook(),
]
class CodeblockNamespace(ComponentNamespace):
"""Namespace for the CodeBlock component."""

View File

@ -7,10 +7,10 @@ import dataclasses
from typing import Any, ClassVar, Dict, Literal, Optional, Union, overload
from reflex.components.component import Component, ComponentNamespace
from reflex.components.markdown.markdown import MarkdownComponentMap
from reflex.constants.colors import Color
from reflex.event import BASE_STATE, EventType
from reflex.style import Style
from reflex.utils.imports import ImportDict
from reflex.vars.base import Var
LiteralCodeLanguage = Literal[
@ -349,8 +349,7 @@ for theme_name in dir(Theme):
continue
setattr(Theme, theme_name, getattr(Theme, theme_name)._replace(_var_type=Theme))
class CodeBlock(Component):
def add_imports(self) -> ImportDict: ...
class CodeBlock(Component, MarkdownComponentMap):
@overload
@classmethod
def create( # type: ignore
@ -984,6 +983,9 @@ class CodeBlock(Component):
...
def add_style(self): ...
@classmethod
def get_component_map_custom_code(cls) -> str: ...
def add_hooks(self) -> list[str | Var]: ...
class CodeblockNamespace(ComponentNamespace):
themes = Theme

View File

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

View File

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

View File

@ -1,22 +1,23 @@
"""A Reflex logo component."""
from typing import Union
import reflex as rx
def logo(**props):
"""A Reflex logo.
def svg_logo(color: Union[str, rx.Var[str]] = rx.color_mode_cond("#110F1F", "white")):
"""A Reflex logo SVG.
Args:
**props: The props to pass to the component.
color: The color of the logo.
Returns:
The logo component.
The Reflex logo SVG.
"""
def logo_path(d):
return rx.el.svg.path(
d=d,
fill=rx.color_mode_cond("#110F1F", "white"),
)
paths = [
@ -28,18 +29,30 @@ def logo(**props):
"M47.04 4.8799V0.399902H49.28V4.8799H47.04ZM53.76 4.8799V0.399902H56V4.8799H53.76ZM49.28 7.1199V4.8799H53.76V7.1199H49.28ZM47.04 11.5999V7.1199H49.28V11.5999H47.04ZM53.76 11.5999V7.1199H56V11.5999H53.76Z",
]
return rx.el.svg(
*[logo_path(d) for d in paths],
width="56",
height="12",
viewBox="0 0 56 12",
fill=color,
xmlns="http://www.w3.org/2000/svg",
)
def logo(**props):
"""A Reflex logo.
Args:
**props: The props to pass to the component.
Returns:
The logo component.
"""
return rx.center(
rx.link(
rx.hstack(
"Built with ",
rx.el.svg(
*[logo_path(d) for d in paths],
width="56",
height="12",
viewBox="0 0 56 12",
fill="none",
xmlns="http://www.w3.org/2000/svg",
),
svg_logo(),
text_align="center",
align="center",
padding="1em",

View File

@ -12,6 +12,7 @@ from reflex.components.core.colors import color
from reflex.components.core.cond import color_mode_cond
from reflex.components.el.elements.forms import Button
from reflex.components.lucide.icon import Icon
from reflex.components.markdown.markdown import MarkdownComponentMap
from reflex.components.props import NoExtrasAllowedProps
from reflex.components.radix.themes.layout.box import Box
from reflex.event import run_script, set_clipboard
@ -489,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
# },
}
)
@ -528,7 +529,7 @@ class ShikiJsTransformer(ShikiBaseTransformers):
super().__init__(**kwargs)
class ShikiCodeBlock(Component):
class ShikiCodeBlock(Component, MarkdownComponentMap):
"""A Code block."""
library = "/components/shiki/code"

View File

@ -7,6 +7,7 @@ from typing import Any, Dict, Literal, Optional, Union, overload
from reflex.base import Base
from reflex.components.component import Component, ComponentNamespace
from reflex.components.markdown.markdown import MarkdownComponentMap
from reflex.components.props import NoExtrasAllowedProps
from reflex.event import BASE_STATE, EventType
from reflex.style import Style
@ -350,7 +351,7 @@ class ShikiJsTransformer(ShikiBaseTransformers):
fns: list[FunctionStringVar]
style: Optional[Style]
class ShikiCodeBlock(Component):
class ShikiCodeBlock(Component, MarkdownComponentMap):
@overload
@classmethod
def create( # type: ignore

View File

@ -111,9 +111,9 @@ def load_dynamic_serializer():
if line.startswith("import "):
if 'from "$/' in line or 'from "/' in line:
module_code_lines[ix] = (
line.replace("import ", "const ", 1).replace(
" from ", " = window['__reflex'][", 1
)
line.replace("import ", "const ", 1)
.replace(" as ", ": ")
.replace(" from ", " = window['__reflex'][", 1)
+ "]"
)
else:
@ -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,
},
),
),

View File

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

View File

@ -7,6 +7,7 @@ from reflex.utils import lazy_loader
_MAPPING = {
"forms": [
"button",
"datalist",
"fieldset",
"form",
"input",

View File

@ -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",

View File

@ -1,4 +1,4 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
"""Base classes."""
from typing import Union
@ -9,7 +9,7 @@ from reflex.vars.base import Var
class BaseHTML(Element):
"""Base class for common attributes."""
# Provides a hint for generating a keyboard shortcut for the current element.
# Provides a hint for generating a keyboard shortcut for the current element.
access_key: Var[Union[str, int, bool]]
# Controls whether and how text input is automatically capitalized as it is entered/edited by the user.

View File

@ -67,7 +67,7 @@ class BaseHTML(Element):
Args:
*children: The children of the component.
access_key: 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.

View File

@ -1,4 +1,4 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
"""Forms classes."""
from __future__ import annotations
@ -84,7 +84,6 @@ class Datalist(BaseHTML):
"""Display the datalist element."""
tag = "datalist"
# No unique attributes, only common ones are inherited
class Fieldset(Element):
@ -241,16 +240,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 +256,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",
]
@ -400,7 +399,6 @@ class Legend(BaseHTML):
"""Display the legend element."""
tag = "legend"
# No unique attributes, only common ones are inherited
class Meter(BaseHTML):
@ -570,6 +568,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 +650,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 +683,7 @@ class Textarea(BaseHTML):
button = Button.create
datalist = Datalist.create
fieldset = Fieldset.create
form = Form.create
input = Input.create

View File

@ -103,7 +103,7 @@ class Button(BaseHTML):
name: Name of the button, used when sending form data
type: Type of the button (submit, reset, or button)
value: Value of the button, used when sending form data
access_key: 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.
@ -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.
@ -367,7 +367,7 @@ class Form(BaseHTML):
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
on_submit: Fired when the form is submitted
access_key: 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.
@ -554,7 +554,7 @@ class Input(BaseHTML):
on_blur: Fired when the input loses focus
on_key_down: Fired when a key is pressed down
on_key_up: Fired when a key is released
access_key: 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.
@ -644,7 +644,7 @@ class Label(BaseHTML):
*children: The children of the component.
html_for: ID of a form control with which the label is associated
form: Associates the label with a form (by id)
access_key: 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.
@ -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.
@ -830,7 +830,7 @@ class Meter(BaseHTML):
min: Minimum value of the range
optimum: Optimum value in the range
value: Current value of the meter
access_key: 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.
@ -920,7 +920,7 @@ class Optgroup(BaseHTML):
*children: The children of the component.
disabled: Disables the optgroup
label: Label for the optgroup
access_key: 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.
@ -1014,7 +1014,7 @@ class Option(BaseHTML):
label: Label for the option, if the text is not the label
selected: Indicates that the option is initially selected
value: Value to be sent as form data
access_key: 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.
@ -1106,7 +1106,7 @@ class Output(BaseHTML):
html_for: Associates the output with one or more elements (by their IDs)
form: Associates the output with a form (by id)
name: Name of the output element for form submission
access_key: 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.
@ -1198,7 +1198,7 @@ class Progress(BaseHTML):
form: Associates the progress element with a form (by id)
max: Maximum value of the progress indicator
value: Current value of the progress indicator
access_key: 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.
@ -1306,7 +1306,7 @@ class Select(BaseHTML):
required: Indicates that the select control must have a selected option
size: Number of visible options in a drop-down list
on_change: Fired when the select value changes
access_key: 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)
@ -1457,7 +1459,7 @@ class Textarea(BaseHTML):
on_blur: Fired when the input loses focus
on_key_down: Fired when a key is pressed down
on_key_up: Fired when a key is released
access_key: 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.
@ -1490,6 +1492,7 @@ class Textarea(BaseHTML):
...
button = Button.create
datalist = Datalist.create
fieldset = Fieldset.create
form = Form.create
input = Input.create

View File

@ -1,4 +1,4 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
"""Inline classes."""
from typing import Union

View File

@ -88,7 +88,7 @@ class A(BaseHTML):
rel: Specifies the relationship between the linked document and the current document
shape: Specifies the shape of the area
target: Specifies where to open the linked document
access_key: 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.
@ -174,7 +174,7 @@ class Abbr(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -260,7 +260,7 @@ class B(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -346,7 +346,7 @@ class Bdi(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -432,7 +432,7 @@ class Bdo(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -518,7 +518,7 @@ class Br(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -604,7 +604,7 @@ class Cite(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -690,7 +690,7 @@ class Code(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -778,7 +778,7 @@ class Data(BaseHTML):
Args:
*children: The children of the component.
value: Specifies the machine-readable translation of the data element.
access_key: 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.
@ -864,7 +864,7 @@ class Dfn(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -950,7 +950,7 @@ class Em(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1036,7 +1036,7 @@ class I(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1122,7 +1122,7 @@ class Kbd(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1208,7 +1208,7 @@ class Mark(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1296,7 +1296,7 @@ class Q(BaseHTML):
Args:
*children: The children of the component.
cite: Specifies the source URL of the quote.
access_key: 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.
@ -1382,7 +1382,7 @@ class Rp(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1468,7 +1468,7 @@ class Rt(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1554,7 +1554,7 @@ class Ruby(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1640,7 +1640,7 @@ class S(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1726,7 +1726,7 @@ class Samp(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1812,7 +1812,7 @@ class Small(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1898,7 +1898,7 @@ class Span(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1984,7 +1984,7 @@ class Strong(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -2070,7 +2070,7 @@ class Sub(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -2156,7 +2156,7 @@ class Sup(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -2244,7 +2244,7 @@ class Time(BaseHTML):
Args:
*children: The children of the component.
date_time: Specifies the date and/or time of the element.
access_key: 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.
@ -2330,7 +2330,7 @@ class U(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -2416,7 +2416,7 @@ class Wbr(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.

View File

@ -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):

View File

@ -94,7 +94,7 @@ class Area(BaseHTML):
rel: Specifies the relationship of the target object to the link object
shape: Defines the shape of the area (rectangle, circle, polygon)
target: Specifies where to open the linked document
access_key: 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.
@ -198,7 +198,7 @@ class Audio(BaseHTML):
muted: Indicates whether the audio is muted by default
preload: Specifies how the audio file should be preloaded
src: URL of the audio to play
access_key: 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.
@ -314,7 +314,7 @@ class Img(BaseHTML):
src: URL of the image to display
src_set: A set of source sizes and URLs for responsive images
use_map: The name of the map to use with the image
access_key: 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.
@ -340,7 +340,6 @@ class Img(BaseHTML):
Returns:
The component.
"""
...
@ -403,7 +402,7 @@ class Map(BaseHTML):
Args:
*children: The children of the component.
name: Name of the map, referenced by the 'usemap' attribute in 'img' and 'object' elements
access_key: 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.
@ -499,7 +498,7 @@ class Track(BaseHTML):
label: Title of the text track, used by the browser when listing available text tracks
src: URL of the track file
src_lang: Language of the track text data
access_key: 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.
@ -609,7 +608,7 @@ class Video(BaseHTML):
poster: URL of an image to show while the video is downloading, or until the user hits the play button
preload: Specifies how the video file should be preloaded
src: URL of the video to play
access_key: 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.
@ -699,7 +698,7 @@ class Embed(BaseHTML):
*children: The children of the component.
src: URL of the embedded content
type: Media type of the embedded content
access_key: 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.
@ -805,7 +804,7 @@ class Iframe(BaseHTML):
sandbox: Security restrictions for the content in the iframe
src: URL of the document to display in the iframe
src_doc: HTML content to embed directly within the iframe
access_key: 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.
@ -901,7 +900,7 @@ class Object(BaseHTML):
name: Name of the object, used for scripting or as a target for forms and links
type: Media type of the data specified in the data attribute
use_map: Name of an image map to use with the object
access_key: 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.
@ -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.
@ -1169,7 +1168,7 @@ class Source(BaseHTML):
src: URL of the media file or an image for the element to use
src_set: A set of source sizes and URLs for responsive images
type: Media type of the source
access_key: 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.
@ -1261,7 +1260,7 @@ class Svg(BaseHTML):
width: The width of the svg.
height: The height of the svg.
xmlns: The XML namespace declaration.
access_key: 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.
@ -1361,7 +1360,7 @@ class Text(BaseHTML):
rotate: Rotates orientation of each individual glyph.
length_adjust: How the text is stretched or compressed to fit the width defined by the text_length attribute.
text_length: A width that the text should be scaled to fit.
access_key: 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.
@ -1457,7 +1456,7 @@ class Line(BaseHTML):
y1: The y-axis coordinate of the line starting point.
y2: The y-axis coordinate of the the line ending point.
path_length: The total path length, in user units.
access_key: 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.
@ -1551,7 +1550,7 @@ class Circle(BaseHTML):
cy: The y-axis coordinate of the center of the circle.
r: The radius of the circle.
path_length: The total length for the circle's circumference, in user units.
access_key: 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.
@ -1647,7 +1646,7 @@ class Ellipse(BaseHTML):
rx: The radius of the ellipse on the x axis.
ry: The radius of the ellipse on the y axis.
path_length: The total length for the ellipse's circumference, in user units.
access_key: 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.
@ -1747,7 +1746,7 @@ class Rect(BaseHTML):
rx: The horizontal corner radius of the rect. Defaults to ry if it is specified.
ry: The vertical corner radius of the rect. Defaults to rx if it is specified.
path_length: The total length of the rectangle's perimeter, in user units.
access_key: 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.
@ -1837,7 +1836,7 @@ class Polygon(BaseHTML):
*children: The children of the component.
points: defines the list of points (pairs of x,y absolute coordinates) required to draw the polygon.
path_length: This prop lets specify the total length for the path, in user units.
access_key: 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.
@ -1923,7 +1922,7 @@ class Defs(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -2023,7 +2022,7 @@ class LinearGradient(BaseHTML):
x2: X coordinate of the ending point of the gradient.
y1: Y coordinate of the starting point of the gradient.
y2: Y coordinate of the ending point of the gradient.
access_key: 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.
@ -2127,7 +2126,7 @@ class RadialGradient(BaseHTML):
gradient_transform: Transform applied to the gradient.
r: The radius of the end circle of the radial gradient.
spread_method: Method used to spread the gradient.
access_key: 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.
@ -2223,7 +2222,7 @@ class Stop(BaseHTML):
offset: Offset of the gradient stop.
stop_color: Color of the gradient stop.
stop_opacity: Opacity of the gradient stop.
access_key: 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.
@ -2311,7 +2310,7 @@ class Path(BaseHTML):
Args:
*children: The children of the component.
d: Defines the shape of the path.
access_key: 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.
@ -2413,7 +2412,7 @@ class SVG(ComponentNamespace):
width: The width of the svg.
height: The height of the svg.
xmlns: The XML namespace declaration.
access_key: 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.

View File

@ -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"

View File

@ -71,7 +71,7 @@ class Base(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -157,7 +157,7 @@ class Head(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -265,7 +265,7 @@ class Link(BaseHTML):
rel: Specifies the relationship between the current document and the linked one
sizes: Specifies the sizes of icons for visual media
type: Specifies the MIME type of the linked document
access_key: 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.
@ -359,7 +359,7 @@ class Meta(BaseHTML):
content: Defines the content of the metadata
http_equiv: Provides an HTTP header for the information/value of the content attribute
name: Specifies a name for the metadata
access_key: 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.

View File

@ -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):

View File

@ -70,7 +70,7 @@ class Details(BaseHTML):
Args:
*children: The children of the component.
open: Indicates whether the details will be visible (expanded) to the user
access_key: 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.
@ -158,7 +158,7 @@ class Dialog(BaseHTML):
Args:
*children: The children of the component.
open: Indicates whether the dialog is active and can be interacted with
access_key: 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.
@ -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.
@ -590,7 +590,7 @@ class Html(BaseHTML):
Args:
*children: The children of the component.
manifest: Specifies the URL of the document's cache manifest (obsolete in HTML5)
access_key: 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.

View File

@ -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):

View File

@ -68,7 +68,7 @@ class Canvas(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -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.
@ -262,7 +262,7 @@ class Script(BaseHTML):
referrer_policy: Specifies which referrer information to send when fetching the script
src: URL of an external script
type: Specifies the MIME type of the script
access_key: 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.

View File

@ -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"

View File

@ -68,7 +68,7 @@ class Body(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -154,7 +154,7 @@ class Address(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -240,7 +240,7 @@ class Article(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -326,7 +326,7 @@ class Aside(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -412,7 +412,7 @@ class Footer(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -498,7 +498,7 @@ class Header(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -584,7 +584,7 @@ class H1(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -670,7 +670,7 @@ class H2(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -756,7 +756,7 @@ class H3(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -842,7 +842,7 @@ class H4(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -928,7 +928,7 @@ class H5(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1014,7 +1014,7 @@ class H6(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1100,7 +1100,7 @@ class Main(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1186,7 +1186,7 @@ class Nav(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1272,7 +1272,7 @@ class Section(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.

View File

@ -1,4 +1,4 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
"""Tables classes."""
from typing import Union

View File

@ -70,7 +70,7 @@ class Caption(BaseHTML):
Args:
*children: The children of the component.
align: Alignment of the caption
access_key: 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.
@ -160,7 +160,7 @@ class Col(BaseHTML):
*children: The children of the component.
align: Alignment of the content within the column
span: Number of columns the col element spans
access_key: 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.
@ -250,7 +250,7 @@ class Colgroup(BaseHTML):
*children: The children of the component.
align: Alignment of the content within the column group
span: Number of columns the colgroup element spans
access_key: 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.
@ -340,7 +340,7 @@ class Table(BaseHTML):
*children: The children of the component.
align: Alignment of the table
summary: Provides a summary of the table's purpose and structure
access_key: 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.
@ -428,7 +428,7 @@ class Tbody(BaseHTML):
Args:
*children: The children of the component.
align: Alignment of the content within the table body
access_key: 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.
@ -522,7 +522,7 @@ class Td(BaseHTML):
col_span: Number of columns a cell should span
headers: IDs of the headers associated with this cell
row_span: Number of rows a cell should span
access_key: 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.
@ -610,7 +610,7 @@ class Tfoot(BaseHTML):
Args:
*children: The children of the component.
align: Alignment of the content within the table footer
access_key: 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.
@ -706,7 +706,7 @@ class Th(BaseHTML):
headers: IDs of the headers associated with this header cell
row_span: Number of rows a header cell should span
scope: Scope of the header cell (row, col, rowgroup, colgroup)
access_key: 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.
@ -794,7 +794,7 @@ class Thead(BaseHTML):
Args:
*children: The children of the component.
align: Alignment of the content within the table header
access_key: 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.
@ -882,7 +882,7 @@ class Tr(BaseHTML):
Args:
*children: The children of the component.
align: Alignment of the content within the table row
access_key: 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.

View File

@ -1,4 +1,4 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
"""Typography classes."""
from typing import Union

View File

@ -70,7 +70,7 @@ class Blockquote(BaseHTML):
Args:
*children: The children of the component.
cite: Define the title of a work.
access_key: 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.
@ -156,7 +156,7 @@ class Dd(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -242,7 +242,7 @@ class Div(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -328,7 +328,7 @@ class Dl(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -414,7 +414,7 @@ class Dt(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -500,7 +500,7 @@ class Figcaption(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -588,7 +588,7 @@ class Hr(BaseHTML):
Args:
*children: The children of the component.
align: Used to specify the alignment of text content of The Element. this attribute is used in all elements.
access_key: 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.
@ -674,7 +674,7 @@ class Li(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -762,7 +762,7 @@ class Menu(BaseHTML):
Args:
*children: The children of the component.
type: Specifies that the menu element is a context menu.
access_key: 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.
@ -854,7 +854,7 @@ class Ol(BaseHTML):
reversed: Reverses the order of the list.
start: Specifies the start value of the first list item in an ordered list.
type: Specifies the kind of marker to use in the list (letters or numbers).
access_key: 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.
@ -940,7 +940,7 @@ class P(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1026,7 +1026,7 @@ class Pre(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1112,7 +1112,7 @@ class Ul(BaseHTML):
Args:
*children: The children of the component.
access_key: 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.
@ -1202,7 +1202,7 @@ class Ins(BaseHTML):
*children: The children of the component.
cite: Specifies the URL of the document that explains the reason why the text was inserted/changed.
date_time: Specifies the date and time of when the text was inserted/changed.
access_key: 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.
@ -1292,7 +1292,7 @@ class Del(BaseHTML):
*children: The children of the component.
cite: Specifies the URL of the document that explains the reason why the text was deleted.
date_time: Specifies the date and time of when the text was deleted.
access_key: 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.

View File

@ -2,25 +2,18 @@
from __future__ import annotations
import dataclasses
import textwrap
from functools import lru_cache
from hashlib import md5
from typing import Any, Callable, Dict, Union
from typing import Any, Callable, Dict, Sequence, Union
from reflex.components.component import Component, CustomComponent
from reflex.components.radix.themes.layout.list import (
ListItem,
OrderedList,
UnorderedList,
)
from reflex.components.radix.themes.typography.heading import Heading
from reflex.components.radix.themes.typography.link import Link
from reflex.components.radix.themes.typography.text import Text
from reflex.components.tags.tag import Tag
from reflex.utils import types
from reflex.utils.imports import ImportDict, ImportVar
from reflex.vars.base import LiteralVar, Var
from reflex.vars.function import ARRAY_ISARRAY
from reflex.vars.function import ARRAY_ISARRAY, ArgsFunctionOperation, DestructuredArg
from reflex.vars.number import ternary_operation
# Special vars used in the component map.
@ -28,6 +21,7 @@ _CHILDREN = Var(_js_expr="children", _var_type=str)
_PROPS = Var(_js_expr="...props")
_PROPS_IN_TAG = Var(_js_expr="{...props}")
_MOCK_ARG = Var(_js_expr="", _var_type=str)
_LANGUAGE = Var(_js_expr="_language", _var_type=str)
# Special remark plugins.
_REMARK_MATH = Var(_js_expr="remarkMath")
@ -53,7 +47,15 @@ def get_base_component_map() -> dict[str, Callable]:
The base component map.
"""
from reflex.components.datadisplay.code import CodeBlock
from reflex.components.radix.themes.layout.list import (
ListItem,
OrderedList,
UnorderedList,
)
from reflex.components.radix.themes.typography.code import Code
from reflex.components.radix.themes.typography.heading import Heading
from reflex.components.radix.themes.typography.link import Link
from reflex.components.radix.themes.typography.text import Text
return {
"h1": lambda value: Heading.create(value, as_="h1", size="6", margin_y="0.5em"),
@ -74,6 +76,67 @@ def get_base_component_map() -> dict[str, Callable]:
}
@dataclasses.dataclass()
class MarkdownComponentMap:
"""Mixin class for handling custom component maps in Markdown components."""
_explicit_return: bool = dataclasses.field(default=False)
@classmethod
def get_component_map_custom_code(cls) -> str:
"""Get the custom code for the component map.
Returns:
The custom code for the component map.
"""
return ""
@classmethod
def create_map_fn_var(
cls,
fn_body: Var | None = None,
fn_args: Sequence[str] | None = None,
explicit_return: bool | None = None,
) -> Var:
"""Create a function Var for the component map.
Args:
fn_body: The formatted component as a string.
fn_args: The function arguments.
explicit_return: Whether to use explicit return syntax.
Returns:
The function Var for the component map.
"""
fn_args = fn_args or cls.get_fn_args()
fn_body = fn_body if fn_body is not None else cls.get_fn_body()
explicit_return = explicit_return or cls._explicit_return
return ArgsFunctionOperation.create(
args_names=(DestructuredArg(fields=tuple(fn_args)),),
return_expr=fn_body,
explicit_return=explicit_return,
)
@classmethod
def get_fn_args(cls) -> Sequence[str]:
"""Get the function arguments for the component map.
Returns:
The function arguments as a list of strings.
"""
return ["node", _CHILDREN._js_expr, _PROPS._js_expr]
@classmethod
def get_fn_body(cls) -> Var:
"""Get the function body for the component map.
Returns:
The function body as a string.
"""
return Var(_js_expr="undefined", _var_type=None)
class Markdown(Component):
"""A markdown component."""
@ -153,9 +216,6 @@ class Markdown(Component):
Returns:
The imports for the markdown component.
"""
from reflex.components.datadisplay.code import CodeBlock, Theme
from reflex.components.radix.themes.typography.code import Code
return [
{
"": "katex/dist/katex.min.css",
@ -179,10 +239,71 @@ class Markdown(Component):
component(_MOCK_ARG)._get_all_imports() # type: ignore
for component in self.component_map.values()
],
CodeBlock.create(theme=Theme.light)._get_imports(),
Code.create()._get_imports(),
]
def _get_tag_map_fn_var(self, tag: str) -> Var:
return self._get_map_fn_var_from_children(self.get_component(tag), tag)
def format_component_map(self) -> dict[str, Var]:
"""Format the component map for rendering.
Returns:
The formatted component map.
"""
components = {
tag: self._get_tag_map_fn_var(tag)
for tag in self.component_map
if tag not in ("code", "codeblock")
}
# Separate out inline code and code blocks.
components["code"] = self._get_inline_code_fn_var()
return components
def _get_inline_code_fn_var(self) -> Var:
"""Get the function variable for inline code.
This function creates a Var that represents a function to handle
both inline code and code blocks in markdown.
Returns:
The Var for inline code.
"""
# Get any custom code from the codeblock and code components.
custom_code_list = self._get_map_fn_custom_code_from_children(
self.get_component("codeblock")
)
custom_code_list.extend(
self._get_map_fn_custom_code_from_children(self.get_component("code"))
)
codeblock_custom_code = "\n".join(custom_code_list)
# Format the code to handle inline and block code.
formatted_code = f"""
const match = (className || '').match(/language-(?<lang>.*)/);
const {_LANGUAGE!s} = match ? match[1] : '';
{codeblock_custom_code};
return inline ? (
{self.format_component("code")}
) : (
{self.format_component("codeblock", language=_LANGUAGE)}
);
""".replace("\n", " ")
return MarkdownComponentMap.create_map_fn_var(
fn_args=(
"node",
"inline",
"className",
_CHILDREN._js_expr,
_PROPS._js_expr,
),
fn_body=Var(_js_expr=formatted_code),
explicit_return=True,
)
def get_component(self, tag: str, **props) -> Component:
"""Get the component for a tag and props.
@ -219,7 +340,7 @@ class Markdown(Component):
# 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(
@ -239,43 +360,53 @@ class Markdown(Component):
"""
return str(self.get_component(tag, **props)).replace("\n", "")
def format_component_map(self) -> dict[str, Var]:
"""Format the component map for rendering.
def _get_map_fn_var_from_children(self, component: Component, tag: str) -> Var:
"""Create a function Var for the component map for the specified tag.
Args:
component: The component to check for custom code.
tag: The tag of the component.
Returns:
The formatted component map.
The function Var for the component map.
"""
components = {
tag: Var(
_js_expr=f"(({{node, {_CHILDREN._js_expr}, {_PROPS._js_expr}}}) => ({self.format_component(tag)}))"
)
for tag in self.component_map
}
# Separate out inline code and code blocks.
components["code"] = Var(
_js_expr=f"""(({{node, inline, className, {_CHILDREN._js_expr}, {_PROPS._js_expr}}}) => {{
const match = (className || '').match(/language-(?<lang>.*)/);
const language = match ? match[1] : '';
if (language) {{
(async () => {{
try {{
const module = await import(`react-syntax-highlighter/dist/cjs/languages/prism/${{language}}`);
SyntaxHighlighter.registerLanguage(language, module.default);
}} catch (error) {{
console.error(`Error importing language module for ${{language}}:`, error);
}}
}})();
}}
return inline ? (
{self.format_component("code")}
) : (
{self.format_component("codeblock", language=Var(_js_expr="language", _var_type=str))}
);
}})""".replace("\n", " ")
formatted_component = Var(
_js_expr=f"({self.format_component(tag)})", _var_type=str
)
if isinstance(component, MarkdownComponentMap):
return component.create_map_fn_var(fn_body=formatted_component)
return components
# fallback to the default fn Var creation if the component is not a MarkdownComponentMap.
return MarkdownComponentMap.create_map_fn_var(fn_body=formatted_component)
def _get_map_fn_custom_code_from_children(self, component) -> list[str]:
"""Recursively get markdown custom code from children components.
Args:
component: The component to check for custom code.
Returns:
A list of markdown custom code strings.
"""
custom_code_list = []
if isinstance(component, MarkdownComponentMap):
custom_code_list.append(component.get_component_map_custom_code())
# If the component is a custom component(rx.memo), obtain the underlining
# component and get the custom code from the children.
if isinstance(component, CustomComponent):
custom_code_list.extend(
self._get_map_fn_custom_code_from_children(
component.component_fn(*component.get_prop_vars())
)
)
elif isinstance(component, Component):
for child in component.children:
custom_code_list.extend(
self._get_map_fn_custom_code_from_children(child)
)
return custom_code_list
@staticmethod
def _component_map_hash(component_map) -> str:
@ -288,17 +419,17 @@ class Markdown(Component):
return f"ComponentMap_{self.component_map_hash}"
def _get_custom_code(self) -> str | None:
hooks = set()
hooks = {}
for _component in self.component_map.values():
comp = _component(_MOCK_ARG)
hooks.update(comp._get_all_hooks_internal())
hooks.update(comp._get_all_hooks())
formatted_hooks = "\n".join(hooks)
formatted_hooks = "\n".join(hooks.keys())
return f"""
function {self._get_component_map_name()} () {{
{formatted_hooks}
return (
{str(LiteralVar.create(self.format_component_map()))}
{LiteralVar.create(self.format_component_map())!s}
)
}}
"""

View File

@ -3,8 +3,9 @@
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
import dataclasses
from functools import lru_cache
from typing import Any, Callable, Dict, Optional, Union, overload
from typing import Any, Callable, Dict, Optional, Sequence, Union, overload
from reflex.components.component import Component
from reflex.event import BASE_STATE, EventType
@ -16,6 +17,7 @@ _CHILDREN = Var(_js_expr="children", _var_type=str)
_PROPS = Var(_js_expr="...props")
_PROPS_IN_TAG = Var(_js_expr="{...props}")
_MOCK_ARG = Var(_js_expr="", _var_type=str)
_LANGUAGE = Var(_js_expr="_language", _var_type=str)
_REMARK_MATH = Var(_js_expr="remarkMath")
_REMARK_GFM = Var(_js_expr="remarkGfm")
_REMARK_UNWRAP_IMAGES = Var(_js_expr="remarkUnwrapImages")
@ -27,6 +29,21 @@ NO_PROPS_TAGS = ("ul", "ol", "li")
@lru_cache
def get_base_component_map() -> dict[str, Callable]: ...
@dataclasses.dataclass()
class MarkdownComponentMap:
@classmethod
def get_component_map_custom_code(cls) -> str: ...
@classmethod
def create_map_fn_var(
cls,
fn_body: Var | None = None,
fn_args: Sequence[str] | None = None,
explicit_return: bool | None = None,
) -> Var: ...
@classmethod
def get_fn_args(cls) -> Sequence[str]: ...
@classmethod
def get_fn_body(cls) -> Var: ...
class Markdown(Component):
@overload
@ -82,6 +99,6 @@ class Markdown(Component):
...
def add_imports(self) -> ImportDict | list[ImportDict]: ...
def format_component_map(self) -> dict[str, Var]: ...
def get_component(self, tag: str, **props) -> Component: ...
def format_component(self, tag: str, **props) -> str: ...
def format_component_map(self) -> dict[str, Var]: ...

View File

@ -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]

View File

@ -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,

View File

@ -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"]]

View File

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

View File

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

View File

@ -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",

View File

@ -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)

View File

@ -160,7 +160,7 @@ class FormRoot(FormComponent, HTMLForm):
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
on_submit: Fired when the form is submitted
access_key: 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.
@ -636,7 +636,7 @@ class Form(FormRoot):
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
on_submit: Fired when the form is submitted
access_key: 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.
@ -769,7 +769,7 @@ class FormNamespace(ComponentNamespace):
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
on_submit: Fired when the form is submitted
access_key: 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.

View File

@ -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)

View File

@ -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"
@ -112,6 +112,9 @@ class RadixThemesComponent(Component):
library = "@radix-ui/themes@^3.0.0"
# Temporary pin < 3.1.5 until radix-ui/themes#627 is resolved.
library = library + " && <3.1.5"
# "Fake" prop color_scheme is used to avoid shadowing CSS prop "color".
_rename_props: Dict[str, str] = {"colorScheme": "color"}
@ -136,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
@ -265,6 +261,7 @@ class Theme(RadixThemesComponent):
_js_expr="{...theme.styles.global[':root'], ...theme.styles.global.body}"
),
)
tag.remove_props("appearance")
return tag

View File

@ -257,7 +257,7 @@ class ColorModeIconButton(IconButton):
name: Name of the button, used when sending form data
type: Type of the button (submit, reset, or button)
value: Value of the button, used when sending form data
access_key: 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.
@ -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.

View File

@ -194,7 +194,7 @@ class AlertDialogContent(elements.Div, RadixThemesComponent):
on_open_auto_focus: Fired when the dialog is opened.
on_close_auto_focus: Fired when the dialog is closed.
on_escape_key_down: Fired when the escape key is pressed.
access_key: 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.

View File

@ -164,7 +164,7 @@ class Badge(elements.Span, RadixThemesComponent):
color_scheme: Color theme of the badge
high_contrast: Whether to render the badge with higher contrast color against background
radius: Override theme radius for badge: "none" | "small" | "medium" | "large" | "full"
access_key: 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.

View File

@ -196,7 +196,7 @@ class Button(elements.Button, RadixLoadingProp, RadixThemesComponent):
name: Name of the button, used when sending form data
type: Type of the button (submit, reset, or button)
value: Value of the button, used when sending form data
access_key: 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.

View File

@ -162,7 +162,7 @@ class CalloutRoot(elements.Div, RadixThemesComponent):
variant: Variant of button: "soft" | "surface" | "outline"
color_scheme: Override theme color for button
high_contrast: Whether to render the button with higher contrast color against background
access_key: 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.
@ -251,7 +251,7 @@ class CalloutIcon(elements.Div, RadixThemesComponent):
Args:
*children: Child components.
access_key: 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.
@ -340,7 +340,7 @@ class CalloutText(elements.P, RadixThemesComponent):
Args:
*children: Child components.
access_key: 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.
@ -516,7 +516,7 @@ class Callout(CalloutRoot):
variant: Variant of button: "soft" | "surface" | "outline"
color_scheme: Override theme color for button
high_contrast: Whether to render the button with higher contrast color against background
access_key: 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.
@ -694,7 +694,7 @@ class CalloutNamespace(ComponentNamespace):
variant: Variant of button: "soft" | "surface" | "outline"
color_scheme: Override theme color for button
high_contrast: Whether to render the button with higher contrast color against background
access_key: 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.

View File

@ -95,7 +95,7 @@ class Card(elements.Div, RadixThemesComponent):
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
size: Card size: "1" - "5"
variant: Variant of Card: "solid" | "soft" | "outline" | "ghost"
access_key: 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.

View File

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

View File

@ -243,7 +243,7 @@ class DialogContent(elements.Div, RadixThemesComponent):
on_escape_key_down: Fired when the escape key is pressed.
on_pointer_down_outside: Fired when the pointer is down outside the dialog.
on_interact_outside: Fired when the pointer interacts outside the dialog.
access_key: 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.

View File

@ -228,7 +228,7 @@ class HoverCardContent(elements.Div, RadixThemesComponent):
sticky: The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless
hide_when_detached: Whether to hide the content when the trigger becomes fully occluded.
size: Hovercard size "1" - "3"
access_key: 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.

View File

@ -193,7 +193,7 @@ class IconButton(elements.Button, RadixLoadingProp, RadixThemesComponent):
name: Name of the button, used when sending form data
type: Type of the button (submit, reset, or button)
value: Value of the button, used when sending form data
access_key: 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.

View File

@ -166,7 +166,7 @@ class Inset(elements.Div, RadixThemesComponent):
pr: Padding on the right
pb: Padding on the bottom
pl: Padding on the left
access_key: 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.

View File

@ -233,7 +233,7 @@ class PopoverContent(elements.Div, RadixThemesComponent):
on_pointer_down_outside: Fired when the pointer is down outside the dialog.
on_focus_outside: Fired when focus moves outside the dialog.
on_interact_outside: Fired when the pointer interacts outside the dialog.
access_key: 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.

View File

@ -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(

View File

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

View File

@ -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:

Some files were not shown because too many files have changed in this diff Show More