Skip to content

Commit

Permalink
cache calendar dates
Browse files Browse the repository at this point in the history
  • Loading branch information
TomJGooding committed Jan 10, 2024
1 parent 1a3d851 commit e16cb16
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/textual/widgets/_month_calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ def __init__(
self._calendar = calendar.Calendar(first_weekday)
self.show_cursor = show_cursor
self.show_other_months = show_other_months
self._calendar_dates = self._get_calendar_dates()

def compose(self) -> ComposeResult:
yield DataTable(show_cursor=self.show_cursor)
Expand Down Expand Up @@ -172,8 +173,7 @@ def _update_calendar_table(self, update_week_header: bool) -> None:

table.hover_coordinate = old_hover_coordinate

@property
def _calendar_dates(self) -> list[list[datetime.date | None]]:
def _get_calendar_dates(self) -> list[list[datetime.date | None]]:
"""A matrix of `datetime.date` objects for this month calendar, where
each row represents a week. If `show_other_months` is True, this returns
a six-week calendar including dates from the previous and next month.
Expand Down Expand Up @@ -224,10 +224,9 @@ def _calendar_dates(self) -> list[list[datetime.date | None]]:

def _get_date_coordinate(self, date: datetime.date) -> Coordinate:
for week_index, week in enumerate(self._calendar_dates):
try:
if date in week:
return Coordinate(week_index, week.index(date))
except ValueError:
pass

raise ValueError("Date is out of range for this month calendar.")

def _format_day(self, date: datetime.date) -> Text:
Expand All @@ -247,6 +246,7 @@ def watch_date(self, old_date: datetime.date, new_date: datetime.date) -> None:
if not self.is_mounted:
return
if (new_date.month != old_date.month) or (new_date.year != old_date.year):
self._calendar_dates = self._get_calendar_dates()
self._update_calendar_table(update_week_header=False)
else:
table = self.query_one(DataTable)
Expand All @@ -255,6 +255,7 @@ def watch_date(self, old_date: datetime.date, new_date: datetime.date) -> None:

def watch_first_weekday(self) -> None:
self._calendar = calendar.Calendar(self.first_weekday)
self._calendar_dates = self._get_calendar_dates()
if not self.is_mounted:
return
self._update_calendar_table(update_week_header=True)
Expand All @@ -266,6 +267,7 @@ def watch_show_cursor(self, show_cursor: bool) -> None:
table.show_cursor = show_cursor

def watch_show_other_months(self) -> None:
self._calendar_dates = self._get_calendar_dates()
if not self.is_mounted:
return
self._update_calendar_table(update_week_header=False)

0 comments on commit e16cb16

Please sign in to comment.