### Run WidgetList Demo (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_list/app_rb Executes the WidgetList demonstration application from the terminal. This example requires Ruby and the ratatui_ruby gem to be installed. ```shell ruby examples/widget_list/app.rb ``` -------------------------------- ### Verify Quickstart Lifecycle with Ratatui Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/verify_quickstart_lifecycle/app_rb This Ruby code demonstrates the complete lifecycle of a Ratatui Ruby application. It initializes the terminal, enters a loop to draw a simple UI (a centered paragraph with borders), polls for user input (quitting on 'q' or Ctrl+C), and ensures the terminal is restored upon exit. It utilizes the `ratatui_ruby` gem. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "ratatui_ruby" class VerifyQuickstartLifecycle def run # [SYNC:START:main] # 1. Initialize the terminal RatatuiRuby.init_terminal begin # The Main Loop loop do # 2. Create your UI (Immediate Mode) # We define a Paragraph widget inside a Block with a title and borders. view = RatatuiRuby::Widgets::Paragraph.new( text: "Hello, Ratatui! Press 'q' to quit.", alignment: :center, block: RatatuiRuby::Widgets::Block.new( title: "My Ruby TUI App", title_alignment: :center, borders: [:all], border_style: { fg: "cyan" }, style: { fg: "white" } ) ) # 3. Draw the UI RatatuiRuby.draw do |frame| frame.render_widget(view, frame.area) end # 4. Poll for events case RatatuiRuby.poll_event in { type: :key, code: "q" } | { type: :key, code: "c", modifiers: ["ctrl"] } break else nil end # 5. Guard against accidental output (optional but recommended) # Wrap any code that might puts/warn to prevent screen corruption. RatatuiRuby.guard_io do # SomeChattyGem.do_something end end ensure # 6. Restore the terminal to its original state RatatuiRuby.restore_terminal end # [SYNC:END:main] end end VerifyQuickstartLifecycle.new.run if __FILE__ == $PROGRAM_NAME ``` -------------------------------- ### Example of Testing Rust Panic in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Debug Provides an example command to trigger a Rust panic and verify Rust backtrace setup by running a Ruby script with the `RUST_BACKTRACE=1` environment variable. ```shell RUST_BACKTRACE=1 ruby -e 'require "ratatui_ruby"; RatatuiRuby::Debug.test_panic!' ``` -------------------------------- ### Run WidgetBlock Demo (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_block/app_rb This command executes the WidgetBlock demonstration application using Ruby. It requires the Ratatui Ruby library to be installed. ```shell ruby examples/widget_block/app.rb ``` -------------------------------- ### Run WidgetBarchart Demo (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_barchart/app_rb This command executes the WidgetBarchart demo application from the terminal. It requires a Ruby environment and the ratatui_ruby gem to be installed. ```shell ruby examples/widget_barchart/app.rb ``` -------------------------------- ### Run Ratatui Ruby TUI Application with DSL Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/verify_quickstart_dsl/app_rb This Ruby code initializes the terminal, enters a run loop, and draws a simple paragraph widget with a bordered block. It listens for the 'q' key press to exit the application. Dependencies include the 'ratatui_ruby' gem. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "ratatui_ruby" class VerifyQuickstartDsl def run # [SYNC:START:main] # 1. Initialize the terminal, start the run loop, and ensure the terminal is restored. RatatuiRuby.run do |tui| loop do # 2. Create your UI with methods instead of classes. view = tui.paragraph( text: "Hello, Ratatui! Press 'q' to quit.", alignment: :center, block: tui.block( title: "My Ruby TUI App", title_alignment: :center, borders: [:all], border_style: { fg: "cyan" }, style: { fg: "white" } ) ) # 3. Use RatatuiRuby methods, too. tui.draw do |frame| frame.render_widget(view, frame.area) end # 4. Poll for events with pattern matching case tui.poll_event in { type: :key, code: "q" } break else # Ignore other events end end end # [SYNC:END:main] end end VerifyQuickstartDsl.new.run if __FILE__ == $PROGRAM_NAME ``` -------------------------------- ### Run Ratatui Layout with Vertical Split in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/verify_quickstart_layout/app_rb This Ruby code demonstrates how to initialize Ratatui, split the terminal vertically into two sections, and render a paragraph widget in the top section and another styled paragraph in the bottom section. It also includes a basic event loop to handle quitting the application. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "ratatui_ruby" class VerifyQuickstartLayout def run RatatuiRuby.run do |tui| # [SYNC:START:main] loop do tui.draw do |frame| # 1. Split the screen top, bottom = tui.layout_split( frame.area, direction: :vertical, constraints: [ tui.constraint_percentage(75), tui.constraint_percentage(25), ] ) # 2. Render Top Widget frame.render_widget( tui.paragraph( text: "Hello, Ratatui!", alignment: :center, block: tui.block(title: "Content", borders: [:all], border_style: { fg: "cyan" }) ), top ) # 3. Render Bottom Widget with Styled Text # We use a Line of Spans to style specific characters text_line = tui.text_line( spans: [ tui.text_span(content: "Press '\"), tui.text_span( content: "q", style: tui.style(modifiers: [:bold, :underlined]) ), tui.text_span(content: "' to quit.") ], alignment: :center ) frame.render_widget( tui.paragraph( text: text_line, block: tui.block(title: "Controls", borders: [:all]) ), bottom ) end case tui.poll_event in { type: :key, code: "q" } break else # Ignore other events end end # [SYNC:END:main] end end end VerifyQuickstartLayout.new.run if __FILE__ == $PROGRAM_NAME ``` -------------------------------- ### Run WidgetLayoutSplit Demo (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_layout_split/app_rb This snippet shows how to execute the WidgetLayoutSplit demo application from the terminal. It requires Ruby and the ratatui_ruby gem to be installed. ```shell ruby examples/widget_layout_split/app.rb ``` -------------------------------- ### Run WidgetChart Demo (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_chart/app_rb This snippet shows how to execute the WidgetChart demo application from the terminal. It requires a Ruby environment and the ratatui_ruby gem to be installed. ```shell ruby examples/widget_chart/app.rb ``` -------------------------------- ### Style Examples using Style.with Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Style/Style Illustrates practical usage of the `Style.with` method for applying various combinations of foreground, background, underline colors, and text modifiers. Includes an example of applying a style to a Paragraph widget. ```ruby Style.with(fg: :red, bg: :black, modifiers: [:bold]) Style.with(fg: :white, modifiers: [:underlined], underline_color: :red) Style.with(modifiers: [:bold], remove_modifiers: [:italic]) # Add bold, remove italic paragraph = Paragraph.new(text: "Alert!", style: Style.with(fg: :red)) ``` -------------------------------- ### Run LineGauge Widget Demo (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_line_gauge/app_rb Executes the `LineGauge` widget demonstration application. This example showcases how to use the `LineGauge` widget for compact status visualization and interactive attribute cycling. It requires the `ratatui_ruby` gem to be installed. ```shell ruby examples/widget_line_gauge/app.rb ``` -------------------------------- ### Ruby Quickstart DSL Verification with RatatuiRuby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/verify_quickstart_dsl/README_md This Ruby code snippet demonstrates the Quickstart DSL for Ratatui Ruby. It initializes the terminal, creates a UI with a paragraph and a block, draws the UI to the frame, and polls for key events to exit the application. It relies on the RatatuiRuby gem. ```ruby # 1. Initialize the terminal, start the run loop, and ensure the terminal is restored. RatatuiRuby.run do |tui| loop do # 2. Create your UI with methods instead of classes. view = tui.paragraph( text: "Hello, Ratatui! Press 'q' to quit.", alignment: :center, block: tui.block( title: "My Ruby TUI App", title_alignment: :center, borders: [:all], border_color: "cyan", style: { fg: "white" } ) ) # 3. Use RatatuiRuby methods, too. tui.draw do |frame| frame.render_widget(view, frame.area) end # 4. Poll for events with pattern matching case tui.poll_event in { type: :key, code: "q" } break else # Ignore other events end end end ``` -------------------------------- ### Ruby Quickstart Lifecycle Verification with Ratatui Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/verify_quickstart_lifecycle/README_md Demonstrates the core lifecycle of a Ratatui Ruby application, including terminal initialization, UI creation, drawing, event polling, and terminal restoration. It uses RatatuiRuby widgets like Paragraph and Block. Ensure Ratatui Ruby is installed. ```ruby # 1. Initialize the terminal RatatuiRuby.init_terminal begin # The Main Loop loop do # 2. Create your UI (Immediate Mode) # We define a Paragraph widget inside a Block with a title and borders. view = RatatuiRuby::Widgets::Paragraph.new( text: "Hello, Ratatui! Press 'q' to quit.", alignment: :center, block: RatatuiRuby::Widgets::Block.new( title: "My Ruby TUI App", title_alignment: :center, borders: [:all], border_color: "cyan", style: { fg: "white" } ) ) # 3. Draw the UI RatatuiRuby.draw do |frame| frame.render_widget(view, frame.area) end # 4. Poll for events case RatatuiRuby.poll_event in { type: :key, code: "q" } | { type: :key, code: "c", modifiers: ["ctrl"] } break else nil end # 5. Guard against accidental output (optional but recommended) # Wrap any code that might puts/warn to prevent screen corruption. RatatuiRuby.guard_io do # SomeChattyGem.do_something end end ensure # 6. Restore the terminal to its original state RatatuiRuby.restore_terminal end ``` -------------------------------- ### Run AppAllEvents Example Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/app_all_events/app_rb Command-line instruction to execute the AppAllEvents example script. This is typically run from the project's root directory. ```shell # Run from the command line: # ruby examples/app_all_events/app.rb app = AppAllEvents.new app.run ``` -------------------------------- ### Run Ratatui Application in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_table/app_rb Starts the Ratatui application using RatatuiRuby.run. It sets up styles, enters a drawing loop, renders the UI, and handles input until the user quits. ```ruby def run RatatuiRuby.run do |tui| @tui = tui setup_styles loop do @tui.draw do |frame| render(frame) end break if handle_input == :quit end end end ``` -------------------------------- ### WidgetOverlay Example in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_overlay/app_rb Demonstrates the Overlay widget for layering widgets with depth. This example uses a predefined list of headlines and requires the 'ratatui_ruby' gem. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "ratatui_ruby" HEADLINES = [ "Scientists Discover New Species of Deep-Sea Octopus Near Hawaii", "Global Climate Summit Reaches Historic Agreement on Emissions", "Tech Giant Announces Breakthrough in Quantum Computing Research", "Local Community Garden Initiative Expands to Ten More Cities", "Astronomers Detect Unusual Radio Signals from Distant Galaxy", "New Study Links Mediterranean Diet to Improved Heart Health", "Electric Vehicle Sales Surge as Battery Technology Improves", "Ancient Manuscripts Reveal Previously Unknown Trading Routes", "Renewable Energy Now Powers 40% of National Grid", "Robotics Team Develops AI System for Disaster Response", "Archaeological Dig Uncovers Evidence of Early Human Settlement", "Major Airline Commits to Carbon-Neutral Flights by 2035", "Breakthrough Treatment Shows Promise for Rare Genetic Disease", "City Council Approves Expanded Public Transportation Network", "Marine Biologists Track Migration Patterns of Endangered Whales", "New App Helps Farmers Optimize Water Usage During Drought", "International Space Station Extends Mission Timeline to 2030", "Local Schools Implement Innovative STEM Education Program", "Wildlife Conservation Efforts Lead to Species Population Recovery", "Research Team Creates Biodegradable Alternative to Plastic Packaging", "Historic Theater Restoration Project Nears Completion", "Cybersecurity Experts Warn of Emerging Online Threats", "Community Food Bank Serves Record Number of Families This Year", "Innovative Urban Planning Reduces Traffic Congestion by 30%", ].freeze # Overlay Example ``` -------------------------------- ### Ruby Radio Menu Example Source: https://www.ratatui-ruby.dev/docs/v1.3/README_rdoc A simple Ruby example demonstrating how to create a radio menu and capture user choice. This snippet shows basic state management for the selected choice. ```ruby def prefix_for(choice_index) return PREFIXES[:active] if choice_index == @choice PREFIXES[:inactive] end def initialize = @choice = 0 end choice = RadioMenu.new.call puts "You chose #{choice}!" ``` -------------------------------- ### Run RatatuiRuby Debugging Example Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/app_debugging_showcase/app_rb Demonstrates how to run the RatatuiRuby debugging example in different modes: normal, with Rust backtraces, and with full debug mode enabled for remote attachment. ```shell # Normal mode (no backtraces): ruby examples/verify_debugging_usage/app.rb # With Rust backtraces only: RUST_BACKTRACE=1 ruby examples/verify_debugging_usage/app.rb # Full debug mode (stops at startup for debugger attachment): RR_DEBUG=1 ruby examples/verify_debugging_usage/app.rb ``` -------------------------------- ### Example Usage of supports_keyboard_enhancement? Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Terminal/Capabilities This example demonstrates how to enable Vim-style keybindings if the terminal supports keyboard enhancements, or fall back to simpler navigation otherwise. This allows for more sophisticated input handling when available. ```ruby if RatatuiRuby::Terminal.supports_keyboard_enhancement? enable_vim_style_keybindings else use_simple_navigation end ``` -------------------------------- ### Run WidgetScrollbar Demo (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_scrollbar/app_rb Executes the WidgetScrollbar demonstration application from the terminal. This example requires the ratatui_ruby gem to be installed. ```shell ruby examples/widget_scrollbar/app.rb ``` -------------------------------- ### Method and Attribute Documentation Example (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/doc/contributors/documentation_style_md Shows the correct way to document attributes and methods in Ruby using RDoc. It includes concise attribute descriptions and a properly formatted `initialize` method with parameter documentation. ```ruby # The styling to apply to the content. attr_reader :style # Creates a new List. # # [items] Array of Strings. # [selected_index] Integer (nullable). def initialize(items: [], selected_index: nil) super end ``` -------------------------------- ### Example Usage of tty? Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Terminal/Capabilities An example illustrating how to conditionally start the TUI if the output is a TTY, or print plain text output if it's redirected. This prevents garbled output when TUI escape codes are sent to non-terminal destinations. ```ruby if RatatuiRuby::Terminal.tty? start_tui else print_plain_output end ``` -------------------------------- ### WidgetTabs Example Implementation (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_tabs/app_rb The source code for the WidgetTabs demo, demonstrating view segregation with interactive tab navigation using Ratatui Ruby's Tabs widget. It includes setup for the terminal application and Faker for data generation. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "ratatui_ruby" require "faker" # Demonstrates view segregation with interactive tab navigation. # # Screen real estate is limited. You cannot show everything at once. Segregating content into views is necessary for complex apps. # # This demo showcases the Tabs widget. It provides an interactive playground where you can select tabs, cycle through dividers and styles, and adjust padding in real-time. # # Use it to understand how to build major mode switches or context navigation for your interface. # # === Example # # Run the demo from the terminal: # # ruby examples/widget_tabs/app.rb # ``` -------------------------------- ### WidgetChart Example Implementation (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_chart/app_rb This Ruby code demonstrates the usage of the Ratatui Ruby Chart widget for visualizing Cartesian data. It includes setup for the widget and interactive elements to control chart attributes like marker types, axis alignments, and legend positions. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "ratatui_ruby" # Demonstrates Cartesian plotting attributes with interactive cycling. # # Trends and patterns are invisible in raw logs. You need to see the shape of the data to understand the story it tells. # # This demo showcases the Chart widget. It provides an interactive playground where you can toggle marker types, axis alignments, and legend positions in real-time. # # Use it to understand how to visualize complex X/Y datasets and trends efficiently. # # === Example # # Run the demo from the terminal: # # ruby examples/widget_chart/app.rb # ``` -------------------------------- ### Initialize WidgetList with Example Data (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_list/app_rb Initializes the WidgetList demo with predefined item sets, highlight symbols, and configuration options for direction, highlight spacing, repeat modes, scroll padding, and offset modes. It uses Faker for generating color and fruit data. ```ruby class WidgetList # Initializes the demo with example data and default configuration. def initialize Faker::Config.random = Random.new(12345) @selected_index = 6 # Start at C# to avoid highlighting the rich text examples @tui_for_setup = nil @item_sets = [ { name: "Programming", items: [ :ruby_styled, # Will be replaced with rich text in run() :rust_styled, # Will be replaced with rich text in run() :python_styled, # Will be replaced with rich text in run() :javascript_styled, # Will be replaced with rich text in run() "Go", "C++", "C#", "Java", "Kotlin", "Swift", "Objective-C", "PHP", "TypeScript", "Perl", "Lua", "R", "Scala", "Haskell", "Elixir", "Clojure", "Groovy", "Closure", "VB.NET", "F#", "Erlang", "Lisp", "Scheme", "Prolog", "Fortran", "COBOL", "Pascal", "Delphi", "Ada", "Bash", "Sh", "Tcl", "Awk", "sed", "Vim Script", "PowerShell", "Batch", "Assembly", "Wasm", "WebAssembly", "Julia", "Matlab", "Octave", "BASIC", ], }, { name: "Large List", items: (1..200).map { |i| "Item #{i}" }, }, { name: "Colors", items: begin Faker::Color.unique.clear Array.new(100) { Faker::Color.color_name } end, }, { name: "Fruits", items: begin Faker::Food.unique.clear Array.new(100) { Faker::Food.fruits } end, }, ] @item_set_index = 0 @highlight_symbol_names = [">> ", "▶ ", "→ ", "• ", "★ "] @highlight_symbol_index = 0 @direction_configs = [ { name: "Top to Bottom", direction: :top_to_bottom }, { name: "Bottom to Top", direction: :bottom_to_top }, ] @direction_index = 0 @highlight_spacing_configs = [ { name: "When Selected", spacing: :when_selected }, { name: "Always", spacing: :always }, { name: "Never", spacing: :never }, ] @highlight_spacing_index = 1 @repeat_modes = [ { name: "Off", repeat: false }, { name: "On", repeat: true }, ] @repeat_index = 0 @scroll_padding_configs = [ { name: "None", padding: nil }, { name: "1 item", padding: 1 }, { name: "2 items", padding: 2 }, ] @scroll_padding_index = 1 # Offset mode configurations to demonstrate offset + selection interaction @offset_modes = [ { name: "Auto (No Offset)", offset: nil, allow_selection: true }, { name: "Offset Only", offset: 10, allow_selection: false }, { name: "Selection + Offset (Conflict)", offset: 0, allow_selection: true }, ] @offset_mode_index = 0 end end ``` -------------------------------- ### Class Documentation - Good Example (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/doc/contributors/documentation_style_md Illustrates the recommended Alexandrian, Zinsser, and Plain Language approach for documenting a Ruby class. It clearly states the problem and how the widget provides a solution. ```ruby # Displays a selectable list of items. # # Users need to choose from options. Menus, file explorers, and selectors are everywhere. # Implementing navigation, highlighting, and scrolling state from scratch is tedious. # # This widget manages the list. It renders the items. It highlights the selection. It handles the scrolling window. # # Use it to build main menus, navigation sidebars, or logs. ``` -------------------------------- ### Full-Screen Application with Ratatui-Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/README_rdoc Illustrates building a full-screen TUI application with Ratatui-Ruby. It includes a managed loop that sets up and restores the terminal, handling keyboard input for exiting the application. The example renders a centered 'Hello, RatatuiRuby!' message. ```ruby RatatuiRuby.run do |tui| loop do tui.draw do |frame| frame.render_widget( tui.paragraph(text: "Hello, RatatuiRuby!", alignment: :center), frame.area ) end case tui.poll_event in { type: :key, code: "q" } then break else nil end end end ``` -------------------------------- ### Example Usage of Window Size (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Backend Demonstrates how to use the `window_size` method to retrieve and display the terminal's character and pixel dimensions. It checks if the `WindowSize` object is successfully obtained before accessing its properties. ```ruby ws = RatatuiRuby::Backend.window_size if ws puts "#{ws.columns_rows.width}x#{ws.columns_rows.height} chars" puts "#{ws.pixels.width}x#{ws.pixels.height} pixels" end ``` -------------------------------- ### WidgetTable Source Code (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_table/app_rb This Ruby code snippet represents the source code for the WidgetTable component. It includes necessary setup for the Ratatui Ruby library and Bundler. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "bundler/setup" require "ratatui_ruby" ``` -------------------------------- ### Key Event Examples Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Event/Key Demonstrates various ways to use the `RatatuiRuby::Event::Key` class for handling keyboard input. ```APIDOC ## Examples ### Using predicates ```ruby if event.key? && event.ctrl? && event.code == "c" exit end ``` ### Using symbol comparison ```ruby if event == :ctrl_c exit end ``` ### Using pattern matching ```ruby case event when type: :key, code: "c", modifiers: ["ctrl"] exit end ``` ### Accessing Attributes ```ruby puts event.code # => "enter" event.kind # => :media puts event.modifiers # => ["ctrl", "shift"] ``` ### Pattern Matching with `deconstruct_keys` ```ruby case event when type: :key, code: "c", modifiers: ["ctrl"] puts "Ctrl+C pressed" when type: :key, kind: :media puts "Media key pressed" end ``` ``` -------------------------------- ### Programmatic Debug Activation Examples in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Debug Demonstrates how to programmatically enable debug mode in Ratatui Ruby using either the direct method or a convenience alias. ```ruby # Programmatic activation RatatuiRuby::Debug.enable! # Or use the convenience alias RatatuiRuby.debug_mode! ``` -------------------------------- ### Getting Terminal Area with RatatuiRuby::Frame#area Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Frame Retrieves the full terminal area as a Rect object. This Rect represents the entire drawable area of the terminal and is used as the starting point for layout calculations. ```ruby RatatuiRuby.draw do |frame| puts "Terminal size: #{frame.area.width}x#{frame.area.height}" end ``` -------------------------------- ### Running the Color Picker Application in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/app_color_picker/README_md Provides the command to execute the Color Picker example application. This application allows users to input color codes and see generated palettes. ```bash ruby examples/app_color_picker/app.rb ``` -------------------------------- ### Get Current Data for Bar Chart in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_barchart/app_rb Provides different datasets for the bar chart based on the current data index. Supports simple hash data, arrays with styles, and grouped data structures. ```ruby private def current_data case @data_index when 0 # Simple Hash { "Q1" => 50, "Q2" => 80, "Q3" => 45, "Q4" => 60, "Q1'" => 55, "Q2'" => 85, "Q3'" => 50, "Q4'" => 65, } when 1 # Array with styles [ ["Mon", 120], ["Tue", 150], ["Wed", 130], ["Thu", 160], ["Fri", 140], ["Sat", 110, @tui.style(fg: :red)], ["Sun", 100, @tui.style(fg: :red)], ] when 2 # Groups [ @tui.bar_chart_bar_group(label: "2024", bars: [ @tui.bar_chart_bar(value: 40, label: "Q1"), @tui.bar_chart_bar(value: 45, label: "Q2"), @tui.bar_chart_bar(value: 50, label: "Q3"), @tui.bar_chart_bar(value: 55, label: "Q4"), ]), @tui.bar_chart_bar_group(label: "2025", bars: [ @tui.bar_chart_bar(value: 60, label: "Q1", style: @tui.style(fg: :yellow)), @tui.bar_chart_bar(value: 65, label: "Q2", style: @tui.style(fg: :yellow)), @tui.bar_chart_bar(value: 70, label: "Q3", style: @tui.style(fg: :yellow)), @tui.bar_chart_bar(value: 75, label: "Q4", style: @tui.style(fg: :yellow)), ]), ] end end ``` -------------------------------- ### Run Ratatui Application Entry Point in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_list/app_rb Defines the main entry point for the Ratatui application. It instantiates and runs the WidgetList when the script is executed directly. This is a standard Ruby idiom for script execution. ```ruby WidgetList.new.run if __FILE__ == $PROGRAM_NAME ``` -------------------------------- ### Setup Styles for Ratatui Table in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_table/app_rb Defines various styles for the Ratatui UI, including text colors, backgrounds, and modifiers like bold. These styles are used for highlighting rows, cells, and hotkeys. ```ruby private def setup_styles @styles = [ { name: "Cyan", style: @tui.style(fg: :cyan) }, { name: "Red", style: @tui.style(fg: :red) }, { name: "Green", style: @tui.style(fg: :green) }, { name: "Blue on White", style: @tui.style(fg: :blue, bg: :white) }, { name: "Magenta", style: @tui.style(fg: :magenta, modifiers: [:bold]) }, ] @column_highlight_style = @tui.style(fg: :red) @cell_highlight_style = @tui.style(fg: :white, bg: :red, modifiers: [:bold]) @hotkey_style = @tui.style(modifiers: [:bold, :underlined]) end ``` -------------------------------- ### RatatuiMascot Widget Implementation in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_ratatui_mascot/app_rb Implements the RatatuiMascot widget for a Ruby terminal application. It includes setup for the TUI, layout management, widget rendering, and input handling for toggling the mascot's block and quitting. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: MIT-0 #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "ratatui_ruby" # Demonstrates personality and charm with the project mascot. # # Interfaces without personality feel clinical and dry. Users appreciate a friendly face in their terminal. # # This demo showcases the RatatuiMascot widget. It provides an interactive playground where you can toggle the surrounding block. # # Use it to understand how to add a playful touch to your terminal dashboards or about screens. # # === Example # # Run the demo from the terminal: # # ruby examples/widget_ratatui_mascot/app.rb # # rdoc-image:/doc/images/widget_ratatui_mascot.png class WidgetRatatuiMascot def initialize @show_block = true end def run RatatuiRuby.run do |tui| loop do tui.draw do |frame| # Layout: Top (Mascot), Bottom (Controls) layout = tui.layout_split( frame.area, direction: :vertical, constraints: [ tui.constraint_fill(1), tui.constraint_length(4), ] ) mascot_area = layout[0] controls_area = layout[1] # Mascot Widget block = if @show_block tui.block( title: "Ratatui Mascot", borders: [:all], border_type: :rounded, border_style: { fg: :green } ) end mascot = tui.ratatui_mascot(block: block) frame.render_widget(mascot, mascot_area) # Controls controls_text = [ tui.text_span(content: "q", style: tui.style(modifiers: [:bold, :underlined])), tui.text_span(content: " Quit"), tui.text_span(content: " "), tui.text_span(content: "b", style: tui.style(modifiers: [:bold, :underlined])), tui.text_span(content: " Toggle Block #{@show_block ? '(On)' : '(Off)'}"), ] controls_paragraph = tui.paragraph( text: tui.text_line(spans: controls_text), block: tui.block(borders: [:top], title: "Controls") ) frame.render_widget(controls_paragraph, controls_area) end break if handle_input(tui) == :quit end end end private def handle_input(tui) event = tui.poll_event if event.key? case event.char when "q" then :quit when "b" then @show_block = !@show_block end elsif event.ctrl_c? :quit end end end WidgetRatatuiMascot.new.run if __FILE__ == $PROGRAM_NAME ``` -------------------------------- ### Run AppColorPicker Application (Ruby) Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/app_color_picker/app_rb This snippet demonstrates how to instantiate and run the AppColorPicker application. It initializes the Ratatui Ruby terminal, creates the main container, and enters an event loop to handle user input and rendering. The application quits when 'q', 'esc', or Ctrl+C is pressed. ```ruby # frozen_string_literal: true #-- # SPDX-FileCopyrightText: 2026 Kerrick Long # SPDX-License-Identifier: AGPL-3.0-or-later #++ $LOAD_PATH.unshift File.expand_path("../../lib", __dir__) $LOAD_PATH.unshift File.expand_path(__dir__) require "ratatui_ruby" require_relative "main_container" # A terminal-based color picker application. # # Terminal users often need to select colors for themes or UI components. # Manually typing hex codes and guessing how they will look is slow and error-prone. # # This application solves the problem by providing an interactive interface. It parses hex strings, # generates palettes, and displays them visually in the terminal. # # === Architecture # # This example uses a Component-Based pattern: # - **Components**: Self-contained UI elements with `render`, `handle_event`, and optional `tick` # - **Container**: Owns layout, delegates to children, routes events via Chain of Responsibility # - **Mediator**: Container interprets symbolic signals (`:consumed`, `:submitted`) for cross-component effects # # === Examples # # AppColorPicker.new.run # class AppColorPicker # Creates a new AppColorPicker instance. def initialize @container = nil end # Starts the terminal session and enters the main event loop. # # This method initializes the terminal, creates the MainContainer, and runs # the event loop until the user quits. # # === Example # # app = AppColorPicker.new # app.run # def run RatatuiRuby.run do |tui| @container = MainContainer.new(tui) loop do @container.tick tui.draw { |frame| @container.render(tui, frame, frame.area) } event = tui.poll_event break if quit_event?(event) @container.handle_event(event) end end end private def quit_event?(event) case event in { type: :key, code: "q" } | { type: :key, code: "esc" } | { type: :key, code: "c", modifiers: [/ctrl/]} true else false end end end AppColorPicker.new.run if __FILE__ == $PROGRAM_NAME ``` -------------------------------- ### Radio Menu Interaction Example Source: https://www.ratatui-ruby.dev/docs/v1.3/lib/ratatui_ruby/table_state_rb A simple Ruby code snippet demonstrating user interaction with a radio menu. It defines a method to determine the prefix for a choice based on its selection state and then calls a `RadioMenu` to get the user's choice. ```ruby def prefix_for(choice_index) # implement the logic yourself. For larger return PREFIXES[:active] if choice_index == @choice # applications, consider using Rooibos, PREFIXES[:inactive] # an MVU framework built with RatatuiRuby. end # Or, use the upcoming ratatui-ruby-kit, # our object-oriented component library. def initialize = @choice = 0 # However, those are both optional, and end # designed for full-screen Terminal UIs. # RatatuiRuby will always give you the most choice = RadioMenu.new.call # control, and is enough for "rich CLI puts "You chose #{choice}!" # moments" like this one. ``` -------------------------------- ### Run TUI Application Lifecycle in Ratatui Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/TerminalLifecycle Starts the TUI application lifecycle, managing terminal setup and teardown. It initializes the terminal, yields a TUI object, and ensures the terminal state is restored even if exceptions occur. This method raises an error if headless mode is enabled. ```ruby # File lib/ratatui_ruby/terminal_lifecycle.rb, line 147 def run(focus_events: true, bracketed_paste: true, viewport: nil, height: nil) init_terminal(focus_events:, bracketed_paste:, viewport:, height:) yield TUI.new ensure restore_terminal end ``` ```ruby RatatuiRuby.run(focus_events: false) do |tui| tui.draw(tui.paragraph(text: "Hi")) sleep 1 end ``` -------------------------------- ### Clear Widget: Initialize and Example Usage Source: https://www.ratatui-ruby.dev/docs/v1.3/RatatuiRuby/Widgets/Clear Demonstrates how to initialize the Clear widget and provides an example of its usage within an Overlay stack for creating opaque popups. It also shows a shortcut for rendering a block directly with the Clear widget. ```ruby # Opaque Popup Construction Overlay.new( layers: [ MainUI.new, Center.new( child: Overlay.new( layers: [ Clear.new, # Wipe the area first Block.new(title: "Modal", borders: [:all]) ] ), width_percent: 50, height_percent: 50 ) ] ) # Shortcut: rendering a block directly Clear.new(block: Block.new(title: "Cleared area", borders: [:all])) ``` ```ruby # File lib/ratatui_ruby/widgets/clear.rb, line 61 def initialize(block: nil) super end ``` -------------------------------- ### Get Current Table Rows in Ratatui Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/app_stateful_interaction/app_rb The `current_table_rows` method in Ruby retrieves the data rows for the currently selected item in the list, which corresponds to the data for the active table in the Ratatui TUI. It uses the selected index from `@list_state` to access the correct data from `@data`. ```ruby private def current_table_rows @data[@tables[@list_state.selected || 0]] end ``` -------------------------------- ### Implement Tabbed Widget with Ratatui in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/widget_tabs/app_rb This Ruby code defines a `WidgetTabs` class that utilizes the Ratatui library to create a functional tabbed interface. It handles user input for navigating between tabs and displays the content associated with each tab. The code assumes the Ratatui library is installed and available. ```ruby require 'ratatui' class WidgetTabs def initialize @tui = Ratatui::Tui.new @tabs = ['Tab 1', 'Tab 2', 'Tab 3'] @tab_text = { 'Tab 1' => 'Content for the first tab.', 'Tab 2' => 'More detailed information for the second tab.', 'Tab 3' => 'Final content for the third and last tab.' } @selected_tab = 0 end def run @tui.enter_alternate_screen loop do @tui.draw do |frame| render(frame) end event = @tui.next_event handle_event(event) break if event == :quit end ensure @tui.exit_alternate_screen end private def render(frame) widget = Ratatui::Widgets::Tabs.new(@tabs) .select(@selected_tab) .divider("|") frame.buffer.set_string([0, 0], widget.render) frame.buffer.set_string([1, 0], tab_contents.render) end def handle_event(event) case event when :left @selected_tab = (@selected_tab - 1) % @tabs.length when :right @selected_tab = (@selected_tab + 1) % @tabs.length when Ratatui::Events::KeyEvent.new(code: :quit) return :quit when Ratatui::Events::KeyEvent.new(code: :down) @padding_right += 1 else # Ignore other events end end private def tab_contents @tui.paragraph( text: @tab_text[@tabs[@selected_tab]], wrap: true, block: @tui.block(borders: [:all], title: @tabs[@selected_tab]) ) end end WidgetTabs.new.run if __FILE__ == $0 ``` -------------------------------- ### Run TUI with Interactive Debugger Breakpoint in Ruby Source: https://www.ratatui-ruby.dev/docs/v1.3/examples/app_debugging_showcase/app_rb Starts the Ratatui Ruby TUI loop. It includes a conditional breakpoint that triggers every 250 loops when debug mode is enabled, allowing inspection of variables like `@status_message` using the `debugger` command. The loop continues until the quit condition is met. ```ruby def run RatatuiRuby.run do |tui| @tui = tui @loop_count = 0 loop do @loop_count += 1 # 🎯 Breakpoint every 250 loops. Try: p @status_message if RatatuiRuby::Debug.enabled? && (@loop_count % 250).zero? you_found_me = "🎉 You found me! Loop ##{@loop_count}" # rubocop:disable Lint/Debugger debugger # rubocop:enable Lint/Debugger _ = you_found_me # Suppress unused variable warning end render break if @quit || handle_input == :quit end end end ``` -------------------------------- ### Ruby Terminal Integration Demo Source: https://www.ratatui-ruby.dev/docs/v1.3/doc/contributors/todo/align/terminal_md An example demonstrating the direct usage of the Ratatui Ruby Terminal instance for creating an inline viewport, displaying information, and handling user input. ```ruby # examples/terminal_instance_demo.rb require "ratatui_ruby" # API 3: Direct Terminal instance terminal = RatatuiRuby::Terminal.new(viewport: :inline, height: 10) terminal.draw do |frame| info = <<~INFO Terminal Information: - Type: #{terminal.viewport_type} - Size: #{terminal.width}x#{terminal.height} Press 'q' to quit INFO paragraph = RatatuiRuby::Widgets::Paragraph.new(text: info) frame.render_widget(paragraph, frame.area) end # Insert log above viewport terminal.insert_before(1, RatatuiRuby::Widgets::Paragraph.new(text: "[LOG] Started")) loop do event = terminal.poll_event break if event.key? && event.code == "q" end terminal.restore ```