Skip to content

Commit

Permalink
refactor: add missing type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
kraanzu committed Jan 26, 2024
1 parent 547d8e8 commit 30bcb38
Show file tree
Hide file tree
Showing 23 changed files with 113 additions and 111 deletions.
4 changes: 2 additions & 2 deletions smassh/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
)
@click.option("--version", "-v", is_flag=True, help="Show version and exit.")
@click.pass_context
def main(ctx, version: bool):
def main(ctx, version: bool) -> None:
if version:
return print(f"smassh - v{pkgVersion('smassh')}")

Expand All @@ -20,5 +20,5 @@ def main(ctx, version: bool):

@main.command(help="Add a language to smassh")
@click.argument("name")
def add(name: str):
def add(name: str) -> None:
AddLanguage().add(name)
2 changes: 1 addition & 1 deletion smassh/src/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys


def convert_css(input_file, output_file):
def convert_css(input_file, output_file) -> None:
with open(input_file, "r") as f:
css_content = f.read()

Expand Down
2 changes: 1 addition & 1 deletion smassh/src/css_generator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from pathlib import Path


def generate_theme_file(theme: str):
def generate_theme_file(theme: str) -> None:
css_folder = Path.absolute(Path(__file__).parent.parent) / "ui" / "css"
themes_folder = css_folder / "themes"

Expand Down
10 changes: 5 additions & 5 deletions smassh/src/parser/config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,25 +51,25 @@ def configured_themes(self) -> List[str]:
]
return themes

def toggle_numbers(self):
def toggle_numbers(self) -> None:
numbers = self.get("numbers")
self.set("numbers", not numbers)

def toggle_punctuations(self):
def toggle_punctuations(self) -> None:
punctuations = self.get("punctuations")
self.set("punctuations", not punctuations)

def toggle_mode(self):
def toggle_mode(self) -> None:
mode = self.get("mode")
mode = "words" if mode == "time" else "time"
self.set("mode", mode)

@property
def theme(self):
def theme(self) -> str:
return self.get("theme") or "nord"

@theme.setter
def theme(self, theme: str):
def theme(self, theme: str) -> None:
self.set("theme", theme)


Expand Down
6 changes: 3 additions & 3 deletions smassh/src/parser/data_parser.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import Dict, List
from typing import Any, Dict, List
from .parser import Parser
from smassh.src.stats_tracker import StatsTracker
from smassh.src.parser.config_parser import config_parser
Expand All @@ -10,7 +10,7 @@ class DataParser(Parser):
config_path = Path(appdirs.user_data_dir("smassh"))
DEFAULT_CONFIG = dict(data=[])

def generate_report(self, stats: StatsTracker):
def generate_report(self, stats: StatsTracker) -> Dict[str, Any]:
mode = config_parser.get("mode")
count = config_parser.get(f"{mode}_count")
start = stats.start_time or 0
Expand All @@ -27,7 +27,7 @@ def generate_report(self, stats: StatsTracker):
accuracy=stats.accuracy,
)

def add_stats(self, stats: StatsTracker, failed: bool):
def add_stats(self, stats: StatsTracker, failed: bool) -> None:
report = self.generate_report(stats) | dict(failed=failed)
self.get("data").append(report)
self.save()
Expand Down
4 changes: 2 additions & 2 deletions smassh/src/plugins/add_language.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
class AddLanguage:
"""Adds a new language to smassh"""

def log(self, message: str, color: str = "green"):
def log(self, message: str, color: str = "green") -> None:
"""Logs a message to the console"""
print(f"=>[bold {color}] {message}[/bold {color}]")

Expand All @@ -23,7 +23,7 @@ def get_pack(self, name: str) -> Optional[str]:

return req.text if (req.status_code == 200) else None

def add(self, name: str):
def add(self, name: str) -> None:
"""Downloads a new language for smassh"""

self.log("Checking if language pack exists...")
Expand Down
15 changes: 7 additions & 8 deletions smassh/src/stats_tracker.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from math import inf
from time import time
from dataclasses import dataclass
from enum import Enum
Expand Down Expand Up @@ -39,7 +38,7 @@ def get_checkpoints_last_word(self) -> List[CheckPoint]:
return list(reversed(word_checkpoints))

@property
def elapsed_time(self):
def elapsed_time(self) -> float:
if not self.start_time:
raise ValueError("Start time not set")

Expand All @@ -49,14 +48,14 @@ def elapsed_time(self):
return time() - self.start_time

@property
def word_count(self):
def word_count(self) -> int:
if not self.checkpoints:
return 0

return sum(checkpoint.letter == " " for checkpoint in self.checkpoints)

@property
def last_word_accuracy(self):
def last_word_accuracy(self) -> int:
correct = 0
incorrect = 0

Expand All @@ -72,18 +71,18 @@ def last_word_accuracy(self):
return round((correct / (correct + incorrect)) * 100)

@property
def last_word_wpm(self):
def last_word_wpm(self) -> int:
checkpoints = self.get_checkpoints_last_word()

if not checkpoints:
return ValueError("No checkpoints")
raise ValueError("No checkpoints")

start = checkpoints[0].elapsed
stop = checkpoints[-1].elapsed
elapsed = stop - start

if elapsed == 0:
return inf
raise ValueError("Elapsed time is 0")

raw = 60 / elapsed
return round(self.last_word_accuracy * raw / 100)
Expand All @@ -101,7 +100,7 @@ def accuracy(self) -> int:
return round(accuracy)

@property
def wpm(self) -> float:
def wpm(self) -> int:
return round(self.raw_wpm * (self.accuracy / 100))

@property
Expand Down
8 changes: 4 additions & 4 deletions smassh/ui/screens/about.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class Section(Widget):
}
"""

def __init__(self, renderable: str):
def __init__(self, renderable: str) -> None:
super().__init__()
self.renderable = renderable

Expand All @@ -46,12 +46,12 @@ def render(self) -> RenderableType:


class AboutDescription(Section):
def __init__(self):
def __init__(self) -> None:
super().__init__(DESCRIPTION)


class Star(Section):
def __init__(self):
def __init__(self) -> None:
super().__init__(STAR)


Expand All @@ -63,7 +63,7 @@ class AboutOutro(Section):
}
"""

def __init__(self):
def __init__(self) -> None:
super().__init__(OUTRO)


Expand Down
2 changes: 1 addition & 1 deletion smassh/ui/screens/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class Table(Widget):

COMPONENT_CLASSES = {"--header", "--key", "--action"}

def __init__(self, title: str, keys: List[Tuple[str, str]] = []):
def __init__(self, title: str, keys: List[Tuple[str, str]] = []) -> None:
super().__init__()
self.title = title
self.keys = keys
Expand Down
8 changes: 4 additions & 4 deletions smassh/ui/screens/palette.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,22 @@ class PaletteScreen(Screen):

@on(PaletteInput.Changed)
@work(thread=True, exclusive=True)
def update_palette_list(self, event):
def update_palette_list(self, event) -> None:
event.stop()
text = self.query_one(PaletteInput).value
self.query_one(PaletteList).apply_filter(text)

@on(PaletteList.OptionHighlighted)
def preview_palette_option(self, event: PaletteList.OptionHighlighted):
def preview_palette_option(self, event: PaletteList.OptionHighlighted) -> None:
palette_list = self.query_one(PaletteList)
prompt = str(event.option.prompt)
prompt = prompt.replace(" ", "_")
self.post_message(palette_list._highlight_event(prompt))

def action_next_option(self):
def action_next_option(self) -> None:
self.query_one(PaletteList).action_cursor_down()

def action_prev_option(self):
def action_prev_option(self) -> None:
self.query_one(PaletteList).action_cursor_up()

def compose(self) -> ComposeResult:
Expand Down
6 changes: 3 additions & 3 deletions smassh/ui/screens/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class ResultScreen(BaseWindow):
}
"""

def __init__(self, **kwargs):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.wpm = Value()
self.accuracy = Value()
Expand All @@ -56,11 +56,11 @@ def compose(self) -> ComposeResult:
yield ResultStrip()
yield Container()

def set_results(self, stats: StatsTracker):
def set_results(self, stats: StatsTracker) -> None:
self.stats = stats
self.query_one(ValueContainer).update_stats(stats)

def on_hide(self):
def on_hide(self) -> None:
space = self.screen.query_one(Space)
if space.paragraph.spans:
self.screen.query_one(Ticker).reset()
Expand Down
9 changes: 5 additions & 4 deletions smassh/ui/screens/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from textual import events
from smassh.ui.widgets import menu
from smassh.ui.widgets import BaseWindow
from smassh.ui.widgets.settings.settings_options import Setting


class SettingsScreen(BaseWindow):
Expand All @@ -11,12 +12,12 @@ class SettingsScreen(BaseWindow):
}
"""

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.current_option = 0

@property
def current_setting(self):
def current_setting(self) -> Setting:
return menu[self.current_option]

def compose(self) -> ComposeResult:
Expand All @@ -25,11 +26,11 @@ def compose(self) -> ComposeResult:

self.update_highlight()

def update_highlight(self):
def update_highlight(self) -> None:
for index, setting in enumerate(menu):
setting.set_class(index == self.current_option, "selected")

async def handle_key(self, event: events.Key):
async def handle_key(self, event: events.Key) -> None:
key = event.key
n = len(menu)

Expand Down
18 changes: 9 additions & 9 deletions smassh/ui/tui.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ def compose(self) -> ComposeResult:
)

@on(SetScreen)
def screen_change(self, event: SetScreen):
def screen_change(self, event: SetScreen) -> None:
self.query_one(ContentSwitcher).current = event.screen_name
self.query_one(Header).set_active(event.screen_name)

@on(ShowResults)
def show_results(self, event: ShowResults):
def show_results(self, event: ShowResults) -> None:
# reset all watching timers
space = self.query_one(Space)
space.check_timer.pause()
Expand All @@ -51,7 +51,7 @@ def show_results(self, event: ShowResults):

data_parser.add_stats(event.stats, event.failed)

async def handle_key(self, event: events.Key):
async def handle_key(self, event: events.Key) -> None:
visible = self.query_one(ContentSwitcher).visible_content
if visible:
await visible.handle_key(event)
Expand All @@ -65,31 +65,31 @@ class Smassh(App):
"language": LanguagePaletteScreen(),
}

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
self.action_theme(config_parser.get("theme"))
super().__init__(*args, **kwargs, watch_css=True)

async def _on_css_change(self) -> None:
await super()._on_css_change()
self.refresh_css()

async def on_mount(self):
async def on_mount(self) -> None:
self.push_screen("main")

@on(ApplyLanguage)
def apply_language(self, event: ApplyLanguage):
def apply_language(self, event: ApplyLanguage) -> None:
config_parser.set("language", event.value)
self.SCREENS["main"].query_one(LanguagePalette).refresh()
self.SCREENS["main"].query_one(Space).reset()

@on(ApplyTheme)
def apply_theme(self, event: ApplyTheme):
def apply_theme(self, event: ApplyTheme) -> None:
self.action_theme(event.value)
config_parser.set("theme", event.value)
self.SCREENS["main"].query_one(ThemePalette).refresh()

def action_star(self):
def action_star(self) -> None:
webbrowser.open("https://github.com/kraanzu/smassh")

def action_theme(self, theme: str):
def action_theme(self, theme: str) -> None:
generate_theme_file(theme)
3 changes: 2 additions & 1 deletion smassh/ui/widgets/base_window.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Optional
from textual.app import events
from textual.widget import Widget
from smassh.ui.events import SetScreen
Expand All @@ -13,6 +14,6 @@ class BaseWindow(Widget):
}
"""

async def handle_key(self, event: events.Key):
async def handle_key(self, event: events.Key) -> Optional[bool]:
if event.key == "escape":
return self.post_message(SetScreen("typing"))
2 changes: 1 addition & 1 deletion smassh/ui/widgets/header.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class Header(Widget):
}
"""

def set_active(self, name: str):
def set_active(self, name: str) -> None:
for i in self.query(NavItem):
i.set_class(i.screen_name == name, "active")

Expand Down
2 changes: 1 addition & 1 deletion smassh/ui/widgets/label.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class NavItemBase(Widget):
}
"""

def __init__(self, text: str, screen_name: Optional[str] = None):
def __init__(self, text: str, screen_name: Optional[str] = None) -> None:
super().__init__()
self.text = text
self.screen_name = screen_name
Expand Down
Loading

0 comments on commit 30bcb38

Please sign in to comment.