BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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