Skip to content

Commit

Permalink
add cache to calculate max width for input
Browse files Browse the repository at this point in the history
  • Loading branch information
kraanzu committed Sep 16, 2024
1 parent 7cc9849 commit 8699f43
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
17 changes: 17 additions & 0 deletions dooit/ui/widgets/inputs/_cacher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from typing import Optional


class InputCache:
def __init__(self):
self.cache = dict()

def get(self, id: str, attr: str, value: str) -> Optional[int]:
key = (id, attr, value)
return self.cache.get(key)

def set(self, id: str, attr: str, value: str, cached_value: int) -> None:
key = (id, attr, value)
self.cache[key] = cached_value


input_cache = InputCache()
26 changes: 26 additions & 0 deletions dooit/ui/widgets/inputs/simple_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,29 @@
from dooit.api.model import DooitModel
from rich.text import TextType
from ._input import Input
from ._cacher import input_cache

ModelType = TypeVar("ModelType", bound=DooitModel)


def max_width_cache(func):

def wrapper(obj: "SimpleInput"):
key = [obj.model.uuid, obj._property, obj.model_value]
cache = input_cache.get(*key)

if cache:
return cache

res = func(obj)
key += [res]
input_cache.set(*key)

return res

return wrapper


class SimpleInput(Input, Generic[ModelType]):
"""
A simple single line Text Input widget
Expand Down Expand Up @@ -37,6 +56,13 @@ def model_value(self) -> Any:
def model_value(self, value: str) -> None:
return setattr(self.model, self._property, value)

@max_width_cache
def get_max_width(self) -> int:
return max(
len(self.value),
len(self.render()),
)

def _typecast_value(self, value: str) -> Any:
return value

Expand Down
5 changes: 1 addition & 4 deletions dooit/ui/widgets/renderers/base_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ def refresh_formatters(self):

def _get_attr_width(self, attr: str) -> int:
simple_input = self._get_component(attr)
return max(
len(simple_input.value),
len(simple_input.render()),
)
return simple_input.get_max_width()

def _get_max_width(self, attr: str) -> int:
renderers: Dict = self.tree._renderers
Expand Down

0 comments on commit 8699f43

Please sign in to comment.