fix card spacing

This commit is contained in:
Death916 2025-04-24 04:35:38 -07:00
parent ea4eaa3f34
commit bbbcbdfc45

View file

@ -12,7 +12,7 @@ from utils.weather import Weather
from utils.scores import NBAScores, mlbScores from utils.scores import NBAScores, mlbScores
from utils.news import News from utils.news import News
# from utils.alarm import Alarm # from utils.alarm import Alarm # Commented out import
import logging import logging
# --- Constants --- # --- Constants ---
@ -27,20 +27,17 @@ class State(rx.State):
current_time: str = "" # Note: rx.moment replaces the need for this if used for display current_time: str = "" # Note: rx.moment replaces the need for this if used for display
alarm_time: str = "" alarm_time: str = ""
alarms: list = [] alarms: list = []
# --- Add type hints ---
news: List[Dict[str, Any]] = [] news: List[Dict[str, Any]] = []
nba_scores: List[Dict[str, Any]] = [] nba_scores: List[Dict[str, Any]] = []
mlb_scores: List[Dict[str, Any]] = [] mlb_scores: List[Dict[str, Any]] = []
# ----------------------
_news_client: News | None = None # This will be set in the constructor _news_client: News | None = None # This will be set in the constructor
last_weather_update: str = "Never" last_weather_update: str = "Never"
weather_img: str = WEATHER_IMAGE_PATH weather_img: str = WEATHER_IMAGE_PATH
_weather_client: Weather | None = None # This will be set in the constructor _weather_client: Weather | None = None # This will be set in the constructor
# --- Add type hints for clients ---
_mlb_client: mlbScores | None = None _mlb_client: mlbScores | None = None
_nba_client: NBAScores | None = None _nba_client: NBAScores | None = None
last_sports_update: float = 0.0 last_sports_update: float = 0.0
# ----------------------------------
# --- Initialize Utility Client --- # --- Initialize Utility Client ---
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -66,9 +63,9 @@ class State(rx.State):
# --- on_load Handler --- # --- on_load Handler ---
async def start_background_tasks(self): async def start_background_tasks(self):
"""Starts the weather background task when the page loads.""" """Starts the weather background task when the page loads."""
rx.remove_local_storage("chakra-ui-color-mode") #trying to test themes remove after rx.remove_local_storage("chakra-ui-color-mode") # trying to test themes remove after
logging.info("Triggering background tasks: Weather") logging.info("Triggering background tasks: Weather")
# *** FIX: Return a list containing the handler reference *** # Return a list containing the handler references
return [State.fetch_weather, State.fetch_sports] return [State.fetch_weather, State.fetch_sports]
# --- Sports Background Task --- # --- Sports Background Task ---
@ -80,8 +77,7 @@ class State(rx.State):
while True: while True:
try: try:
logging.info("Fetching sports scores...") logging.info("Fetching sports scores...")
# Fetch MLB and NBA scores # check if sports has updated in last 5 minutes if so skip
#check if sports has updated in last 5 minutes if so skip
if self.last_sports_update and (time.time() - self.last_sports_update) < 300: if self.last_sports_update and (time.time() - self.last_sports_update) < 300:
logging.info("Sports scores already updated within the last 5 minutes. Skipping fetch.") logging.info("Sports scores already updated within the last 5 minutes. Skipping fetch.")
await asyncio.sleep(300) await asyncio.sleep(300)
@ -116,7 +112,7 @@ class State(rx.State):
logging.error(f"Error in fetch_sports background task: {e}", exc_info=True) logging.error(f"Error in fetch_sports background task: {e}", exc_info=True)
await asyncio.sleep(500) await asyncio.sleep(500)
# format sports scores for display # (Commented out news fetcher)
""" """
@rx.event(background=True) @rx.event(background=True)
async def fetch_news(self): async def fetch_news(self):
@ -165,9 +161,7 @@ class State(rx.State):
if img_web_path: if img_web_path:
async with self: async with self:
timestamp = int(time.time()) timestamp = int(time.time()) # Unused timestamp, kept as per instruction
# Update state with cache-busting query param
# Ensure img_web_path is like "/weather.jpg"
self.weather_img = f"{img_web_path}" self.weather_img = f"{img_web_path}"
self.last_weather_update = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC') self.last_weather_update = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
logging.info(f"State.weather_img updated to: {self.weather_img}") logging.info(f"State.weather_img updated to: {self.weather_img}")
@ -201,7 +195,7 @@ def index() -> rx.Component:
font_size="4xl", font_size="4xl",
font_weight="bold", font_weight="bold",
color="white", color="white",
background_color="#6f42c1", # Original color background_color="#6f42c1",
), ),
@ -226,83 +220,87 @@ def index() -> rx.Component:
), ),
rx.card( rx.card(
rx.vstack( # Added vstack for title/image/status rx.vstack(
rx.heading("Weather", size="4"), rx.heading("Weather", size="4"),
rx.image( rx.image(
src=State.weather_img, src=State.weather_img,
alt="Current weather conditions for Sacramento", alt="Current weather conditions for Sacramento",
width="100%", # Keep original width setting width="100%",
height="auto", # Keep original height setting height="auto",
object_fit="contain", # Adjust fit as needed object_fit="contain",
border_radius="var(--radius-3)", # Use theme radius border_radius="var(--radius-3)",
), ),
rx.text( rx.text(
f"Last Update: {State.last_weather_update}", f"Last Update: {State.last_weather_update}",
size="1", size="1",
color_scheme="gray", color_scheme="gray",
padding_top="0.5em" # Add some space padding_top="0.5em"
), ),
align="center", # Center heading/image/text align="center",
spacing="2", spacing="2",
) )
), ),
# --- Modified MLB Scores Card ---
rx.card( rx.card(
rx.box( rx.box(
rx.text("MLB Scores"), rx.text("MLB Scores"),
rx.foreach( # Add rx.vstack here to control spacing of foreach items
rx.vstack(
rx.foreach(
State.mlb_scores, State.mlb_scores,
lambda score: rx.vstack( # Lambda now returns the styled card directly
rx.card( lambda score: rx.card(
rx.text(f"{score['away_team']} {score['away_score']} @ " rx.text(f"{score.get('away_team','?')} {score.get('away_score','-')} @ " # Use .get() for safety
f"{score['home_team']} {score['home_score']} " f"{score.get('home_team','?')} {score.get('home_score','-')} "
f"(Status: {score['status']})", f"({score.get('status','?')})",
size="1", size="1",
),
), ),
spacing="1",
padding="2",
size="1", size="1",
variant="ghost" padding="1",
variant="surface",
width="100%",
), ),
),
spacing="1",
align_items="stretch",
width="100%",
), ),
), ),
), ),
spacing="3", # Add spacing between cards # --- End of Modified MLB Scores Card ---
spacing="3",
width="100%", width="100%",
justify="center", # Center cards horizontally justify="center",
align="stretch", # Stretch cards vertically if needed align="stretch",
), ),
align="center", align="center",
spacing="4", # Spacing between clock and flex container spacing="4",
), ),
), ),
# Original container settings
padding="2rem", # Add some padding padding="2rem",
max_width="1200px", # Limit width max_width="1200px",
margin="0 auto", # Center container margin="0 auto",
), ),
''' ''' # Commented out style block
style = { style = {
"background_color": "black", # Darker purple "background_color": "black",
"color": "#ffffff", "color": "#ffffff",
"box_shadow": "0 4px 8px rgba(0, 0, 0, 0.2)", "box_shadow": "0 4px 8px rgba(0, 0, 0, 0.2)",
"transition": "background-color 0.3s ease, color 0.3s ease", "transition": "background-color 0.3s ease, color 0.3s ease",
"hover": { "hover": {
"background_color": "#3a2b4d", # Darker shade on hover "background_color": "#3a2b4d",
"color": "#ffffff", "color": "#ffffff",
}, },
} }
''' ''' # Commented out style block
app = rx.App( app = rx.App(
theme=rx.theme( theme=rx.theme(
appearance="dark", appearance="dark",
@ -312,7 +310,7 @@ app = rx.App(
gray_color="mauve", gray_color="mauve",
has_background=True, has_background=True,
), ),
#style=style #using them #style=style # using theme instead
) )
@ -321,10 +319,5 @@ app = rx.App(
app.add_page( app.add_page(
index, index,
title="DeathClock", # Example title title="DeathClock", # Example title
on_load=State.start_background_tasks on_load=State.start_background_tasks # Trigger tasks when this page loads
# Trigger tasks when this page loads
) )
# The original TypeError is resolved by returning [State.fetch_weather]
# from State.start_background_tasks.
# The image display is fixed by binding rx.image src to State.weather_img.