BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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