File: section.py

package info (click to toggle)
python-discord 2.6.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,476 kB
  • sloc: python: 49,910; javascript: 363; makefile: 154
file content (255 lines) | stat: -rw-r--r-- 7,753 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
"""
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Dict, Generator, List, Literal, Optional, TypeVar, Union, ClassVar

from .item import Item
from .text_display import TextDisplay
from ..enums import ComponentType
from ..utils import MISSING, get as _utils_get

if TYPE_CHECKING:
    from typing_extensions import Self

    from .view import LayoutView
    from ..components import SectionComponent

V = TypeVar('V', bound='LayoutView', covariant=True)

__all__ = ('Section',)


class Section(Item[V]):
    r"""Represents a UI section.

    This is a top-level layout component that can only be used on :class:`LayoutView`.

    .. versionadded:: 2.6

    Parameters
    ----------
    \*children: Union[:class:`str`, :class:`TextDisplay`]
        The text displays of this section. Up to 3.
    accessory: :class:`Item`
        The section accessory.
    id: Optional[:class:`int`]
        The ID of this component. This must be unique across the view.
    """

    __item_repr_attributes__ = (
        'accessory',
        'id',
    )
    __discord_ui_section__: ClassVar[bool] = True

    __slots__ = (
        '_children',
        'accessory',
    )

    def __init__(
        self,
        *children: Union[Item[V], str],
        accessory: Item[V],
        id: Optional[int] = None,
    ) -> None:
        super().__init__()
        self._children: List[Item[V]] = []
        if children:
            if len(children) > 3:
                raise ValueError('maximum number of children exceeded')
            self._children.extend(
                [c if isinstance(c, Item) else TextDisplay(c) for c in children],
            )
        self.accessory: Item[V] = accessory
        self.id = id

    def __repr__(self) -> str:
        return f'<{self.__class__.__name__} children={len(self._children)}>'

    @property
    def type(self) -> Literal[ComponentType.section]:
        return ComponentType.section

    @property
    def children(self) -> List[Item[V]]:
        """List[:class:`Item`]: The list of children attached to this section."""
        return self._children.copy()

    @property
    def width(self):
        return 5

    def _is_v2(self) -> bool:
        return True

    def walk_children(self) -> Generator[Item[V], None, None]:
        """An iterator that recursively walks through all the children of this section
        and its children, if applicable. This includes the `accessory`.

        Yields
        ------
        :class:`Item`
            An item in this section.
        """

        for child in self.children:
            yield child
        yield self.accessory

    def _update_view(self, view) -> None:
        self._view = view
        self.accessory._view = view
        for child in self._children:
            child._view = view

    def _has_children(self):
        return True

    def content_length(self) -> int:
        """:class:`int`: Returns the total length of all text content in this section."""
        from .text_display import TextDisplay

        return sum(len(item.content) for item in self._children if isinstance(item, TextDisplay))

    def add_item(self, item: Union[str, Item[Any]]) -> Self:
        """Adds an item to this section.

        This function returns the class instance to allow for fluent-style
        chaining.

        Parameters
        ----------
        item: Union[:class:`str`, :class:`Item`]
            The item to append, if it is a string it automatically wrapped around
            :class:`TextDisplay`.

        Raises
        ------
        TypeError
            An :class:`Item` or :class:`str` was not passed.
        ValueError
            Maximum number of children has been exceeded (3) or (40)
            for the entire view.
        """

        if len(self._children) >= 3:
            raise ValueError('maximum number of children exceeded (3)')

        if not isinstance(item, (Item, str)):
            raise TypeError(f'expected Item or str not {item.__class__.__name__}')

        if self._view:
            self._view._add_count(1)

        item = item if isinstance(item, Item) else TextDisplay(item)
        item._update_view(self.view)
        item._parent = self
        self._children.append(item)

        return self

    def remove_item(self, item: Item[Any]) -> Self:
        """Removes an item from this section.

        This function returns the class instance to allow for fluent-style
        chaining.

        Parameters
        ----------
        item: :class:`Item`
            The item to remove from the section.
        """

        try:
            self._children.remove(item)
        except ValueError:
            pass
        else:
            if self._view:
                self._view._add_count(-1)

        return self

    def find_item(self, id: int, /) -> Optional[Item[V]]:
        """Gets an item with :attr:`Item.id` set as ``id``, or ``None`` if
        not found.

        .. warning::

            This is **not the same** as ``custom_id``.

        Parameters
        ----------
        id: :class:`int`
            The ID of the component.

        Returns
        -------
        Optional[:class:`Item`]
            The item found, or ``None``.
        """
        return _utils_get(self.walk_children(), id=id)

    def clear_items(self) -> Self:
        """Removes all the items from the section.

        This function returns the class instance to allow for fluent-style
        chaining.
        """
        if self._view:
            self._view._add_count(-len(self._children))  # we don't count the accessory because it is required

        self._children.clear()
        return self

    @classmethod
    def from_component(cls, component: SectionComponent) -> Self:
        from .view import _component_to_item

        # using MISSING as accessory so we can create the new one with the parent set
        self = cls(id=component.id, accessory=MISSING)
        self.accessory = _component_to_item(component.accessory, self)
        self.id = component.id
        self._children = [_component_to_item(c, self) for c in component.children]

        return self

    def to_components(self) -> List[Dict[str, Any]]:
        components = []

        for component in self._children:
            components.append(component.to_component_dict())
        return components

    def to_component_dict(self) -> Dict[str, Any]:
        data = {
            'type': self.type.value,
            'components': self.to_components(),
            'accessory': self.accessory.to_component_dict(),
        }
        if self.id is not None:
            data['id'] = self.id
        return data