BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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