o7 0.1.1

O7 workflow DSL runner
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Q&A Panel Rendering — ratatui-based UI for interactive question handling.
//!
//! Draws the question panel with tabs, per-question widgets, preview,
//! review panel, and waiting spinner.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap};

use super::app::{App, QAState, SPINNER_FRAMES};
use super::qa_protocol::{AnswerValue, PreviewBlock, Question, QuestionType};

use std::collections::HashMap;

/// Draw the question panel in the right portion of the body area.
pub fn draw_question_panel(frame: &mut Frame, app: &App, area: Rect) {
    if let Some(ref qout) = app.qa_state.current_qout {
        // Get the current question's preview (per-question, not panel-level).
        let current_preview = if !app.qa_state.show_review {
            qout.questions
                .get(app.qa_state.selected_tab)
                .and_then(|q| q.preview.as_ref())
        } else {
            None
        };
        let has_preview = current_preview.is_some();

        // Build layout constraints dynamically based on whether preview exists.
        let constraints = if has_preview {
            vec![
                Constraint::Length(6), // Preview block
                Constraint::Length(2), // Tab bar
                Constraint::Min(5),    // Question widget or review panel
                Constraint::Min(2),    // Footer hints
            ]
        } else {
            vec![
                Constraint::Length(2), // Tab bar
                Constraint::Min(5),    // Question widget or review panel
                Constraint::Min(2),    // Footer hints
            ]
        };

        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints(constraints)
            .split(area);

        let (preview_area, tab_area, widget_area, hint_area) = if has_preview {
            (Some(chunks[0]), chunks[1], chunks[2], chunks[3])
        } else {
            (None, chunks[0], chunks[1], chunks[2])
        };

        // Draw preview if the current question has one.
        if let (Some(preview_area), Some(preview)) = (preview_area, current_preview) {
            draw_preview(frame, preview, preview_area);
        }

        // Draw tab bar.
        draw_question_tabs(
            frame,
            &qout.questions,
            app.qa_state.selected_tab,
            app.qa_state.show_review,
            &app.qa_state.pending_answers,
            tab_area,
        );

        // Draw either review panel or question widget.
        if app.qa_state.show_review {
            draw_review_panel(
                frame,
                &qout.questions,
                &app.qa_state.pending_answers,
                widget_area,
            );
        } else if let Some(question) = qout.questions.get(app.qa_state.selected_tab) {
            draw_question_widget(frame, question, &app.qa_state, widget_area);
        }

        // Draw Q&A-specific footer hints.
        draw_qa_hints(frame, &app.qa_state, hint_area);
    } else if app.qa_state.waiting {
        draw_waiting_spinner(frame, app.spinner_frame, area);
    } else {
        // No Q&A state — draw an empty panel.
        let block = Block::default()
            .title(" Q&A ")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::DarkGray));
        frame.render_widget(block, area);
    }
}

/// Draw the preview block (markdown/ascii content).
fn draw_preview(frame: &mut Frame, preview: &PreviewBlock, area: Rect) {
    let block = Block::default()
        .title(" Preview ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::DarkGray));

    let paragraph = Paragraph::new(preview.content.as_str())
        .block(block)
        .style(Style::default().fg(Color::White))
        .wrap(Wrap { trim: false });
    frame.render_widget(paragraph, area);
}

/// Draw the tab bar showing question numbers and a Review tab.
fn draw_question_tabs(
    frame: &mut Frame,
    questions: &[Question],
    selected_tab: usize,
    show_review: bool,
    answers: &HashMap<String, AnswerValue>,
    area: Rect,
) {
    let mut spans = Vec::new();
    spans.push(Span::styled(" ", Style::default()));

    for (i, question) in questions.iter().enumerate() {
        let is_selected = !show_review && i == selected_tab;
        let is_answered = answers.contains_key(&question.id);

        let label = format!(" {} ", i + 1);
        let style = if is_selected {
            Style::default()
                .fg(Color::Black)
                .bg(Color::Cyan)
                .add_modifier(Modifier::BOLD)
        } else if is_answered {
            Style::default().fg(Color::Green)
        } else {
            Style::default().fg(Color::DarkGray)
        };

        spans.push(Span::styled(label, style));
        spans.push(Span::raw(" "));
    }

    // Review tab.
    let review_style = if show_review {
        Style::default()
            .fg(Color::Black)
            .bg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    spans.push(Span::styled(" Review ", review_style));

    let line = Line::from(spans);
    let paragraph = Paragraph::new(line);
    frame.render_widget(paragraph, area);
}

/// Draw the widget for a single question based on its type.
fn draw_question_widget(frame: &mut Frame, question: &Question, qa_state: &QAState, area: Rect) {
    let block = Block::default()
        .title(format!(" {} ", question.prompt))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    match question.question_type {
        QuestionType::ChooseOne => {
            draw_choose_one(frame, question, qa_state, inner);
        }
        QuestionType::ChooseMany => {
            draw_choose_many(frame, question, qa_state, inner);
        }
        QuestionType::FreeWrite => {
            draw_free_write(frame, qa_state, inner);
        }
        QuestionType::YesNo => {
            draw_yes_no(frame, qa_state, inner);
        }
    }
}

/// Draw choose-one options with a cursor indicator.
fn draw_choose_one(frame: &mut Frame, question: &Question, qa_state: &QAState, area: Rect) {
    let options = match &question.options {
        Some(opts) => opts,
        None => return,
    };

    let current_answer = qa_state.pending_answers.get(&question.id);

    let items: Vec<ListItem> = options
        .iter()
        .enumerate()
        .map(|(i, opt)| {
            let is_cursor = i == qa_state.widget_cursor;
            let is_answered = match current_answer {
                Some(AnswerValue::Text(t)) => t == opt,
                _ => false,
            };

            let prefix = if is_cursor { "> " } else { "  " };
            let suffix = if is_answered { " [selected]" } else { "" };

            let style = if is_cursor {
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else if is_answered {
                Style::default().fg(Color::Green)
            } else {
                Style::default().fg(Color::Gray)
            };

            ListItem::new(Line::from(Span::styled(
                format!("{}{}{}", prefix, opt, suffix),
                style,
            )))
        })
        .collect();

    let list = List::new(items);
    frame.render_widget(list, area);
}

/// Draw choose-many options with checkbox indicators.
fn draw_choose_many(frame: &mut Frame, question: &Question, qa_state: &QAState, area: Rect) {
    let options = match &question.options {
        Some(opts) => opts,
        None => return,
    };

    let items: Vec<ListItem> = options
        .iter()
        .enumerate()
        .map(|(i, opt)| {
            let is_cursor = i == qa_state.widget_cursor;
            let is_toggled = qa_state.toggled.contains(&i);

            let checkbox = if is_toggled { "[x]" } else { "[ ]" };
            let prefix = if is_cursor { "> " } else { "  " };

            let style = if is_cursor {
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else if is_toggled {
                Style::default().fg(Color::Green)
            } else {
                Style::default().fg(Color::Gray)
            };

            ListItem::new(Line::from(Span::styled(
                format!("{}{} {}", prefix, checkbox, opt),
                style,
            )))
        })
        .collect();

    let list = List::new(items);
    frame.render_widget(list, area);
}

/// Draw free-write text input with cursor at the tracked position.
fn draw_free_write(frame: &mut Frame, qa_state: &QAState, area: Rect) {
    if qa_state.text_buffer.is_empty() {
        let paragraph = Paragraph::new(Span::styled(
            "> Type your answer...",
            Style::default().fg(Color::DarkGray),
        ))
        .wrap(Wrap { trim: false });
        frame.render_widget(paragraph, area);
        return;
    }

    // Collect chars so we can split at cursor position safely.
    let chars: Vec<char> = qa_state.text_buffer.chars().collect();
    let cursor = qa_state.text_cursor.min(chars.len());

    let before: String = chars[..cursor].iter().collect();
    let after: String = chars[cursor..].iter().collect();

    // Show the pipe cursor inline: "> before|after"
    let display = format!("> {}|{}", before, after);
    let paragraph = Paragraph::new(display)
        .style(Style::default().fg(Color::White))
        .wrap(Wrap { trim: false });
    frame.render_widget(paragraph, area);
}

/// Draw yes/no toggle.
fn draw_yes_no(frame: &mut Frame, qa_state: &QAState, area: Rect) {
    let yes_style = if qa_state.widget_cursor == 0 {
        Style::default()
            .fg(Color::White)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Gray)
    };

    let no_style = if qa_state.widget_cursor == 1 {
        Style::default()
            .fg(Color::White)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Gray)
    };

    let yes_prefix = if qa_state.widget_cursor == 0 {
        "> "
    } else {
        "  "
    };
    let no_prefix = if qa_state.widget_cursor == 1 {
        "> "
    } else {
        "  "
    };

    let items = vec![
        ListItem::new(Line::from(Span::styled(
            format!("{}[Y] Yes", yes_prefix),
            yes_style,
        ))),
        ListItem::new(Line::from(Span::styled(
            format!("{}[N] No", no_prefix),
            no_style,
        ))),
    ];

    let list = List::new(items);
    frame.render_widget(list, area);
}

/// Draw the review panel showing all answers.
fn draw_review_panel(
    frame: &mut Frame,
    questions: &[Question],
    answers: &HashMap<String, AnswerValue>,
    area: Rect,
) {
    let block = Block::default()
        .title(" Review Answers ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Yellow));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    let mut lines = Vec::new();

    for (i, question) in questions.iter().enumerate() {
        let prompt_line = Line::from(vec![
            Span::styled(
                format!("{}. ", i + 1),
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(&question.prompt, Style::default().fg(Color::White)),
        ]);
        lines.push(prompt_line);

        let answer_text = match answers.get(&question.id) {
            Some(AnswerValue::Text(t)) => format!("   -> {}", t),
            Some(AnswerValue::Boolean(b)) => {
                format!("   -> {}", if *b { "Yes" } else { "No" })
            }
            Some(AnswerValue::MultiSelect(items)) => {
                format!("   -> {}", items.join(", "))
            }
            None => "   -> (unanswered)".to_string(),
        };

        let answer_style = if answers.contains_key(&question.id) {
            Style::default().fg(Color::Green)
        } else {
            Style::default().fg(Color::Red)
        };

        lines.push(Line::from(Span::styled(answer_text, answer_style)));
        lines.push(Line::from(""));
    }

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(paragraph, inner);
}

/// Draw the waiting spinner when no questions are active.
fn draw_waiting_spinner(frame: &mut Frame, spinner_frame: usize, area: Rect) {
    let block = Block::default()
        .title(" Q&A ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::DarkGray));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    let spinner = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];
    let line = Line::from(vec![
        Span::styled(
            format!("  {} ", spinner),
            Style::default().fg(Color::Yellow),
        ),
        Span::styled(
            "Waiting for questions...",
            Style::default().fg(Color::DarkGray),
        ),
    ]);

    let paragraph = Paragraph::new(line);
    frame.render_widget(paragraph, inner);
}

/// Draw Q&A-specific footer hints.
fn draw_qa_hints(frame: &mut Frame, qa_state: &QAState, area: Rect) {
    let hints = if qa_state.show_review {
        vec![
            ("Enter", "Submit"),
            ("e/Backspace", "Back to edit"),
            ("Left/Right", "Navigate"),
            ("Esc", "Close"),
        ]
    } else {
        let qtype = qa_state
            .current_qout
            .as_ref()
            .and_then(|q| q.questions.get(qa_state.selected_tab))
            .map(|q| &q.question_type);

        match qtype {
            Some(QuestionType::ChooseOne) => {
                vec![
                    ("Up/Down", "Navigate"),
                    ("Enter", "Select"),
                    ("Left/Right", "Tab"),
                    ("Esc", "Close"),
                ]
            }
            Some(QuestionType::ChooseMany) => {
                vec![
                    ("Up/Down", "Navigate"),
                    ("Space", "Toggle"),
                    ("Enter", "Confirm"),
                    ("Left/Right", "Tab"),
                    ("Esc", "Close"),
                ]
            }
            Some(QuestionType::FreeWrite) => {
                vec![
                    ("^←/^→", "Word"),
                    ("S+Enter", "Newline"),
                    ("Enter", "Confirm"),
                    ("Tab/S+Tab", "Switch tab"),
                    ("Esc", "Close"),
                ]
            }
            Some(QuestionType::YesNo) => {
                vec![
                    ("Y/N", "Select"),
                    ("Enter", "Confirm"),
                    ("Left/Right", "Tab"),
                    ("Esc", "Close"),
                ]
            }
            None => vec![("Esc", "Close")],
        }
    };

    let footer = Paragraph::new(render_hint_line(&hints)).wrap(Wrap { trim: false });
    frame.render_widget(footer, area);
}

fn render_hint_line(hints: &[(&str, &str)]) -> Line<'static> {
    let mut spans = Vec::new();
    for (idx, (key, label)) in hints.iter().enumerate() {
        if idx > 0 {
            spans.push(Span::styled("  |  ", Style::default().fg(Color::DarkGray)));
        }
        spans.push(Span::styled(
            key.to_string(),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::raw(": "));
        spans.push(Span::styled(
            label.to_string(),
            Style::default().fg(Color::Gray),
        ));
    }
    Line::from(spans)
}