Skip to content

Commit 78ac685

Browse files
committed
Prevent accidental loss of unsaved notes
1 parent 4146283 commit 78ac685

7 files changed

Lines changed: 186 additions & 22 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
### Fixed
6+
7+
- Closing lesson or chapter notes with unsaved edits now offers Save, Discard, or
8+
Keep editing. Escape and Enter in the prompt return to the draft; failed saves
9+
keep the text in the editor for retry.
10+
311
## 1.2.0 — Repository preparation
412

513
This version is prepared for publication; the tag/release is not created by these files.

‎README.md‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,17 @@ tree; the detail sidebar appears at 118 columns. Press `?` for the in-app key gu
148148
| Search | `Ctrl-U` | Clear the query |
149149
| Notes | `Ctrl-S` | Save and close |
150150
| Notes | `Enter` / arrows | New line / move the cursor |
151-
| Search or notes | `Esc` | Cancel; unsaved note edits are discarded |
151+
| Search | `Esc` | Cancel |
152+
| Notes | `Esc` | Close; prompt if there are unsaved edits |
153+
| Unsaved notes prompt | `S` / `Ctrl-S` | Save and close |
154+
| Unsaved notes prompt | `D` | Discard edits and close |
155+
| Unsaved notes prompt | `Esc` / `Enter` / `C` | Keep editing |
152156

153157
Notes support up to 20,000 characters each. Completion autosaves immediately;
154-
**note edits save when you press `Ctrl-S`**. Undo/redo applies to completion changes,
155-
not notes or quest pins, and resets when you close the app.
158+
**note edits save when you press `Ctrl-S` or choose Save in the close prompt**.
159+
Closing a changed lesson or chapter note asks you to save, discard, or keep editing.
160+
If saving fails, the editor keeps your text so you can retry. Undo/redo applies to
161+
completion changes, not notes or quest pins, and resets when you close the app.
156162

157163
## Command-line options
158164

‎cpp_tree/app.py‎

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -309,26 +309,36 @@ def note_position(self, rows: Sequence[NoteRow]) -> tuple[int, int]:
309309
break
310310
return chosen, self.note_cursor - rows[chosen][0]
311311

312+
def save_note(self) -> None:
313+
modal = self.modal
314+
if modal is None or modal[0] not in ("notes", "notes_confirm"):
315+
return
316+
_, note_key, title, subtitle = modal
317+
old = dict(self.notes)
318+
if self.note_buffer.strip():
319+
self.notes[note_key] = self.note_buffer
320+
else:
321+
_ = self.notes.pop(note_key, None)
322+
if self.save():
323+
self.modal = None
324+
self.notice("Note saved" + (" · demo only" if self.store.demo else ""))
325+
else:
326+
self.notes = old
327+
self.modal = ("notes", note_key, title, subtitle)
328+
312329
def edit_note(self, key: str | int) -> None:
313330
modal = self.modal
314331
if modal is None or modal[0] != "notes":
315332
return
316333
if key == "\x13": # Ctrl-S; terminal is in raw mode, so no flow-control freeze.
317-
_, note_key, _, _ = modal
318-
old = dict(self.notes)
319-
if self.note_buffer.strip():
320-
self.notes[note_key] = self.note_buffer
321-
else:
322-
_ = self.notes.pop(note_key, None)
323-
if self.save():
324-
self.modal = None
325-
self.notice("Note saved" + (" · demo only" if self.store.demo else ""))
326-
else:
327-
self.notes = old
334+
self.save_note()
328335
return
329336
if key == "\x1b":
330-
self.modal = None
331-
self.notice("Note editor closed. Unsaved edits discarded.")
337+
if self.note_buffer != self.notes.get(modal[1], ""):
338+
self.modal = ("notes_confirm", modal[1], modal[2], modal[3])
339+
else:
340+
self.modal = None
341+
self.notice("Note editor closed.")
332342
return
333343
pos = self.note_cursor
334344
if key in (curses.KEY_LEFT, "\x02"):
@@ -385,6 +395,15 @@ def handle_modal(self, key: str | int) -> None:
385395
if modal[0] == "notes":
386396
self.edit_note(key)
387397
return
398+
if modal[0] == "notes_confirm":
399+
if key in ("s", "S", "\x13"):
400+
self.save_note()
401+
elif key in ("d", "D"):
402+
self.modal = None
403+
self.notice("Note editor closed. Unsaved edits discarded.")
404+
elif key in ("c", "C", "\x1b", "\n", "\r", curses.KEY_ENTER):
405+
self.modal = ("notes", modal[1], modal[2], modal[3])
406+
return
388407
if key == "\x1b":
389408
self.modal = None
390409
return

‎cpp_tree/models.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def __init__(self, state: Path) -> None:
6363

6464
Node = Lesson | Chapter
6565
Modal = (
66-
tuple[Literal["notes"], str, str, str]
66+
tuple[Literal["notes", "notes_confirm"], str, str, str]
6767
| tuple[Literal["bulk"], str]
6868
| tuple[Literal["search"]]
6969
| tuple[Literal["help"]]

‎cpp_tree/views.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ def draw_modal(app: App, cv: Canvas) -> None:
270270
cv.text(
271271
x + 3,
272272
y + height - 3,
273-
"Ctrl-S save Esc cancel Enter newline Arrows move",
273+
"Ctrl-S save Esc close Enter newline Arrows move",
274274
"panel_gold",
275275
width - 6,
276276
)
@@ -293,6 +293,14 @@ def draw_modal(app: App, cv: Canvas) -> None:
293293
"panel_gold",
294294
width - 6,
295295
)
296+
elif modal[0] == "notes_confirm":
297+
height, y = 12, (cv.h - 12) // 2
298+
cv.box(x, y, width, height, "panel_gold", "panel")
299+
cv.text(x + 3, y + 1, "UNSAVED NOTE CHANGES", "panel_gold", width - 6)
300+
cv.text(x + 3, y + 3, modal[2] + " · " + modal[3], "panel_muted", width - 6)
301+
cv.text(x + 3, y + 5, "S / Ctrl-S Save and close", "panel", width - 6)
302+
cv.text(x + 3, y + 7, "D Discard changes", "panel", width - 6)
303+
cv.text(x + 3, y + 9, "Esc / Enter / C Keep editing", "panel_gold", width - 6)
296304
elif modal[0] == "search":
297305
height = min(cv.h - 4, 24)
298306
y = (cv.h - height) // 2

‎tests/test_app.py‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ def test_notes_save_cancel_and_stream_view_hide_contents(self):
7777
app.handle("e")
7878
app.note_buffer = "Discard this"
7979
app.handle("\x1b")
80+
app.handle("d")
8081
self.assertNotEqual(app.notes["lesson:0:0.1"], "Discard this")
8182
app.handle("s")
8283
app.handle("e")
@@ -85,6 +86,114 @@ def test_notes_save_cancel_and_stream_view_hide_contents(self):
8586
self.assertNotIn("PRIVATE NOTE CONTENT", text)
8687
self.assertNotIn("PRIVATE NOTE CONTENT", self.path.with_name("stream.txt").read_text())
8788

89+
def test_unsaved_lesson_and_chapter_notes_can_resume_and_save(self):
90+
app = self.app
91+
app.handle("\n")
92+
for shortcut, note_key in (("e", "lesson:0:0.1"), ("E", "chapter:0")):
93+
with self.subTest(shortcut=shortcut):
94+
app.handle(shortcut)
95+
for key in "Draft notes":
96+
app.handle(key)
97+
editor = app.modal
98+
position = (app.note_cursor, app.note_offset)
99+
for resume in ("\x1b", "\n", "c"):
100+
app.handle("\x1b")
101+
self.assertIsNotNone(app.modal)
102+
text = "\n".join(
103+
"".join(ch for ch, _ in row) for row in app.render(72, 22).cells
104+
)
105+
self.assertIn("UNSAVED NOTE CHANGES", text)
106+
self.assertIn("Save and close", text)
107+
self.assertIn("Discard changes", text)
108+
self.assertIn("Keep editing", text)
109+
self.assertNotIn(note_key, read_snapshot(self.path)["notes"])
110+
app.handle(resume)
111+
self.assertEqual(app.modal, editor)
112+
self.assertEqual(app.note_buffer, "Draft notes")
113+
self.assertEqual((app.note_cursor, app.note_offset), position)
114+
app.handle("!")
115+
app.handle("\x1b")
116+
app.handle("s" if shortcut == "e" else "\x13")
117+
self.assertIsNone(app.modal)
118+
self.assertEqual(read_snapshot(self.path)["notes"][note_key], "Draft notes!")
119+
app.handle(shortcut)
120+
self.assertEqual(app.note_buffer, "Draft notes!")
121+
app.handle("\x1b")
122+
self.assertIsNone(app.modal)
123+
124+
def test_discarding_edits_or_deletion_keeps_previous_note(self):
125+
app = self.app
126+
app.handle("\n")
127+
for shortcut, note_key in (("e", "lesson:0:0.1"), ("E", "chapter:0")):
128+
with self.subTest(shortcut=shortcut):
129+
app.handle(shortcut)
130+
app.note_buffer = "Previously saved"
131+
app.handle("\x13")
132+
for draft in ("Replacement", ""):
133+
app.handle(shortcut)
134+
app.note_buffer = draft
135+
app.handle("\x1b")
136+
self.assertIsNotNone(app.modal)
137+
app.handle("d")
138+
self.assertIsNone(app.modal)
139+
self.assertEqual(
140+
read_snapshot(self.path)["notes"][note_key], "Previously saved"
141+
)
142+
app.handle(shortcut)
143+
self.assertEqual(app.note_buffer, "Previously saved")
144+
app.handle("\x1b")
145+
app.handle(shortcut)
146+
app.note_buffer = ""
147+
app.handle("\x1b")
148+
app.handle("s")
149+
self.assertIsNone(app.modal)
150+
self.assertNotIn(note_key, read_snapshot(self.path)["notes"])
151+
152+
def test_unchanged_notes_close_without_prompt_or_write(self):
153+
app = self.app
154+
app.handle("\n")
155+
for shortcut in ("e", "E"):
156+
with self.subTest(shortcut=shortcut), patch.object(self.store, "save") as save:
157+
app.handle(shortcut)
158+
app.handle("x")
159+
app.handle("\x7f")
160+
app.handle("\x1b")
161+
self.assertIsNone(app.modal)
162+
save.assert_not_called()
163+
164+
def test_confirmation_save_failure_keeps_draft_and_allows_retry(self):
165+
app = self.app
166+
app.handle("\n")
167+
app.handle("e")
168+
app.note_buffer = "Original note"
169+
app.handle("\x13")
170+
app.handle("e")
171+
editor = app.modal
172+
app.note_buffer = "Keep this draft"
173+
with patch.object(self.store, "save", side_effect=OSError("disk full")):
174+
app.handle("\x1b")
175+
app.handle("s")
176+
self.assertEqual(app.modal, editor)
177+
self.assertEqual(app.note_buffer, "Keep this draft")
178+
self.assertEqual(app.notes["lesson:0:0.1"], "Original note")
179+
self.assertEqual(read_snapshot(self.path)["notes"]["lesson:0:0.1"], "Original note")
180+
text = "\n".join("".join(ch for ch, _ in row) for row in app.render(72, 22).cells)
181+
self.assertIn("Save failed. Text kept in editor.", text)
182+
app.handle("\x13")
183+
self.assertIsNone(app.modal)
184+
self.assertEqual(read_snapshot(self.path)["notes"]["lesson:0:0.1"], "Keep this draft")
185+
186+
def test_demo_notes_confirmation_does_not_write_to_disk(self):
187+
path = Path(self.temp.name) / "demo" / "progress.json"
188+
app = App(Store(path, demo=True), Options(path))
189+
app.handle("E")
190+
app.note_buffer = "Demo draft"
191+
app.handle("\x1b")
192+
app.handle("s")
193+
self.assertIsNone(app.modal)
194+
self.assertEqual(app.notes["chapter:0"], "Demo draft")
195+
self.assertFalse(path.parent.exists())
196+
88197
def test_failed_save_rolls_back_progress_focus_and_notes(self):
89198
app = self.app
90199
app.handle("\n")
@@ -121,6 +230,7 @@ def test_render_at_supported_and_small_sizes_with_all_modals(self):
121230
("help",),
122231
("bulk", "0"),
123232
("notes", "chapter:0", "CHAPTER 0", "Notes"),
233+
("notes_confirm", "chapter:0", "CHAPTER 0", "Notes"),
124234
):
125235
with self.subTest(size=size, modal=modal):
126236
app.modal = modal

‎tests/test_terminal.py‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Drive actual curses sessions through a pseudoterminal, including saves."""
22

33
import fcntl
4+
import itertools
45
import os
56
import pty
67
import select
@@ -20,11 +21,11 @@
2021

2122
class TerminalTests(unittest.TestCase):
2223
def test_interactive_search_notes_save_and_terminal_modes(self):
23-
for mode in ("truecolor", "256"):
24-
with self.subTest(mode=mode), tempfile.TemporaryDirectory() as work:
24+
for mode, size in itertools.product(("truecolor", "256"), ((22, 72), (40, 140))):
25+
with self.subTest(mode=mode, size=size), tempfile.TemporaryDirectory() as work:
2526
master, slave = pty.openpty()
2627
state = Path(work) / "progress.json"
27-
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 140, 0, 0))
28+
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", *size, 0, 0))
2829
process = subprocess.Popen(
2930
[sys.executable, "-m", "cpp_tree", "--state", str(state), "--color", mode],
3031
cwd=ROOT,
@@ -53,13 +54,25 @@ def read_until(marker, timeout=8):
5354
read_until(b"CORE TALENTS")
5455
os.write(master, b"/4.9\nfe")
5556
read_until(b"NOTES")
56-
os.write(master, b"Terminal integration test\x13 q")
57+
transcript.clear()
58+
os.write(master, b"Terminal integration test\x1b")
59+
read_until(b"UNSAVED NOTE CHANGES")
60+
transcript.clear()
61+
os.write(master, b"\x1b")
62+
read_until(b"Ctrl-S save")
63+
os.write(master, b"\x13E")
64+
read_until(b"CHAPTER 4 NOTES")
65+
transcript.clear()
66+
os.write(master, b"Chapter integration test\x1b")
67+
read_until(b"UNSAVED NOTE CHANGES")
68+
os.write(master, b"s q")
5769
read_until(b"Progress saved")
5870
self.assertEqual(process.wait(timeout=5), 0)
5971
data = read_snapshot(state)
6072
self.assertEqual(data["focus"], "4:4.9")
6173
self.assertIn("4:4.9", data["completed"])
6274
self.assertEqual(data["notes"]["lesson:4:4.9"], "Terminal integration test")
75+
self.assertEqual(data["notes"]["chapter:4"], "Chapter integration test")
6376
finally:
6477
if process.poll() is None:
6578
process.kill()

0 commit comments

Comments
 (0)