| """Loading Spinner - Show loading state""" |
|
|
| import sys |
| import time |
| import threading |
| from typing import Optional |
| from contextlib import contextmanager |
|
|
| from .config import DEFAULT_CONFIG, AnimationConfig |
|
|
|
|
| class Spinner: |
| """Animated loading spinner for terminal""" |
|
|
| FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] |
|
|
| def __init__(self, message: str = "Loading", config: Optional[AnimationConfig] = None): |
| self.message = message |
| self.config = config or DEFAULT_CONFIG |
| self.running = False |
| self.thread: Optional[threading.Thread] = None |
| self.frame_index = 0 |
|
|
| def _spin(self): |
| """Internal spin loop""" |
| while self.running: |
| frame = self.SPINNER_FRAMES[self.frame_index % len(self.SPINNER_FRAMES)] |
| sys.stdout.write(f"\r{self.config.speed} {frame} {self.message}...") |
| sys.stdout.flush() |
| time.sleep(self.config.speed) |
| self.frame_index += 1 |
|
|
| sys.stdout.write("\r" + " " * (len(self.message) + 10)) |
| sys.stdout.write("\r") |
| sys.stdout.flush() |
|
|
| def start(self): |
| """Start the spinner animation""" |
| self.running = True |
| self.thread = threading.Thread(target=self._spin, daemon=True) |
| self.thread.start() |
|
|
| def stop(self): |
| """Stop the spinner animation""" |
| self.running = False |
| if self.thread: |
| self.thread.join(timeout=0.5) |
|
|
| @contextmanager |
| def __call__(self): |
| """Context manager for spinner""" |
| try: |
| self.start() |
| yield self |
| finally: |
| self.stop() |
|
|
|
|
| class SimpleSpinner: |
| """Simple spinner without threading""" |
|
|
| def __init__(self, message: str = "Loading"): |
| self.message = message |
| self.frame_index = 0 |
|
|
| def spin(self) -> str: |
| """Get next spin frame""" |
| frame = Spinner.FRAMES[self.frame_index % len(Spinner.FRAMES)] |
| self.frame_index += 1 |
| return f"\r{frame} {self.message}..." |
|
|
| def reset(self): |
| """Reset spinner state""" |
| self.frame_index = 0 |
|
|
|
|
| def spinning(message: str = "Loading", duration: float = 2.0): |
| """Simple spinning animation for a duration""" |
| spinner = SimpleSpinner(message) |
| end_time = time.time() + duration |
|
|
| while time.time() < end_time: |
| sys.stdout.write(spinner.spin()) |
| sys.stdout.flush() |
| time.sleep(0.1) |
|
|
| sys.stdout.write("\r" + " " * (len(message) + 10)) |
| sys.stdout.write("\r") |
| sys.stdout.flush() |
|
|