BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 79.8 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::{item_selector, label, label_selector, metrics};
175 use crate::settings_section::SettingsSection;
176 use crate::user_activity::UserInput;
177 use crate::views::call_transcript::TranscriptPanel;
178 use crate::views::call_view::CHAT_PANEL_TAG;
179 use crate::views::composer::{
180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 };
183 use crate::views::conversation::{
184 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
185 CHANNEL_DETAILS_TAG,
186 };
187 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
188 use crate::views::find_panel::{
189 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
190 };
191 use crate::views::message_row::BUBBLE_TAGS;
192 use crate::views::pin_banner::PIN_BANNER_TAG;
193 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
194 use crate::views::reaction_proposal_pill::REACTION_PILL;
195 use crate::views::recap_tab::RECAP_REGION;
196 use crate::views::shell::{
197 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
198 };
199 use crate::views::shortcuts::{
200 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
201 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
202 };
203 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
204 use crate::views::sidebar::chat_filter_bar::{
205 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
206 };
207 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
208
209 const GUARDED: &[&str] = &[
210 "shell",
211 "shell/title-bar",
212 "shell/title-bar/search",
213 "shell/title-bar/own-status",
214 "shell/title-bar/own-status/avatar",
215 OWN_AVATAR_DISC,
216 "shell/islands",
217 "shell/islands/rail",
218 "shell/islands/sidebar",
219 "shell/islands/main",
220 ];
221 const CALL_GUARDED: &[&str] = &[
222 "shell/islands/main/call-header",
223 "shell/islands/main/call-stage",
224 "shell/islands/main/call-controls",
225 "shell/islands/main/call-controls/mic",
226 "shell/islands/main/call-controls/leave",
227 ];
228 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
229 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
230 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
231 const FIND_TAGS: &[&str] = &[
232 FIND_PANEL_TAG,
233 FIND_DIVIDER_TAG,
234 FIND_INPUT_TAG,
235 FIND_RESULTS_TAG,
236 ];
237 const CALLS_TAGS: &[&str] = &[
238 "shell/islands/sidebar/calls-actions",
239 "shell/islands/sidebar/calls-actions/meet-now",
240 "shell/islands/sidebar/calls-actions/new-meeting",
241 ];
242 const PREJOIN_TAGS: &[&str] = &[
243 "shell/islands/main/prejoin",
244 "shell/islands/main/prejoin/preview",
245 "shell/islands/main/prejoin/controls",
246 "shell/islands/main/prejoin/devices",
247 "shell/islands/main/prejoin/audio",
248 "shell/islands/main/prejoin/actions",
249 ];
250 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";
251 const CONSULT_GUARDED: &[&str] = &[
252 "shell/islands/main/call-header/call-consult",
253 "shell/islands/main/call-header/call-consult/transfer",
254 "shell/islands/main/call-header/call-consult/resume",
255 ];
256 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
257 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
258 const SHARE_GUARDED: &[&str] = &[
259 "shell/islands/main/call-stage/share-content",
260 "shell/islands/main/call-stage/share-content/zoom-chip",
261 "shell/islands/main/call-stage/share-divider",
262 "shell/islands/main/call-stage/share-strip",
263 ];
264 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
265 const OVERLAY_CHROME: &[&str] = &[
266 "shell/islands/main/call-header",
267 "shell/islands/main/call-stage",
268 ];
269 const MENU: &str = "popup-menu";
270 const OWN_STATUS: &str = "shell/title-bar/own-status";
271 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
272 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
273 const PROPOSAL_CHAT: &str = "demo-chat-release";
274 const REACTION_CHAT: &str = "demo-chat-mara";
275 const AGENT_TAGS: [&str; 4] = [
276 PROPOSAL_CARD,
277 PROPOSAL_THUMBNAILS,
278 PROPOSAL_BUTTONS,
279 REACTION_PILL,
280 ];
281 const SETTINGS_TAGS: &[&str] = &[
282 "settings",
283 "settings/nav",
284 "settings/nav/divider",
285 "settings/nav/about",
286 "settings/main",
287 "settings/main/header",
288 "settings/main/header/close",
289 "settings/main/body",
290 ];
291 const SETTINGS_BODY: &str = "settings/main/body";
292 const SETTINGS_NAV: &str = "settings/nav";
293 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
294 const NAV_LABEL_SIZE: f32 = 14.;
295 const NAV_LINE_HEIGHT: f32 = 20.;
296 const SETTINGS_CONTENT: &str = "settings/main/body/content";
297 const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
298 const MEMBERS_CHAT: &str = "demo-chat-release";
299 const SIDEBAR: &str = "shell/islands/sidebar";
300 const MAIN: &str = "shell/islands/main";
301 const EDGE_DIVIDERS: &[&str] = &[SIDEBAR_SCROLL_DIVIDER, HEADER_DIVIDER];
302 const DIVIDER_SEGMENT: &str = "divider";
303 const DIVIDER_THICKNESS: f32 = 1.;
304 const INSET_TOLERANCE: f32 = 1.;
305 const INSET_RULES: &[InsetRule] = &[
306 InsetRule {
307 panel: "settings/nav",
308 content: "settings/nav/about",
309 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
310 },
311 InsetRule {
312 panel: "settings/main",
313 content: "settings/main/header/close",
314 edges: &[Edge::Top, Edge::Right],
315 },
316 ];
317 const SCROLLED_INSET_RULE: InsetRule = InsetRule {
318 panel: SETTINGS_BODY,
319 content: SETTINGS_CONTENT,
320 edges: &[Edge::Left, Edge::Bottom],
321 };
322 const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
323 SettingsSection::Agents,
324 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
325 )];
326 const SETTINGS_SECTIONS: [SettingsSection; 9] = [
327 SettingsSection::General,
328 SettingsSection::Notifications,
329 SettingsSection::Appearance,
330 SettingsSection::Chats,
331 SettingsSection::Calls,
332 SettingsSection::Devices,
333 SettingsSection::Agents,
334 SettingsSection::Mcp,
335 SettingsSection::About,
336 ];
337 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
338 const TOLERANCE: f32 = 0.5;
339 const KNOWN_VIOLATIONS: &[&str] = &[];
340 const ZOOM_STEP: f32 = 1.25;
341
342 type Tag = (&'static str, Bounds<Pixels>);
343
344 #[derive(Clone, Copy, Debug)]
345 enum Edge {
346 Top,
347 Right,
348 Bottom,
349 Left,
350 }
351
352 struct InsetRule {
353 panel: &'static str,
354 content: &'static str,
355 edges: &'static [Edge],
356 }
357
358 fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {
359 f32::from(match edge {
360 Edge::Top => content.top() - panel.top(),
361 Edge::Right => panel.right() - content.right(),
362 Edge::Bottom => panel.bottom() - content.bottom(),
363 Edge::Left => content.left() - panel.left(),
364 })
365 }
366
367 fn inset_violation(
368 rule: &InsetRule,
369 panel: Bounds<Pixels>,
370 content: Bounds<Pixels>,
371 ) -> Option<(String, String)> {
372 let insets: Vec<(Edge, f32)> = rule
373 .edges
374 .iter()
375 .map(|edge| (*edge, inset(panel, content, *edge)))
376 .collect();
377 let values = insets.iter().map(|(_, value)| *value);
378 let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);
379 (spread > INSET_TOLERANCE).then(|| {
380 (
381 format!("{}:uneven-inset", rule.panel),
382 format!(
383 "{} insets {} by {insets:?}, they must match",
384 rule.panel, rule.content
385 ),
386 )
387 })
388 }
389
390 fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {
391 let bounds_of = |path: &str| {
392 tags.iter()
393 .find(|(tag, _)| *tag == path)
394 .map(|(_, bounds)| *bounds)
395 };
396 rules
397 .iter()
398 .filter_map(
399 |rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {
400 (Some(panel), Some(content)) => inset_violation(rule, panel, content),
401 _ => None,
402 },
403 )
404 .collect()
405 }
406
407 fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {
408 let mut found = Vec::new();
409 for (path, bounds) in tags {
410 let Some((parent, segment)) = path.rsplit_once('/') else {
411 continue;
412 };
413 if !segment.starts_with(DIVIDER_SEGMENT) {
414 continue;
415 }
416 let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {
417 found.push((
418 format!("{path}:no-panel"),
419 format!("{path} needs its panel {parent} tagged"),
420 ));
421 continue;
422 };
423 let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;
424 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
425 let spans = if thin(bounds.size.height) {
426 near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())
427 } else if thin(bounds.size.width) {
428 near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())
429 } else {
430 false
431 };
432 if !spans {
433 found.push((
434 format!("{path}:short-divider"),
435 format!(
436 "{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",
437 describe(*bounds),
438 describe(*panel)
439 ),
440 ));
441 }
442 }
443 found
444 }
445
446 enum Screen {
447 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
448 StatusMenu,
449 Call,
450 Prejoin,
451 CallTranscript,
452 CallPeople,
453 CallShare,
454 CallConsult,
455 }
456
457 fn parent_of(path: &str) -> Option<&str> {
458 path.rsplit_once('/').map(|(parent, _)| parent)
459 }
460
461 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
462 let tolerance = px(TOLERANCE);
463 inner.left() >= outer.left() - tolerance
464 && inner.top() >= outer.top() - tolerance
465 && inner.right() <= outer.right() + tolerance
466 && inner.bottom() <= outer.bottom() + tolerance
467 }
468
469 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
470 let tolerance = px(TOLERANCE);
471 first.left() < second.right() - tolerance
472 && second.left() < first.right() - tolerance
473 && first.top() < second.bottom() - tolerance
474 && second.top() < first.bottom() - tolerance
475 }
476
477 fn describe(bounds: Bounds<Pixels>) -> String {
478 format!(
479 "[{:.1},{:.1} {:.1}x{:.1}]",
480 f32::from(bounds.origin.x),
481 f32::from(bounds.origin.y),
482 f32::from(bounds.size.width),
483 f32::from(bounds.size.height)
484 )
485 }
486
487 fn violations(
488 tags: &[Tag],
489 window: Bounds<Pixels>,
490 expected: &[&str],
491 ) -> Vec<(String, String)> {
492 let mut found = Vec::new();
493 let bounds_of = |path: &str| {
494 tags.iter()
495 .find(|(tag, _)| *tag == path)
496 .map(|(_, bounds)| *bounds)
497 };
498 for path in expected {
499 if bounds_of(path).is_none() {
500 found.push((
501 format!("{path}:missing"),
502 format!("{path} was not rendered"),
503 ));
504 }
505 }
506 for (path, bounds) in tags {
507 if !contains(window, *bounds) {
508 found.push((
509 format!("{path}:outside-window"),
510 format!(
511 "{path} {} leaves the window {}",
512 describe(*bounds),
513 describe(window)
514 ),
515 ));
516 }
517 if let Some(parent) =
518 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
519 {
520 if !contains(parent.1, *bounds) {
521 found.push((
522 format!("{path}:outside-parent"),
523 format!(
524 "{path} {} leaves {} {}",
525 describe(*bounds),
526 parent.0,
527 describe(parent.1)
528 ),
529 ));
530 }
531 }
532 for (other, other_bounds) in tags {
533 let overlays = |first: &str, second: &str| {
534 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
535 };
536 let siblings = path < other
537 && parent_of(path).is_some()
538 && parent_of(path) == parent_of(other)
539 && !overlays(path, other)
540 && !overlays(other, path);
541 if siblings && overlaps(*bounds, *other_bounds) {
542 found.push((
543 format!("{path}:overlaps:{other}"),
544 format!(
545 "{path} {} overlaps {other} {}",
546 describe(*bounds),
547 describe(*other_bounds)
548 ),
549 ));
550 }
551 }
552 }
553 found.extend(divider_violations(tags));
554 found
555 }
556
557 const SETTLE_FRAMES: usize = 2;
558 const SETTLE_LIMIT: usize = 60;
559 const SETTLE_STEP: Duration = Duration::from_millis(50);
560
561 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
562 let mut frames = 0;
563 while frames < SETTLE_FRAMES
564 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
565 {
566 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
567 visual.executor().advance_clock(SETTLE_STEP);
568 std::thread::sleep(SETTLE_STEP);
569 visual.run_until_parked();
570 visual.update(|window, cx| window.render_frame(cx));
571 frames += 1;
572 }
573 GUARDED
574 .iter()
575 .chain(CALL_GUARDED)
576 .chain(CALLS_TAGS)
577 .chain(CHAT_FILTER_TAGS)
578 .chain(CHAT_FILTER_OPEN_TAGS)
579 .chain(FIND_TAGS)
580 .chain(PREJOIN_TAGS)
581 .chain(SHARE_GUARDED)
582 .chain(CONSULT_GUARDED)
583 .chain([
584 &AGENTS_LIST,
585 &CALL_TRANSCRIPT,
586 &MENU,
587 &RECAP_TAB,
588 &RECAP_REGION,
589 &PEOPLE_PANEL,
590 ])
591 .chain(&AGENT_TAGS)
592 .chain(SETTINGS_TAGS)
593 .chain(MEMBERS_TAGS)
594 .chain(EDGE_DIVIDERS)
595 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
596 .collect()
597 }
598
599 fn sharing_call() -> ActiveCall {
600 let mut call = gallery_call();
601 call.model
602 .apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
603 call.share_stage.view.step_in((800., 450.));
604 call
605 }
606
607 fn gallery_call() -> ActiveCall {
608 let (handle, _control) = call_channel();
609 let mut model = CallModel::meeting("Standup", false);
610 model.apply(CallUpdate::State(CallState::Connected {
611 since: Instant::now(),
612 }));
613 model.apply(CallUpdate::Roster(
614 (0..11)
615 .map(|index| RosterEntry {
616 mri: format!("8:orgid:guard-{index}"),
617 display_name: format!("Guest {index}"),
618 muted: false,
619 in_lobby: false,
620 has_video: false,
621 sharing: false,
622 hand: None,
623 spotlight: None,
624 organizer: false,
625 ..Default::default()
626 })
627 .collect(),
628 ));
629 ActiveCall::new(1, model, handle.commands, None, handle.video)
630 }
631
632 fn consult_calls() -> (ActiveCall, ActiveCall) {
633 let connected = |id: u64, name: &str, mri: &str| {
634 let (handle, _control) = call_channel();
635 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
636 model.apply(CallUpdate::State(CallState::Connected {
637 since: Instant::now(),
638 }));
639 ActiveCall::new(id, model, handle.commands, None, handle.video)
640 };
641 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
642 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
643 consult.consult = Some(ConsultCall::new(
644 (
645 "8:orgid:guard-consult".to_owned(),
646 "Jonas Ortega".to_owned(),
647 ),
648 held.model.peer_name.clone(),
649 ));
650 (consult, held)
651 }
652
653 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
654 mount_with(cx, false)
655 }
656
657 fn mount_with(
658 cx: &mut TestAppContext,
659 agent_api: bool,
660 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
661 cx.update(gpui_kit::init);
662 cx.update(|cx| {
663 crate::theme::apply(cx);
664 bind_keys(cx);
665 let store = Store::open_in_memory().expect("in-memory store");
666 demo::seed(&store);
667 let store = Arc::new(store);
668 if agent_api {
669 crate::agent_api::init(store.clone(), true, cx);
670 }
671 let mode = Mode {
672 demo: true,
673 read_only: false,
674 demo_sync: None,
675 };
676 let state = cx.new(|_| AppState::new(store, mode));
677 install_globals(&state, UserInput::new(), cx);
678 crate::agents::install(state.clone(), cx);
679 demo::start_session(&state, cx);
680 let shared_state = state.clone();
681 let startup = Startup {
682 switcher_query: None,
683 composer_text: None,
684 reply_to_last: false,
685 };
686 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
687 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
688 })
689 .expect("open test window")
690 .0;
691 (window, shared_state)
692 })
693 }
694
695 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
696 Bounds {
697 origin: point(px(left), px(top)),
698 size: size(px(width), px(height)),
699 }
700 }
701
702 #[test]
703 fn rules_flag_overlap_and_overflow() {
704 let window = rectangle(0., 0., 100., 100.);
705 let tags: Vec<Tag> = vec![
706 ("shell", rectangle(0., 0., 100., 100.)),
707 ("shell/islands", rectangle(0., 0., 100., 50.)),
708 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
709 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
710 ];
711 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
712 .into_iter()
713 .map(|(key, _)| key)
714 .collect();
715 let line_tags: Vec<Tag> = vec![
716 ("panel", rectangle(0., 0., 100., 100.)),
717 ("panel/divider", rectangle(0., 50., 100., 1.)),
718 ("panel/divider-inset", rectangle(12., 60., 76., 1.)),
719 ("panel/divider-side", rectangle(40., 0., 1., 100.)),
720 ("panel/about", rectangle(12., 76., 76., 12.)),
721 ("panel/footer", rectangle(12., 64., 76., 12.)),
722 ];
723 let line_keys: Vec<String> = divider_violations(&line_tags)
724 .into_iter()
725 .chain(inset_violations(
726 &line_tags,
727 &[
728 InsetRule {
729 panel: "panel",
730 content: "panel/about",
731 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
732 },
733 InsetRule {
734 panel: "panel",
735 content: "panel/footer",
736 edges: &[Edge::Left, Edge::Bottom],
737 },
738 ],
739 ))
740 .map(|(key, _)| key)
741 .collect();
742 assert_eq!(
743 line_keys,
744 ["panel/divider-inset:short-divider", "panel:uneven-inset"]
745 );
746 assert_eq!(
747 keys,
748 [
749 "shell/status-bar:missing",
750 "shell/islands/rail:overlaps:shell/islands/sidebar",
751 "shell/islands/sidebar:outside-window",
752 "shell/islands/sidebar:outside-parent",
753 ]
754 );
755 }
756
757 #[gpui_kit::test]
758 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
759 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
760 }
761
762 #[gpui_kit::test]
763 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
764 let (width, height) = SIZES[1];
765 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
766 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
767 }
768
769 fn check_layout(
770 cx: &mut TestAppContext,
771 sizes: &[(f32, f32)],
772 zoom: f32,
773 known_violations: &[&str],
774 ) {
775 let (handle, app) = mount(cx);
776 let platform_scale = cx
777 .update_window(handle, |_, window, _| window.scale_factor())
778 .expect("test window");
779 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
780 let mut visual = VisualTestContext::from_window(handle, cx);
781 let mut seen_known = HashSet::new();
782 let mut unexpected = Vec::new();
783 for &(width, height) in sizes {
784 visual.simulate_resize(size(px(width), px(height)));
785 let window = Bounds {
786 origin: point(px(0.), px(0.)),
787 size: size(px(width), px(height)),
788 };
789 let screens = [
790 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
791 Screen::Tab(
792 "chat-filter",
793 Some(|visual| {
794 visual.dispatch_action(OpenChatsTab);
795 visual.dispatch_action(OpenChatFilter);
796 visual.dispatch_action(FilterMutedChats);
797 visual.run_until_parked();
798 visual.simulate_input("zzz");
799 }),
800 ),
801 Screen::Tab(
802 "find",
803 Some(|visual| {
804 visual.dispatch_action(OpenChatsTab);
805 visual.dispatch_action(FindInChat);
806 visual.run_until_parked();
807 visual.simulate_input("access");
808 }),
809 ),
810 Screen::Tab(
811 "activity",
812 Some(|visual| visual.dispatch_action(OpenActivity)),
813 ),
814 Screen::Tab(
815 "channels",
816 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
817 ),
818 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
819 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
820 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
821 Screen::Prejoin,
822 Screen::StatusMenu,
823 Screen::Call,
824 Screen::CallTranscript,
825 Screen::CallPeople,
826 Screen::CallShare,
827 Screen::CallConsult,
828 ];
829 for screen in screens {
830 let (screen_name, status_menu) = match screen {
831 Screen::Tab(name, open) => {
832 if let Some(open) = open {
833 open(&mut visual);
834 }
835 (name, false)
836 }
837 Screen::Call | Screen::CallPeople => {
838 let people_open = matches!(screen, Screen::CallPeople);
839 visual.update(|_, cx| {
840 app.update(cx, |state, cx| {
841 let mut call = gallery_call();
842 call.people_open = people_open;
843 state.call = Some(call);
844 cx.notify();
845 })
846 });
847 (if people_open { "call-people" } else { "call" }, false)
848 }
849 Screen::Prejoin => {
850 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
851 visual.update(|_, cx| {
852 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
853 });
854 ("prejoin", false)
855 }
856 Screen::CallTranscript => {
857 visual.update(|window, cx| {
858 app.update(cx, |state, cx| {
859 let mut call = gallery_call();
860 call.model.apply(CallUpdate::Captions(CaptionState::On));
861 for index in 0..40 {
862 call.model.note_caption(
863 CaptionEntry {
864 id: format!("guard-{index}"),
865 user_id: "8:orgid:guard-0".into(),
866 display_name: "Guest 0".into(),
867 text: "A long guarded sentence that has to wrap inside the panel".into(),
868 is_final: true,
869 },
870 Instant::now(),
871 );
872 }
873 call.transcript_open = true;
874 state.call = Some(call);
875 let app_entity = cx.entity();
876 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
877 cx.notify();
878 })
879 });
880 ("call-transcript", false)
881 }
882 Screen::CallShare => {
883 visual.update(|_, cx| {
884 app.update(cx, |state, cx| {
885 state.call = Some(sharing_call());
886 cx.notify();
887 })
888 });
889 ("call-share", false)
890 }
891 Screen::CallConsult => {
892 visual.update(|_, cx| {
893 app.update(cx, |state, cx| {
894 let (consult, held) = consult_calls();
895 state.call = Some(consult);
896 state.held_call = Some(held);
897 cx.notify();
898 })
899 });
900 ("call-consult", false)
901 }
902 Screen::StatusMenu => {
903 let tags = collect(&mut visual, None);
904 let button = tags
905 .iter()
906 .find(|(path, _)| *path == OWN_STATUS)
907 .map(|(_, bounds)| *bounds)
908 .expect("own status button rendered");
909 visual.simulate_click(button.center(), Default::default());
910 ("status-menu", true)
911 }
912 };
913 let is_call = matches!(
914 screen_name,
915 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
916 );
917 let tags = collect(&mut visual, status_menu.then_some(MENU));
918 let mut expected = GUARDED.to_vec();
919 if is_call {
920 expected.extend(CALL_GUARDED);
921 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
922 if sidebar_hidden_in_call(width, panel_open) {
923 expected.retain(|path| *path != "shell/islands/sidebar");
924 }
925 }
926 if screen_name == "call-transcript" {
927 expected.push(CALL_TRANSCRIPT);
928 }
929 if screen_name == "call-people" {
930 expected.push(PEOPLE_PANEL);
931 }
932 if screen_name == "call-share" {
933 expected.extend(SHARE_GUARDED);
934 }
935 if screen_name == "call-consult" {
936 expected.extend(CONSULT_GUARDED);
937 }
938 if status_menu {
939 expected.push(MENU);
940 }
941 match screen_name {
942 "chats" => expected.extend(CHAT_FILTER_TAGS),
943 "chat-filter" => {
944 expected.extend(CHAT_FILTER_TAGS);
945 expected.extend(CHAT_FILTER_OPEN_TAGS);
946 }
947 "find" => expected.extend(FIND_TAGS),
948 "calls" => expected.extend(CALLS_TAGS),
949 "agents" => expected.push(AGENTS_LIST),
950 "prejoin" => expected.extend(PREJOIN_TAGS),
951 _ => {}
952 }
953 let mut found = violations(&tags, window, &expected);
954 if status_menu {
955 let menu = tags
956 .iter()
957 .find(|(path, _)| *path == MENU)
958 .map(|(_, bounds)| *bounds);
959 let button = tags
960 .iter()
961 .find(|(path, _)| *path == OWN_STATUS)
962 .map(|(_, bounds)| *bounds);
963 if let (Some(menu), Some(button)) = (menu, button) {
964 if overlaps(menu, button) {
965 found.push((
966 format!("{MENU}:covers:{OWN_STATUS}"),
967 format!(
968 "{MENU} {} covers {OWN_STATUS} {}",
969 describe(menu),
970 describe(button)
971 ),
972 ));
973 }
974 }
975 visual.simulate_keystrokes("escape");
976 visual.run_until_parked();
977 }
978 if is_call {
979 visual.update(|_, cx| {
980 app.update(cx, |state, cx| {
981 state.call = None;
982 state.held_call = None;
983 cx.notify();
984 })
985 });
986 }
987 if screen_name == "find" {
988 visual.dispatch_action(gpui_kit::component::input::Escape);
989 visual.run_until_parked();
990 }
991 if screen_name == "chat-filter" {
992 visual.dispatch_action(ClearChatFilters);
993 visual.dispatch_action(OpenChatFilter);
994 visual.run_until_parked();
995 }
996 if screen_name == "prejoin" {
997 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
998 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
999 }
1000 for (key, message) in found {
1001 let full_key = format!("{screen_name}@{width}x{height}:{key}");
1002 if known_violations.contains(&full_key.as_str()) {
1003 seen_known.insert(full_key);
1004 } else {
1005 unexpected.push(format!("{full_key}: {message}"));
1006 }
1007 }
1008 }
1009 }
1010 let stale: Vec<String> = known_violations
1011 .iter()
1012 .filter(|key| !seen_known.contains(**key))
1013 .map(|key| format!("stale known violation, remove it: {key}"))
1014 .collect();
1015 assert!(
1016 unexpected.is_empty() && stale.is_empty(),
1017 "{}",
1018 unexpected
1019 .into_iter()
1020 .chain(stale)
1021 .collect::<Vec<_>>()
1022 .join("\n")
1023 );
1024 }
1025 #[gpui_kit::test]
1026 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
1027 let (handle, _) = mount(cx);
1028 let mut visual = VisualTestContext::from_window(handle, cx);
1029 visual.simulate_resize(size(px(1280.), px(800.)));
1030 collect(&mut visual, Some(OWN_AVATAR_DISC));
1031 let disc = visual
1032 .debug_bounds(OWN_AVATAR_DISC)
1033 .expect("own avatar rendered");
1034 let bar = visual
1035 .debug_bounds("shell/title-bar")
1036 .expect("title bar rendered");
1037 assert_eq!(
1038 f32::from(disc.size.width),
1039 TITLE_AVATAR_SIZE,
1040 "{}",
1041 describe(disc)
1042 );
1043 assert_eq!(
1044 f32::from(disc.size.height),
1045 TITLE_AVATAR_SIZE,
1046 "{}",
1047 describe(disc)
1048 );
1049 let top = f32::from(disc.top() - bar.top());
1050 let bottom = f32::from(bar.bottom() - disc.bottom());
1051 assert!(
1052 (top - bottom).abs() <= 1.,
1053 "own avatar {} is not centered in the title bar {}",
1054 describe(disc),
1055 describe(bar)
1056 );
1057 }
1058
1059 const TITLE_SEARCH: &str = "shell/title-bar/search";
1060 const TITLE_NEIGHBOURS: &[&str] = &[
1061 "shell/title-bar/leading",
1062 "shell/title-bar/mode-pill",
1063 "shell/title-bar/trailing",
1064 "shell/title-bar/update",
1065 OWN_STATUS,
1066 ];
1067 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
1068 (1920., 1080., true),
1069 (1280., 800., true),
1070 (640., 480., false),
1071 ];
1072
1073 #[gpui_kit::test]
1074 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
1075 let (handle, _) = mount(cx);
1076 let mut visual = VisualTestContext::from_window(handle, cx);
1077 let shell = visual.update(|window, cx| {
1078 window
1079 .root::<gpui_kit::base::Root>()
1080 .flatten()
1081 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
1082 .expect("app shell is the root view")
1083 });
1084 visual.update(|_, cx| {
1085 shell.update(cx, |shell, cx| {
1086 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
1087 })
1088 });
1089 let mut found = Vec::new();
1090 for (width, height, centered) in TITLE_SEARCH_SIZES {
1091 visual.simulate_resize(size(px(width), px(height)));
1092 collect(&mut visual, Some(TITLE_SEARCH));
1093 let search = visual
1094 .debug_bounds(TITLE_SEARCH)
1095 .expect("title search rendered");
1096 let search_center = f32::from(search.center().x);
1097 eprintln!(
1098 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
1099 describe(search),
1100 width / 2.
1101 );
1102 if centered && (search_center - width / 2.).abs() > 1. {
1103 found.push(format!(
1104 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
1105 width / 2.
1106 ));
1107 }
1108 if !contains(rectangle(0., 0., width, height), search) {
1109 found.push(format!(
1110 "@{width}x{height}: search {} leaves the window",
1111 describe(search)
1112 ));
1113 }
1114 for neighbour in TITLE_NEIGHBOURS {
1115 match visual.debug_bounds(neighbour) {
1116 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
1117 Some(bounds) if overlaps(search, bounds) => found.push(format!(
1118 "@{width}x{height}: search {} overlaps {neighbour} {}",
1119 describe(search),
1120 describe(bounds)
1121 )),
1122 Some(_) => {}
1123 }
1124 }
1125 }
1126 assert!(found.is_empty(), "{}", found.join("\n"));
1127 }
1128
1129 #[gpui_kit::test]
1130 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
1131 let (handle, app) = mount(cx);
1132 let mut visual = VisualTestContext::from_window(handle, cx);
1133 for (width, height) in SIZES {
1134 visual.simulate_resize(size(px(width), px(height)));
1135 visual.update(|_, cx| {
1136 app.update(cx, |state, cx| {
1137 let mut call = gallery_call();
1138 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
1139 call.chat_open = true;
1140 state.call = Some(call);
1141 cx.notify();
1142 })
1143 });
1144 collect(&mut visual, Some(CHAT_PANEL_TAG));
1145 let panel = visual
1146 .debug_bounds(CHAT_PANEL_TAG)
1147 .expect("chat panel rendered");
1148 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
1149 .iter()
1150 .enumerate()
1151 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
1152 .collect();
1153 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
1154 let found: Vec<String> = bubbles
1155 .into_iter()
1156 .filter(|(_, bounds)| {
1157 !inside_horizontally(panel, *bounds) || !overlaps(panel, *bounds)
1158 })
1159 .map(|(index, bounds)| {
1160 format!(
1161 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
1162 describe(bounds),
1163 describe(panel)
1164 )
1165 })
1166 .collect();
1167 visual.update(|_, cx| {
1168 app.update(cx, |state, cx| {
1169 state.call = None;
1170 cx.notify();
1171 })
1172 });
1173 assert!(found.is_empty(), "{}", found.join("\n"));
1174 }
1175 }
1176
1177 fn inside_horizontally(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
1178 let tolerance = px(TOLERANCE);
1179 inner.left() >= outer.left() - tolerance && inner.right() <= outer.right() + tolerance
1180 }
1181
1182 fn scroll_sidebar(visual: &mut VisualTestContext, delta: f32) {
1183 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1184 visual.simulate_event(ScrollWheelEvent {
1185 position: sidebar.center(),
1186 delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1187 ..Default::default()
1188 });
1189 }
1190
1191 #[gpui_kit::test]
1192 fn chat_list_line_shows_only_while_scrolled(cx: &mut TestAppContext) {
1193 let (handle, _) = mount(cx);
1194 let mut visual = VisualTestContext::from_window(handle, cx);
1195 for (width, height) in SIZES {
1196 visual.simulate_resize(size(px(width), px(height)));
1197 let window = Bounds {
1198 origin: point(px(0.), px(0.)),
1199 size: size(px(width), px(height)),
1200 };
1201 collect(&mut visual, None);
1202 scroll_sidebar(&mut visual, 100_000.);
1203 let tags = collect(&mut visual, None);
1204 assert!(
1205 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1206 "chat list at its top must not show the line at {width}x{height}"
1207 );
1208 scroll_sidebar(&mut visual, -120.);
1209 let scrolled = collect(&mut visual, Some(SIDEBAR_SCROLL_DIVIDER));
1210 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1211 let line = visual
1212 .debug_bounds(SIDEBAR_SCROLL_DIVIDER)
1213 .expect("scrolled chat list shows the line");
1214 assert!(
1215 line.top() > sidebar.top() + px(TOLERANCE),
1216 "the line sits under the Chats header, not on the island edge: {} in {}",
1217 describe(line),
1218 describe(sidebar)
1219 );
1220 let found: Vec<String> = violations(&scrolled, window, &[SIDEBAR_SCROLL_DIVIDER])
1221 .into_iter()
1222 .chain(violations(&tags, window, &[]))
1223 .map(|(key, message)| format!("chat-list@{width}x{height}:{key}: {message}"))
1224 .collect();
1225 assert!(found.is_empty(), "{}", found.join("\n"));
1226 scroll_sidebar(&mut visual, 100_000.);
1227 collect(&mut visual, None);
1228 assert!(
1229 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1230 "the line goes away once the chat list is back at its top"
1231 );
1232 }
1233 }
1234
1235 #[gpui_kit::test]
1236 fn header_tabs_sit_above_the_header_line(cx: &mut TestAppContext) {
1237 let (handle, state) = mount(cx);
1238 let mut visual = VisualTestContext::from_window(handle, cx);
1239 for (width, height) in SIZES {
1240 visual.simulate_resize(size(px(width), px(height)));
1241 let window = Bounds {
1242 origin: point(px(0.), px(0.)),
1243 size: size(px(width), px(height)),
1244 };
1245 visual.update(|_, cx| {
1246 state.update(cx, |state, cx| {
1247 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1248 })
1249 });
1250 let tags = collect(&mut visual, Some(RECAP_TAB));
1251 let main = visual.debug_bounds(MAIN).expect("main island rendered");
1252 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1253 let line = visual
1254 .debug_bounds(HEADER_DIVIDER)
1255 .expect("the header line is always shown");
1256 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
1257 assert!(
1258 tab.top() >= main.top() && near(tab.bottom(), line.top()),
1259 "tab {} must sit in the top bar above the line {}",
1260 describe(tab),
1261 describe(line)
1262 );
1263 let found: Vec<String> = violations(&tags, window, &[HEADER_DIVIDER, RECAP_TAB])
1264 .into_iter()
1265 .map(|(key, message)| format!("header@{width}x{height}:{key}: {message}"))
1266 .collect();
1267 assert!(found.is_empty(), "{}", found.join("\n"));
1268 }
1269 }
1270
1271 #[gpui_kit::test]
1272 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1273 let (handle, state) = mount(cx);
1274 let mut visual = VisualTestContext::from_window(handle, cx);
1275 for (width, height) in SIZES {
1276 visual.simulate_resize(size(px(width), px(height)));
1277 let window = Bounds {
1278 origin: point(px(0.), px(0.)),
1279 size: size(px(width), px(height)),
1280 };
1281 visual.update(|_, cx| {
1282 state.update(cx, |state, cx| {
1283 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1284 })
1285 });
1286 collect(&mut visual, Some(RECAP_TAB));
1287 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1288 visual.simulate_click(tab.center(), Default::default());
1289 let tags = collect(&mut visual, Some(RECAP_REGION));
1290 let mut expected = GUARDED.to_vec();
1291 expected.extend([RECAP_TAB, RECAP_REGION]);
1292 let found: Vec<String> = violations(&tags, window, &expected)
1293 .into_iter()
1294 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1295 .collect();
1296 assert!(found.is_empty(), "{}", found.join("\n"));
1297 }
1298 }
1299
1300 #[gpui_kit::test]
1301 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1302 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1303 }
1304
1305 #[gpui_kit::test]
1306 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1307 crate::theme::set_thread_scheme(Some("teams"));
1308 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1309 crate::theme::set_thread_scheme(None);
1310 }
1311
1312 #[gpui_kit::test]
1313 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1314 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1315 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1316 crate::theme::set_thread_shade(None);
1317 }
1318
1319 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1320 let (handle, state) = mount_with(cx, true);
1321 let mut visual = VisualTestContext::from_window(handle, cx);
1322 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1323 visual.simulate_resize(size(px(width), px(height)));
1324 let window = Bounds {
1325 origin: point(px(0.), px(0.)),
1326 size: size(px(width), px(height)),
1327 };
1328 let inset = metrics(width, height).inset;
1329 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1330 for &section in sections {
1331 visual
1332 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1333 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1334 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1335 .into_iter()
1336 .filter(|(key, _)| key.starts_with("settings"))
1337 .chain(inset_violations(&tags, INSET_RULES))
1338 .collect();
1339 if label_sizes {
1340 found.extend(nav_label_violations(&mut visual));
1341 }
1342 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1343 .iter()
1344 .any(|(exempt, _)| *exempt == section);
1345 if !scrolled_exempt {
1346 found.extend(scrolled_inset_violation(&mut visual));
1347 }
1348 let found: Vec<String> = found
1349 .into_iter()
1350 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1351 .collect();
1352 assert!(found.is_empty(), "{}", found.join("\n"));
1353 let dialog = visual
1354 .debug_bounds(SETTINGS_TAGS[0])
1355 .expect("settings dialog");
1356 let edges = [
1357 f32::from(dialog.left()),
1358 f32::from(dialog.top()),
1359 width - f32::from(dialog.right()),
1360 height - f32::from(dialog.bottom()),
1361 ];
1362 assert!(
1363 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1364 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1365 );
1366 }
1367 }
1368 }
1369
1370 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1371
1372 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1373 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1374 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1375 };
1376 let mut found = Vec::new();
1377 for section in SETTINGS_SECTIONS {
1378 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1379 let item_path: &'static str = if section == SettingsSection::About {
1380 SETTINGS_NAV_ABOUT
1381 } else {
1382 Box::leak(item_selector(section).into_boxed_str())
1383 };
1384 let (Some(label_bounds), Some(item)) = (
1385 visual.debug_bounds(label_path),
1386 visual.debug_bounds(item_path),
1387 ) else {
1388 if section != SettingsSection::Agents {
1389 found.push((label_path.to_owned(), "not rendered".to_owned()));
1390 }
1391 continue;
1392 };
1393 let text = label(section);
1394 let text_width = visual.update(|window, _| {
1395 let run = window.text_style().to_run(text.len());
1396 f32::from(
1397 window
1398 .text_system()
1399 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1400 .width,
1401 )
1402 });
1403 let label_width = f32::from(label_bounds.size.width);
1404 let label_height = f32::from(label_bounds.size.height);
1405 if text_width > label_width + TOLERANCE
1406 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1407 {
1408 found.push((
1409 label_path.to_owned(),
1410 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1411 ));
1412 }
1413 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1414 inner.left() < outer.left() - px(TOLERANCE)
1415 || inner.right() > outer.right() + px(TOLERANCE)
1416 || inner.top() < outer.top() - px(TOLERANCE)
1417 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1418 };
1419 if outside(label_bounds, item) {
1420 found.push((
1421 label_path.to_owned(),
1422 format!("label {label_bounds:?} outside item {item:?}"),
1423 ));
1424 }
1425 if item.left() < nav.left() || item.right() > nav.right() {
1426 found.push((
1427 item_path.to_owned(),
1428 format!("item {item:?} outside nav {nav:?}"),
1429 ));
1430 }
1431 }
1432 found
1433 }
1434
1435 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1436 let body = visual.debug_bounds(SETTINGS_BODY)?;
1437 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1438 if content.bottom() <= body.bottom() {
1439 return None;
1440 }
1441 visual.simulate_event(ScrollWheelEvent {
1442 position: body.center(),
1443 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1444 ..Default::default()
1445 });
1446 collect(visual, None);
1447 let body = visual.debug_bounds(SETTINGS_BODY)?;
1448 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1449 inset_violation(&SCROLLED_INSET_RULE, body, content)
1450 }
1451
1452 #[gpui_kit::test]
1453 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1454 let (handle, state) = mount(cx);
1455 let mut visual = VisualTestContext::from_window(handle, cx);
1456 for (width, height) in SIZES {
1457 visual.simulate_resize(size(px(width), px(height)));
1458 let window = Bounds {
1459 origin: point(px(0.), px(0.)),
1460 size: size(px(width), px(height)),
1461 };
1462 visual.update(|_, cx| {
1463 state.update(cx, |state, cx| {
1464 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1465 })
1466 });
1467 collect(&mut visual, Some(MEMBERS_BUTTON));
1468 let button = visual
1469 .debug_bounds(MEMBERS_BUTTON)
1470 .expect("members button rendered");
1471 visual.simulate_click(button.center(), Default::default());
1472 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1473 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1474 .into_iter()
1475 .filter(|(key, _)| key.starts_with("chat-members"))
1476 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1477 .collect();
1478 visual.simulate_keystrokes("escape");
1479 visual.run_until_parked();
1480 assert!(found.is_empty(), "{}", found.join("\n"));
1481 }
1482 }
1483
1484 const PINNED_CHAT: &str = "demo-chat-release";
1485 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1486
1487 #[gpui_kit::test]
1488 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
1489 let (handle, state) = mount(cx);
1490 let mut visual = VisualTestContext::from_window(handle, cx);
1491 let mut found = Vec::new();
1492 for (width, height) in SIZES {
1493 visual.simulate_resize(size(px(width), px(height)));
1494 visual.update(|_, cx| {
1495 state.update(cx, |state, cx| {
1496 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1497 })
1498 });
1499 collect(&mut visual, Some(PIN_BANNER_TAG));
1500 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1501 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1502 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1503 let gaps = [
1504 ("top", f32::from(banner.top() - timeline.top())),
1505 ("left", f32::from(banner.left() - timeline.left())),
1506 ("right", f32::from(timeline.right() - banner.right())),
1507 ("below divider", f32::from(banner.top() - divider.bottom())),
1508 ];
1509 let side = gaps[1].1;
1510 if gaps
1511 .iter()
1512 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1513 {
1514 found.push(format!(
1515 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1516 ));
1517 }
1518 }
1519 assert!(found.is_empty(), "{}", found.join("\n"));
1520 }
1521
1522 #[gpui_kit::test]
1523 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1524 let (handle, state) = mount(cx);
1525 let mut visual = VisualTestContext::from_window(handle, cx);
1526 visual.simulate_resize(size(px(1280.), px(800.)));
1527 visual.update(|_, cx| {
1528 state.update(cx, |state, cx| {
1529 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1530 })
1531 });
1532 collect(&mut visual, Some(TIMELINE_TAG));
1533 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1534 }
1535
1536 #[gpui_kit::test]
1537 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1538 let (handle, state) = mount(cx);
1539 let mut visual = VisualTestContext::from_window(handle, cx);
1540 visual.simulate_resize(size(px(1280.), px(800.)));
1541 visual.update(|_, cx| {
1542 state.update(cx, |state, cx| {
1543 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1544 })
1545 });
1546 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1547 let button = visual
1548 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1549 .expect("channel details button");
1550 visual.simulate_click(button.center(), Default::default());
1551 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1552 let pane = visual
1553 .debug_bounds(CHANNEL_DETAILS_TAG)
1554 .expect("details pane");
1555 let main = visual.debug_bounds(MAIN).expect("main island");
1556 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1557 assert!(
1558 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1559 "pane {pane:?} must end at the main island edge {main:?}"
1560 );
1561 assert!(
1562 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1563 "pane {pane:?} must start under the header divider {divider:?}"
1564 );
1565 }
1566
1567 #[gpui_kit::test]
1568 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
1569 let (handle, state) = mount(cx);
1570 let mut visual = VisualTestContext::from_window(handle, cx);
1571 visual.simulate_resize(size(px(1280.), px(800.)));
1572 visual.update(|_, cx| {
1573 state.update(cx, |state, cx| {
1574 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1575 })
1576 });
1577 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1578 let button = visual
1579 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1580 .expect("channel details button");
1581 visual.simulate_click(button.center(), Default::default());
1582 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
1583 let pane = visual
1584 .debug_bounds(CHANNEL_DETAILS_TAG)
1585 .expect("details pane");
1586 let pinned = visual
1587 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
1588 .expect("pinned section");
1589 let shared = visual
1590 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
1591 .expect("shared section");
1592 assert!(
1593 pinned.bottom() <= shared.top(),
1594 "pinned {pinned:?} must come before shared {shared:?}"
1595 );
1596 for (name, section) in [("pinned", pinned), ("shared", shared)] {
1597 let left = f32::from(section.left() - pane.left());
1598 let right = f32::from(pane.right() - section.right());
1599 assert!(
1600 (left - right).abs() < INSET_TOLERANCE && left > 0.,
1601 "{name} section insets left {left} right {right} must match"
1602 );
1603 }
1604 }
1605
1606 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1607 collect(visual, Some(COMPOSER_SEND_TAG));
1608 let mut bounds_of = |path: &'static str| {
1609 visual
1610 .debug_bounds(path)
1611 .unwrap_or_else(|| panic!("{path} rendered"))
1612 };
1613 let composer = bounds_of(COMPOSER_BOX_TAG);
1614 let leading = bounds_of(COMPOSER_LEADING_TAG);
1615 let send = bounds_of(COMPOSER_SEND_TAG);
1616 [
1617 f32::from(leading.left() - composer.left()),
1618 f32::from(leading.top() - composer.top()),
1619 f32::from(composer.bottom() - leading.bottom()),
1620 f32::from(composer.right() - send.right()),
1621 f32::from(send.top() - composer.top()),
1622 f32::from(composer.bottom() - send.bottom()),
1623 ]
1624 }
1625
1626 #[gpui_kit::test]
1627 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
1628 let (handle, _) = mount(cx);
1629 let mut visual = VisualTestContext::from_window(handle, cx);
1630 visual.simulate_resize(size(px(1280.), px(800.)));
1631 let single_line = composer_button_insets(&mut visual);
1632 let left = single_line[0];
1633 assert!(
1634 single_line
1635 .iter()
1636 .all(|inset| (inset - left).abs() < TOLERANCE),
1637 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
1638 );
1639 let leading = visual
1640 .debug_bounds(COMPOSER_LEADING_TAG)
1641 .expect("leading buttons");
1642 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
1643 visual.simulate_click(
1644 point((leading.right() + send.left()) / 2., send.center().y),
1645 Default::default(),
1646 );
1647 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
1648 let three_lines = composer_button_insets(&mut visual);
1649 assert!(
1650 three_lines[1] > single_line[1] + 30.,
1651 "three lines did not grow the composer: {three_lines:?}"
1652 );
1653 for inset in [
1654 three_lines[0],
1655 three_lines[2],
1656 three_lines[3],
1657 three_lines[5],
1658 ] {
1659 assert!(
1660 (inset - left).abs() < TOLERANCE,
1661 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
1662 );
1663 }
1664 }
1665
1666 #[gpui_kit::test]
1667 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
1668 const FORMAT_TAGS: [&str; 6] = [
1669 COMPOSER_BOX_TAG,
1670 COMPOSER_FORMAT_BAR_TAG,
1671 COMPOSER_FORMAT_DIVIDER_TAG,
1672 COMPOSER_LEADING_TAG,
1673 COMPOSER_FORMAT_TAG,
1674 COMPOSER_SEND_TAG,
1675 ];
1676 let (handle, _) = mount(cx);
1677 let mut visual = VisualTestContext::from_window(handle, cx);
1678 for (width, height) in SIZES {
1679 visual.simulate_resize(size(px(width), px(height)));
1680 let window = Bounds {
1681 origin: point(px(0.), px(0.)),
1682 size: size(px(width), px(height)),
1683 };
1684 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
1685 let toggle = visual
1686 .debug_bounds(COMPOSER_FORMAT_TAG)
1687 .expect("format button");
1688 visual.simulate_click(toggle.center(), Default::default());
1689 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
1690 let tags: Vec<Tag> = FORMAT_TAGS
1691 .iter()
1692 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1693 .collect();
1694 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
1695 .into_iter()
1696 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
1697 .collect();
1698 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
1699 let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");
1700 let toggle = visual
1701 .debug_bounds(COMPOSER_FORMAT_TAG)
1702 .expect("format button");
1703 visual.simulate_click(toggle.center(), Default::default());
1704 collect(&mut visual, None);
1705 assert!(found.is_empty(), "{}", found.join("\n"));
1706 assert!(
1707 bar.bottom() <= leading.top(),
1708 "bar {bar:?} over the buttons {leading:?}"
1709 );
1710 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
1711 }
1712 }
1713
1714 #[gpui_kit::test]
1715 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1716 let (handle, state) = mount_with(cx, true);
1717 let mut visual = VisualTestContext::from_window(handle, cx);
1718 for (width, height) in SIZES {
1719 visual.simulate_resize(size(px(width), px(height)));
1720 let window = Bounds {
1721 origin: point(px(0.), px(0.)),
1722 size: size(px(width), px(height)),
1723 };
1724 for (chat, expected_tags) in [
1725 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
1726 (REACTION_CHAT, &AGENT_TAGS[3..]),
1727 ] {
1728 visual.update(|_, cx| {
1729 state.update(cx, |state, cx| {
1730 state.select(Selection::Chat(chat.to_owned()), cx)
1731 })
1732 });
1733 let tags = collect(&mut visual, Some(expected_tags[0]));
1734 let mut expected = GUARDED.to_vec();
1735 expected.extend(expected_tags);
1736 let found: Vec<String> = violations(&tags, window, &expected)
1737 .into_iter()
1738 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
1739 .collect();
1740 assert!(found.is_empty(), "{}", found.join("\n"));
1741 }
1742 }
1743 }
1744}
1745
1746#[test]
1747fn lines_are_solid() {
1748 let mut files = Vec::new();
1749 for root in source_roots() {
1750 source_files(&root, &mut files);
1751 }
1752 let violations: Vec<String> = files
1753 .iter()
1754 .filter(|file| !file.ends_with("layout_guard.rs"))
1755 .flat_map(|file| {
1756 let source = fs::read_to_string(file).expect("read source file");
1757 source
1758 .lines()
1759 .enumerate()
1760 .filter(|(_, line)| {
1761 line.contains(".border_dashed(") || line.contains(".border_dotted(")
1762 })
1763 .map(|(index, line)| {
1764 format!(
1765 "{}:{}: lines are always solid: {}",
1766 file.display(),
1767 index + 1,
1768 line.trim()
1769 )
1770 })
1771 .collect::<Vec<_>>()
1772 })
1773 .collect();
1774 assert!(violations.is_empty(), "{}", violations.join("\n"));
1775}
1776
1777const STATE_RING_COLORS: &[&str] = &[
1778 "if focused",
1779 "if selected",
1780 "if speaking",
1781 "if current",
1782 "if open",
1783 "if state.failed",
1784];
1785const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
1786 (
1787 "notify/ring_view.rs",
1788 "theme::green()",
1789 "state signal (pulsing ring around the caller while it rings), not a resting outline",
1790 ),
1791 (
1792 "notify/meeting_view.rs",
1793 "theme::border_strong()",
1794 "outlined button, not a surface",
1795 ),
1796 (
1797 "settings/mcp.rs",
1798 "theme::border_strong()",
1799 "outlined button, not a surface",
1800 ),
1801 (
1802 "settings/rows.rs",
1803 "theme::border_strong()",
1804 "outlined button, not a surface",
1805 ),
1806 (
1807 "views/card_widgets.rs",
1808 "border)",
1809 "message content drawn as Teams renders it",
1810 ),
1811 (
1812 "views/card_widgets.rs",
1813 "theme::border_strong()",
1814 "message content drawn as Teams renders it",
1815 ),
1816 ("views/shared_tab.rs", "theme::accent()", "input field"),
1817 ("views/card_input.rs", "if error.is_some()", "input field"),
1818 ("views/format_toolbar.rs", "if refused", "input field"),
1819 (
1820 "views/card_code_block.rs",
1821 "theme::code_header_border()",
1822 "message content drawn as Teams renders it",
1823 ),
1824 ("views/call_transcript.rs", "theme::border()", "input field"),
1825 (
1826 "views/conversation.rs",
1827 "theme::accent()",
1828 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1829 ),
1830 (
1831 "views/attachment_tray.rs",
1832 "theme::accent()",
1833 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1834 ),
1835 (
1836 "views/card_carousel.rs",
1837 "theme::border_strong()",
1838 "message content drawn as Teams renders it",
1839 ),
1840 (
1841 "views/card_table.rs",
1842 "grid_color",
1843 "message content drawn as Teams renders it",
1844 ),
1845 (
1846 "views/activity_panel.rs",
1847 "theme::surface()",
1848 "cutout ring in the background color, invisible against its surface",
1849 ),
1850 (
1851 "views/avatar.rs",
1852 "theme::surface()",
1853 "cutout ring in the background color, invisible against its surface",
1854 ),
1855 (
1856 "views/avatar.rs",
1857 "theme::text_muted()",
1858 "offline presence glyph, Teams icon",
1859 ),
1860 (
1861 "views/message_row.rs",
1862 "theme::border_strong()",
1863 "deleted message placeholder, Teams look",
1864 ),
1865 (
1866 "views/message_row.rs",
1867 "theme::red()",
1868 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1869 ),
1870 (
1871 "views/message_row.rs",
1872 "if row.delivery",
1873 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1874 ),
1875 (
1876 "views/new_meeting_dialog.rs",
1877 "theme::border()",
1878 "input field",
1879 ),
1880 (
1881 "views/call_mini_window.rs",
1882 "theme::border_strong()",
1883 "self view over live video, needs an edge on any picture",
1884 ),
1885 ("views/transfer_picker.rs", "theme::border()", "input field"),
1886 (
1887 "views/call_notice.rs",
1888 "theme::border_strong()",
1889 "outlined button, not a surface",
1890 ),
1891 (
1892 "views/composer/schedule.rs",
1893 "theme::accent()",
1894 "input field",
1895 ),
1896 (
1897 "views/call_mini.rs",
1898 "border)",
1899 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1900 ),
1901 (
1902 "views/sidebar.rs",
1903 "theme::accent()",
1904 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1905 ),
1906 (
1907 "views/adaptive_card.rs",
1908 "theme::border()",
1909 "message content drawn as Teams renders it",
1910 ),
1911 (
1912 "views/adaptive_card.rs",
1913 "border)",
1914 "message content drawn as Teams renders it",
1915 ),
1916 (
1917 "views/share_bar.rs",
1918 "theme::red()",
1919 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1920 ),
1921 ("settings_controls.rs", "if invalid", "input field"),
1922];
1923
1924fn outlines(source: &str) -> Vec<(usize, String)> {
1925 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
1926 pattern
1927 .find_iter(source)
1928 .map(|found| {
1929 let line_number = source[..found.start()].matches('\n').count() + 1;
1930 let after = &source[found.end()..];
1931 let color = after
1932 .find(".border_color(")
1933 .filter(|position| *position < 120)
1934 .map(|position| {
1935 let start = &after[position + ".border_color(".len()..];
1936 start
1937 .lines()
1938 .map(str::trim)
1939 .find(|line| !line.is_empty())
1940 .unwrap_or_default()
1941 .to_owned()
1942 })
1943 .unwrap_or_default();
1944 (line_number, color)
1945 })
1946 .collect()
1947}
1948
1949#[test]
1950fn outline_matcher_reads_the_border_color() {
1951 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
1952 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
1953}
1954
1955#[test]
1956fn surfaces_are_soft() {
1957 let mut matched_allowlist = HashSet::new();
1958 let mut violations = Vec::new();
1959 for root in source_roots() {
1960 let mut files = Vec::new();
1961 source_files(&root, &mut files);
1962 for file in files {
1963 let relative = file
1964 .strip_prefix(&root)
1965 .expect("inside src")
1966 .to_string_lossy()
1967 .replace('\\', "/");
1968 if relative == "layout_guard.rs" {
1969 continue;
1970 }
1971 let source = fs::read_to_string(&file).expect("read source file");
1972 for (line_number, color) in outlines(&source) {
1973 if STATE_RING_COLORS
1974 .iter()
1975 .any(|prefix| color.starts_with(prefix))
1976 {
1977 continue;
1978 }
1979 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
1980 *allowed_file == relative && color.starts_with(prefix)
1981 }) {
1982 Some(position) => {
1983 matched_allowlist.insert(position);
1984 }
1985 None => violations.push(format!(
1986 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
1987 )),
1988 }
1989 }
1990 }
1991 }
1992 let stale = OUTLINE_ALLOWLIST
1993 .iter()
1994 .enumerate()
1995 .filter(|(position, _)| !matched_allowlist.contains(position))
1996 .map(|(_, (file, prefix, _))| {
1997 format!("stale outline allowlist entry, remove it: {file} {prefix}")
1998 });
1999 let report: Vec<String> = violations.into_iter().chain(stale).collect();
2000 assert!(report.is_empty(), "{}", report.join("\n"));
2001}
2002
2003fn indentation(line: &str) -> usize {
2004 line.len() - line.trim_start().len()
2005}
2006
2007fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
2008 let indent = indentation(lines[index]);
2009 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
2010 let start = lines[..index]
2011 .iter()
2012 .rposition(|line| !belongs(line))
2013 .map_or(0, |position| position + 1);
2014 let end = lines[index..]
2015 .iter()
2016 .position(|line| !belongs(line))
2017 .map_or(lines.len(), |position| index + position);
2018 lines[start..end]
2019 .iter()
2020 .filter(|line| indentation(line) == indent)
2021 .copied()
2022 .collect()
2023}
2024
2025fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
2026 let lines: Vec<&str> = source.lines().collect();
2027 (0..lines.len())
2028 .filter(|&index| row_height.is_match(lines[index]))
2029 .filter(|&index| {
2030 !chain_lines(&lines, index).iter().any(|line| {
2031 let line = line.trim();
2032 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
2033 })
2034 })
2035 .map(|index| index + 1)
2036 .collect()
2037}
2038
2039fn row_height_pattern() -> Regex {
2040 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
2041}
2042
2043#[test]
2044fn matcher_finds_rows_without_flex_none() {
2045 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";
2046 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
2047}
2048
2049#[test]
2050fn fixed_height_rows_never_shrink() {
2051 let row_height = row_height_pattern();
2052 let mut files = Vec::new();
2053 for root in source_roots() {
2054 source_files(&root, &mut files);
2055 }
2056 let violations: Vec<String> = files
2057 .iter()
2058 .filter(|file| !file.ends_with("layout_guard.rs"))
2059 .flat_map(|file| {
2060 let source = fs::read_to_string(file).expect("read source file");
2061 shrinking_rows(&row_height, &source)
2062 .into_iter()
2063 .map(|line| format!("{}:{line}", file.display()))
2064 .collect::<Vec<_>>()
2065 })
2066 .collect();
2067 assert!(
2068 violations.is_empty(),
2069 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
2070 );
2071}