BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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