BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 111.3 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 #[gpui_kit::test]
1340 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1341 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1342 }
1343
1344 #[gpui_kit::test]
1345 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1346 crate::theme::set_thread_scheme(Some("teams"));
1347 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1348 crate::theme::set_thread_scheme(None);
1349 }
1350
1351 #[gpui_kit::test]
1352 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1353 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1354 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1355 crate::theme::set_thread_shade(None);
1356 }
1357
1358 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1359 let (handle, state) = mount_with(cx, true);
1360 let mut visual = VisualTestContext::from_window(handle, cx);
1361 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1362 visual.simulate_resize(size(px(width), px(height)));
1363 let window = Bounds {
1364 origin: point(px(0.), px(0.)),
1365 size: size(px(width), px(height)),
1366 };
1367 let inset = metrics(width, height).inset;
1368 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1369 for &section in sections {
1370 visual
1371 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1372 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1373 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1374 .into_iter()
1375 .filter(|(key, _)| key.starts_with("settings"))
1376 .chain(inset_violations(&tags, INSET_RULES))
1377 .collect();
1378 if label_sizes {
1379 found.extend(nav_label_violations(&mut visual));
1380 }
1381 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1382 .iter()
1383 .any(|(exempt, _)| *exempt == section);
1384 if !scrolled_exempt {
1385 found.extend(scrolled_inset_violation(&mut visual));
1386 }
1387 let found: Vec<String> = found
1388 .into_iter()
1389 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1390 .collect();
1391 assert!(found.is_empty(), "{}", found.join("\n"));
1392 let dialog = visual
1393 .debug_bounds(SETTINGS_TAGS[0])
1394 .expect("settings dialog");
1395 let edges = [
1396 f32::from(dialog.left()),
1397 f32::from(dialog.top()),
1398 width - f32::from(dialog.right()),
1399 height - f32::from(dialog.bottom()),
1400 ];
1401 assert!(
1402 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1403 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1404 );
1405 }
1406 }
1407 }
1408
1409 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1410
1411 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1412 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1413 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1414 };
1415 let mut found = Vec::new();
1416 for section in SETTINGS_SECTIONS {
1417 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1418 let item_path: &'static str = if section == SettingsSection::About {
1419 SETTINGS_NAV_ABOUT
1420 } else {
1421 Box::leak(item_selector(section).into_boxed_str())
1422 };
1423 let (Some(label_bounds), Some(item)) = (
1424 visual.debug_bounds(label_path),
1425 visual.debug_bounds(item_path),
1426 ) else {
1427 if section != SettingsSection::Agents {
1428 found.push((label_path.to_owned(), "not rendered".to_owned()));
1429 }
1430 continue;
1431 };
1432 let text = label(section);
1433 let text_width = visual.update(|window, _| {
1434 let run = window.text_style().to_run(text.len());
1435 f32::from(
1436 window
1437 .text_system()
1438 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1439 .width,
1440 )
1441 });
1442 let label_width = f32::from(label_bounds.size.width);
1443 let label_height = f32::from(label_bounds.size.height);
1444 if text_width > label_width + TOLERANCE
1445 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1446 {
1447 found.push((
1448 label_path.to_owned(),
1449 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1450 ));
1451 }
1452 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1453 inner.left() < outer.left() - px(TOLERANCE)
1454 || inner.right() > outer.right() + px(TOLERANCE)
1455 || inner.top() < outer.top() - px(TOLERANCE)
1456 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1457 };
1458 if outside(label_bounds, item) {
1459 found.push((
1460 label_path.to_owned(),
1461 format!("label {label_bounds:?} outside item {item:?}"),
1462 ));
1463 }
1464 if item.left() < nav.left() || item.right() > nav.right() {
1465 found.push((
1466 item_path.to_owned(),
1467 format!("item {item:?} outside nav {nav:?}"),
1468 ));
1469 }
1470 }
1471 found
1472 }
1473
1474 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1475 let body = visual.debug_bounds(SETTINGS_BODY)?;
1476 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1477 if content.bottom() <= body.bottom() {
1478 return None;
1479 }
1480 visual.simulate_event(ScrollWheelEvent {
1481 position: body.center(),
1482 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1483 ..Default::default()
1484 });
1485 collect(visual, None);
1486 let body = visual.debug_bounds(SETTINGS_BODY)?;
1487 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1488 inset_violation(&SCROLLED_INSET_RULE, body, content)
1489 }
1490
1491 #[gpui_kit::test]
1492 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1493 let (handle, state) = mount(cx);
1494 let mut visual = VisualTestContext::from_window(handle, cx);
1495 for (width, height) in SIZES {
1496 visual.simulate_resize(size(px(width), px(height)));
1497 let window = Bounds {
1498 origin: point(px(0.), px(0.)),
1499 size: size(px(width), px(height)),
1500 };
1501 visual.update(|_, cx| {
1502 state.update(cx, |state, cx| {
1503 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1504 })
1505 });
1506 collect(&mut visual, Some(MEMBERS_BUTTON));
1507 let button = visual
1508 .debug_bounds(MEMBERS_BUTTON)
1509 .expect("members button rendered");
1510 visual.simulate_click(button.center(), Default::default());
1511 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1512 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1513 .into_iter()
1514 .filter(|(key, _)| key.starts_with("chat-members"))
1515 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1516 .collect();
1517 visual.simulate_keystrokes("escape");
1518 visual.run_until_parked();
1519 assert!(found.is_empty(), "{}", found.join("\n"));
1520 }
1521 }
1522
1523 const FORWARD_CHAT: &str = "demo-chat-release";
1524 const FORWARD_FOOTER_TAGS: [&str; 4] = [
1525 FORWARD_FOOTER_TAG,
1526 FORWARD_FOOTER_BAR_TAG,
1527 FORWARD_FOOTER_COUNT_TAG,
1528 FORWARD_FOOTER_NEXT_TAG,
1529 ];
1530 const FORWARD_DIALOG_PADDING: f32 = 16.;
1531 const FORWARD_BAR_PADDING: f32 = 8.;
1532 const FORWARD_ROWS_SCANNED: usize = 80;
1533
1534 fn forward_message_ids(
1535 state: &Entity<AppState>,
1536 visual: &mut VisualTestContext,
1537 ) -> Vec<String> {
1538 visual.update(|_, cx| {
1539 let mut records = state
1540 .read(cx)
1541 .store
1542 .messages(FORWARD_CHAT, None, 50)
1543 .expect("demo messages");
1544 records.retain(|record| !record.deleted);
1545 records.sort_by_key(|record| record.created_at);
1546 records
1547 .iter()
1548 .rev()
1549 .take(2)
1550 .map(|record| record.message_id.clone())
1551 .collect()
1552 })
1553 }
1554
1555 #[gpui_kit::test]
1556 fn forward_selection_footer_checks_and_dialog_keep_their_insets(cx: &mut TestAppContext) {
1557 let (handle, state) = mount(cx);
1558 let mut visual = VisualTestContext::from_window(handle, cx);
1559 for (width, height) in SIZES {
1560 visual.simulate_resize(size(px(width), px(height)));
1561 let window = Bounds {
1562 origin: point(px(0.), px(0.)),
1563 size: size(px(width), px(height)),
1564 };
1565 visual.update(|_, cx| {
1566 state.update(cx, |state, cx| {
1567 state.select(Selection::Chat(FORWARD_CHAT.to_owned()), cx)
1568 })
1569 });
1570 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1571 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
1572 let ids = forward_message_ids(&state, &mut visual);
1573 visual.update(|_, cx| {
1574 state.update(cx, |state, cx| {
1575 state.start_forward_selection(FORWARD_CHAT, &ids[0], cx);
1576 state.toggle_forward_selected(&ids[1], cx);
1577 })
1578 });
1579 collect(&mut visual, Some(FORWARD_FOOTER_NEXT_TAG));
1580 assert!(
1581 visual.debug_bounds(COMPOSER_BOX_TAG).is_none(),
1582 "the footer replaces the composer"
1583 );
1584 let tags: Vec<Tag> = FORWARD_FOOTER_TAGS
1585 .iter()
1586 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1587 .collect();
1588 let mut found: Vec<String> = violations(&tags, window, &FORWARD_FOOTER_TAGS)
1589 .into_iter()
1590 .map(|(key, message)| format!("forward@{width}x{height}:{key}: {message}"))
1591 .collect();
1592 let main = visual.debug_bounds(MAIN).expect("main island");
1593 let bar = visual.debug_bounds(FORWARD_FOOTER_BAR_TAG).expect("bar");
1594 let next = visual.debug_bounds(FORWARD_FOOTER_NEXT_TAG).expect("next");
1595 if (f32::from(bar.left() - composer.left())).abs() > TOLERANCE
1596 || (f32::from(bar.right() - composer.right())).abs() > TOLERANCE
1597 {
1598 found.push(format!(
1599 "forward@{width}x{height}: bar {} not on the composer edges {}",
1600 describe(bar),
1601 describe(composer)
1602 ));
1603 }
1604 for edge in [Edge::Top, Edge::Right, Edge::Bottom] {
1605 let gap = inset(bar, next, edge);
1606 if (gap - FORWARD_BAR_PADDING).abs() > TOLERANCE {
1607 found.push(format!(
1608 "forward@{width}x{height}: next button {edge:?} inset {gap} != {FORWARD_BAR_PADDING}"
1609 ));
1610 }
1611 }
1612 let checks: Vec<Bounds<Pixels>> = (0..FORWARD_ROWS_SCANNED)
1613 .filter_map(|index| {
1614 visual.debug_bounds(Box::leak(select_box_selector(index).into_boxed_str()))
1615 })
1616 .filter(|check| contains(main, *check))
1617 .collect();
1618 if checks.is_empty() {
1619 found.push(format!("forward@{width}x{height}: no checkbox rendered"));
1620 }
1621 let expected_left = ROW_PADDING + runway_margin(f32::from(main.size.width));
1622 for check in &checks {
1623 let left = inset(main, *check, Edge::Left);
1624 if (left - expected_left).abs() > TOLERANCE {
1625 found.push(format!(
1626 "forward@{width}x{height}: checkbox {} starts {left} from the island, not {expected_left}",
1627 describe(*check)
1628 ));
1629 }
1630 }
1631 visual.simulate_click(next.center(), Default::default());
1632 collect(&mut visual, Some(FORWARD_PREVIEW_TAG));
1633 let card = visual.debug_bounds(FORWARD_CARD_TAG).expect("dialog card");
1634 let preview = visual.debug_bounds(FORWARD_PREVIEW_TAG).expect("preview");
1635 if !contains(window, card) || !contains(card, preview) {
1636 found.push(format!(
1637 "forward@{width}x{height}: dialog {} or preview {} clipped",
1638 describe(card),
1639 describe(preview)
1640 ));
1641 }
1642 let (left, right) = (
1643 inset(card, preview, Edge::Left),
1644 inset(card, preview, Edge::Right),
1645 );
1646 if (left - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1647 || (right - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1648 {
1649 found.push(format!(
1650 "forward@{width}x{height}: preview insets {left}/{right} != {FORWARD_DIALOG_PADDING}"
1651 ));
1652 }
1653 visual.simulate_keystrokes("escape");
1654 collect(&mut visual, None);
1655 assert!(visual.debug_bounds(FORWARD_CARD_TAG).is_none());
1656 assert!(
1657 visual.debug_bounds(FORWARD_FOOTER_TAG).is_some(),
1658 "closing the dialog keeps the selection"
1659 );
1660 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_forward_selection(cx)));
1661 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1662 assert!(visual.debug_bounds(FORWARD_FOOTER_TAG).is_none());
1663 assert!(found.is_empty(), "{}", found.join("\n"));
1664 }
1665 }
1666
1667 const MENU_ITEMS_SCANNED: usize = 40;
1668 const MENU_CHAT: &str = "demo-chat-release";
1669 const THEME_SELECT: &str = "settings-theme";
1670
1671 struct MenuRow {
1672 index: usize,
1673 item: Bounds<Pixels>,
1674 icon: Option<Bounds<Pixels>>,
1675 label: Option<Bounds<Pixels>>,
1676 }
1677
1678 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1679 (0..MENU_ITEMS_SCANNED)
1680 .filter_map(|index| {
1681 let item =
1682 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1683 Some(MenuRow {
1684 index,
1685 item,
1686 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1687 label: visual
1688 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1689 })
1690 })
1691 .collect()
1692 }
1693
1694 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1695 let mut found = Vec::new();
1696 for row in rows {
1697 let Some(icon) = row.icon else {
1698 continue;
1699 };
1700 let key = format!("{MENU}/item-{}", row.index);
1701 if let Some(label) = row.label {
1702 let gap = f32::from(label.left() - icon.right());
1703 if (gap - expected_gap).abs() > TOLERANCE {
1704 found.push((
1705 format!("{key}:icon-gap"),
1706 format!(
1707 "icon {} to label {} is {gap} px, expected {expected_gap}",
1708 describe(icon),
1709 describe(label)
1710 ),
1711 ));
1712 }
1713 }
1714 let offset = f32::from(icon.center().y - row.item.center().y);
1715 if offset.abs() > TOLERANCE {
1716 found.push((
1717 format!("{key}:icon-off-centre"),
1718 format!(
1719 "icon {} sits {offset} px off the centre of item {}",
1720 describe(icon),
1721 describe(row.item)
1722 ),
1723 ));
1724 }
1725 }
1726 found
1727 }
1728
1729 fn listbox_violations(
1730 trigger: Bounds<Pixels>,
1731 menu: Bounds<Pixels>,
1732 items: Bounds<Pixels>,
1733 rows: &[MenuRow],
1734 ) -> Vec<(String, String)> {
1735 let mut found = Vec::new();
1736 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1737 if !near(f32::from(menu.left() - trigger.left()), 0.) {
1738 found.push((
1739 format!("{MENU}:not-aligned-to-trigger"),
1740 format!(
1741 "list {} must start at the trigger's left edge {}",
1742 describe(menu),
1743 describe(trigger)
1744 ),
1745 ));
1746 }
1747 if !near(
1748 f32::from(menu.top() - trigger.bottom()),
1749 f32::from(DROPDOWN_OFFSET),
1750 ) {
1751 found.push((
1752 format!("{MENU}:trigger-offset"),
1753 format!(
1754 "list {} must open {} px below the trigger {}",
1755 describe(menu),
1756 f32::from(DROPDOWN_OFFSET),
1757 describe(trigger)
1758 ),
1759 ));
1760 }
1761 if menu.size.width < trigger.size.width - px(TOLERANCE) {
1762 found.push((
1763 format!("{MENU}:narrower-than-trigger"),
1764 format!(
1765 "list {} is narrower than the trigger {}",
1766 describe(menu),
1767 describe(trigger)
1768 ),
1769 ));
1770 }
1771 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1772 let top = f32::from(first.item.top() - items.top());
1773 let bottom = f32::from(items.bottom() - last.item.bottom());
1774 let padding = f32::from(MENU_LIST_PADDING);
1775 if !near(top, padding) || !near(bottom, padding) {
1776 found.push((
1777 format!("{MENU}:uneven-padding"),
1778 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1779 ));
1780 }
1781 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1782 match first.icon {
1783 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1784 check => found.push((
1785 format!("{MENU}:check-inset"),
1786 format!(
1787 "check column {check:?} must start {expected_inset} px inside the list {}",
1788 describe(menu)
1789 ),
1790 )),
1791 }
1792 }
1793 found
1794 }
1795
1796 #[test]
1797 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
1798 let row =
1799 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
1800 index,
1801 item: rectangle(4., item_top, 120., 32.),
1802 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
1803 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
1804 };
1805 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
1806 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
1807 .into_iter()
1808 .map(|(key, _)| key)
1809 .collect();
1810 assert_eq!(
1811 keys,
1812 [
1813 "popup-menu/item-1:icon-gap",
1814 "popup-menu/item-1:icon-off-centre"
1815 ]
1816 );
1817
1818 let trigger = rectangle(100., 50., 216., 32.);
1819 let option = |index: usize, top: f32| MenuRow {
1820 index,
1821 item: rectangle(104., top, 208., 32.),
1822 icon: Some(rectangle(110., top + 8., 16., 16.)),
1823 label: Some(rectangle(132., top + 6., 80., 20.)),
1824 };
1825 let aligned = [option(0, 88.), option(1, 122.)];
1826 let menu = rectangle(100., 84., 216., 74.);
1827 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
1828 let shifted = rectangle(96., 90., 200., 80.);
1829 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
1830 .into_iter()
1831 .map(|(key, _)| key)
1832 .collect();
1833 assert_eq!(
1834 keys,
1835 [
1836 "popup-menu:not-aligned-to-trigger",
1837 "popup-menu:trigger-offset",
1838 "popup-menu:narrower-than-trigger",
1839 "popup-menu:uneven-padding",
1840 "popup-menu:check-inset",
1841 ]
1842 );
1843 }
1844
1845 #[gpui_kit::test]
1846 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
1847 let (handle, _) = mount(cx);
1848 let mut visual = VisualTestContext::from_window(handle, cx);
1849 visual.simulate_resize(size(px(1280.), px(800.)));
1850 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
1851 collect(&mut visual, Some(chat_row));
1852 let mut found = Vec::new();
1853 let own_status = visual
1854 .debug_bounds(OWN_STATUS)
1855 .expect("own status button rendered");
1856 visual.simulate_click(own_status.center(), Default::default());
1857 collect(&mut visual, Some(MENU));
1858 let status_rows = menu_rows(&mut visual);
1859 assert!(
1860 status_rows.iter().any(|row| row.icon.is_some()),
1861 "status menu shows icons"
1862 );
1863 found.extend(menu_row_violations(
1864 &status_rows,
1865 f32::from(MENU_ICON_LABEL_GAP),
1866 ));
1867 visual.simulate_keystrokes("escape");
1868 collect(&mut visual, None);
1869 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
1870 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
1871 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
1872 collect(&mut visual, Some(MENU));
1873 let chat_rows = menu_rows(&mut visual);
1874 assert!(
1875 chat_rows.iter().any(|row| row.icon.is_some()),
1876 "chat menu shows icons"
1877 );
1878 found.extend(menu_row_violations(
1879 &chat_rows,
1880 f32::from(MENU_ICON_LABEL_GAP),
1881 ));
1882 let found: Vec<String> = found
1883 .into_iter()
1884 .map(|(key, message)| format!("{key}: {message}"))
1885 .collect();
1886 assert!(found.is_empty(), "{}", found.join("\n"));
1887 }
1888
1889 #[gpui_kit::test]
1890 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
1891 let (handle, state) = mount(cx);
1892 let mut visual = VisualTestContext::from_window(handle, cx);
1893 visual.simulate_resize(size(px(1280.), px(800.)));
1894 visual.update(|_, cx| {
1895 state.update(cx, |state, cx| {
1896 state.open_settings(SettingsSection::Appearance, cx)
1897 })
1898 });
1899 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
1900 collect(&mut visual, Some(select));
1901 let trigger = visual.debug_bounds(select).expect("theme select rendered");
1902 visual.simulate_click(trigger.center(), Default::default());
1903 collect(&mut visual, Some(MENU));
1904 let menu = visual.debug_bounds(MENU).expect("list rendered");
1905 let items = visual
1906 .debug_bounds(ITEMS_SELECTOR)
1907 .expect("list items rendered");
1908 let rows = menu_rows(&mut visual);
1909 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
1910 .into_iter()
1911 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
1912 .map(|(key, message)| format!("{key}: {message}"))
1913 .collect();
1914 assert!(found.is_empty(), "{}", found.join("\n"));
1915 }
1916
1917 const BADGE_SAMPLES: [(u32, bool); 5] =
1918 [(1, false), (42, false), (120, false), (7, true), (15, true)];
1919
1920 struct BadgeSamples;
1921
1922 impl gpui_kit::Render for BadgeSamples {
1923 fn render(
1924 &mut self,
1925 _: &mut gpui_kit::Window,
1926 _: &mut gpui_kit::Context<Self>,
1927 ) -> impl gpui_kit::IntoElement {
1928 use gpui_kit::{ParentElement as _, Styled as _};
1929 gpui_kit::div()
1930 .flex()
1931 .gap(px(12.))
1932 .p(px(12.))
1933 .children(BADGE_SAMPLES.map(|(count, rail)| {
1934 if rail {
1935 badge_pill(
1936 count,
1937 RAIL_BADGE,
1938 crate::theme::accent(),
1939 crate::theme::on_accent(),
1940 )
1941 } else {
1942 count_badge(count, false)
1943 }
1944 }))
1945 }
1946 }
1947
1948 fn badge_violation(
1949 text: &str,
1950 pill: Bounds<Pixels>,
1951 label: Bounds<Pixels>,
1952 ink_offset: (f32, f32),
1953 ) -> Option<(String, String)> {
1954 let ink_x = f32::from(label.center().x) + ink_offset.0;
1955 let ink_y = f32::from(label.center().y) + ink_offset.1;
1956 let off_x = ink_x - f32::from(pill.center().x);
1957 let off_y = ink_y - f32::from(pill.center().y);
1958 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
1959 (
1960 format!("count-badge/{text}:off-centre"),
1961 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
1962 )
1963 })
1964 }
1965
1966 #[test]
1967 fn badge_rule_flags_off_centre_text() {
1968 let pill = rectangle(0., 0., 18., 18.);
1969 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
1970 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
1971 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
1972 }
1973
1974 #[gpui_kit::test]
1975 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
1976 cx.update(gpui_kit::init);
1977 cx.update(crate::theme::apply);
1978 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
1979 collect(visual, None);
1980 let mut found = Vec::new();
1981 for (count, rail) in BADGE_SAMPLES {
1982 let text = crate::format::badge_text(count);
1983 let pill = visual
1984 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
1985 .expect("badge rendered");
1986 let label = visual
1987 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
1988 .expect("badge text rendered");
1989 let font_size = if rail {
1990 RAIL_BADGE.font_size
1991 } else {
1992 COUNT_BADGE.font_size
1993 };
1994 let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));
1995 found.extend(badge_violation(&text, pill, label, offset));
1996 }
1997 let found: Vec<String> = found
1998 .into_iter()
1999 .map(|(key, message)| format!("{key}: {message}"))
2000 .collect();
2001 assert!(found.is_empty(), "{}", found.join("\n"));
2002 }
2003
2004 const PINNED_CHAT: &str = "demo-chat-release";
2005 const PINNED_CHANNEL: &str = "demo-channel-1-1";
2006
2007 #[gpui_kit::test]
2008 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
2009 let (handle, state) = mount(cx);
2010 let mut visual = VisualTestContext::from_window(handle, cx);
2011 let mut found = Vec::new();
2012 for (width, height) in SIZES {
2013 visual.simulate_resize(size(px(width), px(height)));
2014 visual.update(|_, cx| {
2015 state.update(cx, |state, cx| {
2016 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
2017 })
2018 });
2019 collect(&mut visual, Some(PIN_BANNER_TAG));
2020 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
2021 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2022 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2023 let gaps = [
2024 ("top", f32::from(banner.top() - timeline.top())),
2025 ("left", f32::from(banner.left() - timeline.left())),
2026 ("right", f32::from(timeline.right() - banner.right())),
2027 ("below divider", f32::from(banner.top() - divider.bottom())),
2028 ];
2029 let runway = runway_margin(f32::from(timeline.size.width) - 2. * BANNER_INSET);
2030 let sides_ok = gaps[1..3]
2031 .iter()
2032 .all(|(_, gap)| (gap - BANNER_INSET - runway).abs() <= INSET_TOLERANCE);
2033 let vertical_ok = [gaps[0].1, gaps[3].1]
2034 .iter()
2035 .all(|gap| (gap - BANNER_INSET).abs() <= INSET_TOLERANCE);
2036 if !sides_ok || !vertical_ok {
2037 found.push(format!(
2038 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
2039 ));
2040 }
2041 }
2042 assert!(found.is_empty(), "{}", found.join("\n"));
2043 }
2044
2045 #[gpui_kit::test]
2046 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
2047 let (handle, state) = mount(cx);
2048 let mut visual = VisualTestContext::from_window(handle, cx);
2049 visual.simulate_resize(size(px(1280.), px(800.)));
2050 visual.update(|_, cx| {
2051 state.update(cx, |state, cx| {
2052 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2053 })
2054 });
2055 collect(&mut visual, Some(TIMELINE_TAG));
2056 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
2057 }
2058
2059 fn open_channel(cx: &mut TestAppContext, awaited: &'static str) -> VisualTestContext {
2060 let (handle, state) = mount(cx);
2061 let mut visual = VisualTestContext::from_window(handle, cx);
2062 visual.simulate_resize(size(px(1280.), px(800.)));
2063 visual.update(|_, cx| {
2064 state.update(cx, |state, cx| {
2065 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2066 })
2067 });
2068 collect(&mut visual, Some(awaited));
2069 visual
2070 }
2071
2072 #[gpui_kit::test]
2073 fn channel_posts_start_the_body_at_the_avatar_edge_like_teams(cx: &mut TestAppContext) {
2074 let mut visual = open_channel(cx, POST_FOOTER_AVATAR_TAG);
2075 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
2076 visual
2077 .debug_bounds(path)
2078 .unwrap_or_else(|| panic!("{path} rendered"))
2079 };
2080 let card = bounds_of(&mut visual, POST_CARD_TAG);
2081 let avatar = bounds_of(&mut visual, POST_AVATAR_TAG);
2082 let body = bounds_of(&mut visual, POST_BODY_TAG);
2083 let footer_avatar = bounds_of(&mut visual, POST_FOOTER_AVATAR_TAG);
2084 let side = f32::from(avatar.left() - card.left());
2085 let checks = [
2086 ("body left", f32::from(body.left() - avatar.left())),
2087 ("footer avatar left", f32::from(footer_avatar.left() - avatar.left())),
2088 ("body right inset", f32::from(card.right() - body.right()) - side),
2089 ];
2090 for (name, gap) in checks {
2091 assert!(
2092 gap.abs() < INSET_TOLERANCE,
2093 "{name} off by {gap}: card {card:?} avatar {avatar:?} body {body:?} footer {footer_avatar:?}"
2094 );
2095 }
2096 }
2097
2098 #[gpui_kit::test]
2099 fn a_code_line_is_one_frame_inside_the_post_body(cx: &mut TestAppContext) {
2100 let mut visual = open_channel(cx, CODE_LINE_TAG);
2101 let code = visual.debug_bounds(CODE_LINE_TAG).expect("code line");
2102 let body = visual.debug_bounds(POST_BODY_TAG).expect("post body");
2103 assert!(
2104 f32::from(code.size.height) > 40.,
2105 "the long code line wraps inside one frame: {code:?}"
2106 );
2107 assert!(
2108 (f32::from(code.left() - body.left())).abs() < INSET_TOLERANCE
2109 && code.right() <= body.right() + px(INSET_TOLERANCE),
2110 "code {code:?} sits inside the body {body:?}"
2111 );
2112 assert!(visual.debug_bounds(CODE_BLOCK_TAG).is_none());
2113 }
2114
2115 #[gpui_kit::test]
2116 fn the_new_post_row_shows_a_scroll_edge_only_while_scrolled(cx: &mut TestAppContext) {
2117 let mut visual = open_channel(cx, POST_CARD_TAG);
2118 assert!(visual.debug_bounds(FEED_EDGE_TAG).is_none());
2119 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2120 visual.simulate_event(ScrollWheelEvent {
2121 position: timeline.center(),
2122 delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
2123 ..Default::default()
2124 });
2125 collect(&mut visual, Some(FEED_EDGE_TAG));
2126 let edge = visual.debug_bounds(FEED_EDGE_TAG).expect("feed edge");
2127 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2128 assert!(
2129 (f32::from(edge.top() - timeline.top())).abs() < INSET_TOLERANCE
2130 && (f32::from(edge.left() - timeline.left())).abs() < INSET_TOLERANCE
2131 && (f32::from(timeline.right() - edge.right())).abs() < INSET_TOLERANCE,
2132 "edge {edge:?} runs across the top of the timeline {timeline:?}"
2133 );
2134 }
2135
2136 #[gpui_kit::test]
2137 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
2138 let (handle, state) = mount(cx);
2139 let mut visual = VisualTestContext::from_window(handle, cx);
2140 visual.simulate_resize(size(px(1280.), px(800.)));
2141 visual.update(|_, cx| {
2142 state.update(cx, |state, cx| {
2143 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2144 })
2145 });
2146 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2147 let button = visual
2148 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2149 .expect("channel details button");
2150 visual.simulate_click(button.center(), Default::default());
2151 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
2152 let pane = visual
2153 .debug_bounds(CHANNEL_DETAILS_TAG)
2154 .expect("details pane");
2155 let main = visual.debug_bounds(MAIN).expect("main island");
2156 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2157 assert!(
2158 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
2159 "pane {pane:?} must end at the main island edge {main:?}"
2160 );
2161 assert!(
2162 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
2163 "pane {pane:?} must start under the header divider {divider:?}"
2164 );
2165 }
2166
2167 #[gpui_kit::test]
2168 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
2169 let (handle, state) = mount(cx);
2170 let mut visual = VisualTestContext::from_window(handle, cx);
2171 visual.simulate_resize(size(px(1280.), px(800.)));
2172 visual.update(|_, cx| {
2173 state.update(cx, |state, cx| {
2174 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2175 })
2176 });
2177 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2178 let button = visual
2179 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2180 .expect("channel details button");
2181 visual.simulate_click(button.center(), Default::default());
2182 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
2183 let pane = visual
2184 .debug_bounds(CHANNEL_DETAILS_TAG)
2185 .expect("details pane");
2186 let pinned = visual
2187 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
2188 .expect("pinned section");
2189 let shared = visual
2190 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
2191 .expect("shared section");
2192 assert!(
2193 pinned.bottom() <= shared.top(),
2194 "pinned {pinned:?} must come before shared {shared:?}"
2195 );
2196 for (name, section) in [("pinned", pinned), ("shared", shared)] {
2197 let left = f32::from(section.left() - pane.left());
2198 let right = f32::from(pane.right() - section.right());
2199 assert!(
2200 (left - right).abs() < INSET_TOLERANCE && left > 0.,
2201 "{name} section insets left {left} right {right} must match"
2202 );
2203 }
2204 }
2205
2206 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
2207 collect(visual, Some(COMPOSER_SEND_TAG));
2208 let mut bounds_of = |path: &'static str| {
2209 visual
2210 .debug_bounds(path)
2211 .unwrap_or_else(|| panic!("{path} rendered"))
2212 };
2213 let composer = bounds_of(COMPOSER_BOX_TAG);
2214 let input = bounds_of(COMPOSER_INPUT_TAG);
2215 let actions = bounds_of(COMPOSER_ACTIONS_TAG);
2216 let send = bounds_of(COMPOSER_SEND_TAG);
2217 [
2218 f32::from(input.left() - composer.left()),
2219 f32::from(actions.top() - composer.top()),
2220 f32::from(composer.bottom() - actions.bottom()),
2221 f32::from(composer.right() - send.right()),
2222 f32::from(send.top() - composer.top()),
2223 f32::from(composer.bottom() - send.bottom()),
2224 ]
2225 }
2226
2227 #[gpui_kit::test]
2228 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
2229 let (handle, _) = mount(cx);
2230 let mut visual = VisualTestContext::from_window(handle, cx);
2231 visual.simulate_resize(size(px(1280.), px(800.)));
2232 let single_line = composer_button_insets(&mut visual);
2233 let left = single_line[0];
2234 assert!(
2235 single_line
2236 .iter()
2237 .all(|inset| (inset - left).abs() < TOLERANCE),
2238 "single line: insets of the input left, the actions top and bottom, send right, top and bottom {single_line:?}"
2239 );
2240 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2241 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
2242 visual.simulate_click(point(input.center().x, send.center().y), Default::default());
2243 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
2244 let three_lines = composer_button_insets(&mut visual);
2245 assert!(
2246 three_lines[1] > single_line[1] + 30.,
2247 "three lines did not grow the composer: {three_lines:?}"
2248 );
2249 for inset in [
2250 three_lines[0],
2251 three_lines[2],
2252 three_lines[3],
2253 three_lines[5],
2254 ] {
2255 assert!(
2256 (inset - left).abs() < TOLERANCE,
2257 "three lines: insets of the input left, the actions top and bottom, send right, top and bottom {three_lines:?}, expected {left}"
2258 );
2259 }
2260 }
2261
2262 #[gpui_kit::test]
2263 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
2264 const FORMAT_TAGS: [&str; 6] = [
2265 COMPOSER_BOX_TAG,
2266 COMPOSER_FORMAT_BAR_TAG,
2267 COMPOSER_FORMAT_DIVIDER_TAG,
2268 COMPOSER_ACTIONS_TAG,
2269 COMPOSER_FORMAT_TAG,
2270 COMPOSER_SEND_TAG,
2271 ];
2272 let (handle, _) = mount(cx);
2273 let mut visual = VisualTestContext::from_window(handle, cx);
2274 for (width, height) in SIZES {
2275 visual.simulate_resize(size(px(width), px(height)));
2276 let window = Bounds {
2277 origin: point(px(0.), px(0.)),
2278 size: size(px(width), px(height)),
2279 };
2280 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
2281 let toggle = visual
2282 .debug_bounds(COMPOSER_FORMAT_TAG)
2283 .expect("format button");
2284 visual.simulate_click(toggle.center(), Default::default());
2285 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
2286 let tags: Vec<Tag> = FORMAT_TAGS
2287 .iter()
2288 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2289 .collect();
2290 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
2291 .into_iter()
2292 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
2293 .collect();
2294 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
2295 let actions = visual.debug_bounds(COMPOSER_ACTIONS_TAG).expect("actions");
2296 let toggle = visual
2297 .debug_bounds(COMPOSER_FORMAT_TAG)
2298 .expect("format button");
2299 visual.simulate_click(toggle.center(), Default::default());
2300 collect(&mut visual, None);
2301 assert!(found.is_empty(), "{}", found.join("\n"));
2302 assert!(
2303 bar.bottom() <= actions.top(),
2304 "bar {bar:?} over the buttons {actions:?}"
2305 );
2306 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
2307 }
2308 }
2309
2310 #[gpui_kit::test]
2311 fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2312 let (handle, _) = mount_with(cx, true);
2313 let mut visual = VisualTestContext::from_window(handle, cx);
2314 visual.dispatch_action(OpenActivity);
2315 for (width, height) in SIZES {
2316 visual.simulate_resize(size(px(width), px(height)));
2317 let window = Bounds {
2318 origin: point(px(0.), px(0.)),
2319 size: size(px(width), px(height)),
2320 };
2321 let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2322 let mut expected = GUARDED.to_vec();
2323 expected.push(ACTIVITY_PROPOSALS_TAG);
2324 let found: Vec<String> = violations(&tags, window, &expected)
2325 .into_iter()
2326 .map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2327 .collect();
2328 assert!(found.is_empty(), "{}", found.join("\n"));
2329 }
2330 }
2331
2332 #[gpui_kit::test]
2333 fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2334 const DELIVERY_TAGS: [&str; 5] = [
2335 COMPOSER_BOX_TAG,
2336 COMPOSER_ACTIONS_TAG,
2337 COMPOSER_DELIVERY_TAG,
2338 COMPOSER_IMPORTANCE_LABEL_TAG,
2339 COMPOSER_URGENT_BANNER_TAG,
2340 ];
2341 const URGENT_OPTION: &str = "urgent-delivery-option";
2342 const TEXT_INSET: f32 = 6.;
2343 let (handle, _) = mount(cx);
2344 let mut visual = VisualTestContext::from_window(handle, cx);
2345 for (width, height) in SIZES {
2346 visual.simulate_resize(size(px(width), px(height)));
2347 let window = Bounds {
2348 origin: point(px(0.), px(0.)),
2349 size: size(px(width), px(height)),
2350 };
2351 collect(&mut visual, Some(COMPOSER_DELIVERY_TAG));
2352 let button = visual
2353 .debug_bounds(COMPOSER_DELIVERY_TAG)
2354 .expect("delivery button");
2355 visual.simulate_click(button.center(), Default::default());
2356 collect(&mut visual, Some(URGENT_OPTION));
2357 let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2358 assert!(
2359 contains(window, menu),
2360 "menu {} leaves the window",
2361 describe(menu)
2362 );
2363 let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2364 visual.simulate_click(urgent.center(), Default::default());
2365 collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2366 assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2367 let tags: Vec<Tag> = DELIVERY_TAGS
2368 .iter()
2369 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2370 .collect();
2371 let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2372 .into_iter()
2373 .map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2374 .collect();
2375 assert!(found.is_empty(), "{}", found.join("\n"));
2376 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2377 let banner = visual
2378 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2379 .expect("banner");
2380 let label = visual
2381 .debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2382 .expect("label");
2383 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2384 assert!(
2385 (f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2386 && (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2387 "banner {} not on the composer edges {}",
2388 describe(banner),
2389 describe(composer)
2390 );
2391 assert!(
2392 banner.bottom() <= composer.top(),
2393 "banner {} over the composer {}",
2394 describe(banner),
2395 describe(composer)
2396 );
2397 assert!(
2398 (inset(composer, label, Edge::Left)
2399 - inset(composer, input, Edge::Left)
2400 - TEXT_INSET)
2401 .abs()
2402 <= TOLERANCE,
2403 "label {} not on the text edge of {}",
2404 describe(label),
2405 describe(input)
2406 );
2407 let close = visual
2408 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2409 .map(|banner| point(banner.right() - px(18.), banner.center().y))
2410 .expect("banner");
2411 visual.simulate_click(close, Default::default());
2412 collect(&mut visual, None);
2413 assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
2414 assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
2415 }
2416 }
2417
2418 #[gpui_kit::test]
2419 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
2420 let (handle, state) = mount_with(cx, true);
2421 let mut visual = VisualTestContext::from_window(handle, cx);
2422 for (width, height) in SIZES {
2423 visual.simulate_resize(size(px(width), px(height)));
2424 for chat in IMPORTANCE_CHATS {
2425 visual.update(|_, cx| {
2426 state.update(cx, |state, cx| {
2427 state.select(Selection::Chat(chat.to_owned()), cx)
2428 })
2429 });
2430 collect(&mut visual, Some(TIMELINE_TAG));
2431 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2432 visual.simulate_event(ScrollWheelEvent {
2433 position: timeline.center(),
2434 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
2435 ..Default::default()
2436 });
2437 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
2438 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
2439 let bubble = BUBBLE_TAGS
2440 .iter()
2441 .filter_map(|tag| visual.debug_bounds(tag))
2442 .find(|bubble| contains(*bubble, label))
2443 .unwrap_or_else(|| {
2444 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
2445 });
2446 let left = inset(bubble, label, Edge::Left);
2447 let top = inset(bubble, label, Edge::Top);
2448 assert!(
2449 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2450 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
2451 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2452 describe(bubble)
2453 );
2454 }
2455 }
2456 }
2457
2458 #[gpui_kit::test]
2459 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2460 let (handle, state) = mount_with(cx, true);
2461 let mut visual = VisualTestContext::from_window(handle, cx);
2462 for (width, height) in SIZES {
2463 visual.simulate_resize(size(px(width), px(height)));
2464 let window = Bounds {
2465 origin: point(px(0.), px(0.)),
2466 size: size(px(width), px(height)),
2467 };
2468 for (chat, expected_tags) in [
2469 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
2470 (REACTION_CHAT, &AGENT_TAGS[3..]),
2471 ] {
2472 visual.update(|_, cx| {
2473 state.update(cx, |state, cx| {
2474 state.select(Selection::Chat(chat.to_owned()), cx)
2475 })
2476 });
2477 let tags = collect(&mut visual, Some(expected_tags[0]));
2478 let mut expected = GUARDED.to_vec();
2479 expected.extend(expected_tags);
2480 let found: Vec<String> = violations(&tags, window, &expected)
2481 .into_iter()
2482 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
2483 .collect();
2484 assert!(found.is_empty(), "{}", found.join("\n"));
2485 }
2486 }
2487 }
2488}
2489
2490#[test]
2491fn lines_are_solid() {
2492 let mut files = Vec::new();
2493 for root in source_roots() {
2494 source_files(&root, &mut files);
2495 }
2496 let violations: Vec<String> = files
2497 .iter()
2498 .filter(|file| !file.ends_with("layout_guard.rs"))
2499 .flat_map(|file| {
2500 let source = fs::read_to_string(file).expect("read source file");
2501 source
2502 .lines()
2503 .enumerate()
2504 .filter(|(_, line)| {
2505 line.contains(".border_dashed(") || line.contains(".border_dotted(")
2506 })
2507 .map(|(index, line)| {
2508 format!(
2509 "{}:{}: lines are always solid: {}",
2510 file.display(),
2511 index + 1,
2512 line.trim()
2513 )
2514 })
2515 .collect::<Vec<_>>()
2516 })
2517 .collect();
2518 assert!(violations.is_empty(), "{}", violations.join("\n"));
2519}
2520
2521const STATE_RING_COLORS: &[&str] = &[
2522 "if focused",
2523 "if selected",
2524 "if speaking",
2525 "if current",
2526 "if open",
2527 "if state.failed",
2528];
2529const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
2530 (
2531 "notify/ring_view.rs",
2532 "theme::green()",
2533 "state signal (pulsing ring around the caller while it rings), not a resting outline",
2534 ),
2535 (
2536 "notify/meeting_view.rs",
2537 "theme::border_strong()",
2538 "outlined button, not a surface",
2539 ),
2540 (
2541 "settings/mcp.rs",
2542 "theme::border_strong()",
2543 "outlined button, not a surface",
2544 ),
2545 (
2546 "settings/rows.rs",
2547 "theme::border_strong()",
2548 "outlined button, not a surface",
2549 ),
2550 (
2551 "views/card_widgets.rs",
2552 "border)",
2553 "message content drawn as Teams renders it",
2554 ),
2555 (
2556 "views/card_widgets.rs",
2557 "theme::border_strong()",
2558 "message content drawn as Teams renders it",
2559 ),
2560 ("views/shared_tab.rs", "theme::accent()", "input field"),
2561 ("views/card_input.rs", "if error.is_some()", "input field"),
2562 ("views/format_toolbar.rs", "if refused", "input field"),
2563 (
2564 "views/card_code_block.rs",
2565 "theme::code_header_border()",
2566 "message content drawn as Teams renders it",
2567 ),
2568 (
2569 "render/elements.rs",
2570 "theme::code_frame()",
2571 "message content drawn as Teams renders it",
2572 ),
2573 ("views/call_transcript.rs", "theme::border()", "input field"),
2574 (
2575 "views/conversation.rs",
2576 "theme::accent()",
2577 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2578 ),
2579 (
2580 "views/attachment_tray.rs",
2581 "theme::accent()",
2582 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2583 ),
2584 (
2585 "views/card_carousel.rs",
2586 "theme::border_strong()",
2587 "message content drawn as Teams renders it",
2588 ),
2589 (
2590 "views/card_table.rs",
2591 "grid_color",
2592 "message content drawn as Teams renders it",
2593 ),
2594 (
2595 "views/activity_panel.rs",
2596 "theme::surface()",
2597 "cutout ring in the background color, invisible against its surface",
2598 ),
2599 (
2600 "views/avatar.rs",
2601 "theme::surface()",
2602 "cutout ring in the background color, invisible against its surface",
2603 ),
2604 (
2605 "views/message_row.rs",
2606 "theme::border_strong()",
2607 "deleted message placeholder, Teams look",
2608 ),
2609 (
2610 "views/message_row.rs",
2611 "theme::red()",
2612 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2613 ),
2614 (
2615 "views/message_row.rs",
2616 "if row.delivery",
2617 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2618 ),
2619 (
2620 "views/new_meeting_dialog.rs",
2621 "theme::border()",
2622 "input field",
2623 ),
2624 (
2625 "views/call_mini_window.rs",
2626 "theme::border_strong()",
2627 "self view over live video, needs an edge on any picture",
2628 ),
2629 ("views/transfer_picker.rs", "theme::border()", "input field"),
2630 (
2631 "views/call_notice.rs",
2632 "theme::border_strong()",
2633 "outlined button, not a surface",
2634 ),
2635 (
2636 "views/composer/schedule.rs",
2637 "theme::accent()",
2638 "input field",
2639 ),
2640 (
2641 "views/call_mini.rs",
2642 "border)",
2643 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2644 ),
2645 (
2646 "views/sidebar.rs",
2647 "theme::accent()",
2648 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2649 ),
2650 (
2651 "views/adaptive_card.rs",
2652 "theme::border()",
2653 "message content drawn as Teams renders it",
2654 ),
2655 (
2656 "views/adaptive_card.rs",
2657 "border)",
2658 "message content drawn as Teams renders it",
2659 ),
2660 (
2661 "views/share_bar.rs",
2662 "theme::red()",
2663 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2664 ),
2665 ("settings_controls.rs", "if invalid", "input field"),
2666];
2667
2668fn outlines(source: &str) -> Vec<(usize, String)> {
2669 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
2670 pattern
2671 .find_iter(source)
2672 .map(|found| {
2673 let line_number = source[..found.start()].matches('\n').count() + 1;
2674 let after = &source[found.end()..];
2675 let color = after
2676 .find(".border_color(")
2677 .filter(|position| *position < 120)
2678 .map(|position| {
2679 let start = &after[position + ".border_color(".len()..];
2680 start
2681 .lines()
2682 .map(str::trim)
2683 .find(|line| !line.is_empty())
2684 .unwrap_or_default()
2685 .to_owned()
2686 })
2687 .unwrap_or_default();
2688 (line_number, color)
2689 })
2690 .collect()
2691}
2692
2693#[test]
2694fn outline_matcher_reads_the_border_color() {
2695 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
2696 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
2697}
2698
2699#[test]
2700fn surfaces_are_soft() {
2701 let mut matched_allowlist = HashSet::new();
2702 let mut violations = Vec::new();
2703 for root in source_roots() {
2704 let mut files = Vec::new();
2705 source_files(&root, &mut files);
2706 for file in files {
2707 let relative = file
2708 .strip_prefix(&root)
2709 .expect("inside src")
2710 .to_string_lossy()
2711 .replace('\\', "/");
2712 if relative == "layout_guard.rs" {
2713 continue;
2714 }
2715 let source = fs::read_to_string(&file).expect("read source file");
2716 for (line_number, color) in outlines(&source) {
2717 if STATE_RING_COLORS
2718 .iter()
2719 .any(|prefix| color.starts_with(prefix))
2720 {
2721 continue;
2722 }
2723 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
2724 *allowed_file == relative && color.starts_with(prefix)
2725 }) {
2726 Some(position) => {
2727 matched_allowlist.insert(position);
2728 }
2729 None => violations.push(format!(
2730 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
2731 )),
2732 }
2733 }
2734 }
2735 }
2736 let stale = OUTLINE_ALLOWLIST
2737 .iter()
2738 .enumerate()
2739 .filter(|(position, _)| !matched_allowlist.contains(position))
2740 .map(|(_, (file, prefix, _))| {
2741 format!("stale outline allowlist entry, remove it: {file} {prefix}")
2742 });
2743 let report: Vec<String> = violations.into_iter().chain(stale).collect();
2744 assert!(report.is_empty(), "{}", report.join("\n"));
2745}
2746
2747fn indentation(line: &str) -> usize {
2748 line.len() - line.trim_start().len()
2749}
2750
2751fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
2752 let indent = indentation(lines[index]);
2753 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
2754 let start = lines[..index]
2755 .iter()
2756 .rposition(|line| !belongs(line))
2757 .map_or(0, |position| position + 1);
2758 let end = lines[index..]
2759 .iter()
2760 .position(|line| !belongs(line))
2761 .map_or(lines.len(), |position| index + position);
2762 lines[start..end]
2763 .iter()
2764 .filter(|line| indentation(line) == indent)
2765 .copied()
2766 .collect()
2767}
2768
2769fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
2770 let lines: Vec<&str> = source.lines().collect();
2771 (0..lines.len())
2772 .filter(|&index| row_height.is_match(lines[index]))
2773 .filter(|&index| {
2774 !chain_lines(&lines, index).iter().any(|line| {
2775 let line = line.trim();
2776 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
2777 })
2778 })
2779 .map(|index| index + 1)
2780 .collect()
2781}
2782
2783fn row_height_pattern() -> Regex {
2784 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
2785}
2786
2787#[test]
2788fn matcher_finds_rows_without_flex_none() {
2789 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";
2790 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
2791}
2792
2793#[test]
2794fn fixed_height_rows_never_shrink() {
2795 let row_height = row_height_pattern();
2796 let mut files = Vec::new();
2797 for root in source_roots() {
2798 source_files(&root, &mut files);
2799 }
2800 let violations: Vec<String> = files
2801 .iter()
2802 .filter(|file| !file.ends_with("layout_guard.rs"))
2803 .flat_map(|file| {
2804 let source = fs::read_to_string(file).expect("read source file");
2805 shrinking_rows(&row_height, &source)
2806 .into_iter()
2807 .map(|line| format!("{}:{line}", file.display()))
2808 .collect::<Vec<_>>()
2809 })
2810 .collect();
2811 assert!(
2812 violations.is_empty(),
2813 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
2814 );
2815}