Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions docs/assets/reviews/auto-advance-completed.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
215 changes: 215 additions & 0 deletions docs/assets/reviews/auto-advance-countdown.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions pythonlings/core/exercise.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# pythonlings/core/exercise.py
from __future__ import annotations

import io
import tokenize
from dataclasses import dataclass
from pathlib import Path

Expand All @@ -22,6 +24,28 @@ class Exercise:
def is_pending(self) -> bool:
return self.DONE_MARKER in self.path.read_text(encoding="utf-8")

def strip_marker(self, text: str) -> str:
"""Remove standalone marker comments while preserving program text."""
# Token rows count newlines, not Unicode separators inside strings.
lines = io.StringIO(text).readlines()
try:
markers = {
token.start[0]
for token in tokenize.generate_tokens(
io.StringIO(text).readline
)
if token.type == tokenize.COMMENT
and token.string.strip() == self.DONE_MARKER
and lines[token.start[0] - 1].strip() == self.DONE_MARKER
}
except (tokenize.TokenError, IndentationError):
return text
return "".join(
line
for number, line in enumerate(lines, 1)
if number not in markers
)


@dataclass
class RunResult:
Expand Down
99 changes: 94 additions & 5 deletions pythonlings/screens/track.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from pythonlings.widgets.progress import ProgressBar

_DEBOUNCE_SECONDS = 0.6
_AUTO_ADVANCE_SECONDS = 5
_FULL_FOOTER_WIDTH = 70


Expand Down Expand Up @@ -79,7 +80,12 @@ def __init__(self, topic: str, start_exercise: str | None = None) -> None:
self.topic = topic
self._start_exercise = start_exercise
self._save_timer: Timer | None = None
self._advance_timer: Timer | None = None
self._advance_remaining = 0
self._advance_exercise: Exercise | None = None
self._advance_text = ""
self._persisted_text = ""
self._run_id = 0
self._failure_counts: dict[str, int] = {}
self.current: str | None = None

Expand Down Expand Up @@ -147,11 +153,13 @@ def _exercise(self, name: str) -> Exercise:
raise KeyError(name)

def _load_current(self) -> None:
"""Load `self.current` into the editor, resetting per-exercise state."""
if self.current is None:
return
if self._save_timer is not None:
self._save_timer.stop()
self._save_timer = None
self._stop_advance_timer()
self.query_one(OutputPanel).reset_hint()
pane = self.query_one(EditorPane)
pane.load_exercise(self._exercise(self.current))
Expand All @@ -166,10 +174,12 @@ def _record_resume(self, exercise: str | None) -> None:
# --- auto-save / run loop -------------------------------------------

def on_text_area_changed(self, event: TextArea.Changed) -> None:
"""Restart the save/run debounce timer on each real editor edit."""
if event.text_area is not self.query_one("#code", TextArea):
return
if self.query_one(EditorPane).text == self._persisted_text:
return
self._stop_advance_timer()
if self._save_timer is not None:
self._save_timer.stop()
self._save_timer = self.set_timer(
Expand All @@ -190,35 +200,65 @@ def _run_current(self) -> None:
if self.current is None:
return
ex = self._exercise(self.current)
checked_text = self.query_one(EditorPane).text
self._run_id += 1
run_id = self._run_id
completed, total = self._progress_counts()
self.query_one(OutputPanel).render_running(ex, completed, total)
self.run_worker(
lambda: self._run_blocking(ex), exclusive=True, thread=True
lambda: self._run_blocking(ex, checked_text, run_id),
exclusive=True,
thread=True,
)

def _run_blocking(self, exercise: Exercise) -> None:
def _run_blocking(
self, exercise: Exercise, checked_text: str, run_id: int
) -> None:
result = run_exercise(exercise)
self.app.call_from_thread(self._apply_result, exercise, result)
self.app.call_from_thread(
self._apply_result, exercise, result, checked_text, run_id
)

def _apply_result(self, exercise: Exercise, result: RunResult) -> None:
def _apply_result(
self,
exercise: Exercise,
result: RunResult,
checked_text: str,
run_id: int,
) -> None:
"""Render a check result and advance once it's fully passed."""
if not self.is_attached:
return # the track screen was popped while a run was in flight
if exercise.name != self.current:
if (
exercise.name != self.current
or run_id != self._run_id
or self.query_one(EditorPane).text != checked_text
):
return
if result.exit_code != 0 or result.timed_out:
self._failure_counts[exercise.name] = (
self._failure_counts.get(exercise.name, 0) + 1
)
else:
self._failure_counts[exercise.name] = 0
checks_ok = result.exit_code == 0 and not result.timed_out
auto_advance = (
checks_ok and exercise.strip_marker(checked_text) != checked_text
)
completed, total = self._progress_counts()
self.query_one(OutputPanel).render_result(
exercise,
result,
failures=self._failure_counts.get(exercise.name, 0),
completed=completed,
total=total,
auto_advance_seconds=_AUTO_ADVANCE_SECONDS
if auto_advance
else None,
)
if auto_advance:
self._schedule_auto_advance(exercise, checked_text)
return
if not result.passed:
return
self.app.state.mark_done(exercise.name)
Expand All @@ -240,6 +280,53 @@ def _apply_result(self, exercise: Exercise, result: RunResult) -> None:
self._load_current()
self._run_current()

def _schedule_auto_advance(
self, exercise: Exercise, checked_text: str
) -> None:
"""Start the countdown that strips the marker once checks pass."""
self._stop_advance_timer()
self._advance_exercise = exercise
self._advance_text = checked_text
self._advance_remaining = _AUTO_ADVANCE_SECONDS
self._advance_timer = self.set_interval(1.0, self._tick_advance)

def _stop_advance_timer(self) -> None:
"""Cancel any pending auto-advance countdown, e.g. on a resumed edit."""
if self._advance_timer is not None:
self._advance_timer.stop()
self._advance_timer = None
self._advance_exercise = None
self._advance_text = ""

def _tick_advance(self) -> None:
"""Decrement the countdown each second, firing the advance at zero."""
self._advance_remaining -= 1
exercise, checked_text = self._advance_exercise, self._advance_text
if self._advance_remaining <= 0:
self._stop_advance_timer()
if exercise is not None:
self._auto_advance(exercise, checked_text)
return
if self.is_attached:
self.query_one(OutputPanel).update_countdown(
self._advance_remaining
)

def _auto_advance(self, exercise: Exercise, checked_text: str) -> None:
"""Strip the marker and rerun if the checked text is still current."""
if not self.is_attached or exercise.name != self.current:
return
pane = self.query_one(EditorPane)
if pane.text != checked_text:
return # the learner resumed editing; let the normal loop take over
stripped = exercise.strip_marker(checked_text)
if stripped == checked_text:
return
self._persisted_text = stripped
pane.set_text(stripped)
exercise.path.write_text(stripped, encoding="utf-8")
self._run_current()

# --- actions ---------------------------------------------------------

def action_toggle_hint(self) -> None:
Expand Down Expand Up @@ -285,6 +372,8 @@ def action_quit(self) -> None:
self.app.exit(0)

def _flush_pending(self) -> None:
"""Write out an unsaved edit before leaving the screen."""
self._stop_advance_timer()
if self._save_timer is not None:
self._save_timer.stop()
self._save_timer = None
Expand Down
4 changes: 2 additions & 2 deletions pythonlings/screens/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ def welcome_text() -> str:
"The loop is:\n\n"
" 1. Edit the current exercise in the built-in editor.\n"
" 2. Checks rerun automatically as you type.\n"
" 3. Remove the `# I AM NOT DONE` marker "
"to advance to the next one.\n\n"
" 3. Once checks pass, the `# I AM NOT DONE` line clears\n"
" after five seconds. Keep editing to cancel advancement.\n\n"
"Handy keys: F1 hint - F3 exercise list - F4 topics - "
"F5 local docs - Ctrl+Q quit.\n\n"
"Press Enter to start."
Expand Down
6 changes: 6 additions & 0 deletions pythonlings/widgets/editor_pane.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,14 @@ def load_exercise(self, exercise: Exercise) -> None:
area.move_cursor((0, 0))

def focus_editor(self) -> None:
"""Move input focus to the code editor."""
self.query_one("#code", TextArea).focus()

@property
def text(self) -> str:
"""The editor's current buffer contents."""
return self.query_one("#code", TextArea).text

def set_text(self, text: str) -> None:
"""Replace the editor contents without touching the cursor position."""
self.query_one("#code", TextArea).text = text
22 changes: 19 additions & 3 deletions pythonlings/widgets/output_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ def render_result(
failures: int = 0,
completed: int = 0,
total: int = 0,
auto_advance_seconds: float | None = None,
) -> None:
"""Render a finished check run: failure, pending marker, or complete."""
self._render_header(exercise, completed, total)
self.query_one("#goal", Static).update(
f"[bold]Goal[/bold]\n{self._goal_from(exercise)}"
Expand Down Expand Up @@ -98,11 +100,14 @@ def render_result(
if exercise.is_pending():
self.add_class("pending")
self.query_one("#status", Static).update(
"[bold yellow]Checks pass, remove marker[/bold yellow]"
"[bold green]✓ Checks pass[/bold green]"
)
self.query_one("#next-step", Static).update(
"Remove the # I AM NOT DONE line to advance."
next_step = (
self._advance_message(auto_advance_seconds)
if auto_advance_seconds
else "Remove the # I AM NOT DONE line to advance."
)
self.query_one("#next-step", Static).update(next_step)
return
self.add_class("passed")
self.query_one("#status", Static).update(
Expand All @@ -112,6 +117,17 @@ def render_result(
"Loading the next exercise."
)

def update_countdown(self, seconds: int) -> None:
"""Tick the auto-advance countdown shown in the pending state."""
self.query_one("#next-step", Static).update(
self._advance_message(seconds)
)

@staticmethod
def _advance_message(seconds: float) -> str:
"""Format the shared countdown text used by both render paths."""
return f"Advancing to the next exercise in {seconds:.0f}s…"

def show_final(self, message: str) -> None:
"""Render the whole-curriculum-complete screen."""
self._show_complete("All exercises complete", message)
Expand Down
Loading
Loading