refactor: Use pre-defined ASCII frames for spinner animation

This commit is contained in:
Paul Gauthier (aider) 2025-05-08 15:51:37 -07:00
parent 18f702b95a
commit 5bb891b2bb

View file

@ -260,26 +260,37 @@ class Spinner:
def __init__(self, text: str, width: int = 7): def __init__(self, text: str, width: int = 7):
self.text = text self.text = text
self.width = max(1, width)
self.start_time = time.time() self.start_time = time.time()
self.last_update = 0.0 self.last_update = 0.0
self.visible = False self.visible = False
self.is_tty = sys.stdout.isatty() self.is_tty = sys.stdout.isatty()
# Decide which characters to use # Pre-render the animation frames using pure ASCII so they will
scan_char, trail_char = "", "" # always display, even on very limited terminals.
if not self._supports_unicode(): ascii_forward = """
scan_char, trail_char = "#", "-" [#------]
[-#-----]
[--#----]
[---#---]
[----#--]
[-----#-]
[------#]
""".strip().splitlines()
# Build the animation frames # If unicode is supported, swap the ASCII chars for nicer glyphs.
forward = [ if self._supports_unicode():
f"[{trail_char * pos}{scan_char}{trail_char * (self.width - 1 - pos)}]" scan_char, trail_char = "", ""
for pos in range(self.width) forward = [f.replace("#", scan_char).replace("-", trail_char) for f in ascii_forward]
] else:
self.frames = forward + forward[-2:0:-1] # bounce back scan_char, trail_char = "#", "-"
forward = ascii_forward
# Bounce the scanner back and forth.
self.frames = forward + forward[-2:0:-1]
self.frame_idx = 0 self.frame_idx = 0
self.scan_char = scan_char self.scan_char = scan_char
self.animation_len = len(self.frames[0]) self.width = len(forward[0]) - 2 # number of chars between the brackets
self.animation_len = len(forward[0])
def _supports_unicode(self) -> bool: def _supports_unicode(self) -> bool:
if not self.is_tty: if not self.is_tty: