Skip to main content

kasl/libs/messages/
mod.rs

1//! Centralized message management system for kasl application.
2//!
3//! Provides a comprehensive message handling infrastructure that serves as the
4//! foundation for all user communication in the kasl application.
5//!
6//! ## Features
7//!
8//! - **Type Safety**: All messages are compile-time verified with proper parameters
9//! - **Centralization**: Single source of truth for all user-facing text
10//! - **Consistency**: Uniform formatting and presentation across the application
11//! - **Extensibility**: Easy addition of new message types and categories
12//! - **Internationalization**: Structure supports future localization efforts
13//!
14//! ## Usage
15//!
16//! ```rust
17//! use kasl::libs::messages::{Message, success, error};
18//! use kasl::{msg_info, msg_error, msg_success};
19//!
20//! msg_success!(Message::TaskCreated);
21//! msg_error!(Message::ConfigSaveError);
22//! msg_info!(Message::MonitorStarted {
23//!     pause_threshold: 60,
24//!     poll_interval: 500,
25//!     activity_threshold: 30,
26//! });
27//! ```
28
29pub mod display;
30pub mod macros;
31pub mod types;
32
33// Re-export the main Message type for convenient access
34pub use types::Message;
35
36/// Creates a success message with a green checkmark prefix.
37///
38/// This function provides a standardized way to format success messages
39/// throughout the application. It ensures consistent visual presentation
40/// for positive feedback and completion notifications.
41///
42/// ## Visual Format
43///
44/// Success messages are prefixed with a green checkmark (✅) to provide
45/// immediate visual feedback about successful operations. This creates
46/// a consistent user experience across all success scenarios.
47///
48/// ## Usage Context
49///
50/// This function is typically used for:
51/// - Operation completion confirmations
52/// - Successful data saves or updates
53/// - Configuration changes applied successfully
54/// - External API communication success
55/// - File operations completed without errors
56///
57/// # Arguments
58///
59/// * `msg` - A [`Message`] enum variant containing the success details
60///
61/// # Returns
62///
63/// Returns a formatted string with the success prefix and message text.
64///
65/// # Examples
66///
67/// ```rust
68/// use kasl::libs::messages::{Message, success};
69///
70/// // Format a simple success message
71/// let message = success(Message::TaskCreated);
72/// println!("{}", message); // "✅ Task created successfully"
73///
74/// // With parameters
75/// let report_message = success(Message::DailyReportSent("2025-01-15".to_string()));
76/// println!("{}", report_message); // "✅ Your report dated 2025-01-15 has been successfully submitted..."
77/// ```
78///
79/// # Integration with Macros
80///
81/// This function works seamlessly with the application's messaging macros:
82/// ```rust
83/// use kasl::msg_success;
84/// use kasl::libs::messages::Message;
85///
86/// // Equivalent to using success() function directly
87/// msg_success!(Message::TaskCreated);
88/// ```
89pub fn success(msg: Message) -> String {
90    format!("✅ {}", msg)
91}
92
93/// Creates an error message with a red X prefix.
94///
95/// This function provides a standardized way to format error messages
96/// throughout the application. It ensures consistent visual presentation
97/// for error conditions and failure notifications, helping users quickly
98/// identify and understand problems.
99///
100/// ## Visual Format
101///
102/// Error messages are prefixed with a red X (❌) to provide immediate
103/// visual indication of error conditions. This creates a consistent
104/// user experience for error reporting across all application areas.
105///
106/// ## Error Message Philosophy
107///
108/// Error messages created by this function follow these principles:
109/// - **Clear Problem Description**: Explain what went wrong
110/// - **Helpful Context**: Provide relevant details for troubleshooting
111/// - **Action Guidance**: Suggest next steps when possible
112/// - **Non-Technical Language**: Avoid intimidating technical jargon
113///
114/// ## Usage Context
115///
116/// This function is typically used for:
117/// - Operation failures and exceptions
118/// - Validation errors and invalid input
119/// - Configuration problems and conflicts
120/// - External service communication failures
121/// - File system and permission errors
122///
123/// # Arguments
124///
125/// * `msg` - A [`Message`] enum variant containing the error details
126///
127/// # Returns
128///
129/// Returns a formatted string with the error prefix and message text.
130///
131/// # Examples
132///
133/// ```rust
134/// use kasl::libs::messages::{Message, error};
135///
136/// // Format a simple error message
137/// let message = error(Message::ConfigSaveError);
138/// println!("{}", message); // "❌ Failed to save configuration"
139///
140/// // With error details
141/// let detailed_error = error(Message::GitlabFetchFailed("Network timeout".to_string()));
142/// println!("{}", detailed_error); // "❌ [kasl] Failed to get GitLab events: Network timeout"
143/// ```
144///
145/// # Error Handling Integration
146///
147/// This function integrates with the application's error handling:
148/// ```rust
149/// use kasl::msg_error;
150/// use kasl::libs::messages::Message;
151/// use anyhow::Result;
152///
153/// # fn operation() -> Result<()> { Ok(()) }
154/// fn save_config() -> Result<()> {
155///     // ... operation that might fail
156///     if let Err(_) = operation() {
157///         msg_error!(Message::ConfigSaveError);
158///         return Err(anyhow::anyhow!("Configuration save failed"));
159///     }
160///     Ok(())
161/// }
162/// ```
163pub fn error(msg: Message) -> String {
164    format!("❌ {}", msg)
165}
166
167/// Creates a warning message with a yellow warning triangle prefix.
168///
169/// This function provides a standardized way to format warning messages
170/// throughout the application. Warnings indicate situations that require
171/// user attention but are not necessarily errors or failures.
172///
173/// ## Visual Format
174///
175/// Warning messages are prefixed with a yellow warning triangle (âš ī¸) to
176/// indicate important information that users should be aware of. This
177/// provides a visual middle ground between informational and error messages.
178///
179/// ## Warning Message Types
180///
181/// Warnings are appropriate for these scenarios:
182/// - **Deprecation Notices**: Features that will be removed in future versions
183/// - **Configuration Issues**: Non-critical configuration problems
184/// - **Data Quality**: Potential issues with user data or inputs
185/// - **Performance Notices**: Operations that might be slow or resource-intensive
186/// - **Compatibility Warnings**: Version or platform compatibility concerns
187///
188/// ## Usage Context
189///
190/// This function is typically used for:
191/// - Non-critical configuration issues
192/// - Deprecated feature usage notifications
193/// - Data quality concerns or anomalies
194/// - Performance or resource usage warnings
195/// - Compatibility or version mismatch notices
196///
197/// # Arguments
198///
199/// * `msg` - A [`Message`] enum variant containing the warning details
200///
201/// # Returns
202///
203/// Returns a formatted string with the warning prefix and message text.
204///
205/// # Examples
206///
207/// ```rust
208/// use kasl::libs::messages::{Message, warning};
209///
210/// // Format a configuration warning
211/// let message = warning(Message::AutostartRequiresAdmin);
212/// println!("{}", message); // "âš ī¸  Administrator privileges required for system-level autostart."
213///
214/// // Data quality warning
215/// let data_warning = warning(Message::ShortIntervalsDetected(3, "45 minutes".to_string()));
216/// println!("{}", data_warning); // "âš ī¸  Detected 3 short intervals totaling 45 minutes"
217/// ```
218///
219/// # Integration with Application Flow
220///
221/// Warnings often provide guidance for resolution:
222/// ```rust
223/// use kasl::msg_warning;
224/// use kasl::libs::messages::Message;
225///
226/// // Warning with follow-up guidance
227/// let count = 3;
228/// let duration = "45 minutes".to_string();
229/// msg_warning!(Message::ShortIntervalsDetected(count, duration));
230/// ```
231pub fn warning(msg: Message) -> String {
232    format!("âš ī¸  {}", msg)
233}
234
235/// Creates an informational message with a blue info icon prefix.
236///
237/// This function provides a standardized way to format informational messages
238/// throughout the application. Info messages convey status updates, progress
239/// notifications, and general information that helps users understand what
240/// the application is doing.
241///
242/// ## Visual Format
243///
244/// Informational messages are prefixed with a blue info icon (â„šī¸) to indicate
245/// general status information that is helpful but not critical. This provides
246/// clear visual categorization for different types of user feedback.
247///
248/// ## Information Message Types
249///
250/// Info messages are appropriate for these scenarios:
251/// - **Status Updates**: Current operation progress and status
252/// - **Configuration Information**: Details about current settings
253/// - **Process Notifications**: Background process status and lifecycle
254/// - **Data Statistics**: Summaries and counts of application data
255/// - **Help and Guidance**: Instructional content and next steps
256///
257/// ## Usage Context
258///
259/// This function is typically used for:
260/// - Background process status updates
261/// - Operation progress notifications
262/// - Configuration and setup information
263/// - Data summary and statistics display
264/// - General user guidance and tips
265///
266/// # Arguments
267///
268/// * `msg` - A [`Message`] enum variant containing the informational content
269///
270/// # Returns
271///
272/// Returns a formatted string with the info prefix and message text.
273///
274/// # Examples
275///
276/// ```rust
277/// use kasl::libs::messages::{Message, info};
278///
279/// // Format a status update
280/// let message = info(Message::MonitorStarted {
281///     pause_threshold: 60,
282///     poll_interval: 500,
283///     activity_threshold: 30,
284/// });
285/// println!("{}", message); // "â„šī¸  Monitor is running with pause threshold 60s, poll interval 500ms, activity threshold 30s"
286///
287/// // Configuration information
288/// let config_info = info(Message::AutostartStatus("enabled".to_string()));
289/// println!("{}", config_info); // "â„šī¸  Autostart is currently: enabled"
290/// ```
291///
292/// # Complementary Usage
293///
294/// Info messages often work together with other message types:
295/// ```rust
296/// use kasl::{msg_info, msg_success};
297/// use kasl::libs::messages::Message;
298///
299/// // Sequential information flow
300/// msg_info!(Message::WatcherStartingForeground);
301/// // ... operation occurs
302/// msg_success!(Message::WatcherStarted(12345));
303/// ```
304pub fn info(msg: Message) -> String {
305    format!("â„šī¸  {}", msg)
306}
307
308/// Wraps a message with newlines for emphasis and visual separation.
309///
310/// This function provides enhanced visual formatting for messages that require
311/// special emphasis or clear separation from surrounding content. It adds
312/// newlines before and after the message text to create visual whitespace
313/// that draws attention to important information.
314///
315/// ## Visual Format
316///
317/// Wrapped messages are formatted with newlines on both sides:
318/// ```text
319///
320/// Your important message here
321///
322/// ```
323///
324/// This creates clear visual separation from other content and emphasizes
325/// the importance of the message.
326///
327/// ## Usage Context
328///
329/// Message wrapping is appropriate for:
330/// - **Critical Announcements**: Important system notifications
331/// - **Section Headers**: Major section dividers in output
332/// - **Final Results**: Summary information at the end of operations
333/// - **Error Emphasis**: Critical errors that require immediate attention
334/// - **Interactive Prompts**: Important questions or confirmations
335///
336/// ## Design Considerations
337///
338/// Wrapped messages should be used sparingly to maintain their emphasis
339/// effect. Overuse can clutter the interface and reduce the impact of
340/// truly important messages.
341///
342/// # Arguments
343///
344/// * `msg` - A [`Message`] enum variant to be wrapped with emphasis
345///
346/// # Returns
347///
348/// Returns a formatted string with newlines before and after the message text.
349///
350/// # Examples
351///
352/// ```rust
353/// use kasl::libs::messages::{Message, wrap_msg};
354///
355/// // Emphasize a critical message
356/// let message = wrap_msg(Message::ConfirmDeleteAllTodayTasksFinal);
357/// println!("{}", message);
358/// // Output:
359/// //
360/// // This action cannot be undone. Continue?
361/// //
362///
363/// // Wrap a summary message
364/// let summary = wrap_msg(Message::AllMigrationsCompleted);
365/// println!("{}", summary);
366/// // Output:
367/// //
368/// // All migrations completed successfully
369/// //
370/// ```
371///
372/// # Integration with Other Formatting
373///
374/// Wrapped messages can be combined with prefix functions:
375/// ```rust
376/// use kasl::libs::messages::{Message, success, wrap_msg};
377///
378/// // Create an emphasized success message using the prefix function directly
379/// let emphasized_success = format!("\n{}\n", success(Message::OperationCompleted));
380/// // Or use wrap_msg directly on the Message for consistent formatting
381/// let wrapped_success = wrap_msg(Message::OperationCompleted);
382/// ```
383pub fn wrap_msg(msg: Message) -> String {
384    format!("\n{}\n", msg)
385}