Debian Codegraph @

recurring_ical_events/pages.py

raw symbols SCIP
1 """Pagination for recurring ical events.
2
3 See https://github.com/niccokunzmann/python-recurring-ical-events/issues/211
4 """
5
6 from __future__ import annotations
7
8 from typing import TYPE_CHECKING, Iterator, Optional
9
10 from recurring_ical_events.util import compare_greater
11
12 if TYPE_CHECKING:
13 from icalendar import Component
14
15 from recurring_ical_events.occurrence import Occurrence
16 from recurring_ical_events.types import Time
17
18
19 class Page:
20 """One page in a series of pages.
21
22 Examples:
23 Check if the page has components.
24
25 .. code-block:: python
26
27 if page:
28 print(f"We have {len(page)} components.")
29
30 Go though the components:
31
32 .. code-block:: python
33
34 for component in page:
35 print(component)
36 """
37
38 def __init__(self, components: list[Component], next_page_id: str = ""):
39 """ "Create a new page."""
40 self._components = components
41 self._next_page_id = next_page_id
42
43 @property
44 def components(self) -> list[Component]:
45 """All the components of this page."""
46 return self._components
47
48 def has_next_page(self) -> bool:
49 """Wether there is a page following this one."""
50 return self.next_page_id != ""
51
52 @property
53 def next_page_id(self) -> str:
54 """The id of the next page or ``''``."""
55 return self._next_page_id
56
57 def __len__(self) -> int:
58 """The number of components."""
59 return len(self.components)
60
61 def is_last(self) -> bool:
62 """Wether this is the last page and there is no other page following."""
63 return self._next_page_id == ""
64
65 def __iter__(self) -> Iterator[Component]:
66 """Return an iterator over the components."""
67 return iter(self.components)
68
69
70 class Pages:
71 """A pagination configuration to iterate over pages.
72
73 This is an :class:`Iterator` that returns :class:`Page` objects.
74 """
75
76 def __init__(
77 self,
78 occurrence_iterator: Iterator[Occurrence],
79 size: int,
80 stop: Optional[Time] = None,
81 keep_recurrence_attributes: bool = False, # noqa: FBT001
82 ):
83 """Create a new paginated iterator over components."""
84 self._iterator = occurrence_iterator
85 self._stop = stop
86 self._size = size
87 if self._size <= 0:
88 raise ValueError(
89 f"A page must have at least one component, not {self._size}."
90 )
91 self._keep_recurrence_attributes = keep_recurrence_attributes
92 self._next_occurrence: Optional[Occurrence] = None
93 for occurrence in self._iterator:
94 if self._stop is None or compare_greater(self._stop, occurrence.start):
95 self._next_occurrence = occurrence
96 break
97
98 @property
99 def size(self) -> int:
100 """The maximum number of components per page."""
101 return self._size
102
103 def generate_next_page(self) -> Page:
104 """Generate the next page.
105
106 In contrast to ``next(pages)``, this does not raise :class:`StopIteration`.
107 But it works the same: the next page is generated and returned.
108 The last page is empty.
109 """
110 for page in self:
111 return page
112 return Page([])
113
114 def __next__(self) -> Page:
115 """Return the next page."""
116 if self._next_occurrence is None:
117 raise StopIteration
118 last_occurrence = self._next_occurrence
119 occurrences = [last_occurrence]
120 for occurrence in self._iterator:
121 if self._stop is not None and compare_greater(occurrence.start, self._stop):
122 break
123 last_occurrence = occurrence
124 if len(occurrences) < self._size:
125 occurrences.append(occurrence)
126 else:
127 break
128 if occurrences[-1] == last_occurrence:
129 self._next_occurrence = None
130 else:
131 self._next_occurrence = last_occurrence
132 return self._create_page_from_occurrences(occurrences)
133
134 def _create_page_from_occurrences(self, occurrences: list[Occurrence]) -> Page:
135 """Create a new page from the occurrences listed."""
136 return Page(
137 [
138 occurrence.as_component(self._keep_recurrence_attributes)
139 for occurrence in occurrences
140 ],
141 next_page_id=self._next_occurrence.id.to_string()
142 if self._next_occurrence is not None
143 else "",
144 )
145
146 def __iter__(self) -> Pages:
147 """Return the iterator."""
148 return self
149
150
151 __all__ = ["Page", "Pages"]