BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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