BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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