BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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