BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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