/
selector.rs
1244 lines (1098 loc) · 41.4 KB
/
selector.rs
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
use cssparser::*;
use parcel_selectors::{SelectorList, parser::{SelectorImpl, Selector, Combinator, Component}, attr::{AttrSelectorOperator, ParsedAttrSelectorOperation, ParsedCaseSensitivity}};
use std::fmt;
use std::fmt::Write;
use crate::printer::Printer;
use crate::traits::ToCss;
use crate::compat::Feature;
use crate::vendor_prefix::VendorPrefix;
use crate::targets::Browsers;
use crate::rules::{ToCssWithContext, StyleContext};
use std::collections::HashMap;
use crate::error::{ParserError, PrinterError};
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Selectors;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SelectorString(pub String);
impl<'a> std::convert::From<&'a str> for SelectorString {
fn from(s: &str) -> SelectorString {
SelectorString(s.into())
}
}
impl cssparser::ToCss for SelectorString {
fn to_css<W>(&self, dest: &mut W) -> std::fmt::Result where W: std::fmt::Write {
write!(CssStringWriter::new(dest), "{}", &self.0)
}
}
impl SelectorString {
pub fn write_identifier<W>(&self, dest: &mut W)-> Result<(), PrinterError> where W: fmt::Write {
serialize_identifier(&self.0, dest)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct SelectorIdent(pub String);
impl<'a> std::convert::From<&'a str> for SelectorIdent {
fn from(s: &str) -> SelectorIdent {
SelectorIdent(s.into())
}
}
impl cssparser::ToCss for SelectorIdent {
fn to_css<W>(&self, dest: &mut W) -> std::fmt::Result where W: std::fmt::Write {
serialize_identifier(&self.0, dest)
}
}
impl SelectorImpl for Selectors {
type AttrValue = SelectorString;
type Identifier = SelectorIdent;
type LocalName = SelectorIdent;
type NamespacePrefix = SelectorIdent;
type NamespaceUrl = SelectorIdent;
type BorrowedNamespaceUrl = SelectorIdent;
type BorrowedLocalName = SelectorIdent;
type NonTSPseudoClass = PseudoClass;
type PseudoElement = PseudoElement;
type ExtraMatchingData = ();
}
pub struct SelectorParser<'a> {
pub default_namespace: &'a Option<String>,
pub namespace_prefixes: &'a HashMap<String, String>,
pub is_nesting_allowed: bool,
pub css_modules: bool
}
impl<'a, 'i> parcel_selectors::parser::Parser<'i> for SelectorParser<'a> {
type Impl = Selectors;
type Error = ParserError<'i>;
fn parse_non_ts_pseudo_class(
&self,
_: SourceLocation,
name: CowRcStr<'i>,
) -> Result<PseudoClass, ParseError<'i, Self::Error>> {
use PseudoClass::*;
let pseudo_class = match_ignore_ascii_case! { &name,
// https://drafts.csswg.org/selectors-4/#useraction-pseudos
"hover" => Hover,
"active" => Active,
"focus" => Focus,
"focus-visible" => FocusVisible,
"focus-within" => FocusWithin,
// https://drafts.csswg.org/selectors-4/#time-pseudos
"current" => Current,
"past" => Past,
"future" => Future,
// https://drafts.csswg.org/selectors-4/#resource-pseudos
"playing" => Playing,
"paused" => Paused,
"seeking" => Seeking,
"buffering" => Buffering,
"stalled" => Stalled,
"muted" => Muted,
"volume-locked" => VolumeLocked,
// https://fullscreen.spec.whatwg.org/#:fullscreen-pseudo-class
"fullscreen" => Fullscreen(VendorPrefix::None),
"-webkit-full-screen" => Fullscreen(VendorPrefix::WebKit),
"-moz-full-screen" => Fullscreen(VendorPrefix::Moz),
"-ms-fullscreen" => Fullscreen(VendorPrefix::Ms),
// https://drafts.csswg.org/selectors-4/#the-defined-pseudo
"defined" => Defined,
// https://drafts.csswg.org/selectors-4/#location
"any-link" => AnyLink(VendorPrefix::None),
"-webkit-any-link" => AnyLink(VendorPrefix::WebKit),
"-moz-any-link" => AnyLink(VendorPrefix::Moz),
"link" => Link,
"local-link" => LocalLink,
"target" => Target,
"target-within" => TargetWithin,
"visited" => Visited,
// https://drafts.csswg.org/selectors-4/#input-pseudos
"enabled" => Enabled,
"disabled" => Disabled,
"read-only" => ReadOnly(VendorPrefix::None),
"-moz-read-only" => ReadOnly(VendorPrefix::Moz),
"read-write" => ReadWrite(VendorPrefix::None),
"-moz-read-write" => ReadWrite(VendorPrefix::Moz),
"placeholder-shown" => PlaceholderShown(VendorPrefix::None),
"-moz-placeholder-shown" => PlaceholderShown(VendorPrefix::Moz),
"-ms-placeholder-shown" => PlaceholderShown(VendorPrefix::Ms),
"default" => Default,
"checked" => Checked,
"indeterminate" => Indeterminate,
"blank" => Blank,
"valid" => Valid,
"invalid" => Invalid,
"in-range" => InRange,
"out-of-range" => OutOfRange,
"required" => Required,
"optional" => Optional,
"user-valid" => UserValid,
"user-invalid" => UserInvalid,
// https://html.spec.whatwg.org/multipage/semantics-other.html#selector-autofill
"autofill" => Autofill(VendorPrefix::None),
"-webkit-autofill" => Autofill(VendorPrefix::WebKit),
"-o-autofill" => Autofill(VendorPrefix::O),
_ => Custom(name.as_ref().into())
};
Ok(pseudo_class)
}
fn parse_non_ts_functional_pseudo_class<'t>(
&self,
name: CowRcStr<'i>,
parser: &mut cssparser::Parser<'i, 't>,
) -> Result<PseudoClass, ParseError<'i, Self::Error>> {
use PseudoClass::*;
let pseudo_class = match_ignore_ascii_case! { &name,
"lang" => Lang(parser.expect_ident_or_string()?.as_ref().into()),
"dir" => Dir(parser.expect_ident_or_string()?.as_ref().into()),
"local" if self.css_modules => Local(Box::new(parcel_selectors::parser::Selector::parse(self, parser)?)),
"global" if self.css_modules => Global(Box::new(parcel_selectors::parser::Selector::parse(self, parser)?)),
_ => return Err(parser.new_custom_error(parcel_selectors::parser::SelectorParseErrorKind::UnexpectedIdent(name.clone()))),
};
Ok(pseudo_class)
}
fn parse_pseudo_element(
&self,
_: SourceLocation,
name: CowRcStr<'i>,
) -> Result<PseudoElement, ParseError<'i, Self::Error>> {
use PseudoElement::*;
let pseudo_element = match_ignore_ascii_case! { &name,
"before" => Before,
"after" => After,
"first-line" => FirstLine,
"first-letter" => FirstLetter,
"selection" => Selection(VendorPrefix::None),
"-moz-selection" => Selection(VendorPrefix::Moz),
"placeholder" => Placeholder(VendorPrefix::None),
"-webkit-input-placeholder" => Placeholder(VendorPrefix::WebKit),
"-moz-placeholder" => Placeholder(VendorPrefix::Moz),
"-ms-input-placeholder" => Placeholder(VendorPrefix::Moz),
"marker" => Marker,
"backdrop" => Backdrop(VendorPrefix::None),
"-webkit-backdrop" => Backdrop(VendorPrefix::WebKit),
"file-selector-button" => FileSelectorButton(VendorPrefix::None),
"-webkit-file-upload-button" => FileSelectorButton(VendorPrefix::WebKit),
"-ms-browse" => FileSelectorButton(VendorPrefix::Ms),
_ => Custom(name.as_ref().into())
};
Ok(pseudo_element)
}
#[inline]
fn parse_slotted(&self) -> bool {
true
}
#[inline]
fn parse_host(&self) -> bool {
true
}
#[inline]
fn parse_is_and_where(&self) -> bool {
true
}
#[inline]
fn parse_part(&self) -> bool {
true
}
fn default_namespace(&self) -> Option<SelectorIdent> {
self.default_namespace.clone().map(SelectorIdent)
}
fn namespace_for_prefix(&self, prefix: &SelectorIdent) -> Option<SelectorIdent> {
self.namespace_prefixes.get(&prefix.0).cloned().map(SelectorIdent)
}
#[inline]
fn is_nesting_allowed(&self) -> bool {
self.is_nesting_allowed
}
}
/// https://drafts.csswg.org/selectors-4/#structural-pseudos
#[derive(Clone, Eq, PartialEq)]
pub enum PseudoClass {
// https://drafts.csswg.org/selectors-4/#linguistic-pseudos
Lang(Box<str>),
Dir(Box<str>),
// https://drafts.csswg.org/selectors-4/#useraction-pseudos
Hover,
Active,
Focus,
FocusVisible,
FocusWithin,
// https://drafts.csswg.org/selectors-4/#time-pseudos
Current,
Past,
Future,
// https://drafts.csswg.org/selectors-4/#resource-pseudos
Playing,
Paused,
Seeking,
Buffering,
Stalled,
Muted,
VolumeLocked,
// https://fullscreen.spec.whatwg.org/#:fullscreen-pseudo-class
Fullscreen(VendorPrefix),
// https://drafts.csswg.org/selectors-4/#the-defined-pseudo
Defined,
// https://drafts.csswg.org/selectors-4/#location
AnyLink(VendorPrefix),
Link,
LocalLink,
Target,
TargetWithin,
Visited,
// https://drafts.csswg.org/selectors-4/#input-pseudos
Enabled,
Disabled,
ReadOnly(VendorPrefix),
ReadWrite(VendorPrefix),
PlaceholderShown(VendorPrefix),
Default,
Checked,
Indeterminate,
Blank,
Valid,
Invalid,
InRange,
OutOfRange,
Required,
Optional,
UserValid,
UserInvalid,
// https://html.spec.whatwg.org/multipage/semantics-other.html#selector-autofill
Autofill(VendorPrefix),
// CSS modules
Local(Box<parcel_selectors::parser::Selector<Selectors>>),
Global(Box<parcel_selectors::parser::Selector<Selectors>>),
Custom(String)
}
impl parcel_selectors::parser::NonTSPseudoClass for PseudoClass {
type Impl = Selectors;
fn is_active_or_hover(&self) -> bool {
matches!(*self, PseudoClass::Active | PseudoClass::Hover)
}
fn is_user_action_state(&self) -> bool {
matches!(*self, PseudoClass::Active | PseudoClass::Hover | PseudoClass::Focus)
}
}
impl cssparser::ToCss for PseudoClass {
fn to_css<W>(&self, _: &mut W)-> std::fmt::Result where W: fmt::Write {
unreachable!()
}
}
impl ToCssWithContext for PseudoClass {
fn to_css_with_context<W>(&self, dest: &mut Printer<W>, context: Option<&StyleContext>) -> Result<(), PrinterError> where W: fmt::Write {
use PseudoClass::*;
match &self {
Lang(lang) => {
dest.write_str(":lang(")?;
serialize_identifier(lang, dest)?;
return dest.write_str(")");
}
Dir(dir) => {
dest.write_str(":dir(")?;
serialize_identifier(dir, dest)?;
return dest.write_str(")");
}
_ => {}
}
macro_rules! write_prefixed {
($prefix: ident, $val: expr) => {{
dest.write_char(':')?;
// If the printer has a vendor prefix override, use that.
let vp = if !dest.vendor_prefix.is_empty() {
dest.vendor_prefix
} else {
*$prefix
};
vp.to_css(dest)?;
dest.write_str($val)
}};
}
macro_rules! pseudo {
($key: ident, $s: literal) => {{
let class = if let Some(pseudo_classes) = &dest.pseudo_classes {
pseudo_classes.$key
} else {
None
};
if let Some(class) = class {
dest.write_char('.')?;
dest.write_ident(class)
} else {
dest.write_str($s)
}
}};
}
match &self {
// https://drafts.csswg.org/selectors-4/#useraction-pseudos
Hover => pseudo!(hover, ":hover"),
Active => pseudo!(active, ":active"),
Focus => pseudo!(focus, ":focus"),
FocusVisible => pseudo!(focus_visible, ":focus-visible"),
FocusWithin => pseudo!(focus_within, ":focus-within"),
// https://drafts.csswg.org/selectors-4/#time-pseudos
Current => dest.write_str(":current"),
Past => dest.write_str(":past"),
Future => dest.write_str(":future"),
// https://drafts.csswg.org/selectors-4/#resource-pseudos
Playing => dest.write_str(":playing"),
Paused => dest.write_str(":paused"),
Seeking => dest.write_str(":seeking"),
Buffering => dest.write_str(":buffering"),
Stalled => dest.write_str(":stalled"),
Muted => dest.write_str(":muted"),
VolumeLocked => dest.write_str(":volume-locked"),
// https://fullscreen.spec.whatwg.org/#:fullscreen-pseudo-class
Fullscreen(prefix) => {
dest.write_char(':')?;
let vp = if !dest.vendor_prefix.is_empty() {
dest.vendor_prefix
} else {
*prefix
};
vp.to_css(dest)?;
if vp == VendorPrefix::WebKit || vp == VendorPrefix::Moz {
dest.write_str("full-screen")
} else {
dest.write_str("fullscreen")
}
},
// https://drafts.csswg.org/selectors-4/#the-defined-pseudo
Defined => dest.write_str(":defined"),
// https://drafts.csswg.org/selectors-4/#location
AnyLink(prefix) => write_prefixed!(prefix, "any-link"),
Link => dest.write_str(":link"),
LocalLink => dest.write_str(":local-link"),
Target => dest.write_str(":target"),
TargetWithin => dest.write_str(":target-within"),
Visited => dest.write_str(":visited"),
// https://drafts.csswg.org/selectors-4/#input-pseudos
Enabled => dest.write_str(":enabled"),
Disabled => dest.write_str(":disabled"),
ReadOnly(prefix) => write_prefixed!(prefix, "read-only"),
ReadWrite(prefix) => write_prefixed!(prefix, "read-write"),
PlaceholderShown(prefix) => write_prefixed!(prefix, "placeholder-shown"),
Default => dest.write_str(":default"),
Checked => dest.write_str(":checked"),
Indeterminate => dest.write_str(":indeterminate"),
Blank => dest.write_str(":blank"),
Valid => dest.write_str(":valid"),
Invalid => dest.write_str(":invalid"),
InRange => dest.write_str(":in-range"),
OutOfRange => dest.write_str(":out-of-range"),
Required => dest.write_str(":required"),
Optional => dest.write_str(":optional"),
UserValid => dest.write_str(":user-valid"),
UserInvalid => dest.write_str(":user-invalid"),
// https://html.spec.whatwg.org/multipage/semantics-other.html#selector-autofill
Autofill(prefix) => write_prefixed!(prefix, "autofill"),
Local(selector) => selector.to_css_with_context(dest, context),
Global(selector) => {
let css_module = std::mem::take(&mut dest.css_module);
selector.to_css_with_context(dest, context)?;
dest.css_module = css_module;
Ok(())
},
Lang(_) | Dir(_) => unreachable!(),
Custom(val) => {
dest.write_char(':')?;
return dest.write_str(&val)
}
}
}
}
impl PseudoClass {
pub fn is_equivalent(&self, other: &PseudoClass) -> bool {
use PseudoClass::*;
match (self, other) {
(Fullscreen(_), Fullscreen(_)) |
(AnyLink(_), AnyLink(_)) |
(ReadOnly(_), ReadOnly(_)) |
(ReadWrite(_), ReadWrite(_)) |
(PlaceholderShown(_), PlaceholderShown(_)) |
(Autofill(_), Autofill(_)) => true,
(a, b) => a == b
}
}
pub fn get_prefix(&self) -> VendorPrefix {
use PseudoClass::*;
match self {
Fullscreen(p) |
AnyLink(p) |
ReadOnly(p) |
ReadWrite(p) |
PlaceholderShown(p) |
Autofill(p) => *p,
_ => VendorPrefix::empty()
}
}
pub fn get_necessary_prefixes(&self, targets: Browsers) -> VendorPrefix {
use PseudoClass::*;
use crate::prefixes::Feature;
let feature = match self {
Fullscreen(p) if *p == VendorPrefix::None => Feature::PseudoClassFullscreen,
AnyLink(p) if *p == VendorPrefix::None => Feature::PseudoClassAnyLink,
ReadOnly(p) if *p == VendorPrefix::None => Feature::PseudoClassReadOnly,
ReadWrite(p) if *p == VendorPrefix::None => Feature::PseudoClassReadWrite,
PlaceholderShown(p) if *p == VendorPrefix::None => Feature::PseudoClassPlaceholderShown,
Autofill(p) if *p == VendorPrefix::None => Feature::PseudoClassAutofill,
_ => return VendorPrefix::empty()
};
feature.prefixes_for(targets)
}
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum PseudoElement {
After,
Before,
FirstLine,
FirstLetter,
Selection(VendorPrefix),
Placeholder(VendorPrefix),
Marker,
Backdrop(VendorPrefix),
FileSelectorButton(VendorPrefix),
Custom(String)
}
impl cssparser::ToCss for PseudoElement {
fn to_css<W>(&self, _: &mut W)-> std::fmt::Result where W: fmt::Write {
unreachable!();
}
}
impl ToCss for PseudoElement {
fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: fmt::Write {
use PseudoElement::*;
macro_rules! write_prefix {
($prefix: ident) => {{
dest.write_str("::")?;
// If the printer has a vendor prefix override, use that.
let vp = if !dest.vendor_prefix.is_empty() {
dest.vendor_prefix
} else {
*$prefix
};
vp.to_css(dest)?;
vp
}};
}
macro_rules! write_prefixed {
($prefix: ident, $val: expr) => {{
write_prefix!($prefix);
dest.write_str($val)
}};
}
match &self {
// CSS2 pseudo elements support a single colon syntax in addition
// to the more correct double colon for other pseudo elements.
// We use that here because it's supported everywhere and is shorter.
After => dest.write_str(":after"),
Before => dest.write_str(":before"),
FirstLine => dest.write_str(":first-line"),
FirstLetter => dest.write_str(":first-letter"),
Marker => dest.write_str("::marker"),
Selection(prefix) => write_prefixed!(prefix, "selection"),
Placeholder(prefix) => {
let vp = write_prefix!(prefix);
if vp == VendorPrefix::WebKit || vp == VendorPrefix::Ms {
dest.write_str("input-placeholder")
} else {
dest.write_str("placeholder")
}
},
Backdrop(prefix) => write_prefixed!(prefix, "backdrop"),
FileSelectorButton(prefix) => {
let vp = write_prefix!(prefix);
if vp == VendorPrefix::WebKit {
dest.write_str("file-upload-button")
} else if vp == VendorPrefix::Ms {
dest.write_str("browse")
} else {
dest.write_str("file-selector-button")
}
}
Custom(val) => {
dest.write_str("::")?;
return dest.write_str(val)
}
}
}
}
impl parcel_selectors::parser::PseudoElement for PseudoElement {
type Impl = Selectors;
fn accepts_state_pseudo_classes(&self) -> bool {
// Be lenient.
true
}
fn valid_after_slotted(&self) -> bool {
// ::slotted() should support all tree-abiding pseudo-elements, see
// https://drafts.csswg.org/css-scoping/#slotted-pseudo
// https://drafts.csswg.org/css-pseudo-4/#treelike
matches!(
*self,
PseudoElement::Before |
PseudoElement::After |
PseudoElement::Marker |
PseudoElement::Placeholder(_) |
PseudoElement::FileSelectorButton(_)
)
}
}
impl PseudoElement {
pub fn is_equivalent(&self, other: &PseudoElement) -> bool {
use PseudoElement::*;
match (self, other) {
(Selection(_), Selection(_)) |
(Placeholder(_), Placeholder(_)) |
(Backdrop(_), Backdrop(_)) |
(FileSelectorButton(_), FileSelectorButton(_)) => true,
(a, b) => a == b
}
}
pub fn get_prefix(&self) -> VendorPrefix {
use PseudoElement::*;
match self {
Selection(p) |
Placeholder(p) |
Backdrop(p) |
FileSelectorButton(p) => *p,
_ => VendorPrefix::empty()
}
}
pub fn get_necessary_prefixes(&self, targets: Browsers) -> VendorPrefix {
use PseudoElement::*;
use crate::prefixes::Feature;
let feature = match self {
Selection(p) if *p == VendorPrefix::None => Feature::PseudoElementSelection,
Placeholder(p) if *p == VendorPrefix::None => Feature::PseudoElementPlaceholder,
Backdrop(p) if *p == VendorPrefix::None => Feature::PseudoElementBackdrop,
FileSelectorButton(p) if *p == VendorPrefix::None => Feature::PseudoElementFileSelectorButton,
_ => return VendorPrefix::empty()
};
feature.prefixes_for(targets)
}
}
impl ToCssWithContext for SelectorList<Selectors> {
fn to_css_with_context<W>(&self, dest: &mut Printer<W>, context: Option<&StyleContext>)-> Result<(), PrinterError> where W: fmt::Write {
serialize_selector_list(self.0.iter(), dest, context)
}
}
impl ToCss for Combinator {
fn to_css<W>(&self, dest: &mut Printer<W>)-> Result<(), PrinterError>
where
W: fmt::Write,
{
match *self {
Combinator::Child => dest.delim('>', true),
Combinator::Descendant => dest.write_str(" "),
Combinator::NextSibling => dest.delim('+', true),
Combinator::LaterSibling => dest.delim('~', true),
Combinator::PseudoElement | Combinator::Part | Combinator::SlotAssignment => Ok(()),
}
}
}
// Copied from the selectors crate and modified to override to_css implementation.
impl ToCssWithContext for parcel_selectors::parser::Selector<Selectors> {
fn to_css_with_context<W>(&self, dest: &mut Printer<W>, context: Option<&StyleContext>)-> Result<(), PrinterError>
where
W: fmt::Write,
{
use parcel_selectors::parser::*;
// Compound selectors invert the order of their contents, so we need to
// undo that during serialization.
//
// This two-iterator strategy involves walking over the selector twice.
// We could do something more clever, but selector serialization probably
// isn't hot enough to justify it, and the stringification likely
// dominates anyway.
//
// NB: A parse-order iterator is a Rev<>, which doesn't expose as_slice(),
// which we need for |split|. So we split by combinators on a match-order
// sequence and then reverse.
let mut combinators = self
.iter_raw_match_order()
.rev()
.filter_map(|x| x.as_combinator());
let compound_selectors = self
.iter_raw_match_order()
.as_slice()
.split(|x| x.is_combinator())
.rev();
let mut combinators_exhausted = false;
for compound in compound_selectors {
debug_assert!(!combinators_exhausted);
// https://drafts.csswg.org/cssom/#serializing-selectors
if compound.is_empty() {
continue;
}
let has_leading_nesting = matches!(compound[0], Component::Nesting);
let first_index = if has_leading_nesting { 1 } else { 0 };
// 1. If there is only one simple selector in the compound selectors
// which is a universal selector, append the result of
// serializing the universal selector to s.
//
// Check if `!compound.empty()` first--this can happen if we have
// something like `... > ::before`, because we store `>` and `::`
// both as combinators internally.
//
// If we are in this case, after we have serialized the universal
// selector, we skip Step 2 and continue with the algorithm.
let (can_elide_namespace, first_non_namespace) = match compound.get(first_index) {
Some(Component::ExplicitAnyNamespace) |
Some(Component::ExplicitNoNamespace) |
Some(Component::Namespace(..)) => (false, first_index + 1),
Some(Component::DefaultNamespace(..)) => (true, first_index + 1),
_ => (true, first_index),
};
let mut perform_step_2 = true;
let next_combinator = combinators.next();
if first_non_namespace == compound.len() - 1 {
match (next_combinator, &compound[first_non_namespace]) {
// We have to be careful here, because if there is a
// pseudo element "combinator" there isn't really just
// the one simple selector. Technically this compound
// selector contains the pseudo element selector as well
// -- Combinator::PseudoElement, just like
// Combinator::SlotAssignment, don't exist in the
// spec.
(Some(Combinator::PseudoElement), _) |
(Some(Combinator::SlotAssignment), _) => (),
(_, &Component::ExplicitUniversalType) => {
// Iterate over everything so we serialize the namespace
// too.
let mut iter = compound.iter();
let swap_nesting = has_leading_nesting && context.is_some() && is_type_selector(compound.get(first_index));
if swap_nesting {
// Swap nesting and type selector (e.g. &div -> div&).
iter.next();
}
for simple in iter {
simple.to_css_with_context(dest, context)?;
}
if swap_nesting {
serialize_nesting(dest, context, false)?;
}
// Skip step 2, which is an "otherwise".
perform_step_2 = false;
},
_ => (),
}
}
// 2. Otherwise, for each simple selector in the compound selectors
// that is not a universal selector of which the namespace prefix
// maps to a namespace that is not the default namespace
// serialize the simple selector and append the result to s.
//
// See https://github.com/w3c/csswg-drafts/issues/1606, which is
// proposing to change this to match up with the behavior asserted
// in cssom/serialize-namespaced-type-selectors.html, which the
// following code tries to match.
if perform_step_2 {
let mut iter = compound.iter();
if has_leading_nesting && context.is_some() && is_type_selector(compound.get(first_index)) {
// Swap nesting and type selector (e.g. &div -> div&).
// This ensures that the compiled selector is valid. e.g. (div.foo is valid, .foodiv is not).
let nesting = iter.next().unwrap();
let local = iter.next().unwrap();
local.to_css_with_context(dest, context)?;
// Also check the next item in case of namespaces.
if is_type_selector(compound.get(first_index + 1)) {
let local = iter.next().unwrap();
local.to_css_with_context(dest, context)?;
}
nesting.to_css_with_context(dest, context)?;
} else if has_leading_nesting && context.is_some() {
// Nesting selector may serialize differently if it is leading, due to type selectors.
iter.next();
serialize_nesting(dest, context, true)?;
}
for simple in iter {
if let Component::ExplicitUniversalType = *simple {
// Can't have a namespace followed by a pseudo-element
// selector followed by a universal selector in the same
// compound selector, so we don't have to worry about the
// real namespace being in a different `compound`.
if can_elide_namespace {
continue;
}
}
simple.to_css_with_context(dest, context)?;
}
}
// 3. If this is not the last part of the chain of the selector
// append a single SPACE (U+0020), followed by the combinator
// ">", "+", "~", ">>", "||", as appropriate, followed by another
// single SPACE (U+0020) if the combinator was not whitespace, to
// s.
match next_combinator {
Some(c) => c.to_css(dest)?,
None => combinators_exhausted = true,
};
// 4. If this is the last part of the chain of the selector and
// there is a pseudo-element, append "::" followed by the name of
// the pseudo-element, to s.
//
// (we handle this above)
}
Ok(())
}
}
impl ToCssWithContext for Component<Selectors> {
fn to_css_with_context<W>(&self, dest: &mut Printer<W>, context: Option<&StyleContext>)-> Result<(), PrinterError> where W: fmt::Write {
use Component::*;
match &self {
Combinator(ref c) => c.to_css(dest),
AttributeInNoNamespace {
ref local_name,
operator,
ref value,
case_sensitivity,
..
} => {
use cssparser::ToCss;
dest.write_char('[')?;
local_name.to_css(dest)?;
cssparser::ToCss::to_css(operator, dest)?;
if dest.minify {
// Serialize as both an identifier and a string and choose the shorter one.
let mut id = String::new();
value.write_identifier(&mut id)?;
let mut s = String::new();
value.to_css(&mut s)?;
if id.len() > 0 && id.len() < s.len() + 2 {
dest.write_str(&id)?;
} else {
dest.write_char('"')?;
dest.write_str(&s)?;
dest.write_char('"')?;
}
} else {
dest.write_char('"')?;
value.to_css(dest)?;
dest.write_char('"')?;
}
match case_sensitivity {
parcel_selectors::attr::ParsedCaseSensitivity::CaseSensitive |
parcel_selectors::attr::ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {},
parcel_selectors::attr::ParsedCaseSensitivity::AsciiCaseInsensitive => dest.write_str(" i")?,
parcel_selectors::attr::ParsedCaseSensitivity::ExplicitCaseSensitive => dest.write_str(" s")?,
}
dest.write_char(']')
},
Is(ref list) | Where(ref list) | Negation(ref list) => {
match *self {
Where(..) => dest.write_str(":where(")?,
Is(..) => dest.write_str(":is(")?,
Negation(..) => dest.write_str(":not(")?,
_ => unreachable!(),
}
serialize_selector_list(list.iter(), dest, context)?;
dest.write_str(")")
},
NonTSPseudoClass(pseudo) => {
pseudo.to_css_with_context(dest, context)
},
PseudoElement(pseudo) => {
pseudo.to_css(dest)
},
Nesting => {
serialize_nesting(dest, context, false)
},
Class(ref class) => {
dest.write_char('.')?;
dest.write_ident(&class.0)
}
ID(ref id) => {
dest.write_char('#')?;
dest.write_ident(&id.0)
}
_ => {
cssparser::ToCss::to_css(self, dest)?;
Ok(())
}
}
}
}
fn serialize_nesting<W>(dest: &mut Printer<W>, context: Option<&StyleContext>, first: bool)-> Result<(), PrinterError> where W: fmt::Write {
if let Some(ctx) = context {
// If there's only one selector, just serialize it directly.
// Otherwise, use an :is() pseudo class.
// Type selectors are only allowed at the start of a compound selector,
// so use :is() if that is not the case.
if ctx.rule.selectors.0.len() == 1 && (first || !has_type_selector(&ctx.rule.selectors.0[0])) {
ctx.rule.selectors.0.first().unwrap().to_css_with_context(dest, ctx.parent)
} else {
dest.write_str(":is(")?;
serialize_selector_list(ctx.rule.selectors.0.iter(), dest, ctx.parent)?;
dest.write_char(')')
}
} else {
dest.write_char('&')
}
}
fn has_type_selector(selector: &parcel_selectors::parser::Selector<Selectors>) -> bool {
let mut iter = selector.iter_raw_parse_order_from(0);
let first = iter.next();
is_type_selector(first)
}
fn is_type_selector(component: Option<&Component<Selectors>>) -> bool {
matches!(
component,
Some(Component::ExplicitAnyNamespace) |
Some(Component::ExplicitNoNamespace) |
Some(Component::Namespace(..)) |
Some(Component::DefaultNamespace(_)) |
Some(Component::LocalName(_)) |
Some(Component::ExplicitUniversalType)
)
}
fn serialize_selector_list<'a, I, W>(iter: I, dest: &mut Printer<W>, context: Option<&StyleContext>)-> Result<(), PrinterError>
where
I: Iterator<Item = &'a Selector<Selectors>>,
W: fmt::Write,
{
let mut first = true;
for selector in iter {
if !first {
dest.delim(',', false)?;
}
first = false;
selector.to_css_with_context(dest, context)?;
}
Ok(())
}
pub fn is_compatible(selectors: &SelectorList<Selectors>, targets: Option<Browsers>) -> bool {
for selector in &selectors.0 {
let iter = selector.iter();
for component in iter {
let feature = match component {
Component::ID(_) |
Component::Class(_) |
Component::LocalName(_) => continue,
Component::ExplicitAnyNamespace |
Component::ExplicitNoNamespace |
Component::DefaultNamespace(_) |
Component::Namespace(_, _) => Feature::CssNamespaces,
Component::ExplicitUniversalType => Feature::CssSel2,
Component::AttributeInNoNamespaceExists { .. } => Feature::CssSel2,
Component::AttributeInNoNamespace { operator, case_sensitivity, .. } => {
if *case_sensitivity != ParsedCaseSensitivity::CaseSensitive {
Feature::CssCaseInsensitive
} else {
match operator {
AttrSelectorOperator::Equal |
AttrSelectorOperator::Includes |
AttrSelectorOperator::DashMatch => Feature::CssSel2,
AttrSelectorOperator::Prefix |
AttrSelectorOperator::Substring |
AttrSelectorOperator::Suffix => Feature::CssSel3,
}
}