BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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