tailwind-rs-core 0.15.4

Core types and utilities for tailwind-rs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Plugin system for extending Tailwind-RS functionality
//!
//! This module provides a plugin system that allows users to extend Tailwind-RS
//! with custom utilities, components, and optimizations.

use crate::css_generator::{CssGenerator, CssProperty, CssRule};
use crate::error::{Result, TailwindError};
use std::collections::HashMap;
use std::sync::Arc;

/// Plugin hook types
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PluginHook {
    /// Hook called before CSS generation
    BeforeGenerate,
    /// Hook called after CSS generation
    AfterGenerate,
    /// Hook called when a class is added
    OnClassAdd,
    /// Hook called when a rule is created
    OnRuleCreate,
    /// Hook called during optimization
    OnOptimize,
}

/// Plugin context containing current state
#[derive(Debug, Clone)]
pub struct PluginContext {
    /// Current CSS generator
    pub generator: Arc<CssGenerator>,
    /// Plugin data storage
    pub data: HashMap<String, serde_json::Value>,
    /// Configuration
    pub config: HashMap<String, serde_json::Value>,
}

/// Plugin trait that all plugins must implement
pub trait Plugin: Send + Sync {
    /// Get the plugin name
    fn name(&self) -> &str;

    /// Get the plugin version
    fn version(&self) -> &str;

    /// Get the plugin description
    fn description(&self) -> &str;

    /// Initialize the plugin
    fn initialize(&mut self, context: &mut PluginContext) -> Result<()>;

    /// Handle plugin hooks
    fn handle_hook(&mut self, hook: PluginHook, context: &mut PluginContext) -> Result<()>;

    /// Get plugin configuration schema
    fn get_config_schema(&self) -> Option<serde_json::Value>;

    /// Validate plugin configuration
    fn validate_config(&self, config: &serde_json::Value) -> Result<()>;
}

/// Plugin registry for managing plugins
pub struct PluginRegistry {
    plugins: HashMap<String, Box<dyn Plugin>>,
    hooks: HashMap<PluginHook, Vec<String>>,
    context: PluginContext,
}

impl Default for PluginRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl PluginRegistry {
    /// Create a new plugin registry
    pub fn new() -> Self {
        Self {
            plugins: HashMap::new(),
            hooks: HashMap::new(),
            context: PluginContext {
                generator: Arc::new(CssGenerator::new()),
                data: HashMap::new(),
                config: HashMap::new(),
            },
        }
    }

    /// Register a plugin
    pub fn register_plugin(&mut self, plugin: Box<dyn Plugin>) -> Result<()> {
        let name = plugin.name().to_string();

        if self.plugins.contains_key(&name) {
            return Err(TailwindError::build(format!(
                "Plugin '{}' is already registered",
                name
            )));
        }

        // Initialize the plugin
        let mut plugin_box = plugin;
        plugin_box.initialize(&mut self.context)?;

        // Register the plugin
        self.plugins.insert(name.clone(), plugin_box);

        // Register default hooks
        self.register_default_hooks(&name);

        Ok(())
    }

    /// Unregister a plugin
    pub fn unregister_plugin(&mut self, name: &str) -> Result<()> {
        if !self.plugins.contains_key(name) {
            return Err(TailwindError::build(format!(
                "Plugin '{}' is not registered",
                name
            )));
        }

        // Remove from plugins
        self.plugins.remove(name);

        // Remove from hooks
        for hook_list in self.hooks.values_mut() {
            hook_list.retain(|plugin_name| plugin_name != name);
        }

        Ok(())
    }

    /// Get a plugin by name
    pub fn get_plugin(&self, name: &str) -> Option<&dyn Plugin> {
        self.plugins.get(name).map(|p| p.as_ref())
    }

    /// Get a mutable plugin by name
    pub fn get_plugin_mut(&mut self, name: &str) -> Option<&mut (dyn Plugin + '_)> {
        if let Some(plugin) = self.plugins.get_mut(name) {
            Some(plugin.as_mut())
        } else {
            None
        }
    }

    /// List all registered plugins
    pub fn list_plugins(&self) -> Vec<String> {
        self.plugins.keys().cloned().collect()
    }

    /// Execute a hook for all registered plugins
    pub fn execute_hook(&mut self, hook: PluginHook) -> Result<()> {
        if let Some(plugin_names) = self.hooks.get(&hook) {
            for plugin_name in plugin_names {
                if let Some(plugin) = self.plugins.get_mut(plugin_name) {
                    plugin.handle_hook(hook.clone(), &mut self.context)?;
                }
            }
        }
        Ok(())
    }

    /// Set plugin configuration
    pub fn set_plugin_config(
        &mut self,
        plugin_name: &str,
        config: serde_json::Value,
    ) -> Result<()> {
        if let Some(plugin) = self.plugins.get(plugin_name) {
            plugin.validate_config(&config)?;
        }

        self.context.config.insert(plugin_name.to_string(), config);
        Ok(())
    }

    /// Get plugin configuration
    pub fn get_plugin_config(&self, plugin_name: &str) -> Option<&serde_json::Value> {
        self.context.config.get(plugin_name)
    }

    /// Set plugin data
    pub fn set_plugin_data(&mut self, key: String, value: serde_json::Value) {
        self.context.data.insert(key, value);
    }

    /// Get plugin data
    pub fn get_plugin_data(&self, key: &str) -> Option<&serde_json::Value> {
        self.context.data.get(key)
    }

    /// Update the CSS generator
    pub fn update_generator(&mut self, generator: CssGenerator) {
        self.context.generator = Arc::new(generator);
    }

    /// Get the current CSS generator
    pub fn get_generator(&self) -> Arc<CssGenerator> {
        self.context.generator.clone()
    }

    /// Register default hooks for a plugin
    fn register_default_hooks(&mut self, plugin_name: &str) {
        let default_hooks = vec![
            PluginHook::BeforeGenerate,
            PluginHook::AfterGenerate,
            PluginHook::OnClassAdd,
            PluginHook::OnRuleCreate,
            PluginHook::OnOptimize,
        ];

        for hook in default_hooks {
            self.hooks
                .entry(hook)
                .or_default()
                .push(plugin_name.to_string());
        }
    }
}

/// Example plugin: Custom utilities
#[derive(Debug)]
pub struct CustomUtilitiesPlugin {
    name: String,
    version: String,
    description: String,
    custom_utilities: HashMap<String, CssRule>,
}

impl Default for CustomUtilitiesPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl CustomUtilitiesPlugin {
    /// Create a new custom utilities plugin
    pub fn new() -> Self {
        Self {
            name: "custom-utilities".to_string(),
            version: "1.0.0".to_string(),
            description: "Adds custom utility classes".to_string(),
            custom_utilities: HashMap::new(),
        }
    }

    /// Add a custom utility
    pub fn add_utility(&mut self, class_name: String, rule: CssRule) {
        self.custom_utilities.insert(class_name, rule);
    }
}

impl Plugin for CustomUtilitiesPlugin {
    fn name(&self) -> &str {
        &self.name
    }

    fn version(&self) -> &str {
        &self.version
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn initialize(&mut self, _context: &mut PluginContext) -> Result<()> {
        // Add some default custom utilities
        self.add_utility(
            "custom-shadow".to_string(),
            CssRule {
                selector: ".custom-shadow".to_string(),
                properties: vec![CssProperty {
                    name: "box-shadow".to_string(),
                    value: "0 4px 6px -1px rgba(0, 0, 0, 0.1)".to_string(),
                    important: false,
                }],
                media_query: None,
                specificity: 10,
            },
        );

        Ok(())
    }

    fn handle_hook(&mut self, hook: PluginHook, _context: &mut PluginContext) -> Result<()> {
        match hook {
            PluginHook::BeforeGenerate => {
                // Add custom utilities to the generator
                // Note: This is a simplified implementation
                // In a real implementation, we would need to modify the generator
                println!(
                    "Custom utilities plugin: Adding {} custom utilities",
                    self.custom_utilities.len()
                );
            }
            PluginHook::AfterGenerate => {
                println!("Custom utilities plugin: CSS generation completed");
            }
            _ => {}
        }
        Ok(())
    }

    fn get_config_schema(&self) -> Option<serde_json::Value> {
        Some(serde_json::json!({
            "type": "object",
            "properties": {
                "utilities": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string"},
                            "properties": {"type": "object"}
                        }
                    }
                }
            }
        }))
    }

    fn validate_config(&self, config: &serde_json::Value) -> Result<()> {
        if !config.is_object() {
            return Err(TailwindError::build(
                "Plugin config must be an object".to_string(),
            ));
        }
        Ok(())
    }
}

/// Example plugin: CSS minifier
#[derive(Debug)]
pub struct MinifierPlugin {
    name: String,
    version: String,
    description: String,
    minify: bool,
}

impl Default for MinifierPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl MinifierPlugin {
    /// Create a new minifier plugin
    pub fn new() -> Self {
        Self {
            name: "minifier".to_string(),
            version: "1.0.0".to_string(),
            description: "Minifies CSS output".to_string(),
            minify: true,
        }
    }
}

impl Plugin for MinifierPlugin {
    fn name(&self) -> &str {
        &self.name
    }

    fn version(&self) -> &str {
        &self.version
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn initialize(&mut self, _context: &mut PluginContext) -> Result<()> {
        Ok(())
    }

    fn handle_hook(&mut self, hook: PluginHook, _context: &mut PluginContext) -> Result<()> {
        if hook == PluginHook::OnOptimize && self.minify {
            println!("Minifier plugin: Applying minification");
        }
        Ok(())
    }

    fn get_config_schema(&self) -> Option<serde_json::Value> {
        Some(serde_json::json!({
            "type": "object",
            "properties": {
                "enabled": {"type": "boolean"}
            }
        }))
    }

    fn validate_config(&self, config: &serde_json::Value) -> Result<()> {
        if let Some(enabled) = config.get("enabled") {
            if !enabled.is_boolean() {
                return Err(TailwindError::build(
                    "Minifier enabled must be a boolean".to_string(),
                ));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_plugin_registry_creation() {
        let registry = PluginRegistry::new();
        assert!(registry.list_plugins().is_empty());
    }

    #[test]
    fn test_register_plugin() {
        let mut registry = PluginRegistry::new();
        let plugin = Box::new(CustomUtilitiesPlugin::new());

        registry.register_plugin(plugin).unwrap();

        assert_eq!(registry.list_plugins().len(), 1);
        assert!(registry
            .list_plugins()
            .contains(&"custom-utilities".to_string()));
    }

    #[test]
    fn test_duplicate_plugin_registration() {
        let mut registry = PluginRegistry::new();
        let plugin1 = Box::new(CustomUtilitiesPlugin::new());
        let plugin2 = Box::new(CustomUtilitiesPlugin::new());

        registry.register_plugin(plugin1).unwrap();
        let result = registry.register_plugin(plugin2);

        assert!(result.is_err());
    }

    #[test]
    fn test_unregister_plugin() {
        let mut registry = PluginRegistry::new();
        let plugin = Box::new(CustomUtilitiesPlugin::new());

        registry.register_plugin(plugin).unwrap();
        assert_eq!(registry.list_plugins().len(), 1);

        registry.unregister_plugin("custom-utilities").unwrap();
        assert!(registry.list_plugins().is_empty());
    }

    #[test]
    fn test_plugin_config() {
        let mut registry = PluginRegistry::new();
        let plugin = Box::new(MinifierPlugin::new());

        registry.register_plugin(plugin).unwrap();

        let config = serde_json::json!({"enabled": true});
        registry
            .set_plugin_config("minifier", config.clone())
            .unwrap();

        assert_eq!(registry.get_plugin_config("minifier"), Some(&config));
    }

    #[test]
    fn test_plugin_data() {
        let mut registry = PluginRegistry::new();

        let data = serde_json::json!({"key": "value"});
        registry.set_plugin_data("test_key".to_string(), data.clone());

        assert_eq!(registry.get_plugin_data("test_key"), Some(&data));
    }

    #[test]
    fn test_execute_hook() {
        let mut registry = PluginRegistry::new();
        let plugin = Box::new(MinifierPlugin::new());

        registry.register_plugin(plugin).unwrap();

        // This should not panic
        registry.execute_hook(PluginHook::OnOptimize).unwrap();
    }

    #[test]
    fn test_custom_utilities_plugin() {
        let mut plugin = CustomUtilitiesPlugin::new();
        let mut context = PluginContext {
            generator: Arc::new(CssGenerator::new()),
            data: HashMap::new(),
            config: HashMap::new(),
        };

        plugin.initialize(&mut context).unwrap();
        assert_eq!(plugin.name(), "custom-utilities");
        assert_eq!(plugin.version(), "1.0.0");
    }

    #[test]
    fn test_minifier_plugin() {
        let mut plugin = MinifierPlugin::new();
        let mut context = PluginContext {
            generator: Arc::new(CssGenerator::new()),
            data: HashMap::new(),
            config: HashMap::new(),
        };

        plugin.initialize(&mut context).unwrap();
        assert_eq!(plugin.name(), "minifier");
        assert_eq!(plugin.version(), "1.0.0");
    }
}