BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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