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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
use std::sync::Arc;
use kimun_core::NoteVault;
use kimun_core::nfs::VaultPath;
use ratatui::Frame;
use ratatui::crossterm::event::KeyEvent;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::Style;
use ratatui::widgets::{Block, Borders, Paragraph};
use tokio::task::JoinHandle;
use crate::components::Component;
use crate::components::dialogs::ValidationState;
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, FileOp, OverlayData};
use crate::components::panel::{ModalSpec, modal_chrome};
use crate::components::single_line_input::{InputOutcome, SingleLineInput};
use crate::settings::themes::Theme;
// ---------------------------------------------------------------------------
// RenameDialog
// ---------------------------------------------------------------------------
/// Modal dialog that lets the user rename a note or directory.
///
/// The input is pre-filled with the current filename. As the user types,
/// an async task checks whether the new name already exists in the vault and
/// updates `validation_state` accordingly. Pressing `Enter` while the name
/// is `Available` triggers the actual rename operation.
pub struct RenameDialog {
/// The vault path being renamed.
pub path: VaultPath,
/// Shared reference to the vault for existence checks and the rename op.
pub vault: Arc<NoteVault>,
/// Pre-computed `" {path}"` for zero-allocation rendering.
pub path_display: String,
/// Current text in the input field.
pub input: SingleLineInput,
/// Result of the most-recent validation check.
pub validation_state: ValidationState,
/// Handle to the running validation task so we can abort it on new input.
pub validation_task: Option<JoinHandle<()>>,
/// Optional error message surfaced from a failed rename attempt.
pub error: Option<String>,
}
impl RenameDialog {
/// Create a new `RenameDialog` for `path`.
///
/// The input field is pre-filled with the filename component of `path`.
pub fn new(path: VaultPath, vault: Arc<NoteVault>) -> Self {
let (_, filename) = path.get_parent_path();
let path_display = format!(" {}", path);
Self {
path,
vault,
path_display,
input: SingleLineInput::with_value(filename),
validation_state: ValidationState::Idle,
validation_task: None,
error: None,
}
}
// -----------------------------------------------------------------------
// Validation helpers
// -----------------------------------------------------------------------
/// Abort any in-flight validation task and spawn a new one for the
/// current value of `self.input`. The result is sent as
/// [`OverlayData::RenameValidation`] so that state updates happen in
/// `handle_app_message` rather than in `render`.
fn spawn_validation(&mut self, tx: &AppTx) {
// Abort the previous task if it is still running.
if let Some(handle) = self.validation_task.take() {
handle.abort();
}
let vault = Arc::clone(&self.vault);
let input = self.input.value().to_string();
let path = self.path.clone();
let tx_clone = tx.clone();
let handle = tokio::spawn(async move {
let parent = path.get_parent_path().0;
let candidate = if path.is_note() {
parent.append(&VaultPath::note_path_from(&input))
} else {
parent.append(&VaultPath::new(&input))
};
let exists = vault.exists(&candidate).await;
// `true` means the name is *available* (does not exist yet).
tx_clone
.send(AppEvent::OverlayData(OverlayData::RenameValidation {
available: !exists,
}))
.ok();
});
self.validation_task = Some(handle);
self.validation_state = ValidationState::Pending;
}
// -----------------------------------------------------------------------
// Input handling
// -----------------------------------------------------------------------
/// Handle a raw [`KeyEvent`]. Returns [`EventState::Consumed`] for keys
/// this dialog acts on; callers should forward only key events.
pub fn handle_key(&mut self, key: KeyEvent, tx: &AppTx) -> EventState {
match self.input.handle_key(&key) {
InputOutcome::Submit => {
if self.validation_state == ValidationState::Available {
let from = self.path.clone();
let parent = from.get_parent_path().0;
let new_name = self.input.value();
let new_path = if from.is_note() {
parent.append(&VaultPath::note_path_from(new_name))
} else {
parent.append(&VaultPath::new(new_name))
};
let vault = Arc::clone(&self.vault);
let tx2 = tx.clone();
tokio::spawn(async move {
// Core classifies the entry and routes to the right
// rename (note / directory / attachment).
let result = vault.rename_entry(&from, &new_path).await;
match result {
Ok(()) => {
tx2.send(AppEvent::FileOp(FileOp::Renamed { from, to: new_path }))
.ok();
}
Err(e) => {
tx2.send(AppEvent::OverlayData(OverlayData::Error(e.to_string())))
.ok();
}
}
});
}
EventState::Consumed
}
InputOutcome::Cancel => {
tx.send(AppEvent::CloseOverlay).ok();
EventState::Consumed
}
InputOutcome::Changed => {
self.spawn_validation(tx);
EventState::Consumed
}
InputOutcome::Consumed => EventState::Consumed,
InputOutcome::NotConsumed => EventState::NotConsumed,
}
}
}
// ---------------------------------------------------------------------------
// Component trait
// ---------------------------------------------------------------------------
impl Component for RenameDialog {
fn render(&mut self, f: &mut Frame, rect: Rect, theme: &Theme, _focused: bool) {
// Fixed size: 50 wide; height depends on whether there is an error row.
// Border(2) + spacer + path + separator + label + input(3) + validation
// + spacer + hint [+ error] = 11 or 12.
let height = if self.error.is_some() { 13 } else { 12 };
let popup_area = super::fixed_centered_rect(50, height, rect);
let inner = modal_chrome(
f,
popup_area,
theme,
ModalSpec {
title: Some(" Rename "),
border: Some(Style::default().fg(theme.fg.to_ratatui())),
..Default::default()
},
);
// ── Vertical layout inside the block ─────────────────────────────────
//
// Row 0: spacer
// Row 1: current path
// Row 2: separator
// Row 3: "NEW NAME" label
// Row 4: input field (height 3, bordered)
// Row 5: validation status
// Row 6: spacer
// Row 7: hint line
// Row 8 (optional): error line
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1), // 0: spacer
Constraint::Length(1), // 1: path
Constraint::Length(1), // 2: separator
Constraint::Length(1), // 3: "NEW NAME" label
Constraint::Length(3), // 4: input field (bordered)
Constraint::Length(1), // 5: validation status
Constraint::Length(1), // 6: spacer
Constraint::Length(1), // 7: hint
Constraint::Min(0), // 8: remainder / error
])
.split(inner);
let bg = theme.bg_panel.to_ratatui();
let fg = theme.fg.to_ratatui();
let gray = theme.gray.to_ratatui();
// Row 1: path.
super::render_path_row(f, rows[1], &self.path_display, fg, bg);
// Row 2: separator.
super::render_separator(f, rows[2], gray, bg);
// Row 3: "NEW NAME" label.
f.render_widget(
Paragraph::new(" NEW NAME").style(Style::default().fg(gray).bg(bg)),
rows[3],
);
// Row 4: input field with cursor and validation indicator.
//
// Split horizontally: [input_area | indicator (3 cols)].
let input_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Min(1), // input field
Constraint::Length(3), // validation indicator
])
.split(rows[4]);
let input_block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(gray))
.style(Style::default().bg(bg));
let input_inner = input_block.inner(input_chunks[0]);
f.render_widget(input_block, input_chunks[0]);
self.input
.render(f, input_inner, Style::default().fg(fg).bg(bg), 0, true);
// Validation indicator glyph, centred vertically in the 3-row area.
let (indicator_text, indicator_style) = match self.validation_state {
ValidationState::Idle => (" ", Style::default()),
ValidationState::Pending => (" \u{231b} ", Style::default().fg(gray)),
ValidationState::Available => {
(" \u{2713} ", Style::default().fg(theme.green.to_ratatui()))
}
ValidationState::Taken => (" \u{2717} ", Style::default().fg(theme.red.to_ratatui())),
};
let indicator_rows = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Length(1),
])
.split(input_chunks[1]);
f.render_widget(
Paragraph::new(indicator_text).style(indicator_style.bg(bg)),
indicator_rows[1],
);
// Row 5: validation status text.
let (status_text, status_style) = match self.validation_state {
ValidationState::Idle => ("", Style::default()),
ValidationState::Pending => (" Checking...", Style::default().fg(gray).bg(bg)),
ValidationState::Available => (
" Available",
Style::default().fg(theme.green.to_ratatui()).bg(bg),
),
ValidationState::Taken => (
" Already exists",
Style::default().fg(theme.red.to_ratatui()).bg(bg),
),
};
f.render_widget(Paragraph::new(status_text).style(status_style), rows[5]);
// Row 7: hint. Dim the Enter part unless rename is available.
super::render_confirm_hint(
f,
rows[7],
" [Enter] Rename",
self.validation_state == ValidationState::Available,
fg,
gray,
bg,
);
// Row 8 (optional): error message.
if let Some(msg) = &self.error {
super::render_error_row(f, rows[8], msg, theme);
}
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use kimun_core::VaultConfig;
use tokio::sync::mpsc;
/// Compile-time smoke test: verify all `ValidationState` variants are
/// accessible and exhaustively matched without a real vault.
#[test]
fn validation_state_variants_compile() {
let states = [
ValidationState::Idle,
ValidationState::Pending,
ValidationState::Available,
ValidationState::Taken,
];
for state in states {
let _label = match state {
ValidationState::Idle => "idle",
ValidationState::Pending => "pending",
ValidationState::Available => "available",
ValidationState::Taken => "taken",
};
}
}
/// Verifies that the `input` field is pre-filled with the filename
/// component of the supplied path.
///
/// This test does not exercise the vault at all — `new()` never calls
/// any async vault method — so it runs without any file-system setup.
///
/// NOTE: It is gated `#[ignore]` because constructing `NoteVault` requires
/// a real SQLite database on disk. Run it explicitly with:
///
/// ```text
/// cargo test -- --ignored rename_dialog::tests::new_prefills_input
/// ```
#[tokio::test]
#[ignore = "requires a real vault directory with kimun.sqlite"]
async fn new_prefills_input() {
use std::path::PathBuf;
let tmp = std::env::temp_dir().join("kimun_rename_test_vault");
std::fs::create_dir_all(&tmp).unwrap();
let vault = Arc::new(
NoteVault::new(VaultConfig::new(crate::test_support::sys(PathBuf::from(
&tmp,
))))
.await
.expect("vault creation failed"),
);
let (_tx, _rx) = mpsc::unbounded_channel::<AppEvent>();
let path = VaultPath::new("notes/projects/kimun.md");
let (_, expected_filename) = path.get_parent_path();
let dialog = RenameDialog::new(path, vault);
assert_eq!(dialog.input.value(), expected_filename);
}
/// Verifies that pressing `Esc` sends `AppEvent::CloseOverlay` and returns
/// `EventState::Consumed`, without touching the vault.
#[test]
fn esc_sends_close_dialog() {
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let tmp = std::env::temp_dir().join("kimun_rename_esc_test");
std::fs::create_dir_all(&tmp).unwrap();
let vault_result =
NoteVault::new(VaultConfig::new(crate::test_support::sys(tmp))).await;
let Ok(vault) = vault_result else {
// No vault available in CI — skip gracefully.
return;
};
let vault = Arc::new(vault);
let (tx, mut rx) = mpsc::unbounded_channel::<AppEvent>();
let mut dialog = RenameDialog::new(VaultPath::new("notes/test.md"), vault);
let key = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
let state = dialog.handle_key(key, &tx);
assert_eq!(state, EventState::Consumed);
let event = rx.try_recv().expect("expected AppEvent::CloseOverlay");
assert!(matches!(event, AppEvent::CloseOverlay));
});
}
}