bun_css 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
#![warn(unused_must_use)]
use crate as css;
use crate::PrintErr;
use crate::Printer;

use crate::css_values::image::Image;
use crate::css_values::length::LengthOrNumber;
use crate::css_values::length::LengthPercentage;
use crate::css_values::position::Position;
use crate::css_values::rect::Rect;

use crate::css_properties::border_radius::BorderRadius;
// `shape` is still gated; FillRule referenced only by the (gated) BasicShape::Polygon body.

use crate::css_properties::shape::FillRule;

use crate::css_properties::background::BackgroundRepeat;
use crate::css_properties::background::BackgroundSize;
use crate::css_properties::border_image::BorderImage;
use crate::css_properties::border_image::BorderImageRepeat;
use crate::css_properties::border_image::BorderImageSideWidth;
use crate::css_properties::border_image::BorderImageSlice;

use crate::VendorPrefix;
use crate::generics::{CssEql, DeepClone};
use crate::properties::PropertyId;
use crate::properties::PropertyIdTag;

/// A [`<geometry-box>`](https://www.w3.org/TR/css-masking-1/#typedef-geometry-box) value
/// as used in the `mask-clip` and `clip-path` properties.
// TODO(port): css.DefineEnumProperty(@This()) — comptime-generated eql/hash/parse/toCss/deepClone.
// In Rust this becomes #[derive] of the css enum-property protocol (kebab-case serialization).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, css::Parse, css::ToCss)]
pub enum GeometryBox {
    /// The painted content is clipped to the content box.
    #[css(name = "border-box")]
    #[default]
    BorderBox,
    /// The painted content is clipped to the padding box.
    #[css(name = "padding-box")]
    PaddingBox,
    /// The painted content is clipped to the border box.
    #[css(name = "content-box")]
    ContentBox,
    /// The painted content is clipped to the margin box.
    #[css(name = "margin-box")]
    MarginBox,
    /// The painted content is clipped to the object bounding box.
    #[css(name = "fill-box")]
    FillBox,
    /// The painted content is clipped to the stroke bounding box.
    #[css(name = "stroke-box")]
    StrokeBox,
    /// Uses the nearest SVG viewport as reference box.
    #[css(name = "view-box")]
    ViewBox,
}

impl GeometryBox {
    pub fn into_mask_clip(self) -> MaskClip {
        MaskClip::GeometryBox(self)
    }
}

/// A CSS [`<basic-shape>`](https://www.w3.org/TR/css-shapes-1/#basic-shape-functions) value.
pub enum BasicShape {
    /// An inset rectangle.
    Inset(InsetRect),
    /// A circle.
    Circle(Circle),
    /// An ellipse.
    Ellipse(Ellipse),
    /// A polygon.
    Polygon(Polygon),
}

/// An [`inset()`](https://www.w3.org/TR/css-shapes-1/#funcdef-inset) rectangle shape.
// Zig declares this `const` (file-private) but it's reachable via `pub enum BasicShape::Inset`,
// so Rust requires `pub` here — Zig has no private-in-public lint.
pub struct InsetRect {
    /// The rectangle.
    pub rect: Rect<LengthPercentage>,
    /// A corner radius for the rectangle.
    pub radius: BorderRadius,
}

/// A [`circle()`](https://www.w3.org/TR/css-shapes-1/#funcdef-circle) shape.
pub struct Circle {
    /// The radius of the circle.
    pub radius: ShapeRadius,
    /// The position of the center of the circle.
    pub position: Position,
}

/// An [`ellipse()`](https://www.w3.org/TR/css-shapes-1/#funcdef-ellipse) shape.
pub struct Ellipse {
    /// The x-radius of the ellipse.
    pub radius_x: ShapeRadius,
    /// The y-radius of the ellipse.
    pub radius_y: ShapeRadius,
    /// The position of the center of the ellipse.
    pub position: Position,
}

/// A [`polygon()`](https://www.w3.org/TR/css-shapes-1/#funcdef-polygon) shape.
pub struct Polygon {
    /// The fill rule used to determine the interior of the polygon.
    pub fill_rule: FillRule,
    /// The points of each vertex of the polygon.
    // TODO(port): css is an AST crate (§Allocators) — if Polygon is arena-fed this must become
    // `bun_alloc::ArenaVec<'bump, Point>` and Polygon/BasicShape/ClipPath gain `<'bump>`.
    // No construction site exists in src/css/*.zig today, so provenance is unconfirmed; keeping
    // plain Vec<Point> until the arena story is verified.
    pub points: Vec<Point>,
}

/// A [`<shape-radius>`](https://www.w3.org/TR/css-shapes-1/#typedef-shape-radius) value
/// that defines the radius of a `circle()` or `ellipse()` shape.
pub enum ShapeRadius {
    /// An explicit length or percentage.
    LengthPercentage(LengthPercentage),
    /// The length from the center to the closest side of the box.
    ClosestSide,
    /// The length from the center to the farthest side of the box.
    FarthestSide,
}

/// A point within a `polygon()` shape.
///
/// See [Polygon](Polygon).
pub struct Point {
    /// The x position of the point.
    pub x: LengthPercentage,
    /// The y position of the point.
    pub y: LengthPercentage,
}

/// A value for the [mask-mode](https://www.w3.org/TR/css-masking-1/#the-mask-mode) property.
// TODO(port): css.DefineEnumProperty(@This()) → derive css enum-property protocol
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, css::Parse, css::ToCss)]
pub enum MaskMode {
    /// The luminance values of the mask image is used.
    #[css(name = "luminance")]
    Luminance,
    /// The alpha values of the mask image is used.
    #[css(name = "alpha")]
    Alpha,
    /// If an SVG source is used, the value matches the `mask-type` property. Otherwise, the alpha values are used.
    #[css(name = "match-source")]
    #[default]
    MatchSource,
}

/// A value for the [mask-clip](https://www.w3.org/TR/css-masking-1/#the-mask-clip) property.
// TODO(port): css.DeriveParse / css.DeriveToCss → derive css union-property protocol
#[derive(Debug, Clone, Copy, PartialEq, Eq, css::Parse, css::ToCss)]
pub enum MaskClip {
    /// A geometry box.
    // Zig: @"geometry-box"
    GeometryBox(GeometryBox),
    /// The painted content is not clipped.
    #[css(name = "no-clip")]
    NoClip,
}

/// A value for the [mask-composite](https://www.w3.org/TR/css-masking-1/#the-mask-composite) property.
// TODO(port): css.DefineEnumProperty(@This()) → derive css enum-property protocol
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, css::Parse, css::ToCss)]
pub enum MaskComposite {
    /// The source is placed over the destination.
    #[css(name = "add")]
    #[default]
    Add,
    /// The source is placed, where it falls outside of the destination.
    #[css(name = "subtract")]
    Subtract,
    /// The parts of source that overlap the destination, replace the destination.
    #[css(name = "intersect")]
    Intersect,
    /// The non-overlapping regions of source and destination are combined.
    #[css(name = "exclude")]
    Exclude,
}

/// A value for the [mask-type](https://www.w3.org/TR/css-masking-1/#the-mask-type) property.
// TODO(port): css.DefineEnumProperty(@This()) → derive css enum-property protocol
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, css::Parse, css::ToCss)]
pub enum MaskType {
    /// The luminance values of the mask is used.
    #[css(name = "luminance")]
    Luminance,
    /// The alpha values of the mask is used.
    #[css(name = "alpha")]
    Alpha,
}

/// A value for the [mask](https://www.w3.org/TR/css-masking-1/#the-mask) shorthand property.
// PORT NOTE: Debug/Clone/PartialEq derives gated on `Image`/`Position`/
// `BackgroundSize`/`BackgroundRepeat` gaining those derives upstream.
#[cfg_attr(any(), derive(Debug, Clone, PartialEq))]
#[derive(DeepClone, CssEql)]
pub struct Mask {
    /// The mask image.
    pub image: Image,
    /// The position of the mask.
    pub position: Position,
    /// The size of the mask image.
    pub size: BackgroundSize,
    /// How the mask repeats.
    pub repeat: BackgroundRepeat,
    /// The box in which the mask is clipped.
    pub clip: MaskClip,
    /// The origin of the mask.
    pub origin: GeometryBox,
    /// How the mask is composited with the element.
    pub composite: MaskComposite,
    /// How the mask image is interpreted.
    pub mode: MaskMode,
}

impl Mask {
    // TODO(port): PropertyFieldMap was a Zig anon-struct const consumed by comptime
    // reflection in shorthand handlers. Represented as an assoc const slice; could
    // be replaced with a trait/derive.
    pub const PROPERTY_FIELD_MAP: &'static [(&'static str, PropertyIdTag)] = &[
        ("image", PropertyIdTag::MaskImage),
        ("position", PropertyIdTag::MaskPosition),
        ("size", PropertyIdTag::MaskSize),
        ("repeat", PropertyIdTag::MaskRepeat),
        ("clip", PropertyIdTag::MaskClip),
        ("origin", PropertyIdTag::MaskOrigin),
        ("composite", PropertyIdTag::MaskComposite),
        ("mode", PropertyIdTag::MaskMode),
    ];

    // TODO(port): VendorPrefixMap was a Zig anon-struct const of bools consumed by
    // comptime reflection. Represented as a field-name slice; could be replaced with trait/derive.
    pub const VENDOR_PREFIX_MAP: &'static [&'static str] =
        &["image", "position", "size", "repeat", "clip", "origin"];

    pub fn parse(input: &mut css::Parser) -> css::Result<Self> {
        let mut image: Option<Image> = None;
        let mut position: Option<Position> = None;
        let mut size: Option<BackgroundSize> = None;
        let mut repeat: Option<BackgroundRepeat> = None;
        let mut clip: Option<MaskClip> = None;
        let mut origin: Option<GeometryBox> = None;
        let mut composite: Option<MaskComposite> = None;
        let mut mode: Option<MaskMode> = None;

        loop {
            if image.is_none() {
                if let Ok(value) = input.try_parse(Image::parse) {
                    image = Some(value);
                    continue;
                }
            }

            if position.is_none() {
                if let Ok(value) = input.try_parse(Position::parse) {
                    position = Some(value);
                    size = input
                        .try_parse(|i: &mut css::Parser| -> css::Result<BackgroundSize> {
                            i.expect_delim(b'/')?;
                            BackgroundSize::parse(i)
                        })
                        .ok();
                    continue;
                }
            }

            if repeat.is_none() {
                if let Ok(value) = input.try_parse(BackgroundRepeat::parse) {
                    repeat = Some(value);
                    continue;
                }
            }

            if origin.is_none() {
                if let Ok(value) = input.try_parse(GeometryBox::parse) {
                    origin = Some(value);
                    continue;
                }
            }

            if clip.is_none() {
                if let Ok(value) = input.try_parse(MaskClip::parse) {
                    clip = Some(value);
                    continue;
                }
            }

            if composite.is_none() {
                if let Ok(value) = input.try_parse(MaskComposite::parse) {
                    composite = Some(value);
                    continue;
                }
            }

            if mode.is_none() {
                if let Ok(value) = input.try_parse(MaskMode::parse) {
                    mode = Some(value);
                    continue;
                }
            }

            break;
        }

        if clip.is_none() {
            if let Some(o) = origin {
                clip = Some(o.into_mask_clip());
            }
        }

        Ok(Self {
            image: image.unwrap_or_default(),
            position: position.unwrap_or_default(),
            repeat: repeat.unwrap_or_else(BackgroundRepeat::default),
            size: size.unwrap_or_else(BackgroundSize::default),
            origin: origin.unwrap_or(GeometryBox::BorderBox),
            clip: clip.unwrap_or_else(|| GeometryBox::BorderBox.into_mask_clip()),
            composite: composite.unwrap_or(MaskComposite::Add),
            mode: mode.unwrap_or(MaskMode::MatchSource),
        })
    }

    pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> {
        self.image.to_css(dest)?;

        if self.position != Position::default() || self.size != BackgroundSize::default() {
            dest.write_char(b' ')?;
            self.position.to_css(dest)?;

            if self.size != BackgroundSize::default() {
                dest.delim(b'/', true)?;
                self.size.to_css(dest)?;
            }
        }

        if self.repeat != BackgroundRepeat::default() {
            dest.write_char(b' ')?;
            self.repeat.to_css(dest)?;
        }

        if self.origin != GeometryBox::BorderBox
            || self.clip != GeometryBox::BorderBox.into_mask_clip()
        {
            dest.write_char(b' ')?;
            self.origin.to_css(dest)?;

            if self.clip != self.origin.into_mask_clip() {
                dest.write_char(b' ')?;
                self.clip.to_css(dest)?;
            }
        }

        if self.composite != MaskComposite::default() {
            dest.write_char(b' ')?;
            self.composite.to_css(dest)?;
        }

        if self.mode != MaskMode::default() {
            dest.write_char(b' ')?;
            self.mode.to_css(dest)?;
        }

        Ok(())
    }

    // eql → #[derive(PartialEq)]
    // deepClone → #[derive(Clone)]
}

/// A value for the [mask-border-mode](https://www.w3.org/TR/css-masking-1/#the-mask-border-mode) property.
// TODO(port): css.DefineEnumProperty(@This()) → derive css enum-property protocol
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, css::Parse, css::ToCss)]
pub enum MaskBorderMode {
    /// The luminance values of the mask image is used.
    #[css(name = "luminance")]
    Luminance,
    /// The alpha values of the mask image is used.
    #[css(name = "alpha")]
    #[default]
    Alpha,
}

/// A value for the [mask-border](https://www.w3.org/TR/css-masking-1/#the-mask-border) shorthand property.
// PORT NOTE: Debug/Clone/PartialEq derives gated on `Image`/`Rect<_>` gaining
// those derives upstream.
#[cfg_attr(any(), derive(Debug, Clone, PartialEq))]
#[derive(DeepClone, CssEql)]
pub struct MaskBorder {
    /// The mask image.
    pub source: Image,
    /// The offsets that define where the image is sliced.
    pub slice: BorderImageSlice,
    /// The width of the mask image.
    pub width: Rect<BorderImageSideWidth>,
    /// The amount that the image extends beyond the border box.
    pub outset: Rect<LengthOrNumber>,
    /// How the mask image is scaled and tiled.
    pub repeat: BorderImageRepeat,
    /// How the mask image is interpreted.
    pub mode: MaskBorderMode,
}

impl MaskBorder {
    // (old using name space) css.DefineShorthand(@This(), css.PropertyIdTag.@"mask-border", PropertyFieldMap);

    // TODO(port): PropertyFieldMap — see note on Mask::PROPERTY_FIELD_MAP
    pub const PROPERTY_FIELD_MAP: &'static [(&'static str, PropertyIdTag)] = &[
        ("source", PropertyIdTag::MaskBorderSource),
        ("slice", PropertyIdTag::MaskBorderSlice),
        ("width", PropertyIdTag::MaskBorderWidth),
        ("outset", PropertyIdTag::MaskBorderOutset),
        ("repeat", PropertyIdTag::MaskBorderRepeat),
        ("mode", PropertyIdTag::MaskBorderMode),
    ];

    pub fn parse(input: &mut css::Parser) -> css::Result<Self> {
        let mut mode: Option<MaskBorderMode> = None;
        let border_image = BorderImage::parse_with_callback(input, |p: &mut css::Parser| -> bool {
            if mode.is_none() {
                if let Ok(value) = p.try_parse(MaskBorderMode::parse) {
                    mode = Some(value);
                    return true;
                }
            }
            false
        });

        if border_image.is_ok() || mode.is_some() {
            // PERF(port): Zig used `comptime BorderImage.default()` — could const-eval the default
            let bi = border_image.unwrap_or_else(|_| BorderImage::default());
            Ok(MaskBorder {
                source: bi.source,
                slice: bi.slice,
                width: bi.width,
                outset: bi.outset,
                repeat: bi.repeat,
                mode: mode.unwrap_or_default(),
            })
        } else {
            Err(input.new_custom_error(css::ParserError::invalid_declaration))
        }
    }

    pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> {
        BorderImage::to_css_internal(
            &self.source,
            &self.slice,
            &self.width,
            &self.outset,
            &self.repeat,
            dest,
        )?;
        if self.mode != MaskBorderMode::default() {
            dest.write_char(b' ')?;
            self.mode.to_css(dest)?;
        }
        Ok(())
    }

    // eql → #[derive(PartialEq)]
    // deepClone → #[derive(Clone)]
}

/// A value for the [-webkit-mask-composite](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-composite)
/// property.
///
/// See also [MaskComposite](MaskComposite).
/// A value for the [-webkit-mask-composite](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-composite)
/// property.
///
/// See also [MaskComposite](MaskComposite).
// TODO(port): css.DefineEnumProperty(@This()) → derive css enum-property protocol
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, css::Parse, css::ToCss)]
pub enum WebKitMaskComposite {
    #[css(name = "clear")]
    Clear,
    #[css(name = "copy")]
    Copy,
    /// Equivalent to `add` in the standard `mask-composite` syntax.
    #[css(name = "source-over")]
    SourceOver,
    /// Equivalent to `intersect` in the standard `mask-composite` syntax.
    #[css(name = "source-in")]
    SourceIn,
    /// Equivalent to `subtract` in the standard `mask-composite` syntax.
    #[css(name = "source-out")]
    SourceOut,
    #[css(name = "source-atop")]
    SourceAtop,
    #[css(name = "destination-over")]
    DestinationOver,
    #[css(name = "destination-in")]
    DestinationIn,
    #[css(name = "destination-out")]
    DestinationOut,
    #[css(name = "destination-atop")]
    DestinationAtop,
    /// Equivalent to `exclude` in the standard `mask-composite` syntax.
    #[css(name = "xor")]
    Xor,
}

/// A value for the [-webkit-mask-source-type](https://github.com/WebKit/WebKit/blob/6eece09a1c31e47489811edd003d1e36910e9fd3/Source/WebCore/css/CSSProperties.json#L6578-L6587)
/// property.
///
/// See also [MaskMode](MaskMode).
/// A value for the [-webkit-mask-source-type](https://github.com/WebKit/WebKit/blob/6eece09a1c31e47489811edd003d1e36910e9fd3/Source/WebCore/css/CSSProperties.json#L6578-L6587)
/// property.
///
/// See also [MaskMode](MaskMode).
// TODO(port): css.DefineEnumProperty(@This()) → derive css enum-property protocol
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, css::Parse, css::ToCss)]
pub enum WebKitMaskSourceType {
    /// Equivalent to `match-source` in the standard `mask-mode` syntax.
    #[css(name = "auto")]
    Auto,
    /// The luminance values of the mask image is used.
    #[css(name = "luminance")]
    Luminance,
    /// The alpha values of the mask image is used.
    #[css(name = "alpha")]
    Alpha,
}

// blocked_on: PropertyId::WebKitMaskComposite variant name (codegen spelling is `WebKitMaskComposite`)
pub fn get_webkit_mask_property(property_id: &PropertyId) -> Option<PropertyId> {
    // TODO(port): PropertyId variant naming — Zig uses kebab-case @"mask-border-source" etc.
    // Mapping to PascalCase variants here; verify exact PropertyId enum shape.
    match property_id {
        PropertyId::MaskBorderSource => Some(PropertyId::MaskBoxImageSource(VendorPrefix::WEBKIT)),
        PropertyId::MaskBorderSlice => Some(PropertyId::MaskBoxImageSlice(VendorPrefix::WEBKIT)),
        PropertyId::MaskBorderWidth => Some(PropertyId::MaskBoxImageWidth(VendorPrefix::WEBKIT)),
        PropertyId::MaskBorderOutset => Some(PropertyId::MaskBoxImageOutset(VendorPrefix::WEBKIT)),
        PropertyId::MaskBorderRepeat => Some(PropertyId::MaskBoxImageRepeat(VendorPrefix::WEBKIT)),
        PropertyId::MaskBorder => Some(PropertyId::MaskBoxImage(VendorPrefix::WEBKIT)),
        PropertyId::MaskComposite => Some(PropertyId::WebKitMaskComposite),
        PropertyId::MaskMode => Some(PropertyId::MaskSourceType(VendorPrefix::WEBKIT)),
        _ => None,
    }
}

// ported from: src/css/properties/masking.zig