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

use $ syntax #4237

Merged
merged 7 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions reflex/.templates/jinja/web/pages/_app.js.jinja2
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{% extends "web/pages/base_page.js.jinja2" %}

{% block early_imports %}
import '/styles/styles.css'
import '$/styles/styles.css'
{% endblock %}

{% block declaration %}
import { EventLoopProvider, StateProvider, defaultColorMode } from "/utils/context.js";
import { EventLoopProvider, StateProvider, defaultColorMode } from "$/utils/context.js";
import { ThemeProvider } from 'next-themes'
{% for library_alias, library_path in window_libraries %}
import * as {{library_alias}} from "{{library_path}}";
Expand Down
4 changes: 3 additions & 1 deletion reflex/.templates/jinja/web/utils/context.js.jinja2
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createContext, useContext, useMemo, useReducer, useState } from "react"
import { applyDelta, Event, hydrateClientStorage, useEventLoop, refs } from "/utils/state.js"
import { applyDelta, Event, hydrateClientStorage, useEventLoop, refs } from "$/utils/state.js"

{% if initial_state %}
export const initialState = {{ initial_state|json_dumps }}
Expand Down Expand Up @@ -59,6 +59,8 @@ export const initialEvents = () => [
{% else %}
export const state_name = undefined

export const exception_state_name = undefined

export const onLoadInternalEvent = () => []

export const initialEvents = () => []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import {
ColorModeContext,
defaultColorMode,
isDevMode,
lastCompiledTimeStamp
} from "/utils/context.js";
lastCompiledTimeStamp,
} from "$/utils/context.js";

export default function RadixThemesColorModeProvider({ children }) {
const { theme, resolvedTheme, setTheme } = useTheme();
Expand Down Expand Up @@ -37,7 +37,7 @@ export default function RadixThemesColorModeProvider({ children }) {
const allowedModes = ["light", "dark", "system"];
if (!allowedModes.includes(mode)) {
console.error(
`Invalid color mode "${mode}". Defaulting to "${defaultColorMode}".`,
`Invalid color mode "${mode}". Defaulting to "${defaultColorMode}".`
);
mode = defaultColorMode;
}
Expand Down
3 changes: 2 additions & 1 deletion reflex/.templates/web/jsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$/*": ["*"],
"@/*": ["public/*"]
}
}
}
}
8 changes: 4 additions & 4 deletions reflex/.templates/web/utils/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import axios from "axios";
import io from "socket.io-client";
import JSON5 from "json5";
import env from "/env.json";
import env from "$/env.json";
import Cookies from "universal-cookie";
import { useEffect, useRef, useState } from "react";
import Router, { useRouter } from "next/router";
Expand All @@ -12,9 +12,9 @@ import {
onLoadInternalEvent,
state_name,
exception_state_name,
} from "utils/context.js";
import debounce from "/utils/helpers/debounce";
import throttle from "/utils/helpers/throttle";
} from "$/utils/context.js";
import debounce from "$/utils/helpers/debounce";
import throttle from "$/utils/helpers/throttle";
import * as Babel from "@babel/standalone";

// Endpoint URLs.
Expand Down
2 changes: 1 addition & 1 deletion reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,7 @@ def _get_frontend_packages(self, imports: Dict[str, set[ImportVar]]):
for i, tags in imports.items()
if i not in constants.PackageJson.DEPENDENCIES
and i not in constants.PackageJson.DEV_DEPENDENCIES
and not any(i.startswith(prefix) for prefix in ["/", ".", "next/"])
and not any(i.startswith(prefix) for prefix in ["/", "$/", ".", "next/"])
and i != ""
and any(tag.install for tag in tags)
}
Expand Down
8 changes: 4 additions & 4 deletions reflex/compiler/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ def _compile_app(app_root: Component) -> str:
window_libraries = [
(_normalize_library_name(name), name) for name in bundled_libraries
] + [
("utils_context", f"/{constants.Dirs.UTILS}/context"),
("utils_state", f"/{constants.Dirs.UTILS}/state"),
("utils_context", f"$/{constants.Dirs.UTILS}/context"),
("utils_state", f"$/{constants.Dirs.UTILS}/state"),
]

return templates.APP_ROOT.render(
Expand Down Expand Up @@ -228,7 +228,7 @@ def _compile_components(
"""
imports = {
"react": [ImportVar(tag="memo")],
f"/{constants.Dirs.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 @@ -315,7 +315,7 @@ def get_shared_components_recursive(component: BaseComponent):
# Don't import from the file that we're about to create.
all_imports = utils.merge_imports(*all_import_dicts)
all_imports.pop(
f"/{constants.Dirs.UTILS}/{constants.PageNames.STATEFUL_COMPONENTS}", None
f"$/{constants.Dirs.UTILS}/{constants.PageNames.STATEFUL_COMPONENTS}", None
)

return templates.STATEFUL_COMPONENTS.render(
Expand Down
6 changes: 6 additions & 0 deletions reflex/compiler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ def validate_imports(import_dict: ParsedImportDict):
f"{_import.tag}/{_import.alias}" if _import.alias else _import.tag
)
if import_name in used_tags:
already_imported = used_tags[import_name]
if (already_imported[0] == "$" and already_imported[1:] == lib) or (
lib[0] == "$" and lib[1:] == already_imported
):
used_tags[import_name] = lib if lib[0] == "$" else already_imported
continue
raise ValueError(
f"Can not compile, the tag {import_name} is used multiple time from {lib} and {used_tags[import_name]}"
)
Expand Down
8 changes: 5 additions & 3 deletions reflex/components/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -1308,7 +1308,9 @@ def _get_hooks_imports(self) -> ParsedImportDict:
if self._get_ref_hook():
# Handle hooks needed for attaching react refs to DOM nodes.
_imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
_imports.setdefault(f"/{Dirs.STATE_PATH}", set()).add(ImportVar(tag="refs"))
_imports.setdefault(f"$/{Dirs.STATE_PATH}", set()).add(
ImportVar(tag="refs")
)

if self._get_mount_lifecycle_hook():
# Handle hooks for `on_mount` / `on_unmount`.
Expand Down Expand Up @@ -1665,7 +1667,7 @@ class CustomComponent(Component):
"""A custom user-defined component."""

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

# The function that creates the component.
component_fn: Callable[..., Component] = Component.create
Expand Down Expand Up @@ -2233,7 +2235,7 @@ def _get_all_imports(self) -> ParsedImportDict:
"""
if self.rendered_as_shared:
return {
f"/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
f"$/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
ImportVar(tag=self.tag)
]
}
Expand Down
4 changes: 2 additions & 2 deletions reflex/components/core/banner.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ def create(cls) -> Var:
_js_expr="getBackendURL(env.EVENT).href",
_var_data=VarData(
imports={
"/env.json": [ImportVar(tag="env", is_default=True)],
f"/{Dirs.STATE_PATH}": [ImportVar(tag="getBackendURL")],
"$/env.json": [ImportVar(tag="env", is_default=True)],
f"$/{Dirs.STATE_PATH}": [ImportVar(tag="getBackendURL")],
},
),
_var_type=WebsocketTargetURL,
Expand Down
2 changes: 1 addition & 1 deletion reflex/components/core/client_side_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
class ClientSideRouting(Component):
"""The client-side routing component."""

library = "/utils/client_side_routing"
library = "$/utils/client_side_routing"
tag = "useClientSideRouting"

def add_hooks(self) -> list[str]:
Expand Down
2 changes: 1 addition & 1 deletion reflex/components/core/clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def add_imports(self) -> dict[str, ImportVar]:
The import dict for the component.
"""
return {
"/utils/helpers/paste.js": ImportVar(
"$/utils/helpers/paste.js": ImportVar(
tag="usePasteHandler", is_default=True
),
}
Expand Down
2 changes: 1 addition & 1 deletion reflex/components/core/cond.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from reflex.vars.number import ternary_operation

_IS_TRUE_IMPORT: ImportDict = {
f"/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
f"$/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
}


Expand Down
8 changes: 4 additions & 4 deletions reflex/components/core/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
upload_files_context_var_data: VarData = VarData(
imports={
"react": "useContext",
f"/{Dirs.CONTEXTS_PATH}": "UploadFilesContext",
f"$/{Dirs.CONTEXTS_PATH}": "UploadFilesContext",
},
hooks={
"const [filesById, setFilesById] = useContext(UploadFilesContext);": None,
Expand Down Expand Up @@ -134,8 +134,8 @@ def get_upload_dir() -> Path:
_js_expr="getBackendURL(env.UPLOAD)",
_var_data=VarData(
imports={
f"/{Dirs.STATE_PATH}": "getBackendURL",
"/env.json": ImportVar(tag="env", is_default=True),
f"$/{Dirs.STATE_PATH}": "getBackendURL",
"$/env.json": ImportVar(tag="env", is_default=True),
}
),
).to(str)
Expand Down Expand Up @@ -170,7 +170,7 @@ def _on_drop_spec(files: Var) -> Tuple[Var[Any]]:
class UploadFilesProvider(Component):
"""AppWrap component that provides a dict of selected files by ID via useContext."""

library = f"/{Dirs.CONTEXTS_PATH}"
library = f"$/{Dirs.CONTEXTS_PATH}"
tag = "UploadFilesProvider"


Expand Down
4 changes: 2 additions & 2 deletions reflex/components/core/upload.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ uploaded_files_url_prefix = Var(
_js_expr="getBackendURL(env.UPLOAD)",
_var_data=VarData(
imports={
f"/{Dirs.STATE_PATH}": "getBackendURL",
"/env.json": ImportVar(tag="env", is_default=True),
f"$/{Dirs.STATE_PATH}": "getBackendURL",
"$/env.json": ImportVar(tag="env", is_default=True),
}
),
).to(str)
Expand Down
2 changes: 1 addition & 1 deletion reflex/components/datadisplay/dataeditor.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ def add_imports(self) -> ImportDict:
return {
"": f"{format.format_library_name(self.library)}/dist/index.css",
self.library: "GridCellKind",
"/utils/helpers/dataeditor.js": ImportVar(
"$/utils/helpers/dataeditor.js": ImportVar(
tag="formatDataEditorCells", is_default=False, install=False
),
}
Expand Down
6 changes: 3 additions & 3 deletions reflex/components/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def make_component(component: Component) -> str:
for lib, names in component._get_all_imports().items():
formatted_lib_name = format_library_name(lib)
if (
not lib.startswith((".", "/"))
not lib.startswith((".", "/", "$/"))
and not lib.startswith("http")
and formatted_lib_name not in libs_in_window
):
Expand All @@ -106,7 +106,7 @@ def make_component(component: Component) -> str:
# Rewrite imports from `/` to destructure from window
for ix, line in enumerate(module_code_lines[:]):
if line.startswith("import "):
if 'from "/' in line:
if 'from "$/' in line or 'from "/' in line:
module_code_lines[ix] = (
line.replace("import ", "const ", 1).replace(
" from ", " = window['__reflex'][", 1
Expand Down Expand Up @@ -157,7 +157,7 @@ def evaluate_component(js_string: Var[str]) -> Var[Component]:
merge_var_data=VarData.merge(
VarData(
imports={
f"/{constants.Dirs.STATE_PATH}": [
f"$/{constants.Dirs.STATE_PATH}": [
imports.ImportVar(tag="evalReactComponent"),
],
"react": [
Expand Down
2 changes: 1 addition & 1 deletion reflex/components/el/elements/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def add_imports(self) -> ImportDict:
"""
return {
"react": "useCallback",
f"/{Dirs.STATE_PATH}": ["getRefValue", "getRefValues"],
f"$/{Dirs.STATE_PATH}": ["getRefValue", "getRefValues"],
}

def add_hooks(self) -> list[str]:
Expand Down
4 changes: 2 additions & 2 deletions reflex/components/radix/themes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def add_imports(self) -> ImportDict | list[ImportDict]:
The import dict.
"""
_imports: ImportDict = {
"/utils/theme.js": [ImportVar(tag="theme", is_default=True)],
"$/utils/theme.js": [ImportVar(tag="theme", is_default=True)],
}
if get_config().tailwind is None:
# When tailwind is disabled, import the radix-ui styles directly because they will
Expand Down Expand Up @@ -265,7 +265,7 @@ def add_imports(self) -> dict[str, str]:
class RadixThemesColorModeProvider(Component):
"""Next-themes integration for radix themes components."""

library = "/components/reflex/radix_themes_color_mode_provider.js"
library = "$/components/reflex/radix_themes_color_mode_provider.js"
tag = "RadixThemesColorModeProvider"
is_default = True

Expand Down
2 changes: 1 addition & 1 deletion reflex/components/sonner/toast.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def add_hooks(self) -> list[Var | str]:
_js_expr=f"{toast_ref} = toast",
_var_data=VarData(
imports={
"/utils/state": [ImportVar(tag="refs")],
"$/utils/state": [ImportVar(tag="refs")],
self.library: [ImportVar(tag="toast", install=False)],
}
),
Expand Down
4 changes: 2 additions & 2 deletions reflex/constants/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ class Imports(SimpleNamespace):

EVENTS = {
"react": [ImportVar(tag="useContext")],
f"/{Dirs.CONTEXTS_PATH}": [ImportVar(tag="EventLoopContext")],
f"/{Dirs.STATE_PATH}": [ImportVar(tag=CompileVars.TO_EVENT)],
f"$/{Dirs.CONTEXTS_PATH}": [ImportVar(tag="EventLoopContext")],
f"$/{Dirs.STATE_PATH}": [ImportVar(tag=CompileVars.TO_EVENT)],
}


Expand Down
2 changes: 1 addition & 1 deletion reflex/experimental/client_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@


_refs_import = {
f"/{constants.Dirs.STATE_PATH}": [ImportVar(tag="refs")],
f"$/{constants.Dirs.STATE_PATH}": [ImportVar(tag="refs")],
}


Expand Down
2 changes: 1 addition & 1 deletion reflex/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

# Reference the global ColorModeContext
color_mode_imports = {
f"/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="ColorModeContext")],
f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="ColorModeContext")],
"react": [ImportVar(tag="useContext")],
}

Expand Down
6 changes: 6 additions & 0 deletions reflex/utils/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ def merge_imports(
for lib, fields in (
import_dict if isinstance(import_dict, tuple) else import_dict.items()
):
# If the lib is an absolute path, we need to prefix it with a $
lib = (
"$" + lib
if lib.startswith(("/utils/", "/components/", "/styles/", "/public/"))
else lib
)
if isinstance(fields, (list, tuple, set)):
all_imports[lib].extend(
(
Expand Down
6 changes: 3 additions & 3 deletions reflex/vars/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def from_state(cls, state: Type[BaseState] | str, field_name: str = "") -> VarDa
): None
},
imports={
f"/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
"react": [ImportVar(tag="useContext")],
},
)
Expand Down Expand Up @@ -956,7 +956,7 @@ def as_ref(self) -> Var:
_js_expr="refs",
_var_data=VarData(
imports={
f"/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")]
f"$/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")]
}
),
).to(ObjectVar, Dict[str, str])
Expand Down Expand Up @@ -2530,7 +2530,7 @@ def get_uuid_string_var() -> Var:
unique_uuid_var = get_unique_variable_name()
unique_uuid_var_data = VarData(
imports={
f"/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # type: ignore
f"$/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # type: ignore
"react": "useMemo",
},
hooks={f"const {unique_uuid_var} = useMemo(generateUUID, [])": None},
Expand Down
2 changes: 1 addition & 1 deletion reflex/vars/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,7 @@ def create(cls, value: bool, _var_data: VarData | None = None):


_IS_TRUE_IMPORT: ImportDict = {
f"/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
f"$/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
}


Expand Down
Loading
Loading