gwm 0.3.4

Git Worktree Manager - A CLI tool for managing Git worktrees with an interactive TUI
Documentation
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! イベントハンドリング
//!
//! キーボード入力などのイベント処理を提供します。

use std::time::Duration;

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};

use crate::error::Result;
use crate::utils::{generate_worktree_preview, validate_branch_name};

use super::app::{App, AppState, ConfirmChoice};

/// キャンセルキー(Ctrl+C または Esc)の判定
pub fn is_cancel_key(key: &KeyEvent) -> bool {
    matches!(
        (key.modifiers, key.code),
        (KeyModifiers::CONTROL, KeyCode::Char('c')) | (KeyModifiers::NONE, KeyCode::Esc)
    )
}

/// イベントをポーリング
///
/// 指定されたタイムアウト内でイベントがあれば返します。
pub fn poll_event(timeout: Duration) -> Result<Option<Event>> {
    if event::poll(timeout)? {
        Ok(Some(event::read()?))
    } else {
        Ok(None)
    }
}

/// キーイベントを処理
///
/// 現在の画面状態に応じて適切なハンドラを呼び出します。
pub fn handle_key_event(app: &mut App, key: KeyEvent) {
    match &app.state {
        AppState::Loading { .. } => {
            // ローディング中でもCtrl+C/Escでキャンセル可能
            if is_cancel_key(&key) {
                app.quit();
            }
        }

        AppState::Success { .. } | AppState::Error { .. } => {
            // 任意のキーで終了
            app.quit();
        }

        AppState::TextInput { .. } => {
            handle_text_input_key(app, key);
        }

        AppState::SelectList { .. } => {
            handle_select_list_key(app, key);
        }

        AppState::Confirm { .. } => {
            handle_confirm_key(app, key);
        }

        AppState::Progress { .. } => {
            // 進捗表示中でもCtrl+C/Escでキャンセル可能
            if is_cancel_key(&key) {
                app.quit();
            }
        }
    }
}

/// テキスト入力のキーハンドリング
fn handle_text_input_key(app: &mut App, key: KeyEvent) {
    // Ctrl+C / Escapeキーは常にキャンセル
    if is_cancel_key(&key) {
        app.quit();
        return;
    }

    // Enterキーは状態によって処理が異なるため、呼び出し元で処理
    if key.code == KeyCode::Enter {
        return;
    }

    // Tabキーはモード切替のため、呼び出し元で処理
    if key.code == KeyCode::Tab {
        return;
    }

    if let AppState::TextInput { input, .. } = &mut app.state {
        match (key.modifiers, key.code) {
            // 全削除(Ctrl+U / Cmd+Backspace)
            (KeyModifiers::CONTROL, KeyCode::Char('u')) => {
                input.clear();
            }

            // 単語削除(Ctrl+W / Alt+Backspace)
            (KeyModifiers::CONTROL, KeyCode::Char('w'))
            | (KeyModifiers::ALT, KeyCode::Backspace) => {
                input.delete_word_backward();
            }

            // 削除
            (_, KeyCode::Backspace) => {
                input.delete_backward();
            }
            (_, KeyCode::Delete) => {
                input.delete_forward();
            }

            // カーソル移動
            (_, KeyCode::Left) | (KeyModifiers::CONTROL, KeyCode::Char('b')) => {
                input.move_left();
            }
            (_, KeyCode::Right) | (KeyModifiers::CONTROL, KeyCode::Char('f')) => {
                input.move_right();
            }
            (KeyModifiers::CONTROL, KeyCode::Char('a')) | (_, KeyCode::Home) => {
                input.move_start();
            }
            (KeyModifiers::CONTROL, KeyCode::Char('e')) | (_, KeyCode::End) => {
                input.move_end();
            }

            // 文字入力
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(c)) => {
                input.insert(c);
            }

            _ => {}
        }
    }

    // バリデーションとプレビュー更新
    update_text_input_validation(app);
}

/// テキスト入力のバリデーションとプレビューを更新
pub fn update_text_input_validation(app: &mut App) {
    if let AppState::TextInput {
        input,
        validation_error,
        preview,
        ..
    } = &mut app.state
    {
        let value = input.value.trim();

        // バリデーション
        *validation_error = validate_branch_name(value);

        // プレビュー生成
        *preview = if value.is_empty() || validation_error.is_some() {
            None
        } else {
            generate_worktree_preview(value, &app.config)
        };
    }
}

/// 選択リストのキーハンドリング
fn handle_select_list_key(app: &mut App, key: KeyEvent) {
    // Ctrl+C / Escapeキーは常にキャンセル
    if is_cancel_key(&key) {
        app.quit();
        return;
    }

    // Enterキーは選択確定のため、呼び出し元で処理
    if key.code == KeyCode::Enter {
        return;
    }

    let mut needs_preview_update = false;

    if let AppState::SelectList { input, state, .. } = &mut app.state {
        match (key.modifiers, key.code) {
            // 上移動
            (_, KeyCode::Up) | (KeyModifiers::CONTROL, KeyCode::Char('p')) => {
                state.move_up();
                needs_preview_update = true;
            }

            // 下移動
            (_, KeyCode::Down) | (KeyModifiers::CONTROL, KeyCode::Char('n')) => {
                state.move_down();
                needs_preview_update = true;
            }

            // 全削除(Ctrl+U)
            (KeyModifiers::CONTROL, KeyCode::Char('u')) => {
                input.clear();
                state.update_filter(&input.value);
                needs_preview_update = true;
            }

            // 単語削除(Ctrl+W / Alt+Backspace)
            (KeyModifiers::CONTROL, KeyCode::Char('w'))
            | (KeyModifiers::ALT, KeyCode::Backspace) => {
                input.delete_word_backward();
                state.update_filter(&input.value);
                needs_preview_update = true;
            }

            // 削除
            (_, KeyCode::Backspace) => {
                input.delete_backward();
                state.update_filter(&input.value);
                needs_preview_update = true;
            }
            (_, KeyCode::Delete) => {
                input.delete_forward();
                state.update_filter(&input.value);
                needs_preview_update = true;
            }

            // カーソル移動
            (_, KeyCode::Left) | (KeyModifiers::CONTROL, KeyCode::Char('b')) => {
                input.move_left();
            }
            (_, KeyCode::Right) | (KeyModifiers::CONTROL, KeyCode::Char('f')) => {
                input.move_right();
            }
            (KeyModifiers::CONTROL, KeyCode::Char('a')) | (_, KeyCode::Home) => {
                input.move_start();
            }
            (KeyModifiers::CONTROL, KeyCode::Char('e')) | (_, KeyCode::End) => {
                input.move_end();
            }

            // 文字入力
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(c)) => {
                input.insert(c);
                state.update_filter(&input.value);
                needs_preview_update = true;
            }

            _ => {}
        }
    }

    // プレビューを更新
    if needs_preview_update {
        update_select_list_preview(app);
    }
}

/// 選択リストのプレビューを更新
pub fn update_select_list_preview(app: &mut App) {
    if let AppState::SelectList { state, preview, .. } = &mut app.state {
        *preview = state
            .selected_item()
            .and_then(|item| generate_worktree_preview(&item.value, &app.config));
    }
}

/// 確認ダイアログのキーハンドリング
fn handle_confirm_key(app: &mut App, key: KeyEvent) {
    // Ctrl+Cは即座に終了
    if matches!(
        (key.modifiers, key.code),
        (KeyModifiers::CONTROL, KeyCode::Char('c'))
    ) {
        app.quit();
        return;
    }

    if let AppState::Confirm { selected, .. } = &mut app.state {
        // Ctrl+N/Ctrl+P で選択肢を移動
        if key.modifiers.contains(KeyModifiers::CONTROL) {
            match key.code {
                KeyCode::Char('n') => {
                    *selected = selected.next();
                }
                KeyCode::Char('p') => {
                    *selected = selected.prev();
                }
                _ => {}
            }
            return;
        }

        match key.code {
            KeyCode::Esc => {
                *selected = ConfirmChoice::SkipHooks;
                // Enterで確定されるまで待つ
            }
            KeyCode::Enter => {
                // 選択確定は呼び出し元で処理
            }
            KeyCode::Left | KeyCode::Up => {
                *selected = selected.prev();
            }
            KeyCode::Right | KeyCode::Down | KeyCode::Tab => {
                *selected = selected.next();
            }
            KeyCode::Char('t') | KeyCode::Char('T') => {
                *selected = ConfirmChoice::Trust;
            }
            KeyCode::Char('o') | KeyCode::Char('O') => {
                *selected = ConfirmChoice::Once;
            }
            KeyCode::Char('c') | KeyCode::Char('C') => {
                *selected = ConfirmChoice::SkipHooks;
            }
            _ => {}
        }
    }
}

/// 選択リストから現在選択されているアイテムを取得
pub fn get_selected_item(app: &App) -> Option<&super::app::SelectItem> {
    if let AppState::SelectList { state, .. } = &app.state {
        return state.selected_item();
    }
    None
}

/// テキスト入力から現在の値を取得
pub fn get_input_value(app: &App) -> Option<String> {
    if let AppState::TextInput { input, .. } = &app.state {
        let value = input.value.trim().to_string();
        if !value.is_empty() {
            return Some(value);
        }
    }
    None
}

/// テキスト入力のバリデーションエラーを取得
pub fn get_validation_error(app: &App) -> Option<&str> {
    if let AppState::TextInput {
        validation_error, ..
    } = &app.state
    {
        return validation_error.as_deref();
    }
    None
}

/// 確認ダイアログの選択を取得
pub fn get_confirm_choice(app: &App) -> Option<ConfirmChoice> {
    if let AppState::Confirm { selected, .. } = &app.state {
        return Some(*selected);
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::ui::app::SelectItem;

    fn create_test_app() -> App {
        App::new(Config::default())
    }

    #[test]
    fn test_handle_text_input_escape() {
        let mut app = create_test_app();
        app.set_text_input("Test", "Enter text...");

        let key = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        handle_key_event(&mut app, key);

        assert!(app.should_quit);
    }

    #[test]
    fn test_handle_text_input_character() {
        let mut app = create_test_app();
        app.set_text_input("Test", "Enter text...");

        let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE);
        handle_key_event(&mut app, key);

        if let AppState::TextInput { input, .. } = &app.state {
            assert_eq!(input.value, "a");
        } else {
            panic!("Expected TextInput state");
        }
    }

    #[test]
    fn test_handle_select_list_navigation() {
        let mut app = create_test_app();
        let items = vec![
            SelectItem {
                label: "Item 1".to_string(),
                value: "item1".to_string(),
                description: None,
                metadata: None,
            },
            SelectItem {
                label: "Item 2".to_string(),
                value: "item2".to_string(),
                description: None,
                metadata: None,
            },
        ];
        app.set_select_list("Test", "Search...", items);

        // 下に移動
        let key = KeyEvent::new(KeyCode::Down, KeyModifiers::NONE);
        handle_key_event(&mut app, key);

        if let AppState::SelectList { state, .. } = &app.state {
            assert_eq!(state.cursor_index, 1);
        } else {
            panic!("Expected SelectList state");
        }
    }
}