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