Skip to content

Commit

Permalink
Merge branch 'main' into lendemor/use_custom_bunfig_toml
Browse files Browse the repository at this point in the history
  • Loading branch information
Lendemor committed Nov 5, 2024
2 parents 1749e50 + bb903b6 commit 97b019a
Show file tree
Hide file tree
Showing 124 changed files with 2,885 additions and 1,128 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ You can create a multi-page app by adding more pages.

<div align="center">

📑 [Docs](https://reflex.dev/docs/getting-started/introduction) &nbsp; | &nbsp; 🗞️ [Blog](https://reflex.dev/blog) &nbsp; | &nbsp; 📱 [Component Library](https://reflex.dev/docs/library) &nbsp; | &nbsp; 🖼️ [Gallery](https://reflex.dev/docs/gallery) &nbsp; | &nbsp; 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start) &nbsp;
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) &nbsp; | &nbsp; 🗞️ [Blog](https://reflex.dev/blog) &nbsp; | &nbsp; 📱 [Component Library](https://reflex.dev/docs/library) &nbsp; | &nbsp; 🖼️ [Templates](https://reflex.dev/templates/) &nbsp; | &nbsp; 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start) &nbsp;

</div>

Expand Down
3 changes: 1 addition & 2 deletions benchmarks/benchmark_lighthouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ def get_lighthouse_scores(directory_path: str | Path) -> dict:
try:
for filename in directory_path.iterdir():
if filename.suffix == ".json" and filename.stem != "manifest":
file_path = directory_path / filename
data = json.loads(file_path.read_text())
data = json.loads(filename.read_text())
# Extract scores and add them to the dictionary with the filename as key
scores[data["finalUrl"].replace("http://localhost:3000/", "/")] = {
"performance_score": data["categories"]["performance"]["score"],
Expand Down
12 changes: 4 additions & 8 deletions reflex/.templates/jinja/web/pages/utils.js.jinja2
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,10 @@
{# component: component dictionary #}
{% macro render_tag(component) %}
<{{component.name}} {{- render_props(component.props) }}>
{%- if component.args is not none -%}
{{- render_arg_content(component) }}
{%- else -%}
{{ component.contents }}
{% for child in component.children %}
{{ render(child) }}
{% endfor %}
{%- endif -%}
{{ component.contents }}
{% for child in component.children %}
{{ render(child) }}
{% endfor %}
</{{component.name}}>
{%- endmacro %}

Expand Down
27 changes: 16 additions & 11 deletions reflex/.templates/web/components/shiki/code.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import { useEffect, useState } from "react"
import { codeToHtml} from "shiki"

export function Code ({code, theme, language, transformers, ...divProps}) {
/**
* Code component that uses Shiki to convert code to HTML and render it.
*
* @param code - The code to be highlighted.
* @param theme - The theme to be used for highlighting.
* @param language - The language of the code.
* @param transformers - The transformers to be applied to the code.
* @param decorations - The decorations to be applied to the code.
* @param divProps - Additional properties to be passed to the div element.
* @returns The rendered code block.
*/
export function Code ({code, theme, language, transformers, decorations, ...divProps}) {
const [codeResult, setCodeResult] = useState("")
useEffect(() => {
async function fetchCode() {
let final_code;

if (Array.isArray(code)) {
final_code = code[0];
} else {
final_code = code;
}
const result = await codeToHtml(final_code, {
const result = await codeToHtml(code, {
lang: language,
theme,
transformers
transformers,
decorations
});
setCodeResult(result);
}
fetchCode();
}, [code, language, theme, transformers]
}, [code, language, theme, transformers, decorations]

)
return (
Expand Down
39 changes: 20 additions & 19 deletions reflex/.templates/web/utils/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
} from "$/utils/context.js";
import debounce from "$/utils/helpers/debounce";
import throttle from "$/utils/helpers/throttle";
import * as Babel from "@babel/standalone";

// Endpoint URLs.
const EVENTURL = env.EVENT;
Expand Down Expand Up @@ -139,8 +138,7 @@ export const evalReactComponent = async (component) => {
if (!window.React && window.__reflex) {
window.React = window.__reflex.react;
}
const output = Babel.transform(component, { presets: ["react"] }).code;
const encodedJs = encodeURIComponent(output);
const encodedJs = encodeURIComponent(component);
const dataUri = "data:text/javascript;charset=utf-8," + encodedJs;
const module = await eval(`import(dataUri)`);
return module.default;
Expand Down Expand Up @@ -180,11 +178,6 @@ export const applyEvent = async (event, socket) => {
return false;
}

if (event.name == "_console") {
console.log(event.payload.message);
return false;
}

if (event.name == "_remove_cookie") {
cookies.remove(event.payload.key, { ...event.payload.options });
queueEventIfSocketExists(initialEvents(), socket);
Expand Down Expand Up @@ -215,12 +208,6 @@ export const applyEvent = async (event, socket) => {
return false;
}

if (event.name == "_set_clipboard") {
const content = event.payload.content;
navigator.clipboard.writeText(content);
return false;
}

if (event.name == "_download") {
const a = document.createElement("a");
a.hidden = true;
Expand All @@ -235,11 +222,6 @@ export const applyEvent = async (event, socket) => {
return false;
}

if (event.name == "_alert") {
alert(event.payload.message);
return false;
}

if (event.name == "_set_focus") {
const ref =
event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref;
Expand All @@ -256,6 +238,25 @@ export const applyEvent = async (event, socket) => {
return false;
}

if (event.name == "_call_function") {
try {
const eval_result = event.payload.function();
if (event.payload.callback) {
if (!!eval_result && typeof eval_result.then === "function") {
event.payload.callback(await eval_result);
} else {
event.payload.callback(eval_result);
}
}
} catch (e) {
console.log("_call_function", e);
if (window && window?.onerror) {
window.onerror(e.message, null, null, null, e);
}
}
return false;
}

if (event.name == "_call_script") {
try {
const eval_result = eval(event.payload.javascript_code);
Expand Down
3 changes: 3 additions & 0 deletions reflex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,13 @@
"EventHandler",
"background",
"call_script",
"call_function",
"run_script",
"clear_local_storage",
"clear_session_storage",
"console_log",
"download",
"noop",
"prevent_default",
"redirect",
"remove_cookie",
Expand Down
3 changes: 3 additions & 0 deletions reflex/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -155,17 +155,20 @@ from .constants import Env as Env
from .event import EventChain as EventChain
from .event import EventHandler as EventHandler
from .event import background as background
from .event import call_function as call_function
from .event import call_script as call_script
from .event import clear_local_storage as clear_local_storage
from .event import clear_session_storage as clear_session_storage
from .event import console_log as console_log
from .event import download as download
from .event import event as event
from .event import noop as noop
from .event import prevent_default as prevent_default
from .event import redirect as redirect
from .event import remove_cookie as remove_cookie
from .event import remove_local_storage as remove_local_storage
from .event import remove_session_storage as remove_session_storage
from .event import run_script as run_script
from .event import scroll_to as scroll_to
from .event import set_clipboard as set_clipboard
from .event import set_focus as set_focus
Expand Down
64 changes: 33 additions & 31 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
from reflex import constants
from reflex.admin import AdminDash
from reflex.app_mixins import AppMixin, LifespanMixin, MiddlewareMixin
from reflex.base import Base
from reflex.compiler import compiler
from reflex.compiler import utils as compiler_utils
from reflex.compiler.compiler import (
Expand All @@ -70,7 +69,14 @@
from reflex.components.core.upload import Upload, get_upload_dir
from reflex.components.radix import themes
from reflex.config import environment, get_config
from reflex.event import Event, EventHandler, EventSpec, window_alert
from reflex.event import (
Event,
EventHandler,
EventSpec,
EventType,
IndividualEventType,
window_alert,
)
from reflex.model import Model, get_db_status
from reflex.page import (
DECORATED_PAGES,
Expand Down Expand Up @@ -189,11 +195,12 @@ class UnevaluatedPage:
title: Union[Var, str, None]
description: Union[Var, str, None]
image: str
on_load: Union[EventHandler, EventSpec, List[Union[EventHandler, EventSpec]], None]
on_load: Union[EventType[[]], None]
meta: List[Dict[str, str]]


class App(MiddlewareMixin, LifespanMixin, Base):
@dataclasses.dataclass()
class App(MiddlewareMixin, LifespanMixin):
"""The main Reflex app that encapsulates the backend and frontend.
Every Reflex app needs an app defined in its main module.
Expand All @@ -215,24 +222,26 @@ class App(MiddlewareMixin, LifespanMixin, Base):
"""

# The global [theme](https://reflex.dev/docs/styling/theming/#theme) for the entire app.
theme: Optional[Component] = themes.theme(accent_color="blue")
theme: Optional[Component] = dataclasses.field(
default_factory=lambda: themes.theme(accent_color="blue")
)

# The [global style](https://reflex.dev/docs/styling/overview/#global-styles}) for the app.
style: ComponentStyle = {}
style: ComponentStyle = dataclasses.field(default_factory=dict)

# A list of URLs to [stylesheets](https://reflex.dev/docs/styling/custom-stylesheets/) to include in the app.
stylesheets: List[str] = []
stylesheets: List[str] = dataclasses.field(default_factory=list)

# A component that is present on every page (defaults to the Connection Error banner).
overlay_component: Optional[Union[Component, ComponentCallable]] = (
default_overlay_component()
dataclasses.field(default_factory=default_overlay_component)
)

# Error boundary component to wrap the app with.
error_boundary: Optional[ComponentCallable] = default_error_boundary

# Components to add to the head of every page.
head_components: List[Component] = []
head_components: List[Component] = dataclasses.field(default_factory=list)

# The Socket.IO AsyncServer instance.
sio: Optional[AsyncServer] = None
Expand All @@ -244,10 +253,12 @@ class App(MiddlewareMixin, LifespanMixin, Base):
html_custom_attrs: Optional[Dict[str, str]] = None

# A map from a route to an unevaluated page. PRIVATE.
unevaluated_pages: Dict[str, UnevaluatedPage] = {}
unevaluated_pages: Dict[str, UnevaluatedPage] = dataclasses.field(
default_factory=dict
)

# A map from a page route to the component to render. Users should use `add_page`. PRIVATE.
pages: Dict[str, Component] = {}
pages: Dict[str, Component] = dataclasses.field(default_factory=dict)

# The backend API object. PRIVATE.
api: FastAPI = None # type: ignore
Expand All @@ -259,7 +270,9 @@ class App(MiddlewareMixin, LifespanMixin, Base):
_state_manager: Optional[StateManager] = None

# Mapping from a route to event handlers to trigger when the page loads. PRIVATE.
load_events: Dict[str, List[Union[EventHandler, EventSpec]]] = {}
load_events: Dict[str, List[IndividualEventType[[]]]] = dataclasses.field(
default_factory=dict
)

# Admin dashboard to view and manage the database. PRIVATE.
admin_dash: Optional[AdminDash] = None
Expand All @@ -268,7 +281,7 @@ class App(MiddlewareMixin, LifespanMixin, Base):
event_namespace: Optional[EventNamespace] = None

# Background tasks that are currently running. PRIVATE.
background_tasks: Set[asyncio.Task] = set()
background_tasks: Set[asyncio.Task] = dataclasses.field(default_factory=set)

# Frontend Error Handler Function
frontend_exception_handler: Callable[[Exception], None] = (
Expand All @@ -280,23 +293,14 @@ class App(MiddlewareMixin, LifespanMixin, Base):
[Exception], Union[EventSpec, List[EventSpec], None]
] = default_backend_exception_handler

def __init__(self, **kwargs):
def __post_init__(self):
"""Initialize the app.
Args:
**kwargs: Kwargs to initialize the app with.
Raises:
ValueError: If the event namespace is not provided in the config.
Also, if there are multiple client subclasses of rx.BaseState(Subclasses of rx.BaseState should consist
of the DefaultState and the client app state).
"""
if "connect_error_component" in kwargs:
raise ValueError(
"`connect_error_component` is deprecated, use `overlay_component` instead"
)
super().__init__(**kwargs)

# Special case to allow test cases have multiple subclasses of rx.BaseState.
if not is_testing_env() and BaseState.__subclasses__() != [State]:
# Only rx.State is allowed as Base State subclass.
Expand Down Expand Up @@ -471,9 +475,7 @@ def add_page(
title: str | Var | None = None,
description: str | Var | None = None,
image: str = constants.DefaultPage.IMAGE,
on_load: (
EventHandler | EventSpec | list[EventHandler | EventSpec] | None
) = None,
on_load: EventType[[]] | None = None,
meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
):
"""Add a page to the app.
Expand Down Expand Up @@ -559,7 +561,7 @@ def _compile_page(self, route: str):
self._check_routes_conflict(route)
self.pages[route] = component

def get_load_events(self, route: str) -> list[EventHandler | EventSpec]:
def get_load_events(self, route: str) -> list[IndividualEventType[[]]]:
"""Get the load events for a route.
Args:
Expand Down Expand Up @@ -618,9 +620,7 @@ def add_custom_404_page(
title: str = constants.Page404.TITLE,
image: str = constants.Page404.IMAGE,
description: str = constants.Page404.DESCRIPTION,
on_load: (
EventHandler | EventSpec | list[EventHandler | EventSpec] | None
) = None,
on_load: EventType[[]] | None = None,
meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
):
"""Define a custom 404 page for any url having no match.
Expand Down Expand Up @@ -929,6 +929,8 @@ def get_compilation_time() -> str:
)
compile_results.append((stateful_components_path, stateful_components_code))

progress.advance(task)

# Compile the root document before fork.
compile_results.append(
compiler.compile_document_root(
Expand Down Expand Up @@ -1389,7 +1391,7 @@ async def upload_file(request: Request, files: List[UploadFile]):
if isinstance(func, EventHandler):
if func.is_background:
raise UploadTypeError(
f"@rx.background is not supported for upload handler `{handler}`.",
f"@rx.event(background=True) is not supported for upload handler `{handler}`.",
)
func = func.fn
if isinstance(func, functools.partial):
Expand Down
Loading

0 comments on commit 97b019a

Please sign in to comment.