BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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