Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions discord/ui/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,21 @@ def key(item: ViewItem[V]) -> int:

return components

def to_component_instances(self) -> list[Component]:
"""Converts this view's items into component class instances.

This is useful for in-memory state snapshots and later restoration with
:meth:`from_components`.

Returns
-------
List[:class:`.Component`]
The converted component instances. For :class:`View`, the returned
list contains top-level :class:`~discord.components.ActionRow`
components with their children attached.
"""
return [_component_factory(component) for component in self.to_components()]

@classmethod
def from_message(
cls, message: Message, /, *, timeout: float | None = 180.0
Expand Down Expand Up @@ -706,6 +721,42 @@ def from_dict(
view.add_item(_component_to_item(component))
return view

@classmethod
def from_components(
cls,
components: list[Component],
/,
*,
timeout: float | None = 180.0,
Comment thread
tobezdev marked this conversation as resolved.
) -> View:
"""Converts component class instances into a :class:`View`.

Parameters
----------
components: List[:class:`.Component`]
The components to convert into a view.
timeout: Optional[:class:`float`]
The timeout of the converted view.

Returns
-------
:class:`View`
The converted view. This always returns a :class:`View` and not
one of its subclasses.
"""
view = View(timeout=timeout)
for row_index, component in enumerate(components):
if isinstance(component, ActionRowComponent):
for child in component.children:
item = _component_to_item(child)
with contextlib.suppress(AttributeError, ValueError):
Comment thread
tobezdev marked this conversation as resolved.
Outdated
Comment thread
tobezdev marked this conversation as resolved.
Outdated
item.row = row_index
view.add_item(item)
continue

view.add_item(_component_to_item(component))
return view

def add_item(self, item: ViewItem[V]) -> Self:
"""Adds an item to the view. Attempting to add a :class:`~discord.ui.ActionRow` will add its children instead.

Expand Down Expand Up @@ -938,6 +989,47 @@ def add_item(self, item: ViewItem[V]) -> Self:
super().add_item(item)
return self

def to_component_instances(self) -> list[Component]:
"""Converts this view's items into component class instances.

This is useful for in-memory state snapshots and later restoration with
:meth:`from_components`.

Returns
-------
List[:class:`.Component`]
The converted component instances.
"""
return [_component_factory(component) for component in self.to_components()]
Comment thread
tobezdev marked this conversation as resolved.
Outdated

@classmethod
def from_components(
cls,
components: list[Component],
/,
*,
timeout: float | None = 180.0,
Comment thread
tobezdev marked this conversation as resolved.
) -> DesignerView:
"""Converts component class instances into a :class:`DesignerView`.

Parameters
----------
components: List[:class:`.Component`]
The components to convert into a view.
timeout: Optional[:class:`float`]
The timeout of the converted view.

Returns
-------
:class:`DesignerView`
The converted view. This always returns a :class:`DesignerView` and
not one of its subclasses.
"""
view = DesignerView(timeout=timeout)
for component in components:
view.add_item(_component_to_item(component))
return view

def _refresh(self, components: list[Component]):
# Refreshes view data using discord's values
# Assumes the components and items are identical
Expand Down
79 changes: 79 additions & 0 deletions tests/ui/test_view_component_instances.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""
The MIT License (MIT)

Copyright (c) 2015-2021 Rapptz
Comment thread
tobezdev marked this conversation as resolved.
Outdated
Copyright (c) 2021-present Pycord Development

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.
"""

import pytest

import discord
from discord.components import ActionRow as ActionRowComponent
from discord.components import Container as ContainerComponent


@pytest.mark.asyncio
async def test_view_component_instances_roundtrip():
view = discord.ui.View(timeout=90.0)
view.add_item(discord.ui.Button(label="Primary", custom_id="primary"))
view.add_item(discord.ui.Button(label="Secondary", custom_id="secondary", row=1))
Comment thread
tobezdev marked this conversation as resolved.

components = view.to_component_instances()

assert all(isinstance(component, ActionRowComponent) for component in components)

restored = discord.ui.View.from_components(components, timeout=30.0)

assert restored.timeout == 30.0
assert restored.to_components() == view.to_components()


@pytest.mark.asyncio
async def test_designerview_component_instances_roundtrip():
view = discord.ui.DesignerView(timeout=120.0)
view.add_item(discord.ui.TextDisplay("Top level text"))
view.add_item(
discord.ui.ActionRow(
discord.ui.Button(label="Inside row", custom_id="inside-row"),
)
)
view.add_item(discord.ui.Container(discord.ui.TextDisplay("Nested text")))

components = view.to_component_instances()

assert any(isinstance(component, ContainerComponent) for component in components)

restored = discord.ui.DesignerView.from_components(components, timeout=None)

assert restored.timeout is None
assert restored.to_components() == view.to_components()


@pytest.mark.asyncio
async def test_existing_dict_roundtrip_unchanged():
view = discord.ui.View(timeout=45.0)
view.add_item(discord.ui.Button(label="Dict path", custom_id="dict-path"))

payload = view.to_components()
restored = discord.ui.View.from_dict(payload, timeout=None)

assert restored.timeout is None
assert restored.to_components() == payload
Loading