BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 136.5 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 app_ui_kit::layout::{COMFY_RUNWAY_WIDTH, ROW_PADDING};
160 use gpui_kit::test::TestWindowExt as _;
161 use gpui_kit::{
162 AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,
163 VisualTestContext, WindowOptions, point, px, size,
164 };
165 use store::Store;
166
167 use std::time::Instant;
168
169 use calling::{CallState, CallUpdate, CaptionEntry, CaptionState, RosterEntry, call_channel};
170 use gpui_kit::Entity;
171
172 use crate::app_state::{AppHandle, AppState, Mode, Selection};
173 use crate::call::{ActiveCall, CallModel, ConsultCall};
174 use crate::demo;
175 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
176 use crate::settings::select_selector;
177 use crate::settings::{item_selector, label, label_selector, metrics};
178 use crate::settings_section::SettingsSection;
179 use crate::user_activity::UserInput;
180 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
181 use crate::views::call_transcript::TranscriptPanel;
182 use crate::views::call_view::CHAT_PANEL_TAG;
183 use crate::views::call_window::CALL_WINDOW_TAG;
184 use crate::views::composer::delivery::{
185 COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG, DELIVERY_MENU_TAG,
186 };
187 use crate::views::composer::plus_menu::{COMPOSER_PLUS_TAG, PlusAction};
188 use crate::views::composer::{
189 COMPOSER_ACTIONS_TAG, COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG,
190 COMPOSER_FORMAT_DIVIDER_TAG, COMPOSER_FORMAT_TAG, COMPOSER_INPUT_TAG, COMPOSER_SEND_TAG,
191 COMPOSER_STACKED_ACTIONS_TAG, POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG,
192 POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG, POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG,
193 POST_CARD_SEND_TAG, POST_CARD_SUBJECT_TAG,
194 };
195 use crate::views::conversation::{
196 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
197 CHANNEL_DETAILS_TAG,
198 };
199 use crate::views::conversation::{
200 FEED_EDGE_TAG, FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG,
201 FORWARD_FOOTER_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG, TYPING_TAG,
202 };
203 use crate::views::find_panel::{
204 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
205 };
206 use crate::views::forward_dialog::{FORWARD_CARD_TAG, FORWARD_PREVIEW_TAG};
207 use crate::views::group_name::{GROUP_NAME_BUTTON, GROUP_NAME_FORM};
208 use crate::views::message_row::{
209 BUBBLE_META_TAGS, BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y, select_box_selector,
210 };
211 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
212 use crate::views::post_card::{
213 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
214 };
215 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
216 use crate::views::reaction_proposal_pill::REACTION_PILL;
217 use crate::views::recap_tab::RECAP_REGION;
218 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals};
219 use crate::views::shortcuts::{
220 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCalendar,
221 OpenCallsTab, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
222 };
223 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
224 use crate::views::sidebar::chat_filter_bar::{
225 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
226 };
227 use crate::views::sidebar::chat_row_selector;
228 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
229 use crate::views::widgets::{
230 COUNT_BADGE, RAIL_BADGE, badge_ink_centre, badge_pill, badge_selector, badge_text_origin,
231 badge_text_selector, count_badge,
232 };
233 use gpui_kit::MouseButton;
234 use gpui_kit::component::fluent::{
235 DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,
236 OPTION_CHECK_INSET,
237 };
238 use gpui_kit::component::menu::selectors::{
239 ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,
240 label_selector as menu_label_selector,
241 };
242
243 fn runway_margin(width: f32) -> f32 {
244 ((width - COMFY_RUNWAY_WIDTH) / 2.).max(0.)
245 }
246
247 const GUARDED: &[&str] = &[
248 "shell",
249 "shell/title-bar",
250 "shell/title-bar/search",
251 "shell/title-bar/own-status",
252 "shell/title-bar/own-status/avatar",
253 OWN_AVATAR_DISC,
254 "shell/islands",
255 "shell/islands/rail",
256 "shell/islands/sidebar",
257 "shell/islands/main",
258 ];
259 const CALL_GUARDED: &[&str] = &[
260 "shell/islands/main/call-header",
261 "shell/islands/main/call-stage",
262 "shell/islands/main/call-header/controls",
263 "shell/islands/main/call-header/controls/mic",
264 "shell/islands/main/call-header/leave",
265 ];
266 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
267 const CALENDAR: &str = "shell/islands/calendar";
268 use crate::views::calendar_picker::{CALENDAR_PANE_TAG, MINI_MONTH_TAG};
269 use crate::views::calendar_view::{
270 CALENDAR_DAY_HEADERS_TAG, CALENDAR_HEADER_TAG, CALENDAR_NEW_MEETING_TAG,
271 };
272 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
273 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
274 const FIND_TAGS: &[&str] = &[
275 FIND_PANEL_TAG,
276 FIND_DIVIDER_TAG,
277 FIND_INPUT_TAG,
278 FIND_RESULTS_TAG,
279 ];
280 const CALLS_TAGS: &[&str] = &[
281 "shell/islands/main/calls-dial",
282 "shell/islands/main/calls-history",
283 CALLS_SPEED_DIAL,
284 ];
285 const CALLS_SPEED_DIAL: &str = "shell/islands/main/calls-speed-dial";
286 const PREJOIN_TAGS: &[&str] = &[
287 "shell/islands/main/prejoin",
288 "shell/islands/main/prejoin/preview",
289 "shell/islands/main/prejoin/controls",
290 "shell/islands/main/prejoin/devices",
291 "shell/islands/main/prejoin/audio",
292 "shell/islands/main/prejoin/actions",
293 ];
294 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";
295 const CONSULT_GUARDED: &[&str] = &[
296 "shell/islands/main/call-header/call-consult",
297 "shell/islands/main/call-header/call-consult/transfer",
298 "shell/islands/main/call-header/call-consult/resume",
299 ];
300 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
301 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
302 const SHARE_GUARDED: &[&str] = &[
303 "shell/islands/main/call-stage/share-content",
304 "shell/islands/main/call-stage/share-content/zoom-chip",
305 "shell/islands/main/call-stage/share-strip",
306 ];
307 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
308 const OVERLAY_CHROME: &[&str] = &[
309 "shell/islands/main/call-header",
310 "shell/islands/main/call-stage",
311 ];
312 const MENU: &str = "popup-menu";
313 const OWN_STATUS: &str = "shell/title-bar/own-status";
314 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
315 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
316 const PROPOSAL_CHAT: &str = "demo-chat-release";
317 const REACTION_CHAT: &str = "demo-chat-mara";
318 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
319 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
320 const AGENT_TAGS: [&str; 4] = [
321 PROPOSAL_CARD,
322 PROPOSAL_THUMBNAILS,
323 PROPOSAL_BUTTONS,
324 REACTION_PILL,
325 ];
326 const SETTINGS_TAGS: &[&str] = &[
327 "settings",
328 "settings/nav",
329 "settings/nav/help",
330 "settings/nav/about",
331 "settings/main",
332 "settings/main/header",
333 "settings/main/header/close",
334 "settings/main/body",
335 ];
336 const SETTINGS_BODY: &str = "settings/main/body";
337 const SETTINGS_NAV: &str = "settings/nav";
338 const SETTINGS_NAV_HELP: &str = "settings/nav/help";
339 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
340 const NAV_LABEL_SIZE: f32 = 14.;
341 const NAV_LINE_HEIGHT: f32 = 20.;
342 const SETTINGS_CONTENT: &str = "settings/main/body/content";
343 const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
344 const MEMBERS_CHAT: &str = "demo-chat-release";
345 const SIDEBAR: &str = "shell/islands/sidebar";
346 const MAIN: &str = "shell/islands/main";
347 const EDGE_DIVIDERS: &[&str] = &[SIDEBAR_SCROLL_DIVIDER, HEADER_DIVIDER];
348 const DIVIDER_SEGMENT: &str = "divider";
349 const DIVIDER_THICKNESS: f32 = 1.;
350 const INSET_TOLERANCE: f32 = 1.;
351 const INSET_RULES: &[InsetRule] = &[
352 InsetRule {
353 panel: "settings/nav",
354 content: "settings/nav/about",
355 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
356 },
357 InsetRule {
358 panel: "settings/nav",
359 content: "settings/nav/help",
360 edges: &[Edge::Left, Edge::Right],
361 },
362 InsetRule {
363 panel: "settings/main",
364 content: "settings/main/header/close",
365 edges: &[Edge::Top, Edge::Right],
366 },
367 ];
368 const SCROLLED_INSET_RULE: InsetRule = InsetRule {
369 panel: SETTINGS_BODY,
370 content: SETTINGS_CONTENT,
371 edges: &[Edge::Left, Edge::Bottom],
372 };
373 const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
374 SettingsSection::Agents,
375 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
376 )];
377 const SETTINGS_SECTIONS: [SettingsSection; 12] = [
378 SettingsSection::General,
379 SettingsSection::Notifications,
380 SettingsSection::Appearance,
381 SettingsSection::Chats,
382 SettingsSection::Calls,
383 SettingsSection::Calendar,
384 SettingsSection::CalendarAccounts,
385 SettingsSection::Devices,
386 SettingsSection::Agents,
387 SettingsSection::Mcp,
388 SettingsSection::Help,
389 SettingsSection::About,
390 ];
391 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
392 const TOLERANCE: f32 = 0.5;
393 const KNOWN_VIOLATIONS: &[&str] = &[];
394 const ZOOM_STEP: f32 = 1.25;
395
396 type Tag = (&'static str, Bounds<Pixels>);
397
398 #[derive(Clone, Copy, Debug)]
399 enum Edge {
400 Top,
401 Right,
402 Bottom,
403 Left,
404 }
405
406 struct InsetRule {
407 panel: &'static str,
408 content: &'static str,
409 edges: &'static [Edge],
410 }
411
412 fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {
413 f32::from(match edge {
414 Edge::Top => content.top() - panel.top(),
415 Edge::Right => panel.right() - content.right(),
416 Edge::Bottom => panel.bottom() - content.bottom(),
417 Edge::Left => content.left() - panel.left(),
418 })
419 }
420
421 fn inset_violation(
422 rule: &InsetRule,
423 panel: Bounds<Pixels>,
424 content: Bounds<Pixels>,
425 ) -> Option<(String, String)> {
426 let insets: Vec<(Edge, f32)> = rule
427 .edges
428 .iter()
429 .map(|edge| (*edge, inset(panel, content, *edge)))
430 .collect();
431 let values = insets.iter().map(|(_, value)| *value);
432 let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);
433 (spread > INSET_TOLERANCE).then(|| {
434 (
435 format!("{}:uneven-inset", rule.panel),
436 format!(
437 "{} insets {} by {insets:?}, they must match",
438 rule.panel, rule.content
439 ),
440 )
441 })
442 }
443
444 fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {
445 let bounds_of = |path: &str| {
446 tags.iter()
447 .find(|(tag, _)| *tag == path)
448 .map(|(_, bounds)| *bounds)
449 };
450 rules
451 .iter()
452 .filter_map(
453 |rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {
454 (Some(panel), Some(content)) => inset_violation(rule, panel, content),
455 _ => None,
456 },
457 )
458 .collect()
459 }
460
461 fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {
462 let mut found = Vec::new();
463 for (path, bounds) in tags {
464 let Some((parent, segment)) = path.rsplit_once('/') else {
465 continue;
466 };
467 if !segment.starts_with(DIVIDER_SEGMENT) {
468 continue;
469 }
470 let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {
471 found.push((
472 format!("{path}:no-panel"),
473 format!("{path} needs its panel {parent} tagged"),
474 ));
475 continue;
476 };
477 let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;
478 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
479 let spans = if thin(bounds.size.height) {
480 near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())
481 } else if thin(bounds.size.width) {
482 near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())
483 } else {
484 false
485 };
486 if !spans {
487 found.push((
488 format!("{path}:short-divider"),
489 format!(
490 "{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",
491 describe(*bounds),
492 describe(*panel)
493 ),
494 ));
495 }
496 }
497 found
498 }
499
500 enum Screen {
501 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
502 StatusMenu,
503 Call,
504 Prejoin,
505 CallTranscript,
506 CallPeople,
507 CallShare,
508 CallConsult,
509 }
510
511 fn parent_of(path: &str) -> Option<&str> {
512 path.rsplit_once('/').map(|(parent, _)| parent)
513 }
514
515 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
516 let tolerance = px(TOLERANCE);
517 inner.left() >= outer.left() - tolerance
518 && inner.top() >= outer.top() - tolerance
519 && inner.right() <= outer.right() + tolerance
520 && inner.bottom() <= outer.bottom() + tolerance
521 }
522
523 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
524 let tolerance = px(TOLERANCE);
525 first.left() < second.right() - tolerance
526 && second.left() < first.right() - tolerance
527 && first.top() < second.bottom() - tolerance
528 && second.top() < first.bottom() - tolerance
529 }
530
531 fn describe(bounds: Bounds<Pixels>) -> String {
532 format!(
533 "[{:.1},{:.1} {:.1}x{:.1}]",
534 f32::from(bounds.origin.x),
535 f32::from(bounds.origin.y),
536 f32::from(bounds.size.width),
537 f32::from(bounds.size.height)
538 )
539 }
540
541 fn violations(
542 tags: &[Tag],
543 window: Bounds<Pixels>,
544 expected: &[&str],
545 ) -> Vec<(String, String)> {
546 let mut found = Vec::new();
547 let bounds_of = |path: &str| {
548 tags.iter()
549 .find(|(tag, _)| *tag == path)
550 .map(|(_, bounds)| *bounds)
551 };
552 for path in expected {
553 if bounds_of(path).is_none() {
554 found.push((
555 format!("{path}:missing"),
556 format!("{path} was not rendered"),
557 ));
558 }
559 }
560 for (path, bounds) in tags {
561 if !contains(window, *bounds) {
562 found.push((
563 format!("{path}:outside-window"),
564 format!(
565 "{path} {} leaves the window {}",
566 describe(*bounds),
567 describe(window)
568 ),
569 ));
570 }
571 if let Some(parent) =
572 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
573 {
574 if !contains(parent.1, *bounds) {
575 found.push((
576 format!("{path}:outside-parent"),
577 format!(
578 "{path} {} leaves {} {}",
579 describe(*bounds),
580 parent.0,
581 describe(parent.1)
582 ),
583 ));
584 }
585 }
586 for (other, other_bounds) in tags {
587 let overlays = |first: &str, second: &str| {
588 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
589 };
590 let siblings = path < other
591 && parent_of(path).is_some()
592 && parent_of(path) == parent_of(other)
593 && !overlays(path, other)
594 && !overlays(other, path);
595 if siblings && overlaps(*bounds, *other_bounds) {
596 found.push((
597 format!("{path}:overlaps:{other}"),
598 format!(
599 "{path} {} overlaps {other} {}",
600 describe(*bounds),
601 describe(*other_bounds)
602 ),
603 ));
604 }
605 }
606 }
607 found.extend(divider_violations(tags));
608 found
609 }
610
611 const SETTLE_FRAMES: usize = 2;
612 const SETTLE_LIMIT: usize = 60;
613 const SETTLE_STEP: Duration = Duration::from_millis(50);
614
615 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
616 let mut frames = 0;
617 while frames < SETTLE_FRAMES
618 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
619 {
620 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
621 visual.executor().advance_clock(SETTLE_STEP);
622 std::thread::sleep(SETTLE_STEP);
623 visual.run_until_parked();
624 visual.update(|window, cx| window.render_frame(cx));
625 frames += 1;
626 }
627 GUARDED
628 .iter()
629 .chain(CALL_GUARDED)
630 .chain(CALLS_TAGS)
631 .chain(CHAT_FILTER_TAGS)
632 .chain(CHAT_FILTER_OPEN_TAGS)
633 .chain(FIND_TAGS)
634 .chain(PREJOIN_TAGS)
635 .chain(SHARE_GUARDED)
636 .chain(CONSULT_GUARDED)
637 .chain([
638 &ACTIVITY_PROPOSALS_TAG,
639 &AGENTS_LIST,
640 &CALENDAR,
641 &CALENDAR_HEADER_TAG,
642 &CALENDAR_DAY_HEADERS_TAG,
643 &CALENDAR_NEW_MEETING_TAG,
644 &CALENDAR_PANE_TAG,
645 &MINI_MONTH_TAG,
646 &CALL_TRANSCRIPT,
647 &MENU,
648 &RECAP_TAB,
649 &RECAP_REGION,
650 &PEOPLE_PANEL,
651 ])
652 .chain(&AGENT_TAGS)
653 .chain(SETTINGS_TAGS)
654 .chain(MEMBERS_TAGS)
655 .chain(EDGE_DIVIDERS)
656 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
657 .collect()
658 }
659
660 fn sharing_call() -> ActiveCall {
661 let mut call = gallery_call();
662 call.model
663 .apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
664 call.share_stage.view.step_in((800., 450.));
665 call
666 }
667
668 fn gallery_call() -> ActiveCall {
669 let (handle, _control) = call_channel();
670 let mut model = CallModel::meeting("Standup", false);
671 model.apply(CallUpdate::State(CallState::Connected {
672 since: Instant::now(),
673 }));
674 model.apply(CallUpdate::Roster(
675 (0..11)
676 .map(|index| RosterEntry {
677 mri: format!("8:orgid:guard-{index}"),
678 display_name: format!("Guest {index}"),
679 muted: false,
680 in_lobby: false,
681 has_video: false,
682 sharing: false,
683 hand: None,
684 spotlight: None,
685 organizer: false,
686 ..Default::default()
687 })
688 .collect(),
689 ));
690 ActiveCall::new(1, model, handle.commands, None, handle.video)
691 }
692
693 fn consult_calls() -> (ActiveCall, ActiveCall) {
694 let connected = |id: u64, name: &str, mri: &str| {
695 let (handle, _control) = call_channel();
696 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
697 model.apply(CallUpdate::State(CallState::Connected {
698 since: Instant::now(),
699 }));
700 ActiveCall::new(id, model, handle.commands, None, handle.video)
701 };
702 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
703 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
704 consult.consult = Some(ConsultCall::new(
705 (
706 "8:orgid:guard-consult".to_owned(),
707 "Jonas Ortega".to_owned(),
708 ),
709 held.model.peer_name.clone(),
710 ));
711 (consult, held)
712 }
713
714 /// The meeting window the call controller opens once a call is set.
715 fn call_window_context(visual: &mut VisualTestContext) -> VisualTestContext {
716 for _ in 0..SETTLE_LIMIT {
717 let main = visual.update(|window, _| window.window_handle());
718 let candidates = visual.update(|_, cx| cx.windows());
719 for handle in candidates.into_iter().filter(|handle| *handle != main) {
720 let alive = visual.update(|_, cx| handle.update(cx, |_, _, _| ()).is_ok());
721 if !alive {
722 continue;
723 }
724 let mut candidate = VisualTestContext::from_window(handle, visual);
725 candidate.update(|window, cx| window.render_frame(cx));
726 if candidate.debug_bounds(CALL_WINDOW_TAG).is_some() {
727 return candidate;
728 }
729 }
730 visual.executor().advance_clock(SETTLE_STEP);
731 std::thread::sleep(SETTLE_STEP);
732 visual.run_until_parked();
733 }
734 panic!("the call window never opened");
735 }
736
737 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
738 mount_with(cx, false)
739 }
740
741 fn mount_with(
742 cx: &mut TestAppContext,
743 agent_api: bool,
744 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
745 cx.update(gpui_kit::init);
746 cx.update(|cx| {
747 crate::theme::apply(cx);
748 bind_keys(cx);
749 let store = Store::open_in_memory().expect("in-memory store");
750 demo::seed(&store);
751 let store = Arc::new(store);
752 if agent_api {
753 crate::agent_api::init(store.clone(), true, cx);
754 }
755 let mode = Mode {
756 demo: true,
757 read_only: false,
758 demo_sync: None,
759 };
760 let state = cx.new(|_| AppState::new(store, mode));
761 install_globals(&state, UserInput::new(), cx);
762 crate::agents::install(state.clone(), cx);
763 demo::start_session(&state, cx);
764 let shared_state = state.clone();
765 let startup = Startup {
766 switcher_query: None,
767 composer_text: None,
768 reply_to_last: false,
769 launched_by_autostart: false,
770 };
771 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
772 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
773 })
774 .expect("open test window")
775 .0;
776 (window, shared_state)
777 })
778 }
779
780 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
781 Bounds {
782 origin: point(px(left), px(top)),
783 size: size(px(width), px(height)),
784 }
785 }
786
787 #[test]
788 fn rules_flag_overlap_and_overflow() {
789 let window = rectangle(0., 0., 100., 100.);
790 let tags: Vec<Tag> = vec![
791 ("shell", rectangle(0., 0., 100., 100.)),
792 ("shell/islands", rectangle(0., 0., 100., 50.)),
793 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
794 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
795 ];
796 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
797 .into_iter()
798 .map(|(key, _)| key)
799 .collect();
800 let line_tags: Vec<Tag> = vec![
801 ("panel", rectangle(0., 0., 100., 100.)),
802 ("panel/divider", rectangle(0., 50., 100., 1.)),
803 ("panel/divider-inset", rectangle(12., 60., 76., 1.)),
804 ("panel/divider-side", rectangle(40., 0., 1., 100.)),
805 ("panel/about", rectangle(12., 76., 76., 12.)),
806 ("panel/footer", rectangle(12., 64., 76., 12.)),
807 ];
808 let line_keys: Vec<String> = divider_violations(&line_tags)
809 .into_iter()
810 .chain(inset_violations(
811 &line_tags,
812 &[
813 InsetRule {
814 panel: "panel",
815 content: "panel/about",
816 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
817 },
818 InsetRule {
819 panel: "panel",
820 content: "panel/footer",
821 edges: &[Edge::Left, Edge::Bottom],
822 },
823 ],
824 ))
825 .map(|(key, _)| key)
826 .collect();
827 assert_eq!(
828 line_keys,
829 ["panel/divider-inset:short-divider", "panel:uneven-inset"]
830 );
831 assert_eq!(
832 keys,
833 [
834 "shell/status-bar:missing",
835 "shell/islands/rail:overlaps:shell/islands/sidebar",
836 "shell/islands/sidebar:outside-window",
837 "shell/islands/sidebar:outside-parent",
838 ]
839 );
840 }
841
842 #[gpui_kit::test]
843 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
844 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
845 }
846
847 #[gpui_kit::test]
848 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
849 let (width, height) = SIZES[1];
850 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
851 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
852 }
853
854 fn check_layout(
855 cx: &mut TestAppContext,
856 sizes: &[(f32, f32)],
857 zoom: f32,
858 known_violations: &[&str],
859 ) {
860 let (handle, app) = mount(cx);
861 let platform_scale = cx
862 .update_window(handle, |_, window, _| window.scale_factor())
863 .expect("test window");
864 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
865 let mut visual = VisualTestContext::from_window(handle, cx);
866 let mut seen_known = HashSet::new();
867 let mut unexpected = Vec::new();
868 for &(width, height) in sizes {
869 visual.simulate_resize(size(px(width), px(height)));
870 let window = Bounds {
871 origin: point(px(0.), px(0.)),
872 size: size(px(width), px(height)),
873 };
874 let screens = [
875 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
876 Screen::Tab(
877 "chat-filter",
878 Some(|visual| {
879 visual.dispatch_action(OpenChatsTab);
880 visual.dispatch_action(OpenChatFilter);
881 visual.dispatch_action(FilterMutedChats);
882 visual.run_until_parked();
883 visual.simulate_input("zzz");
884 }),
885 ),
886 Screen::Tab(
887 "find",
888 Some(|visual| {
889 visual.dispatch_action(OpenChatsTab);
890 visual.dispatch_action(FindInChat);
891 visual.run_until_parked();
892 visual.simulate_input("access");
893 }),
894 ),
895 Screen::Tab(
896 "activity",
897 Some(|visual| visual.dispatch_action(OpenActivity)),
898 ),
899 Screen::Tab(
900 "channels",
901 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
902 ),
903 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
904 Screen::Tab(
905 "calendar",
906 Some(|visual| visual.dispatch_action(OpenCalendar)),
907 ),
908 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
909 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
910 Screen::Prejoin,
911 Screen::StatusMenu,
912 Screen::Call,
913 Screen::CallTranscript,
914 Screen::CallPeople,
915 Screen::CallShare,
916 Screen::CallConsult,
917 ];
918 for screen in screens {
919 let (screen_name, status_menu) = match screen {
920 Screen::Tab(name, open) => {
921 if let Some(open) = open {
922 open(&mut visual);
923 }
924 (name, false)
925 }
926 Screen::Call | Screen::CallPeople => {
927 let people_open = matches!(screen, Screen::CallPeople);
928 visual.update(|_, cx| {
929 app.update(cx, |state, cx| {
930 let mut call = gallery_call();
931 call.people_open = people_open;
932 state.call = Some(call);
933 cx.notify();
934 })
935 });
936 (if people_open { "call-people" } else { "call" }, false)
937 }
938 Screen::Prejoin => {
939 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
940 visual.update(|_, cx| {
941 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
942 });
943 ("prejoin", false)
944 }
945 Screen::CallTranscript => {
946 visual.update(|window, cx| {
947 app.update(cx, |state, cx| {
948 let mut call = gallery_call();
949 call.model.apply(CallUpdate::Captions(CaptionState::On));
950 for index in 0..40 {
951 call.model.note_caption(
952 CaptionEntry {
953 id: format!("guard-{index}"),
954 user_id: "8:orgid:guard-0".into(),
955 display_name: "Guest 0".into(),
956 text: "A long guarded sentence that has to wrap inside the panel".into(),
957 is_final: true,
958 },
959 Instant::now(),
960 );
961 }
962 call.transcript_open = true;
963 state.call = Some(call);
964 let app_entity = cx.entity();
965 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
966 cx.notify();
967 })
968 });
969 ("call-transcript", false)
970 }
971 Screen::CallShare => {
972 visual.update(|_, cx| {
973 app.update(cx, |state, cx| {
974 state.call = Some(sharing_call());
975 cx.notify();
976 })
977 });
978 ("call-share", false)
979 }
980 Screen::CallConsult => {
981 visual.update(|_, cx| {
982 app.update(cx, |state, cx| {
983 let (consult, held) = consult_calls();
984 state.call = Some(consult);
985 state.held_call = Some(held);
986 cx.notify();
987 })
988 });
989 ("call-consult", false)
990 }
991 Screen::StatusMenu => {
992 let tags = collect(&mut visual, None);
993 let button = tags
994 .iter()
995 .find(|(path, _)| *path == OWN_STATUS)
996 .map(|(_, bounds)| *bounds)
997 .expect("own status button rendered");
998 visual.simulate_click(button.center(), Default::default());
999 ("status-menu", true)
1000 }
1001 };
1002 let is_call = matches!(
1003 screen_name,
1004 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
1005 );
1006 let in_call_window = is_call || screen_name == "prejoin";
1007 let tags = if in_call_window {
1008 let mut call_visual = call_window_context(&mut visual);
1009 call_visual.simulate_resize(size(px(width), px(height)));
1010 collect(&mut call_visual, None)
1011 } else {
1012 collect(&mut visual, status_menu.then_some(MENU))
1013 };
1014 let mut expected = GUARDED.to_vec();
1015 if in_call_window {
1016 expected = vec!["shell/islands/main"];
1017 }
1018 if is_call {
1019 expected.extend(CALL_GUARDED);
1020 }
1021 if screen_name == "call-transcript" {
1022 expected.push(CALL_TRANSCRIPT);
1023 }
1024 if screen_name == "call-people" {
1025 expected.push(PEOPLE_PANEL);
1026 }
1027 if screen_name == "call-share" {
1028 expected.extend(SHARE_GUARDED);
1029 }
1030 if screen_name == "call-consult" {
1031 expected.extend(CONSULT_GUARDED);
1032 }
1033 if status_menu {
1034 expected.push(MENU);
1035 }
1036 match screen_name {
1037 "chats" => expected.extend(CHAT_FILTER_TAGS),
1038 "chat-filter" => {
1039 expected.extend(CHAT_FILTER_TAGS);
1040 expected.extend(CHAT_FILTER_OPEN_TAGS);
1041 }
1042 "find" => expected.extend(FIND_TAGS),
1043 "calls" => {
1044 expected.retain(|path| *path != "shell/islands/sidebar");
1045 expected.extend(CALLS_TAGS);
1046 if !crate::views::calls_page::shows_speed_dial(width) {
1047 expected.retain(|path| *path != CALLS_SPEED_DIAL);
1048 }
1049 }
1050 "agents" => expected.push(AGENTS_LIST),
1051 "calendar" => {
1052 expected.retain(|path| {
1053 !matches!(*path, "shell/islands/sidebar" | "shell/islands/main")
1054 });
1055 expected.push(CALENDAR);
1056 expected.extend([CALENDAR_HEADER_TAG, CALENDAR_DAY_HEADERS_TAG]);
1057 // The calendar list pane hides on narrow windows.
1058 if width >= crate::views::calendar_view::COMPACT_HEADER_WIDTH {
1059 expected.extend([CALENDAR_PANE_TAG, MINI_MONTH_TAG]);
1060 }
1061 }
1062 "prejoin" => expected.extend(PREJOIN_TAGS),
1063 _ => {}
1064 }
1065 let mut found = violations(&tags, window, &expected);
1066 let bounds_of = |wanted: &str| {
1067 tags.iter()
1068 .find(|(path, _)| *path == wanted)
1069 .map(|(_, bounds)| *bounds)
1070 };
1071 let first_island =
1072 bounds_of("shell/islands/sidebar").or_else(|| bounds_of(CALENDAR));
1073 if let (Some(rail), Some(island)) = (bounds_of("shell/islands/rail"), first_island)
1074 {
1075 let gap =
1076 f32::from(island.origin.x) - f32::from(rail.origin.x + rail.size.width);
1077 if gap.abs() > 0.5 {
1078 found.push((
1079 "shell/islands/rail:gap".to_owned(),
1080 format!("first island starts {gap} px after the rail, expected 0"),
1081 ));
1082 }
1083 }
1084 if screen_name == "calendar"
1085 && let (Some(header), Some(button)) = (
1086 bounds_of(CALENDAR_HEADER_TAG),
1087 bounds_of(CALENDAR_NEW_MEETING_TAG),
1088 )
1089 {
1090 let overflow = f32::from(button.origin.x + button.size.width)
1091 - f32::from(header.origin.x + header.size.width);
1092 if overflow > TOLERANCE {
1093 found.push((
1094 CALENDAR_HEADER_TAG.to_owned(),
1095 format!("header controls overflow by {overflow} px"),
1096 ));
1097 }
1098 }
1099 if status_menu {
1100 let menu = tags
1101 .iter()
1102 .find(|(path, _)| *path == MENU)
1103 .map(|(_, bounds)| *bounds);
1104 let button = tags
1105 .iter()
1106 .find(|(path, _)| *path == OWN_STATUS)
1107 .map(|(_, bounds)| *bounds);
1108 if let (Some(menu), Some(button)) = (menu, button) {
1109 if overlaps(menu, button) {
1110 found.push((
1111 format!("{MENU}:covers:{OWN_STATUS}"),
1112 format!(
1113 "{MENU} {} covers {OWN_STATUS} {}",
1114 describe(menu),
1115 describe(button)
1116 ),
1117 ));
1118 }
1119 }
1120 visual.simulate_keystrokes("escape");
1121 visual.run_until_parked();
1122 }
1123 if is_call {
1124 visual.update(|_, cx| {
1125 app.update(cx, |state, cx| {
1126 state.call = None;
1127 state.held_call = None;
1128 cx.notify();
1129 })
1130 });
1131 }
1132 if screen_name == "find" {
1133 visual.dispatch_action(gpui_kit::component::input::Escape);
1134 visual.run_until_parked();
1135 }
1136 if screen_name == "chat-filter" {
1137 visual.dispatch_action(ClearChatFilters);
1138 visual.dispatch_action(OpenChatFilter);
1139 visual.run_until_parked();
1140 }
1141 if screen_name == "prejoin" {
1142 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
1143 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
1144 }
1145 for (key, message) in found {
1146 let full_key = format!("{screen_name}@{width}x{height}:{key}");
1147 if known_violations.contains(&full_key.as_str()) {
1148 seen_known.insert(full_key);
1149 } else {
1150 unexpected.push(format!("{full_key}: {message}"));
1151 }
1152 }
1153 }
1154 }
1155 let stale: Vec<String> = known_violations
1156 .iter()
1157 .filter(|key| !seen_known.contains(**key))
1158 .map(|key| format!("stale known violation, remove it: {key}"))
1159 .collect();
1160 assert!(
1161 unexpected.is_empty() && stale.is_empty(),
1162 "{}",
1163 unexpected
1164 .into_iter()
1165 .chain(stale)
1166 .collect::<Vec<_>>()
1167 .join("\n")
1168 );
1169 }
1170 #[gpui_kit::test]
1171 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
1172 let (handle, _) = mount(cx);
1173 let mut visual = VisualTestContext::from_window(handle, cx);
1174 visual.simulate_resize(size(px(1280.), px(800.)));
1175 collect(&mut visual, Some(OWN_AVATAR_DISC));
1176 let disc = visual
1177 .debug_bounds(OWN_AVATAR_DISC)
1178 .expect("own avatar rendered");
1179 let bar = visual
1180 .debug_bounds("shell/title-bar")
1181 .expect("title bar rendered");
1182 assert_eq!(
1183 f32::from(disc.size.width),
1184 TITLE_AVATAR_SIZE,
1185 "{}",
1186 describe(disc)
1187 );
1188 assert_eq!(
1189 f32::from(disc.size.height),
1190 TITLE_AVATAR_SIZE,
1191 "{}",
1192 describe(disc)
1193 );
1194 let top = f32::from(disc.top() - bar.top());
1195 let bottom = f32::from(bar.bottom() - disc.bottom());
1196 assert!(
1197 (top - bottom).abs() <= 1.,
1198 "own avatar {} is not centered in the title bar {}",
1199 describe(disc),
1200 describe(bar)
1201 );
1202 }
1203
1204 #[gpui_kit::test]
1205 fn a_narrow_composer_puts_its_actions_below_a_full_width_input(cx: &mut TestAppContext) {
1206 let (handle, _) = mount(cx);
1207 let mut visual = VisualTestContext::from_window(handle, cx);
1208 visual.simulate_resize(size(px(760.), px(700.)));
1209 collect(&mut visual, Some(COMPOSER_STACKED_ACTIONS_TAG));
1210 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
1211 visual
1212 .debug_bounds(path)
1213 .unwrap_or_else(|| panic!("{path} missing"))
1214 };
1215 let card = bounds_of(&mut visual, COMPOSER_BOX_TAG);
1216 let input = bounds_of(&mut visual, COMPOSER_INPUT_TAG);
1217 let stacked = bounds_of(&mut visual, COMPOSER_STACKED_ACTIONS_TAG);
1218 let send = bounds_of(&mut visual, COMPOSER_SEND_TAG);
1219 assert!(
1220 input.bottom() <= stacked.top(),
1221 "actions {} not below input {}",
1222 describe(stacked),
1223 describe(input)
1224 );
1225 assert!(
1226 contains(card, stacked) && contains(stacked, send),
1227 "send {} outside {}",
1228 describe(send),
1229 describe(stacked)
1230 );
1231 let side = f32::from(card.right() - send.right());
1232 let bottom = f32::from(card.bottom() - send.bottom());
1233 assert!(
1234 (side - bottom).abs() < TOLERANCE,
1235 "send insets: side {side}, bottom {bottom}"
1236 );
1237 visual.simulate_resize(size(px(1280.), px(800.)));
1238 collect(&mut visual, Some(COMPOSER_SEND_TAG));
1239 assert!(
1240 visual.debug_bounds(COMPOSER_STACKED_ACTIONS_TAG).is_none(),
1241 "wide composer stacked"
1242 );
1243 }
1244
1245 const TITLE_SEARCH: &str = "shell/title-bar/search";
1246 const TITLE_NEIGHBOURS: &[&str] = &[
1247 "shell/title-bar/leading",
1248 "shell/title-bar/mode-pill",
1249 "shell/title-bar/trailing",
1250 "shell/title-bar/update",
1251 OWN_STATUS,
1252 ];
1253 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
1254 (1920., 1080., true),
1255 (1280., 800., true),
1256 (640., 480., false),
1257 ];
1258
1259 #[gpui_kit::test]
1260 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
1261 let (handle, _) = mount(cx);
1262 let mut visual = VisualTestContext::from_window(handle, cx);
1263 let shell = visual.update(|window, cx| {
1264 window
1265 .root::<gpui_kit::base::Root>()
1266 .flatten()
1267 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
1268 .expect("app shell is the root view")
1269 });
1270 visual.update(|_, cx| {
1271 shell.update(cx, |shell, cx| {
1272 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
1273 })
1274 });
1275 let mut found = Vec::new();
1276 for (width, height, centered) in TITLE_SEARCH_SIZES {
1277 visual.simulate_resize(size(px(width), px(height)));
1278 collect(&mut visual, Some(TITLE_SEARCH));
1279 let search = visual
1280 .debug_bounds(TITLE_SEARCH)
1281 .expect("title search rendered");
1282 let search_center = f32::from(search.center().x);
1283 eprintln!(
1284 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
1285 describe(search),
1286 width / 2.
1287 );
1288 if centered && (search_center - width / 2.).abs() > 1. {
1289 found.push(format!(
1290 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
1291 width / 2.
1292 ));
1293 }
1294 if !contains(rectangle(0., 0., width, height), search) {
1295 found.push(format!(
1296 "@{width}x{height}: search {} leaves the window",
1297 describe(search)
1298 ));
1299 }
1300 for neighbour in TITLE_NEIGHBOURS {
1301 match visual.debug_bounds(neighbour) {
1302 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
1303 Some(bounds) if overlaps(search, bounds) => found.push(format!(
1304 "@{width}x{height}: search {} overlaps {neighbour} {}",
1305 describe(search),
1306 describe(bounds)
1307 )),
1308 Some(_) => {}
1309 }
1310 }
1311 }
1312 assert!(found.is_empty(), "{}", found.join("\n"));
1313 }
1314
1315 #[gpui_kit::test]
1316 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
1317 let (handle, app) = mount(cx);
1318 let mut visual = VisualTestContext::from_window(handle, cx);
1319 for (width, height) in SIZES {
1320 visual.simulate_resize(size(px(width), px(height)));
1321 visual.update(|_, cx| {
1322 app.update(cx, |state, cx| {
1323 let mut call = gallery_call();
1324 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
1325 call.chat_open = true;
1326 state.call = Some(call);
1327 cx.notify();
1328 })
1329 });
1330 let mut call_visual = call_window_context(&mut visual);
1331 call_visual.simulate_resize(size(px(width), px(height)));
1332 collect(&mut call_visual, Some(CHAT_PANEL_TAG));
1333 let panel = call_visual
1334 .debug_bounds(CHAT_PANEL_TAG)
1335 .expect("chat panel rendered");
1336 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
1337 .iter()
1338 .enumerate()
1339 .filter_map(|(index, tag)| {
1340 call_visual.debug_bounds(tag).map(|bounds| (index, bounds))
1341 })
1342 .collect();
1343 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
1344 let found: Vec<String> = bubbles
1345 .into_iter()
1346 .filter(|(_, bounds)| {
1347 !inside_horizontally(panel, *bounds) || !overlaps(panel, *bounds)
1348 })
1349 .map(|(index, bounds)| {
1350 format!(
1351 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
1352 describe(bounds),
1353 describe(panel)
1354 )
1355 })
1356 .collect();
1357 visual.update(|_, cx| {
1358 app.update(cx, |state, cx| {
1359 state.call = None;
1360 cx.notify();
1361 })
1362 });
1363 assert!(found.is_empty(), "{}", found.join("\n"));
1364 }
1365 }
1366
1367 #[gpui_kit::test]
1368 fn the_typing_bubble_stays_put_when_an_own_message_arrives(cx: &mut TestAppContext) {
1369 let (handle, app) = mount(cx);
1370 let mut visual = VisualTestContext::from_window(handle, cx);
1371 visual.simulate_resize(size(px(1280.), px(520.)));
1372 visual.update(|_, cx| {
1373 app.update(cx, |state, cx| {
1374 state.select(Selection::Chat(REACTION_CHAT.to_owned()), cx)
1375 })
1376 });
1377 collect(&mut visual, Some(TYPING_TAG));
1378 collect(&mut visual, None);
1379 let resting = visual
1380 .debug_bounds(TYPING_TAG)
1381 .expect("typing bubble")
1382 .bottom();
1383 visual.update(|_, cx| {
1384 app.update(cx, |state, cx| {
1385 let record = store::MessageRecord {
1386 conversation_id: REACTION_CHAT.to_owned(),
1387 message_id: "guard-own".to_owned(),
1388 sender_id: Some(demo::DEMO_USER_ID.to_owned()),
1389 sender_name: Some("Me".to_owned()),
1390 created_at: chrono::Utc::now().max(demo::at(0, 10, 48)),
1391 body_html: "<p>Sent while Mara types</p>".to_owned(),
1392 links_json: "[]".to_owned(),
1393 attachments_json: "[]".to_owned(),
1394 reactions_json: "[]".to_owned(),
1395 mentions_json: "[]".to_owned(),
1396 ..Default::default()
1397 };
1398 state
1399 .store
1400 .upsert_messages(&[record])
1401 .expect("store message");
1402 state.typing.start(
1403 REACTION_CHAT,
1404 demo::MARA_ID,
1405 "Mara Lindqvist",
1406 std::time::Instant::now(),
1407 chrono::Utc::now() + chrono::Duration::days(1),
1408 );
1409 state.apply(
1410 crate::backend::BackendEvent::Core(teams_core::CoreEvent::MessagesChanged {
1411 conversation_id: REACTION_CHAT.to_owned(),
1412 }),
1413 cx,
1414 );
1415 })
1416 });
1417 let mut bottoms = Vec::new();
1418 for _ in 0..12 {
1419 visual.executor().advance_clock(Duration::from_millis(16));
1420 visual.run_until_parked();
1421 visual.update(|window, cx| window.render_frame(cx));
1422 bottoms.push(
1423 visual
1424 .debug_bounds(TYPING_TAG)
1425 .map(|bounds| f32::from(bounds.bottom())),
1426 );
1427 }
1428 let positions: Vec<f32> = bottoms
1429 .iter()
1430 .map(|bottom| bottom.expect("typing bubble"))
1431 .collect();
1432 let steps: Vec<f32> = positions
1433 .windows(2)
1434 .map(|pair| pair[1] - pair[0])
1435 .filter(|step| step.abs() > 0.5)
1436 .collect();
1437 let reversals = steps
1438 .windows(2)
1439 .filter(|pair| pair[0].signum() != pair[1].signum())
1440 .count();
1441 assert_eq!(reversals, 0, "resting {resting:?}, frames {positions:?}");
1442 }
1443
1444 #[gpui_kit::test]
1445 fn a_chat_with_someone_of_another_organization_says_external(cx: &mut TestAppContext) {
1446 let (handle, app) = mount(cx);
1447 let mut visual = VisualTestContext::from_window(handle, cx);
1448 visual.simulate_resize(size(px(1280.), px(800.)));
1449 visual.update(|_, cx| {
1450 app.update(cx, |state, cx| {
1451 state
1452 .directory
1453 .external
1454 .insert(demo::MARA_ID.to_owned(), Some("Example Corp".to_owned()));
1455 state.select(Selection::Chat(REACTION_CHAT.to_owned()), cx)
1456 })
1457 });
1458 collect(&mut visual, Some(TIMELINE_TAG));
1459 collect(&mut visual, None);
1460 assert!(
1461 visual
1462 .debug_bounds(crate::views::conversation::chat_header_actions::EXTERNAL_BADGE)
1463 .is_some()
1464 );
1465 }
1466
1467 #[gpui_kit::test]
1468 fn the_time_of_a_short_own_message_with_a_reaction_stays_in_its_bubble(
1469 cx: &mut TestAppContext,
1470 ) {
1471 const SHORT_CHAT: &str = "demo-chat-priya";
1472 let (handle, app) = mount(cx);
1473 let mut visual = VisualTestContext::from_window(handle, cx);
1474 visual.simulate_resize(size(px(1280.), px(800.)));
1475 visual.update(|_, cx| {
1476 app.update(cx, |state, cx| {
1477 let reactions = vec![teams_core::ReactionInfo {
1478 reaction_type: "like".to_owned(),
1479 user_id: Some(demo::MARA_ID.to_owned()),
1480 user_name: Some("Mara Lindqvist".to_owned()),
1481 created_at: Some(chrono::Utc::now()),
1482 }];
1483 let record = store::MessageRecord {
1484 conversation_id: SHORT_CHAT.to_owned(),
1485 message_id: "guard-short".to_owned(),
1486 sender_id: Some(demo::DEMO_USER_ID.to_owned()),
1487 sender_name: Some("Me".to_owned()),
1488 created_at: chrono::Utc::now().max(demo::at(0, 10, 48)),
1489 body_html: "<p>danke</p>".to_owned(),
1490 links_json: "[]".to_owned(),
1491 attachments_json: "[]".to_owned(),
1492 reactions_json: serde_json::to_string(&reactions).expect("reactions"),
1493 mentions_json: "[]".to_owned(),
1494 ..Default::default()
1495 };
1496 state
1497 .store
1498 .upsert_messages(&[record])
1499 .expect("store message");
1500 state.select(Selection::Chat(SHORT_CHAT.to_owned()), cx)
1501 })
1502 });
1503 collect(&mut visual, Some(TIMELINE_TAG));
1504 collect(&mut visual, None);
1505 let pairs: Vec<(Bounds<Pixels>, Bounds<Pixels>)> = BUBBLE_TAGS
1506 .iter()
1507 .zip(BUBBLE_META_TAGS)
1508 .filter_map(|(bubble, meta)| {
1509 Some((visual.debug_bounds(bubble)?, visual.debug_bounds(meta)?))
1510 })
1511 .collect();
1512 let (bubble, meta) = pairs
1513 .iter()
1514 .max_by(|left, right| f32::from(left.0.top()).total_cmp(&f32::from(right.0.top())))
1515 .expect("the newest bubble and its time");
1516 assert_eq!(
1517 f32::from(bubble.right() - meta.right()),
1518 8.,
1519 "time {meta:?} is not 8 px inside its bubble {bubble:?}"
1520 );
1521 }
1522
1523 #[gpui_kit::test]
1524 fn a_new_message_never_opens_a_gap_between_the_rows_above(cx: &mut TestAppContext) {
1525 const GAP_CHAT: &str = "demo-chat-priya";
1526 let (handle, app) = mount(cx);
1527 let mut visual = VisualTestContext::from_window(handle, cx);
1528 visual.simulate_resize(size(px(1280.), px(800.)));
1529 visual.update(|_, cx| {
1530 app.update(cx, |state, cx| {
1531 state.select(Selection::Chat(GAP_CHAT.to_owned()), cx)
1532 })
1533 });
1534 collect(&mut visual, Some(TIMELINE_TAG));
1535 collect(&mut visual, None);
1536 let bubble_positions = |visual: &mut VisualTestContext| -> Vec<(usize, f32, f32)> {
1537 BUBBLE_TAGS
1538 .iter()
1539 .enumerate()
1540 .filter_map(|(index, tag)| {
1541 visual
1542 .debug_bounds(tag)
1543 .map(|bounds| (index, f32::from(bounds.top()), f32::from(bounds.bottom())))
1544 })
1545 .collect()
1546 };
1547 let before = bubble_positions(&mut visual);
1548 visual.update(|_, cx| {
1549 app.update(cx, |state, cx| {
1550 let record = store::MessageRecord {
1551 conversation_id: GAP_CHAT.to_owned(),
1552 message_id: "guard-new".to_owned(),
1553 sender_id: Some(demo::PRIYA_ID.to_owned()),
1554 sender_name: Some("Priya Nair".to_owned()),
1555 created_at: chrono::Utc::now().max(demo::at(0, 10, 48)),
1556 body_html: "<p>Fresh message</p>".to_owned(),
1557 links_json: "[]".to_owned(),
1558 attachments_json: "[]".to_owned(),
1559 reactions_json: "[]".to_owned(),
1560 mentions_json: "[]".to_owned(),
1561 ..Default::default()
1562 };
1563 state
1564 .store
1565 .upsert_messages(&[record])
1566 .expect("store message");
1567 state.apply(
1568 crate::backend::BackendEvent::Core(teams_core::CoreEvent::MessagesChanged {
1569 conversation_id: GAP_CHAT.to_owned(),
1570 }),
1571 cx,
1572 );
1573 })
1574 });
1575 let mut frames = Vec::new();
1576 for _ in 0..12 {
1577 visual.executor().advance_clock(Duration::from_millis(16));
1578 visual.run_until_parked();
1579 visual.update(|window, cx| window.render_frame(cx));
1580 frames.push(bubble_positions(&mut visual));
1581 }
1582 let spacing = |positions: &[(usize, f32, f32)]| -> Vec<(usize, f32)> {
1583 positions
1584 .windows(2)
1585 .map(|pair| (pair[1].0, pair[1].1 - pair[0].2))
1586 .collect()
1587 };
1588 let resting = spacing(&before);
1589 let found: Vec<String> = frames
1590 .iter()
1591 .enumerate()
1592 .flat_map(|(frame, positions)| {
1593 let resting = resting.clone();
1594 spacing(positions)
1595 .into_iter()
1596 .filter_map(move |(index, gap)| {
1597 let expected = resting.iter().find(|(known, _)| *known == index)?.1;
1598 ((gap - expected).abs() > TOLERANCE).then(|| {
1599 format!(
1600 "frame {frame}: gap above bubble {index} is {gap}, was {expected}"
1601 )
1602 })
1603 })
1604 })
1605 .collect();
1606 assert!(found.is_empty(), "{}", found.join("\n"));
1607 }
1608
1609 fn inside_horizontally(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
1610 let tolerance = px(TOLERANCE);
1611 inner.left() >= outer.left() - tolerance && inner.right() <= outer.right() + tolerance
1612 }
1613
1614 fn scroll_sidebar(visual: &mut VisualTestContext, delta: f32) {
1615 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1616 visual.simulate_event(ScrollWheelEvent {
1617 position: sidebar.center(),
1618 delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1619 ..Default::default()
1620 });
1621 }
1622
1623 #[gpui_kit::test]
1624 fn chat_list_line_shows_only_while_scrolled(cx: &mut TestAppContext) {
1625 let (handle, _) = mount(cx);
1626 let mut visual = VisualTestContext::from_window(handle, cx);
1627 for (width, height) in SIZES {
1628 visual.simulate_resize(size(px(width), px(height)));
1629 let window = Bounds {
1630 origin: point(px(0.), px(0.)),
1631 size: size(px(width), px(height)),
1632 };
1633 collect(&mut visual, None);
1634 scroll_sidebar(&mut visual, 100_000.);
1635 let tags = collect(&mut visual, None);
1636 assert!(
1637 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1638 "chat list at its top must not show the line at {width}x{height}"
1639 );
1640 scroll_sidebar(&mut visual, -120.);
1641 let scrolled = collect(&mut visual, Some(SIDEBAR_SCROLL_DIVIDER));
1642 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1643 let line = visual
1644 .debug_bounds(SIDEBAR_SCROLL_DIVIDER)
1645 .expect("scrolled chat list shows the line");
1646 assert!(
1647 line.top() > sidebar.top() + px(TOLERANCE),
1648 "the line sits under the Chats header, not on the island edge: {} in {}",
1649 describe(line),
1650 describe(sidebar)
1651 );
1652 let found: Vec<String> = violations(&scrolled, window, &[SIDEBAR_SCROLL_DIVIDER])
1653 .into_iter()
1654 .chain(violations(&tags, window, &[]))
1655 .map(|(key, message)| format!("chat-list@{width}x{height}:{key}: {message}"))
1656 .collect();
1657 assert!(found.is_empty(), "{}", found.join("\n"));
1658 scroll_sidebar(&mut visual, 100_000.);
1659 collect(&mut visual, None);
1660 assert!(
1661 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1662 "the line goes away once the chat list is back at its top"
1663 );
1664 }
1665 }
1666
1667 #[gpui_kit::test]
1668 fn header_tabs_sit_above_the_header_line(cx: &mut TestAppContext) {
1669 let (handle, state) = mount(cx);
1670 let mut visual = VisualTestContext::from_window(handle, cx);
1671 for (width, height) in SIZES {
1672 visual.simulate_resize(size(px(width), px(height)));
1673 let window = Bounds {
1674 origin: point(px(0.), px(0.)),
1675 size: size(px(width), px(height)),
1676 };
1677 visual.update(|_, cx| {
1678 state.update(cx, |state, cx| {
1679 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1680 })
1681 });
1682 let tags = collect(&mut visual, Some(RECAP_TAB));
1683 let main = visual.debug_bounds(MAIN).expect("main island rendered");
1684 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1685 let line = visual
1686 .debug_bounds(HEADER_DIVIDER)
1687 .expect("the header line is always shown");
1688 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
1689 assert!(
1690 tab.top() >= main.top() && near(tab.bottom(), line.top()),
1691 "tab {} must sit in the top bar above the line {}",
1692 describe(tab),
1693 describe(line)
1694 );
1695 let found: Vec<String> = violations(&tags, window, &[HEADER_DIVIDER, RECAP_TAB])
1696 .into_iter()
1697 .map(|(key, message)| format!("header@{width}x{height}:{key}: {message}"))
1698 .collect();
1699 assert!(found.is_empty(), "{}", found.join("\n"));
1700 }
1701 }
1702
1703 #[gpui_kit::test]
1704 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1705 let (handle, state) = mount(cx);
1706 let mut visual = VisualTestContext::from_window(handle, cx);
1707 for (width, height) in SIZES {
1708 visual.simulate_resize(size(px(width), px(height)));
1709 let window = Bounds {
1710 origin: point(px(0.), px(0.)),
1711 size: size(px(width), px(height)),
1712 };
1713 visual.update(|_, cx| {
1714 state.update(cx, |state, cx| {
1715 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1716 })
1717 });
1718 collect(&mut visual, Some(RECAP_TAB));
1719 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1720 visual.simulate_click(tab.center(), Default::default());
1721 let tags = collect(&mut visual, Some(RECAP_REGION));
1722 let mut expected = GUARDED.to_vec();
1723 expected.extend([RECAP_TAB, RECAP_REGION]);
1724 let found: Vec<String> = violations(&tags, window, &expected)
1725 .into_iter()
1726 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1727 .collect();
1728 assert!(found.is_empty(), "{}", found.join("\n"));
1729 }
1730 }
1731
1732 // Devices opens a camera preview; the effects worker schedules onto the
1733 // deterministic test scheduler and trips "Your test is not deterministic".
1734 #[gpui_kit::test]
1735 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1736 let sections: Vec<_> = SETTINGS_SECTIONS
1737 .into_iter()
1738 .filter(|section| *section != SettingsSection::Devices)
1739 .collect();
1740 check_settings_dialog(cx, &sections);
1741 }
1742
1743 #[gpui_kit::test]
1744 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1745 crate::theme::set_thread_scheme(Some("teams"));
1746 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1747 crate::theme::set_thread_scheme(None);
1748 }
1749
1750 #[gpui_kit::test]
1751 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1752 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1753 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1754 crate::theme::set_thread_shade(None);
1755 }
1756
1757 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1758 let (handle, state) = mount_with(cx, true);
1759 let mut visual = VisualTestContext::from_window(handle, cx);
1760 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1761 visual.simulate_resize(size(px(width), px(height)));
1762 let window = Bounds {
1763 origin: point(px(0.), px(0.)),
1764 size: size(px(width), px(height)),
1765 };
1766 let inset = metrics(width, height).inset;
1767 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1768 for &section in sections {
1769 visual
1770 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1771 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1772 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1773 .into_iter()
1774 .filter(|(key, _)| key.starts_with("settings"))
1775 .chain(inset_violations(&tags, INSET_RULES))
1776 .collect();
1777 if label_sizes {
1778 found.extend(nav_label_violations(&mut visual));
1779 }
1780 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1781 .iter()
1782 .any(|(exempt, _)| *exempt == section);
1783 if !scrolled_exempt {
1784 found.extend(scrolled_inset_violation(&mut visual));
1785 }
1786 let found: Vec<String> = found
1787 .into_iter()
1788 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1789 .collect();
1790 assert!(found.is_empty(), "{}", found.join("\n"));
1791 let dialog = visual
1792 .debug_bounds(SETTINGS_TAGS[0])
1793 .expect("settings dialog");
1794 let edges = [
1795 f32::from(dialog.left()),
1796 f32::from(dialog.top()),
1797 width - f32::from(dialog.right()),
1798 height - f32::from(dialog.bottom()),
1799 ];
1800 assert!(
1801 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1802 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1803 );
1804 }
1805 }
1806 }
1807
1808 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1809
1810 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1811 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1812 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1813 };
1814 let mut found = Vec::new();
1815 for section in SETTINGS_SECTIONS {
1816 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1817 let item_path: &'static str = if section == SettingsSection::About {
1818 SETTINGS_NAV_ABOUT
1819 } else if section == SettingsSection::Help {
1820 SETTINGS_NAV_HELP
1821 } else {
1822 Box::leak(item_selector(section).into_boxed_str())
1823 };
1824 let (Some(label_bounds), Some(item)) = (
1825 visual.debug_bounds(label_path),
1826 visual.debug_bounds(item_path),
1827 ) else {
1828 if section != SettingsSection::Agents {
1829 found.push((label_path.to_owned(), "not rendered".to_owned()));
1830 }
1831 continue;
1832 };
1833 let text = label(section);
1834 let text_width = visual.update(|window, _| {
1835 let run = window.text_style().to_run(text.len());
1836 f32::from(
1837 window
1838 .text_system()
1839 .shape_line(text.clone().into(), px(NAV_LABEL_SIZE), &[run], None)
1840 .width,
1841 )
1842 });
1843 let label_width = f32::from(label_bounds.size.width);
1844 let label_height = f32::from(label_bounds.size.height);
1845 if text_width > label_width + TOLERANCE
1846 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1847 {
1848 found.push((
1849 label_path.to_owned(),
1850 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1851 ));
1852 }
1853 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1854 inner.left() < outer.left() - px(TOLERANCE)
1855 || inner.right() > outer.right() + px(TOLERANCE)
1856 || inner.top() < outer.top() - px(TOLERANCE)
1857 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1858 };
1859 if outside(label_bounds, item) {
1860 found.push((
1861 label_path.to_owned(),
1862 format!("label {label_bounds:?} outside item {item:?}"),
1863 ));
1864 }
1865 if item.left() < nav.left() || item.right() > nav.right() {
1866 found.push((
1867 item_path.to_owned(),
1868 format!("item {item:?} outside nav {nav:?}"),
1869 ));
1870 }
1871 }
1872 found
1873 }
1874
1875 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1876 let body = visual.debug_bounds(SETTINGS_BODY)?;
1877 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1878 if content.bottom() <= body.bottom() {
1879 return None;
1880 }
1881 visual.simulate_event(ScrollWheelEvent {
1882 position: body.center(),
1883 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1884 ..Default::default()
1885 });
1886 collect(visual, None);
1887 let body = visual.debug_bounds(SETTINGS_BODY)?;
1888 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1889 inset_violation(&SCROLLED_INSET_RULE, body, content)
1890 }
1891
1892 #[gpui_kit::test]
1893 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1894 let (handle, state) = mount(cx);
1895 let mut visual = VisualTestContext::from_window(handle, cx);
1896 for (width, height) in SIZES {
1897 visual.simulate_resize(size(px(width), px(height)));
1898 let window = Bounds {
1899 origin: point(px(0.), px(0.)),
1900 size: size(px(width), px(height)),
1901 };
1902 visual.update(|_, cx| {
1903 state.update(cx, |state, cx| {
1904 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1905 })
1906 });
1907 collect(&mut visual, Some(MEMBERS_BUTTON));
1908 let button = visual
1909 .debug_bounds(MEMBERS_BUTTON)
1910 .expect("members button rendered");
1911 visual.simulate_click(button.center(), Default::default());
1912 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1913 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1914 .into_iter()
1915 .filter(|(key, _)| key.starts_with("chat-members"))
1916 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1917 .collect();
1918 visual.simulate_keystrokes("escape");
1919 visual.run_until_parked();
1920 assert!(found.is_empty(), "{}", found.join("\n"));
1921 }
1922 }
1923
1924 #[gpui_kit::test]
1925 fn a_long_members_list_scrolls_to_its_last_person(cx: &mut TestAppContext) {
1926 const PEOPLE: usize = 12;
1927 let (handle, state) = mount(cx);
1928 let mut visual = VisualTestContext::from_window(handle, cx);
1929 visual.simulate_resize(size(px(1280.), px(800.)));
1930 visual.update(|_, cx| {
1931 state.update(cx, |state, cx| {
1932 if let Some(chat) = state
1933 .sidebar
1934 .chats
1935 .iter_mut()
1936 .find(|chat| chat.id == MEMBERS_CHAT)
1937 {
1938 chat.members = (0..PEOPLE)
1939 .map(|index| store::MemberRecord {
1940 user_id: Some(format!("guard-person-{index}")),
1941 display_name: format!("Person {index}"),
1942 })
1943 .collect();
1944 }
1945 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1946 })
1947 });
1948 collect(&mut visual, Some(MEMBERS_BUTTON));
1949 let button = visual
1950 .debug_bounds(MEMBERS_BUTTON)
1951 .expect("members button rendered");
1952 visual.simulate_click(button.center(), Default::default());
1953 collect(&mut visual, Some("chat-members-popup/list"));
1954 let list = visual
1955 .debug_bounds("chat-members-popup/list")
1956 .expect("list");
1957 let last_row = "chat-members-popup/row-11";
1958 visual.simulate_event(ScrollWheelEvent {
1959 position: list.center(),
1960 delta: ScrollDelta::Pixels(point(px(0.), px(-2_000.))),
1961 ..Default::default()
1962 });
1963 collect(&mut visual, None);
1964 let list = visual
1965 .debug_bounds("chat-members-popup/list")
1966 .expect("list");
1967 let last = visual.debug_bounds(last_row).expect("last person rendered");
1968 assert!(
1969 last.bottom() <= list.bottom() + px(0.5),
1970 "last person {last:?} below the list {list:?}"
1971 );
1972 }
1973
1974 #[gpui_kit::test]
1975 fn the_group_name_field_keeps_typed_text_across_frames(cx: &mut TestAppContext) {
1976 let (handle, state) = mount(cx);
1977 let mut visual = VisualTestContext::from_window(handle, cx);
1978 visual.update(|_, cx| {
1979 state.update(cx, |state, cx| {
1980 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1981 })
1982 });
1983 collect(&mut visual, Some(GROUP_NAME_BUTTON));
1984 let button = visual
1985 .debug_bounds(GROUP_NAME_BUTTON)
1986 .expect("group name button rendered");
1987 visual.simulate_click(button.center(), Default::default());
1988 collect(&mut visual, Some(GROUP_NAME_FORM));
1989 assert!(
1990 visual.debug_bounds(GROUP_NAME_FORM).is_some(),
1991 "group name form open"
1992 );
1993 visual.simulate_keystrokes("backspace x space y enter");
1994 visual.run_until_parked();
1995 let title = visual.update(|_, cx| {
1996 state
1997 .read(cx)
1998 .sidebar
1999 .chats
2000 .iter()
2001 .find(|chat| chat.id == MEMBERS_CHAT)
2002 .map(|chat| chat.title.clone())
2003 });
2004 assert_eq!(title.as_deref(), Some("Release planninx y"));
2005 }
2006
2007 const FORWARD_CHAT: &str = "demo-chat-release";
2008 const FORWARD_FOOTER_TAGS: [&str; 4] = [
2009 FORWARD_FOOTER_TAG,
2010 FORWARD_FOOTER_BAR_TAG,
2011 FORWARD_FOOTER_COUNT_TAG,
2012 FORWARD_FOOTER_NEXT_TAG,
2013 ];
2014 const FORWARD_DIALOG_PADDING: f32 = 16.;
2015 const FORWARD_BAR_PADDING: f32 = 8.;
2016 const FORWARD_ROWS_SCANNED: usize = 80;
2017
2018 fn forward_message_ids(
2019 state: &Entity<AppState>,
2020 visual: &mut VisualTestContext,
2021 ) -> Vec<String> {
2022 visual.update(|_, cx| {
2023 let mut records = state
2024 .read(cx)
2025 .store
2026 .messages(FORWARD_CHAT, None, 50)
2027 .expect("demo messages");
2028 records.retain(|record| !record.deleted);
2029 records.sort_by_key(|record| record.created_at);
2030 records
2031 .iter()
2032 .rev()
2033 .take(2)
2034 .map(|record| record.message_id.clone())
2035 .collect()
2036 })
2037 }
2038
2039 #[gpui_kit::test]
2040 fn forward_selection_footer_checks_and_dialog_keep_their_insets(cx: &mut TestAppContext) {
2041 let (handle, state) = mount(cx);
2042 let mut visual = VisualTestContext::from_window(handle, cx);
2043 for (width, height) in SIZES {
2044 visual.simulate_resize(size(px(width), px(height)));
2045 let window = Bounds {
2046 origin: point(px(0.), px(0.)),
2047 size: size(px(width), px(height)),
2048 };
2049 visual.update(|_, cx| {
2050 state.update(cx, |state, cx| {
2051 state.select(Selection::Chat(FORWARD_CHAT.to_owned()), cx)
2052 })
2053 });
2054 collect(&mut visual, Some(COMPOSER_BOX_TAG));
2055 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2056 let ids = forward_message_ids(&state, &mut visual);
2057 visual.update(|_, cx| {
2058 state.update(cx, |state, cx| {
2059 state.start_forward_selection(FORWARD_CHAT, &ids[0], cx);
2060 state.toggle_forward_selected(&ids[1], cx);
2061 })
2062 });
2063 collect(&mut visual, Some(FORWARD_FOOTER_NEXT_TAG));
2064 assert!(
2065 visual.debug_bounds(COMPOSER_BOX_TAG).is_none(),
2066 "the footer replaces the composer"
2067 );
2068 let tags: Vec<Tag> = FORWARD_FOOTER_TAGS
2069 .iter()
2070 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2071 .collect();
2072 let mut found: Vec<String> = violations(&tags, window, &FORWARD_FOOTER_TAGS)
2073 .into_iter()
2074 .map(|(key, message)| format!("forward@{width}x{height}:{key}: {message}"))
2075 .collect();
2076 let main = visual.debug_bounds(MAIN).expect("main island");
2077 let bar = visual.debug_bounds(FORWARD_FOOTER_BAR_TAG).expect("bar");
2078 let next = visual.debug_bounds(FORWARD_FOOTER_NEXT_TAG).expect("next");
2079 if (f32::from(bar.left() - composer.left())).abs() > TOLERANCE
2080 || (f32::from(bar.right() - composer.right())).abs() > TOLERANCE
2081 {
2082 found.push(format!(
2083 "forward@{width}x{height}: bar {} not on the composer edges {}",
2084 describe(bar),
2085 describe(composer)
2086 ));
2087 }
2088 for edge in [Edge::Top, Edge::Right, Edge::Bottom] {
2089 let gap = inset(bar, next, edge);
2090 if (gap - FORWARD_BAR_PADDING).abs() > TOLERANCE {
2091 found.push(format!(
2092 "forward@{width}x{height}: next button {edge:?} inset {gap} != {FORWARD_BAR_PADDING}"
2093 ));
2094 }
2095 }
2096 let checks: Vec<Bounds<Pixels>> = (0..FORWARD_ROWS_SCANNED)
2097 .filter_map(|index| {
2098 visual.debug_bounds(Box::leak(select_box_selector(index).into_boxed_str()))
2099 })
2100 .filter(|check| contains(main, *check))
2101 .collect();
2102 if checks.is_empty() {
2103 found.push(format!("forward@{width}x{height}: no checkbox rendered"));
2104 }
2105 let expected_left = ROW_PADDING + runway_margin(f32::from(main.size.width));
2106 for check in &checks {
2107 let left = inset(main, *check, Edge::Left);
2108 if (left - expected_left).abs() > TOLERANCE {
2109 found.push(format!(
2110 "forward@{width}x{height}: checkbox {} starts {left} from the island, not {expected_left}",
2111 describe(*check)
2112 ));
2113 }
2114 }
2115 visual.simulate_click(next.center(), Default::default());
2116 collect(&mut visual, Some(FORWARD_PREVIEW_TAG));
2117 let card = visual.debug_bounds(FORWARD_CARD_TAG).expect("dialog card");
2118 let preview = visual.debug_bounds(FORWARD_PREVIEW_TAG).expect("preview");
2119 if !contains(window, card) || !contains(card, preview) {
2120 found.push(format!(
2121 "forward@{width}x{height}: dialog {} or preview {} clipped",
2122 describe(card),
2123 describe(preview)
2124 ));
2125 }
2126 let (left, right) = (
2127 inset(card, preview, Edge::Left),
2128 inset(card, preview, Edge::Right),
2129 );
2130 if (left - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
2131 || (right - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
2132 {
2133 found.push(format!(
2134 "forward@{width}x{height}: preview insets {left}/{right} != {FORWARD_DIALOG_PADDING}"
2135 ));
2136 }
2137 visual.simulate_keystrokes("escape");
2138 collect(&mut visual, None);
2139 assert!(visual.debug_bounds(FORWARD_CARD_TAG).is_none());
2140 assert!(
2141 visual.debug_bounds(FORWARD_FOOTER_TAG).is_some(),
2142 "closing the dialog keeps the selection"
2143 );
2144 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_forward_selection(cx)));
2145 collect(&mut visual, Some(COMPOSER_BOX_TAG));
2146 assert!(visual.debug_bounds(FORWARD_FOOTER_TAG).is_none());
2147 assert!(found.is_empty(), "{}", found.join("\n"));
2148 }
2149 }
2150
2151 const MENU_ITEMS_SCANNED: usize = 40;
2152 const MENU_CHAT: &str = "demo-chat-release";
2153 const THEME_SELECT: &str = "settings-theme";
2154 const CALENDAR_DEFAULT_VIEW_SELECT: &str = "settings-calendar-default-view";
2155
2156 struct MenuRow {
2157 index: usize,
2158 item: Bounds<Pixels>,
2159 icon: Option<Bounds<Pixels>>,
2160 label: Option<Bounds<Pixels>>,
2161 }
2162
2163 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
2164 (0..MENU_ITEMS_SCANNED)
2165 .filter_map(|index| {
2166 let item =
2167 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
2168 Some(MenuRow {
2169 index,
2170 item,
2171 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
2172 label: visual
2173 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
2174 })
2175 })
2176 .collect()
2177 }
2178
2179 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
2180 let mut found = Vec::new();
2181 for row in rows {
2182 let Some(icon) = row.icon else {
2183 continue;
2184 };
2185 let key = format!("{MENU}/item-{}", row.index);
2186 if let Some(label) = row.label {
2187 let gap = f32::from(label.left() - icon.right());
2188 if (gap - expected_gap).abs() > TOLERANCE {
2189 found.push((
2190 format!("{key}:icon-gap"),
2191 format!(
2192 "icon {} to label {} is {gap} px, expected {expected_gap}",
2193 describe(icon),
2194 describe(label)
2195 ),
2196 ));
2197 }
2198 }
2199 let offset = f32::from(icon.center().y - row.item.center().y);
2200 if offset.abs() > TOLERANCE {
2201 found.push((
2202 format!("{key}:icon-off-centre"),
2203 format!(
2204 "icon {} sits {offset} px off the centre of item {}",
2205 describe(icon),
2206 describe(row.item)
2207 ),
2208 ));
2209 }
2210 }
2211 found
2212 }
2213
2214 fn listbox_violations(
2215 trigger: Bounds<Pixels>,
2216 menu: Bounds<Pixels>,
2217 items: Bounds<Pixels>,
2218 rows: &[MenuRow],
2219 ) -> Vec<(String, String)> {
2220 let mut found = Vec::new();
2221 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
2222 if !near(f32::from(menu.left() - trigger.left()), 0.) {
2223 found.push((
2224 format!("{MENU}:not-aligned-to-trigger"),
2225 format!(
2226 "list {} must start at the trigger's left edge {}",
2227 describe(menu),
2228 describe(trigger)
2229 ),
2230 ));
2231 }
2232 if !near(
2233 f32::from(menu.top() - trigger.bottom()),
2234 f32::from(DROPDOWN_OFFSET),
2235 ) {
2236 found.push((
2237 format!("{MENU}:trigger-offset"),
2238 format!(
2239 "list {} must open {} px below the trigger {}",
2240 describe(menu),
2241 f32::from(DROPDOWN_OFFSET),
2242 describe(trigger)
2243 ),
2244 ));
2245 }
2246 if menu.size.width < trigger.size.width - px(TOLERANCE) {
2247 found.push((
2248 format!("{MENU}:narrower-than-trigger"),
2249 format!(
2250 "list {} is narrower than the trigger {}",
2251 describe(menu),
2252 describe(trigger)
2253 ),
2254 ));
2255 }
2256 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
2257 let top = f32::from(first.item.top() - items.top());
2258 let bottom = f32::from(items.bottom() - last.item.bottom());
2259 let padding = f32::from(MENU_LIST_PADDING);
2260 if !near(top, padding) || !near(bottom, padding) {
2261 found.push((
2262 format!("{MENU}:uneven-padding"),
2263 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
2264 ));
2265 }
2266 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
2267 match first.icon {
2268 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
2269 check => found.push((
2270 format!("{MENU}:check-inset"),
2271 format!(
2272 "check column {check:?} must start {expected_inset} px inside the list {}",
2273 describe(menu)
2274 ),
2275 )),
2276 }
2277 }
2278 found
2279 }
2280
2281 #[test]
2282 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
2283 let row =
2284 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
2285 index,
2286 item: rectangle(4., item_top, 120., 32.),
2287 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
2288 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
2289 };
2290 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
2291 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
2292 .into_iter()
2293 .map(|(key, _)| key)
2294 .collect();
2295 assert_eq!(
2296 keys,
2297 [
2298 "popup-menu/item-1:icon-gap",
2299 "popup-menu/item-1:icon-off-centre"
2300 ]
2301 );
2302
2303 let trigger = rectangle(100., 50., 216., 32.);
2304 let option = |index: usize, top: f32| MenuRow {
2305 index,
2306 item: rectangle(104., top, 208., 32.),
2307 icon: Some(rectangle(110., top + 8., 16., 16.)),
2308 label: Some(rectangle(132., top + 6., 80., 20.)),
2309 };
2310 let aligned = [option(0, 88.), option(1, 122.)];
2311 let menu = rectangle(100., 84., 216., 74.);
2312 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
2313 let shifted = rectangle(96., 90., 200., 80.);
2314 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
2315 .into_iter()
2316 .map(|(key, _)| key)
2317 .collect();
2318 assert_eq!(
2319 keys,
2320 [
2321 "popup-menu:not-aligned-to-trigger",
2322 "popup-menu:trigger-offset",
2323 "popup-menu:narrower-than-trigger",
2324 "popup-menu:uneven-padding",
2325 "popup-menu:check-inset",
2326 ]
2327 );
2328 }
2329
2330 #[gpui_kit::test]
2331 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
2332 let (handle, _) = mount(cx);
2333 let mut visual = VisualTestContext::from_window(handle, cx);
2334 visual.simulate_resize(size(px(1280.), px(800.)));
2335 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
2336 collect(&mut visual, Some(chat_row));
2337 let mut found = Vec::new();
2338 let own_status = visual
2339 .debug_bounds(OWN_STATUS)
2340 .expect("own status button rendered");
2341 visual.simulate_click(own_status.center(), Default::default());
2342 collect(&mut visual, Some(MENU));
2343 let status_rows = menu_rows(&mut visual);
2344 assert!(
2345 status_rows.iter().any(|row| row.icon.is_some()),
2346 "status menu shows icons"
2347 );
2348 found.extend(menu_row_violations(
2349 &status_rows,
2350 f32::from(MENU_ICON_LABEL_GAP),
2351 ));
2352 visual.simulate_keystrokes("escape");
2353 collect(&mut visual, None);
2354 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
2355 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
2356 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
2357 collect(&mut visual, Some(MENU));
2358 let chat_rows = menu_rows(&mut visual);
2359 assert!(
2360 chat_rows.iter().any(|row| row.icon.is_some()),
2361 "chat menu shows icons"
2362 );
2363 found.extend(menu_row_violations(
2364 &chat_rows,
2365 f32::from(MENU_ICON_LABEL_GAP),
2366 ));
2367 let found: Vec<String> = found
2368 .into_iter()
2369 .map(|(key, message)| format!("{key}: {message}"))
2370 .collect();
2371 assert!(found.is_empty(), "{}", found.join("\n"));
2372 }
2373
2374 #[gpui_kit::test]
2375 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2376 select_list_lines_up(cx, SettingsSection::Appearance, THEME_SELECT);
2377 }
2378
2379 #[gpui_kit::test]
2380 fn calendar_default_view_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2381 select_list_lines_up(cx, SettingsSection::Calendar, CALENDAR_DEFAULT_VIEW_SELECT);
2382 }
2383
2384 fn select_list_lines_up(cx: &mut TestAppContext, section: SettingsSection, id: &str) {
2385 let (handle, state) = mount(cx);
2386 let mut visual = VisualTestContext::from_window(handle, cx);
2387 visual.simulate_resize(size(px(1280.), px(800.)));
2388 visual.update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
2389 let select: &'static str = Box::leak(select_selector(id).into_boxed_str());
2390 collect(&mut visual, Some(select));
2391 let trigger = visual.debug_bounds(select).expect("select rendered");
2392 visual.simulate_click(trigger.center(), Default::default());
2393 collect(&mut visual, Some(MENU));
2394 let menu = visual.debug_bounds(MENU).expect("list rendered");
2395 let items = visual
2396 .debug_bounds(ITEMS_SELECTOR)
2397 .expect("list items rendered");
2398 let rows = menu_rows(&mut visual);
2399 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
2400 .into_iter()
2401 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
2402 .map(|(key, message)| format!("{key}: {message}"))
2403 .collect();
2404 assert!(found.is_empty(), "{}", found.join("\n"));
2405 }
2406
2407 const BADGE_SAMPLES: [(u32, bool); 5] =
2408 [(1, false), (42, false), (120, false), (7, true), (15, true)];
2409
2410 struct BadgeSamples;
2411
2412 impl gpui_kit::Render for BadgeSamples {
2413 fn render(
2414 &mut self,
2415 _: &mut gpui_kit::Window,
2416 _: &mut gpui_kit::Context<Self>,
2417 ) -> impl gpui_kit::IntoElement {
2418 use gpui_kit::{ParentElement as _, Styled as _};
2419 gpui_kit::div()
2420 .flex()
2421 .gap(px(12.))
2422 .p(px(12.))
2423 .children(BADGE_SAMPLES.map(|(count, rail)| {
2424 if rail {
2425 badge_pill(
2426 count,
2427 RAIL_BADGE,
2428 crate::theme::accent(),
2429 crate::theme::on_accent(),
2430 )
2431 } else {
2432 count_badge(count, false)
2433 }
2434 }))
2435 }
2436 }
2437
2438 fn badge_violation(
2439 text: &str,
2440 pill: Bounds<Pixels>,
2441 label: Bounds<Pixels>,
2442 ink_offset: (f32, f32),
2443 ) -> Option<(String, String)> {
2444 let ink_x = f32::from(label.center().x) + ink_offset.0;
2445 let ink_y = f32::from(label.center().y) + ink_offset.1;
2446 let off_x = ink_x - f32::from(pill.center().x);
2447 let off_y = ink_y - f32::from(pill.center().y);
2448 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
2449 (
2450 format!("count-badge/{text}:off-centre"),
2451 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
2452 )
2453 })
2454 }
2455
2456 #[test]
2457 fn badge_rule_flags_off_centre_text() {
2458 let pill = rectangle(0., 0., 18., 18.);
2459 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
2460 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
2461 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
2462 }
2463
2464 #[gpui_kit::test]
2465 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
2466 cx.update(gpui_kit::init);
2467 cx.update(crate::theme::apply);
2468 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
2469 collect(visual, None);
2470 let mut found = Vec::new();
2471 for (count, rail) in BADGE_SAMPLES {
2472 let text = crate::format::badge_text(count);
2473 let pill = visual
2474 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
2475 .expect("badge rendered");
2476 let label = visual
2477 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
2478 .expect("badge text rendered");
2479 let font_size = if rail {
2480 RAIL_BADGE.font_size
2481 } else {
2482 COUNT_BADGE.font_size
2483 };
2484 let offset = visual.update(|window, _| {
2485 let origin = badge_text_origin(window, &text, font_size, pill);
2486 let (ink_centre, cap_height) = badge_ink_centre(window, &text, font_size);
2487 (
2488 f32::from(origin.x) + ink_centre - f32::from(label.center().x),
2489 f32::from(origin.y) - cap_height / 2. - f32::from(label.center().y),
2490 )
2491 });
2492 found.extend(badge_violation(&text, pill, label, offset));
2493 }
2494 let found: Vec<String> = found
2495 .into_iter()
2496 .map(|(key, message)| format!("{key}: {message}"))
2497 .collect();
2498 assert!(found.is_empty(), "{}", found.join("\n"));
2499 }
2500
2501 const PINNED_CHAT: &str = "demo-chat-release";
2502 const PINNED_CHANNEL: &str = "demo-channel-1-1";
2503
2504 #[gpui_kit::test]
2505 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
2506 let (handle, state) = mount(cx);
2507 let mut visual = VisualTestContext::from_window(handle, cx);
2508 let mut found = Vec::new();
2509 for (width, height) in SIZES {
2510 visual.simulate_resize(size(px(width), px(height)));
2511 visual.update(|_, cx| {
2512 state.update(cx, |state, cx| {
2513 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
2514 })
2515 });
2516 collect(&mut visual, Some(PIN_BANNER_TAG));
2517 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
2518 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2519 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2520 let gaps = [
2521 ("top", f32::from(banner.top() - timeline.top())),
2522 ("left", f32::from(banner.left() - timeline.left())),
2523 ("right", f32::from(timeline.right() - banner.right())),
2524 ("below divider", f32::from(banner.top() - divider.bottom())),
2525 ];
2526 let runway = runway_margin(f32::from(timeline.size.width) - 2. * BANNER_INSET);
2527 let sides_ok = gaps[1..3]
2528 .iter()
2529 .all(|(_, gap)| (gap - BANNER_INSET - runway).abs() <= INSET_TOLERANCE);
2530 let vertical_ok = [gaps[0].1, gaps[3].1]
2531 .iter()
2532 .all(|gap| (gap - BANNER_INSET).abs() <= INSET_TOLERANCE);
2533 if !sides_ok || !vertical_ok {
2534 found.push(format!(
2535 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
2536 ));
2537 }
2538 }
2539 assert!(found.is_empty(), "{}", found.join("\n"));
2540 }
2541
2542 #[gpui_kit::test]
2543 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
2544 let (handle, state) = mount(cx);
2545 let mut visual = VisualTestContext::from_window(handle, cx);
2546 visual.simulate_resize(size(px(1280.), px(800.)));
2547 visual.update(|_, cx| {
2548 state.update(cx, |state, cx| {
2549 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2550 })
2551 });
2552 collect(&mut visual, Some(TIMELINE_TAG));
2553 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
2554 }
2555
2556 fn open_channel(cx: &mut TestAppContext, awaited: &'static str) -> VisualTestContext {
2557 let (handle, state) = mount(cx);
2558 let mut visual = VisualTestContext::from_window(handle, cx);
2559 visual.simulate_resize(size(px(1280.), px(800.)));
2560 visual.update(|_, cx| {
2561 state.update(cx, |state, cx| {
2562 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2563 })
2564 });
2565 collect(&mut visual, Some(awaited));
2566 visual
2567 }
2568
2569 #[gpui_kit::test]
2570 fn the_new_post_is_one_card_with_subject_divider_format_bar_and_post_button(
2571 cx: &mut TestAppContext,
2572 ) {
2573 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2574 let open = visual
2575 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2576 .expect("post in channel card");
2577 visual.simulate_click(open.center(), Default::default());
2578 collect(&mut visual, Some(POST_CARD_SEND_TAG));
2579 let mut bounds_of = |path: &'static str| {
2580 visual
2581 .debug_bounds(path)
2582 .unwrap_or_else(|| panic!("{path} missing"))
2583 };
2584 let card = bounds_of(COMPOSER_BOX_TAG);
2585 let header = bounds_of(POST_CARD_HEADER_TAG);
2586 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2587 let divider = bounds_of(POST_CARD_DIVIDER_TAG);
2588 let format_bar = bounds_of(COMPOSER_FORMAT_BAR_TAG);
2589 let footer = bounds_of(POST_CARD_FOOTER_TAG);
2590 let send = bounds_of(POST_CARD_SEND_TAG);
2591 assert!(
2592 visual.debug_bounds(COMPOSER_SEND_TAG).is_none(),
2593 "chat send button shown in a post"
2594 );
2595 assert!(
2596 visual.debug_bounds(COMPOSER_FORMAT_TAG).is_none(),
2597 "format toggle shown although the bar stays open"
2598 );
2599 assert!(header.bottom() <= subject.top() && subject.bottom() <= divider.top());
2600 assert!(divider.bottom() <= format_bar.top() && format_bar.bottom() <= footer.top());
2601 assert!(
2602 f32::from(divider.left() - card.left()).abs() < 1.5
2603 && f32::from(card.right() - divider.right()).abs() < 1.5,
2604 "subject divider {} does not run edge to edge in {}",
2605 describe(divider),
2606 describe(card)
2607 );
2608 let side = f32::from(card.right() - send.right());
2609 let bottom = f32::from(card.bottom() - send.bottom());
2610 assert!(
2611 (side - bottom).abs() < TOLERANCE,
2612 "Post button insets: side {side}, bottom {bottom}"
2613 );
2614 }
2615
2616 #[gpui_kit::test]
2617 fn announcement_mode_puts_the_banner_between_author_and_subheading(cx: &mut TestAppContext) {
2618 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2619 let open = visual
2620 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2621 .expect("post in channel card");
2622 visual.simulate_click(open.center(), Default::default());
2623 collect(&mut visual, Some(POST_ANNOUNCEMENT_TOGGLE_TAG));
2624 let toggle = visual
2625 .debug_bounds(POST_ANNOUNCEMENT_TOGGLE_TAG)
2626 .expect("announcement toggle in the format bar");
2627 let format_bar = visual
2628 .debug_bounds(COMPOSER_FORMAT_BAR_TAG)
2629 .expect("format bar");
2630 assert!(
2631 format_bar.contains(&toggle.center()),
2632 "toggle outside the format bar"
2633 );
2634 visual.simulate_click(toggle.center(), Default::default());
2635 collect(&mut visual, Some(POST_ANNOUNCEMENT_TAG));
2636 let mut bounds_of = |path: &'static str| {
2637 visual
2638 .debug_bounds(path)
2639 .unwrap_or_else(|| panic!("{path} missing"))
2640 };
2641 let card = bounds_of(COMPOSER_BOX_TAG);
2642 let header = bounds_of(POST_CARD_HEADER_TAG);
2643 let banner = bounds_of(POST_ANNOUNCEMENT_TAG);
2644 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2645 assert!(header.bottom() <= banner.top() && banner.bottom() <= subject.top());
2646 let gap = f32::from(subject.top() - banner.bottom());
2647 assert!(gap >= 6., "subheading {gap} px under the banner");
2648 let audience = bounds_of(POST_AUDIENCE_TAG);
2649 assert!(
2650 audience.bottom() <= card.top(),
2651 "audience hint not above the card"
2652 );
2653 let left = f32::from(banner.left() - card.left());
2654 let right = f32::from(card.right() - banner.right());
2655 assert!(
2656 (left - right).abs() < TOLERANCE,
2657 "banner insets: left {left}, right {right}"
2658 );
2659 }
2660
2661 #[gpui_kit::test]
2662 fn channel_posts_start_the_body_at_the_avatar_edge_like_teams(cx: &mut TestAppContext) {
2663 let mut visual = open_channel(cx, POST_FOOTER_AVATAR_TAG);
2664 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
2665 visual
2666 .debug_bounds(path)
2667 .unwrap_or_else(|| panic!("{path} rendered"))
2668 };
2669 let card = bounds_of(&mut visual, POST_CARD_TAG);
2670 let avatar = bounds_of(&mut visual, POST_AVATAR_TAG);
2671 let body = bounds_of(&mut visual, POST_BODY_TAG);
2672 let footer_avatar = bounds_of(&mut visual, POST_FOOTER_AVATAR_TAG);
2673 let side = f32::from(avatar.left() - card.left());
2674 let checks = [
2675 ("body left", f32::from(body.left() - avatar.left())),
2676 (
2677 "footer avatar left",
2678 f32::from(footer_avatar.left() - avatar.left()),
2679 ),
2680 (
2681 "body right inset",
2682 f32::from(card.right() - body.right()) - side,
2683 ),
2684 ];
2685 for (name, gap) in checks {
2686 assert!(
2687 gap.abs() < INSET_TOLERANCE,
2688 "{name} off by {gap}: card {card:?} avatar {avatar:?} body {body:?} footer {footer_avatar:?}"
2689 );
2690 }
2691 }
2692
2693 #[gpui_kit::test]
2694 fn a_code_line_is_one_frame_inside_the_post_body(cx: &mut TestAppContext) {
2695 let mut visual = open_channel(cx, CODE_LINE_TAG);
2696 let code = visual.debug_bounds(CODE_LINE_TAG).expect("code line");
2697 let body = visual.debug_bounds(POST_BODY_TAG).expect("post body");
2698 assert!(
2699 f32::from(code.size.height) > 40.,
2700 "the long code line wraps inside one frame: {code:?}"
2701 );
2702 assert!(
2703 (f32::from(code.left() - body.left())).abs() < INSET_TOLERANCE
2704 && code.right() <= body.right() + px(INSET_TOLERANCE),
2705 "code {code:?} sits inside the body {body:?}"
2706 );
2707 assert!(visual.debug_bounds(CODE_BLOCK_TAG).is_none());
2708 }
2709
2710 #[gpui_kit::test]
2711 fn the_new_post_row_shows_a_scroll_edge_only_while_scrolled(cx: &mut TestAppContext) {
2712 let mut visual = open_channel(cx, POST_CARD_TAG);
2713 assert!(visual.debug_bounds(FEED_EDGE_TAG).is_none());
2714 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2715 visual.simulate_event(ScrollWheelEvent {
2716 position: timeline.center(),
2717 delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
2718 ..Default::default()
2719 });
2720 collect(&mut visual, Some(FEED_EDGE_TAG));
2721 let edge = visual.debug_bounds(FEED_EDGE_TAG).expect("feed edge");
2722 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2723 assert!(
2724 (f32::from(edge.top() - timeline.top())).abs() < INSET_TOLERANCE
2725 && (f32::from(edge.left() - timeline.left())).abs() < INSET_TOLERANCE
2726 && (f32::from(timeline.right() - edge.right())).abs() < INSET_TOLERANCE,
2727 "edge {edge:?} runs across the top of the timeline {timeline:?}"
2728 );
2729 }
2730
2731 #[gpui_kit::test]
2732 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
2733 let (handle, state) = mount(cx);
2734 let mut visual = VisualTestContext::from_window(handle, cx);
2735 visual.simulate_resize(size(px(1280.), px(800.)));
2736 visual.update(|_, cx| {
2737 state.update(cx, |state, cx| {
2738 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2739 })
2740 });
2741 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2742 let button = visual
2743 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2744 .expect("channel details button");
2745 visual.simulate_click(button.center(), Default::default());
2746 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
2747 let pane = visual
2748 .debug_bounds(CHANNEL_DETAILS_TAG)
2749 .expect("details pane");
2750 let main = visual.debug_bounds(MAIN).expect("main island");
2751 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2752 assert!(
2753 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
2754 "pane {pane:?} must end at the main island edge {main:?}"
2755 );
2756 assert!(
2757 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
2758 "pane {pane:?} must start under the header divider {divider:?}"
2759 );
2760 }
2761
2762 #[gpui_kit::test]
2763 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
2764 let (handle, state) = mount(cx);
2765 let mut visual = VisualTestContext::from_window(handle, cx);
2766 visual.simulate_resize(size(px(1280.), px(800.)));
2767 visual.update(|_, cx| {
2768 state.update(cx, |state, cx| {
2769 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2770 })
2771 });
2772 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2773 let button = visual
2774 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2775 .expect("channel details button");
2776 visual.simulate_click(button.center(), Default::default());
2777 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
2778 let pane = visual
2779 .debug_bounds(CHANNEL_DETAILS_TAG)
2780 .expect("details pane");
2781 let pinned = visual
2782 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
2783 .expect("pinned section");
2784 let shared = visual
2785 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
2786 .expect("shared section");
2787 assert!(
2788 pinned.bottom() <= shared.top(),
2789 "pinned {pinned:?} must come before shared {shared:?}"
2790 );
2791 for (name, section) in [("pinned", pinned), ("shared", shared)] {
2792 let left = f32::from(section.left() - pane.left());
2793 let right = f32::from(pane.right() - section.right());
2794 assert!(
2795 (left - right).abs() < INSET_TOLERANCE && left > 0.,
2796 "{name} section insets left {left} right {right} must match"
2797 );
2798 }
2799 }
2800
2801 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
2802 collect(visual, Some(COMPOSER_SEND_TAG));
2803 let mut bounds_of = |path: &'static str| {
2804 visual
2805 .debug_bounds(path)
2806 .unwrap_or_else(|| panic!("{path} rendered"))
2807 };
2808 let composer = bounds_of(COMPOSER_BOX_TAG);
2809 let input = bounds_of(COMPOSER_INPUT_TAG);
2810 let actions = bounds_of(COMPOSER_ACTIONS_TAG);
2811 let send = bounds_of(COMPOSER_SEND_TAG);
2812 [
2813 f32::from(input.left() - composer.left()),
2814 f32::from(actions.top() - composer.top()),
2815 f32::from(composer.bottom() - actions.bottom()),
2816 f32::from(composer.right() - send.right()),
2817 f32::from(send.top() - composer.top()),
2818 f32::from(composer.bottom() - send.bottom()),
2819 ]
2820 }
2821
2822 #[gpui_kit::test]
2823 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
2824 let (handle, _) = mount(cx);
2825 let mut visual = VisualTestContext::from_window(handle, cx);
2826 visual.simulate_resize(size(px(1280.), px(800.)));
2827 let single_line = composer_button_insets(&mut visual);
2828 let left = single_line[0];
2829 assert!(
2830 single_line
2831 .iter()
2832 .all(|inset| (inset - left).abs() < TOLERANCE),
2833 "single line: insets of the input left, the actions top and bottom, send right, top and bottom {single_line:?}"
2834 );
2835 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2836 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
2837 visual.simulate_click(point(input.center().x, send.center().y), Default::default());
2838 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
2839 let three_lines = composer_button_insets(&mut visual);
2840 assert!(
2841 three_lines[1] > single_line[1] + 30.,
2842 "three lines did not grow the composer: {three_lines:?}"
2843 );
2844 for inset in [
2845 three_lines[0],
2846 three_lines[2],
2847 three_lines[3],
2848 three_lines[5],
2849 ] {
2850 assert!(
2851 (inset - left).abs() < TOLERANCE,
2852 "three lines: insets of the input left, the actions top and bottom, send right, top and bottom {three_lines:?}, expected {left}"
2853 );
2854 }
2855 }
2856
2857 #[gpui_kit::test]
2858 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
2859 const FORMAT_TAGS: [&str; 6] = [
2860 COMPOSER_BOX_TAG,
2861 COMPOSER_FORMAT_BAR_TAG,
2862 COMPOSER_FORMAT_DIVIDER_TAG,
2863 COMPOSER_ACTIONS_TAG,
2864 COMPOSER_FORMAT_TAG,
2865 COMPOSER_SEND_TAG,
2866 ];
2867 let (handle, _) = mount(cx);
2868 let mut visual = VisualTestContext::from_window(handle, cx);
2869 for (width, height) in SIZES {
2870 visual.simulate_resize(size(px(width), px(height)));
2871 let window = Bounds {
2872 origin: point(px(0.), px(0.)),
2873 size: size(px(width), px(height)),
2874 };
2875 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
2876 let toggle = visual
2877 .debug_bounds(COMPOSER_FORMAT_TAG)
2878 .expect("format button");
2879 visual.simulate_click(toggle.center(), Default::default());
2880 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
2881 let tags: Vec<Tag> = FORMAT_TAGS
2882 .iter()
2883 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2884 .collect();
2885 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
2886 .into_iter()
2887 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
2888 .collect();
2889 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
2890 let actions = visual.debug_bounds(COMPOSER_ACTIONS_TAG).expect("actions");
2891 let toggle = visual
2892 .debug_bounds(COMPOSER_FORMAT_TAG)
2893 .expect("format button");
2894 visual.simulate_click(toggle.center(), Default::default());
2895 collect(&mut visual, None);
2896 assert!(found.is_empty(), "{}", found.join("\n"));
2897 assert!(
2898 bar.bottom() <= actions.top(),
2899 "bar {bar:?} over the buttons {actions:?}"
2900 );
2901 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
2902 }
2903 }
2904
2905 #[gpui_kit::test]
2906 fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2907 let (handle, _) = mount_with(cx, true);
2908 let mut visual = VisualTestContext::from_window(handle, cx);
2909 visual.dispatch_action(OpenActivity);
2910 for (width, height) in SIZES {
2911 visual.simulate_resize(size(px(width), px(height)));
2912 let window = Bounds {
2913 origin: point(px(0.), px(0.)),
2914 size: size(px(width), px(height)),
2915 };
2916 let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2917 let mut expected = GUARDED.to_vec();
2918 expected.push(ACTIVITY_PROPOSALS_TAG);
2919 let found: Vec<String> = violations(&tags, window, &expected)
2920 .into_iter()
2921 .map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2922 .collect();
2923 assert!(found.is_empty(), "{}", found.join("\n"));
2924 }
2925 }
2926
2927 #[gpui_kit::test]
2928 fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2929 const DELIVERY_TAGS: [&str; 5] = [
2930 COMPOSER_BOX_TAG,
2931 COMPOSER_ACTIONS_TAG,
2932 COMPOSER_PLUS_TAG,
2933 COMPOSER_IMPORTANCE_LABEL_TAG,
2934 COMPOSER_URGENT_BANNER_TAG,
2935 ];
2936 const URGENT_OPTION: &str = "urgent-delivery-option";
2937 const TEXT_INSET: f32 = 6.;
2938 let (handle, _) = mount(cx);
2939 let mut visual = VisualTestContext::from_window(handle, cx);
2940 for (width, height) in SIZES {
2941 visual.simulate_resize(size(px(width), px(height)));
2942 let window = Bounds {
2943 origin: point(px(0.), px(0.)),
2944 size: size(px(width), px(height)),
2945 };
2946 collect(&mut visual, Some(COMPOSER_PLUS_TAG));
2947 let button = visual.debug_bounds(COMPOSER_PLUS_TAG).expect("plus button");
2948 visual.simulate_click(button.center(), Default::default());
2949 let delivery_tag = PlusAction::DeliveryOptions.tag();
2950 collect(&mut visual, Some(delivery_tag));
2951 let delivery = visual.debug_bounds(delivery_tag).expect("delivery item");
2952 visual.simulate_click(delivery.center(), Default::default());
2953 collect(&mut visual, Some(URGENT_OPTION));
2954 let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2955 assert!(
2956 contains(window, menu),
2957 "menu {} leaves the window",
2958 describe(menu)
2959 );
2960 let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2961 visual.simulate_click(urgent.center(), Default::default());
2962 collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2963 assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2964 let tags: Vec<Tag> = DELIVERY_TAGS
2965 .iter()
2966 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2967 .collect();
2968 let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2969 .into_iter()
2970 .map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2971 .collect();
2972 assert!(found.is_empty(), "{}", found.join("\n"));
2973 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2974 let banner = visual
2975 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2976 .expect("banner");
2977 let label = visual
2978 .debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2979 .expect("label");
2980 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2981 assert!(
2982 (f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2983 && (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2984 "banner {} not on the composer edges {}",
2985 describe(banner),
2986 describe(composer)
2987 );
2988 assert!(
2989 banner.bottom() <= composer.top(),
2990 "banner {} over the composer {}",
2991 describe(banner),
2992 describe(composer)
2993 );
2994 assert!(
2995 (inset(composer, label, Edge::Left)
2996 - inset(composer, input, Edge::Left)
2997 - TEXT_INSET)
2998 .abs()
2999 <= TOLERANCE,
3000 "label {} not on the text edge of {}",
3001 describe(label),
3002 describe(input)
3003 );
3004 let close = visual
3005 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
3006 .map(|banner| point(banner.right() - px(18.), banner.center().y))
3007 .expect("banner");
3008 visual.simulate_click(close, Default::default());
3009 collect(&mut visual, None);
3010 assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
3011 assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
3012 }
3013 }
3014
3015 #[gpui_kit::test]
3016 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
3017 let (handle, state) = mount_with(cx, true);
3018 let mut visual = VisualTestContext::from_window(handle, cx);
3019 for (width, height) in SIZES {
3020 visual.simulate_resize(size(px(width), px(height)));
3021 for chat in IMPORTANCE_CHATS {
3022 visual.update(|_, cx| {
3023 state.update(cx, |state, cx| {
3024 state.select(Selection::Chat(chat.to_owned()), cx)
3025 })
3026 });
3027 collect(&mut visual, Some(TIMELINE_TAG));
3028 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
3029 visual.simulate_event(ScrollWheelEvent {
3030 position: timeline.center(),
3031 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
3032 ..Default::default()
3033 });
3034 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
3035 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
3036 let bubble = BUBBLE_TAGS
3037 .iter()
3038 .filter_map(|tag| visual.debug_bounds(tag))
3039 .find(|bubble| contains(*bubble, label))
3040 .unwrap_or_else(|| {
3041 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
3042 });
3043 let left = inset(bubble, label, Edge::Left);
3044 let top = inset(bubble, label, Edge::Top);
3045 assert!(
3046 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
3047 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
3048 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
3049 describe(bubble)
3050 );
3051 }
3052 }
3053 }
3054
3055 #[gpui_kit::test]
3056 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
3057 let (handle, state) = mount_with(cx, true);
3058 let mut visual = VisualTestContext::from_window(handle, cx);
3059 for (width, height) in SIZES {
3060 visual.simulate_resize(size(px(width), px(height)));
3061 let window = Bounds {
3062 origin: point(px(0.), px(0.)),
3063 size: size(px(width), px(height)),
3064 };
3065 for (chat, expected_tags) in [
3066 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
3067 (REACTION_CHAT, &AGENT_TAGS[3..]),
3068 ] {
3069 visual.update(|_, cx| {
3070 state.update(cx, |state, cx| {
3071 state.select(Selection::Chat(chat.to_owned()), cx)
3072 })
3073 });
3074 let tags = collect(&mut visual, Some(expected_tags[0]));
3075 let mut expected = GUARDED.to_vec();
3076 expected.extend(expected_tags);
3077 let found: Vec<String> = violations(&tags, window, &expected)
3078 .into_iter()
3079 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
3080 .collect();
3081 assert!(found.is_empty(), "{}", found.join("\n"));
3082 }
3083 }
3084 }
3085}
3086
3087#[test]
3088fn lines_are_solid() {
3089 let mut files = Vec::new();
3090 for root in source_roots() {
3091 source_files(&root, &mut files);
3092 }
3093 let violations: Vec<String> = files
3094 .iter()
3095 .filter(|file| !file.ends_with("layout_guard.rs"))
3096 .flat_map(|file| {
3097 let source = fs::read_to_string(file).expect("read source file");
3098 source
3099 .lines()
3100 .enumerate()
3101 .filter(|(_, line)| {
3102 line.contains(".border_dashed(") || line.contains(".border_dotted(")
3103 })
3104 .map(|(index, line)| {
3105 format!(
3106 "{}:{}: lines are always solid: {}",
3107 file.display(),
3108 index + 1,
3109 line.trim()
3110 )
3111 })
3112 .collect::<Vec<_>>()
3113 })
3114 .collect();
3115 assert!(violations.is_empty(), "{}", violations.join("\n"));
3116}
3117
3118const STATE_RING_COLORS: &[&str] = &[
3119 "if focused",
3120 "if selected",
3121 "if speaking",
3122 "if current",
3123 "if open",
3124 "if state.failed",
3125];
3126const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
3127 (
3128 "notify/ring_view.rs",
3129 "theme::green()",
3130 "state signal (pulsing ring around the caller while it rings), not a resting outline",
3131 ),
3132 (
3133 "settings/mcp.rs",
3134 "theme::border_strong()",
3135 "outlined button, not a surface",
3136 ),
3137 (
3138 "settings/rows.rs",
3139 "theme::border_strong()",
3140 "outlined button, not a surface",
3141 ),
3142 (
3143 "views/card_widgets.rs",
3144 "border)",
3145 "message content drawn as Teams renders it",
3146 ),
3147 (
3148 "views/card_widgets.rs",
3149 "theme::border_strong()",
3150 "message content drawn as Teams renders it",
3151 ),
3152 ("views/shared_tab.rs", "theme::accent()", "input field"),
3153 ("views/card_input.rs", "if error.is_some()", "input field"),
3154 ("views/format_toolbar.rs", "if refused", "input field"),
3155 (
3156 "views/card_code_block.rs",
3157 "theme::code_header_border()",
3158 "message content drawn as Teams renders it",
3159 ),
3160 (
3161 "render/elements.rs",
3162 "theme::code_frame()",
3163 "message content drawn as Teams renders it",
3164 ),
3165 ("views/call_transcript.rs", "theme::border()", "input field"),
3166 (
3167 "views/conversation.rs",
3168 "theme::accent()",
3169 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3170 ),
3171 (
3172 "views/attachment_tray.rs",
3173 "theme::accent()",
3174 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3175 ),
3176 (
3177 "views/card_carousel.rs",
3178 "theme::border_strong()",
3179 "message content drawn as Teams renders it",
3180 ),
3181 (
3182 "views/card_table.rs",
3183 "grid_color",
3184 "message content drawn as Teams renders it",
3185 ),
3186 (
3187 "views/activity_panel.rs",
3188 "theme::surface()",
3189 "cutout ring in the background color, invisible against its surface",
3190 ),
3191 (
3192 "views/avatar.rs",
3193 "theme::surface()",
3194 "cutout ring in the background color, invisible against its surface",
3195 ),
3196 (
3197 "views/message_row.rs",
3198 "theme::border_strong()",
3199 "deleted message placeholder, Teams look",
3200 ),
3201 (
3202 "views/message_row.rs",
3203 "theme::red()",
3204 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3205 ),
3206 (
3207 "views/message_row.rs",
3208 "if row.delivery",
3209 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3210 ),
3211 (
3212 "views/new_meeting_dialog.rs",
3213 "theme::border()",
3214 "input field",
3215 ),
3216 (
3217 "views/call_mini_window.rs",
3218 "theme::border_strong()",
3219 "self view over live video, needs an edge on any picture",
3220 ),
3221 ("views/transfer_picker.rs", "theme::border()", "input field"),
3222 (
3223 "views/call_notice.rs",
3224 "theme::border_strong()",
3225 "outlined button, not a surface",
3226 ),
3227 (
3228 "views/composer/schedule.rs",
3229 "theme::accent()",
3230 "input field",
3231 ),
3232 (
3233 "views/sidebar.rs",
3234 "theme::accent()",
3235 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3236 ),
3237 (
3238 "views/adaptive_card.rs",
3239 "theme::border()",
3240 "message content drawn as Teams renders it",
3241 ),
3242 (
3243 "views/adaptive_card.rs",
3244 "border)",
3245 "message content drawn as Teams renders it",
3246 ),
3247 (
3248 "views/share_bar.rs",
3249 "theme::red()",
3250 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3251 ),
3252 ("settings_controls.rs", "if invalid", "input field"),
3253];
3254
3255fn outlines(source: &str) -> Vec<(usize, String)> {
3256 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
3257 pattern
3258 .find_iter(source)
3259 .map(|found| {
3260 let line_number = source[..found.start()].matches('\n').count() + 1;
3261 let after = &source[found.end()..];
3262 let color = after
3263 .find(".border_color(")
3264 .filter(|position| *position < 120)
3265 .map(|position| {
3266 let start = &after[position + ".border_color(".len()..];
3267 start
3268 .lines()
3269 .map(str::trim)
3270 .find(|line| !line.is_empty())
3271 .unwrap_or_default()
3272 .to_owned()
3273 })
3274 .unwrap_or_default();
3275 (line_number, color)
3276 })
3277 .collect()
3278}
3279
3280#[test]
3281fn outline_matcher_reads_the_border_color() {
3282 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
3283 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
3284}
3285
3286#[test]
3287fn surfaces_are_soft() {
3288 let mut matched_allowlist = HashSet::new();
3289 let mut violations = Vec::new();
3290 for root in source_roots() {
3291 let mut files = Vec::new();
3292 source_files(&root, &mut files);
3293 for file in files {
3294 let relative = file
3295 .strip_prefix(&root)
3296 .expect("inside src")
3297 .to_string_lossy()
3298 .replace('\\', "/");
3299 if relative == "layout_guard.rs" {
3300 continue;
3301 }
3302 let source = fs::read_to_string(&file).expect("read source file");
3303 for (line_number, color) in outlines(&source) {
3304 if STATE_RING_COLORS
3305 .iter()
3306 .any(|prefix| color.starts_with(prefix))
3307 {
3308 continue;
3309 }
3310 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
3311 *allowed_file == relative && color.starts_with(prefix)
3312 }) {
3313 Some(position) => {
3314 matched_allowlist.insert(position);
3315 }
3316 None => violations.push(format!(
3317 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
3318 )),
3319 }
3320 }
3321 }
3322 }
3323 let stale = OUTLINE_ALLOWLIST
3324 .iter()
3325 .enumerate()
3326 .filter(|(position, _)| !matched_allowlist.contains(position))
3327 .map(|(_, (file, prefix, _))| {
3328 format!("stale outline allowlist entry, remove it: {file} {prefix}")
3329 });
3330 let report: Vec<String> = violations.into_iter().chain(stale).collect();
3331 assert!(report.is_empty(), "{}", report.join("\n"));
3332}
3333
3334fn indentation(line: &str) -> usize {
3335 line.len() - line.trim_start().len()
3336}
3337
3338fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
3339 let indent = indentation(lines[index]);
3340 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
3341 let start = lines[..index]
3342 .iter()
3343 .rposition(|line| !belongs(line))
3344 .map_or(0, |position| position + 1);
3345 let end = lines[index..]
3346 .iter()
3347 .position(|line| !belongs(line))
3348 .map_or(lines.len(), |position| index + position);
3349 lines[start..end]
3350 .iter()
3351 .filter(|line| indentation(line) == indent)
3352 .copied()
3353 .collect()
3354}
3355
3356fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
3357 let lines: Vec<&str> = source.lines().collect();
3358 (0..lines.len())
3359 .filter(|&index| row_height.is_match(lines[index]))
3360 .filter(|&index| {
3361 !chain_lines(&lines, index).iter().any(|line| {
3362 let line = line.trim();
3363 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
3364 })
3365 })
3366 .map(|index| index + 1)
3367 .collect()
3368}
3369
3370fn row_height_pattern() -> Regex {
3371 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
3372}
3373
3374#[test]
3375fn matcher_finds_rows_without_flex_none() {
3376 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";
3377 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
3378}
3379
3380#[test]
3381fn fixed_height_rows_never_shrink() {
3382 let row_height = row_height_pattern();
3383 let mut files = Vec::new();
3384 for root in source_roots() {
3385 source_files(&root, &mut files);
3386 }
3387 let violations: Vec<String> = files
3388 .iter()
3389 .filter(|file| !file.ends_with("layout_guard.rs"))
3390 .flat_map(|file| {
3391 let source = fs::read_to_string(file).expect("read source file");
3392 shrinking_rows(&row_height, &source)
3393 .into_iter()
3394 .map(|line| format!("{}:{line}", file.display()))
3395 .collect::<Vec<_>>()
3396 })
3397 .collect();
3398 assert!(
3399 violations.is_empty(),
3400 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
3401 );
3402}