BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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