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