BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 125.2 KiB Download Raw
1use std::collections::HashSet;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6
7const WIDGETS_FILE: &str = "widgets.rs";
8const SCAN_ALLOWLIST: &[(&str, &str)] = &[
9 ("views/toolbar_placement.rs", ".top(px(-SLOT_HEIGHT))"),
10 ("views/conversation.rs", ".bottom(px(-1.))"),
11];
12
13fn source_roots() -> Vec<PathBuf> {
14 let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
15 let mut roots: Vec<PathBuf> = fs::read_dir(&crates_directory)
16 .expect("read crates directory")
17 .map(|entry| entry.expect("directory entry").path())
18 .filter(|path| {
19 path.file_name()
20 .is_some_and(|name| name.to_string_lossy().starts_with("app"))
21 })
22 .map(|path| path.join("src"))
23 .filter(|path| path.is_dir())
24 .collect();
25 roots.sort();
26 roots
27}
28
29fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {
30 for entry in fs::read_dir(directory).expect("read source directory") {
31 let path = entry.expect("directory entry").path();
32 if path.is_dir() {
33 source_files(&path, files);
34 } else if path.extension().is_some_and(|extension| extension == "rs") {
35 files.push(path);
36 }
37 }
38}
39
40fn negative_offsets(
41 pattern: &Regex,
42 source: &str,
43 relative: &str,
44) -> Vec<(usize, Option<usize>, String)> {
45 pattern
46 .find_iter(source)
47 .map(|found| {
48 let line_number = source[..found.start()].matches('\n').count() + 1;
49 let from_match = &source[found.start()..];
50 let allowed = SCAN_ALLOWLIST.iter().position(|(allowed_file, snippet)| {
51 *allowed_file == relative && from_match.starts_with(snippet)
52 });
53 let line_end = from_match.find('\n').unwrap_or(from_match.len());
54 (
55 line_number,
56 allowed,
57 from_match[..line_end].trim().to_owned(),
58 )
59 })
60 .collect()
61}
62
63fn offset_pattern() -> Regex {
64 Regex::new(r"\.(top|right|bottom|left|inset)\(\s*(px\(\s*)?-").expect("pattern")
65}
66
67#[test]
68fn matcher_catches_wrapped_offsets() {
69 let source = "let a = 1;\nlet b = div()\n .top(\n px(-4.))\n .left(px(2.));\n";
70 let found = negative_offsets(&offset_pattern(), source, "views/other.rs");
71 assert_eq!(found, [(3, None, ".top(".to_owned())]);
72}
73
74#[test]
75fn matcher_matches_allowlist_from_match_start() {
76 let source = "x\n .bottom(px(-1.))\n";
77 let found = negative_offsets(&offset_pattern(), source, "views/conversation.rs");
78 assert_eq!(found, [(2, Some(1), ".bottom(px(-1.))".to_owned())]);
79}
80
81#[test]
82fn negative_offsets_go_through_corner_badge() {
83 let pattern = offset_pattern();
84 let mut matched_allowlist = HashSet::new();
85 let mut violations = Vec::new();
86 for root in source_roots() {
87 let mut files = Vec::new();
88 source_files(&root, &mut files);
89 for file in files {
90 let relative = file
91 .strip_prefix(&root)
92 .expect("inside src")
93 .to_string_lossy()
94 .replace('\\', "/");
95 if relative == WIDGETS_FILE || relative == "layout_guard.rs" {
96 continue;
97 }
98 let source = fs::read_to_string(&file).expect("read source file");
99 for (line_number, position, text) in negative_offsets(&pattern, &source, &relative) {
100 match position {
101 Some(position) => {
102 matched_allowlist.insert(position);
103 }
104 None => violations.push(format!(
105 "{relative}:{line_number}: negative absolute offset, use widgets::corner_badge: {text}"
106 )),
107 }
108 }
109 }
110 }
111 let stale: Vec<String> = SCAN_ALLOWLIST
112 .iter()
113 .enumerate()
114 .filter(|(position, _)| !matched_allowlist.contains(position))
115 .map(|(_, (file, snippet))| format!("stale allowlist entry, remove it: {file} {snippet}"))
116 .collect();
117 assert!(
118 violations.is_empty() && stale.is_empty(),
119 "{}",
120 violations
121 .into_iter()
122 .chain(stale)
123 .collect::<Vec<_>>()
124 .join("\n")
125 );
126}
127
128#[test]
129fn hover_styles_never_toggle_display() {
130 let toggle =
131 Regex::new(r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)").unwrap();
132 let mut files = Vec::new();
133 for root in source_roots() {
134 source_files(&root, &mut files);
135 }
136 let offenders: Vec<String> = files
137 .iter()
138 .flat_map(|path| {
139 let source = fs::read_to_string(path).unwrap();
140 source
141 .lines()
142 .enumerate()
143 .filter(|(_, line)| toggle.is_match(line))
144 .map(|(index, _)| format!("{}:{}", path.display(), index + 1))
145 .collect::<Vec<_>>()
146 })
147 .collect();
148 assert!(
149 offenders.is_empty(),
150 "hover styles must toggle visible()/invisible(), not display (gpui panics \"must call prepaint before paint\"): {offenders:?}"
151 );
152}
153
154mod frames {
155 use std::collections::HashSet;
156 use std::sync::Arc;
157 use std::time::Duration;
158
159 use app_ui_kit::layout::{COMFY_RUNWAY_WIDTH, ROW_PADDING};
160 use gpui_kit::test::TestWindowExt as _;
161 use gpui_kit::{
162 AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,
163 VisualTestContext, WindowOptions, point, px, size,
164 };
165 use store::Store;
166
167 use std::time::Instant;
168
169 use calling::{CallState, CallUpdate, CaptionEntry, CaptionState, RosterEntry, call_channel};
170 use gpui_kit::Entity;
171
172 use crate::app_state::{AppHandle, AppState, Mode, Selection};
173 use crate::call::{ActiveCall, CallModel, ConsultCall};
174 use crate::demo;
175 use crate::settings::select_selector;
176 use crate::settings::{item_selector, label, label_selector, metrics};
177 use crate::settings_section::SettingsSection;
178 use crate::user_activity::UserInput;
179 use crate::views::call_transcript::TranscriptPanel;
180 use crate::views::call_view::CHAT_PANEL_TAG;
181 use crate::views::composer::delivery::{
182 COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG,
183 DELIVERY_MENU_TAG,
184 };
185 use crate::views::composer::plus_menu::{COMPOSER_PLUS_TAG, PlusAction};
186 use crate::views::composer::{
187 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
188 COMPOSER_ACTIONS_TAG, COMPOSER_FORMAT_TAG, COMPOSER_INPUT_TAG, COMPOSER_SEND_TAG, COMPOSER_STACKED_ACTIONS_TAG,
189 POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG, POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG, POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG, POST_CARD_SEND_TAG,
190 POST_CARD_SUBJECT_TAG,
191 };
192 use crate::views::call_window::CALL_WINDOW_TAG;
193 use crate::views::conversation::{
194 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
195 CHANNEL_DETAILS_TAG,
196 };
197 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
198 use crate::views::conversation::{
199 FEED_EDGE_TAG, FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG,
200 FORWARD_FOOTER_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG,
201 };
202 use crate::views::group_name::{GROUP_NAME_BUTTON, GROUP_NAME_FORM};
203 use crate::views::post_card::{
204 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
205 };
206 use crate::views::find_panel::{
207 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
208 };
209 use crate::views::forward_dialog::{FORWARD_CARD_TAG, FORWARD_PREVIEW_TAG};
210 use crate::views::message_row::{
211 BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y, select_box_selector,
212 };
213 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
214 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
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, OpenCallsTab,
223 OpenCalendar, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
224 };
225 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
226 use crate::views::sidebar::chat_row_selector;
227 use crate::views::sidebar::chat_filter_bar::{
228 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
229 };
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 = bounds_of("shell/islands/sidebar").or_else(|| bounds_of(CALENDAR));
1051 if let (Some(rail), Some(island)) = (bounds_of("shell/islands/rail"), first_island) {
1052 let gap = f32::from(island.origin.x) - f32::from(rail.origin.x + rail.size.width);
1053 if gap.abs() > 0.5 {
1054 found.push((
1055 "shell/islands/rail:gap".to_owned(),
1056 format!("first island starts {gap} px after the rail, expected 0"),
1057 ));
1058 }
1059 }
1060 if status_menu {
1061 let menu = tags
1062 .iter()
1063 .find(|(path, _)| *path == MENU)
1064 .map(|(_, bounds)| *bounds);
1065 let button = tags
1066 .iter()
1067 .find(|(path, _)| *path == OWN_STATUS)
1068 .map(|(_, bounds)| *bounds);
1069 if let (Some(menu), Some(button)) = (menu, button) {
1070 if overlaps(menu, button) {
1071 found.push((
1072 format!("{MENU}:covers:{OWN_STATUS}"),
1073 format!(
1074 "{MENU} {} covers {OWN_STATUS} {}",
1075 describe(menu),
1076 describe(button)
1077 ),
1078 ));
1079 }
1080 }
1081 visual.simulate_keystrokes("escape");
1082 visual.run_until_parked();
1083 }
1084 if is_call {
1085 visual.update(|_, cx| {
1086 app.update(cx, |state, cx| {
1087 state.call = None;
1088 state.held_call = None;
1089 cx.notify();
1090 })
1091 });
1092 }
1093 if screen_name == "find" {
1094 visual.dispatch_action(gpui_kit::component::input::Escape);
1095 visual.run_until_parked();
1096 }
1097 if screen_name == "chat-filter" {
1098 visual.dispatch_action(ClearChatFilters);
1099 visual.dispatch_action(OpenChatFilter);
1100 visual.run_until_parked();
1101 }
1102 if screen_name == "prejoin" {
1103 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
1104 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
1105 }
1106 for (key, message) in found {
1107 let full_key = format!("{screen_name}@{width}x{height}:{key}");
1108 if known_violations.contains(&full_key.as_str()) {
1109 seen_known.insert(full_key);
1110 } else {
1111 unexpected.push(format!("{full_key}: {message}"));
1112 }
1113 }
1114 }
1115 }
1116 let stale: Vec<String> = known_violations
1117 .iter()
1118 .filter(|key| !seen_known.contains(**key))
1119 .map(|key| format!("stale known violation, remove it: {key}"))
1120 .collect();
1121 assert!(
1122 unexpected.is_empty() && stale.is_empty(),
1123 "{}",
1124 unexpected
1125 .into_iter()
1126 .chain(stale)
1127 .collect::<Vec<_>>()
1128 .join("\n")
1129 );
1130 }
1131 #[gpui_kit::test]
1132 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
1133 let (handle, _) = mount(cx);
1134 let mut visual = VisualTestContext::from_window(handle, cx);
1135 visual.simulate_resize(size(px(1280.), px(800.)));
1136 collect(&mut visual, Some(OWN_AVATAR_DISC));
1137 let disc = visual
1138 .debug_bounds(OWN_AVATAR_DISC)
1139 .expect("own avatar rendered");
1140 let bar = visual
1141 .debug_bounds("shell/title-bar")
1142 .expect("title bar rendered");
1143 assert_eq!(
1144 f32::from(disc.size.width),
1145 TITLE_AVATAR_SIZE,
1146 "{}",
1147 describe(disc)
1148 );
1149 assert_eq!(
1150 f32::from(disc.size.height),
1151 TITLE_AVATAR_SIZE,
1152 "{}",
1153 describe(disc)
1154 );
1155 let top = f32::from(disc.top() - bar.top());
1156 let bottom = f32::from(bar.bottom() - disc.bottom());
1157 assert!(
1158 (top - bottom).abs() <= 1.,
1159 "own avatar {} is not centered in the title bar {}",
1160 describe(disc),
1161 describe(bar)
1162 );
1163 }
1164
1165 #[gpui_kit::test]
1166 fn a_narrow_composer_puts_its_actions_below_a_full_width_input(cx: &mut TestAppContext) {
1167 let (handle, _) = mount(cx);
1168 let mut visual = VisualTestContext::from_window(handle, cx);
1169 visual.simulate_resize(size(px(760.), px(700.)));
1170 collect(&mut visual, Some(COMPOSER_STACKED_ACTIONS_TAG));
1171 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
1172 visual.debug_bounds(path).unwrap_or_else(|| panic!("{path} missing"))
1173 };
1174 let card = bounds_of(&mut visual, COMPOSER_BOX_TAG);
1175 let input = bounds_of(&mut visual, COMPOSER_INPUT_TAG);
1176 let stacked = bounds_of(&mut visual, COMPOSER_STACKED_ACTIONS_TAG);
1177 let send = bounds_of(&mut visual, COMPOSER_SEND_TAG);
1178 assert!(input.bottom() <= stacked.top(), "actions {} not below input {}", describe(stacked), describe(input));
1179 assert!(contains(card, stacked) && contains(stacked, send), "send {} outside {}", describe(send), describe(stacked));
1180 let side = f32::from(card.right() - send.right());
1181 let bottom = f32::from(card.bottom() - send.bottom());
1182 assert!((side - bottom).abs() < TOLERANCE, "send insets: side {side}, bottom {bottom}");
1183 visual.simulate_resize(size(px(1280.), px(800.)));
1184 collect(&mut visual, Some(COMPOSER_SEND_TAG));
1185 assert!(visual.debug_bounds(COMPOSER_STACKED_ACTIONS_TAG).is_none(), "wide composer stacked");
1186 }
1187
1188 const TITLE_SEARCH: &str = "shell/title-bar/search";
1189 const TITLE_NEIGHBOURS: &[&str] = &[
1190 "shell/title-bar/leading",
1191 "shell/title-bar/mode-pill",
1192 "shell/title-bar/trailing",
1193 "shell/title-bar/update",
1194 OWN_STATUS,
1195 ];
1196 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
1197 (1920., 1080., true),
1198 (1280., 800., true),
1199 (640., 480., false),
1200 ];
1201
1202 #[gpui_kit::test]
1203 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
1204 let (handle, _) = mount(cx);
1205 let mut visual = VisualTestContext::from_window(handle, cx);
1206 let shell = visual.update(|window, cx| {
1207 window
1208 .root::<gpui_kit::base::Root>()
1209 .flatten()
1210 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
1211 .expect("app shell is the root view")
1212 });
1213 visual.update(|_, cx| {
1214 shell.update(cx, |shell, cx| {
1215 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
1216 })
1217 });
1218 let mut found = Vec::new();
1219 for (width, height, centered) in TITLE_SEARCH_SIZES {
1220 visual.simulate_resize(size(px(width), px(height)));
1221 collect(&mut visual, Some(TITLE_SEARCH));
1222 let search = visual
1223 .debug_bounds(TITLE_SEARCH)
1224 .expect("title search rendered");
1225 let search_center = f32::from(search.center().x);
1226 eprintln!(
1227 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
1228 describe(search),
1229 width / 2.
1230 );
1231 if centered && (search_center - width / 2.).abs() > 1. {
1232 found.push(format!(
1233 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
1234 width / 2.
1235 ));
1236 }
1237 if !contains(rectangle(0., 0., width, height), search) {
1238 found.push(format!(
1239 "@{width}x{height}: search {} leaves the window",
1240 describe(search)
1241 ));
1242 }
1243 for neighbour in TITLE_NEIGHBOURS {
1244 match visual.debug_bounds(neighbour) {
1245 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
1246 Some(bounds) if overlaps(search, bounds) => found.push(format!(
1247 "@{width}x{height}: search {} overlaps {neighbour} {}",
1248 describe(search),
1249 describe(bounds)
1250 )),
1251 Some(_) => {}
1252 }
1253 }
1254 }
1255 assert!(found.is_empty(), "{}", found.join("\n"));
1256 }
1257
1258 #[gpui_kit::test]
1259 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
1260 let (handle, app) = mount(cx);
1261 let mut visual = VisualTestContext::from_window(handle, cx);
1262 for (width, height) in SIZES {
1263 visual.simulate_resize(size(px(width), px(height)));
1264 visual.update(|_, cx| {
1265 app.update(cx, |state, cx| {
1266 let mut call = gallery_call();
1267 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
1268 call.chat_open = true;
1269 state.call = Some(call);
1270 cx.notify();
1271 })
1272 });
1273 let mut call_visual = call_window_context(&mut visual);
1274 call_visual.simulate_resize(size(px(width), px(height)));
1275 collect(&mut call_visual, Some(CHAT_PANEL_TAG));
1276 let panel = call_visual
1277 .debug_bounds(CHAT_PANEL_TAG)
1278 .expect("chat panel rendered");
1279 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
1280 .iter()
1281 .enumerate()
1282 .filter_map(|(index, tag)| call_visual.debug_bounds(tag).map(|bounds| (index, bounds)))
1283 .collect();
1284 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
1285 let found: Vec<String> = bubbles
1286 .into_iter()
1287 .filter(|(_, bounds)| {
1288 !inside_horizontally(panel, *bounds) || !overlaps(panel, *bounds)
1289 })
1290 .map(|(index, bounds)| {
1291 format!(
1292 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
1293 describe(bounds),
1294 describe(panel)
1295 )
1296 })
1297 .collect();
1298 visual.update(|_, cx| {
1299 app.update(cx, |state, cx| {
1300 state.call = None;
1301 cx.notify();
1302 })
1303 });
1304 assert!(found.is_empty(), "{}", found.join("\n"));
1305 }
1306 }
1307
1308 #[gpui_kit::test]
1309 fn a_new_message_never_opens_a_gap_between_the_rows_above(cx: &mut TestAppContext) {
1310 const GAP_CHAT: &str = "demo-chat-priya";
1311 let (handle, app) = mount(cx);
1312 let mut visual = VisualTestContext::from_window(handle, cx);
1313 visual.simulate_resize(size(px(1280.), px(800.)));
1314 visual.update(|_, cx| {
1315 app.update(cx, |state, cx| {
1316 state.select(Selection::Chat(GAP_CHAT.to_owned()), cx)
1317 })
1318 });
1319 collect(&mut visual, Some(TIMELINE_TAG));
1320 collect(&mut visual, None);
1321 let bubble_positions = |visual: &mut VisualTestContext| -> Vec<(usize, f32, f32)> {
1322 BUBBLE_TAGS
1323 .iter()
1324 .enumerate()
1325 .filter_map(|(index, tag)| {
1326 visual
1327 .debug_bounds(tag)
1328 .map(|bounds| (index, f32::from(bounds.top()), f32::from(bounds.bottom())))
1329 })
1330 .collect()
1331 };
1332 let before = bubble_positions(&mut visual);
1333 visual.update(|_, cx| {
1334 app.update(cx, |state, cx| {
1335 let record = store::MessageRecord {
1336 conversation_id: GAP_CHAT.to_owned(),
1337 message_id: "guard-new".to_owned(),
1338 sender_id: Some(demo::PRIYA_ID.to_owned()),
1339 sender_name: Some("Priya Nair".to_owned()),
1340 created_at: chrono::Utc::now().max(demo::at(0, 10, 48)),
1341 body_html: "<p>Fresh message</p>".to_owned(),
1342 links_json: "[]".to_owned(),
1343 attachments_json: "[]".to_owned(),
1344 reactions_json: "[]".to_owned(),
1345 mentions_json: "[]".to_owned(),
1346 ..Default::default()
1347 };
1348 state.store.upsert_messages(&[record]).expect("store message");
1349 state.apply(
1350 crate::backend::BackendEvent::Core(teams_core::CoreEvent::MessagesChanged {
1351 conversation_id: GAP_CHAT.to_owned(),
1352 }),
1353 cx,
1354 );
1355 })
1356 });
1357 let mut frames = Vec::new();
1358 for _ in 0..12 {
1359 visual.executor().advance_clock(Duration::from_millis(16));
1360 visual.run_until_parked();
1361 visual.update(|window, cx| window.render_frame(cx));
1362 frames.push(bubble_positions(&mut visual));
1363 }
1364 let spacing = |positions: &[(usize, f32, f32)]| -> Vec<(usize, f32)> {
1365 positions
1366 .windows(2)
1367 .map(|pair| (pair[1].0, pair[1].1 - pair[0].2))
1368 .collect()
1369 };
1370 let resting = spacing(&before);
1371 let found: Vec<String> = frames
1372 .iter()
1373 .enumerate()
1374 .flat_map(|(frame, positions)| {
1375 let resting = resting.clone();
1376 spacing(positions)
1377 .into_iter()
1378 .filter_map(move |(index, gap)| {
1379 let expected = resting.iter().find(|(known, _)| *known == index)?.1;
1380 ((gap - expected).abs() > TOLERANCE).then(|| {
1381 format!("frame {frame}: gap above bubble {index} is {gap}, was {expected}")
1382 })
1383 })
1384 })
1385 .collect();
1386 assert!(found.is_empty(), "{}", found.join("\n"));
1387 }
1388
1389 fn inside_horizontally(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
1390 let tolerance = px(TOLERANCE);
1391 inner.left() >= outer.left() - tolerance && inner.right() <= outer.right() + tolerance
1392 }
1393
1394 fn scroll_sidebar(visual: &mut VisualTestContext, delta: f32) {
1395 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1396 visual.simulate_event(ScrollWheelEvent {
1397 position: sidebar.center(),
1398 delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1399 ..Default::default()
1400 });
1401 }
1402
1403 #[gpui_kit::test]
1404 fn chat_list_line_shows_only_while_scrolled(cx: &mut TestAppContext) {
1405 let (handle, _) = mount(cx);
1406 let mut visual = VisualTestContext::from_window(handle, cx);
1407 for (width, height) in SIZES {
1408 visual.simulate_resize(size(px(width), px(height)));
1409 let window = Bounds {
1410 origin: point(px(0.), px(0.)),
1411 size: size(px(width), px(height)),
1412 };
1413 collect(&mut visual, None);
1414 scroll_sidebar(&mut visual, 100_000.);
1415 let tags = collect(&mut visual, None);
1416 assert!(
1417 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1418 "chat list at its top must not show the line at {width}x{height}"
1419 );
1420 scroll_sidebar(&mut visual, -120.);
1421 let scrolled = collect(&mut visual, Some(SIDEBAR_SCROLL_DIVIDER));
1422 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1423 let line = visual
1424 .debug_bounds(SIDEBAR_SCROLL_DIVIDER)
1425 .expect("scrolled chat list shows the line");
1426 assert!(
1427 line.top() > sidebar.top() + px(TOLERANCE),
1428 "the line sits under the Chats header, not on the island edge: {} in {}",
1429 describe(line),
1430 describe(sidebar)
1431 );
1432 let found: Vec<String> = violations(&scrolled, window, &[SIDEBAR_SCROLL_DIVIDER])
1433 .into_iter()
1434 .chain(violations(&tags, window, &[]))
1435 .map(|(key, message)| format!("chat-list@{width}x{height}:{key}: {message}"))
1436 .collect();
1437 assert!(found.is_empty(), "{}", found.join("\n"));
1438 scroll_sidebar(&mut visual, 100_000.);
1439 collect(&mut visual, None);
1440 assert!(
1441 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1442 "the line goes away once the chat list is back at its top"
1443 );
1444 }
1445 }
1446
1447 #[gpui_kit::test]
1448 fn header_tabs_sit_above_the_header_line(cx: &mut TestAppContext) {
1449 let (handle, state) = mount(cx);
1450 let mut visual = VisualTestContext::from_window(handle, cx);
1451 for (width, height) in SIZES {
1452 visual.simulate_resize(size(px(width), px(height)));
1453 let window = Bounds {
1454 origin: point(px(0.), px(0.)),
1455 size: size(px(width), px(height)),
1456 };
1457 visual.update(|_, cx| {
1458 state.update(cx, |state, cx| {
1459 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1460 })
1461 });
1462 let tags = collect(&mut visual, Some(RECAP_TAB));
1463 let main = visual.debug_bounds(MAIN).expect("main island rendered");
1464 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1465 let line = visual
1466 .debug_bounds(HEADER_DIVIDER)
1467 .expect("the header line is always shown");
1468 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
1469 assert!(
1470 tab.top() >= main.top() && near(tab.bottom(), line.top()),
1471 "tab {} must sit in the top bar above the line {}",
1472 describe(tab),
1473 describe(line)
1474 );
1475 let found: Vec<String> = violations(&tags, window, &[HEADER_DIVIDER, RECAP_TAB])
1476 .into_iter()
1477 .map(|(key, message)| format!("header@{width}x{height}:{key}: {message}"))
1478 .collect();
1479 assert!(found.is_empty(), "{}", found.join("\n"));
1480 }
1481 }
1482
1483 #[gpui_kit::test]
1484 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1485 let (handle, state) = mount(cx);
1486 let mut visual = VisualTestContext::from_window(handle, cx);
1487 for (width, height) in SIZES {
1488 visual.simulate_resize(size(px(width), px(height)));
1489 let window = Bounds {
1490 origin: point(px(0.), px(0.)),
1491 size: size(px(width), px(height)),
1492 };
1493 visual.update(|_, cx| {
1494 state.update(cx, |state, cx| {
1495 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1496 })
1497 });
1498 collect(&mut visual, Some(RECAP_TAB));
1499 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1500 visual.simulate_click(tab.center(), Default::default());
1501 let tags = collect(&mut visual, Some(RECAP_REGION));
1502 let mut expected = GUARDED.to_vec();
1503 expected.extend([RECAP_TAB, RECAP_REGION]);
1504 let found: Vec<String> = violations(&tags, window, &expected)
1505 .into_iter()
1506 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1507 .collect();
1508 assert!(found.is_empty(), "{}", found.join("\n"));
1509 }
1510 }
1511
1512 // Not a platform assertion: on macOS the camera effects worker schedules onto
1513 // the deterministic test scheduler while this dialog is open.
1514 #[cfg_attr(target_os = "macos", ignore = "camera effects thread trips the test scheduler")]
1515 #[gpui_kit::test]
1516 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1517 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1518 }
1519
1520 #[gpui_kit::test]
1521 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1522 crate::theme::set_thread_scheme(Some("teams"));
1523 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1524 crate::theme::set_thread_scheme(None);
1525 }
1526
1527 #[gpui_kit::test]
1528 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1529 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1530 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1531 crate::theme::set_thread_shade(None);
1532 }
1533
1534 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1535 let (handle, state) = mount_with(cx, true);
1536 let mut visual = VisualTestContext::from_window(handle, cx);
1537 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1538 visual.simulate_resize(size(px(width), px(height)));
1539 let window = Bounds {
1540 origin: point(px(0.), px(0.)),
1541 size: size(px(width), px(height)),
1542 };
1543 let inset = metrics(width, height).inset;
1544 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1545 for &section in sections {
1546 visual
1547 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1548 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1549 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1550 .into_iter()
1551 .filter(|(key, _)| key.starts_with("settings"))
1552 .chain(inset_violations(&tags, INSET_RULES))
1553 .collect();
1554 if label_sizes {
1555 found.extend(nav_label_violations(&mut visual));
1556 }
1557 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1558 .iter()
1559 .any(|(exempt, _)| *exempt == section);
1560 if !scrolled_exempt {
1561 found.extend(scrolled_inset_violation(&mut visual));
1562 }
1563 let found: Vec<String> = found
1564 .into_iter()
1565 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1566 .collect();
1567 assert!(found.is_empty(), "{}", found.join("\n"));
1568 let dialog = visual
1569 .debug_bounds(SETTINGS_TAGS[0])
1570 .expect("settings dialog");
1571 let edges = [
1572 f32::from(dialog.left()),
1573 f32::from(dialog.top()),
1574 width - f32::from(dialog.right()),
1575 height - f32::from(dialog.bottom()),
1576 ];
1577 assert!(
1578 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1579 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1580 );
1581 }
1582 }
1583 }
1584
1585 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1586
1587 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1588 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1589 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1590 };
1591 let mut found = Vec::new();
1592 for section in SETTINGS_SECTIONS {
1593 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1594 let item_path: &'static str = if section == SettingsSection::About {
1595 SETTINGS_NAV_ABOUT
1596 } else {
1597 Box::leak(item_selector(section).into_boxed_str())
1598 };
1599 let (Some(label_bounds), Some(item)) = (
1600 visual.debug_bounds(label_path),
1601 visual.debug_bounds(item_path),
1602 ) else {
1603 if section != SettingsSection::Agents {
1604 found.push((label_path.to_owned(), "not rendered".to_owned()));
1605 }
1606 continue;
1607 };
1608 let text = label(section);
1609 let text_width = visual.update(|window, _| {
1610 let run = window.text_style().to_run(text.len());
1611 f32::from(
1612 window
1613 .text_system()
1614 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1615 .width,
1616 )
1617 });
1618 let label_width = f32::from(label_bounds.size.width);
1619 let label_height = f32::from(label_bounds.size.height);
1620 if text_width > label_width + TOLERANCE
1621 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1622 {
1623 found.push((
1624 label_path.to_owned(),
1625 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1626 ));
1627 }
1628 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1629 inner.left() < outer.left() - px(TOLERANCE)
1630 || inner.right() > outer.right() + px(TOLERANCE)
1631 || inner.top() < outer.top() - px(TOLERANCE)
1632 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1633 };
1634 if outside(label_bounds, item) {
1635 found.push((
1636 label_path.to_owned(),
1637 format!("label {label_bounds:?} outside item {item:?}"),
1638 ));
1639 }
1640 if item.left() < nav.left() || item.right() > nav.right() {
1641 found.push((
1642 item_path.to_owned(),
1643 format!("item {item:?} outside nav {nav:?}"),
1644 ));
1645 }
1646 }
1647 found
1648 }
1649
1650 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1651 let body = visual.debug_bounds(SETTINGS_BODY)?;
1652 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1653 if content.bottom() <= body.bottom() {
1654 return None;
1655 }
1656 visual.simulate_event(ScrollWheelEvent {
1657 position: body.center(),
1658 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1659 ..Default::default()
1660 });
1661 collect(visual, None);
1662 let body = visual.debug_bounds(SETTINGS_BODY)?;
1663 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1664 inset_violation(&SCROLLED_INSET_RULE, body, content)
1665 }
1666
1667 #[gpui_kit::test]
1668 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1669 let (handle, state) = mount(cx);
1670 let mut visual = VisualTestContext::from_window(handle, cx);
1671 for (width, height) in SIZES {
1672 visual.simulate_resize(size(px(width), px(height)));
1673 let window = Bounds {
1674 origin: point(px(0.), px(0.)),
1675 size: size(px(width), px(height)),
1676 };
1677 visual.update(|_, cx| {
1678 state.update(cx, |state, cx| {
1679 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1680 })
1681 });
1682 collect(&mut visual, Some(MEMBERS_BUTTON));
1683 let button = visual
1684 .debug_bounds(MEMBERS_BUTTON)
1685 .expect("members button rendered");
1686 visual.simulate_click(button.center(), Default::default());
1687 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1688 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1689 .into_iter()
1690 .filter(|(key, _)| key.starts_with("chat-members"))
1691 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1692 .collect();
1693 visual.simulate_keystrokes("escape");
1694 visual.run_until_parked();
1695 assert!(found.is_empty(), "{}", found.join("\n"));
1696 }
1697 }
1698
1699 #[gpui_kit::test]
1700 fn the_group_name_field_keeps_typed_text_across_frames(cx: &mut TestAppContext) {
1701 let (handle, state) = mount(cx);
1702 let mut visual = VisualTestContext::from_window(handle, cx);
1703 visual.update(|_, cx| {
1704 state.update(cx, |state, cx| {
1705 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1706 })
1707 });
1708 collect(&mut visual, Some(GROUP_NAME_BUTTON));
1709 let button = visual
1710 .debug_bounds(GROUP_NAME_BUTTON)
1711 .expect("group name button rendered");
1712 visual.simulate_click(button.center(), Default::default());
1713 collect(&mut visual, Some(GROUP_NAME_FORM));
1714 assert!(visual.debug_bounds(GROUP_NAME_FORM).is_some(), "group name form open");
1715 visual.simulate_keystrokes("backspace x space y enter");
1716 visual.run_until_parked();
1717 let title = visual.update(|_, cx| {
1718 state
1719 .read(cx)
1720 .sidebar
1721 .chats
1722 .iter()
1723 .find(|chat| chat.id == MEMBERS_CHAT)
1724 .map(|chat| chat.title.clone())
1725 });
1726 assert_eq!(title.as_deref(), Some("Release planninx y"));
1727 }
1728
1729 const FORWARD_CHAT: &str = "demo-chat-release";
1730 const FORWARD_FOOTER_TAGS: [&str; 4] = [
1731 FORWARD_FOOTER_TAG,
1732 FORWARD_FOOTER_BAR_TAG,
1733 FORWARD_FOOTER_COUNT_TAG,
1734 FORWARD_FOOTER_NEXT_TAG,
1735 ];
1736 const FORWARD_DIALOG_PADDING: f32 = 16.;
1737 const FORWARD_BAR_PADDING: f32 = 8.;
1738 const FORWARD_ROWS_SCANNED: usize = 80;
1739
1740 fn forward_message_ids(
1741 state: &Entity<AppState>,
1742 visual: &mut VisualTestContext,
1743 ) -> Vec<String> {
1744 visual.update(|_, cx| {
1745 let mut records = state
1746 .read(cx)
1747 .store
1748 .messages(FORWARD_CHAT, None, 50)
1749 .expect("demo messages");
1750 records.retain(|record| !record.deleted);
1751 records.sort_by_key(|record| record.created_at);
1752 records
1753 .iter()
1754 .rev()
1755 .take(2)
1756 .map(|record| record.message_id.clone())
1757 .collect()
1758 })
1759 }
1760
1761 #[gpui_kit::test]
1762 fn forward_selection_footer_checks_and_dialog_keep_their_insets(cx: &mut TestAppContext) {
1763 let (handle, state) = mount(cx);
1764 let mut visual = VisualTestContext::from_window(handle, cx);
1765 for (width, height) in SIZES {
1766 visual.simulate_resize(size(px(width), px(height)));
1767 let window = Bounds {
1768 origin: point(px(0.), px(0.)),
1769 size: size(px(width), px(height)),
1770 };
1771 visual.update(|_, cx| {
1772 state.update(cx, |state, cx| {
1773 state.select(Selection::Chat(FORWARD_CHAT.to_owned()), cx)
1774 })
1775 });
1776 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1777 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
1778 let ids = forward_message_ids(&state, &mut visual);
1779 visual.update(|_, cx| {
1780 state.update(cx, |state, cx| {
1781 state.start_forward_selection(FORWARD_CHAT, &ids[0], cx);
1782 state.toggle_forward_selected(&ids[1], cx);
1783 })
1784 });
1785 collect(&mut visual, Some(FORWARD_FOOTER_NEXT_TAG));
1786 assert!(
1787 visual.debug_bounds(COMPOSER_BOX_TAG).is_none(),
1788 "the footer replaces the composer"
1789 );
1790 let tags: Vec<Tag> = FORWARD_FOOTER_TAGS
1791 .iter()
1792 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1793 .collect();
1794 let mut found: Vec<String> = violations(&tags, window, &FORWARD_FOOTER_TAGS)
1795 .into_iter()
1796 .map(|(key, message)| format!("forward@{width}x{height}:{key}: {message}"))
1797 .collect();
1798 let main = visual.debug_bounds(MAIN).expect("main island");
1799 let bar = visual.debug_bounds(FORWARD_FOOTER_BAR_TAG).expect("bar");
1800 let next = visual.debug_bounds(FORWARD_FOOTER_NEXT_TAG).expect("next");
1801 if (f32::from(bar.left() - composer.left())).abs() > TOLERANCE
1802 || (f32::from(bar.right() - composer.right())).abs() > TOLERANCE
1803 {
1804 found.push(format!(
1805 "forward@{width}x{height}: bar {} not on the composer edges {}",
1806 describe(bar),
1807 describe(composer)
1808 ));
1809 }
1810 for edge in [Edge::Top, Edge::Right, Edge::Bottom] {
1811 let gap = inset(bar, next, edge);
1812 if (gap - FORWARD_BAR_PADDING).abs() > TOLERANCE {
1813 found.push(format!(
1814 "forward@{width}x{height}: next button {edge:?} inset {gap} != {FORWARD_BAR_PADDING}"
1815 ));
1816 }
1817 }
1818 let checks: Vec<Bounds<Pixels>> = (0..FORWARD_ROWS_SCANNED)
1819 .filter_map(|index| {
1820 visual.debug_bounds(Box::leak(select_box_selector(index).into_boxed_str()))
1821 })
1822 .filter(|check| contains(main, *check))
1823 .collect();
1824 if checks.is_empty() {
1825 found.push(format!("forward@{width}x{height}: no checkbox rendered"));
1826 }
1827 let expected_left = ROW_PADDING + runway_margin(f32::from(main.size.width));
1828 for check in &checks {
1829 let left = inset(main, *check, Edge::Left);
1830 if (left - expected_left).abs() > TOLERANCE {
1831 found.push(format!(
1832 "forward@{width}x{height}: checkbox {} starts {left} from the island, not {expected_left}",
1833 describe(*check)
1834 ));
1835 }
1836 }
1837 visual.simulate_click(next.center(), Default::default());
1838 collect(&mut visual, Some(FORWARD_PREVIEW_TAG));
1839 let card = visual.debug_bounds(FORWARD_CARD_TAG).expect("dialog card");
1840 let preview = visual.debug_bounds(FORWARD_PREVIEW_TAG).expect("preview");
1841 if !contains(window, card) || !contains(card, preview) {
1842 found.push(format!(
1843 "forward@{width}x{height}: dialog {} or preview {} clipped",
1844 describe(card),
1845 describe(preview)
1846 ));
1847 }
1848 let (left, right) = (
1849 inset(card, preview, Edge::Left),
1850 inset(card, preview, Edge::Right),
1851 );
1852 if (left - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1853 || (right - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1854 {
1855 found.push(format!(
1856 "forward@{width}x{height}: preview insets {left}/{right} != {FORWARD_DIALOG_PADDING}"
1857 ));
1858 }
1859 visual.simulate_keystrokes("escape");
1860 collect(&mut visual, None);
1861 assert!(visual.debug_bounds(FORWARD_CARD_TAG).is_none());
1862 assert!(
1863 visual.debug_bounds(FORWARD_FOOTER_TAG).is_some(),
1864 "closing the dialog keeps the selection"
1865 );
1866 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_forward_selection(cx)));
1867 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1868 assert!(visual.debug_bounds(FORWARD_FOOTER_TAG).is_none());
1869 assert!(found.is_empty(), "{}", found.join("\n"));
1870 }
1871 }
1872
1873 const MENU_ITEMS_SCANNED: usize = 40;
1874 const MENU_CHAT: &str = "demo-chat-release";
1875 const THEME_SELECT: &str = "settings-theme";
1876
1877 struct MenuRow {
1878 index: usize,
1879 item: Bounds<Pixels>,
1880 icon: Option<Bounds<Pixels>>,
1881 label: Option<Bounds<Pixels>>,
1882 }
1883
1884 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1885 (0..MENU_ITEMS_SCANNED)
1886 .filter_map(|index| {
1887 let item =
1888 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1889 Some(MenuRow {
1890 index,
1891 item,
1892 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1893 label: visual
1894 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1895 })
1896 })
1897 .collect()
1898 }
1899
1900 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1901 let mut found = Vec::new();
1902 for row in rows {
1903 let Some(icon) = row.icon else {
1904 continue;
1905 };
1906 let key = format!("{MENU}/item-{}", row.index);
1907 if let Some(label) = row.label {
1908 let gap = f32::from(label.left() - icon.right());
1909 if (gap - expected_gap).abs() > TOLERANCE {
1910 found.push((
1911 format!("{key}:icon-gap"),
1912 format!(
1913 "icon {} to label {} is {gap} px, expected {expected_gap}",
1914 describe(icon),
1915 describe(label)
1916 ),
1917 ));
1918 }
1919 }
1920 let offset = f32::from(icon.center().y - row.item.center().y);
1921 if offset.abs() > TOLERANCE {
1922 found.push((
1923 format!("{key}:icon-off-centre"),
1924 format!(
1925 "icon {} sits {offset} px off the centre of item {}",
1926 describe(icon),
1927 describe(row.item)
1928 ),
1929 ));
1930 }
1931 }
1932 found
1933 }
1934
1935 fn listbox_violations(
1936 trigger: Bounds<Pixels>,
1937 menu: Bounds<Pixels>,
1938 items: Bounds<Pixels>,
1939 rows: &[MenuRow],
1940 ) -> Vec<(String, String)> {
1941 let mut found = Vec::new();
1942 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1943 if !near(f32::from(menu.left() - trigger.left()), 0.) {
1944 found.push((
1945 format!("{MENU}:not-aligned-to-trigger"),
1946 format!(
1947 "list {} must start at the trigger's left edge {}",
1948 describe(menu),
1949 describe(trigger)
1950 ),
1951 ));
1952 }
1953 if !near(
1954 f32::from(menu.top() - trigger.bottom()),
1955 f32::from(DROPDOWN_OFFSET),
1956 ) {
1957 found.push((
1958 format!("{MENU}:trigger-offset"),
1959 format!(
1960 "list {} must open {} px below the trigger {}",
1961 describe(menu),
1962 f32::from(DROPDOWN_OFFSET),
1963 describe(trigger)
1964 ),
1965 ));
1966 }
1967 if menu.size.width < trigger.size.width - px(TOLERANCE) {
1968 found.push((
1969 format!("{MENU}:narrower-than-trigger"),
1970 format!(
1971 "list {} is narrower than the trigger {}",
1972 describe(menu),
1973 describe(trigger)
1974 ),
1975 ));
1976 }
1977 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1978 let top = f32::from(first.item.top() - items.top());
1979 let bottom = f32::from(items.bottom() - last.item.bottom());
1980 let padding = f32::from(MENU_LIST_PADDING);
1981 if !near(top, padding) || !near(bottom, padding) {
1982 found.push((
1983 format!("{MENU}:uneven-padding"),
1984 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1985 ));
1986 }
1987 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1988 match first.icon {
1989 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1990 check => found.push((
1991 format!("{MENU}:check-inset"),
1992 format!(
1993 "check column {check:?} must start {expected_inset} px inside the list {}",
1994 describe(menu)
1995 ),
1996 )),
1997 }
1998 }
1999 found
2000 }
2001
2002 #[test]
2003 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
2004 let row =
2005 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
2006 index,
2007 item: rectangle(4., item_top, 120., 32.),
2008 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
2009 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
2010 };
2011 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
2012 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
2013 .into_iter()
2014 .map(|(key, _)| key)
2015 .collect();
2016 assert_eq!(
2017 keys,
2018 [
2019 "popup-menu/item-1:icon-gap",
2020 "popup-menu/item-1:icon-off-centre"
2021 ]
2022 );
2023
2024 let trigger = rectangle(100., 50., 216., 32.);
2025 let option = |index: usize, top: f32| MenuRow {
2026 index,
2027 item: rectangle(104., top, 208., 32.),
2028 icon: Some(rectangle(110., top + 8., 16., 16.)),
2029 label: Some(rectangle(132., top + 6., 80., 20.)),
2030 };
2031 let aligned = [option(0, 88.), option(1, 122.)];
2032 let menu = rectangle(100., 84., 216., 74.);
2033 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
2034 let shifted = rectangle(96., 90., 200., 80.);
2035 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
2036 .into_iter()
2037 .map(|(key, _)| key)
2038 .collect();
2039 assert_eq!(
2040 keys,
2041 [
2042 "popup-menu:not-aligned-to-trigger",
2043 "popup-menu:trigger-offset",
2044 "popup-menu:narrower-than-trigger",
2045 "popup-menu:uneven-padding",
2046 "popup-menu:check-inset",
2047 ]
2048 );
2049 }
2050
2051 #[gpui_kit::test]
2052 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
2053 let (handle, _) = mount(cx);
2054 let mut visual = VisualTestContext::from_window(handle, cx);
2055 visual.simulate_resize(size(px(1280.), px(800.)));
2056 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
2057 collect(&mut visual, Some(chat_row));
2058 let mut found = Vec::new();
2059 let own_status = visual
2060 .debug_bounds(OWN_STATUS)
2061 .expect("own status button rendered");
2062 visual.simulate_click(own_status.center(), Default::default());
2063 collect(&mut visual, Some(MENU));
2064 let status_rows = menu_rows(&mut visual);
2065 assert!(
2066 status_rows.iter().any(|row| row.icon.is_some()),
2067 "status menu shows icons"
2068 );
2069 found.extend(menu_row_violations(
2070 &status_rows,
2071 f32::from(MENU_ICON_LABEL_GAP),
2072 ));
2073 visual.simulate_keystrokes("escape");
2074 collect(&mut visual, None);
2075 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
2076 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
2077 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
2078 collect(&mut visual, Some(MENU));
2079 let chat_rows = menu_rows(&mut visual);
2080 assert!(
2081 chat_rows.iter().any(|row| row.icon.is_some()),
2082 "chat menu shows icons"
2083 );
2084 found.extend(menu_row_violations(
2085 &chat_rows,
2086 f32::from(MENU_ICON_LABEL_GAP),
2087 ));
2088 let found: Vec<String> = found
2089 .into_iter()
2090 .map(|(key, message)| format!("{key}: {message}"))
2091 .collect();
2092 assert!(found.is_empty(), "{}", found.join("\n"));
2093 }
2094
2095 #[gpui_kit::test]
2096 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2097 let (handle, state) = mount(cx);
2098 let mut visual = VisualTestContext::from_window(handle, cx);
2099 visual.simulate_resize(size(px(1280.), px(800.)));
2100 visual.update(|_, cx| {
2101 state.update(cx, |state, cx| {
2102 state.open_settings(SettingsSection::Appearance, cx)
2103 })
2104 });
2105 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
2106 collect(&mut visual, Some(select));
2107 let trigger = visual.debug_bounds(select).expect("theme select rendered");
2108 visual.simulate_click(trigger.center(), Default::default());
2109 collect(&mut visual, Some(MENU));
2110 let menu = visual.debug_bounds(MENU).expect("list rendered");
2111 let items = visual
2112 .debug_bounds(ITEMS_SELECTOR)
2113 .expect("list items rendered");
2114 let rows = menu_rows(&mut visual);
2115 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
2116 .into_iter()
2117 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
2118 .map(|(key, message)| format!("{key}: {message}"))
2119 .collect();
2120 assert!(found.is_empty(), "{}", found.join("\n"));
2121 }
2122
2123 const BADGE_SAMPLES: [(u32, bool); 5] =
2124 [(1, false), (42, false), (120, false), (7, true), (15, true)];
2125
2126 struct BadgeSamples;
2127
2128 impl gpui_kit::Render for BadgeSamples {
2129 fn render(
2130 &mut self,
2131 _: &mut gpui_kit::Window,
2132 _: &mut gpui_kit::Context<Self>,
2133 ) -> impl gpui_kit::IntoElement {
2134 use gpui_kit::{ParentElement as _, Styled as _};
2135 gpui_kit::div()
2136 .flex()
2137 .gap(px(12.))
2138 .p(px(12.))
2139 .children(BADGE_SAMPLES.map(|(count, rail)| {
2140 if rail {
2141 badge_pill(
2142 count,
2143 RAIL_BADGE,
2144 crate::theme::accent(),
2145 crate::theme::on_accent(),
2146 )
2147 } else {
2148 count_badge(count, false)
2149 }
2150 }))
2151 }
2152 }
2153
2154 fn badge_violation(
2155 text: &str,
2156 pill: Bounds<Pixels>,
2157 label: Bounds<Pixels>,
2158 ink_offset: (f32, f32),
2159 ) -> Option<(String, String)> {
2160 let ink_x = f32::from(label.center().x) + ink_offset.0;
2161 let ink_y = f32::from(label.center().y) + ink_offset.1;
2162 let off_x = ink_x - f32::from(pill.center().x);
2163 let off_y = ink_y - f32::from(pill.center().y);
2164 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
2165 (
2166 format!("count-badge/{text}:off-centre"),
2167 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
2168 )
2169 })
2170 }
2171
2172 #[test]
2173 fn badge_rule_flags_off_centre_text() {
2174 let pill = rectangle(0., 0., 18., 18.);
2175 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
2176 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
2177 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
2178 }
2179
2180 #[gpui_kit::test]
2181 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
2182 cx.update(gpui_kit::init);
2183 cx.update(crate::theme::apply);
2184 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
2185 collect(visual, None);
2186 let mut found = Vec::new();
2187 for (count, rail) in BADGE_SAMPLES {
2188 let text = crate::format::badge_text(count);
2189 let pill = visual
2190 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
2191 .expect("badge rendered");
2192 let label = visual
2193 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
2194 .expect("badge text rendered");
2195 let font_size = if rail {
2196 RAIL_BADGE.font_size
2197 } else {
2198 COUNT_BADGE.font_size
2199 };
2200 let offset = visual.update(|window, _| {
2201 let origin = badge_text_origin(window, &text, font_size, pill);
2202 let (ink_centre, cap_height) = badge_ink_centre(window, &text, font_size);
2203 (
2204 f32::from(origin.x) + ink_centre - f32::from(label.center().x),
2205 f32::from(origin.y) - cap_height / 2. - f32::from(label.center().y),
2206 )
2207 });
2208 found.extend(badge_violation(&text, pill, label, offset));
2209 }
2210 let found: Vec<String> = found
2211 .into_iter()
2212 .map(|(key, message)| format!("{key}: {message}"))
2213 .collect();
2214 assert!(found.is_empty(), "{}", found.join("\n"));
2215 }
2216
2217 const PINNED_CHAT: &str = "demo-chat-release";
2218 const PINNED_CHANNEL: &str = "demo-channel-1-1";
2219
2220 #[gpui_kit::test]
2221 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
2222 let (handle, state) = mount(cx);
2223 let mut visual = VisualTestContext::from_window(handle, cx);
2224 let mut found = Vec::new();
2225 for (width, height) in SIZES {
2226 visual.simulate_resize(size(px(width), px(height)));
2227 visual.update(|_, cx| {
2228 state.update(cx, |state, cx| {
2229 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
2230 })
2231 });
2232 collect(&mut visual, Some(PIN_BANNER_TAG));
2233 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
2234 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2235 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2236 let gaps = [
2237 ("top", f32::from(banner.top() - timeline.top())),
2238 ("left", f32::from(banner.left() - timeline.left())),
2239 ("right", f32::from(timeline.right() - banner.right())),
2240 ("below divider", f32::from(banner.top() - divider.bottom())),
2241 ];
2242 let runway = runway_margin(f32::from(timeline.size.width) - 2. * BANNER_INSET);
2243 let sides_ok = gaps[1..3]
2244 .iter()
2245 .all(|(_, gap)| (gap - BANNER_INSET - runway).abs() <= INSET_TOLERANCE);
2246 let vertical_ok = [gaps[0].1, gaps[3].1]
2247 .iter()
2248 .all(|gap| (gap - BANNER_INSET).abs() <= INSET_TOLERANCE);
2249 if !sides_ok || !vertical_ok {
2250 found.push(format!(
2251 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
2252 ));
2253 }
2254 }
2255 assert!(found.is_empty(), "{}", found.join("\n"));
2256 }
2257
2258 #[gpui_kit::test]
2259 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
2260 let (handle, state) = mount(cx);
2261 let mut visual = VisualTestContext::from_window(handle, cx);
2262 visual.simulate_resize(size(px(1280.), px(800.)));
2263 visual.update(|_, cx| {
2264 state.update(cx, |state, cx| {
2265 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2266 })
2267 });
2268 collect(&mut visual, Some(TIMELINE_TAG));
2269 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
2270 }
2271
2272 fn open_channel(cx: &mut TestAppContext, awaited: &'static str) -> VisualTestContext {
2273 let (handle, state) = mount(cx);
2274 let mut visual = VisualTestContext::from_window(handle, cx);
2275 visual.simulate_resize(size(px(1280.), px(800.)));
2276 visual.update(|_, cx| {
2277 state.update(cx, |state, cx| {
2278 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2279 })
2280 });
2281 collect(&mut visual, Some(awaited));
2282 visual
2283 }
2284
2285 #[gpui_kit::test]
2286 fn the_new_post_is_one_card_with_subject_divider_format_bar_and_post_button(
2287 cx: &mut TestAppContext,
2288 ) {
2289 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2290 let open = visual
2291 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2292 .expect("post in channel card");
2293 visual.simulate_click(open.center(), Default::default());
2294 collect(&mut visual, Some(POST_CARD_SEND_TAG));
2295 let mut bounds_of = |path: &'static str| {
2296 visual
2297 .debug_bounds(path)
2298 .unwrap_or_else(|| panic!("{path} missing"))
2299 };
2300 let card = bounds_of(COMPOSER_BOX_TAG);
2301 let header = bounds_of(POST_CARD_HEADER_TAG);
2302 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2303 let divider = bounds_of(POST_CARD_DIVIDER_TAG);
2304 let format_bar = bounds_of(COMPOSER_FORMAT_BAR_TAG);
2305 let footer = bounds_of(POST_CARD_FOOTER_TAG);
2306 let send = bounds_of(POST_CARD_SEND_TAG);
2307 assert!(
2308 visual.debug_bounds(COMPOSER_SEND_TAG).is_none(),
2309 "chat send button shown in a post"
2310 );
2311 assert!(
2312 visual.debug_bounds(COMPOSER_FORMAT_TAG).is_none(),
2313 "format toggle shown although the bar stays open"
2314 );
2315 assert!(header.bottom() <= subject.top() && subject.bottom() <= divider.top());
2316 assert!(divider.bottom() <= format_bar.top() && format_bar.bottom() <= footer.top());
2317 assert!(
2318 f32::from(divider.left() - card.left()).abs() < 1.5
2319 && f32::from(card.right() - divider.right()).abs() < 1.5,
2320 "subject divider {} does not run edge to edge in {}",
2321 describe(divider),
2322 describe(card)
2323 );
2324 let side = f32::from(card.right() - send.right());
2325 let bottom = f32::from(card.bottom() - send.bottom());
2326 assert!(
2327 (side - bottom).abs() < TOLERANCE,
2328 "Post button insets: side {side}, bottom {bottom}"
2329 );
2330 }
2331
2332 #[gpui_kit::test]
2333 fn announcement_mode_puts_the_banner_between_author_and_subheading(cx: &mut TestAppContext) {
2334 let mut visual = open_channel(cx, crate::views::post_card::POST_IN_CHANNEL_TAG);
2335 let open = visual
2336 .debug_bounds(crate::views::post_card::POST_IN_CHANNEL_TAG)
2337 .expect("post in channel card");
2338 visual.simulate_click(open.center(), Default::default());
2339 collect(&mut visual, Some(POST_ANNOUNCEMENT_TOGGLE_TAG));
2340 let toggle = visual
2341 .debug_bounds(POST_ANNOUNCEMENT_TOGGLE_TAG)
2342 .expect("announcement toggle in the format bar");
2343 let format_bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("format bar");
2344 assert!(format_bar.contains(&toggle.center()), "toggle outside the format bar");
2345 visual.simulate_click(toggle.center(), Default::default());
2346 collect(&mut visual, Some(POST_ANNOUNCEMENT_TAG));
2347 let mut bounds_of = |path: &'static str| {
2348 visual
2349 .debug_bounds(path)
2350 .unwrap_or_else(|| panic!("{path} missing"))
2351 };
2352 let card = bounds_of(COMPOSER_BOX_TAG);
2353 let header = bounds_of(POST_CARD_HEADER_TAG);
2354 let banner = bounds_of(POST_ANNOUNCEMENT_TAG);
2355 let subject = bounds_of(POST_CARD_SUBJECT_TAG);
2356 assert!(header.bottom() <= banner.top() && banner.bottom() <= subject.top());
2357 let gap = f32::from(subject.top() - banner.bottom());
2358 assert!(gap >= 6., "subheading {gap} px under the banner");
2359 let audience = bounds_of(POST_AUDIENCE_TAG);
2360 assert!(audience.bottom() <= card.top(), "audience hint not above the card");
2361 let left = f32::from(banner.left() - card.left());
2362 let right = f32::from(card.right() - banner.right());
2363 assert!((left - right).abs() < TOLERANCE, "banner insets: left {left}, right {right}");
2364 }
2365
2366 #[gpui_kit::test]
2367 fn channel_posts_start_the_body_at_the_avatar_edge_like_teams(cx: &mut TestAppContext) {
2368 let mut visual = open_channel(cx, POST_FOOTER_AVATAR_TAG);
2369 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
2370 visual
2371 .debug_bounds(path)
2372 .unwrap_or_else(|| panic!("{path} rendered"))
2373 };
2374 let card = bounds_of(&mut visual, POST_CARD_TAG);
2375 let avatar = bounds_of(&mut visual, POST_AVATAR_TAG);
2376 let body = bounds_of(&mut visual, POST_BODY_TAG);
2377 let footer_avatar = bounds_of(&mut visual, POST_FOOTER_AVATAR_TAG);
2378 let side = f32::from(avatar.left() - card.left());
2379 let checks = [
2380 ("body left", f32::from(body.left() - avatar.left())),
2381 ("footer avatar left", f32::from(footer_avatar.left() - avatar.left())),
2382 ("body right inset", f32::from(card.right() - body.right()) - side),
2383 ];
2384 for (name, gap) in checks {
2385 assert!(
2386 gap.abs() < INSET_TOLERANCE,
2387 "{name} off by {gap}: card {card:?} avatar {avatar:?} body {body:?} footer {footer_avatar:?}"
2388 );
2389 }
2390 }
2391
2392 #[gpui_kit::test]
2393 fn a_code_line_is_one_frame_inside_the_post_body(cx: &mut TestAppContext) {
2394 let mut visual = open_channel(cx, CODE_LINE_TAG);
2395 let code = visual.debug_bounds(CODE_LINE_TAG).expect("code line");
2396 let body = visual.debug_bounds(POST_BODY_TAG).expect("post body");
2397 assert!(
2398 f32::from(code.size.height) > 40.,
2399 "the long code line wraps inside one frame: {code:?}"
2400 );
2401 assert!(
2402 (f32::from(code.left() - body.left())).abs() < INSET_TOLERANCE
2403 && code.right() <= body.right() + px(INSET_TOLERANCE),
2404 "code {code:?} sits inside the body {body:?}"
2405 );
2406 assert!(visual.debug_bounds(CODE_BLOCK_TAG).is_none());
2407 }
2408
2409 #[gpui_kit::test]
2410 fn the_new_post_row_shows_a_scroll_edge_only_while_scrolled(cx: &mut TestAppContext) {
2411 let mut visual = open_channel(cx, POST_CARD_TAG);
2412 assert!(visual.debug_bounds(FEED_EDGE_TAG).is_none());
2413 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2414 visual.simulate_event(ScrollWheelEvent {
2415 position: timeline.center(),
2416 delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
2417 ..Default::default()
2418 });
2419 collect(&mut visual, Some(FEED_EDGE_TAG));
2420 let edge = visual.debug_bounds(FEED_EDGE_TAG).expect("feed edge");
2421 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2422 assert!(
2423 (f32::from(edge.top() - timeline.top())).abs() < INSET_TOLERANCE
2424 && (f32::from(edge.left() - timeline.left())).abs() < INSET_TOLERANCE
2425 && (f32::from(timeline.right() - edge.right())).abs() < INSET_TOLERANCE,
2426 "edge {edge:?} runs across the top of the timeline {timeline:?}"
2427 );
2428 }
2429
2430 #[gpui_kit::test]
2431 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
2432 let (handle, state) = mount(cx);
2433 let mut visual = VisualTestContext::from_window(handle, cx);
2434 visual.simulate_resize(size(px(1280.), px(800.)));
2435 visual.update(|_, cx| {
2436 state.update(cx, |state, cx| {
2437 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2438 })
2439 });
2440 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2441 let button = visual
2442 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2443 .expect("channel details button");
2444 visual.simulate_click(button.center(), Default::default());
2445 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
2446 let pane = visual
2447 .debug_bounds(CHANNEL_DETAILS_TAG)
2448 .expect("details pane");
2449 let main = visual.debug_bounds(MAIN).expect("main island");
2450 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
2451 assert!(
2452 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
2453 "pane {pane:?} must end at the main island edge {main:?}"
2454 );
2455 assert!(
2456 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
2457 "pane {pane:?} must start under the header divider {divider:?}"
2458 );
2459 }
2460
2461 #[gpui_kit::test]
2462 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
2463 let (handle, state) = mount(cx);
2464 let mut visual = VisualTestContext::from_window(handle, cx);
2465 visual.simulate_resize(size(px(1280.), px(800.)));
2466 visual.update(|_, cx| {
2467 state.update(cx, |state, cx| {
2468 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
2469 })
2470 });
2471 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
2472 let button = visual
2473 .debug_bounds(CHANNEL_DETAILS_BUTTON)
2474 .expect("channel details button");
2475 visual.simulate_click(button.center(), Default::default());
2476 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
2477 let pane = visual
2478 .debug_bounds(CHANNEL_DETAILS_TAG)
2479 .expect("details pane");
2480 let pinned = visual
2481 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
2482 .expect("pinned section");
2483 let shared = visual
2484 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
2485 .expect("shared section");
2486 assert!(
2487 pinned.bottom() <= shared.top(),
2488 "pinned {pinned:?} must come before shared {shared:?}"
2489 );
2490 for (name, section) in [("pinned", pinned), ("shared", shared)] {
2491 let left = f32::from(section.left() - pane.left());
2492 let right = f32::from(pane.right() - section.right());
2493 assert!(
2494 (left - right).abs() < INSET_TOLERANCE && left > 0.,
2495 "{name} section insets left {left} right {right} must match"
2496 );
2497 }
2498 }
2499
2500 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
2501 collect(visual, Some(COMPOSER_SEND_TAG));
2502 let mut bounds_of = |path: &'static str| {
2503 visual
2504 .debug_bounds(path)
2505 .unwrap_or_else(|| panic!("{path} rendered"))
2506 };
2507 let composer = bounds_of(COMPOSER_BOX_TAG);
2508 let input = bounds_of(COMPOSER_INPUT_TAG);
2509 let actions = bounds_of(COMPOSER_ACTIONS_TAG);
2510 let send = bounds_of(COMPOSER_SEND_TAG);
2511 [
2512 f32::from(input.left() - composer.left()),
2513 f32::from(actions.top() - composer.top()),
2514 f32::from(composer.bottom() - actions.bottom()),
2515 f32::from(composer.right() - send.right()),
2516 f32::from(send.top() - composer.top()),
2517 f32::from(composer.bottom() - send.bottom()),
2518 ]
2519 }
2520
2521 #[gpui_kit::test]
2522 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
2523 let (handle, _) = mount(cx);
2524 let mut visual = VisualTestContext::from_window(handle, cx);
2525 visual.simulate_resize(size(px(1280.), px(800.)));
2526 let single_line = composer_button_insets(&mut visual);
2527 let left = single_line[0];
2528 assert!(
2529 single_line
2530 .iter()
2531 .all(|inset| (inset - left).abs() < TOLERANCE),
2532 "single line: insets of the input left, the actions top and bottom, send right, top and bottom {single_line:?}"
2533 );
2534 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2535 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
2536 visual.simulate_click(point(input.center().x, send.center().y), Default::default());
2537 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
2538 let three_lines = composer_button_insets(&mut visual);
2539 assert!(
2540 three_lines[1] > single_line[1] + 30.,
2541 "three lines did not grow the composer: {three_lines:?}"
2542 );
2543 for inset in [
2544 three_lines[0],
2545 three_lines[2],
2546 three_lines[3],
2547 three_lines[5],
2548 ] {
2549 assert!(
2550 (inset - left).abs() < TOLERANCE,
2551 "three lines: insets of the input left, the actions top and bottom, send right, top and bottom {three_lines:?}, expected {left}"
2552 );
2553 }
2554 }
2555
2556 #[gpui_kit::test]
2557 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
2558 const FORMAT_TAGS: [&str; 6] = [
2559 COMPOSER_BOX_TAG,
2560 COMPOSER_FORMAT_BAR_TAG,
2561 COMPOSER_FORMAT_DIVIDER_TAG,
2562 COMPOSER_ACTIONS_TAG,
2563 COMPOSER_FORMAT_TAG,
2564 COMPOSER_SEND_TAG,
2565 ];
2566 let (handle, _) = mount(cx);
2567 let mut visual = VisualTestContext::from_window(handle, cx);
2568 for (width, height) in SIZES {
2569 visual.simulate_resize(size(px(width), px(height)));
2570 let window = Bounds {
2571 origin: point(px(0.), px(0.)),
2572 size: size(px(width), px(height)),
2573 };
2574 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
2575 let toggle = visual
2576 .debug_bounds(COMPOSER_FORMAT_TAG)
2577 .expect("format button");
2578 visual.simulate_click(toggle.center(), Default::default());
2579 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
2580 let tags: Vec<Tag> = FORMAT_TAGS
2581 .iter()
2582 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2583 .collect();
2584 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
2585 .into_iter()
2586 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
2587 .collect();
2588 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
2589 let actions = visual.debug_bounds(COMPOSER_ACTIONS_TAG).expect("actions");
2590 let toggle = visual
2591 .debug_bounds(COMPOSER_FORMAT_TAG)
2592 .expect("format button");
2593 visual.simulate_click(toggle.center(), Default::default());
2594 collect(&mut visual, None);
2595 assert!(found.is_empty(), "{}", found.join("\n"));
2596 assert!(
2597 bar.bottom() <= actions.top(),
2598 "bar {bar:?} over the buttons {actions:?}"
2599 );
2600 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
2601 }
2602 }
2603
2604 #[gpui_kit::test]
2605 fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2606 let (handle, _) = mount_with(cx, true);
2607 let mut visual = VisualTestContext::from_window(handle, cx);
2608 visual.dispatch_action(OpenActivity);
2609 for (width, height) in SIZES {
2610 visual.simulate_resize(size(px(width), px(height)));
2611 let window = Bounds {
2612 origin: point(px(0.), px(0.)),
2613 size: size(px(width), px(height)),
2614 };
2615 let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2616 let mut expected = GUARDED.to_vec();
2617 expected.push(ACTIVITY_PROPOSALS_TAG);
2618 let found: Vec<String> = violations(&tags, window, &expected)
2619 .into_iter()
2620 .map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2621 .collect();
2622 assert!(found.is_empty(), "{}", found.join("\n"));
2623 }
2624 }
2625
2626 #[gpui_kit::test]
2627 fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2628 const DELIVERY_TAGS: [&str; 5] = [
2629 COMPOSER_BOX_TAG,
2630 COMPOSER_ACTIONS_TAG,
2631 COMPOSER_PLUS_TAG,
2632 COMPOSER_IMPORTANCE_LABEL_TAG,
2633 COMPOSER_URGENT_BANNER_TAG,
2634 ];
2635 const URGENT_OPTION: &str = "urgent-delivery-option";
2636 const TEXT_INSET: f32 = 6.;
2637 let (handle, _) = mount(cx);
2638 let mut visual = VisualTestContext::from_window(handle, cx);
2639 for (width, height) in SIZES {
2640 visual.simulate_resize(size(px(width), px(height)));
2641 let window = Bounds {
2642 origin: point(px(0.), px(0.)),
2643 size: size(px(width), px(height)),
2644 };
2645 collect(&mut visual, Some(COMPOSER_PLUS_TAG));
2646 let button = visual.debug_bounds(COMPOSER_PLUS_TAG).expect("plus button");
2647 visual.simulate_click(button.center(), Default::default());
2648 let delivery_tag = PlusAction::DeliveryOptions.tag();
2649 collect(&mut visual, Some(delivery_tag));
2650 let delivery = visual.debug_bounds(delivery_tag).expect("delivery item");
2651 visual.simulate_click(delivery.center(), Default::default());
2652 collect(&mut visual, Some(URGENT_OPTION));
2653 let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2654 assert!(
2655 contains(window, menu),
2656 "menu {} leaves the window",
2657 describe(menu)
2658 );
2659 let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2660 visual.simulate_click(urgent.center(), Default::default());
2661 collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2662 assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2663 let tags: Vec<Tag> = DELIVERY_TAGS
2664 .iter()
2665 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2666 .collect();
2667 let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2668 .into_iter()
2669 .map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2670 .collect();
2671 assert!(found.is_empty(), "{}", found.join("\n"));
2672 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2673 let banner = visual
2674 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2675 .expect("banner");
2676 let label = visual
2677 .debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2678 .expect("label");
2679 let input = visual.debug_bounds(COMPOSER_INPUT_TAG).expect("input");
2680 assert!(
2681 (f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2682 && (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2683 "banner {} not on the composer edges {}",
2684 describe(banner),
2685 describe(composer)
2686 );
2687 assert!(
2688 banner.bottom() <= composer.top(),
2689 "banner {} over the composer {}",
2690 describe(banner),
2691 describe(composer)
2692 );
2693 assert!(
2694 (inset(composer, label, Edge::Left)
2695 - inset(composer, input, Edge::Left)
2696 - TEXT_INSET)
2697 .abs()
2698 <= TOLERANCE,
2699 "label {} not on the text edge of {}",
2700 describe(label),
2701 describe(input)
2702 );
2703 let close = visual
2704 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2705 .map(|banner| point(banner.right() - px(18.), banner.center().y))
2706 .expect("banner");
2707 visual.simulate_click(close, Default::default());
2708 collect(&mut visual, None);
2709 assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
2710 assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
2711 }
2712 }
2713
2714 #[gpui_kit::test]
2715 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
2716 let (handle, state) = mount_with(cx, true);
2717 let mut visual = VisualTestContext::from_window(handle, cx);
2718 for (width, height) in SIZES {
2719 visual.simulate_resize(size(px(width), px(height)));
2720 for chat in IMPORTANCE_CHATS {
2721 visual.update(|_, cx| {
2722 state.update(cx, |state, cx| {
2723 state.select(Selection::Chat(chat.to_owned()), cx)
2724 })
2725 });
2726 collect(&mut visual, Some(TIMELINE_TAG));
2727 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2728 visual.simulate_event(ScrollWheelEvent {
2729 position: timeline.center(),
2730 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
2731 ..Default::default()
2732 });
2733 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
2734 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
2735 let bubble = BUBBLE_TAGS
2736 .iter()
2737 .filter_map(|tag| visual.debug_bounds(tag))
2738 .find(|bubble| contains(*bubble, label))
2739 .unwrap_or_else(|| {
2740 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
2741 });
2742 let left = inset(bubble, label, Edge::Left);
2743 let top = inset(bubble, label, Edge::Top);
2744 assert!(
2745 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2746 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
2747 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2748 describe(bubble)
2749 );
2750 }
2751 }
2752 }
2753
2754 #[gpui_kit::test]
2755 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2756 let (handle, state) = mount_with(cx, true);
2757 let mut visual = VisualTestContext::from_window(handle, cx);
2758 for (width, height) in SIZES {
2759 visual.simulate_resize(size(px(width), px(height)));
2760 let window = Bounds {
2761 origin: point(px(0.), px(0.)),
2762 size: size(px(width), px(height)),
2763 };
2764 for (chat, expected_tags) in [
2765 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
2766 (REACTION_CHAT, &AGENT_TAGS[3..]),
2767 ] {
2768 visual.update(|_, cx| {
2769 state.update(cx, |state, cx| {
2770 state.select(Selection::Chat(chat.to_owned()), cx)
2771 })
2772 });
2773 let tags = collect(&mut visual, Some(expected_tags[0]));
2774 let mut expected = GUARDED.to_vec();
2775 expected.extend(expected_tags);
2776 let found: Vec<String> = violations(&tags, window, &expected)
2777 .into_iter()
2778 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
2779 .collect();
2780 assert!(found.is_empty(), "{}", found.join("\n"));
2781 }
2782 }
2783 }
2784}
2785
2786#[test]
2787fn lines_are_solid() {
2788 let mut files = Vec::new();
2789 for root in source_roots() {
2790 source_files(&root, &mut files);
2791 }
2792 let violations: Vec<String> = files
2793 .iter()
2794 .filter(|file| !file.ends_with("layout_guard.rs"))
2795 .flat_map(|file| {
2796 let source = fs::read_to_string(file).expect("read source file");
2797 source
2798 .lines()
2799 .enumerate()
2800 .filter(|(_, line)| {
2801 line.contains(".border_dashed(") || line.contains(".border_dotted(")
2802 })
2803 .map(|(index, line)| {
2804 format!(
2805 "{}:{}: lines are always solid: {}",
2806 file.display(),
2807 index + 1,
2808 line.trim()
2809 )
2810 })
2811 .collect::<Vec<_>>()
2812 })
2813 .collect();
2814 assert!(violations.is_empty(), "{}", violations.join("\n"));
2815}
2816
2817const STATE_RING_COLORS: &[&str] = &[
2818 "if focused",
2819 "if selected",
2820 "if speaking",
2821 "if current",
2822 "if open",
2823 "if state.failed",
2824];
2825const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
2826 (
2827 "notify/ring_view.rs",
2828 "theme::green()",
2829 "state signal (pulsing ring around the caller while it rings), not a resting outline",
2830 ),
2831 (
2832 "settings/mcp.rs",
2833 "theme::border_strong()",
2834 "outlined button, not a surface",
2835 ),
2836 (
2837 "settings/rows.rs",
2838 "theme::border_strong()",
2839 "outlined button, not a surface",
2840 ),
2841 (
2842 "views/card_widgets.rs",
2843 "border)",
2844 "message content drawn as Teams renders it",
2845 ),
2846 (
2847 "views/card_widgets.rs",
2848 "theme::border_strong()",
2849 "message content drawn as Teams renders it",
2850 ),
2851 ("views/shared_tab.rs", "theme::accent()", "input field"),
2852 ("views/card_input.rs", "if error.is_some()", "input field"),
2853 ("views/format_toolbar.rs", "if refused", "input field"),
2854 (
2855 "views/card_code_block.rs",
2856 "theme::code_header_border()",
2857 "message content drawn as Teams renders it",
2858 ),
2859 (
2860 "render/elements.rs",
2861 "theme::code_frame()",
2862 "message content drawn as Teams renders it",
2863 ),
2864 ("views/call_transcript.rs", "theme::border()", "input field"),
2865 (
2866 "views/conversation.rs",
2867 "theme::accent()",
2868 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2869 ),
2870 (
2871 "views/attachment_tray.rs",
2872 "theme::accent()",
2873 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2874 ),
2875 (
2876 "views/card_carousel.rs",
2877 "theme::border_strong()",
2878 "message content drawn as Teams renders it",
2879 ),
2880 (
2881 "views/card_table.rs",
2882 "grid_color",
2883 "message content drawn as Teams renders it",
2884 ),
2885 (
2886 "views/activity_panel.rs",
2887 "theme::surface()",
2888 "cutout ring in the background color, invisible against its surface",
2889 ),
2890 (
2891 "views/avatar.rs",
2892 "theme::surface()",
2893 "cutout ring in the background color, invisible against its surface",
2894 ),
2895 (
2896 "views/message_row.rs",
2897 "theme::border_strong()",
2898 "deleted message placeholder, Teams look",
2899 ),
2900 (
2901 "views/message_row.rs",
2902 "theme::red()",
2903 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2904 ),
2905 (
2906 "views/message_row.rs",
2907 "if row.delivery",
2908 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2909 ),
2910 (
2911 "views/new_meeting_dialog.rs",
2912 "theme::border()",
2913 "input field",
2914 ),
2915 (
2916 "views/call_mini_window.rs",
2917 "theme::border_strong()",
2918 "self view over live video, needs an edge on any picture",
2919 ),
2920 ("views/transfer_picker.rs", "theme::border()", "input field"),
2921 (
2922 "views/call_notice.rs",
2923 "theme::border_strong()",
2924 "outlined button, not a surface",
2925 ),
2926 (
2927 "views/composer/schedule.rs",
2928 "theme::accent()",
2929 "input field",
2930 ),
2931 (
2932 "views/sidebar.rs",
2933 "theme::accent()",
2934 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2935 ),
2936 (
2937 "views/adaptive_card.rs",
2938 "theme::border()",
2939 "message content drawn as Teams renders it",
2940 ),
2941 (
2942 "views/adaptive_card.rs",
2943 "border)",
2944 "message content drawn as Teams renders it",
2945 ),
2946 (
2947 "views/share_bar.rs",
2948 "theme::red()",
2949 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
2950 ),
2951 ("settings_controls.rs", "if invalid", "input field"),
2952];
2953
2954fn outlines(source: &str) -> Vec<(usize, String)> {
2955 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
2956 pattern
2957 .find_iter(source)
2958 .map(|found| {
2959 let line_number = source[..found.start()].matches('\n').count() + 1;
2960 let after = &source[found.end()..];
2961 let color = after
2962 .find(".border_color(")
2963 .filter(|position| *position < 120)
2964 .map(|position| {
2965 let start = &after[position + ".border_color(".len()..];
2966 start
2967 .lines()
2968 .map(str::trim)
2969 .find(|line| !line.is_empty())
2970 .unwrap_or_default()
2971 .to_owned()
2972 })
2973 .unwrap_or_default();
2974 (line_number, color)
2975 })
2976 .collect()
2977}
2978
2979#[test]
2980fn outline_matcher_reads_the_border_color() {
2981 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
2982 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
2983}
2984
2985#[test]
2986fn surfaces_are_soft() {
2987 let mut matched_allowlist = HashSet::new();
2988 let mut violations = Vec::new();
2989 for root in source_roots() {
2990 let mut files = Vec::new();
2991 source_files(&root, &mut files);
2992 for file in files {
2993 let relative = file
2994 .strip_prefix(&root)
2995 .expect("inside src")
2996 .to_string_lossy()
2997 .replace('\\', "/");
2998 if relative == "layout_guard.rs" {
2999 continue;
3000 }
3001 let source = fs::read_to_string(&file).expect("read source file");
3002 for (line_number, color) in outlines(&source) {
3003 if STATE_RING_COLORS
3004 .iter()
3005 .any(|prefix| color.starts_with(prefix))
3006 {
3007 continue;
3008 }
3009 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
3010 *allowed_file == relative && color.starts_with(prefix)
3011 }) {
3012 Some(position) => {
3013 matched_allowlist.insert(position);
3014 }
3015 None => violations.push(format!(
3016 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
3017 )),
3018 }
3019 }
3020 }
3021 }
3022 let stale = OUTLINE_ALLOWLIST
3023 .iter()
3024 .enumerate()
3025 .filter(|(position, _)| !matched_allowlist.contains(position))
3026 .map(|(_, (file, prefix, _))| {
3027 format!("stale outline allowlist entry, remove it: {file} {prefix}")
3028 });
3029 let report: Vec<String> = violations.into_iter().chain(stale).collect();
3030 assert!(report.is_empty(), "{}", report.join("\n"));
3031}
3032
3033fn indentation(line: &str) -> usize {
3034 line.len() - line.trim_start().len()
3035}
3036
3037fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
3038 let indent = indentation(lines[index]);
3039 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
3040 let start = lines[..index]
3041 .iter()
3042 .rposition(|line| !belongs(line))
3043 .map_or(0, |position| position + 1);
3044 let end = lines[index..]
3045 .iter()
3046 .position(|line| !belongs(line))
3047 .map_or(lines.len(), |position| index + position);
3048 lines[start..end]
3049 .iter()
3050 .filter(|line| indentation(line) == indent)
3051 .copied()
3052 .collect()
3053}
3054
3055fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
3056 let lines: Vec<&str> = source.lines().collect();
3057 (0..lines.len())
3058 .filter(|&index| row_height.is_match(lines[index]))
3059 .filter(|&index| {
3060 !chain_lines(&lines, index).iter().any(|line| {
3061 let line = line.trim();
3062 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
3063 })
3064 })
3065 .map(|index| index + 1)
3066 .collect()
3067}
3068
3069fn row_height_pattern() -> Regex {
3070 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
3071}
3072
3073#[test]
3074fn matcher_finds_rows_without_flex_none() {
3075 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";
3076 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
3077}
3078
3079#[test]
3080fn fixed_height_rows_never_shrink() {
3081 let row_height = row_height_pattern();
3082 let mut files = Vec::new();
3083 for root in source_roots() {
3084 source_files(&root, &mut files);
3085 }
3086 let violations: Vec<String> = files
3087 .iter()
3088 .filter(|file| !file.ends_with("layout_guard.rs"))
3089 .flat_map(|file| {
3090 let source = fs::read_to_string(file).expect("read source file");
3091 shrinking_rows(&row_height, &source)
3092 .into_iter()
3093 .map(|line| format!("{}:{line}", file.display()))
3094 .collect::<Vec<_>>()
3095 })
3096 .collect();
3097 assert!(
3098 violations.is_empty(),
3099 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
3100 );
3101}