utils.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING, Iterable, List, TypeVar, cast, overload
  3. from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple
  4. if TYPE_CHECKING:
  5. from typing_extensions import SupportsIndex
  6. __all__ = [
  7. "explode_text_fragments",
  8. ]
  9. _T = TypeVar("_T", bound=OneStyleAndTextTuple)
  10. class _ExplodedList(List[_T]):
  11. """
  12. Wrapper around a list, that marks it as 'exploded'.
  13. As soon as items are added or the list is extended, the new items are
  14. automatically exploded as well.
  15. """
  16. exploded = True
  17. def append(self, item: _T) -> None:
  18. self.extend([item])
  19. def extend(self, lst: Iterable[_T]) -> None:
  20. super().extend(explode_text_fragments(lst))
  21. def insert(self, index: SupportsIndex, item: _T) -> None:
  22. raise NotImplementedError # TODO
  23. # TODO: When creating a copy() or [:], return also an _ExplodedList.
  24. @overload
  25. def __setitem__(self, index: SupportsIndex, value: _T) -> None: ...
  26. @overload
  27. def __setitem__(self, index: slice, value: Iterable[_T]) -> None: ...
  28. def __setitem__(
  29. self, index: SupportsIndex | slice, value: _T | Iterable[_T]
  30. ) -> None:
  31. """
  32. Ensure that when `(style_str, 'long string')` is set, the string will be
  33. exploded.
  34. """
  35. if not isinstance(index, slice):
  36. int_index = index.__index__()
  37. index = slice(int_index, int_index + 1)
  38. if isinstance(value, tuple): # In case of `OneStyleAndTextTuple`.
  39. value = cast("List[_T]", [value])
  40. super().__setitem__(index, explode_text_fragments(value))
  41. def explode_text_fragments(fragments: Iterable[_T]) -> _ExplodedList[_T]:
  42. """
  43. Turn a list of (style_str, text) tuples into another list where each string is
  44. exactly one character.
  45. It should be fine to call this function several times. Calling this on a
  46. list that is already exploded, is a null operation.
  47. :param fragments: List of (style, text) tuples.
  48. """
  49. # When the fragments is already exploded, don't explode again.
  50. if isinstance(fragments, _ExplodedList):
  51. return fragments
  52. result: list[_T] = []
  53. for style, string, *rest in fragments:
  54. for c in string:
  55. result.append((style, c, *rest)) # type: ignore
  56. return _ExplodedList(result)