BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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