BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 133.2 KiB Download Raw
1use std::collections::HashSet;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6
7const WIDGETS_FILE: &str = "widgets.rs";
8const SCAN_ALLOWLIST: &[(&str, &str)] = &[
9 ("views/toolbar_placement.rs", ".top(px(-SLOT_HEIGHT))"),
10 ("views/conversation.rs", ".bottom(px(-1.))"),
11];
12
13fn source_roots() -> Vec<PathBuf> {
14 let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
15 let mut roots: Vec<PathBuf> = fs::read_dir(&crates_directory)
16 .expect("read crates directory")
17 .map(|entry| entry.expect("directory entry").path())
18 .filter(|path| {
19 path.file_name()
20 .is_some_and(|name| name.to_string_lossy().starts_with("app"))
21 })
22 .map(|path| path.join("src"))
23 .filter(|path| path.is_dir())
24 .collect();
25 roots.sort();
26 roots
27}
28
29fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {
30 for entry in fs::read_dir(directory).expect("read source directory") {
31 let path = entry.expect("directory entry").path();
32 if path.is_dir() {
33 source_files(&path, files);
34 } else if path.extension().is_some_and(|extension| extension == "rs") {
35 files.push(path);
36 }
37 }
38}
39
40fn negative_offsets(
41 pattern: &Regex,
42 source: &str,
43 relative: &str,
44) -> Vec<(usize, Option<usize>, String)> {
45 pattern
46 .find_iter(source)
47 .map(|found| {
48 let line_number = source[..found.start()].matches('\n').count() + 1;
49 let from_match = &source[found.start()..];
50 let allowed = SCAN_ALLOWLIST.iter().position(|(allowed_file, snippet)| {
51 *allowed_file == relative && from_match.starts_with(snippet)
52 });
53 let line_end = from_match.find('\n').unwrap_or(from_match.len());
54 (
55 line_number,
56 allowed,
57 from_match[..line_end].trim().to_owned(),
58 )
59 })
60 .collect()
61}
62
63fn offset_pattern() -> Regex {
64 Regex::new(r"\.(top|right|bottom|left|inset)\(\s*(px\(\s*)?-").expect("pattern")
65}
66
67#[test]
68fn matcher_catches_wrapped_offsets() {
69 let source = "let a = 1;\nlet b = div()\n .top(\n px(-4.))\n .left(px(2.));\n";
70 let found = negative_offsets(&offset_pattern(), source, "views/other.rs");
71 assert_eq!(found, [(3, None, ".top(".to_owned())]);
72}
73
74#[test]
75fn matcher_matches_allowlist_from_match_start() {
76 let source = "x\n .bottom(px(-1.))\n";
77 let found = negative_offsets(&offset_pattern(), source, "views/conversation.rs");
78 assert_eq!(found, [(2, Some(1), ".bottom(px(-1.))".to_owned())]);
79}
80
81#[test]
82fn negative_offsets_go_through_corner_badge() {
83 let pattern = offset_pattern();
84 let mut matched_allowlist = HashSet::new();
85 let mut violations = Vec::new();
86 for root in source_roots() {
87 let mut files = Vec::new();
88 source_files(&root, &mut files);
89 for file in files {
90 let relative = file
91 .strip_prefix(&root)
92 .expect("inside src")
93 .to_string_lossy()
94 .replace('\\', "/");
95 if relative == WIDGETS_FILE || relative == "layout_guard.rs" {
96 continue;
97 }
98 let source = fs::read_to_string(&file).expect("read source file");
99 for (line_number, position, text) in negative_offsets(&pattern, &source, &relative) {
100 match position {
101 Some(position) => {
102 matched_allowlist.insert(position);
103 }
104 None => violations.push(format!(
105 "{relative}:{line_number}: negative absolute offset, use widgets::corner_badge: {text}"
106 )),
107 }
108 }
109 }
110 }
111 let stale: Vec<String> = SCAN_ALLOWLIST
112 .iter()
113 .enumerate()
114 .filter(|(position, _)| !matched_allowlist.contains(position))
115 .map(|(_, (file, snippet))| format!("stale allowlist entry, remove it: {file} {snippet}"))
116 .collect();
117 assert!(
118 violations.is_empty() && stale.is_empty(),
119 "{}",
120 violations
121 .into_iter()
122 .chain(stale)
123 .collect::<Vec<_>>()
124 .join("\n")
125 );
126}
127
128#[test]
129fn hover_styles_never_toggle_display() {
130 let toggle =
131 Regex::new(r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)").unwrap();
132 let mut files = Vec::new();
133 for root in source_roots() {
134 source_files(&root, &mut files);
135 }
136 let offenders: Vec<String> = files
137 .iter()
138 .flat_map(|path| {
139 let source = fs::read_to_string(path).unwrap();
140 source
141 .lines()
142 .enumerate()
143 .filter(|(_, line)| toggle.is_match(line))
144 .map(|(index, _)| format!("{}:{}", path.display(), index + 1))
145 .collect::<Vec<_>>()
146 })
147 .collect();
148 assert!(
149 offenders.is_empty(),
150 "hover styles must toggle visible()/invisible(), not display (gpui panics \"must call prepaint before paint\"): {offenders:?}"
151 );
152}
153
154mod frames {
155 use std::collections::HashSet;
156 use std::sync::Arc;
157 use std::time::Duration;
158
159 use 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_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_new_message_never_opens_a_gap_between_the_rows_above(cx: &mut TestAppContext) {
1446 const GAP_CHAT: &str = "demo-chat-priya";
1447 let (handle, app) = mount(cx);
1448 let mut visual = VisualTestContext::from_window(handle, cx);
1449 visual.simulate_resize(size(px(1280.), px(800.)));
1450 visual.update(|_, cx| {
1451 app.update(cx, |state, cx| {
1452 state.select(Selection::Chat(GAP_CHAT.to_owned()), cx)
1453 })
1454 });
1455 collect(&mut visual, Some(TIMELINE_TAG));
1456 collect(&mut visual, None);
1457 let bubble_positions = |visual: &mut VisualTestContext| -> Vec<(usize, f32, f32)> {
1458 BUBBLE_TAGS
1459 .iter()
1460 .enumerate()
1461 .filter_map(|(index, tag)| {
1462 visual
1463 .debug_bounds(tag)
1464 .map(|bounds| (index, f32::from(bounds.top()), f32::from(bounds.bottom())))
1465 })
1466 .collect()
1467 };
1468 let before = bubble_positions(&mut visual);
1469 visual.update(|_, cx| {
1470 app.update(cx, |state, cx| {
1471 let record = store::MessageRecord {
1472 conversation_id: GAP_CHAT.to_owned(),
1473 message_id: "guard-new".to_owned(),
1474 sender_id: Some(demo::PRIYA_ID.to_owned()),
1475 sender_name: Some("Priya Nair".to_owned()),
1476 created_at: chrono::Utc::now().max(demo::at(0, 10, 48)),
1477 body_html: "<p>Fresh message</p>".to_owned(),
1478 links_json: "[]".to_owned(),
1479 attachments_json: "[]".to_owned(),
1480 reactions_json: "[]".to_owned(),
1481 mentions_json: "[]".to_owned(),
1482 ..Default::default()
1483 };
1484 state
1485 .store
1486 .upsert_messages(&[record])
1487 .expect("store message");
1488 state.apply(
1489 crate::backend::BackendEvent::Core(teams_core::CoreEvent::MessagesChanged {
1490 conversation_id: GAP_CHAT.to_owned(),
1491 }),
1492 cx,
1493 );
1494 })
1495 });
1496 let mut frames = Vec::new();
1497 for _ in 0..12 {
1498 visual.executor().advance_clock(Duration::from_millis(16));
1499 visual.run_until_parked();
1500 visual.update(|window, cx| window.render_frame(cx));
1501 frames.push(bubble_positions(&mut visual));
1502 }
1503 let spacing = |positions: &[(usize, f32, f32)]| -> Vec<(usize, f32)> {
1504 positions
1505 .windows(2)
1506 .map(|pair| (pair[1].0, pair[1].1 - pair[0].2))
1507 .collect()
1508 };
1509 let resting = spacing(&before);
1510 let found: Vec<String> = frames
1511 .iter()
1512 .enumerate()
1513 .flat_map(|(frame, positions)| {
1514 let resting = resting.clone();
1515 spacing(positions)
1516 .into_iter()
1517 .filter_map(move |(index, gap)| {
1518 let expected = resting.iter().find(|(known, _)| *known == index)?.1;
1519 ((gap - expected).abs() > TOLERANCE).then(|| {
1520 format!(
1521 "frame {frame}: gap above bubble {index} is {gap}, was {expected}"
1522 )
1523 })
1524 })
1525 })
1526 .collect();
1527 assert!(found.is_empty(), "{}", found.join("\n"));
1528 }
1529
1530 fn inside_horizontally(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
1531 let tolerance = px(TOLERANCE);
1532 inner.left() >= outer.left() - tolerance && inner.right() <= outer.right() + tolerance
1533 }
1534
1535 fn scroll_sidebar(visual: &mut VisualTestContext, delta: f32) {
1536 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1537 visual.simulate_event(ScrollWheelEvent {
1538 position: sidebar.center(),
1539 delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1540 ..Default::default()
1541 });
1542 }
1543
1544 #[gpui_kit::test]
1545 fn chat_list_line_shows_only_while_scrolled(cx: &mut TestAppContext) {
1546 let (handle, _) = mount(cx);
1547 let mut visual = VisualTestContext::from_window(handle, cx);
1548 for (width, height) in SIZES {
1549 visual.simulate_resize(size(px(width), px(height)));
1550 let window = Bounds {
1551 origin: point(px(0.), px(0.)),
1552 size: size(px(width), px(height)),
1553 };
1554 collect(&mut visual, None);
1555 scroll_sidebar(&mut visual, 100_000.);
1556 let tags = collect(&mut visual, None);
1557 assert!(
1558 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1559 "chat list at its top must not show the line at {width}x{height}"
1560 );
1561 scroll_sidebar(&mut visual, -120.);
1562 let scrolled = collect(&mut visual, Some(SIDEBAR_SCROLL_DIVIDER));
1563 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1564 let line = visual
1565 .debug_bounds(SIDEBAR_SCROLL_DIVIDER)
1566 .expect("scrolled chat list shows the line");
1567 assert!(
1568 line.top() > sidebar.top() + px(TOLERANCE),
1569 "the line sits under the Chats header, not on the island edge: {} in {}",
1570 describe(line),
1571 describe(sidebar)
1572 );
1573 let found: Vec<String> = violations(&scrolled, window, &[SIDEBAR_SCROLL_DIVIDER])
1574 .into_iter()
1575 .chain(violations(&tags, window, &[]))
1576 .map(|(key, message)| format!("chat-list@{width}x{height}:{key}: {message}"))
1577 .collect();
1578 assert!(found.is_empty(), "{}", found.join("\n"));
1579 scroll_sidebar(&mut visual, 100_000.);
1580 collect(&mut visual, None);
1581 assert!(
1582 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1583 "the line goes away once the chat list is back at its top"
1584 );
1585 }
1586 }
1587
1588 #[gpui_kit::test]
1589 fn header_tabs_sit_above_the_header_line(cx: &mut TestAppContext) {
1590 let (handle, state) = mount(cx);
1591 let mut visual = VisualTestContext::from_window(handle, cx);
1592 for (width, height) in SIZES {
1593 visual.simulate_resize(size(px(width), px(height)));
1594 let window = Bounds {
1595 origin: point(px(0.), px(0.)),
1596 size: size(px(width), px(height)),
1597 };
1598 visual.update(|_, cx| {
1599 state.update(cx, |state, cx| {
1600 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1601 })
1602 });
1603 let tags = collect(&mut visual, Some(RECAP_TAB));
1604 let main = visual.debug_bounds(MAIN).expect("main island rendered");
1605 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1606 let line = visual
1607 .debug_bounds(HEADER_DIVIDER)
1608 .expect("the header line is always shown");
1609 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
1610 assert!(
1611 tab.top() >= main.top() && near(tab.bottom(), line.top()),
1612 "tab {} must sit in the top bar above the line {}",
1613 describe(tab),
1614 describe(line)
1615 );
1616 let found: Vec<String> = violations(&tags, window, &[HEADER_DIVIDER, RECAP_TAB])
1617 .into_iter()
1618 .map(|(key, message)| format!("header@{width}x{height}:{key}: {message}"))
1619 .collect();
1620 assert!(found.is_empty(), "{}", found.join("\n"));
1621 }
1622 }
1623
1624 #[gpui_kit::test]
1625 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1626 let (handle, state) = mount(cx);
1627 let mut visual = VisualTestContext::from_window(handle, cx);
1628 for (width, height) in SIZES {
1629 visual.simulate_resize(size(px(width), px(height)));
1630 let window = Bounds {
1631 origin: point(px(0.), px(0.)),
1632 size: size(px(width), px(height)),
1633 };
1634 visual.update(|_, cx| {
1635 state.update(cx, |state, cx| {
1636 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1637 })
1638 });
1639 collect(&mut visual, Some(RECAP_TAB));
1640 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1641 visual.simulate_click(tab.center(), Default::default());
1642 let tags = collect(&mut visual, Some(RECAP_REGION));
1643 let mut expected = GUARDED.to_vec();
1644 expected.extend([RECAP_TAB, RECAP_REGION]);
1645 let found: Vec<String> = violations(&tags, window, &expected)
1646 .into_iter()
1647 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1648 .collect();
1649 assert!(found.is_empty(), "{}", found.join("\n"));
1650 }
1651 }
1652
1653 // Devices opens a camera preview; the effects worker schedules onto the
1654 // deterministic test scheduler and trips "Your test is not deterministic".
1655 #[gpui_kit::test]
1656 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1657 let sections: Vec<_> = SETTINGS_SECTIONS
1658 .into_iter()
1659 .filter(|section| *section != SettingsSection::Devices)
1660 .collect();
1661 check_settings_dialog(cx, &sections);
1662 }
1663
1664 #[gpui_kit::test]
1665 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1666 crate::theme::set_thread_scheme(Some("teams"));
1667 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1668 crate::theme::set_thread_scheme(None);
1669 }
1670
1671 #[gpui_kit::test]
1672 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1673 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1674 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1675 crate::theme::set_thread_shade(None);
1676 }
1677
1678 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1679 let (handle, state) = mount_with(cx, true);
1680 let mut visual = VisualTestContext::from_window(handle, cx);
1681 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1682 visual.simulate_resize(size(px(width), px(height)));
1683 let window = Bounds {
1684 origin: point(px(0.), px(0.)),
1685 size: size(px(width), px(height)),
1686 };
1687 let inset = metrics(width, height).inset;
1688 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1689 for &section in sections {
1690 visual
1691 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1692 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1693 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1694 .into_iter()
1695 .filter(|(key, _)| key.starts_with("settings"))
1696 .chain(inset_violations(&tags, INSET_RULES))
1697 .collect();
1698 if label_sizes {
1699 found.extend(nav_label_violations(&mut visual));
1700 }
1701 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1702 .iter()
1703 .any(|(exempt, _)| *exempt == section);
1704 if !scrolled_exempt {
1705 found.extend(scrolled_inset_violation(&mut visual));
1706 }
1707 let found: Vec<String> = found
1708 .into_iter()
1709 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1710 .collect();
1711 assert!(found.is_empty(), "{}", found.join("\n"));
1712 let dialog = visual
1713 .debug_bounds(SETTINGS_TAGS[0])
1714 .expect("settings dialog");
1715 let edges = [
1716 f32::from(dialog.left()),
1717 f32::from(dialog.top()),
1718 width - f32::from(dialog.right()),
1719 height - f32::from(dialog.bottom()),
1720 ];
1721 assert!(
1722 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1723 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1724 );
1725 }
1726 }
1727 }
1728
1729 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1730
1731 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1732 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1733 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1734 };
1735 let mut found = Vec::new();
1736 for section in SETTINGS_SECTIONS {
1737 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1738 let item_path: &'static str = if section == SettingsSection::About {
1739 SETTINGS_NAV_ABOUT
1740 } else if section == SettingsSection::Help {
1741 SETTINGS_NAV_HELP
1742 } else {
1743 Box::leak(item_selector(section).into_boxed_str())
1744 };
1745 let (Some(label_bounds), Some(item)) = (
1746 visual.debug_bounds(label_path),
1747 visual.debug_bounds(item_path),
1748 ) else {
1749 if section != SettingsSection::Agents {
1750 found.push((label_path.to_owned(), "not rendered".to_owned()));
1751 }
1752 continue;
1753 };
1754 let text = label(section);
1755 let text_width = visual.update(|window, _| {
1756 let run = window.text_style().to_run(text.len());
1757 f32::from(
1758 window
1759 .text_system()
1760 .shape_line(text.clone().into(), px(NAV_LABEL_SIZE), &[run], None)
1761 .width,
1762 )
1763 });
1764 let label_width = f32::from(label_bounds.size.width);
1765 let label_height = f32::from(label_bounds.size.height);
1766 if text_width > label_width + TOLERANCE
1767 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1768 {
1769 found.push((
1770 label_path.to_owned(),
1771 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1772 ));
1773 }
1774 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1775 inner.left() < outer.left() - px(TOLERANCE)
1776 || inner.right() > outer.right() + px(TOLERANCE)
1777 || inner.top() < outer.top() - px(TOLERANCE)
1778 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1779 };
1780 if outside(label_bounds, item) {
1781 found.push((
1782 label_path.to_owned(),
1783 format!("label {label_bounds:?} outside item {item:?}"),
1784 ));
1785 }
1786 if item.left() < nav.left() || item.right() > nav.right() {
1787 found.push((
1788 item_path.to_owned(),
1789 format!("item {item:?} outside nav {nav:?}"),
1790 ));
1791 }
1792 }
1793 found
1794 }
1795
1796 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1797 let body = visual.debug_bounds(SETTINGS_BODY)?;
1798 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1799 if content.bottom() <= body.bottom() {
1800 return None;
1801 }
1802 visual.simulate_event(ScrollWheelEvent {
1803 position: body.center(),
1804 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1805 ..Default::default()
1806 });
1807 collect(visual, None);
1808 let body = visual.debug_bounds(SETTINGS_BODY)?;
1809 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1810 inset_violation(&SCROLLED_INSET_RULE, body, content)
1811 }
1812
1813 #[gpui_kit::test]
1814 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1815 let (handle, state) = mount(cx);
1816 let mut visual = VisualTestContext::from_window(handle, cx);
1817 for (width, height) in SIZES {
1818 visual.simulate_resize(size(px(width), px(height)));
1819 let window = Bounds {
1820 origin: point(px(0.), px(0.)),
1821 size: size(px(width), px(height)),
1822 };
1823 visual.update(|_, cx| {
1824 state.update(cx, |state, cx| {
1825 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1826 })
1827 });
1828 collect(&mut visual, Some(MEMBERS_BUTTON));
1829 let button = visual
1830 .debug_bounds(MEMBERS_BUTTON)
1831 .expect("members button rendered");
1832 visual.simulate_click(button.center(), Default::default());
1833 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1834 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1835 .into_iter()
1836 .filter(|(key, _)| key.starts_with("chat-members"))
1837 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1838 .collect();
1839 visual.simulate_keystrokes("escape");
1840 visual.run_until_parked();
1841 assert!(found.is_empty(), "{}", found.join("\n"));
1842 }
1843 }
1844
1845 #[gpui_kit::test]
1846 fn a_long_members_list_scrolls_to_its_last_person(cx: &mut TestAppContext) {
1847 const PEOPLE: usize = 12;
1848 let (handle, state) = mount(cx);
1849 let mut visual = VisualTestContext::from_window(handle, cx);
1850 visual.simulate_resize(size(px(1280.), px(800.)));
1851 visual.update(|_, cx| {
1852 state.update(cx, |state, cx| {
1853 if let Some(chat) = state
1854 .sidebar
1855 .chats
1856 .iter_mut()
1857 .find(|chat| chat.id == MEMBERS_CHAT)
1858 {
1859 chat.members = (0..PEOPLE)
1860 .map(|index| store::MemberRecord {
1861 user_id: Some(format!("guard-person-{index}")),
1862 display_name: format!("Person {index}"),
1863 })
1864 .collect();
1865 }
1866 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1867 })
1868 });
1869 collect(&mut visual, Some(MEMBERS_BUTTON));
1870 let button = visual
1871 .debug_bounds(MEMBERS_BUTTON)
1872 .expect("members button rendered");
1873 visual.simulate_click(button.center(), Default::default());
1874 collect(&mut visual, Some("chat-members-popup/list"));
1875 let list = visual
1876 .debug_bounds("chat-members-popup/list")
1877 .expect("list");
1878 let last_row = "chat-members-popup/row-11";
1879 visual.simulate_event(ScrollWheelEvent {
1880 position: list.center(),
1881 delta: ScrollDelta::Pixels(point(px(0.), px(-2_000.))),
1882 ..Default::default()
1883 });
1884 collect(&mut visual, None);
1885 let list = visual
1886 .debug_bounds("chat-members-popup/list")
1887 .expect("list");
1888 let last = visual.debug_bounds(last_row).expect("last person rendered");
1889 assert!(
1890 last.bottom() <= list.bottom() + px(0.5),
1891 "last person {last:?} below the list {list:?}"
1892 );
1893 }
1894
1895 #[gpui_kit::test]
1896 fn the_group_name_field_keeps_typed_text_across_frames(cx: &mut TestAppContext) {
1897 let (handle, state) = mount(cx);
1898 let mut visual = VisualTestContext::from_window(handle, cx);
1899 visual.update(|_, cx| {
1900 state.update(cx, |state, cx| {
1901 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1902 })
1903 });
1904 collect(&mut visual, Some(GROUP_NAME_BUTTON));
1905 let button = visual
1906 .debug_bounds(GROUP_NAME_BUTTON)
1907 .expect("group name button rendered");
1908 visual.simulate_click(button.center(), Default::default());
1909 collect(&mut visual, Some(GROUP_NAME_FORM));
1910 assert!(
1911 visual.debug_bounds(GROUP_NAME_FORM).is_some(),
1912 "group name form open"
1913 );
1914 visual.simulate_keystrokes("backspace x space y enter");
1915 visual.run_until_parked();
1916 let title = visual.update(|_, cx| {
1917 state
1918 .read(cx)
1919 .sidebar
1920 .chats
1921 .iter()
1922 .find(|chat| chat.id == MEMBERS_CHAT)
1923 .map(|chat| chat.title.clone())
1924 });
1925 assert_eq!(title.as_deref(), Some("Release planninx y"));
1926 }
1927
1928 const FORWARD_CHAT: &str = "demo-chat-release";
1929 const FORWARD_FOOTER_TAGS: [&str; 4] = [
1930 FORWARD_FOOTER_TAG,
1931 FORWARD_FOOTER_BAR_TAG,
1932 FORWARD_FOOTER_COUNT_TAG,
1933 FORWARD_FOOTER_NEXT_TAG,
1934 ];
1935 const FORWARD_DIALOG_PADDING: f32 = 16.;
1936 const FORWARD_BAR_PADDING: f32 = 8.;
1937 const FORWARD_ROWS_SCANNED: usize = 80;
1938
1939 fn forward_message_ids(
1940 state: &Entity<AppState>,
1941 visual: &mut VisualTestContext,
1942 ) -> Vec<String> {
1943 visual.update(|_, cx| {
1944 let mut records = state
1945 .read(cx)
1946 .store
1947 .messages(FORWARD_CHAT, None, 50)
1948 .expect("demo messages");
1949 records.retain(|record| !record.deleted);
1950 records.sort_by_key(|record| record.created_at);
1951 records
1952 .iter()
1953 .rev()
1954 .take(2)
1955 .map(|record| record.message_id.clone())
1956 .collect()
1957 })
1958 }
1959
1960 #[gpui_kit::test]
1961 fn forward_selection_footer_checks_and_dialog_keep_their_insets(cx: &mut TestAppContext) {
1962 let (handle, state) = mount(cx);
1963 let mut visual = VisualTestContext::from_window(handle, cx);
1964 for (width, height) in SIZES {
1965 visual.simulate_resize(size(px(width), px(height)));
1966 let window = Bounds {
1967 origin: point(px(0.), px(0.)),
1968 size: size(px(width), px(height)),
1969 };
1970 visual.update(|_, cx| {
1971 state.update(cx, |state, cx| {
1972 state.select(Selection::Chat(FORWARD_CHAT.to_owned()), cx)
1973 })
1974 });
1975 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1976 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
1977 let ids = forward_message_ids(&state, &mut visual);
1978 visual.update(|_, cx| {
1979 state.update(cx, |state, cx| {
1980 state.start_forward_selection(FORWARD_CHAT, &ids[0], cx);
1981 state.toggle_forward_selected(&ids[1], cx);
1982 })
1983 });
1984 collect(&mut visual, Some(FORWARD_FOOTER_NEXT_TAG));
1985 assert!(
1986 visual.debug_bounds(COMPOSER_BOX_TAG).is_none(),
1987 "the footer replaces the composer"
1988 );
1989 let tags: Vec<Tag> = FORWARD_FOOTER_TAGS
1990 .iter()
1991 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1992 .collect();
1993 let mut found: Vec<String> = violations(&tags, window, &FORWARD_FOOTER_TAGS)
1994 .into_iter()
1995 .map(|(key, message)| format!("forward@{width}x{height}:{key}: {message}"))
1996 .collect();
1997 let main = visual.debug_bounds(MAIN).expect("main island");
1998 let bar = visual.debug_bounds(FORWARD_FOOTER_BAR_TAG).expect("bar");
1999 let next = visual.debug_bounds(FORWARD_FOOTER_NEXT_TAG).expect("next");
2000 if (f32::from(bar.left() - composer.left())).abs() > TOLERANCE
2001 || (f32::from(bar.right() - composer.right())).abs() > TOLERANCE
2002 {
2003 found.push(format!(
2004 "forward@{width}x{height}: bar {} not on the composer edges {}",
2005 describe(bar),
2006 describe(composer)
2007 ));
2008 }
2009 for edge in [Edge::Top, Edge::Right, Edge::Bottom] {
2010 let gap = inset(bar, next, edge);
2011 if (gap - FORWARD_BAR_PADDING).abs() > TOLERANCE {
2012 found.push(format!(
2013 "forward@{width}x{height}: next button {edge:?} inset {gap} != {FORWARD_BAR_PADDING}"
2014 ));
2015 }
2016 }
2017 let checks: Vec<Bounds<Pixels>> = (0..FORWARD_ROWS_SCANNED)
2018 .filter_map(|index| {
2019 visual.debug_bounds(Box::leak(select_box_selector(index).into_boxed_str()))
2020 })
2021 .filter(|check| contains(main, *check))
2022 .collect();
2023 if checks.is_empty() {
2024 found.push(format!("forward@{width}x{height}: no checkbox rendered"));
2025 }
2026 let expected_left = ROW_PADDING + runway_margin(f32::from(main.size.width));
2027 for check in &checks {
2028 let left = inset(main, *check, Edge::Left);
2029 if (left - expected_left).abs() > TOLERANCE {
2030 found.push(format!(
2031 "forward@{width}x{height}: checkbox {} starts {left} from the island, not {expected_left}",
2032 describe(*check)
2033 ));
2034 }
2035 }
2036 visual.simulate_click(next.center(), Default::default());
2037 collect(&mut visual, Some(FORWARD_PREVIEW_TAG));
2038 let card = visual.debug_bounds(FORWARD_CARD_TAG).expect("dialog card");
2039 let preview = visual.debug_bounds(FORWARD_PREVIEW_TAG).expect("preview");
2040 if !contains(window, card) || !contains(card, preview) {
2041 found.push(format!(
2042 "forward@{width}x{height}: dialog {} or preview {} clipped",
2043 describe(card),
2044 describe(preview)
2045 ));
2046 }
2047 let (left, right) = (
2048 inset(card, preview, Edge::Left),
2049 inset(card, preview, Edge::Right),
2050 );
2051 if (left - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
2052 || (right - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
2053 {
2054 found.push(format!(
2055 "forward@{width}x{height}: preview insets {left}/{right} != {FORWARD_DIALOG_PADDING}"
2056 ));
2057 }
2058 visual.simulate_keystrokes("escape");
2059 collect(&mut visual, None);
2060 assert!(visual.debug_bounds(FORWARD_CARD_TAG).is_none());
2061 assert!(
2062 visual.debug_bounds(FORWARD_FOOTER_TAG).is_some(),
2063 "closing the dialog keeps the selection"
2064 );
2065 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_forward_selection(cx)));
2066 collect(&mut visual, Some(COMPOSER_BOX_TAG));
2067 assert!(visual.debug_bounds(FORWARD_FOOTER_TAG).is_none());
2068 assert!(found.is_empty(), "{}", found.join("\n"));
2069 }
2070 }
2071
2072 const MENU_ITEMS_SCANNED: usize = 40;
2073 const MENU_CHAT: &str = "demo-chat-release";
2074 const THEME_SELECT: &str = "settings-theme";
2075 const CALENDAR_DEFAULT_VIEW_SELECT: &str = "settings-calendar-default-view";
2076
2077 struct MenuRow {
2078 index: usize,
2079 item: Bounds<Pixels>,
2080 icon: Option<Bounds<Pixels>>,
2081 label: Option<Bounds<Pixels>>,
2082 }
2083
2084 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
2085 (0..MENU_ITEMS_SCANNED)
2086 .filter_map(|index| {
2087 let item =
2088 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
2089 Some(MenuRow {
2090 index,
2091 item,
2092 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
2093 label: visual
2094 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
2095 })
2096 })
2097 .collect()
2098 }
2099
2100 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
2101 let mut found = Vec::new();
2102 for row in rows {
2103 let Some(icon) = row.icon else {
2104 continue;
2105 };
2106 let key = format!("{MENU}/item-{}", row.index);
2107 if let Some(label) = row.label {
2108 let gap = f32::from(label.left() - icon.right());
2109 if (gap - expected_gap).abs() > TOLERANCE {
2110 found.push((
2111 format!("{key}:icon-gap"),
2112 format!(
2113 "icon {} to label {} is {gap} px, expected {expected_gap}",
2114 describe(icon),
2115 describe(label)
2116 ),
2117 ));
2118 }
2119 }
2120 let offset = f32::from(icon.center().y - row.item.center().y);
2121 if offset.abs() > TOLERANCE {
2122 found.push((
2123 format!("{key}:icon-off-centre"),
2124 format!(
2125 "icon {} sits {offset} px off the centre of item {}",
2126 describe(icon),
2127 describe(row.item)
2128 ),
2129 ));
2130 }
2131 }
2132 found
2133 }
2134
2135 fn listbox_violations(
2136 trigger: Bounds<Pixels>,
2137 menu: Bounds<Pixels>,
2138 items: Bounds<Pixels>,
2139 rows: &[MenuRow],
2140 ) -> Vec<(String, String)> {
2141 let mut found = Vec::new();
2142 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
2143 if !near(f32::from(menu.left() - trigger.left()), 0.) {
2144 found.push((
2145 format!("{MENU}:not-aligned-to-trigger"),
2146 format!(
2147 "list {} must start at the trigger's left edge {}",
2148 describe(menu),
2149 describe(trigger)
2150 ),
2151 ));
2152 }
2153 if !near(
2154 f32::from(menu.top() - trigger.bottom()),
2155 f32::from(DROPDOWN_OFFSET),
2156 ) {
2157 found.push((
2158 format!("{MENU}:trigger-offset"),
2159 format!(
2160 "list {} must open {} px below the trigger {}",
2161 describe(menu),
2162 f32::from(DROPDOWN_OFFSET),
2163 describe(trigger)
2164 ),
2165 ));
2166 }
2167 if menu.size.width < trigger.size.width - px(TOLERANCE) {
2168 found.push((
2169 format!("{MENU}:narrower-than-trigger"),
2170 format!(
2171 "list {} is narrower than the trigger {}",
2172 describe(menu),
2173 describe(trigger)
2174 ),
2175 ));
2176 }
2177 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
2178 let top = f32::from(first.item.top() - items.top());
2179 let bottom = f32::from(items.bottom() - last.item.bottom());
2180 let padding = f32::from(MENU_LIST_PADDING);
2181 if !near(top, padding) || !near(bottom, padding) {
2182 found.push((
2183 format!("{MENU}:uneven-padding"),
2184 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
2185 ));
2186 }
2187 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
2188 match first.icon {
2189 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
2190 check => found.push((
2191 format!("{MENU}:check-inset"),
2192 format!(
2193 "check column {check:?} must start {expected_inset} px inside the list {}",
2194 describe(menu)
2195 ),
2196 )),
2197 }
2198 }
2199 found
2200 }
2201
2202 #[test]
2203 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
2204 let row =
2205 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
2206 index,
2207 item: rectangle(4., item_top, 120., 32.),
2208 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
2209 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
2210 };
2211 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
2212 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
2213 .into_iter()
2214 .map(|(key, _)| key)
2215 .collect();
2216 assert_eq!(
2217 keys,
2218 [
2219 "popup-menu/item-1:icon-gap",
2220 "popup-menu/item-1:icon-off-centre"
2221 ]
2222 );
2223
2224 let trigger = rectangle(100., 50., 216., 32.);
2225 let option = |index: usize, top: f32| MenuRow {
2226 index,
2227 item: rectangle(104., top, 208., 32.),
2228 icon: Some(rectangle(110., top + 8., 16., 16.)),
2229 label: Some(rectangle(132., top + 6., 80., 20.)),
2230 };
2231 let aligned = [option(0, 88.), option(1, 122.)];
2232 let menu = rectangle(100., 84., 216., 74.);
2233 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
2234 let shifted = rectangle(96., 90., 200., 80.);
2235 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
2236 .into_iter()
2237 .map(|(key, _)| key)
2238 .collect();
2239 assert_eq!(
2240 keys,
2241 [
2242 "popup-menu:not-aligned-to-trigger",
2243 "popup-menu:trigger-offset",
2244 "popup-menu:narrower-than-trigger",
2245 "popup-menu:uneven-padding",
2246 "popup-menu:check-inset",
2247 ]
2248 );
2249 }
2250
2251 #[gpui_kit::test]
2252 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
2253 let (handle, _) = mount(cx);
2254 let mut visual = VisualTestContext::from_window(handle, cx);
2255 visual.simulate_resize(size(px(1280.), px(800.)));
2256 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
2257 collect(&mut visual, Some(chat_row));
2258 let mut found = Vec::new();
2259 let own_status = visual
2260 .debug_bounds(OWN_STATUS)
2261 .expect("own status button rendered");
2262 visual.simulate_click(own_status.center(), Default::default());
2263 collect(&mut visual, Some(MENU));
2264 let status_rows = menu_rows(&mut visual);
2265 assert!(
2266 status_rows.iter().any(|row| row.icon.is_some()),
2267 "status menu shows icons"
2268 );
2269 found.extend(menu_row_violations(
2270 &status_rows,
2271 f32::from(MENU_ICON_LABEL_GAP),
2272 ));
2273 visual.simulate_keystrokes("escape");
2274 collect(&mut visual, None);
2275 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
2276 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
2277 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
2278 collect(&mut visual, Some(MENU));
2279 let chat_rows = menu_rows(&mut visual);
2280 assert!(
2281 chat_rows.iter().any(|row| row.icon.is_some()),
2282 "chat menu shows icons"
2283 );
2284 found.extend(menu_row_violations(
2285 &chat_rows,
2286 f32::from(MENU_ICON_LABEL_GAP),
2287 ));
2288 let found: Vec<String> = found
2289 .into_iter()
2290 .map(|(key, message)| format!("{key}: {message}"))
2291 .collect();
2292 assert!(found.is_empty(), "{}", found.join("\n"));
2293 }
2294
2295 #[gpui_kit::test]
2296 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2297 select_list_lines_up(cx, SettingsSection::Appearance, THEME_SELECT);
2298 }
2299
2300 #[gpui_kit::test]
2301 fn calendar_default_view_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2302 select_list_lines_up(cx, SettingsSection::Calendar, CALENDAR_DEFAULT_VIEW_SELECT);
2303 }
2304
2305 fn select_list_lines_up(cx: &mut TestAppContext, section: SettingsSection, id: &str) {
2306 let (handle, state) = mount(cx);
2307 let mut visual = VisualTestContext::from_window(handle, cx);
2308 visual.simulate_resize(size(px(1280.), px(800.)));
2309 visual.update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
2310 let select: &'static str = Box::leak(select_selector(id).into_boxed_str());
2311 collect(&mut visual, Some(select));
2312 let trigger = visual.debug_bounds(select).expect("select rendered");
2313 visual.simulate_click(trigger.center(), Default::default());
2314 collect(&mut visual, Some(MENU));
2315 let menu = visual.debug_bounds(MENU).expect("list rendered");
2316 let items = visual
2317 .debug_bounds(ITEMS_SELECTOR)
2318 .expect("list items rendered");
2319 let rows = menu_rows(&mut visual);
2320 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
2321 .into_iter()
2322 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
2323 .map(|(key, message)| format!("{key}: {message}"))
2324 .collect();
2325 assert!(found.is_empty(), "{}", found.join("\n"));
2326 }
2327
2328 const BADGE_SAMPLES: [(u32, bool); 5] =
2329 [(1, false), (42, false), (120, false), (7, true), (15, true)];
2330
2331 struct BadgeSamples;
2332
2333 impl gpui_kit::Render for BadgeSamples {
2334 fn render(
2335 &mut self,
2336 _: &mut gpui_kit::Window,
2337 _: &mut gpui_kit::Context<Self>,
2338 ) -> impl gpui_kit::IntoElement {
2339 use gpui_kit::{ParentElement as _, Styled as _};
2340 gpui_kit::div()
2341 .flex()
2342 .gap(px(12.))
2343 .p(px(12.))
2344 .children(BADGE_SAMPLES.map(|(count, rail)| {
2345 if rail {
2346 badge_pill(
2347 count,
2348 RAIL_BADGE,
2349 crate::theme::accent(),
2350 crate::theme::on_accent(),
2351 )
2352 } else {
2353 count_badge(count, false)
2354 }
2355 }))
2356 }
2357 }
2358
2359 fn badge_violation(
2360 text: &str,
2361 pill: Bounds<Pixels>,
2362 label: Bounds<Pixels>,
2363 ink_offset: (f32, f32),
2364 ) -> Option<(String, String)> {
2365 let ink_x = f32::from(label.center().x) + ink_offset.0;
2366 let ink_y = f32::from(label.center().y) + ink_offset.1;
2367 let off_x = ink_x - f32::from(pill.center().x);
2368 let off_y = ink_y - f32::from(pill.center().y);
2369 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
2370 (
2371 format!("count-badge/{text}:off-centre"),
2372 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
2373 )
2374 })
2375 }
2376
2377 #[test]
2378 fn badge_rule_flags_off_centre_text() {
2379 let pill = rectangle(0., 0., 18., 18.);
2380 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
2381 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
2382 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
2383 }
2384
2385 #[gpui_kit::test]
2386 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
2387 cx.update(gpui_kit::init);
2388 cx.update(crate::theme::apply);
2389 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
2390 collect(visual, None);
2391 let mut found = Vec::new();
2392 for (count, rail) in BADGE_SAMPLES {
2393 let text = crate::format::badge_text(count);
2394 let pill = visual
2395 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
2396 .expect("badge rendered");
2397 let label = visual
2398 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
2399 .expect("badge text rendered");
2400 let font_size = if rail {
2401 RAIL_BADGE.font_size
2402 } else {
2403 COUNT_BADGE.font_size
2404 };
2405 let offset = visual.update(|window, _| {
2406 let origin = badge_text_origin(window, &text, font_size, pill);
2407 let (ink_centre, cap_height) = badge_ink_centre(window, &text, font_size);
2408 (
2409 f32::from(origin.x) + ink_centre - f32::from(label.center().x),
2410 f32::from(origin.y) - cap_height / 2. - f32::from(label.center().y),
2411 )
2412 });
2413 found.extend(badge_violation(&text, pill, label, offset));
2414 }
2415 let found: Vec<String> = found
2416 .into_iter()
2417 .map(|(key, message)| format!("{key}: {message}"))
2418 .collect();
2419 assert!(found.is_empty(), "{}", found.join("\n"));
2420 }
2421
2422 const PINNED_CHAT: &str = "demo-chat-release";
2423 const PINNED_CHANNEL: &str = "demo-channel-1-1";
2424
2425 #[gpui_kit::test]
2426 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
2427 let (handle, state) = mount(cx);
2428 let mut visual = VisualTestContext::from_window(handle, cx);
2429 let mut found = Vec::new();
2430 for (width, height) in SIZES {
2431 visual.simulate_resize(size(px(width), px(height)));
2432 visual.update(|_, cx| {
2433 state.update(cx, |state, cx| {
2434 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
2435 })
2436 });
2437 collect(&mut visual, Some(PIN_BANNER_TAG));
2438 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
2439 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2440 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2441 let gaps = [
2442 ("top", f32::from(banner.top() - timeline.top())),
2443 ("left", f32::from(banner.left() - timeline.left())),
2444 ("right", f32::from(timeline.right() - banner.right())),
2445 ("below divider", f32::from(banner.top() - divider.bottom())),
2446 ];
2447 let runway = runway_margin(f32::from(timeline.size.width) - 2. * BANNER_INSET);
2448 let sides_ok = gaps[1..3]
2449 .iter()
2450 .all(|(_, gap)| (gap - BANNER_INSET - runway).abs() <= INSET_TOLERANCE);
2451 let vertical_ok = [gaps[0].1, gaps[3].1]
2452 .iter()
2453 .all(|gap| (gap - BANNER_INSET).abs() <= INSET_TOLERANCE);
2454 if !sides_ok || !vertical_ok {
2455 found.push(format!(
2456 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
2457 ));
2458 }
2459 }
2460 assert!(found.is_empty(), "{}", found.join("\n"));
2461 }
2462
2463 #[gpui_kit::test]
2464 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
2465 let (handle, state) = mount(cx);
2466 let mut visual = VisualTestContext::from_window(handle, cx);
2467 visual.simulate_resize(size(px(1280.), px(800.)));
2468 visual.update(|_, cx| {
2469 state.update(cx, |state, cx| {
2470 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2471 })
2472 });
2473 collect(&mut visual, Some(TIMELINE_TAG));
2474 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
2475 }
2476
2477 fn open_channel(cx: &mut TestAppContext, awaited: &'static str) -> VisualTestContext {
2478 let (handle, state) = mount(cx);
2479 let mut visual = VisualTestContext::from_window(handle, cx);
2480 visual.simulate_resize(size(px(1280.), px(800.)));
2481 visual.update(|_, cx| {
2482 state.update(cx, |state, cx| {
2483 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2484 })
2485 });
2486 collect(&mut visual, Some(awaited));
2487 visual
2488 }
2489
2490 #[gpui_kit::test]
2491 fn the_new_post_is_one_card_with_subject_divider_format_bar_and_post_button(
2492 cx: &mut TestAppContext,
2493 ) {
2494 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2495 let open = visual
2496 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2497 .expect("post in channel card");
2498 visual.simulate_click(open.center(), Default::default());
2499 collect(&mut visual, Some(POST_CARD_SEND_TAG));
2500 let mut bounds_of = |path: &'static str| {
2501 visual
2502 .debug_bounds(path)
2503 .unwrap_or_else(|| panic!("{path} missing"))
2504 };
2505 let card = bounds_of(COMPOSER_BOX_TAG);
2506 let header = bounds_of(POST_CARD_HEADER_TAG);
2507 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2508 let divider = bounds_of(POST_CARD_DIVIDER_TAG);
2509 let format_bar = bounds_of(COMPOSER_FORMAT_BAR_TAG);
2510 let footer = bounds_of(POST_CARD_FOOTER_TAG);
2511 let send = bounds_of(POST_CARD_SEND_TAG);
2512 assert!(
2513 visual.debug_bounds(COMPOSER_SEND_TAG).is_none(),
2514 "chat send button shown in a post"
2515 );
2516 assert!(
2517 visual.debug_bounds(COMPOSER_FORMAT_TAG).is_none(),
2518 "format toggle shown although the bar stays open"
2519 );
2520 assert!(header.bottom() <= subject.top() && subject.bottom() <= divider.top());
2521 assert!(divider.bottom() <= format_bar.top() && format_bar.bottom() <= footer.top());
2522 assert!(
2523 f32::from(divider.left() - card.left()).abs() < 1.5
2524 && f32::from(card.right() - divider.right()).abs() < 1.5,
2525 "subject divider {} does not run edge to edge in {}",
2526 describe(divider),
2527 describe(card)
2528 );
2529 let side = f32::from(card.right() - send.right());
2530 let bottom = f32::from(card.bottom() - send.bottom());
2531 assert!(
2532 (side - bottom).abs() < TOLERANCE,
2533 "Post button insets: side {side}, bottom {bottom}"
2534 );
2535 }
2536
2537 #[gpui_kit::test]
2538 fn announcement_mode_puts_the_banner_between_author_and_subheading(cx: &mut TestAppContext) {
2539 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2540 let open = visual
2541 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2542 .expect("post in channel card");
2543 visual.simulate_click(open.center(), Default::default());
2544 collect(&mut visual, Some(POST_ANNOUNCEMENT_TOGGLE_TAG));
2545 let toggle = visual
2546 .debug_bounds(POST_ANNOUNCEMENT_TOGGLE_TAG)
2547 .expect("announcement toggle in the format bar");
2548 let format_bar = visual
2549 .debug_bounds(COMPOSER_FORMAT_BAR_TAG)
2550 .expect("format bar");
2551 assert!(
2552 format_bar.contains(&toggle.center()),
2553 "toggle outside the format bar"
2554 );
2555 visual.simulate_click(toggle.center(), Default::default());
2556 collect(&mut visual, Some(POST_ANNOUNCEMENT_TAG));
2557 let mut bounds_of = |path: &'static str| {
2558 visual
2559 .debug_bounds(path)
2560 .unwrap_or_else(|| panic!("{path} missing"))
2561 };
2562 let card = bounds_of(COMPOSER_BOX_TAG);
2563 let header = bounds_of(POST_CARD_HEADER_TAG);
2564 let banner = bounds_of(POST_ANNOUNCEMENT_TAG);
2565 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2566 assert!(header.bottom() <= banner.top() && banner.bottom() <= subject.top());
2567 let gap = f32::from(subject.top() - banner.bottom());
2568 assert!(gap >= 6., "subheading {gap} px under the banner");
2569 let audience = bounds_of(POST_AUDIENCE_TAG);
2570 assert!(
2571 audience.bottom() <= card.top(),
2572 "audience hint not above the card"
2573 );
2574 let left = f32::from(banner.left() - card.left());
2575 let right = f32::from(card.right() - banner.right());
2576 assert!(
2577 (left - right).abs() < TOLERANCE,
2578 "banner insets: left {left}, right {right}"
2579 );
2580 }
2581
2582 #[gpui_kit::test]
2583 fn channel_posts_start_the_body_at_the_avatar_edge_like_teams(cx: &mut TestAppContext) {
2584 let mut visual = open_channel(cx, POST_FOOTER_AVATAR_TAG);
2585 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
2586 visual
2587 .debug_bounds(path)
2588 .unwrap_or_else(|| panic!("{path} rendered"))
2589 };
2590 let card = bounds_of(&mut visual, POST_CARD_TAG);
2591 let avatar = bounds_of(&mut visual, POST_AVATAR_TAG);
2592 let body = bounds_of(&mut visual, POST_BODY_TAG);
2593 let footer_avatar = bounds_of(&mut visual, POST_FOOTER_AVATAR_TAG);
2594 let side = f32::from(avatar.left() - card.left());
2595 let checks = [
2596 ("body left", f32::from(body.left() - avatar.left())),
2597 (
2598 "footer avatar left",
2599 f32::from(footer_avatar.left() - avatar.left()),
2600 ),
2601 (
2602 "body right inset",
2603 f32::from(card.right() - body.right()) - side,
2604 ),
2605 ];
2606 for (name, gap) in checks {
2607 assert!(
2608 gap.abs() < INSET_TOLERANCE,
2609 "{name} off by {gap}: card {card:?} avatar {avatar:?} body {body:?} footer {footer_avatar:?}"
2610 );
2611 }
2612 }
2613
2614 #[gpui_kit::test]
2615 fn a_code_line_is_one_frame_inside_the_post_body(cx: &mut TestAppContext) {
2616 let mut visual = open_channel(cx, CODE_LINE_TAG);
2617 let code = visual.debug_bounds(CODE_LINE_TAG).expect("code line");
2618 let body = visual.debug_bounds(POST_BODY_TAG).expect("post body");
2619 assert!(
2620 f32::from(code.size.height) > 40.,
2621 "the long code line wraps inside one frame: {code:?}"
2622 );
2623 assert!(
2624 (f32::from(code.left() - body.left())).abs() < INSET_TOLERANCE
2625 && code.right() <= body.right() + px(INSET_TOLERANCE),
2626 "code {code:?} sits inside the body {body:?}"
2627 );
2628 assert!(visual.debug_bounds(CODE_BLOCK_TAG).is_none());
2629 }
2630
2631 #[gpui_kit::test]
2632 fn the_new_post_row_shows_a_scroll_edge_only_while_scrolled(cx: &mut TestAppContext) {
2633 let mut visual = open_channel(cx, POST_CARD_TAG);
2634 assert!(visual.debug_bounds(FEED_EDGE_TAG).is_none());
2635 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2636 visual.simulate_event(ScrollWheelEvent {
2637 position: timeline.center(),
2638 delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
2639 ..Default::default()
2640 });
2641 collect(&mut visual, Some(FEED_EDGE_TAG));
2642 let edge = visual.debug_bounds(FEED_EDGE_TAG).expect("feed edge");
2643 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2644 assert!(
2645 (f32::from(edge.top() - timeline.top())).abs() < INSET_TOLERANCE
2646 && (f32::from(edge.left() - timeline.left())).abs() < INSET_TOLERANCE
2647 && (f32::from(timeline.right() - edge.right())).abs() < INSET_TOLERANCE,
2648 "edge {edge:?} runs across the top of the timeline {timeline:?}"
2649 );
2650 }
2651
2652 #[gpui_kit::test]
2653 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
2654 let (handle, state) = mount(cx);
2655 let mut visual = VisualTestContext::from_window(handle, cx);
2656 visual.simulate_resize(size(px(1280.), px(800.)));
2657 visual.update(|_, cx| {
2658 state.update(cx, |state, cx| {
2659 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2660 })
2661 });
2662 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2663 let button = visual
2664 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2665 .expect("channel details button");
2666 visual.simulate_click(button.center(), Default::default());
2667 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
2668 let pane = visual
2669 .debug_bounds(CHANNEL_DETAILS_TAG)
2670 .expect("details pane");
2671 let main = visual.debug_bounds(MAIN).expect("main island");
2672 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2673 assert!(
2674 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
2675 "pane {pane:?} must end at the main island edge {main:?}"
2676 );
2677 assert!(
2678 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
2679 "pane {pane:?} must start under the header divider {divider:?}"
2680 );
2681 }
2682
2683 #[gpui_kit::test]
2684 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
2685 let (handle, state) = mount(cx);
2686 let mut visual = VisualTestContext::from_window(handle, cx);
2687 visual.simulate_resize(size(px(1280.), px(800.)));
2688 visual.update(|_, cx| {
2689 state.update(cx, |state, cx| {
2690 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2691 })
2692 });
2693 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2694 let button = visual
2695 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2696 .expect("channel details button");
2697 visual.simulate_click(button.center(), Default::default());
2698 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
2699 let pane = visual
2700 .debug_bounds(CHANNEL_DETAILS_TAG)
2701 .expect("details pane");
2702 let pinned = visual
2703 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
2704 .expect("pinned section");
2705 let shared = visual
2706 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
2707 .expect("shared section");
2708 assert!(
2709 pinned.bottom() <= shared.top(),
2710 "pinned {pinned:?} must come before shared {shared:?}"
2711 );
2712 for (name, section) in [("pinned", pinned), ("shared", shared)] {
2713 let left = f32::from(section.left() - pane.left());
2714 let right = f32::from(pane.right() - section.right());
2715 assert!(
2716 (left - right).abs() < INSET_TOLERANCE && left > 0.,
2717 "{name} section insets left {left} right {right} must match"
2718 );
2719 }
2720 }
2721
2722 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
2723 collect(visual, Some(COMPOSER_SEND_TAG));
2724 let mut bounds_of = |path: &'static str| {
2725 visual
2726 .debug_bounds(path)
2727 .unwrap_or_else(|| panic!("{path} rendered"))
2728 };
2729 let composer = bounds_of(COMPOSER_BOX_TAG);
2730 let input = bounds_of(COMPOSER_INPUT_TAG);
2731 let actions = bounds_of(COMPOSER_ACTIONS_TAG);
2732 let send = bounds_of(COMPOSER_SEND_TAG);
2733 [
2734 f32::from(input.left() - composer.left()),
2735 f32::from(actions.top() - composer.top()),
2736 f32::from(composer.bottom() - actions.bottom()),
2737 f32::from(composer.right() - send.right()),
2738 f32::from(send.top() - composer.top()),
2739 f32::from(composer.bottom() - send.bottom()),
2740 ]
2741 }
2742
2743 #[gpui_kit::test]
2744 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
2745 let (handle, _) = mount(cx);
2746 let mut visual = VisualTestContext::from_window(handle, cx);
2747 visual.simulate_resize(size(px(1280.), px(800.)));
2748 let single_line = composer_button_insets(&mut visual);
2749 let left = single_line[0];
2750 assert!(
2751 single_line
2752 .iter()
2753 .all(|inset| (inset - left).abs() < TOLERANCE),
2754 "single line: insets of the input left, the actions top and bottom, send right, top and bottom {single_line:?}"
2755 );
2756 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2757 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
2758 visual.simulate_click(point(input.center().x, send.center().y), Default::default());
2759 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
2760 let three_lines = composer_button_insets(&mut visual);
2761 assert!(
2762 three_lines[1] > single_line[1] + 30.,
2763 "three lines did not grow the composer: {three_lines:?}"
2764 );
2765 for inset in [
2766 three_lines[0],
2767 three_lines[2],
2768 three_lines[3],
2769 three_lines[5],
2770 ] {
2771 assert!(
2772 (inset - left).abs() < TOLERANCE,
2773 "three lines: insets of the input left, the actions top and bottom, send right, top and bottom {three_lines:?}, expected {left}"
2774 );
2775 }
2776 }
2777
2778 #[gpui_kit::test]
2779 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
2780 const FORMAT_TAGS: [&str; 6] = [
2781 COMPOSER_BOX_TAG,
2782 COMPOSER_FORMAT_BAR_TAG,
2783 COMPOSER_FORMAT_DIVIDER_TAG,
2784 COMPOSER_ACTIONS_TAG,
2785 COMPOSER_FORMAT_TAG,
2786 COMPOSER_SEND_TAG,
2787 ];
2788 let (handle, _) = mount(cx);
2789 let mut visual = VisualTestContext::from_window(handle, cx);
2790 for (width, height) in SIZES {
2791 visual.simulate_resize(size(px(width), px(height)));
2792 let window = Bounds {
2793 origin: point(px(0.), px(0.)),
2794 size: size(px(width), px(height)),
2795 };
2796 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
2797 let toggle = visual
2798 .debug_bounds(COMPOSER_FORMAT_TAG)
2799 .expect("format button");
2800 visual.simulate_click(toggle.center(), Default::default());
2801 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
2802 let tags: Vec<Tag> = FORMAT_TAGS
2803 .iter()
2804 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2805 .collect();
2806 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
2807 .into_iter()
2808 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
2809 .collect();
2810 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
2811 let actions = visual.debug_bounds(COMPOSER_ACTIONS_TAG).expect("actions");
2812 let toggle = visual
2813 .debug_bounds(COMPOSER_FORMAT_TAG)
2814 .expect("format button");
2815 visual.simulate_click(toggle.center(), Default::default());
2816 collect(&mut visual, None);
2817 assert!(found.is_empty(), "{}", found.join("\n"));
2818 assert!(
2819 bar.bottom() <= actions.top(),
2820 "bar {bar:?} over the buttons {actions:?}"
2821 );
2822 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
2823 }
2824 }
2825
2826 #[gpui_kit::test]
2827 fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2828 let (handle, _) = mount_with(cx, true);
2829 let mut visual = VisualTestContext::from_window(handle, cx);
2830 visual.dispatch_action(OpenActivity);
2831 for (width, height) in SIZES {
2832 visual.simulate_resize(size(px(width), px(height)));
2833 let window = Bounds {
2834 origin: point(px(0.), px(0.)),
2835 size: size(px(width), px(height)),
2836 };
2837 let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2838 let mut expected = GUARDED.to_vec();
2839 expected.push(ACTIVITY_PROPOSALS_TAG);
2840 let found: Vec<String> = violations(&tags, window, &expected)
2841 .into_iter()
2842 .map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2843 .collect();
2844 assert!(found.is_empty(), "{}", found.join("\n"));
2845 }
2846 }
2847
2848 #[gpui_kit::test]
2849 fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2850 const DELIVERY_TAGS: [&str; 5] = [
2851 COMPOSER_BOX_TAG,
2852 COMPOSER_ACTIONS_TAG,
2853 COMPOSER_PLUS_TAG,
2854 COMPOSER_IMPORTANCE_LABEL_TAG,
2855 COMPOSER_URGENT_BANNER_TAG,
2856 ];
2857 const URGENT_OPTION: &str = "urgent-delivery-option";
2858 const TEXT_INSET: f32 = 6.;
2859 let (handle, _) = mount(cx);
2860 let mut visual = VisualTestContext::from_window(handle, cx);
2861 for (width, height) in SIZES {
2862 visual.simulate_resize(size(px(width), px(height)));
2863 let window = Bounds {
2864 origin: point(px(0.), px(0.)),
2865 size: size(px(width), px(height)),
2866 };
2867 collect(&mut visual, Some(COMPOSER_PLUS_TAG));
2868 let button = visual.debug_bounds(COMPOSER_PLUS_TAG).expect("plus button");
2869 visual.simulate_click(button.center(), Default::default());
2870 let delivery_tag = PlusAction::DeliveryOptions.tag();
2871 collect(&mut visual, Some(delivery_tag));
2872 let delivery = visual.debug_bounds(delivery_tag).expect("delivery item");
2873 visual.simulate_click(delivery.center(), Default::default());
2874 collect(&mut visual, Some(URGENT_OPTION));
2875 let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2876 assert!(
2877 contains(window, menu),
2878 "menu {} leaves the window",
2879 describe(menu)
2880 );
2881 let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2882 visual.simulate_click(urgent.center(), Default::default());
2883 collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2884 assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2885 let tags: Vec<Tag> = DELIVERY_TAGS
2886 .iter()
2887 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2888 .collect();
2889 let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2890 .into_iter()
2891 .map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2892 .collect();
2893 assert!(found.is_empty(), "{}", found.join("\n"));
2894 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2895 let banner = visual
2896 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2897 .expect("banner");
2898 let label = visual
2899 .debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2900 .expect("label");
2901 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2902 assert!(
2903 (f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2904 && (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2905 "banner {} not on the composer edges {}",
2906 describe(banner),
2907 describe(composer)
2908 );
2909 assert!(
2910 banner.bottom() <= composer.top(),
2911 "banner {} over the composer {}",
2912 describe(banner),
2913 describe(composer)
2914 );
2915 assert!(
2916 (inset(composer, label, Edge::Left)
2917 - inset(composer, input, Edge::Left)
2918 - TEXT_INSET)
2919 .abs()
2920 <= TOLERANCE,
2921 "label {} not on the text edge of {}",
2922 describe(label),
2923 describe(input)
2924 );
2925 let close = visual
2926 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2927 .map(|banner| point(banner.right() - px(18.), banner.center().y))
2928 .expect("banner");
2929 visual.simulate_click(close, Default::default());
2930 collect(&mut visual, None);
2931 assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
2932 assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
2933 }
2934 }
2935
2936 #[gpui_kit::test]
2937 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
2938 let (handle, state) = mount_with(cx, true);
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 for chat in IMPORTANCE_CHATS {
2943 visual.update(|_, cx| {
2944 state.update(cx, |state, cx| {
2945 state.select(Selection::Chat(chat.to_owned()), cx)
2946 })
2947 });
2948 collect(&mut visual, Some(TIMELINE_TAG));
2949 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2950 visual.simulate_event(ScrollWheelEvent {
2951 position: timeline.center(),
2952 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
2953 ..Default::default()
2954 });
2955 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
2956 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
2957 let bubble = BUBBLE_TAGS
2958 .iter()
2959 .filter_map(|tag| visual.debug_bounds(tag))
2960 .find(|bubble| contains(*bubble, label))
2961 .unwrap_or_else(|| {
2962 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
2963 });
2964 let left = inset(bubble, label, Edge::Left);
2965 let top = inset(bubble, label, Edge::Top);
2966 assert!(
2967 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2968 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
2969 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2970 describe(bubble)
2971 );
2972 }
2973 }
2974 }
2975
2976 #[gpui_kit::test]
2977 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2978 let (handle, state) = mount_with(cx, true);
2979 let mut visual = VisualTestContext::from_window(handle, cx);
2980 for (width, height) in SIZES {
2981 visual.simulate_resize(size(px(width), px(height)));
2982 let window = Bounds {
2983 origin: point(px(0.), px(0.)),
2984 size: size(px(width), px(height)),
2985 };
2986 for (chat, expected_tags) in [
2987 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
2988 (REACTION_CHAT, &AGENT_TAGS[3..]),
2989 ] {
2990 visual.update(|_, cx| {
2991 state.update(cx, |state, cx| {
2992 state.select(Selection::Chat(chat.to_owned()), cx)
2993 })
2994 });
2995 let tags = collect(&mut visual, Some(expected_tags[0]));
2996 let mut expected = GUARDED.to_vec();
2997 expected.extend(expected_tags);
2998 let found: Vec<String> = violations(&tags, window, &expected)
2999 .into_iter()
3000 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
3001 .collect();
3002 assert!(found.is_empty(), "{}", found.join("\n"));
3003 }
3004 }
3005 }
3006}
3007
3008#[test]
3009fn lines_are_solid() {
3010 let mut files = Vec::new();
3011 for root in source_roots() {
3012 source_files(&root, &mut files);
3013 }
3014 let violations: Vec<String> = files
3015 .iter()
3016 .filter(|file| !file.ends_with("layout_guard.rs"))
3017 .flat_map(|file| {
3018 let source = fs::read_to_string(file).expect("read source file");
3019 source
3020 .lines()
3021 .enumerate()
3022 .filter(|(_, line)| {
3023 line.contains(".border_dashed(") || line.contains(".border_dotted(")
3024 })
3025 .map(|(index, line)| {
3026 format!(
3027 "{}:{}: lines are always solid: {}",
3028 file.display(),
3029 index + 1,
3030 line.trim()
3031 )
3032 })
3033 .collect::<Vec<_>>()
3034 })
3035 .collect();
3036 assert!(violations.is_empty(), "{}", violations.join("\n"));
3037}
3038
3039const STATE_RING_COLORS: &[&str] = &[
3040 "if focused",
3041 "if selected",
3042 "if speaking",
3043 "if current",
3044 "if open",
3045 "if state.failed",
3046];
3047const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
3048 (
3049 "notify/ring_view.rs",
3050 "theme::green()",
3051 "state signal (pulsing ring around the caller while it rings), not a resting outline",
3052 ),
3053 (
3054 "settings/mcp.rs",
3055 "theme::border_strong()",
3056 "outlined button, not a surface",
3057 ),
3058 (
3059 "settings/rows.rs",
3060 "theme::border_strong()",
3061 "outlined button, not a surface",
3062 ),
3063 (
3064 "views/card_widgets.rs",
3065 "border)",
3066 "message content drawn as Teams renders it",
3067 ),
3068 (
3069 "views/card_widgets.rs",
3070 "theme::border_strong()",
3071 "message content drawn as Teams renders it",
3072 ),
3073 ("views/shared_tab.rs", "theme::accent()", "input field"),
3074 ("views/card_input.rs", "if error.is_some()", "input field"),
3075 ("views/format_toolbar.rs", "if refused", "input field"),
3076 (
3077 "views/card_code_block.rs",
3078 "theme::code_header_border()",
3079 "message content drawn as Teams renders it",
3080 ),
3081 (
3082 "render/elements.rs",
3083 "theme::code_frame()",
3084 "message content drawn as Teams renders it",
3085 ),
3086 ("views/call_transcript.rs", "theme::border()", "input field"),
3087 (
3088 "views/conversation.rs",
3089 "theme::accent()",
3090 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3091 ),
3092 (
3093 "views/attachment_tray.rs",
3094 "theme::accent()",
3095 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3096 ),
3097 (
3098 "views/card_carousel.rs",
3099 "theme::border_strong()",
3100 "message content drawn as Teams renders it",
3101 ),
3102 (
3103 "views/card_table.rs",
3104 "grid_color",
3105 "message content drawn as Teams renders it",
3106 ),
3107 (
3108 "views/activity_panel.rs",
3109 "theme::surface()",
3110 "cutout ring in the background color, invisible against its surface",
3111 ),
3112 (
3113 "views/avatar.rs",
3114 "theme::surface()",
3115 "cutout ring in the background color, invisible against its surface",
3116 ),
3117 (
3118 "views/message_row.rs",
3119 "theme::border_strong()",
3120 "deleted message placeholder, Teams look",
3121 ),
3122 (
3123 "views/message_row.rs",
3124 "theme::red()",
3125 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3126 ),
3127 (
3128 "views/message_row.rs",
3129 "if row.delivery",
3130 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3131 ),
3132 (
3133 "views/new_meeting_dialog.rs",
3134 "theme::border()",
3135 "input field",
3136 ),
3137 (
3138 "views/call_mini_window.rs",
3139 "theme::border_strong()",
3140 "self view over live video, needs an edge on any picture",
3141 ),
3142 ("views/transfer_picker.rs", "theme::border()", "input field"),
3143 (
3144 "views/call_notice.rs",
3145 "theme::border_strong()",
3146 "outlined button, not a surface",
3147 ),
3148 (
3149 "views/composer/schedule.rs",
3150 "theme::accent()",
3151 "input field",
3152 ),
3153 (
3154 "views/sidebar.rs",
3155 "theme::accent()",
3156 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3157 ),
3158 (
3159 "views/adaptive_card.rs",
3160 "theme::border()",
3161 "message content drawn as Teams renders it",
3162 ),
3163 (
3164 "views/adaptive_card.rs",
3165 "border)",
3166 "message content drawn as Teams renders it",
3167 ),
3168 (
3169 "views/share_bar.rs",
3170 "theme::red()",
3171 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3172 ),
3173 ("settings_controls.rs", "if invalid", "input field"),
3174];
3175
3176fn outlines(source: &str) -> Vec<(usize, String)> {
3177 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
3178 pattern
3179 .find_iter(source)
3180 .map(|found| {
3181 let line_number = source[..found.start()].matches('\n').count() + 1;
3182 let after = &source[found.end()..];
3183 let color = after
3184 .find(".border_color(")
3185 .filter(|position| *position < 120)
3186 .map(|position| {
3187 let start = &after[position + ".border_color(".len()..];
3188 start
3189 .lines()
3190 .map(str::trim)
3191 .find(|line| !line.is_empty())
3192 .unwrap_or_default()
3193 .to_owned()
3194 })
3195 .unwrap_or_default();
3196 (line_number, color)
3197 })
3198 .collect()
3199}
3200
3201#[test]
3202fn outline_matcher_reads_the_border_color() {
3203 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
3204 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
3205}
3206
3207#[test]
3208fn surfaces_are_soft() {
3209 let mut matched_allowlist = HashSet::new();
3210 let mut violations = Vec::new();
3211 for root in source_roots() {
3212 let mut files = Vec::new();
3213 source_files(&root, &mut files);
3214 for file in files {
3215 let relative = file
3216 .strip_prefix(&root)
3217 .expect("inside src")
3218 .to_string_lossy()
3219 .replace('\\', "/");
3220 if relative == "layout_guard.rs" {
3221 continue;
3222 }
3223 let source = fs::read_to_string(&file).expect("read source file");
3224 for (line_number, color) in outlines(&source) {
3225 if STATE_RING_COLORS
3226 .iter()
3227 .any(|prefix| color.starts_with(prefix))
3228 {
3229 continue;
3230 }
3231 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
3232 *allowed_file == relative && color.starts_with(prefix)
3233 }) {
3234 Some(position) => {
3235 matched_allowlist.insert(position);
3236 }
3237 None => violations.push(format!(
3238 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
3239 )),
3240 }
3241 }
3242 }
3243 }
3244 let stale = OUTLINE_ALLOWLIST
3245 .iter()
3246 .enumerate()
3247 .filter(|(position, _)| !matched_allowlist.contains(position))
3248 .map(|(_, (file, prefix, _))| {
3249 format!("stale outline allowlist entry, remove it: {file} {prefix}")
3250 });
3251 let report: Vec<String> = violations.into_iter().chain(stale).collect();
3252 assert!(report.is_empty(), "{}", report.join("\n"));
3253}
3254
3255fn indentation(line: &str) -> usize {
3256 line.len() - line.trim_start().len()
3257}
3258
3259fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
3260 let indent = indentation(lines[index]);
3261 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
3262 let start = lines[..index]
3263 .iter()
3264 .rposition(|line| !belongs(line))
3265 .map_or(0, |position| position + 1);
3266 let end = lines[index..]
3267 .iter()
3268 .position(|line| !belongs(line))
3269 .map_or(lines.len(), |position| index + position);
3270 lines[start..end]
3271 .iter()
3272 .filter(|line| indentation(line) == indent)
3273 .copied()
3274 .collect()
3275}
3276
3277fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
3278 let lines: Vec<&str> = source.lines().collect();
3279 (0..lines.len())
3280 .filter(|&index| row_height.is_match(lines[index]))
3281 .filter(|&index| {
3282 !chain_lines(&lines, index).iter().any(|line| {
3283 let line = line.trim();
3284 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
3285 })
3286 })
3287 .map(|index| index + 1)
3288 .collect()
3289}
3290
3291fn row_height_pattern() -> Regex {
3292 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
3293}
3294
3295#[test]
3296fn matcher_finds_rows_without_flex_none() {
3297 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";
3298 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
3299}
3300
3301#[test]
3302fn fixed_height_rows_never_shrink() {
3303 let row_height = row_height_pattern();
3304 let mut files = Vec::new();
3305 for root in source_roots() {
3306 source_files(&root, &mut files);
3307 }
3308 let violations: Vec<String> = files
3309 .iter()
3310 .filter(|file| !file.ends_with("layout_guard.rs"))
3311 .flat_map(|file| {
3312 let source = fs::read_to_string(file).expect("read source file");
3313 shrinking_rows(&row_height, &source)
3314 .into_iter()
3315 .map(|line| format!("{}:{line}", file.display()))
3316 .collect::<Vec<_>>()
3317 })
3318 .collect();
3319 assert!(
3320 violations.is_empty(),
3321 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
3322 );
3323}