ratatui_ruby 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. checksums.yaml +4 -4
  2. data/.builds/ruby-3.2.yml +1 -1
  3. data/.builds/ruby-3.3.yml +1 -1
  4. data/.builds/ruby-3.4.yml +1 -1
  5. data/.builds/ruby-4.0.0.yml +1 -1
  6. data/AGENTS.md +4 -4
  7. data/CHANGELOG.md +35 -0
  8. data/README.md +26 -1
  9. data/doc/application_architecture.md +16 -16
  10. data/doc/application_testing.md +1 -1
  11. data/doc/contributors/architectural_overhaul/chat_conversations.md +4952 -0
  12. data/doc/contributors/architectural_overhaul/implementation_plan.md +60 -0
  13. data/doc/contributors/architectural_overhaul/task.md +37 -0
  14. data/doc/contributors/design/ruby_frontend.md +277 -81
  15. data/doc/contributors/design/rust_backend.md +349 -55
  16. data/doc/contributors/developing_examples.md +5 -5
  17. data/doc/contributors/index.md +7 -5
  18. data/doc/contributors/v1.0.0_blockers.md +1729 -0
  19. data/doc/index.md +11 -6
  20. data/doc/interactive_design.md +2 -2
  21. data/doc/quickstart.md +66 -97
  22. data/doc/v0.7.0_migration.md +236 -0
  23. data/doc/why.md +93 -0
  24. data/examples/app_all_events/README.md +6 -4
  25. data/examples/app_all_events/app.rb +1 -1
  26. data/examples/app_all_events/model/app_model.rb +1 -1
  27. data/examples/app_all_events/model/msg.rb +1 -1
  28. data/examples/app_all_events/update.rb +1 -1
  29. data/examples/app_all_events/view/app_view.rb +1 -1
  30. data/examples/app_all_events/view/controls_view.rb +1 -1
  31. data/examples/app_all_events/view/counts_view.rb +1 -1
  32. data/examples/app_all_events/view/live_view.rb +1 -1
  33. data/examples/app_all_events/view/log_view.rb +1 -1
  34. data/examples/app_color_picker/README.md +7 -5
  35. data/examples/app_color_picker/app.rb +1 -1
  36. data/examples/app_login_form/README.md +2 -0
  37. data/examples/app_stateful_interaction/README.md +2 -0
  38. data/examples/app_stateful_interaction/app.rb +1 -1
  39. data/examples/verify_quickstart_dsl/README.md +4 -3
  40. data/examples/verify_quickstart_dsl/app.rb +1 -1
  41. data/examples/verify_quickstart_layout/README.md +1 -1
  42. data/examples/verify_quickstart_lifecycle/README.md +3 -3
  43. data/examples/verify_quickstart_lifecycle/app.rb +2 -2
  44. data/examples/verify_readme_usage/README.md +1 -1
  45. data/examples/widget_barchart_demo/README.md +2 -1
  46. data/examples/widget_block_demo/README.md +2 -0
  47. data/examples/widget_box_demo/README.md +3 -3
  48. data/examples/widget_calendar_demo/README.md +3 -3
  49. data/examples/widget_calendar_demo/app.rb +5 -1
  50. data/examples/widget_canvas_demo/README.md +3 -3
  51. data/examples/widget_cell_demo/README.md +3 -3
  52. data/examples/widget_center_demo/README.md +3 -3
  53. data/examples/widget_chart_demo/README.md +3 -3
  54. data/examples/widget_gauge_demo/README.md +3 -3
  55. data/examples/widget_layout_split/README.md +3 -3
  56. data/examples/widget_line_gauge_demo/README.md +3 -3
  57. data/examples/widget_list_demo/README.md +3 -3
  58. data/examples/widget_map_demo/README.md +3 -3
  59. data/examples/widget_map_demo/app.rb +2 -2
  60. data/examples/widget_overlay_demo/README.md +36 -0
  61. data/examples/widget_popup_demo/README.md +3 -3
  62. data/examples/widget_ratatui_logo_demo/README.md +3 -3
  63. data/examples/widget_ratatui_logo_demo/app.rb +1 -1
  64. data/examples/widget_ratatui_mascot_demo/README.md +3 -3
  65. data/examples/widget_rect/README.md +3 -3
  66. data/examples/widget_render/README.md +3 -3
  67. data/examples/widget_render/app.rb +3 -3
  68. data/examples/widget_rich_text/README.md +3 -3
  69. data/examples/widget_scroll_text/README.md +3 -3
  70. data/examples/widget_scrollbar_demo/README.md +3 -3
  71. data/examples/widget_sparkline_demo/README.md +3 -3
  72. data/examples/widget_style_colors/README.md +3 -3
  73. data/examples/widget_table_demo/README.md +3 -3
  74. data/examples/widget_table_demo/app.rb +19 -4
  75. data/examples/widget_tabs_demo/README.md +3 -3
  76. data/examples/widget_text_width/README.md +3 -3
  77. data/examples/widget_text_width/app.rb +8 -1
  78. data/ext/ratatui_ruby/Cargo.lock +1 -1
  79. data/ext/ratatui_ruby/Cargo.toml +1 -1
  80. data/ext/ratatui_ruby/src/frame.rs +6 -5
  81. data/ext/ratatui_ruby/src/lib.rs +3 -2
  82. data/ext/ratatui_ruby/src/rendering.rs +22 -21
  83. data/ext/ratatui_ruby/src/text.rs +12 -3
  84. data/ext/ratatui_ruby/src/widgets/canvas.rs +5 -5
  85. data/ext/ratatui_ruby/src/widgets/table.rs +81 -36
  86. data/lib/ratatui_ruby/buffer/cell.rb +168 -0
  87. data/lib/ratatui_ruby/buffer.rb +15 -0
  88. data/lib/ratatui_ruby/frame.rb +8 -8
  89. data/lib/ratatui_ruby/layout/constraint.rb +95 -0
  90. data/lib/ratatui_ruby/layout/layout.rb +106 -0
  91. data/lib/ratatui_ruby/layout/rect.rb +118 -0
  92. data/lib/ratatui_ruby/layout.rb +19 -0
  93. data/lib/ratatui_ruby/list_state.rb +2 -2
  94. data/lib/ratatui_ruby/schema/layout.rb +1 -1
  95. data/lib/ratatui_ruby/schema/row.rb +66 -0
  96. data/lib/ratatui_ruby/schema/table.rb +10 -10
  97. data/lib/ratatui_ruby/schema/text.rb +27 -2
  98. data/lib/ratatui_ruby/style/style.rb +81 -0
  99. data/lib/ratatui_ruby/style.rb +15 -0
  100. data/lib/ratatui_ruby/table_state.rb +1 -1
  101. data/lib/ratatui_ruby/test_helper/snapshot.rb +24 -0
  102. data/lib/ratatui_ruby/test_helper/style_assertions.rb +1 -1
  103. data/lib/ratatui_ruby/tui/buffer_factories.rb +20 -0
  104. data/lib/ratatui_ruby/tui/canvas_factories.rb +44 -0
  105. data/lib/ratatui_ruby/tui/core.rb +38 -0
  106. data/lib/ratatui_ruby/tui/layout_factories.rb +74 -0
  107. data/lib/ratatui_ruby/tui/state_factories.rb +33 -0
  108. data/lib/ratatui_ruby/tui/style_factories.rb +20 -0
  109. data/lib/ratatui_ruby/tui/text_factories.rb +44 -0
  110. data/lib/ratatui_ruby/tui/widget_factories.rb +195 -0
  111. data/lib/ratatui_ruby/tui.rb +75 -0
  112. data/lib/ratatui_ruby/version.rb +1 -1
  113. data/lib/ratatui_ruby/widgets/bar_chart/bar.rb +47 -0
  114. data/lib/ratatui_ruby/widgets/bar_chart/bar_group.rb +25 -0
  115. data/lib/ratatui_ruby/widgets/bar_chart.rb +239 -0
  116. data/lib/ratatui_ruby/widgets/block.rb +192 -0
  117. data/lib/ratatui_ruby/widgets/calendar.rb +84 -0
  118. data/lib/ratatui_ruby/widgets/canvas.rb +231 -0
  119. data/lib/ratatui_ruby/widgets/cell.rb +47 -0
  120. data/lib/ratatui_ruby/widgets/center.rb +59 -0
  121. data/lib/ratatui_ruby/widgets/chart.rb +185 -0
  122. data/lib/ratatui_ruby/widgets/clear.rb +54 -0
  123. data/lib/ratatui_ruby/widgets/cursor.rb +42 -0
  124. data/lib/ratatui_ruby/widgets/gauge.rb +72 -0
  125. data/lib/ratatui_ruby/widgets/line_gauge.rb +80 -0
  126. data/lib/ratatui_ruby/widgets/list.rb +127 -0
  127. data/lib/ratatui_ruby/widgets/list_item.rb +43 -0
  128. data/lib/ratatui_ruby/widgets/overlay.rb +43 -0
  129. data/lib/ratatui_ruby/widgets/paragraph.rb +99 -0
  130. data/lib/ratatui_ruby/widgets/ratatui_logo.rb +31 -0
  131. data/lib/ratatui_ruby/widgets/ratatui_mascot.rb +36 -0
  132. data/lib/ratatui_ruby/widgets/row.rb +68 -0
  133. data/lib/ratatui_ruby/widgets/scrollbar.rb +143 -0
  134. data/lib/ratatui_ruby/widgets/shape/label.rb +68 -0
  135. data/lib/ratatui_ruby/widgets/sparkline.rb +134 -0
  136. data/lib/ratatui_ruby/widgets/table.rb +141 -0
  137. data/lib/ratatui_ruby/widgets/tabs.rb +85 -0
  138. data/lib/ratatui_ruby/widgets.rb +40 -0
  139. data/lib/ratatui_ruby.rb +23 -39
  140. data/sig/examples/app_all_events/view.rbs +1 -1
  141. data/sig/examples/app_all_events/view_state.rbs +1 -1
  142. data/sig/ratatui_ruby/schema/row.rbs +22 -0
  143. data/sig/ratatui_ruby/schema/table.rbs +1 -1
  144. data/sig/ratatui_ruby/schema/text.rbs +1 -0
  145. data/sig/ratatui_ruby/session.rbs +29 -49
  146. data/sig/ratatui_ruby/tui/buffer_factories.rbs +10 -0
  147. data/sig/ratatui_ruby/tui/canvas_factories.rbs +14 -0
  148. data/sig/ratatui_ruby/tui/core.rbs +14 -0
  149. data/sig/ratatui_ruby/tui/layout_factories.rbs +19 -0
  150. data/sig/ratatui_ruby/tui/state_factories.rbs +12 -0
  151. data/sig/ratatui_ruby/tui/style_factories.rbs +10 -0
  152. data/sig/ratatui_ruby/tui/text_factories.rbs +14 -0
  153. data/sig/ratatui_ruby/tui/widget_factories.rbs +39 -0
  154. data/sig/ratatui_ruby/tui.rbs +19 -0
  155. data/tasks/autodoc.rake +1 -35
  156. data/tasks/sourcehut.rake +4 -1
  157. metadata +62 -15
  158. data/doc/contributors/dwim_dx.md +0 -366
  159. data/doc/contributors/examples_audit/p1_high.md +0 -21
  160. data/doc/contributors/examples_audit/p2_moderate.md +0 -81
  161. data/doc/contributors/examples_audit.md +0 -41
  162. data/doc/images/app_analytics.png +0 -0
  163. data/doc/images/app_custom_widget.png +0 -0
  164. data/doc/images/app_mouse_events.png +0 -0
  165. data/doc/images/widget_table_flex.png +0 -0
  166. data/lib/ratatui_ruby/session/autodoc.rb +0 -482
  167. data/lib/ratatui_ruby/session.rb +0 -178
  168. data/tasks/autodoc/inventory.rb +0 -63
  169. data/tasks/autodoc/notice.rb +0 -26
  170. data/tasks/autodoc/rbs.rb +0 -38
  171. data/tasks/autodoc/rdoc.rb +0 -45
@@ -5,58 +5,352 @@
5
5
 
6
6
  # Rust Backend Design (`ratatui_ruby` extension)
7
7
 
8
- This document describes the internal architecture of the `ratatui_ruby` Rust extension.
9
-
10
- ## Architecture Guidelines
11
-
12
- The project follows a **Structured Design** approach, separating concerns into modules to improve cohesiveness and testability.
13
-
14
- ### Core Principles
15
-
16
- 1. **Single Generic Renderer**: The backend implements a single generic renderer that accepts a Ruby `Value` representing the root of the view tree.
17
- 2. **No Custom Rust Structs for UI**: Do not define custom Rust structs that mirror Ruby UI components. Instead, extract data directly from Ruby objects using `funcall`.
18
- 3. **Dynamic Dispatch**: Use `value.class().name()` (e.g., `"RatatuiRuby::Paragraph"`) to dynamically dispatch rendering logic to the appropriate widget module.
19
- * *Exception:* `render_stateful_widget` bypasses generic dispatch for specific Widget/State pairs (e.g., List + ListState) to allow mutating the State object.
20
- 4. **Immediate Mode**: The renderer traverses the Ruby object tree every frame and rebuilds the Ratatui widget tree on the fly.
21
-
22
- ### Module Structure
23
-
24
- The Rust extension is located in `ext/ratatui_ruby/src/` and is organized as follows:
25
-
26
- * **`lib.rs`**: The entry point for the compiled extension. It defines the Ruby module structure using `magnus` and exports public functions (`init_terminal`, `draw`, `poll_event`). It wires together the submodules.
27
- * **`terminal.rs`**: Encapsulates the global `TERMINAL` state (mutex-wrapped `CrosstermBackend`). It provides functions to initialize and restore the terminal to raw mode.
28
- * **`events.rs`**: Handles keyboard input polling and mapping Crossterm events to Ruby hashes.
29
- * **`style.rs`**: Provides pure functions for parsing styling information (Colors, Styles, Blocks) from Ruby values.
30
- * **`rendering.rs`**: The central dispatcher for the render loop. It takes the top-level Ruby View Tree node and recursively delegates to specific widget implementations based on the Ruby class name.
31
- * **`widgets/`**: A directory containing individual modules for each Ratatui widget (e.g., `paragraph.rs`, `list.rs`).
32
-
33
- ### Adding a New Widget
34
-
35
- To add a new widget:
36
-
37
- 1. Create a new file `src/widgets/my_widget.rs`.
38
- 2. Implement a public `render` function:
39
- ```rust
40
- /// Renders the widget to the given area.
41
- ///
42
- /// # Arguments
43
- ///
44
- /// * `frame` - The Ratatui frame to render to.
45
- /// * `area` - The rectangular area within the frame to draw the widget.
46
- /// * `node` - The Ruby object (Value) containing the widget's properties.
47
- pub fn render(frame: &mut Frame, area: Rect, node: Value) -> Result<(), Error>
48
- ```
49
- 3. Inside `render`:
50
- * Extract properties from the `node` (Ruby value) using `.funcall("method_name", ())?`.
51
- * Construct the Ratatui widget.
52
- * Render it using `frame.render_widget`.
53
- 4. Register the module in `src/widgets/mod.rs`.
54
- 5. Add a dispatch arm in `src/rendering.rs` matching the Ruby class name (e.g., `RatatuiRuby::MyWidget`).
55
-
56
- ### Testing Strategy
57
-
58
- * **Unit Tests (`cargo test`)**:
59
- * **Logic**: Test pure logic like `parse_color` in `style.rs` without needing a terminal or Ruby VM if possible (though `magnus::Value` usually requires it).
60
- * **Rendering**: Verify that widgets render *something* to a buffer. Ratatui's `TestBackend` or `Buffer` can be used to assert that cells are filled.
61
- * **Integration Tests (`rake test`)**:
62
- * Run Ruby scripts that exercise the full stack. Verify no crashes and expected return values.
8
+ This document describes the internal architecture of the `ratatui_ruby` Rust extension. It is intended for contributors, architects, and AI agents working on the codebase.
9
+
10
+ This is the companion document to [Ruby Frontend Design](./ruby_frontend.md). The Ruby layer defines data structures; the Rust layer renders them.
11
+
12
+ ## Key Dependencies
13
+
14
+ | Crate | Purpose |
15
+ |-------|---------|
16
+ | `ratatui` | TUI framework providing widgets, layout, and rendering |
17
+ | `crossterm` | Cross-platform terminal manipulation (raw mode, events, colors) |
18
+ | `magnus` | Ruby FFI bindings for Rust (value extraction, exception handling) |
19
+
20
+ **Why `ratatui` vs `ratatui-crossterm`?**
21
+
22
+ Ratatui's workspace includes modular crates (`ratatui-crossterm`, `ratatui-core`, etc.) for library authors who need fine-grained dependency control. We use the main `ratatui` crate because:
23
+
24
+ 1. We're building an application extension, not a widget library
25
+ 2. The main crate includes crossterm backend by default
26
+ 3. It provides the complete API surface we need
27
+
28
+ ## Guiding Design Principles
29
+
30
+ ### 1. Ruby Defines, Rust Renders
31
+
32
+ The Rust backend is a pure rendering engine. It receives Ruby objects representing the desired UI state and converts them to Ratatui primitives. It does not own or manage UI state—that responsibility belongs to Ruby.
33
+
34
+ **The Contract:**
35
+ - Ruby constructs a tree of `Data.define` objects describing the UI
36
+ - Ruby calls `RatatuiRuby.draw { |frame| ... }` or passes a widget to `frame.render_widget`
37
+ - Rust walks the Ruby object tree via `magnus::Value` and `funcall`
38
+ - Rust builds Ratatui widgets and renders them to the terminal buffer
39
+
40
+ ### 2. Single Generic Renderer
41
+
42
+ The backend implements one generic rendering function that accepts any Ruby `Value` and dispatches based on class name. There is no compile-time knowledge of Ruby types—everything is runtime reflection.
43
+
44
+ ```rust
45
+ // rendering.rs
46
+ pub fn render_widget(frame: &mut Frame, area: Rect, node: Value) -> Result<(), Error> {
47
+ let class_name: String = node.class().name()?.into_owned();
48
+
49
+ match class_name.as_str() {
50
+ "RatatuiRuby::Widgets::Paragraph" => paragraph::render(frame, area, node),
51
+ "RatatuiRuby::Widgets::Block" => block::render(frame, area, node),
52
+ "RatatuiRuby::Widgets::Table" => table::render(frame, area, node),
53
+ // ... etc
54
+ _ => Err(Error::new(
55
+ magnus::exception::type_error(),
56
+ format!("Unknown widget type: {}", class_name)
57
+ ))
58
+ }
59
+ }
60
+ ```
61
+
62
+ ### 3. No Custom Rust Structs for UI
63
+
64
+ Do not define Rust structs that mirror Ruby UI components. This would create synchronization problems when Ruby classes change.
65
+
66
+ **What We Do:**
67
+ ```rust
68
+ // Extract directly from Ruby object
69
+ let text: String = node.funcall("text", ())?;
70
+ let style_val: Value = node.funcall("style", ())?;
71
+ let style = parse_style(style_val)?;
72
+ ```
73
+
74
+ **What We Don't Do:**
75
+ ```rust
76
+ // NO: Rust struct mirroring Ruby
77
+ struct Paragraph {
78
+ text: String,
79
+ style: Option<Style>,
80
+ block: Option<Block>,
81
+ }
82
+ ```
83
+
84
+ ### 4. Immediate Mode Rendering
85
+
86
+ The renderer traverses the Ruby object tree every frame and rebuilds the Ratatui widget tree from scratch. No widget state persists between frames in Rust.
87
+
88
+ This mirrors Ratatui's own immediate mode paradigm. The Rust backend is stateless (except for terminal state).
89
+
90
+ ### 5. Memory Safety via Value Extraction
91
+
92
+ Ruby's GC can move or collect objects at any time. All data extracted from Ruby must be owned (copied) before use, never borrowed.
93
+
94
+ ```rust
95
+ // SAFE: Convert to owned String immediately
96
+ let text: String = node.funcall::<_, String>("text", ())?.into_owned();
97
+
98
+ // UNSAFE: Holding reference across GC-safe point
99
+ let text_ref: &str = node.funcall("text", ())?; // DON'T
100
+ do_something_that_might_gc();
101
+ use(text_ref); // CRASH: text_ref may be invalid
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Directory Structure
107
+
108
+ ```
109
+ ext/ratatui_ruby/src/
110
+ ├── lib.rs # Entry point, Ruby module registration
111
+ ├── terminal.rs # Global TERMINAL state, init/restore
112
+ ├── frame.rs # Frame wrapper for render_widget, area access
113
+ ├── events.rs # Event polling, crossterm -> Ruby conversion
114
+ ├── style.rs # Style/Color parsing from Ruby values
115
+ ├── text.rs # Span/Line parsing
116
+ ├── rendering.rs # Central dispatcher, class name -> widget module
117
+ └── widgets/ # Per-widget rendering modules
118
+ ├── mod.rs # Re-exports all widget modules
119
+ ├── paragraph.rs
120
+ ├── block.rs
121
+ ├── table.rs
122
+ ├── list.rs
123
+ ├── canvas.rs
124
+ └── ...
125
+ ```
126
+
127
+ ---
128
+
129
+ ## Module Responsibilities
130
+
131
+ ### `lib.rs` — Entry Point
132
+
133
+ Defines the Ruby module hierarchy using `magnus` and exports public functions (`init_terminal`, `restore_terminal`, `draw`, `poll_event`, `get_cell_at`).
134
+
135
+ ### `terminal.rs` — Terminal State
136
+
137
+ Manages the global `TERMINAL` singleton (mutex-wrapped `CrosstermBackend<Stdout>`).
138
+
139
+ Key functions:
140
+ - `init()` — Enter raw mode, enable mouse capture, switch to alternate screen
141
+ - `restore()` — Disable raw mode, restore main screen
142
+ - `get_cell_at(x, y)` — Return buffer cell as Ruby `Buffer::Cell` object
143
+
144
+ **Safety Note:** The terminal is a global mutable resource. All access goes through a mutex. Holding the lock across Ruby calls risks deadlock—release the lock before calling back into Ruby.
145
+
146
+ ### `frame.rs` — Frame Wrapper
147
+
148
+ Wraps Ratatui's `Frame` struct for safe Ruby access. The `Frame` reference is only valid inside the `draw` closure. The `FrameWrapper` tracks validity and raises `Safety` error if used after the closure returns.
149
+
150
+ ### `events.rs` — Event Conversion
151
+
152
+ Polls crossterm events and converts them to Ruby `Event::*` objects. Handles key, mouse, resize, paste, and focus events.
153
+
154
+ ### `style.rs` — Style Parsing
155
+
156
+ Pure functions for extracting style information from Ruby values. Handles `parse_style`, `parse_color` (symbols, integers 0-255, hex strings), and `parse_modifiers`.
157
+
158
+ ### `rendering.rs` — Central Dispatcher
159
+
160
+ The routing layer that maps Ruby class names to widget renderers:
161
+
162
+ ```rust
163
+ pub fn render_widget(frame: &mut Frame, area: Rect, node: Value) -> Result<(), Error> {
164
+ let class_name: String = node.class().name()?.into_owned();
165
+
166
+ match class_name.as_str() {
167
+ // Widgets module
168
+ "RatatuiRuby::Widgets::Paragraph" => widgets::paragraph::render(frame, area, node),
169
+ "RatatuiRuby::Widgets::Block" => widgets::block::render(frame, area, node),
170
+ "RatatuiRuby::Widgets::Table" => widgets::table::render(frame, area, node),
171
+ "RatatuiRuby::Widgets::List" => widgets::list::render(frame, area, node),
172
+ "RatatuiRuby::Widgets::Tabs" => widgets::tabs::render(frame, area, node),
173
+ "RatatuiRuby::Widgets::Gauge" => widgets::gauge::render(frame, area, node),
174
+ "RatatuiRuby::Widgets::Chart" => widgets::chart::render(frame, area, node),
175
+ "RatatuiRuby::Widgets::Canvas" => widgets::canvas::render(frame, area, node),
176
+ "RatatuiRuby::Widgets::Scrollbar" => widgets::scrollbar::render(frame, area, node),
177
+ "RatatuiRuby::Widgets::Calendar" => widgets::calendar::render(frame, area, node),
178
+ // ... all widgets
179
+
180
+ // Special widgets
181
+ "RatatuiRuby::Widgets::Clear" => widgets::clear::render(frame, area, node),
182
+ "RatatuiRuby::Widgets::Cursor" => widgets::cursor::render(frame, area, node),
183
+
184
+ // Custom widgets (Ruby escape hatch)
185
+ _ if has_render_method(node) => widgets::custom::render(frame, area, node),
186
+
187
+ _ => Err(Error::new(
188
+ magnus::exception::type_error(),
189
+ format!("Unknown widget type: {}", class_name)
190
+ ))
191
+ }
192
+ }
193
+ ```
194
+
195
+ **Namespace Pattern:** All built-in widgets use the `RatatuiRuby::Widgets::*` namespace. The dispatcher matches on full class names, not prefixes.
196
+
197
+ ### `widgets/*.rs` — Widget Renderers
198
+
199
+ Each widget has its own module with a standard interface:
200
+
201
+ ```rust
202
+ // widgets/paragraph.rs
203
+ pub fn render(frame: &mut Frame, area: Rect, node: Value) -> Result<(), Error> {
204
+ // 1. Extract properties from Ruby object
205
+ let text = parse_text(node.funcall("text", ())?)?;
206
+ let style = parse_style(node.funcall("style", ())?)?;
207
+ let alignment = parse_alignment(node.funcall("alignment", ())?)?;
208
+ let block_val: Value = node.funcall("block", ())?;
209
+
210
+ // 2. Build Ratatui widget
211
+ let mut paragraph = Paragraph::new(text)
212
+ .style(style)
213
+ .alignment(alignment);
214
+
215
+ // 3. Handle optional block wrapper
216
+ if !block_val.is_nil() {
217
+ paragraph = paragraph.block(parse_block(block_val)?);
218
+ }
219
+
220
+ // 4. Render
221
+ frame.render_widget(paragraph, area);
222
+ Ok(())
223
+ }
224
+ ```
225
+
226
+ ---
227
+
228
+ ## Adding a New Widget
229
+
230
+ ### Step 1: Create the Widget Module
231
+
232
+ ```rust
233
+ // src/widgets/my_widget.rs
234
+
235
+ use magnus::{Error, Value};
236
+ use ratatui::prelude::*;
237
+
238
+ use crate::style::parse_style;
239
+
240
+ pub fn render(frame: &mut Frame, area: Rect, node: Value) -> Result<(), Error> {
241
+ // Extract properties
242
+ let content: String = node.funcall::<_, String>("content", ())?.into_owned();
243
+ let style = parse_style(node.funcall("style", ())?)?;
244
+
245
+ // Build and render
246
+ let widget = MyWidget::new(content).style(style);
247
+ frame.render_widget(widget, area);
248
+
249
+ Ok(())
250
+ }
251
+ ```
252
+
253
+ ### Step 2: Register in `widgets/mod.rs`
254
+
255
+ ```rust
256
+ pub mod my_widget;
257
+ ```
258
+
259
+ ### Step 3: Add Dispatch Arm in `rendering.rs`
260
+
261
+ ```rust
262
+ "RatatuiRuby::Widgets::MyWidget" => widgets::my_widget::render(frame, area, node),
263
+ ```
264
+
265
+ ### Step 4: Test
266
+
267
+ Run `cargo test` for Rust unit tests, then `rake test` for Ruby integration tests.
268
+
269
+ ---
270
+
271
+ ## Stateful Widget Rendering
272
+
273
+ Some widgets (List, Table, Scrollbar) support stateful rendering where a mutable State object tracks scroll position and selection.
274
+
275
+ ### The Pattern
276
+
277
+ ```rust
278
+ pub fn render_stateful_widget(
279
+ frame: &mut Frame,
280
+ area: Rect,
281
+ widget_node: Value,
282
+ state_node: Value
283
+ ) -> Result<(), Error> {
284
+ // 1. Build the widget (immutable configuration)
285
+ let list = build_list(widget_node)?;
286
+
287
+ // 2. Extract mutable state
288
+ let mut state = ListState::default();
289
+ if let Ok(selected) = state_node.funcall::<_, Option<i64>>("selected", ()) {
290
+ state.select(selected.map(|i| i as usize));
291
+ }
292
+
293
+ // 3. Render with state (Ratatui may mutate offset)
294
+ frame.render_stateful_widget(list, area, &mut state);
295
+
296
+ // 4. Write computed values back to Ruby state object
297
+ state_node.funcall::<_, Value>("set_offset", (state.offset() as i64,))?;
298
+
299
+ Ok(())
300
+ }
301
+ ```
302
+
303
+ **State Precedence:** When using stateful rendering, the State object's values take precedence over Widget properties. This is documented in Ruby.
304
+
305
+ ---
306
+
307
+ ## Custom Widget Escape Hatch
308
+
309
+ Ruby users can define custom widgets that implement a `render(area)` method returning an array of `Draw` commands. The dispatcher detects a `render` method and calls it, processing the returned commands to manipulate the buffer directly. This is the "escape hatch" for functionality not yet wrapped by built-in widgets.
310
+
311
+ ---
312
+
313
+ ## Error Handling
314
+
315
+ All Rust functions that can fail return `Result<T, magnus::Error>`. Magnus automatically converts these to Ruby exceptions.
316
+
317
+ **Error Types:**
318
+
319
+ | Scenario | Ruby Exception | Notes |
320
+ |----------|---------------|-------|
321
+ | Invalid argument | `ArgumentError` | Wrong type, out of range |
322
+ | Unknown widget | `TypeError` | Class name not in dispatch table |
323
+ | Terminal not initialized | `RatatuiRuby::Error::Terminal` | Custom exception class |
324
+ | Frame used after draw block | `RatatuiRuby::Error::Safety` | Memory safety violation |
325
+
326
+ ---
327
+
328
+ ## Testing Strategy
329
+
330
+ ### Rust Unit Tests (`cargo test`)
331
+
332
+ Test pure parsing functions that don't require Ruby VM. Most tests require Ruby VM via magnus, which means they run in integration test style.
333
+
334
+ ### Ruby Integration Tests (`rake test`)
335
+
336
+ The primary testing strategy. Ruby tests exercise the full stack and verify end-to-end behavior without testing Rust internals.
337
+
338
+ ### Buffer Verification
339
+
340
+ For Rust-level rendering tests, use Ratatui's `TestBackend` or `Buffer` to assert cells are filled correctly.
341
+
342
+ ---
343
+
344
+ ## Performance Considerations
345
+
346
+ ### Avoid Repeated `funcall`
347
+
348
+ Each `funcall` crosses the Ruby/Rust boundary. Cache results when accessing the same property multiple times rather than calling `funcall` repeatedly.
349
+
350
+ ### String Ownership
351
+
352
+ Always convert to owned `String` immediately via `into_owned()` to avoid GC-related memory safety issues.
353
+
354
+ ### Batch Collection Iteration
355
+
356
+ When processing Ruby arrays, collect all values into a `Vec<Value>` before processing to avoid holding references across iterations.
@@ -126,14 +126,14 @@ sig/examples/
126
126
 
127
127
  2. **Use `RatatuiRuby.run` for terminal management.** Never call `init_terminal` or `restore_terminal` directly. The `run` block handles terminal setup/teardown automatically and safely, even if an exception occurs.
128
128
 
129
- 3. **Use the Session API (`tui`) for cleaner code.** Accept the `tui` block parameter from `RatatuiRuby.run` and use it throughout your app:
129
+ 3. **Use the TUI API (`tui`) for cleaner code.** Accept the `tui` block parameter from `RatatuiRuby.run` and use it throughout your app:
130
130
  - `@tui.draw { |frame| ... }` instead of `RatatuiRuby.draw`
131
131
  - `@tui.poll_event` instead of `RatatuiRuby.poll_event`
132
- - `@tui.style(...)` instead of `RatatuiRuby::Style.new(...)`
133
- - `@tui.paragraph(...)` instead of `RatatuiRuby::Paragraph.new(...)`
134
- - `@tui.block(...)` instead of `RatatuiRuby::Block.new(...)`
132
+ - `@tui.style(...)` instead of `RatatuiRuby::Style::Style.new(...)`
133
+ - `@tui.paragraph(...)` instead of `RatatuiRuby::Widgets::Paragraph.new(...)`
134
+ - `@tui.block(...)` instead of `RatatuiRuby::Widgets::Block.new(...)`
135
135
  - `@tui.layout_split(...)` instead of `RatatuiRuby::Layout.split(...)`
136
- - `@tui.constraint_fill(...)` instead of `RatatuiRuby::Constraint.fill(...)`
136
+ - `@tui.constraint_fill(...)` instead of `RatatuiRuby::Layout::Constraint.fill(...)`
137
137
  - `@tui.text_line(...)` instead of `RatatuiRuby::Text::Line.new(...)`
138
138
  - `@tui.text_span(...)` instead of `RatatuiRuby::Text::Span.new(...)`
139
139
 
@@ -7,13 +7,15 @@
7
7
 
8
8
  ## Documentation for Contributors
9
9
 
10
- - [Contributing Guidelines](https://man.sr.ht/~kerrick/ratatui_ruby/contributing.md)
11
- - [Documentation Guide](https://man.sr.ht/~kerrick/ratatui_ruby/documentation_guide.md)
12
- - [The Design of **ratatui_ruby**](./design.md)
10
+ - [Contributing Guidelines](https://man.sr.ht/~kerrick/ratatui_ruby/contributing.md): Issues, pull requests, and development setup
11
+ - [Documentation Guide](https://man.sr.ht/~kerrick/ratatui_ruby/documentation_guide.md): Where to document (RDoc, repo docs, wiki)
12
+ - [The Design of **ratatui_ruby**](./design.md): Architecture overview
13
+ - [Ruby Frontend Design](./design/ruby_frontend.md): Two-layer architecture, TUI facade, data-driven UI
14
+ - [Rust Backend Design](./design/rust_backend.md): Rendering pipeline, namespace dispatch, magnus integration
13
15
 
14
16
 
15
17
 
16
18
  ## Documentation for Users
17
19
 
18
- - [README](../../README.md)
19
- - [More Documentation for Users](../index.md)
20
+ - [README](../../README.md): Project overview and installation
21
+ - [More Documentation for Users](../index.md): Full user documentation index