BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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