File size: 2,548 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""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()