BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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