Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

code cleanup (split constants into a folder) #1866

Merged
merged 15 commits into from
Sep 29, 2023
46 changes: 24 additions & 22 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,8 @@ def __init__(self, *args, **kwargs):
else config.cors_allowed_origins,
cors_credentials=True,
max_http_buffer_size=constants.POLLING_MAX_HTTP_BUFFER_SIZE,
ping_interval=constants.PING_INTERVAL,
ping_timeout=constants.PING_TIMEOUT,
ping_interval=constants.Ping.INTERVAL,
ping_timeout=constants.Ping.TIMEOUT,
)

# Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
Expand Down Expand Up @@ -340,14 +340,14 @@ def add_page(
self,
component: Component | ComponentCallable,
route: str | None = None,
title: str = constants.DEFAULT_TITLE,
description: str = constants.DEFAULT_DESCRIPTION,
image=constants.DEFAULT_IMAGE,
title: str = constants.DefaultPage.TITLE,
description: str = constants.DefaultPage.DESCRIPTION,
image: str = constants.DefaultPage.IMAGE,
on_load: EventHandler
| EventSpec
| list[EventHandler | EventSpec]
| None = None,
meta: list[dict[str, str]] = constants.DEFAULT_META_LIST,
meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
script_tags: list[Component] | None = None,
):
"""Add a page to the app.
Expand Down Expand Up @@ -433,7 +433,7 @@ def get_load_events(self, route: str) -> list[EventHandler | EventSpec]:
"""
route = route.lstrip("/")
if route == "":
route = constants.INDEX_ROUTE
route = constants.PageNames.INDEX_ROUTE
return self.load_events.get(route, [])

def _check_routes_conflict(self, new_route: str):
Expand Down Expand Up @@ -472,14 +472,14 @@ def _check_routes_conflict(self, new_route: str):
def add_custom_404_page(
self,
component: Component | ComponentCallable | None = None,
title: str = constants.TITLE_404,
image: str = constants.FAVICON_404,
description: str = constants.DESCRIPTION_404,
title: str = constants.Page404.TITLE,
image: str = constants.Page404.IMAGE,
description: str = constants.Page404.DESCRIPTION,
on_load: EventHandler
| EventSpec
| list[EventHandler | EventSpec]
| None = None,
meta: list[dict[str, str]] = constants.DEFAULT_META_LIST,
meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
):
"""Define a custom 404 page for any url having no match.

Expand All @@ -498,10 +498,10 @@ def add_custom_404_page(
component = Default404Page.create()
self.add_page(
component=wait_for_client_redirect(self._generate_component(component)),
route=constants.SLUG_404,
title=title or constants.TITLE_404,
image=image or constants.FAVICON_404,
description=description or constants.DESCRIPTION_404,
route=constants.Page404.SLUG,
title=title or constants.Page404.TITLE,
image=image or constants.Page404.IMAGE,
description=description or constants.Page404.DESCRIPTION,
on_load=on_load,
meta=meta,
)
Expand Down Expand Up @@ -541,11 +541,13 @@ def get_frontend_packages(self, imports: Dict[str, set[ImportVar]]):
page_imports = {
i
for i, tags in imports.items()
if i not in compiler.DEFAULT_IMPORTS.keys()
and i != "focus-visible/dist/focus-visible"
and "next" not in i
and not i.startswith("/")
and not i.startswith(".")
if i
not in [
*compiler.DEFAULT_IMPORTS.keys(),
*constants.PackageJson.DEPENDENCIES.keys(),
*constants.PackageJson.DEV_DEPENDENCIES.keys(),
]
and not any(i.startswith(prefix) for prefix in ["/", ".", "next/"])
and i != ""
and any(tag.install for tag in tags)
}
Expand Down Expand Up @@ -581,7 +583,7 @@ def compile(self):
self.add_page(render, **kwargs)

# Render a default 404 page if the user didn't supply one
if constants.SLUG_404 not in self.pages:
if constants.Page404.SLUG not in self.pages:
self.add_custom_404_page()

task = progress.add_task("Compiling: ", total=len(self.pages))
Expand Down Expand Up @@ -649,7 +651,7 @@ def compile(self):
# Compile the Tailwind config.
if config.tailwind is not None:
config.tailwind["content"] = config.tailwind.get(
"content", constants.TAILWIND_CONTENT
"content", constants.Tailwind.CONTENT
)
compile_results.append(compiler.compile_tailwind(config.tailwind))

Expand Down
18 changes: 9 additions & 9 deletions reflex/compiler/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
ImportVar(tag="useContext"),
},
"next/router": {ImportVar(tag="useRouter")},
f"/{constants.STATE_PATH}": {
f"/{constants.Dirs.STATE_PATH}": {
ImportVar(tag="uploadFiles"),
ImportVar(tag="Event"),
ImportVar(tag="isTrue"),
Expand All @@ -40,9 +40,9 @@
ImportVar(tag="initialEvents"),
ImportVar(tag="StateContext"),
},
"": {ImportVar(tag="focus-visible/dist/focus-visible")},
"": {ImportVar(tag="focus-visible/dist/focus-visible", install=False)},
"@chakra-ui/react": {
ImportVar(tag=constants.USE_COLOR_MODE),
ImportVar(tag=constants.ColorMode.USE),
ImportVar(tag="Box"),
ImportVar(tag="Text"),
},
Expand Down Expand Up @@ -151,15 +151,15 @@ def _compile_root_stylesheet(stylesheets: list[str]) -> str:
"""
# Add tailwind css if enabled.
sheets = (
[constants.TAILWIND_ROOT_STYLE_PATH]
[constants.Tailwind.ROOT_STYLE_PATH]
if get_config().tailwind is not None
else []
)
for stylesheet in stylesheets:
if not utils.is_valid_url(stylesheet):
# check if stylesheet provided exists.
stylesheet_full_path = (
Path.cwd() / constants.APP_ASSETS_DIR / stylesheet.strip("/")
Path.cwd() / constants.Dirs.APP_ASSETS / stylesheet.strip("/")
)
if not os.path.exists(stylesheet_full_path):
raise FileNotFoundError(
Expand Down Expand Up @@ -193,7 +193,7 @@ def _compile_components(components: set[CustomComponent]) -> str:
"""
imports = {
"react": {ImportVar(tag="memo")},
f"/{constants.STATE_PATH}": {ImportVar(tag="E"), ImportVar(tag="isTrue")},
f"/{constants.Dirs.STATE_PATH}": {ImportVar(tag="E"), ImportVar(tag="isTrue")},
}
component_renders = []

Expand Down Expand Up @@ -236,7 +236,7 @@ def compile_document_root(head_components: list[Component]) -> tuple[str, str]:
The path and code of the compiled document root.
"""
# Get the path for the output file.
output_path = utils.get_page_path(constants.DOCUMENT_ROOT)
output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)

# Create the document root.
document_root = utils.create_document_root(head_components)
Expand Down Expand Up @@ -330,7 +330,7 @@ def compile_tailwind(
The compiled Tailwind config.
"""
# Get the path for the output file.
output_path = constants.TAILWIND_CONFIG
output_path = constants.Tailwind.CONFIG

# Compile the config.
code = _compile_tailwind(config)
Expand All @@ -339,4 +339,4 @@ def compile_tailwind(

def purge_web_pages_dir():
"""Empty out .web directory."""
utils.empty_dir(constants.WEB_PAGES_DIR, keep_files=["_app.js"])
utils.empty_dir(constants.Dirs.WEB_PAGES, keep_files=["_app.js"])
32 changes: 16 additions & 16 deletions reflex/compiler/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,26 @@ def __init__(self) -> None:
)
self.filters["json_dumps"] = json_dumps
self.filters["react_setter"] = lambda state: f"set{state.capitalize()}"
self.loader = FileSystemLoader(constants.JINJA_TEMPLATE_DIR)
self.loader = FileSystemLoader(constants.Templates.Dirs.JINJA_TEMPLATE)
self.globals["const"] = {
"socket": constants.SOCKET,
"result": constants.RESULT,
"router": constants.ROUTER,
"socket": constants.CompileVars.SOCKET,
"result": constants.CompileVars.RESULT,
"router": constants.CompileVars.ROUTER,
"event_endpoint": constants.Endpoint.EVENT.name,
"events": constants.EVENTS,
"state": constants.STATE,
"final": constants.FINAL,
"processing": constants.PROCESSING,
"events": constants.CompileVars.EVENTS,
"state": constants.CompileVars.STATE,
"final": constants.CompileVars.FINAL,
"processing": constants.CompileVars.PROCESSING,
"initial_result": {
constants.STATE: None,
constants.EVENTS: [],
constants.FINAL: True,
constants.PROCESSING: False,
constants.CompileVars.STATE: None,
constants.CompileVars.EVENTS: [],
constants.CompileVars.FINAL: True,
constants.CompileVars.PROCESSING: False,
},
"color_mode": constants.COLOR_MODE,
"toggle_color_mode": constants.TOGGLE_COLOR_MODE,
"use_color_mode": constants.USE_COLOR_MODE,
"hydrate": constants.HYDRATE,
"color_mode": constants.ColorMode.NAME,
"toggle_color_mode": constants.ColorMode.TOGGLE,
"use_color_mode": constants.ColorMode.USE,
"hydrate": constants.CompileVars.HYDRATE,
}


Expand Down
22 changes: 11 additions & 11 deletions reflex/compiler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def compile_imports(imports: imports.ImportDict) -> list[dict]:
default, rest = compile_import_statement(fields)

# prevent lib from being rendered on the page if all imports are non rendered kind
if all({not f.render for f in fields}): # type: ignore
if not any({f.render for f in fields}): # type: ignore
continue

if not lib:
Expand All @@ -104,9 +104,7 @@ def compile_imports(imports: imports.ImportDict) -> list[dict]:
continue

# remove the version before rendering the package imports
lib, at, version = lib.rpartition("@")
if not lib:
lib = at + version
lib = format.format_library_name(lib)

import_dicts.append(get_import_dict(lib, default, rest))
return import_dicts
Expand Down Expand Up @@ -313,7 +311,7 @@ def get_page_path(path: str) -> str:
Returns:
The path of the compiled JS file.
"""
return os.path.join(constants.WEB_PAGES_DIR, path + constants.JS_EXT)
return os.path.join(constants.Dirs.WEB_PAGES, path + constants.Ext.JS)


def get_theme_path() -> str:
Expand All @@ -322,7 +320,9 @@ def get_theme_path() -> str:
Returns:
The path of the theme style.
"""
return os.path.join(constants.WEB_UTILS_DIR, constants.THEME + constants.JS_EXT)
return os.path.join(
constants.Dirs.WEB_UTILS, constants.PageNames.THEME + constants.Ext.JS
)


def get_root_stylesheet_path() -> str:
Expand All @@ -332,7 +332,7 @@ def get_root_stylesheet_path() -> str:
The path of the app root file.
"""
return os.path.join(
constants.STYLES_DIR, constants.STYLESHEET_ROOT + constants.CSS_EXT
constants.STYLES_DIR, constants.PageNames.STYLESHEET_ROOT + constants.Ext.CSS
)


Expand All @@ -342,7 +342,7 @@ def get_context_path() -> str:
Returns:
The path of the context module.
"""
return os.path.join(constants.WEB_UTILS_DIR, "context" + constants.JS_EXT)
return os.path.join(constants.Dirs.WEB_UTILS, "context" + constants.Ext.JS)


def get_components_path() -> str:
Expand All @@ -351,7 +351,7 @@ def get_components_path() -> str:
Returns:
The path of the compiled components.
"""
return os.path.join(constants.WEB_UTILS_DIR, "components" + constants.JS_EXT)
return os.path.join(constants.Dirs.WEB_UTILS, "components" + constants.Ext.JS)


def get_asset_path(filename: str | None = None) -> str:
Expand All @@ -364,9 +364,9 @@ def get_asset_path(filename: str | None = None) -> str:
The path of the asset.
"""
if filename is None:
return constants.WEB_ASSETS_DIR
return constants.Dirs.WEB_ASSETS
else:
return os.path.join(constants.WEB_ASSETS_DIR, filename)
return os.path.join(constants.Dirs.WEB_ASSETS, filename)


def add_meta(
Expand Down
5 changes: 2 additions & 3 deletions reflex/components/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@
from functools import wraps
from typing import Any, Callable, Dict, List, Optional, Set, Type, Union

from reflex import constants
from reflex.base import Base
from reflex.components.tags import Tag
from reflex.constants import EventTriggers
from reflex.constants import Dirs, EventTriggers
from reflex.event import (
EventChain,
EventHandler,
Expand Down Expand Up @@ -762,7 +761,7 @@ class CustomComponent(Component):
"""A custom user-defined component."""

# Use the components library.
library = f"/{constants.COMPONENTS_PATH}"
library = f"/{Dirs.COMPONENTS_PATH}"

# The function that creates the component.
component_fn: Callable[..., Component] = Component.create
Expand Down
6 changes: 2 additions & 4 deletions reflex/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ class Config:
telemetry_enabled: bool = True

# The bun path
bun_path: str = constants.DEFAULT_BUN_PATH
bun_path: str = constants.Bun.DEFAULT_PATH

# List of origins that are allowed to connect to the backend API.
cors_allowed_origins: List[str] = ["*"]
Expand Down Expand Up @@ -284,11 +284,9 @@ def get_config(reload: bool = False) -> Config:
Returns:
The app config.
"""
from reflex.config import Config

sys.path.insert(0, os.getcwd())
try:
rxconfig = __import__(constants.CONFIG_MODULE)
rxconfig = __import__(constants.Config.MODULE)
if reload:
importlib.reload(rxconfig)
return rxconfig.config
Expand Down
Loading
Loading