BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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