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