Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • hive/clive
1 result
Show changes
Commits on Source (10)
Showing
with 609 additions and 245 deletions
......@@ -9,7 +9,7 @@ if TYPE_CHECKING:
@lru_cache(maxsize=2048)
def __count_parameters(callback: Callable[..., Any]) -> int:
def count_parameters(callback: Callable[..., Any]) -> int:
"""Count the number of parameters in a callable."""
return len(signature(callback).parameters)
......@@ -27,7 +27,7 @@ async def invoke(callback: Callable[..., Any], *params: Any) -> Any:
-------
The return value of the invoked callable.
"""
parameter_count = __count_parameters(callback)
parameter_count = count_parameters(callback)
result = callback(*params[:parameter_count])
if isawaitable(result):
result = await result
......
......@@ -12,6 +12,7 @@ from textual import on, work
from textual._context import active_message_pump
from textual.app import App, AutopilotCallbackType
from textual.binding import Binding
from textual.events import ScreenResume
from textual.notifications import Notification, Notify, SeverityLevel
from textual.reactive import reactive, var
......@@ -262,7 +263,9 @@ class Clive(App[int], ManualReactive):
with self.batch_update():
while not self.__screen_eq(self.screen_stack[-1], screen):
self.pop_screen()
with self.prevent(ScreenResume):
self.pop_screen()
self.screen.post_message(ScreenResume())
break # Screen found and located on top of the stack, stop
else:
raise ScreenNotFoundError(
......
......@@ -101,12 +101,12 @@ class AccountInfo(Container, AccountReferencingWidget):
yield DynamicLabel(
self.app.world,
"profile_data",
lambda _: f"History entry: {humanize_datetime(self._account.data.last_history_entry)}",
lambda: f"History entry: {humanize_datetime(self._account.data.last_history_entry)}",
)
yield DynamicLabel(
self.app.world,
"profile_data",
lambda _: f"Account update: {humanize_datetime(self._account.data.last_account_update)}",
lambda: f"Account update: {humanize_datetime(self._account.data.last_account_update)}",
)
......
......@@ -3,7 +3,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from clive.__private.core.hive_vests_conversions import hive_to_vests
from clive.__private.ui.widgets.dynamic_label import DynamicLabel
from clive.__private.ui.widgets.notice import Notice
from clive.models import Asset
if TYPE_CHECKING:
......@@ -11,23 +11,12 @@ if TYPE_CHECKING:
from clive.__private.ui.data_providers.hive_power_data_provider import HivePowerDataProvider
class HpVestsFactor(DynamicLabel):
DEFAULT_CSS = """
HpVestsFactor {
width: 1fr;
height: 1;
margin-bottom: 1;
align: center middle;
background: $warning;
color: $text;
}
"""
class HpVestsFactor(Notice):
def __init__(self, provider: HivePowerDataProvider):
super().__init__(
obj_to_watch=provider, attribute_name="_content", callback=self._get_hp_vests_factor, init=False
)
def _get_hp_vests_factor(self, content: HivePowerData) -> str:
factor = hive_to_vests(1000, content.gdpo)
factor = hive_to_vests(Asset.hive(1), content.gdpo)
return f"HP is calculated to VESTS with the factor: 1.000 HP -> {Asset.pretty_amount(factor)} VESTS"
from __future__ import annotations
from textual.widgets import Static
class OperationNameInfo(Static):
"""Widget used to inform the user about the real name of the operation in the blockchain."""
DEFAULT_CSS = """
OperationNameInfo {
text-style: bold;
margin-bottom: 1;
background: $accent;
width: 1fr;
height: 1;
text-align: center;
}
"""
def __init__(self, operation_name: str, operation_alias: str):
"""
Initialize the `OperationNameInfo` widget.
Args:
----
operation_name: the real name of the operation in the blockchain.
operation_alias: common name of the operation.
"""
super().__init__(
renderable=f"{operation_alias.capitalize()} corresponds to a `{operation_name.lower()}` blockchain operation"
)
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from textual.widgets import TabPane
from textual import on
from textual.containers import Horizontal, ScrollableContainer
from textual.widgets import Pretty, Static, TabPane
from clive.__private.core.formatters.humanize import humanize_datetime
from clive.__private.core.hive_vests_conversions import hive_to_vests
from clive.__private.ui.data_providers.hive_power_data_provider import HivePowerDataProvider
from clive.__private.ui.get_css import get_css_from_relative_path
from clive.__private.ui.operations.bindings.operation_action_bindings import OperationActionBindings
from clive.__private.ui.operations.hive_power_management.common_hive_power.hp_vests_factor import HpVestsFactor
from clive.__private.ui.operations.hive_power_management.common_hive_power.operation_name_widget import (
OperationNameInfo,
)
from clive.__private.ui.operations.operation_summary.cancel_power_down import CancelPowerDown
from clive.__private.ui.widgets.clive_button import CliveButton
from clive.__private.ui.widgets.clive_checkerboard_table import (
EVEN_CLASS_NAME,
ODD_CLASS_NAME,
CliveCheckerboardTable,
CliveCheckerBoardTableCell,
CliveCheckerboardTableRow,
)
from clive.__private.ui.widgets.clive_widget import CliveWidget
from clive.__private.ui.widgets.currency_selector.currency_selector_hp_vests import CurrencySelectorHpVests
from clive.__private.ui.widgets.generous_button import GenerousButton
from clive.__private.ui.widgets.inputs.hp_vests_amount_input import HPVestsAmountInput
from clive.__private.ui.widgets.notice import Notice
from clive.models import Asset
from schemas.operations import WithdrawVestingOperation
if TYPE_CHECKING:
from rich.text import TextType
from textual.app import ComposeResult
from textual.widget import Widget
from clive.__private.core.commands.data_retrieval.hive_power_data import HivePowerData
class PowerDown(TabPane, CliveWidget):
class PlaceTaker(Static):
pass
class ScrollablePart(ScrollableContainer):
pass
class WithdrawRoutesDisplay(CliveWidget):
"""Widget used just to inform user to which account has withdrawal route and how much % it is."""
def compose(self) -> ComposeResult:
yield Static("Loading...", id="withdraw-routes-header")
yield Pretty({})
def on_mount(self) -> None:
self.watch(self.provider, "_content", self._update_withdraw_routes, init=False)
def _update_withdraw_routes(self, content: HivePowerData) -> None:
"""Update withdraw routes pretty widget."""
if not content.withdraw_routes:
self.query_one("#withdraw-routes-header", Static).update("You have no withdraw routes")
self.query_one(Pretty).display = False
return
withdraw_routes = {}
for withdraw_route in content.withdraw_routes:
withdraw_routes[withdraw_route.to_account] = f"{withdraw_route.percent / 100}%"
self.query_one("#withdraw-routes-header", Static).update("Your withdraw routes")
self.query_one(Pretty).update(withdraw_routes)
self.display = True
@property
def provider(self) -> HivePowerDataProvider:
return self.screen.query_one(HivePowerDataProvider)
class PendingPowerDownHeader(Horizontal):
def compose(self) -> ComposeResult:
yield Static("Next power down", classes=EVEN_CLASS_NAME)
yield Static("Power down [HP]", classes=ODD_CLASS_NAME)
yield Static("Power down [VESTS]", classes=EVEN_CLASS_NAME)
yield PlaceTaker()
class PendingPowerDown(CliveCheckerboardTable):
def __init__(self) -> None:
super().__init__(
Static("Current power down", id="current-power-down-title"), PendingPowerDownHeader(), dynamic=True
)
self._previous_next_vesting_withdrawal: datetime = datetime.min
def create_dynamic_rows(self, content: HivePowerData) -> list[CliveCheckerboardTableRow]:
self._previous_next_vesting_withdrawal = content.next_vesting_withdrawal
return [
CliveCheckerboardTableRow(
CliveCheckerBoardTableCell(humanize_datetime(content.next_vesting_withdrawal)),
CliveCheckerBoardTableCell(Asset.pretty_amount(content.next_power_down.hp_balance)),
CliveCheckerBoardTableCell(Asset.pretty_amount(content.next_power_down.vests_balance)),
CliveButton("Cancel", variant="error"),
)
]
def get_no_content_available_widget(self) -> Widget:
return Static("You have no current power down process", id="no-current-power-down-info")
@on(CliveButton.Pressed)
def push_operation_summary_screen(self) -> None:
self.app.push_screen(
CancelPowerDown(self.provider.content.next_vesting_withdrawal, self.provider.content.next_power_down)
)
@property
def is_anything_to_display(self) -> bool:
return humanize_datetime(self.provider.content.next_vesting_withdrawal) != "never"
@property
def provider(self) -> HivePowerDataProvider:
return self.screen.query_one(HivePowerDataProvider)
@property
def check_if_should_be_updated(self) -> bool:
return self.provider.content.next_vesting_withdrawal != self._previous_next_vesting_withdrawal
class PowerDown(TabPane, OperationActionBindings):
"""TabPane with all content about power down."""
def __init__(self, title: TextType):
DEFAULT_CSS = get_css_from_relative_path(__file__)
def __init__(self, title: TextType) -> None:
"""
Initialize a TabPane.
Initialize the PowerDown tab-pane.
Args:
----
title: Title of the TabPane (will be displayed in a tab label).
"""
super().__init__(title=title)
self._shares_input = HPVestsAmountInput()
self._one_withdrawal_display = Notice(
obj_to_watch=self._shares_input.input,
attribute_name="value",
callback=self._calculate_one_withdrawal,
)
self._one_withdrawal_display.display = False
def compose(self) -> ComposeResult:
with ScrollablePart():
yield OperationNameInfo("withdraw vesting", "power down")
yield HpVestsFactor(self.provider)
with Horizontal(id="input-with-button"):
yield self._shares_input
yield GenerousButton(self._shares_input, self._get_shares_balance) # type: ignore[arg-type]
yield self._one_withdrawal_display
yield PendingPowerDown()
yield WithdrawRoutesDisplay()
def _get_shares_balance(self) -> Asset.Hive | Asset.Vests:
if self._shares_input.selected_asset_type is Asset.Hive:
return self.provider.content.owned_balance.hp_balance - self.provider.content.delegated_balance.hp_balance
return self.provider.content.owned_balance.vests_balance - self.provider.content.delegated_balance.vests_balance
def _calculate_one_withdrawal(self) -> str:
"""The withdrawal is divided into 13 parts - calculate and inform the user of the amount of one of them."""
shares_input = self._shares_input.value_or_none()
if shares_input is None:
self._one_withdrawal_display.display = False
return ""
one_withdrawal = shares_input / 13
self._one_withdrawal_display.display = True
asset = f"{Asset.pretty_amount(one_withdrawal)} {'VESTS' if isinstance(one_withdrawal, Asset.Vests) else 'HP'}"
return f"The withdrawal will be divided into 13 parts, one of which is: {asset}"
@on(CurrencySelectorHpVests.Changed)
def shares_type_changed(self) -> None:
"""Clear input when shares type was changed and hide factor display when vests selected."""
self._shares_input.input.clear()
hp_vests_factor = self.query_one(HpVestsFactor)
if self._shares_input.selected_asset_type is Asset.Vests:
hp_vests_factor.display = False
return
hp_vests_factor.display = True
def _create_operation(self) -> WithdrawVestingOperation | None:
asset = self._shares_input.value_or_none()
if asset is None:
return None
if isinstance(asset, Asset.Hive):
# If the user has passed an amount in `HP` - convert it to `VESTS`. The operation is performed using VESTS.
asset = hive_to_vests(asset, self.provider.content.gdpo)
return WithdrawVestingOperation(account=self.working_account, vesting_shares=asset)
@property
def provider(self) -> HivePowerDataProvider:
return self.screen.query_one(HivePowerDataProvider)
@property
def working_account(self) -> str:
return self.app.world.profile_data.working_account.name
CliveButton {
width: 1fr;
}
WithdrawRoutesDisplay Pretty {
content-align: center middle;
margin-top: 1;
width: 1fr;
}
WithdrawRoutesDisplay {
height: auto;
}
HpVestsFactor {
margin-bottom: 1;
}
#input-with-button {
background: $panel;
padding: 2 2;
height: auto;
}
#withdraw-routes-header {
text-style: bold;
margin-top: 1;
background: $primary;
width: 1fr;
height: 1;
text-align: center;
}
/* Pending power down */
#current-power-down-title {
text-style: bold;
margin-top: 1;
background: $primary;
width: 1fr;
height: 1;
text-align: center;
}
#no-current-power-down-info {
text-style: bold;
margin-top: 1;
background: $primary;
width: 1fr;
height: 1;
text-align: center;
}
PendingPowerDown {
height: auto;
}
PendingPowerDownHeader {
height: 1;
}
PendingPowerDownHeader Static {
text-style: bold;
width: 1fr;
text-align: center;
}
......@@ -3,10 +3,13 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from textual.containers import Horizontal, ScrollableContainer, Vertical
from textual.widgets import Static, TabPane
from textual.widgets import TabPane
from clive.__private.ui.get_css import get_css_from_relative_path
from clive.__private.ui.operations.bindings.operation_action_bindings import OperationActionBindings
from clive.__private.ui.operations.hive_power_management.common_hive_power.operation_name_widget import (
OperationNameInfo,
)
from clive.__private.ui.widgets.generous_button import GenerousButton
from clive.__private.ui.widgets.inputs.account_name_input import AccountNameInput
from clive.__private.ui.widgets.inputs.clive_validated_input import CliveValidatedInput
......@@ -44,7 +47,7 @@ class PowerUp(TabPane, OperationActionBindings):
def compose(self) -> ComposeResult:
with ScrollablePart():
yield Static("Power up corresponds to a `transfer to vesting` operation", id="operation-name-info")
yield OperationNameInfo("transfer to vesting", "power up")
yield Notice("Your governance voting power will be increased after 30 days")
with Vertical(id="power-up-inputs"):
yield self._receiver_input
......
......@@ -23,12 +23,3 @@ Notice {
margin-top: 1;
height: auto;
}
#input-with-button HiveAssetAmountInput {
width: 1fr;
}
#input-with-button GenerousButton {
width: 14;
min-width: 14;
}
......@@ -2,17 +2,107 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from textual.widgets import TabPane
from textual import on
from textual.containers import Horizontal, ScrollableContainer, Vertical
from textual.widgets import Checkbox, Static, TabPane
from clive.__private.ui.widgets.clive_widget import CliveWidget
from clive.__private.ui.data_providers.hive_power_data_provider import HivePowerDataProvider
from clive.__private.ui.get_css import get_css_from_relative_path
from clive.__private.ui.operations.bindings import OperationActionBindings
from clive.__private.ui.operations.operation_summary.remove_withdraw_vesting_route import RemoveWithdrawVestingRoute
from clive.__private.ui.widgets.clive_button import CliveButton
from clive.__private.ui.widgets.clive_checkerboard_table import (
EVEN_CLASS_NAME,
ODD_CLASS_NAME,
CliveCheckerboardTable,
CliveCheckerBoardTableCell,
CliveCheckerboardTableRow,
)
from clive.__private.ui.widgets.inputs.account_name_input import AccountNameInput
from clive.__private.ui.widgets.inputs.clive_validated_input import CliveValidatedInput
from clive.__private.ui.widgets.inputs.percent_input import PercentInput
from schemas.operations import SetWithdrawVestingRouteOperation
if TYPE_CHECKING:
from rich.text import TextType
from textual.app import ComposeResult
from textual.widget import Widget
from clive.__private.core.commands.data_retrieval.hive_power_data import HivePowerData
from schemas.apis.database_api.fundaments_of_reponses import WithdrawVestingRoutesFundament as WithdrawRouteSchema
class WithdrawRoutes(TabPane, CliveWidget):
class PlaceTaker(Static):
pass
class WithdrawRoutesHeader(Horizontal):
def compose(self) -> ComposeResult:
yield Static("To", classes=EVEN_CLASS_NAME)
yield Static("Percent", classes=ODD_CLASS_NAME)
yield Static("Auto vest", classes=EVEN_CLASS_NAME)
yield PlaceTaker()
class WithdrawRoute(CliveCheckerboardTableRow):
"""Row of the `WithdrawRoutesTable`."""
def __init__(self, withdraw_route: WithdrawRouteSchema) -> None:
super().__init__(
CliveCheckerBoardTableCell(withdraw_route.to_account),
CliveCheckerBoardTableCell(f"{withdraw_route.percent / 100} %"),
CliveCheckerBoardTableCell(f"{withdraw_route.auto_vest}"),
CliveButton("Remove", classes="remove-withdraw-route-button", variant="error"),
)
self._withdraw_route = withdraw_route
@on(CliveButton.Pressed, ".remove-withdraw-route-button")
def push_operation_summary_screen(self) -> None:
self.app.push_screen(RemoveWithdrawVestingRoute(self._withdraw_route))
class WithdrawRoutesTable(CliveCheckerboardTable):
"""Table with WithdrawRoutes."""
def __init__(self) -> None:
super().__init__(
Static("Current withdraw routes", id="withdraw-routes-table-title"), WithdrawRoutesHeader(), dynamic=True
)
self._withdraw_routes: list[WithdrawRouteSchema] | None = None
def create_dynamic_rows(self, content: HivePowerData) -> list[CliveCheckerboardTableRow]:
self._withdraw_routes = content.withdraw_routes
withdraw_routes: list[CliveCheckerboardTableRow] = [
WithdrawRoute(withdraw_route) for withdraw_route in self._withdraw_routes
]
return withdraw_routes
def get_no_content_available_widget(self) -> Widget:
return Static("You have no withdraw routes", id="no-withdraw-routes-info")
@property
def provider(self) -> HivePowerDataProvider:
return self.screen.query_one(HivePowerDataProvider)
@property
def check_if_should_be_updated(self) -> bool:
return self.provider.content.withdraw_routes != self._withdraw_routes
@property
def is_anything_to_display(self) -> bool:
return len(self.provider.content.withdraw_routes) != 0
@property
def working_account(self) -> str:
return self.app.world.profile_data.working_account.name
class WithdrawRoutes(TabPane, OperationActionBindings):
"""TabPane with all content about setting withdraw routes."""
DEFAULT_CSS = get_css_from_relative_path(__file__)
def __init__(self, title: TextType):
"""
Initialize a TabPane.
......@@ -22,3 +112,30 @@ class WithdrawRoutes(TabPane, CliveWidget):
title: Title of the TabPane (will be displayed in a tab label).
"""
super().__init__(title=title)
self._account_input = AccountNameInput()
self._percent_input = PercentInput("Percent")
self._auto_vest_checkbox = Checkbox("Auto vest")
def compose(self) -> ComposeResult:
with ScrollableContainer():
yield Static("Set withdraw route", id="set-withdraw-route-title")
with Vertical(id="inputs-container"):
yield self._account_input
with Horizontal(id="input-with-checkbox"):
yield self._percent_input
yield self._auto_vest_checkbox
yield WithdrawRoutesTable()
def _create_operation(self) -> SetWithdrawVestingRouteOperation | None:
CliveValidatedInput.validate_many(self._account_input, self._percent_input)
return SetWithdrawVestingRouteOperation(
from_account=self.working_account,
to_account=self._account_input.value_or_error,
percent=self._percent_input.value_or_error * 100,
auto_vest=self._auto_vest_checkbox.value,
)
@property
def working_account(self) -> str:
return self.app.world.profile_data.working_account.name
WithdrawRoutes {
height: 1fr;
}
WithdrawRoutes Static {
text-style: bold;
width: 1fr;
text-align: center;
}
/* Set withdraw route */
#set-withdraw-route-title {
background: $primary;
width: 1fr;
height: 1;
}
#inputs-container {
background: $panel;
padding: 2 4;
height: auto;
}
#input-with-checkbox {
margin-top: 1;
height: auto;
}
#input-with-checkbox IntegerInput {
width: 1fr;
}
#input-with-checkbox Checkbox {
width: 17;
}
AccountNameInput KnownAccount {
margin-left: 3;
}
/* Withdraw routes table */
WithdrawRoutesHeader {
height: auto;
}
WithdrawRoutesTable {
margin-top: 1;
height: auto;
}
#no-withdraw-routes-info {
background: $primary;
height: auto;
}
#withdraw-routes-table-title {
background: $primary;
width: 1fr;
}
WithdrawRoute {
height: auto;
}
WithdrawRoute .remove-withdraw-route-button {
background: $error-darken-1;
width: 1fr;
}
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar, Final
from clive.__private.ui.operations.operation_summary.operation_summary import OperationSummary
from clive.__private.ui.widgets.inputs.labelized_input import LabelizedInput
from schemas.operations import SetWithdrawVestingRouteOperation
if TYPE_CHECKING:
from textual.app import ComposeResult
from schemas.apis.database_api.fundaments_of_reponses import WithdrawVestingRoutesFundament as WithdrawRoute
WITHDRAW_ROUTE_REMOVE_PERCENT: Final[int] = 0
class RemoveWithdrawVestingRoute(OperationSummary):
"""Screen to remove withdraw vesting route."""
BIG_TITLE: ClassVar[str] = "Remove withdraw route"
def __init__(self, withdraw_route: WithdrawRoute) -> None:
super().__init__()
self._withdraw_route = withdraw_route
def content(self) -> ComposeResult:
yield LabelizedInput("From account", self.working_account)
yield LabelizedInput("To account", self._withdraw_route.to_account)
yield LabelizedInput("Percent", str(self._withdraw_route.percent / 100))
yield LabelizedInput("Auto vest", str(self._withdraw_route.auto_vest))
def _create_operation(self) -> SetWithdrawVestingRouteOperation | None:
return SetWithdrawVestingRouteOperation(
from_account=self.working_account,
to_account=self._withdraw_route.to_account,
auto_vest=self._withdraw_route.auto_vest,
percent=WITHDRAW_ROUTE_REMOVE_PERCENT,
)
@property
def working_account(self) -> str:
return self.app.world.profile_data.working_account.name
......@@ -25,6 +25,6 @@ class AccountReferencingWidget(CliveWidget):
return DynamicLabel(
self.app.world,
"profile_data",
lambda _: foo() if self._account.name else "NULL",
lambda: foo() if self._account.name else "NULL",
classes=classes,
)
from __future__ import annotations
from .currency_selector import CurrencySelector
from .currency_selector_base import CurrencySelectorBase
from .currency_selector_hive import CurrencySelectorHive
from .currency_selector_hp_vests import CurrencySelectorHpVests
from .currency_selector_liquid import CurrencySelectorLiquid
__all__ = [
"CurrencySelector",
"CurrencySelectorLiquid",
"CurrencySelectorHive",
"CurrencySelectorHpVests",
"CurrencySelectorBase",
]
from __future__ import annotations
from clive.__private.ui.widgets.currency_selector.currency_selector_base import (
CurrencySelectorBase,
)
from clive.models import Asset
from clive.models.asset import AssetFactoryHolder
class CurrencySelectorHive(CurrencySelectorBase[Asset.Hive]):
@staticmethod
def _create_selectable() -> dict[str, AssetFactoryHolder[Asset.Hive]]:
return {
"HIVE": AssetFactoryHolder(asset_cls=Asset.Hive, asset_factory=Asset.hive),
}
def on_mount(self) -> None:
self.disabled = True
from __future__ import annotations
from inspect import isawaitable
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Union
from textual.widgets import Label
from clive.__private.core.callback import count_parameters
from clive.__private.ui.widgets.clive_widget import CliveWidget
if TYPE_CHECKING:
from collections.abc import Callable
from rich.console import RenderableType
from textual.app import ComposeResult
from textual.reactive import Reactable
DynamicLabelCallbackType = Union[
Callable[[], Awaitable[str]],
Callable[[Any], Awaitable[str]],
Callable[[Any, Any], Awaitable[str]],
Callable[[], str],
Callable[[Any], str],
Callable[[Any, Any], str],
]
class DynamicLabel(CliveWidget):
"""A label that can be updated dynamically when a reactive variable changes."""
......@@ -34,7 +43,7 @@ class DynamicLabel(CliveWidget):
self,
obj_to_watch: Reactable,
attribute_name: str,
callback: Callable[[Any], Any],
callback: DynamicLabelCallbackType,
*,
prefix: str = "",
init: bool = True,
......@@ -57,17 +66,26 @@ class DynamicLabel(CliveWidget):
return self.__label.renderable
def on_mount(self) -> None:
def delegate_work(attribute: Any) -> None:
self.run_worker(self.attribute_changed(attribute))
def delegate_work(old_value: Any, value: Any) -> None:
self.run_worker(self.attribute_changed(old_value, value))
self.watch(self.__obj_to_watch, self.__attribute_name, delegate_work, self._init)
def compose(self) -> ComposeResult:
yield self.__label
async def attribute_changed(self, attribute: Any) -> None:
value = self.__callback(attribute)
if isawaitable(value):
value = await value
if value != self.__label.renderable:
self.__label.update(f"{self.__prefix}{value}")
async def attribute_changed(self, old_value: Any, value: Any) -> None:
callback = self.__callback
param_count = count_parameters(callback)
if param_count == 2: # noqa: PLR2004
result = callback(old_value, value) # type: ignore[call-arg]
elif param_count == 1:
result = callback(value) # type: ignore[call-arg]
else:
result = callback() # type: ignore[call-arg]
if isawaitable(result):
result = await result
if result != self.__label.renderable:
self.__label.update(f"{self.__prefix}{result}")
......@@ -16,6 +16,13 @@ if TYPE_CHECKING:
class GenerousButton(CliveButton):
"""Button that fill the related input with the entire selected asset balance."""
DEFAULT_CSS = """
GenerousButton {
min-width: 14;
width: 14;
}
"""
def __init__(
self,
related_input: CliveValidatedInput[Asset.AnyT],
......
......@@ -20,7 +20,7 @@ if TYPE_CHECKING:
from textual.app import ComposeResult
from textual.widgets._input import InputValidationOn
AssetInputT = TypeVar("AssetInputT", Asset.VotingT, Asset.LiquidT)
AssetInputT = TypeVar("AssetInputT", Asset.VotingT, Asset.LiquidT, Asset.Hive)
class AssetAmountInput(CliveValidatedInput[AssetInputT], Generic[AssetInputT], AbstractClassMessagePump):
......@@ -29,6 +29,7 @@ class AssetAmountInput(CliveValidatedInput[AssetInputT], Generic[AssetInputT], A
DEFAULT_CSS = """
AssetAmountInput {
height: auto;
width: 1fr;
Vertical {
height: auto;
......
......@@ -2,65 +2,16 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from clive.__private.ui.widgets.inputs.liquid_asset_amount_input import LiquidAssetAmountInput
from clive.__private.ui.widgets.currency_selector import CurrencySelectorHive
from clive.__private.ui.widgets.inputs.asset_amount_base_input import AssetAmountInput
from clive.models import Asset
if TYPE_CHECKING:
from collections.abc import Iterable
from clive.__private.ui.widgets.currency_selector import CurrencySelectorBase
from textual.widgets._input import InputValidationOn
class HiveAssetAmountInput(LiquidAssetAmountInput):
class HiveAssetAmountInput(AssetAmountInput[Asset.Hive]):
"""An input for asset HIVE amount."""
def __init__(
self,
title: str = "Amount",
value: str | float | None = None,
*,
always_show_title: bool = False,
include_title_in_placeholder_when_blurred: bool = True,
show_invalid_reasons: bool = True,
required: bool = True,
validate_on: Iterable[InputValidationOn] | None = None,
valid_empty: bool = False,
id: str | None = None, # noqa: A002
classes: str | None = None,
disabled: bool = False,
) -> None:
super().__init__(
title=title,
value=value,
always_show_title=always_show_title,
include_title_in_placeholder_when_blurred=include_title_in_placeholder_when_blurred,
show_invalid_reasons=show_invalid_reasons,
required=required,
validate_on=validate_on,
valid_empty=valid_empty,
id=id,
classes=classes,
disabled=disabled,
)
symbol = Asset.Hive.get_asset_information().symbol[0]
self._currency_selector.value = self._currency_selector.get_selectable(symbol)
self._currency_selector.prompt = symbol
self._currency_selector.disabled = True
@property
def _value(self) -> Asset.Hive:
"""
Return the value of the input as a HIVE asset.
Probably you want to use other `value_` properties instead.
Raises
------
AssetAmountInvalidFormatError: Raised when given amount is in invalid format.
"""
return super()._value # type: ignore[return-value] # we re sure it is Hive
@property
def selected_asset_type(self) -> type[Asset.Hive]:
return super().selected_asset_type # type: ignore[return-value] # we re sure it is Hive
def create_currency_selector(self) -> CurrencySelectorBase[Asset.Hive]:
return CurrencySelectorHive()
......@@ -2,148 +2,14 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from textual import on
from textual.containers import Horizontal, Vertical
from clive.__private.ui.widgets.currency_selector import CurrencySelectorLiquid
from clive.__private.ui.widgets.inputs.clive_validated_input import (
CliveValidatedInput,
)
from clive.__private.validators.asset_amount_validator import AssetAmountValidator
from clive.__private.ui.widgets.inputs.asset_amount_base_input import AssetAmountInput
from clive.models import Asset
if TYPE_CHECKING:
from collections.abc import Iterable
from textual.app import ComposeResult
from textual.widgets._input import InputValidationOn
class LiquidAssetAmountInput(CliveValidatedInput[Asset.LiquidT]):
"""An input for a liquid asset (HBD/HIVE) amount."""
DEFAULT_CSS = """
LiquidAssetAmountInput {
height: auto;
Vertical {
height: auto;
Horizontal {
height: auto;
CliveInput {
width: 1fr;
}
CurrencySelectorLiquid {
width: 14;
}
}
}
}
"""
def __init__(
self,
title: str = "Amount",
value: str | float | None = None,
placeholder: str | None = None,
*,
always_show_title: bool = False,
include_title_in_placeholder_when_blurred: bool = True,
show_invalid_reasons: bool = True,
required: bool = True,
validate_on: Iterable[InputValidationOn] | None = None,
valid_empty: bool = False,
id: str | None = None, # noqa: A002
classes: str | None = None,
disabled: bool = False,
) -> None:
"""
Initialize the widget.
Args difference from `CliveValidatedInput`:
----
placeholder: If not provided, placeholder will be dynamically generated based on the asset type.
"""
self._currency_selector = CurrencySelectorLiquid()
default_asset_type = self._currency_selector.default_asset_cls
default_asset_precision = default_asset_type.get_asset_information().precision
super().__init__(
title=title,
value=str(value) if value is not None else None,
placeholder=self._get_dynamic_placeholder(default_asset_precision),
always_show_title=always_show_title,
include_title_in_placeholder_when_blurred=include_title_in_placeholder_when_blurred,
show_invalid_reasons=show_invalid_reasons,
required=required,
restrict=self._create_restriction(default_asset_precision),
type="number",
validators=[AssetAmountValidator(default_asset_type)],
validate_on=validate_on,
valid_empty=valid_empty,
id=id,
classes=classes,
disabled=disabled,
)
self._dynamic_placeholder = placeholder is None
@property
def _value(self) -> Asset.LiquidT:
"""
Return the value of the input as a liquid asset.
Probably you want to use other `value_` properties instead.
Raises
------
AssetAmountInvalidFormatError: Raised when given amount is in invalid format.
"""
return self._currency_selector.create_asset(self.value_raw)
@property
def selected_asset_type(self) -> type[Asset.LiquidT]:
return self._currency_selector.asset_cls
@property
def selected_asset_precision(self) -> int:
return self.selected_asset_type.get_asset_information().precision
def compose(self) -> ComposeResult:
with Vertical():
with Horizontal():
yield self.input
yield self._currency_selector
yield self.pretty
@on(CurrencySelectorLiquid.Changed)
def _asset_changed(self) -> None:
# update placeholder
if self._dynamic_placeholder:
self.input.set_unmodified_placeholder(self._get_dynamic_placeholder(self.selected_asset_precision))
# update input restrict
self.input.restrict = self._create_restriction(self.selected_asset_precision)
# update asset amount validator
self.input.validators = [
validator for validator in self.input.validators if not isinstance(validator, AssetAmountValidator)
]
self.input.validators.append(AssetAmountValidator(self.selected_asset_type))
# need to revalidate the input (possible to switch from higher precision to lower precision)
self.input.validate(self.input.value)
from clive.__private.ui.widgets.currency_selector import CurrencySelectorBase
def _create_restriction(self, precision: int) -> str:
precision_digits = f"{{0,{precision}}}"
return rf"\d*\.?\d{precision_digits}"
def _get_dynamic_placeholder(self, precision: int) -> str:
max_allowed_precision = 9
assert precision >= 0, f"Precision must be non-negative, got {precision}"
assert precision <= max_allowed_precision, f"Precision must be at most {max_allowed_precision}, got {precision}"
numbers = "123456789"
return f"e.g.: 1.{numbers[:precision]}"
class LiquidAssetAmountInput(AssetAmountInput[Asset.LiquidT]):
def create_currency_selector(self) -> CurrencySelectorBase[Asset.LiquidT]:
return CurrencySelectorLiquid()