BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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