BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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