taskli-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
taskli/py.typed ADDED
File without changes
taskli/render.py ADDED
@@ -0,0 +1,520 @@
1
+ """CLI Taskli rendering function."""
2
+
3
+ from collections.abc import Iterator
4
+ from datetime import datetime
5
+
6
+ from rich.console import Console, Group, RenderableType
7
+ from rich.panel import Panel
8
+ from rich.table import Table
9
+ from rich.text import Text
10
+ from rich.tree import Tree
11
+
12
+ from .hierarchy import ancestor_chain
13
+ from .models import registry
14
+ from .models.attributes import Color
15
+ from .models.config import Config
16
+ from .models.dates import today
17
+ from .models.tasks import TaskliItem, TaskliList
18
+
19
+ __all__ = [
20
+ "render_items",
21
+ "render_list_tree",
22
+ "render_list_names",
23
+ "render_agenda",
24
+ "render_item_details",
25
+ "render_config",
26
+ "render_message",
27
+ "render_value",
28
+ "render_error",
29
+ "render_warning",
30
+ "render_reminder",
31
+ ]
32
+
33
+ _console = Console()
34
+ _err_console = Console(stderr=True)
35
+
36
+
37
+ def _span(text: str, style: str = "") -> Text:
38
+ """Build a Text whose style is span-scoped, not painting cell padding."""
39
+
40
+ result = Text()
41
+ result.append(text, style=style)
42
+
43
+ return result
44
+
45
+
46
+ def _label(
47
+ name: str, color: str | Color | None, *, bold: bool = False
48
+ ) -> Text:
49
+ """Build a Text label, bold and/or list-colored per the flags."""
50
+
51
+ parts: list[str] = []
52
+ if bold:
53
+ parts.append("bold")
54
+ if color is not None:
55
+ parts.append(str(color))
56
+
57
+ return _span(name, " ".join(parts))
58
+
59
+
60
+ def _task_rows(
61
+ items: list[TaskliItem], prefix: str = "", top: bool = True
62
+ ) -> Iterator[tuple[TaskliItem, str]]:
63
+ """Yield each item with its tree-branch prefix, pre-order DFS."""
64
+
65
+ for item in items:
66
+ is_last = item is items[-1]
67
+ if top:
68
+ yield item, ""
69
+ yield from _task_rows(item.children, "", top=False)
70
+ continue
71
+
72
+ connector = "└── " if is_last else "├── "
73
+ yield item, prefix + connector
74
+ ext = " " if is_last else "│ "
75
+ yield from _task_rows(item.children, prefix + ext, top=False)
76
+
77
+
78
+ def _task_cell(item: TaskliItem, prefix: str) -> Text:
79
+ """Build the Task cell: prefix, state marker, id, text, and ¶."""
80
+
81
+ result = Text()
82
+ result.append(prefix, style="dim")
83
+ result.append(f"{item.status.marker} ", style=item.status.marker_style)
84
+ dim = "dim" if item.done else ""
85
+ # trailing dot at every level: "2" -> "2.", "2.1" -> "2.1."
86
+ result.append(f"{item.id}. ", style=dim)
87
+ result.append(item.text, style="dim strike" if item.done else "")
88
+ if item.description:
89
+ result.append(" ¶", style="dim strike" if item.done else "dim")
90
+
91
+ return result
92
+
93
+
94
+ def _items_table(items: list[TaskliItem], color: Color | None = None) -> Table:
95
+ """Build a table of tasks.
96
+
97
+ Parameters
98
+ ----------
99
+ items : list[TaskliItem]
100
+ The top-level items; children render as their own nested rows.
101
+
102
+ Returns
103
+ -------
104
+ Table
105
+ The rendered table.
106
+ """
107
+
108
+ columns = registry.renderable()
109
+
110
+ table = Table()
111
+ table.add_column(_label("Task", color), justify="left")
112
+ for column in columns:
113
+ table.add_column(_label(column.header, color), justify=column.justify)
114
+
115
+ for item, prefix in _task_rows(items):
116
+ cells: list[str | Text] = [_task_cell(item, prefix)]
117
+ for column in columns:
118
+ cell = column.format(item)
119
+ style = column.style(item) if column.style is not None else None
120
+ cells.append(_span(cell, style) if style else cell)
121
+ table.add_row(*cells)
122
+
123
+ return table
124
+
125
+
126
+ def render_items(
127
+ list_name: str, items: list[TaskliItem], color: Color | None = None
128
+ ) -> None:
129
+ """Print a table of tasks for a list.
130
+
131
+ Parameters
132
+ ----------
133
+ list_name : str
134
+ The list's name, shown in the table title.
135
+ items : list[TaskliItem]
136
+ The top-level items; children render as their own nested rows.
137
+ color : Color | None, optional
138
+ The list's display color, by default none.
139
+ """
140
+
141
+ table = Group(
142
+ _label(list_name, color, bold=True), _items_table(items, color)
143
+ )
144
+ _console.print(table)
145
+
146
+ return None
147
+
148
+
149
+ def render_list_tree(
150
+ lists: list[TaskliList],
151
+ delimiter: str = ".",
152
+ ) -> None:
153
+ """Print item tables nested in a parent-indented tree.
154
+
155
+ Parameters
156
+ ----------
157
+ lists : list[TaskliList]
158
+ Ordered TaskliList objects, where subsequent items are descendant
159
+ lists.
160
+ delimiter : str, optional
161
+ Display delimiter for the root section's name, by default ".".
162
+ """
163
+
164
+ if not lists:
165
+ return None
166
+
167
+ head = lists[0]
168
+ head_node = Tree(
169
+ Group(
170
+ _label(head.display_name(delimiter), head.color, bold=True),
171
+ _items_table(head.items, head.color),
172
+ )
173
+ )
174
+ nodes: dict[str, Tree] = {head.name: head_node}
175
+
176
+ for sublist in lists[1:]:
177
+ parent_name = sublist.name.rsplit(".", 1)[0]
178
+ parent = nodes.get(parent_name, head_node)
179
+ label = sublist.name.rsplit(".", 1)[-1]
180
+ node = parent.add(
181
+ Group(
182
+ _label(label, sublist.color, bold=True),
183
+ _items_table(sublist.items, sublist.color),
184
+ )
185
+ )
186
+ nodes[sublist.name] = node
187
+
188
+ _console.print(head_node)
189
+
190
+ return None
191
+
192
+
193
+ def render_list_names(
194
+ entries: list[tuple[str, Color | None]],
195
+ default_name: str | None = None,
196
+ ) -> None:
197
+ """Print list names as a parent-indented tree.
198
+
199
+ Parameters
200
+ ----------
201
+ entries : list[tuple[str, Color | None]]
202
+ (list_name, color) pairs for all existing lists (flat), in
203
+ any order.
204
+ default_name : str | None, optional
205
+ Dot-normalized name of the configured default list, bolded in
206
+ the tree if present, by default none.
207
+ """
208
+
209
+ if not entries:
210
+ _console.print(Text("no lists yet.", style="dim"))
211
+
212
+ return None
213
+
214
+ colors = dict(entries)
215
+
216
+ # create a tree for each root of a list.
217
+ roots: dict[str, Tree] = {}
218
+ nodes: dict[str, Tree] = {}
219
+
220
+ for name in sorted(colors):
221
+ parent = None
222
+ chain = [*ancestor_chain(name), name]
223
+ for i in chain:
224
+ if i in nodes:
225
+ parent = nodes[i]
226
+ continue
227
+
228
+ node_bold = i == default_name
229
+
230
+ if parent is None:
231
+ node = Tree(_label(i, colors.get(i), bold=node_bold))
232
+ roots[i] = node
233
+ else:
234
+ label = i.rsplit(".", 1)[-1]
235
+ node = parent.add(_label(label, colors.get(i), bold=node_bold))
236
+
237
+ nodes[i] = node
238
+ parent = node
239
+
240
+ _console.print(*list(roots.values()))
241
+
242
+ return None
243
+
244
+
245
+ def _attr_display(name: str, item: TaskliItem) -> tuple[str, str | None]:
246
+ """Return an item's formatted attribute value and its rich style.
247
+
248
+ Parameters
249
+ ----------
250
+ name : str
251
+ The registry attribute name (``"priority"``, ``"due_date"``).
252
+ item : TaskliItem
253
+ The item whose cell to build.
254
+
255
+ Returns
256
+ -------
257
+ tuple[str, str | None]
258
+ The formatted value and the style name (``None`` when the cell
259
+ should render plain), both from the attribute's registry entry.
260
+ """
261
+
262
+ attr = registry.ATTRIBUTES[name]
263
+ assert attr.render_format is not None
264
+ style = attr.render_style(item) if attr.render_style is not None else None
265
+
266
+ return attr.render_format(item), style
267
+
268
+
269
+ def _due_display(item: TaskliItem) -> tuple[str, str | None]:
270
+ """Return an item's formatted due date and its rich style.
271
+
272
+ Parameters
273
+ ----------
274
+ item : TaskliItem
275
+ The item whose due-date cell to build.
276
+
277
+ Returns
278
+ -------
279
+ tuple[str, str | None]
280
+ The formatted date string and the style name, shared by
281
+ ``render_agenda`` and ``render_item_details``.
282
+ """
283
+
284
+ return _attr_display("due_date", item)
285
+
286
+
287
+ def render_agenda(
288
+ rows: list[tuple[str, TaskliItem]], delimiter: str = "."
289
+ ) -> None:
290
+ """Print a chronological, cross-list table of due items.
291
+
292
+ Parameters
293
+ ----------
294
+ rows : list[tuple[str, TaskliItem]]
295
+ (list_name, item) pairs, in the order they should render.
296
+ delimiter : str, optional
297
+ Display delimiter for each row's list name, by default ".".
298
+ """
299
+
300
+ if not rows:
301
+ _console.print(Text("nothing on the agenda.", style="dim"))
302
+
303
+ return None
304
+
305
+ priority_attr = registry.ATTRIBUTES["priority"]
306
+ assert priority_attr.column_header is not None
307
+
308
+ table = Table()
309
+ table.add_column("List")
310
+ table.add_column("Task")
311
+ table.add_column(
312
+ priority_attr.column_header, justify=priority_attr.column_justify
313
+ )
314
+ table.add_column("Due")
315
+
316
+ display_names: dict[str, str] = {}
317
+ for name, item in rows:
318
+ if name not in display_names:
319
+ display_names[name] = TaskliList(name=name).display_name(delimiter)
320
+
321
+ label, label_style = _attr_display("priority", item)
322
+ priority = _span(label, label_style) if label_style else label
323
+ formatted, style = _due_display(item)
324
+ due = _span(formatted, style) if style else formatted
325
+ table.add_row(display_names[name], _task_cell(item, ""), priority, due)
326
+
327
+ _console.print(table)
328
+
329
+ return None
330
+
331
+
332
+ def _relative_due(due: datetime) -> str:
333
+ """Return a human phrase for a due date relative to today."""
334
+
335
+ delta = (due.date() - today()).days
336
+ if delta == 0:
337
+ return "today"
338
+ if delta == 1:
339
+ return "tomorrow"
340
+ if delta == -1:
341
+ return "yesterday"
342
+ if delta > 1:
343
+ return f"in {delta} days"
344
+
345
+ return f"{-delta} days ago"
346
+
347
+
348
+ def render_item_details(
349
+ task_list: TaskliList, item: TaskliItem, delimiter: str = "."
350
+ ) -> None:
351
+ """Print a single task's full detail as a bordered panel.
352
+
353
+ Parameters
354
+ ----------
355
+ task_list : TaskliList
356
+ The list holding the item, named in the panel title.
357
+ item : TaskliItem
358
+ The item to show.
359
+ delimiter : str, optional
360
+ Display delimiter for the panel title's list name, by default ".".
361
+ """
362
+
363
+ header = Text()
364
+ header.append(f"{item.status.marker} ", style=item.status.marker_style)
365
+ header.append(item.text, style="bold strike" if item.done else "bold")
366
+
367
+ metadata = Table.grid(padding=(0, 2))
368
+ metadata.add_column()
369
+ metadata.add_column()
370
+
371
+ meta_rows: list[tuple[str, str | Text]] = [
372
+ ("status", item.status.label),
373
+ ("priority", _span(item.priority.label, item.priority.color)),
374
+ ]
375
+ if item.tags:
376
+ meta_rows.append(("tags", ", ".join(item.tags)))
377
+ if item.due_date is not None:
378
+ formatted, due_style = _due_display(item)
379
+ due_value = f"{formatted} ({_relative_due(item.due_date)})"
380
+ meta_rows.append(
381
+ ("due", _span(due_value, due_style) if due_style else due_value)
382
+ )
383
+ meta_rows.append(("created", item.created_at.strftime("%Y-%m-%d %H:%M")))
384
+ if item.modified_at is not None:
385
+ meta_rows.append(
386
+ ("modified", item.modified_at.strftime("%Y-%m-%d %H:%M"))
387
+ )
388
+
389
+ for label, value in meta_rows:
390
+ metadata.add_row(_span(label, "dim"), value)
391
+
392
+ parts: list[RenderableType] = [header, "", metadata]
393
+
394
+ if item.description:
395
+ description = Text()
396
+ description.append("description", style="dim")
397
+ for line in item.description.splitlines():
398
+ description.append(f"\n {line}")
399
+ parts += ["", description]
400
+
401
+ if item.children:
402
+ subtasks = Text()
403
+ subtasks.append("subtasks", style="dim")
404
+ subtasks.append("\n")
405
+ for child, prefix in _task_rows(item.children):
406
+ subtasks.append_text(_task_cell(child, prefix))
407
+ subtasks.append("\n")
408
+ parts += ["", subtasks]
409
+
410
+ panel = Panel(
411
+ Group(*parts),
412
+ title=f"{task_list.display_name(delimiter)} / {item.id}",
413
+ title_align="left",
414
+ border_style="dim",
415
+ padding=(0, 1),
416
+ )
417
+ _console.print(panel)
418
+
419
+ return None
420
+
421
+
422
+ def render_config(config: Config) -> None:
423
+ """Print a table of all config keys and their current values.
424
+
425
+ Parameters
426
+ ----------
427
+ config : Config
428
+ The config to display.
429
+ """
430
+
431
+ table = Table()
432
+ table.add_column("Key")
433
+ table.add_column("Value")
434
+
435
+ keys = config.model_dump().keys()
436
+ for key in keys:
437
+ table.add_row(_span(key), _span(str(config.get_value(key))))
438
+
439
+ _console.print(table)
440
+
441
+ return None
442
+
443
+
444
+ def render_message(message: str) -> None:
445
+ """Print a plain status message.
446
+
447
+ Parameters
448
+ ----------
449
+ message : str
450
+ The message text.
451
+ """
452
+
453
+ _console.print(Text(message))
454
+
455
+ return None
456
+
457
+
458
+ def render_value(value: str) -> None:
459
+ """Print a raw value verbatim, without markup or line wrapping.
460
+
461
+ Parameters
462
+ ----------
463
+ value : str
464
+ The value to print (e.g. a storage path or a config value).
465
+ """
466
+
467
+ _console.print(Text(value), highlight=False, soft_wrap=True)
468
+
469
+ return None
470
+
471
+
472
+ def render_error(message: str) -> None:
473
+ """Print an error message in red.
474
+
475
+ Parameters
476
+ ----------
477
+ message : str
478
+ The error text.
479
+ """
480
+
481
+ _err_console.print(Text.assemble(("error:", "bold red"), f" {message}"))
482
+
483
+ return None
484
+
485
+
486
+ def render_warning(message: str) -> None:
487
+ """Print a non-fatal warning message in yellow.
488
+
489
+ Parameters
490
+ ----------
491
+ message : str
492
+ The warning text.
493
+ """
494
+
495
+ _console.print(Text.assemble(("warning:", "bold yellow"), f" {message}"))
496
+
497
+ return None
498
+
499
+
500
+ def render_reminder(overdue: int, due_today: int) -> None:
501
+ """Print a due/overdue reminder banner to stderr.
502
+
503
+ Parameters
504
+ ----------
505
+ overdue : int
506
+ The number of overdue, not-done items.
507
+ due_today : int
508
+ The number of items due today.
509
+ """
510
+
511
+ parts: list[str] = []
512
+ if overdue:
513
+ parts.append(f"{overdue} overdue")
514
+ if due_today:
515
+ parts.append(f"{due_today} due today")
516
+ message = ", ".join(parts)
517
+
518
+ _err_console.print(Text.assemble(("⚠", "bold yellow"), f" {message}"))
519
+
520
+ return None