BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 131.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 the_group_name_field_keeps_typed_text_across_frames(cx: &mut TestAppContext) {
1847 let (handle, state) = mount(cx);
1848 let mut visual = VisualTestContext::from_window(handle, cx);
1849 visual.update(|_, cx| {
1850 state.update(cx, |state, cx| {
1851 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1852 })
1853 });
1854 collect(&mut visual, Some(GROUP_NAME_BUTTON));
1855 let button = visual
1856 .debug_bounds(GROUP_NAME_BUTTON)
1857 .expect("group name button rendered");
1858 visual.simulate_click(button.center(), Default::default());
1859 collect(&mut visual, Some(GROUP_NAME_FORM));
1860 assert!(
1861 visual.debug_bounds(GROUP_NAME_FORM).is_some(),
1862 "group name form open"
1863 );
1864 visual.simulate_keystrokes("backspace x space y enter");
1865 visual.run_until_parked();
1866 let title = visual.update(|_, cx| {
1867 state
1868 .read(cx)
1869 .sidebar
1870 .chats
1871 .iter()
1872 .find(|chat| chat.id == MEMBERS_CHAT)
1873 .map(|chat| chat.title.clone())
1874 });
1875 assert_eq!(title.as_deref(), Some("Release planninx y"));
1876 }
1877
1878 const FORWARD_CHAT: &str = "demo-chat-release";
1879 const FORWARD_FOOTER_TAGS: [&str; 4] = [
1880 FORWARD_FOOTER_TAG,
1881 FORWARD_FOOTER_BAR_TAG,
1882 FORWARD_FOOTER_COUNT_TAG,
1883 FORWARD_FOOTER_NEXT_TAG,
1884 ];
1885 const FORWARD_DIALOG_PADDING: f32 = 16.;
1886 const FORWARD_BAR_PADDING: f32 = 8.;
1887 const FORWARD_ROWS_SCANNED: usize = 80;
1888
1889 fn forward_message_ids(
1890 state: &Entity<AppState>,
1891 visual: &mut VisualTestContext,
1892 ) -> Vec<String> {
1893 visual.update(|_, cx| {
1894 let mut records = state
1895 .read(cx)
1896 .store
1897 .messages(FORWARD_CHAT, None, 50)
1898 .expect("demo messages");
1899 records.retain(|record| !record.deleted);
1900 records.sort_by_key(|record| record.created_at);
1901 records
1902 .iter()
1903 .rev()
1904 .take(2)
1905 .map(|record| record.message_id.clone())
1906 .collect()
1907 })
1908 }
1909
1910 #[gpui_kit::test]
1911 fn forward_selection_footer_checks_and_dialog_keep_their_insets(cx: &mut TestAppContext) {
1912 let (handle, state) = mount(cx);
1913 let mut visual = VisualTestContext::from_window(handle, cx);
1914 for (width, height) in SIZES {
1915 visual.simulate_resize(size(px(width), px(height)));
1916 let window = Bounds {
1917 origin: point(px(0.), px(0.)),
1918 size: size(px(width), px(height)),
1919 };
1920 visual.update(|_, cx| {
1921 state.update(cx, |state, cx| {
1922 state.select(Selection::Chat(FORWARD_CHAT.to_owned()), cx)
1923 })
1924 });
1925 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1926 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
1927 let ids = forward_message_ids(&state, &mut visual);
1928 visual.update(|_, cx| {
1929 state.update(cx, |state, cx| {
1930 state.start_forward_selection(FORWARD_CHAT, &ids[0], cx);
1931 state.toggle_forward_selected(&ids[1], cx);
1932 })
1933 });
1934 collect(&mut visual, Some(FORWARD_FOOTER_NEXT_TAG));
1935 assert!(
1936 visual.debug_bounds(COMPOSER_BOX_TAG).is_none(),
1937 "the footer replaces the composer"
1938 );
1939 let tags: Vec<Tag> = FORWARD_FOOTER_TAGS
1940 .iter()
1941 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1942 .collect();
1943 let mut found: Vec<String> = violations(&tags, window, &FORWARD_FOOTER_TAGS)
1944 .into_iter()
1945 .map(|(key, message)| format!("forward@{width}x{height}:{key}: {message}"))
1946 .collect();
1947 let main = visual.debug_bounds(MAIN).expect("main island");
1948 let bar = visual.debug_bounds(FORWARD_FOOTER_BAR_TAG).expect("bar");
1949 let next = visual.debug_bounds(FORWARD_FOOTER_NEXT_TAG).expect("next");
1950 if (f32::from(bar.left() - composer.left())).abs() > TOLERANCE
1951 || (f32::from(bar.right() - composer.right())).abs() > TOLERANCE
1952 {
1953 found.push(format!(
1954 "forward@{width}x{height}: bar {} not on the composer edges {}",
1955 describe(bar),
1956 describe(composer)
1957 ));
1958 }
1959 for edge in [Edge::Top, Edge::Right, Edge::Bottom] {
1960 let gap = inset(bar, next, edge);
1961 if (gap - FORWARD_BAR_PADDING).abs() > TOLERANCE {
1962 found.push(format!(
1963 "forward@{width}x{height}: next button {edge:?} inset {gap} != {FORWARD_BAR_PADDING}"
1964 ));
1965 }
1966 }
1967 let checks: Vec<Bounds<Pixels>> = (0..FORWARD_ROWS_SCANNED)
1968 .filter_map(|index| {
1969 visual.debug_bounds(Box::leak(select_box_selector(index).into_boxed_str()))
1970 })
1971 .filter(|check| contains(main, *check))
1972 .collect();
1973 if checks.is_empty() {
1974 found.push(format!("forward@{width}x{height}: no checkbox rendered"));
1975 }
1976 let expected_left = ROW_PADDING + runway_margin(f32::from(main.size.width));
1977 for check in &checks {
1978 let left = inset(main, *check, Edge::Left);
1979 if (left - expected_left).abs() > TOLERANCE {
1980 found.push(format!(
1981 "forward@{width}x{height}: checkbox {} starts {left} from the island, not {expected_left}",
1982 describe(*check)
1983 ));
1984 }
1985 }
1986 visual.simulate_click(next.center(), Default::default());
1987 collect(&mut visual, Some(FORWARD_PREVIEW_TAG));
1988 let card = visual.debug_bounds(FORWARD_CARD_TAG).expect("dialog card");
1989 let preview = visual.debug_bounds(FORWARD_PREVIEW_TAG).expect("preview");
1990 if !contains(window, card) || !contains(card, preview) {
1991 found.push(format!(
1992 "forward@{width}x{height}: dialog {} or preview {} clipped",
1993 describe(card),
1994 describe(preview)
1995 ));
1996 }
1997 let (left, right) = (
1998 inset(card, preview, Edge::Left),
1999 inset(card, preview, Edge::Right),
2000 );
2001 if (left - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
2002 || (right - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
2003 {
2004 found.push(format!(
2005 "forward@{width}x{height}: preview insets {left}/{right} != {FORWARD_DIALOG_PADDING}"
2006 ));
2007 }
2008 visual.simulate_keystrokes("escape");
2009 collect(&mut visual, None);
2010 assert!(visual.debug_bounds(FORWARD_CARD_TAG).is_none());
2011 assert!(
2012 visual.debug_bounds(FORWARD_FOOTER_TAG).is_some(),
2013 "closing the dialog keeps the selection"
2014 );
2015 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_forward_selection(cx)));
2016 collect(&mut visual, Some(COMPOSER_BOX_TAG));
2017 assert!(visual.debug_bounds(FORWARD_FOOTER_TAG).is_none());
2018 assert!(found.is_empty(), "{}", found.join("\n"));
2019 }
2020 }
2021
2022 const MENU_ITEMS_SCANNED: usize = 40;
2023 const MENU_CHAT: &str = "demo-chat-release";
2024 const THEME_SELECT: &str = "settings-theme";
2025 const CALENDAR_DEFAULT_VIEW_SELECT: &str = "settings-calendar-default-view";
2026
2027 struct MenuRow {
2028 index: usize,
2029 item: Bounds<Pixels>,
2030 icon: Option<Bounds<Pixels>>,
2031 label: Option<Bounds<Pixels>>,
2032 }
2033
2034 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
2035 (0..MENU_ITEMS_SCANNED)
2036 .filter_map(|index| {
2037 let item =
2038 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
2039 Some(MenuRow {
2040 index,
2041 item,
2042 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
2043 label: visual
2044 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
2045 })
2046 })
2047 .collect()
2048 }
2049
2050 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
2051 let mut found = Vec::new();
2052 for row in rows {
2053 let Some(icon) = row.icon else {
2054 continue;
2055 };
2056 let key = format!("{MENU}/item-{}", row.index);
2057 if let Some(label) = row.label {
2058 let gap = f32::from(label.left() - icon.right());
2059 if (gap - expected_gap).abs() > TOLERANCE {
2060 found.push((
2061 format!("{key}:icon-gap"),
2062 format!(
2063 "icon {} to label {} is {gap} px, expected {expected_gap}",
2064 describe(icon),
2065 describe(label)
2066 ),
2067 ));
2068 }
2069 }
2070 let offset = f32::from(icon.center().y - row.item.center().y);
2071 if offset.abs() > TOLERANCE {
2072 found.push((
2073 format!("{key}:icon-off-centre"),
2074 format!(
2075 "icon {} sits {offset} px off the centre of item {}",
2076 describe(icon),
2077 describe(row.item)
2078 ),
2079 ));
2080 }
2081 }
2082 found
2083 }
2084
2085 fn listbox_violations(
2086 trigger: Bounds<Pixels>,
2087 menu: Bounds<Pixels>,
2088 items: Bounds<Pixels>,
2089 rows: &[MenuRow],
2090 ) -> Vec<(String, String)> {
2091 let mut found = Vec::new();
2092 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
2093 if !near(f32::from(menu.left() - trigger.left()), 0.) {
2094 found.push((
2095 format!("{MENU}:not-aligned-to-trigger"),
2096 format!(
2097 "list {} must start at the trigger's left edge {}",
2098 describe(menu),
2099 describe(trigger)
2100 ),
2101 ));
2102 }
2103 if !near(
2104 f32::from(menu.top() - trigger.bottom()),
2105 f32::from(DROPDOWN_OFFSET),
2106 ) {
2107 found.push((
2108 format!("{MENU}:trigger-offset"),
2109 format!(
2110 "list {} must open {} px below the trigger {}",
2111 describe(menu),
2112 f32::from(DROPDOWN_OFFSET),
2113 describe(trigger)
2114 ),
2115 ));
2116 }
2117 if menu.size.width < trigger.size.width - px(TOLERANCE) {
2118 found.push((
2119 format!("{MENU}:narrower-than-trigger"),
2120 format!(
2121 "list {} is narrower than the trigger {}",
2122 describe(menu),
2123 describe(trigger)
2124 ),
2125 ));
2126 }
2127 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
2128 let top = f32::from(first.item.top() - items.top());
2129 let bottom = f32::from(items.bottom() - last.item.bottom());
2130 let padding = f32::from(MENU_LIST_PADDING);
2131 if !near(top, padding) || !near(bottom, padding) {
2132 found.push((
2133 format!("{MENU}:uneven-padding"),
2134 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
2135 ));
2136 }
2137 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
2138 match first.icon {
2139 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
2140 check => found.push((
2141 format!("{MENU}:check-inset"),
2142 format!(
2143 "check column {check:?} must start {expected_inset} px inside the list {}",
2144 describe(menu)
2145 ),
2146 )),
2147 }
2148 }
2149 found
2150 }
2151
2152 #[test]
2153 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
2154 let row =
2155 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
2156 index,
2157 item: rectangle(4., item_top, 120., 32.),
2158 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
2159 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
2160 };
2161 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
2162 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
2163 .into_iter()
2164 .map(|(key, _)| key)
2165 .collect();
2166 assert_eq!(
2167 keys,
2168 [
2169 "popup-menu/item-1:icon-gap",
2170 "popup-menu/item-1:icon-off-centre"
2171 ]
2172 );
2173
2174 let trigger = rectangle(100., 50., 216., 32.);
2175 let option = |index: usize, top: f32| MenuRow {
2176 index,
2177 item: rectangle(104., top, 208., 32.),
2178 icon: Some(rectangle(110., top + 8., 16., 16.)),
2179 label: Some(rectangle(132., top + 6., 80., 20.)),
2180 };
2181 let aligned = [option(0, 88.), option(1, 122.)];
2182 let menu = rectangle(100., 84., 216., 74.);
2183 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
2184 let shifted = rectangle(96., 90., 200., 80.);
2185 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
2186 .into_iter()
2187 .map(|(key, _)| key)
2188 .collect();
2189 assert_eq!(
2190 keys,
2191 [
2192 "popup-menu:not-aligned-to-trigger",
2193 "popup-menu:trigger-offset",
2194 "popup-menu:narrower-than-trigger",
2195 "popup-menu:uneven-padding",
2196 "popup-menu:check-inset",
2197 ]
2198 );
2199 }
2200
2201 #[gpui_kit::test]
2202 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
2203 let (handle, _) = mount(cx);
2204 let mut visual = VisualTestContext::from_window(handle, cx);
2205 visual.simulate_resize(size(px(1280.), px(800.)));
2206 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
2207 collect(&mut visual, Some(chat_row));
2208 let mut found = Vec::new();
2209 let own_status = visual
2210 .debug_bounds(OWN_STATUS)
2211 .expect("own status button rendered");
2212 visual.simulate_click(own_status.center(), Default::default());
2213 collect(&mut visual, Some(MENU));
2214 let status_rows = menu_rows(&mut visual);
2215 assert!(
2216 status_rows.iter().any(|row| row.icon.is_some()),
2217 "status menu shows icons"
2218 );
2219 found.extend(menu_row_violations(
2220 &status_rows,
2221 f32::from(MENU_ICON_LABEL_GAP),
2222 ));
2223 visual.simulate_keystrokes("escape");
2224 collect(&mut visual, None);
2225 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
2226 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
2227 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
2228 collect(&mut visual, Some(MENU));
2229 let chat_rows = menu_rows(&mut visual);
2230 assert!(
2231 chat_rows.iter().any(|row| row.icon.is_some()),
2232 "chat menu shows icons"
2233 );
2234 found.extend(menu_row_violations(
2235 &chat_rows,
2236 f32::from(MENU_ICON_LABEL_GAP),
2237 ));
2238 let found: Vec<String> = found
2239 .into_iter()
2240 .map(|(key, message)| format!("{key}: {message}"))
2241 .collect();
2242 assert!(found.is_empty(), "{}", found.join("\n"));
2243 }
2244
2245 #[gpui_kit::test]
2246 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2247 select_list_lines_up(cx, SettingsSection::Appearance, THEME_SELECT);
2248 }
2249
2250 #[gpui_kit::test]
2251 fn calendar_default_view_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2252 select_list_lines_up(cx, SettingsSection::Calendar, CALENDAR_DEFAULT_VIEW_SELECT);
2253 }
2254
2255 fn select_list_lines_up(cx: &mut TestAppContext, section: SettingsSection, id: &str) {
2256 let (handle, state) = mount(cx);
2257 let mut visual = VisualTestContext::from_window(handle, cx);
2258 visual.simulate_resize(size(px(1280.), px(800.)));
2259 visual.update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
2260 let select: &'static str = Box::leak(select_selector(id).into_boxed_str());
2261 collect(&mut visual, Some(select));
2262 let trigger = visual.debug_bounds(select).expect("select rendered");
2263 visual.simulate_click(trigger.center(), Default::default());
2264 collect(&mut visual, Some(MENU));
2265 let menu = visual.debug_bounds(MENU).expect("list rendered");
2266 let items = visual
2267 .debug_bounds(ITEMS_SELECTOR)
2268 .expect("list items rendered");
2269 let rows = menu_rows(&mut visual);
2270 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
2271 .into_iter()
2272 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
2273 .map(|(key, message)| format!("{key}: {message}"))
2274 .collect();
2275 assert!(found.is_empty(), "{}", found.join("\n"));
2276 }
2277
2278 const BADGE_SAMPLES: [(u32, bool); 5] =
2279 [(1, false), (42, false), (120, false), (7, true), (15, true)];
2280
2281 struct BadgeSamples;
2282
2283 impl gpui_kit::Render for BadgeSamples {
2284 fn render(
2285 &mut self,
2286 _: &mut gpui_kit::Window,
2287 _: &mut gpui_kit::Context<Self>,
2288 ) -> impl gpui_kit::IntoElement {
2289 use gpui_kit::{ParentElement as _, Styled as _};
2290 gpui_kit::div()
2291 .flex()
2292 .gap(px(12.))
2293 .p(px(12.))
2294 .children(BADGE_SAMPLES.map(|(count, rail)| {
2295 if rail {
2296 badge_pill(
2297 count,
2298 RAIL_BADGE,
2299 crate::theme::accent(),
2300 crate::theme::on_accent(),
2301 )
2302 } else {
2303 count_badge(count, false)
2304 }
2305 }))
2306 }
2307 }
2308
2309 fn badge_violation(
2310 text: &str,
2311 pill: Bounds<Pixels>,
2312 label: Bounds<Pixels>,
2313 ink_offset: (f32, f32),
2314 ) -> Option<(String, String)> {
2315 let ink_x = f32::from(label.center().x) + ink_offset.0;
2316 let ink_y = f32::from(label.center().y) + ink_offset.1;
2317 let off_x = ink_x - f32::from(pill.center().x);
2318 let off_y = ink_y - f32::from(pill.center().y);
2319 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
2320 (
2321 format!("count-badge/{text}:off-centre"),
2322 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
2323 )
2324 })
2325 }
2326
2327 #[test]
2328 fn badge_rule_flags_off_centre_text() {
2329 let pill = rectangle(0., 0., 18., 18.);
2330 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
2331 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
2332 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
2333 }
2334
2335 #[gpui_kit::test]
2336 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
2337 cx.update(gpui_kit::init);
2338 cx.update(crate::theme::apply);
2339 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
2340 collect(visual, None);
2341 let mut found = Vec::new();
2342 for (count, rail) in BADGE_SAMPLES {
2343 let text = crate::format::badge_text(count);
2344 let pill = visual
2345 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
2346 .expect("badge rendered");
2347 let label = visual
2348 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
2349 .expect("badge text rendered");
2350 let font_size = if rail {
2351 RAIL_BADGE.font_size
2352 } else {
2353 COUNT_BADGE.font_size
2354 };
2355 let offset = visual.update(|window, _| {
2356 let origin = badge_text_origin(window, &text, font_size, pill);
2357 let (ink_centre, cap_height) = badge_ink_centre(window, &text, font_size);
2358 (
2359 f32::from(origin.x) + ink_centre - f32::from(label.center().x),
2360 f32::from(origin.y) - cap_height / 2. - f32::from(label.center().y),
2361 )
2362 });
2363 found.extend(badge_violation(&text, pill, label, offset));
2364 }
2365 let found: Vec<String> = found
2366 .into_iter()
2367 .map(|(key, message)| format!("{key}: {message}"))
2368 .collect();
2369 assert!(found.is_empty(), "{}", found.join("\n"));
2370 }
2371
2372 const PINNED_CHAT: &str = "demo-chat-release";
2373 const PINNED_CHANNEL: &str = "demo-channel-1-1";
2374
2375 #[gpui_kit::test]
2376 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
2377 let (handle, state) = mount(cx);
2378 let mut visual = VisualTestContext::from_window(handle, cx);
2379 let mut found = Vec::new();
2380 for (width, height) in SIZES {
2381 visual.simulate_resize(size(px(width), px(height)));
2382 visual.update(|_, cx| {
2383 state.update(cx, |state, cx| {
2384 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
2385 })
2386 });
2387 collect(&mut visual, Some(PIN_BANNER_TAG));
2388 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
2389 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2390 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2391 let gaps = [
2392 ("top", f32::from(banner.top() - timeline.top())),
2393 ("left", f32::from(banner.left() - timeline.left())),
2394 ("right", f32::from(timeline.right() - banner.right())),
2395 ("below divider", f32::from(banner.top() - divider.bottom())),
2396 ];
2397 let runway = runway_margin(f32::from(timeline.size.width) - 2. * BANNER_INSET);
2398 let sides_ok = gaps[1..3]
2399 .iter()
2400 .all(|(_, gap)| (gap - BANNER_INSET - runway).abs() <= INSET_TOLERANCE);
2401 let vertical_ok = [gaps[0].1, gaps[3].1]
2402 .iter()
2403 .all(|gap| (gap - BANNER_INSET).abs() <= INSET_TOLERANCE);
2404 if !sides_ok || !vertical_ok {
2405 found.push(format!(
2406 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
2407 ));
2408 }
2409 }
2410 assert!(found.is_empty(), "{}", found.join("\n"));
2411 }
2412
2413 #[gpui_kit::test]
2414 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
2415 let (handle, state) = mount(cx);
2416 let mut visual = VisualTestContext::from_window(handle, cx);
2417 visual.simulate_resize(size(px(1280.), px(800.)));
2418 visual.update(|_, cx| {
2419 state.update(cx, |state, cx| {
2420 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2421 })
2422 });
2423 collect(&mut visual, Some(TIMELINE_TAG));
2424 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
2425 }
2426
2427 fn open_channel(cx: &mut TestAppContext, awaited: &'static str) -> VisualTestContext {
2428 let (handle, state) = mount(cx);
2429 let mut visual = VisualTestContext::from_window(handle, cx);
2430 visual.simulate_resize(size(px(1280.), px(800.)));
2431 visual.update(|_, cx| {
2432 state.update(cx, |state, cx| {
2433 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2434 })
2435 });
2436 collect(&mut visual, Some(awaited));
2437 visual
2438 }
2439
2440 #[gpui_kit::test]
2441 fn the_new_post_is_one_card_with_subject_divider_format_bar_and_post_button(
2442 cx: &mut TestAppContext,
2443 ) {
2444 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2445 let open = visual
2446 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2447 .expect("post in channel card");
2448 visual.simulate_click(open.center(), Default::default());
2449 collect(&mut visual, Some(POST_CARD_SEND_TAG));
2450 let mut bounds_of = |path: &'static str| {
2451 visual
2452 .debug_bounds(path)
2453 .unwrap_or_else(|| panic!("{path} missing"))
2454 };
2455 let card = bounds_of(COMPOSER_BOX_TAG);
2456 let header = bounds_of(POST_CARD_HEADER_TAG);
2457 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2458 let divider = bounds_of(POST_CARD_DIVIDER_TAG);
2459 let format_bar = bounds_of(COMPOSER_FORMAT_BAR_TAG);
2460 let footer = bounds_of(POST_CARD_FOOTER_TAG);
2461 let send = bounds_of(POST_CARD_SEND_TAG);
2462 assert!(
2463 visual.debug_bounds(COMPOSER_SEND_TAG).is_none(),
2464 "chat send button shown in a post"
2465 );
2466 assert!(
2467 visual.debug_bounds(COMPOSER_FORMAT_TAG).is_none(),
2468 "format toggle shown although the bar stays open"
2469 );
2470 assert!(header.bottom() <= subject.top() && subject.bottom() <= divider.top());
2471 assert!(divider.bottom() <= format_bar.top() && format_bar.bottom() <= footer.top());
2472 assert!(
2473 f32::from(divider.left() - card.left()).abs() < 1.5
2474 && f32::from(card.right() - divider.right()).abs() < 1.5,
2475 "subject divider {} does not run edge to edge in {}",
2476 describe(divider),
2477 describe(card)
2478 );
2479 let side = f32::from(card.right() - send.right());
2480 let bottom = f32::from(card.bottom() - send.bottom());
2481 assert!(
2482 (side - bottom).abs() < TOLERANCE,
2483 "Post button insets: side {side}, bottom {bottom}"
2484 );
2485 }
2486
2487 #[gpui_kit::test]
2488 fn announcement_mode_puts_the_banner_between_author_and_subheading(cx: &mut TestAppContext) {
2489 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2490 let open = visual
2491 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2492 .expect("post in channel card");
2493 visual.simulate_click(open.center(), Default::default());
2494 collect(&mut visual, Some(POST_ANNOUNCEMENT_TOGGLE_TAG));
2495 let toggle = visual
2496 .debug_bounds(POST_ANNOUNCEMENT_TOGGLE_TAG)
2497 .expect("announcement toggle in the format bar");
2498 let format_bar = visual
2499 .debug_bounds(COMPOSER_FORMAT_BAR_TAG)
2500 .expect("format bar");
2501 assert!(
2502 format_bar.contains(&toggle.center()),
2503 "toggle outside the format bar"
2504 );
2505 visual.simulate_click(toggle.center(), Default::default());
2506 collect(&mut visual, Some(POST_ANNOUNCEMENT_TAG));
2507 let mut bounds_of = |path: &'static str| {
2508 visual
2509 .debug_bounds(path)
2510 .unwrap_or_else(|| panic!("{path} missing"))
2511 };
2512 let card = bounds_of(COMPOSER_BOX_TAG);
2513 let header = bounds_of(POST_CARD_HEADER_TAG);
2514 let banner = bounds_of(POST_ANNOUNCEMENT_TAG);
2515 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2516 assert!(header.bottom() <= banner.top() && banner.bottom() <= subject.top());
2517 let gap = f32::from(subject.top() - banner.bottom());
2518 assert!(gap >= 6., "subheading {gap} px under the banner");
2519 let audience = bounds_of(POST_AUDIENCE_TAG);
2520 assert!(
2521 audience.bottom() <= card.top(),
2522 "audience hint not above the card"
2523 );
2524 let left = f32::from(banner.left() - card.left());
2525 let right = f32::from(card.right() - banner.right());
2526 assert!(
2527 (left - right).abs() < TOLERANCE,
2528 "banner insets: left {left}, right {right}"
2529 );
2530 }
2531
2532 #[gpui_kit::test]
2533 fn channel_posts_start_the_body_at_the_avatar_edge_like_teams(cx: &mut TestAppContext) {
2534 let mut visual = open_channel(cx, POST_FOOTER_AVATAR_TAG);
2535 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
2536 visual
2537 .debug_bounds(path)
2538 .unwrap_or_else(|| panic!("{path} rendered"))
2539 };
2540 let card = bounds_of(&mut visual, POST_CARD_TAG);
2541 let avatar = bounds_of(&mut visual, POST_AVATAR_TAG);
2542 let body = bounds_of(&mut visual, POST_BODY_TAG);
2543 let footer_avatar = bounds_of(&mut visual, POST_FOOTER_AVATAR_TAG);
2544 let side = f32::from(avatar.left() - card.left());
2545 let checks = [
2546 ("body left", f32::from(body.left() - avatar.left())),
2547 (
2548 "footer avatar left",
2549 f32::from(footer_avatar.left() - avatar.left()),
2550 ),
2551 (
2552 "body right inset",
2553 f32::from(card.right() - body.right()) - side,
2554 ),
2555 ];
2556 for (name, gap) in checks {
2557 assert!(
2558 gap.abs() < INSET_TOLERANCE,
2559 "{name} off by {gap}: card {card:?} avatar {avatar:?} body {body:?} footer {footer_avatar:?}"
2560 );
2561 }
2562 }
2563
2564 #[gpui_kit::test]
2565 fn a_code_line_is_one_frame_inside_the_post_body(cx: &mut TestAppContext) {
2566 let mut visual = open_channel(cx, CODE_LINE_TAG);
2567 let code = visual.debug_bounds(CODE_LINE_TAG).expect("code line");
2568 let body = visual.debug_bounds(POST_BODY_TAG).expect("post body");
2569 assert!(
2570 f32::from(code.size.height) > 40.,
2571 "the long code line wraps inside one frame: {code:?}"
2572 );
2573 assert!(
2574 (f32::from(code.left() - body.left())).abs() < INSET_TOLERANCE
2575 && code.right() <= body.right() + px(INSET_TOLERANCE),
2576 "code {code:?} sits inside the body {body:?}"
2577 );
2578 assert!(visual.debug_bounds(CODE_BLOCK_TAG).is_none());
2579 }
2580
2581 #[gpui_kit::test]
2582 fn the_new_post_row_shows_a_scroll_edge_only_while_scrolled(cx: &mut TestAppContext) {
2583 let mut visual = open_channel(cx, POST_CARD_TAG);
2584 assert!(visual.debug_bounds(FEED_EDGE_TAG).is_none());
2585 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2586 visual.simulate_event(ScrollWheelEvent {
2587 position: timeline.center(),
2588 delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
2589 ..Default::default()
2590 });
2591 collect(&mut visual, Some(FEED_EDGE_TAG));
2592 let edge = visual.debug_bounds(FEED_EDGE_TAG).expect("feed edge");
2593 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2594 assert!(
2595 (f32::from(edge.top() - timeline.top())).abs() < INSET_TOLERANCE
2596 && (f32::from(edge.left() - timeline.left())).abs() < INSET_TOLERANCE
2597 && (f32::from(timeline.right() - edge.right())).abs() < INSET_TOLERANCE,
2598 "edge {edge:?} runs across the top of the timeline {timeline:?}"
2599 );
2600 }
2601
2602 #[gpui_kit::test]
2603 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
2604 let (handle, state) = mount(cx);
2605 let mut visual = VisualTestContext::from_window(handle, cx);
2606 visual.simulate_resize(size(px(1280.), px(800.)));
2607 visual.update(|_, cx| {
2608 state.update(cx, |state, cx| {
2609 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2610 })
2611 });
2612 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2613 let button = visual
2614 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2615 .expect("channel details button");
2616 visual.simulate_click(button.center(), Default::default());
2617 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
2618 let pane = visual
2619 .debug_bounds(CHANNEL_DETAILS_TAG)
2620 .expect("details pane");
2621 let main = visual.debug_bounds(MAIN).expect("main island");
2622 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2623 assert!(
2624 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
2625 "pane {pane:?} must end at the main island edge {main:?}"
2626 );
2627 assert!(
2628 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
2629 "pane {pane:?} must start under the header divider {divider:?}"
2630 );
2631 }
2632
2633 #[gpui_kit::test]
2634 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
2635 let (handle, state) = mount(cx);
2636 let mut visual = VisualTestContext::from_window(handle, cx);
2637 visual.simulate_resize(size(px(1280.), px(800.)));
2638 visual.update(|_, cx| {
2639 state.update(cx, |state, cx| {
2640 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2641 })
2642 });
2643 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2644 let button = visual
2645 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2646 .expect("channel details button");
2647 visual.simulate_click(button.center(), Default::default());
2648 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
2649 let pane = visual
2650 .debug_bounds(CHANNEL_DETAILS_TAG)
2651 .expect("details pane");
2652 let pinned = visual
2653 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
2654 .expect("pinned section");
2655 let shared = visual
2656 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
2657 .expect("shared section");
2658 assert!(
2659 pinned.bottom() <= shared.top(),
2660 "pinned {pinned:?} must come before shared {shared:?}"
2661 );
2662 for (name, section) in [("pinned", pinned), ("shared", shared)] {
2663 let left = f32::from(section.left() - pane.left());
2664 let right = f32::from(pane.right() - section.right());
2665 assert!(
2666 (left - right).abs() < INSET_TOLERANCE && left > 0.,
2667 "{name} section insets left {left} right {right} must match"
2668 );
2669 }
2670 }
2671
2672 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
2673 collect(visual, Some(COMPOSER_SEND_TAG));
2674 let mut bounds_of = |path: &'static str| {
2675 visual
2676 .debug_bounds(path)
2677 .unwrap_or_else(|| panic!("{path} rendered"))
2678 };
2679 let composer = bounds_of(COMPOSER_BOX_TAG);
2680 let input = bounds_of(COMPOSER_INPUT_TAG);
2681 let actions = bounds_of(COMPOSER_ACTIONS_TAG);
2682 let send = bounds_of(COMPOSER_SEND_TAG);
2683 [
2684 f32::from(input.left() - composer.left()),
2685 f32::from(actions.top() - composer.top()),
2686 f32::from(composer.bottom() - actions.bottom()),
2687 f32::from(composer.right() - send.right()),
2688 f32::from(send.top() - composer.top()),
2689 f32::from(composer.bottom() - send.bottom()),
2690 ]
2691 }
2692
2693 #[gpui_kit::test]
2694 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
2695 let (handle, _) = mount(cx);
2696 let mut visual = VisualTestContext::from_window(handle, cx);
2697 visual.simulate_resize(size(px(1280.), px(800.)));
2698 let single_line = composer_button_insets(&mut visual);
2699 let left = single_line[0];
2700 assert!(
2701 single_line
2702 .iter()
2703 .all(|inset| (inset - left).abs() < TOLERANCE),
2704 "single line: insets of the input left, the actions top and bottom, send right, top and bottom {single_line:?}"
2705 );
2706 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2707 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
2708 visual.simulate_click(point(input.center().x, send.center().y), Default::default());
2709 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
2710 let three_lines = composer_button_insets(&mut visual);
2711 assert!(
2712 three_lines[1] > single_line[1] + 30.,
2713 "three lines did not grow the composer: {three_lines:?}"
2714 );
2715 for inset in [
2716 three_lines[0],
2717 three_lines[2],
2718 three_lines[3],
2719 three_lines[5],
2720 ] {
2721 assert!(
2722 (inset - left).abs() < TOLERANCE,
2723 "three lines: insets of the input left, the actions top and bottom, send right, top and bottom {three_lines:?}, expected {left}"
2724 );
2725 }
2726 }
2727
2728 #[gpui_kit::test]
2729 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
2730 const FORMAT_TAGS: [&str; 6] = [
2731 COMPOSER_BOX_TAG,
2732 COMPOSER_FORMAT_BAR_TAG,
2733 COMPOSER_FORMAT_DIVIDER_TAG,
2734 COMPOSER_ACTIONS_TAG,
2735 COMPOSER_FORMAT_TAG,
2736 COMPOSER_SEND_TAG,
2737 ];
2738 let (handle, _) = mount(cx);
2739 let mut visual = VisualTestContext::from_window(handle, cx);
2740 for (width, height) in SIZES {
2741 visual.simulate_resize(size(px(width), px(height)));
2742 let window = Bounds {
2743 origin: point(px(0.), px(0.)),
2744 size: size(px(width), px(height)),
2745 };
2746 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
2747 let toggle = visual
2748 .debug_bounds(COMPOSER_FORMAT_TAG)
2749 .expect("format button");
2750 visual.simulate_click(toggle.center(), Default::default());
2751 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
2752 let tags: Vec<Tag> = FORMAT_TAGS
2753 .iter()
2754 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2755 .collect();
2756 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
2757 .into_iter()
2758 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
2759 .collect();
2760 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
2761 let actions = visual.debug_bounds(COMPOSER_ACTIONS_TAG).expect("actions");
2762 let toggle = visual
2763 .debug_bounds(COMPOSER_FORMAT_TAG)
2764 .expect("format button");
2765 visual.simulate_click(toggle.center(), Default::default());
2766 collect(&mut visual, None);
2767 assert!(found.is_empty(), "{}", found.join("\n"));
2768 assert!(
2769 bar.bottom() <= actions.top(),
2770 "bar {bar:?} over the buttons {actions:?}"
2771 );
2772 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
2773 }
2774 }
2775
2776 #[gpui_kit::test]
2777 fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2778 let (handle, _) = mount_with(cx, true);
2779 let mut visual = VisualTestContext::from_window(handle, cx);
2780 visual.dispatch_action(OpenActivity);
2781 for (width, height) in SIZES {
2782 visual.simulate_resize(size(px(width), px(height)));
2783 let window = Bounds {
2784 origin: point(px(0.), px(0.)),
2785 size: size(px(width), px(height)),
2786 };
2787 let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2788 let mut expected = GUARDED.to_vec();
2789 expected.push(ACTIVITY_PROPOSALS_TAG);
2790 let found: Vec<String> = violations(&tags, window, &expected)
2791 .into_iter()
2792 .map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2793 .collect();
2794 assert!(found.is_empty(), "{}", found.join("\n"));
2795 }
2796 }
2797
2798 #[gpui_kit::test]
2799 fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2800 const DELIVERY_TAGS: [&str; 5] = [
2801 COMPOSER_BOX_TAG,
2802 COMPOSER_ACTIONS_TAG,
2803 COMPOSER_PLUS_TAG,
2804 COMPOSER_IMPORTANCE_LABEL_TAG,
2805 COMPOSER_URGENT_BANNER_TAG,
2806 ];
2807 const URGENT_OPTION: &str = "urgent-delivery-option";
2808 const TEXT_INSET: f32 = 6.;
2809 let (handle, _) = mount(cx);
2810 let mut visual = VisualTestContext::from_window(handle, cx);
2811 for (width, height) in SIZES {
2812 visual.simulate_resize(size(px(width), px(height)));
2813 let window = Bounds {
2814 origin: point(px(0.), px(0.)),
2815 size: size(px(width), px(height)),
2816 };
2817 collect(&mut visual, Some(COMPOSER_PLUS_TAG));
2818 let button = visual.debug_bounds(COMPOSER_PLUS_TAG).expect("plus button");
2819 visual.simulate_click(button.center(), Default::default());
2820 let delivery_tag = PlusAction::DeliveryOptions.tag();
2821 collect(&mut visual, Some(delivery_tag));
2822 let delivery = visual.debug_bounds(delivery_tag).expect("delivery item");
2823 visual.simulate_click(delivery.center(), Default::default());
2824 collect(&mut visual, Some(URGENT_OPTION));
2825 let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2826 assert!(
2827 contains(window, menu),
2828 "menu {} leaves the window",
2829 describe(menu)
2830 );
2831 let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2832 visual.simulate_click(urgent.center(), Default::default());
2833 collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2834 assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2835 let tags: Vec<Tag> = DELIVERY_TAGS
2836 .iter()
2837 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2838 .collect();
2839 let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2840 .into_iter()
2841 .map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2842 .collect();
2843 assert!(found.is_empty(), "{}", found.join("\n"));
2844 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2845 let banner = visual
2846 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2847 .expect("banner");
2848 let label = visual
2849 .debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2850 .expect("label");
2851 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2852 assert!(
2853 (f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2854 && (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2855 "banner {} not on the composer edges {}",
2856 describe(banner),
2857 describe(composer)
2858 );
2859 assert!(
2860 banner.bottom() <= composer.top(),
2861 "banner {} over the composer {}",
2862 describe(banner),
2863 describe(composer)
2864 );
2865 assert!(
2866 (inset(composer, label, Edge::Left)
2867 - inset(composer, input, Edge::Left)
2868 - TEXT_INSET)
2869 .abs()
2870 <= TOLERANCE,
2871 "label {} not on the text edge of {}",
2872 describe(label),
2873 describe(input)
2874 );
2875 let close = visual
2876 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2877 .map(|banner| point(banner.right() - px(18.), banner.center().y))
2878 .expect("banner");
2879 visual.simulate_click(close, Default::default());
2880 collect(&mut visual, None);
2881 assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
2882 assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
2883 }
2884 }
2885
2886 #[gpui_kit::test]
2887 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
2888 let (handle, state) = mount_with(cx, true);
2889 let mut visual = VisualTestContext::from_window(handle, cx);
2890 for (width, height) in SIZES {
2891 visual.simulate_resize(size(px(width), px(height)));
2892 for chat in IMPORTANCE_CHATS {
2893 visual.update(|_, cx| {
2894 state.update(cx, |state, cx| {
2895 state.select(Selection::Chat(chat.to_owned()), cx)
2896 })
2897 });
2898 collect(&mut visual, Some(TIMELINE_TAG));
2899 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2900 visual.simulate_event(ScrollWheelEvent {
2901 position: timeline.center(),
2902 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
2903 ..Default::default()
2904 });
2905 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
2906 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
2907 let bubble = BUBBLE_TAGS
2908 .iter()
2909 .filter_map(|tag| visual.debug_bounds(tag))
2910 .find(|bubble| contains(*bubble, label))
2911 .unwrap_or_else(|| {
2912 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
2913 });
2914 let left = inset(bubble, label, Edge::Left);
2915 let top = inset(bubble, label, Edge::Top);
2916 assert!(
2917 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2918 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
2919 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2920 describe(bubble)
2921 );
2922 }
2923 }
2924 }
2925
2926 #[gpui_kit::test]
2927 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2928 let (handle, state) = mount_with(cx, true);
2929 let mut visual = VisualTestContext::from_window(handle, cx);
2930 for (width, height) in SIZES {
2931 visual.simulate_resize(size(px(width), px(height)));
2932 let window = Bounds {
2933 origin: point(px(0.), px(0.)),
2934 size: size(px(width), px(height)),
2935 };
2936 for (chat, expected_tags) in [
2937 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
2938 (REACTION_CHAT, &AGENT_TAGS[3..]),
2939 ] {
2940 visual.update(|_, cx| {
2941 state.update(cx, |state, cx| {
2942 state.select(Selection::Chat(chat.to_owned()), cx)
2943 })
2944 });
2945 let tags = collect(&mut visual, Some(expected_tags[0]));
2946 let mut expected = GUARDED.to_vec();
2947 expected.extend(expected_tags);
2948 let found: Vec<String> = violations(&tags, window, &expected)
2949 .into_iter()
2950 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
2951 .collect();
2952 assert!(found.is_empty(), "{}", found.join("\n"));
2953 }
2954 }
2955 }
2956}
2957
2958#[test]
2959fn lines_are_solid() {
2960 let mut files = Vec::new();
2961 for root in source_roots() {
2962 source_files(&root, &mut files);
2963 }
2964 let violations: Vec<String> = files
2965 .iter()
2966 .filter(|file| !file.ends_with("layout_guard.rs"))
2967 .flat_map(|file| {
2968 let source = fs::read_to_string(file).expect("read source file");
2969 source
2970 .lines()
2971 .enumerate()
2972 .filter(|(_, line)| {
2973 line.contains(".border_dashed(") || line.contains(".border_dotted(")
2974 })
2975 .map(|(index, line)| {
2976 format!(
2977 "{}:{}: lines are always solid: {}",
2978 file.display(),
2979 index + 1,
2980 line.trim()
2981 )
2982 })
2983 .collect::<Vec<_>>()
2984 })
2985 .collect();
2986 assert!(violations.is_empty(), "{}", violations.join("\n"));
2987}
2988
2989const STATE_RING_COLORS: &[&str] = &[
2990 "if focused",
2991 "if selected",
2992 "if speaking",
2993 "if current",
2994 "if open",
2995 "if state.failed",
2996];
2997const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
2998 (
2999 "notify/ring_view.rs",
3000 "theme::green()",
3001 "state signal (pulsing ring around the caller while it rings), not a resting outline",
3002 ),
3003 (
3004 "settings/mcp.rs",
3005 "theme::border_strong()",
3006 "outlined button, not a surface",
3007 ),
3008 (
3009 "settings/rows.rs",
3010 "theme::border_strong()",
3011 "outlined button, not a surface",
3012 ),
3013 (
3014 "views/card_widgets.rs",
3015 "border)",
3016 "message content drawn as Teams renders it",
3017 ),
3018 (
3019 "views/card_widgets.rs",
3020 "theme::border_strong()",
3021 "message content drawn as Teams renders it",
3022 ),
3023 ("views/shared_tab.rs", "theme::accent()", "input field"),
3024 ("views/card_input.rs", "if error.is_some()", "input field"),
3025 ("views/format_toolbar.rs", "if refused", "input field"),
3026 (
3027 "views/card_code_block.rs",
3028 "theme::code_header_border()",
3029 "message content drawn as Teams renders it",
3030 ),
3031 (
3032 "render/elements.rs",
3033 "theme::code_frame()",
3034 "message content drawn as Teams renders it",
3035 ),
3036 ("views/call_transcript.rs", "theme::border()", "input field"),
3037 (
3038 "views/conversation.rs",
3039 "theme::accent()",
3040 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3041 ),
3042 (
3043 "views/attachment_tray.rs",
3044 "theme::accent()",
3045 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3046 ),
3047 (
3048 "views/card_carousel.rs",
3049 "theme::border_strong()",
3050 "message content drawn as Teams renders it",
3051 ),
3052 (
3053 "views/card_table.rs",
3054 "grid_color",
3055 "message content drawn as Teams renders it",
3056 ),
3057 (
3058 "views/activity_panel.rs",
3059 "theme::surface()",
3060 "cutout ring in the background color, invisible against its surface",
3061 ),
3062 (
3063 "views/avatar.rs",
3064 "theme::surface()",
3065 "cutout ring in the background color, invisible against its surface",
3066 ),
3067 (
3068 "views/message_row.rs",
3069 "theme::border_strong()",
3070 "deleted message placeholder, Teams look",
3071 ),
3072 (
3073 "views/message_row.rs",
3074 "theme::red()",
3075 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3076 ),
3077 (
3078 "views/message_row.rs",
3079 "if row.delivery",
3080 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3081 ),
3082 (
3083 "views/new_meeting_dialog.rs",
3084 "theme::border()",
3085 "input field",
3086 ),
3087 (
3088 "views/call_mini_window.rs",
3089 "theme::border_strong()",
3090 "self view over live video, needs an edge on any picture",
3091 ),
3092 ("views/transfer_picker.rs", "theme::border()", "input field"),
3093 (
3094 "views/call_notice.rs",
3095 "theme::border_strong()",
3096 "outlined button, not a surface",
3097 ),
3098 (
3099 "views/composer/schedule.rs",
3100 "theme::accent()",
3101 "input field",
3102 ),
3103 (
3104 "views/sidebar.rs",
3105 "theme::accent()",
3106 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3107 ),
3108 (
3109 "views/adaptive_card.rs",
3110 "theme::border()",
3111 "message content drawn as Teams renders it",
3112 ),
3113 (
3114 "views/adaptive_card.rs",
3115 "border)",
3116 "message content drawn as Teams renders it",
3117 ),
3118 (
3119 "views/share_bar.rs",
3120 "theme::red()",
3121 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
3122 ),
3123 ("settings_controls.rs", "if invalid", "input field"),
3124];
3125
3126fn outlines(source: &str) -> Vec<(usize, String)> {
3127 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
3128 pattern
3129 .find_iter(source)
3130 .map(|found| {
3131 let line_number = source[..found.start()].matches('\n').count() + 1;
3132 let after = &source[found.end()..];
3133 let color = after
3134 .find(".border_color(")
3135 .filter(|position| *position < 120)
3136 .map(|position| {
3137 let start = &after[position + ".border_color(".len()..];
3138 start
3139 .lines()
3140 .map(str::trim)
3141 .find(|line| !line.is_empty())
3142 .unwrap_or_default()
3143 .to_owned()
3144 })
3145 .unwrap_or_default();
3146 (line_number, color)
3147 })
3148 .collect()
3149}
3150
3151#[test]
3152fn outline_matcher_reads_the_border_color() {
3153 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
3154 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
3155}
3156
3157#[test]
3158fn surfaces_are_soft() {
3159 let mut matched_allowlist = HashSet::new();
3160 let mut violations = Vec::new();
3161 for root in source_roots() {
3162 let mut files = Vec::new();
3163 source_files(&root, &mut files);
3164 for file in files {
3165 let relative = file
3166 .strip_prefix(&root)
3167 .expect("inside src")
3168 .to_string_lossy()
3169 .replace('\\', "/");
3170 if relative == "layout_guard.rs" {
3171 continue;
3172 }
3173 let source = fs::read_to_string(&file).expect("read source file");
3174 for (line_number, color) in outlines(&source) {
3175 if STATE_RING_COLORS
3176 .iter()
3177 .any(|prefix| color.starts_with(prefix))
3178 {
3179 continue;
3180 }
3181 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
3182 *allowed_file == relative && color.starts_with(prefix)
3183 }) {
3184 Some(position) => {
3185 matched_allowlist.insert(position);
3186 }
3187 None => violations.push(format!(
3188 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
3189 )),
3190 }
3191 }
3192 }
3193 }
3194 let stale = OUTLINE_ALLOWLIST
3195 .iter()
3196 .enumerate()
3197 .filter(|(position, _)| !matched_allowlist.contains(position))
3198 .map(|(_, (file, prefix, _))| {
3199 format!("stale outline allowlist entry, remove it: {file} {prefix}")
3200 });
3201 let report: Vec<String> = violations.into_iter().chain(stale).collect();
3202 assert!(report.is_empty(), "{}", report.join("\n"));
3203}
3204
3205fn indentation(line: &str) -> usize {
3206 line.len() - line.trim_start().len()
3207}
3208
3209fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
3210 let indent = indentation(lines[index]);
3211 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
3212 let start = lines[..index]
3213 .iter()
3214 .rposition(|line| !belongs(line))
3215 .map_or(0, |position| position + 1);
3216 let end = lines[index..]
3217 .iter()
3218 .position(|line| !belongs(line))
3219 .map_or(lines.len(), |position| index + position);
3220 lines[start..end]
3221 .iter()
3222 .filter(|line| indentation(line) == indent)
3223 .copied()
3224 .collect()
3225}
3226
3227fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
3228 let lines: Vec<&str> = source.lines().collect();
3229 (0..lines.len())
3230 .filter(|&index| row_height.is_match(lines[index]))
3231 .filter(|&index| {
3232 !chain_lines(&lines, index).iter().any(|line| {
3233 let line = line.trim();
3234 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
3235 })
3236 })
3237 .map(|index| index + 1)
3238 .collect()
3239}
3240
3241fn row_height_pattern() -> Regex {
3242 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
3243}
3244
3245#[test]
3246fn matcher_finds_rows_without_flex_none() {
3247 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";
3248 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
3249}
3250
3251#[test]
3252fn fixed_height_rows_never_shrink() {
3253 let row_height = row_height_pattern();
3254 let mut files = Vec::new();
3255 for root in source_roots() {
3256 source_files(&root, &mut files);
3257 }
3258 let violations: Vec<String> = files
3259 .iter()
3260 .filter(|file| !file.ends_with("layout_guard.rs"))
3261 .flat_map(|file| {
3262 let source = fs::read_to_string(file).expect("read source file");
3263 shrinking_rows(&row_height, &source)
3264 .into_iter()
3265 .map(|line| format!("{}:{line}", file.display()))
3266 .collect::<Vec<_>>()
3267 })
3268 .collect();
3269 assert!(
3270 violations.is_empty(),
3271 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
3272 );
3273}