BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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