BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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