BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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