Skip to content

Activity Heatmap

textual_timepiece.activity_heatmap

Activity Heatmap graph widgets for a yearly overview.

CLASS DESCRIPTION
ActivityHeatmap

Base renderable widget for an activity heatmap.

HeatmapManager

Composite widget that manages navigating a heatmap.

ActivityHeatmap

Bases: ScrollView, BaseWidget

Base renderable widget for an activity heatmap.

PARAMETER DESCRIPTION
values

A dictionary of values for each date.

TYPE: ActivityData | None DEFAULT: None

year

Year for verifying dates.

TYPE: int | None DEFAULT: None

name

The name of the widget.

TYPE: str | None DEFAULT: None

id

The ID of the widget in the DOM.

TYPE: str | None DEFAULT: None

classes

The CSS classes for the widget.

TYPE: str | None DEFAULT: None

select_on_focus

Whether to setup a keyboard cursor on focus.

TYPE: bool DEFAULT: True

disabled

Whether the widget is disabled or not.

TYPE: bool DEFAULT: False

Examples:

>>> def compose(self) -> ComposeResult:
>>>     yield ActivityHeatmap(year2025)
>>> def on_mount(self) -> None:
>>>     activity = generate_activity()
>>>     self.query_one(ActivityHeatmap).values = activity
CLASS DESCRIPTION
DateSelected

Message sent when a day is selected.

WeekSelected

Message sent when a week number is selected.

MonthSelected

Message sent when a month label is selected.

METHOD DESCRIPTION
action_move_cursor

Move the keyboard cursor.

action_clear_cursor

Clear the navigation cursor.

sum_week

Get the total for a week for any specified date.

sum_month

Get the total for a month for any specified date.

generate_empty_activity

Generates empty data for a specified year.

ATTRIBUTE DESCRIPTION
ActivityData

Final data type that the heatmap uses.

TYPE: TypeAlias

BINDINGS

All bindings for the ActivityHeatmap.

TYPE: list[BindingType]

DEFAULT_CSS

Default CSS Styling for the ActivityHeatmap

TYPE: str

COMPONENT_CLASSES

All component classes that the ActivityHeatmap uses.

TYPE: set[str]

data

Two dimensional data that should be normalized between 0 and 1.

year

Current year for calculating dates.

values

Original pre normalized values for tooltips.

mouse_offset

Current mouse offfset for tracking the cursor.

cursor

Current hovered day, week or month.

Source code in src/textual_timepiece/_activity_heatmap.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
class ActivityHeatmap(ScrollView, BaseWidget):
    """Base renderable widget for an activity heatmap.

    Params:
        values: A dictionary of values for each date.
        year: Year for verifying dates.
        name: The name of the widget.
        id: The ID of the widget in the DOM.
        classes: The CSS classes for the widget.
        select_on_focus: Whether to setup a keyboard cursor on focus.
        disabled: Whether the widget is disabled or not.

    Examples:
        >>> def compose(self) -> ComposeResult:
        >>>     yield ActivityHeatmap(year2025)

        >>> def on_mount(self) -> None:
        >>>     activity = generate_activity()
        >>>     self.query_one(ActivityHeatmap).values = activity
    """

    @dataclass
    class DateSelected(BaseMessage):
        """Message sent when a day is selected."""

        widget: ActivityHeatmap
        day: Date

    @dataclass
    class WeekSelected(BaseMessage):
        """Message sent when a week number is selected."""

        widget: ActivityHeatmap
        week: Date

    @dataclass
    class MonthSelected(BaseMessage):
        """Message sent when a month label is selected."""

        widget: ActivityHeatmap
        month: Date

    can_focus = True

    ActivityData: TypeAlias = defaultdict[date, float]
    """Final data type that the heatmap uses."""

    BORDER_TITLE = "Activity Heatmap"
    BINDING_GROUP_TITLE = "Activity Heatmap"

    BINDINGS: ClassVar[list[BindingType]] = [
        Binding(
            "right",
            "move_cursor('right')",
            "Move Right",
            tooltip="Move the keyboard cursor right.",
            show=False,
            priority=True,
        ),
        Binding(
            "down",
            "move_cursor('down')",
            "Move Down",
            tooltip="Move the keyboard cursor down.",
            show=False,
            priority=True,
        ),
        Binding(
            "left",
            "move_cursor('left')",
            tooltip="Move the keyboard cursor left.",
            show=False,
            priority=True,
        ),
        Binding(
            "up",
            "move_cursor('up')",
            "Move Up",
            tooltip="Move the keyboard cursor up.",
            show=False,
            priority=True,
        ),
        Binding(
            "enter",
            "select_tile",
            "Select",
            tooltip="Select the highlighted day.",
            show=False,
        ),
        Binding(
            "escape",
            "clear_cursor",
            "Clear Cursor",
            tooltip="Clear the cursor selection.",
            show=False,
        ),
    ]
    """All bindings for the `ActivityHeatmap`.

    | Key(s) | Description |
    | :- | :- |
    | right | Move Cursor Right |
    | down | Move Cursor Down |
    | left | Move Cursor Left |
    | up | Move Cursor Up |
    | enter | Select Highlighted Day |
    | escape | Clear Any Cursor Selection. |
    """

    DEFAULT_CSS: ClassVar[str] = """
    ActivityHeatmap {
        background: transparent;
        height: auto;
        .activityheatmap--empty {
            background: transparent;
            color: $primary;
            text-style: bold;
        }
        .activityheatmap--empty-alt {
            background: transparent;
            color: $secondary;
            text-style: bold;
        }
        .activityheatmap--color {
            background: $panel-darken-1;
            color: $secondary;
        }
        .activityheatmap--hover {
            background: $panel-darken-1;
            color: $accent;
            border-bottom: white;
        }
    }
    Tooltip {
        padding: 1;
        text-align: center;
    }
    """
    """Default CSS Styling for the `ActivityHeatmap`"""

    COMPONENT_CLASSES: ClassVar[set[str]] = {
        "activityheatmap--color",
        "activityheatmap--empty",
        "activityheatmap--empty-alt",
        "activityheatmap--hover",
    }
    """All component classes that the `ActivityHeatmap` uses.

    | Class | Description |
    | :- | :- |
    | `activityheatmap--color` | Base color of the tiles |
    | `activityheatmap--empty` | Empty tile color for navigation. |
    | `activityheatmap--empty-alt` | Alternative empty tile color for navigation. |
    | `activityheatmap--hover` | Color when something is hovered. |
    """  # noqa: E501
    data = reactive[list[list[float]]](list, init=False, layout=True)
    """Two dimensional data that should be normalized between 0 and 1."""

    year = var[int](lambda: Date.today_in_system_tz().year, init=False)
    """Current year for calculating dates."""

    values = var[ActivityData](lambda: defaultdict(lambda: 0), init=False)
    """Original pre normalized values for tooltips.

    Assign data to this reactive to update values.
    """

    mouse_offset = var[Offset](Offset, init=False)
    """Current mouse offfset for tracking the cursor."""

    cursor = reactive[HeatmapCursor | None](None, init=False)
    """Current hovered day, week or month."""

    def __init__(
        self,
        values: ActivityData | None = None,
        year: int | None = None,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
        *,
        select_on_focus: bool = True,
        disabled: bool = False,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes, disabled=disabled)

        self.select_on_focus = select_on_focus
        self.virtual_size = Size(163, 18)
        if values:
            self.set_reactive(ActivityHeatmap.values, values)
        if year:
            self.set_reactive(ActivityHeatmap.year, year)

    def _get_color_strength(
        self,
        value: float,
        base: Color,
        bg: Color,
    ) -> RColor:
        return base.blend(bg, value).rich_color

    def _get_day_style(
        self,
        day: int,
        week: int,
        value: float,
        background: Color,
        color: Color,
        hover_color: RStyle,
    ) -> RStyle:
        if self._is_tile_hovered(day=day, week=week):
            return hover_color

        return RStyle(color=self._get_color_strength(value, color, background))

    def _get_segment(
        self,
        day: int,
        week: int,
        background: Color,
        color: Color,
        hover_color: RStyle,
        empty: RStyle,
    ) -> Segment:
        if (value := self.data[week][day]) is not None:
            return Segment(
                "██",
                style=self._get_day_style(
                    day, week, value, background, color, hover_color
                ),
            )
        if self._is_tile_hovered(day=day, week=week):
            return Segment("██", hover_color)

        return Segment("  ")

    def _render_weekday(
        self,
        y: int,
        empty_bg: RStyle,
        empty_seg: Segment,
    ) -> Strip:
        base_color = self.get_component_rich_style("activityheatmap--color")
        empty_alt = self.get_component_rich_style("activityheatmap--empty-alt")
        hover_color = self.get_component_rich_style("activityheatmap--hover")
        day = y // 2

        color, background = (
            Color.from_rich_color(base_color.color),
            Color.from_rich_color(base_color.bgcolor),
        )
        segs = [
            Segment(day_abbr[day], empty_bg if day % 2 == 0 else empty_alt),
            empty_seg,
        ]
        empty_bg = empty_bg.background_style
        for week in range(len(self.data)):
            segs.append(empty_seg)
            segs.append(
                self._get_segment(
                    day, week, background, color, hover_color, empty_bg
                )
            )

        return Strip(segs)

    def _render_weeks(
        self,
        empty_background: RStyle,
        empty_seg: Segment,
    ) -> Strip:
        empty_alt = self.get_component_rich_style("activityheatmap--empty-alt")
        hover_color = self.get_component_rich_style("activityheatmap--hover")

        segments = [Segment(" " * 4, style=empty_seg.style)]
        for i in range(2, 108, 2):
            segments.append(empty_seg)
            style = (
                hover_color
                if self._is_tile_hovered(week=i // 2)
                else empty_background
                if i % 2 != 0
                else empty_alt
            )
            segments.append(Segment(str(i // 2).rjust(2), style=style))

        return Strip(segments)

    def _render_months(
        self,
        empty_background: RStyle,
        empty_seg: Segment,
    ) -> Strip:
        empty_alt = self.get_component_rich_style("activityheatmap--empty-alt")
        hover_color = self.get_component_rich_style("activityheatmap--hover")
        segments = [empty_seg] * 3
        for month in range(1, 13):
            segments.append(
                Segment(
                    month_abbr[month],
                    style=hover_color
                    if self._is_tile_hovered(month=month)
                    else empty_background
                    if month % 2 != 0
                    else empty_alt,
                )
            )
            segments.append(Segment(" " * 10, style=empty_background))
        return Strip(segments)

    def render_line(self, y: int) -> Strip:
        empty_background = self.get_component_rich_style(
            "activityheatmap--empty"
        )
        empty_seg = Segment(" ", style=empty_background)

        scroll_x, scroll_y = self.scroll_offset
        y += scroll_y

        if y == 15:
            strip = self._render_weeks(empty_background, empty_seg)
        elif y == 17:
            strip = self._render_months(empty_background, empty_seg)
        elif y % 2 == 0 or not self.data or (len(self.data[0]) * 2) < y - 2:
            strip = Strip.blank(self.size.width)
        else:
            strip = self._render_weekday(y, empty_background, empty_seg)

        return strip.crop(scroll_x, scroll_x + self.size.width)

    def _watch_values(self, new: ActivityData) -> None:
        self._process_data(new, self.year)

    @work(name="heatmap", thread=True, exclusive=True)
    def _process_data(self, data: ActivityData, year: int) -> None:
        """Entrypoint worker for the heatmap data.

        Normalizes & inverts the data into usable values.

        Args:
            data: Two dimensional data that is ready to be converted.
        """
        template = ActivityHeatmap.generate_empty_activity(year)
        values = [
            [data[day] if day else None for day in week] for week in template
        ]
        flat: list[float | None] = list(chain.from_iterable(values))
        normalized = [
            1 - v if v is not None else None for v in normalize_values(flat)
        ]
        self.app.call_from_thread(
            setattr, self, "data", flat_to_shape(normalized, values)
        )

    def _on_focus(self, event: Focus) -> None:
        self.action_move_cursor("right")

    def _on_leave(self, event: Leave) -> None:
        if not self.has_focus:
            self.cursor = None

    def _on_blur(self, event: Blur) -> None:
        self.cursor = None

    def _on_mouse_move(self, event: MouseMove) -> None:
        self.mouse_offset = event.offset + self.scroll_offset

    def _validate_date(self, day: Date) -> Date:
        return Date(day.year, 1, 1)

    def _watch_time_range(self) -> None:
        self.virtual_size = Size(110, 18)

    def _watch_cursor(self, cursor: HeatmapCursor | None) -> None:
        if cursor is None:
            return

        x = ((cursor.week - 1) * 3) + 4
        if not (
            self.scroll_offset.x < x < self.scroll_offset.x + self.size.width
        ):
            self.scroll_to(x=x)

        y = ((cursor.day - 1) * 2) + 1
        if not (
            self.scroll_offset.y < y < self.scroll_offset.y + self.size.height
        ):
            self.scroll_to(y=y)

    @on(Click)
    def _action_select_tile(self) -> None:
        if (day := self._date_lookup()) is not None:
            self.post_message(self.DateSelected(self, day))
        elif (week := self._week_lookup()) is not None:
            self.post_message(self.WeekSelected(self, week))
        elif (month := self._month_lookup()) is not None:
            self.post_message(self.MonthSelected(self, month))

        self.cursor = None

    def _watch_mouse_offset(self, new: Offset) -> None:
        self.cursor = (
            self._get_cursor_tile(new)
            or self._get_cursor_week(new)
            or self._get_cursor_month(new)
        )

    def _is_tile_hovered(
        self,
        *,
        day: int | None = None,
        week: int | None = None,
        month: int | None = None,
    ) -> bool:
        if self.cursor is None:
            return False

        if week is not None and self.cursor.is_week:
            if day is not None:
                week += 1
            return week == self.cursor.week

        if self.cursor.is_month:
            if month is not None:
                return month == self.cursor.month
            elif day is not None and week is not None:
                year = self.year
                if week == 52:
                    week = 0
                    year += 1
                try:
                    cal = date.fromisocalendar(year, week + 1, day + 1)
                except ValueError:
                    return False
                return cal.month == self.cursor.month and cal.year == self.year

        if day is None or week is None:
            return False

        return day + 1 == self.cursor.day and week + 1 == self.cursor.week

    def _is_offset_on_tile(self, offset: Offset) -> bool:
        return bool(
            4 <= offset.x <= 165
            and 1 <= offset.y <= 14
            and ((offset.x - 4) % 3 != 0)
            and offset.y % 2 != 0
        )

    def action_move_cursor(self, direction: Directions) -> None:
        """Move the keyboard cursor."""
        if self.cursor is None:
            self.cursor = HeatmapCursor(1, 1)

        elif direction == "right":
            self.cursor = self.cursor.move(self.year, week_delta=1)
        elif direction == "down":
            self.cursor = self.cursor.move(self.year, day_delta=1)
        elif direction == "left":
            self.cursor = self.cursor.move(self.year, week_delta=-1)
        elif direction == "up":
            self.cursor = self.cursor.move(self.year, day_delta=-1)

    def action_clear_cursor(self) -> None:
        """Clear the navigation cursor."""
        self.cursor = None

    def check_action(
        self,
        action: str,
        parameters: tuple[object, ...],
    ) -> bool | None:
        if action == "move_cursor" and self.cursor:
            if parameters[0] == "right":
                return self.cursor.week < 53
            elif parameters[0] == "down":
                return self.cursor.day < 9
            elif parameters[0] == "left":
                return self.cursor.week > 1
            else:
                return self.cursor.day > 1

        if action == "clear_cursor":
            return isinstance(self.cursor, HeatmapCursor)

        return True

    def get_content_width(self, container: Size, viewport: Size) -> int:
        return 163

    def get_content_height(
        self,
        container: Size,
        viewport: Size,
        width: int,
    ) -> int:
        return 18

    def _get_cursor_tile(self, offset: Offset) -> HeatmapCursor | None:
        if self._is_offset_on_tile(offset):
            return HeatmapCursor(
                ((offset.x - 4) // 3) + 1,
                ((offset.y - 1) // 2) + 1,
            )

        return None

    def _get_cursor_week(self, offset: Offset) -> HeatmapCursor | None:
        if offset.y == 15 and 5 <= offset.x <= 165 and offset.x - 2 % 3 != 0:
            return HeatmapCursor(((offset.x - 4) // 3) + 1, 8)

        return None

    def _get_cursor_month(self, offset: Offset) -> HeatmapCursor | None:
        if month := self._is_offset_on_month(offset):
            return HeatmapCursor(((offset.x - 4) // 3) + 1, 9, month)

        return None

    def _is_offset_on_month(self, offset: Offset) -> int:
        if offset.y != 17 or not (3 <= offset.x <= 148):
            return 0

        month, rem = divmod(cast(int, offset.x) - 2, 13)

        if rem not in {0, 1, 2}:
            return 0

        return month + 1

    def _date_lookup(self) -> Date | None:
        if self.cursor is not None and self.cursor.is_day:
            if (
                day := self.cursor.to_date(self.year)
            ) is not None and day.year == self.year:
                return day

        return None

    def _week_lookup(self) -> Date | None:
        if self.cursor is not None and self.cursor.is_week:
            return self.cursor.to_date(self.year)

        return None

    def _month_lookup(self) -> Date | None:
        if self.cursor is not None and self.cursor.is_month:
            return self.cursor.to_date(self.year)

        return None

    def sum_week(self, week: Date) -> float:
        """Get the total for a week for any specified date."""
        return sum(
            self.values[day.py_date()]
            for day in iterate_timespan(week, days(1), 7)
        )

    def sum_month(self, month: Date) -> float:
        """Get the total for a month for any specified date."""
        return sum(
            self.values[day.py_date()]
            for day in iterate_timespan(
                month,
                days(1),
                monthrange(month.year, month.month)[1],
            )
        )

    @staticmethod
    def generate_empty_activity(year: int) -> list[list[date | None]]:
        """Generates empty data for a specified year.

        Args:
            year: Year to generate. Minimum year 1 to a maximum year 9998.

        Returns:
            A 2 dimensional array of dates or None if the day belongs to
                another year.
        """
        raw = list(
            chain.from_iterable(Calendar().yeardatescalendar(year, 12)[0])
        )
        new_cal: list[list[date | None]] = []
        for i, week in enumerate(raw):
            if i and week[0] in new_cal[-1]:
                continue

            new_cal.append([])
            for day in week:
                if day.year != year:
                    new_cal[-1].append(None)
                else:
                    new_cal[-1].append(day)

        return new_cal

    @property  # type: ignore[misc]  # NOTE: Tooltip is generated inside.
    def tooltip(self) -> str | None:  # type: ignore[override]
        if (tip_date := self._date_lookup()) is not None:
            total = int(self.values[tip_date.py_date()])
            tooltip = f"{tip_date.py_date():%-d %B}\n"
            return tooltip + format_seconds(total, include_seconds=False)

        if (tip_week := self._week_lookup()) is not None:
            total = int(self.sum_week(tip_week))
            tooltip = f"{tip_week.py_date():%U week of %Y}\n"
            return tooltip + format_seconds(total, include_seconds=False)

        if (tip_month := self._month_lookup()) is not None:
            total = int(self.sum_month(tip_month))
            tooltip = f"{tip_month.py_date():%B %Y}\n"
            return tooltip + format_seconds(total, include_seconds=False)

        return None

ActivityData class-attribute instance-attribute

ActivityData: TypeAlias = defaultdict[date, float]

Final data type that the heatmap uses.

BINDINGS class-attribute

BINDINGS: list[BindingType] = [
    Binding(
        "right",
        "move_cursor('right')",
        "Move Right",
        tooltip="Move the keyboard cursor right.",
        show=False,
        priority=True,
    ),
    Binding(
        "down",
        "move_cursor('down')",
        "Move Down",
        tooltip="Move the keyboard cursor down.",
        show=False,
        priority=True,
    ),
    Binding(
        "left",
        "move_cursor('left')",
        tooltip="Move the keyboard cursor left.",
        show=False,
        priority=True,
    ),
    Binding(
        "up",
        "move_cursor('up')",
        "Move Up",
        tooltip="Move the keyboard cursor up.",
        show=False,
        priority=True,
    ),
    Binding(
        "enter",
        "select_tile",
        "Select",
        tooltip="Select the highlighted day.",
        show=False,
    ),
    Binding(
        "escape",
        "clear_cursor",
        "Clear Cursor",
        tooltip="Clear the cursor selection.",
        show=False,
    ),
]

All bindings for the ActivityHeatmap.

Key(s) Description
right Move Cursor Right
down Move Cursor Down
left Move Cursor Left
up Move Cursor Up
enter Select Highlighted Day
escape Clear Any Cursor Selection.

DEFAULT_CSS class-attribute

ActivityHeatmap {
    background: transparent;
    height: auto;
    .activityheatmap--empty {
        background: transparent;
        color: $primary;
        text-style: bold;
    }
    .activityheatmap--empty-alt {
        background: transparent;
        color: $secondary;
        text-style: bold;
    }
    .activityheatmap--color {
        background: $panel-darken-1;
        color: $secondary;
    }
    .activityheatmap--hover {
        background: $panel-darken-1;
        color: $accent;
        border-bottom: white;
    }
}
Tooltip {
    padding: 1;
    text-align: center;
}

Default CSS Styling for the ActivityHeatmap

COMPONENT_CLASSES class-attribute

COMPONENT_CLASSES: set[str] = {
    "activityheatmap--color",
    "activityheatmap--empty",
    "activityheatmap--empty-alt",
    "activityheatmap--hover",
}

All component classes that the ActivityHeatmap uses.

Class Description
activityheatmap--color Base color of the tiles
activityheatmap--empty Empty tile color for navigation.
activityheatmap--empty-alt Alternative empty tile color for navigation.
activityheatmap--hover Color when something is hovered.

data class-attribute instance-attribute

data = reactive[list[list[float]]](list, init=False, layout=True)

Two dimensional data that should be normalized between 0 and 1.

year class-attribute instance-attribute

year = var[int](lambda: year, init=False)

Current year for calculating dates.

values class-attribute instance-attribute

values = var[ActivityData](lambda: defaultdict(lambda: 0), init=False)

Original pre normalized values for tooltips.

Assign data to this reactive to update values.

mouse_offset class-attribute instance-attribute

mouse_offset = var[Offset](Offset, init=False)

Current mouse offfset for tracking the cursor.

cursor class-attribute instance-attribute

cursor = reactive[HeatmapCursor | None](None, init=False)

Current hovered day, week or month.

DateSelected dataclass

Bases: BaseMessage

Message sent when a day is selected.

Source code in src/textual_timepiece/_activity_heatmap.py
142
143
144
145
146
147
@dataclass
class DateSelected(BaseMessage):
    """Message sent when a day is selected."""

    widget: ActivityHeatmap
    day: Date

WeekSelected dataclass

Bases: BaseMessage

Message sent when a week number is selected.

Source code in src/textual_timepiece/_activity_heatmap.py
149
150
151
152
153
154
@dataclass
class WeekSelected(BaseMessage):
    """Message sent when a week number is selected."""

    widget: ActivityHeatmap
    week: Date

MonthSelected dataclass

Bases: BaseMessage

Message sent when a month label is selected.

Source code in src/textual_timepiece/_activity_heatmap.py
156
157
158
159
160
161
@dataclass
class MonthSelected(BaseMessage):
    """Message sent when a month label is selected."""

    widget: ActivityHeatmap
    month: Date

action_move_cursor

action_move_cursor(direction: Directions) -> None

Move the keyboard cursor.

Source code in src/textual_timepiece/_activity_heatmap.py
570
571
572
573
574
575
576
577
578
579
580
581
582
def action_move_cursor(self, direction: Directions) -> None:
    """Move the keyboard cursor."""
    if self.cursor is None:
        self.cursor = HeatmapCursor(1, 1)

    elif direction == "right":
        self.cursor = self.cursor.move(self.year, week_delta=1)
    elif direction == "down":
        self.cursor = self.cursor.move(self.year, day_delta=1)
    elif direction == "left":
        self.cursor = self.cursor.move(self.year, week_delta=-1)
    elif direction == "up":
        self.cursor = self.cursor.move(self.year, day_delta=-1)

action_clear_cursor

action_clear_cursor() -> None

Clear the navigation cursor.

Source code in src/textual_timepiece/_activity_heatmap.py
584
585
586
def action_clear_cursor(self) -> None:
    """Clear the navigation cursor."""
    self.cursor = None

sum_week

sum_week(week: Date) -> float

Get the total for a week for any specified date.

Source code in src/textual_timepiece/_activity_heatmap.py
672
673
674
675
676
677
def sum_week(self, week: Date) -> float:
    """Get the total for a week for any specified date."""
    return sum(
        self.values[day.py_date()]
        for day in iterate_timespan(week, days(1), 7)
    )

sum_month

sum_month(month: Date) -> float

Get the total for a month for any specified date.

Source code in src/textual_timepiece/_activity_heatmap.py
679
680
681
682
683
684
685
686
687
688
def sum_month(self, month: Date) -> float:
    """Get the total for a month for any specified date."""
    return sum(
        self.values[day.py_date()]
        for day in iterate_timespan(
            month,
            days(1),
            monthrange(month.year, month.month)[1],
        )
    )

generate_empty_activity staticmethod

generate_empty_activity(year: int) -> list[list[date | None]]

Generates empty data for a specified year.

PARAMETER DESCRIPTION
year

Year to generate. Minimum year 1 to a maximum year 9998.

TYPE: int

RETURNS DESCRIPTION
list[list[date | None]]

A 2 dimensional array of dates or None if the day belongs to another year.

Source code in src/textual_timepiece/_activity_heatmap.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
@staticmethod
def generate_empty_activity(year: int) -> list[list[date | None]]:
    """Generates empty data for a specified year.

    Args:
        year: Year to generate. Minimum year 1 to a maximum year 9998.

    Returns:
        A 2 dimensional array of dates or None if the day belongs to
            another year.
    """
    raw = list(
        chain.from_iterable(Calendar().yeardatescalendar(year, 12)[0])
    )
    new_cal: list[list[date | None]] = []
    for i, week in enumerate(raw):
        if i and week[0] in new_cal[-1]:
            continue

        new_cal.append([])
        for day in week:
            if day.year != year:
                new_cal[-1].append(None)
            else:
                new_cal[-1].append(day)

    return new_cal

HeatmapManager

Bases: BaseWidget

Composite widget that manages navigating a heatmap.

PARAMETER DESCRIPTION
year

Initial value for the year.

TYPE: int | None DEFAULT: None

name

The name of the widget.

TYPE: str | None DEFAULT: None

id

The ID of the widget in the DOM.

TYPE: str | None DEFAULT: None

classes

The CSS classes for the widget.

TYPE: str | None DEFAULT: None

disabled

Whether the widget is disabled or not.

TYPE: bool DEFAULT: False

CLASS DESCRIPTION
YearChanged

Message sent when the year is updated.

ATTRIBUTE DESCRIPTION
DEFAULT_CSS

Default CSS for the HeatmapManager.

TYPE: str

year

Current year that the widget is set to. Max is 9999 and minimum 1

navigation

Horizonal bar holding all navigation widgets.

TYPE: Horizontal

year_input

Input widget showing the selected year.

TYPE: MaskedInput

heatmap

Underlying ActivityHeatmap displaying data.

TYPE: ActivityHeatmap

Source code in src/textual_timepiece/_activity_heatmap.py
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
class HeatmapManager(BaseWidget):
    """Composite widget that manages navigating a heatmap.

    Params:
        year: Initial value for the year.
        name: The name of the widget.
        id: The ID of the widget in the DOM.
        classes: The CSS classes for the widget.
        disabled: Whether the widget is disabled or not.
    """

    @dataclass
    class YearChanged(BaseMessage):
        """Message sent when the year is updated."""

        widget: HeatmapManager
        year: int

    DEFAULT_CSS: ClassVar[str] = """
    HeatmapManager {
        layout: vertical;
        align: center middle;
        height: auto;
        width: auto;

        Horizontal#navigation {
            align-horizontal: center;
            max-height: 1;
            hatch: vertical $secondary 10%;

            & > #year-input {
                align-horizontal: center;
                width: auto;
                min-width: 8;
                height: 1;
                border: none;
            }

            & > .nav {
                border: none;
                &Button {
                    max-width: 4;
                    text-align: center;

                    &#today-button {
                        width: auto;
                    }
                }
            }
        }

        &:focus-within {
            Horizontal#navigation {
                hatch: vertical $primary 30%;
            }
        }
    }
    """
    """Default CSS for the `HeatmapManager`."""

    year = var[int](
        lambda: Date.today_in_system_tz().year, init=False, bindings=True
    )
    """Current year that the widget is set to. Max is 9999 and minimum 1"""

    def __init__(
        self,
        year: int | None = None,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
        disabled: bool = False,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes, disabled=disabled)
        if year:
            self.set_reactive(HeatmapManager.year, year)

    def _validate_year(self, year: int) -> int:
        return max(1, min(year, 9999))

    def compose(self) -> ComposeResult:
        with Horizontal(id="navigation"):
            yield Button(
                "<<",
                id="prev-year-5",
                classes="nav",
                tooltip="Jump Back Five Years",
            )
            yield Button(
                "<",
                id="prev-year",
                classes="nav",
                tooltip="View Previous Year",
            )
            yield MaskedInput(
                "9999",
                str(self.year),
                classes="nav",
                valid_empty=False,
                validators=[Integer(minimum=1, maximum=9998)],
                validate_on=("blur", "submitted"),
                id="year-input",
            )
            yield TargetButton(
                id="today-button",
                classes="nav",
                tooltip="View Current Year",
                disabled=True,
            )
            yield Button(
                ">",
                id="next-year",
                classes="nav",
                tooltip="View Next Year",
            )
            yield Button(
                ">>",
                id="next-year-5",
                classes="nav",
                tooltip="Jump Forward Five Years",
            )

        with Horizontal():
            yield Center(ActivityHeatmap().data_bind(HeatmapManager.year))

    def _watch_year(self, year: int) -> None:
        for button in self.navigation.query(Button):
            if button.id in {"prev-year-5", "prev-year"}:
                button.disabled = year <= 1
            elif button.id in {"next-year", "next-year-5"}:
                button.disabled = year >= 9998
            elif button.id == "today-button":
                button.disabled = year == Date.today_in_system_tz().year
        self.post_message(self.YearChanged(self, year))

    def _on_descendant_focus(self) -> None:
        self.navigation.refresh()

    def _on_descendant_blur(self) -> None:
        self.navigation.refresh()

    @on(Input.Submitted)
    @on(DescendantBlur)
    def _verify_year(self, message: Input.Submitted | DescendantBlur) -> None:
        message.stop()
        if not isinstance(message.control, Input):
            return

        if message.control.is_valid:
            try:
                self.year = int(message.control.value)
            except ValueError:
                return

    def _on_button_pressed(self, message: Button.Pressed) -> None:
        message.stop()
        if message.button.id == "prev-year-5":
            self.year -= 5
        elif message.button.id == "prev-year":
            self.year -= 1
        elif message.button.id == "next-year":
            self.year += 1
        elif message.button.id == "next-year-5":
            self.year += 5
        elif message.button.id == "today-button":
            self.year = Date.today_in_system_tz().year

        with self.year_input.prevent(Input.Changed):
            self.year_input.value = str(self.year)

    @cached_property
    def navigation(self) -> Horizontal:
        """`Horizonal` bar holding all navigation widgets."""
        return self.query_one("#navigation", Horizontal)

    @cached_property
    def year_input(self) -> MaskedInput:
        """Input widget showing the selected year."""
        return self.query_exactly_one(MaskedInput)

    @cached_property
    def heatmap(self) -> ActivityHeatmap:
        """Underlying `ActivityHeatmap` displaying data."""
        return self.query_exactly_one(ActivityHeatmap)

DEFAULT_CSS class-attribute

HeatmapManager {
    layout: vertical;
    align: center middle;
    height: auto;
    width: auto;

    Horizontal#navigation {
        align-horizontal: center;
        max-height: 1;
        hatch: vertical $secondary 10%;

        & > #year-input {
            align-horizontal: center;
            width: auto;
            min-width: 8;
            height: 1;
            border: none;
        }

        & > .nav {
            border: none;
            &Button {
                max-width: 4;
                text-align: center;

                &#today-button {
                    width: auto;
                }
            }
        }
    }

    &:focus-within {
        Horizontal#navigation {
            hatch: vertical $primary 30%;
        }
    }
}

Default CSS for the HeatmapManager.

year class-attribute instance-attribute

year = var[int](lambda: year, init=False, bindings=True)

Current year that the widget is set to. Max is 9999 and minimum 1

navigation cached property

navigation: Horizontal

Horizonal bar holding all navigation widgets.

year_input cached property

year_input: MaskedInput

Input widget showing the selected year.

heatmap cached property

heatmap: ActivityHeatmap

Underlying ActivityHeatmap displaying data.

YearChanged dataclass

Bases: BaseMessage

Message sent when the year is updated.

Source code in src/textual_timepiece/_activity_heatmap.py
749
750
751
752
753
754
@dataclass
class YearChanged(BaseMessage):
    """Message sent when the year is updated."""

    widget: HeatmapManager
    year: int