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