1use std::rc::Rc;
5
6use gpui::{
7 px, relative, AbsoluteLength, DefiniteLength, Hsla, Length, Overflow, StyleRefinement,
8 TransformLength, TransformSpec,
9};
10use lightningcss::declaration::DeclarationBlock;
11use lightningcss::properties::align::{ContentPosition, SelfPosition};
12use lightningcss::properties::border::LineStyle;
13use lightningcss::properties::display::{DisplayInside, DisplayKeyword};
14use lightningcss::properties::flex::FlexDirection as CssFlexDirection;
15use lightningcss::properties::font::{
16 AbsoluteFontWeight, FontFamily as CssFontFamily, FontWeight as CssFontWeight,
17 LineHeight as CssLineHeight,
18};
19use lightningcss::properties::masking::ClipPath as CssClipPath;
20use lightningcss::properties::overflow::OverflowKeyword;
21use lightningcss::properties::size::Size as CssSize;
22use lightningcss::properties::text::TextAlign as CssTextAlign;
23use lightningcss::properties::{Property, PropertyId};
24use lightningcss::stylesheet::{ParserOptions, PrinterOptions};
25use lightningcss::values::color::CssColor;
26use lightningcss::values::length::{
27 Length as CssLength, LengthPercentage, LengthPercentageOrAuto, LengthValue,
28};
29use lightningcss::values::percentage::DimensionPercentage;
30
31use crate::keyframes::{AnimationCollector, AnimationPatch, AnimationSpec};
32use crate::transition::{Collector, TransitionSpec};
33use crate::vars::{self, Vars};
34
35pub type Decls = Vec<(String, String)>;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum ObjectFit {
44 Fill,
45 Contain,
46 Cover,
47 ScaleDown,
48 None,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum WindowDrag {
55 Move,
56 None,
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum WindowControl {
64 Minimize,
65 Maximize,
66 Close,
67 None,
68}
69
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum UserSelect {
72 Auto,
75 None,
76 Text,
77 All,
78}
79
80#[derive(Clone, Copy, Debug, PartialEq)]
81pub struct DropShadow {
82 pub dx: f32,
83 pub dy: f32,
84 pub blur: f32,
87 pub color: Option<gpui::Hsla>,
88}
89
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
93pub struct RadiusInherit {
94 pub declared: u8,
95 pub inherit: u8,
96}
97
98impl RadiusInherit {
99 pub const TOP_LEFT: u8 = 1;
100 pub const TOP_RIGHT: u8 = 2;
101 pub const BOTTOM_RIGHT: u8 = 4;
102 pub const BOTTOM_LEFT: u8 = 8;
103 pub const ALL: u8 = 15;
104
105 pub(crate) fn write(&mut self, corners: u8, inherit: bool) {
106 self.declared |= corners;
107 if inherit {
108 self.inherit |= corners;
109 } else {
110 self.inherit &= !corners;
111 }
112 }
113
114 pub(crate) fn refine(&mut self, later: &RadiusInherit) {
115 self.inherit = (self.inherit & !later.declared) | (later.inherit & later.declared);
116 self.declared |= later.declared;
117 }
118}
119
120#[derive(Clone, Debug, Default, PartialEq)]
121pub struct Extras {
122 pub object_fit: Option<ObjectFit>,
123 pub window_drag: Option<WindowDrag>,
126 pub window_control: Option<WindowControl>,
127 pub fixed: Option<bool>,
128 pub drop_shadow: Option<DropShadow>,
129 pub sticky: Option<bool>,
132 pub z_index: Option<Option<i32>>,
133 pub isolate: Option<bool>,
134 pub positioned: Option<bool>,
137 pub pointer_events_none: Option<bool>,
140 pub visibility_hidden: Option<bool>,
143 pub user_select: Option<UserSelect>,
146 pub inline_level: Option<bool>,
149 pub appearance_none: Option<bool>,
150 pub accent_color: Option<Option<Hsla>>,
151 pub fill: Option<SvgPaint>,
152 pub stroke: Option<SvgPaint>,
153 pub svg_presentation: Option<Rc<Vec<(&'static str, Rc<str>)>>>,
154 pub text_transform: Option<TextTransform>,
157 pub white_space: Option<WhiteSpaceMode>,
160 pub content: Option<Rc<str>>,
161 pub content_none: bool,
164 pub background_clip_text: Option<bool>,
165 pub text_fill_color: Option<TextFill>,
168 pub background_key_color: Option<gpui::Hsla>,
169 pub background_images: Option<Rc<Vec<BackgroundLayer>>>,
172 pub background_urls: Option<Rc<Vec<BackgroundUrl>>>,
173 pub background_size: Option<Rc<Vec<BackgroundSize>>>,
174 pub background_position: Option<Rc<Vec<(TileLength, TileLength)>>>,
175 pub background_repeat: Option<Rc<Vec<(bool, bool)>>>,
176 pub list_marker: Option<ListMarker>,
177 pub list_marker_inside: Option<bool>,
178 pub web_font: Option<Rc<[String]>>,
181 pub underline_offset: Option<f32>,
182 pub decoration: DecorationPatch,
183 pub outline: OutlinePatch,
184 pub current_color: CurrentColorTargets,
187 pub current_color_overrides: CurrentColorTargets,
188 pub blur: Option<f32>,
191 pub filter_url: Option<Rc<str>>,
192 pub scrollbar_width: Option<ScrollbarWidth>,
193 pub scrollbar_color: Option<(gpui::Hsla, gpui::Hsla)>,
194 pub overscroll_x: Option<OverscrollBehavior>,
195 pub overscroll_y: Option<OverscrollBehavior>,
196 pub contain_paint: Option<bool>,
198 pub contain_size: Option<u8>,
200 pub scroll_smooth: Option<bool>,
202 pub overflow_x: Option<OverflowKeyword>,
204 pub overflow_y: Option<OverflowKeyword>,
205 pub mask_images: Option<MaskImages>,
208 pub mask_clips: Option<MaskClips>,
209 pub mask_composite: Option<MaskCompositing>,
210 pub mask: MaskPatch,
211 pub radius_inherit: RadiusInherit,
212 pub view_transition_name: Option<Option<Rc<str>>>,
215 pub view_transition_class: Option<Rc<[Rc<str>]>>,
217 pub plus_lighter: Option<bool>,
220}
221
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub enum MaskImages {
224 None,
225 TwoOpaque,
226 Other,
227}
228
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
230pub enum MaskClips {
231 ContentThenBorder,
232 Other,
233}
234
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub enum MaskCompositing {
237 Add,
238 Exclude,
239 Other,
240}
241
242#[derive(Clone, Debug, Default, PartialEq)]
245pub struct MaskPatch {
246 pub images: Option<Rc<Vec<BackgroundLayer>>>,
247 pub urls: Option<Rc<Vec<BackgroundUrl>>>,
248 pub size: Option<Rc<Vec<BackgroundSize>>>,
249 pub position: Option<Rc<Vec<(TileLength, TileLength)>>>,
250 pub repeat: Option<Rc<Vec<(bool, bool)>>>,
251 pub luminance: Option<bool>,
252}
253
254impl MaskPatch {
255 fn refine(&mut self, other: &Self) {
256 if other.images.is_some() {
257 self.images = other.images.clone();
258 self.urls = other.urls.clone();
259 }
260 if other.size.is_some() {
261 self.size = other.size.clone();
262 }
263 if other.position.is_some() {
264 self.position = other.position.clone();
265 }
266 if other.repeat.is_some() {
267 self.repeat = other.repeat.clone();
268 }
269 if other.luminance.is_some() {
270 self.luminance = other.luminance;
271 }
272 }
273}
274
275#[derive(Clone, Debug, PartialEq)]
277pub struct MaskStack {
278 pub layers: Vec<PaintLayer>,
279 pub luminance: bool,
280}
281
282#[derive(Clone, Copy, Debug, PartialEq, Eq)]
283pub enum ScrollbarWidth {
284 Auto,
287 Thin,
289 None,
290}
291
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub enum OverscrollBehavior {
294 Auto,
295 Contain,
296 None,
297}
298
299impl OverscrollBehavior {
300 pub fn chains(self) -> bool {
301 matches!(self, Self::Auto)
302 }
303}
304
305#[derive(Clone, Copy, Debug, PartialEq, Eq)]
306pub enum TextTransform {
307 None,
308 Uppercase,
309 Lowercase,
310 Capitalize,
311}
312
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub enum WhiteSpaceMode {
315 Normal,
316 Nowrap,
317 Pre,
318 PreWrap,
319 PreLine,
320 BreakSpaces,
321}
322
323impl WhiteSpaceMode {
324 pub fn collapses_spaces(self) -> bool {
325 matches!(
326 self,
327 WhiteSpaceMode::Normal | WhiteSpaceMode::Nowrap | WhiteSpaceMode::PreLine
328 )
329 }
330
331 pub fn preserves_newlines(self) -> bool {
332 !matches!(self, WhiteSpaceMode::Normal | WhiteSpaceMode::Nowrap)
333 }
334}
335
336impl TextTransform {
337 pub fn apply(self, text: &str) -> Option<String> {
338 match self {
339 TextTransform::None => None,
340 TextTransform::Uppercase => Some(text.to_uppercase()),
341 TextTransform::Lowercase => Some(text.to_lowercase()),
342 TextTransform::Capitalize => {
345 let mut out = String::with_capacity(text.len());
346 let mut at_word_start = true;
347 for ch in text.chars() {
348 if at_word_start && ch.is_alphabetic() {
349 out.extend(ch.to_uppercase());
350 at_word_start = false;
351 } else {
352 out.push(ch);
353 if ch.is_whitespace() {
354 at_word_start = true;
355 }
356 }
357 }
358 Some(out)
359 }
360 }
361 }
362}
363
364#[derive(Clone, Copy, Debug, PartialEq)]
365pub enum TextFill {
366 CurrentColor,
367 Color(Hsla),
368}
369
370#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
371pub enum SvgPaint {
372 None,
373 Current,
374 Color(Hsla),
375 Server,
376}
377
378impl SvgPaint {
379 pub fn as_attr(self) -> std::borrow::Cow<'static, str> {
380 match self {
381 SvgPaint::None => "none".into(),
382 SvgPaint::Current | SvgPaint::Server => "currentColor".into(),
383 SvgPaint::Color(c) => {
384 let c = gpui::Rgba::from(c);
385 let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
386 let (r, g, b) = (q(c.r), q(c.g), q(c.b));
387 let a = (c.a.clamp(0.0, 1.0) * 1000.0).round() / 1000.0;
388 if a >= 1.0 {
389 format!("rgb({r},{g},{b})").into()
390 } else {
391 format!("rgba({r},{g},{b},{a})").into()
392 }
393 }
394 }
395 }
396}
397
398#[derive(Clone, Copy, Debug, Default, PartialEq)]
399pub struct DecorationPatch {
400 pub color: Option<Option<Hsla>>,
403 pub thickness: Option<f32>,
404 pub wavy: Option<bool>,
405}
406
407impl DecorationPatch {
408 pub(crate) fn refine(&mut self, other: &Self) {
409 if other.color.is_some() {
410 self.color = other.color;
411 }
412 if other.thickness.is_some() {
413 self.thickness = other.thickness;
414 }
415 if other.wavy.is_some() {
416 self.wavy = other.wavy;
417 }
418 }
419
420 pub(crate) fn apply(&self, text: &mut gpui::TextStyleRefinement) {
424 let cancelled = |thickness: gpui::Pixels, color: Option<Hsla>| {
425 thickness == px(0.0) && color == Some(gpui::transparent_black())
426 };
427 if let Some(underline) = text.underline.as_mut() {
428 if !cancelled(underline.thickness, underline.color) {
429 if let Some(Some(color)) = self.color {
430 underline.color = Some(color);
431 }
432 if let Some(thickness) = self.thickness {
433 underline.thickness = px(thickness);
434 }
435 if let Some(wavy) = self.wavy {
436 underline.wavy = wavy;
437 }
438 }
439 }
440 if let (Some(strikethrough), Some(Some(color))) = (text.strikethrough.as_mut(), self.color)
441 {
442 if !cancelled(strikethrough.thickness, strikethrough.color) {
443 strikethrough.color = Some(color);
444 }
445 }
446 }
447}
448
449#[derive(Clone, Copy, Debug, Default, PartialEq)]
450pub struct OutlinePatch {
451 pub width: Option<f32>,
452 pub style: Option<gpui::BorderStyle>,
453 pub hidden: Option<bool>,
454 pub color: Option<Option<Hsla>>,
455 pub offset: Option<f32>,
456}
457
458impl OutlinePatch {
459 pub(crate) fn refine(&mut self, other: &Self) {
460 if other.width.is_some() {
461 self.width = other.width;
462 }
463 if other.style.is_some() {
464 self.style = other.style;
465 }
466 if other.hidden.is_some() {
467 self.hidden = other.hidden;
468 }
469 if other.color.is_some() {
470 self.color = other.color;
471 }
472 if other.offset.is_some() {
473 self.offset = other.offset;
474 }
475 }
476
477 pub(crate) fn merge_over(
478 &self,
479 earlier: Option<gpui::Outline>,
480 slot: &mut Option<gpui::Outline>,
481 ) {
482 let Some(mut ring) = earlier else { return };
483 if *self == Self::default() {
484 return;
485 }
486 if self.hidden == Some(true) {
487 ring.width = px(0.0);
488 } else {
489 if let Some(style) = self.style {
490 ring.style = style;
491 if ring.width == px(0.0) {
492 ring.width = px(3.0);
493 }
494 }
495 if let Some(width) = self.width {
496 ring.width = px(width);
497 }
498 }
499 if let Some(Some(color)) = self.color {
500 ring.color = color;
501 }
502 if let Some(offset) = self.offset {
503 ring.offset = px(offset);
504 }
505 *slot = Some(ring);
506 }
507
508 pub(crate) fn inherit_from(&self, base: gpui::Outline, ring: &mut gpui::Outline) {
512 if self.width.is_none() && self.hidden != Some(true) {
513 let medium = self.style.is_some() && ring.width == px(3.0) && base.width > px(0.0);
514 if ring.width == px(0.0) || medium {
515 ring.width = base.width;
516 }
517 }
518 if self.offset.is_none() && ring.offset == px(0.0) {
519 ring.offset = base.offset;
520 }
521 if self.color.is_none() && ring.color == Hsla::default() {
522 ring.color = base.color;
523 }
524 if self.style.is_none() && ring.style == gpui::BorderStyle::Solid {
525 ring.style = base.style;
526 }
527 }
528}
529
530impl Extras {
531 pub(crate) fn refine(&mut self, other: &Extras) {
532 if other.object_fit.is_some() {
533 self.object_fit = other.object_fit;
534 }
535 if other.window_drag.is_some() {
536 self.window_drag = other.window_drag;
537 }
538 if other.window_control.is_some() {
539 self.window_control = other.window_control;
540 }
541 if other.fixed.is_some() {
542 self.fixed = other.fixed;
543 }
544 if other.sticky.is_some() {
545 self.sticky = other.sticky;
546 }
547 if other.appearance_none.is_some() {
548 self.appearance_none = other.appearance_none;
549 }
550 if other.accent_color.is_some() {
551 self.accent_color = other.accent_color;
552 }
553 if other.z_index.is_some() {
554 self.z_index = other.z_index;
555 }
556 if other.isolate.is_some() {
557 self.isolate = other.isolate;
558 }
559 if other.view_transition_name.is_some() {
560 self.view_transition_name = other.view_transition_name.clone();
561 }
562 if other.view_transition_class.is_some() {
563 self.view_transition_class = other.view_transition_class.clone();
564 }
565 if other.plus_lighter.is_some() {
566 self.plus_lighter = other.plus_lighter;
567 }
568 if other.positioned.is_some() {
569 self.positioned = other.positioned;
570 }
571 if other.pointer_events_none.is_some() {
572 self.pointer_events_none = other.pointer_events_none;
573 }
574 if other.visibility_hidden.is_some() {
575 self.visibility_hidden = other.visibility_hidden;
576 }
577 if other.user_select.is_some() {
578 self.user_select = other.user_select;
579 }
580 if other.inline_level.is_some() {
581 self.inline_level = other.inline_level;
582 }
583 if other.fill.is_some() {
584 self.fill = other.fill;
585 }
586 if other.stroke.is_some() {
587 self.stroke = other.stroke;
588 }
589 if other.white_space.is_some() {
590 self.white_space = other.white_space;
591 }
592 if other.text_transform.is_some() {
593 self.text_transform = other.text_transform;
594 }
595 if other.content.is_some() {
596 self.content = other.content.clone();
597 self.content_none = false;
598 } else if other.content_none {
599 self.content = None;
600 self.content_none = true;
601 }
602 if other.blur.is_some() {
603 self.blur = other.blur;
604 self.drop_shadow = other.drop_shadow;
605 self.filter_url = other.filter_url.clone();
606 }
607 if other.background_clip_text.is_some() {
608 self.background_clip_text = other.background_clip_text;
609 }
610 if other.text_fill_color.is_some() {
611 self.text_fill_color = other.text_fill_color;
612 }
613 if let Some(theirs) = &other.svg_presentation {
614 self.svg_presentation = Some(match self.svg_presentation.take() {
615 None => theirs.clone(),
616 Some(mine) => {
617 let mut merged = (*mine).clone();
618 for (name, value) in theirs.iter() {
619 set_presentation(&mut merged, name, value.clone());
620 }
621 Rc::new(merged)
622 }
623 });
624 }
625 if other.background_key_color.is_some() {
626 self.background_key_color = other.background_key_color;
627 }
628 if other.background_images.is_some() {
629 self.background_images = other.background_images.clone();
630 self.background_urls = other.background_urls.clone();
631 }
632 if other.background_size.is_some() {
633 self.background_size = other.background_size.clone();
634 }
635 if other.background_position.is_some() {
636 self.background_position = other.background_position.clone();
637 }
638 if other.background_repeat.is_some() {
639 self.background_repeat = other.background_repeat.clone();
640 }
641 if other.list_marker.is_some() {
642 self.list_marker = other.list_marker;
643 }
644 if other.list_marker_inside.is_some() {
645 self.list_marker_inside = other.list_marker_inside;
646 }
647 if other.web_font.is_some() {
648 self.web_font = other.web_font.clone();
649 }
650 if other.underline_offset.is_some() {
651 self.underline_offset = other.underline_offset;
652 }
653 self.decoration.refine(&other.decoration);
654 self.outline.refine(&other.outline);
655 if other.scrollbar_width.is_some() {
656 self.scrollbar_width = other.scrollbar_width;
657 }
658 if other.scrollbar_color.is_some() {
659 self.scrollbar_color = other.scrollbar_color;
660 }
661 if other.overscroll_x.is_some() {
662 self.overscroll_x = other.overscroll_x;
663 }
664 if other.overscroll_y.is_some() {
665 self.overscroll_y = other.overscroll_y;
666 }
667 if other.contain_paint.is_some() {
668 self.contain_paint = other.contain_paint;
669 }
670 if other.contain_size.is_some() {
671 self.contain_size = other.contain_size;
672 }
673 if other.scroll_smooth.is_some() {
674 self.scroll_smooth = other.scroll_smooth;
675 }
676 if other.overflow_x.is_some() {
677 self.overflow_x = other.overflow_x;
678 }
679 if other.overflow_y.is_some() {
680 self.overflow_y = other.overflow_y;
681 }
682 if other.mask_images.is_some() {
683 self.mask_images = other.mask_images;
684 }
685 if other.mask_clips.is_some() {
686 self.mask_clips = other.mask_clips;
687 }
688 if other.mask_composite.is_some() {
689 self.mask_composite = other.mask_composite;
690 }
691 self.mask.refine(&other.mask);
692 self.current_color.0 =
693 (self.current_color.0 & !other.current_color_overrides.0) | other.current_color.0;
694 self.current_color_overrides.0 |= other.current_color_overrides.0;
695 self.radius_inherit.refine(&other.radius_inherit);
696 }
697
698 pub fn mask_ring(&self) -> bool {
699 self.mask_images == Some(MaskImages::TwoOpaque)
700 && self.mask_clips == Some(MaskClips::ContentThenBorder)
701 && self.mask_composite == Some(MaskCompositing::Exclude)
702 }
703
704 pub fn resolve_background_layers(&self) -> Vec<gpui::Background> {
705 let Some(images) = self.background_images.as_ref() else {
706 return Vec::new();
707 };
708 let mut out: Vec<gpui::Background> = images
709 .iter()
710 .map(|layer| self.tiled_gradient(layer))
711 .collect();
712 out.reverse();
713 out
714 }
715
716 pub fn resolve_background_stack(&self) -> Option<Vec<PaintLayer>> {
717 self.background_urls.as_ref().filter(|u| !u.is_empty())?;
718 Some(self.background_tiles().stack(
719 self.background_images.as_deref(),
720 self.background_urls.as_deref(),
721 ))
722 }
723
724 pub fn resolve_mask_stack(&self) -> Option<MaskStack> {
727 if self.mask_ring() {
728 return None;
729 }
730 let m = &self.mask;
731 let tiles = Tiles {
732 size: m.size.as_ref(),
733 position: m.position.as_ref(),
734 repeat: m.repeat.as_ref(),
735 };
736 let layers = tiles.stack(m.images.as_deref(), m.urls.as_deref());
737 (!layers.is_empty()).then(|| MaskStack {
738 layers,
739 luminance: m.luminance == Some(true),
740 })
741 }
742
743 fn background_tiles(&self) -> Tiles<'_> {
744 Tiles {
745 size: self.background_size.as_ref(),
746 position: self.background_position.as_ref(),
747 repeat: self.background_repeat.as_ref(),
748 }
749 }
750
751 fn tiled_gradient(&self, layer: &BackgroundLayer) -> gpui::Background {
752 self.background_tiles().gradient(layer)
753 }
754
755 pub fn z(&self) -> Option<i32> {
756 self.z_index.flatten()
757 }
758
759 pub fn may_defer(&self) -> bool {
762 self.z().is_some_and(|z| z != 0) || self.fixed == Some(true)
763 }
764}
765
766pub(crate) struct Converted {
769 pub normal: Option<Rc<StyleRefinement>>,
770 pub important: Option<Rc<StyleRefinement>>,
771 pub normal_transitions: Option<Rc<Vec<TransitionSpec>>>,
772 pub important_transitions: Option<Rc<Vec<TransitionSpec>>>,
773 pub normal_transition_declarations: Option<Rc<Collector>>,
774 pub important_transition_declarations: Option<Rc<Collector>>,
775 pub normal_animations: Option<Rc<Vec<AnimationSpec>>>,
776 pub important_animations: Option<Rc<Vec<AnimationSpec>>>,
777 pub normal_animation_patch: Option<AnimationPatch>,
778 pub important_animation_patch: Option<AnimationPatch>,
779 pub normal_extras: Extras,
780 pub important_extras: Extras,
781 pub normal_custom: Option<Rc<Decls>>,
782 pub important_custom: Option<Rc<Decls>>,
783 pub normal_dynamic: Option<Rc<Decls>>,
784 pub important_dynamic: Option<Rc<Decls>>,
785 pub normal_font: Option<FontDecls>,
786 pub important_font: Option<FontDecls>,
787 pub diagnostics: Option<Rc<Vec<String>>>,
790}
791
792pub type FontDecls = Rc<Vec<Property<'static>>>;
795
796#[derive(Default)]
797struct Half {
798 refinement: Option<Rc<StyleRefinement>>,
799 transitions: Option<Rc<Vec<TransitionSpec>>>,
800 transition_declarations: Option<Rc<Collector>>,
801 animations: Option<Rc<Vec<AnimationSpec>>>,
802 animation_patch: Option<AnimationPatch>,
803 extras: Extras,
804 custom: Option<Rc<Decls>>,
805 dynamic: Option<Rc<Decls>>,
806 font: Option<FontDecls>,
807}
808
809fn apply_static<'i>(
810 p: &Property<'i>,
811 r: &mut StyleRefinement,
812 x: &mut Extras,
813 font: &mut Option<Vec<Property<'static>>>,
814 diagnostics: &mut Vec<String>,
815) {
816 use lightningcss::traits::IntoOwned as _;
817 let ((), relative) = noting_font_units(|| apply(p, r, x, diagnostics));
818 if relative || font.is_some() {
819 font.get_or_insert_with(Vec::new)
820 .push(p.clone().into_owned());
821 }
822}
823
824enum Channel {
825 Custom(String, String),
826 Dynamic(String, String),
827 Static,
828}
829
830fn value_text(p: &Property) -> Option<String> {
833 let css = p.to_css_string(false, PrinterOptions::default()).ok()?;
834 let (_, value) = css.split_once(':')?;
835 Some(value.trim().to_string())
836}
837
838fn initial_inset_sides(name: &str, value: &lightningcss::properties::custom::TokenList<'_>) -> u8 {
841 if !single_ident_is(value, "initial") && !single_ident_is(value, "unset") {
842 return 0;
843 }
844 match name {
845 "top" | "inset-block-start" => 0b0001,
846 "right" | "inset-inline-end" => 0b0010,
847 "bottom" | "inset-block-end" => 0b0100,
848 "left" | "inset-inline-start" => 0b1000,
849 "inset-block" => 0b0101,
850 "inset-inline" => 0b1010,
851 "inset" => 0b1111,
852 _ => 0,
853 }
854}
855
856pub(crate) fn decl_pairs(block: &DeclarationBlock) -> Vec<(String, String, bool)> {
857 let mut out = Vec::new();
858 for (props, important) in [
859 (&block.declarations, false),
860 (&block.important_declarations, true),
861 ] {
862 for p in props.iter() {
863 let Some(css) = p.to_css_string(false, PrinterOptions::default()).ok() else {
864 continue;
865 };
866 match css.split_once(':') {
867 Some((name, value)) => {
868 out.push((name.trim().to_string(), value.trim().to_string(), important))
869 }
870 None => out.push((css, String::new(), important)),
873 }
874 }
875 }
876 out
877}
878
879fn channel(p: &Property, diagnostics: &mut Vec<String>) -> Channel {
880 use lightningcss::properties::custom::CustomPropertyName;
881 match p {
882 Property::Custom(c) => match &c.name {
883 CustomPropertyName::Custom(name) if name.0.as_ref() == effect::SHADING => {
884 Channel::Static
885 }
886 CustomPropertyName::Custom(name) if name.0.as_ref() == WINDOW_CONTROL => {
887 Channel::Static
888 }
889 CustomPropertyName::Custom(name) => match value_text(p) {
890 Some(v) => Channel::Custom(name.0.as_ref().to_string(), v),
891 None => {
892 once(
893 diagnostics,
894 format!(
895 "`{}` could not be serialized back to text and was dropped (v1)",
896 name.0.as_ref()
897 ),
898 );
899 Channel::Static
900 }
901 },
902 CustomPropertyName::Unknown(name)
903 if has_substitution(&c.value) || has_current_color_function(&c.value) =>
904 {
905 match value_text(p) {
906 Some(v) => Channel::Dynamic(name.0.as_ref().to_string(), v),
907 None => Channel::Static,
908 }
909 }
910 CustomPropertyName::Unknown(_) => Channel::Static,
911 },
912 Property::Unparsed(u)
913 if matches!(u.property_id, PropertyId::ClipPath(_)) && !has_substitution(&u.value) =>
914 {
915 Channel::Static
916 }
917 Property::Unparsed(u) if initial_inset_sides(u.property_id.name(), &u.value) != 0 => {
918 Channel::Static
919 }
920 Property::Unparsed(u) => match value_text(p) {
921 Some(v) => Channel::Dynamic(u.property_id.name().to_string(), v),
922 None => Channel::Static,
923 },
924 _ => Channel::Static,
925 }
926}
927
928pub(crate) fn convert_block(block: &DeclarationBlock) -> Converted {
929 let mut diagnostics: Vec<String> = Vec::new();
930 let diagnostics = &mut diagnostics;
931 let mut convert = |props: &[Property]| -> Half {
932 if props.is_empty() {
933 return Half::default();
934 }
935 let mut r = StyleRefinement::default();
936 let mut extras = Extras::default();
937 let mut transitions = Collector::default();
938 let mut animations = AnimationCollector::default();
939 let mut custom: Decls = Vec::new();
940 let mut dynamic: Decls = Vec::new();
941 let mut font: Option<Vec<Property<'static>>> = None;
942 let mut styled = false;
943 for p in props {
944 if crate::prefix::property_dropped(p) {
947 continue;
948 }
949 match channel(p, diagnostics) {
950 Channel::Custom(name, value) => custom.push((name, value)),
951 Channel::Dynamic(name, value) => dynamic.push((name, value)),
952 Channel::Static => {
953 if transitions.take(p, diagnostics) {
954 continue;
955 }
956 if animations.take(p, diagnostics) {
957 continue;
958 }
959 let id = p.property_id();
960 if dynamic.iter().any(|(n, _)| *n == id.name()) {
961 once(
962 diagnostics,
963 format!(
964 "`{}` is declared twice in one rule, once through var() and once \
965 literally — the literal one wins regardless of source order (v1)",
966 id.name()
967 ),
968 );
969 }
970 apply_static(p, &mut r, &mut extras, &mut font, diagnostics);
971 styled = true;
972 }
973 }
974 }
975 let (animation_list, animation_patch) = animations.finish();
976 Half {
977 refinement: styled.then(|| Rc::new(r)),
978 transition_declarations: transitions.declarations(),
979 transitions: transitions.finish().map(Rc::new),
980 animations: animation_list.map(Rc::new),
981 animation_patch,
982 extras,
983 custom: (!custom.is_empty()).then(|| Rc::new(custom)),
984 dynamic: (!dynamic.is_empty()).then(|| Rc::new(dynamic)),
985 font: font.map(Rc::new),
986 }
987 };
988 let normal = convert(&block.declarations);
989 let important = convert(&block.important_declarations);
990 let diagnostics = std::mem::take(diagnostics);
991 Converted {
992 normal: normal.refinement,
993 important: important.refinement,
994 normal_transitions: normal.transitions,
995 important_transitions: important.transitions,
996 normal_transition_declarations: normal.transition_declarations,
997 important_transition_declarations: important.transition_declarations,
998 normal_animations: normal.animations,
999 important_animations: important.animations,
1000 normal_animation_patch: normal.animation_patch,
1001 important_animation_patch: important.animation_patch,
1002 normal_extras: normal.extras,
1003 important_extras: important.extras,
1004 normal_custom: normal.custom,
1005 important_custom: important.custom,
1006 normal_dynamic: normal.dynamic,
1007 important_dynamic: important.dynamic,
1008 normal_font: normal.font,
1009 important_font: important.font,
1010 diagnostics: (!diagnostics.is_empty()).then(|| Rc::new(diagnostics)),
1011 }
1012}
1013
1014thread_local! {
1015 static CURRENT_COLOR: std::cell::Cell<Option<(Hsla, Hsla)>> = const { std::cell::Cell::new(None) };
1019 static CURRENT_COLOR_READ: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1020}
1021
1022pub(crate) struct CurrentColorScope {
1026 outer: Option<(Hsla, Hsla)>,
1027 outer_read: bool,
1028}
1029
1030impl CurrentColorScope {
1031 pub(crate) fn enter(parent: Hsla, own: Hsla) -> Self {
1032 Self {
1033 outer: CURRENT_COLOR.with(|c| c.replace(Some((parent, own)))),
1034 outer_read: CURRENT_COLOR_READ.with(|r| r.replace(false)),
1035 }
1036 }
1037
1038 pub(crate) fn read(&self) -> bool {
1039 CURRENT_COLOR_READ.with(std::cell::Cell::get)
1040 }
1041}
1042
1043impl Drop for CurrentColorScope {
1044 fn drop(&mut self) {
1045 CURRENT_COLOR.with(|c| c.set(self.outer));
1046 CURRENT_COLOR_READ.with(|r| r.set(self.outer_read));
1047 }
1048}
1049
1050fn current_color_substituted(name: &str, value: &str) -> Option<String> {
1054 const KEYWORD: &str = "currentcolor";
1055 let lower = value.to_ascii_lowercase();
1056 let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'-' || b == b'_';
1057 let bytes = lower.as_bytes();
1058 let starts: Vec<usize> = lower
1059 .match_indices(KEYWORD)
1060 .map(|(at, _)| at)
1061 .filter(|&at| {
1062 let end = at + KEYWORD.len();
1063 (at == 0 || !ident(bytes[at - 1])) && (end == bytes.len() || !ident(bytes[end]))
1064 })
1065 .collect();
1066 if starts.is_empty() {
1067 return None;
1068 }
1069 let (parent, own) = CURRENT_COLOR.with(std::cell::Cell::get)?;
1070 CURRENT_COLOR_READ.with(|r| r.set(true));
1071 let c = gpui::Rgba::from(if name == "color" { parent } else { own });
1072 let literal = format!(
1073 "rgb({} {} {} / {})",
1074 c.r * 255.0,
1075 c.g * 255.0,
1076 c.b * 255.0,
1077 c.a
1078 );
1079 let mut out = String::with_capacity(value.len() + starts.len() * literal.len());
1080 let mut from = 0;
1081 for at in starts {
1082 out.push_str(&value[from..at]);
1083 out.push_str(&literal);
1084 from = at + KEYWORD.len();
1085 }
1086 out.push_str(&value[from..]);
1087 Some(out)
1088}
1089
1090pub(crate) fn apply_dynamic(
1093 name: &str,
1094 raw: &str,
1095 vars: &Vars,
1096 env: &crate::Env,
1097 r: &mut StyleRefinement,
1098 x: &mut Extras,
1099 diagnostics: &mut Vec<String>,
1100) {
1101 let value = match vars::substitute_with(raw, vars, env) {
1102 Ok(v) => v,
1103 Err(vars::VarError::Unresolved(_)) => return,
1106 Err(e) => {
1107 once(
1108 diagnostics,
1109 format!(
1110 "`{name}: {raw}` is invalid at computed-value time — {} (the declaration was \
1111 dropped, as it would be in a browser)",
1112 e.describe()
1113 ),
1114 );
1115 return;
1116 }
1117 };
1118 use lightningcss::traits::IntoOwned as _;
1119 let parse = |value: &str| {
1120 Property::parse_string(PropertyId::from(name), value, ParserOptions::default())
1121 .ok()
1122 .map(|p| p.into_owned())
1123 };
1124 let property = match parse(&value) {
1125 Some(unresolved @ (Property::Unparsed(_) | Property::Custom(_))) => {
1126 match current_color_substituted(name, &value) {
1127 Some(concrete) => parse(&concrete),
1128 None => Some(unresolved),
1129 }
1130 }
1131 parsed => parsed,
1132 };
1133 let Some(property) = property else {
1134 once(
1135 diagnostics,
1136 format!("`{name}: {value}` did not parse after var() substitution (v1)"),
1137 );
1138 return;
1139 };
1140 if matches!(
1143 property,
1144 Property::Transition(..)
1145 | Property::TransitionProperty(..)
1146 | Property::TransitionDuration(..)
1147 | Property::TransitionDelay(..)
1148 | Property::TransitionTimingFunction(..)
1149 ) {
1150 once(
1151 diagnostics,
1152 format!(
1153 "`{name}` composed with var() is not honoured (v1) — the transition list is folded \
1154 once per rule, not per element; declare the transition literally"
1155 ),
1156 );
1157 return;
1158 }
1159 apply(&property, r, x, diagnostics);
1160}
1161
1162pub fn parse_inline(body: &str, diagnostics: &mut Vec<String>) -> StyleRefinement {
1163 let (refinement, transitions, _) = parse_inline_full(body, diagnostics);
1164 if !transitions.is_empty() {
1165 diagnostics.push(
1166 "inline `transition` is parsed but dropped by parse_inline — the caller must use \
1167 parse_inline_with_transitions to honor it"
1168 .into(),
1169 );
1170 }
1171 refinement
1172}
1173
1174pub fn parse_inline_with_transitions(
1175 body: &str,
1176 diagnostics: &mut Vec<String>,
1177) -> (StyleRefinement, Vec<TransitionSpec>) {
1178 let (r, t, _) = parse_inline_full(body, diagnostics);
1179 (r, t)
1180}
1181
1182pub fn parse_inline_full(
1183 body: &str,
1184 diagnostics: &mut Vec<String>,
1185) -> (StyleRefinement, Vec<TransitionSpec>, Extras) {
1186 let inline = parse_inline_style(body, diagnostics);
1187 (
1188 inline.refinement.map(|r| (*r).clone()).unwrap_or_default(),
1189 inline.transitions.map(|t| (*t).clone()).unwrap_or_default(),
1190 inline.extras,
1191 )
1192}
1193
1194#[derive(Clone, Debug, Default)]
1195pub struct InlineMotion {
1196 pub(crate) transitions: Option<Rc<Collector>>,
1197 pub(crate) animations: Option<AnimationPatch>,
1198}
1199impl InlineMotion {
1200 fn is_empty(&self) -> bool {
1201 self.transitions.is_none() && self.animations.is_none()
1202 }
1203}
1204
1205#[derive(Clone, Debug, Default, PartialEq)]
1206pub struct InlinePriority {
1207 pub refinement: Option<Rc<StyleRefinement>>,
1208 pub extras: Extras,
1209 pub custom: Option<Rc<Decls>>,
1210 pub dynamic: Option<Rc<Decls>>,
1211 pub font: Option<FontDecls>,
1212}
1213
1214#[derive(Clone, Debug, Default)]
1215pub struct InlineStyle {
1216 pub normal_motion: Option<InlineMotion>,
1217 pub important_motion: Option<InlineMotion>,
1218 pub refinement: Option<Rc<StyleRefinement>>,
1219 pub transitions: Option<Rc<Vec<TransitionSpec>>>,
1222 pub animations: Option<Rc<Vec<AnimationSpec>>>,
1225 pub animation_patch: Option<AnimationPatch>,
1228 pub extras: Extras,
1229 pub custom: Decls,
1230 pub dynamic: Decls,
1231 pub font: Option<FontDecls>,
1233 #[doc(hidden)]
1234 pub priority: Option<Rc<[InlinePriority; 2]>>,
1235}
1236
1237impl InlineStyle {
1238 pub fn is_empty(&self) -> bool {
1239 self.refinement.is_none()
1240 && self.transitions.is_none()
1241 && self.animations.is_none()
1242 && self.animation_patch.is_none()
1243 && self.extras == Extras::default()
1244 && self.custom.is_empty()
1245 && self.dynamic.is_empty()
1246 && self.font.is_none()
1247 }
1248}
1249
1250pub fn accepts_declaration(name: &str, value: &str) -> bool {
1253 matches!(verdict(name, value), Verdict::Applied | Verdict::Inert)
1254}
1255
1256#[derive(Clone, Debug, PartialEq, Eq)]
1258pub enum Verdict {
1259 Applied,
1261 Inert,
1263 Rejected(String),
1265 Dropped,
1267 Invalid,
1269}
1270
1271pub fn verdict(name: &str, value: &str) -> Verdict {
1272 let name = name.trim();
1273 if name.starts_with("--") {
1274 return if value.contains(';') {
1275 Verdict::Invalid
1276 } else {
1277 Verdict::Applied
1278 };
1279 }
1280 let body = format!("{name}: {value}");
1281 let Ok(block) = DeclarationBlock::parse_string(&body, ParserOptions::default()) else {
1282 return Verdict::Invalid;
1283 };
1284 if block.len() != 1 {
1285 return Verdict::Invalid;
1286 }
1287 let p = block
1288 .declarations
1289 .iter()
1290 .chain(block.important_declarations.iter())
1291 .next();
1292 if p.is_some_and(crate::prefix::property_dropped) {
1293 return Verdict::Dropped;
1294 }
1295 let mut diagnostics = Vec::new();
1296 let changed = match p {
1297 Some(Property::Unparsed(u)) => {
1298 if has_substitution(&u.value) || is_css_wide_keyword(&u.value) {
1299 return Verdict::Applied;
1300 }
1301 let (mut r, mut x) = (StyleRefinement::default(), Extras::default());
1302 if !apply_unparsed(u, &mut r, &mut x, &mut diagnostics) {
1303 return Verdict::Invalid;
1304 }
1305 r != StyleRefinement::default() || x != Extras::default()
1306 }
1307 Some(Property::Custom(c)) if has_substitution(&c.value) => return Verdict::Applied,
1308 _ => {
1309 let style = parse_inline_style(&body, &mut diagnostics);
1310 style
1311 .refinement
1312 .as_deref()
1313 .is_some_and(|s| *s != StyleRefinement::default())
1314 || style.extras != Extras::default()
1315 || style.transitions.is_some()
1316 || style.animations.is_some()
1317 || style.animation_patch.is_some()
1318 || style.font.is_some()
1319 }
1320 };
1321 if let Some(first) = diagnostics.into_iter().next() {
1322 return Verdict::Rejected(first);
1323 }
1324 if changed {
1325 Verdict::Applied
1326 } else {
1327 Verdict::Inert
1328 }
1329}
1330
1331pub fn parse_inline_style(body: &str, diagnostics: &mut Vec<String>) -> InlineStyle {
1332 let mut r = StyleRefinement::default();
1333 let mut extras = Extras::default();
1334 let mut normal_transitions = Collector::default();
1335 let mut important_transitions = Collector::default();
1336 let mut normal_animations = AnimationCollector::default();
1337 let mut important_animations = AnimationCollector::default();
1338 let mut custom: Decls = Vec::new();
1339 let mut dynamic: Decls = Vec::new();
1340 let mut font: Option<Vec<Property<'static>>> = None;
1341 let mut styled = false;
1342 let mut priority = None;
1343 let warnings = std::sync::Arc::new(std::sync::RwLock::new(Vec::new()));
1345 let options = ParserOptions {
1346 error_recovery: true,
1347 warnings: Some(warnings.clone()),
1348 ..ParserOptions::default()
1349 };
1350 let parsed = DeclarationBlock::parse_string(body, options);
1351 if let Ok(skipped) = warnings.read() {
1352 for e in skipped.iter() {
1353 diagnostics.push(format!(
1354 "inline style: {e} in {body:?} — skipped, as a browser skips it"
1355 ));
1356 }
1357 }
1358 match parsed {
1359 Ok(block) => {
1360 for (important, declarations) in [
1361 (false, &block.declarations),
1362 (true, &block.important_declarations),
1363 ] {
1364 let transitions = if important {
1365 &mut important_transitions
1366 } else {
1367 &mut normal_transitions
1368 };
1369 let animations = if important {
1370 &mut important_animations
1371 } else {
1372 &mut normal_animations
1373 };
1374 for p in declarations {
1375 if crate::prefix::property_dropped(p) {
1376 continue;
1377 }
1378 match channel(p, diagnostics) {
1379 Channel::Custom(name, value) => custom.push((name, value)),
1380 Channel::Dynamic(name, value) => dynamic.push((name, value)),
1381 Channel::Static => {
1382 if transitions.take(p, diagnostics) {
1383 continue;
1384 }
1385 if animations.take(p, diagnostics) {
1386 continue;
1387 }
1388 apply_static(p, &mut r, &mut extras, &mut font, diagnostics);
1389 styled = true;
1390 }
1391 }
1392 }
1393 }
1394 if !custom.is_empty() || !dynamic.is_empty() || !block.important_declarations.is_empty()
1395 {
1396 let converted = convert_block(&block);
1397 let half = |important| InlinePriority {
1398 refinement: if important {
1399 converted.important.clone()
1400 } else {
1401 converted.normal.clone()
1402 },
1403 extras: if important {
1404 converted.important_extras.clone()
1405 } else {
1406 converted.normal_extras.clone()
1407 },
1408 custom: if important {
1409 converted.important_custom.clone()
1410 } else {
1411 converted.normal_custom.clone()
1412 },
1413 dynamic: if important {
1414 converted.important_dynamic.clone()
1415 } else {
1416 converted.normal_dynamic.clone()
1417 },
1418 font: if important {
1419 converted.important_font.clone()
1420 } else {
1421 converted.normal_font.clone()
1422 },
1423 };
1424 priority = Some(Rc::new([half(false), half(true)]));
1425 }
1426 }
1427 Err(e) => diagnostics.push(format!("inline style parse error: {e} in {body:?}")),
1428 }
1429 let normal_motion = InlineMotion {
1430 transitions: normal_transitions.declarations(),
1431 animations: normal_animations.clone().finish().1,
1432 };
1433 let important_motion = InlineMotion {
1434 transitions: important_transitions.declarations(),
1435 animations: important_animations.clone().finish().1,
1436 };
1437 normal_transitions.merge(&important_transitions);
1438 normal_animations.merge(&important_animations);
1439 let (animation_list, animation_patch) = normal_animations.finish();
1440 InlineStyle {
1441 normal_motion: (!normal_motion.is_empty()).then_some(normal_motion),
1442 important_motion: (!important_motion.is_empty()).then_some(important_motion),
1443 refinement: styled.then(|| Rc::new(r)),
1444 transitions: normal_transitions.finish().map(Rc::new),
1445 animations: animation_list.map(Rc::new),
1446 animation_patch,
1447 extras,
1448 custom,
1449 dynamic,
1450 font: font.map(Rc::new),
1451 priority,
1452 }
1453}
1454
1455fn color(c: &CssColor) -> Option<Hsla> {
1456 let [r, g, b, a] = srgb(c)?;
1457 Some(gpui::Rgba { r, g, b, a }.into())
1458}
1459
1460pub(crate) fn srgb(c: &CssColor) -> Option<[f32; 4]> {
1464 use lightningcss::values::color::{ColorSpace, SRGB};
1465 match c {
1466 CssColor::RGBA(c) => Some([
1467 c.red as f32 / 255.0,
1468 c.green as f32 / 255.0,
1469 c.blue as f32 / 255.0,
1470 c.alpha_f32(),
1471 ]),
1472 CssColor::LAB(_) | CssColor::Predefined(_) | CssColor::Float(_) => {
1473 let c = SRGB::try_from(c).ok()?.resolve_missing();
1474 Some([c.r, c.g, c.b, c.alpha].map(|v| v.clamp(0.0, 1.0)))
1475 }
1476 CssColor::CurrentColor | CssColor::LightDark(..) | CssColor::System(_) => None,
1477 }
1478}
1479
1480thread_local! {
1481 static REM_BASIS: std::cell::Cell<f32> = const { std::cell::Cell::new(INITIAL_REM_BASIS) };
1482 static VIEWPORT_BASIS: std::cell::Cell<(f32, f32)> =
1483 const { std::cell::Cell::new(INITIAL_VIEWPORT_BASIS) };
1484 static VIEWPORT_UNITS_SEEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1487 static CALC_DROPPED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1488 static FONT_SOURCE: std::cell::RefCell<Option<Box<dyn Fn() -> Vec<String>>>> =
1489 const { std::cell::RefCell::new(None) };
1490 static INSTALLED_FONTS: std::cell::RefCell<Option<Rc<std::collections::HashSet<String>>>> =
1491 const { std::cell::RefCell::new(None) };
1492 static FONT_MISSES: std::cell::RefCell<Vec<(String, Option<String>)>> =
1493 const { std::cell::RefCell::new(Vec::new()) };
1494 static WEB_FONTS: std::cell::RefCell<std::collections::HashSet<String>> =
1495 std::cell::RefCell::new(std::collections::HashSet::new());
1496}
1497
1498pub fn set_web_font_families(families: impl IntoIterator<Item = String>) {
1499 let set = families.into_iter().map(|f| f.to_lowercase()).collect();
1500 WEB_FONTS.with(|w| *w.borrow_mut() = set);
1501}
1502
1503fn waiting_web_font(families: &[CssFontFamily]) -> Option<Rc<[String]>> {
1504 use lightningcss::traits::ToCss;
1505 WEB_FONTS.with(|w| {
1506 let w = w.borrow();
1507 if w.is_empty() {
1508 return None;
1509 }
1510 let mut out = Vec::new();
1511 for f in families {
1512 let CssFontFamily::FamilyName(name) = f else {
1513 break;
1514 };
1515 let Ok(css) = name.to_css_string(Default::default()) else {
1516 continue;
1517 };
1518 let clean = css.trim_matches('"');
1519 if w.contains(&clean.to_lowercase()) {
1520 out.push(clean.to_string());
1521 }
1522 if font_installed(clean) != Some(false) {
1523 break;
1524 }
1525 }
1526 Some(Rc::from(out))
1527 })
1528}
1529
1530pub fn set_font_source(source: impl Fn() -> Vec<String> + 'static) {
1533 FONT_SOURCE.with(|s| *s.borrow_mut() = Some(Box::new(source)));
1534 INSTALLED_FONTS.with(|c| *c.borrow_mut() = None);
1535}
1536
1537fn font_installed(name: &str) -> Option<bool> {
1538 let set = INSTALLED_FONTS.with(|c| c.borrow().clone()).or_else(|| {
1539 let names = FONT_SOURCE.with(|s| s.borrow().as_ref().map(|f| f()))?;
1540 let set = Rc::new(names.into_iter().collect::<std::collections::HashSet<_>>());
1541 INSTALLED_FONTS.with(|c| *c.borrow_mut() = Some(set.clone()));
1542 Some(set)
1543 })?;
1544 Some(set.contains(name))
1545}
1546
1547pub fn take_font_misses() -> Vec<(String, Option<String>)> {
1548 FONT_MISSES.with(|m| std::mem::take(&mut *m.borrow_mut()))
1549}
1550
1551fn note_font_miss(asked: String, used: Option<String>) {
1552 FONT_MISSES.with(|m| {
1553 let mut m = m.borrow_mut();
1554 if !m.iter().any(|(a, _)| *a == asked) {
1555 m.push((asked, used));
1556 }
1557 });
1558}
1559
1560fn generic_family(g: &lightningcss::properties::font::GenericFontFamily) -> Option<String> {
1563 use lightningcss::properties::font::GenericFontFamily as G;
1564 let candidates: &[&str] = match g {
1565 G::SystemUI => return Some(".SystemUIFont".into()),
1566 G::SansSerif => &["Arial", "Helvetica", "Liberation Sans"],
1567 G::Serif => &["Times New Roman", "Times", "Liberation Serif"],
1568 G::Monospace => &[
1569 "Consolas",
1570 "Menlo",
1571 "DejaVu Sans Mono",
1572 "Liberation Mono",
1573 "Courier New",
1574 ],
1575 G::Cursive => &["Comic Sans MS"],
1576 G::Fantasy => &["Impact"],
1577 _ => return None,
1578 };
1579 Some(
1580 candidates
1581 .iter()
1582 .find(|c| font_installed(c) != Some(false))
1583 .map_or(".SystemUIFont", |c| *c)
1584 .into(),
1585 )
1586}
1587
1588fn first_available_family(families: &[CssFontFamily]) -> Option<String> {
1589 use lightningcss::traits::ToCss;
1590 let mut first_named = None;
1591 let mut asked_first = None;
1592 for (i, f) in families.iter().enumerate() {
1593 let found = match f {
1594 CssFontFamily::FamilyName(name) => {
1595 let Ok(css) = name.to_css_string(Default::default()) else {
1596 continue;
1597 };
1598 let clean = css.trim_matches('"').to_string();
1599 if font_installed(&clean) == Some(false) {
1600 if i == 0 {
1601 asked_first = Some(clean.clone());
1602 }
1603 first_named.get_or_insert(clean);
1604 None
1605 } else {
1606 Some(clean)
1607 }
1608 }
1609 CssFontFamily::Generic(g) => generic_family(g),
1610 };
1611 if let Some(used) = found {
1612 if let Some(asked) = asked_first {
1613 note_font_miss(asked, Some(used.clone()));
1614 }
1615 return Some(used);
1616 }
1617 }
1618 if let Some(asked) = asked_first {
1619 note_font_miss(asked, None);
1620 }
1621 first_named
1622}
1623
1624thread_local! {
1625 static COMPOSED_FONTS: std::cell::RefCell<Vec<(String, bool)>> = const { std::cell::RefCell::new(Vec::new()) };
1626 static UNREACHED_FONTS: std::cell::RefCell<Vec<(String, String)>> = const { std::cell::RefCell::new(Vec::new()) };
1627}
1628
1629pub fn set_composed_font_families(families: impl IntoIterator<Item = (String, bool)>) {
1630 let list = families
1631 .into_iter()
1632 .map(|(f, latin)| (f.to_lowercase(), latin))
1633 .collect();
1634 COMPOSED_FONTS.with(|c| *c.borrow_mut() = list);
1635}
1636
1637pub fn take_unreached_fonts() -> Vec<(String, String)> {
1638 UNREACHED_FONTS.with(|m| std::mem::take(&mut *m.borrow_mut()))
1639}
1640
1641fn composed_font_stack(families: &[CssFontFamily]) -> Option<(String, gpui::FontFallbacks)> {
1642 use lightningcss::traits::ToCss;
1643 let composed = COMPOSED_FONTS.with(|c| c.borrow().clone());
1644 if composed.is_empty() {
1645 return None;
1646 }
1647 let mut stack: Vec<(String, Option<bool>)> = Vec::new();
1648 for f in families {
1649 let (name, generic) = match f {
1650 CssFontFamily::FamilyName(name) => {
1651 let Ok(css) = name.to_css_string(Default::default()) else {
1652 continue;
1653 };
1654 (css.trim_matches('"').to_string(), false)
1655 }
1656 CssFontFamily::Generic(g) => match generic_family(g) {
1657 Some(name) => (name, true),
1658 None => continue,
1659 },
1660 };
1661 let latin = composed
1662 .iter()
1663 .find(|(c, _)| c.eq_ignore_ascii_case(&name))
1664 .map(|c| c.1);
1665 if latin.is_none() && !generic && font_installed(&name) == Some(false) {
1666 continue;
1667 }
1668 if !stack.iter().any(|(s, _)| s.eq_ignore_ascii_case(&name)) {
1669 stack.push((name, latin));
1670 }
1671 }
1672 let (first, latin) = stack.first()?.clone();
1673 if latin.is_none() {
1674 for (name, _) in stack.iter().skip(1).filter(|s| s.1.is_some()) {
1677 UNREACHED_FONTS.with(|u| {
1678 let mut u = u.borrow_mut();
1679 if !u.iter().any(|(n, _)| n == name) {
1680 u.push((name.clone(), first.clone()));
1681 }
1682 });
1683 }
1684 return Some((first, gpui::FontFallbacks::default()));
1685 }
1686 let rest = stack.into_iter().skip(1).map(|s| s.0).collect();
1687 Some((first, gpui::FontFallbacks::from_fonts(rest)))
1688}
1689
1690pub const INITIAL_REM_BASIS: f32 = 16.0;
1691
1692pub fn rem_basis() -> f32 {
1693 REM_BASIS.with(|c| c.get())
1694}
1695
1696pub fn set_rem_basis(px: f32) -> bool {
1699 if !(px.is_finite() && (1.0..=200.0).contains(&px)) {
1700 return false;
1701 }
1702 REM_BASIS.with(|c| {
1703 if (c.get() - px).abs() < f32::EPSILON {
1704 false
1705 } else {
1706 c.set(px);
1707 true
1708 }
1709 })
1710}
1711
1712pub const INITIAL_VIEWPORT_BASIS: (f32, f32) = (1280.0, 720.0);
1714
1715pub fn viewport_basis() -> (f32, f32) {
1716 VIEWPORT_BASIS.with(|c| c.get())
1717}
1718
1719pub fn uses_viewport_units() -> bool {
1720 VIEWPORT_UNITS_SEEN.with(|c| c.get())
1721}
1722
1723pub fn reset_viewport_units_seen() {
1724 VIEWPORT_UNITS_SEEN.with(|c| c.set(false));
1725}
1726
1727pub(crate) fn noting_viewport_units<R>(f: impl FnOnce() -> R) -> (R, bool) {
1728 let before = VIEWPORT_UNITS_SEEN.with(|c| c.replace(false));
1729 let out = f();
1730 let seen = VIEWPORT_UNITS_SEEN.with(|c| c.get());
1731 VIEWPORT_UNITS_SEEN.with(|c| c.set(before || seen));
1732 (out, seen)
1733}
1734
1735pub fn set_viewport_basis(width: f32, height: f32) -> bool {
1736 if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) {
1737 return false;
1738 }
1739 VIEWPORT_BASIS.with(|c| {
1740 let (w, h) = c.get();
1741 if (w - width).abs() < f32::EPSILON && (h - height).abs() < f32::EPSILON {
1742 false
1743 } else {
1744 c.set((width, height));
1745 true
1746 }
1747 })
1748}
1749
1750fn viewport_value_px(v: &LengthValue) -> Option<f32> {
1754 let (w, h) = viewport_basis();
1755 let px = match v {
1756 LengthValue::Vw(p)
1757 | LengthValue::Svw(p)
1758 | LengthValue::Lvw(p)
1759 | LengthValue::Dvw(p)
1760 | LengthValue::Vi(p)
1761 | LengthValue::Svi(p)
1762 | LengthValue::Lvi(p)
1763 | LengthValue::Dvi(p) => p / 100.0 * w,
1764 LengthValue::Vh(p)
1765 | LengthValue::Svh(p)
1766 | LengthValue::Lvh(p)
1767 | LengthValue::Dvh(p)
1768 | LengthValue::Vb(p)
1769 | LengthValue::Svb(p)
1770 | LengthValue::Lvb(p)
1771 | LengthValue::Dvb(p) => p / 100.0 * h,
1772 LengthValue::Vmin(p)
1773 | LengthValue::Svmin(p)
1774 | LengthValue::Lvmin(p)
1775 | LengthValue::Dvmin(p) => p / 100.0 * w.min(h),
1776 LengthValue::Vmax(p)
1777 | LengthValue::Svmax(p)
1778 | LengthValue::Lvmax(p)
1779 | LengthValue::Dvmax(p) => p / 100.0 * w.max(h),
1780 _ => return None,
1781 };
1782 VIEWPORT_UNITS_SEEN.with(|c| c.set(true));
1783 Some(px)
1784}
1785
1786fn viewport_unit_px(unit: &str, value: f32) -> Option<f32> {
1787 let (w, h) = viewport_basis();
1788 let basis = match unit {
1789 "vw" | "svw" | "lvw" | "dvw" | "vi" | "svi" | "lvi" | "dvi" => w,
1790 "vh" | "svh" | "lvh" | "dvh" | "vb" | "svb" | "lvb" | "dvb" => h,
1791 "vmin" | "svmin" | "lvmin" | "dvmin" => w.min(h),
1792 "vmax" | "svmax" | "lvmax" | "dvmax" => w.max(h),
1793 _ => return None,
1794 };
1795 VIEWPORT_UNITS_SEEN.with(|c| c.set(true));
1796 Some(value / 100.0 * basis)
1797}
1798
1799fn length_value_px(v: &LengthValue) -> Option<f32> {
1800 match v {
1801 LengthValue::Px(v) => Some(*v),
1802 LengthValue::Rem(v) => Some(v * rem_basis()),
1803 LengthValue::Em(v) => Some(v * em_basis()),
1804 LengthValue::Ch(v) => Some(v * character_basis(false)),
1805 LengthValue::Ex(v) => Some(v * character_basis(true)),
1806 LengthValue::Rch(v) | LengthValue::Rex(v) => Some(v * HALF_EM * rem_basis()),
1807 other => viewport_value_px(other),
1808 }
1809}
1810
1811const HALF_EM: f32 = 0.5;
1813
1814#[derive(Clone, Copy, Debug, PartialEq)]
1815pub struct FontRelativeMetrics {
1816 pub zero_advance: f32,
1817 pub x_height: f32,
1818}
1819
1820thread_local! {
1821 static FONT_METRIC_SOURCE: std::cell::RefCell<Option<Box<dyn Fn(&gpui::Font, f32) -> Option<FontRelativeMetrics>>>> = const { std::cell::RefCell::new(None) };
1822 static FONT_METRIC_GENERATION: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1823 static FONT_FACE: std::cell::RefCell<Option<gpui::Font>> = const { std::cell::RefCell::new(None) };
1824}
1825
1826pub fn set_font_metric_source(
1829 source: impl Fn(&gpui::Font, f32) -> Option<FontRelativeMetrics> + 'static,
1830) {
1831 FONT_METRIC_SOURCE.with(|slot| *slot.borrow_mut() = Some(Box::new(source)));
1832 FONT_METRIC_GENERATION.with(|generation| generation.set(generation.get().wrapping_add(1)));
1833}
1834
1835pub(crate) fn font_metric_generation() -> u32 {
1836 FONT_METRIC_GENERATION.with(|generation| generation.get())
1837}
1838
1839pub(crate) fn with_font_face<R>(font: &gpui::Font, f: impl FnOnce() -> R) -> R {
1840 struct Restore(Option<gpui::Font>);
1841 impl Drop for Restore {
1842 fn drop(&mut self) {
1843 FONT_FACE.with(|slot| *slot.borrow_mut() = self.0.take());
1844 }
1845 }
1846 let _restore = Restore(FONT_FACE.with(|slot| slot.replace(Some(font.clone()))));
1847 f()
1848}
1849
1850fn character_basis(x_height: bool) -> f32 {
1851 let size = em_basis();
1852 let font = FONT_FACE.with(|slot| slot.borrow().clone());
1853 font.and_then(|font| {
1854 FONT_METRIC_SOURCE.with(|slot| {
1855 slot.borrow()
1856 .as_ref()
1857 .and_then(|source| source(&font, size))
1858 })
1859 })
1860 .map(|metrics| {
1861 if x_height {
1862 metrics.x_height
1863 } else {
1864 metrics.zero_advance
1865 }
1866 })
1867 .filter(|value| value.is_finite() && *value > 0.0)
1868 .unwrap_or(HALF_EM * size)
1869}
1870
1871fn font_unit_px(unit: &str, value: f32) -> Option<f32> {
1872 match unit {
1873 "rem" => Some(value * rem_basis()),
1874 "em" => Some(value * em_basis()),
1875 "ch" => Some(value * character_basis(false)),
1876 "ex" => Some(value * character_basis(true)),
1877 "rch" | "rex" => Some(value * HALF_EM * rem_basis()),
1878 _ => None,
1879 }
1880}
1881
1882thread_local! {
1883 static FONT_BASIS: std::cell::Cell<f32> = const { std::cell::Cell::new(f32::NAN) };
1884 static FONT_UNITS_SEEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1885}
1886
1887fn em_basis() -> f32 {
1888 FONT_UNITS_SEEN.with(|c| c.set(true));
1889 let basis = FONT_BASIS.with(|c| c.get());
1890 if basis.is_nan() {
1891 rem_basis()
1892 } else {
1893 basis
1894 }
1895}
1896
1897pub(crate) fn with_font_basis<R>(px: f32, f: impl FnOnce() -> R) -> R {
1898 struct Restore(f32);
1899 impl Drop for Restore {
1900 fn drop(&mut self) {
1901 FONT_BASIS.with(|c| c.set(self.0));
1902 }
1903 }
1904 let _restore = Restore(FONT_BASIS.with(|c| c.replace(px)));
1905 f()
1906}
1907
1908pub(crate) fn noting_font_units<R>(f: impl FnOnce() -> R) -> (R, bool) {
1909 let before = FONT_UNITS_SEEN.with(|c| c.replace(false));
1910 let out = f();
1911 let seen = FONT_UNITS_SEEN.with(|c| c.replace(before));
1912 FONT_UNITS_SEEN.with(|c| c.set(before || seen));
1913 (out, seen)
1914}
1915
1916pub(crate) fn sets_font_size(p: &Property) -> bool {
1919 matches!(p, Property::FontSize(_))
1920}
1921
1922pub(crate) fn apply_at(
1923 p: &Property,
1924 basis: f32,
1925 r: &mut StyleRefinement,
1926 x: &mut Extras,
1927 diagnostics: &mut Vec<String>,
1928) {
1929 with_font_basis(basis, || apply(p, r, x, diagnostics));
1930}
1931
1932pub(crate) fn font_size_px(l: AbsoluteLength) -> f32 {
1933 match l {
1934 AbsoluteLength::Pixels(p) => f32::from(p),
1935 AbsoluteLength::Rems(r) => r.0 * rem_basis(),
1936 }
1937}
1938
1939fn absolute_font_size_px(k: &lightningcss::properties::font::AbsoluteFontSize) -> f32 {
1940 use lightningcss::properties::font::AbsoluteFontSize as A;
1941 match k {
1942 A::XXSmall => 9.0,
1943 A::XSmall => 10.0,
1944 A::Small => 13.0,
1945 A::Medium => 16.0,
1946 A::Large => 18.0,
1947 A::XLarge => 24.0,
1948 A::XXLarge => 32.0,
1949 A::XXXLarge => 48.0,
1950 }
1951}
1952
1953fn calc_px<V>(
1956 calc: &lightningcss::values::calc::Calc<V>,
1957 leaf: &dyn Fn(&V) -> Option<f32>,
1958) -> Option<f32> {
1959 calc_term(calc, leaf).filter(|px| px.is_finite())
1960}
1961
1962fn calc_term<V>(
1963 calc: &lightningcss::values::calc::Calc<V>,
1964 leaf: &dyn Fn(&V) -> Option<f32>,
1965) -> Option<f32> {
1966 use lightningcss::values::calc::{Calc, MathFunction};
1967 match calc {
1968 Calc::Value(v) => leaf(v),
1969 Calc::Number(n) => Some(*n),
1970 Calc::Sum(a, b) => Some(calc_term(a, leaf)? + calc_term(b, leaf)?),
1971 Calc::Product(n, v) => Some(n * calc_term(v, leaf)?),
1972 Calc::Function(f) => match &**f {
1973 MathFunction::Calc(c) => calc_term(c, leaf),
1974 MathFunction::Min(list) => list
1975 .iter()
1976 .map(|c| calc_term(c, leaf))
1977 .try_fold(f32::INFINITY, |acc, v| Some(acc.min(v?))),
1978 MathFunction::Max(list) => list
1979 .iter()
1980 .map(|c| calc_term(c, leaf))
1981 .try_fold(f32::NEG_INFINITY, |acc, v| Some(acc.max(v?))),
1982 MathFunction::Clamp(lo, v, hi) => Some(
1984 calc_term(v, leaf)?
1985 .min(calc_term(hi, leaf)?)
1986 .max(calc_term(lo, leaf)?),
1987 ),
1988 MathFunction::Abs(v) => Some(calc_term(v, leaf)?.abs()),
1989 MathFunction::Sign(v) => Some(calc_term(v, leaf)?.signum()),
1990 _ => None,
1991 },
1992 }
1993}
1994
1995fn advise_list_marker(diagnostics: &mut Vec<String>) {
1996 warn_once(
1997 diagnostics,
1998 "this list marker is not generated (v1) — the PREDEFINED counter styles (`disc`, \
1999 `circle`, `square`, `decimal`, `decimal-leading-zero`, and the alpha and roman ones) do \
2000 generate a real marker box now. A `@counter-style` rule and a `list-style-image` have no \
2001 model here: the first needs a counter-style engine, the second a raster in the marker \
2002 box. Pick a predefined style, or render the marker as a real element (a `<span>`, or \
2003 `::before { content: \"…\" }`)",
2004 );
2005}
2006
2007fn spacing_px(spacing: &lightningcss::properties::text::Spacing) -> Option<f32> {
2008 use lightningcss::properties::text::Spacing;
2009 match spacing {
2010 Spacing::Normal => Some(0.0),
2011 Spacing::Length(l) => css_length_px(l),
2012 }
2013}
2014
2015fn css_length_px(l: &CssLength) -> Option<f32> {
2016 match l {
2017 CssLength::Value(v) => length_value_px(v),
2018 CssLength::Calc(c) => calc_px(c, &|v: &CssLength| css_length_px(v)),
2019 }
2020}
2021
2022fn lp_leaf_px(lp: &LengthPercentage) -> Option<f32> {
2023 match lp {
2024 DimensionPercentage::Dimension(v) => length_value_px(v),
2025 DimensionPercentage::Percentage(_) => None,
2028 DimensionPercentage::Calc(c) => calc_px(c, &lp_leaf_px),
2029 }
2030}
2031
2032fn lp_calc_px(c: &lightningcss::values::calc::Calc<LengthPercentage>) -> Option<f32> {
2035 let v = calc_px(c, &lp_leaf_px);
2036 if v.is_none() {
2037 calc_dropped();
2038 }
2039 v
2040}
2041
2042fn calc_dropped() {
2043 CALC_DROPPED.with(|c| c.set(true));
2044}
2045
2046fn calc_linear(c: &lightningcss::values::calc::Calc<LengthPercentage>) -> Option<(f32, f32)> {
2047 use lightningcss::values::calc::{Calc, MathFunction};
2048 match c {
2049 Calc::Value(v) => match &**v {
2050 DimensionPercentage::Dimension(d) => Some((0.0, length_value_px(d)?)),
2051 DimensionPercentage::Percentage(p) => Some((p.0, 0.0)),
2052 DimensionPercentage::Calc(inner) => calc_linear(inner),
2053 },
2054 Calc::Number(_) => None,
2055 Calc::Sum(a, b) => {
2056 let (fa, pa) = calc_linear(a)?;
2057 let (fb, pb) = calc_linear(b)?;
2058 Some((fa + fb, pa + pb))
2059 }
2060 Calc::Product(n, v) => {
2061 let (f, p) = calc_linear(v)?;
2062 Some((n * f, n * p))
2063 }
2064 Calc::Function(f) => match &**f {
2065 MathFunction::Calc(inner) => calc_linear(inner),
2066 _ => calc_px(c, &lp_leaf_px).map(|p| (0.0, p)),
2067 },
2068 }
2069}
2070
2071fn lp_definite(lp: &LengthPercentage) -> Option<DefiniteLength> {
2072 match lp {
2073 DimensionPercentage::Dimension(v) => length_value_px(v).map(|p| px(p).into()),
2074 DimensionPercentage::Percentage(p) => Some(relative(p.0)),
2075 DimensionPercentage::Calc(c) => match calc_px(c, &lp_leaf_px) {
2076 Some(p) => Some(px(p).into()),
2077 None => match calc_linear(c) {
2078 Some((fraction, pixels)) if fraction == 0.0 => Some(px(pixels).into()),
2079 Some((fraction, pixels)) => Some(DefiniteLength::Calc {
2080 fraction,
2081 pixels: px(pixels),
2082 }),
2083 None => {
2084 calc_dropped();
2085 None
2086 }
2087 },
2088 },
2089 }
2090}
2091
2092fn lpa_length(v: &LengthPercentageOrAuto) -> Option<Length> {
2093 match v {
2094 LengthPercentageOrAuto::Auto => Some(Length::Auto),
2095 LengthPercentageOrAuto::LengthPercentage(lp) => lp_definite(lp).map(Length::Definite),
2096 }
2097}
2098
2099fn size_length(v: &CssSize) -> Option<Length> {
2100 match v {
2101 CssSize::Auto => Some(Length::Auto),
2102 CssSize::LengthPercentage(lp) => lp_definite(lp).map(Length::Definite),
2103 _ => None,
2104 }
2105}
2106
2107fn max_size_length(v: &lightningcss::properties::size::MaxSize) -> Option<Length> {
2108 use lightningcss::properties::size::MaxSize;
2109 match v {
2110 MaxSize::None => Some(Length::Auto),
2111 MaxSize::LengthPercentage(lp) => lp_definite(lp).map(Length::Definite),
2112 _ => None,
2113 }
2114}
2115
2116fn corner(
2117 length: &mut Option<AbsoluteLength>,
2118 relative: &mut Option<Option<gpui::VnCornerRadius>>,
2119 radius: &lightningcss::values::size::Size2D<LengthPercentage>,
2120) -> bool {
2121 let (Some(x), Some(y)) = (lp_definite(&radius.0), lp_definite(&radius.1)) else {
2122 return false;
2123 };
2124 match (x, y) {
2125 (DefiniteLength::Absolute(a), DefiniteLength::Absolute(b)) if a == b => {
2126 *length = Some(a);
2127 *relative = Some(None);
2128 }
2129 (x, y) => {
2130 *length = Some(px(0.).into());
2131 *relative = Some(Some(gpui::VnCornerRadius { x, y }));
2132 }
2133 }
2134 true
2135}
2136
2137fn lp_absolute(lp: &LengthPercentage) -> Option<AbsoluteLength> {
2138 match lp {
2139 DimensionPercentage::Dimension(v) => length_value_px(v).map(|p| px(p).into()),
2140 DimensionPercentage::Calc(c) => lp_calc_px(c).map(|p| px(p).into()),
2141 DimensionPercentage::Percentage(_) => None,
2142 }
2143}
2144
2145fn gap_definite(v: &lightningcss::properties::align::GapValue) -> Option<DefiniteLength> {
2146 use lightningcss::properties::align::GapValue;
2147 match v {
2148 GapValue::LengthPercentage(lp) => lp_definite(lp),
2149 GapValue::Normal => None,
2150 }
2151}
2152
2153fn self_position(v: &SelfPosition) -> gpui::AlignItems {
2154 use gpui::AlignItems as G;
2155 match v {
2156 SelfPosition::Center => G::Center,
2157 SelfPosition::Start | SelfPosition::FlexStart | SelfPosition::SelfStart => G::FlexStart,
2158 SelfPosition::End | SelfPosition::FlexEnd | SelfPosition::SelfEnd => G::FlexEnd,
2159 }
2160}
2161
2162fn grid_template(v: &lightningcss::properties::grid::TrackSizing) -> Option<gpui::GridTemplate> {
2165 use lightningcss::properties::grid::{
2166 RepeatCount, TrackBreadth, TrackListItem, TrackSize, TrackSizing,
2167 };
2168 let TrackSizing::TrackList(list) = v else {
2169 return None;
2170 };
2171 let [TrackListItem::TrackRepeat(repeat)] = list.items.as_slice() else {
2172 return None;
2173 };
2174 let RepeatCount::Number(count) = repeat.count else {
2175 return None;
2176 };
2177 if count < 0 {
2178 return None;
2179 }
2180 let [TrackSize::MinMax { min, max }] = repeat.track_sizes.as_slice() else {
2181 return None;
2182 };
2183 if !matches!(max, TrackBreadth::Flex(f) if *f == 1.0) {
2185 return None;
2186 }
2187 let min_size = match min {
2188 TrackBreadth::Length(DimensionPercentage::Dimension(l))
2189 if length_value_px(l) == Some(0.0) =>
2190 {
2191 gpui::GridTemplateMinSize::Zero
2192 }
2193 TrackBreadth::MinContent => gpui::GridTemplateMinSize::MinContent,
2194 TrackBreadth::MaxContent => gpui::GridTemplateMinSize::MaxContent,
2195 _ => return None,
2196 };
2197 Some(gpui::GridTemplate {
2198 repeat: count as u16,
2199 min_size,
2200 })
2201}
2202
2203fn track_breadth(b: &lightningcss::properties::grid::TrackBreadth) -> Option<gpui::GridTrackSize> {
2206 use gpui::GridTrackSize as G;
2207 use lightningcss::properties::grid::TrackBreadth as B;
2208 Some(match b {
2209 B::Auto => G::Auto,
2210 B::MinContent => G::MinContent,
2211 B::MaxContent => G::MaxContent,
2212 B::Flex(f) => G::Fr(*f),
2213 B::Length(DimensionPercentage::Dimension(l)) => G::Px(length_value_px(l)?),
2214 B::Length(DimensionPercentage::Percentage(p)) => G::Percent(p.0),
2215 B::Length(DimensionPercentage::Calc(c)) => G::Px(lp_calc_px(c)?),
2216 })
2217}
2218
2219fn track_size(s: &lightningcss::properties::grid::TrackSize) -> Option<gpui::GridTrack> {
2220 use lightningcss::properties::grid::{TrackBreadth as B, TrackSize as S};
2221 match s {
2222 S::TrackBreadth(B::Flex(f)) => Some(gpui::GridTrack::fr(*f)),
2223 S::TrackBreadth(b) => Some(gpui::GridTrack::fixed(track_breadth(b)?)),
2224 S::MinMax { min, max } => Some(gpui::GridTrack {
2225 min: track_breadth(min)?,
2226 max: track_breadth(max)?,
2227 }),
2228 S::FitContent(_) => None,
2230 }
2231}
2232
2233const NO_AUTO_REPEAT: gpui::GridAutoRepeat = gpui::GridAutoRepeat {
2236 fit: false,
2237 start: 0,
2238 len: 0,
2239};
2240
2241fn grid_tracks(
2242 v: &lightningcss::properties::grid::TrackSizing,
2243) -> Option<(Vec<gpui::GridTrack>, gpui::GridAutoRepeat)> {
2244 use lightningcss::properties::grid::{RepeatCount, TrackListItem, TrackSizing};
2245 let TrackSizing::TrackList(list) = v else {
2246 return None;
2247 };
2248 let mut out: Vec<gpui::GridTrack> = Vec::new();
2249 let mut auto: Option<gpui::GridAutoRepeat> = None;
2250 for item in &list.items {
2251 match item {
2252 TrackListItem::TrackSize(s) => out.push(track_size(s)?),
2253 TrackListItem::TrackRepeat(rep) => {
2254 let one: Vec<gpui::GridTrack> = rep
2255 .track_sizes
2256 .iter()
2257 .map(track_size)
2258 .collect::<Option<_>>()?;
2259 let fit = match rep.count {
2260 RepeatCount::Number(count) => {
2261 if count < 0 || count > 1024 {
2262 return None;
2263 }
2264 for _ in 0..count {
2265 out.extend(one.iter().copied());
2266 }
2267 continue;
2268 }
2269 RepeatCount::AutoFill => false,
2270 RepeatCount::AutoFit => true,
2271 };
2272 if auto.is_some() || one.is_empty() || out.len() + one.len() > u16::MAX as usize {
2273 return None;
2274 }
2275 auto = Some(gpui::GridAutoRepeat {
2276 fit,
2277 start: out.len() as u16,
2278 len: one.len() as u16,
2279 });
2280 out.extend(one);
2281 }
2282 }
2283 }
2284 if out.is_empty() {
2285 return None;
2286 }
2287 if auto.is_some() && !out.iter().all(fixed_track) {
2288 return None;
2289 }
2290 Some((out, auto.unwrap_or(NO_AUTO_REPEAT)))
2291}
2292
2293fn fixed_track(t: &gpui::GridTrack) -> bool {
2294 use gpui::GridTrackSize as G;
2295 let fixed = |s: G| matches!(s, G::Px(_) | G::Percent(_));
2296 fixed(t.min) || (fixed(t.max) && !matches!(t.min, G::Fr(_)))
2297}
2298
2299fn grid_line(l: &lightningcss::properties::grid::GridLine<'_>) -> Option<gpui::GridPlacement> {
2301 use lightningcss::properties::grid::GridLine as L;
2302 match l {
2303 L::Auto => Some(gpui::GridPlacement::Auto),
2304 L::Line { index, name: None } => Some(gpui::GridPlacement::Line(*index as i16)),
2305 L::Span { index, name: None } if *index > 0 => {
2306 Some(gpui::GridPlacement::Span(*index as u16))
2307 }
2308 _ => None,
2309 }
2310}
2311
2312fn outline_mut(r: &mut StyleRefinement) -> &mut gpui::Outline {
2313 r.vn_outline.get_or_insert(gpui::Outline {
2314 width: px(0.0),
2315 offset: px(0.0),
2316 color: Hsla::default(),
2317 style: gpui::BorderStyle::Solid,
2318 })
2319}
2320
2321#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2322pub enum ListMarker {
2323 None,
2324 Disc,
2325 Circle,
2326 Square,
2327 Decimal,
2328 DecimalLeadingZero,
2329 LowerAlpha,
2330 UpperAlpha,
2331 LowerRoman,
2332 UpperRoman,
2333}
2334
2335impl ListMarker {
2336 pub fn render(self, n: usize) -> Option<String> {
2337 fn alpha(mut n: usize, upper: bool) -> String {
2338 let base = if upper { b'A' } else { b'a' };
2339 let mut out = Vec::new();
2340 while n > 0 {
2341 n -= 1;
2342 out.push(base + (n % 26) as u8);
2343 n /= 26;
2344 }
2345 out.reverse();
2346 String::from_utf8(out).unwrap_or_default()
2347 }
2348 fn roman(mut n: usize, upper: bool) -> String {
2349 const TABLE: [(usize, &str); 13] = [
2350 (1000, "m"),
2351 (900, "cm"),
2352 (500, "d"),
2353 (400, "cd"),
2354 (100, "c"),
2355 (90, "xc"),
2356 (50, "l"),
2357 (40, "xl"),
2358 (10, "x"),
2359 (9, "ix"),
2360 (5, "v"),
2361 (4, "iv"),
2362 (1, "i"),
2363 ];
2364 let mut out = String::new();
2365 for (value, glyph) in TABLE {
2366 while n >= value {
2367 out.push_str(glyph);
2368 n -= value;
2369 }
2370 }
2371 if upper {
2372 out.to_uppercase()
2373 } else {
2374 out
2375 }
2376 }
2377 match self {
2378 ListMarker::None => None,
2379 ListMarker::Disc => Some("\u{2022}".into()),
2380 ListMarker::Circle => Some("\u{25e6}".into()),
2381 ListMarker::Square => Some("\u{25aa}".into()),
2382 ListMarker::Decimal => Some(format!("{n}.")),
2383 ListMarker::DecimalLeadingZero => Some(format!("{n:02}.")),
2384 ListMarker::LowerAlpha => Some(format!("{}.", alpha(n, false))),
2385 ListMarker::UpperAlpha => Some(format!("{}.", alpha(n, true))),
2386 ListMarker::LowerRoman => Some(format!("{}.", roman(n, false))),
2387 ListMarker::UpperRoman => Some(format!("{}.", roman(n, true))),
2388 }
2389 }
2390}
2391
2392fn list_marker(style: &lightningcss::properties::list::ListStyleType<'_>) -> Option<ListMarker> {
2393 use lightningcss::properties::list::{
2394 CounterStyle as C, ListStyleType as T, PredefinedCounterStyle as P,
2395 };
2396 match style {
2397 T::None => Some(ListMarker::None),
2398 T::CounterStyle(C::Predefined(p)) => Some(match p {
2399 P::Disc => ListMarker::Disc,
2400 P::Circle => ListMarker::Circle,
2401 P::Square => ListMarker::Square,
2402 P::Decimal => ListMarker::Decimal,
2403 P::DecimalLeadingZero => ListMarker::DecimalLeadingZero,
2404 P::LowerAlpha | P::LowerLatin => ListMarker::LowerAlpha,
2405 P::UpperAlpha | P::UpperLatin => ListMarker::UpperAlpha,
2406 P::LowerRoman => ListMarker::LowerRoman,
2407 P::UpperRoman => ListMarker::UpperRoman,
2408 _ => return None,
2409 }),
2410 _ => None,
2411 }
2412}
2413
2414#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2415pub struct CurrentColorTargets(pub u16);
2416
2417impl CurrentColorTargets {
2418 pub const BORDER: u16 = 1 << 0;
2419 pub const OUTLINE: u16 = 1 << 1;
2420 pub const BACKGROUND: u16 = 1 << 2;
2421 pub const FILL: u16 = 1 << 3;
2422 pub const STROKE: u16 = 1 << 4;
2423 pub const DECORATION: u16 = 1 << 5;
2424 pub const BORDER_TOP: u16 = 1 << 6;
2425 pub const BORDER_RIGHT: u16 = 1 << 7;
2426 pub const BORDER_BOTTOM: u16 = 1 << 8;
2427 pub const BORDER_LEFT: u16 = 1 << 9;
2428
2429 pub fn has(self, bit: u16) -> bool {
2430 self.0 & bit != 0
2431 }
2432}
2433
2434fn cycled<T: Copy>(list: Option<&Rc<Vec<T>>>, i: usize) -> Option<T> {
2436 let list = list.filter(|l| !l.is_empty())?;
2437 Some(list[i % list.len()])
2438}
2439
2440struct Tiles<'a> {
2442 size: Option<&'a Rc<Vec<BackgroundSize>>>,
2443 position: Option<&'a Rc<Vec<(TileLength, TileLength)>>>,
2444 repeat: Option<&'a Rc<Vec<(bool, bool)>>>,
2445}
2446
2447impl Tiles<'_> {
2448 fn gradient(&self, layer: &BackgroundLayer) -> gpui::Background {
2451 let index = layer.index as usize;
2452 let mut background = layer.background;
2453 if let Some(BackgroundSize::Explicit(Some(w), Some(h))) = cycled(self.size, index) {
2454 let position = cycled(self.position, index)
2455 .unwrap_or((TileLength::Fraction(0.0), TileLength::Fraction(0.0)));
2456 let repeat = cycled(self.repeat, index).unwrap_or((true, true));
2457 background = background.tiled(
2458 (w.value(), h.value()),
2459 (w.is_fraction(), h.is_fraction()),
2460 (position.0.value(), position.1.value()),
2461 (position.0.is_fraction(), position.1.is_fraction()),
2462 repeat,
2463 );
2464 }
2465 background
2466 }
2467
2468 fn stack(
2470 &self,
2471 images: Option<&Vec<BackgroundLayer>>,
2472 urls: Option<&Vec<BackgroundUrl>>,
2473 ) -> Vec<PaintLayer> {
2474 let mut stack: Vec<(u16, PaintLayer)> = Vec::new();
2475 for layer in images.into_iter().flatten() {
2476 stack.push((layer.index, PaintLayer::Gradient(self.gradient(layer))));
2477 }
2478 for u in urls.into_iter().flatten() {
2479 let i = u.index as usize;
2480 stack.push((
2481 u.index,
2482 PaintLayer::Image {
2483 url: u.url.clone(),
2484 size: cycled(self.size, i).unwrap_or(BackgroundSize::Explicit(None, None)),
2485 position: cycled(self.position, i)
2486 .unwrap_or((TileLength::Fraction(0.0), TileLength::Fraction(0.0))),
2487 repeat: cycled(self.repeat, i).unwrap_or((true, true)),
2488 },
2489 ));
2490 }
2491 stack.sort_by_key(|(index, _)| *index);
2492 stack.into_iter().rev().map(|(_, layer)| layer).collect()
2493 }
2494}
2495
2496#[derive(Clone, Debug, PartialEq)]
2497pub struct BackgroundUrl {
2498 pub index: u16,
2499 pub url: Rc<str>,
2500}
2501
2502#[derive(Clone, Copy, Debug, PartialEq)]
2503pub enum BackgroundSize {
2504 Explicit(Option<TileLength>, Option<TileLength>),
2505 Cover,
2506 Contain,
2507}
2508
2509#[derive(Clone, Debug, PartialEq)]
2510pub enum PaintLayer {
2511 Gradient(gpui::Background),
2512 Image {
2513 url: Rc<str>,
2514 size: BackgroundSize,
2515 position: (TileLength, TileLength),
2516 repeat: (bool, bool),
2517 },
2518}
2519
2520#[derive(Clone, Copy, Debug, PartialEq)]
2521pub struct BackgroundLayer {
2522 pub index: u16,
2523 pub background: gpui::Background,
2524}
2525
2526#[derive(Clone, Copy, Debug, PartialEq)]
2527pub enum TileLength {
2528 Pixels(f32),
2529 Fraction(f32),
2530}
2531
2532impl TileLength {
2533 pub fn value(self) -> f32 {
2534 match self {
2535 TileLength::Pixels(v) | TileLength::Fraction(v) => v,
2536 }
2537 }
2538
2539 pub fn is_fraction(self) -> bool {
2540 matches!(self, TileLength::Fraction(_))
2541 }
2542
2543 fn from_length_percentage(v: &LengthPercentage) -> Option<Self> {
2544 match v {
2545 DimensionPercentage::Percentage(p) => Some(TileLength::Fraction(p.0)),
2546 DimensionPercentage::Dimension(d) => length_value_px(d).map(TileLength::Pixels),
2547 DimensionPercentage::Calc(c) => lp_calc_px(c).map(TileLength::Pixels),
2548 }
2549 }
2550}
2551
2552#[derive(Clone, Copy, Debug)]
2553struct Stop {
2554 color: Hsla,
2555 position: Option<StopPosition>,
2556}
2557
2558#[derive(Clone, Copy, Debug, PartialEq)]
2559enum StopPosition {
2560 Fraction(f32),
2561 Pixels(f32),
2562}
2563
2564fn resolve_stop_positions(stops: &mut [Stop]) {
2565 let n = stops.len();
2566 if n == 0 {
2567 return;
2568 }
2569 if stops[0].position.is_none() {
2570 stops[0].position = Some(StopPosition::Fraction(0.0));
2571 }
2572 if stops[n - 1].position.is_none() {
2573 stops[n - 1].position = Some(StopPosition::Fraction(1.0));
2574 }
2575
2576 let mut anchor = 0;
2577 for i in 1..n {
2578 if stops[i].position.is_none() {
2579 continue;
2580 }
2581 if i > anchor + 1 {
2582 let gap = (i - anchor) as f32;
2583 let ends = match (stops[anchor].position, stops[i].position) {
2584 (Some(StopPosition::Fraction(a)), Some(StopPosition::Fraction(b))) => {
2585 Some((a, b, true))
2586 }
2587 (Some(StopPosition::Pixels(a)), Some(StopPosition::Pixels(b))) => {
2588 Some((a, b, false))
2589 }
2590 _ => None,
2591 };
2592 for (step, slot) in (anchor + 1..i).enumerate() {
2593 let t = (step + 1) as f32 / gap;
2594 stops[slot].position = Some(match ends {
2595 Some((a, b, true)) => StopPosition::Fraction(a + (b - a) * t),
2596 Some((a, b, false)) => StopPosition::Pixels(a + (b - a) * t),
2597 None => StopPosition::Fraction(slot as f32 / (n - 1).max(1) as f32),
2598 });
2599 }
2600 }
2601 anchor = i;
2602 }
2603
2604 let mut floor: Option<StopPosition> = None;
2607 for stop in stops.iter_mut() {
2608 match (&mut stop.position, floor) {
2609 (Some(StopPosition::Fraction(p)), Some(StopPosition::Fraction(f))) => *p = p.max(f),
2610 (Some(StopPosition::Pixels(p)), Some(StopPosition::Pixels(f))) => *p = p.max(f),
2611 _ => {}
2612 }
2613 floor = stop.position;
2614 }
2615}
2616
2617fn hint_stop(before: Hsla, after: Hsla, position: StopPosition) -> Stop {
2618 Stop {
2619 color: mix_hsla(before, after),
2620 position: Some(position),
2621 }
2622}
2623
2624fn mix_hsla(a: Hsla, b: Hsla) -> Hsla {
2627 let mut hue_delta = b.h - a.h;
2628 if hue_delta > 0.5 {
2629 hue_delta -= 1.0;
2630 } else if hue_delta < -0.5 {
2631 hue_delta += 1.0;
2632 }
2633 Hsla {
2634 h: (a.h + hue_delta * 0.5).rem_euclid(1.0),
2635 s: (a.s + b.s) * 0.5,
2636 l: (a.l + b.l) * 0.5,
2637 a: (a.a + b.a) * 0.5,
2638 }
2639}
2640
2641fn stop_position_lp(v: &LengthPercentage) -> Option<StopPosition> {
2642 match v {
2643 DimensionPercentage::Percentage(p) => Some(StopPosition::Fraction(p.0)),
2644 DimensionPercentage::Dimension(d) => length_value_px(d).map(StopPosition::Pixels),
2645 DimensionPercentage::Calc(c) => lp_calc_px(c).map(StopPosition::Pixels),
2646 }
2647}
2648
2649fn stop_position_angle(
2650 v: &DimensionPercentage<lightningcss::values::angle::Angle>,
2651) -> Option<StopPosition> {
2652 match v {
2653 DimensionPercentage::Percentage(p) => Some(StopPosition::Fraction(p.0)),
2654 DimensionPercentage::Dimension(a) => Some(StopPosition::Fraction(a.to_degrees() / 360.0)),
2655 DimensionPercentage::Calc(_) => {
2656 calc_dropped();
2657 None
2658 }
2659 }
2660}
2661
2662fn collect_stops<P: Clone>(
2663 items: &[lightningcss::values::gradient::GradientItem<P>],
2664 position_of: &dyn Fn(&P) -> Option<StopPosition>,
2665) -> Option<Vec<Stop>> {
2666 use lightningcss::values::gradient::GradientItem;
2667
2668 let mut stops: Vec<Stop> = Vec::with_capacity(items.len());
2669 let mut pending_hints: Vec<StopPosition> = Vec::new();
2670 for item in items {
2671 match item {
2672 GradientItem::ColorStop(s) => {
2673 let color = color(&s.color)?;
2674 for hint in pending_hints.drain(..) {
2675 if let Some(before) = stops.last().map(|s: &Stop| s.color) {
2676 stops.push(hint_stop(before, color, hint));
2677 }
2678 }
2679 stops.push(Stop {
2680 color,
2681 position: s.position.as_ref().and_then(|p| position_of(p)),
2682 });
2683 }
2684 GradientItem::Hint(h) => {
2685 if let Some(p) = position_of(h) {
2686 pending_hints.push(p);
2687 }
2688 }
2689 }
2690 }
2691 if stops.is_empty() {
2692 return None;
2693 }
2694 resolve_stop_positions(&mut stops);
2695 Some(stops)
2696}
2697
2698fn gradient_center(position: &lightningcss::values::position::Position) -> ((f32, f32), bool) {
2699 use lightningcss::values::position::{
2700 HorizontalPositionKeyword as H, PositionComponent as P, VerticalPositionKeyword as V,
2701 };
2702
2703 fn component<S: Copy>(c: &P<S>, from_start: impl Fn(S) -> bool) -> (f32, bool) {
2704 let absolute = |v: &LengthPercentage| match v {
2705 DimensionPercentage::Dimension(d) => length_value_px(d),
2706 DimensionPercentage::Calc(c) => lp_calc_px(c),
2707 DimensionPercentage::Percentage(_) => None,
2708 };
2709 match c {
2710 P::Center => (0.5, false),
2711 P::Length(DimensionPercentage::Percentage(p)) => (p.0, false),
2712 P::Length(v) => absolute(v).map(|px| (px, true)).unwrap_or((0.5, false)),
2713 P::Side { side, offset } => {
2714 let near = from_start(*side);
2715 match offset {
2716 None => (if near { 0.0 } else { 1.0 }, false),
2717 Some(DimensionPercentage::Percentage(p)) => {
2718 (if near { p.0 } else { 1.0 - p.0 }, false)
2719 }
2720 Some(v) => match absolute(v) {
2723 Some(px) if near => (px, true),
2724 _ => (if near { 0.0 } else { 1.0 }, false),
2725 },
2726 }
2727 }
2728 }
2729 }
2730
2731 let (x, x_px) = component(&position.x, |s| matches!(s, H::Left));
2732 let (y, y_px) = component(&position.y, |s| matches!(s, V::Top));
2733 match (x_px, y_px) {
2734 (true, true) => ((x, y), true),
2735 (true, false) => ((0.0, y), false),
2736 (false, true) => ((x, 0.0), false),
2737 (false, false) => ((x, y), false),
2738 }
2739}
2740
2741fn with_resolved_stops(background: gpui::Background, stops: &[Stop]) -> gpui::Background {
2742 let packed: Vec<gpui::LinearColorStop> = stops
2743 .iter()
2744 .map(|s| {
2745 let value = match s.position {
2746 Some(StopPosition::Pixels(v)) | Some(StopPosition::Fraction(v)) => v,
2747 None => 0.0,
2748 };
2749 gpui::linear_color_stop(s.color, value)
2750 })
2751 .collect();
2752 let mut background = background.with_stops(&packed);
2753 for (i, stop) in stops.iter().enumerate().take(gpui::GRADIENT_STOPS) {
2754 if matches!(stop.position, Some(StopPosition::Pixels(_))) {
2755 background = background.stop_in_pixels(i);
2756 }
2757 }
2758 background
2759}
2760
2761fn band_stops(stops: &[Stop]) -> Vec<Vec<Stop>> {
2764 const REAL_PER_BAND: usize = gpui::GRADIENT_STOPS - 2;
2765 if stops.len() <= gpui::GRADIENT_STOPS {
2766 return vec![stops.to_vec()];
2767 }
2768 let transparent = |at: Option<StopPosition>| Stop {
2769 color: Hsla {
2770 h: 0.0,
2771 s: 0.0,
2772 l: 0.0,
2773 a: 0.0,
2774 },
2775 position: at,
2776 };
2777 let mut bands = Vec::new();
2778 let mut start = 0;
2779 while start + 1 < stops.len() {
2780 let end = (start + REAL_PER_BAND - 1).min(stops.len() - 1);
2781 let mut band: Vec<Stop> = Vec::with_capacity(gpui::GRADIENT_STOPS);
2782 if start > 0 {
2783 band.push(transparent(stops[start].position));
2784 }
2785 band.extend_from_slice(&stops[start..=end]);
2786 if end + 1 < stops.len() {
2787 band.push(transparent(stops[end].position));
2788 }
2789 bands.push(band);
2790 start = end;
2791 }
2792 bands
2793}
2794
2795fn mask_images<'a>(
2796 images: impl Iterator<Item = &'a lightningcss::values::image::Image<'a>>,
2797) -> MaskImages {
2798 use lightningcss::values::image::Image;
2799 let images: Vec<_> = images.collect();
2800 if images.iter().all(|i| matches!(i, Image::None)) {
2801 MaskImages::None
2802 } else if images.len() == 2 && images.iter().all(|i| opaque_mask_layer(i)) {
2803 MaskImages::TwoOpaque
2804 } else {
2805 MaskImages::Other
2806 }
2807}
2808
2809fn opaque_mask_layer(image: &lightningcss::values::image::Image<'_>) -> bool {
2810 use lightningcss::values::gradient::{Gradient, GradientItem};
2811 use lightningcss::values::image::Image;
2812 fn opaque<D>(items: &[GradientItem<D>]) -> bool {
2813 items.iter().all(|item| match item {
2814 GradientItem::ColorStop(stop) => color(&stop.color).is_some_and(|c| c.a >= 1.0),
2815 GradientItem::Hint(_) => true,
2816 })
2817 }
2818 let Image::Gradient(gradient) = image else {
2819 return false;
2820 };
2821 match gradient.as_ref() {
2822 Gradient::Linear(g) | Gradient::RepeatingLinear(g) => opaque(&g.items),
2823 Gradient::Radial(g) | Gradient::RepeatingRadial(g) => opaque(&g.items),
2824 Gradient::Conic(g) | Gradient::RepeatingConic(g) => opaque(&g.items),
2825 Gradient::WebKitGradient(_) => false,
2826 }
2827}
2828
2829fn mask_clips<'a>(
2830 clips: impl Iterator<Item = &'a lightningcss::properties::masking::MaskClip>,
2831) -> MaskClips {
2832 use lightningcss::properties::masking::{GeometryBox as B, MaskClip as C};
2833 let clips: Vec<_> = clips.collect();
2834 match clips.as_slice() {
2835 [C::GeometryBox(B::ContentBox), C::GeometryBox(B::BorderBox)] => {
2836 MaskClips::ContentThenBorder
2837 }
2838 _ => MaskClips::Other,
2839 }
2840}
2841
2842fn mask_compositing(c: lightningcss::properties::masking::MaskComposite) -> MaskCompositing {
2843 use lightningcss::properties::masking::MaskComposite as C;
2844 match c {
2845 C::Add => MaskCompositing::Add,
2846 C::Exclude => MaskCompositing::Exclude,
2847 C::Subtract | C::Intersect => MaskCompositing::Other,
2848 }
2849}
2850
2851fn webkit_mask_compositing(keyword: &str) -> MaskCompositing {
2852 match keyword.to_ascii_lowercase().as_str() {
2853 "source-over" => MaskCompositing::Add,
2854 "xor" | "destination-out" => MaskCompositing::Exclude,
2855 _ => MaskCompositing::Other,
2856 }
2857}
2858
2859fn advise_mask(x: &Extras, diagnostics: &mut Vec<String>) {
2860 let excluded = x.mask_composite == Some(MaskCompositing::Exclude)
2861 && x.mask_images
2862 .is_some_and(|images| images != MaskImages::TwoOpaque);
2863 if x.mask_composite == Some(MaskCompositing::Other) || excluded {
2864 warn_once(
2865 diagnostics,
2866 "`mask-composite` other than `add` is not applied (v1): the mask layers are added. \
2867 The one exception is the gradient-border ring (two opaque layers, the top one \
2868 clipped to `content-box`, composited with `exclude`). Combine the layers into one \
2869 image instead",
2870 );
2871 }
2872}
2873
2874fn webkit_mask(
2877 prefix: lightningcss::vendor_prefix::VendorPrefix,
2878 property: &str,
2879 ring: bool,
2880 diagnostics: &mut Vec<String>,
2881) -> bool {
2882 use lightningcss::vendor_prefix::VendorPrefix;
2883 if prefix.contains(VendorPrefix::None) || prefix.is_empty() {
2884 return false;
2885 }
2886 if !ring {
2887 warn_once(
2888 diagnostics,
2889 &format!(
2890 "`-webkit-{property}` is not supported and is ignored — use `{property}`, which \
2891 takes the same values"
2892 ),
2893 );
2894 }
2895 true
2896}
2897
2898fn collect_mask_images<'a>(
2899 images: impl Iterator<Item = &'a lightningcss::values::image::Image<'a>>,
2900 x: &mut Extras,
2901 diagnostics: &mut Vec<String>,
2902) {
2903 let mut layers: Vec<BackgroundLayer> = Vec::new();
2904 let mut urls: Vec<BackgroundUrl> = Vec::new();
2905 for (index, image) in images.enumerate() {
2906 let index = index.min(u16::MAX as usize) as u16;
2907 if let lightningcss::values::image::Image::Url(u) = image {
2908 let url = u.url.trim();
2909 if url.starts_with('#') {
2910 warn_once(
2911 diagnostics,
2912 "`mask-image: url(#…)` names an SVG `<mask>` element, which is not supported \
2913 (v1); the layer is left out. Point the URL at an image file, or write the \
2914 mask as a gradient",
2915 );
2916 } else if !url.is_empty() {
2917 urls.push(BackgroundUrl {
2918 index,
2919 url: Rc::from(url),
2920 });
2921 }
2922 continue;
2923 }
2924 if let Some((backgrounds, _)) = gradient_layer(image, diagnostics) {
2925 layers.extend(
2926 backgrounds
2927 .into_iter()
2928 .map(|background| BackgroundLayer { index, background }),
2929 );
2930 }
2931 }
2932 x.mask.images = Some(Rc::new(layers));
2933 x.mask.urls = Some(Rc::new(urls));
2934}
2935
2936fn mask_luminance<'a>(
2937 modes: impl Iterator<Item = &'a lightningcss::properties::masking::MaskMode>,
2938 diagnostics: &mut Vec<String>,
2939) -> bool {
2940 use lightningcss::properties::masking::MaskMode as M;
2941 let modes: Vec<bool> = modes.map(|m| *m == M::Luminance).collect();
2942 let luminance = modes.first().copied().unwrap_or(false);
2943 if modes.iter().any(|&m| m != luminance) {
2944 warn_once(
2945 diagnostics,
2946 "`mask-mode` differs between mask layers, which is not supported (v1): the first \
2947 layer's mode applies to all of them. Give every layer the same mode",
2948 );
2949 }
2950 luminance
2951}
2952
2953fn advise_mask_clip<'a>(
2954 clips: impl Iterator<Item = &'a lightningcss::properties::masking::MaskClip>,
2955 diagnostics: &mut Vec<String>,
2956) {
2957 use lightningcss::properties::masking::{GeometryBox as B, MaskClip as C};
2958 if clips
2959 .into_iter()
2960 .any(|c| *c != C::GeometryBox(B::BorderBox))
2961 {
2962 warn_once(
2963 diagnostics,
2964 "`mask-clip` other than `border-box` is not applied (v1): the mask is clipped at the \
2965 border box. Size and position the mask layers to fit instead",
2966 );
2967 }
2968}
2969
2970fn mask_position(
2971 position: &lightningcss::values::position::Position,
2972 diagnostics: &mut Vec<String>,
2973) -> (TileLength, TileLength) {
2974 (
2975 position_component(&position.x, true, diagnostics),
2976 position_component(&position.y, false, diagnostics),
2977 )
2978}
2979
2980fn advise_mask_box<'a>(
2981 boxes: impl Iterator<Item = &'a lightningcss::properties::masking::GeometryBox>,
2982 property: &str,
2983 diagnostics: &mut Vec<String>,
2984) {
2985 use lightningcss::properties::masking::GeometryBox as B;
2986 if boxes.into_iter().any(|b| *b != B::BorderBox) {
2987 warn_once(
2988 diagnostics,
2989 &format!(
2990 "`{property}` other than `border-box` is not applied (v1): the mask is laid out \
2991 and clipped at the border box. Size and position the mask layers to fit instead"
2992 ),
2993 );
2994 }
2995}
2996
2997fn collect_background_images<'a>(
2998 images: impl Iterator<Item = &'a lightningcss::values::image::Image<'a>>,
2999 x: &mut Extras,
3000 diagnostics: &mut Vec<String>,
3001) {
3002 let mut layers: Vec<BackgroundLayer> = Vec::new();
3003 let mut urls: Vec<BackgroundUrl> = Vec::new();
3004 for (index, image) in images.enumerate() {
3005 if let lightningcss::values::image::Image::Url(u) = image {
3006 if !u.url.trim().is_empty() {
3007 urls.push(BackgroundUrl {
3008 index: index.min(u16::MAX as usize) as u16,
3009 url: Rc::from(u.url.as_ref()),
3010 });
3011 }
3012 continue;
3013 }
3014 let Some((backgrounds, key)) = gradient_layer(image, diagnostics) else {
3015 continue;
3016 };
3017 if x.background_key_color.is_none() || index == 0 {
3018 x.background_key_color = Some(key);
3019 }
3020 for background in backgrounds {
3021 layers.push(BackgroundLayer {
3022 index: index.min(u16::MAX as usize) as u16,
3023 background,
3024 });
3025 }
3026 }
3027 x.background_images = Some(Rc::new(layers));
3028 x.background_urls = Some(Rc::new(urls));
3029}
3030
3031fn background_size(size: &lightningcss::properties::background::BackgroundSize) -> BackgroundSize {
3032 use lightningcss::properties::background::BackgroundSize as BS;
3033 match size {
3034 BS::Cover => BackgroundSize::Cover,
3035 BS::Contain => BackgroundSize::Contain,
3036 BS::Explicit { width, height } => {
3037 let axis = |v: &LengthPercentageOrAuto| match v {
3038 LengthPercentageOrAuto::Auto => None,
3039 LengthPercentageOrAuto::LengthPercentage(lp) => {
3040 TileLength::from_length_percentage(lp)
3041 }
3042 };
3043 BackgroundSize::Explicit(axis(width), axis(height))
3044 }
3045 }
3046}
3047
3048fn background_repeat(
3049 repeat: &lightningcss::properties::background::BackgroundRepeat,
3050) -> (bool, bool) {
3051 use lightningcss::properties::background::BackgroundRepeatKeyword as K;
3052 let on = |k: &K| !matches!(k, K::NoRepeat);
3055 (on(&repeat.x), on(&repeat.y))
3056}
3057
3058fn background_position(
3059 position: &lightningcss::properties::background::BackgroundPosition,
3060 diagnostics: &mut Vec<String>,
3061) -> (TileLength, TileLength) {
3062 (
3063 position_component(&position.x, true, diagnostics),
3064 position_component(&position.y, false, diagnostics),
3065 )
3066}
3067
3068fn position_component<S: Copy>(
3069 component: &lightningcss::values::position::PositionComponent<S>,
3070 horizontal: bool,
3071 diagnostics: &mut Vec<String>,
3072) -> TileLength
3073where
3074 S: PositionSide,
3075{
3076 use lightningcss::values::position::PositionComponent as P;
3077 let absolute = |v: &LengthPercentage| match v {
3078 DimensionPercentage::Dimension(d) => length_value_px(d),
3079 DimensionPercentage::Calc(c) => lp_calc_px(c),
3080 DimensionPercentage::Percentage(_) => None,
3081 };
3082 match component {
3083 P::Center => TileLength::Fraction(0.5),
3084 P::Length(DimensionPercentage::Percentage(p)) => TileLength::Fraction(p.0),
3085 P::Length(v) => absolute(v)
3086 .map(TileLength::Pixels)
3087 .unwrap_or(TileLength::Fraction(0.0)),
3088 P::Side { side, offset } => {
3089 let near = side.is_near_edge();
3090 match offset {
3091 None => TileLength::Fraction(if near { 0.0 } else { 1.0 }),
3092 Some(DimensionPercentage::Percentage(p)) => {
3093 TileLength::Fraction(if near { p.0 } else { 1.0 - p.0 })
3094 }
3095 Some(v) if near => absolute(v)
3096 .map(TileLength::Pixels)
3097 .unwrap_or(TileLength::Fraction(0.0)),
3098 Some(_) => {
3099 warn_once(
3100 diagnostics,
3101 &format!(
3102 "`background-position: {} <length>` is placed flush against that edge \
3103 (v1) — an offset from the FAR edge is a fraction of the box minus a \
3104 length, and the tile carries one number per axis. Write it from the \
3105 near edge (`left`/`top`), or as a percentage, both of which are exact",
3106 if horizontal { "right" } else { "bottom" }
3107 ),
3108 );
3109 TileLength::Fraction(1.0)
3110 }
3111 }
3112 }
3113 }
3114}
3115
3116pub(crate) trait PositionSide {
3117 fn is_near_edge(self) -> bool;
3118}
3119
3120impl PositionSide for lightningcss::values::position::HorizontalPositionKeyword {
3121 fn is_near_edge(self) -> bool {
3122 matches!(self, Self::Left)
3123 }
3124}
3125
3126impl PositionSide for lightningcss::values::position::VerticalPositionKeyword {
3127 fn is_near_edge(self) -> bool {
3128 matches!(self, Self::Top)
3129 }
3130}
3131
3132fn gradient_layer(
3133 img: &lightningcss::values::image::Image<'_>,
3134 diagnostics: &mut Vec<String>,
3135) -> Option<(Vec<gpui::Background>, Hsla)> {
3136 use lightningcss::values::gradient::{
3137 Circle, Ellipse, EndingShape, Gradient, LineDirection, ShapeExtent,
3138 };
3139 use lightningcss::values::image::Image;
3140 use lightningcss::values::position::{
3141 HorizontalPositionKeyword as H, VerticalPositionKeyword as V,
3142 };
3143
3144 let gradient = match img {
3145 Image::Gradient(g) => g.as_ref(),
3146 Image::Url(_) => return None,
3147 Image::ImageSet(_) => {
3148 warn_once(
3149 diagnostics,
3150 "background-image: image-set() is not painted (v1) — write one source as a plain \
3151 `url()`, which is; there is no resolution negotiation here",
3152 );
3153 return None;
3154 }
3155 Image::None => return None,
3156 };
3157
3158 let (background, stops) = match gradient {
3159 Gradient::Linear(l) | Gradient::RepeatingLinear(l) => {
3160 let stops = collect_stops(&l.items, &stop_position_lp)?;
3161 let angle = match &l.direction {
3162 LineDirection::Angle(a) => Some(a.to_degrees()),
3163 LineDirection::Vertical(V::Top) => Some(0.0),
3164 LineDirection::Vertical(V::Bottom) => Some(180.0),
3165 LineDirection::Horizontal(H::Right) => Some(90.0),
3166 LineDirection::Horizontal(H::Left) => Some(270.0),
3167 LineDirection::Corner { .. } => None,
3168 };
3169 let background = match angle {
3170 Some(angle) => gpui::linear_gradient_stops(angle, &[]),
3171 None => {
3172 let LineDirection::Corner {
3173 horizontal,
3174 vertical,
3175 } = &l.direction
3176 else {
3177 unreachable!("only a corner direction leaves the angle unresolved")
3178 };
3179 gpui::linear_gradient_stops(0.0, &[]).to_corner(match (horizontal, vertical) {
3180 (H::Right, V::Top) => 0,
3181 (H::Right, V::Bottom) => 1,
3182 (H::Left, V::Bottom) => 2,
3183 (H::Left, V::Top) => 3,
3184 })
3185 }
3186 };
3187 (background, stops)
3188 }
3189 Gradient::Radial(r) | Gradient::RepeatingRadial(r) => {
3190 let stops = collect_stops(&r.items, &stop_position_lp)?;
3191 let (center, center_px) = gradient_center(&r.position);
3192 let extent = |e: &ShapeExtent| match e {
3193 ShapeExtent::ClosestSide => 1u8,
3194 ShapeExtent::FarthestSide => 2,
3195 ShapeExtent::ClosestCorner => 3,
3196 ShapeExtent::FarthestCorner => 4,
3197 };
3198 let background = gpui::radial_gradient(&[]).at(center, center_px);
3199 let background = match &r.shape {
3200 EndingShape::Circle(Circle::Extent(e)) => background.with_extent(extent(e), false),
3201 EndingShape::Circle(Circle::Radius(len)) => match css_length_px(len) {
3202 Some(radius) => background.with_radii((radius, radius), true),
3203 None => background.with_extent(4, false),
3204 },
3205 EndingShape::Ellipse(Ellipse::Extent(e)) => background.with_extent(extent(e), true),
3206 EndingShape::Ellipse(Ellipse::Size { x, y }) => {
3207 let axis = |v: &LengthPercentage| match v {
3208 DimensionPercentage::Percentage(p) => Some((p.0, false)),
3209 DimensionPercentage::Dimension(d) => length_value_px(d).map(|v| (v, true)),
3210 DimensionPercentage::Calc(c) => lp_calc_px(c).map(|v| (v, true)),
3211 };
3212 match (axis(x), axis(y)) {
3213 (Some((rx, true)), Some((ry, true))) => {
3215 background.with_radii((rx, ry), true)
3216 }
3217 (Some((rx, false)), Some((ry, false))) => {
3218 background.with_radii((rx, ry), false)
3219 }
3220 _ => background.with_extent(4, true),
3221 }
3222 }
3223 };
3224 (background, stops)
3225 }
3226 Gradient::Conic(c) | Gradient::RepeatingConic(c) => {
3227 let stops = collect_stops(&c.items, &stop_position_angle)?;
3228 let (center, center_px) = gradient_center(&c.position);
3229 (
3230 gpui::conic_gradient(c.angle.to_degrees(), &[]).at(center, center_px),
3231 stops,
3232 )
3233 }
3234 Gradient::WebKitGradient(_) => {
3235 warn_once(
3236 diagnostics,
3237 "the legacy `-webkit-gradient()` is not painted (v1) — write the standard \
3238 `linear-gradient()`, which does",
3239 );
3240 return None;
3241 }
3242 };
3243
3244 let repeating = matches!(
3245 gradient,
3246 Gradient::RepeatingLinear(_) | Gradient::RepeatingRadial(_) | Gradient::RepeatingConic(_)
3247 );
3248 let background = background.repeating(repeating);
3249
3250 let key = if stops.len() == 1 {
3251 stops[0].color
3252 } else {
3253 mix_hsla(stops[0].color, stops[stops.len() - 1].color)
3254 };
3255 let layers = band_stops(&stops)
3256 .into_iter()
3257 .map(|band| with_resolved_stops(background, &band))
3258 .collect();
3259 Some((layers, key))
3260}
3261
3262pub(crate) fn once(diagnostics: &mut Vec<String>, msg: String) {
3263 if !diagnostics.iter().any(|d| *d == msg) {
3264 diagnostics.push(msg);
3265 }
3266}
3267
3268fn unsupported(diagnostics: &mut Vec<String>, what: &str) {
3269 once(diagnostics, format!("unsupported value for {what} (v1)"));
3270}
3271
3272fn warn_once(diagnostics: &mut Vec<String>, msg: &str) {
3273 once(diagnostics, msg.to_string());
3274}
3275
3276pub(crate) fn apply_current_color(
3277 r: &mut StyleRefinement,
3278 targets: CurrentColorTargets,
3279 color: Hsla,
3280) {
3281 let sides = [
3282 r.vn_border_colors.top,
3283 r.vn_border_colors.right,
3284 r.vn_border_colors.bottom,
3285 r.vn_border_colors.left,
3286 ];
3287 if sides.iter().all(|side| *side == Some(None))
3288 || (targets.has(CurrentColorTargets::BORDER)
3289 && r.border_color.is_none()
3290 && sides.iter().all(Option::is_none))
3291 {
3292 r.border_color = Some(color);
3293 }
3294 for slot in [
3297 &mut r.vn_border_colors.top,
3298 &mut r.vn_border_colors.right,
3299 &mut r.vn_border_colors.bottom,
3300 &mut r.vn_border_colors.left,
3301 ] {
3302 if *slot == Some(None) {
3303 *slot = Some(Some(color));
3304 }
3305 }
3306 if targets.has(CurrentColorTargets::OUTLINE) {
3307 if let Some(outline) = r.vn_outline.as_mut() {
3308 outline.color = color;
3309 }
3310 }
3311 if targets.has(CurrentColorTargets::BACKGROUND) {
3312 r.background = Some(gpui::Fill::Color(color.into()));
3313 }
3314}
3315
3316pub(crate) fn border_needs_current_color(r: &StyleRefinement) -> bool {
3317 [
3318 r.vn_border_colors.top,
3319 r.vn_border_colors.right,
3320 r.vn_border_colors.bottom,
3321 r.vn_border_colors.left,
3322 ]
3323 .contains(&Some(None))
3324}
3325
3326fn border_side_color(
3327 slot: &mut Option<Option<Hsla>>,
3328 bit: u16,
3329 value: &CssColor,
3330 extras: &mut Extras,
3331 diagnostics: &mut Vec<String>,
3332) {
3333 let resolved = match value {
3334 CssColor::CurrentColor => None,
3335 value => match color(value) {
3336 Some(color) => Some(color),
3337 None => {
3338 unresolved_color(diagnostics, "border-color");
3339 return;
3340 }
3341 },
3342 };
3343 *slot = Some(resolved);
3344 extras.current_color_overrides.0 |= bit | CurrentColorTargets::BORDER;
3345 extras.current_color.0 &= !(bit | CurrentColorTargets::BORDER);
3346 if matches!(value, CssColor::CurrentColor) {
3347 extras.current_color.0 |= bit;
3348 }
3349}
3350
3351fn all_border_colors(
3352 r: &mut StyleRefinement,
3353 x: &mut Extras,
3354 colors: [&CssColor; 4],
3355 diagnostics: &mut Vec<String>,
3356) {
3357 border_side_color(
3358 &mut r.vn_border_colors.top,
3359 CurrentColorTargets::BORDER_TOP,
3360 colors[0],
3361 x,
3362 diagnostics,
3363 );
3364 border_side_color(
3365 &mut r.vn_border_colors.right,
3366 CurrentColorTargets::BORDER_RIGHT,
3367 colors[1],
3368 x,
3369 diagnostics,
3370 );
3371 border_side_color(
3372 &mut r.vn_border_colors.bottom,
3373 CurrentColorTargets::BORDER_BOTTOM,
3374 colors[2],
3375 x,
3376 diagnostics,
3377 );
3378 border_side_color(
3379 &mut r.vn_border_colors.left,
3380 CurrentColorTargets::BORDER_LEFT,
3381 colors[3],
3382 x,
3383 diagnostics,
3384 );
3385 r.border_color = color(colors[0]);
3386 if colors
3387 .iter()
3388 .all(|value| matches!(value, CssColor::CurrentColor))
3389 {
3390 x.current_color.0 |= CurrentColorTargets::BORDER;
3391 }
3392}
3393
3394fn unresolved_color(diagnostics: &mut Vec<String>, what: &str) {
3395 once(
3396 diagnostics,
3397 format!(
3398 "`{what}` value does not resolve to a concrete color (v1) — `light-dark()` and \
3399 system colors (`Canvas`, `ButtonText`, …) are not computed; write the color, and \
3400 switch it with `@media (prefers-color-scheme: dark)` where it must follow the theme"
3401 ),
3402 );
3403}
3404
3405const MAX_TEXT_SHADOW_BLUR_DEVICE_PX: f32 = 2. * gpui::MAX_GLYPH_SHADOW_SIGMA;
3407
3408fn text_shadows(
3410 shadows: &[lightningcss::properties::text::TextShadow],
3411 diagnostics: &mut Vec<String>,
3412) -> Option<Vec<gpui::TextShadow>> {
3413 let mut out = Vec::with_capacity(shadows.len());
3414 for s in shadows {
3415 if css_length_px(&s.spread) != Some(0.0) {
3416 once(
3417 diagnostics,
3418 "`text-shadow` was dropped: it takes no spread distance (a fourth length), and \
3419 browsers drop the whole declaration for one. Remove the fourth length"
3420 .into(),
3421 );
3422 return None;
3423 }
3424 let (Some(x), Some(y), Some(blur)) = (
3425 css_length_px(&s.x_offset),
3426 css_length_px(&s.y_offset),
3427 css_length_px(&s.blur),
3428 ) else {
3429 once(
3430 diagnostics,
3431 "`text-shadow` was dropped: an offset or blur radius does not resolve to a length \
3432 here. Use px, em, rem or a calc() of them"
3433 .into(),
3434 );
3435 return None;
3436 };
3437 if blur < 0.0 {
3438 once(
3439 diagnostics,
3440 "`text-shadow` was dropped: a blur radius cannot be negative, and browsers drop \
3441 the declaration. Use 0 for a sharp shadow"
3442 .into(),
3443 );
3444 return None;
3445 }
3446 if blur > MAX_TEXT_SHADOW_BLUR_DEVICE_PX / 2.0 {
3447 once(
3448 diagnostics,
3449 format!(
3450 "`text-shadow` blur radius {blur}px is drawn at most {}px wide in device \
3451 pixels ({}px at 2x); a softer shadow needs `filter: drop-shadow()`",
3452 MAX_TEXT_SHADOW_BLUR_DEVICE_PX,
3453 MAX_TEXT_SHADOW_BLUR_DEVICE_PX / 2.0
3454 ),
3455 );
3456 }
3457 let color = match &s.color {
3458 CssColor::CurrentColor => None,
3459 c => match color(c) {
3460 Some(c) => Some(c),
3461 None => {
3462 unresolved_color(diagnostics, "text-shadow");
3463 continue;
3464 }
3465 },
3466 };
3467 out.push(gpui::TextShadow {
3468 color,
3469 offset: gpui::point(px(x), px(y)),
3470 blur_radius: px(blur),
3471 });
3472 }
3473 Some(out)
3474}
3475
3476pub fn text_shadow_css(shadows: &[gpui::TextShadow], current_color: Hsla) -> String {
3478 if shadows.is_empty() {
3479 return "none".into();
3480 }
3481 let rgb = |c: Hsla| {
3482 let c = gpui::Rgba::from(c);
3483 let channel = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
3484 let (r, g, b) = (channel(c.r), channel(c.g), channel(c.b));
3485 if c.a >= 1.0 {
3486 format!("rgb({r}, {g}, {b})")
3487 } else {
3488 let a = (c.a.clamp(0.0, 1.0) * 1000.0).round() / 1000.0;
3489 format!("rgba({r}, {g}, {b}, {a})")
3490 }
3491 };
3492 shadows
3493 .iter()
3494 .map(|s| {
3495 format!(
3496 "{} {}px {}px {}px",
3497 rgb(s.color.unwrap_or(current_color)),
3498 f32::from(s.offset.x),
3499 f32::from(s.offset.y),
3500 f32::from(s.blur_radius)
3501 )
3502 })
3503 .collect::<Vec<_>>()
3504 .join(", ")
3505}
3506
3507#[path = "effect.rs"]
3508pub(crate) mod effect;
3509
3510fn object_position(p: &Property, diagnostics: &mut Vec<String>) -> Option<gpui::ObjectPosition> {
3511 use lightningcss::traits::Parse;
3512 use lightningcss::values::position::{Position, PositionComponent as C};
3513 fn axis<S: PositionSide + Copy>(c: &C<S>) -> Option<(f32, f32)> {
3514 let linear = |v: &LengthPercentage| match v {
3515 DimensionPercentage::Dimension(d) => Some((0.0, length_value_px(d)?)),
3516 DimensionPercentage::Percentage(p) => Some((p.0, 0.0)),
3517 DimensionPercentage::Calc(c) => calc_linear(c),
3518 };
3519 match c {
3520 C::Center => Some((0.5, 0.0)),
3521 C::Length(v) => linear(v),
3522 C::Side { side, offset } => {
3523 let (f, px) = offset.as_ref().map_or(Some((0.0, 0.0)), linear)?;
3524 Some(if side.is_near_edge() {
3525 (f, px)
3526 } else {
3527 (1.0 - f, -px)
3528 })
3529 }
3530 }
3531 }
3532 let raw = value_text(p)?;
3533 let resolved = Position::parse_string(&raw)
3534 .ok()
3535 .and_then(|pos| Some((axis(&pos.x)?, axis(&pos.y)?)));
3536 let Some(((x_fraction, x_offset), (y_fraction, y_offset))) = resolved else {
3537 once(
3538 diagnostics,
3539 format!(
3540 "unsupported value for object-position: {raw} — expected one to four keywords, \
3541 lengths or percentages, as in `left 10px top 20%`"
3542 ),
3543 );
3544 return None;
3545 };
3546 Some(gpui::ObjectPosition {
3547 x_fraction,
3548 x_offset: px(x_offset),
3549 y_fraction,
3550 y_offset: px(y_offset),
3551 })
3552}
3553
3554fn object_fit(
3555 value: &lightningcss::properties::custom::TokenList,
3556 diagnostics: &mut Vec<String>,
3557) -> Option<ObjectFit> {
3558 match single_ident(value, "object-fit", diagnostics) {
3559 Some("fill") => Some(ObjectFit::Fill),
3560 Some("contain") => Some(ObjectFit::Contain),
3561 Some("cover") => Some(ObjectFit::Cover),
3562 Some("scale-down") => Some(ObjectFit::ScaleDown),
3563 Some("none") => Some(ObjectFit::None),
3564 other => {
3565 once(
3566 diagnostics,
3567 format!(
3568 "unsupported value for object-fit: {} — expected fill | contain | cover | \
3569 scale-down | none",
3570 other.unwrap_or("<not a keyword>")
3571 ),
3572 );
3573 None
3574 }
3575 }
3576}
3577
3578pub(crate) const WINDOW_CONTROL: &str = "--window-control";
3579
3580fn single_ident<'a>(
3581 value: &'a lightningcss::properties::custom::TokenList<'_>,
3582 what: &str,
3583 diagnostics: &mut Vec<String>,
3584) -> Option<&'a str> {
3585 use lightningcss::properties::custom::{Token, TokenOrValue};
3586 let mut idents = value.0.iter().filter_map(|t| match t {
3587 TokenOrValue::Token(Token::Ident(s)) => Some(s.as_ref()),
3588 _ => None,
3589 });
3590 let first = idents.next();
3591 if idents.next().is_some() {
3592 once(
3593 diagnostics,
3594 format!("`{what}` takes a single keyword — the declaration was dropped"),
3595 );
3596 return None;
3597 }
3598 first
3599}
3600
3601fn clip_path(v: &CssClipPath<'_>, diagnostics: &mut Vec<String>) -> Option<gpui::VnClipPath> {
3602 use gpui::{VnClipBox, VnClipPath, VnShapeRadius};
3603 use lightningcss::properties::masking::GeometryBox as G;
3604 use lightningcss::values::shape::{BasicShape, ShapeRadius};
3605 let reference = |b: &G| match b {
3606 G::MarginBox => VnClipBox::Margin,
3607 G::BorderBox | G::StrokeBox | G::ViewBox => VnClipBox::Border,
3608 G::PaddingBox => VnClipBox::Padding,
3609 G::ContentBox | G::FillBox => VnClipBox::Content,
3610 };
3611 let radius = |r: &ShapeRadius| match r {
3612 ShapeRadius::LengthPercentage(lp) => lp_definite(lp).map(VnShapeRadius::Length),
3613 ShapeRadius::ClosestSide => Some(VnShapeRadius::ClosestSide),
3614 ShapeRadius::FarthestSide => Some(VnShapeRadius::FarthestSide),
3615 };
3616 let unsupported = |diagnostics: &mut Vec<String>, what: &str| {
3617 clip_path_unsupported(diagnostics, what);
3618 None
3619 };
3620 match v {
3621 CssClipPath::None => Some(VnClipPath::None),
3622 CssClipPath::Box(b) => Some(VnClipPath::Box(reference(b))),
3623 CssClipPath::Url(_) => unsupported(diagnostics, "url()"),
3624 CssClipPath::Shape {
3625 shape,
3626 reference_box,
3627 } => {
3628 let reference = reference(reference_box);
3629 match &**shape {
3630 BasicShape::Inset(inset) => {
3631 let r = &inset.rect;
3632 let insets = [
3633 lp_definite(&r.0)?,
3634 lp_definite(&r.1)?,
3635 lp_definite(&r.2)?,
3636 lp_definite(&r.3)?,
3637 ];
3638 let corner = |c: &lightningcss::values::size::Size2D<LengthPercentage>| {
3639 Some(gpui::VnCornerRadius {
3640 x: lp_definite(&c.0)?,
3641 y: lp_definite(&c.1)?,
3642 })
3643 };
3644 let b = &inset.radius;
3645 let radii = [
3646 corner(&b.top_left)?,
3647 corner(&b.top_right)?,
3648 corner(&b.bottom_right)?,
3649 corner(&b.bottom_left)?,
3650 ];
3651 Some(VnClipPath::Inset {
3652 reference,
3653 insets,
3654 radii,
3655 })
3656 }
3657 BasicShape::Circle(c) => {
3658 let r = radius(&c.radius)?;
3659 let center = shape_center(&c.position)?;
3660 Some(VnClipPath::Ellipse {
3661 reference,
3662 center,
3663 radius: [r, r],
3664 circle: true,
3665 })
3666 }
3667 BasicShape::Ellipse(e) => {
3668 let (rx, ry) = (radius(&e.radius_x)?, radius(&e.radius_y)?);
3669 let center = shape_center(&e.position)?;
3670 Some(VnClipPath::Ellipse {
3671 reference,
3672 center,
3673 radius: [rx, ry],
3674 circle: false,
3675 })
3676 }
3677 BasicShape::Polygon(polygon) => match clip_path_polygon(polygon) {
3678 Some(points) => Some(VnClipPath::Polygon {
3679 reference,
3680 fill_rule: fill_rule(polygon.fill_rule),
3681 points: points.into(),
3682 }),
3683 None => unsupported(
3684 diagnostics,
3685 "polygon() with a vertex that is no length or percentage",
3686 ),
3687 },
3688 }
3689 }
3690 }
3691}
3692
3693fn clip_path_unsupported(diagnostics: &mut Vec<String>, what: &str) {
3694 warn_once(
3695 diagnostics,
3696 &format!(
3697 "`clip-path: {what}` is not applied (v1) and the element paints unclipped — \
3698 `inset()`, `circle()`, `ellipse()`, `polygon()`, `path()` and a box \
3699 (`padding-box`…) are honoured"
3700 ),
3701 );
3702}
3703
3704fn fill_rule(rule: lightningcss::values::shape::FillRule) -> gpui::VnFillRule {
3705 match rule {
3706 lightningcss::values::shape::FillRule::Nonzero => gpui::VnFillRule::NonZero,
3707 lightningcss::values::shape::FillRule::Evenodd => gpui::VnFillRule::EvenOdd,
3708 }
3709}
3710
3711fn clip_path_polygon(
3712 polygon: &lightningcss::values::shape::Polygon,
3713) -> Option<Vec<[DefiniteLength; 2]>> {
3714 use lightningcss::traits::{Parse, ToCss};
3715 polygon
3716 .points
3717 .iter()
3718 .map(|point| {
3719 let text = point
3720 .to_css_string(lightningcss::stylesheet::PrinterOptions::default())
3721 .ok()?;
3722 let mut depth = 0i32;
3723 let split = text.char_indices().find_map(|(i, c)| {
3724 match c {
3725 '(' => depth += 1,
3726 ')' => depth -= 1,
3727 ' ' if depth == 0 => return Some(i),
3728 _ => {}
3729 }
3730 None
3731 })?;
3732 let x = LengthPercentage::parse_string(text[..split].trim()).ok()?;
3733 let y = LengthPercentage::parse_string(text[split..].trim()).ok()?;
3734 Some([lp_definite(&x)?, lp_definite(&y)?])
3735 })
3736 .collect()
3737}
3738
3739fn clip_path_path(
3740 tokens: &lightningcss::properties::custom::TokenList<'_>,
3741) -> Option<Result<gpui::VnClipPath, String>> {
3742 use gpui::{VnClipBox, VnFillRule};
3743 use lightningcss::properties::custom::{Token, TokenOrValue};
3744 let mut path = None;
3745 let mut reference = None;
3746 for t in &tokens.0 {
3747 match t {
3748 TokenOrValue::Function(f)
3749 if f.name.0.as_ref().eq_ignore_ascii_case("path") && path.is_none() =>
3750 {
3751 path = Some(&f.arguments);
3752 }
3753 TokenOrValue::Token(Token::Ident(id)) if path.is_some() && reference.is_none() => {
3754 reference = Some(match id.as_ref().to_ascii_lowercase().as_str() {
3755 "margin-box" => VnClipBox::Margin,
3756 "border-box" | "stroke-box" | "view-box" => VnClipBox::Border,
3757 "padding-box" => VnClipBox::Padding,
3758 "content-box" | "fill-box" => VnClipBox::Content,
3759 other => return Some(Err(format!("`{other}` is no <geometry-box>"))),
3760 });
3761 }
3762 TokenOrValue::Token(Token::WhiteSpace(_)) => {}
3763 _ if path.is_none() => return None,
3764 _ => return Some(Err("unexpected text after `path()`".into())),
3765 }
3766 }
3767 let arguments = path?;
3768 let mut fill_rule = None;
3769 let mut data = None;
3770 let mut comma = false;
3771 for t in &arguments.0 {
3772 match t {
3773 TokenOrValue::Token(Token::WhiteSpace(_)) => {}
3774 TokenOrValue::Token(Token::Ident(id)) if fill_rule.is_none() && data.is_none() => {
3775 fill_rule = Some(match id.as_ref().to_ascii_lowercase().as_str() {
3776 "nonzero" => VnFillRule::NonZero,
3777 "evenodd" => VnFillRule::EvenOdd,
3778 other => return Some(Err(format!("`{other}` is no <fill-rule>"))),
3779 });
3780 }
3781 TokenOrValue::Token(Token::Comma) if fill_rule.is_some() && !comma => comma = true,
3782 TokenOrValue::Token(Token::String(d))
3783 if data.is_none() && (fill_rule.is_none() || comma) =>
3784 {
3785 data = Some(d.as_ref().to_string());
3786 }
3787 _ => {
3788 return Some(Err(
3789 "`path()` takes an optional fill rule, a comma and a string".into(),
3790 ))
3791 }
3792 }
3793 }
3794 let Some(data) = data else {
3795 return Some(Err("`path()` has no path string".into()));
3796 };
3797 Some(
3798 crate::path_data::parse(&data).map(|verbs| gpui::VnClipPath::Path {
3799 reference: reference.unwrap_or_default(),
3800 fill_rule: fill_rule.unwrap_or_default(),
3801 verbs: verbs.into(),
3802 }),
3803 )
3804}
3805
3806fn shape_center(
3807 position: &lightningcss::values::position::Position,
3808) -> Option<[DefiniteLength; 2]> {
3809 use lightningcss::values::position::PositionComponent as P;
3810 fn component<S: PositionSide + Copy>(c: &P<S>) -> Option<DefiniteLength> {
3811 match c {
3812 P::Center => Some(relative(0.5)),
3813 P::Length(lp) => lp_definite(lp),
3814 P::Side { side, offset } => {
3815 let near = side.is_near_edge();
3816 let Some(offset) = offset else {
3817 return Some(relative(if near { 0.0 } else { 1.0 }));
3818 };
3819 let offset = lp_definite(offset)?;
3820 if near {
3821 return Some(offset);
3822 }
3823 match offset {
3824 DefiniteLength::Fraction(f) => Some(relative(1.0 - f)),
3825 DefiniteLength::Absolute(AbsoluteLength::Pixels(p)) => {
3826 Some(DefiniteLength::Calc {
3827 fraction: 1.0,
3828 pixels: -p,
3829 })
3830 }
3831 DefiniteLength::Calc { fraction, pixels } => Some(DefiniteLength::Calc {
3832 fraction: 1.0 - fraction,
3833 pixels: -pixels,
3834 }),
3835 DefiniteLength::Absolute(AbsoluteLength::Rems(_)) => None,
3836 }
3837 }
3838 }
3839 }
3840 Some([component(&position.x)?, component(&position.y)?])
3841}
3842
3843fn clip_rect_is_empty(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
3844 use lightningcss::properties::custom::{Token, TokenOrValue};
3845
3846 fn scan(
3847 tokens: &[lightningcss::properties::custom::TokenOrValue<'_>],
3848 saw_rect: &mut bool,
3849 numbers: &mut Vec<f32>,
3850 ) {
3851 for t in tokens {
3852 match t {
3853 TokenOrValue::Function(f) => {
3856 if f.name.0.as_ref() == "rect" {
3857 *saw_rect = true;
3858 }
3859 scan(&f.arguments.0, saw_rect, numbers);
3860 }
3861 TokenOrValue::Token(Token::Function(name)) if name.as_ref() == "rect" => {
3862 *saw_rect = true
3863 }
3864 TokenOrValue::Token(Token::Number { value, .. }) => numbers.push(*value),
3865 TokenOrValue::Length(l) => numbers.push(length_value_px(l).unwrap_or(f32::NAN)),
3866 TokenOrValue::Token(Token::Dimension { value, .. }) => numbers.push(*value),
3867 _ => {}
3868 }
3869 }
3870 }
3871
3872 let mut saw_rect = false;
3873 let mut numbers: Vec<f32> = Vec::new();
3874 scan(&value.0, &mut saw_rect, &mut numbers);
3875 saw_rect
3876 && numbers.len() == 4
3877 && ((numbers[0] - numbers[2]).abs() < f32::EPSILON
3878 || (numbers[3] - numbers[1]).abs() < f32::EPSILON)
3879}
3880
3881fn is_css_wide_keyword(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
3882 single_ident_raw(value).is_some_and(|v| {
3883 matches!(
3884 v.to_ascii_lowercase().as_str(),
3885 "inherit" | "initial" | "unset" | "revert" | "revert-layer"
3886 )
3887 })
3888}
3889
3890fn single_ident_is(
3891 value: &lightningcss::properties::custom::TokenList<'_>,
3892 expected: &str,
3893) -> bool {
3894 single_ident_raw(value).is_some_and(|v| v.eq_ignore_ascii_case(expected))
3895}
3896
3897fn font_features(
3898 value: &lightningcss::properties::custom::TokenList<'_>,
3899 property: &str,
3900) -> Option<gpui::FontFeatures> {
3901 use lightningcss::properties::custom::{Token, TokenOrValue};
3902 if is_css_wide_keyword(value) {
3903 return Some(gpui::FontFeatures::default());
3904 }
3905 let mut pairs: Vec<(String, u32)> = Vec::new();
3906 if property == "font-variant-numeric" {
3907 for t in value.0.iter() {
3908 let TokenOrValue::Token(Token::Ident(name)) = t else {
3909 continue;
3910 };
3911 let tag = match name.as_ref() {
3912 "normal" => continue,
3913 "lining-nums" => "lnum",
3914 "oldstyle-nums" => "onum",
3915 "proportional-nums" => "pnum",
3916 "tabular-nums" => "tnum",
3917 "diagonal-fractions" => "frac",
3918 "stacked-fractions" => "afrc",
3919 "ordinal" => "ordn",
3920 "slashed-zero" => "zero",
3921 _ => return None,
3922 };
3923 pairs.push((tag.to_string(), 1));
3924 }
3925 return Some(gpui::FontFeatures(std::sync::Arc::new(pairs)));
3926 }
3927 if property == "font-kerning" {
3928 return match single_ident_raw(value)?.to_ascii_lowercase().as_str() {
3929 "auto" | "normal" => Some(gpui::FontFeatures::default()),
3930 "none" => Some(gpui::FontFeatures(std::sync::Arc::new(vec![(
3931 "kern".into(),
3932 0,
3933 )]))),
3934 _ => None,
3935 };
3936 }
3937 if property == "font-variant-ligatures" {
3938 for t in value.0.iter() {
3939 let TokenOrValue::Token(Token::Ident(name)) = t else {
3940 continue;
3941 };
3942 let set: &[(&str, u32)] = match name.as_ref() {
3943 "normal" => continue,
3944 "none" => &[
3945 ("liga", 0),
3946 ("clig", 0),
3947 ("dlig", 0),
3948 ("hlig", 0),
3949 ("calt", 0),
3950 ],
3951 "common-ligatures" => &[("liga", 1), ("clig", 1)],
3952 "no-common-ligatures" => &[("liga", 0), ("clig", 0)],
3953 "discretionary-ligatures" => &[("dlig", 1)],
3954 "no-discretionary-ligatures" => &[("dlig", 0)],
3955 "historical-ligatures" => &[("hlig", 1)],
3956 "no-historical-ligatures" => &[("hlig", 0)],
3957 "contextual" => &[("calt", 1)],
3958 "no-contextual" => &[("calt", 0)],
3959 _ => return None,
3960 };
3961 pairs.extend(set.iter().map(|(tag, v)| (tag.to_string(), *v)));
3962 }
3963 return Some(gpui::FontFeatures(std::sync::Arc::new(pairs)));
3964 }
3965
3966 let mut pending: Option<String> = None;
3967 for t in value.0.iter() {
3968 match t {
3969 TokenOrValue::Token(Token::WhiteSpace(_)) | TokenOrValue::Token(Token::Comma) => {}
3970 TokenOrValue::Token(Token::String(tag)) => {
3971 if let Some(previous) = pending.take() {
3972 pairs.push((previous, 1));
3973 }
3974 if tag.len() != 4 {
3975 return None;
3976 }
3977 pending = Some(tag.to_string());
3978 }
3979 TokenOrValue::Token(Token::Number { value, .. }) => {
3980 pairs.push((pending.take()?, *value as u32));
3981 }
3982 TokenOrValue::Token(Token::Ident(word)) => match word.as_ref() {
3983 "on" => pairs.push((pending.take()?, 1)),
3984 "off" => pairs.push((pending.take()?, 0)),
3985 "normal" => {}
3986 _ => return None,
3987 },
3988 _ => return None,
3989 }
3990 }
3991 if let Some(previous) = pending {
3992 pairs.push((previous, 1));
3993 }
3994 Some(gpui::FontFeatures(std::sync::Arc::new(pairs)))
3995}
3996
3997fn single_length_px(value: &lightningcss::properties::custom::TokenList<'_>) -> Option<f32> {
3998 use lightningcss::properties::custom::{Token, TokenOrValue};
3999 let mut found = None;
4000 for t in value.0.iter() {
4001 match t {
4002 TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4003 TokenOrValue::Length(l) => {
4004 if found.is_some() {
4005 return None;
4006 }
4007 found = length_value_px(l);
4008 }
4009 TokenOrValue::Token(Token::Dimension { value, unit, .. }) => {
4010 if found.is_some() {
4011 return None;
4012 }
4013 found = match unit.as_ref() {
4014 "px" => Some(*value),
4015 other => match font_unit_px(other, *value)
4016 .or_else(|| viewport_unit_px(other, *value))
4017 {
4018 Some(px) => Some(px),
4019 None => return None,
4020 },
4021 };
4022 }
4023 TokenOrValue::Token(Token::Number { value, .. }) if *value == 0.0 => {
4024 if found.is_some() {
4025 return None;
4026 }
4027 found = Some(0.0);
4028 }
4029 _ => return None,
4030 }
4031 }
4032 found
4033}
4034
4035fn has_substitution(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4036 use lightningcss::properties::custom::{TokenOrValue, UnresolvedColor};
4037 value.0.iter().any(|token| match token {
4038 TokenOrValue::Var(_) | TokenOrValue::Env(_) => true,
4039 TokenOrValue::Function(function) => has_substitution(&function.arguments),
4040 TokenOrValue::UnresolvedColor(
4041 UnresolvedColor::RGB { alpha, .. } | UnresolvedColor::HSL { alpha, .. },
4042 ) => has_substitution(alpha),
4043 TokenOrValue::UnresolvedColor(UnresolvedColor::LightDark { light, dark }) => {
4044 has_substitution(light) || has_substitution(dark)
4045 }
4046 _ => false,
4047 })
4048}
4049
4050fn has_current_color_function(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4053 use lightningcss::properties::custom::{Token, TokenOrValue};
4054 fn mentions(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4055 value.0.iter().any(|token| match token {
4056 TokenOrValue::Token(Token::Ident(id)) => id.eq_ignore_ascii_case("currentcolor"),
4057 TokenOrValue::Color(lightningcss::values::color::CssColor::CurrentColor) => true,
4058 TokenOrValue::Function(f) => mentions(&f.arguments),
4059 _ => false,
4060 })
4061 }
4062 value.0.iter().any(|token| match token {
4063 TokenOrValue::Function(f) => mentions(&f.arguments),
4064 _ => false,
4065 })
4066}
4067
4068enum ContentValue {
4069 Text(Rc<str>),
4070 None,
4071 Unsupported(String),
4072}
4073
4074fn content_string(value: &lightningcss::properties::custom::TokenList<'_>) -> ContentValue {
4075 use lightningcss::properties::custom::{Token, TokenOrValue};
4076 let mut out = String::new();
4077 let mut saw_string = false;
4078 for t in value.0.iter() {
4079 match t {
4080 TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4081 TokenOrValue::Token(Token::String(sv)) => {
4082 out.push_str(sv.as_ref());
4083 saw_string = true;
4084 }
4085 TokenOrValue::Token(Token::Ident(id)) if matches!(id.as_ref(), "none" | "normal") => {
4086 return ContentValue::None;
4087 }
4088 TokenOrValue::Token(Token::Function(f)) => {
4089 return ContentValue::Unsupported(format!("{}()", f.as_ref()));
4090 }
4091 TokenOrValue::Url(_) => return ContentValue::Unsupported("url()".into()),
4092 TokenOrValue::Token(Token::Ident(id)) => {
4093 return ContentValue::Unsupported(id.as_ref().to_string());
4094 }
4095 TokenOrValue::Var(_) => return ContentValue::Unsupported("var()".into()),
4096 _ => return ContentValue::Unsupported("that value".into()),
4097 }
4098 }
4099 if saw_string {
4100 ContentValue::Text(Rc::from(out.as_str()))
4101 } else {
4102 ContentValue::None
4103 }
4104}
4105
4106fn single_ident_raw<'a>(
4107 value: &'a lightningcss::properties::custom::TokenList<'_>,
4108) -> Option<&'a str> {
4109 use lightningcss::properties::custom::{Token, TokenOrValue};
4110 let mut found = None;
4111 for t in value.0.iter() {
4112 match t {
4113 TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4114 TokenOrValue::Token(Token::Ident(id)) => {
4115 if found.is_some() {
4116 return None;
4117 }
4118 found = Some(id.as_ref());
4119 }
4120 _ => return None,
4121 }
4122 }
4123 found
4124}
4125
4126fn single_number(value: &lightningcss::properties::custom::TokenList<'_>) -> Option<f32> {
4127 use lightningcss::properties::custom::{Token, TokenOrValue};
4128 let mut found = None;
4129 for t in value.0.iter() {
4130 match t {
4131 TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4132 TokenOrValue::Token(Token::Number { value, .. }) => {
4133 if found.is_some() {
4134 return None;
4135 }
4136 found = Some(*value);
4137 }
4138 _ => return None,
4139 }
4140 }
4141 found
4142}
4143
4144fn window_drag(
4145 property: &str,
4146 value: &lightningcss::properties::custom::TokenList,
4147 diagnostics: &mut Vec<String>,
4148) -> Option<WindowDrag> {
4149 match single_ident(value, property, diagnostics) {
4150 Some("move") | Some("drag") => Some(WindowDrag::Move),
4151 Some("none") | Some("no-drag") => Some(WindowDrag::None),
4152 other => {
4153 once(
4154 diagnostics,
4155 format!(
4156 "unsupported value for `{property}`: {} — expected `move` | `none` \
4157 (or the legacy `drag` | `no-drag`)",
4158 other.unwrap_or("<not a keyword>")
4159 ),
4160 );
4161 None
4162 }
4163 }
4164}
4165
4166fn scrollbar_width(
4167 value: &lightningcss::properties::custom::TokenList,
4168 diagnostics: &mut Vec<String>,
4169) -> Option<ScrollbarWidth> {
4170 match single_ident(value, "scrollbar-width", diagnostics) {
4171 Some("auto") => Some(ScrollbarWidth::Auto),
4172 Some("thin") => Some(ScrollbarWidth::Thin),
4173 Some("none") => Some(ScrollbarWidth::None),
4174 other => {
4175 once(
4176 diagnostics,
4177 format!(
4178 "unsupported value for `scrollbar-width`: {} — expected `auto` | `thin` | `none`",
4179 other.unwrap_or("<not a keyword>")
4180 ),
4181 );
4182 None
4183 }
4184 }
4185}
4186
4187fn named_color(ident: &str) -> Option<Hsla> {
4190 match Property::parse_string(PropertyId::from("color"), ident, ParserOptions::default()) {
4191 Ok(Property::Color(c)) => color(&c),
4192 _ => None,
4193 }
4194}
4195
4196fn scrollbar_color(
4197 value: &lightningcss::properties::custom::TokenList,
4198 diagnostics: &mut Vec<String>,
4199) -> Option<(Hsla, Hsla)> {
4200 use lightningcss::properties::custom::{
4201 CustomProperty, CustomPropertyName, Token, TokenOrValue,
4202 };
4203 let tokens: Vec<_> = value
4204 .0
4205 .iter()
4206 .filter(|token| !token.is_whitespace())
4207 .collect();
4208 if matches!(tokens.as_slice(), [TokenOrValue::Token(Token::Ident(id))] if id.as_ref().eq_ignore_ascii_case("auto"))
4209 {
4210 return None;
4211 }
4212 let property = Property::Custom(CustomProperty {
4213 name: CustomPropertyName::Unknown(lightningcss::values::ident::Ident(
4214 "scrollbar-color".into(),
4215 )),
4216 value: value.clone(),
4217 });
4218 if tokens.len() == 2 {
4219 if let Some(raw) = value_text(&property) {
4220 if let Ok(Property::BorderColor(pair)) = Property::parse_string(
4221 PropertyId::from("border-color"),
4222 &raw,
4223 ParserOptions::default(),
4224 ) {
4225 if let (Some(thumb), Some(track)) = (color(&pair.top), color(&pair.right)) {
4226 return Some((thumb, track));
4227 }
4228 }
4229 }
4230 }
4231 once(
4232 diagnostics,
4233 "`scrollbar-color` requires auto or two valid colours (thumb then track)".to_string(),
4234 );
4235 None
4236}
4237
4238fn contain(
4241 value: &lightningcss::properties::custom::TokenList,
4242 diagnostics: &mut Vec<String>,
4243) -> Option<(bool, u8)> {
4244 use lightningcss::properties::custom::{Token, TokenOrValue};
4245 let (mut paint, mut size) = (false, 0);
4246 for token in value.0.iter().filter(|t| !t.is_whitespace()) {
4247 let TokenOrValue::Token(Token::Ident(id)) = token else {
4248 unsupported(diagnostics, "contain");
4249 return None;
4250 };
4251 match id.to_ascii_lowercase().as_str() {
4252 "none" | "layout" | "style" => {}
4253 "paint" | "content" => paint = true,
4254 "strict" => (paint, size) = (true, Extras::CONTAIN_WIDTH | Extras::CONTAIN_HEIGHT),
4255 "size" => size = Extras::CONTAIN_WIDTH | Extras::CONTAIN_HEIGHT,
4256 "inline-size" => size |= Extras::CONTAIN_WIDTH,
4257 _ => {
4258 unsupported(diagnostics, "contain");
4259 return None;
4260 }
4261 }
4262 }
4263 Some((paint, size))
4264}
4265
4266pub(crate) fn advise_contain_size(r: &StyleRefinement, x: &Extras, diagnostics: &mut Vec<String>) {
4269 let axes = x.contain_size.unwrap_or(0);
4270 let auto = |l: Option<Length>| matches!(l, None | Some(Length::Auto));
4271 if (axes & Extras::CONTAIN_WIDTH != 0 && auto(r.size.width))
4272 || (axes & Extras::CONTAIN_HEIGHT != 0 && auto(r.size.height))
4273 {
4274 warn_once(
4275 diagnostics,
4276 "`contain: size` (or `strict`, `inline-size`) does not size the box as if it were \
4277 empty (v1) — an axis without a width or height is still sized by the content; give \
4278 the box an explicit size on that axis",
4279 );
4280 }
4281}
4282
4283fn overscroll(
4284 property: &str,
4285 value: &lightningcss::properties::custom::TokenList,
4286 diagnostics: &mut Vec<String>,
4287) -> Option<OverscrollBehavior> {
4288 match single_ident(value, property, diagnostics) {
4289 Some("auto") => Some(OverscrollBehavior::Auto),
4290 Some("contain") => Some(OverscrollBehavior::Contain),
4291 Some("none") => Some(OverscrollBehavior::None),
4292 other => {
4293 once(
4294 diagnostics,
4295 format!(
4296 "unsupported value for `{property}`: {} — expected `auto` | `contain` | `none`",
4297 other.unwrap_or("<not a keyword>")
4298 ),
4299 );
4300 None
4301 }
4302 }
4303}
4304
4305fn window_control(
4306 value: &lightningcss::properties::custom::TokenList,
4307 diagnostics: &mut Vec<String>,
4308) -> Option<WindowControl> {
4309 match single_ident(value, WINDOW_CONTROL, diagnostics) {
4310 Some("minimize") => Some(WindowControl::Minimize),
4311 Some("maximize") => Some(WindowControl::Maximize),
4312 Some("close") => Some(WindowControl::Close),
4313 Some("none") => Some(WindowControl::None),
4314 other => {
4315 once(
4316 diagnostics,
4317 format!(
4318 "unsupported value for `{WINDOW_CONTROL}`: {} — expected \
4319 `minimize` | `maximize` | `close` | `none`",
4320 other.unwrap_or("<not a keyword>")
4321 ),
4322 );
4323 None
4324 }
4325 }
4326}
4327
4328fn apply(p: &Property, r: &mut StyleRefinement, x: &mut Extras, diagnostics: &mut Vec<String>) {
4329 CALC_DROPPED.with(|c| c.set(false));
4330 apply_property(p, r, x, diagnostics);
4331 if CALC_DROPPED.with(|c| c.replace(false)) {
4332 once(
4333 diagnostics,
4334 format!(
4335 "`{}`: this calc() is dropped (v1) — a calc() that mixes a percentage with a \
4336 length is resolved at layout only by the sizing properties (width/height and \
4337 their min/max, inset, margin, padding, gap, flex-basis) and at paint by \
4338 border-radius, and only in its linear form (sums and scalings; min()/max()/clamp() over a percentage are \
4339 not). Here the declaration is ignored, as if it were invalid. Write the \
4340 length or the percentage alone, or move the offset into a sizing property",
4341 p.property_id().name()
4342 ),
4343 );
4344 }
4345}
4346
4347fn apply_property(
4348 p: &Property,
4349 r: &mut StyleRefinement,
4350 x: &mut Extras,
4351 diagnostics: &mut Vec<String>,
4352) {
4353 use Property::*;
4354 match p {
4355 Display(d) => {
4356 use lightningcss::properties::display::{Display as D, DisplayOutside};
4357 x.inline_level = Some(matches!(
4361 d,
4362 D::Pair(p) if matches!(p.outside, DisplayOutside::Inline)
4363 ));
4364 r.display = Some(match d {
4365 D::Keyword(DisplayKeyword::None) => gpui::Display::None,
4366 D::Pair(pair) => match pair.inside {
4367 DisplayInside::Flex(_) => gpui::Display::Flex,
4368 DisplayInside::Grid => gpui::Display::Grid,
4369 _ => gpui::Display::Block,
4370 },
4371 _ => gpui::Display::Block,
4372 });
4373 }
4374 FlexDirection(d, _) => {
4375 r.flex_direction = Some(match d {
4376 CssFlexDirection::Row => gpui::FlexDirection::Row,
4377 CssFlexDirection::RowReverse => gpui::FlexDirection::RowReverse,
4378 CssFlexDirection::Column => gpui::FlexDirection::Column,
4379 CssFlexDirection::ColumnReverse => gpui::FlexDirection::ColumnReverse,
4380 });
4381 }
4382 FlexGrow(v, _) => r.flex_grow = Some(*v),
4383 FlexShrink(v, _) => r.flex_shrink = Some(*v),
4384 Order(v, _) => r.vn_order = Some(*v),
4385 FlexBasis(v, _) => r.flex_basis = lpa_length(v),
4386 Flex(v, _) => {
4387 r.flex_grow = Some(v.grow);
4388 r.flex_shrink = Some(v.shrink);
4389 r.flex_basis = lpa_length(&v.basis);
4390 }
4391 FlexWrap(v, _) => {
4392 use lightningcss::properties::flex::FlexWrap as W;
4393 r.flex_wrap = Some(match v {
4394 W::NoWrap => gpui::FlexWrap::NoWrap,
4395 W::Wrap => gpui::FlexWrap::Wrap,
4396 W::WrapReverse => gpui::FlexWrap::WrapReverse,
4397 });
4398 }
4399 AlignItems(v, _) => {
4400 use gpui::AlignItems as G;
4401 let mapped = match v {
4402 lightningcss::properties::align::AlignItems::Stretch => Some(G::Stretch),
4403 lightningcss::properties::align::AlignItems::SelfPosition { value, .. } => {
4404 Some(self_position(value))
4405 }
4406 lightningcss::properties::align::AlignItems::BaselinePosition(_) => {
4407 Some(G::Baseline)
4408 }
4409 _ => None,
4410 };
4411 match mapped {
4412 Some(m) => r.align_items = Some(m),
4413 None => unsupported(diagnostics, "align-items"),
4414 }
4415 }
4416 AlignSelf(v, _) => {
4417 use lightningcss::properties::align::AlignSelf as A;
4418 let mapped = match v {
4419 A::Auto => None,
4423 A::Stretch => Some(gpui::AlignItems::Stretch),
4424 A::BaselinePosition(_) => Some(gpui::AlignItems::Baseline),
4425 A::SelfPosition { value, .. } => Some(self_position(value)),
4426 A::Normal => None,
4427 };
4428 match mapped {
4429 Some(m) => r.align_self = Some(m),
4430 None => unsupported(
4434 diagnostics,
4435 "align-self: auto/normal — cannot undo an earlier align-self",
4436 ),
4437 }
4438 }
4439 AlignContent(v, _) => {
4440 use gpui::AlignContent as G;
4441 use lightningcss::properties::align::AlignContent as A;
4442 let mapped = match v {
4443 A::ContentDistribution(d) => {
4444 use lightningcss::properties::align::ContentDistribution as CD;
4445 Some(match d {
4446 CD::SpaceBetween => G::SpaceBetween,
4447 CD::SpaceAround => G::SpaceAround,
4448 CD::SpaceEvenly => G::SpaceEvenly,
4449 CD::Stretch => G::Stretch,
4450 })
4451 }
4452 A::ContentPosition { value, .. } => Some(match value {
4453 ContentPosition::Center => G::Center,
4454 ContentPosition::Start | ContentPosition::FlexStart => G::FlexStart,
4455 ContentPosition::End | ContentPosition::FlexEnd => G::FlexEnd,
4456 }),
4457 _ => None,
4458 };
4459 match mapped {
4460 Some(m) => r.align_content = Some(m),
4461 None => unsupported(diagnostics, "align-content"),
4462 }
4463 }
4464 JustifyContent(v, _) => {
4465 use gpui::JustifyContent as G;
4466 let mapped = match v {
4467 lightningcss::properties::align::JustifyContent::ContentDistribution(d) => {
4468 use lightningcss::properties::align::ContentDistribution as CD;
4469 Some(match d {
4470 CD::SpaceBetween => G::SpaceBetween,
4471 CD::SpaceAround => G::SpaceAround,
4472 CD::SpaceEvenly => G::SpaceEvenly,
4473 CD::Stretch => G::Stretch,
4474 })
4475 }
4476 lightningcss::properties::align::JustifyContent::ContentPosition {
4477 value, ..
4478 } => match value {
4479 ContentPosition::Center => Some(G::Center),
4480 ContentPosition::Start | ContentPosition::FlexStart => Some(G::FlexStart),
4481 ContentPosition::End | ContentPosition::FlexEnd => Some(G::FlexEnd),
4482 },
4483 _ => None,
4484 };
4485 match mapped {
4486 Some(m) => r.justify_content = Some(m),
4487 None => unsupported(diagnostics, "justify-content"),
4488 }
4489 }
4490 Gap(gap) => {
4491 if let Some(v) = gap_definite(&gap.row) {
4492 r.gap.height = Some(v);
4493 }
4494 if let Some(v) = gap_definite(&gap.column) {
4495 r.gap.width = Some(v);
4496 }
4497 }
4498 RowGap(v) => r.gap.height = gap_definite(v),
4499 ColumnGap(v) => r.gap.width = gap_definite(v),
4500 Width(v) => r.size.width = size_length(v),
4501 Height(v) => r.size.height = size_length(v),
4502 MinWidth(v) => r.min_size.width = size_length(v),
4503 MinHeight(v) => r.min_size.height = size_length(v),
4504 MaxWidth(v) => r.max_size.width = max_size_length(v),
4505 MaxHeight(v) => r.max_size.height = max_size_length(v),
4506 Padding(v) => {
4507 r.padding.top = lp_definite_of_lpa(&v.top);
4508 r.padding.right = lp_definite_of_lpa(&v.right);
4509 r.padding.bottom = lp_definite_of_lpa(&v.bottom);
4510 r.padding.left = lp_definite_of_lpa(&v.left);
4511 }
4512 PaddingTop(v) => r.padding.top = lp_definite_of_lpa(v),
4513 PaddingRight(v) => r.padding.right = lp_definite_of_lpa(v),
4514 PaddingBottom(v) => r.padding.bottom = lp_definite_of_lpa(v),
4515 PaddingLeft(v) => r.padding.left = lp_definite_of_lpa(v),
4516 Margin(v) => {
4517 r.margin.top = lpa_length(&v.top);
4518 r.margin.right = lpa_length(&v.right);
4519 r.margin.bottom = lpa_length(&v.bottom);
4520 r.margin.left = lpa_length(&v.left);
4521 }
4522 MarginTop(v) => r.margin.top = lpa_length(v),
4523 MarginRight(v) => r.margin.right = lpa_length(v),
4524 MarginBottom(v) => r.margin.bottom = lpa_length(v),
4525 MarginLeft(v) => r.margin.left = lpa_length(v),
4526 PaddingInline(v) => {
4527 r.padding.left = lp_definite_of_lpa(&v.inline_start);
4528 r.padding.right = lp_definite_of_lpa(&v.inline_end);
4529 }
4530 PaddingBlock(v) => {
4531 r.padding.top = lp_definite_of_lpa(&v.block_start);
4532 r.padding.bottom = lp_definite_of_lpa(&v.block_end);
4533 }
4534 PaddingInlineStart(v) => r.padding.left = lp_definite_of_lpa(v),
4535 PaddingInlineEnd(v) => r.padding.right = lp_definite_of_lpa(v),
4536 PaddingBlockStart(v) => r.padding.top = lp_definite_of_lpa(v),
4537 PaddingBlockEnd(v) => r.padding.bottom = lp_definite_of_lpa(v),
4538 MarginInline(v) => {
4539 r.margin.left = lpa_length(&v.inline_start);
4540 r.margin.right = lpa_length(&v.inline_end);
4541 }
4542 MarginBlock(v) => {
4543 r.margin.top = lpa_length(&v.block_start);
4544 r.margin.bottom = lpa_length(&v.block_end);
4545 }
4546 MarginInlineStart(v) => r.margin.left = lpa_length(v),
4547 MarginInlineEnd(v) => r.margin.right = lpa_length(v),
4548 MarginBlockStart(v) => r.margin.top = lpa_length(v),
4549 MarginBlockEnd(v) => r.margin.bottom = lpa_length(v),
4550 Position(v) => {
4551 use lightningcss::properties::position::Position as P;
4552 x.fixed = Some(matches!(v, P::Fixed));
4553 x.sticky = Some(matches!(v, P::Sticky(_)));
4554 x.positioned = Some(!matches!(v, P::Static));
4555 r.position = Some(match v {
4556 P::Absolute => gpui::Position::Absolute,
4557 P::Fixed => gpui::Position::Absolute,
4562 P::Static | P::Relative => gpui::Position::Relative,
4563 _ => gpui::Position::Relative,
4564 });
4565 }
4566 ZIndex(v) => {
4568 use lightningcss::properties::position::ZIndex as Z;
4569 match v {
4570 Z::Integer(n) => x.z_index = Some(Some(*n)),
4571 Z::Auto => x.z_index = Some(None),
4572 }
4573 }
4574 Transform(list, _) => apply_transform(list, r, diagnostics),
4575 TransformOrigin(pos, _) => {
4578 use lightningcss::values::position::{
4579 HorizontalPositionKeyword as H, PositionComponent as P,
4580 VerticalPositionKeyword as V,
4581 };
4582 fn axis<S: Copy>(
4583 c: &P<S>,
4584 keyword: impl Fn(&S) -> Option<f32>,
4585 ) -> Option<TransformLength> {
4586 match c {
4587 P::Center => Some(TransformLength::Fraction(0.5)),
4588 P::Length(DimensionPercentage::Dimension(l)) => {
4589 length_value_px(l).map(TransformLength::Pixels)
4590 }
4591 P::Length(DimensionPercentage::Percentage(p)) => {
4592 Some(TransformLength::Fraction(p.0))
4593 }
4594 P::Length(DimensionPercentage::Calc(_)) => {
4595 calc_dropped();
4596 None
4597 }
4598 P::Side { side, offset: None } => keyword(side).map(TransformLength::Fraction),
4599 P::Side { .. } => None,
4600 }
4601 }
4602 let x = axis(&pos.x, |s: &H| {
4603 Some(match s {
4604 H::Left => 0.0,
4605 H::Right => 1.0,
4606 })
4607 });
4608 let y = axis(&pos.y, |s: &V| {
4609 Some(match s {
4610 V::Top => 0.0,
4611 V::Bottom => 1.0,
4612 })
4613 });
4614 match (x, y) {
4615 (Some(x), Some(y)) => {
4616 let spec = r.vn_transform.get_or_insert(TransformSpec::IDENTITY);
4617 spec.origin = (x, y);
4618 }
4619 _ => unsupported(
4620 diagnostics,
4621 "transform-origin with a calc() or keyword-plus-offset component — lengths, \
4622 percentages and the bare `left/right/top/bottom/center` keywords are modelled",
4623 ),
4624 }
4625 }
4626 BoxOrient(..) | BoxAlign(..) | BoxPack(..) => {}
4629 TextDecorationSkipInk(v, _) => {
4631 use lightningcss::properties::text::TextDecorationSkipInk as Skip;
4632 if !matches!(v, Skip::None) {
4633 warn_once(
4634 diagnostics,
4635 "`text-decoration-skip-ink: auto` is not applied (v1) — gpui draws one unbroken underline and does not lift it around descenders. `none` (draw it straight through) is what it already does",
4636 );
4637 }
4638 }
4639 TextDecorationColor(c, _) => match color(c) {
4642 Some(v) => {
4643 x.decoration.color = Some(Some(v));
4644 let mut hit = false;
4645 if let Some(u) = r.text.underline.as_mut() {
4646 u.color = Some(v);
4647 hit = true;
4648 }
4649 if let Some(s) = r.text.strikethrough.as_mut() {
4650 s.color = Some(v);
4651 hit = true;
4652 }
4653 let _ = hit;
4654 }
4655 None => unresolved_color(diagnostics, "text-decoration-color"),
4656 },
4657 TextDecorationStyle(s, _) => {
4658 use lightningcss::properties::text::TextDecorationStyle as S;
4659 x.decoration.wavy = Some(matches!(s, S::Wavy));
4660 if let Some(u) = r.text.underline.as_mut() {
4661 u.wavy = matches!(s, S::Wavy);
4662 }
4663 if !matches!(s, S::Solid | S::Wavy) {
4664 unsupported(
4665 diagnostics,
4666 "text-decoration-style — gpui draws a solid or a wavy line, so `double`, \
4667 `dotted` and `dashed` fall back to solid",
4668 );
4669 }
4670 }
4671 TextDecorationThickness(t) => {
4672 use lightningcss::properties::text::TextDecorationThickness as T;
4673 if let T::LengthPercentage(DimensionPercentage::Dimension(l)) = t {
4674 if let Some(w) = length_value_px(l) {
4675 x.decoration.thickness = Some(w);
4676 if let Some(u) = r.text.underline.as_mut() {
4677 u.thickness = px(w);
4678 }
4679 }
4680 }
4681 }
4682 TextDecoration(d, _) => {
4685 use lightningcss::properties::text::TextDecorationLine as TDL;
4686 if d.line.contains(TDL::Underline) {
4687 r.text.underline = Some(gpui::UnderlineStyle::default());
4688 }
4689 if d.line.contains(TDL::LineThrough) {
4690 r.text.strikethrough = Some(gpui::StrikethroughStyle::default());
4691 }
4692 x.decoration.color = Some(color(&d.color));
4693 if let Some(c) = color(&d.color) {
4694 if let Some(u) = r.text.underline.as_mut() {
4695 u.color = Some(c);
4696 }
4697 if let Some(s) = r.text.strikethrough.as_mut() {
4698 s.color = Some(c);
4699 }
4700 }
4701 if d.line.is_empty() {
4702 unsupported(
4703 diagnostics,
4704 "text-decoration: none — cannot undo an earlier underline",
4705 );
4706 }
4707 }
4708 Fill(p) => x.fill = Some(svg_paint(p, "fill", diagnostics)),
4709 Stroke(p) => x.stroke = Some(svg_paint(p, "stroke", diagnostics)),
4710 FillOpacity(_) | FillRule(_) | StrokeOpacity(_) | StrokeWidth(_) | StrokeLinecap(_)
4711 | StrokeLinejoin(_) | StrokeMiterlimit(_) | StrokeDasharray(_) | StrokeDashoffset(_)
4712 | ShapeRendering(_) => {
4713 if let (Some(name), Some(value)) = (presentation_name(p), value_text(p)) {
4714 let value = presentation_value(name, value);
4715 let list = x.svg_presentation.get_or_insert_with(Default::default);
4716 set_presentation(Rc::make_mut(list), name, value.into());
4717 }
4718 }
4719 BoxSizing(v, _) => {
4720 use lightningcss::properties::size::BoxSizing as BS;
4721 if matches!(v, BS::ContentBox) {
4722 warn_once(
4723 diagnostics,
4724 "`box-sizing: content-box` is not supported (v1) — taffy sizes every box as \
4725 `border-box`, so padding and border stay INSIDE the declared width/height",
4726 );
4727 }
4728 }
4729 Top(v) => r.inset.top = lpa_length(v),
4730 Right(v) => r.inset.right = lpa_length(v),
4731 Bottom(v) => r.inset.bottom = lpa_length(v),
4732 Left(v) => r.inset.left = lpa_length(v),
4733 Inset(v) => {
4734 r.inset.top = lpa_length(&v.top);
4735 r.inset.right = lpa_length(&v.right);
4736 r.inset.bottom = lpa_length(&v.bottom);
4737 r.inset.left = lpa_length(&v.left);
4738 }
4739 InsetInline(v) => {
4740 r.inset.left = lpa_length(&v.inline_start);
4741 r.inset.right = lpa_length(&v.inline_end);
4742 }
4743 InsetBlock(v) => {
4744 r.inset.top = lpa_length(&v.block_start);
4745 r.inset.bottom = lpa_length(&v.block_end);
4746 }
4747 InsetInlineStart(v) => r.inset.left = lpa_length(v),
4748 InsetInlineEnd(v) => r.inset.right = lpa_length(v),
4749 InsetBlockStart(v) => r.inset.top = lpa_length(v),
4750 InsetBlockEnd(v) => r.inset.bottom = lpa_length(v),
4751 Overflow(v) => {
4752 r.overflow.x = Some(overflow(v.x));
4753 r.overflow.y = Some(overflow(v.y));
4754 x.overflow_x = Some(v.x);
4755 x.overflow_y = Some(v.y);
4756 }
4757 OverflowX(v) => {
4760 r.overflow.x = Some(overflow(*v));
4761 x.overflow_x = Some(*v);
4762 }
4763 OverflowY(v) => {
4764 r.overflow.y = Some(overflow(*v));
4765 x.overflow_y = Some(*v);
4766 }
4767 Visibility(v) => {
4768 use lightningcss::properties::display::Visibility as V;
4769 x.visibility_hidden = Some(!matches!(v, V::Visible));
4770 r.visibility = Some(match v {
4771 V::Visible => gpui::Visibility::Visible,
4772 V::Hidden => gpui::Visibility::Hidden,
4773 V::Collapse => gpui::Visibility::Hidden,
4774 });
4775 }
4776 AspectRatio(v) => match &v.ratio {
4777 Some(ratio) if !v.auto && ratio.1 != 0.0 => r.aspect_ratio = Some(ratio.0 / ratio.1),
4778 _ => unsupported(
4781 diagnostics,
4782 "aspect-ratio: auto — cannot undo an earlier ratio",
4783 ),
4784 },
4785 Opacity(v) => r.opacity = Some(v.0),
4786 Color(CssColor::CurrentColor) => {}
4789 Color(c) => match color(c) {
4790 Some(c) => r.text.color = Some(c),
4791 None => unresolved_color(diagnostics, "color"),
4792 },
4793 BackgroundColor(CssColor::CurrentColor) => {
4794 x.current_color.0 |= CurrentColorTargets::BACKGROUND;
4795 }
4796 BackgroundColor(c) => match color(c) {
4797 Some(c) => {
4798 r.background = Some(gpui::Fill::Color(c.into()));
4799 x.background_key_color = Some(c);
4800 }
4801 None => unresolved_color(diagnostics, "background-color"),
4802 },
4803 Background(layers) => {
4804 if let Some(last) = layers.last() {
4805 if last.color == CssColor::CurrentColor {
4806 x.current_color.0 |= CurrentColorTargets::BACKGROUND;
4807 } else if let Some(c) = color(&last.color) {
4808 r.background = Some(gpui::Fill::Color(c.into()));
4809 x.background_key_color = Some(c);
4810 }
4811 }
4812 collect_background_images(layers.iter().map(|l| &l.image), x, diagnostics);
4813 x.background_size = Some(Rc::new(
4814 layers.iter().map(|l| background_size(&l.size)).collect(),
4815 ));
4816 x.background_position = Some(Rc::new(
4817 layers
4818 .iter()
4819 .map(|l| background_position(&l.position, diagnostics))
4820 .collect(),
4821 ));
4822 x.background_repeat = Some(Rc::new(
4823 layers
4824 .iter()
4825 .map(|l| background_repeat(&l.repeat))
4826 .collect(),
4827 ));
4828 }
4829 BackgroundImage(images) => {
4830 collect_background_images(images.iter(), x, diagnostics);
4831 }
4832 BackgroundSize(sizes) => {
4833 x.background_size = Some(Rc::new(sizes.iter().map(background_size).collect()));
4834 }
4835 BackgroundPosition(positions) => {
4836 x.background_position = Some(Rc::new(
4837 positions
4838 .iter()
4839 .map(|p| background_position(p, diagnostics))
4840 .collect(),
4841 ));
4842 }
4843 BackgroundPositionX(list) => {
4844 let previous = x.background_position.clone();
4845 x.background_position = Some(Rc::new(
4846 list.iter()
4847 .enumerate()
4848 .map(|(i, h)| {
4849 let y = previous
4850 .as_ref()
4851 .filter(|p| !p.is_empty())
4852 .map(|p| p[i % p.len()].1)
4853 .unwrap_or(TileLength::Fraction(0.0));
4854 (position_component(h, true, diagnostics), y)
4855 })
4856 .collect(),
4857 ));
4858 }
4859 BackgroundPositionY(list) => {
4860 let previous = x.background_position.clone();
4861 x.background_position = Some(Rc::new(
4862 list.iter()
4863 .enumerate()
4864 .map(|(i, v)| {
4865 let h = previous
4866 .as_ref()
4867 .filter(|p| !p.is_empty())
4868 .map(|p| p[i % p.len()].0)
4869 .unwrap_or(TileLength::Fraction(0.0));
4870 (h, position_component(v, false, diagnostics))
4871 })
4872 .collect(),
4873 ));
4874 }
4875 BackgroundRepeat(list) => {
4876 x.background_repeat = Some(Rc::new(list.iter().map(background_repeat).collect()));
4877 }
4878 BackgroundAttachment(_) | BackgroundOrigin(_) => {}
4879 BackgroundClip(v, _) => {
4880 use lightningcss::properties::background::BackgroundClip as BC;
4881 if matches!(v.first(), Some(BC::Text)) {
4882 x.background_clip_text = Some(true);
4883 } else {
4884 warn_once(
4885 diagnostics,
4886 "`background-clip` is ignored (v1) — the background always fills the padding \
4887 box (`padding-box`, the value a rounded box wants anyway)",
4888 );
4889 }
4890 }
4891 Mask(layers, prefix) => {
4892 let images = mask_images(layers.iter().map(|l| &l.image));
4893 x.mask_images = Some(images);
4894 x.mask_clips = Some(mask_clips(layers.iter().map(|l| &l.clip)));
4895 x.mask_composite = Some(
4896 layers
4897 .first()
4898 .map_or(MaskCompositing::Add, |l| mask_compositing(l.composite)),
4899 );
4900 if webkit_mask(
4901 *prefix,
4902 "mask",
4903 images == MaskImages::TwoOpaque,
4904 diagnostics,
4905 ) {
4906 return;
4907 }
4908 collect_mask_images(layers.iter().map(|l| &l.image), x, diagnostics);
4909 x.mask.size = Some(Rc::new(
4910 layers.iter().map(|l| background_size(&l.size)).collect(),
4911 ));
4912 x.mask.position = Some(Rc::new(
4913 layers
4914 .iter()
4915 .map(|l| mask_position(&l.position, diagnostics))
4916 .collect(),
4917 ));
4918 x.mask.repeat = Some(Rc::new(
4919 layers
4920 .iter()
4921 .map(|l| background_repeat(&l.repeat))
4922 .collect(),
4923 ));
4924 x.mask.luminance = Some(mask_luminance(layers.iter().map(|l| &l.mode), diagnostics));
4925 if !(images == MaskImages::TwoOpaque
4926 && x.mask_clips == Some(MaskClips::ContentThenBorder))
4927 {
4928 advise_mask_box(layers.iter().map(|l| &l.origin), "mask-origin", diagnostics);
4929 advise_mask_clip(layers.iter().map(|l| &l.clip), diagnostics);
4930 }
4931 advise_mask(x, diagnostics);
4932 }
4933 MaskImage(images, prefix) => {
4934 let kinds = mask_images(images.iter());
4935 x.mask_images = Some(kinds);
4936 if webkit_mask(
4937 *prefix,
4938 "mask-image",
4939 kinds == MaskImages::TwoOpaque,
4940 diagnostics,
4941 ) {
4942 return;
4943 }
4944 collect_mask_images(images.iter(), x, diagnostics);
4945 advise_mask(x, diagnostics);
4946 }
4947 MaskClip(clips, prefix) => {
4948 let kinds = mask_clips(clips.iter());
4949 x.mask_clips = Some(kinds);
4950 if !webkit_mask(*prefix, "mask-clip", true, diagnostics)
4951 && kinds != MaskClips::ContentThenBorder
4952 {
4953 advise_mask_clip(clips.iter(), diagnostics);
4954 }
4955 }
4956 MaskSize(sizes, prefix) => {
4957 if !webkit_mask(*prefix, "mask-size", false, diagnostics) {
4958 x.mask.size = Some(Rc::new(sizes.iter().map(background_size).collect()));
4959 }
4960 }
4961 MaskPosition(positions, prefix) => {
4962 if !webkit_mask(*prefix, "mask-position", false, diagnostics) {
4963 x.mask.position = Some(Rc::new(
4964 positions
4965 .iter()
4966 .map(|p| mask_position(p, diagnostics))
4967 .collect(),
4968 ));
4969 }
4970 }
4971 MaskPositionX(list) => {
4972 let previous = x.mask.position.clone();
4973 x.mask.position = Some(Rc::new(
4974 list.iter()
4975 .enumerate()
4976 .map(|(i, h)| {
4977 let y = previous
4978 .as_ref()
4979 .filter(|p| !p.is_empty())
4980 .map(|p| p[i % p.len()].1)
4981 .unwrap_or(TileLength::Fraction(0.0));
4982 (position_component(h, true, diagnostics), y)
4983 })
4984 .collect(),
4985 ));
4986 }
4987 MaskPositionY(list) => {
4988 let previous = x.mask.position.clone();
4989 x.mask.position = Some(Rc::new(
4990 list.iter()
4991 .enumerate()
4992 .map(|(i, v)| {
4993 let h = previous
4994 .as_ref()
4995 .filter(|p| !p.is_empty())
4996 .map(|p| p[i % p.len()].0)
4997 .unwrap_or(TileLength::Fraction(0.0));
4998 (h, position_component(v, false, diagnostics))
4999 })
5000 .collect(),
5001 ));
5002 }
5003 MaskRepeat(list, prefix) => {
5004 if !webkit_mask(*prefix, "mask-repeat", false, diagnostics) {
5005 x.mask.repeat = Some(Rc::new(list.iter().map(background_repeat).collect()));
5006 }
5007 }
5008 MaskOrigin(boxes, prefix) => {
5009 if !webkit_mask(*prefix, "mask-origin", false, diagnostics) {
5010 advise_mask_box(boxes.iter(), "mask-origin", diagnostics);
5011 }
5012 }
5013 MaskMode(modes) => x.mask.luminance = Some(mask_luminance(modes.iter(), diagnostics)),
5014 MaskComposite(list) => {
5015 x.mask_composite = Some(
5016 list.first()
5017 .map_or(MaskCompositing::Add, |c| mask_compositing(*c)),
5018 );
5019 advise_mask(x, diagnostics);
5020 }
5021 WebKitMaskComposite(list) => {
5022 use lightningcss::traits::ToCss;
5023 let first = list
5024 .first()
5025 .and_then(|c| c.to_css_string(Default::default()).ok());
5026 x.mask_composite = Some(webkit_mask_compositing(
5027 first.as_deref().unwrap_or("source-over"),
5028 ));
5029 advise_mask(x, diagnostics);
5030 }
5031 BorderColor(v) => {
5032 all_border_colors(r, x, [&v.top, &v.right, &v.bottom, &v.left], diagnostics)
5033 }
5034 Border(b) => {
5035 if let Some(w) = border_width_px(&b.width) {
5036 let w: AbsoluteLength = px(w).into();
5037 r.border_widths.top = Some(w);
5038 r.border_widths.right = Some(w);
5039 r.border_widths.bottom = Some(w);
5040 r.border_widths.left = Some(w);
5041 }
5042 all_border_colors(r, x, [&b.color; 4], diagnostics);
5043 set_border_style(r, b.style, SIDES_ALL, diagnostics);
5044 }
5045 BorderWidth(v) => {
5046 r.border_widths.top = border_width_px(&v.top).map(|w| px(w).into());
5047 r.border_widths.right = border_width_px(&v.right).map(|w| px(w).into());
5048 r.border_widths.bottom = border_width_px(&v.bottom).map(|w| px(w).into());
5049 r.border_widths.left = border_width_px(&v.left).map(|w| px(w).into());
5050 }
5051 BorderTopColor(c) => border_side_color(
5052 &mut r.vn_border_colors.top,
5053 CurrentColorTargets::BORDER_TOP,
5054 c,
5055 x,
5056 diagnostics,
5057 ),
5058 BorderRightColor(c) => border_side_color(
5059 &mut r.vn_border_colors.right,
5060 CurrentColorTargets::BORDER_RIGHT,
5061 c,
5062 x,
5063 diagnostics,
5064 ),
5065 BorderBottomColor(c) => border_side_color(
5066 &mut r.vn_border_colors.bottom,
5067 CurrentColorTargets::BORDER_BOTTOM,
5068 c,
5069 x,
5070 diagnostics,
5071 ),
5072 BorderLeftColor(c) => border_side_color(
5073 &mut r.vn_border_colors.left,
5074 CurrentColorTargets::BORDER_LEFT,
5075 c,
5076 x,
5077 diagnostics,
5078 ),
5079 BorderTop(b) => {
5080 r.border_widths.top = border_width_px(&b.width).map(|w| px(w).into());
5081 border_side_color(
5082 &mut r.vn_border_colors.top,
5083 CurrentColorTargets::BORDER_TOP,
5084 &b.color,
5085 x,
5086 diagnostics,
5087 );
5088 set_border_style(r, b.style, SIDE_TOP, diagnostics);
5089 }
5090 BorderRight(b) => {
5091 r.border_widths.right = border_width_px(&b.width).map(|w| px(w).into());
5092 border_side_color(
5093 &mut r.vn_border_colors.right,
5094 CurrentColorTargets::BORDER_RIGHT,
5095 &b.color,
5096 x,
5097 diagnostics,
5098 );
5099 set_border_style(r, b.style, SIDE_RIGHT, diagnostics);
5100 }
5101 BorderBottom(b) => {
5102 r.border_widths.bottom = border_width_px(&b.width).map(|w| px(w).into());
5103 border_side_color(
5104 &mut r.vn_border_colors.bottom,
5105 CurrentColorTargets::BORDER_BOTTOM,
5106 &b.color,
5107 x,
5108 diagnostics,
5109 );
5110 set_border_style(r, b.style, SIDE_BOTTOM, diagnostics);
5111 }
5112 BorderLeft(b) => {
5113 r.border_widths.left = border_width_px(&b.width).map(|w| px(w).into());
5114 border_side_color(
5115 &mut r.vn_border_colors.left,
5116 CurrentColorTargets::BORDER_LEFT,
5117 &b.color,
5118 x,
5119 diagnostics,
5120 );
5121 set_border_style(r, b.style, SIDE_LEFT, diagnostics);
5122 }
5123 BorderTopWidth(v) => r.border_widths.top = border_width_px(v).map(|w| px(w).into()),
5124 BorderRightWidth(v) => r.border_widths.right = border_width_px(v).map(|w| px(w).into()),
5125 BorderBottomWidth(v) => r.border_widths.bottom = border_width_px(v).map(|w| px(w).into()),
5126 BorderLeftWidth(v) => r.border_widths.left = border_width_px(v).map(|w| px(w).into()),
5127 BorderStyle(v) => {
5128 set_border_style(r, v.left, SIDE_LEFT, diagnostics);
5129 set_border_style(r, v.bottom, SIDE_BOTTOM, diagnostics);
5130 set_border_style(r, v.right, SIDE_RIGHT, diagnostics);
5131 set_border_style(r, v.top, SIDE_TOP, diagnostics);
5132 }
5133 BorderTopStyle(v) => set_border_style(r, *v, SIDE_TOP, diagnostics),
5134 BorderRightStyle(v) => set_border_style(r, *v, SIDE_RIGHT, diagnostics),
5135 BorderBottomStyle(v) => set_border_style(r, *v, SIDE_BOTTOM, diagnostics),
5136 BorderLeftStyle(v) => set_border_style(r, *v, SIDE_LEFT, diagnostics),
5137 BorderRadius(v, _) => {
5138 let mut wrote = 0;
5139 if corner(
5140 &mut r.corner_radii.top_left,
5141 &mut r.vn_corner_radii.top_left,
5142 &v.top_left,
5143 ) {
5144 wrote |= RadiusInherit::TOP_LEFT;
5145 }
5146 if corner(
5147 &mut r.corner_radii.top_right,
5148 &mut r.vn_corner_radii.top_right,
5149 &v.top_right,
5150 ) {
5151 wrote |= RadiusInherit::TOP_RIGHT;
5152 }
5153 if corner(
5154 &mut r.corner_radii.bottom_right,
5155 &mut r.vn_corner_radii.bottom_right,
5156 &v.bottom_right,
5157 ) {
5158 wrote |= RadiusInherit::BOTTOM_RIGHT;
5159 }
5160 if corner(
5161 &mut r.corner_radii.bottom_left,
5162 &mut r.vn_corner_radii.bottom_left,
5163 &v.bottom_left,
5164 ) {
5165 wrote |= RadiusInherit::BOTTOM_LEFT;
5166 }
5167 x.radius_inherit.write(wrote, false);
5168 }
5169 BorderTopLeftRadius(v, _) => {
5170 if corner(
5171 &mut r.corner_radii.top_left,
5172 &mut r.vn_corner_radii.top_left,
5173 v,
5174 ) {
5175 x.radius_inherit.write(RadiusInherit::TOP_LEFT, false);
5176 }
5177 }
5178 BorderTopRightRadius(v, _) => {
5179 if corner(
5180 &mut r.corner_radii.top_right,
5181 &mut r.vn_corner_radii.top_right,
5182 v,
5183 ) {
5184 x.radius_inherit.write(RadiusInherit::TOP_RIGHT, false);
5185 }
5186 }
5187 BorderBottomRightRadius(v, _) => {
5188 if corner(
5189 &mut r.corner_radii.bottom_right,
5190 &mut r.vn_corner_radii.bottom_right,
5191 v,
5192 ) {
5193 x.radius_inherit.write(RadiusInherit::BOTTOM_RIGHT, false);
5194 }
5195 }
5196 BorderBottomLeftRadius(v, _) => {
5197 if corner(
5198 &mut r.corner_radii.bottom_left,
5199 &mut r.vn_corner_radii.bottom_left,
5200 v,
5201 ) {
5202 x.radius_inherit.write(RadiusInherit::BOTTOM_LEFT, false);
5203 }
5204 }
5205 GridTemplateColumns(v) => match grid_template(v) {
5206 Some(t) => r.grid_cols = Some(t),
5207 None => match grid_tracks(v) {
5208 Some((tracks, auto)) => {
5209 r.vn_grid_cols = Some(tracks);
5210 r.vn_grid_cols_auto = Some(auto);
5211 }
5212 None => unsupported(
5213 diagnostics,
5214 "grid-template-columns — `fit-content()`, named lines, a `calc()` breadth \
5215 with a percentage in it, and a `repeat(auto-fill|auto-fit, …)` next to a \
5216 track that is not fixed-size (invalid CSS) are not modelled; every track \
5217 list of lengths, percentages, `auto`, `min-content`, `max-content`, \
5218 `<flex>`, `minmax()` and `repeat()` (counted or auto) is",
5219 ),
5220 },
5221 },
5222 GridTemplateRows(v) => match grid_template(v) {
5223 Some(t) => r.grid_rows = Some(t),
5224 None => match grid_tracks(v) {
5225 Some((tracks, auto)) => {
5226 r.vn_grid_rows = Some(tracks);
5227 r.vn_grid_rows_auto = Some(auto);
5228 }
5229 None => unsupported(
5230 diagnostics,
5231 "grid-template-rows — `fit-content()`, named lines, a `calc()` breadth with \
5232 a percentage in it, and a `repeat(auto-fill|auto-fit, …)` next to a track \
5233 that is not fixed-size (invalid CSS) are not modelled; every track list of \
5234 lengths, percentages, `auto`, `min-content`, `max-content`, `<flex>`, \
5235 `minmax()` and `repeat()` (counted or auto) is",
5236 ),
5237 },
5238 },
5239 GridColumnStart(l) | GridColumnEnd(l) | GridRowStart(l) | GridRowEnd(l) => {
5240 let Some(placement) = grid_line(l) else {
5241 unsupported(
5242 diagnostics,
5243 "grid-row/grid-column with a NAMED line or area — the named grid is not \
5244 modelled; use line numbers or `span N`",
5245 );
5246 return;
5247 };
5248 let loc = r.grid_location.get_or_insert_default();
5249 match p {
5250 GridColumnStart(_) => loc.column.start = placement,
5251 GridColumnEnd(_) => loc.column.end = placement,
5252 GridRowStart(_) => loc.row.start = placement,
5253 _ => loc.row.end = placement,
5254 }
5255 }
5256 GridColumn(v) => match (grid_line(&v.start), grid_line(&v.end)) {
5257 (Some(s), Some(e)) => {
5258 let loc = r.grid_location.get_or_insert_default();
5259 loc.column = s..e;
5260 }
5261 _ => unsupported(
5262 diagnostics,
5263 "grid-column with a NAMED line or area — use line numbers or `span N`",
5264 ),
5265 },
5266 GridRow(v) => match (grid_line(&v.start), grid_line(&v.end)) {
5267 (Some(s), Some(e)) => {
5268 let loc = r.grid_location.get_or_insert_default();
5269 loc.row = s..e;
5270 }
5271 _ => unsupported(
5272 diagnostics,
5273 "grid-row with a NAMED line or area — use line numbers or `span N`",
5274 ),
5275 },
5276 GridArea(v) => {
5277 match (
5278 grid_line(&v.row_start),
5279 grid_line(&v.row_end),
5280 grid_line(&v.column_start),
5281 grid_line(&v.column_end),
5282 ) {
5283 (Some(rs), Some(re), Some(cs), Some(ce)) => {
5284 let loc = r.grid_location.get_or_insert_default();
5285 loc.row = rs..re;
5286 loc.column = cs..ce;
5287 }
5288 _ => unsupported(
5289 diagnostics,
5290 "grid-area naming a template AREA — `grid-template-areas` is not modelled; \
5291 the four-line form (`grid-area: 1 / 1 / 3 / 2`) is",
5292 ),
5293 }
5294 }
5295 GridAutoFlow(v) => {
5296 use lightningcss::properties::grid::GridAutoFlow as F;
5297 let dense = v.contains(F::Dense);
5298 r.vn_grid_auto_flow = Some(if v.contains(F::Column) {
5299 if dense {
5300 gpui::GridAutoFlow::ColumnDense
5301 } else {
5302 gpui::GridAutoFlow::Column
5303 }
5304 } else if dense {
5305 gpui::GridAutoFlow::RowDense
5306 } else {
5307 gpui::GridAutoFlow::Row
5308 });
5309 }
5310 GridTemplateAreas(_) | GridTemplate(_) | Grid(_) => unsupported(
5311 diagnostics,
5312 "grid-template-areas (and the `grid` / `grid-template` shorthands that carry it) — \
5313 the named grid is not modelled. Declare `grid-template-columns`/`-rows` and place \
5314 items with `grid-column`/`grid-row` line numbers",
5315 ),
5316 GridAutoColumns(list) | GridAutoRows(list) => {
5317 match list.0.iter().map(track_size).collect::<Option<Vec<_>>>() {
5318 Some(tracks) => {
5319 if matches!(p, GridAutoColumns(_)) {
5320 r.vn_grid_auto_cols = Some(tracks);
5321 } else {
5322 r.vn_grid_auto_rows = Some(tracks);
5323 }
5324 }
5325 None => unsupported(
5326 diagnostics,
5327 "grid-auto-columns / grid-auto-rows — fit-content() and percentage-dependent calc() \
5328 track sizes are not modelled; use lengths, percentages, auto, min-content, \
5329 max-content, flex, or minmax()",
5330 ),
5331 }
5332 }
5333 JustifyItems(v) => {
5334 use lightningcss::properties::align::JustifyItems as J;
5335 match v {
5336 J::Normal => r.vn_justify_items = Some(gpui::AlignItems::Stretch),
5337 J::Stretch => r.vn_justify_items = Some(gpui::AlignItems::Stretch),
5338 J::BaselinePosition(_) => r.vn_justify_items = Some(gpui::AlignItems::Baseline),
5339 J::SelfPosition { value, .. } => {
5340 r.vn_justify_items = Some(self_position(value));
5341 }
5342 J::Legacy(_) => unsupported(diagnostics, "justify-items: legacy"),
5343 J::Left { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexStart),
5344 J::Right { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexEnd),
5345 }
5346 }
5347 JustifySelf(v) => {
5348 use lightningcss::properties::align::JustifySelf as J;
5349 match v {
5350 J::Auto | J::Normal | J::Stretch => {
5351 r.vn_justify_self = Some(gpui::AlignSelf::Stretch)
5352 }
5353 J::BaselinePosition(_) => r.vn_justify_self = Some(gpui::AlignSelf::Baseline),
5354 J::SelfPosition { value, .. } => r.vn_justify_self = Some(self_position(value)),
5355 J::Left { .. } => r.vn_justify_self = Some(gpui::AlignSelf::FlexStart),
5356 J::Right { .. } => r.vn_justify_self = Some(gpui::AlignSelf::FlexEnd),
5357 }
5358 }
5359 PlaceItems(v) => {
5360 use lightningcss::properties::align::{AlignItems as A, JustifyItems as J};
5361 match &v.align {
5362 A::Stretch | A::Normal => r.align_items = Some(gpui::AlignItems::Stretch),
5363 A::BaselinePosition(_) => r.align_items = Some(gpui::AlignItems::Baseline),
5364 A::SelfPosition { value, .. } => r.align_items = Some(self_position(value)),
5365 }
5366 match &v.justify {
5367 J::Normal | J::Stretch => r.vn_justify_items = Some(gpui::AlignItems::Stretch),
5368 J::BaselinePosition(_) => r.vn_justify_items = Some(gpui::AlignItems::Baseline),
5369 J::SelfPosition { value, .. } => r.vn_justify_items = Some(self_position(value)),
5370 J::Legacy(_) => unsupported(diagnostics, "place-items: legacy justify"),
5371 J::Left { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexStart),
5372 J::Right { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexEnd),
5373 }
5374 }
5375 Outline(o) => {
5376 use lightningcss::properties::outline::OutlineStyle as OS;
5377 let out = outline_mut(r);
5378 match &o.style {
5379 OS::Auto => out.style = gpui::BorderStyle::Solid,
5380 OS::LineStyle(LineStyle::None) | OS::LineStyle(LineStyle::Hidden) => {
5381 out.width = px(0.0)
5382 }
5383 OS::LineStyle(ls) => {
5384 out.style = if matches!(ls, LineStyle::Dashed | LineStyle::Dotted) {
5385 gpui::BorderStyle::Dashed
5386 } else {
5387 gpui::BorderStyle::Solid
5388 }
5389 }
5390 }
5391 let style = out.style;
5392 if matches!(&o.style, OS::LineStyle(LineStyle::None | LineStyle::Hidden)) {
5396 x.outline.hidden = Some(true);
5397 } else {
5398 x.outline.hidden = Some(false);
5399 x.outline.style = Some(style);
5400 if let Some(w) = border_width_px(&o.width) {
5401 r.vn_outline.as_mut().unwrap().width = px(w);
5402 x.outline.width = Some(w);
5403 }
5404 match &o.color {
5405 CssColor::CurrentColor => {
5406 x.current_color.0 |= CurrentColorTargets::OUTLINE;
5407 x.outline.color = Some(None);
5408 }
5409 c => match color(c) {
5410 Some(c) => {
5411 r.vn_outline.as_mut().unwrap().color = c;
5412 x.outline.color = Some(Some(c));
5413 }
5414 None => unresolved_color(diagnostics, "outline-color"),
5415 },
5416 }
5417 }
5418 }
5419 OutlineWidth(w) => {
5420 if let Some(v) = border_width_px(w) {
5421 outline_mut(r).width = px(v);
5422 x.outline.width = Some(v);
5423 }
5424 }
5425 OutlineColor(CssColor::CurrentColor) => {
5426 outline_mut(r);
5427 x.current_color.0 |= CurrentColorTargets::OUTLINE;
5428 x.outline.color = Some(None);
5429 }
5430 OutlineColor(c) => match color(c) {
5431 Some(v) => {
5432 outline_mut(r).color = v;
5433 x.outline.color = Some(Some(v));
5434 }
5435 None => unresolved_color(diagnostics, "outline-color"),
5436 },
5437 OutlineStyle(s) => {
5438 use lightningcss::properties::outline::OutlineStyle as OS;
5439 let out = outline_mut(r);
5440 match s {
5441 OS::LineStyle(LineStyle::None) | OS::LineStyle(LineStyle::Hidden) => {
5442 out.width = px(0.0);
5443 x.outline.hidden = Some(true);
5444 }
5445 other => {
5446 out.style = if matches!(
5447 other,
5448 OS::LineStyle(LineStyle::Dashed) | OS::LineStyle(LineStyle::Dotted)
5449 ) {
5450 gpui::BorderStyle::Dashed
5451 } else {
5452 gpui::BorderStyle::Solid
5453 };
5454 x.outline.hidden = Some(false);
5455 x.outline.style = Some(out.style);
5456 if out.width == px(0.0) {
5457 out.width = px(3.0);
5458 }
5459 }
5460 }
5461 }
5462 BoxShadow(shadows, _) => {
5463 let mut out = Vec::new();
5464 for s in shadows.iter() {
5465 let (Some(c), Some(x), Some(y)) = (
5466 color(&s.color),
5467 css_length_px(&s.x_offset),
5468 css_length_px(&s.y_offset),
5469 ) else {
5470 unresolved_color(diagnostics, "box-shadow");
5474 continue;
5475 };
5476 out.push(gpui::BoxShadow {
5477 color: c,
5478 offset: gpui::point(px(x), px(y)),
5479 blur_radius: px(css_length_px(&s.blur).unwrap_or(0.0)),
5480 spread_radius: px(css_length_px(&s.spread).unwrap_or(0.0)),
5481 inset: s.inset,
5482 });
5483 }
5484 r.box_shadow = Some(out);
5485 }
5486 TextShadow(shadows) => {
5487 if let Some(shadows) = text_shadows(shadows, diagnostics) {
5488 r.text.text_shadow = Some(shadows);
5489 }
5490 }
5491 FontFamily(families) => {
5492 x.web_font = waiting_web_font(families);
5493 if let Some(family) = first_available_family(families) {
5494 r.text.font_family = Some(gpui::SharedString::from(family));
5495 }
5496 if let Some((family, fallbacks)) = composed_font_stack(families) {
5497 r.text.font_family = Some(gpui::SharedString::from(family));
5498 r.text.font_fallbacks = Some(fallbacks);
5499 }
5500 }
5501 FontSize(v) => {
5502 use lightningcss::properties::font::{FontSize as FS, RelativeFontSize as R};
5503 let size = match v {
5504 FS::Length(DimensionPercentage::Percentage(p)) => Some(p.0 * em_basis()),
5505 FS::Length(DimensionPercentage::Calc(c)) => match calc_px(c, &lp_leaf_px) {
5506 Some(p) => Some(p),
5507 None => calc_linear(c).map(|(fraction, pixels)| fraction * em_basis() + pixels),
5508 },
5509 FS::Length(lp) => lp_absolute(lp).map(font_size_px),
5510 FS::Absolute(k) => Some(absolute_font_size_px(k)),
5511 FS::Relative(R::Smaller) => Some(em_basis() / 1.2),
5512 FS::Relative(R::Larger) => Some(em_basis() * 1.2),
5513 };
5514 if let Some(size) = size {
5515 r.text.font_size = Some(px(size.max(0.0)).into());
5516 }
5517 }
5518 FontWeight(w) => {
5519 let n = match w {
5520 CssFontWeight::Absolute(AbsoluteFontWeight::Weight(n)) => Some(*n),
5521 CssFontWeight::Absolute(AbsoluteFontWeight::Normal) => Some(400.0),
5522 CssFontWeight::Absolute(AbsoluteFontWeight::Bold) => Some(700.0),
5523 _ => None,
5524 };
5525 match n {
5526 Some(n) => r.text.font_weight = Some(gpui::FontWeight(n)),
5527 None => {
5528 r.text.font_weight = Some(match w {
5529 CssFontWeight::Bolder => gpui::FontWeight(700.0),
5530 _ => gpui::FontWeight(100.0),
5531 })
5532 }
5533 }
5534 }
5535 LineHeight(v) => {
5536 r.text.line_height = match v {
5537 CssLineHeight::Number(n) => Some(relative(*n)),
5540 CssLineHeight::Length(DimensionPercentage::Percentage(p)) => {
5541 Some(px(p.0 * em_basis()).into())
5542 }
5543 CssLineHeight::Length(lp) => lp_definite(lp),
5544 CssLineHeight::Normal => Some(relative(1.2)),
5545 };
5546 }
5547 FontStyle(v) => {
5548 use lightningcss::properties::font::FontStyle as FS;
5549 r.text.font_style = Some(match v {
5550 FS::Normal => gpui::FontStyle::Normal,
5551 FS::Italic => gpui::FontStyle::Italic,
5552 FS::Oblique(_) => {
5553 unsupported(diagnostics, "font-style: oblique <angle> (angle ignored)");
5554 gpui::FontStyle::Oblique
5555 }
5556 });
5557 }
5558 TextAlign(v) => {
5559 use gpui::TextAlign as G;
5560 let mapped = match v {
5561 CssTextAlign::Left | CssTextAlign::Start => Some(G::Left),
5562 CssTextAlign::Center => Some(G::Center),
5563 CssTextAlign::Right | CssTextAlign::End => Some(G::Right),
5564 _ => None,
5565 };
5566 match mapped {
5567 Some(m) => r.text.text_align = Some(m),
5568 None => unsupported(diagnostics, "text-align"),
5569 }
5570 }
5571 WhiteSpace(v) => {
5572 use lightningcss::properties::text::WhiteSpace as WS;
5573 let mode = match v {
5574 WS::Normal => WhiteSpaceMode::Normal,
5575 WS::NoWrap => WhiteSpaceMode::Nowrap,
5576 WS::Pre => WhiteSpaceMode::Pre,
5577 WS::PreWrap => WhiteSpaceMode::PreWrap,
5578 WS::PreLine => WhiteSpaceMode::PreLine,
5579 WS::BreakSpaces => WhiteSpaceMode::BreakSpaces,
5580 };
5581 x.white_space = Some(mode);
5582 r.text.white_space = Some(match mode {
5583 WhiteSpaceMode::Nowrap | WhiteSpaceMode::Pre => gpui::WhiteSpace::Nowrap,
5586 _ => gpui::WhiteSpace::Normal,
5587 });
5588 }
5589 TextOverflow(v, _) => {
5590 use lightningcss::properties::overflow::TextOverflow as TO;
5591 match v {
5592 TO::Ellipsis => {
5593 r.text.text_overflow = Some(gpui::TextOverflow::Truncate("…".into()))
5594 }
5595 TO::Clip => unsupported(
5598 diagnostics,
5599 "text-overflow: clip — cannot undo an earlier ellipsis",
5600 ),
5601 }
5602 }
5603 TextDecorationLine(v, _) => {
5604 use lightningcss::properties::text::TextDecorationLine as TDL;
5605 if v.contains(TDL::Underline) {
5606 r.text.underline = Some(gpui::UnderlineStyle::default());
5607 }
5608 if v.contains(TDL::LineThrough) {
5609 r.text.strikethrough = Some(gpui::StrikethroughStyle::default());
5610 }
5611 if v.intersects(TDL::Overline | TDL::Blink) {
5612 unsupported(diagnostics, "text-decoration-line: overline/blink");
5613 }
5614 if v.is_empty() {
5615 r.text.underline = Some(gpui::UnderlineStyle {
5619 thickness: px(0.0),
5620 color: Some(gpui::transparent_black()),
5621 wavy: false,
5622 offset: px(0.0),
5623 });
5624 r.text.strikethrough = Some(gpui::StrikethroughStyle {
5625 thickness: px(0.0),
5626 color: Some(gpui::transparent_black()),
5627 });
5628 }
5629 }
5630 Cursor(c) => {
5631 use gpui::CursorStyle as C;
5632 use lightningcss::properties::ui::CursorKeyword as K;
5633 let mapped = match c.keyword {
5634 K::Pointer => C::PointingHand,
5635 K::Default | K::Auto => C::Arrow,
5636 K::Text => C::IBeam,
5637 K::VerticalText => C::IBeamCursorForVerticalLayout,
5638 K::Crosshair | K::Cell => C::Crosshair,
5639 K::Grab | K::Move | K::AllScroll => C::OpenHand,
5640 K::Grabbing => C::ClosedHand,
5641 K::EResize => C::ResizeRight,
5642 K::WResize => C::ResizeLeft,
5643 K::NResize => C::ResizeUp,
5644 K::SResize => C::ResizeDown,
5645 K::EwResize => C::ResizeLeftRight,
5646 K::NsResize => C::ResizeUpDown,
5647 K::NwResize | K::SeResize | K::NwseResize => C::ResizeUpLeftDownRight,
5650 K::NeResize | K::SwResize | K::NeswResize => C::ResizeUpRightDownLeft,
5651 K::ColResize => C::ResizeColumn,
5652 K::RowResize => C::ResizeRow,
5653 K::NotAllowed | K::NoDrop => C::OperationNotAllowed,
5654 K::Alias => C::DragLink,
5655 K::Copy => C::DragCopy,
5656 K::ContextMenu => C::ContextualMenu,
5657 K::None | K::Help | K::Progress | K::Wait | K::ZoomIn | K::ZoomOut => {
5658 diagnostics.push(format!(
5659 "`cursor: {:?}` has no native platform shape; using the arrow cursor",
5660 c.keyword
5661 ));
5662 C::Arrow
5663 }
5664 };
5665 r.mouse_cursor = Some(mapped);
5666 }
5667 Filter(list, _) => apply_filter(list, x, diagnostics),
5668 BackdropFilter(list, _) => apply_backdrop_filter(list, r, diagnostics),
5669 Custom(c) => match &c.name {
5670 lightningcss::properties::custom::CustomPropertyName::Custom(name)
5674 if name.0.as_ref() == effect::SHADING =>
5675 {
5676 if let Some(spec) = effect::parse(&c.value, diagnostics) {
5677 r.vn_effect = Some(spec);
5678 }
5679 }
5680 lightningcss::properties::custom::CustomPropertyName::Custom(name)
5681 if name.0.as_ref() == WINDOW_CONTROL =>
5682 {
5683 if let Some(c) = window_control(&c.value, diagnostics) {
5684 x.window_control = Some(c);
5685 }
5686 }
5687 lightningcss::properties::custom::CustomPropertyName::Custom(_) => {}
5688 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5689 if name.0.as_ref() == "object-fit" =>
5690 {
5691 if let Some(fit) = object_fit(&c.value, diagnostics) {
5692 x.object_fit = Some(fit);
5693 }
5694 }
5695 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5696 if name.0.as_ref() == "object-position" =>
5697 {
5698 if let Some(position) = object_position(p, diagnostics) {
5699 r.vn_object_position = Some(position);
5700 }
5701 }
5702 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5703 if matches!(
5704 name.0.as_ref(),
5705 "window-drag" | "app-region" | "-webkit-app-region"
5706 ) =>
5707 {
5708 if let Some(d) = window_drag(name.0.as_ref(), &c.value, diagnostics) {
5709 x.window_drag = Some(d);
5710 }
5711 }
5712 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5713 if name.0.as_ref() == "pointer-events" =>
5714 {
5715 match single_ident(&c.value, "pointer-events", diagnostics) {
5716 Some("none") => x.pointer_events_none = Some(true),
5717 Some("auto") => x.pointer_events_none = Some(false),
5718 other => once(
5719 diagnostics,
5720 format!(
5721 "unsupported value for pointer-events: {} — only `none` and `auto` \
5722 are modelled (SVG-only values have nothing to apply to)",
5723 other.unwrap_or("<not a keyword>")
5724 ),
5725 ),
5726 }
5727 }
5728 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5729 if name.0.as_ref() == "content" =>
5730 {
5731 match content_string(&c.value) {
5732 ContentValue::Text(t) => {
5733 x.content = Some(t);
5734 x.content_none = false;
5735 }
5736 ContentValue::None => {
5737 x.content = None;
5738 x.content_none = true;
5739 }
5740 ContentValue::Unsupported(what) => once(
5741 diagnostics,
5742 format!(
5743 "`content: {what}` does not generate a box (v1) — only a literal \
5744 string does. Counters, `attr()`, `url()` and the `open-quote` \
5745 family have no model here; render the value as a real element"
5746 ),
5747 ),
5748 }
5749 }
5750 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5751 if name.0.as_ref() == "outline-offset" =>
5752 {
5753 match single_length_px(&c.value) {
5754 Some(v) => {
5755 outline_mut(r).offset = px(v);
5756 x.outline.offset = Some(v);
5757 }
5758 None => unsupported(diagnostics, "outline-offset (a <length> is expected)"),
5759 }
5760 }
5761 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5762 if name.0.as_ref() == "-webkit-line-clamp" || name.0.as_ref() == "line-clamp" =>
5763 {
5764 match single_number(&c.value) {
5765 Some(n) if n >= 1.0 => r.text.line_clamp = Some(n as usize),
5766 _ => unsupported(
5767 diagnostics,
5768 "line-clamp: none — cannot undo an earlier clamp",
5769 ),
5770 }
5771 }
5772 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5773 if name
5774 .0
5775 .as_ref()
5776 .eq_ignore_ascii_case("-webkit-text-fill-color") =>
5777 {
5778 use lightningcss::properties::custom::{Token, TokenOrValue};
5779 let mut tokens = c
5780 .value
5781 .0
5782 .iter()
5783 .filter(|t| !matches!(t, TokenOrValue::Token(Token::WhiteSpace(_))));
5784 let fill = match (tokens.next(), tokens.next()) {
5785 (Some(TokenOrValue::Color(cc)), None) => color(cc).map(TextFill::Color),
5786 (Some(TokenOrValue::Token(Token::Ident(id))), None)
5787 if id.as_ref().eq_ignore_ascii_case("currentcolor") =>
5788 {
5789 Some(TextFill::CurrentColor)
5790 }
5791 (Some(TokenOrValue::Token(Token::Ident(id))), None) => {
5792 named_color(id.as_ref()).map(TextFill::Color)
5793 }
5794 _ => None,
5795 };
5796 match fill {
5797 Some(f) => x.text_fill_color = Some(f),
5798 None if is_css_wide_keyword(&c.value) => {}
5799 None => unsupported(
5800 diagnostics,
5801 "-webkit-text-fill-color (a <color> is expected)",
5802 ),
5803 }
5804 }
5805 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5806 if name.0.as_ref() == "text-underline-offset" =>
5807 {
5808 if single_ident_is(&c.value, "auto") || is_css_wide_keyword(&c.value) {
5809 } else if let Some(offset) = single_length_px(&c.value) {
5810 x.underline_offset = Some(offset);
5811 if let Some(u) = r.text.underline.as_mut() {
5812 u.offset = px(offset);
5813 }
5814 } else {
5815 unsupported(
5816 diagnostics,
5817 "text-underline-offset (a <length> is expected)",
5818 );
5819 }
5820 }
5821 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5824 if name.0.as_ref() == "text-decoration-skip-ink" =>
5825 {
5826 if !single_ident_is(&c.value, "none") && !is_css_wide_keyword(&c.value) {
5827 warn_once(
5828 diagnostics,
5829 "`text-decoration-skip-ink: auto` is not applied (v1) — gpui draws one \
5830 unbroken underline and does not lift it around descenders. `none` (draw \
5831 it straight through) is what it already does",
5832 );
5833 }
5834 }
5835 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5836 if matches!(
5837 name.0.as_ref(),
5838 "font-feature-settings"
5839 | "font-variant-numeric"
5840 | "font-variant-ligatures"
5841 | "font-kerning"
5842 ) =>
5843 {
5844 match font_features(&c.value, name.0.as_ref()) {
5845 Some(features) if features.0.is_empty() => {}
5846 Some(features) => {
5847 let mut pairs = r
5848 .text
5849 .font_features
5850 .take()
5851 .map(|f| (*f.0).clone())
5852 .unwrap_or_default();
5853 for (tag, v) in features.0.iter() {
5854 match pairs.iter_mut().find(|(t, _)| t == tag) {
5855 Some(slot) => slot.1 = *v,
5856 None => pairs.push((tag.clone(), *v)),
5857 }
5858 }
5859 r.text.font_features = Some(gpui::FontFeatures(std::sync::Arc::new(pairs)));
5860 }
5861 None => warn_once(
5862 diagnostics,
5863 "an OpenType FEATURE value was not understood (v1) — \
5864 `font-feature-settings` takes `\"tag\" <number|on|off>` pairs, \
5865 `font-variant-numeric` / `font-variant-ligatures` their keyword sets and \
5866 `font-kerning` `auto | normal | none`; all reach the shaper when they \
5867 parse",
5868 ),
5869 }
5870 }
5871 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5872 if name.0.as_ref() == "font-optical-sizing" =>
5873 {
5874 if !single_ident_is(&c.value, "auto") && !is_css_wide_keyword(&c.value) {
5875 warn_once(
5876 diagnostics,
5877 "`font-optical-sizing: none` is not applied (v1) — a variable font's \
5878 `opsz` axis is driven from the font size here, which is what `auto` (the \
5879 initial value, and what every browser does) asks for. There is no way to \
5880 switch it off",
5881 );
5882 }
5883 }
5884 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5885 if name.0.as_ref() == "font-variation-settings" =>
5886 {
5887 if single_ident_is(&c.value, "normal") || is_css_wide_keyword(&c.value) {
5888 return;
5889 }
5890 warn_once(
5891 diagnostics,
5892 "`font-variation-settings` is not applied (v1) — a face is selected through \
5893 the weight/width/slope model, not by axis value, so an arbitrary axis \
5894 (`wdth`, `slnt`, a custom one) cannot be instantiated. `font-weight` and \
5895 `font-style` do reach the axis the WWS model covers, and `opsz` is driven \
5896 from the font size",
5897 )
5898 }
5899 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5900 if matches!(name.0.as_ref(), "touch-action" | "will-change") => {}
5901 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5902 if name.0.as_ref() == "scroll-behavior" =>
5903 {
5904 match single_ident(&c.value, "scroll-behavior", diagnostics) {
5905 Some("auto") => x.scroll_smooth = Some(false),
5906 Some("smooth") => x.scroll_smooth = Some(true),
5907 _ => unsupported(diagnostics, "scroll-behavior"),
5908 }
5909 }
5910 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5911 if name.0.as_ref() == "contain" =>
5912 {
5913 if let Some((paint, size)) = contain(&c.value, diagnostics) {
5914 x.contain_paint = Some(paint);
5915 x.contain_size = Some(size);
5916 }
5917 }
5918 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5919 if name.0.as_ref() == "scrollbar-width" =>
5920 {
5921 if let Some(w) = scrollbar_width(&c.value, diagnostics) {
5922 x.scrollbar_width = Some(w);
5923 }
5924 }
5925 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5926 if name.0.as_ref() == "scrollbar-color" =>
5927 {
5928 if let Some(pair) = scrollbar_color(&c.value, diagnostics) {
5929 x.scrollbar_color = Some(pair);
5930 }
5931 }
5932 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5933 if matches!(
5934 name.0.as_ref(),
5935 "overscroll-behavior"
5936 | "overscroll-behavior-x"
5937 | "overscroll-behavior-y"
5938 | "overscroll-behavior-inline"
5939 | "overscroll-behavior-block"
5940 ) =>
5941 {
5942 let property = name.0.as_ref();
5943 if let Some(b) = overscroll(property, &c.value, diagnostics) {
5944 match property {
5945 "overscroll-behavior-x" | "overscroll-behavior-inline" => {
5946 x.overscroll_x = Some(b)
5947 }
5948 "overscroll-behavior-y" | "overscroll-behavior-block" => {
5949 x.overscroll_y = Some(b)
5950 }
5951 _ => {
5952 x.overscroll_x = Some(b);
5953 x.overscroll_y = Some(b);
5954 }
5955 }
5956 }
5957 }
5958 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5959 if name.0.as_ref() == "isolation" =>
5960 {
5961 if single_ident_is(&c.value, "isolate") {
5962 x.isolate = Some(true);
5963 } else if single_ident_is(&c.value, "auto") {
5964 x.isolate = Some(false);
5965 } else if !is_css_wide_keyword(&c.value) {
5966 unsupported(diagnostics, "isolation (expected `auto` or `isolate`)");
5967 }
5968 }
5969 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5970 if matches!(
5971 name.0.as_ref(),
5972 "border-collapse"
5973 | "border-spacing"
5974 | "caption-side"
5975 | "table-layout"
5976 | "empty-cells"
5977 ) =>
5978 {
5979 warn_once(
5980 diagnostics,
5981 "the table properties are not applied (v1) — `<table>` and friends lay out as \
5982 plain blocks; build tables out of flex rows or a grid track list, which both \
5983 render",
5984 )
5985 }
5986 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5987 if name.0.as_ref() == "clip" =>
5988 {
5989 if clip_rect_is_empty(&c.value) {
5991 r.visibility = Some(gpui::Visibility::Hidden);
5992 } else {
5993 warn_once(
5994 diagnostics,
5995 "a non-empty legacy `clip: rect()` is not applied (v1) — it is deprecated \
5996 in CSS too, and clipping a box to an arbitrary sub-rectangle needs a \
5997 content mask the paint path does not carry. `clip: rect(0,0,0,0)` (the \
5998 visually-hidden idiom) IS honoured, and `overflow: hidden` on a sized \
5999 box clips for real",
6000 );
6001 }
6002 }
6003 lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6007 if name
6008 .0
6009 .as_ref()
6010 .eq_ignore_ascii_case("-webkit-mask-composite") =>
6011 {
6012 use lightningcss::properties::custom::{Token, TokenOrValue};
6013 let first = c.value.0.iter().find_map(|t| match t {
6014 TokenOrValue::Token(Token::Ident(id)) => Some(id.as_ref()),
6015 _ => None,
6016 });
6017 x.mask_composite = Some(webkit_mask_compositing(first.unwrap_or("source-over")));
6018 advise_mask(x, diagnostics);
6019 }
6020 lightningcss::properties::custom::CustomPropertyName::Unknown(name) => {
6021 once(
6022 diagnostics,
6023 format!("property not mapped (v1): {}", name.0.as_ref()),
6024 );
6025 }
6026 },
6027 LetterSpacing(v) => {
6028 if let Some(px) = spacing_px(v) {
6029 r.text.letter_spacing = Some(gpui::px(px));
6030 }
6031 }
6032 WordSpacing(v) => {
6033 if let Some(px) = spacing_px(v) {
6034 r.text.word_spacing = Some(gpui::px(px));
6035 }
6036 }
6037 VerticalAlign(v) => {
6038 use lightningcss::properties::font::VerticalAlign as VA;
6039 use lightningcss::properties::font::VerticalAlignKeyword as VK;
6040 let block_level = matches!(
6044 r.display,
6045 Some(gpui::Display::Block | gpui::Display::Flex | gpui::Display::Grid)
6046 ) && x.inline_level != Some(true);
6047 if !matches!(v, VA::Keyword(VK::Baseline)) && !block_level {
6048 warn_once(
6049 diagnostics,
6050 "`vertical-align` is not applied (v1) — it aligns boxes inside a LINE box, \
6051 and taffy has no inline formatting context. `align-items` / `align-self` on \
6052 the flex parent is the equivalent that works",
6053 );
6054 }
6055 }
6056 TextIndent(v) => {
6057 if lp_definite(&v.value).is_none_or(|l| l != gpui::px(0.0).into()) {
6058 warn_once(
6059 diagnostics,
6060 "`text-indent` is not applied (v1) — there is no first-line concept in the shaper. `padding-left` indents the whole block",
6061 );
6062 }
6063 }
6064 ListStyle(v) => {
6065 use lightningcss::properties::list::ListStylePosition as P;
6066 match list_marker(&v.list_style_type) {
6067 Some(marker) => x.list_marker = Some(marker),
6068 None => advise_list_marker(diagnostics),
6069 }
6070 x.list_marker_inside = Some(matches!(v.position, P::Inside));
6071 }
6072 ListStyleType(v) => match list_marker(v) {
6073 Some(marker) => x.list_marker = Some(marker),
6074 None => advise_list_marker(diagnostics),
6075 },
6076 ListStyleImage(v) => {
6079 if !matches!(v, lightningcss::values::image::Image::None) {
6080 advise_list_marker(diagnostics);
6081 }
6082 }
6083 ListStylePosition(v) => {
6084 use lightningcss::properties::list::ListStylePosition as P;
6085 x.list_marker_inside = Some(matches!(v, P::Inside));
6086 }
6087 Resize(v) => {
6088 use lightningcss::properties::ui::Resize as R;
6089 if !matches!(v, R::None) {
6092 warn_once(
6093 diagnostics,
6094 "`resize` is not applied (v1) — there is no user-resize affordance on a gpui box. A drag handle has to be a real element with a pointer handler",
6095 );
6096 }
6097 }
6098 UserSelect(v, _) => {
6099 use crate::mapper::UserSelect as S;
6100 use lightningcss::properties::ui::UserSelect as U;
6101 x.user_select = Some(match v {
6102 U::Auto => S::Auto,
6103 U::None => S::None,
6104 U::Text => S::Text,
6105 U::All => S::All,
6106 U::Contain => {
6107 warn_once(
6108 diagnostics,
6109 "`user-select: contain` selects like `text` here: a selection that starts \
6110 inside the element is not kept inside it",
6111 );
6112 S::Text
6113 }
6114 });
6115 }
6116 AccentColor(c) => {
6117 use lightningcss::properties::ui::ColorOrAuto;
6118 x.accent_color = Some(match c {
6119 ColorOrAuto::Auto => None,
6120 ColorOrAuto::Color(c) => color(c),
6121 });
6122 }
6123 Appearance(a, _) => {
6124 x.appearance_none = Some(matches!(a, lightningcss::properties::ui::Appearance::None))
6125 }
6126 TabSize(..) => {}
6129 TextSizeAdjust(..) => {}
6131 ClipPath(v, _) => {
6134 if let Some(clip) = clip_path(v, diagnostics) {
6135 r.vn_clip_path = Some(clip);
6136 }
6137 }
6138 WordWrap(v) | OverflowWrap(v) => {
6139 use lightningcss::properties::text::OverflowWrap as OW;
6140 r.text.overflow_wrap = Some(match v {
6141 OW::Normal => gpui::OverflowWrap::Normal,
6142 OW::BreakWord => gpui::OverflowWrap::BreakWord,
6143 OW::Anywhere => gpui::OverflowWrap::Anywhere,
6144 });
6145 }
6146 WordBreak(v) => {
6147 use lightningcss::properties::text::WordBreak as WB;
6148 r.text.word_break = Some(match v {
6149 WB::Normal => gpui::WordBreak::Normal,
6150 WB::BreakAll => gpui::WordBreak::BreakAll,
6151 WB::KeepAll => gpui::WordBreak::KeepAll,
6152 WB::BreakWord => gpui::WordBreak::BreakWord,
6153 });
6154 }
6155 Hyphens(v, _) => {
6156 use lightningcss::properties::text::Hyphens as H;
6157 r.text.hyphens = Some(match v {
6158 H::None => gpui::Hyphens::None,
6159 H::Manual => gpui::Hyphens::Manual,
6160 H::Auto => {
6161 warn_once(
6162 diagnostics,
6163 "`hyphens: auto` hyphenates only at soft hyphens (`­`), as `manual` \
6164 does (v1) — there is no hyphenation dictionary",
6165 );
6166 gpui::Hyphens::Manual
6167 }
6168 });
6169 }
6170 ScrollMarginTop(_)
6171 | ScrollMarginBottom(_)
6172 | ScrollMarginLeft(_)
6173 | ScrollMarginRight(_)
6174 | ScrollMargin(_)
6175 | ScrollMarginBlock(_)
6176 | ScrollMarginInline(_)
6177 | ScrollMarginBlockStart(_)
6178 | ScrollMarginBlockEnd(_)
6179 | ScrollMarginInlineStart(_)
6180 | ScrollMarginInlineEnd(_)
6181 | ScrollPaddingTop(_)
6182 | ScrollPaddingBottom(_)
6183 | ScrollPaddingLeft(_)
6184 | ScrollPaddingRight(_)
6185 | ScrollPadding(_) => {}
6186 TextTransform(t) => {
6187 use crate::mapper::TextTransform as TT;
6188 use lightningcss::properties::text::TextTransformCase as C;
6189 x.text_transform = Some(match t.case {
6190 C::None => TT::None,
6191 C::Uppercase => TT::Uppercase,
6192 C::Lowercase => TT::Lowercase,
6193 C::Capitalize => TT::Capitalize,
6194 });
6195 }
6196 Unparsed(u) => {
6199 if !apply_unparsed(u, r, x, diagnostics) {
6200 once(
6201 diagnostics,
6202 format!(
6203 "`{}` value is still unresolved after var()/env() substitution (v1)",
6204 u.property_id.name()
6205 ),
6206 );
6207 }
6208 }
6209 Property::ViewTransitionName(name) => {
6210 use lightningcss::properties::transition::ViewTransitionName as N;
6211 x.view_transition_name = Some(match name {
6212 N::None => None,
6213 N::Auto => Some("auto".into()),
6214 N::Custom(ident) => Some(ident.0.as_ref().into()),
6215 });
6216 }
6217 Property::ViewTransitionClass(list) => {
6218 use lightningcss::values::ident::NoneOrCustomIdentList as L;
6219 x.view_transition_class = Some(match list {
6220 L::None => Rc::from([]),
6221 L::Idents(idents) => idents.iter().map(|i| Rc::from(i.0.as_ref())).collect(),
6222 });
6223 }
6224 Property::MixBlendMode(mode) => {
6225 use lightningcss::properties::effects::BlendMode;
6226 match mode {
6227 BlendMode::Normal => x.plus_lighter = Some(false),
6228 BlendMode::PlusLighter => x.plus_lighter = Some(true),
6229 _ => unsupported(
6230 diagnostics,
6231 "mix-blend-mode (only `normal`, and `plus-lighter` on view transition images)",
6232 ),
6233 }
6234 }
6235 other => {
6236 once(
6237 diagnostics,
6238 format!("property not mapped (v1): {}", prop_name(other)),
6239 );
6240 }
6241 }
6242}
6243
6244fn apply_unparsed(
6247 u: &lightningcss::properties::custom::UnparsedProperty,
6248 r: &mut StyleRefinement,
6249 x: &mut Extras,
6250 diagnostics: &mut Vec<String>,
6251) -> bool {
6252 let reset = initial_inset_sides(u.property_id.name(), &u.value);
6253 if reset != 0 {
6254 if reset & 0b0001 != 0 {
6255 r.inset.top = Some(Length::Auto);
6256 }
6257 if reset & 0b0010 != 0 {
6258 r.inset.right = Some(Length::Auto);
6259 }
6260 if reset & 0b0100 != 0 {
6261 r.inset.bottom = Some(Length::Auto);
6262 }
6263 if reset & 0b1000 != 0 {
6264 r.inset.left = Some(Length::Auto);
6265 }
6266 return true;
6267 }
6268 if matches!(u.property_id, PropertyId::BoxShadow(_))
6272 && matches!(single_ident_raw(&u.value), Some("none"))
6273 {
6274 r.box_shadow = Some(Vec::new());
6275 return true;
6276 }
6277 if matches!(u.property_id, PropertyId::TextShadow)
6278 && matches!(single_ident_raw(&u.value), Some("none" | "initial"))
6279 {
6280 r.text.text_shadow = Some(Vec::new());
6281 return true;
6282 }
6283 if matches!(u.property_id, PropertyId::ClipPath(_)) && !has_substitution(&u.value) {
6288 use lightningcss::properties::custom::{Token, TokenOrValue};
6289 match clip_path_path(&u.value) {
6290 Some(Ok(clip)) => {
6291 r.vn_clip_path = Some(clip);
6292 return true;
6293 }
6294 Some(Err(why)) => {
6295 once(
6296 diagnostics,
6297 format!(
6298 "`clip-path: path()` was dropped as invalid, as Chromium drops it: {why}"
6299 ),
6300 );
6301 return true;
6302 }
6303 None => {}
6304 }
6305 let what = u.value.0.iter().find_map(|t| match t {
6306 TokenOrValue::Function(f) => Some(format!("{}()", f.name.0.as_ref())),
6307 TokenOrValue::Token(Token::Function(name)) => Some(format!("{}()", name.as_ref())),
6308 _ => None,
6309 });
6310 clip_path_unsupported(diagnostics, what.as_deref().unwrap_or("this value"));
6311 return true;
6312 }
6313 if matches!(single_ident_raw(&u.value), Some("inherit")) {
6314 let corners = match u.property_id {
6315 PropertyId::BorderRadius(_) => RadiusInherit::ALL,
6316 PropertyId::BorderTopLeftRadius(_) => RadiusInherit::TOP_LEFT,
6317 PropertyId::BorderTopRightRadius(_) => RadiusInherit::TOP_RIGHT,
6318 PropertyId::BorderBottomRightRadius(_) => RadiusInherit::BOTTOM_RIGHT,
6319 PropertyId::BorderBottomLeftRadius(_) => RadiusInherit::BOTTOM_LEFT,
6320 _ => 0,
6321 };
6322 x.radius_inherit.write(corners, true);
6323 return true;
6324 }
6325 false
6326}
6327
6328fn presentation_name(p: &Property) -> Option<&'static str> {
6329 use Property::*;
6330 Some(match p {
6331 FillOpacity(_) => "fill-opacity",
6332 FillRule(_) => "fill-rule",
6333 StrokeOpacity(_) => "stroke-opacity",
6334 StrokeWidth(_) => "stroke-width",
6335 StrokeLinecap(_) => "stroke-linecap",
6336 StrokeLinejoin(_) => "stroke-linejoin",
6337 StrokeMiterlimit(_) => "stroke-miterlimit",
6338 StrokeDasharray(_) => "stroke-dasharray",
6339 StrokeDashoffset(_) => "stroke-dashoffset",
6340 ShapeRendering(_) => "shape-rendering",
6341 _ => return None,
6342 })
6343}
6344
6345fn presentation_value(name: &str, value: String) -> String {
6348 if name != "shape-rendering" {
6349 return value;
6350 }
6351 match value.to_ascii_lowercase().as_str() {
6352 "optimizespeed" => "optimizeSpeed".into(),
6353 "crispedges" => "crispEdges".into(),
6354 "geometricprecision" => "geometricPrecision".into(),
6355 _ => value,
6356 }
6357}
6358
6359fn set_presentation(list: &mut Vec<(&'static str, Rc<str>)>, name: &'static str, value: Rc<str>) {
6360 match list.iter_mut().find(|(n, _)| *n == name) {
6361 Some(slot) => slot.1 = value,
6362 None => list.push((name, value)),
6363 }
6364}
6365
6366fn svg_paint(
6367 p: &lightningcss::properties::svg::SVGPaint<'_>,
6368 what: &str,
6369 diagnostics: &mut Vec<String>,
6370) -> SvgPaint {
6371 use lightningcss::properties::svg::SVGPaint as P;
6372 match p {
6373 P::None => SvgPaint::None,
6374 P::Color(c) if is_current_color(c) => SvgPaint::Current,
6375 P::Color(c) => match color(c) {
6376 Some(c) => SvgPaint::Color(c),
6377 None => {
6378 unresolved_color(diagnostics, what);
6379 SvgPaint::Server
6380 }
6381 },
6382 P::Url { .. } | P::ContextFill | P::ContextStroke => SvgPaint::Server,
6385 }
6386}
6387
6388fn is_current_color(c: &lightningcss::values::color::CssColor) -> bool {
6389 matches!(c, lightningcss::values::color::CssColor::CurrentColor)
6390}
6391
6392fn apply_transform(
6393 list: &lightningcss::properties::transform::TransformList,
6394 r: &mut StyleRefinement,
6395 diagnostics: &mut Vec<String>,
6396) {
6397 use lightningcss::properties::transform::Transform as T;
6398 use lightningcss::values::percentage::NumberOrPercentage;
6399 const UNIT: [[f64; 2]; 2] = [[1.0, 0.0], [0.0, 1.0]];
6400 const ZERO: [[f64; 3]; 2] = [[0.0; 3]; 2];
6401 fn len(v: &LengthPercentage, axis: usize) -> Option<[f64; 3]> {
6402 match v {
6403 DimensionPercentage::Dimension(l) => {
6404 length_value_px(l).map(|p| [f64::from(p), 0.0, 0.0])
6405 }
6406 DimensionPercentage::Percentage(p) => {
6407 let mut row = [0.0; 3];
6408 row[axis + 1] = f64::from(p.0);
6409 Some(row)
6410 }
6411 DimensionPercentage::Calc(_) => {
6412 calc_dropped();
6413 None
6414 }
6415 }
6416 }
6417 fn factor(v: &NumberOrPercentage) -> f64 {
6418 f64::from(match v {
6419 NumberOrPercentage::Number(n) => *n,
6420 NumberOrPercentage::Percentage(p) => p.0,
6421 })
6422 }
6423 fn append(
6424 linear: &mut [[f64; 2]; 2],
6425 offset: &mut [[f64; 3]; 2],
6426 m: [[f64; 2]; 2],
6427 t: [[f64; 3]; 2],
6428 ) {
6429 let old = *linear;
6430 for row in 0..2 {
6431 for term in 0..3 {
6432 offset[row][term] += old[row][0] * t[0][term] + old[row][1] * t[1][term];
6433 }
6434 for column in 0..2 {
6435 linear[row][column] = old[row][0] * m[0][column] + old[row][1] * m[1][column];
6436 }
6437 }
6438 }
6439 fn slot(row: [f32; 3], axis: usize) -> Option<TransformLength> {
6440 let own = row[axis + 1];
6441 let cross = row[2 - axis];
6442 if cross != 0.0 || (row[0] != 0.0 && own != 0.0) {
6443 None
6444 } else if own != 0.0 {
6445 Some(TransformLength::Fraction(own))
6446 } else {
6447 Some(TransformLength::Pixels(row[0]))
6448 }
6449 }
6450 let mut linear = UNIT;
6451 let mut offset = ZERO;
6452 let mut authored_rotate = 0.0f64;
6453 let mut authored_scale = (1.0f64, 1.0f64);
6454 let mut affine = false;
6455 let mut dropped: Vec<&str> = Vec::new();
6456 for transform in &list.0 {
6457 let mut m = UNIT;
6458 let mut t = ZERO;
6459 match transform {
6460 T::Translate(a, b) | T::Translate3d(a, b, _) => {
6461 let (Some(x), Some(y)) = (len(a, 0), len(b, 1)) else {
6462 dropped.push("translate() with a calc() length");
6463 continue;
6464 };
6465 t = [x, y];
6466 if let T::Translate3d(_, _, z) = transform {
6467 if !matches!(css_length_px(z), Some(0.0)) {
6468 dropped.push("the Z axis of a 3D translate");
6469 }
6470 }
6471 }
6472 T::TranslateX(v) => {
6473 let Some(value) = len(v, 0) else {
6474 dropped.push("translateX() with a calc() length");
6475 continue;
6476 };
6477 t[0] = value;
6478 }
6479 T::TranslateY(v) => {
6480 let Some(value) = len(v, 1) else {
6481 dropped.push("translateY() with a calc() length");
6482 continue;
6483 };
6484 t[1] = value;
6485 }
6486 T::Rotate(a) | T::RotateZ(a) => {
6487 let angle = f64::from(a.to_radians());
6488 let (sin, cos) = angle.sin_cos();
6489 m = [[cos, -sin], [sin, cos]];
6490 authored_rotate += angle;
6491 }
6492 T::RotateX(a) | T::RotateY(a) if a.to_degrees() == 0.0 => {}
6493 T::RotateX(_) | T::RotateY(_) | T::Rotate3d(..) => {
6494 dropped.push("rotate3d()/rotateX()/rotateY()");
6495 continue;
6496 }
6497 T::Scale(a, b) | T::Scale3d(a, b, _) => {
6498 let (x, y) = (factor(a), factor(b));
6499 m = [[x, 0.0], [0.0, y]];
6500 authored_scale = (authored_scale.0 * x, authored_scale.1 * y);
6501 }
6502 T::ScaleX(value) => {
6503 let x = factor(value);
6504 m[0][0] = x;
6505 authored_scale.0 *= x;
6506 }
6507 T::ScaleY(value) => {
6508 let y = factor(value);
6509 m[1][1] = y;
6510 authored_scale.1 *= y;
6511 }
6512 T::ScaleZ(_) => {}
6513 T::Skew(a, b) => {
6514 m = [
6515 [1.0, f64::from(a.to_radians()).tan()],
6516 [f64::from(b.to_radians()).tan(), 1.0],
6517 ];
6518 affine |= a.to_degrees() != 0.0 || b.to_degrees() != 0.0;
6519 }
6520 T::SkewX(a) => {
6521 m[0][1] = f64::from(a.to_radians()).tan();
6522 affine |= a.to_degrees() != 0.0;
6523 }
6524 T::SkewY(a) => {
6525 m[1][0] = f64::from(a.to_radians()).tan();
6526 affine |= a.to_degrees() != 0.0;
6527 }
6528 T::Matrix(value) => {
6529 m = [
6530 [f64::from(value.a), f64::from(value.c)],
6531 [f64::from(value.b), f64::from(value.d)],
6532 ];
6533 t[0][0] = f64::from(value.e);
6534 t[1][0] = f64::from(value.f);
6535 affine = true;
6536 }
6537 T::Matrix3d(_) => {
6538 dropped.push("matrix3d()");
6539 continue;
6540 }
6541 T::Perspective(_) => {
6542 dropped.push("perspective()");
6543 continue;
6544 }
6545 T::TranslateZ(_) => {
6546 dropped.push("the Z axis of a 3D translate");
6547 continue;
6548 }
6549 }
6550 if m.iter()
6551 .flatten()
6552 .chain(t.iter().flatten())
6553 .any(|v| !v.is_finite())
6554 {
6555 dropped.push("a non-finite 2D transform");
6556 continue;
6557 }
6558 append(&mut linear, &mut offset, m, t);
6559 }
6560 let (sin, cos) = authored_rotate.sin_cos();
6561 let expected = [
6562 [cos * authored_scale.0, -sin * authored_scale.1],
6563 [sin * authored_scale.0, cos * authored_scale.1],
6564 ];
6565 affine |= linear
6566 .iter()
6567 .flatten()
6568 .zip(expected.iter().flatten())
6569 .any(|(a, b)| (a - b).abs() > 1e-6 * a.abs().max(b.abs()).max(1.0));
6570 let (mut rotate, mut scale, mut shear) = (
6571 authored_rotate as f32,
6572 (authored_scale.0 as f32, authored_scale.1 as f32),
6573 0.0f32,
6574 );
6575 if affine {
6576 let [[a, c], [b, d]] = linear;
6577 let sx = a.hypot(b);
6578 if sx != 0.0 {
6579 rotate = b.atan2(a) as f32;
6580 scale = (sx as f32, ((a * d - b * c) / sx) as f32);
6581 shear = ((a * c + b * d) / sx) as f32;
6582 } else {
6583 rotate = (-c).atan2(d) as f32;
6584 scale = (0.0, c.hypot(d) as f32);
6585 }
6586 }
6587 let basis = offset.map(|row| row.map(|value| value as f32));
6588 let (x, y) = (slot(basis[0], 0), slot(basis[1], 1));
6589 let origin = r
6590 .vn_transform
6591 .map(|t| t.origin)
6592 .unwrap_or(TransformSpec::CENTRE_ORIGIN);
6593 let mut spec = TransformSpec {
6594 translate: (
6595 x.unwrap_or(TransformLength::ZERO),
6596 y.unwrap_or(TransformLength::ZERO),
6597 ),
6598 rotate,
6599 scale,
6600 shear,
6601 origin,
6602 translation_basis: (x.is_none() || y.is_none()).then_some(basis),
6603 };
6604 if [rotate, scale.0, scale.1, shear]
6605 .iter()
6606 .chain(basis.iter().flatten())
6607 .any(|v| !v.is_finite())
6608 {
6609 dropped.push("an out-of-range 2D composition");
6610 spec = TransformSpec {
6611 origin,
6612 ..TransformSpec::IDENTITY
6613 };
6614 }
6615 r.vn_transform = Some(spec);
6616 if !dropped.is_empty() {
6617 dropped.sort_unstable();
6618 dropped.dedup();
6619 once(diagnostics, format!("`transform` supports ordered 2D translate(), rotate(), scale(), skew(), matrix() and `transform-origin` at paint time — dropped {}", dropped.join(", ")));
6620 }
6621}
6622pub fn transform_css(spec: TransformSpec) -> String {
6623 if spec.is_identity() {
6624 return "none".into();
6625 }
6626 let mut parts = Vec::new();
6627 let len = |value: TransformLength| match value {
6628 TransformLength::Pixels(value) => format!("{value}px"),
6629 TransformLength::Fraction(value) => format!("{}%", value * 100.0),
6630 };
6631 if let Some([[px, width, cross_x], [py, cross_y, height]]) = spec.translation_basis {
6632 if px != 0.0 || py != 0.0 {
6633 parts.push(format!("translate({px}px, {py}px)"));
6634 }
6635 if width != 0.0 || height != 0.0 {
6636 parts.push(format!(
6637 "translate({}%, {}%)",
6638 width * 100.0,
6639 height * 100.0
6640 ));
6641 }
6642 if cross_x != 0.0 {
6643 parts.push(format!(
6644 "rotate(-90deg) translateY({}%) rotate(90deg)",
6645 cross_x * 100.0
6646 ));
6647 }
6648 if cross_y != 0.0 {
6649 parts.push(format!(
6650 "rotate(90deg) translateX({}%) rotate(-90deg)",
6651 cross_y * 100.0
6652 ));
6653 }
6654 } else if !spec.translate.0.is_zero() || !spec.translate.1.is_zero() {
6655 parts.push(format!(
6656 "translate({}, {})",
6657 len(spec.translate.0),
6658 len(spec.translate.1)
6659 ));
6660 }
6661 if spec.rotate != 0.0 {
6662 parts.push(format!("rotate({}deg)", spec.rotate.to_degrees()));
6663 }
6664 if spec.shear != 0.0 {
6665 parts.push(format!(
6666 "matrix({},0,{},{},0,0)",
6667 spec.scale.0, spec.shear, spec.scale.1
6668 ));
6669 } else if spec.scale != (1.0, 1.0) {
6670 parts.push(format!("scale({}, {})", spec.scale.0, spec.scale.1));
6671 }
6672 parts.join(" ")
6673}
6674fn apply_backdrop_filter(
6675 list: &lightningcss::properties::effects::FilterList,
6676 r: &mut StyleRefinement,
6677 diagnostics: &mut Vec<String>,
6678) {
6679 use lightningcss::properties::effects::{Filter, FilterList};
6680
6681 let filters = match list {
6682 FilterList::None => {
6683 r.backdrop_blur = Some(px(0.0));
6684 return;
6685 }
6686 FilterList::Filters(filters) => filters,
6687 };
6688
6689 let mut blur_radius = None;
6690 let mut others = Vec::new();
6691 for filter in filters.iter() {
6692 match filter {
6693 Filter::Blur(length) => match css_length_px(length) {
6694 Some(radius) if blur_radius.is_none() => blur_radius = Some(radius.max(0.0)),
6695 Some(_) => others.push("a second blur()"),
6696 None => others.push("blur() with a non-absolute length"),
6697 },
6698 Filter::Brightness(_) => others.push("brightness()"),
6699 Filter::Contrast(_) => others.push("contrast()"),
6700 Filter::Grayscale(_) => others.push("grayscale()"),
6701 Filter::HueRotate(_) => others.push("hue-rotate()"),
6702 Filter::Invert(_) => others.push("invert()"),
6703 Filter::Opacity(_) => others.push("opacity()"),
6704 Filter::Saturate(_) => others.push("saturate()"),
6705 Filter::Sepia(_) => others.push("sepia()"),
6706 Filter::DropShadow(_) => others.push("drop-shadow()"),
6707 Filter::Url(_) => others.push("url() SVG filters"),
6708 }
6709 }
6710
6711 if let Some(radius) = blur_radius {
6712 r.backdrop_blur = Some(px(radius));
6713 }
6714 if !others.is_empty() {
6715 once(
6716 diagnostics,
6717 format!(
6718 "backdrop-filter: only blur() is implemented (v1) — dropped {}",
6719 others.join(", ")
6720 ),
6721 );
6722 }
6723}
6724
6725fn apply_filter(
6726 list: &lightningcss::properties::effects::FilterList,
6727 x: &mut Extras,
6728 diagnostics: &mut Vec<String>,
6729) {
6730 use lightningcss::properties::effects::{Filter, FilterList};
6731
6732 let filters = match list {
6733 FilterList::None => {
6734 x.blur = Some(0.0);
6735 x.drop_shadow = None;
6736 x.filter_url = None;
6737 return;
6738 }
6739 FilterList::Filters(filters) => filters,
6740 };
6741
6742 let mut blur_radius = None;
6743 let mut drop_shadow = None;
6744 let mut filter_url = None;
6745 let mut others = Vec::new();
6746 for filter in filters.iter() {
6747 match filter {
6748 Filter::Blur(length) => match css_length_px(length) {
6749 Some(radius) if blur_radius.is_none() => blur_radius = Some(radius.max(0.0)),
6750 Some(_) => others.push("a second blur()"),
6751 None => others.push("blur() with a non-absolute length"),
6752 },
6753 Filter::Brightness(_) => others.push("brightness()"),
6754 Filter::Contrast(_) => others.push("contrast()"),
6755 Filter::Grayscale(_) => others.push("grayscale()"),
6756 Filter::HueRotate(_) => others.push("hue-rotate()"),
6757 Filter::Invert(_) => others.push("invert()"),
6758 Filter::Opacity(_) => others.push("opacity()"),
6759 Filter::Saturate(_) => others.push("saturate()"),
6760 Filter::Sepia(_) => others.push("sepia()"),
6761 Filter::DropShadow(shadow) => match drop_shadow_of(shadow) {
6762 Some(s) if drop_shadow.is_none() => drop_shadow = Some(s),
6763 Some(_) => others.push("a second drop-shadow()"),
6764 None => others.push("drop-shadow() with a non-absolute length"),
6765 },
6766 Filter::Url(url) if filters.len() == 1 && url.url.starts_with('#') => {
6767 filter_url = Some(Rc::from(url.url.as_ref()));
6768 }
6769 Filter::Url(_) => others.push("external or chained url() SVG filters"),
6770 }
6771 }
6772
6773 x.blur = Some(blur_radius.unwrap_or(0.0));
6774 x.drop_shadow = drop_shadow;
6775 x.filter_url = filter_url;
6776
6777 if !others.is_empty() {
6778 once(
6779 diagnostics,
6780 format!(
6781 "`filter`: supported functions are blur(), drop-shadow(), and a single \
6782 same-document SVG feColorMatrix URL. Blur and drop-shadow require the \
6783 painted shape described by the render-side advisory — dropped {}",
6784 others.join(", ")
6785 ),
6786 );
6787 }
6788}
6789
6790fn drop_shadow_of(shadow: &lightningcss::properties::effects::DropShadow) -> Option<DropShadow> {
6791 Some(DropShadow {
6792 dx: css_length_px(&shadow.x_offset)?,
6793 dy: css_length_px(&shadow.y_offset)?,
6794 blur: css_length_px(&shadow.blur)?.max(0.0),
6795 color: color(&shadow.color),
6798 })
6799}
6800
6801const SIDE_TOP: u8 = 1;
6802const SIDE_RIGHT: u8 = 2;
6803const SIDE_BOTTOM: u8 = 4;
6804const SIDE_LEFT: u8 = 8;
6805const SIDES_ALL: u8 = SIDE_TOP | SIDE_RIGHT | SIDE_BOTTOM | SIDE_LEFT;
6806
6807fn set_border_style(
6808 r: &mut StyleRefinement,
6809 s: LineStyle,
6810 sides: u8,
6811 diagnostics: &mut Vec<String>,
6812) {
6813 if matches!(s, LineStyle::None | LineStyle::Hidden) {
6814 let zero: AbsoluteLength = px(0.0).into();
6815 if sides & SIDE_TOP != 0 {
6816 r.border_widths.top = Some(zero);
6817 }
6818 if sides & SIDE_RIGHT != 0 {
6819 r.border_widths.right = Some(zero);
6820 }
6821 if sides & SIDE_BOTTOM != 0 {
6822 r.border_widths.bottom = Some(zero);
6823 }
6824 if sides & SIDE_LEFT != 0 {
6825 r.border_widths.left = Some(zero);
6826 }
6827 return;
6828 }
6829 r.border_style = Some(match s {
6830 LineStyle::Dashed => gpui::BorderStyle::Dashed,
6831 LineStyle::Solid => gpui::BorderStyle::Solid,
6832 _ => {
6833 unsupported(
6834 diagnostics,
6835 "border-style (dotted/double/groove/ridge/inset/outset render as solid)",
6836 );
6837 gpui::BorderStyle::Solid
6838 }
6839 });
6840}
6841
6842fn lp_definite_of_lpa(v: &LengthPercentageOrAuto) -> Option<DefiniteLength> {
6843 match v {
6844 LengthPercentageOrAuto::LengthPercentage(lp) => lp_definite(lp),
6845 LengthPercentageOrAuto::Auto => None,
6846 }
6847}
6848
6849fn overflow(k: OverflowKeyword) -> Overflow {
6850 match k {
6851 OverflowKeyword::Hidden | OverflowKeyword::Clip => Overflow::Hidden,
6852 OverflowKeyword::Scroll | OverflowKeyword::Auto => Overflow::Scroll,
6853 OverflowKeyword::Visible => Overflow::Visible,
6854 }
6855}
6856
6857fn overflow_keyword(axis: Option<Overflow>, declared: Option<OverflowKeyword>) -> OverflowKeyword {
6858 use OverflowKeyword as K;
6859 match axis {
6860 None | Some(Overflow::Visible) => K::Visible,
6861 Some(Overflow::Clip) => K::Clip,
6862 Some(Overflow::Hidden) if declared == Some(K::Clip) => K::Clip,
6863 Some(Overflow::Hidden) => K::Hidden,
6864 Some(Overflow::Scroll) if declared == Some(K::Auto) => K::Auto,
6865 Some(Overflow::Scroll) => K::Scroll,
6866 }
6867}
6868
6869pub(crate) fn compute_overflow(r: &mut StyleRefinement, x: &mut Extras) {
6870 use OverflowKeyword as K;
6871 if x.contain_paint == Some(true) {
6872 if overflow_keyword(r.overflow.x, x.overflow_x) == K::Visible {
6873 r.overflow.x = Some(overflow(K::Clip));
6874 x.overflow_x = Some(K::Clip);
6875 }
6876 if overflow_keyword(r.overflow.y, x.overflow_y) == K::Visible {
6877 r.overflow.y = Some(overflow(K::Clip));
6878 x.overflow_y = Some(K::Clip);
6879 }
6880 }
6881 let kx = overflow_keyword(r.overflow.x, x.overflow_x);
6882 let ky = overflow_keyword(r.overflow.y, x.overflow_y);
6883 let plain = |k: K| matches!(k, K::Visible | K::Clip);
6884 if plain(kx) == plain(ky) {
6885 return;
6886 }
6887 let computed = |k: K| match k {
6888 K::Visible => K::Auto,
6889 K::Clip => K::Hidden,
6890 k => k,
6891 };
6892 if plain(kx) {
6893 r.overflow.x = Some(overflow(computed(kx)));
6894 x.overflow_x = Some(computed(kx));
6895 } else {
6896 r.overflow.y = Some(overflow(computed(ky)));
6897 x.overflow_y = Some(computed(ky));
6898 }
6899}
6900
6901impl Extras {
6902 pub const CONTAIN_WIDTH: u8 = 1;
6903 pub const CONTAIN_HEIGHT: u8 = 2;
6904
6905 pub fn overflow_names(&self, base: &StyleRefinement) -> [&'static str; 2] {
6906 let name = |k: OverflowKeyword| match k {
6907 OverflowKeyword::Visible => "visible",
6908 OverflowKeyword::Hidden => "hidden",
6909 OverflowKeyword::Clip => "clip",
6910 OverflowKeyword::Scroll => "scroll",
6911 OverflowKeyword::Auto => "auto",
6912 };
6913 [
6914 name(overflow_keyword(base.overflow.x, self.overflow_x)),
6915 name(overflow_keyword(base.overflow.y, self.overflow_y)),
6916 ]
6917 }
6918}
6919
6920fn border_width_px(w: &lightningcss::properties::border::BorderSideWidth) -> Option<f32> {
6921 use lightningcss::properties::border::BorderSideWidth as W;
6922 match w {
6923 W::Length(l) => css_length_px(l),
6924 W::Thin => Some(1.0),
6925 W::Medium => Some(3.0),
6926 W::Thick => Some(5.0),
6927 }
6928}
6929
6930fn prop_name(p: &Property) -> String {
6931 let d = format!("{p:?}");
6932 d.split(['(', ' ', '{']).next().unwrap_or("?").to_string()
6933}
6934
6935#[cfg(test)]
6936mod tests {
6937 use super::*;
6938
6939 fn map(body: &str) -> (StyleRefinement, Vec<String>) {
6940 let mut diagnostics = Vec::new();
6941 let r = parse_inline(body, &mut diagnostics);
6942 (r, diagnostics)
6943 }
6944
6945 fn map_full(body: &str) -> (StyleRefinement, Extras, Vec<String>) {
6946 let mut diagnostics = Vec::new();
6947 let (refinement, _, extras) = parse_inline_full(body, &mut diagnostics);
6948 (refinement, extras, diagnostics)
6949 }
6950
6951 fn clean(body: &str) -> StyleRefinement {
6952 let (r, d) = map(body);
6953 assert!(d.is_empty(), "{body:?} produced {d:?}");
6954 r
6955 }
6956
6957 #[test]
6958 fn overflow_longhands_set_one_axis_each() {
6959 let r = clean("overflow-x: hidden");
6960 assert_eq!(r.overflow.x, Some(Overflow::Hidden));
6961 assert_eq!(r.overflow.y, None, "overflow-x must not touch the y axis");
6962
6963 let r = clean("overflow-y: scroll");
6964 assert_eq!(r.overflow.y, Some(Overflow::Scroll));
6965 assert_eq!(r.overflow.x, None);
6966
6967 assert_eq!(clean("overflow-y: auto").overflow.y, Some(Overflow::Scroll));
6968 assert_eq!(
6969 clean("overflow-x: visible").overflow.x,
6970 Some(Overflow::Visible)
6971 );
6972 }
6973
6974 #[test]
6975 fn a_longhand_after_the_shorthand_wins_on_its_axis_only() {
6976 let r = clean("overflow: hidden; overflow-y: scroll");
6977 assert_eq!(r.overflow.x, Some(Overflow::Hidden));
6978 assert_eq!(r.overflow.y, Some(Overflow::Scroll));
6979 }
6980
6981 fn computed_overflow(body: &str) -> (StyleRefinement, [&'static str; 2]) {
6982 let (mut r, mut x, d) = map_full(body);
6983 assert!(d.is_empty(), "{body:?} produced {d:?}");
6984 compute_overflow(&mut r, &mut x);
6985 let names = x.overflow_names(&r);
6986 (r, names)
6987 }
6988
6989 #[test]
6990 fn visible_beside_a_scrolling_axis_computes_to_auto() {
6991 let (r, names) = computed_overflow("overflow-y: auto");
6992 assert_eq!(names, ["auto", "auto"]);
6993 assert_eq!(
6994 r.overflow.x,
6995 Some(Overflow::Scroll),
6996 "x scrolls too, it is not just clipped"
6997 );
6998 assert_eq!(r.overflow.y, Some(Overflow::Scroll));
6999
7000 let (r, names) = computed_overflow("overflow-x: hidden");
7001 assert_eq!(names, ["hidden", "auto"]);
7002 assert_eq!(r.overflow.y, Some(Overflow::Scroll));
7003
7004 assert_eq!(
7005 computed_overflow("overflow-x: scroll").1,
7006 ["scroll", "auto"]
7007 );
7008 assert_eq!(computed_overflow("overflow: auto").1, ["auto", "auto"]);
7009 assert_eq!(
7010 computed_overflow("overflow: hidden scroll").1,
7011 ["hidden", "scroll"]
7012 );
7013 }
7014
7015 #[test]
7016 fn clip_beside_a_scrolling_axis_computes_to_hidden_and_beside_visible_stays() {
7017 assert_eq!(
7018 computed_overflow("overflow-x: clip; overflow-y: auto").1,
7019 ["hidden", "auto"]
7020 );
7021 let (r, names) = computed_overflow("overflow-x: clip");
7022 assert_eq!(names, ["clip", "visible"]);
7023 assert_eq!(r.overflow.y, None);
7024 assert_eq!(computed_overflow("overflow: clip").1, ["clip", "clip"]);
7025 assert_eq!(computed_overflow("color: red").1, ["visible", "visible"]);
7026 }
7027
7028 #[test]
7029 fn the_refinement_decides_and_the_keyword_only_qualifies_it() {
7030 let (mut base, mut x, _) = map_full("color: red");
7031 x.refine(&map_full("overflow-y: auto").1);
7032 compute_overflow(&mut base, &mut x);
7033 assert_eq!(x.overflow_names(&base), ["visible", "visible"]);
7034 assert_eq!(base.overflow.x, None);
7035 }
7036
7037 #[test]
7038 fn gap_longhands_map_to_the_matching_axis() {
7039 let r = clean("row-gap: 4px; column-gap: 8px");
7040 assert_eq!(r.gap.height, Some(px(4.0).into()));
7041 assert_eq!(r.gap.width, Some(px(8.0).into()));
7042 }
7043
7044 #[test]
7045 fn border_style_none_computes_the_widths_to_zero() {
7046 let r = clean("border: 3px solid red; border-style: none");
7047 let zero: AbsoluteLength = px(0.0).into();
7048 assert_eq!(r.border_widths.top, Some(zero));
7049 assert_eq!(r.border_widths.right, Some(zero));
7050 assert_eq!(r.border_widths.bottom, Some(zero));
7051 assert_eq!(r.border_widths.left, Some(zero));
7052 }
7053
7054 #[test]
7055 fn border_style_none_on_one_side_leaves_the_others() {
7056 let zero: AbsoluteLength = px(0.0).into();
7057 let one: AbsoluteLength = px(1.0).into();
7058 for body in [
7059 "border: 1px solid red; border-bottom: none",
7060 "border: 1px solid red; border-bottom: 0",
7061 "border: 1px solid red; border-bottom-style: none",
7062 "border: 1px solid red; border-style: solid solid none",
7063 ] {
7064 let r = clean(body);
7065 assert_eq!(r.border_widths.bottom, Some(zero), "{body}");
7066 assert_eq!(r.border_widths.top, Some(one), "{body}");
7067 assert_eq!(r.border_widths.right, Some(one), "{body}");
7068 assert_eq!(r.border_widths.left, Some(one), "{body}");
7069 assert_eq!(r.border_style, Some(gpui::BorderStyle::Solid), "{body}");
7070 }
7071 let r = clean("border-right: none");
7072 assert_eq!(r.border_widths.right, Some(zero));
7073 assert_eq!(r.border_widths.top, None);
7074 }
7075
7076 #[test]
7077 fn border_style_dashed_and_solid_for_the_rest() {
7078 assert_eq!(
7079 clean("border-style: dashed").border_style,
7080 Some(gpui::BorderStyle::Dashed)
7081 );
7082 let (r, _) = map("border-style: dotted");
7083 assert_eq!(r.border_style, Some(gpui::BorderStyle::Solid));
7084 }
7085
7086 #[test]
7087 fn corner_radius_longhands() {
7088 let r = clean("border-top-left-radius: 8px; border-bottom-right-radius: 2px");
7089 assert_eq!(r.corner_radii.top_left, Some(px(8.0).into()));
7090 assert_eq!(r.corner_radii.bottom_right, Some(px(2.0).into()));
7091 assert_eq!(r.corner_radii.top_right, None);
7092 assert_eq!(r.vn_corner_radii.top_left, Some(None));
7093 assert_eq!(r.vn_corner_radii.top_right, None);
7094 }
7095
7096 #[test]
7097 fn relative_and_elliptical_radii_resolve_at_paint() {
7098 let half = gpui::VnCornerRadius {
7099 x: relative(0.5),
7100 y: relative(0.5),
7101 };
7102 let r = clean("border-radius: 50%");
7103 for (length, relative) in [
7104 (r.corner_radii.top_left, r.vn_corner_radii.top_left),
7105 (r.corner_radii.top_right, r.vn_corner_radii.top_right),
7106 (r.corner_radii.bottom_right, r.vn_corner_radii.bottom_right),
7107 (r.corner_radii.bottom_left, r.vn_corner_radii.bottom_left),
7108 ] {
7109 assert_eq!(length, Some(px(0.).into()));
7110 assert_eq!(relative, Some(Some(half)));
7111 }
7112
7113 let r = clean("border-top-left-radius: calc(50% - 2px)");
7114 let calc = DefiniteLength::Calc {
7115 fraction: 0.5,
7116 pixels: px(-2.),
7117 };
7118 assert_eq!(
7119 r.vn_corner_radii.top_left,
7120 Some(Some(gpui::VnCornerRadius { x: calc, y: calc }))
7121 );
7122
7123 let r = clean("border-radius: 10px / 20px");
7124 assert_eq!(
7125 r.vn_corner_radii.bottom_left,
7126 Some(Some(gpui::VnCornerRadius {
7127 x: px(10.).into(),
7128 y: px(20.).into()
7129 }))
7130 );
7131
7132 let r = clean("border-radius: 6px / 6px");
7133 assert_eq!(r.corner_radii.top_right, Some(px(6.).into()));
7134 assert_eq!(r.vn_corner_radii.top_right, Some(None));
7135 }
7136
7137 #[test]
7138 fn flex_shorthand_fills_all_three_fields() {
7139 let r = clean("flex: 1 1 0%");
7140 assert_eq!(r.flex_grow, Some(1.0));
7141 assert_eq!(r.flex_shrink, Some(1.0));
7142 assert_eq!(r.flex_basis, Some(Length::Definite(relative(0.0))));
7143
7144 let r = clean("flex: none");
7145 assert_eq!(r.flex_grow, Some(0.0));
7146 assert_eq!(r.flex_shrink, Some(0.0));
7147 assert_eq!(r.flex_basis, Some(Length::Auto));
7148 }
7149
7150 #[test]
7151 fn order_reaches_the_layout_in_every_spelling() {
7152 assert_eq!(clean("order: -3").vn_order, Some(-3));
7153 assert_eq!(clean("-webkit-order: 2").vn_order, Some(2));
7154 let mut d = Vec::new();
7155 let vars = crate::vars::resolve(
7156 &Rc::new(Vars::default()),
7157 &[&("--o".to_string(), "7".to_string())],
7158 &crate::Env::default(),
7159 &mut d,
7160 );
7161 let mut r = StyleRefinement::default();
7162 apply_dynamic(
7163 "order",
7164 "var(--o)",
7165 &vars,
7166 &crate::Env::default(),
7167 &mut r,
7168 &mut Extras::default(),
7169 &mut d,
7170 );
7171 assert!(d.is_empty(), "{d:?}");
7172 assert_eq!(r.vn_order, Some(7));
7173 }
7174
7175 fn rgb8(c: Option<Hsla>) -> [u8; 4] {
7176 let c = gpui::Rgba::from(c.expect("a concrete colour"));
7177 [c.r, c.g, c.b, c.a].map(|v| (v * 255.0).round() as u8)
7178 }
7179
7180 #[test]
7181 fn css_color_4_and_5_functions_compute_to_srgb() {
7182 let text = |value: &str| rgb8(clean(&format!("color: {value}")).text.color);
7183 assert_eq!(text("oklch(62.8% 0.2577 29.23)"), [255, 0, 0, 255]);
7184 assert_eq!(text("oklab(0.5 0 0)"), [99, 99, 99, 255]);
7185 assert_eq!(text("lab(54.29% 80.82 69.91)"), [255, 0, 0, 255]);
7186 assert_eq!(text("lch(54.29% 106.84 40.85 / 50%)"), [255, 0, 0, 128]);
7187 assert_eq!(text("hwb(120 0% 0%)"), [0, 255, 0, 255]);
7188 assert_eq!(text("color(srgb 0 0.5 1)"), [0, 128, 255, 255]);
7189 assert_eq!(
7190 text("color(srgb-linear 0.2158 0.2158 0.2158)"),
7191 [128, 128, 128, 255]
7192 );
7193 assert_eq!(text("color-mix(in srgb, red, blue)"), [128, 0, 128, 255]);
7194 assert_eq!(
7195 text("color-mix(in srgb, red 25%, transparent)"),
7196 [255, 0, 0, 64]
7197 );
7198 assert_eq!(text("rgb(from #ff0000 r g 255)"), [255, 0, 255, 255]);
7199 assert_eq!(text("oklch(from #00ff00 l c h / 0.5)"), [0, 255, 0, 128]);
7200 }
7201
7202 #[test]
7203 fn a_wide_gamut_colour_is_clipped_into_srgb() {
7204 let [r, g, b, _] = rgb8(clean("color: color(display-p3 1 0 0)").text.color);
7205 assert!(r == 255 && g < 40 && b < 40, "{r} {g} {b}");
7206 let [r, g, b, _] = rgb8(clean("color: oklch(90% 0.4 145)").text.color);
7207 assert!(
7208 g > r && g > b && g > 220,
7209 "a too-vivid green stays green: {r} {g} {b}"
7210 );
7211 }
7212
7213 #[test]
7214 fn every_colour_valued_property_takes_a_css_color_4_value() {
7215 let red = "oklch(62.8% 0.2577 29.23)";
7216 let solid = |r: &StyleRefinement| match &r.background {
7217 Some(gpui::Fill::Color(bg)) => bg.as_solid(),
7218 _ => None,
7219 };
7220 let want = [255, 0, 0, 255];
7221 assert_eq!(
7222 rgb8(solid(&clean(&format!("background-color: {red}")))),
7223 want
7224 );
7225 assert_eq!(
7226 rgb8(clean(&format!("border-color: {red}")).border_color),
7227 want
7228 );
7229 assert_eq!(
7230 rgb8(
7231 clean(&format!("border-left: 1px solid {red}"))
7232 .vn_border_colors
7233 .left
7234 .flatten()
7235 ),
7236 want
7237 );
7238 let outline = clean(&format!("outline: 2px solid {red}"))
7239 .vn_outline
7240 .expect("ring");
7241 assert_eq!(rgb8(Some(outline.color)), want);
7242 let shadow = clean(&format!("box-shadow: 0 0 4px {red}"))
7243 .box_shadow
7244 .expect("shadow");
7245 assert_eq!(rgb8(Some(shadow[0].color)), want);
7246 let decoration = clean(&format!("text-decoration: underline {red}"))
7247 .text
7248 .underline
7249 .expect("line");
7250 assert_eq!(rgb8(decoration.color), want);
7251
7252 let (x, d) = extras(&format!(
7253 "accent-color: {red}; fill: {red}; overflow: auto; scrollbar-color: {red} lab(0% 0 0)"
7254 ));
7255 assert!(d.is_empty(), "{d:?}");
7256 assert_eq!(rgb8(x.accent_color.flatten()), want);
7257 let Some(SvgPaint::Color(fill)) = x.fill else {
7258 panic!("{:?}", x.fill)
7259 };
7260 assert_eq!(rgb8(Some(fill)), want);
7261 let (thumb, track) = x.scrollbar_color.expect("pair");
7262 assert_eq!(
7263 (rgb8(Some(thumb)), rgb8(Some(track))),
7264 (want, [0, 0, 0, 255])
7265 );
7266
7267 let (x, d) = extras(&format!(
7268 "background-image: linear-gradient({red}, color-mix(in oklab, {red}, {red}))"
7269 ));
7270 assert!(d.is_empty(), "{d:?}");
7271 assert!(x.background_images.is_some_and(|l| !l.is_empty()));
7272 }
7273
7274 #[test]
7275 fn scroll_behavior_is_carried_for_the_scroller_and_a_later_auto_takes_it_back() {
7276 let (x, d) = extras("scroll-behavior: smooth");
7277 assert_eq!((x.scroll_smooth, d.len()), (Some(true), 0));
7278 let (x, d) = extras("scroll-behavior: smooth; scroll-behavior: auto");
7279 assert_eq!((x.scroll_smooth, d.len()), (Some(false), 0));
7280 let (x, d) = extras("scroll-behavior: slowly");
7281 assert_eq!((x.scroll_smooth, d.len()), (None, 1));
7282 }
7283
7284 #[test]
7285 fn object_position_is_a_fraction_of_the_free_space_plus_an_offset() {
7286 let at = |body: &str| {
7287 let p = clean(body).vn_object_position.expect("mapped");
7288 (
7289 p.x_fraction,
7290 f32::from(p.x_offset),
7291 p.y_fraction,
7292 f32::from(p.y_offset),
7293 )
7294 };
7295 assert_eq!(at("object-position: left"), (0.0, 0.0, 0.5, 0.0));
7296 assert_eq!(at("object-position: 25% 10px"), (0.25, 0.0, 0.0, 10.0));
7297 assert_eq!(
7298 at("object-position: right 10px bottom 20%"),
7299 (1.0, -10.0, 0.8, 0.0)
7300 );
7301 assert_eq!(at("object-position: top right"), (1.0, 0.0, 0.0, 0.0));
7302 assert_eq!(
7303 at("object-position: calc(50% + 4px) center"),
7304 (0.5, 4.0, 0.5, 0.0)
7305 );
7306 let (r, d) = map("object-position: 10px sideways");
7307 assert_eq!(r.vn_object_position, None);
7308 assert_eq!(d.len(), 1, "{d:?}");
7309 }
7310
7311 #[test]
7312 fn grid_cols_maps_tailwinds_repeat_minmax() {
7313 let r = clean("grid-template-columns: repeat(3, minmax(0, 1fr))");
7314 assert_eq!(
7315 r.grid_cols,
7316 Some(gpui::GridTemplate {
7317 repeat: 3,
7318 min_size: gpui::GridTemplateMinSize::Zero,
7319 })
7320 );
7321 let r = clean("grid-template-rows: repeat(2, minmax(0, 1fr))");
7322 assert_eq!(r.grid_rows.map(|t| t.repeat), Some(2));
7323 }
7324
7325 #[test]
7326 fn an_arbitrary_track_list_becomes_an_explicit_track_list() {
7327 use gpui::{GridTrack, GridTrackSize as G};
7328 let r = clean("grid-template-columns: 200px 1fr");
7329 assert_eq!(r.grid_cols, None);
7330 assert_eq!(
7331 r.vn_grid_cols,
7332 Some(vec![GridTrack::fixed(G::Px(200.0)), GridTrack::fr(1.0)])
7333 );
7334 assert_eq!(
7335 clean("grid-template-columns: 1fr auto").vn_grid_cols,
7336 Some(vec![GridTrack::fr(1.0), GridTrack::fixed(G::Auto)])
7337 );
7338 assert_eq!(
7339 clean("grid-template-rows: repeat(2, minmax(min-content, 1fr)) 40px").vn_grid_rows,
7340 Some(vec![
7341 GridTrack {
7342 min: G::MinContent,
7343 max: G::Fr(1.0)
7344 },
7345 GridTrack {
7346 min: G::MinContent,
7347 max: G::Fr(1.0)
7348 },
7349 GridTrack::fixed(G::Px(40.0)),
7350 ])
7351 );
7352 assert_eq!(
7353 clean("grid-template-columns: 25% 75%").vn_grid_cols,
7354 Some(vec![
7355 GridTrack::fixed(G::Percent(0.25)),
7356 GridTrack::fixed(G::Percent(0.75)),
7357 ])
7358 );
7359 }
7360
7361 #[test]
7362 fn an_auto_repeat_is_counted_by_the_layout() {
7363 use gpui::{GridAutoRepeat, GridTrack, GridTrackSize as G};
7364 let r = clean("grid-template-columns: repeat(auto-fill, minmax(120px, 1fr))");
7365 assert_eq!(r.grid_cols, None);
7366 assert_eq!(
7367 r.vn_grid_cols,
7368 Some(vec![GridTrack {
7369 min: G::Px(120.0),
7370 max: G::Fr(1.0)
7371 }])
7372 );
7373 assert_eq!(
7374 r.vn_grid_cols_auto,
7375 Some(GridAutoRepeat {
7376 fit: false,
7377 start: 0,
7378 len: 1
7379 })
7380 );
7381
7382 let r = clean("grid-template-rows: 40px repeat(auto-fit, 10px 20%) 1rem");
7383 assert_eq!(
7384 r.vn_grid_rows,
7385 Some(vec![
7386 GridTrack::fixed(G::Px(40.0)),
7387 GridTrack::fixed(G::Px(10.0)),
7388 GridTrack::fixed(G::Percent(0.2)),
7389 GridTrack::fixed(G::Px(16.0)),
7390 ])
7391 );
7392 assert_eq!(
7393 r.vn_grid_rows_auto,
7394 Some(GridAutoRepeat {
7395 fit: true,
7396 start: 1,
7397 len: 2
7398 })
7399 );
7400
7401 assert_eq!(
7402 clean("grid-template-columns: 1fr auto").vn_grid_cols_auto,
7403 Some(GridAutoRepeat {
7404 fit: false,
7405 start: 0,
7406 len: 0
7407 })
7408 );
7409 }
7410
7411 #[test]
7412 fn an_unmodelable_track_list_is_dropped_not_a_wrong_grid() {
7413 for body in [
7414 "grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)) 1fr",
7415 "grid-template-columns: repeat(auto-fill, auto)",
7416 "grid-template-columns: fit-content(200px) 1fr",
7417 ] {
7418 let (r, _) = map(body);
7419 assert_eq!(r.grid_cols, None, "{body}");
7420 assert_eq!(r.vn_grid_cols, None, "{body}");
7421 }
7422 }
7423
7424 #[test]
7425 fn grid_placement_maps_lines_and_spans() {
7426 use gpui::GridPlacement as P;
7427 let r = clean("grid-column: 2 / 4");
7428 let loc = r.grid_location.clone().expect("a grid location");
7429 assert_eq!(loc.column, P::Line(2)..P::Line(4));
7430 let r = clean("grid-row: span 2");
7431 let loc = r.grid_location.clone().expect("a grid location");
7432 assert_eq!(loc.row.start, P::Span(2));
7433 let r = clean("grid-column-start: 3");
7434 assert_eq!(r.grid_location.unwrap().column.start, P::Line(3));
7435 }
7436
7437 #[test]
7438 fn implicit_track_lists_map_fractional_and_repeating_patterns() {
7439 use gpui::{GridTrack, GridTrackSize as Track};
7440 assert_eq!(
7441 clean("grid-auto-columns: 1fr").vn_grid_auto_cols,
7442 Some(vec![GridTrack::fr(1.0)])
7443 );
7444 assert_eq!(
7445 clean("grid-auto-rows: 20px 2rem 25% minmax(min-content, 1fr)").vn_grid_auto_rows,
7446 Some(vec![
7447 GridTrack::fixed(Track::Px(20.0)),
7448 GridTrack::fixed(Track::Px(32.0)),
7449 GridTrack::fixed(Track::Percent(0.25)),
7450 GridTrack {
7451 min: Track::MinContent,
7452 max: Track::Fr(1.0)
7453 }
7454 ])
7455 );
7456 assert_eq!(
7459 clean("grid-auto-rows: 20px; grid-auto-rows: auto").vn_grid_auto_rows,
7460 Some(Vec::new())
7461 );
7462 let (style, _) = map("grid-auto-columns: 12px fit-content(30px)");
7463 assert!(
7464 style.vn_grid_auto_cols.is_none(),
7465 "unsupported tracks cannot leave a truncated pattern"
7466 );
7467 }
7468
7469 #[test]
7470 fn declared_visibility_is_not_the_paint_switch() {
7471 assert_eq!(extras("visibility: hidden").0.visibility_hidden, Some(true));
7472 assert_eq!(
7473 extras("visibility: collapse").0.visibility_hidden,
7474 Some(true)
7475 );
7476 assert_eq!(
7477 extras("visibility: visible").0.visibility_hidden,
7478 Some(false)
7479 );
7480 assert_eq!(extras("color: red").0.visibility_hidden, None);
7481 for sr_only in ["clip: rect(0, 0, 0, 0)"] {
7482 let mut d = Vec::new();
7483 let inline = parse_inline_style(sr_only, &mut d);
7484 assert_eq!(
7485 inline.refinement.and_then(|r| r.visibility),
7486 Some(gpui::Visibility::Hidden),
7487 "{sr_only}"
7488 );
7489 assert_eq!(inline.extras.visibility_hidden, None, "{sr_only}");
7490 }
7491 let mut d = Vec::new();
7492 let inline = parse_inline_style("clip-path: inset(50%)", &mut d);
7493 assert_eq!(inline.extras.visibility_hidden, None);
7494 }
7495
7496 #[test]
7497 fn custom_properties_travel_their_own_channel() {
7498 let mut d = Vec::new();
7499 let inline = parse_inline_style(
7500 "--tw-shadow: 0 0 #0000; --tw-ring-color: red; --whatever: 3; color: blue",
7501 &mut d,
7502 );
7503 assert!(d.is_empty(), "{d:?}");
7504 assert_eq!(
7505 inline.custom,
7506 vec![
7507 ("--tw-shadow".to_string(), "0 0 #0000".to_string()),
7508 ("--tw-ring-color".to_string(), "red".to_string()),
7509 ("--whatever".to_string(), "3".to_string()),
7510 ]
7511 );
7512 assert!(inline.refinement.is_some_and(|r| r.text.color.is_some()));
7513 }
7514
7515 #[test]
7516 fn a_var_composed_value_is_deferred_to_computed_value_time() {
7517 let mut d = Vec::new();
7518 let inline = parse_inline_style("box-shadow: var(--tw-shadow)", &mut d);
7519 assert!(d.is_empty(), "{d:?}");
7520 assert!(inline.refinement.is_none());
7521 assert_eq!(
7522 inline.dynamic,
7523 vec![("box-shadow".to_string(), "var(--tw-shadow)".to_string())]
7524 );
7525 }
7526
7527 #[test]
7528 fn apply_dynamic_substitutes_then_maps() {
7529 let mut d = Vec::new();
7530 let vars = crate::vars::resolve(
7531 &Rc::new(Vars::default()),
7532 &[&(
7533 "--tw-shadow".to_string(),
7534 "0 1px 2px 0 rgb(0 0 0 / 0.5)".to_string(),
7535 )],
7536 &crate::Env::default(),
7537 &mut d,
7538 );
7539 let mut r = StyleRefinement::default();
7540 let mut x = Extras::default();
7541 apply_dynamic(
7542 "box-shadow",
7543 "var(--tw-shadow)",
7544 &vars,
7545 &crate::Env::default(),
7546 &mut r,
7547 &mut x,
7548 &mut d,
7549 );
7550 assert!(d.is_empty(), "{d:?}");
7551 let shadows = r.box_shadow.expect("box-shadow mapped");
7552 assert_eq!(shadows.len(), 1);
7553 assert_eq!(shadows[0].blur_radius, px(2.0));
7554 }
7555
7556 #[test]
7557 fn currentcolor_is_recorded_for_substitution_after_the_cascade() {
7558 let (r, x, d) = map_full("background-color: currentColor");
7559 assert_eq!(r.background, None, "not resolvable yet");
7560 assert!(x.current_color.has(CurrentColorTargets::BACKGROUND));
7561 assert!(d.is_empty(), "{d:?}");
7562
7563 let (_, x, d) = map_full("border-color: currentColor");
7564 assert!(x.current_color.has(CurrentColorTargets::BORDER));
7565 assert!(d.is_empty(), "{d:?}");
7566
7567 let (r, x, d) = map_full("color: currentColor");
7568 assert_eq!(r.text.color, None);
7569 assert_eq!(x.current_color, CurrentColorTargets::default());
7570 assert!(d.is_empty(), "{d:?}");
7571 }
7572
7573 #[test]
7574 fn calc_that_is_not_a_finite_length_does_not_reach_the_layout() {
7575 let (r, _) = map("width: clamp(2rem, 5px, 1rem)");
7576 assert_eq!(r.size.width, Some(Length::Definite(px(32.0).into())));
7577 let (r, _) = map("width: calc(100px / 0)");
7578 assert_eq!(r.size.width, None);
7579 let (r, _) = map("padding-top: calc(1px * (1 / 0))");
7580 assert_eq!(r.padding.top, None);
7581 }
7582
7583 #[test]
7584 fn calc_sums_and_products_resolve_to_pixels() {
7585 assert_eq!(
7586 clean("border-radius: calc(0.5rem - 2px)")
7587 .corner_radii
7588 .top_left,
7589 Some(px(6.0).into())
7590 );
7591 assert_eq!(
7592 clean("padding-top: calc(1rem + 4px)").padding.top,
7593 Some(px(20.0).into())
7594 );
7595 assert_eq!(
7596 clean("width: calc(2 * 8px)").size.width,
7597 Some(Length::Definite(px(16.0).into()))
7598 );
7599 assert_eq!(
7600 clean("border-top-width: calc(4px + 1px)").border_widths.top,
7601 Some(px(5.0).into())
7602 );
7603 assert_eq!(
7604 clean("width: min(100px, 40px)").size.width,
7605 Some(Length::Definite(px(40.0).into()))
7606 );
7607 assert_eq!(
7608 clean("width: clamp(10px, 4px, 100px)").size.width,
7609 Some(Length::Definite(px(10.0).into()))
7610 );
7611 }
7612
7613 #[test]
7614 fn a_percentage_inside_calc_is_resolved_by_the_layout() {
7615 let calc = |fraction: f32, pixels: f32| {
7616 Some(Length::Definite(DefiniteLength::Calc {
7617 fraction,
7618 pixels: px(pixels),
7619 }))
7620 };
7621 assert_eq!(
7622 clean("left: calc(38.89% + 13.33px)").inset.left,
7623 calc(0.3889, 13.33)
7624 );
7625 assert_eq!(clean("width: calc(100% - 8px)").size.width, calc(1.0, -8.0));
7626 assert_eq!(
7627 clean("max-width: calc((100% - 1rem) * 0.5)").max_size.width,
7628 calc(0.5, -8.0)
7629 );
7630 assert_eq!(
7631 clean("margin-left: calc(-50% + 2px)").margin.left,
7632 calc(-0.5, 2.0)
7633 );
7634 assert_eq!(
7635 clean("padding-top: calc(10% - 1px)").padding.top,
7636 Some(DefiniteLength::Calc {
7637 fraction: 0.1,
7638 pixels: px(-1.0)
7639 })
7640 );
7641 assert_eq!(
7642 clean("width: calc(50% - 50% + 3px)").size.width,
7643 Some(Length::Definite(px(3.0).into()))
7644 );
7645 }
7646
7647 #[test]
7648 fn a_calc_that_cannot_be_laid_out_is_dropped() {
7649 let (r, _) = map("width: min(100%, 10px)");
7650 assert_eq!(r.size.width, None);
7651 let (r, _) = map("left: clamp(0px, 50%, 100px)");
7652 assert_eq!(r.inset.left, None);
7653 }
7654
7655 #[test]
7656 fn a_cursor_image_falls_back_to_its_keyword() {
7657 assert_eq!(
7658 clean("cursor: url(brush.svg) 8 8, crosshair").mouse_cursor,
7659 Some(gpui::CursorStyle::Crosshair)
7660 );
7661 }
7662
7663 fn extras(body: &str) -> (Extras, Vec<String>) {
7664 let mut d = Vec::new();
7665 let inline = parse_inline_style(body, &mut d);
7666 (inline.extras, d)
7667 }
7668
7669 fn transform(body: &str) -> (Option<TransformSpec>, Vec<String>) {
7670 let mut d = Vec::new();
7671 let inline = parse_inline_style(body, &mut d);
7672 (inline.refinement.and_then(|r| r.vn_transform), d)
7673 }
7674
7675 #[test]
7676 fn absolute_and_inset_map_straight_through() {
7677 let r = clean("position: absolute; inset: 0; left: 50%; top: 8px");
7678 assert_eq!(r.position, Some(gpui::Position::Absolute));
7679 assert_eq!(r.inset.right, Some(Length::Definite(px(0.0).into())));
7680 assert_eq!(r.inset.left, Some(Length::Definite(relative(0.5))));
7681 assert_eq!(r.inset.top, Some(Length::Definite(px(8.0).into())));
7682 }
7683
7684 #[test]
7685 fn css_wide_inset_resets_clear_offsets_and_keep_literal_source_order() {
7686 for keyword in ["initial", "unset"] {
7687 let r = clean(&format!(
7688 "inset: 9px; bottom: {keyword}; inset-inline-start: {keyword}"
7689 ));
7690 assert_eq!(r.inset.top, Some(px(9.0).into()));
7691 assert_eq!(r.inset.right, Some(px(9.0).into()));
7692 assert_eq!(r.inset.bottom, Some(Length::Auto));
7693 assert_eq!(r.inset.left, Some(Length::Auto));
7694 let r = clean(&format!("inset: {keyword}; bottom: 8px; inset-inline: 2px"));
7695 assert_eq!(r.inset.top, Some(Length::Auto));
7696 assert_eq!(r.inset.bottom, Some(px(8.0).into()));
7697 assert_eq!(r.inset.left, Some(px(2.0).into()));
7698 assert_eq!(r.inset.right, Some(px(2.0).into()));
7699 }
7700 }
7701
7702 #[test]
7703 fn appearance_none_takes_the_select_skin_away() {
7704 for (body, none) in [
7705 ("appearance: none", Some(true)),
7706 ("-webkit-appearance: none", Some(true)),
7707 ("-moz-appearance: none", None),
7708 ("appearance: auto", Some(false)),
7709 ("appearance: menulist-button", Some(false)),
7710 ("color: red", None),
7711 ] {
7712 let (x, d) = extras(body);
7713 assert_eq!(x.appearance_none, none, "{body}");
7714 assert!(d.is_empty(), "{body}: {d:?}");
7715 }
7716 let (mut x, _) = extras("appearance: none");
7717 x.refine(&extras("appearance: auto").0);
7718 assert_eq!(x.appearance_none, Some(false), "a later rule wins");
7719 }
7720
7721 #[test]
7722 fn fixed_is_absolute_plus_a_deferred_layer_and_no_advisory() {
7723 let (x, d) = extras("position: fixed");
7724 assert_eq!(x.fixed, Some(true));
7725 assert!(x.may_defer());
7726 assert!(d.is_empty(), "{d:?}");
7727 let (x, _) = extras("position: fixed; position: relative");
7728 assert_eq!(x.fixed, Some(false));
7729 assert!(!x.may_defer());
7730 }
7731
7732 #[test]
7733 fn z_index_auto_is_not_zero() {
7734 assert_eq!(extras("z-index: auto").0.z_index, Some(None));
7735 assert_eq!(extras("z-index: 0").0.z_index, Some(Some(0)));
7736 assert_eq!(extras("color: red").0.z_index, None);
7737 let mut folded = extras("z-index: 10").0;
7738 folded.refine(&extras("z-index: auto").0);
7739 assert_eq!(folded.z(), None);
7740 folded.refine(&extras("color: red").0);
7741 assert_eq!(
7742 folded.z_index,
7743 Some(None),
7744 "a block that says nothing keeps it"
7745 );
7746 }
7747
7748 #[test]
7749 fn translate_is_kept_in_its_authored_unit() {
7750 let (r, d) = transform("transform: translate(-50%, -50%)");
7751 assert!(d.is_empty(), "{d:?}");
7752 let t = r.expect("declared");
7753 assert_eq!(
7754 t.translate,
7755 (
7756 TransformLength::Fraction(-0.5),
7757 TransformLength::Fraction(-0.5)
7758 )
7759 );
7760 assert_eq!(TransformLength::Fraction(-0.5).resolve(400.0), -200.0);
7761
7762 let t = transform("transform: translateX(1.25rem)")
7763 .0
7764 .expect("declared");
7765 assert_eq!(
7766 t.translate,
7767 (TransformLength::Pixels(20.0), TransformLength::Pixels(0.0))
7768 );
7769 }
7770
7771 #[test]
7772 fn tailwinds_identity_transform_chain_is_silent() {
7773 let (r, d) = transform(
7774 "transform: translate(-50%, -50%) rotate(0) skewX(0) skewY(0) scaleX(1) scaleY(1)",
7775 );
7776 assert!(d.is_empty(), "{d:?}");
7777 let t = r.expect("declared");
7778 assert_eq!(
7779 t.translate,
7780 (
7781 TransformLength::Fraction(-0.5),
7782 TransformLength::Fraction(-0.5)
7783 )
7784 );
7785 assert_eq!(t.rotate, 0.0);
7786 assert_eq!(t.scale, (1.0, 1.0));
7787 }
7788
7789 #[test]
7790 fn transform_none_is_a_value_not_an_absence() {
7791 let (r, d) = transform("transform: rotate(0deg)");
7792 assert!(d.is_empty(), "{d:?}");
7793 assert_eq!(r, Some(TransformSpec::IDENTITY));
7794 assert!(r.unwrap().is_identity());
7795 assert_eq!(transform("color: red").0, None);
7796 }
7797
7798 #[test]
7799 fn rotate_and_scale_reach_the_computed_value() {
7800 let (r, d) = transform("transform: translateY(4px) rotate(45deg) scale(1.5)");
7801 assert!(d.is_empty(), "{d:?}");
7802 let t = r.expect("declared");
7803 assert_eq!(
7804 t.translate,
7805 (TransformLength::Pixels(0.0), TransformLength::Pixels(4.0))
7806 );
7807 assert!(
7808 (t.rotate - std::f32::consts::FRAC_PI_4).abs() < 1e-5,
7809 "{}",
7810 t.rotate
7811 );
7812 assert_eq!(t.scale, (1.5, 1.5));
7813
7814 let spin = transform("transform: rotate(360deg)").0.expect("declared");
7815 assert!(
7816 (spin.rotate - std::f32::consts::TAU).abs() < 1e-4,
7817 "{}",
7818 spin.rotate
7819 );
7820 assert_eq!(
7821 transform("transform: scaleX(-1)")
7822 .0
7823 .expect("declared")
7824 .scale,
7825 (-1.0, 1.0)
7826 );
7827
7828 let (r, _) = transform("transform: rotateY(30deg) skewX(10deg)");
7829 assert_eq!(r.expect("declared").rotate, 0.0);
7830 }
7831
7832 #[test]
7833 fn every_gradient_shape_becomes_a_background_layer() {
7834 let layers = |body: &str| {
7835 let (_, x, d) = map_full(body);
7836 assert!(d.is_empty(), "{body}: {d:?}");
7837 x.resolve_background_layers()
7838 };
7839 let one = |body: &str| {
7840 let list = layers(body);
7841 assert_eq!(list.len(), 1, "{body}");
7842 list[0]
7843 };
7844
7845 let right = one("background-image: linear-gradient(to right, #ff0000, #0000ff)");
7846 let ninety = one("background: linear-gradient(90deg, #ff0000 0%, #0000ff 100%)");
7847 assert_eq!(
7848 format!("{right:?}"),
7849 format!("{ninety:?}"),
7850 "`to right` is 90deg"
7851 );
7852 let down = one("background-image: linear-gradient(#fff, #000)");
7853 let explicit = one("background-image: linear-gradient(180deg, #fff, #000)");
7854 assert_eq!(
7855 format!("{down:?}"),
7856 format!("{explicit:?}"),
7857 "the default is `to bottom`"
7858 );
7859
7860 assert!(
7861 format!("{:?}", one("background-image: radial-gradient(#fff, #000)"))
7862 .starts_with("RadialGradient")
7863 );
7864 assert!(
7865 format!("{:?}", one("background-image: conic-gradient(#fff, #000)"))
7866 .starts_with("ConicGradient")
7867 );
7868
7869 let three = one("background-image: linear-gradient(#f00, #0f0, #00f)");
7870 assert_eq!(three.live_stops().len(), 3);
7871
7872 let repeating = one("background-image: repeating-linear-gradient(#f00 0px, #00f 10px)");
7873 assert_eq!(repeating.live_stops().len(), 2);
7874 assert_ne!(
7875 format!("{repeating:?}"),
7876 format!(
7877 "{:?}",
7878 one("background-image: linear-gradient(#f00 0px, #00f 10px)")
7879 )
7880 );
7881
7882 let stack =
7883 layers("background-image: linear-gradient(#f00, #f00), linear-gradient(#00f, #00f)");
7884 assert_eq!(stack.len(), 2);
7885 }
7886
7887 #[test]
7888 fn background_size_and_position_tile_the_gradient() {
7889 let (_, x, d) = map_full(
7890 "background-image: linear-gradient(rgba(255,255,255,.02) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.02) 1px, transparent 1px); background-size: 64px 64px",
7891 );
7892 assert!(d.is_empty(), "{d:?}");
7893 let layers = x.resolve_background_layers();
7894 assert_eq!(layers.len(), 2);
7895 for layer in &layers {
7896 assert!(layer.is_tiled(), "{layer:?}");
7897 assert_eq!(layer.live_stops()[0].percentage, 1.0);
7898 }
7899 assert!(format!("{:?}", layers[0]).contains("LinearGradient(90"));
7900
7901 let (_, x, _) = map_full("background-image: linear-gradient(#f00, #00f)");
7902 assert!(!x.resolve_background_layers()[0].is_tiled());
7903 }
7904
7905 #[test]
7906 fn a_url_background_is_carried_with_its_geometry() {
7907 let (r, x, d) = map_full(
7908 "background-image: url(atlas.webp); background-size: 6100% 600%; \
7909 background-position: 45% 20%; background-repeat: no-repeat",
7910 );
7911 assert!(d.is_empty(), "{d:?}");
7912 assert_eq!(r.background, None);
7913 assert_eq!(
7914 x.resolve_background_stack(),
7915 Some(vec![PaintLayer::Image {
7916 url: Rc::from("atlas.webp"),
7917 size: BackgroundSize::Explicit(
7918 Some(TileLength::Fraction(61.0)),
7919 Some(TileLength::Fraction(6.0))
7920 ),
7921 position: (TileLength::Fraction(0.45), TileLength::Fraction(0.2)),
7922 repeat: (false, false),
7923 }])
7924 );
7925
7926 let (_, x, _) = map_full(
7927 "background-image: url(\"a.png\"); background-size: 1342px 268px; \
7928 background-position: -88px -44px",
7929 );
7930 let stack = x.resolve_background_stack().unwrap();
7931 let [PaintLayer::Image {
7932 size,
7933 position,
7934 repeat,
7935 ..
7936 }] = stack.as_slice()
7937 else {
7938 panic!("one image layer: {stack:?}");
7939 };
7940 assert_eq!(
7941 *size,
7942 BackgroundSize::Explicit(
7943 Some(TileLength::Pixels(1342.0)),
7944 Some(TileLength::Pixels(268.0))
7945 )
7946 );
7947 assert_eq!(
7948 *position,
7949 (TileLength::Pixels(-88.0), TileLength::Pixels(-44.0))
7950 );
7951 assert_eq!(*repeat, (true, true));
7952 let size_of = |body: &str| match map_full(body).1.resolve_background_stack().unwrap()[0] {
7953 PaintLayer::Image { size, .. } => size,
7954 ref other => panic!("{other:?}"),
7955 };
7956 assert_eq!(
7957 size_of("background: url(b.png) center / cover no-repeat"),
7958 BackgroundSize::Cover
7959 );
7960 assert_eq!(
7961 size_of("background-image: url(b.png); background-size: contain"),
7962 BackgroundSize::Contain
7963 );
7964
7965 let (_, x, _) =
7966 map_full("background-image: linear-gradient(#0008, #0008), url(banner.png)");
7967 let stack = x.resolve_background_stack().unwrap();
7968 assert!(matches!(stack[0], PaintLayer::Image { .. }), "{stack:?}");
7969 assert!(matches!(stack[1], PaintLayer::Gradient(_)), "{stack:?}");
7970
7971 let (_, x, _) = map_full("background-image: linear-gradient(#f00, #00f)");
7972 assert_eq!(x.resolve_background_stack(), None);
7973 assert_eq!(
7974 map_full("background-image: url(\"\")")
7975 .1
7976 .resolve_background_stack(),
7977 None
7978 );
7979 }
7980
7981 #[test]
7982 fn a_later_background_image_replaces_an_earlier_url() {
7983 let (_, mut x, _) = map_full("background-image: url(a.png)");
7984 let (_, later, _) = map_full("background-image: linear-gradient(#f00, #00f)");
7985 x.refine(&later);
7986 assert_eq!(x.resolve_background_stack(), None);
7987 assert_eq!(x.resolve_background_layers().len(), 1);
7988 }
7989
7990 #[test]
7991 fn letter_and_word_spacing_reach_the_text_style() {
7992 assert_eq!(
7993 clean("letter-spacing: 6.3px").text.letter_spacing,
7994 Some(px(6.3))
7995 );
7996 assert_eq!(clean("word-spacing: 2px").text.word_spacing, Some(px(2.0)));
7997 assert_eq!(
7998 clean("letter-spacing: normal").text.letter_spacing,
7999 Some(px(0.0))
8000 );
8001 assert_eq!(
8002 clean("letter-spacing: 0.5em").text.letter_spacing,
8003 Some(px(0.5 * crate::rem_basis()))
8004 );
8005 }
8006
8007 #[test]
8008 fn no_underline_cancels_an_earlier_one() {
8009 let r = clean("text-decoration-line: underline; text-decoration-line: none");
8010 let u = r
8011 .text
8012 .underline
8013 .expect("declared, so it wins over the earlier one");
8014 assert_eq!(u.thickness, px(0.0));
8015 assert_eq!(u.color.map(|c| c.a), Some(0.0));
8016 let strike = r.text.strikethrough.expect("cleared too");
8017 assert_eq!(strike.thickness, px(0.0));
8018 }
8019
8020 #[test]
8021 fn underline_offset_lands_on_the_decoration() {
8022 let (r, x, d) = map_full("text-decoration-line: underline; text-underline-offset: 4px");
8023 assert!(d.is_empty(), "{d:?}");
8024 assert_eq!(r.text.underline.expect("declared").offset, px(4.0));
8025 assert_eq!(x.underline_offset, Some(4.0));
8026
8027 let (_, x, d) = map_full("text-underline-offset: 4px");
8028 assert!(d.is_empty(), "{d:?}");
8029 assert_eq!(x.underline_offset, Some(4.0));
8030 }
8031
8032 #[test]
8033 fn font_features_reach_the_shaper_and_axes_do_not() {
8034 let features = clean("font-feature-settings: \"ss01\" 1, \"liga\" 0")
8035 .text
8036 .font_features
8037 .expect("declared");
8038 assert_eq!(
8039 &*features.0,
8040 &[("ss01".into(), 1u32), ("liga".into(), 0u32)]
8041 );
8042
8043 let numeric = clean("font-variant-numeric: tabular-nums")
8044 .text
8045 .font_features
8046 .expect("declared");
8047 assert_eq!(&*numeric.0, &[("tnum".into(), 1u32)]);
8048 }
8049
8050 #[test]
8051 fn kerning_and_ligature_keywords_become_features() {
8052 let features = |css: &str| {
8053 clean(css)
8054 .text
8055 .font_features
8056 .map(|f| (*f.0).clone())
8057 .unwrap_or_default()
8058 };
8059 let pairs = |p: &[(&str, u32)]| -> Vec<(String, u32)> {
8060 p.iter().map(|(t, v)| (t.to_string(), *v)).collect()
8061 };
8062 assert_eq!(features("font-kerning: none"), pairs(&[("kern", 0)]));
8063 assert!(features("font-kerning: auto").is_empty());
8064 assert!(features("font-kerning: normal").is_empty());
8065 assert!(features("font-variant-ligatures: normal").is_empty());
8066 assert_eq!(
8067 features("font-variant-ligatures: none"),
8068 pairs(&[
8069 ("liga", 0),
8070 ("clig", 0),
8071 ("dlig", 0),
8072 ("hlig", 0),
8073 ("calt", 0)
8074 ])
8075 );
8076 assert_eq!(
8077 features("font-variant-ligatures: no-common-ligatures discretionary-ligatures"),
8078 pairs(&[("liga", 0), ("clig", 0), ("dlig", 1)])
8079 );
8080 assert_eq!(
8081 features("font-variant-ligatures: no-contextual"),
8082 pairs(&[("calt", 0)])
8083 );
8084 assert_eq!(
8085 features(
8086 "font-variant-numeric: tabular-nums; font-kerning: none; \
8087 font-variant-ligatures: no-common-ligatures; font-feature-settings: \"liga\" 1"
8088 ),
8089 pairs(&[("tnum", 1), ("kern", 0), ("liga", 1), ("clig", 0)])
8090 );
8091 }
8092
8093 #[test]
8094 fn font_family_takes_the_first_installed_family() {
8095 let family = |css: &str| clean(css).text.font_family.map(|f| f.to_string());
8096 assert_eq!(
8097 family("font-family: Inter, sans-serif").as_deref(),
8098 Some("Inter")
8099 );
8100
8101 set_font_source(|| vec!["Segoe UI".into(), "Consolas".into(), "Arial".into()]);
8102 assert_eq!(
8103 family("font-family: Inter, \"Segoe UI\", sans-serif").as_deref(),
8104 Some("Segoe UI")
8105 );
8106 assert_eq!(
8107 family(
8108 "font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \
8109 \"Liberation Mono\", \"Courier New\", monospace"
8110 )
8111 .as_deref(),
8112 Some("Consolas")
8113 );
8114 assert_eq!(
8115 family(
8116 "font-family: ui-sans-serif, system-ui, sans-serif, \"Apple Color Emoji\", \
8117 \"Segoe UI Emoji\""
8118 )
8119 .as_deref(),
8120 Some(".SystemUIFont")
8121 );
8122 assert_eq!(
8123 family("font-family: monospace").as_deref(),
8124 Some("Consolas")
8125 );
8126 assert_eq!(family("font-family: sans-serif").as_deref(), Some("Arial"));
8127 assert_eq!(
8128 family("font-family: serif").as_deref(),
8129 Some(".SystemUIFont")
8130 );
8131 assert_eq!(
8132 family("font-family: Roboto, Helvetica").as_deref(),
8133 Some("Roboto")
8134 );
8135 let misses = take_font_misses();
8136 assert_eq!(
8137 misses,
8138 vec![
8139 ("Inter".to_string(), Some("Segoe UI".to_string())),
8140 ("Roboto".to_string(), None),
8141 ],
8142 "{misses:?}"
8143 );
8144 assert!(take_font_misses().is_empty());
8145 }
8146
8147 #[test]
8148 fn composed_web_families_hand_gpui_the_rest_of_the_list() {
8149 let font = |css: &str| {
8150 let t = clean(css).text;
8151 (
8152 t.font_family.map(|f| f.to_string()),
8153 t.font_fallbacks.map(|f| f.fallback_list().join("|")),
8154 )
8155 };
8156 set_font_source(|| vec!["Arial".into(), "Mix".into(), "Segoe UI".into()]);
8157 assert_eq!(font("font-family: Mix, Arial"), (Some("Mix".into()), None));
8158
8159 set_composed_font_families([("Mix".to_string(), true), ("SK PUA".to_string(), false)]);
8160 let some = |f: &str, rest: &str| (Some(f.to_string()), Some(rest.to_string()));
8161 assert_eq!(
8162 font("font-family: Mix, \"Segoe UI\", sans-serif"),
8163 some("Mix", "Segoe UI|Arial")
8164 );
8165 assert_eq!(
8166 font("font-family: \"SK PUA\", Nowhere, mix, sans-serif"),
8167 some("SK PUA", "mix|Arial")
8168 );
8169 assert_eq!(
8170 font("font-family: Nowhere, \"SK PUA\", Mix"),
8171 some("SK PUA", "Mix")
8172 );
8173 assert!(take_unreached_fonts().is_empty());
8174 assert_eq!(
8175 font("font-family: Arial, Mix, \"SK PUA\""),
8176 some("Arial", "")
8177 );
8178 assert_eq!(
8179 take_unreached_fonts(),
8180 vec![
8181 ("Mix".to_string(), "Arial".to_string()),
8182 ("SK PUA".to_string(), "Arial".to_string())
8183 ]
8184 );
8185 assert_eq!(font("font-family: Arial"), some("Arial", ""));
8186 assert!(take_unreached_fonts().is_empty());
8187 set_composed_font_families([]);
8188 assert_eq!(font("font-family: Mix"), (Some("Mix".into()), None));
8189 }
8190
8191 #[test]
8192 fn waiting_web_fonts_are_recorded_for_the_host() {
8193 let web = |css: &str| extras(css).0.web_font.map(|f| f.join("|"));
8194 set_font_source(|| vec!["Arial".into(), "SK Half".into()]);
8195 assert_eq!(web("font-family: \"SK Web\", Arial"), None);
8196
8197 set_web_font_families([
8198 "SK Web".to_string(),
8199 "sk half".to_string(),
8200 "SK PUA".to_string(),
8201 ]);
8202 assert_eq!(
8203 web("font-family: \"SK Web\", Arial").as_deref(),
8204 Some("SK Web")
8205 );
8206 assert_eq!(
8207 clean("font-family: \"SK Web\", Arial")
8208 .text
8209 .font_family
8210 .as_deref(),
8211 Some("Arial")
8212 );
8213 assert_eq!(
8214 web("font-family: Nowhere, sk web, sans-serif").as_deref(),
8215 Some("sk web")
8216 );
8217 assert_eq!(
8218 web("font-family: \"SK PUA\", \"SK Web\", serif").as_deref(),
8219 Some("SK PUA|SK Web")
8220 );
8221 assert_eq!(web("font-family: Arial, \"SK Web\"").as_deref(), Some(""));
8222 assert_eq!(
8223 web("font-family: sans-serif, \"SK Web\"").as_deref(),
8224 Some("")
8225 );
8226 assert_eq!(
8227 web("font-family: \"SK Half\", \"SK Web\"").as_deref(),
8228 Some("SK Half")
8229 );
8230 assert_eq!(web("color: red"), None);
8231 set_web_font_families(Vec::new());
8232 }
8233
8234 #[test]
8235 fn the_visually_hidden_clip_idiom_hides_the_box() {
8236 assert_eq!(
8237 clean("clip: rect(0, 0, 0, 0)").visibility,
8238 Some(gpui::Visibility::Hidden)
8239 );
8240 assert_eq!(
8241 clean("clip: rect(0 0 0 0)").visibility,
8242 Some(gpui::Visibility::Hidden)
8243 );
8244 let (r, _) = map("clip: rect(0, 20px, 20px, 0)");
8245 assert_eq!(r.visibility, None);
8246 }
8247
8248 #[test]
8249 fn ordered_markers_count_from_one() {
8250 use crate::ListMarker;
8251 assert_eq!(ListMarker::Disc.render(3).as_deref(), Some("\u{2022}"));
8252 assert_eq!(ListMarker::None.render(3), None);
8253 assert_eq!(ListMarker::Decimal.render(1).as_deref(), Some("1."));
8254 assert_eq!(
8255 ListMarker::DecimalLeadingZero.render(7).as_deref(),
8256 Some("07.")
8257 );
8258 assert_eq!(ListMarker::LowerAlpha.render(1).as_deref(), Some("a."));
8259 assert_eq!(ListMarker::LowerAlpha.render(26).as_deref(), Some("z."));
8260 assert_eq!(ListMarker::LowerAlpha.render(27).as_deref(), Some("aa."));
8261 assert_eq!(ListMarker::UpperAlpha.render(28).as_deref(), Some("AB."));
8262 assert_eq!(ListMarker::LowerRoman.render(4).as_deref(), Some("iv."));
8263 assert_eq!(
8264 ListMarker::UpperRoman.render(1994).as_deref(),
8265 Some("MCMXCIV.")
8266 );
8267 }
8268
8269 #[test]
8270 fn outline_folds_the_shorthand_and_the_longhands_into_one_ring() {
8271 let r = clean("outline: 2px solid #ff0000; outline-offset: 3px");
8272 let o = r.vn_outline.expect("an outline");
8273 assert_eq!(o.width, px(2.0));
8274 assert_eq!(o.offset, px(3.0));
8275 assert_eq!(o.style, gpui::BorderStyle::Solid);
8276 assert!((o.color.a - 1.0).abs() < 1e-3, "{o:?}");
8277
8278 let r = clean("outline: 2px solid #ff0000; outline: none");
8279 assert_eq!(r.vn_outline.unwrap().width, px(0.0));
8280
8281 let r = clean("outline: 2px solid transparent; outline-offset: 2px");
8282 let o = r.vn_outline.unwrap();
8283 assert_eq!(o.width, px(2.0));
8284 assert_eq!(o.color.a, 0.0, "transparent paints nothing");
8285
8286 assert_eq!(
8287 clean("outline-color: #ff0000").vn_outline.unwrap().width,
8288 px(0.0)
8289 );
8290 assert_eq!(
8291 clean("outline-style: solid").vn_outline.unwrap().width,
8292 px(3.0)
8293 );
8294 assert_eq!(
8295 clean("outline-style: dashed").vn_outline.unwrap().style,
8296 gpui::BorderStyle::Dashed
8297 );
8298 }
8299
8300 #[test]
8301 fn box_shadow_carries_every_shadow_with_spread_and_inset() {
8302 let r = clean(
8303 "box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #3b82f6, inset 0 1px 2px 0 rgb(0 0 0 / 0.4)",
8304 );
8305 let shadows = r.box_shadow.expect("shadows");
8306 assert_eq!(shadows.len(), 3);
8307 assert_eq!(shadows[0].spread_radius, px(2.0));
8308 assert_eq!(shadows[1].spread_radius, px(4.0));
8309 assert!(!shadows[0].inset && !shadows[1].inset);
8310 assert!(shadows[2].inset, "the third is an inset shadow");
8311 assert_eq!(shadows[2].blur_radius, px(2.0));
8312 assert_eq!(shadows[2].offset.y, px(1.0));
8313 let mut d = Vec::new();
8314 let mut r = StyleRefinement::default();
8315 r.box_shadow = Some(vec![gpui::BoxShadow {
8316 color: Hsla::default(),
8317 offset: gpui::point(px(0.0), px(1.0)),
8318 blur_radius: px(2.0),
8319 spread_radius: px(0.0),
8320 inset: false,
8321 }]);
8322 apply_dynamic(
8323 "box-shadow",
8324 "none",
8325 &Vars::default(),
8326 &crate::Env::default(),
8327 &mut r,
8328 &mut Extras::default(),
8329 &mut d,
8330 );
8331 assert_eq!(r.box_shadow, Some(Vec::new()), "{d:?}");
8332 assert!(d.is_empty(), "{d:?}");
8333 }
8334
8335 #[test]
8336 fn text_shadow_keeps_order_offsets_blur_and_current_color() {
8337 let shadows = clean("text-shadow: 1px 2px 3px red, -0.5em 0 #00f, 0 0 4px")
8338 .text
8339 .text_shadow
8340 .expect("text-shadow");
8341 assert_eq!(shadows.len(), 3);
8342 assert_eq!(shadows[0].offset, gpui::point(px(1.0), px(2.0)));
8343 assert_eq!(shadows[0].blur_radius, px(3.0));
8344 assert_eq!(shadows[0].color, Some(gpui::red()));
8345 assert_eq!(
8346 shadows[1].offset.x,
8347 px(-8.0),
8348 "em resolves against the font size"
8349 );
8350 assert_eq!(shadows[1].blur_radius, px(0.0));
8351 assert_eq!(shadows[2].color, None, "an omitted color is currentColor");
8352 for none in ["none", "initial"] {
8353 let mut d = Vec::new();
8354 let mut r = clean("text-shadow: 1px 1px red");
8355 apply_dynamic(
8356 "text-shadow",
8357 none,
8358 &Vars::default(),
8359 &crate::Env::default(),
8360 &mut r,
8361 &mut Extras::default(),
8362 &mut d,
8363 );
8364 assert_eq!(r.text.text_shadow, Some(Vec::new()), "{none}");
8365 assert!(d.is_empty(), "{d:?}");
8366 }
8367 assert_eq!(clean("text-shadow: inherit").text.text_shadow, None);
8368 }
8369
8370 #[test]
8371 fn invalid_text_shadows_drop_the_declaration_and_say_why() {
8372 for body in [
8373 "text-shadow: 1px 1px 2px 3px red",
8374 "text-shadow: 1px 1px -2px red",
8375 ] {
8376 let (r, d) = map(&format!("text-shadow: 4px 4px blue; {body}"));
8377 assert_eq!(
8378 r.text.text_shadow.map(|s| s[0].offset.x),
8379 Some(px(4.0)),
8380 "{body} must not replace the earlier value"
8381 );
8382 assert_eq!(d.len(), 1, "{body}: {d:?}");
8383 }
8384 }
8385
8386 #[test]
8387 fn content_keeps_literal_strings_and_drops_the_rest() {
8388 let (x, d) = extras(r#"content: "->""#);
8389 assert_eq!(x.content.as_deref(), Some("->"));
8390 assert!(d.is_empty(), "{d:?}");
8391 assert_eq!(extras(r#"content: """#).0.content.as_deref(), Some(""));
8392 assert_eq!(extras("content: none").0.content, None);
8393 for body in [
8394 "content: counter(x)",
8395 "content: attr(data-x)",
8396 "content: url(a.png)",
8397 ] {
8398 assert_eq!(extras(body).0.content, None, "{body}");
8399 }
8400 }
8401
8402 #[test]
8403 fn text_transform_rewrites_the_text() {
8404 use crate::mapper::TextTransform as TT;
8405 assert_eq!(TT::Uppercase.apply("Sign in").as_deref(), Some("SIGN IN"));
8406 assert_eq!(TT::Lowercase.apply("Sign In").as_deref(), Some("sign in"));
8407 assert_eq!(
8408 TT::Capitalize.apply("sign iN now").as_deref(),
8409 Some("Sign IN Now")
8410 );
8411 assert_eq!(TT::None.apply("Sign in"), None);
8412 }
8413
8414 #[test]
8415 fn referenced_color_filter_is_replaced_by_later_none_in_one_rule_or_cascade() {
8416 let (mut referenced, diagnostics) = extras("filter:url('#color-matrix')");
8417 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8418 assert_eq!(referenced.filter_url.as_deref(), Some("#color-matrix"));
8419 referenced.refine(&extras("filter:none").0);
8420 assert!(referenced.filter_url.is_none());
8421 assert!(extras("filter:url('#color-matrix'); filter:none")
8422 .0
8423 .filter_url
8424 .is_none());
8425 assert!(extras("filter:drop-shadow(1px 2px red); filter:none")
8426 .0
8427 .drop_shadow
8428 .is_none());
8429 }
8430
8431 #[test]
8432 fn a_blur_is_recorded_even_beside_other_filters() {
8433 let (x, d) = extras("filter: blur(64px)");
8434 assert_eq!(x.blur, Some(64.0));
8435 assert!(
8436 d.is_empty(),
8437 "a lone blur() is implemented, not advised: {d:?}"
8438 );
8439
8440 assert_eq!(extras("filter: none").0.blur, Some(0.0));
8441
8442 assert_eq!(extras("filter: blur(8px) ").0.blur, Some(8.0));
8443
8444 let (x, _) = extras("filter: blur(4px) grayscale(1)");
8445 assert_eq!(x.blur, Some(4.0), "the blur still lands");
8446 }
8447
8448 #[test]
8449 fn nickname_six_color_and_thirteen_stop_travelling_gradients_keep_every_stop() {
8450 let palette = [0xff3355, 0xffaa00, 0x00ff44, 0x0088ff, 0x9933ff, 0xff55bb];
8451 for travelling in [false, true] {
8452 let colors: Vec<_> = if travelling {
8453 palette
8454 .iter()
8455 .chain(palette.iter())
8456 .chain(palette[..1].iter())
8457 .copied()
8458 .collect()
8459 } else {
8460 palette.to_vec()
8461 };
8462 let css = format!("background-image:linear-gradient(90deg,{});background-clip:text;color:transparent;background-size:200% 100%;background-position:-100% 0",
8463 colors.iter().map(|color| format!("#{color:06x}")).collect::<Vec<_>>().join(","));
8464 let (extras, diagnostics) = extras(&css);
8465 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8466 let layers = extras
8467 .background_images
8468 .as_ref()
8469 .expect("gradient brush stack");
8470 for (index, color) in colors.iter().enumerate() {
8471 let expected: Hsla = gpui::rgb(*color).into();
8472 let position = index as f32 / (colors.len() - 1) as f32;
8473 assert!(
8474 layers
8475 .iter()
8476 .flat_map(|layer| layer.background.live_stops())
8477 .any(|stop| stop.color == expected
8478 && (stop.percentage - position).abs() < 1e-5),
8479 "stop {index}/{} must survive transparent-band packing",
8480 colors.len()
8481 );
8482 }
8483 assert!(layers
8484 .iter()
8485 .all(|layer| layer.background.live_stops().len() <= gpui::GRADIENT_STOPS));
8486 assert_eq!(extras.background_clip_text, Some(true));
8487 assert_eq!(
8488 extras.background_position.as_ref().unwrap()[0].0,
8489 TileLength::Fraction(-1.)
8490 );
8491 }
8492 }
8493
8494 #[test]
8495 fn background_clip_text_records_the_clip_and_background_metadata() {
8496 let (x, _) = extras(
8497 "background-image: linear-gradient(to right, #fbbf24, #eab308); \
8498 background-clip: text; color: transparent",
8499 );
8500 assert_eq!(x.background_clip_text, Some(true));
8501 let key = x
8502 .background_key_color
8503 .expect("a gradient contributes a key colour");
8504 assert!(key.s > 0.8 && key.l > 0.4 && key.l < 0.7, "{key:?}");
8505 assert!(
8506 key.h < 0.15,
8507 "an amber ramp must not average to a cold hue: {key:?}"
8508 );
8509
8510 let (x, _) = extras("background-color: #ff0000; -webkit-background-clip: text");
8511 assert_eq!(x.background_clip_text, Some(true));
8512 assert_eq!(x.background_key_color.map(|c| c.h), Some(0.0));
8513 }
8514
8515 #[test]
8516 fn rem_resolves_against_the_root_font_size() {
8517 assert_eq!(rem_basis(), INITIAL_REM_BASIS);
8518 assert_eq!(
8519 clean("width: 32rem").size.width,
8520 Some(Length::Definite(px(512.0).into()))
8521 );
8522
8523 assert!(set_rem_basis(14.0), "a new basis is a change");
8524 assert!(!set_rem_basis(14.0), "the same basis is not");
8525 assert_eq!(
8526 clean("width: 32rem").size.width,
8527 Some(Length::Definite(px(448.0).into()))
8528 );
8529
8530 assert!(!set_rem_basis(0.0));
8533 assert!(!set_rem_basis(f32::NAN));
8534 assert_eq!(rem_basis(), 14.0);
8535
8536 set_rem_basis(INITIAL_REM_BASIS);
8537 }
8538
8539 #[test]
8540 fn ch_and_ex_compile_to_half_an_em_of_the_root() {
8541 let w = |body: &str| clean(body).size.width;
8542 assert_eq!(w("width: 1ch"), Some(Length::Definite(px(8.0).into())));
8543 assert_eq!(w("width: 3ex"), Some(Length::Definite(px(24.0).into())));
8544 assert_eq!(w("width: 2rch"), Some(Length::Definite(px(16.0).into())));
8545 assert_eq!(w("width: 2rex"), Some(Length::Definite(px(16.0).into())));
8546 assert_eq!(
8547 w("width: calc(2ch + 1px)"),
8548 Some(Length::Definite(px(17.0).into()))
8549 );
8550
8551 assert!(set_rem_basis(14.0));
8552 assert_eq!(w("width: 1ch"), Some(Length::Definite(px(7.0).into())));
8553 set_rem_basis(INITIAL_REM_BASIS);
8554 }
8555
8556 #[test]
8557 fn the_css_wide_inherit_keyword_is_a_no_op_rather_than_an_advisory() {
8558 for body in [
8559 "letter-spacing: inherit",
8560 "font-weight: inherit",
8561 "color: inherit",
8562 "font-size: inherit",
8563 "line-height: inherit",
8564 ] {
8565 let (_, d) = map(body);
8566 assert!(d.is_empty(), "{body:?} should be silent, said {d:?}");
8567 }
8568 }
8569
8570 #[test]
8571 fn border_radius_inherit_is_recorded_per_corner() {
8572 let inherit = |name: &str| {
8573 let (mut r, mut x, mut d) = (StyleRefinement::default(), Extras::default(), Vec::new());
8574 apply_dynamic(
8575 name,
8576 "inherit",
8577 &Vars::default(),
8578 &crate::Env::default(),
8579 &mut r,
8580 &mut x,
8581 &mut d,
8582 );
8583 assert!(d.is_empty(), "{name}: {d:?}");
8584 (r, x)
8585 };
8586 let (r, x) = inherit("border-radius");
8587 assert_eq!(
8588 x.radius_inherit,
8589 RadiusInherit {
8590 declared: 15,
8591 inherit: 15
8592 }
8593 );
8594 assert_eq!(
8595 r.corner_radii.top_left, None,
8596 "nothing to write until the parent is known"
8597 );
8598 let (_, x) = inherit("border-bottom-left-radius");
8599 let bl = RadiusInherit::BOTTOM_LEFT;
8600 assert_eq!(
8601 x.radius_inherit,
8602 RadiusInherit {
8603 declared: bl,
8604 inherit: bl
8605 }
8606 );
8607 assert_eq!(inherit("color").1.radius_inherit, RadiusInherit::default());
8608
8609 let (_, x, d) = map_full("border-radius: 4px; border-top-left-radius: 50%");
8610 assert!(d.is_empty(), "{d:?}");
8611 assert_eq!(
8612 x.radius_inherit,
8613 RadiusInherit {
8614 declared: 15,
8615 inherit: 0
8616 }
8617 );
8618 let mut folded = inherit("border-radius").1;
8619 folded.refine(&map_full("border-top-right-radius: 2px").1);
8620 assert_eq!(
8621 folded.radius_inherit.inherit,
8622 RadiusInherit::ALL & !RadiusInherit::TOP_RIGHT
8623 );
8624 folded.refine(&inherit("border-top-right-radius").1);
8625 assert_eq!(folded.radius_inherit.inherit, RadiusInherit::ALL);
8626 }
8627
8628 #[test]
8629 fn a_property_with_no_divergence_says_nothing() {
8630 for body in [
8631 "user-select: none",
8632 "user-select: text",
8633 "user-select: auto",
8634 "user-select: all",
8635 "appearance: none",
8636 "appearance: textfield",
8637 "tab-size: 4",
8638 "text-size-adjust: 100%",
8639 "touch-action: none",
8640 "-webkit-font-smoothing: antialiased",
8641 "-webkit-box-orient: vertical",
8642 "vertical-align: baseline",
8643 "text-indent: 0",
8644 "resize: none",
8645 "overflow-wrap: normal",
8646 "word-break: normal",
8647 "overflow-wrap: break-word",
8648 "overflow-wrap: anywhere",
8649 "word-wrap: break-word",
8650 "word-break: break-all",
8651 "word-break: keep-all",
8652 "word-break: break-word",
8653 "hyphens: manual",
8654 "hyphens: none",
8655 "list-style: none",
8656 "list-style-type: none",
8657 "list-style-type: disc",
8658 "list-style: decimal inside",
8659 "list-style-position: inside",
8660 "text-decoration-color: #f00",
8661 "visibility: collapse",
8662 "letter-spacing: 0.05em",
8663 "word-spacing: 2px",
8664 "font-variant-numeric: tabular-nums",
8665 "font-feature-settings: \"ss01\" 1, \"liga\" 0",
8666 "font-feature-settings: normal",
8667 "font-kerning: none",
8668 "font-kerning: auto",
8669 "font-variant-ligatures: no-common-ligatures",
8670 "font-variant-ligatures: normal",
8671 "font-variation-settings: normal",
8672 "font-optical-sizing: auto",
8673 "text-underline-offset: 4px",
8674 "text-decoration-skip-ink: none",
8675 "clip: rect(0, 0, 0, 0)",
8676 "scroll-margin-top: 4rem",
8677 "scroll-padding: 1rem",
8678 "background-size: cover",
8679 "background-image: linear-gradient(#f00, #00f); background-size: 64px 64px",
8680 "background-repeat: no-repeat",
8681 "background-position: center",
8682 "background-image: radial-gradient(circle at 30% 40%, #fff, #000)",
8683 "background-image: conic-gradient(from 45deg, #f00, #0f0, #00f)",
8684 "background-image: repeating-linear-gradient(45deg, #f00 0 10px, #00f 10px 20px)",
8685 "background-image: linear-gradient(to bottom right, #f00, #0f0, #00f, #ff0)",
8686 ] {
8687 let (_, d) = map(body);
8688 assert!(d.is_empty(), "{body:?} should be silent, said {d:?}");
8689 }
8690 }
8691
8692 #[test]
8693 fn per_side_border_colours_are_independent_and_silent() {
8694 let (r, diagnostics) = map("border-top: 1px solid #ff0000; border-left-color: #00ff00");
8695 assert_eq!(r.border_widths.top, Some(px(1.0).into()));
8696 assert_eq!(r.border_widths.bottom, None);
8697 assert_eq!(
8698 r.vn_border_colors.top,
8699 Some(Some(gpui::rgb(0xff0000).into()))
8700 );
8701 assert_eq!(
8702 r.vn_border_colors.left,
8703 Some(Some(gpui::rgb(0x00ff00).into()))
8704 );
8705 assert_eq!(r.vn_border_colors.right, None);
8706 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8707 }
8708
8709 #[test]
8710 fn border_color_shorthand_retains_four_colours_and_resets_side_overrides() {
8711 let (r, diagnostics) = map("border-color: red green blue transparent");
8712 assert_eq!(
8713 r.vn_border_colors.top,
8714 Some(Some(gpui::rgb(0xff0000).into()))
8715 );
8716 assert_eq!(
8717 r.vn_border_colors.right,
8718 Some(Some(gpui::rgb(0x008000).into()))
8719 );
8720 assert_eq!(
8721 r.vn_border_colors.bottom,
8722 Some(Some(gpui::rgb(0x0000ff).into()))
8723 );
8724 assert!(r
8725 .vn_border_colors
8726 .left
8727 .flatten()
8728 .is_some_and(|c| c.is_transparent()));
8729 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8730 let (r, diagnostics) = map("border-left-color: blue; border-color: red");
8731 assert_eq!(
8732 r.vn_border_colors.left,
8733 Some(Some(gpui::rgb(0xff0000).into()))
8734 );
8735 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8736 }
8737
8738 #[test]
8739 fn scrollbar_color_accepts_functional_colours() {
8740 for body in [
8741 "scrollbar-color: hsl(240 5% 64% / 0.35) transparent",
8742 "scrollbar-color: rgba(128, 24, 255, 0.5) #0000",
8743 "scrollbar-color: hsl(0 0% 10%) transparent",
8744 ] {
8745 let (_, extras, diagnostics) = map_full(body);
8746 assert!(extras.scrollbar_color.is_some(), "{body}: {diagnostics:?}");
8747 assert!(diagnostics.is_empty(), "{body}: {diagnostics:?}");
8748 }
8749 }
8750
8751 #[test]
8752 fn transform_origin_survives_beside_the_transform() {
8753 let spec = transform("transform-origin: left top; transform: rotate(45deg)")
8754 .0
8755 .expect("declared");
8756 assert_eq!(
8757 spec.origin,
8758 (
8759 TransformLength::Fraction(0.0),
8760 TransformLength::Fraction(0.0)
8761 )
8762 );
8763 let spec = transform("transform: rotate(45deg); transform-origin: 100% 0")
8764 .0
8765 .expect("declared");
8766 assert_eq!(
8767 spec.origin,
8768 (TransformLength::Fraction(1.0), TransformLength::Pixels(0.0))
8769 );
8770 assert_eq!(
8771 transform("transform: scale(2)").0.unwrap().origin,
8772 TransformSpec::CENTRE_ORIGIN
8773 );
8774 let alone = transform("transform-origin: left top").0.expect("declared");
8775 assert!(alone.is_identity(), "an origin alone transforms nothing");
8776 }
8777
8778 #[test]
8779 fn a_corner_transform_origin_pins_that_corner() {
8780 use gpui::{Bounds, Point, Size};
8781 let bounds = Bounds {
8782 origin: Point {
8783 x: px(100.0),
8784 y: px(50.0),
8785 },
8786 size: Size {
8787 width: px(200.0),
8788 height: px(100.0),
8789 },
8790 };
8791 let spec = transform("transform-origin: left top; transform: scale(2)")
8792 .0
8793 .expect("declared");
8794 let m = spec.to_matrix(bounds, 1.0);
8795 let pinned = m.apply(bounds.origin);
8796 assert!((f32::from(pinned.x) - 100.0).abs() < 1e-3, "{pinned:?}");
8797 assert!((f32::from(pinned.y) - 50.0).abs() < 1e-3, "{pinned:?}");
8798 let far = m.apply(Point {
8799 x: px(300.0),
8800 y: px(150.0),
8801 });
8802 assert!((f32::from(far.x) - 500.0).abs() < 1e-3, "{far:?}");
8803 assert!((f32::from(far.y) - 250.0).abs() < 1e-3, "{far:?}");
8804 }
8805
8806 #[test]
8807 fn a_matrix_decomposes_into_translate_rotate_scale() {
8808 let spec = transform("transform: matrix(2, 0, 0, 2, 10, 20)")
8809 .0
8810 .expect("declared");
8811 assert_eq!(
8812 spec.translate,
8813 (TransformLength::Pixels(10.0), TransformLength::Pixels(20.0))
8814 );
8815 assert!((spec.scale.0 - 2.0).abs() < 1e-4, "{spec:?}");
8816 assert!((spec.scale.1 - 2.0).abs() < 1e-4, "{spec:?}");
8817 assert!(spec.rotate.abs() < 1e-4, "{spec:?}");
8818 let spec = transform("transform: matrix(0, 1, -1, 0, 0, 0)")
8819 .0
8820 .expect("declared");
8821 assert!(
8822 (spec.rotate - std::f32::consts::FRAC_PI_2).abs() < 1e-4,
8823 "{spec:?}"
8824 );
8825 assert!((spec.scale.0 - 1.0).abs() < 1e-4 && (spec.scale.1 - 1.0).abs() < 1e-4);
8826 let (_, d) = map("transform: matrix(1, 0, 0.5, 1, 0, 0)");
8827 assert!(d.is_empty(), "{d:?}");
8828 }
8829
8830 #[test]
8831 fn finite_affine_matrices_keep_every_coefficient_including_singular_ones() {
8832 use gpui::{Bounds, Point, Size};
8833 let bounds = Bounds {
8834 origin: Point::new(px(100.0), px(50.0)),
8835 size: Size::new(px(200.0), px(100.0)),
8836 };
8837 for [a, b, c, d, e, f] in [
8838 [1.0, 0.25, 0.5, 1.0, 10.0, 20.0],
8839 [-2.0, 0.0, 0.5, 3.0, -10.0, 4.0],
8840 [0.0, 0.0, 2.0, 3.0, 0.0, 0.0],
8841 [1.0, 2.0, 2.0, 4.0, 0.0, 0.0],
8842 [0.0; 6],
8843 ] {
8844 let (spec, diagnostics) = transform(&format!(
8845 "transform-origin:0 0; transform:matrix({a},{b},{c},{d},{e},{f})"
8846 ));
8847 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8848 let matrix = spec.unwrap().to_matrix(bounds, 1.0);
8849 for (x, y) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (30.0, -17.0)] {
8850 let point = matrix.apply(Point::new(px(100.0 + x), px(50.0 + y)));
8851 assert!(
8852 (f32::from(point.x) - (100.0 + a * x + c * y + e)).abs() < 0.001,
8853 "{matrix:?} {point:?}"
8854 );
8855 assert!(
8856 (f32::from(point.y) - (50.0 + b * x + d * y + f)).abs() < 0.001,
8857 "{matrix:?} {point:?}"
8858 );
8859 }
8860 }
8861 }
8862
8863 #[test]
8864 fn projected_editor_matrix_preserves_centring_and_post_rotation_scale() {
8865 use gpui::{Bounds, Point, Size};
8866 let bounds = Bounds {
8867 origin: Point::new(px(0.0), px(0.0)),
8868 size: Size::new(px(200.0), px(100.0)),
8869 };
8870 let (spec, diagnostics) = transform(
8871 "transform:translate(-50%,-50%) matrix(1,.25,.5,1,0,0) rotate(90deg) scale(2,3)",
8872 );
8873 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8874 let spec = spec.unwrap();
8875 assert!(spec.translation_basis.is_none());
8876 let matrix = spec.to_matrix(bounds, 1.0);
8877 for (x, y, ex, ey) in [
8878 (100.0, 50.0, 0.0, 0.0),
8879 (101.0, 50.0, 1.0, 2.0),
8880 (100.0, 51.0, -3.0, -0.75),
8881 ] {
8882 let point = matrix.apply(Point::new(px(x), px(y)));
8883 assert!(
8884 (f32::from(point.x) - ex).abs() < 0.001 && (f32::from(point.y) - ey).abs() < 0.001,
8885 "{point:?} vs {ex},{ey}"
8886 );
8887 }
8888 }
8889
8890 #[test]
8891 fn ordered_translation_can_mix_pixels_and_both_box_axes_at_any_dpi() {
8892 use gpui::{Bounds, Point, Size};
8893 let bounds = Bounds {
8894 origin: Point::new(px(0.0), px(0.0)),
8895 size: Size::new(px(200.0), px(100.0)),
8896 };
8897 for (css, x, y) in [
8898 ("rotate(90deg) translate(50%,25%)", -25.0, 100.0),
8899 ("translate(-50%,25%) matrix(1,0,0,1,10,-4)", -90.0, 21.0),
8900 ("matrix(1,.25,.5,1,10,20) translate(8px,4px)", 20.0, 26.0),
8901 ] {
8902 let (spec, diagnostics) = transform(&format!("transform-origin:0 0; transform:{css}"));
8903 assert!(diagnostics.is_empty(), "{diagnostics:?}");
8904 for dpi in [1.0, 2.0] {
8905 let point = spec
8906 .unwrap()
8907 .to_matrix(bounds, dpi)
8908 .apply(Point::new(px(0.0), px(0.0)));
8909 assert!(
8910 (f32::from(point.x) - x * dpi).abs() < 0.001
8911 && (f32::from(point.y) - y * dpi).abs() < 0.001,
8912 "{css}: {point:?}"
8913 );
8914 }
8915 }
8916 }
8917
8918 #[test]
8919 fn shear_and_mixed_translation_survive_cssom_and_waapi_serialization() {
8920 use gpui::{Bounds, Point, Size};
8921 let bounds = Bounds {
8922 origin: Point::new(px(0.0), px(0.0)),
8923 size: Size::new(px(200.0), px(100.0)),
8924 };
8925 for css in [
8926 "matrix(1,.25,.5,1,10,20)",
8927 "rotate(90deg) translate(50%,25%) skewX(20deg)",
8928 "translate(-50%,25%) matrix(1,0,.5,1,10,-4)",
8929 ] {
8930 let original = transform(&format!("transform:{css}")).0.unwrap();
8931 let text = transform_css(original);
8932 let replayed = transform(&format!("transform:{text}")).0.unwrap();
8933 for (x, y) in [(0.0, 0.0), (20.0, 30.0), (200.0, 100.0)] {
8934 let p = Point::new(px(x), px(y));
8935 let a = original.to_matrix(bounds, 1.0).apply(p);
8936 let b = replayed.to_matrix(bounds, 1.0).apply(p);
8937 assert!(
8938 (f32::from(a.x) - f32::from(b.x)).abs() < 0.001
8939 && (f32::from(a.y) - f32::from(b.y)).abs() < 0.001,
8940 "{css} -> {text}: {a:?} vs {b:?}"
8941 );
8942 }
8943 }
8944 let spin = transform("transform:rotate(360deg) skew(0deg,0deg)")
8945 .0
8946 .unwrap();
8947 assert!(
8948 (TransformSpec::IDENTITY.interpolate(spin, 0.5).rotate - std::f32::consts::PI).abs()
8949 < 0.0001
8950 );
8951 let shear = transform("transform:matrix(1,0,1,1,0,0)").0.unwrap();
8952 assert!((TransformSpec::IDENTITY.interpolate(shear, 0.5).shear - 0.5).abs() < 0.0001);
8953 }
8954
8955 #[test]
8956 fn the_matrix_turns_about_the_box_centre() {
8957 use gpui::{Bounds, Point, Size};
8958 let bounds = Bounds {
8959 origin: Point {
8960 x: px(100.0),
8961 y: px(50.0),
8962 },
8963 size: Size {
8964 width: px(200.0),
8965 height: px(100.0),
8966 },
8967 };
8968 let quarter = transform("transform: rotate(90deg)").0.expect("declared");
8969 let m = quarter.to_matrix(bounds, 1.0);
8970 let centre = m.apply(bounds.center());
8971 assert!((f32::from(centre.x) - 200.0).abs() < 1e-3, "{centre:?}");
8972 assert!((f32::from(centre.y) - 100.0).abs() < 1e-3, "{centre:?}");
8973 let corner = m.apply(bounds.origin);
8974 assert!((f32::from(corner.x) - 250.0).abs() < 1e-3, "{corner:?}");
8975 assert!(f32::from(corner.y).abs() < 1e-3, "{corner:?}");
8976
8977 let half = transform("transform: translate(-50%, -50%)")
8978 .0
8979 .expect("declared");
8980 let m = half.to_matrix(bounds, 1.0);
8981 let moved = m.apply(bounds.origin);
8982 assert!((f32::from(moved.x) - 0.0).abs() < 1e-3, "{moved:?}");
8983 assert!((f32::from(moved.y) - 0.0).abs() < 1e-3, "{moved:?}");
8984 }
8985
8986 #[test]
8987 fn svg_paint_keeps_the_concrete_colour() {
8988 assert_eq!(extras("fill: none").0.fill, Some(SvgPaint::None));
8989 assert_eq!(extras("fill: currentColor").0.fill, Some(SvgPaint::Current));
8990 let red = extras("fill: #ff0000").0.fill;
8991 assert!(matches!(red, Some(SvgPaint::Color(_))), "{red:?}");
8992 assert_eq!(red.unwrap().as_attr(), "rgb(255,0,0)");
8993 let faint = extras("stroke: rgba(219, 232, 255, 0.17)")
8994 .0
8995 .stroke
8996 .expect("declared");
8997 assert_eq!(faint.as_attr(), "rgba(219,232,255,0.169)");
8998 assert_eq!(
8999 extras("stroke: currentColor").0.stroke,
9000 Some(SvgPaint::Current)
9001 );
9002 assert_eq!(SvgPaint::None.as_attr(), "none");
9003 assert_eq!(extras("fill: url(#g)").0.fill, Some(SvgPaint::Server));
9004 assert_eq!(SvgPaint::Server.as_attr(), "currentColor");
9005 assert_eq!(extras("color: red").0.fill, None);
9006 }
9007
9008 #[test]
9009 fn svg_presentation_properties_travel_as_text_and_merge_per_name() {
9010 let (x, d) = extras(
9011 "fill: none; stroke: currentColor; stroke-opacity: 0.28; stroke-width: 1; \
9012 shape-rendering: crispEdges",
9013 );
9014 assert!(d.is_empty(), "{d:?}");
9015 let list = x.svg_presentation.clone().expect("carried");
9016 let get = |l: &[(&'static str, Rc<str>)], n: &str| {
9017 l.iter().find(|(k, _)| *k == n).map(|(_, v)| v.to_string())
9018 };
9019 assert_eq!(get(&list, "stroke-opacity").as_deref(), Some(".28")); assert_eq!(get(&list, "stroke-width").as_deref(), Some("1px"));
9021 assert_eq!(get(&list, "shape-rendering").as_deref(), Some("crispEdges"));
9022 let (dash, d) = extras("stroke-dasharray: 5 5; stroke-dashoffset: 10px");
9023 assert!(d.is_empty(), "{d:?}");
9024 assert_eq!(dash.svg_presentation.as_ref().map(|l| l.len()), Some(2));
9025 let mut merged = x.clone();
9026 merged.refine(&extras("stroke-width: 2").0);
9027 let list = merged.svg_presentation.expect("merged");
9028 assert_eq!(get(&list, "stroke-width").as_deref(), Some("2px"));
9029 assert_eq!(get(&list, "stroke-opacity").as_deref(), Some(".28"));
9030 }
9031
9032 #[test]
9033 fn logical_margin_padding_and_inset_are_their_physical_sides() {
9034 let r = clean(
9035 "margin-inline: auto; margin-block: 2px 4px; padding-inline: 6px 8px; \
9036 padding-block-start: 10px; padding-block-end: 12px; inset-inline: 0 -22px; \
9037 inset-block-start: 3px; inset-block-end: 5%",
9038 );
9039 assert_eq!(r.margin.left, Some(Length::Auto));
9040 assert_eq!(r.margin.right, Some(Length::Auto));
9041 assert_eq!(r.margin.top, Some(px(2.0).into()));
9042 assert_eq!(r.margin.bottom, Some(px(4.0).into()));
9043 assert_eq!(r.padding.left, Some(px(6.0).into()));
9044 assert_eq!(r.padding.right, Some(px(8.0).into()));
9045 assert_eq!(r.padding.top, Some(px(10.0).into()));
9046 assert_eq!(r.padding.bottom, Some(px(12.0).into()));
9047 assert_eq!(r.inset.left, Some(px(0.0).into()));
9048 assert_eq!(r.inset.right, Some(px(-22.0).into()));
9049 assert_eq!(r.inset.top, Some(px(3.0).into()));
9050 assert_eq!(r.inset.bottom, Some(gpui::relative(0.05).into()));
9051
9052 let later = |body: &str| clean(body).margin.left;
9053 assert_eq!(
9054 later("margin-left: 3px; margin-inline-start: 5px"),
9055 Some(px(5.0).into())
9056 );
9057 assert_eq!(
9058 later("margin-inline-start: 5px; margin-left: 3px"),
9059 Some(px(3.0).into())
9060 );
9061 assert_eq!(
9062 clean("margin: 1px; margin-inline-end: 9px").margin.right,
9063 Some(px(9.0).into())
9064 );
9065 }
9066
9067 #[test]
9068 fn the_demo_cards_utilities_all_render() {
9069 let r = clean(
9070 "display: flex; flex-direction: column; gap: 0.5rem; padding: 1rem; \
9071 border-radius: 0.75rem; background-color: rgb(255 255 255 / 0.1); \
9072 font-size: 0.875rem; line-height: 1.25rem; font-weight: 600",
9073 );
9074 assert_eq!(r.display, Some(gpui::Display::Flex));
9075 assert_eq!(r.flex_direction, Some(gpui::FlexDirection::Column));
9076 assert_eq!(r.gap.width, Some(px(8.0).into()));
9077 assert_eq!(r.gap.height, Some(px(8.0).into()));
9078 assert_eq!(r.padding.top, Some(px(16.0).into()));
9079 assert_eq!(r.corner_radii.top_left, Some(px(12.0).into()));
9080 assert_eq!(r.text.font_size, Some(px(14.0).into()));
9081 assert_eq!(r.text.font_weight, Some(gpui::FontWeight(600.0)));
9082 assert!(matches!(r.background, Some(gpui::Fill::Color(_))));
9083 }
9084
9085 #[test]
9086 fn drop_shadow_parses_into_extras_and_says_nothing() {
9087 let (_, x, d) = map_full("filter: drop-shadow(2px 4px 6px rgb(0 0 0 / 0.5))");
9088 assert!(
9089 d.is_empty(),
9090 "the shape gpui can draw exactly must not advise: {d:?}"
9091 );
9092 let s = x.drop_shadow.expect("drop-shadow() reached Extras");
9093 assert_eq!((s.dx, s.dy, s.blur), (2.0, 4.0, 6.0));
9094 assert!(s.color.is_some(), "an explicit colour is flattened here");
9095
9096 let (_, x, d) = map_full("filter: drop-shadow(1px 2px 3px)");
9099 assert!(d.is_empty(), "{d:?}");
9100 assert_eq!(x.drop_shadow.map(|s| s.color), Some(None));
9101
9102 let (_, x, _) =
9103 map_full("filter: drop-shadow(1px 1px 1px red) drop-shadow(2px 2px 2px blue)");
9104 assert!(x.drop_shadow.is_some(), "the first one is still honoured");
9105 }
9106
9107 #[test]
9108 fn the_gradient_border_mask_is_a_ring_and_others_are_not() {
9109 let ring = "-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
9110 mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
9111 -webkit-mask-composite: xor;
9112 mask-composite: exclude";
9113 let (_, x, d) = map_full(ring);
9114 assert!(d.is_empty(), "{d:?}");
9115 assert!(x.mask_ring());
9116 for composite in [
9117 "-webkit-mask-composite: xor",
9118 "-webkit-mask-composite: destination-out",
9119 ] {
9120 let (_, x, d) = map_full(&format!(
9121 "mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); {composite}"
9122 ));
9123 assert!(d.is_empty() && x.mask_ring(), "{composite}: {d:?}");
9124 }
9125 let (_, x, d) =
9126 map_full("mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)");
9127 assert!(d.is_empty(), "{d:?}");
9128 assert!(!x.mask_ring());
9129 let (_, x, d) = map_full(
9130 "mask-image: linear-gradient(red, blue), linear-gradient(#fff 0 0);
9131 mask-clip: content-box, border-box; mask-composite: exclude",
9132 );
9133 assert!(d.is_empty() && x.mask_ring(), "{d:?}");
9134 let (_, x, _) = map_full(&format!(
9136 "{ring}; mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)"
9137 ));
9138 assert!(!x.mask_ring());
9139
9140 for other in [
9141 "mask-image: linear-gradient(to right, black 90%, transparent)",
9142 "mask-image: url(icon.svg)",
9143 "mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); mask-composite: intersect",
9144 ] {
9145 assert!(!map_full(other).1.mask_ring(), "{other}");
9146 }
9147 let (_, x, d) = map_full("mask: none");
9148 assert!(d.is_empty() && !x.mask_ring(), "{d:?}");
9149 }
9150
9151 #[test]
9152 fn a_mask_resolves_to_layers_with_their_size_position_and_repeat() {
9153 use TileLength::{Fraction as F, Pixels as P};
9154 let (_, x, d) = map_full(
9155 "mask-image: url(icons/check.svg); mask-size: contain; mask-repeat: no-repeat;
9156 mask-position: center",
9157 );
9158 assert!(d.is_empty(), "{d:?}");
9159 let stack = x.resolve_mask_stack().expect("a mask");
9160 assert!(!stack.luminance);
9161 assert_eq!(
9162 stack.layers,
9163 vec![PaintLayer::Image {
9164 url: "icons/check.svg".into(),
9165 size: BackgroundSize::Contain,
9166 position: (F(0.5), F(0.5)),
9167 repeat: (false, false),
9168 }]
9169 );
9170
9171 let (_, x, d) = map_full(
9173 "mask: url(a.png) 4px 0 / 10px 20px repeat-x, \
9174 linear-gradient(to bottom, #000 80%, transparent) luminance",
9175 );
9176 assert!(d.iter().any(|d| d.contains("mask-mode")), "{d:?}");
9177 let stack = x.resolve_mask_stack().expect("a mask");
9178 let [PaintLayer::Gradient(_), PaintLayer::Image {
9179 size,
9180 position,
9181 repeat,
9182 ..
9183 }] = stack.layers.as_slice()
9184 else {
9185 panic!("{:?}", stack.layers)
9186 };
9187 assert_eq!(*size, BackgroundSize::Explicit(Some(P(10.)), Some(P(20.))));
9188 assert_eq!(*position, (P(4.), P(0.)));
9189 assert_eq!(*repeat, (true, false));
9190
9191 let (_, x, _) = map_full("mask-image: url(a.svg); mask-image: none");
9192 assert_eq!(x.resolve_mask_stack(), None);
9193 let (_, x, _) =
9194 map_full("mask-image: linear-gradient(#000, transparent); mask-mode: luminance");
9195 assert!(x.resolve_mask_stack().expect("a mask").luminance);
9196 }
9197
9198 #[test]
9199 fn a_webkit_mask_is_ignored_and_the_ring_still_cuts() {
9200 for prefixed in [
9201 "-webkit-mask-image: url(icon.svg)",
9202 "-webkit-mask: url(icon.svg) center / contain no-repeat",
9203 ] {
9204 let (_, x, d) = map_full(prefixed);
9205 assert_eq!(x.resolve_mask_stack(), None, "{prefixed}");
9206 assert_eq!(d.len(), 1, "{prefixed}: {d:?}");
9207 }
9208 let (_, x, _) =
9209 map_full("mask-image: url(icon.svg); -webkit-mask-position: 0 0; mask-position: right");
9210 let stack = x.resolve_mask_stack().expect("a mask");
9211 assert!(
9212 matches!(stack.layers[0], PaintLayer::Image { position: (TileLength::Fraction(f), _), .. } if f == 1.0),
9213 "{stack:?}"
9214 );
9215 let ring = "-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
9216 -webkit-mask-composite: xor";
9217 let (_, x, d) = map_full(ring);
9218 assert!(d.is_empty() && x.mask_ring(), "{d:?}");
9219 assert_eq!(x.resolve_mask_stack(), None);
9220 }
9221
9222 #[test]
9223 fn clip_path_is_a_rounded_mask_and_the_other_shapes_are_dropped() {
9224 use gpui::{VnClipBox as B, VnClipPath as C, VnCornerRadius, VnShapeRadius as R};
9225 let at = |x: f32, y: f32| VnCornerRadius {
9226 x: px(x).into(),
9227 y: px(y).into(),
9228 };
9229 let half = relative(0.5);
9230 for sr_only in ["clip-path: inset(50%)", "clip-path: inset(50% 50% 50% 50%)"] {
9231 let r = clean(sr_only);
9232 assert_eq!(r.visibility, None, "{sr_only}");
9233 assert_eq!(
9234 r.vn_clip_path,
9235 Some(C::Inset {
9236 reference: B::Border,
9237 insets: [half; 4],
9238 radii: [at(0., 0.); 4]
9239 }),
9240 "{sr_only}"
9241 );
9242 }
9243 assert_eq!(
9244 clean("clip-path: inset(10px 20% round 8px 8px 8px 4px / 8px 8px 8px 6px) padding-box")
9245 .vn_clip_path,
9246 Some(C::Inset {
9247 reference: B::Padding,
9248 insets: [px(10.).into(), relative(0.2), px(10.).into(), relative(0.2)],
9249 radii: [at(8., 8.), at(8., 8.), at(8., 8.), at(4., 6.)],
9250 })
9251 );
9252 assert_eq!(
9253 clean("clip-path: circle(40%)").vn_clip_path,
9254 Some(C::Ellipse {
9255 reference: B::Border,
9256 center: [half, half],
9257 radius: [R::Length(relative(0.4)); 2],
9258 circle: true,
9259 })
9260 );
9261 assert_eq!(
9262 clean("clip-path: circle(at right 10px top) content-box").vn_clip_path,
9263 Some(C::Ellipse {
9264 reference: B::Content,
9265 center: [
9266 DefiniteLength::Calc {
9267 fraction: 1.0,
9268 pixels: px(-10.)
9269 },
9270 relative(0.)
9271 ],
9272 radius: [R::ClosestSide; 2],
9273 circle: true,
9274 })
9275 );
9276 assert_eq!(
9277 clean("clip-path: ellipse(30% farthest-side at 25% 75%)").vn_clip_path,
9278 Some(C::Ellipse {
9279 reference: B::Border,
9280 center: [relative(0.25), relative(0.75)],
9281 radius: [R::Length(relative(0.3)), R::FarthestSide],
9282 circle: false,
9283 })
9284 );
9285 assert!(clean("clip-path: ellipse(20px 20px)")
9286 .vn_clip_path
9287 .is_some());
9288 assert_eq!(
9289 clean("clip-path: margin-box").vn_clip_path,
9290 Some(C::Box(B::Margin))
9291 );
9292 assert_eq!(
9293 clean("clip-path: fill-box").vn_clip_path,
9294 Some(C::Box(B::Content))
9295 );
9296 assert_eq!(
9297 clean("clip-path: stroke-box").vn_clip_path,
9298 Some(C::Box(B::Border))
9299 );
9300 for other in [
9301 "url(#c)",
9302 "rect(0 10px 10px 0)",
9303 "xywh(0 0 10px 10px)",
9304 "shape(from 0 0, line to 10px 10px)",
9305 ] {
9306 let (r, _) = map(&format!("clip-path: {other}"));
9307 assert_eq!(r.vn_clip_path, None, "{other}");
9308 }
9309 let r = clean("clip-path: none");
9310 assert_eq!((r.vn_clip_path, r.visibility), (Some(C::None), None));
9311 }
9312
9313 #[test]
9314 fn clip_path_polygon_and_path_are_shapes() {
9315 use gpui::{VnClipBox as B, VnClipPath as C, VnFillRule as F, VnPathVerb::*};
9316 let polygon = |r: &StyleRefinement| match &r.vn_clip_path {
9317 Some(C::Polygon {
9318 reference,
9319 fill_rule,
9320 points,
9321 }) => (*reference, *fill_rule, points.to_vec()),
9322 other => panic!("{other:?}"),
9323 };
9324 assert_eq!(
9325 polygon(&clean("clip-path: polygon(50% 0, 100% 100%, 0 100%)")),
9326 (
9327 B::Border,
9328 F::NonZero,
9329 vec![
9330 [relative(0.5), px(0.).into()],
9331 [relative(1.), relative(1.)],
9332 [px(0.).into(), relative(1.)]
9333 ]
9334 )
9335 );
9336 let (rb, rule, points) = polygon(&clean(
9337 "clip-path: polygon(evenodd, calc(100% - 8px) 0, 8px 100%) content-box",
9338 ));
9339 assert_eq!((rb, rule), (B::Content, F::EvenOdd));
9340 assert_eq!(
9341 points[0],
9342 [
9343 DefiniteLength::Calc {
9344 fraction: 1.,
9345 pixels: px(-8.)
9346 },
9347 px(0.).into()
9348 ]
9349 );
9350 assert_eq!(points[1], [px(8.).into(), relative(1.)]);
9351
9352 let path = |r: &StyleRefinement| match &r.vn_clip_path {
9353 Some(C::Path {
9354 reference,
9355 fill_rule,
9356 verbs,
9357 }) => (*reference, *fill_rule, verbs.to_vec()),
9358 other => panic!("{other:?}"),
9359 };
9360 let notch = "clip-path: path('M0 0 C12.1506 0 22 9.8494 22 22 V42 Q22 64 44 64 H420 Q442 64 442 42 V22 C442 9.8494 451.8494 0 464 0 Z')";
9361 let (rb, rule, verbs) = path(&clean(notch));
9362 assert_eq!((rb, rule, verbs.len()), (B::Border, F::NonZero, 9));
9363 assert_eq!(verbs[3], QuadTo([22., 64.], [44., 64.]));
9364 let mut d = Vec::new();
9365 let inline = parse_inline_style(notch, &mut d);
9366 assert!(d.is_empty(), "{d:?}");
9367 assert!(format!("{inline:?}").contains("Path"), "{inline:?}");
9368 let (rb, rule, verbs) = path(&clean(
9369 r#"clip-path: path(evenodd, "M0 0 h10 v10 h-10 z M2 2 h6 v6 h-6 z") padding-box"#,
9370 ));
9371 assert_eq!((rb, rule, verbs.len()), (B::Padding, F::EvenOdd, 10));
9372 assert_eq!(verbs[5], MoveTo([2., 2.]));
9373 assert_eq!(path(&clean("clip-path: path('')")).2, vec![]);
9374 for bad in [
9375 "path('M0 0 L')",
9376 "path('L10 10')",
9377 "path(round, 'M0 0')",
9378 "path(evenodd)",
9379 "path('M0 0') blue",
9380 ] {
9381 let (r, _) = map(&format!("clip-path: {bad}"));
9382 assert_eq!(r.vn_clip_path, None, "{bad}");
9383 }
9384 }
9385}
9386
9387#[cfg(test)]
9388mod scrollbar_tests {
9389 use super::*;
9390
9391 fn extras_of(body: &str) -> Extras {
9392 let mut d = Vec::new();
9393 parse_inline_style(body, &mut d).extras
9394 }
9395
9396 #[test]
9397 fn scrollbar_color_takes_two_colours_thumb_first() {
9398 let x = extras_of("scrollbar-color: #ff0000 #0000ff");
9399 let (thumb, track) = x.scrollbar_color.expect("a pair");
9400 assert!(
9401 thumb.h < 0.02,
9402 "thumb is the first colour (red), got {thumb:?}"
9403 );
9404 assert!(
9405 (track.h - 0.6667).abs() < 0.02,
9406 "track is the second (blue), got {track:?}"
9407 );
9408 assert_eq!(extras_of("scrollbar-color: auto").scrollbar_color, None);
9409 assert_eq!(
9410 extras_of("scrollbar-color: red").scrollbar_color,
9411 None,
9412 "one colour is not a pair"
9413 );
9414 let named = extras_of("scrollbar-color: red blue");
9415 let (thumb, track) = named.scrollbar_color.expect("a pair of named colours");
9416 assert!(thumb.h < 0.02, "thumb is red, got {thumb:?}");
9417 assert!(
9418 (track.h - 0.6667).abs() < 0.02,
9419 "track is blue, got {track:?}"
9420 );
9421 }
9422
9423 #[test]
9424 fn overscroll_behavior_sets_both_axes_or_one() {
9425 let both = extras_of("overscroll-behavior: contain");
9426 assert_eq!(both.overscroll_x, Some(OverscrollBehavior::Contain));
9427 assert_eq!(both.overscroll_y, Some(OverscrollBehavior::Contain));
9428 let y = extras_of("overscroll-behavior-y: none");
9429 assert_eq!(y.overscroll_x, None);
9430 assert_eq!(y.overscroll_y, Some(OverscrollBehavior::None));
9431 }
9432
9433 #[test]
9434 fn a_malformed_inline_declaration_is_skipped_and_the_rest_applies() {
9435 let mut d = Vec::new();
9436 let inline = parse_inline_style("0: d; display: flex; }; gap: 4px", &mut d);
9437 let r = inline
9438 .refinement
9439 .expect("the valid declarations still apply");
9440 assert_eq!(r.display, Some(gpui::Display::Flex));
9441 assert!(
9442 r.gap.width.is_some(),
9443 "gap after the bad declarations applies too"
9444 );
9445 }
9446
9447 #[test]
9448 fn accepts_declaration_is_what_the_engine_applies() {
9449 assert!(accepts_declaration("display", "flex"));
9450 assert!(accepts_declaration("width", "10px"));
9451 assert!(accepts_declaration("width", "var(--w)"));
9452 assert!(accepts_declaration("color", "inherit"));
9453 assert!(accepts_declaration("--anything", "at all"));
9454 assert!(!accepts_declaration("width", "abc"));
9456 assert!(!accepts_declaration("width", "10qq"));
9457 assert!(!accepts_declaration("color", "notacolor"));
9458 assert!(!accepts_declaration("display", ""));
9459 assert!(!accepts_declaration("display", "flex; color: red"));
9461 assert!(!accepts_declaration("-ms-flex-pack", "center"));
9463 assert!(!accepts_declaration("-moz-appearance", "none"));
9466 assert!(!accepts_declaration("-moz-transition", "var(--t)"));
9467 assert!(accepts_declaration("-webkit-user-select", "none"));
9468 }
9469}
9470
9471#[cfg(test)]
9472mod prefix_tests {
9473 use super::*;
9474
9475 fn extras(body: &str) -> (Extras, Vec<String>) {
9476 let mut d = Vec::new();
9477 let inline = parse_inline_style(body, &mut d);
9478 (inline.extras, d)
9479 }
9480
9481 #[test]
9482 fn a_prefixed_declaration_the_engine_does_not_apply_is_dropped_without_a_word() {
9483 for body in [
9484 "-moz-osx-font-smoothing: grayscale",
9485 "-webkit-font-smoothing: antialiased",
9486 "-webkit-touch-callout: none",
9487 "-webkit-tap-highlight-color: transparent",
9488 "-webkit-overflow-scrolling: touch",
9489 "-ms-overflow-style: none",
9490 "-moz-tab-size: 4",
9491 "-moz-user-select: none",
9492 "-moz-appearance: none",
9493 "-ms-flex: 1",
9494 "-o-transition: opacity 1s",
9495 "-webkit-text-decoration: underline dotted",
9496 "-moz-transition: var(--t)",
9497 "-WEBKIT-TOUCH-CALLOUT: none",
9498 ] {
9499 let mut d = Vec::new();
9500 let inline = parse_inline_style(body, &mut d);
9501 assert!(d.is_empty(), "{body:?} said {d:?}");
9502 assert!(inline.is_empty(), "{body:?} applied something");
9503 }
9504 }
9505
9506 #[test]
9507 fn a_dropped_prefix_never_reaches_a_rule_and_an_honoured_one_does() {
9508 assert_eq!(extras("-moz-user-select: none").0.user_select, None);
9509 assert_eq!(
9510 extras("-webkit-user-select: none").0.user_select,
9511 Some(UserSelect::None)
9512 );
9513 fn block(body: &str) -> DeclarationBlock<'_> {
9514 DeclarationBlock::parse_string(body, ParserOptions::default()).expect("parses")
9515 }
9516 let c = convert_block(&block(
9517 "-moz-transition: opacity 1s; -ms-transform: scale(2); -webkit-touch-callout: none",
9518 ));
9519 assert!(c.normal.is_none() && c.normal_transitions.is_none());
9520 assert!(c.diagnostics.is_none(), "{:?}", c.diagnostics);
9521 let c = convert_block(&block(
9522 "-webkit-transition: opacity 1s; -webkit-transform: scale(2)",
9523 ));
9524 assert!(c.normal.is_some() && c.normal_transitions.is_some());
9525 assert!(c.diagnostics.is_none(), "{:?}", c.diagnostics);
9526 }
9527
9528 #[test]
9529 fn webkit_text_fill_color_is_a_glyph_colour() {
9530 let is_red = |f: Option<TextFill>| match f {
9531 Some(TextFill::Color(c)) => {
9532 c.h.abs() < 1e-3 && (c.s - 1.0).abs() < 1e-3 && (c.l - 0.5).abs() < 1e-3
9533 }
9534 _ => false,
9535 };
9536 assert!(is_red(
9537 extras("-webkit-text-fill-color: #ff0000").0.text_fill_color
9538 ));
9539 assert!(is_red(
9540 extras("-webkit-text-fill-color: red").0.text_fill_color
9541 ));
9542 assert_eq!(
9543 extras("-webkit-text-fill-color: currentColor")
9544 .0
9545 .text_fill_color,
9546 Some(TextFill::CurrentColor)
9547 );
9548 match extras("-webkit-text-fill-color: transparent")
9549 .0
9550 .text_fill_color
9551 {
9552 Some(TextFill::Color(c)) => assert_eq!(c.a, 0.0),
9553 other => panic!("{other:?}"),
9554 }
9555 let (x, d) = extras(
9556 "background-image: linear-gradient(90deg, #f00, #00f); -webkit-background-clip: text; \
9557 background-clip: text; -webkit-text-fill-color: transparent",
9558 );
9559 assert_eq!(x.background_clip_text, Some(true));
9560 assert!(x.text_fill_color.is_some());
9561 assert!(d.is_empty(), "{d:?}");
9562 assert_eq!(
9563 extras("-webkit-text-fill-color: 3px").0.text_fill_color,
9564 None
9565 );
9566 }
9567}