BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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