encre-css 0.21.0

A TailwindCSS-compatible utility-first CSS generation library written in Rust
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
//! A [`Plugin`] is a handler used to convert utility classes into CSS declarations.
//!
//! A lot of plugins are built in (like the ones from Tailwind CSS) and some others live in
//! their own crates and need to be imported manually. They usually define a `register` function taking
//! a mutable reference to a [`Config`] structure.
//!
//! # Example (with `encre-css-typography`)
//!
//! ```ignore
//! use encre_css::Config;
//!
//! # fn main() -> encre_css::Result<()> {
//! let mut config = Config::from_file("encre-css.toml")?;
//! // Or let mut config = Config::default();
//!
//! encre_css_typography::register(&mut config);
//!
//! let _css = encre_css::generate(
//!     [r#"<div class="prose prose-headings:text-blue-500 prose-slate lg:prose-lg dark:prose-invert"></div>"#],
//!     &config,
//! );
//! // Do something with the CSS
//! # Ok(())
//! # }
//! ```
//!
//! # Official plugins
//!
//! - [`encre-css-typography`](https://gitlab.com/encre-org/encre-css/tree/main/crates/encre-css-typography): used to define beautiful typographic defaults for HTML you don't control.
//! - [`encre-css-icons`](https://gitlab.com/encre-org/encre-css/tree/main/crates/encre-css-icons): used to quickly add pure CSS icons to your website.
//!
//! If you want to write your own plugins, see [`Plugin`].
//!
//! [`Config`]: crate::Config

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::{generator::{ContextCanHandle, ContextHandle}, selector::CssType};

pub mod accessibility;
pub mod background;
pub mod border;
pub mod css_property;
pub mod effect;
pub mod filter;
pub mod flexbox;
pub mod grid;
pub mod interactivity;
pub mod layout;
pub mod sizing;
pub mod spacing;
pub mod svg;
pub mod table;
pub mod transform;
pub mod transition;
pub mod typography;

/// An alias to a [`Plugin`] which can easily be defined in Rust, e.g in const environments.
///
/// It requires using `&'static str` for all configuration. If you need to use `String`s for some
/// dynamic configuration, use [`DynamicPlugin`] instead.
pub type StaticPlugin = Plugin<
    &'static str,
    &'static [&'static str],
    phf::Map<&'static str, &'static str>,
    phf::Map<&'static str, &'static [&'static str]>,
    &'static [CssType],
>;

/// An alias to a [`Plugin`] which contain configuration defined using `String`s instead of static
/// string references, likely deserialized from a configuration file.
///
/// If you need to define a plugin using Rust without needing any heap-allocated `String`s, use
/// [`StaticPlugin`] instead.
pub type DynamicPlugin = Plugin<
    String,
    Vec<String>,
    HashMap<String, String>,
    HashMap<String, Vec<String>>,
    Vec<CssType>,
>;

/// An alias to a [`PropertyName`] which is defined using `&'static str`, adapted for use in const
/// environments.
pub type StaticPropertyName = PropertyName<&'static str, &'static [&'static str]>;

/// An alias to a [`PropertyName`] which is defined using `String`, adapted for use when a name
/// needs to be dynamic or deserialized.
pub type DynamicPropertyName = PropertyName<String, Vec<String>>;

fn can_handle_nop(_: &ContextCanHandle) -> bool { false }
fn handle_nop(_: &mut ContextHandle) {}

#[derive(Debug, Clone, Serialize)]
pub(crate) enum CustomPlugin {
    #[serde(skip_serializing)]
    Static(&'static StaticPlugin),
    Dynamic(DynamicPlugin),
}

impl<'de> Deserialize<'de> for CustomPlugin {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(Self::Dynamic(DynamicPlugin::deserialize(deserializer)?))
    }
}

/// Either a single or several CSS property names.
///
/// This enumeration is used when defining plugins to specify which CSS property name should be
/// generated. In the case of several property names (i.e [`MultipleProps`]), the
/// CSS value will be copied to all the properties.
///
/// When using [the `build_plugin` prelude](`crate::prelude::build_plugin`), the variants of this
/// enumeration are reexported so that you can simply write [`SingleProp`] and [`MultipleProps`]
/// without having to prefix them with `PropertyName::`.
///
/// When [defining a plugin using TOML](Plugin#define-a-plugin-in-toml), if you use a string, the
/// [`SingleProp`] variant will automatically be used, and if you use an array, the [`MultipleProps`]
/// variants will be used.
///
/// [`SingleProp`]: PropertyName::SingleProp
/// [`MultipleProps`]: PropertyName::MultipleProps
#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PropertyName<Str, ArrayStr> {
    /// A single CSS property name.
    SingleProp(Str),

    /// Several CSS property names in the order they will be generated.
    ///
    /// The CSS value defined by the plugin will be copied to each of the properties.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::{Config, generate};
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::Color(Color {
    ///     namespace: "custom-decoration",
    ///     prop: MultipleProps(&["-webkit-text-decoration-color", "text-decoration-color"]),
    ///     ..Color::default()
    /// });
    ///
    /// let mut config = Config::default();
    /// config.register_plugin(&PLUGIN);
    ///
    /// let generated = generate(["custom-decoration-red-200"], &config);
    ///
    /// assert!(generated.ends_with(r".custom-decoration-red-200 {
    ///   -webkit-text-decoration-color: oklch(88.5% .062 18.334);
    ///   text-decoration-color: oklch(88.5% .062 18.334);
    /// }"));
    /// ```
    MultipleProps(ArrayStr),
}

/// When defining a [`PluginArbitraryMatcher`] for an [`Arbitrary`] kind, defines how values
/// are separated.
///
/// A lot of CSS properties allow specifying several values of a single type separated by a
/// character, e.g `margin` allows [`<length>`](crate::utils::value_matchers::is_matching_length`)
/// or [`<percentage>`](crate::utils::value_matchers::is_matching_percentage`)
/// values separated by spaces, to define a specific margin for each side of the CSS layout box.
///
/// This enumeration helps matching these values when using a [`PluginArbitraryMatcher`], e.g for
/// the `margin` example, you would use
///
/// ```ignore
/// Plugin::new(...)
///     .matchers(&[Length, Percentage], PluginArbitraryMatcherSeparation::Space)
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Serialize, Deserialize)]
pub enum ArbitraryDisambiguateSeparation {
    /// No separation, a single value is matched.
    None,

    /// Separated by commas (`,`).
    ///
    /// Example: `33px, 42%, 6em`.
    Comma,

    /// Separated by spaces (` `).
    ///
    /// Example: `left top`.
    Space,

    /// Separated by commas (`,`) then spaces (` `).
    ///
    /// Example: `left, 12% 33px, right center`.
    Both,
}

#[doc = include_str!("./doc_extra_slash.md")]
#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
pub struct ExtraSlash<Str, MapStr> {
    /// The mapping between the string parsed after the slash (`/`) and the actual values generated
    /// in the CSS value.
    pub values: MapStr,

    /// The key in [`ExtraSlash::values`] which is chosen by default when no slash is present in the
    /// utility class.
    pub default: Str,
}

#[doc = include_str!("./doc_arbitrary_disambiguate.md")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArbitraryDisambiguate<ArrayMatched> {
    /// The list of CSS types which are accepted as arbitrary value by this plugin.
    pub matched: ArrayMatched,

    /// Define how values are specified inside the CSS value.
    ///
    /// In practice, you can check the values accepted by the CSS property and set this field to
    ///
    /// - [`ArbitraryDisambiguateSeparation::Space`] if it accepts several values separated by spaces
    /// - [`ArbitraryDisambiguateSeparation::Comma`] if it accepts several values separated by commas
    /// - [`ArbitraryDisambiguateSeparation::Both`] if it accepts several values separated by commas
    /// which themselves accept several values separated by spaces
    /// - [`ArbitraryDisambiguateSeparation::None`] otherwise
    pub separation: ArbitraryDisambiguateSeparation,
}

/// Define a plugin using a map between utility classes and raw CSS lines.
///
/// It directly generates the CSS of the map value if the utility class as map key is scanned.
///
/// Map values are arrays which represent individual lines of the CSS so that each line can be
/// correctly indented.
///
/// If a utility class maps to an empty array, no class will be generated at all. This behavior can
/// be combined with [`ListProperties::extra_css`] to generate root-level CSS blocks (like
/// `@keyframe` animations).
///
/// If you instead need to map CSS property values to a single CSS property, use [`ListValues`].
///
/// ### Example
///
/// ```
/// use encre_css::{Config, generate};
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::ListProperties(ListProperties {
///     props: map! {
///         "overflow-visible" => &["overflow: visible;"],
///         "overflow-hidden" => &["overflow: hidden;"],
///         "overflow-clip" => &["overflow: clip;"],
///         "overflow-scroll" => &["overflow: scroll;"],
///         "overflow-auto" => &["overflow: auto;"],
///     },
///     ..ListProperties::default()
/// });
///
/// let mut config = Config::default();
/// config.register_plugin(&PLUGIN);
///
/// let generated = generate(["overflow-scroll"], &config);
///
/// assert!(generated.ends_with(r".overflow-scroll {
///   overflow: scroll;
/// }"));
/// ```
///
/// ### Example in TOML
///
/// ```toml
/// [[custom_plugins]]
///
/// [custom_plugins.ListProperties]
///
/// [custom_plugins.ListProperties.props]
/// overflow-visible = ["overflow: visible;"]
/// overflow-hidden = ["overflow: hidden;"]
/// overflow-clip = ["overflow: clip;"]
/// overflow-scroll = ["overflow: scroll;"]
/// overflow-auto = ["overflow: auto;"]
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListProperties<Str, ArrayStr, MapStr, MapArrayStr> {
    /// The map between utility classes and raw CSS lines.
    ///
    /// This field should be assigned separately after calling [`ListProperties::default`] (or
    /// [`ListProperties::default_dynamic`]).
    pub props: MapArrayStr,

    /// Define a [namespace](crate::selector) (i.e a prefix) common to all utility classes declared in the map keys.
    ///
    /// The last dash character (`-`) should be omitted due to the way the parsing of utility classes work
    /// (e.g in the example below, `overflow` is correct while `overflow-` is **incorrect**).
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::{Config, generate};
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::ListProperties(ListProperties {
    ///     namespace: Some("overflow"),
    ///     props: map! {
    ///         "visible" => &["overflow: visible;"],
    ///         "hidden" => &["overflow: hidden;"],
    ///         "clip" => &["overflow: clip;"],
    ///         "scroll" => &["overflow: scroll;"],
    ///         "auto" => &["overflow: auto;"],
    ///     },
    ///     ..ListProperties::default()
    /// });
    ///
    /// let mut config = Config::default();
    /// config.register_plugin(&PLUGIN);
    ///
    /// let generated = generate(["overflow-scroll"], &config);
    ///
    /// assert!(generated.ends_with(r".overflow-scroll {
    ///   overflow: scroll;
    /// }"));
    /// ```
    pub namespace: Option<Str>,

    #[doc = include_str!("./doc_extra_rule_css.md")]
    pub extra_rule_css: Option<ArrayStr>,

    #[doc = include_str!("./doc_extra_css.md")]
    pub extra_css: Option<MapStr>,

    #[doc = include_str!("./doc_extra_class.md")]
    pub extra_class: Option<Str>,
}

impl<Str, ArrayStr, MapStr> ListProperties<Str, ArrayStr, MapStr, phf::Map<&'static str, &'static [&'static str]>> {
    /// Make a default [`ListProperties`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`ListProperties::props`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`ListProperties::default_dynamic`] is that this function can only be used to
    /// build a plugin using static structures like `&[]`s, `&'static str`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::ListProperties(ListProperties {
    ///     props: map! {
    ///         "overflow-visible" => &["overflow: visible;"],
    ///         "overflow-hidden" => &["overflow: hidden;"],
    ///         "overflow-clip" => &["overflow: clip;"],
    ///         "overflow-scroll" => &["overflow: scroll;"],
    ///         "overflow-auto" => &["overflow: auto;"],
    ///     },
    ///     ..ListProperties::default()
    /// });
    /// ```
    pub const fn default() -> Self {
        Self {
            props: phf::Map::new(),
            namespace: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
        }
    }
}

impl<Str, ArrayStr, MapStr> ListProperties<Str, ArrayStr, MapStr, HashMap<String, Vec<String>>> {
    /// Make a default [`ListProperties`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`ListProperties::props`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`ListProperties::default`] is that this function can only be used to
    /// build a plugin using heap-allocated structures like `String`s, `Vec`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// fn main() {
    ///     let props = HashMap::from_iter(
    ///         ["visible", "hidden", "clip", "scroll", "auto"].iter().map(|v| {
    ///             (format!("overflow-{v}"), vec![format!("overflow: {v};")])
    ///         })
    ///     );
    ///
    ///     // Note: the DynamicPlugin type hint is required to help the compiler
    ///     // find the concrete types of type parameters
    ///     let _plugin: DynamicPlugin = Plugin::ListProperties(ListProperties {
    ///         props,
    ///         ..ListProperties::default_dynamic()
    ///     });
    /// }
    /// ```
    ///
    /// This example is equivalent to the one of [`ListProperties::default`].
    pub fn default_dynamic() -> Self {
        Self {
            props: HashMap::new(),
            namespace: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
        }
    }
}

/// Define a plugin using a map between utility classes and the values of a single CSS property.
///
/// If you instead need to generate several CSS properties or to have more control on the CSS lines
/// generated, use [`ListProperties`].
///
/// ### Example
///
/// ```
/// use encre_css::{Config, generate};
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::ListValues(ListValues {
///     prop: SingleProp("width"),
///     values: map! {
///         "w-fit" => "fit-content",
///         "w-max" => "max-content",
///         "w-min" => "min-content",
///     },
///     ..ListValues::default()
/// });
///
/// let mut config = Config::default();
/// config.register_plugin(&PLUGIN);
///
/// let generated = generate(["w-max"], &config);
///
/// assert!(generated.ends_with(r".w-max {
///   width: max-content;
/// }"));
/// ```
///
/// ### Example in TOML
///
/// ```toml
/// [[custom_plugins]]
///
/// [custom_plugins.ListValues]
/// prop = "width"
///
/// [custom_plugins.ListValues.values]
/// w-fit = "fit-content"
/// w-max = "max-content"
/// w-min = "min-content"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListValues<Str, ArrayStr, MapStr> {
    /// The CSS property name of the generated CSS rule.
    ///
    /// It can be a single property using [`PropertyName::SingleProp`] or a list of properties
    /// using [`PropertyName::MultipleProps`], in which case the value will be copied for all
    /// properties.
    ///
    /// This field should be assigned separately after calling [`ListValues::default`] (or
    /// [`ListValues::default_dynamic`]).
    pub prop: PropertyName<Str, ArrayStr>,

    /// The map between utility classes and the CSS values of the property [`ListValues::prop`].
    ///
    /// This field should be assigned separately after calling [`ListValues::default`] (or
    /// [`ListValues::default_dynamic`]).
    pub values: MapStr,

    /// Define a [namespace](crate::selector) (i.e a prefix) common to all utility classes declared in the map keys.
    ///
    /// The last dash character (`-`) should be omitted due to the way the parsing of utility classes work
    /// (e.g in the example below, `overflow` is correct while `overflow-` is **incorrect**).
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::{Config, generate};
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::ListValues(ListValues {
    ///     namespace: Some("w"),
    ///     prop: SingleProp("width"),
    ///     values: map! {
    ///         "fit" => "fit-content",
    ///         "max" => "max-content",
    ///         "min" => "min-content",
    ///     },
    ///     ..ListValues::default()
    /// });
    ///
    /// let mut config = Config::default();
    /// config.register_plugin(&PLUGIN);
    ///
    /// let generated = generate(["w-max"], &config);
    ///
    /// assert!(generated.ends_with(r".w-max {
    ///   width: max-content;
    /// }"));
    /// ```
    pub namespace: Option<Str>,

    #[doc = include_str!("./doc_extra_rule_css.md")]
    pub extra_rule_css: Option<ArrayStr>,

    #[doc = include_str!("./doc_extra_css.md")]
    pub extra_css: Option<MapStr>,

    #[doc = include_str!("./doc_extra_class.md")]
    pub extra_class: Option<Str>,

    #[doc = include_str!("./doc_extra_slash.md")]
    pub extra_slash: Option<ExtraSlash<Str, MapStr>>,
}

impl<ArrayStr> ListValues<&'static str, ArrayStr, phf::Map<&'static str, &'static str>> {
    /// Make a default [`ListValues`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`ListValues::prop`] and [`ListValues::values`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`ListValues::default_dynamic`] is that this function can only be used to
    /// build a plugin using static structures like `&[]`s, `&'static str`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::ListValues(ListValues {
    ///     prop: SingleProp("width"),
    ///     values: map! {
    ///         "w-fit" => "fit-content",
    ///         "w-max" => "max-content",
    ///         "w-min" => "min-content",
    ///     },
    ///     ..ListValues::default()
    /// });
    /// ```
    pub const fn default() -> Self {
        Self {
            prop: PropertyName::SingleProp(""),
            values: phf::Map::new(),
            namespace: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
            extra_slash: None,
        }
    }
}

impl<ArrayStr> ListValues<String, ArrayStr, HashMap<String, String>> {
    /// Make a default [`ListValues`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`ListValues::prop`] and [`ListValues::values`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`ListProperties::default`] is that this function can only be used to
    /// build a plugin using heap-allocated structures like `String`s, `Vec`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// fn main() {
    ///     let values = HashMap::from_iter(
    ///         ["fit", "max", "min"].iter().map(|v| {
    ///             (format!("w-{v}"), format!("width: {v}-content;"))
    ///         })
    ///     );
    ///
    ///     // Note: the DynamicPlugin type hint is required to help the compiler
    ///     // find the concrete types of type parameters
    ///     let _plugin: DynamicPlugin = Plugin::ListValues(ListValues {
    ///         prop: SingleProp("width".to_string()),
    ///         values,
    ///         ..ListValues::default_dynamic()
    ///     });
    /// }
    /// ```
    ///
    /// This example is equivalent to the one of [`ListValues::default`].
    pub fn default_dynamic() -> Self {
        Self {
            prop: PropertyName::SingleProp(String::new()),
            values: HashMap::new(),
            namespace: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
            extra_slash: None,
        }
    }
}

/// Define a plugin which supports all spacing modifiers,
/// that is a (potentially floating) number, a fraction (e.g `3/4`) or `px`.
///
/// This plugin kind can also support the `auto` and `full` modifiers by setting [`Spacing::has_auto`] and [`Spacing::has_full`].
///
/// ### Example
///
/// ```
/// use encre_css::{Config, generate};
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::Spacing(Spacing {
///     namespace: "h",
///     prop: SingleProp("height"),
///     has_auto: Some(true),
///     has_full: Some(true),
///     ..Spacing::default()
/// });
///
/// let mut config = Config::default();
/// config.register_plugin(&PLUGIN);
///
/// let generated = generate(["h-2", "h-3/4", "h-px", "h-auto", "h-full"], &config);
///
/// assert!(generated.ends_with(r".h-2 {
///   height: 0.5rem;
/// }
///
/// .h-3\/4 {
///   height: 75%;
/// }
///
/// .h-auto {
///   height: auto;
/// }
///
/// .h-full {
///   height: 100%;
/// }
///
/// .h-px {
///   height: 1px;
/// }"));
/// ```
///
/// ### Example in TOML
///
/// ```toml
/// [[custom_plugins]]
///
/// [custom_plugins.Spacing]
/// namespace = "h"
/// prop = "height"
/// has_auto = true
/// has_full = true
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Spacing<Str, ArrayStr, MapStr> {
    /// The namespace (i.e common prefix) that all classes need to start with in order to be
    /// matched by this plugin.
    pub namespace: Str,

    /// The CSS property name of the generated CSS rule.
    ///
    /// It can be a single property using [`PropertyName::SingleProp`] or a list of properties
    /// using [`PropertyName::MultipleProps`], in which case the value will be copied for all
    /// properties.
    pub prop: PropertyName<Str, ArrayStr>,

    /// Automatically add support for the `auto` modifier.
    ///
    /// If this method is called, an `auto` modifier will generate an `auto` CSS property value.
    pub has_auto: Option<bool>,

    /// Automatically add support for the `full` modifier.
    ///
    /// If this method is called, a `full` modifier will generate a `100%` CSS property value.
    pub has_full: Option<bool>,

    #[doc = include_str!("./doc_template.md")]
    pub template: Option<PropertyName<Str, ArrayStr>>,

    #[doc = include_str!("./doc_extra_rule_css.md")]
    pub extra_rule_css: Option<ArrayStr>,

    #[doc = include_str!("./doc_extra_css.md")]
    pub extra_css: Option<MapStr>,

    #[doc = include_str!("./doc_extra_class.md")]
    pub extra_class: Option<Str>,

    #[doc = include_str!("./doc_extra_slash.md")]
    pub extra_slash: Option<ExtraSlash<Str, MapStr>>,
}

impl<ArrayStr, MapStr> Spacing<&'static str, ArrayStr, MapStr> {
    /// Make a default [`Spacing`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Spacing::namespace`] and [`Spacing::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Spacing::default_dynamic`] is that this function can only be used to
    /// build a plugin using static structures like `&[]`s, `&'static str`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::Spacing(Spacing {
    ///     namespace: "h",
    ///     prop: SingleProp("height"),
    ///     ..Spacing::default()
    /// });
    /// ```
    pub const fn default() -> Self {
        Self {
            namespace: "",
            prop: PropertyName::SingleProp(""),
            has_auto: None,
            has_full: None,
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
            extra_slash: None,
        }
    }
}

impl<ArrayStr, MapStr> Spacing<String, ArrayStr, MapStr> {
    /// Make a default [`Spacing`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Spacing::namespace`] and [`Spacing::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Spacing::default`] is that this function can only be used to
    /// build a plugin using heap-allocated structures like `String`s, `Vec`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// fn main() {
    ///     // Note: the DynamicPlugin type hint is required to help the compiler
    ///     // find the concrete types of type parameters
    ///     let _plugin: DynamicPlugin = Plugin::Spacing(Spacing {
    ///         namespace: "h".to_string(),
    ///         prop: SingleProp("height".to_string()),
    ///         ..Spacing::default_dynamic()
    ///     });
    /// }
    /// ```
    ///
    /// This example is equivalent to the one of [`Spacing::default`].
    pub fn default_dynamic() -> Self {
        Self {
            namespace: String::new(),
            prop: PropertyName::SingleProp(String::new()),
            has_auto: None,
            has_full: None,
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
            extra_slash: None,
        }
    }
}

/// Define a plugin which supports all color modifiers, e.g `red-200` (the list of colors is based
/// on [`BUILTIN_COLORS`] and [`Theme::colors`] which is defined by the [`Config`]).
///
/// [`BUILTIN_COLORS`]: crate::config::BUILTIN_COLORS
/// [`Theme::colors`]: crate::config::Theme::colors
/// [`Config`]: crate::config::Config
///
/// ### Example
///
/// ```
/// use encre_css::{Config, generate};
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::Color(Color {
///     namespace: "bg",
///     prop: SingleProp("background-color"),
///     ..Color::default()
/// });
///
/// let mut config = Config::default();
/// config.register_plugin(&PLUGIN);
///
/// let generated = generate(["bg-red-200", "bg-black", "bg-inherit"], &config);
///
/// assert!(generated.ends_with(r".bg-black {
///   background-color: #000;
/// }
///
/// .bg-inherit {
///   background-color: inherit;
/// }
///
/// .bg-red-200 {
///   background-color: oklch(88.5% .062 18.334);
/// }"));
/// ```
///
/// ### Example in TOML
///
/// ```toml
/// [[custom_plugins]]
///
/// [custom_plugins.Color]
/// namespace = "bg"
/// prop = "background-color"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Color<Str, ArrayStr, MapStr> {
    /// The namespace (i.e common prefix) that all classes need to start with in order to be
    /// matched by this plugin.
    pub namespace: Str,

    /// The CSS property name of the generated CSS rule.
    ///
    /// It can be a single property using [`PropertyName::SingleProp`] or a list of properties
    /// using [`PropertyName::MultipleProps`], in which case the value will be copied for all
    /// properties.
    pub prop: PropertyName<Str, ArrayStr>,

    #[doc = include_str!("./doc_template.md")]
    pub template: Option<PropertyName<Str, ArrayStr>>,

    #[doc = include_str!("./doc_extra_rule_css.md")]
    pub extra_rule_css: Option<ArrayStr>,

    #[doc = include_str!("./doc_extra_css.md")]
    pub extra_css: Option<MapStr>,

    #[doc = include_str!("./doc_extra_class.md")]
    pub extra_class: Option<Str>,
}

impl<ArrayStr, MapStr> Color<&'static str, ArrayStr, MapStr> {
    /// Make a default [`Color`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Color::namespace`] and [`Color::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Color::default_dynamic`] is that this function can only be used to
    /// build a plugin using static structures like `&[]`s, `&'static str`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::Color(Color {
    ///     namespace: "bg",
    ///     prop: SingleProp("background-color"),
    ///     ..Color::default()
    /// });
    /// ```
    pub const fn default() -> Self {
        Self {
            namespace: "",
            prop: PropertyName::SingleProp(""),
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
        }
    }
}

impl<ArrayStr, MapStr> Color<String, ArrayStr, MapStr> {
    /// Make a default [`Color`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Color::namespace`] and [`Color::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Color::default`] is that this function can only be used to
    /// build a plugin using heap-allocated structures like `String`s, `Vec`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// fn main() {
    ///     // Note: the DynamicPlugin type hint is required to help the compiler
    ///     // find the concrete types of type parameters
    ///     let _plugin: DynamicPlugin = Plugin::Color(Color {
    ///         namespace: "bg".to_string(),
    ///         prop: SingleProp("background-color".to_string()),
    ///         ..Color::default_dynamic()
    ///     });
    /// }
    /// ```
    ///
    /// This example is equivalent to the one of [`Color::default`].
    pub fn default_dynamic() -> Self {
        Self {
            namespace: String::new(),
            prop: PropertyName::SingleProp(String::new()),
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
        }
    }
}

/// Define a plugin which supports any number as modifier.
///
/// The number must be an integer (signed integers can be supported by enabling
/// [`Number::has_negative`]).
///
/// ### Example
///
/// ```
/// use encre_css::{Config, generate};
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::Number(Number {
///    namespace: "z",
///    prop: SingleProp("z-index"),
///    has_negative: Some(true),
///    has_auto: Some(true),
///    ..Number::default()
/// });
///
/// let mut config = Config::default();
/// config.register_plugin(&PLUGIN);
///
/// let generated = generate(["z-20", "-z-5", "z-auto"], &config);
///
/// assert!(generated.ends_with(r".-z-5 {
///   z-index: -5;
/// }
///
/// .z-20 {
///   z-index: 20;
/// }
///
/// .z-auto {
///   z-index: auto;
/// }"));
/// ```
///
/// ### Example in TOML
///
/// ```toml
/// [[custom_plugins]]
///
/// [custom_plugins.Number]
/// namespace = "z"
/// prop = "z-index"
/// has_negative = true
/// has_auto = true
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Number<Str, ArrayStr, MapStr> {
    /// The namespace (i.e common prefix) that all classes need to start with in order to be
    /// matched by this plugin.
    pub namespace: Str,

    /// The CSS property name of the generated CSS rule.
    ///
    /// It can be a single property using [`PropertyName::SingleProp`] or a list of properties
    /// using [`PropertyName::MultipleProps`], in which case the value will be copied for all
    /// properties.
    pub prop: PropertyName<Str, ArrayStr>,

    /// A float by which to divide the number given in the utility class.
    ///
    /// It can for example be used to support classes having a percentage between 1-100 but which
    /// need to generate a CSS property value between 0-1.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::{Config, generate};
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::Number(Number {
    ///     namespace: "custom-opacity",
    ///     prop: SingleProp("opacity"),
    ///     divide_by: Some(100.0),
    ///     ..Number::default()
    /// });
    ///
    /// let mut config = Config::default();
    /// config.register_plugin(&PLUGIN);
    ///
    /// let generated = generate(["custom-opacity-80", "custom-opacity-2"], &config);
    ///
    /// assert!(generated.ends_with(r".custom-opacity-2 {
    ///   opacity: 0.02;
    /// }
    ///
    /// .custom-opacity-80 {
    ///   opacity: 0.8;
    /// }"));
    /// ```
    pub divide_by: Option<f32>,

    /// Automatically add support for the `auto` modifier.
    ///
    /// If this method is called, an `auto` modifier will generate an `auto` CSS property value.
    pub has_auto: Option<bool>,

    /// Automatically add support for an empty modifier.
    ///
    /// If this method is called, an empty modifier will generate a `1` CSS property value.
    pub has_empty: Option<bool>,

    /// Automatically add support for negative modifiers.
    pub has_negative: Option<bool>,

    #[doc = include_str!("./doc_template.md")]
    pub template: Option<PropertyName<Str, ArrayStr>>,

    #[doc = include_str!("./doc_extra_rule_css.md")]
    pub extra_rule_css: Option<ArrayStr>,

    #[doc = include_str!("./doc_extra_css.md")]
    pub extra_css: Option<MapStr>,

    #[doc = include_str!("./doc_extra_class.md")]
    pub extra_class: Option<Str>,

    #[doc = include_str!("./doc_extra_slash.md")]
    pub extra_slash: Option<ExtraSlash<Str, MapStr>>,
}

impl<ArrayStr, MapStr> Number<&'static str, ArrayStr, MapStr> {
    /// Make a default [`Number`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Number::namespace`] and [`Number::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Number::default_dynamic`] is that this function can only be used to
    /// build a plugin using static structures like `&[]`s, `&'static str`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::Number(Number {
    ///     namespace: "z",
    ///     prop: SingleProp("z-index"),
    ///     ..Number::default()
    /// });
    /// ```
    pub const fn default() -> Self {
        Self {
            namespace: "",
            prop: PropertyName::SingleProp(""),
            divide_by: None,
            has_auto: None,
            has_empty: None,
            has_negative: None,
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
            extra_slash: None,
        }
    }
}

impl<ArrayStr, MapStr> Number<String, ArrayStr, MapStr> {
    /// Make a default [`Number`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Number::namespace`] and [`Number::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Number::default`] is that this function can only be used to
    /// build a plugin using heap-allocated structures like `String`s, `Vec`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// fn main() {
    ///     // Note: the DynamicPlugin type hint is required to help the compiler
    ///     // find the concrete types of type parameters
    ///     let _plugin: DynamicPlugin = Plugin::Number(Number {
    ///         namespace: "z".to_string(),
    ///         prop: SingleProp("z-index".to_string()),
    ///         ..Number::default_dynamic()
    ///     });
    /// }
    /// ```
    ///
    /// This example is equivalent to the one of [`Number::default`].
    pub fn default_dynamic() -> Self {
        Self {
            namespace: String::new(),
            prop: PropertyName::SingleProp(String::new()),
            divide_by: None,
            has_auto: None,
            has_empty: None,
            has_negative: None,
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
            extra_slash: None,
        }
    }
}

/// Define a plugin supporting [`arbitrary values`], i.e all selectors in the form
/// `<namespace>-[...]` (i.e the modifier is wrapped in square brackets).
///
/// It directly copies the contents given inside brackets as the value of the `<prop>` CSS
/// propertie(s).
///
/// By default, all values are allowed by the plugin and it's up to the final user to only use
/// valid CSS values for the property. However, if several [`Arbitrary`] plugins
/// share the same namespace, it's *required* to disambiguate which plugins should handle the
/// selector. In this case, [`Arbitrary::disambiguate`] should be used to
/// only handle the selector if the arbitrary CSS value has a specific CSS type or a specific manual hint.
///
/// ### Example
///
/// ```
/// use encre_css::{Config, generate};
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::Arbitrary(Arbitrary {
///     namespace: "mask",
///     prop: SingleProp("mask-position"),
///     ..Arbitrary::default()
/// });
///
/// let mut config = Config::default();
/// config.register_plugin(&PLUGIN);
///
/// let generated = generate(["mask-[25%]", "mask-[left_center]"], &config);
///
/// assert!(generated.ends_with(r".mask-\[25\%\] {
///   mask-position: 25%;
/// }
///
/// .mask-\[left_center\] {
///   mask-position: left center;
/// }"));
/// ```
///
/// ### Example in TOML
///
/// ```toml
/// [[custom_plugins]]
///
/// [custom_plugins.Arbitrary]
/// namespace = "mask"
/// prop = "mask-position"
/// ```
///
/// [`arbitrary values`]: crate::selector
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Arbitrary<Str, ArrayStr, MapStr, ArrayMatched> {
    /// The namespace (i.e common prefix) that all classes need to start with in order to be
    /// matched by this plugin.
    pub namespace: Str,

    /// The CSS property name of the generated CSS rule.
    ///
    /// It can be a single property using [`PropertyName::SingleProp`] or a list of properties
    /// using [`PropertyName::MultipleProps`], in which case the value will be copied for all
    /// properties.
    pub prop: PropertyName<Str, ArrayStr>,

    /// If the arbitrary value is a shadow, replace all the colors used by a single CSS variable
    /// given as string.
    ///
    /// This field should only be used for shadows that need to have their colors separately set
    /// using a dedicated utility class.
    ///
    /// If the value contains a placeholder `{}`, it will be replaced by the previous color value.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::{Config, generate};
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN_SHADOW: StaticPlugin = Plugin::Arbitrary(Arbitrary {
    ///     namespace: "custom-shadow",
    ///     prop: SingleProp("box-shadow"),
    ///     shadow_color_replacement: Some("var(--shadow-color, {})"),
    ///     ..Arbitrary::default()
    /// });
    ///
    /// const PLUGIN_SHADOW_COLOR: StaticPlugin = Plugin::Color(Color {
    ///     namespace: "custom-shadow-color",
    ///     prop: SingleProp("--shadow-color"),
    ///     ..Color::default()
    /// });
    ///
    /// let mut config = Config::default();
    /// config.register_plugin(&PLUGIN_SHADOW);
    /// config.register_plugin(&PLUGIN_SHADOW_COLOR);
    ///
    /// let generated = generate(["custom-shadow-[10px_5px_5px_red]", "custom-shadow-color-blue-100"], &config);
    ///
    /// assert!(generated.ends_with(r"
    /// .custom-shadow-\[10px_5px_5px_red\] {
    ///   box-shadow: 10px 5px 5px var(--shadow-color, red);
    /// }
    ///
    /// .custom-shadow-color-blue-100 {
    ///   --shadow-color: oklch(93.2% .032 255.585);
    /// }"));
    /// ```
    ///
    ///
    pub shadow_color_replacement: Option<Str>,

    /// See [`ArbitraryDisambiguate`].
    pub disambiguate: Option<ArbitraryDisambiguate<ArrayMatched>>,

    #[doc = include_str!("./doc_template.md")]
    pub template: Option<PropertyName<Str, ArrayStr>>,

    #[doc = include_str!("./doc_extra_rule_css.md")]
    pub extra_rule_css: Option<ArrayStr>,

    #[doc = include_str!("./doc_extra_css.md")]
    pub extra_css: Option<MapStr>,

    #[doc = include_str!("./doc_extra_class.md")]
    pub extra_class: Option<Str>,
}

impl<ArrayStr, MapStr, ArrayMatched> Arbitrary<&'static str, ArrayStr, MapStr, ArrayMatched> {
    /// Make a default [`Arbitrary`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Arbitrary::namespace`] and [`Arbitrary::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Arbitrary::default_dynamic`] is that this function can only be used to
    /// build a plugin using static structures like `&[]`s, `&'static str`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::Arbitrary(Arbitrary {
    ///     namespace: "gap",
    ///     prop: SingleProp("gap"),
    ///     ..Arbitrary::default()
    /// });
    /// ```
    pub const fn default() -> Self {
        Self {
            namespace: "",
            prop: PropertyName::SingleProp(""),
            shadow_color_replacement: None,
            disambiguate: None,
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,

        }
    }
}

impl<ArrayStr, MapStr, ArrayMatched> Arbitrary<String, ArrayStr, MapStr, ArrayMatched> {
    /// Make a default [`Arbitrary`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Arbitrary::namespace`] and [`Arbitrary::prop`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Arbitrary::default`] is that this function can only be used to
    /// build a plugin using heap-allocated structures like `String`s, `Vec`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// fn main() {
    ///     // Note: the DynamicPlugin type hint is required to help the compiler
    ///     // find the concrete types of type parameters
    ///     let _plugin: DynamicPlugin = Plugin::Arbitrary(Arbitrary {
    ///         namespace: "gap".to_string(),
    ///         prop: SingleProp("gap".to_string()),
    ///         ..Arbitrary::default_dynamic()
    ///     });
    /// }
    /// ```
    ///
    /// This example is equivalent to the one of [`Arbitrary::default`].
    pub fn default_dynamic() -> Self {
        Self {
            namespace: String::new(),
            prop: PropertyName::SingleProp(String::new()),
            shadow_color_replacement: None,
            disambiguate: None,
            template: None,
            extra_rule_css: None,
            extra_css: None,
            extra_class: None,
        }
    }
}

/// A powerful kind allowing the use a Rust function to handle all selectors in the form
/// `<namespace>-...`.
///
/// This plugin kind is (of course) not serializable.
///
/// The [`can_handle`] field function takes a [`ContextCanHandle`] structure and returns whether
/// the plugin is capable of handling the utility class given in the context.
///
/// The [`handle`] field function takes a [`ContextHandle`] structure containing the modifier, the current
/// configuration and a buffer containing the whole CSS currently generated. You can use the
/// [`Buffer`] structure (especially the [`Buffer::line`] and [`Buffer::lines`] functions) to
/// push CSS declarations to it, they will be automatically indented.
///
/// [`generate_wrapper`] (and the more powerful [`generate_at_rules`] and [`generate_class`])
/// should be called to generate the CSS rule wrapping.
///
/// ### Example
///
/// ```
/// use encre_css::{Config, generate};
/// use encre_css::prelude::build_plugin::*;
/// use std::collections::HashMap;
///
/// /// Reads the `emoji` extra field of the configuration to find the replacement emoji.
/// fn extract_emoji_value<'a>(config: &'a Config, value: &str) -> Option<&'a str> {
///     config.extra.get("emoji")
///         .and_then(|r| r.as_table())
///         .and_then(|r| r.get(value))
///         .and_then(|r| r.as_str())
/// }
///
/// const PLUGIN: StaticPlugin = Plugin::Functional(Functional {
///     namespace: "emoji",
///     can_handle: |context| matches!(context.modifier, Modifier::Builtin {
///         value,
///         ..
///     } if extract_emoji_value(context.config, value).is_some()),
///     handle: |context| {
///         // Only accept static modifiers, and dynamically fetch them from the
///         // `emoji` extra field of the configuration
///         if let Modifier::Builtin { value, .. } = context.modifier
///         && let Some(value) = extract_emoji_value(&context.config, value) {
///             generate_wrapper(context, |context| {
///                 context.buffer.line(format_args!("content: \"{value}\";"));
///             });
///         }
///     },
/// });
///
/// let mut config = Config::default();
/// config.extra.add(
///     "emoji",
///     HashMap::from_iter([("tada", "\u{1f389}"), ("rocket", "\u{1f680}")]),
/// );
/// config.register_plugin(&PLUGIN);
///
/// let generated = generate(["emoji-tada", "emoji-rocket"], &config);
///
/// assert!(generated.ends_with(".emoji-rocket {
///   content: \"\u{1f680}\";
/// }
///
/// .emoji-tada {
///   content: \"\u{1f389}\";
/// }"));
/// ```
///
/// [`Buffer`]: crate::utils::buffer::Buffer
/// [`Buffer::line`]: crate::utils::buffer::Buffer::line
/// [`Buffer::lines`]: crate::utils::buffer::Buffer::lines
/// [`can_handle`]: Functional::can_handle
/// [`handle`]: Functional::handle
/// [`generate_at_rules`]: crate::generator::generate_at_rules
/// [`generate_class`]: crate::generator::generate_class
/// [`generate_wrapper`]: crate::generator::generate_wrapper
#[derive(Debug, Clone)]
pub struct Functional<Str> {
    /// The namespace (i.e common prefix) that all classes need to start with in order to be
    /// matched by this plugin.
    pub namespace: Str,

    /// A function returning whether a specific class (passed inside the context) is matched by
    /// this plugin.
    pub can_handle: fn(&ContextCanHandle) -> bool,

    /// A function called to generate the CSS of a matched class.
    ///
    /// It should use [`generate_wrapper`] (and the more powerful [`generate_at_rules`] and [`generate_class`])
    /// to generate the CSS rule wrapping.
    ///
    /// Various notes:
    ///
    /// - The CSS written should end with a newline
    /// - Arbitrary values are already normalized (e.g. underscores are replaced by spaces)
    /// - This function is guaranteed to be called only once per selector
    ///
    /// [`generate_wrapper`]: crate::generator::generate_wrapper
    /// [`generate_at_rules`]: crate::generator::generate_at_rules
    /// [`generate_class`]: crate::generator::generate_class
    pub handle: fn(&mut ContextHandle),
}

impl Functional<&'static str> {
    /// Make a default [`Functional`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Functional::namespace`], [`Functional::can_handle`] and [`Functional::handle`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Functional::default_dynamic`] is that this function can only be used to
    /// build a plugin using static structures like `&[]`s, `&'static str`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// const PLUGIN: StaticPlugin = Plugin::Functional(Functional {
    ///     namespace: "emoji",
    ///     can_handle: |context| matches!(context.modifier, Modifier::Builtin { value: "tada", .. }),
    ///     handle: |context| {
    ///         generate_wrapper(context, |context| {
    ///             context.buffer.line(format_args!("content: \"\u{1f389}\";"));
    ///         });
    ///     },
    ///     ..Functional::default()
    /// });
    /// ```
    pub const fn default() -> Self {
        Self {
            namespace: "",
            can_handle: can_handle_nop,
            handle: handle_nop,
        }
    }
}

impl Functional<String> {
    /// Make a default [`Functional`] plugin kind.
    ///
    /// All required fields are initialized with empty values and optional fields are initialized
    /// with `None`.
    ///
    /// You should at least set [`Functional::namespace`], [`Functional::can_handle`] and [`Functional::handle`] after calling this function.
    ///
    /// This function is intended to be used as an automatic filler for default values using the
    /// [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
    ///
    /// The difference with [`Functional::default`] is that this function can only be used to
    /// build a plugin using heap-allocated structures like `String`s, `Vec`s.
    ///
    /// ### Example
    ///
    /// ```
    /// use encre_css::prelude::build_plugin::*;
    ///
    /// fn main() {
    ///     // Note: the DynamicPlugin type hint is required to help the compiler
    ///     // find the concrete types of type parameters
    ///     let _plugin: DynamicPlugin = Plugin::Functional(Functional {
    ///         namespace: "emoji".to_string(),
    ///         can_handle: |context| matches!(context.modifier, Modifier::Builtin { value: "tada", .. }),
    ///         handle: |context| {
    ///             generate_wrapper(context, |context| {
    ///                 context.buffer.line(format_args!("content: \"\u{1f389}\";"));
    ///             });
    ///         },
    ///         ..Functional::default_dynamic()
    ///     });
    /// }
    /// ```
    ///
    /// This example is equivalent to the one of [`Functional::default`].
    pub fn default_dynamic() -> Self {
        Self {
            namespace: String::new(),
            can_handle: can_handle_nop,
            handle: handle_nop,
        }
    }
}

/// A plugin is a structure capable of generating CSS styles from a CSS selector.
///
/// Several kinds of plugins exist and define what values are accepted as selector or modifier and
/// what CSS is generated based on the input selector. The API is designed to be fully declarative
/// (so that plugin declarations are serializable), except for the
/// [functional kind](Plugin::Functional).
///
/// Each plugin kind has a set of required parameters and a set of default parameters which can be
/// automatically filled in Rust using the [struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax).
///
/// It's common to define several plugins to handle a single utility class, and to define static
/// plugins as constants (the `default` function on each plugin kind is a `const fn`).
///
/// After you have defined a plugin, you need to register it in the [`Config`] structure by calling
/// [`Config::register_plugin`].
///
/// # Simple example (defines the static values of the `font-family` plugin)
///
/// ```
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::ListValues(ListValues {
///     prop: SingleProp("font-family"),
///     values: map! {
///         "font-sans" => r#"ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont"#,
///         "font-serif" => r#"Georgia, Cambria, "Times New Roman", Times, serif"#,
///         "font-mono" => r#"Menlo, Monaco, Consolas, "Liberation Mono", monospace"#,
///     },
///     ..ListValues::default()
/// });
/// ```
///
/// # More advanced example (defines the `stroke-width` plugin)
///
/// ```
/// use encre_css::prelude::build_plugin::*;
///
/// const PLUGIN: StaticPlugin = Plugin::Number(Number {
///     namespace: "stroke",
///     prop: SingleProp("stroke-width"),
///     template: Some(SingleProp("{}px")),
///     ..Number::default()
/// });
///
/// // There's also a plugin sharing the same `stroke` namespace (which helps changing the
/// // stroke color, e.g `stroke-red-500`), so it's required to define `hints` and `matchers`
/// const PLUGIN_ARBITRARY: StaticPlugin = Plugin::Arbitrary(Arbitrary {
///     namespace: "stroke",
///     prop: SingleProp("stroke-width"),
///     disambiguate: Some(ArbitraryDisambiguate {
///         matched: &[CssType::Length, CssType::Percentage, CssType::LineWidth, CssType::Number],
///         separation: ArbitraryDisambiguateSeparation::None,
///     }),
///     ..Arbitrary::default()
/// });
/// ```
///
/// # More powerful usage
///
/// If you need to have full control over the CSS **rule** generated, you can use the [`Functional`]
/// plugin kind. It allows executing a full-blown Rust function for each selector having a specific
/// namespace. However, it's (of course) not serializable, and thus cannot be used in, e.g a TOML
/// configuration.
///
/// ### Example
///
/// ```
/// use encre_css::Config;
/// use encre_css::prelude::build_plugin::*;
///
/// /// Reads the `emoji` extra field of the configuration to find the replacement emoji.
/// fn extract_emoji_value<'a>(config: &'a Config, value: &str) -> Option<&'a str> {
///     config.extra.get("emoji")
///         .and_then(|r| r.as_table())
///         .and_then(|r| r.get(value))
///         .and_then(|r| r.as_str())
/// }
///
/// const PLUGIN: StaticPlugin = Plugin::Functional(Functional {
///     namespace: "emoji",
///     can_handle: |context| matches!(context.modifier, Modifier::Builtin {
///         value,
///         ..
///     } if extract_emoji_value(context.config, value).is_some()),
///     handle: |context| {
///         // Only accept static modifiers, and dynamically fetch them from the
///         // `emoji` extra field of the configuration
///         if let Modifier::Builtin { value, .. } = context.modifier
///         && let Some(value) = extract_emoji_value(&context.config, value) {
///             generate_at_rules(context, |context| {
///                 generate_class(
///                     context,
///                     |context| {
///                         context.buffer.line(format_args!("content: \"{value}\";"));
///                     },
///                     "",
///                 );
///             });
///         }
///     },
/// });
/// ```
///
/// Have a look at <https://gitlab.com/encre-org/encre-css/tree/main/crates/encre-css/src/plugins>
/// for more examples.
///
/// # Define a plugin in TOML
///
/// Instead of defining plugins in Rust, you can also define them in `encre-css`'s TOML configuration
/// (or every other language that uses a `serde` deserializer).
/// The sole exception is plugins using the [`Functional`] kind which are not serializable.
///
/// To do that, you need to add a new entry in the `custom_plugins` list of the configuration.
/// You can then define plugins as you would do in Rust.
///
/// ### Example
///
/// ```toml
/// [[custom_plugins]]
///
/// [custom_plugins.Number]
/// namespace = "stroke"
/// prop = "stroke-width"
/// template = "{}px"
///
/// [[custom_plugins]]
///
/// [custom_plugins.Arbitrary]
/// namespace = "stroke"
/// prop = "stroke-width"
/// hints = ["Length", "Percentage"]
/// matchers = [["Length", "Percentage", "LineWidth", "Number"], "None"]
/// ```
///
/// # Advice
///
/// `encre-css` builds a [trie structure](https://en.wikipedia.org/wiki/Trie) based on the
/// namespace of the plugins to optimize matching a utility class to a specific plugin, so it's
/// **highly discouraged to leave the namespace of a plugin empty**, otherwise the performances will
/// decrease heavily.
///
/// # Release a plugin as a crate
///
/// If you want to release your custom plugins as a crate, you can export a `register` function
/// taking a mutable reference to a [`Config`] structure and use the [`Config::register_plugin`]
/// function to register them.
///
/// ```ignore
/// pub fn register(config: &mut Config) {
///     config.register_plugin(&PLUGIN);
///     config.register_plugin(&PLUGIN_ARBITRARY);
/// }
/// ```
///
/// [`Config::register_plugin`]: crate::Config::register_plugin
/// [`Config`]: crate::Config
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Plugin<Str, ArrayStr, MapStr, MapArrayStr, ArrayMatched> {
    /// See [`ListProperties`].
    ListProperties(ListProperties<Str, ArrayStr, MapStr, MapArrayStr>),

    /// See [`ListValues`].
    ListValues(ListValues<Str, ArrayStr, MapStr>),

    /// See [`Spacing`].
    Spacing(Spacing<Str, ArrayStr, MapStr>),

    /// See [`Color`].
    Color(Color<Str, ArrayStr, MapStr>),

    /// See [`Number`].
    Number(Number<Str, ArrayStr, MapStr>),

    /// See [`Arbitrary`].
    Arbitrary(Arbitrary<Str, ArrayStr, MapStr, ArrayMatched>),

    /// See [`Functional`].
    ///
    /// Not serializable.
    #[serde(skip)]
    Functional(Functional<Str>),
}