BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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