### Implement and Execute Commands with Flatscrew Latte Source: https://context7.com/flatscrew/latte/llms.txt Demonstrates how to define and execute asynchronous commands using the Flatscrew Latte Command interface. Includes examples of timer commands, batching commands for parallel execution, sequencing commands for serial execution, and implementing custom commands for fetching data. Commands return Messages to be processed. ```java import org.flatscrew.latte.Command; import org.flatscrew.latte.Message; import java.time.Duration; import java.time.LocalDateTime; import java.util.concurrent.CompletableFuture; // Timer command example public class TickMessage implements Message { private final LocalDateTime time; public TickMessage(LocalDateTime time) { this.time = time; } public LocalDateTime getTime() { return time; } } // Using built-in command utilities Command tickCommand = Command.tick( Duration.ofSeconds(1), time -> new TickMessage(time) ); // Batch commands (execute in parallel) Command batchCmd = Command.batch( Command.checkWindowSize(), Command.println("Starting application..."), tickCommand ); // Sequence commands (execute serially) Command sequenceCmd = Command.sequence( Command.clearScreen(), Command.setWidowTitle("My Application"), Command.println("Initialized") ); // Custom command implementation public class FetchDataCommand implements Command { private final String url; public FetchDataCommand(String url) { this.url = url; } @Override public Message execute() { try { String data = fetchFromUrl(url); return new DataReceivedMessage(data); // Assuming DataReceivedMessage exists } catch (Exception e) { return new ErrorMessage(e); // Assuming ErrorMessage exists } } private String fetchFromUrl(String url) { // Actual HTTP fetch implementation return "data"; } } // Placeholder for assumed Message classes class DataReceivedMessage implements Message { private final String data; public DataReceivedMessage(String data) { this.data = data; } } class ErrorMessage implements Message { private final Exception exception; public ErrorMessage(Exception exception) { this.exception = exception; } } ``` -------------------------------- ### Core API: Command Interface Source: https://context7.com/flatscrew/latte/llms.txt The Core API allows for asynchronous operations through Commands, which return Messages for processing. Examples include timer commands, batch, and sequential command execution, as well as custom command implementations. ```APIDOC ## Core API: Command Interface Commands represent asynchronous operations that return Messages to be processed by the update method. ### Method N/A (Code examples provided) ### Description Defines how to create and execute commands, including built-in utilities for timing, batching, and sequencing, as well as custom command implementation. ### Request Body N/A ### Response N/A ### Examples ```java // Timer command example public class TickMessage implements Message { private final LocalDateTime time; public TickMessage(LocalDateTime time) { this.time = time; } public LocalDateTime getTime() { return time; } } // Using built-in command utilities Command tickCommand = Command.tick( Duration.ofSeconds(1), time -> new TickMessage(time) ); // Batch commands (execute in parallel) Command batchCmd = Command.batch( Command.checkWindowSize(), Command.println("Starting application..."), tickCommand ); // Sequence commands (execute serially) Command sequenceCmd = Command.sequence( Command.clearScreen(), Command.setWidowTitle("My Application"), Command.println("Initialized") ); // Custom command implementation public class FetchDataCommand implements Command { private final String url; public FetchDataCommand(String url) { this.url = url; } @Override public Message execute() { try { String data = fetchFromUrl(url); return new DataReceivedMessage(data); } catch (Exception e) { return new ErrorMessage(e); } } private String fetchFromUrl(String url) { // Actual HTTP fetch implementation return "data"; } } ``` ``` -------------------------------- ### Interactive Dashboard Application in Java with Latte Source: https://context7.com/flatscrew/latte/llms.txt A complete example of an interactive dashboard application built using the Latte framework. It demonstrates real-time updates, user input handling (keyboard events), and dynamic view rendering for terminal applications. Dependencies include the Latte framework core and its cream components for UI elements and styling. ```java import org.flatscrew.latte.*; import org.flatscrew.latte.cream.*; import org.flatscrew.latte.cream.color.Color; import org.flatscrew.latte.cream.border.StandardBorder; import org.flatscrew.latte.message.*; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Dashboard implements Model { private static final Style TITLE_STYLE = Style.newStyle() .foreground(Color.color("#FFFFFF")) .background(Color.color("#7D56F4")) .bold(true) .padding(0, 1) .width(60); private static final Style BOX_STYLE = Style.newStyle() .border(StandardBorder.RoundedBorder) .borderForeground(Color.color("62")) .padding(1) .width(28); private LocalDateTime currentTime; private int counter; private String status = "Running"; @Override public Command init() { return Command.tick(Duration.ofSeconds(1), time -> new TickMessage(time)); } @Override public UpdateResult update(Message msg) { if (msg instanceof TickMessage tickMsg) { this.currentTime = tickMsg.getTime(); Command nextTick = Command.tick(Duration.ofSeconds(1), time -> new TickMessage(time)); return UpdateResult.from(this, nextTick); } if (msg instanceof KeyPressMessage keyMsg) { return switch (keyMsg.key()) { case "up" -> { counter++; yield UpdateResult.from(this); } case "down" -> { counter = Math.max(0, counter - 1); yield UpdateResult.from(this); } case "r" -> { counter = 0; yield UpdateResult.from(this); } case "q", "ctrl+c" -> UpdateResult.from(this, QuitMessage::new); default -> UpdateResult.from(this); }; } if (msg instanceof WindowSizeMessage) { // Handle terminal resize return UpdateResult.from(this); } return UpdateResult.from(this); } @Override public String view() { String title = TITLE_STYLE.render("Dashboard Application"); String timeBox = BOX_STYLE.render( "Current Time\n\n" + (currentTime != null ? currentTime.format(DateTimeFormatter.ISO_LOCAL_TIME) : "--:--:--") ); String counterBox = BOX_STYLE.render( "Counter\n\n" + counter ); String statusBox = Style.newStyle() .width(60) .render("Status: " + status); String controls = Style.newStyle() .foreground(Color.color("241")) .render("\n↑/↓: Adjust counter | R: Reset | Q: Quit"); return title + "\n\n" + HorizontalJoinDecorator.joinHorizontal(Position.Top, timeBox, counterBox) + "\n" + statusBox + controls; } public static void main(String[] args) { Dashboard model = new Dashboard(); Program program = new Program(model) .withAltScreen() .withReportFocus(); program.run(); System.out.println("Application exited gracefully"); } } // Supporting message class class TickMessage implements Message { private final LocalDateTime time; public TickMessage(LocalDateTime time) { this.time = time; } public LocalDateTime getTime() { return time; } } ``` -------------------------------- ### Component API: Build Static and Dynamic Lists Source: https://context7.com/flatscrew/latte/llms.txt Provides a `List` component for displaying data, supporting both static arrays and dynamic data sources via `ListDataSource`. Includes `DefaultItem` for basic item structure and `ProductDataSource` as an example for fetching and filtering data with pagination. Requires importing list-related classes. ```java import org.flatscrew.latte.spice.list.*; // Define list items public class ProductItem implements DefaultItem { private final String title; private final String description; public ProductItem(String title, String description) { this.title = title; this.description = description; } @Override public String title() { return title; } @Override public String description() { return description; } @Override public String filterValue() { return title; } } // Static list usage Item[] items = { new ProductItem("Laptop", "High-performance laptop"), new ProductItem("Smartphone", "Latest model smartphone"), new ProductItem("Headphones", "Noise-canceling headphones") }; List staticList = new List(items, 40, 10); // width: 40, height: 10 // Dynamic list with data source public class ProductDataSource implements ListDataSource { private final ProductRepository repository; public ProductDataSource(ProductRepository repository) { this.repository = repository; } @Override public FetchedItems fetchItems(int page, int perPage, String filterValue) { List products = (filterValue == null || filterValue.isEmpty()) ? repository.findAll(PageRequest.of(page, perPage)).getContent() : repository.findByNameContaining(filterValue, PageRequest.of(page, perPage)); List items = products.stream() .map(p -> new ProductItem(p.getName(), p.getDescription())) .map(FilteredItem::new) .toList(); long total = repository.count(); return new FetchedItems(items, items.size(), total, (int) Math.ceil((double) total / perPage)); } @Override public long totalItems() { return repository.count(); } } List dynamicList = new List(new ProductDataSource(repository), 40, 10); ``` -------------------------------- ### Add Flatscrew Latte Maven Dependency Source: https://context7.com/flatscrew/latte/llms.txt This XML configuration demonstrates how to add the 'latte-tui' artifact from the 'org.flatscrew' group to a Maven project. It ensures automatic dependency management for the Latte library. The example also includes the 'maven-compiler-plugin' configuration for Java 21. ```xml org.flatscrew latte-tui 0.1.2 org.apache.maven.plugins maven-compiler-plugin 3.11.0 21 21 ``` -------------------------------- ### Latte Program Initialization and Execution in Java Source: https://context7.com/flatscrew/latte/llms.txt Shows how to initialize and run a Latte TUI application using the Program class. Includes basic and advanced configurations for terminal features. Requires Latte framework and a Model implementation. ```java import org.flatscrew.latte.Program; public class Main { public static void main(String[] args) { // Basic program initialization CoffeeOrder model = new CoffeeOrder(); Program program = new Program(model); program.run(); System.out.printf("You chose: %s!\n", model.getChoice()); } public static void advancedExample() { // Program with advanced terminal features CoffeeOrder model = new CoffeeOrder(); Program program = new Program(model) .withAltScreen() // Use alternate screen buffer .withMouseAllMotion() // Enable mouse tracking .withReportFocus(); // Track focus events program.run(); } } ``` -------------------------------- ### Run Latte Program Entry Point in Java Source: https://github.com/flatscrew/latte/blob/main/README.md The main method serves as the entry point for the Latte application. It initializes the application's model, creates a Program instance with the model, and then runs the program. After execution, it checks if a choice was made and prints the selected item to the console. ```java public static void main(String[] args) { Demo demoModel = new Demo(); Program program = new Program(demoModel); program.run(); if (demoModel.getChoice() == null) { return; } System.out.printf("\n---\nYou chose: %s!\n", demoModel.getChoice()); } ``` -------------------------------- ### Initialize Latte Application Model in Java Source: https://github.com/flatscrew/latte/blob/main/README.md This code demonstrates how to initialize the model for a Latte TUI application in Java. It involves creating an instance of the model class and defining the initial state. For initial I/O operations, the `init` method can return a `Command` or `null` if no command is needed. ```java Demo demoModel = new Demo(); ``` ```java @Override public Command init() { return null; } ``` -------------------------------- ### Create Latte List with Dynamic Data Source (Java) Source: https://github.com/flatscrew/latte/blob/main/ListComponent.md Shows how to initialize a Latte List component with a dynamic data source (ListDataSource), suitable for large or frequently updated datasets. Leverages Latte's DefaultDelegate. ```java ListDataSource productDataSource = new ProductDataSource(productRepository); // List constructor that automatically assigns DefaultDelegate List list = new List(productDataSource, 40, 10); ``` ```java List list = new List(productDataSource, new DefaultDelegate(), 40, 10); ``` -------------------------------- ### Latte Model Interface Implementation in Java Source: https://context7.com/flatscrew/latte/llms.txt Demonstrates implementing the Model interface for Latte TUI applications. It defines the application's state, handles user input messages, and renders the UI. Requires Latte framework dependencies. ```java import org.flatscrew.latte.Model; import org.flatscrew.latte.Command; import org.flatscrew.latte.Message; import org.flatscrew.latte.UpdateResult; import org.flatscrew.latte.message.KeyPressMessage; import org.flatscrew.latte.message.QuitMessage; public class CoffeeOrder implements Model { private static final String[] CHOICES = {"Espresso", "Americano", "Latte"}; private int cursor = 0; private String choice; @Override public Command init() { // Return initial command or null if no async operations needed return null; } @Override public UpdateResult update(Message msg) { if (msg instanceof KeyPressMessage keyPressMessage) { return switch (keyPressMessage.key()) { case "up", "k" -> { cursor = (cursor - 1 + CHOICES.length) % CHOICES.length; yield UpdateResult.from(this); } case "down", "j" -> { cursor = (cursor + 1) % CHOICES.length; yield UpdateResult.from(this); } case "enter" -> { choice = CHOICES[cursor]; yield UpdateResult.from(this, QuitMessage::new); } case "q", "Q" -> UpdateResult.from(this, QuitMessage::new); default -> UpdateResult.from(this); }; } return UpdateResult.from(this); } @Override public String view() { StringBuilder sb = new StringBuilder("Select your coffee:\n\n"); for (int i = 0; i < CHOICES.length; i++) { sb.append(i == cursor ? "[•] " : "[ ] ") .append(CHOICES[i]) .append("\n"); } return sb.append("\n(press q to quit)").toString(); } public String getChoice() { return choice; } } ``` -------------------------------- ### Create Latte List with Static Array (Java) Source: https://github.com/flatscrew/latte/blob/main/ListComponent.md Demonstrates creating a Latte List component using a static array of ProductItem objects. This is suitable for small, predefined lists and utilizes Latte's DefaultDelegate. ```java Item[] items = { new ProductItem("Laptop", "High-performance laptop"), new ProductItem("Smartphone", "Latest model smartphone"), new ProductItem("Headphones", "Noise-canceling headphones") }; // List constructor that automatically assigns DefaultDelegate List list = new List(items, 40, 10); ``` ```java List list = new List(items, new DefaultDelegate(), 40, 10); ``` -------------------------------- ### Implement View Method for UI Rendering in Java Source: https://github.com/flatscrew/latte/blob/main/README.md The view method is responsible for rendering the application's user interface as a String. It iterates through choices, displaying them with a cursor indicator for the selected item and a checkbox. It also includes instructions for the user, such as how to quit. This method is simple as Latte handles redrawing logic. ```java @Override public String view() { StringBuilder buffer = new StringBuilder(); buffer.append("What kind of Coffee would you like to order?\n\n"); for (int index = 0; index < CHOICES.length; index++) { if (cursor == index) { buffer.append(SELECTION.render("[•]", CHOICES[index])); } else { buffer.append("[ ] ").append(CHOICES[index]); } buffer.append("\n"); } buffer.append("\n(press q to quit)"); return buffer.toString(); } ``` -------------------------------- ### Maven Dependency Integration Source: https://context7.com/flatscrew/latte/llms.txt Instructions on how to add the Latte TUI library as a dependency to your Java project using Maven. ```APIDOC ## Maven Dependency ### Description Add Latte to your Java project using Maven with automatic dependency management. ### Method N/A (Dependency declaration) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Request Example ```xml org.flatscrew latte-tui 0.1.2 org.apache.maven.plugins maven-compiler-plugin 3.11.0 21 21 ``` ### Response Example N/A ``` -------------------------------- ### Message API: Handle Keyboard Input Events Source: https://context7.com/flatscrew/latte/llms.txt Illustrates handling keyboard input messages within an `update` method. Supports string-based key matching for common actions, checks for modifier keys (Alt), accesses raw character runes, and determines key types. Requires importing `KeyPressMessage` and `KeyType`. ```java import org.flatscrew.latte.message.KeyPressMessage; import org.flatscrew.latte.input.key.KeyType; @Override public UpdateResult update(Message msg) { if (msg instanceof KeyPressMessage keyMsg) { // String-based key matching return switch (keyMsg.key()) { case "up", "k", "K" -> handleMoveUp(); case "down", "j", "J" -> handleMoveDown(); case "left", "h" -> handleMoveLeft(); case "right", "l" -> handleMoveRight(); case "enter" -> handleSelect(); case "esc" -> handleEscape(); case "ctrl+c", "q" -> UpdateResult.from(this, QuitMessage::new); case "space" -> handleToggle(); case "tab" -> handleTab(); case "backspace" -> handleBackspace(); default -> UpdateResult.from(this); }; // Check for modifiers if (keyMsg.alt()) { // Handle Alt+key combinations } // Access raw character runes char[] runes = keyMsg.runes(); // Check key type KeyType type = keyMsg.type(); } return UpdateResult.from(this); } ``` -------------------------------- ### Define Latte Model State in Java Source: https://github.com/flatscrew/latte/blob/main/README.md This snippet shows how to define the state for a Latte application by implementing the `org.flatscrew.latte.Model` interface. It includes fields to hold the application's data, such as choices and selected items. Dependencies include the `org.flatscrew.latte.Model` interface. ```java import org.flatscrew.latte.Model; public class Demo implements Model { private final static String[] CHOICES = {"Espresso", "Americano", "Latte"}; private int cursor; private String choice; } ``` -------------------------------- ### Utilize Color Utilities in Flatscrew Latte for Terminal Output Source: https://context7.com/flatscrew/latte/llms.txt Explains the use of Flatscrew Latte's Color utilities for terminal output, supporting Hex, ANSI256, and basic ANSI color formats. Demonstrates applying colors to foreground, background, and borders, including multi-color applications for borders. ```java import org.flatscrew.latte.cream.Style; import org.flatscrew.latte.cream.color.Color; import org.flatscrew.latte.cream.border.StandardBorder; // Hex colors (automatically converted to terminal color) Color red = Color.color("#FF0000"); Color blue = Color.color("#0000FF"); // ANSI 256 colors (0-255) Color brightRed = Color.color("9"); Color purple = Color.color("141"); // Using colors in styles Style coloredStyle = Style.newStyle() .foreground(Color.color("#FAFAFA")) .background(Color.color("62")); String colored = coloredStyle.render("Colored text"); // Multiple color applications Style multiColor = Style.newStyle() .border(StandardBorder.RoundedBorder) .borderForeground( Color.color("205"), // top Color.color("62"), // right Color.color("205"), // bottom Color.color("62") // left ) .borderBackground(Color.color("235")); ``` -------------------------------- ### Apply Rich Styling to Terminal Text with Flatscrew Latte Source: https://context7.com/flatscrew/latte/llms.txt Showcases the Flatscrew Latte Style class for fluent text styling in terminals. Covers setting foreground/background colors, bold, padding, width, alignment, borders, margins, and height. Demonstrates rendering styled text and outlines available border styles and selective border application. ```java import org.flatscrew.latte.cream.Style; import org.flatscrew.latte.cream.Position; import org.flatscrew.latte.cream.color.Color; import org.flatscrew.latte.cream.border.StandardBorder; // Create styled text Style headerStyle = Style.newStyle() .foreground(Color.color("#FFFFFF")) .background(Color.color("#7D56F4")) .bold(true) .padding(1, 2) .width(40) .align(Position.Center); String header = headerStyle.render("Application Title"); // Complex styling with borders Style boxStyle = Style.newStyle() .foreground(Color.color("205")) .background(Color.color("235")) .border(StandardBorder.RoundedBorder) .borderForeground(Color.color("62")) .padding(1) .margin(1, 2) .width(50) .height(10); String box = boxStyle.render("Content inside styled box"); // Available border styles Style.newStyle().border(StandardBorder.NormalBorder); // ┌─┐ style Style.newStyle().border(StandardBorder.RoundedBorder); // ╭─╮ style Style.newStyle().border(StandardBorder.ThickBorder); // ┏━┓ style Style.newStyle().border(StandardBorder.DoubleBorder); // ╔═╗ style Style.newStyle().border(StandardBorder.BlockBorder); // █ style // Selective borders Style.newStyle() .borderDecoration(StandardBorder.NormalBorder) .borderTop(true) .borderBottom(true) .borderLeft(false) .borderRight(false); // Text styling options Style textStyle = Style.newStyle() .bold(true) .italic(true) .underline(true) .blink(true) .faint(true) .reverse(true); ``` -------------------------------- ### Layout API: Join Decorators Source: https://context7.com/flatscrew/latte/llms.txt Combine multiple styled components horizontally or vertically with alignment options using HorizontalJoinDecorator and VerticalJoinDecorator. ```APIDOC ## Layout API: Join Decorators Combine multiple styled components horizontally or vertically with alignment options. ### Description This API allows for the arrangement of UI elements in horizontal or vertical layouts. It supports various alignment options and can be used to create complex dashboard structures. ### Method N/A (This is a class-based API, not endpoint-based) ### Endpoint N/A ### Parameters N/A ### Request Example ```java // Example for Horizontal Layout Style leftBox = Style.newStyle().border(StandardBorder.RoundedBorder).padding(1).width(20); Style rightBox = Style.newStyle().border(StandardBorder.RoundedBorder).padding(1).width(20); String left = leftBox.render("Left Panel"); String right = rightBox.render("Right Panel"); String horizontal = HorizontalJoinDecorator.joinHorizontal(Position.Top, left, right); // Example for Vertical Layout String top = Style.newStyle().border(StandardBorder.RoundedBorder).width(40).height(5).render("Top Section"); String bottom = Style.newStyle().border(StandardBorder.RoundedBorder).width(40).height(5).render("Bottom Section"); String vertical = VerticalJoinDecorator.joinVertical(Position.Left, top, bottom); // Example for Complex Layout String dashboardLayout = HorizontalJoinDecorator.joinHorizontal( Position.Top, VerticalJoinDecorator.joinVertical(Position.Left, header, sidebar), mainContent ); ``` ### Response N/A (This API generates layout strings) ### Response Example N/A ``` -------------------------------- ### Layout API: Combine Components Horizontally and Vertically Source: https://context7.com/flatscrew/latte/llms.txt Demonstrates using HorizontalJoinDecorator and VerticalJoinDecorator to arrange UI components. Supports various alignment options and nesting for complex layouts. Requires importing necessary decorator and Position classes. ```java import org.flatscrew.latte.cream.join.HorizontalJoinDecorator; import org.flatscrew.latte.cream.join.VerticalJoinDecorator; import org.flatscrew.latte.cream.Position; // Horizontal layout Style leftBox = Style.newStyle() .border(StandardBorder.RoundedBorder) .padding(1) .width(20); Style rightBox = Style.newStyle() .border(StandardBorder.RoundedBorder) .padding(1) .width(20); String left = leftBox.render("Left Panel"); String right = rightBox.render("Right Panel"); // Join horizontally with top alignment String horizontal = HorizontalJoinDecorator.joinHorizontal( Position.Top, left, right ); // Vertical layout String top = Style.newStyle() .border(StandardBorder.RoundedBorder) .width(40) .height(5) .render("Top Section"); String bottom = Style.newStyle() .border(StandardBorder.RoundedBorder) .width(40) .height(5) .render("Bottom Section"); String vertical = VerticalJoinDecorator.joinVertical( Position.Left, top, bottom ); // Complex layouts combining both String dashboardLayout = HorizontalJoinDecorator.joinHorizontal( Position.Top, VerticalJoinDecorator.joinVertical(Position.Left, header, sidebar), mainContent ); ``` -------------------------------- ### Handle Terminal Window Events with Java Message API Source: https://context7.com/flatscrew/latte/llms.txt This Java code snippet shows how to handle terminal window size changes using the WindowSizeMessage from the org.flatscrew.latte.message package. It updates internal window dimensions and can be used to trigger layout adjustments. The init() method demonstrates how to programmatically check the window size, and a clearScreen() command is also provided. ```java import org.flatscrew.latte.message.WindowSizeMessage; import org.flatscrew.latte.Command; @Override public UpdateResult update(Message msg) { if (msg instanceof WindowSizeMessage sizeMsg) { int width = sizeMsg.width(); int height = sizeMsg.height(); // Adjust layout based on new dimensions this.windowWidth = width; this.windowHeight = height; return UpdateResult.from(this); } return UpdateResult.from(this); } // Programmatically check window size @Override public Command init() { return Command.checkWindowSize(); } // Clear screen command Command clearCmd = Command.clearScreen(); ``` -------------------------------- ### Implement ListDataSource for Latte Dynamic Lists (Java) Source: https://github.com/flatscrew/latte/blob/main/ListComponent.md Provides a custom implementation of ListDataSource for Latte, enabling dynamic data fetching and filtering, typically from a repository. This is recommended for large datasets. ```java public class ProductDataSource implements ListDataSource { private final ProductRepository productRepository; public ProductDataSource(ProductRepository productRepository) { this.productRepository = productRepository; } @Override public FetchedItems fetchItems(int page, int perPage, String filterValue) { PageRequest pageRequest = PageRequest.of(page, perPage); List products = (filterValue == null || filterValue.isEmpty()) ? productRepository.findAll(pageRequest).getContent() : productRepository.findByNameContaining(filterValue, pageRequest); List filteredItems = products.stream() .map(product -> new ProductItem(product.getName(), product.getDescription())) .map(FilteredItem::new) .toList(); long totalItems = productRepository.count(); return new FetchedItems(filteredItems, filteredItems.size(), totalItems, (int) Math.ceil((double) totalItems / perPage)); } @Override public long totalItems() { return productRepository.count(); } } ``` -------------------------------- ### Styling API: Color Utilities Source: https://context7.com/flatscrew/latte/llms.txt Provides comprehensive color support with options for RGB (hex), ANSI256, and basic ANSI color codes, enabling flexible text and border coloring. ```APIDOC ## Styling API: Color Utilities Color support with multiple color profile options including RGB, ANSI256, and basic ANSI colors. ### Method N/A (Code examples provided) ### Description Illustrates how to use the Color utility for various color formats (hex, ANSI256) and apply them to text and borders within styles. ### Request Body N/A ### Response N/A ### Examples ```java import org.flatscrew.latte.cream.color.Color; import org.flatscrew.latte.cream.border.StandardBorder; import org.flatscrew.latte.cream.Style; // Hex colors (automatically converted to terminal color) Color red = Color.color("#FF0000"); Color blue = Color.color("#0000FF"); // ANSI 256 colors (0-255) Color brightRed = Color.color("9"); Color purple = Color.color("141"); // Using colors in styles Style coloredStyle = Style.newStyle() .foreground(Color.color("#FAFAFA")) .background(Color.color("62")); String colored = coloredStyle.render("Colored text"); // Multiple color applications Style multiColor = Style.newStyle() .border(StandardBorder.RoundedBorder) .borderForeground( Color.color("205"), // top Color.color("62"), // right Color.color("205"), // bottom Color.color("62") // left ) .borderBackground(Color.color("235")); ``` ``` -------------------------------- ### Component API: List Component Source: https://context7.com/flatscrew/latte/llms.txt A pre-built list component that supports static arrays and dynamic data sources with filtering and pagination capabilities. ```APIDOC ## Component API: List Component Pre-built list component supporting static arrays and dynamic data sources with filtering and pagination. ### Description This component provides a versatile way to display lists of items. It can be populated with predefined data or fetch data dynamically from a source, offering features like filtering and pagination. ### Method N/A (This is a class-based API, not endpoint-based) ### Endpoint N/A ### Parameters N/A ### Request Example ```java // Example for Static List public class ProductItem implements DefaultItem { ... } Item[] items = { new ProductItem("Laptop", "High-performance laptop"), ... }; List staticList = new List(items, 40, 10); // Example for Dynamic List public class ProductDataSource implements ListDataSource { ... } List dynamicList = new List(new ProductDataSource(repository), 40, 10); ``` ### Response N/A (This API generates UI components) ### Response Example N/A ``` -------------------------------- ### Styling API: Style Class Source: https://context7.com/flatscrew/latte/llms.txt The Style class offers a fluent API for customizing text appearance, including foreground and background colors, bolding, padding, width, alignment, borders, and margins. ```APIDOC ## Styling API: Style Class The Style class provides a fluent API for styling text with colors, borders, padding, and alignment. ### Method N/A (Code examples provided) ### Description Demonstrates how to create and apply styles to text for various visual effects, including complex border styling and text decorations. ### Request Body N/A ### Response N/A ### Examples ```java import org.flatscrew.latte.cream.Style; import org.flatscrew.latte.cream.Position; import org.flatscrew.latte.cream.color.Color; import org.flatscrew.latte.cream.border.StandardBorder; // Create styled text Style headerStyle = Style.newStyle() .foreground(Color.color("#FFFFFF")) .background(Color.color("#7D56F4")) .bold(true) .padding(1, 2) .width(40) .align(Position.Center); String header = headerStyle.render("Application Title"); // Complex styling with borders Style boxStyle = Style.newStyle() .foreground(Color.color("205")) .background(Color.color("235")) .border(StandardBorder.RoundedBorder) .borderForeground(Color.color("62")) .padding(1) .margin(1, 2) .width(50) .height(10); String box = boxStyle.render("Content inside styled box"); // Available border styles Style.newStyle().border(StandardBorder.NormalBorder); // ┌─┐ style Style.newStyle().border(StandardBorder.RoundedBorder); // ╭─╮ style Style.newStyle().border(StandardBorder.ThickBorder); // ┏━┓ style Style.newStyle().border(StandardBorder.DoubleBorder); // ╔═╗ style Style.newStyle().border(StandardBorder.BlockBorder); // █ style // Selective borders Style.newStyle() .borderDecoration(StandardBorder.NormalBorder) .borderTop(true) .borderBottom(true) .borderLeft(false) .borderRight(false); // Text styling options Style textStyle = Style.newStyle() .bold(true) .italic(true) .underline(true) .blink(true) .faint(true) .reverse(true); ``` ``` -------------------------------- ### Message API: Window Events Source: https://context7.com/flatscrew/latte/llms.txt This API handles terminal window size changes and screen clearing events within the Latte TUI. ```APIDOC ## Message API: Window Events ### Description Handle terminal window size changes and screen clearing. ### Method N/A (Event-driven) ### Endpoint N/A (Internal message handling) ### Parameters N/A ### Request Example ```java // Example of receiving a WindowSizeMessage if (msg instanceof WindowSizeMessage sizeMsg) { int width = sizeMsg.width(); int height = sizeMsg.height(); // Adjust layout based on new dimensions this.windowWidth = width; this.windowHeight = height; } ``` ### Response N/A (Internal state update) ### Request Example ```java // Programmatically check window size Command.checkWindowSize(); // Clear screen command Command.clearScreen(); ``` ### Response Example N/A ``` -------------------------------- ### Message API: Keyboard Input Source: https://context7.com/flatscrew/latte/llms.txt Handles keyboard events, including special keys, arrow keys, and modifier combinations. ```APIDOC ## Message API: Keyboard Input Handle keyboard events including special keys, arrow keys, and modifier combinations. ### Description This API allows applications to capture and process keyboard input, distinguishing between regular character keys, special keys, and key combinations involving modifier keys like Alt and Ctrl. ### Method N/A (This is typically part of an event handling or update loop) ### Endpoint N/A ### Parameters N/A ### Request Example ```java @Override public UpdateResult update(Message msg) { if (msg instanceof KeyPressMessage keyMsg) { // String-based key matching return switch (keyMsg.key()) { case "up", "k", "K" -> handleMoveUp(); case "down", "j", "J" -> handleMoveDown(); // ... other cases ... default -> UpdateResult.from(this); }; // Check for modifiers if (keyMsg.alt()) { // Handle Alt+key combinations } // Access raw character runes char[] runes = keyMsg.runes(); // Check key type KeyType type = keyMsg.type(); } return UpdateResult.from(this); } ``` ### Response N/A (This API handles input events) ### Response Example N/A ``` -------------------------------- ### Define DefaultItem for Latte List Component (Java) Source: https://github.com/flatscrew/latte/blob/main/ListComponent.md Implements the DefaultItem interface for Latte's List component, providing title and description for default rendering. Requires Latte's DefaultDelegate to function. ```java public class ProductItem implements DefaultItem { private final String title; private final String description; public ProductItem(String title, String description) { this.title = title; this.description = description; } @Override public String title() { return title; } @Override public String description() { return description; } @Override public String filterValue() { return title; // Used for filtering } } ``` -------------------------------- ### Define DefaultItem Interface for Latte Lists (Java) Source: https://github.com/flatscrew/latte/blob/main/ListComponent.md Defines the DefaultItem interface, which extends Latte's base Item interface. This interface is required by DefaultDelegate for rendering list items, mandating title() and description() methods. ```java public interface DefaultItem extends Item { String title(); String description(); } ``` -------------------------------- ### Implement Update Method for User Input Handling in Java Source: https://github.com/flatscrew/latte/blob/main/README.md The update method processes incoming messages, such as key presses, to modify the application's model. It uses a switch statement to handle different key inputs, updating the cursor position or making a selection. It can also return commands like QuitMessage to control program flow. Dependencies include the Message, KeyPressMessage, UpdateResult, and Model interfaces. ```java public class LatteExample { // ... other fields and methods ... @Override public UpdateResult update(Message msg) { // is this a key press? if (msg instanceof KeyPressMessage keyPressMessage) { // cool, what whas the actual key pressed? return switch (keyPressMessage.key()) { // the "up" and "k" keys move the cursor up case 'k', 'K', 65 -> new UpdateResult<>(this.moveUp(), null); // the "down" and "j" keys move the cursor down case 'j', 'J', 66 -> new UpdateResult<>(this.moveDown(), null); // the "enter" and the spacebar (a literal space) toggle // the selected state for the item that the cursor is pointing at. case 13, ' ' -> new UpdateResult<>(this.makeChoice(), QuitMessage::new); // this key should exit the program case 'q', 'Q' -> new UpdateResult<>(this, QuitMessage::new); default -> new UpdateResult<>(this, null); }; } // return the updated model to Latte for processing return new UpdateResult<>(this, null); } private Model moveUp() { if (cursor - 1 < 0) { cursor = CHOICES.length - 1; return this; } cursor--; return this; } private Model moveDown() { if (cursor + 1 >= CHOICES.length) { cursor = 0; return this; } cursor++; return this; } private Model makeChoice() { for (int index = 0; index < CHOICES.length ; index++) { String choice = CHOICES[index]; if (index == cursor) { this.choice = choice; return this; } } return this; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.