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
use cssparser::Parser;
use parser::{Parse, ParserContext};
use std::{fmt, mem, usize};
use style_traits::{ToCss, ParseError, StyleParseErrorKind};
use values::{CSSFloat, CustomIdent};
use values::computed::{Context, ToComputedValue};
use values::specified;
use values::specified::grid::parse_line_names;
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct GridLine<Integer> {
pub is_span: bool,
pub ident: Option<CustomIdent>,
pub line_num: Option<Integer>,
}
impl<Integer> GridLine<Integer> {
pub fn auto() -> Self {
Self {
is_span: false,
line_num: None,
ident: None,
}
}
pub fn is_auto(&self) -> bool {
self.ident.is_none() && self.line_num.is_none() && !self.is_span
}
}
impl<Integer> ToCss for GridLine<Integer>
where
Integer: ToCss,
{
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.is_auto() {
return dest.write_str("auto")
}
if self.is_span {
dest.write_str("span")?;
}
if let Some(ref i) = self.line_num {
if self.is_span {
dest.write_str(" ")?;
}
i.to_css(dest)?;
}
if let Some(ref s) = self.ident {
if self.is_span || self.line_num.is_some() {
dest.write_str(" ")?;
}
s.to_css(dest)?;
}
Ok(())
}
}
impl Parse for GridLine<specified::Integer> {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let mut grid_line = Self::auto();
if input.try(|i| i.expect_ident_matching("auto")).is_ok() {
return Ok(grid_line)
}
let mut val_before_span = false;
for _ in 0..3 {
let location = input.current_source_location();
if input.try(|i| i.expect_ident_matching("span")).is_ok() {
if grid_line.is_span {
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
if grid_line.line_num.is_some() || grid_line.ident.is_some() {
val_before_span = true;
}
grid_line.is_span = true;
} else if let Ok(i) = input.try(|i| specified::Integer::parse(context, i)) {
if i.value() == 0 || val_before_span || grid_line.line_num.is_some() {
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
grid_line.line_num = Some(i);
} else if let Ok(name) = input.try(|i| i.expect_ident_cloned()) {
if val_before_span || grid_line.ident.is_some() {
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
grid_line.ident = Some(CustomIdent::from_ident(location, &name, &[])?);
} else {
break
}
}
if grid_line.is_auto() {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
if grid_line.is_span {
if let Some(i) = grid_line.line_num {
if i.value() <= 0 {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
} else if grid_line.ident.is_none() {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
Ok(grid_line)
}
}
define_css_keyword_enum!{ TrackKeyword:
"auto" => Auto,
"max-content" => MaxContent,
"min-content" => MinContent
}
add_impls_for_keyword_enum!(TrackKeyword);
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum TrackBreadth<L> {
Breadth(L),
#[css(dimension)]
Fr(CSSFloat),
Keyword(TrackKeyword),
}
impl<L> TrackBreadth<L> {
#[inline]
pub fn is_fixed(&self) -> bool {
match *self {
TrackBreadth::Breadth(ref _lop) => true,
_ => false,
}
}
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub enum TrackSize<L> {
Breadth(TrackBreadth<L>),
Minmax(TrackBreadth<L>, TrackBreadth<L>),
FitContent(L),
}
impl<L> TrackSize<L> {
pub fn is_fixed(&self) -> bool {
match *self {
TrackSize::Breadth(ref breadth) => breadth.is_fixed(),
TrackSize::Minmax(ref breadth_1, ref breadth_2) => {
if breadth_1.is_fixed() {
return true
}
match *breadth_1 {
TrackBreadth::Fr(_) => false,
_ => breadth_2.is_fixed(),
}
},
TrackSize::FitContent(_) => false,
}
}
}
impl<L> Default for TrackSize<L> {
fn default() -> Self {
TrackSize::Breadth(TrackBreadth::Keyword(TrackKeyword::Auto))
}
}
impl<L: PartialEq> TrackSize<L> {
pub fn is_default(&self) -> bool {
*self == TrackSize::default()
}
}
impl<L: ToCss> ToCss for TrackSize<L> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
TrackSize::Breadth(ref breadth) => breadth.to_css(dest),
TrackSize::Minmax(ref min, ref max) => {
if let TrackBreadth::Keyword(TrackKeyword::Auto) = *min {
if let TrackBreadth::Fr(_) = *max {
return max.to_css(dest);
}
}
dest.write_str("minmax(")?;
min.to_css(dest)?;
dest.write_str(", ")?;
max.to_css(dest)?;
dest.write_str(")")
},
TrackSize::FitContent(ref lop) => {
dest.write_str("fit-content(")?;
lop.to_css(dest)?;
dest.write_str(")")
},
}
}
}
impl<L: ToComputedValue> ToComputedValue for TrackSize<L> {
type ComputedValue = TrackSize<L::ComputedValue>;
#[inline]
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
TrackSize::Breadth(TrackBreadth::Fr(ref f)) => {
TrackSize::Minmax(
TrackBreadth::Keyword(TrackKeyword::Auto),
TrackBreadth::Fr(f.to_computed_value(context)),
)
},
TrackSize::Breadth(ref b) => {
TrackSize::Breadth(b.to_computed_value(context))
},
TrackSize::Minmax(ref b1, ref b2) => {
TrackSize::Minmax(
b1.to_computed_value(context),
b2.to_computed_value(context),
)
}
TrackSize::FitContent(ref lop) => {
TrackSize::FitContent(lop.to_computed_value(context))
},
}
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
match *computed {
TrackSize::Breadth(ref b) => {
TrackSize::Breadth(ToComputedValue::from_computed_value(b))
},
TrackSize::Minmax(ref b1, ref b2) => {
TrackSize::Minmax(
ToComputedValue::from_computed_value(b1),
ToComputedValue::from_computed_value(b2),
)
},
TrackSize::FitContent(ref lop) => {
TrackSize::FitContent(ToComputedValue::from_computed_value(lop))
},
}
}
}
pub fn concat_serialize_idents<W>(
prefix: &str,
suffix: &str,
slice: &[CustomIdent],
sep: &str,
dest: &mut W,
) -> fmt::Result
where
W: fmt::Write
{
if let Some((ref first, rest)) = slice.split_first() {
dest.write_str(prefix)?;
first.to_css(dest)?;
for thing in rest {
dest.write_str(sep)?;
thing.to_css(dest)?;
}
dest.write_str(suffix)?;
}
Ok(())
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum RepeatCount<Integer> {
Number(Integer),
AutoFill,
AutoFit,
}
impl Parse for RepeatCount<specified::Integer> {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
const MAX_LINE: i32 = 10000;
if let Ok(mut i) = input.try(|i| specified::Integer::parse_positive(context, i)) {
if i.value() > MAX_LINE {
i = specified::Integer::new(MAX_LINE);
}
Ok(RepeatCount::Number(i))
} else {
try_match_ident_ignore_ascii_case! { input,
"auto-fill" => Ok(RepeatCount::AutoFill),
"auto-fit" => Ok(RepeatCount::AutoFit),
}
}
}
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct TrackRepeat<L, I> {
pub count: RepeatCount<I>,
#[compute(clone)]
pub line_names: Box<[Box<[CustomIdent]>]>,
pub track_sizes: Vec<TrackSize<L>>,
}
impl<L: ToCss, I: ToCss> ToCss for TrackRepeat<L, I> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("repeat(")?;
self.count.to_css(dest)?;
dest.write_str(", ")?;
let mut line_names_iter = self.line_names.iter();
for (i, (ref size, ref names)) in self.track_sizes.iter()
.zip(&mut line_names_iter).enumerate() {
if i > 0 {
dest.write_str(" ")?;
}
concat_serialize_idents("[", "] ", names, " ", dest)?;
size.to_css(dest)?;
}
if let Some(line_names_last) = line_names_iter.next() {
concat_serialize_idents(" [", "]", line_names_last, " ", dest)?;
}
dest.write_str(")")?;
Ok(())
}
}
impl<L: Clone> TrackRepeat<L, specified::Integer> {
pub fn expand(&self) -> Self {
if let RepeatCount::Number(num) = self.count {
let mut line_names = vec![];
let mut track_sizes = vec![];
let mut prev_names = vec![];
for _ in 0..num.value() {
let mut names_iter = self.line_names.iter();
for (size, names) in self.track_sizes.iter().zip(&mut names_iter) {
prev_names.extend_from_slice(&names);
let vec = mem::replace(&mut prev_names, vec![]);
line_names.push(vec.into_boxed_slice());
track_sizes.push(size.clone());
}
if let Some(names) = names_iter.next() {
prev_names.extend_from_slice(&names);
}
}
line_names.push(prev_names.into_boxed_slice());
TrackRepeat {
count: self.count,
track_sizes: track_sizes,
line_names: line_names.into_boxed_slice(),
}
} else {
TrackRepeat {
count: self.count,
track_sizes: self.track_sizes.clone(),
line_names: self.line_names.clone(),
}
}
}
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum TrackListValue<LengthOrPercentage, Integer> {
TrackSize(TrackSize<LengthOrPercentage>),
TrackRepeat(TrackRepeat<LengthOrPercentage, Integer>),
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum TrackListType {
Auto(u16),
Normal,
Explicit,
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct TrackList<LengthOrPercentage, Integer> {
pub list_type: TrackListType,
pub values: Vec<TrackListValue<LengthOrPercentage, Integer>>,
pub line_names: Box<[Box<[CustomIdent]>]>,
pub auto_repeat: Option<TrackRepeat<LengthOrPercentage, Integer>>,
}
impl<L: ToCss, I: ToCss> ToCss for TrackList<L, I> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let auto_idx = match self.list_type {
TrackListType::Auto(i) => i as usize,
_ => usize::MAX,
};
let mut values_iter = self.values.iter().peekable();
let mut line_names_iter = self.line_names.iter().peekable();
for idx in 0.. {
let names = line_names_iter.next().unwrap();
concat_serialize_idents("[", "]", names, " ", dest)?;
match self.auto_repeat {
Some(ref repeat) if idx == auto_idx => {
if !names.is_empty() {
dest.write_str(" ")?;
}
repeat.to_css(dest)?;
},
_ => match values_iter.next() {
Some(value) => {
if !names.is_empty() {
dest.write_str(" ")?;
}
value.to_css(dest)?;
},
None => break,
},
}
if values_iter.peek().is_some() || line_names_iter.peek().map_or(false, |v| !v.is_empty()) ||
(idx + 1 == auto_idx) {
dest.write_str(" ")?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq)]
pub struct LineNameList {
pub names: Box<[Box<[CustomIdent]>]>,
pub fill_idx: Option<u32>,
}
trivial_to_computed_value!(LineNameList);
impl Parse for LineNameList {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.expect_ident_matching("subgrid")?;
let mut line_names = vec![];
let mut fill_idx = None;
loop {
let repeat_parse_result = input.try(|input| {
input.expect_function_matching("repeat")?;
input.parse_nested_block(|input| {
let count = RepeatCount::parse(context, input)?;
input.expect_comma()?;
let mut names_list = vec![];
names_list.push(parse_line_names(input)?);
while let Ok(names) = input.try(parse_line_names) {
names_list.push(names);
}
Ok((names_list, count))
})
});
if let Ok((mut names_list, count)) = repeat_parse_result {
match count {
RepeatCount::Number(num) =>
line_names.extend(names_list.iter().cloned().cycle()
.take(num.value() as usize * names_list.len())),
RepeatCount::AutoFill if fill_idx.is_none() => {
if names_list.len() != 1 {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
let names = names_list.pop().unwrap();
line_names.push(names);
fill_idx = Some(line_names.len() as u32 - 1);
},
_ => return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
} else if let Ok(names) = input.try(parse_line_names) {
line_names.push(names);
} else {
break
}
}
Ok(LineNameList {
names: line_names.into_boxed_slice(),
fill_idx: fill_idx,
})
}
}
impl ToCss for LineNameList {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("subgrid")?;
let fill_idx = self.fill_idx.map(|v| v as usize).unwrap_or(usize::MAX);
for (i, names) in self.names.iter().enumerate() {
if i == fill_idx {
dest.write_str(" repeat(auto-fill,")?;
}
dest.write_str(" [")?;
if let Some((ref first, rest)) = names.split_first() {
first.to_css(dest)?;
for name in rest {
dest.write_str(" ")?;
name.to_css(dest)?;
}
}
dest.write_str("]")?;
if i == fill_idx {
dest.write_str(")")?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum GridTemplateComponent<L, I> {
None,
TrackList(TrackList<L, I>),
Subgrid(LineNameList),
}
impl<L, I> GridTemplateComponent<L, I> {
pub fn track_list_len(&self) -> usize {
match *self {
GridTemplateComponent::TrackList(ref tracklist) => tracklist.values.len(),
_ => 0,
}
}
}