Debian Codegraph @

examples/slow_typing.py

raw symbols SCIP
1 """This file details implementing a more advanced macro.
2
3 Using this macro, you can have an animation mimicking someone
4 typing a message out.
5
6 It uses a factory-like pattern, where new macros are defined
7 on-demand, allowing for use of multiple different typing animations
8 on one screen.
9 """
10
11 from __future__ import annotations
12
13 import time
14
15 import pytermgui as ptg
16
17
18 def define_slow_macro(
19 ms_per_char: int = 100, lang: ptg.MarkupLanguage = ptg.tim
20 ) -> str:
21 """Defines a slow typer macro, returns its name.
22 Args:
23 ms_per_char: How many milliseconds should pass between each
24 char being displayed.
25 lang: The markup language to define the new macro on.
26
27 Returns:
28 The name of the newly defined macro. The name follows the form:
29 `slow12345`
30 ...where `12345` is the last 5 characters of the current `time.time()`.
31 """
32
33 start = time.time()
34
35 def _macro(text: str) -> str:
36 current = time.time()
37 char_count = (current - start) / (ms_per_char / 1000)
38
39 trimmed = text[: round(char_count)]
40
41 if int(current) % 2 == 0:
42 return trimmed + "█"
43
44 return trimmed
45
46 name = f"!slow{str(time.time())[-5:]}"
47 lang.define(name, _macro)
48 return name
49
50
51 with ptg.WindowManager() as manager:
52 slow1 = define_slow_macro()
53 time.sleep(0.1)
54 slow2 = define_slow_macro()
55
56 manager.add(
57 ptg.Window(
58 ptg.Label(
59 f"[210 bold {slow1}]This is a very long message...",
60 parent_align=0,
61 ),
62 ptg.Label(f"[{slow2}]This is a very long message...", parent_align=0),
63 width=50,
64 )
65 )