返回 CodeWhale
showcase.rs
根目录 / vendor / codewhale-ratatui / src / gallery / showcase.rs
1 //! An authored, interactive specimen of the public kit. All state is supplied
2 //! by a host; no provider, filesystem, execution or timer lives in this view.
3 use std::time::Duration;
4
5 use ratatui::{
6 buffer::Buffer,
7 layout::{Margin, Rect},
8 style::Modifier,
9 text::{Line, Span},
10 };
11
12 use super::Entry;
13 use crate::{
14 ApprovalCard, ApprovalChoice, ApprovalEffect, ApprovalKey, ApprovalKind, ApprovalScope,
15 ApprovalState, ApprovalSubject, ChoiceId, Depth, Diff, DiffGutter, DiffWrap, Form, FormField,
16 FormState, Habitat, HabitatDensity, HorizonRule, Message, MetricKind, MetricSegment,
17 MetricsLine, MotionMode, NativeComposer, NativeComposerDensity, OceanColumn, OceanPhase, Ombre,
18 OmbreDirection, Paint, PaneHeader, Picker, PickerItem, PickerMatches, PickerState, PostureBar,
19 Receipt, ReceiptValue, Role, Segmented, SegmentedState, SettingDetail, SettingRow, Spinner,
20 State, StatusMark, TerminalShell, TextInputState, Theme, Toggle, ToggleState, TuiGround,
21 TuiInk, TuiPalette, VerificationSpinner, WaterPalette, Whale, WhaleState, Workbar,
22 WorkbarAgent, WorkbarPanel, WorkbarRow, WorkbarState, WorkbarTab, WorkbarTone,
23 WorkflowProgress, WorkflowRun, WorkflowRunState, parse_unified,
24 testing::Profile,
25 text,
26 whale_motion::{Activity, ColoredGrid, Context, Inputs, Presence, Stage, colored_braille},
27 };
28
29 /// Rows for the standalone workbar gallery. The Work view uses
30 /// [`ShowcaseState::workbar`] for its phase-aware fixture.
31 #[must_use]
32 pub fn workbar_rows(panel: WorkbarPanel) -> Vec<crate::WorkbarRow> {
33 super::workbar::sample(panel).rows
34 }
35
36 /// The six destinations of the demonstration. The last exposes every
37 /// existing catalogue entry, rather than selecting a second component list.
38 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39 pub enum ShowcaseSection {
40 #[default]
41 Work,
42 Decisions,
43 Controls,
44 Color,
45 Life,
46 Components,
47 }
48 impl ShowcaseSection {
49 pub const ALL: [Self; 6] = [
50 Self::Work,
51 Self::Decisions,
52 Self::Controls,
53 Self::Color,
54 Self::Life,
55 Self::Components,
56 ];
57 pub const fn name(self) -> &'static str {
58 match self {
59 Self::Work => "Work",
60 Self::Decisions => "Decisions",
61 Self::Controls => "Controls",
62 Self::Color => "Color",
63 Self::Life => "Life",
64 Self::Components => "Components",
65 }
66 }
67 pub fn index(self) -> usize {
68 Self::ALL.iter().position(|v| *v == self).unwrap_or(0)
69 }
70 }
71
72 /// Explicit host-owned fixture phases. Advancing this never runs a command.
73 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74 pub enum ShowcasePhase {
75 #[default]
76 Working,
77 NeedsYou,
78 Verifying,
79 Done,
80 }
81 impl ShowcasePhase {
82 pub const fn word(self) -> &'static str {
83 match self {
84 Self::Working => "Working",
85 Self::NeedsYou => "Needs you",
86 Self::Verifying => "Verifying",
87 Self::Done => "Done",
88 }
89 }
90 pub const fn state(self) -> State {
91 match self {
92 Self::Working | Self::Verifying => State::Working,
93 Self::NeedsYou => State::NeedsYou,
94 Self::Done => State::Done,
95 }
96 }
97 pub const fn whale(self) -> WhaleState {
98 match self {
99 Self::Working => WhaleState::Write,
100 Self::NeedsYou => WhaleState::NeedsYou,
101 Self::Verifying => WhaleState::Run,
102 Self::Done => WhaleState::Done,
103 }
104 }
105 }
106
107 /// Native permission labels for the specimen. These never grant the gallery
108 /// host access to a command, provider or filesystem operation.
109 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110 pub enum ShowcasePermission {
111 #[default]
112 Ask,
113 AutoReview,
114 FullAccess,
115 }
116 impl ShowcasePermission {
117 pub const fn next(self) -> Self {
118 match self {
119 Self::Ask => Self::AutoReview,
120 Self::AutoReview => Self::FullAccess,
121 Self::FullAccess => Self::Ask,
122 }
123 }
124 pub const fn word(self) -> &'static str {
125 match self {
126 Self::Ask => "ask",
127 Self::AutoReview => "auto-review",
128 Self::FullAccess => "full access",
129 }
130 }
131 pub const fn ink(self) -> TuiInk {
132 match self {
133 Self::Ask => TuiInk::PermissionAsk,
134 Self::AutoReview => TuiInk::PermissionAutoReview,
135 Self::FullAccess => TuiInk::PermissionFullAccess,
136 }
137 }
138 }
139
140 /// State kept by the example host. Its clock is an elapsed Duration, supplied
141 /// to the renderer; the fields do not infer account, cost or execution state.
142 #[derive(Clone, Debug)]
143 pub struct ShowcaseState {
144 pub section: ShowcaseSection,
145 pub phase: ShowcasePhase,
146 pub phase_started: Duration,
147 pub palette: WaterPalette,
148 pub direction: OmbreDirection,
149 pub profile: Profile,
150 pub motion: MotionMode,
151 pub focus: usize,
152 pub editing: bool,
153 pub permission: ShowcasePermission,
154 pub queued: Vec<String>,
155 pub followups: Vec<String>,
156 pub details: ToggleState,
157 pub readouts: ToggleState,
158 pub draft: TextInputState,
159 pub form: FormState,
160 pub approval: ApprovalState,
161 pub approval_open: bool,
162 pub note: String,
163 pub action: usize,
164 pub action_playing: bool,
165 pub query: TextInputState,
166 pub picker: PickerState,
167 pub preview_scroll: u16,
168 pub dock: WorkbarState,
169 pub native_palette: TuiPalette,
170 }
171 impl Default for ShowcaseState {
172 fn default() -> Self {
173 Self::new()
174 }
175 }
176 impl ShowcaseState {
177 /// Resolve one palette for the character, surface and exported frame.
178 #[must_use]
179 pub fn theme_for(&self, input: &Theme) -> Theme {
180 let palette = if self.native_palette == TuiPalette::Underwater
181 && input.caps().appearance == crate::detect::Appearance::Light
182 {
183 TuiPalette::WhaleLight
184 } else {
185 self.native_palette
186 };
187 super::tui_palettes::theme_for(palette, input)
188 }
189
190 pub fn new() -> Self {
191 Self {
192 section: ShowcaseSection::Work,
193 phase: ShowcasePhase::Working,
194 phase_started: Duration::ZERO,
195 palette: WaterPalette::Ocean,
196 direction: OmbreDirection::Diagonal,
197 profile: Profile::DarkTrue,
198 motion: MotionMode::Full,
199 focus: 0,
200 editing: true,
201 permission: ShowcasePermission::Ask,
202 queued: Vec::new(),
203 followups: Vec::new(),
204 details: ToggleState::from(false),
205 readouts: ToggleState::from(true),
206 draft: TextInputState::with_text("Also preserve the search shortcut."),
207 form: FormState::new(vec![
208 FormField::text("Project")
209 .value("codewhale-ratatui")
210 .validate(project_name),
211 FormField::text("Result title")
212 .value("A quieter workspace")
213 .validate(project_name),
214 FormField::check("Keep the receipt", true),
215 FormField::read_only("Execution", "Preview"),
216 ]),
217 approval: approval_choices(),
218 approval_open: false,
219 note: "Choose a component to explore.".into(),
220 action: 0,
221 action_playing: false,
222 query: TextInputState::new(),
223 picker: PickerState::default(),
224 preview_scroll: 0,
225 dock: WorkbarState::default(),
226 native_palette: TuiPalette::Underwater,
227 }
228 }
229 pub fn set_phase(&mut self, phase: ShowcasePhase, elapsed: Duration) {
230 self.phase = phase;
231 self.phase_started = elapsed;
232 self.approval_open = phase == ShowcasePhase::NeedsYou;
233 if self.approval_open {
234 self.approval = approval_choices();
235 }
236 }
237 pub fn phase_elapsed(&self, elapsed: Duration) -> Duration {
238 elapsed.saturating_sub(self.phase_started)
239 }
240
241 /// The work view and its keyboard host consume the same phase-aware rows.
242 #[must_use]
243 pub fn workbar(&self) -> Workbar {
244 let mut dock = super::workbar::sample(self.dock.panel);
245 let done = self.phase == ShowcasePhase::Done;
246 let live = if done {
247 WorkbarTone::Success
248 } else {
249 WorkbarTone::Live
250 };
251 let mark = if done { "✓" } else { "●" };
252 dock.rows = match self.dock.panel {
253 WorkbarPanel::Tasks => vec![
254 WorkbarRow::new("session:selection", "Preserve session selection")
255 .mark("✓")
256 .tone(WorkbarTone::Success),
257 WorkbarRow::new("session:layout", "Refine the narrow layout")
258 .mark(mark)
259 .tone(live),
260 ],
261 WorkbarPanel::Fleet => vec![
262 WorkbarRow::new("worker:build", "Builder").mark(mark).agent(
263 WorkbarAgent::new(
264 "builder",
265 if done { "completed" } else { "running" },
266 "Keep the session list readable in compact windows",
267 )
268 .elapsed_seconds(6),
269 ),
270 WorkbarRow::new("worker:review", "Reviewer")
271 .mark("✓")
272 .agent(
273 WorkbarAgent::new(
274 "reviewer",
275 "completed",
276 "Check search and keyboard selection",
277 )
278 .elapsed_seconds(3),
279 ),
280 ],
281 WorkbarPanel::Terminal => vec![WorkbarRow::new(
282 "terminal:host",
283 "Terminal sessions are supplied by the host",
284 )],
285 WorkbarPanel::Jobs => vec![
286 WorkbarRow::new("shell:layout", "Check the compact session layout")
287 .mark(mark)
288 .tone(live),
289 ],
290 WorkbarPanel::Files => vec![
291 WorkbarRow::new("files:edited", "Edited 2")
292 .mark("▾")
293 .tone(WorkbarTone::Heading)
294 .selectable(false),
295 WorkbarRow::new("files:list", "src/components/native_views.rs")
296 .mark("✎")
297 .tone(WorkbarTone::Success)
298 .detail("+18 -8"),
299 WorkbarRow::new("files:gallery", "src/gallery/native_views.rs")
300 .mark("✎")
301 .tone(WorkbarTone::Success)
302 .detail("+6 -2"),
303 ],
304 WorkbarPanel::Notes => vec![
305 WorkbarRow::new("notes:1", "Keep search visible at every width")
306 .mark("▪")
307 .tone(WorkbarTone::Live),
308 WorkbarRow::new("notes:2", "Preserve selection while filtering")
309 .mark("▪")
310 .tone(WorkbarTone::Live),
311 ],
312 WorkbarPanel::Context => vec![
313 WorkbarRow::new("context:budget", "30.7k of 128k · 24% · compacts at 90%")
314 .mark("◔")
315 .tone(WorkbarTone::Live),
316 WorkbarRow::new("context:system", "system + tools · 8.4k")
317 .mark("·")
318 .selectable(false),
319 WorkbarRow::new("context:conversation", "conversation + output · 22.3k")
320 .mark("·")
321 .selectable(false),
322 WorkbarRow::new("context:compact", "compact now")
323 .mark("▸")
324 .tone(WorkbarTone::Live),
325 ],
326 WorkbarPanel::Git => vec![
327 WorkbarRow::new("git:branch", "session-layout · up to date")
328 .mark("⎇")
329 .tone(WorkbarTone::Live)
330 .detail("codewhale-ratatui"),
331 WorkbarRow::new("git:changes", "2 modified files")
332 .mark("±")
333 .tone(WorkbarTone::Live)
334 .detail("/diff"),
335 ],
336 WorkbarPanel::Cost => dock.rows,
337 };
338 if self.dock.panel == WorkbarPanel::Tasks {
339 dock.goal = Some("Make session navigation feel effortless".into());
340 dock.progress = Some(
341 if done {
342 "TODO · 2/2 · done"
343 } else {
344 "TODO · 1/2 · 1 left"
345 }
346 .into(),
347 );
348 }
349 dock.tabs = WorkbarPanel::ORDER
350 .into_iter()
351 .map(|panel| match panel {
352 WorkbarPanel::Tasks
353 | WorkbarPanel::Fleet
354 | WorkbarPanel::Files
355 | WorkbarPanel::Notes => WorkbarTab::new(panel).count(2),
356 WorkbarPanel::Jobs => WorkbarTab::new(panel).count(1),
357 _ => WorkbarTab::new(panel),
358 })
359 .collect();
360 self.dock.apply(dock)
361 }
362 pub fn active_motion(&self) -> bool {
363 self.motion == MotionMode::Full
364 && !self.approval_open
365 && match self.section {
366 ShowcaseSection::Work => matches!(
367 self.phase,
368 ShowcasePhase::Working | ShowcasePhase::Verifying
369 ),
370 ShowcaseSection::Decisions => self.phase == ShowcasePhase::Verifying,
371 ShowcaseSection::Life => self.action_playing,
372 _ => false,
373 }
374 }
375 pub fn catalogue(&self) -> (Vec<Entry>, Vec<PickerItem>, PickerMatches) {
376 let entries: Vec<_> = super::entries()
377 .into_iter()
378 .filter(|e| !e.name.starts_with("showcase-"))
379 .collect();
380 let items: Vec<_> = entries
381 .iter()
382 .map(|e| PickerItem::new(e.name).detail(format!("{} x {}", e.width, e.height)))
383 .collect();
384 let matches = PickerMatches::rank(&items, self.query.text(), None);
385 (entries, items, matches)
386 }
387 }
388 fn project_name(value: &str) -> Result<(), std::borrow::Cow<'static, str>> {
389 if value.trim().is_empty() {
390 Err("Give this example a name.".into())
391 } else {
392 Ok(())
393 }
394 }
395
396 /// Typed inputs for the explicitly labeled action study. These describe
397 /// authored specimen facts; they are never inferred from a command or log.
398 pub fn showcase_inputs(action: WhaleState, identity: &str) -> Inputs {
399 let (presence, kind) = match action {
400 WhaleState::Rest => (Presence::Idle, None),
401 WhaleState::Listen => (Presence::Listening, None),
402 WhaleState::Think => (Presence::Thinking, None),
403 WhaleState::NeedsYou => (Presence::NeedsYou, None),
404 WhaleState::Done => (Presence::Done, None),
405 WhaleState::Stuck => (Presence::Stuck, None),
406 WhaleState::Asleep => (Presence::Offline, None),
407 WhaleState::Read => (Presence::Working, Some("reading")),
408 WhaleState::Search => (Presence::Working, Some("searching")),
409 WhaleState::Write => (Presence::Working, Some("editing")),
410 WhaleState::Run => (Presence::Working, Some("executing")),
411 WhaleState::Browse => (Presence::Working, Some("browsing")),
412 WhaleState::Talk => (Presence::Working, Some("responding")),
413 WhaleState::Pod { .. } => (Presence::Working, Some("delegating")),
414 WhaleState::Computer => (Presence::Working, Some("computer")),
415 WhaleState::Connect => (Presence::Working, Some("network")),
416 WhaleState::Busy => (Presence::Working, None),
417 };
418 Inputs {
419 presence,
420 activity: Some(Activity {
421 kind: kind.map(str::to_owned),
422 observed: kind.is_some(),
423 parallel: if matches!(action, WhaleState::Pod { .. }) {
424 Some(3.0)
425 } else {
426 None
427 },
428 active: vec![],
429 }),
430 context: Context {
431 live: true,
432 turn_id: Some(identity.to_owned()),
433 status: Some(
434 if action == WhaleState::Stuck {
435 "failed"
436 } else {
437 "completed"
438 }
439 .into(),
440 ),
441 now_ms: Some(1_000.0),
442 failed_at_ms: Some(0.0),
443 },
444 }
445 }
446 fn approval_choices() -> ApprovalState {
447 ApprovalState::new(vec![
448 ApprovalChoice::new(ChoiceId(1), "Allow once", ApprovalEffect::Grants).char_key('y'),
449 ApprovalChoice::new(ChoiceId(2), "Keep waiting", ApprovalEffect::Refuses).char_key('n'),
450 ])
451 .reveal(ApprovalKey::char('o'))
452 }
453
454 /// The same pure renderer is used by the live example and frame exports.
455 /// Native whale geometry is supplied by the host's one Stage; absent geometry
456 /// uses the kit's still pose. Rendering never reads an Instant or advances it.
457 pub struct ShowcaseFrame<'a> {
458 pub state: &'a ShowcaseState,
459 pub elapsed: Duration,
460 pub whale: Option<&'a ColoredGrid>,
461 }
462 impl<'a> ShowcaseFrame<'a> {
463 pub const fn new(state: &'a ShowcaseState, elapsed: Duration) -> Self {
464 Self {
465 state,
466 elapsed,
467 whale: None,
468 }
469 }
470 pub const fn whale(mut self, grid: &'a ColoredGrid) -> Self {
471 self.whale = Some(grid);
472 self
473 }
474 /// The caller can rasterize its one native Stage at the actual viewport
475 /// size. Hidden side panes request no art and therefore no actor clock.
476 pub fn whale_size(&self, area: Rect) -> Option<(usize, usize)> {
477 if self.state.section != ShowcaseSection::Life {
478 return None;
479 }
480 let art = Self::life_art(area);
481 let rows = art.height.saturating_sub(1).min(16);
482 (art.width >= 16 && rows >= 8).then_some((usize::from(art.width), usize::from(rows)))
483 }
484 }
485 impl Paint for ShowcaseFrame<'_> {
486 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
487 let area = area.intersection(buf.area);
488 if area.is_empty() {
489 return;
490 }
491 // Kit widgets can use ordinary local coordinates even when the host
492 // paints into an offset buffer at the last representable coordinate.
493 let mut local = Buffer::empty(Rect::new(0, 0, area.width, area.height));
494 self.paint_local(local.area, &mut local, theme);
495 for y in 0..area.height {
496 for x in 0..area.width {
497 buf[(area.x + x, area.y + y)] = local[(x, y)].clone();
498 }
499 }
500 }
501 }
502
503 fn band(area: Rect, offset: u16, height: u16) -> Rect {
504 let offset = offset.min(area.height);
505 Rect::new(
506 area.x,
507 area.y.saturating_add(offset),
508 area.width,
509 height.min(area.height.saturating_sub(offset)),
510 )
511 }
512 fn row(area: Rect, buf: &mut Buffer, line: Line<'_>) {
513 let area = area.intersection(buf.area);
514 if !area.is_empty() {
515 buf.set_line(area.x, area.y, &line, area.width);
516 }
517 }
518 fn caption(area: Rect, buf: &mut Buffer, theme: &Theme, value: &str, role: Role) {
519 row(
520 area,
521 buf,
522 Line::styled(
523 text::truncate_words(
524 &text::display_safe(value),
525 usize::from(area.width),
526 theme.ascii(),
527 )
528 .into_owned(),
529 theme.fg(role),
530 ),
531 );
532 }
533 fn title(area: Rect, buf: &mut Buffer, theme: &Theme, value: &str) {
534 row(
535 area,
536 buf,
537 Line::styled(
538 text::truncate_words(
539 &text::display_safe(value),
540 usize::from(area.width),
541 theme.ascii(),
542 )
543 .into_owned(),
544 theme.fg(Role::Foreground).add_modifier(Modifier::BOLD),
545 ),
546 );
547 }
548 fn mode_word(mode: MotionMode) -> &'static str {
549 match mode {
550 MotionMode::Full => "Full",
551 MotionMode::Reduced => "Reduced",
552 MotionMode::Still => "Still",
553 }
554 }
555
556 impl ShowcaseFrame<'_> {
557 fn native_composer(&self, theme: &Theme) -> NativeComposer<'_> {
558 let mut composer = NativeComposer::new(self.state.draft.text())
559 .density(NativeComposerDensity::Compact)
560 .cursor(self.state.draft.cursor())
561 .placeholder("Write a task or use /.")
562 .focused(self.state.editing && !self.state.dock.focused)
563 .can_submit(!self.state.draft.text().is_empty());
564 if matches!(
565 self.state.phase,
566 ShowcasePhase::Working | ShowcasePhase::Verifying
567 ) {
568 composer = composer.submit_hint(if theme.ascii() {
569 "Enter send after this turn"
570 } else {
571 "↵ send after this turn"
572 });
573 }
574 composer
575 }
576
577 /// Native slot geometry shared with the terminal cursor owner.
578 #[must_use]
579 pub fn work_areas(&self, area: Rect, theme: &Theme) -> crate::ShellAreas {
580 let dock = self.state.workbar();
581 let dock_rows = if self.state.readouts.on {
582 dock.height(area.width, theme)
583 } else {
584 0
585 };
586 let pending_rows = u16::from(!self.state.queued.is_empty());
587 let workflow_rows = u16::from(self.state.details.on);
588 let composer_budget = area
589 .height
590 .saturating_sub(3 + 2 + dock_rows + pending_rows + workflow_rows)
591 .max(1)
592 .min(area.height);
593 let composer_height = self
594 .native_composer(theme)
595 .desired_height(area.width, composer_budget);
596 TerminalShell::new(composer_height)
597 .pending_rows(pending_rows)
598 .workflow_rows(workflow_rows)
599 .workbar_rows(dock_rows)
600 .areas(area)
601 }
602
603 #[must_use]
604 pub fn composer_cursor(&self, area: Rect, theme: &Theme) -> Option<ratatui::layout::Position> {
605 self.native_composer(theme)
606 .cursor_position(self.work_areas(area, theme).composer)
607 }
608
609 fn paint_local(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
610 let theme = self.state.theme_for(theme);
611 buf.set_style(
612 area,
613 theme.bg(Role::Background).patch(theme.fg(Role::Foreground)),
614 );
615 match self.state.section {
616 ShowcaseSection::Work => self.work(area, buf, &theme),
617 ShowcaseSection::Decisions => self.decisions(area, buf, &theme),
618 ShowcaseSection::Controls => self.controls(area, buf, &theme),
619 ShowcaseSection::Color => self.colors(area, buf, &theme),
620 ShowcaseSection::Life => self.life(area, buf, &theme),
621 ShowcaseSection::Components => self.components(area, buf, &theme),
622 }
623 let phase = if self.state.section == ShowcaseSection::Life {
624 match WhaleState::ALL[self.state.action.min(16)].state() {
625 State::Working => OceanPhase::Working,
626 State::NeedsYou => OceanPhase::Waiting,
627 State::Failed => OceanPhase::Failed,
628 State::Done => OceanPhase::Done,
629 _ => OceanPhase::Idle,
630 }
631 } else if self.state.approval_open {
632 OceanPhase::Approval
633 } else {
634 match self.state.phase {
635 ShowcasePhase::Working => OceanPhase::Working,
636 ShowcasePhase::NeedsYou => OceanPhase::Waiting,
637 ShowcasePhase::Verifying => OceanPhase::Verifying,
638 ShowcasePhase::Done => OceanPhase::Done,
639 }
640 };
641 if self.state.palette == WaterPalette::Ocean {
642 let column = OceanColumn::new(
643 self.elapsed,
644 if self.state.active_motion() {
645 self.state.motion
646 } else {
647 MotionMode::Still
648 },
649 )
650 .phase(phase)
651 .context_percent(if self.state.section == ShowcaseSection::Work {
652 24
653 } else {
654 0
655 })
656 .completion_elapsed(self.state.phase_elapsed(self.elapsed))
657 .viewport(area);
658 column.apply(area, buf, &theme);
659 if self.state.section == ShowcaseSection::Work {
660 let regions = self.work_areas(area, &theme);
661 for (region, ground) in [
662 (regions.composer, TuiGround::Composer),
663 (regions.posture, TuiGround::Footer),
664 (regions.metrics, TuiGround::Header),
665 ] {
666 if let Some(ground) = theme.tui_ground(ground).bg {
667 column.apply_matching(region, buf, &theme, ground);
668 }
669 }
670 }
671 } else {
672 Ombre::new(self.state.palette)
673 .direction(self.state.direction)
674 .apply(area, buf, &theme);
675 }
676 if self.state.section == ShowcaseSection::Life {
677 self.paint_whale(
678 Self::life_art(area),
679 buf,
680 &theme,
681 WhaleState::ALL[self.state.action.min(16)],
682 );
683 }
684 }
685
686 fn marker(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
687 let elapsed = self.state.phase_elapsed(self.elapsed);
688 match self.state.phase {
689 ShowcasePhase::Working => {
690 Spinner::new("Checking the narrow layout", elapsed, self.state.motion)
691 .paint(area, buf, theme)
692 }
693 ShowcasePhase::Verifying => {
694 VerificationSpinner::new("Checking the changes", elapsed, self.state.motion)
695 .paint(area, buf, theme)
696 }
697 ShowcasePhase::NeedsYou => StatusMark::new(State::NeedsYou)
698 .word("Needs you")
699 .paint(area, buf, theme),
700 ShowcasePhase::Done => Receipt::new(State::Done, "Done")
701 .value(ReceiptValue::Duration(Some(Duration::from_secs(6))))
702 .paint(area, buf, theme),
703 }
704 }
705 fn paint_whale(&self, area: Rect, buf: &mut Buffer, theme: &Theme, state: WhaleState) {
706 let whale = Whale::new(state).words(state.words());
707 if let Some(grid) = self.whale {
708 grid.paint_with_contrast(&whale, area, buf, theme, 3.0);
709 } else {
710 whale.paint(area, buf, theme);
711 }
712 }
713 fn split(&self, area: Rect, side_width: u16) -> (Rect, Option<Rect>) {
714 if area.width >= 96 {
715 (
716 Rect::new(
717 area.x,
718 area.y,
719 area.width.saturating_sub(side_width + 3),
720 area.height,
721 ),
722 Some(Rect::new(
723 area.right().saturating_sub(side_width),
724 area.y,
725 side_width,
726 area.height,
727 )),
728 )
729 } else {
730 (area, None)
731 }
732 }
733 fn composer(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
734 self.native_composer(theme).paint(area, buf, theme);
735 }
736
737 fn work(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
738 let dock = self.state.workbar();
739 let regions = self.work_areas(area, theme);
740 TerminalShell::new(0).paint(area, buf, theme);
741 let user = Message::native("Make the session picker readable in narrow windows.")
742 .role(Role::Accent)
743 .marker(crate::glyphs::USER);
744 let mut next = 1;
745 let height = user.height(regions.conversation.width, theme);
746 user.paint(band(regions.conversation, next, height), buf, theme);
747 next += height + 1;
748 let reply = match self.state.phase {
749 ShowcasePhase::Working => {
750 "The list now keeps its search field, numbering and current-session marker.\nLong titles wrap cleanly, and the selection stays visible as the window narrows.\n\nI'm checking the compact layout before wrapping up."
751 }
752 ShowcasePhase::NeedsYou if self.state.approval_open => {
753 "Review the command below before continuing."
754 }
755 ShowcasePhase::NeedsYou => "The turn is paused. Your draft is still here.",
756 ShowcasePhase::Verifying => {
757 "The list, search field and current-session marker keep their place.\nI'm checking the compact layout and keyboard navigation."
758 }
759 ShowcasePhase::Done => {
760 "The session picker is ready for review.\nSearch, numbering and selection remain visible in narrow windows."
761 }
762 };
763 let reply = Message::native(reply);
764 let height = reply.height(regions.conversation.width, theme);
765 reply.paint(band(regions.conversation, next, height), buf, theme);
766 next += height + 1;
767 for followup in &self.state.followups {
768 let message = Message::native(followup).marker(crate::glyphs::USER);
769 let height = message.height(regions.conversation.width, theme);
770 message.paint(band(regions.conversation, next, height), buf, theme);
771 next = next.saturating_add(height).saturating_add(1);
772 }
773 if next < regions.conversation.height {
774 self.marker(band(regions.conversation, next, 1), buf, theme);
775 }
776 if theme.native_palette() == Some(TuiPalette::Underwater) {
777 Habitat::new(
778 self.elapsed,
779 if self.state.active_motion() {
780 self.state.motion
781 } else {
782 MotionMode::Still
783 },
784 )
785 .density(HabitatDensity::Sparse)
786 .paint(regions.conversation, buf, theme);
787 }
788 if let Some(queued) = self.state.queued.last() {
789 caption(
790 regions.pending,
791 buf,
792 theme,
793 &format!(
794 "{} queued {} {}",
795 self.state.queued.len(),
796 if theme.ascii() { "." } else { "·" },
797 queued
798 ),
799 Role::Accent,
800 );
801 }
802 self.composer(regions.composer, buf, theme);
803 buf.set_style(regions.posture, theme.tui_ground(TuiGround::Footer));
804 let mut posture = PostureBar::new(self.state.permission.word())
805 .permission_ink(self.state.permission.ink())
806 .permission_key("Shift+Tab")
807 .mode_ink("work", TuiInk::ModeWork)
808 .context_percent(24);
809 if self.state.phase == ShowcasePhase::Done {
810 posture = posture.session_clock("worked 6 s", Role::Muted);
811 } else {
812 posture = posture.turn_clock(
813 format!(
814 "{} {}",
815 self.state.phase.word().to_lowercase(),
816 crate::duration(self.state.phase_elapsed(self.elapsed))
817 ),
818 self.state.phase.state().role(),
819 );
820 }
821 if self.state.editing
822 && matches!(
823 self.state.phase,
824 ShowcasePhase::Working | ShowcasePhase::Verifying
825 )
826 {
827 posture = posture.hint("Esc to interrupt", Role::Hint);
828 }
829 posture.paint(regions.posture, buf, theme);
830 WorkflowProgress::new(vec![
831 WorkflowRun::new(
832 "Update the component library",
833 if self.state.phase == ShowcasePhase::Done {
834 WorkflowRunState::Succeeded
835 } else {
836 WorkflowRunState::Running
837 },
838 )
839 .outcomes(
840 if self.state.phase == ShowcasePhase::Done {
841 3
842 } else {
843 1
844 },
845 0,
846 0,
847 3,
848 )
849 .elapsed(if self.state.phase == ShowcasePhase::Done {
850 self.state.phase_started
851 } else {
852 self.elapsed
853 }),
854 ])
855 .paint(regions.workflows, buf, theme);
856 buf.set_style(regions.metrics, theme.tui_ground(TuiGround::Header));
857 MetricsLine::new(vec![
858 MetricSegment::new(MetricKind::Model, "", "deepseek-v4"),
859 MetricSegment::new(MetricKind::Context, "ctx", "24%"),
860 MetricSegment::new(MetricKind::Workspace, "", "codewhale-ratatui"),
861 MetricSegment::new(MetricKind::GitBranch, "", "session-layout"),
862 ])
863 .help_hint("F6 components")
864 .paint(
865 regions
866 .metrics
867 .inner(Margin::new(u16::from(regions.metrics.width >= 8), 0)),
868 buf,
869 theme,
870 );
871 dock.paint(regions.workbar, buf, theme);
872 }
873
874 fn decisions(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
875 if self.state.approval_open {
876 self.approval(area, buf, theme);
877 return;
878 }
879 title(band(area, 1, 1), buf, theme, "Review changes");
880 const PATCH: &str = "--- a/workspace.rs\n+++ b/workspace.rs\n@@ -1,3 +1,4 @@\n fn draw() {\n- draw_all();\n+ composer.paint(area, buffer, theme);\n+ workbar.paint(dock, buffer, theme);\n }\n";
881 Diff::new(parse_unified(PATCH))
882 .gutter(DiffGutter::Both)
883 .wrap(DiffWrap::Wrap)
884 .paint(band(area, 4, area.height.saturating_sub(7)), buf, theme);
885 self.marker(band(area, area.height.saturating_sub(2), 1), buf, theme);
886 caption(
887 band(area, area.height.saturating_sub(1), 1),
888 buf,
889 theme,
890 "F1 conversation / F10 continue",
891 Role::Hint,
892 );
893 }
894
895 fn approval(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
896 // A full reading surface at narrow widths; no creature or decoration
897 // can enter even the blank space of this decision.
898 let width = area.width.min(72);
899 let modal = Rect::new(
900 area.x + area.width.saturating_sub(width) / 2,
901 area.y,
902 width,
903 area.height,
904 );
905 buf.set_style(
906 modal,
907 theme.bg(Role::Surface).patch(theme.fg(Role::Foreground)),
908 );
909 for y in modal.top()..modal.bottom() {
910 for x in modal.left()..modal.right() {
911 buf[(x, y)].set_symbol(" ");
912 }
913 }
914 title(band(modal, 0, 1), buf, theme, "Run a command");
915 let subject = ApprovalSubject::new(ApprovalKind::Command, "git diff --check")
916 .cwd("codewhale-ratatui")
917 .scope(ApprovalScope::Inside)
918 .agent("Verifier", false)
919 .risk_note("Checks whitespace in the current changes.");
920 ApprovalCard::new(&subject, &self.state.approval).paint(
921 band(modal, 2, modal.height.saturating_sub(3)),
922 buf,
923 theme,
924 );
925 caption(
926 band(modal, modal.height.saturating_sub(1), 1),
927 buf,
928 theme,
929 "y advance / n wait / Esc preserve draft",
930 Role::Attention,
931 );
932 }
933 fn controls(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
934 let (main, side) = self.split(area, 34);
935 title(band(main, 0, 1), buf, theme, "Settings");
936 caption(
937 band(main, 2, 2),
938 buf,
939 theme,
940 if self.state.editing {
941 "Editing / Tab moves between fields; Enter validates"
942 } else {
943 "Enter edits the form. F7-F9 change appearance."
944 },
945 Role::Muted,
946 );
947 Form::new(&self.state.form)
948 .focused(self.state.editing)
949 .paint(band(main, 5, 11), buf, theme);
950 Toggle::new("Workflow progress", self.state.details)
951 .focused(!self.state.editing && self.state.focus == 0)
952 .paint(band(main, 17, 1), buf, theme);
953 Toggle::new("Workbar", self.state.readouts)
954 .focused(!self.state.editing && self.state.focus == 1)
955 .paint(band(main, 19, 1), buf, theme);
956 caption(band(main, 21, 2), buf, theme, &self.state.note, Role::Live);
957 if let Some(side) = side {
958 self.settings(side, buf, theme);
959 }
960 }
961 fn settings(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
962 PaneHeader::new("Appearance").paint(band(area, 0, 2), buf, theme);
963 let rows = [
964 SettingRow::new("Palette", self.state.palette.name()).source("your choice"),
965 SettingRow::new("Profile", self.state.profile.name()).source("terminal"),
966 SettingRow::new("Motion", mode_word(self.state.motion)).source("your choice"),
967 ];
968 let mut top = 3;
969 for setting in rows {
970 let h = setting.height(area.width, theme);
971 setting.paint(band(area, top, h), buf, theme);
972 top += h;
973 }
974 SettingDetail::new("Appearance", "Palette changes the atmosphere. State marks, action ink and decision scope keep their meaning.").default_value("Ocean / Full").source("workspace").paint(band(area, top + 2, area.height.saturating_sub(top + 2)), buf, theme);
975 }
976 fn colors(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
977 title(band(area, 0, 1), buf, theme, "Appearance");
978 let palette = WaterPalette::ALL
979 .iter()
980 .position(|p| *p == self.state.palette)
981 .unwrap_or(0);
982 Segmented::new(
983 WaterPalette::ALL.map(WaterPalette::name),
984 SegmentedState::new(palette),
985 )
986 .focused(self.state.focus == 0)
987 .paint(band(area, 2, 1), buf, theme);
988 Segmented::new(
989 ["Full", "Reduced", "Still"],
990 SegmentedState::new(match self.state.motion {
991 MotionMode::Full => 0,
992 MotionMode::Reduced => 1,
993 MotionMode::Still => 2,
994 }),
995 )
996 .focused(self.state.focus == 1)
997 .paint(band(area, 4, 1), buf, theme);
998 caption(
999 band(area, 6, 1),
1000 buf,
1001 theme,
1002 &format!("Profile {} / Left, Right", self.state.profile.name()),
1003 if self.state.focus == 2 {
1004 Role::Accent
1005 } else {
1006 Role::Muted
1007 },
1008 );
1009 Segmented::new(
1010 ["Vertical", "Diagonal"],
1011 SegmentedState::new(usize::from(
1012 self.state.direction == OmbreDirection::Diagonal,
1013 )),
1014 )
1015 .focused(self.state.focus == 3)
1016 .paint(band(area, 8, 1), buf, theme);
1017 let columns = if area.width >= 72 { 3 } else { 2 };
1018 let cell_width = area.width / columns;
1019 for (index, role) in Role::ALL.into_iter().enumerate() {
1020 let x = area.x + (index as u16 % columns) * cell_width;
1021 let y = area.y + 11 + index as u16 / columns;
1022 let cell = Rect::new(x, y, cell_width.saturating_sub(1), 1).intersection(area);
1023 if cell.is_empty() {
1024 continue;
1025 }
1026 let label = format!("{:?}", role);
1027 let sample = if role.is_ground() {
1028 theme.bg(role).patch(theme.fg(Role::Foreground))
1029 } else if role == Role::PrimaryForeground {
1030 theme.bg(Role::Primary).patch(theme.fg(role))
1031 } else {
1032 theme.fg(role)
1033 };
1034 let label_width = cell.width.saturating_sub(3);
1035 row(
1036 cell,
1037 buf,
1038 Line::from(vec![
1039 Span::styled(
1040 text::pad(&label, usize::from(label_width), theme.ascii()),
1041 theme.fg(Role::Foreground),
1042 ),
1043 Span::styled(" Aa", sample),
1044 ]),
1045 );
1046 }
1047 let start = if columns == 3 { 19 } else { 22 };
1048 if area.height > start + 2 {
1049 let width = area.width / 4;
1050 for (index, depth) in [Depth::Deep, Depth::Stage, Depth::Raised, Depth::Overlay]
1051 .into_iter()
1052 .enumerate()
1053 {
1054 let cell = Rect::new(
1055 area.x + index as u16 * width,
1056 area.y + start,
1057 width.saturating_sub(1),
1058 2,
1059 )
1060 .intersection(area);
1061 buf.set_style(cell, theme.bg(depth.ground()));
1062 caption(cell, buf, theme, &format!("{depth:?}"), Role::Foreground);
1063 }
1064 HorizonRule::new().label("One spatial wash").paint(
1065 band(area, start + 3, 1),
1066 buf,
1067 theme,
1068 );
1069 }
1070 }
1071 fn life_art(area: Rect) -> Rect {
1072 let water = band(area, 4, area.height.saturating_sub(4));
1073 let art_width = water.width.min(40);
1074 Rect::new(
1075 water.x + water.width.saturating_sub(art_width) / 2,
1076 water.y + u16::from(water.height >= 19) * 2,
1077 art_width,
1078 water.height.min(17),
1079 )
1080 }
1081 fn life(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
1082 let action = WhaleState::ALL[self.state.action.min(WhaleState::ALL.len() - 1)];
1083 title(
1084 band(area, 0, 1),
1085 buf,
1086 theme,
1087 "One whale. Seventeen native actions.",
1088 );
1089 caption(
1090 band(area, 2, 1),
1091 buf,
1092 theme,
1093 &format!(
1094 "Action study / {} / {} of 17 / Left, Right / Space play",
1095 action.words(),
1096 self.state.action.min(16) + 1
1097 ),
1098 Role::Accent,
1099 );
1100 let water = band(area, 4, area.height.saturating_sub(4));
1101 let art = Self::life_art(area);
1102 if !self.state.approval_open {
1103 Habitat::new(
1104 self.elapsed,
1105 if self.state.action_playing {
1106 self.state.motion
1107 } else {
1108 MotionMode::Still
1109 },
1110 )
1111 .density(HabitatDensity::Rich)
1112 .hold_jellyfish_visit(true)
1113 .protected(vec![art])
1114 .paint(water, buf, theme);
1115 }
1116 if water.height >= 20 {
1117 caption(
1118 band(water, water.height - 2, 1),
1119 buf,
1120 theme,
1121 "Native dots, colored ink, fish, one jellyfish and bubbles",
1122 Role::Muted,
1123 );
1124 caption(
1125 band(water, water.height - 1, 1),
1126 buf,
1127 theme,
1128 if self.state.active_motion() {
1129 "Space pause / Left, Right action / F8 motion"
1130 } else {
1131 "Space play / Left, Right action / F8 motion"
1132 },
1133 Role::Muted,
1134 );
1135 }
1136 }
1137 fn components(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
1138 let (entries, items, matches) = self.state.catalogue();
1139 let narrow = area.width < 76;
1140 let list_width = if narrow { area.width } else { 28 };
1141 let list_height = if narrow {
1142 area.height.min(8)
1143 } else {
1144 area.height
1145 };
1146 let list = Rect::new(area.x, area.y, list_width, list_height);
1147 let picker = Picker::new(&items, self.state.picker)
1148 .query(
1149 self.state.query.text(),
1150 text::width(self.state.query.text()),
1151 )
1152 .matches(&matches);
1153 picker.paint(list, buf, theme);
1154 let Some(selected) = matches
1155 .get(self.state.picker.selected)
1156 .and_then(|hit| entries.get(hit.index))
1157 else {
1158 return;
1159 };
1160 let preview = if narrow {
1161 band(
1162 area,
1163 list_height + 1,
1164 area.height.saturating_sub(list_height + 1),
1165 )
1166 } else {
1167 Rect::new(
1168 area.x + 31,
1169 area.y,
1170 area.width.saturating_sub(31),
1171 area.height,
1172 )
1173 };
1174 PaneHeader::new(selected.name)
1175 .meta(format!(
1176 "{} x {} / PgUp, PgDn",
1177 selected.width, selected.height
1178 ))
1179 .paint(band(preview, 0, 2), buf, theme);
1180 let body = band(preview, 3, preview.height.saturating_sub(3));
1181 if body.is_empty() {
1182 return;
1183 }
1184 // Tall components scroll, rather than being silently clipped to the
1185 // viewport. Width belongs to the current terminal specimen.
1186 let source_height = selected.height.max(body.height);
1187 let mut source = Buffer::empty(Rect::new(0, 0, body.width, source_height));
1188 source.set_style(source.area, theme.bg(Role::Background));
1189 (selected.draw)(source.area, &mut source, theme);
1190 let top = self
1191 .state
1192 .preview_scroll
1193 .min(source_height.saturating_sub(body.height));
1194 for y in 0..body.height {
1195 for x in 0..body.width {
1196 buf[(body.x + x, body.y + y)] = source[(x, y + top)].clone();
1197 }
1198 }
1199 }
1200 }
1201
1202 fn fixture(
1203 section: ShowcaseSection,
1204 phase: ShowcasePhase,
1205 area: Rect,
1206 buf: &mut Buffer,
1207 theme: &Theme,
1208 ) {
1209 let mut state = ShowcaseState::new();
1210 state.section = section;
1211 state.phase = phase;
1212 state.approval_open = section == ShowcaseSection::Decisions;
1213 state.action = 8;
1214 state.action_playing = true;
1215 let frame = ShowcaseFrame::new(&state, Duration::from_millis(6_800));
1216 if let Some((cols, rows)) = frame.whale_size(area) {
1217 let action = if section == ShowcaseSection::Life {
1218 WhaleState::ALL[state.action]
1219 } else {
1220 phase.whale()
1221 };
1222 let mut stage = Stage::new();
1223 stage.observe(
1224 Some("gallery-action-study"),
1225 showcase_inputs(action, "gallery-action-study"),
1226 theme.ascii(),
1227 );
1228 let base = std::time::Instant::now();
1229 // Fixed caller-supplied steps sample a living native pose. The pure
1230 // renderer merely consumes this one fixture-owned Stage's output.
1231 for index in 0..=8 {
1232 stage.advance(base + Duration::from_millis(index * 200));
1233 }
1234 let native = colored_braille(
1235 stage.director(),
1236 cols,
1237 rows,
1238 theme.caps().appearance != crate::detect::Appearance::Light,
1239 );
1240 frame.whale(&native).paint(area, buf, theme);
1241 } else {
1242 frame.paint(area, buf, theme);
1243 }
1244 }
1245 pub(crate) fn entries() -> Vec<Entry> {
1246 vec![
1247 Entry {
1248 name: "showcase-work",
1249 width: 104,
1250 height: 30,
1251 draw: |a, b, t| fixture(ShowcaseSection::Work, ShowcasePhase::Working, a, b, t),
1252 },
1253 Entry {
1254 name: "showcase-decision",
1255 width: 104,
1256 height: 30,
1257 draw: |a, b, t| fixture(ShowcaseSection::Decisions, ShowcasePhase::NeedsYou, a, b, t),
1258 },
1259 Entry {
1260 name: "showcase-color",
1261 width: 112,
1262 height: 38,
1263 draw: |a, b, t| fixture(ShowcaseSection::Color, ShowcasePhase::Done, a, b, t),
1264 },
1265 Entry {
1266 name: "showcase-life",
1267 width: 112,
1268 height: 38,
1269 draw: |a, b, t| fixture(ShowcaseSection::Life, ShowcasePhase::Working, a, b, t),
1270 },
1271 Entry {
1272 name: "showcase-narrow",
1273 width: 40,
1274 height: 28,
1275 draw: |a, b, t| fixture(ShowcaseSection::Work, ShowcasePhase::Done, a, b, t),
1276 },
1277 ]
1278 }
1279
1279 lines RUST