BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / layout_guard.rs

layout_guard.rs

layout_guard.rs 91.2 KiB Download Raw
1use std::collections::HashSet;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6
7const WIDGETS_FILE: &str = "widgets.rs";
8const SCAN_ALLOWLIST: &[(&str, &str)] = &[
9 ("views/toolbar_placement.rs", ".top(px(-SLOT_HEIGHT))"),
10 ("views/conversation.rs", ".bottom(px(-1.))"),
11];
12
13fn source_roots() -> Vec<PathBuf> {
14 let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
15 let mut roots: Vec<PathBuf> = fs::read_dir(&crates_directory)
16 .expect("read crates directory")
17 .map(|entry| entry.expect("directory entry").path())
18 .filter(|path| {
19 path.file_name()
20 .is_some_and(|name| name.to_string_lossy().starts_with("app"))
21 })
22 .map(|path| path.join("src"))
23 .filter(|path| path.is_dir())
24 .collect();
25 roots.sort();
26 roots
27}
28
29fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {
30 for entry in fs::read_dir(directory).expect("read source directory") {
31 let path = entry.expect("directory entry").path();
32 if path.is_dir() {
33 source_files(&path, files);
34 } else if path.extension().is_some_and(|extension| extension == "rs") {
35 files.push(path);
36 }
37 }
38}
39
40fn negative_offsets(
41 pattern: &Regex,
42 source: &str,
43 relative: &str,
44) -> Vec<(usize, Option<usize>, String)> {
45 pattern
46 .find_iter(source)
47 .map(|found| {
48 let line_number = source[..found.start()].matches('\n').count() + 1;
49 let from_match = &source[found.start()..];
50 let allowed = SCAN_ALLOWLIST.iter().position(|(allowed_file, snippet)| {
51 *allowed_file == relative && from_match.starts_with(snippet)
52 });
53 let line_end = from_match.find('\n').unwrap_or(from_match.len());
54 (
55 line_number,
56 allowed,
57 from_match[..line_end].trim().to_owned(),
58 )
59 })
60 .collect()
61}
62
63fn offset_pattern() -> Regex {
64 Regex::new(r"\.(top|right|bottom|left|inset)\(\s*(px\(\s*)?-").expect("pattern")
65}
66
67#[test]
68fn matcher_catches_wrapped_offsets() {
69 let source = "let a = 1;\nlet b = div()\n .top(\n px(-4.))\n .left(px(2.));\n";
70 let found = negative_offsets(&offset_pattern(), source, "views/other.rs");
71 assert_eq!(found, [(3, None, ".top(".to_owned())]);
72}
73
74#[test]
75fn matcher_matches_allowlist_from_match_start() {
76 let source = "x\n .bottom(px(-1.))\n";
77 let found = negative_offsets(&offset_pattern(), source, "views/conversation.rs");
78 assert_eq!(found, [(2, Some(1), ".bottom(px(-1.))".to_owned())]);
79}
80
81#[test]
82fn negative_offsets_go_through_corner_badge() {
83 let pattern = offset_pattern();
84 let mut matched_allowlist = HashSet::new();
85 let mut violations = Vec::new();
86 for root in source_roots() {
87 let mut files = Vec::new();
88 source_files(&root, &mut files);
89 for file in files {
90 let relative = file
91 .strip_prefix(&root)
92 .expect("inside src")
93 .to_string_lossy()
94 .replace('\\', "/");
95 if relative == WIDGETS_FILE || relative == "layout_guard.rs" {
96 continue;
97 }
98 let source = fs::read_to_string(&file).expect("read source file");
99 for (line_number, position, text) in negative_offsets(&pattern, &source, &relative) {
100 match position {
101 Some(position) => {
102 matched_allowlist.insert(position);
103 }
104 None => violations.push(format!(
105 "{relative}:{line_number}: negative absolute offset, use widgets::corner_badge: {text}"
106 )),
107 }
108 }
109 }
110 }
111 let stale: Vec<String> = SCAN_ALLOWLIST
112 .iter()
113 .enumerate()
114 .filter(|(position, _)| !matched_allowlist.contains(position))
115 .map(|(_, (file, snippet))| format!("stale allowlist entry, remove it: {file} {snippet}"))
116 .collect();
117 assert!(
118 violations.is_empty() && stale.is_empty(),
119 "{}",
120 violations
121 .into_iter()
122 .chain(stale)
123 .collect::<Vec<_>>()
124 .join("\n")
125 );
126}
127
128#[test]
129fn hover_styles_never_toggle_display() {
130 let toggle =
131 Regex::new(r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)").unwrap();
132 let mut files = Vec::new();
133 for root in source_roots() {
134 source_files(&root, &mut files);
135 }
136 let offenders: Vec<String> = files
137 .iter()
138 .flat_map(|path| {
139 let source = fs::read_to_string(path).unwrap();
140 source
141 .lines()
142 .enumerate()
143 .filter(|(_, line)| toggle.is_match(line))
144 .map(|(index, _)| format!("{}:{}", path.display(), index + 1))
145 .collect::<Vec<_>>()
146 })
147 .collect();
148 assert!(
149 offenders.is_empty(),
150 "hover styles must toggle visible()/invisible(), not display (gpui panics \"must call prepaint before paint\"): {offenders:?}"
151 );
152}
153
154mod frames {
155 use std::collections::HashSet;
156 use std::sync::Arc;
157 use std::time::Duration;
158
159 use gpui_kit::test::TestWindowExt as _;
160 use gpui_kit::{
161 AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,
162 VisualTestContext, WindowOptions, point, px, size,
163 };
164 use store::Store;
165
166 use std::time::Instant;
167
168 use calling::{CallState, CallUpdate, CaptionEntry, CaptionState, RosterEntry, call_channel};
169 use gpui_kit::Entity;
170
171 use crate::app_state::{AppHandle, AppState, Mode, Selection};
172 use crate::call::{ActiveCall, CallModel, ConsultCall};
173 use crate::demo;
174 use crate::settings::select_selector;
175 use crate::settings::{item_selector, label, label_selector, metrics};
176 use crate::settings_section::SettingsSection;
177 use crate::user_activity::UserInput;
178 use crate::views::call_transcript::TranscriptPanel;
179 use crate::views::call_view::CHAT_PANEL_TAG;
180 use crate::views::composer::{
181 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
182 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
183 };
184 use crate::views::conversation::{
185 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
186 CHANNEL_DETAILS_TAG,
187 };
188 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
189 use crate::views::message_row::BUBBLE_TAGS;
190 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
191 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
192 use crate::views::reaction_proposal_pill::REACTION_PILL;
193 use crate::views::recap_tab::RECAP_REGION;
194 use crate::views::shell::{
195 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
196 };
197 use crate::views::shortcuts::{
198 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
199 };
200 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
201 use crate::views::sidebar::chat_row_selector;
202 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
203 use crate::views::widgets::{
204 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
205 count_badge,
206 };
207 use gpui_kit::MouseButton;
208 use gpui_kit::component::fluent::{
209 DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,
210 OPTION_CHECK_INSET,
211 };
212 use gpui_kit::component::menu::selectors::{
213 ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,
214 label_selector as menu_label_selector,
215 };
216
217 const GUARDED: &[&str] = &[
218 "shell",
219 "shell/title-bar",
220 "shell/title-bar/search",
221 "shell/title-bar/own-status",
222 "shell/title-bar/own-status/avatar",
223 OWN_AVATAR_DISC,
224 "shell/islands",
225 "shell/islands/rail",
226 "shell/islands/sidebar",
227 "shell/islands/main",
228 ];
229 const CALL_GUARDED: &[&str] = &[
230 "shell/islands/main/call-header",
231 "shell/islands/main/call-stage",
232 "shell/islands/main/call-controls",
233 "shell/islands/main/call-controls/mic",
234 "shell/islands/main/call-controls/leave",
235 ];
236 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
237 const CALLS_TAGS: &[&str] = &[
238 "shell/islands/sidebar/calls-actions",
239 "shell/islands/sidebar/calls-actions/meet-now",
240 "shell/islands/sidebar/calls-actions/new-meeting",
241 ];
242 const PREJOIN_TAGS: &[&str] = &[
243 "shell/islands/main/prejoin",
244 "shell/islands/main/prejoin/preview",
245 "shell/islands/main/prejoin/controls",
246 "shell/islands/main/prejoin/devices",
247 "shell/islands/main/prejoin/audio",
248 "shell/islands/main/prejoin/actions",
249 ];
250 const PREJOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_guard%40thread.v2/0?context=%7b%22Tid%22%3a%22t%22%2c%22Oid%22%3a%22o%22%7d";
251 const CONSULT_GUARDED: &[&str] = &[
252 "shell/islands/main/call-header/call-consult",
253 "shell/islands/main/call-header/call-consult/transfer",
254 "shell/islands/main/call-header/call-consult/resume",
255 ];
256 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
257 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
258 const SHARE_GUARDED: &[&str] = &[
259 "shell/islands/main/call-stage/share-content",
260 "shell/islands/main/call-stage/share-content/zoom-chip",
261 "shell/islands/main/call-stage/share-divider",
262 "shell/islands/main/call-stage/share-strip",
263 ];
264 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
265 const OVERLAY_CHROME: &[&str] = &[
266 "shell/islands/main/call-header",
267 "shell/islands/main/call-stage",
268 ];
269 const MENU: &str = "popup-menu";
270 const OWN_STATUS: &str = "shell/title-bar/own-status";
271 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
272 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
273 const PROPOSAL_CHAT: &str = "demo-chat-release";
274 const REACTION_CHAT: &str = "demo-chat-mara";
275 const AGENT_TAGS: [&str; 4] = [
276 PROPOSAL_CARD,
277 PROPOSAL_THUMBNAILS,
278 PROPOSAL_BUTTONS,
279 REACTION_PILL,
280 ];
281 const SETTINGS_TAGS: &[&str] = &[
282 "settings",
283 "settings/nav",
284 "settings/nav/divider",
285 "settings/nav/about",
286 "settings/main",
287 "settings/main/header",
288 "settings/main/header/close",
289 "settings/main/body",
290 ];
291 const SETTINGS_BODY: &str = "settings/main/body";
292 const SETTINGS_NAV: &str = "settings/nav";
293 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
294 const NAV_LABEL_SIZE: f32 = 14.;
295 const NAV_LINE_HEIGHT: f32 = 20.;
296 const SETTINGS_CONTENT: &str = "settings/main/body/content";
297 const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
298 const MEMBERS_CHAT: &str = "demo-chat-release";
299 const SIDEBAR: &str = "shell/islands/sidebar";
300 const MAIN: &str = "shell/islands/main";
301 const EDGE_DIVIDERS: &[&str] = &[SIDEBAR_SCROLL_DIVIDER, HEADER_DIVIDER];
302 const DIVIDER_SEGMENT: &str = "divider";
303 const DIVIDER_THICKNESS: f32 = 1.;
304 const INSET_TOLERANCE: f32 = 1.;
305 const INSET_RULES: &[InsetRule] = &[
306 InsetRule {
307 panel: "settings/nav",
308 content: "settings/nav/about",
309 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
310 },
311 InsetRule {
312 panel: "settings/main",
313 content: "settings/main/header/close",
314 edges: &[Edge::Top, Edge::Right],
315 },
316 ];
317 const SCROLLED_INSET_RULE: InsetRule = InsetRule {
318 panel: SETTINGS_BODY,
319 content: SETTINGS_CONTENT,
320 edges: &[Edge::Left, Edge::Bottom],
321 };
322 const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
323 SettingsSection::Agents,
324 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
325 )];
326 const SETTINGS_SECTIONS: [SettingsSection; 9] = [
327 SettingsSection::General,
328 SettingsSection::Notifications,
329 SettingsSection::Appearance,
330 SettingsSection::Chats,
331 SettingsSection::Calls,
332 SettingsSection::Devices,
333 SettingsSection::Agents,
334 SettingsSection::Mcp,
335 SettingsSection::About,
336 ];
337 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
338 const TOLERANCE: f32 = 0.5;
339 const KNOWN_VIOLATIONS: &[&str] = &[];
340 const ZOOM_STEP: f32 = 1.25;
341
342 type Tag = (&'static str, Bounds<Pixels>);
343
344 #[derive(Clone, Copy, Debug)]
345 enum Edge {
346 Top,
347 Right,
348 Bottom,
349 Left,
350 }
351
352 struct InsetRule {
353 panel: &'static str,
354 content: &'static str,
355 edges: &'static [Edge],
356 }
357
358 fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {
359 f32::from(match edge {
360 Edge::Top => content.top() - panel.top(),
361 Edge::Right => panel.right() - content.right(),
362 Edge::Bottom => panel.bottom() - content.bottom(),
363 Edge::Left => content.left() - panel.left(),
364 })
365 }
366
367 fn inset_violation(
368 rule: &InsetRule,
369 panel: Bounds<Pixels>,
370 content: Bounds<Pixels>,
371 ) -> Option<(String, String)> {
372 let insets: Vec<(Edge, f32)> = rule
373 .edges
374 .iter()
375 .map(|edge| (*edge, inset(panel, content, *edge)))
376 .collect();
377 let values = insets.iter().map(|(_, value)| *value);
378 let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);
379 (spread > INSET_TOLERANCE).then(|| {
380 (
381 format!("{}:uneven-inset", rule.panel),
382 format!(
383 "{} insets {} by {insets:?}, they must match",
384 rule.panel, rule.content
385 ),
386 )
387 })
388 }
389
390 fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {
391 let bounds_of = |path: &str| {
392 tags.iter()
393 .find(|(tag, _)| *tag == path)
394 .map(|(_, bounds)| *bounds)
395 };
396 rules
397 .iter()
398 .filter_map(
399 |rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {
400 (Some(panel), Some(content)) => inset_violation(rule, panel, content),
401 _ => None,
402 },
403 )
404 .collect()
405 }
406
407 fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {
408 let mut found = Vec::new();
409 for (path, bounds) in tags {
410 let Some((parent, segment)) = path.rsplit_once('/') else {
411 continue;
412 };
413 if !segment.starts_with(DIVIDER_SEGMENT) {
414 continue;
415 }
416 let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {
417 found.push((
418 format!("{path}:no-panel"),
419 format!("{path} needs its panel {parent} tagged"),
420 ));
421 continue;
422 };
423 let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;
424 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
425 let spans = if thin(bounds.size.height) {
426 near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())
427 } else if thin(bounds.size.width) {
428 near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())
429 } else {
430 false
431 };
432 if !spans {
433 found.push((
434 format!("{path}:short-divider"),
435 format!(
436 "{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",
437 describe(*bounds),
438 describe(*panel)
439 ),
440 ));
441 }
442 }
443 found
444 }
445
446 enum Screen {
447 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
448 StatusMenu,
449 Call,
450 Prejoin,
451 CallTranscript,
452 CallPeople,
453 CallShare,
454 CallConsult,
455 }
456
457 fn parent_of(path: &str) -> Option<&str> {
458 path.rsplit_once('/').map(|(parent, _)| parent)
459 }
460
461 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
462 let tolerance = px(TOLERANCE);
463 inner.left() >= outer.left() - tolerance
464 && inner.top() >= outer.top() - tolerance
465 && inner.right() <= outer.right() + tolerance
466 && inner.bottom() <= outer.bottom() + tolerance
467 }
468
469 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
470 let tolerance = px(TOLERANCE);
471 first.left() < second.right() - tolerance
472 && second.left() < first.right() - tolerance
473 && first.top() < second.bottom() - tolerance
474 && second.top() < first.bottom() - tolerance
475 }
476
477 fn describe(bounds: Bounds<Pixels>) -> String {
478 format!(
479 "[{:.1},{:.1} {:.1}x{:.1}]",
480 f32::from(bounds.origin.x),
481 f32::from(bounds.origin.y),
482 f32::from(bounds.size.width),
483 f32::from(bounds.size.height)
484 )
485 }
486
487 fn violations(
488 tags: &[Tag],
489 window: Bounds<Pixels>,
490 expected: &[&str],
491 ) -> Vec<(String, String)> {
492 let mut found = Vec::new();
493 let bounds_of = |path: &str| {
494 tags.iter()
495 .find(|(tag, _)| *tag == path)
496 .map(|(_, bounds)| *bounds)
497 };
498 for path in expected {
499 if bounds_of(path).is_none() {
500 found.push((
501 format!("{path}:missing"),
502 format!("{path} was not rendered"),
503 ));
504 }
505 }
506 for (path, bounds) in tags {
507 if !contains(window, *bounds) {
508 found.push((
509 format!("{path}:outside-window"),
510 format!(
511 "{path} {} leaves the window {}",
512 describe(*bounds),
513 describe(window)
514 ),
515 ));
516 }
517 if let Some(parent) =
518 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
519 {
520 if !contains(parent.1, *bounds) {
521 found.push((
522 format!("{path}:outside-parent"),
523 format!(
524 "{path} {} leaves {} {}",
525 describe(*bounds),
526 parent.0,
527 describe(parent.1)
528 ),
529 ));
530 }
531 }
532 for (other, other_bounds) in tags {
533 let overlays = |first: &str, second: &str| {
534 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
535 };
536 let siblings = path < other
537 && parent_of(path).is_some()
538 && parent_of(path) == parent_of(other)
539 && !overlays(path, other)
540 && !overlays(other, path);
541 if siblings && overlaps(*bounds, *other_bounds) {
542 found.push((
543 format!("{path}:overlaps:{other}"),
544 format!(
545 "{path} {} overlaps {other} {}",
546 describe(*bounds),
547 describe(*other_bounds)
548 ),
549 ));
550 }
551 }
552 }
553 found.extend(divider_violations(tags));
554 found
555 }
556
557 const SETTLE_FRAMES: usize = 2;
558 const SETTLE_LIMIT: usize = 60;
559 const SETTLE_STEP: Duration = Duration::from_millis(50);
560
561 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
562 let mut frames = 0;
563 while frames < SETTLE_FRAMES
564 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
565 {
566 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
567 visual.executor().advance_clock(SETTLE_STEP);
568 std::thread::sleep(SETTLE_STEP);
569 visual.run_until_parked();
570 visual.update(|window, cx| window.render_frame(cx));
571 frames += 1;
572 }
573 GUARDED
574 .iter()
575 .chain(CALL_GUARDED)
576 .chain(CALLS_TAGS)
577 .chain(PREJOIN_TAGS)
578 .chain(SHARE_GUARDED)
579 .chain(CONSULT_GUARDED)
580 .chain([
581 &AGENTS_LIST,
582 &CALL_TRANSCRIPT,
583 &MENU,
584 &RECAP_TAB,
585 &RECAP_REGION,
586 &PEOPLE_PANEL,
587 ])
588 .chain(&AGENT_TAGS)
589 .chain(SETTINGS_TAGS)
590 .chain(MEMBERS_TAGS)
591 .chain(EDGE_DIVIDERS)
592 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
593 .collect()
594 }
595
596 fn sharing_call() -> ActiveCall {
597 let mut call = gallery_call();
598 call.model
599 .apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
600 call.share_stage.view.step_in((800., 450.));
601 call
602 }
603
604 fn gallery_call() -> ActiveCall {
605 let (handle, _control) = call_channel();
606 let mut model = CallModel::meeting("Standup", false);
607 model.apply(CallUpdate::State(CallState::Connected {
608 since: Instant::now(),
609 }));
610 model.apply(CallUpdate::Roster(
611 (0..11)
612 .map(|index| RosterEntry {
613 mri: format!("8:orgid:guard-{index}"),
614 display_name: format!("Guest {index}"),
615 muted: false,
616 in_lobby: false,
617 has_video: false,
618 sharing: false,
619 hand: None,
620 spotlight: None,
621 organizer: false,
622 ..Default::default()
623 })
624 .collect(),
625 ));
626 ActiveCall::new(1, model, handle.commands, None, handle.video)
627 }
628
629 fn consult_calls() -> (ActiveCall, ActiveCall) {
630 let connected = |id: u64, name: &str, mri: &str| {
631 let (handle, _control) = call_channel();
632 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
633 model.apply(CallUpdate::State(CallState::Connected {
634 since: Instant::now(),
635 }));
636 ActiveCall::new(id, model, handle.commands, None, handle.video)
637 };
638 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
639 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
640 consult.consult = Some(ConsultCall::new(
641 (
642 "8:orgid:guard-consult".to_owned(),
643 "Jonas Ortega".to_owned(),
644 ),
645 held.model.peer_name.clone(),
646 ));
647 (consult, held)
648 }
649
650 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
651 mount_with(cx, false)
652 }
653
654 fn mount_with(
655 cx: &mut TestAppContext,
656 agent_api: bool,
657 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
658 cx.update(gpui_kit::init);
659 cx.update(|cx| {
660 crate::theme::apply(cx);
661 bind_keys(cx);
662 let store = Store::open_in_memory().expect("in-memory store");
663 demo::seed(&store);
664 let store = Arc::new(store);
665 if agent_api {
666 crate::agent_api::init(store.clone(), true, cx);
667 }
668 let mode = Mode {
669 demo: true,
670 read_only: false,
671 demo_sync: None,
672 };
673 let state = cx.new(|_| AppState::new(store, mode));
674 install_globals(&state, UserInput::new(), cx);
675 crate::agents::install(state.clone(), cx);
676 demo::start_session(&state, cx);
677 let shared_state = state.clone();
678 let startup = Startup {
679 switcher_query: None,
680 composer_text: None,
681 reply_to_last: false,
682 };
683 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
684 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
685 })
686 .expect("open test window")
687 .0;
688 (window, shared_state)
689 })
690 }
691
692 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
693 Bounds {
694 origin: point(px(left), px(top)),
695 size: size(px(width), px(height)),
696 }
697 }
698
699 #[test]
700 fn rules_flag_overlap_and_overflow() {
701 let window = rectangle(0., 0., 100., 100.);
702 let tags: Vec<Tag> = vec![
703 ("shell", rectangle(0., 0., 100., 100.)),
704 ("shell/islands", rectangle(0., 0., 100., 50.)),
705 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
706 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
707 ];
708 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
709 .into_iter()
710 .map(|(key, _)| key)
711 .collect();
712 let line_tags: Vec<Tag> = vec![
713 ("panel", rectangle(0., 0., 100., 100.)),
714 ("panel/divider", rectangle(0., 50., 100., 1.)),
715 ("panel/divider-inset", rectangle(12., 60., 76., 1.)),
716 ("panel/divider-side", rectangle(40., 0., 1., 100.)),
717 ("panel/about", rectangle(12., 76., 76., 12.)),
718 ("panel/footer", rectangle(12., 64., 76., 12.)),
719 ];
720 let line_keys: Vec<String> = divider_violations(&line_tags)
721 .into_iter()
722 .chain(inset_violations(
723 &line_tags,
724 &[
725 InsetRule {
726 panel: "panel",
727 content: "panel/about",
728 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
729 },
730 InsetRule {
731 panel: "panel",
732 content: "panel/footer",
733 edges: &[Edge::Left, Edge::Bottom],
734 },
735 ],
736 ))
737 .map(|(key, _)| key)
738 .collect();
739 assert_eq!(
740 line_keys,
741 ["panel/divider-inset:short-divider", "panel:uneven-inset"]
742 );
743 assert_eq!(
744 keys,
745 [
746 "shell/status-bar:missing",
747 "shell/islands/rail:overlaps:shell/islands/sidebar",
748 "shell/islands/sidebar:outside-window",
749 "shell/islands/sidebar:outside-parent",
750 ]
751 );
752 }
753
754 #[gpui_kit::test]
755 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
756 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
757 }
758
759 #[gpui_kit::test]
760 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
761 let (width, height) = SIZES[1];
762 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
763 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
764 }
765
766 fn check_layout(
767 cx: &mut TestAppContext,
768 sizes: &[(f32, f32)],
769 zoom: f32,
770 known_violations: &[&str],
771 ) {
772 let (handle, app) = mount(cx);
773 let platform_scale = cx
774 .update_window(handle, |_, window, _| window.scale_factor())
775 .expect("test window");
776 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
777 let mut visual = VisualTestContext::from_window(handle, cx);
778 let mut seen_known = HashSet::new();
779 let mut unexpected = Vec::new();
780 for &(width, height) in sizes {
781 visual.simulate_resize(size(px(width), px(height)));
782 let window = Bounds {
783 origin: point(px(0.), px(0.)),
784 size: size(px(width), px(height)),
785 };
786 let screens = [
787 Screen::Tab("chats", None),
788 Screen::Tab(
789 "activity",
790 Some(|visual| visual.dispatch_action(OpenActivity)),
791 ),
792 Screen::Tab(
793 "channels",
794 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
795 ),
796 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
797 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
798 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
799 Screen::Prejoin,
800 Screen::StatusMenu,
801 Screen::Call,
802 Screen::CallTranscript,
803 Screen::CallPeople,
804 Screen::CallShare,
805 Screen::CallConsult,
806 ];
807 for screen in screens {
808 let (screen_name, status_menu) = match screen {
809 Screen::Tab(name, open) => {
810 if let Some(open) = open {
811 open(&mut visual);
812 }
813 (name, false)
814 }
815 Screen::Call | Screen::CallPeople => {
816 let people_open = matches!(screen, Screen::CallPeople);
817 visual.update(|_, cx| {
818 app.update(cx, |state, cx| {
819 let mut call = gallery_call();
820 call.people_open = people_open;
821 state.call = Some(call);
822 cx.notify();
823 })
824 });
825 (if people_open { "call-people" } else { "call" }, false)
826 }
827 Screen::Prejoin => {
828 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
829 visual.update(|_, cx| {
830 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
831 });
832 ("prejoin", false)
833 }
834 Screen::CallTranscript => {
835 visual.update(|window, cx| {
836 app.update(cx, |state, cx| {
837 let mut call = gallery_call();
838 call.model.apply(CallUpdate::Captions(CaptionState::On));
839 for index in 0..40 {
840 call.model.note_caption(
841 CaptionEntry {
842 id: format!("guard-{index}"),
843 user_id: "8:orgid:guard-0".into(),
844 display_name: "Guest 0".into(),
845 text: "A long guarded sentence that has to wrap inside the panel".into(),
846 is_final: true,
847 },
848 Instant::now(),
849 );
850 }
851 call.transcript_open = true;
852 state.call = Some(call);
853 let app_entity = cx.entity();
854 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
855 cx.notify();
856 })
857 });
858 ("call-transcript", false)
859 }
860 Screen::CallShare => {
861 visual.update(|_, cx| {
862 app.update(cx, |state, cx| {
863 state.call = Some(sharing_call());
864 cx.notify();
865 })
866 });
867 ("call-share", false)
868 }
869 Screen::CallConsult => {
870 visual.update(|_, cx| {
871 app.update(cx, |state, cx| {
872 let (consult, held) = consult_calls();
873 state.call = Some(consult);
874 state.held_call = Some(held);
875 cx.notify();
876 })
877 });
878 ("call-consult", false)
879 }
880 Screen::StatusMenu => {
881 let tags = collect(&mut visual, None);
882 let button = tags
883 .iter()
884 .find(|(path, _)| *path == OWN_STATUS)
885 .map(|(_, bounds)| *bounds)
886 .expect("own status button rendered");
887 visual.simulate_click(button.center(), Default::default());
888 ("status-menu", true)
889 }
890 };
891 let is_call = matches!(
892 screen_name,
893 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
894 );
895 let tags = collect(&mut visual, status_menu.then_some(MENU));
896 let mut expected = GUARDED.to_vec();
897 if is_call {
898 expected.extend(CALL_GUARDED);
899 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
900 if sidebar_hidden_in_call(width, panel_open) {
901 expected.retain(|path| *path != "shell/islands/sidebar");
902 }
903 }
904 if screen_name == "call-transcript" {
905 expected.push(CALL_TRANSCRIPT);
906 }
907 if screen_name == "call-people" {
908 expected.push(PEOPLE_PANEL);
909 }
910 if screen_name == "call-share" {
911 expected.extend(SHARE_GUARDED);
912 }
913 if screen_name == "call-consult" {
914 expected.extend(CONSULT_GUARDED);
915 }
916 if status_menu {
917 expected.push(MENU);
918 }
919 match screen_name {
920 "calls" => expected.extend(CALLS_TAGS),
921 "agents" => expected.push(AGENTS_LIST),
922 "prejoin" => expected.extend(PREJOIN_TAGS),
923 _ => {}
924 }
925 let mut found = violations(&tags, window, &expected);
926 if status_menu {
927 let menu = tags
928 .iter()
929 .find(|(path, _)| *path == MENU)
930 .map(|(_, bounds)| *bounds);
931 let button = tags
932 .iter()
933 .find(|(path, _)| *path == OWN_STATUS)
934 .map(|(_, bounds)| *bounds);
935 if let (Some(menu), Some(button)) = (menu, button) {
936 if overlaps(menu, button) {
937 found.push((
938 format!("{MENU}:covers:{OWN_STATUS}"),
939 format!(
940 "{MENU} {} covers {OWN_STATUS} {}",
941 describe(menu),
942 describe(button)
943 ),
944 ));
945 }
946 }
947 visual.simulate_keystrokes("escape");
948 visual.run_until_parked();
949 }
950 if is_call {
951 visual.update(|_, cx| {
952 app.update(cx, |state, cx| {
953 state.call = None;
954 state.held_call = None;
955 cx.notify();
956 })
957 });
958 }
959 if screen_name == "prejoin" {
960 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
961 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
962 }
963 for (key, message) in found {
964 let full_key = format!("{screen_name}@{width}x{height}:{key}");
965 if known_violations.contains(&full_key.as_str()) {
966 seen_known.insert(full_key);
967 } else {
968 unexpected.push(format!("{full_key}: {message}"));
969 }
970 }
971 }
972 }
973 let stale: Vec<String> = known_violations
974 .iter()
975 .filter(|key| !seen_known.contains(**key))
976 .map(|key| format!("stale known violation, remove it: {key}"))
977 .collect();
978 assert!(
979 unexpected.is_empty() && stale.is_empty(),
980 "{}",
981 unexpected
982 .into_iter()
983 .chain(stale)
984 .collect::<Vec<_>>()
985 .join("\n")
986 );
987 }
988 #[gpui_kit::test]
989 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
990 let (handle, _) = mount(cx);
991 let mut visual = VisualTestContext::from_window(handle, cx);
992 visual.simulate_resize(size(px(1280.), px(800.)));
993 collect(&mut visual, Some(OWN_AVATAR_DISC));
994 let disc = visual
995 .debug_bounds(OWN_AVATAR_DISC)
996 .expect("own avatar rendered");
997 let bar = visual
998 .debug_bounds("shell/title-bar")
999 .expect("title bar rendered");
1000 assert_eq!(
1001 f32::from(disc.size.width),
1002 TITLE_AVATAR_SIZE,
1003 "{}",
1004 describe(disc)
1005 );
1006 assert_eq!(
1007 f32::from(disc.size.height),
1008 TITLE_AVATAR_SIZE,
1009 "{}",
1010 describe(disc)
1011 );
1012 let top = f32::from(disc.top() - bar.top());
1013 let bottom = f32::from(bar.bottom() - disc.bottom());
1014 assert!(
1015 (top - bottom).abs() <= 1.,
1016 "own avatar {} is not centered in the title bar {}",
1017 describe(disc),
1018 describe(bar)
1019 );
1020 }
1021
1022 const TITLE_SEARCH: &str = "shell/title-bar/search";
1023 const TITLE_NEIGHBOURS: &[&str] = &[
1024 "shell/title-bar/leading",
1025 "shell/title-bar/mode-pill",
1026 "shell/title-bar/trailing",
1027 "shell/title-bar/update",
1028 OWN_STATUS,
1029 ];
1030 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
1031 (1920., 1080., true),
1032 (1280., 800., true),
1033 (640., 480., false),
1034 ];
1035
1036 #[gpui_kit::test]
1037 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
1038 let (handle, _) = mount(cx);
1039 let mut visual = VisualTestContext::from_window(handle, cx);
1040 let shell = visual.update(|window, cx| {
1041 window
1042 .root::<gpui_kit::base::Root>()
1043 .flatten()
1044 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
1045 .expect("app shell is the root view")
1046 });
1047 visual.update(|_, cx| {
1048 shell.update(cx, |shell, cx| {
1049 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
1050 })
1051 });
1052 let mut found = Vec::new();
1053 for (width, height, centered) in TITLE_SEARCH_SIZES {
1054 visual.simulate_resize(size(px(width), px(height)));
1055 collect(&mut visual, Some(TITLE_SEARCH));
1056 let search = visual
1057 .debug_bounds(TITLE_SEARCH)
1058 .expect("title search rendered");
1059 let search_center = f32::from(search.center().x);
1060 eprintln!(
1061 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
1062 describe(search),
1063 width / 2.
1064 );
1065 if centered && (search_center - width / 2.).abs() > 1. {
1066 found.push(format!(
1067 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
1068 width / 2.
1069 ));
1070 }
1071 if !contains(rectangle(0., 0., width, height), search) {
1072 found.push(format!(
1073 "@{width}x{height}: search {} leaves the window",
1074 describe(search)
1075 ));
1076 }
1077 for neighbour in TITLE_NEIGHBOURS {
1078 match visual.debug_bounds(neighbour) {
1079 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
1080 Some(bounds) if overlaps(search, bounds) => found.push(format!(
1081 "@{width}x{height}: search {} overlaps {neighbour} {}",
1082 describe(search),
1083 describe(bounds)
1084 )),
1085 Some(_) => {}
1086 }
1087 }
1088 }
1089 assert!(found.is_empty(), "{}", found.join("\n"));
1090 }
1091
1092 #[gpui_kit::test]
1093 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
1094 let (handle, app) = mount(cx);
1095 let mut visual = VisualTestContext::from_window(handle, cx);
1096 for (width, height) in SIZES {
1097 visual.simulate_resize(size(px(width), px(height)));
1098 visual.update(|_, cx| {
1099 app.update(cx, |state, cx| {
1100 let mut call = gallery_call();
1101 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
1102 call.chat_open = true;
1103 state.call = Some(call);
1104 cx.notify();
1105 })
1106 });
1107 collect(&mut visual, Some(CHAT_PANEL_TAG));
1108 let panel = visual
1109 .debug_bounds(CHAT_PANEL_TAG)
1110 .expect("chat panel rendered");
1111 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
1112 .iter()
1113 .enumerate()
1114 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
1115 .collect();
1116 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
1117 let found: Vec<String> = bubbles
1118 .into_iter()
1119 .filter(|(_, bounds)| {
1120 !inside_horizontally(panel, *bounds) || !overlaps(panel, *bounds)
1121 })
1122 .map(|(index, bounds)| {
1123 format!(
1124 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
1125 describe(bounds),
1126 describe(panel)
1127 )
1128 })
1129 .collect();
1130 visual.update(|_, cx| {
1131 app.update(cx, |state, cx| {
1132 state.call = None;
1133 cx.notify();
1134 })
1135 });
1136 assert!(found.is_empty(), "{}", found.join("\n"));
1137 }
1138 }
1139
1140 fn inside_horizontally(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
1141 let tolerance = px(TOLERANCE);
1142 inner.left() >= outer.left() - tolerance && inner.right() <= outer.right() + tolerance
1143 }
1144
1145 fn scroll_sidebar(visual: &mut VisualTestContext, delta: f32) {
1146 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1147 visual.simulate_event(ScrollWheelEvent {
1148 position: sidebar.center(),
1149 delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1150 ..Default::default()
1151 });
1152 }
1153
1154 #[gpui_kit::test]
1155 fn chat_list_line_shows_only_while_scrolled(cx: &mut TestAppContext) {
1156 let (handle, _) = mount(cx);
1157 let mut visual = VisualTestContext::from_window(handle, cx);
1158 for (width, height) in SIZES {
1159 visual.simulate_resize(size(px(width), px(height)));
1160 let window = Bounds {
1161 origin: point(px(0.), px(0.)),
1162 size: size(px(width), px(height)),
1163 };
1164 collect(&mut visual, None);
1165 scroll_sidebar(&mut visual, 100_000.);
1166 let tags = collect(&mut visual, None);
1167 assert!(
1168 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1169 "chat list at its top must not show the line at {width}x{height}"
1170 );
1171 scroll_sidebar(&mut visual, -120.);
1172 let scrolled = collect(&mut visual, Some(SIDEBAR_SCROLL_DIVIDER));
1173 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1174 let line = visual
1175 .debug_bounds(SIDEBAR_SCROLL_DIVIDER)
1176 .expect("scrolled chat list shows the line");
1177 assert!(
1178 line.top() > sidebar.top() + px(TOLERANCE),
1179 "the line sits under the Chats header, not on the island edge: {} in {}",
1180 describe(line),
1181 describe(sidebar)
1182 );
1183 let found: Vec<String> = violations(&scrolled, window, &[SIDEBAR_SCROLL_DIVIDER])
1184 .into_iter()
1185 .chain(violations(&tags, window, &[]))
1186 .map(|(key, message)| format!("chat-list@{width}x{height}:{key}: {message}"))
1187 .collect();
1188 assert!(found.is_empty(), "{}", found.join("\n"));
1189 scroll_sidebar(&mut visual, 100_000.);
1190 collect(&mut visual, None);
1191 assert!(
1192 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1193 "the line goes away once the chat list is back at its top"
1194 );
1195 }
1196 }
1197
1198 #[gpui_kit::test]
1199 fn header_tabs_sit_above_the_header_line(cx: &mut TestAppContext) {
1200 let (handle, state) = mount(cx);
1201 let mut visual = VisualTestContext::from_window(handle, cx);
1202 for (width, height) in SIZES {
1203 visual.simulate_resize(size(px(width), px(height)));
1204 let window = Bounds {
1205 origin: point(px(0.), px(0.)),
1206 size: size(px(width), px(height)),
1207 };
1208 visual.update(|_, cx| {
1209 state.update(cx, |state, cx| {
1210 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1211 })
1212 });
1213 let tags = collect(&mut visual, Some(RECAP_TAB));
1214 let main = visual.debug_bounds(MAIN).expect("main island rendered");
1215 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1216 let line = visual
1217 .debug_bounds(HEADER_DIVIDER)
1218 .expect("the header line is always shown");
1219 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
1220 assert!(
1221 tab.top() >= main.top() && near(tab.bottom(), line.top()),
1222 "tab {} must sit in the top bar above the line {}",
1223 describe(tab),
1224 describe(line)
1225 );
1226 let found: Vec<String> = violations(&tags, window, &[HEADER_DIVIDER, RECAP_TAB])
1227 .into_iter()
1228 .map(|(key, message)| format!("header@{width}x{height}:{key}: {message}"))
1229 .collect();
1230 assert!(found.is_empty(), "{}", found.join("\n"));
1231 }
1232 }
1233
1234 #[gpui_kit::test]
1235 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1236 let (handle, state) = mount(cx);
1237 let mut visual = VisualTestContext::from_window(handle, cx);
1238 for (width, height) in SIZES {
1239 visual.simulate_resize(size(px(width), px(height)));
1240 let window = Bounds {
1241 origin: point(px(0.), px(0.)),
1242 size: size(px(width), px(height)),
1243 };
1244 visual.update(|_, cx| {
1245 state.update(cx, |state, cx| {
1246 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1247 })
1248 });
1249 collect(&mut visual, Some(RECAP_TAB));
1250 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1251 visual.simulate_click(tab.center(), Default::default());
1252 let tags = collect(&mut visual, Some(RECAP_REGION));
1253 let mut expected = GUARDED.to_vec();
1254 expected.extend([RECAP_TAB, RECAP_REGION]);
1255 let found: Vec<String> = violations(&tags, window, &expected)
1256 .into_iter()
1257 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1258 .collect();
1259 assert!(found.is_empty(), "{}", found.join("\n"));
1260 }
1261 }
1262
1263 #[gpui_kit::test]
1264 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1265 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1266 }
1267
1268 #[gpui_kit::test]
1269 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1270 crate::theme::set_thread_scheme(Some("teams"));
1271 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1272 crate::theme::set_thread_scheme(None);
1273 }
1274
1275 #[gpui_kit::test]
1276 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1277 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1278 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1279 crate::theme::set_thread_shade(None);
1280 }
1281
1282 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1283 let (handle, state) = mount_with(cx, true);
1284 let mut visual = VisualTestContext::from_window(handle, cx);
1285 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1286 visual.simulate_resize(size(px(width), px(height)));
1287 let window = Bounds {
1288 origin: point(px(0.), px(0.)),
1289 size: size(px(width), px(height)),
1290 };
1291 let inset = metrics(width, height).inset;
1292 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1293 for &section in sections {
1294 visual
1295 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1296 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1297 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1298 .into_iter()
1299 .filter(|(key, _)| key.starts_with("settings"))
1300 .chain(inset_violations(&tags, INSET_RULES))
1301 .collect();
1302 if label_sizes {
1303 found.extend(nav_label_violations(&mut visual));
1304 }
1305 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1306 .iter()
1307 .any(|(exempt, _)| *exempt == section);
1308 if !scrolled_exempt {
1309 found.extend(scrolled_inset_violation(&mut visual));
1310 }
1311 let found: Vec<String> = found
1312 .into_iter()
1313 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1314 .collect();
1315 assert!(found.is_empty(), "{}", found.join("\n"));
1316 let dialog = visual
1317 .debug_bounds(SETTINGS_TAGS[0])
1318 .expect("settings dialog");
1319 let edges = [
1320 f32::from(dialog.left()),
1321 f32::from(dialog.top()),
1322 width - f32::from(dialog.right()),
1323 height - f32::from(dialog.bottom()),
1324 ];
1325 assert!(
1326 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1327 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1328 );
1329 }
1330 }
1331 }
1332
1333 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1334
1335 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1336 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1337 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1338 };
1339 let mut found = Vec::new();
1340 for section in SETTINGS_SECTIONS {
1341 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1342 let item_path: &'static str = if section == SettingsSection::About {
1343 SETTINGS_NAV_ABOUT
1344 } else {
1345 Box::leak(item_selector(section).into_boxed_str())
1346 };
1347 let (Some(label_bounds), Some(item)) = (
1348 visual.debug_bounds(label_path),
1349 visual.debug_bounds(item_path),
1350 ) else {
1351 if section != SettingsSection::Agents {
1352 found.push((label_path.to_owned(), "not rendered".to_owned()));
1353 }
1354 continue;
1355 };
1356 let text = label(section);
1357 let text_width = visual.update(|window, _| {
1358 let run = window.text_style().to_run(text.len());
1359 f32::from(
1360 window
1361 .text_system()
1362 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1363 .width,
1364 )
1365 });
1366 let label_width = f32::from(label_bounds.size.width);
1367 let label_height = f32::from(label_bounds.size.height);
1368 if text_width > label_width + TOLERANCE
1369 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1370 {
1371 found.push((
1372 label_path.to_owned(),
1373 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1374 ));
1375 }
1376 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1377 inner.left() < outer.left() - px(TOLERANCE)
1378 || inner.right() > outer.right() + px(TOLERANCE)
1379 || inner.top() < outer.top() - px(TOLERANCE)
1380 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1381 };
1382 if outside(label_bounds, item) {
1383 found.push((
1384 label_path.to_owned(),
1385 format!("label {label_bounds:?} outside item {item:?}"),
1386 ));
1387 }
1388 if item.left() < nav.left() || item.right() > nav.right() {
1389 found.push((
1390 item_path.to_owned(),
1391 format!("item {item:?} outside nav {nav:?}"),
1392 ));
1393 }
1394 }
1395 found
1396 }
1397
1398 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1399 let body = visual.debug_bounds(SETTINGS_BODY)?;
1400 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1401 if content.bottom() <= body.bottom() {
1402 return None;
1403 }
1404 visual.simulate_event(ScrollWheelEvent {
1405 position: body.center(),
1406 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1407 ..Default::default()
1408 });
1409 collect(visual, None);
1410 let body = visual.debug_bounds(SETTINGS_BODY)?;
1411 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1412 inset_violation(&SCROLLED_INSET_RULE, body, content)
1413 }
1414
1415 #[gpui_kit::test]
1416 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1417 let (handle, state) = mount(cx);
1418 let mut visual = VisualTestContext::from_window(handle, cx);
1419 for (width, height) in SIZES {
1420 visual.simulate_resize(size(px(width), px(height)));
1421 let window = Bounds {
1422 origin: point(px(0.), px(0.)),
1423 size: size(px(width), px(height)),
1424 };
1425 visual.update(|_, cx| {
1426 state.update(cx, |state, cx| {
1427 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1428 })
1429 });
1430 collect(&mut visual, Some(MEMBERS_BUTTON));
1431 let button = visual
1432 .debug_bounds(MEMBERS_BUTTON)
1433 .expect("members button rendered");
1434 visual.simulate_click(button.center(), Default::default());
1435 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1436 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1437 .into_iter()
1438 .filter(|(key, _)| key.starts_with("chat-members"))
1439 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1440 .collect();
1441 visual.simulate_keystrokes("escape");
1442 visual.run_until_parked();
1443 assert!(found.is_empty(), "{}", found.join("\n"));
1444 }
1445 }
1446
1447 const MENU_ITEMS_SCANNED: usize = 40;
1448 const MENU_CHAT: &str = "demo-chat-release";
1449 const THEME_SELECT: &str = "settings-theme";
1450
1451 struct MenuRow {
1452 index: usize,
1453 item: Bounds<Pixels>,
1454 icon: Option<Bounds<Pixels>>,
1455 label: Option<Bounds<Pixels>>,
1456 }
1457
1458 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1459 (0..MENU_ITEMS_SCANNED)
1460 .filter_map(|index| {
1461 let item =
1462 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1463 Some(MenuRow {
1464 index,
1465 item,
1466 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1467 label: visual
1468 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1469 })
1470 })
1471 .collect()
1472 }
1473
1474 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1475 let mut found = Vec::new();
1476 for row in rows {
1477 let Some(icon) = row.icon else {
1478 continue;
1479 };
1480 let key = format!("{MENU}/item-{}", row.index);
1481 if let Some(label) = row.label {
1482 let gap = f32::from(label.left() - icon.right());
1483 if (gap - expected_gap).abs() > TOLERANCE {
1484 found.push((
1485 format!("{key}:icon-gap"),
1486 format!(
1487 "icon {} to label {} is {gap} px, expected {expected_gap}",
1488 describe(icon),
1489 describe(label)
1490 ),
1491 ));
1492 }
1493 }
1494 let offset = f32::from(icon.center().y - row.item.center().y);
1495 if offset.abs() > TOLERANCE {
1496 found.push((
1497 format!("{key}:icon-off-centre"),
1498 format!(
1499 "icon {} sits {offset} px off the centre of item {}",
1500 describe(icon),
1501 describe(row.item)
1502 ),
1503 ));
1504 }
1505 }
1506 found
1507 }
1508
1509 fn listbox_violations(
1510 trigger: Bounds<Pixels>,
1511 menu: Bounds<Pixels>,
1512 items: Bounds<Pixels>,
1513 rows: &[MenuRow],
1514 ) -> Vec<(String, String)> {
1515 let mut found = Vec::new();
1516 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1517 if !near(f32::from(menu.left() - trigger.left()), 0.) {
1518 found.push((
1519 format!("{MENU}:not-aligned-to-trigger"),
1520 format!(
1521 "list {} must start at the trigger's left edge {}",
1522 describe(menu),
1523 describe(trigger)
1524 ),
1525 ));
1526 }
1527 if !near(
1528 f32::from(menu.top() - trigger.bottom()),
1529 f32::from(DROPDOWN_OFFSET),
1530 ) {
1531 found.push((
1532 format!("{MENU}:trigger-offset"),
1533 format!(
1534 "list {} must open {} px below the trigger {}",
1535 describe(menu),
1536 f32::from(DROPDOWN_OFFSET),
1537 describe(trigger)
1538 ),
1539 ));
1540 }
1541 if menu.size.width < trigger.size.width - px(TOLERANCE) {
1542 found.push((
1543 format!("{MENU}:narrower-than-trigger"),
1544 format!(
1545 "list {} is narrower than the trigger {}",
1546 describe(menu),
1547 describe(trigger)
1548 ),
1549 ));
1550 }
1551 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1552 let top = f32::from(first.item.top() - items.top());
1553 let bottom = f32::from(items.bottom() - last.item.bottom());
1554 let padding = f32::from(MENU_LIST_PADDING);
1555 if !near(top, padding) || !near(bottom, padding) {
1556 found.push((
1557 format!("{MENU}:uneven-padding"),
1558 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1559 ));
1560 }
1561 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1562 match first.icon {
1563 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1564 check => found.push((
1565 format!("{MENU}:check-inset"),
1566 format!(
1567 "check column {check:?} must start {expected_inset} px inside the list {}",
1568 describe(menu)
1569 ),
1570 )),
1571 }
1572 }
1573 found
1574 }
1575
1576 #[test]
1577 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
1578 let row =
1579 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
1580 index,
1581 item: rectangle(4., item_top, 120., 32.),
1582 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
1583 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
1584 };
1585 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
1586 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
1587 .into_iter()
1588 .map(|(key, _)| key)
1589 .collect();
1590 assert_eq!(
1591 keys,
1592 [
1593 "popup-menu/item-1:icon-gap",
1594 "popup-menu/item-1:icon-off-centre"
1595 ]
1596 );
1597
1598 let trigger = rectangle(100., 50., 216., 32.);
1599 let option = |index: usize, top: f32| MenuRow {
1600 index,
1601 item: rectangle(104., top, 208., 32.),
1602 icon: Some(rectangle(110., top + 8., 16., 16.)),
1603 label: Some(rectangle(132., top + 6., 80., 20.)),
1604 };
1605 let aligned = [option(0, 88.), option(1, 122.)];
1606 let menu = rectangle(100., 84., 216., 74.);
1607 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
1608 let shifted = rectangle(96., 90., 200., 80.);
1609 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
1610 .into_iter()
1611 .map(|(key, _)| key)
1612 .collect();
1613 assert_eq!(
1614 keys,
1615 [
1616 "popup-menu:not-aligned-to-trigger",
1617 "popup-menu:trigger-offset",
1618 "popup-menu:narrower-than-trigger",
1619 "popup-menu:uneven-padding",
1620 "popup-menu:check-inset",
1621 ]
1622 );
1623 }
1624
1625 #[gpui_kit::test]
1626 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
1627 let (handle, _) = mount(cx);
1628 let mut visual = VisualTestContext::from_window(handle, cx);
1629 visual.simulate_resize(size(px(1280.), px(800.)));
1630 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
1631 collect(&mut visual, Some(chat_row));
1632 let mut found = Vec::new();
1633 let own_status = visual
1634 .debug_bounds(OWN_STATUS)
1635 .expect("own status button rendered");
1636 visual.simulate_click(own_status.center(), Default::default());
1637 collect(&mut visual, Some(MENU));
1638 let status_rows = menu_rows(&mut visual);
1639 assert!(
1640 status_rows.iter().any(|row| row.icon.is_some()),
1641 "status menu shows icons"
1642 );
1643 found.extend(menu_row_violations(
1644 &status_rows,
1645 f32::from(MENU_ICON_LABEL_GAP),
1646 ));
1647 visual.simulate_keystrokes("escape");
1648 collect(&mut visual, None);
1649 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
1650 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
1651 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
1652 collect(&mut visual, Some(MENU));
1653 let chat_rows = menu_rows(&mut visual);
1654 assert!(
1655 chat_rows.iter().any(|row| row.icon.is_some()),
1656 "chat menu shows icons"
1657 );
1658 found.extend(menu_row_violations(
1659 &chat_rows,
1660 f32::from(MENU_ICON_LABEL_GAP),
1661 ));
1662 let found: Vec<String> = found
1663 .into_iter()
1664 .map(|(key, message)| format!("{key}: {message}"))
1665 .collect();
1666 assert!(found.is_empty(), "{}", found.join("\n"));
1667 }
1668
1669 #[gpui_kit::test]
1670 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
1671 let (handle, state) = mount(cx);
1672 let mut visual = VisualTestContext::from_window(handle, cx);
1673 visual.simulate_resize(size(px(1280.), px(800.)));
1674 visual.update(|_, cx| {
1675 state.update(cx, |state, cx| {
1676 state.open_settings(SettingsSection::Appearance, cx)
1677 })
1678 });
1679 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
1680 collect(&mut visual, Some(select));
1681 let trigger = visual.debug_bounds(select).expect("theme select rendered");
1682 visual.simulate_click(trigger.center(), Default::default());
1683 collect(&mut visual, Some(MENU));
1684 let menu = visual.debug_bounds(MENU).expect("list rendered");
1685 let items = visual
1686 .debug_bounds(ITEMS_SELECTOR)
1687 .expect("list items rendered");
1688 let rows = menu_rows(&mut visual);
1689 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
1690 .into_iter()
1691 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
1692 .map(|(key, message)| format!("{key}: {message}"))
1693 .collect();
1694 assert!(found.is_empty(), "{}", found.join("\n"));
1695 }
1696
1697 const BADGE_SAMPLES: [(u32, bool); 5] =
1698 [(1, false), (42, false), (120, false), (7, true), (15, true)];
1699
1700 struct BadgeSamples;
1701
1702 impl gpui_kit::Render for BadgeSamples {
1703 fn render(
1704 &mut self,
1705 _: &mut gpui_kit::Window,
1706 _: &mut gpui_kit::Context<Self>,
1707 ) -> impl gpui_kit::IntoElement {
1708 use gpui_kit::{ParentElement as _, Styled as _};
1709 gpui_kit::div()
1710 .flex()
1711 .gap(px(12.))
1712 .p(px(12.))
1713 .children(BADGE_SAMPLES.map(|(count, rail)| {
1714 if rail {
1715 badge_pill(
1716 count,
1717 RAIL_BADGE,
1718 crate::theme::accent(),
1719 crate::theme::on_accent(),
1720 )
1721 } else {
1722 count_badge(count, false)
1723 }
1724 }))
1725 }
1726 }
1727
1728 fn badge_violation(
1729 text: &str,
1730 pill: Bounds<Pixels>,
1731 label: Bounds<Pixels>,
1732 ink_offset: (f32, f32),
1733 ) -> Option<(String, String)> {
1734 let ink_x = f32::from(label.center().x) + ink_offset.0;
1735 let ink_y = f32::from(label.center().y) + ink_offset.1;
1736 let off_x = ink_x - f32::from(pill.center().x);
1737 let off_y = ink_y - f32::from(pill.center().y);
1738 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
1739 (
1740 format!("count-badge/{text}:off-centre"),
1741 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
1742 )
1743 })
1744 }
1745
1746 #[test]
1747 fn badge_rule_flags_off_centre_text() {
1748 let pill = rectangle(0., 0., 18., 18.);
1749 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
1750 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
1751 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
1752 }
1753
1754 #[gpui_kit::test]
1755 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
1756 cx.update(gpui_kit::init);
1757 cx.update(crate::theme::apply);
1758 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
1759 collect(visual, None);
1760 let mut found = Vec::new();
1761 for (count, rail) in BADGE_SAMPLES {
1762 let text = crate::format::badge_text(count);
1763 let pill = visual
1764 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
1765 .expect("badge rendered");
1766 let label = visual
1767 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
1768 .expect("badge text rendered");
1769 let font_size = if rail {
1770 RAIL_BADGE.font_size
1771 } else {
1772 COUNT_BADGE.font_size
1773 };
1774 let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));
1775 found.extend(badge_violation(&text, pill, label, offset));
1776 }
1777 let found: Vec<String> = found
1778 .into_iter()
1779 .map(|(key, message)| format!("{key}: {message}"))
1780 .collect();
1781 assert!(found.is_empty(), "{}", found.join("\n"));
1782 }
1783
1784 const PINNED_CHAT: &str = "demo-chat-release";
1785 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1786
1787 #[gpui_kit::test]
1788 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
1789 let (handle, state) = mount(cx);
1790 let mut visual = VisualTestContext::from_window(handle, cx);
1791 let mut found = Vec::new();
1792 for (width, height) in SIZES {
1793 visual.simulate_resize(size(px(width), px(height)));
1794 visual.update(|_, cx| {
1795 state.update(cx, |state, cx| {
1796 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1797 })
1798 });
1799 collect(&mut visual, Some(PIN_BANNER_TAG));
1800 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1801 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1802 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1803 let gaps = [
1804 ("top", f32::from(banner.top() - timeline.top())),
1805 ("left", f32::from(banner.left() - timeline.left())),
1806 ("right", f32::from(timeline.right() - banner.right())),
1807 ("below divider", f32::from(banner.top() - divider.bottom())),
1808 ];
1809 let side = gaps[1].1;
1810 if (side - BANNER_INSET).abs() > INSET_TOLERANCE
1811 || gaps
1812 .iter()
1813 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1814 {
1815 found.push(format!(
1816 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
1817 ));
1818 }
1819 }
1820 assert!(found.is_empty(), "{}", found.join("\n"));
1821 }
1822
1823 #[gpui_kit::test]
1824 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1825 let (handle, state) = mount(cx);
1826 let mut visual = VisualTestContext::from_window(handle, cx);
1827 visual.simulate_resize(size(px(1280.), px(800.)));
1828 visual.update(|_, cx| {
1829 state.update(cx, |state, cx| {
1830 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1831 })
1832 });
1833 collect(&mut visual, Some(TIMELINE_TAG));
1834 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1835 }
1836
1837 #[gpui_kit::test]
1838 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1839 let (handle, state) = mount(cx);
1840 let mut visual = VisualTestContext::from_window(handle, cx);
1841 visual.simulate_resize(size(px(1280.), px(800.)));
1842 visual.update(|_, cx| {
1843 state.update(cx, |state, cx| {
1844 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1845 })
1846 });
1847 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1848 let button = visual
1849 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1850 .expect("channel details button");
1851 visual.simulate_click(button.center(), Default::default());
1852 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1853 let pane = visual
1854 .debug_bounds(CHANNEL_DETAILS_TAG)
1855 .expect("details pane");
1856 let main = visual.debug_bounds(MAIN).expect("main island");
1857 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1858 assert!(
1859 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1860 "pane {pane:?} must end at the main island edge {main:?}"
1861 );
1862 assert!(
1863 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1864 "pane {pane:?} must start under the header divider {divider:?}"
1865 );
1866 }
1867
1868 #[gpui_kit::test]
1869 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
1870 let (handle, state) = mount(cx);
1871 let mut visual = VisualTestContext::from_window(handle, cx);
1872 visual.simulate_resize(size(px(1280.), px(800.)));
1873 visual.update(|_, cx| {
1874 state.update(cx, |state, cx| {
1875 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1876 })
1877 });
1878 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1879 let button = visual
1880 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1881 .expect("channel details button");
1882 visual.simulate_click(button.center(), Default::default());
1883 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
1884 let pane = visual
1885 .debug_bounds(CHANNEL_DETAILS_TAG)
1886 .expect("details pane");
1887 let pinned = visual
1888 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
1889 .expect("pinned section");
1890 let shared = visual
1891 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
1892 .expect("shared section");
1893 assert!(
1894 pinned.bottom() <= shared.top(),
1895 "pinned {pinned:?} must come before shared {shared:?}"
1896 );
1897 for (name, section) in [("pinned", pinned), ("shared", shared)] {
1898 let left = f32::from(section.left() - pane.left());
1899 let right = f32::from(pane.right() - section.right());
1900 assert!(
1901 (left - right).abs() < INSET_TOLERANCE && left > 0.,
1902 "{name} section insets left {left} right {right} must match"
1903 );
1904 }
1905 }
1906
1907 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1908 collect(visual, Some(COMPOSER_SEND_TAG));
1909 let mut bounds_of = |path: &'static str| {
1910 visual
1911 .debug_bounds(path)
1912 .unwrap_or_else(|| panic!("{path} rendered"))
1913 };
1914 let composer = bounds_of(COMPOSER_BOX_TAG);
1915 let leading = bounds_of(COMPOSER_LEADING_TAG);
1916 let send = bounds_of(COMPOSER_SEND_TAG);
1917 [
1918 f32::from(leading.left() - composer.left()),
1919 f32::from(leading.top() - composer.top()),
1920 f32::from(composer.bottom() - leading.bottom()),
1921 f32::from(composer.right() - send.right()),
1922 f32::from(send.top() - composer.top()),
1923 f32::from(composer.bottom() - send.bottom()),
1924 ]
1925 }
1926
1927 #[gpui_kit::test]
1928 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
1929 let (handle, _) = mount(cx);
1930 let mut visual = VisualTestContext::from_window(handle, cx);
1931 visual.simulate_resize(size(px(1280.), px(800.)));
1932 let single_line = composer_button_insets(&mut visual);
1933 let left = single_line[0];
1934 assert!(
1935 single_line
1936 .iter()
1937 .all(|inset| (inset - left).abs() < TOLERANCE),
1938 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
1939 );
1940 let leading = visual
1941 .debug_bounds(COMPOSER_LEADING_TAG)
1942 .expect("leading buttons");
1943 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
1944 visual.simulate_click(
1945 point((leading.right() + send.left()) / 2., send.center().y),
1946 Default::default(),
1947 );
1948 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
1949 let three_lines = composer_button_insets(&mut visual);
1950 assert!(
1951 three_lines[1] > single_line[1] + 30.,
1952 "three lines did not grow the composer: {three_lines:?}"
1953 );
1954 for inset in [
1955 three_lines[0],
1956 three_lines[2],
1957 three_lines[3],
1958 three_lines[5],
1959 ] {
1960 assert!(
1961 (inset - left).abs() < TOLERANCE,
1962 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
1963 );
1964 }
1965 }
1966
1967 #[gpui_kit::test]
1968 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
1969 const FORMAT_TAGS: [&str; 6] = [
1970 COMPOSER_BOX_TAG,
1971 COMPOSER_FORMAT_BAR_TAG,
1972 COMPOSER_FORMAT_DIVIDER_TAG,
1973 COMPOSER_LEADING_TAG,
1974 COMPOSER_FORMAT_TAG,
1975 COMPOSER_SEND_TAG,
1976 ];
1977 let (handle, _) = mount(cx);
1978 let mut visual = VisualTestContext::from_window(handle, cx);
1979 for (width, height) in SIZES {
1980 visual.simulate_resize(size(px(width), px(height)));
1981 let window = Bounds {
1982 origin: point(px(0.), px(0.)),
1983 size: size(px(width), px(height)),
1984 };
1985 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
1986 let toggle = visual
1987 .debug_bounds(COMPOSER_FORMAT_TAG)
1988 .expect("format button");
1989 visual.simulate_click(toggle.center(), Default::default());
1990 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
1991 let tags: Vec<Tag> = FORMAT_TAGS
1992 .iter()
1993 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1994 .collect();
1995 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
1996 .into_iter()
1997 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
1998 .collect();
1999 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
2000 let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");
2001 let toggle = visual
2002 .debug_bounds(COMPOSER_FORMAT_TAG)
2003 .expect("format button");
2004 visual.simulate_click(toggle.center(), Default::default());
2005 collect(&mut visual, None);
2006 assert!(found.is_empty(), "{}", found.join("\n"));
2007 assert!(
2008 bar.bottom() <= leading.top(),
2009 "bar {bar:?} over the buttons {leading:?}"
2010 );
2011 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
2012 }
2013 }
2014
2015 #[gpui_kit::test]
2016 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2017 let (handle, state) = mount_with(cx, true);
2018 let mut visual = VisualTestContext::from_window(handle, cx);
2019 for (width, height) in SIZES {
2020 visual.simulate_resize(size(px(width), px(height)));
2021 let window = Bounds {
2022 origin: point(px(0.), px(0.)),
2023 size: size(px(width), px(height)),
2024 };
2025 for (chat, expected_tags) in [
2026 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
2027 (REACTION_CHAT, &AGENT_TAGS[3..]),
2028 ] {
2029 visual.update(|_, cx| {
2030 state.update(cx, |state, cx| {
2031 state.select(Selection::Chat(chat.to_owned()), cx)
2032 })
2033 });
2034 let tags = collect(&mut visual, Some(expected_tags[0]));
2035 let mut expected = GUARDED.to_vec();
2036 expected.extend(expected_tags);
2037 let found: Vec<String> = violations(&tags, window, &expected)
2038 .into_iter()
2039 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
2040 .collect();
2041 assert!(found.is_empty(), "{}", found.join("\n"));
2042 }
2043 }
2044 }
2045}
2046
2047#[test]
2048fn lines_are_solid() {
2049 let mut files = Vec::new();
2050 for root in source_roots() {
2051 source_files(&root, &mut files);
2052 }
2053 let violations: Vec<String> = files
2054 .iter()
2055 .filter(|file| !file.ends_with("layout_guard.rs"))
2056 .flat_map(|file| {
2057 let source = fs::read_to_string(file).expect("read source file");
2058 source
2059 .lines()
2060 .enumerate()
2061 .filter(|(_, line)| {
2062 line.contains(".border_dashed(") || line.contains(".border_dotted(")
2063 })
2064 .map(|(index, line)| {
2065 format!(
2066 "{}:{}: lines are always solid: {}",
2067 file.display(),
2068 index + 1,
2069 line.trim()
2070 )
2071 })
2072 .collect::<Vec<_>>()
2073 })
2074 .collect();
2075 assert!(violations.is_empty(), "{}", violations.join("\n"));
2076}
2077
2078const STATE_RING_COLORS: &[&str] = &[
2079 "if focused",
2080 "if selected",
2081 "if speaking",
2082 "if current",
2083 "if open",
2084 "if state.failed",
2085];
2086const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
2087 (
2088 "notify/ring_view.rs",
2089 "theme::green()",
2090 "state signal (pulsing ring around the caller while it rings), not a resting outline",
2091 ),
2092 (
2093 "notify/meeting_view.rs",
2094 "theme::border_strong()",
2095 "outlined button, not a surface",
2096 ),
2097 (
2098 "settings/mcp.rs",
2099 "theme::border_strong()",
2100 "outlined button, not a surface",
2101 ),
2102 (
2103 "settings/rows.rs",
2104 "theme::border_strong()",
2105 "outlined button, not a surface",
2106 ),
2107 (
2108 "views/card_widgets.rs",
2109 "border)",
2110 "message content drawn as Teams renders it",
2111 ),
2112 (
2113 "views/card_widgets.rs",
2114 "theme::border_strong()",
2115 "message content drawn as Teams renders it",
2116 ),
2117 ("views/shared_tab.rs", "theme::accent()", "input field"),
2118 ("views/card_input.rs", "if error.is_some()", "input field"),
2119 ("views/format_toolbar.rs", "if refused", "input field"),
2120 (
2121 "views/card_code_block.rs",
2122 "theme::code_header_border()",
2123 "message content drawn as Teams renders it",
2124 ),
2125 ("views/call_transcript.rs", "theme::border()", "input field"),
2126 (
2127 "views/conversation.rs",
2128 "theme::accent()",
2129 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2130 ),
2131 (
2132 "views/attachment_tray.rs",
2133 "theme::accent()",
2134 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2135 ),
2136 (
2137 "views/card_carousel.rs",
2138 "theme::border_strong()",
2139 "message content drawn as Teams renders it",
2140 ),
2141 (
2142 "views/card_table.rs",
2143 "grid_color",
2144 "message content drawn as Teams renders it",
2145 ),
2146 (
2147 "views/activity_panel.rs",
2148 "theme::surface()",
2149 "cutout ring in the background color, invisible against its surface",
2150 ),
2151 (
2152 "views/avatar.rs",
2153 "theme::surface()",
2154 "cutout ring in the background color, invisible against its surface",
2155 ),
2156 (
2157 "views/avatar.rs",
2158 "theme::text_muted()",
2159 "offline presence glyph, Teams icon",
2160 ),
2161 (
2162 "views/message_row.rs",
2163 "theme::border_strong()",
2164 "deleted message placeholder, Teams look",
2165 ),
2166 (
2167 "views/message_row.rs",
2168 "theme::red()",
2169 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2170 ),
2171 (
2172 "views/message_row.rs",
2173 "if row.delivery",
2174 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2175 ),
2176 (
2177 "views/new_meeting_dialog.rs",
2178 "theme::border()",
2179 "input field",
2180 ),
2181 (
2182 "views/call_mini_window.rs",
2183 "theme::border_strong()",
2184 "self view over live video, needs an edge on any picture",
2185 ),
2186 ("views/transfer_picker.rs", "theme::border()", "input field"),
2187 (
2188 "views/call_notice.rs",
2189 "theme::border_strong()",
2190 "outlined button, not a surface",
2191 ),
2192 (
2193 "views/composer/schedule.rs",
2194 "theme::accent()",
2195 "input field",
2196 ),
2197 (
2198 "views/call_mini.rs",
2199 "border)",
2200 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2201 ),
2202 (
2203 "views/sidebar.rs",
2204 "theme::accent()",
2205 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2206 ),
2207 (
2208 "views/adaptive_card.rs",
2209 "theme::border()",
2210 "message content drawn as Teams renders it",
2211 ),
2212 (
2213 "views/adaptive_card.rs",
2214 "border)",
2215 "message content drawn as Teams renders it",
2216 ),
2217 (
2218 "views/share_bar.rs",
2219 "theme::red()",
2220 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2221 ),
2222 ("settings_controls.rs", "if invalid", "input field"),
2223];
2224
2225fn outlines(source: &str) -> Vec<(usize, String)> {
2226 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
2227 pattern
2228 .find_iter(source)
2229 .map(|found| {
2230 let line_number = source[..found.start()].matches('\n').count() + 1;
2231 let after = &source[found.end()..];
2232 let color = after
2233 .find(".border_color(")
2234 .filter(|position| *position < 120)
2235 .map(|position| {
2236 let start = &after[position + ".border_color(".len()..];
2237 start
2238 .lines()
2239 .map(str::trim)
2240 .find(|line| !line.is_empty())
2241 .unwrap_or_default()
2242 .to_owned()
2243 })
2244 .unwrap_or_default();
2245 (line_number, color)
2246 })
2247 .collect()
2248}
2249
2250#[test]
2251fn outline_matcher_reads_the_border_color() {
2252 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
2253 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
2254}
2255
2256#[test]
2257fn surfaces_are_soft() {
2258 let mut matched_allowlist = HashSet::new();
2259 let mut violations = Vec::new();
2260 for root in source_roots() {
2261 let mut files = Vec::new();
2262 source_files(&root, &mut files);
2263 for file in files {
2264 let relative = file
2265 .strip_prefix(&root)
2266 .expect("inside src")
2267 .to_string_lossy()
2268 .replace('\\', "/");
2269 if relative == "layout_guard.rs" {
2270 continue;
2271 }
2272 let source = fs::read_to_string(&file).expect("read source file");
2273 for (line_number, color) in outlines(&source) {
2274 if STATE_RING_COLORS
2275 .iter()
2276 .any(|prefix| color.starts_with(prefix))
2277 {
2278 continue;
2279 }
2280 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
2281 *allowed_file == relative && color.starts_with(prefix)
2282 }) {
2283 Some(position) => {
2284 matched_allowlist.insert(position);
2285 }
2286 None => violations.push(format!(
2287 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
2288 )),
2289 }
2290 }
2291 }
2292 }
2293 let stale = OUTLINE_ALLOWLIST
2294 .iter()
2295 .enumerate()
2296 .filter(|(position, _)| !matched_allowlist.contains(position))
2297 .map(|(_, (file, prefix, _))| {
2298 format!("stale outline allowlist entry, remove it: {file} {prefix}")
2299 });
2300 let report: Vec<String> = violations.into_iter().chain(stale).collect();
2301 assert!(report.is_empty(), "{}", report.join("\n"));
2302}
2303
2304fn indentation(line: &str) -> usize {
2305 line.len() - line.trim_start().len()
2306}
2307
2308fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
2309 let indent = indentation(lines[index]);
2310 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
2311 let start = lines[..index]
2312 .iter()
2313 .rposition(|line| !belongs(line))
2314 .map_or(0, |position| position + 1);
2315 let end = lines[index..]
2316 .iter()
2317 .position(|line| !belongs(line))
2318 .map_or(lines.len(), |position| index + position);
2319 lines[start..end]
2320 .iter()
2321 .filter(|line| indentation(line) == indent)
2322 .copied()
2323 .collect()
2324}
2325
2326fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
2327 let lines: Vec<&str> = source.lines().collect();
2328 (0..lines.len())
2329 .filter(|&index| row_height.is_match(lines[index]))
2330 .filter(|&index| {
2331 !chain_lines(&lines, index).iter().any(|line| {
2332 let line = line.trim();
2333 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
2334 })
2335 })
2336 .map(|index| index + 1)
2337 .collect()
2338}
2339
2340fn row_height_pattern() -> Regex {
2341 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
2342}
2343
2344#[test]
2345fn matcher_finds_rows_without_flex_none() {
2346 let source = "fn rows() {\n h_flex()\n .h(px(ROW_HEIGHT))\n .child(\n div()\n .flex_none(),\n );\n div()\n .id(1)\n .h(px(OWN_ROW_HEIGHT))\n .flex_none();\n}\n";
2347 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
2348}
2349
2350#[test]
2351fn fixed_height_rows_never_shrink() {
2352 let row_height = row_height_pattern();
2353 let mut files = Vec::new();
2354 for root in source_roots() {
2355 source_files(&root, &mut files);
2356 }
2357 let violations: Vec<String> = files
2358 .iter()
2359 .filter(|file| !file.ends_with("layout_guard.rs"))
2360 .flat_map(|file| {
2361 let source = fs::read_to_string(file).expect("read source file");
2362 shrinking_rows(&row_height, &source)
2363 .into_iter()
2364 .map(|line| format!("{}:{line}", file.display()))
2365 .collect::<Vec<_>>()
2366 })
2367 .collect();
2368 assert!(
2369 violations.is_empty(),
2370 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
2371 );
2372}