Skip to content

Commit

Permalink
Refacto Page System
Browse files Browse the repository at this point in the history
  • Loading branch information
pbrochar committed Feb 19, 2024
1 parent d76470b commit d619758
Show file tree
Hide file tree
Showing 15 changed files with 311 additions and 178 deletions.
29 changes: 22 additions & 7 deletions blitz/models/blitz/file.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Any, ClassVar, NoReturn
from pydantic import BaseModel, Field, field_serializer
from pydantic import BaseModel, Field, ValidationError, field_serializer
from blitz.models.blitz.config import BlitzAppConfig
from blitz.models.blitz.resource import BlitzResourceConfig
from pathlib import Path
Expand Down Expand Up @@ -35,7 +35,9 @@ class FileType(StrEnum):
RESOURCES_FIELD_NAME: ClassVar[str] = "resources"

config: BlitzAppConfig
resources_configs: list[BlitzResourceConfig] = Field(default=[], serialization_alias=RESOURCES_FIELD_NAME)
resources_configs: list[BlitzResourceConfig] = Field(
default=[], serialization_alias=RESOURCES_FIELD_NAME
)
raw_file: dict[str, Any] = Field(exclude=True)
path: Path | None = Field(default=None, exclude=True)
file_type: FileType | None = Field(default=None, exclude=True)
Expand All @@ -45,10 +47,14 @@ class FileType(StrEnum):
# blitz_file.write(self.model_dump_json)

@field_serializer("resources_configs")
def _serialize_resources_configs(self, resources_configs: list[BlitzResourceConfig], _info: Any) -> dict[str, Any]:
def _serialize_resources_configs(
self, resources_configs: list[BlitzResourceConfig], _info: Any
) -> dict[str, Any]:
serialized_resources_configs = {}
for resource_config in resources_configs:
serialized_resources_configs[resource_config.name] = resource_config.model_dump()
serialized_resources_configs[resource_config.name] = (
resource_config.model_dump()
)

return serialized_resources_configs

Expand All @@ -75,15 +81,24 @@ def from_dict(
resources_configs: list[BlitzResourceConfig] = []
resource_name: str
resource_config: dict[str, Any]
for resource_name, resource_config in blitz_file.get(cls.RESOURCES_FIELD_NAME, {}).items():

for resource_name, resource_config in blitz_file.get(
cls.RESOURCES_FIELD_NAME, {}
).items():
settings_fields = {}
fields = {}
for field_name, field_value in resource_config.items():
if field_name.startswith(BlitzResourceConfig.Settings.FIELD_PREFIX):
settings_fields[field_name[len(BlitzResourceConfig.Settings.FIELD_PREFIX) :]] = field_value
settings_fields[
field_name[len(BlitzResourceConfig.Settings.FIELD_PREFIX) :]
] = field_value
else:
fields[field_name] = field_value
resources_configs.append(BlitzResourceConfig(name=resource_name, fields=fields, settings=settings_fields))
resources_configs.append(
BlitzResourceConfig(
name=resource_name, fields=fields, settings=settings_fields
)
)

return cls(
config=blitz_file.get(cls.CONFIG_FIELD_NAME),
Expand Down
7 changes: 7 additions & 0 deletions blitz/ui/blitz_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ def __init__(self, settings: Settings = get_settings()) -> None:
def current_project(self) -> str | None:
return self._current_project

@current_project.setter
def current_project(self, project: str) -> None:
print(project)
self._current_project = project



@property
def current_app(self) -> BlitzApp | None:
return self._current_app
Expand Down
8 changes: 8 additions & 0 deletions blitz/ui/components/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from blitz.ui.blitz_ui import BlitzUI, get_blitz_ui


class BaseComponent:
def __init__(self, blitz_ui: BlitzUI = get_blitz_ui()) -> None:
self.blitz_ui: BlitzUI = blitz_ui
self.current_project = blitz_ui.current_project
self.current_app = blitz_ui.current_app
28 changes: 20 additions & 8 deletions blitz/ui/components/gpt_chat_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ def validate_blitz_file(self, json: dict[str, Any]) -> bool:
BlitzFile.from_dict(json)
except ValidationError:
return False
except Exception:
return False
else:
return True

Expand All @@ -69,13 +71,13 @@ def action_buttons(self) -> None:
if self._dialog is None:
# TODO: handle error
raise Exception
ui.button(icon="file_download", color="transparent", on_click=self._dialog.open).props(
"dense flat size=xm color=grey"
)
ui.button(
icon="file_download", color="transparent", on_click=self._dialog.open
).props("dense flat size=xm color=grey")

def download_dialog(self) -> None:
with ui.dialog() as self._dialog, ui.card().classes("w-full px-4"):
if not self.is_valid_blitz_file:
if self.is_valid_blitz_file is False:
self.invalid_blitz_file()
# with ui.expansion("Edit File", icon="edit").classes("w-full h-auto rounded-lg border-solid border overflow-hidden grow overflow-hidden"):
# JsonEditorComponent(self.json).render()
Expand All @@ -93,7 +95,9 @@ def _download_json(self) -> None:
)

def _download_yaml(self) -> None:
ui.download(str.encode(yaml.dump(self.json)), filename=self._get_filename("yaml"))
ui.download(
str.encode(yaml.dump(self.json)), filename=self._get_filename("yaml")
)

def _get_filename(self, extension: str) -> str:
return f"{self.blitz_app_title.replace(' ', '_').replace('.', '_').lower()}.{extension}"
Expand Down Expand Up @@ -184,7 +188,9 @@ class UserQuestion(GPTChatComponent):
AVATAR_COLOR = "#a72bff"

def __init__(self, text: str = "") -> None:
super().__init__(label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR)
super().__init__(
label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR
)

def as_gpt_dict(self) -> ChatCompletionMessageParam:
return {
Expand All @@ -207,8 +213,11 @@ class GPTResponse(GPTChatComponent):
AVATAR_COLOR = "#74aa9c"

def __init__(self, text: str = "", text_is_finished: bool = False) -> None:
super().__init__(label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR)
super().__init__(
label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR
)
self._text_is_finished = text_is_finished
self.text_is_finished = text_is_finished

def add(self, text: str) -> None:
self.text += text
Expand Down Expand Up @@ -254,4 +263,7 @@ def split_response(text: str) -> list[Any]:

@classmethod
def from_gpt_dict(cls, gpt_dict: dict[str, Any]) -> "GPTChatComponent":
return cls(text=gpt_dict.get("content", ""), text_is_finished=gpt_dict.get("text_is_finished", False))
return cls(
text=gpt_dict.get("content", ""),
text_is_finished=gpt_dict.get("text_is_finished", False),
)
73 changes: 51 additions & 22 deletions blitz/ui/components/header.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from nicegui import ui
from nicegui.page_layout import LeftDrawer
from blitz.ui.blitz_ui import BlitzUI, get_blitz_ui
from blitz.ui.components.base import BaseComponent

MAIN_PINK = "#cd87ff"
DARK_PINK = "#a72bff"
Expand All @@ -17,14 +18,25 @@ def render(self) -> None:


class HeaderComponent:
def __init__(self, title: str = "", blitz_ui: BlitzUI = get_blitz_ui(), drawer: LeftDrawer | None = None) -> None:
def __init__(
self,
title: str = "",
blitz_ui: BlitzUI = get_blitz_ui(),
drawer: LeftDrawer | None = None,
) -> None:
self.title = title
self.blitz_ui = blitz_ui

self.dark_mode = ui.dark_mode(value=True)
self.home_link = f"dashboard/projects/{blitz_ui.current_project}" if blitz_ui.current_project else "projects"
self.home_link = (
f"dashboard/projects/{blitz_ui.current_project}"
if blitz_ui.current_project
else "projects"
)
self.drawer = drawer
ui.add_head_html(f"<style>{(Path(__file__).parent.parent / 'static' / 'style.css').read_text()}</style>")
ui.add_head_html(
f"<style>{(Path(__file__).parent.parent / 'static' / 'style.css').read_text()}</style>"
)

ui.add_head_html(
f"<style>{(Path(__file__).parent.parent / 'static' / 'jse_theme_dark.css').read_text()}</style>"
Expand All @@ -39,22 +51,30 @@ def __init__(self, title: str = "", blitz_ui: BlitzUI = get_blitz_ui(), drawer:
)

def render(self) -> None:
with ui.header(bordered=True).classes("pl-1 pr-8 justify-between content-center h-16 backdrop-blur-sm"):
with ui.header(bordered=True).classes(
"pl-1 pr-8 justify-between content-center h-16 backdrop-blur-sm"
):
with ui.row().classes("items-center space-x-20 content-center my-auto"):
with ui.row().classes("items-center space-x-0 content-center "):
if self.drawer is not None:
ui.button(icon="menu", on_click=self.drawer.toggle).props("flat")
ui.button(icon="menu", on_click=self.drawer.toggle).props(
"flat"
)
ui.icon(name="bolt", color=DARK_PINK, size="32px")
with ui.link(target=f"/projects/{self.blitz_ui.current_project}"):
ui.label("Blitz Dashboard")

with ui.row().classes("items-center justify-between content-center"):
with ui.link(target=f"{self.blitz_ui.localhost_url}/projects").classes("disabled"):
with ui.link(
target=f"{self.blitz_ui.localhost_url}/projects"
).classes("disabled"):
ui.tooltip("Multiple App management is coming soon")
ui.label("Projects")
with ui.link(target="/gpt"):
ui.label("GPT Builder")
with ui.link(target="https://paperz-org.github.io/blitz/", new_tab=True):
with ui.link(
target="https://paperz-org.github.io/blitz/", new_tab=True
):
ui.label("Documentation")
with ui.row().classes("items-center content-center my-auto"):
with ui.element():
Expand All @@ -71,8 +91,12 @@ def render(self) -> None:
self.dark_mode, "value", value=True
)
ui.tooltip("White mode is coming soon")
with ui.link(target="https://github.com/Paperz-org/blitz", new_tab=True).classes(" w-8"):
ui.image(Path(__file__).parent.parent / "./assets/github_white.png").classes("w-8 ")
with ui.link(
target="https://github.com/Paperz-org/blitz", new_tab=True
).classes(" w-8"):
ui.image(
Path(__file__).parent.parent / "./assets/github_white.png"
).classes("w-8 ")


class MenuLink:
Expand All @@ -82,42 +106,47 @@ def __init__(self, label: str, link: str, icon: str) -> None:
self.icon = icon

def render(self) -> None:
with ui.link(target=self.link).classes("w-full"), ui.button(on_click=self.go_to).props(
"flat align=left"
).classes("px-4 hover:bg-slate-700 rounded-sm w-full") as self.button:
with ui.link(target=self.link).classes("w-full"), ui.button(
on_click=self.go_to
).props("flat align=left").classes(
"px-4 hover:bg-slate-700 rounded-sm w-full"
) as self.button:
ui.icon(name=self.icon, size="sm").props("flat").classes("pr-4")
ui.label(self.label)

def go_to(self) -> None:
ui.open(self.link)


class FrameComponent:
class FrameComponent(BaseComponent):
def __init__(
self,
blitz_ui: BlitzUI = get_blitz_ui(),
show_drawer: bool = True,
drawer_open: bool = True,
) -> None:
self.blitz_ui = blitz_ui
self.current_project = blitz_ui.current_project
super().__init__()
print("+++________")
self.show_drawer = show_drawer
self.drawer_open = drawer_open

# Only for declarative
self.drawer: LeftDrawer | None = None

def left_drawer(self) -> None:
with ui.left_drawer(value=self.drawer_open, fixed=True, bottom_corner=True).props("width=200").classes(
"px-0 bg-[#14151a]"
) as self.drawer:
MenuLink("Dashboard", f"/projects/{self.current_project}", "dashboard").render()
with ui.left_drawer(
value=self.drawer_open, fixed=True, bottom_corner=True
).props("width=200").classes("px-0 bg-[#14151a]") as self.drawer:
MenuLink(
"Dashboard", f"/projects/{self.current_project}", "dashboard"
).render()
MenuLink(
"Admin",
f"{self.blitz_ui.localhost_url}/admin/",
"table_chart",
).render()
MenuLink("Swagger", f"/projects/{self.current_project}/swagger", "api").render()
MenuLink(
"Swagger", f"/projects/{self.current_project}/swagger", "api"
).render()
MenuLink(
"Blitz File",
f"/projects/{self.current_project}/blitz-file",
Expand All @@ -131,6 +160,6 @@ def left_drawer(self) -> None:
MenuLink("Logs", f"/projects/{self.current_project}/logs", "list").render()

def render(self) -> None:
if self.show_drawer and self.current_project is not None:
if self.show_drawer and self.blitz_ui.current_project is not None:
self.left_drawer()
HeaderComponent(drawer=self.drawer).render()
Loading

0 comments on commit d619758

Please sign in to comment.