roam-sdk 0.4.0

Roam Research SDK and terminal UI client
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use crate::api::types::Block;
use crate::edit_buffer::EditBuffer;
use crate::export;
use crate::keys::preset::Action;
use crate::markdown;

use super::blocks::{
    find_block_in_days, find_block_index_by_uid, generate_uid, insert_block_in_days,
    resolve_block_at_index, set_block_open,
};
use super::nav::{
    navigate_to_page, push_nav_snapshot, restore_nav_snapshot, save_nav_snapshot_at_index,
};
use super::search::{filter_blocks, SEARCH_LIMIT};
use super::search::{filter_page_titles, QUICK_SWITCHER_LIMIT};
use super::state::{
    count_blocks_recursive, AppState, CreateInfo, InputMode, LinkPickerState, LinkedRefItem,
    LoadRequest, QuickSwitcherState, SearchState, Selection, ViewMode, ViewSnapshot,
};

pub fn handle_action(state: &mut AppState, action: &Action) -> Option<LoadRequest> {
    match action {
        Action::Quit => {
            state.should_quit = true;
            None
        }
        Action::MoveUp => {
            if state.selected_block > 0 {
                state.selected_block -= 1;
                state.selection = Selection::Single(state.selected_block);
                state.cursor_col = 0;
            }
            None
        }
        Action::MoveDown => {
            let total = state.total_navigable_count();
            if total == 0 {
                return None;
            }
            let flat = state.flat_block_count();

            // In daily notes: trigger load-more when crossing from regular blocks
            // into linked refs zone (at the boundary)
            let load_request = if flat > 0
                && state.selected_block == flat - 1
                && !state.loading_more
                && state.view_mode == ViewMode::DailyNotes
            {
                let oldest = state
                    .days
                    .last()
                    .map(|d| d.date)
                    .unwrap_or(state.current_date);
                let prev_date = oldest - chrono::Duration::days(1);
                state.loading_more = true;
                Some(LoadRequest::DailyNote(prev_date))
            } else {
                None
            };

            // Navigate down regardless
            if state.selected_block < total - 1 {
                state.selected_block += 1;
                state.selection = Selection::Single(state.selected_block);
                state.cursor_col = 0;
            }

            load_request
        }
        Action::EditBlock => {
            // Guard: no editing in linked refs zone
            if state
                .resolve_linked_ref_item(state.selected_block)
                .is_some()
            {
                return None;
            }
            if let Some(info) =
                resolve_block_at_index(&state.days, &state.linked_refs, state.selected_block)
            {
                state.input_mode = InputMode::Insert {
                    buffer: EditBuffer::new(&info.text),
                    block_uid: info.block_uid,
                    original_text: info.text,
                    create_info: None,
                };
            }
            None
        }
        Action::CreateBlock => {
            // Guard: no creating in linked refs zone
            if state
                .resolve_linked_ref_item(state.selected_block)
                .is_some()
            {
                return None;
            }
            if let Some(info) =
                resolve_block_at_index(&state.days, &state.linked_refs, state.selected_block)
            {
                let new_uid = generate_uid();
                let order = info.order + 1;
                let parent_uid = info.parent_uid.clone();
                let placeholder = Block {
                    uid: new_uid.clone(),
                    string: String::new(),
                    order,
                    children: vec![],
                    open: true,
                    refs: vec![],
                };
                insert_block_in_days(&mut state.days, &parent_uid, order, placeholder);
                if let Some(idx) =
                    find_block_index_by_uid(&state.days, &state.linked_refs, &new_uid)
                {
                    state.selected_block = idx;
                    state.cursor_col = 0;
                }
                state.input_mode = InputMode::Insert {
                    buffer: EditBuffer::new_empty(),
                    block_uid: new_uid,
                    original_text: String::new(),
                    create_info: Some(CreateInfo { parent_uid, order }),
                };
            } else if let Some(day) = state.days.first() {
                // No blocks yet — create the first block as child of the day page
                let new_uid = generate_uid();
                let parent_uid = day.uid.clone();
                let placeholder = Block {
                    uid: new_uid.clone(),
                    string: String::new(),
                    order: 0,
                    children: vec![],
                    open: true,
                    refs: vec![],
                };
                state.days[0].blocks.push(placeholder);
                state.selected_block = 0;
                state.cursor_col = 0;
                state.input_mode = InputMode::Insert {
                    buffer: EditBuffer::new_empty(),
                    block_uid: new_uid,
                    original_text: String::new(),
                    create_info: Some(CreateInfo {
                        parent_uid,
                        order: 0,
                    }),
                };
            }
            None
        }
        Action::Search => {
            state.search = Some(SearchState {
                query: String::new(),
                results: filter_blocks(&state.days, &state.block_ref_cache, "", SEARCH_LIMIT),
                selected: 0,
            });
            None
        }
        Action::Collapse => {
            if state
                .resolve_linked_ref_item(state.selected_block)
                .is_some()
            {
                return None;
            }
            if let Some(info) =
                resolve_block_at_index(&state.days, &state.linked_refs, state.selected_block)
            {
                set_block_open(&mut state.days, &info.block_uid, false);
            }
            None
        }
        Action::Expand => {
            if state
                .resolve_linked_ref_item(state.selected_block)
                .is_some()
            {
                return None;
            }
            if let Some(info) =
                resolve_block_at_index(&state.days, &state.linked_refs, state.selected_block)
            {
                set_block_open(&mut state.days, &info.block_uid, true);
            }
            None
        }
        Action::Enter => {
            // Check if we're in the linked refs zone
            if let Some(item) = state.resolve_linked_ref_item(state.selected_block) {
                match item {
                    LinkedRefItem::SectionHeader => {
                        if let Some(day_title) = state.linked_ref_day_at(state.selected_block) {
                            if let Some(lr) = state.linked_refs.get_mut(&day_title) {
                                lr.collapsed = !lr.collapsed;
                            }
                        }
                    }
                    LinkedRefItem::GroupHeader(title) => {
                        return Some(navigate_to_page(state, title));
                    }
                    LinkedRefItem::Block(block) => {
                        return Some(navigate_to_page(state, block.page_title));
                    }
                }
                return None;
            }
            if let Some(info) =
                resolve_block_at_index(&state.days, &state.linked_refs, state.selected_block)
            {
                let links = markdown::extract_page_links(&info.text);
                match links.len() {
                    0 => {
                        // No links — toggle collapse (original behavior)
                        if let Some(block) = find_block_in_days(&state.days, &info.block_uid) {
                            set_block_open(&mut state.days, &info.block_uid, !block.open);
                        }
                    }
                    1 => {
                        // Single link — navigate directly
                        let title = links.into_iter().next().unwrap();
                        return Some(navigate_to_page(state, title));
                    }
                    _ => {
                        // Multiple links — open picker
                        state.link_picker = Some(LinkPickerState { links, selected: 0 });
                    }
                }
            }
            None
        }
        Action::NextDay => {
            if state.view_mode != ViewMode::DailyNotes {
                return None;
            }
            // Jump to the first block of the next (more recent) day
            if state.days.len() > 1 {
                let mut block_count = 0;
                for (i, day) in state.days.iter().enumerate() {
                    let day_blocks = count_blocks_recursive(&day.blocks);
                    if state.selected_block < block_count + day_blocks && i > 0 {
                        // Currently in this day, jump to previous day (more recent)
                        state.selected_block = block_count
                            .saturating_sub(count_blocks_recursive(&state.days[i - 1].blocks));
                        state.cursor_col = 0;
                        break;
                    }
                    block_count += day_blocks;
                }
            }
            None
        }
        Action::PrevDay => {
            if state.view_mode != ViewMode::DailyNotes {
                return None;
            }
            // Jump to first block of the next older day, or load it
            let mut block_count = 0;
            let mut found = false;
            for (i, day) in state.days.iter().enumerate() {
                let day_blocks = count_blocks_recursive(&day.blocks);
                if state.selected_block < block_count + day_blocks {
                    // Currently in day i, jump to day i+1 if exists
                    if i + 1 < state.days.len() {
                        state.selected_block = block_count + day_blocks;
                        state.cursor_col = 0;
                        found = true;
                    }
                    break;
                }
                block_count += day_blocks;
            }
            if !found && !state.loading_more {
                // Load older day
                let oldest = state
                    .days
                    .last()
                    .map(|d| d.date)
                    .unwrap_or(state.current_date);
                let prev_date = oldest - chrono::Duration::days(1);
                state.loading_more = true;
                return Some(LoadRequest::DailyNote(prev_date));
            }
            None
        }
        Action::GoDaily => {
            if state.view_mode != ViewMode::DailyNotes {
                // In page view — save to history, return to daily notes
                push_nav_snapshot(state);
                state.view_mode = ViewMode::DailyNotes;
                state.days.clear();
                state.selected_block = 0;
                state.cursor_col = 0;
                state.loading = true;
                state.linked_refs.clear();
                state.status_message = Some("Loading today's notes...".into());
                return Some(LoadRequest::DailyNote(state.current_date));
            }
            // Already in daily notes — jump to first block of today
            state.selected_block = 0;
            state.cursor_col = 0;
            if state.days.first().map(|d| d.date) != Some(state.current_date) {
                return Some(LoadRequest::DailyNote(state.current_date));
            }
            None
        }
        Action::Help => {
            state.show_help = !state.show_help;
            None
        }
        Action::Exit => {
            // Close any overlay, or do nothing
            if state.show_help {
                state.show_help = false;
            }
            None
        }
        Action::CursorLeft => {
            if state.cursor_col > 0 {
                state.cursor_col -= 1;
            }
            None
        }
        Action::CursorRight => {
            if let Some(info) =
                resolve_block_at_index(&state.days, &state.linked_refs, state.selected_block)
            {
                let first_line = info.text.split('\n').next().unwrap_or("");
                let rendered_len = markdown::rendered_char_count(first_line);
                if rendered_len > 0 && state.cursor_col < rendered_len - 1 {
                    state.cursor_col += 1;
                }
            }
            None
        }
        Action::NavBack => {
            if state.can_nav_back() {
                // Save current view: push if at end, or update in place
                if state.nav_index == state.nav_history.len() {
                    state.nav_history.push(ViewSnapshot {
                        view_mode: state.view_mode.clone(),
                        days: state.days.clone(),
                        selected_block: state.selected_block,
                    });
                } else {
                    save_nav_snapshot_at_index(state);
                }
                state.nav_index -= 1;
                restore_nav_snapshot(state);
            }
            None
        }
        Action::NavForward => {
            if state.can_nav_forward() {
                save_nav_snapshot_at_index(state);
                state.nav_index += 1;
                restore_nav_snapshot(state);
            }
            None
        }
        Action::QuickSwitcher => {
            let filtered = if !state.page_title_cache.is_empty() {
                filter_page_titles(&state.page_title_cache, "", QUICK_SWITCHER_LIMIT)
            } else {
                Vec::new()
            };
            state.quick_switcher = Some(QuickSwitcherState {
                query: String::new(),
                filtered,
                selected: 0,
                debounce_ticks: 0,
                fetching: false,
            });
            None
        }
        Action::SelectUp => {
            if state.selected_block > 0 {
                let anchor = match &state.selection {
                    Selection::Single(i) => *i,
                    Selection::Range { anchor, .. } => *anchor,
                };
                state.selected_block -= 1;
                state.selection = Selection::Range {
                    anchor,
                    head: state.selected_block,
                };
                state.cursor_col = 0;
            }
            None
        }
        Action::SelectDown => {
            let total = state.total_navigable_count();
            if total > 0 && state.selected_block < total - 1 {
                let anchor = match &state.selection {
                    Selection::Single(i) => *i,
                    Selection::Range { anchor, .. } => *anchor,
                };
                state.selected_block += 1;
                state.selection = Selection::Range {
                    anchor,
                    head: state.selected_block,
                };
                state.cursor_col = 0;
            }
            None
        }
        Action::Export => {
            let title = match &state.view_mode {
                ViewMode::DailyNotes => "daily-notes".to_string(),
                ViewMode::Page { title } => title.clone(),
            };

            let content = match &state.view_mode {
                ViewMode::DailyNotes => export::daily_notes_to_markdown(&state.days),
                ViewMode::Page { title } => {
                    if let Some(day) = state.days.first() {
                        export::blocks_to_markdown(title, &day.blocks)
                    } else {
                        String::new()
                    }
                }
            };

            let export_dir = directories::UserDirs::new()
                .map(|d| d.home_dir().to_path_buf())
                .unwrap_or_default()
                .join("roam-export");
            let _ = std::fs::create_dir_all(&export_dir);
            let safe_title = title
                .chars()
                .map(|c| {
                    if c.is_alphanumeric() || c == '-' || c == '_' {
                        c
                    } else {
                        '_'
                    }
                })
                .collect::<String>();
            let filename = format!("{}.md", safe_title);
            let path = export_dir.join(&filename);

            match std::fs::write(&path, &content) {
                Ok(_) => {
                    state.status_message = Some(format!("Exported to {}", path.display()));
                }
                Err(e) => {
                    state.status_message = Some(format!("Export failed: {}", e));
                }
            }
            None
        }
        _ => None,
    }
}