BlueGit

ict rusty-teams

Files

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

layout_guard.rs

d39bdfed History
layout_guard.rs 33.4 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, TestAppContext, VisualTestContext, WindowOptions, point,
162 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::user_activity::UserInput;
175 use crate::views::call_transcript::TranscriptPanel;
176 use crate::views::call_view::CHAT_PANEL_TAG;
177 use crate::views::message_row::BUBBLE_TAGS;
178 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
179 use crate::views::reaction_proposal_pill::REACTION_PILL;
180 use crate::views::recap_tab::RECAP_REGION;
181 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call};
182 use crate::views::shortcuts::{OpenActivity, OpenCallsTab, OpenChannelsTab, OpenSaved};
183
184 const GUARDED: &[&str] = &[
185 "shell",
186 "shell/title-bar",
187 "shell/title-bar/search",
188 "shell/title-bar/own-status",
189 "shell/title-bar/own-status/avatar",
190 "shell/islands",
191 "shell/islands/rail",
192 "shell/islands/sidebar",
193 "shell/islands/main",
194 "shell/status-bar",
195 ];
196 const CALL_GUARDED: &[&str] = &[
197 "shell/islands/main/call-header",
198 "shell/islands/main/call-stage",
199 "shell/islands/main/call-controls",
200 "shell/islands/main/call-controls/mic",
201 "shell/islands/main/call-controls/leave",
202 ];
203 const CALLS_TAGS: &[&str] = &[
204 "shell/islands/sidebar/calls-actions",
205 "shell/islands/sidebar/calls-actions/meet-now",
206 "shell/islands/sidebar/calls-actions/new-meeting",
207 ];
208 const PREJOIN_TAGS: &[&str] = &[
209 "shell/islands/main/prejoin",
210 "shell/islands/main/prejoin/preview",
211 "shell/islands/main/prejoin/controls",
212 "shell/islands/main/prejoin/devices",
213 "shell/islands/main/prejoin/audio",
214 "shell/islands/main/prejoin/actions",
215 ];
216 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";
217 const CONSULT_GUARDED: &[&str] = &[
218 "shell/islands/main/call-header/call-consult",
219 "shell/islands/main/call-header/call-consult/transfer",
220 "shell/islands/main/call-header/call-consult/resume",
221 ];
222 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
223 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
224 const SHARE_GUARDED: &[&str] = &[
225 "shell/islands/main/call-stage/share-content",
226 "shell/islands/main/call-stage/share-content/zoom-chip",
227 "shell/islands/main/call-stage/share-divider",
228 "shell/islands/main/call-stage/share-strip",
229 ];
230 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
231 const OVERLAY_CHROME: &[&str] = &[
232 "shell/islands/main/call-header",
233 "shell/islands/main/call-stage",
234 ];
235 const MENU: &str = "popup-menu";
236 const OWN_STATUS: &str = "shell/title-bar/own-status";
237 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
238 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
239 const PROPOSAL_CHAT: &str = "demo-chat-release";
240 const REACTION_CHAT: &str = "demo-chat-mara";
241 const AGENT_TAGS: [&str; 4] = [
242 PROPOSAL_CARD,
243 PROPOSAL_THUMBNAILS,
244 PROPOSAL_BUTTONS,
245 REACTION_PILL,
246 ];
247 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
248 const TOLERANCE: f32 = 0.5;
249 const KNOWN_VIOLATIONS: &[&str] = &[];
250
251 type Tag = (&'static str, Bounds<Pixels>);
252
253 enum Screen {
254 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
255 StatusMenu,
256 Call,
257 Prejoin,
258 CallTranscript,
259 CallPeople,
260 CallShare,
261 CallConsult,
262 }
263
264 fn parent_of(path: &str) -> Option<&str> {
265 path.rsplit_once('/').map(|(parent, _)| parent)
266 }
267
268 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
269 let tolerance = px(TOLERANCE);
270 inner.left() >= outer.left() - tolerance
271 && inner.top() >= outer.top() - tolerance
272 && inner.right() <= outer.right() + tolerance
273 && inner.bottom() <= outer.bottom() + tolerance
274 }
275
276 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
277 let tolerance = px(TOLERANCE);
278 first.left() < second.right() - tolerance
279 && second.left() < first.right() - tolerance
280 && first.top() < second.bottom() - tolerance
281 && second.top() < first.bottom() - tolerance
282 }
283
284 fn describe(bounds: Bounds<Pixels>) -> String {
285 format!(
286 "[{:.1},{:.1} {:.1}x{:.1}]",
287 f32::from(bounds.origin.x),
288 f32::from(bounds.origin.y),
289 f32::from(bounds.size.width),
290 f32::from(bounds.size.height)
291 )
292 }
293
294 fn violations(
295 tags: &[Tag],
296 window: Bounds<Pixels>,
297 expected: &[&str],
298 ) -> Vec<(String, String)> {
299 let mut found = Vec::new();
300 let bounds_of = |path: &str| {
301 tags.iter()
302 .find(|(tag, _)| *tag == path)
303 .map(|(_, bounds)| *bounds)
304 };
305 for path in expected {
306 if bounds_of(path).is_none() {
307 found.push((
308 format!("{path}:missing"),
309 format!("{path} was not rendered"),
310 ));
311 }
312 }
313 for (path, bounds) in tags {
314 if !contains(window, *bounds) {
315 found.push((
316 format!("{path}:outside-window"),
317 format!(
318 "{path} {} leaves the window {}",
319 describe(*bounds),
320 describe(window)
321 ),
322 ));
323 }
324 if let Some(parent) =
325 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
326 {
327 if !contains(parent.1, *bounds) {
328 found.push((
329 format!("{path}:outside-parent"),
330 format!(
331 "{path} {} leaves {} {}",
332 describe(*bounds),
333 parent.0,
334 describe(parent.1)
335 ),
336 ));
337 }
338 }
339 for (other, other_bounds) in tags {
340 let overlays = |first: &str, second: &str| {
341 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
342 };
343 let siblings = path < other
344 && parent_of(path).is_some()
345 && parent_of(path) == parent_of(other)
346 && !overlays(path, other)
347 && !overlays(other, path);
348 if siblings && overlaps(*bounds, *other_bounds) {
349 found.push((
350 format!("{path}:overlaps:{other}"),
351 format!(
352 "{path} {} overlaps {other} {}",
353 describe(*bounds),
354 describe(*other_bounds)
355 ),
356 ));
357 }
358 }
359 }
360 found
361 }
362
363 const SETTLE_FRAMES: usize = 2;
364 const SETTLE_LIMIT: usize = 60;
365 const SETTLE_STEP: Duration = Duration::from_millis(50);
366
367 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
368 let mut frames = 0;
369 while frames < SETTLE_FRAMES
370 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
371 {
372 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
373 visual.executor().advance_clock(SETTLE_STEP);
374 std::thread::sleep(SETTLE_STEP);
375 visual.run_until_parked();
376 visual.update(|window, cx| window.render_frame(cx));
377 frames += 1;
378 }
379 GUARDED
380 .iter()
381 .chain(CALL_GUARDED)
382 .chain(CALLS_TAGS)
383 .chain(PREJOIN_TAGS)
384 .chain(SHARE_GUARDED)
385 .chain(CONSULT_GUARDED)
386 .chain([
387 &CALL_TRANSCRIPT,
388 &MENU,
389 &RECAP_TAB,
390 &RECAP_REGION,
391 &PEOPLE_PANEL,
392 ])
393 .chain(&AGENT_TAGS)
394 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
395 .collect()
396 }
397
398 fn sharing_call() -> ActiveCall {
399 let mut call = gallery_call();
400 call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
401 call.share_stage.view.step_in((800., 450.));
402 call
403 }
404
405 fn gallery_call() -> ActiveCall {
406 let (handle, _control) = call_channel();
407 let mut model = CallModel::meeting("Standup", false);
408 model.apply(CallUpdate::State(CallState::Connected {
409 since: Instant::now(),
410 }));
411 model.apply(CallUpdate::Roster(
412 (0..11)
413 .map(|index| RosterEntry {
414 mri: format!("8:orgid:guard-{index}"),
415 display_name: format!("Guest {index}"),
416 muted: false,
417 in_lobby: false,
418 has_video: false,
419 sharing: false,
420 hand: None,
421 spotlight: None,
422 organizer: false,
423 ..Default::default()
424 })
425 .collect(),
426 ));
427 ActiveCall::new(1, model, handle.commands, None, handle.video)
428 }
429
430 fn consult_calls() -> (ActiveCall, ActiveCall) {
431 let connected = |id: u64, name: &str, mri: &str| {
432 let (handle, _control) = call_channel();
433 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
434 model.apply(CallUpdate::State(CallState::Connected {
435 since: Instant::now(),
436 }));
437 ActiveCall::new(id, model, handle.commands, None, handle.video)
438 };
439 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
440 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
441 consult.consult = Some(ConsultCall::new(
442 ("8:orgid:guard-consult".to_owned(), "Jonas Ortega".to_owned()),
443 held.model.peer_name.clone(),
444 ));
445 (consult, held)
446 }
447
448 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
449 mount_with(cx, false)
450 }
451
452 fn mount_with(
453 cx: &mut TestAppContext,
454 agent_api: bool,
455 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
456 cx.update(gpui_kit::init);
457 cx.update(|cx| {
458 crate::theme::apply(cx);
459 bind_keys(cx);
460 let store = Store::open_in_memory().expect("in-memory store");
461 demo::seed(&store);
462 let store = Arc::new(store);
463 if agent_api {
464 crate::agent_api::init(store.clone(), true, cx);
465 }
466 let mode = Mode {
467 demo: true,
468 read_only: false,
469 demo_sync: None,
470 };
471 let state = cx.new(|_| AppState::new(store, mode));
472 install_globals(&state, UserInput::new(), cx);
473 demo::start_session(&state, cx);
474 let shared_state = state.clone();
475 let startup = Startup {
476 switcher_query: None,
477 composer_text: None,
478 reply_to_last: false,
479 };
480 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
481 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
482 })
483 .expect("open test window")
484 .0;
485 (window, shared_state)
486 })
487 }
488
489 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
490 Bounds {
491 origin: point(px(left), px(top)),
492 size: size(px(width), px(height)),
493 }
494 }
495
496 #[test]
497 fn rules_flag_overlap_and_overflow() {
498 let window = rectangle(0., 0., 100., 100.);
499 let tags: Vec<Tag> = vec![
500 ("shell", rectangle(0., 0., 100., 100.)),
501 ("shell/islands", rectangle(0., 0., 100., 50.)),
502 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
503 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
504 ];
505 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
506 .into_iter()
507 .map(|(key, _)| key)
508 .collect();
509 assert_eq!(
510 keys,
511 [
512 "shell/status-bar:missing",
513 "shell/islands/rail:overlaps:shell/islands/sidebar",
514 "shell/islands/sidebar:outside-window",
515 "shell/islands/sidebar:outside-parent",
516 ]
517 );
518 }
519
520 #[gpui_kit::test]
521 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
522 let (handle, app) = mount(cx);
523 let mut visual = VisualTestContext::from_window(handle, cx);
524 let mut seen_known = HashSet::new();
525 let mut unexpected = Vec::new();
526 for (width, height) in SIZES {
527 visual.simulate_resize(size(px(width), px(height)));
528 let window = Bounds {
529 origin: point(px(0.), px(0.)),
530 size: size(px(width), px(height)),
531 };
532 let screens = [
533 Screen::Tab("chats", None),
534 Screen::Tab(
535 "activity",
536 Some(|visual| visual.dispatch_action(OpenActivity)),
537 ),
538 Screen::Tab(
539 "channels",
540 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
541 ),
542 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
543 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
544 Screen::Prejoin,
545 Screen::StatusMenu,
546 Screen::Call,
547 Screen::CallTranscript,
548 Screen::CallPeople,
549 Screen::CallShare,
550 Screen::CallConsult,
551 ];
552 for screen in screens {
553 let (screen_name, status_menu) = match screen {
554 Screen::Tab(name, open) => {
555 if let Some(open) = open {
556 open(&mut visual);
557 }
558 (name, false)
559 }
560 Screen::Call | Screen::CallPeople => {
561 let people_open = matches!(screen, Screen::CallPeople);
562 visual.update(|_, cx| {
563 app.update(cx, |state, cx| {
564 let mut call = gallery_call();
565 call.people_open = people_open;
566 state.call = Some(call);
567 cx.notify();
568 })
569 });
570 (if people_open { "call-people" } else { "call" }, false)
571 }
572 Screen::Prejoin => {
573 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
574 visual.update(|_, cx| {
575 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
576 });
577 ("prejoin", false)
578 }
579 Screen::CallTranscript => {
580 visual.update(|window, cx| {
581 app.update(cx, |state, cx| {
582 let mut call = gallery_call();
583 call.model.apply(CallUpdate::Captions(CaptionState::On));
584 for index in 0..40 {
585 call.model.note_caption(
586 CaptionEntry {
587 id: format!("guard-{index}"),
588 user_id: "8:orgid:guard-0".into(),
589 display_name: "Guest 0".into(),
590 text: "A long guarded sentence that has to wrap inside the panel".into(),
591 is_final: true,
592 },
593 Instant::now(),
594 );
595 }
596 call.transcript_open = true;
597 state.call = Some(call);
598 let app_entity = cx.entity();
599 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
600 cx.notify();
601 })
602 });
603 ("call-transcript", false)
604 }
605 Screen::CallShare => {
606 visual.update(|_, cx| {
607 app.update(cx, |state, cx| {
608 state.call = Some(sharing_call());
609 cx.notify();
610 })
611 });
612 ("call-share", false)
613 }
614 Screen::CallConsult => {
615 visual.update(|_, cx| {
616 app.update(cx, |state, cx| {
617 let (consult, held) = consult_calls();
618 state.call = Some(consult);
619 state.held_call = Some(held);
620 cx.notify();
621 })
622 });
623 ("call-consult", false)
624 }
625 Screen::StatusMenu => {
626 let tags = collect(&mut visual, None);
627 let button = tags
628 .iter()
629 .find(|(path, _)| *path == OWN_STATUS)
630 .map(|(_, bounds)| *bounds)
631 .expect("own status button rendered");
632 visual.simulate_click(button.center(), Default::default());
633 ("status-menu", true)
634 }
635 };
636 let is_call = matches!(
637 screen_name,
638 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
639 );
640 let tags = collect(&mut visual, status_menu.then_some(MENU));
641 let mut expected = GUARDED.to_vec();
642 if is_call {
643 expected.extend(CALL_GUARDED);
644 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
645 if sidebar_hidden_in_call(width, panel_open) {
646 expected.retain(|path| *path != "shell/islands/sidebar");
647 }
648 }
649 if screen_name == "call-transcript" {
650 expected.push(CALL_TRANSCRIPT);
651 }
652 if screen_name == "call-people" {
653 expected.push(PEOPLE_PANEL);
654 }
655 if screen_name == "call-share" {
656 expected.extend(SHARE_GUARDED);
657 }
658 if screen_name == "call-consult" {
659 expected.extend(CONSULT_GUARDED);
660 }
661 if status_menu {
662 expected.push(MENU);
663 }
664 match screen_name {
665 "calls" => expected.extend(CALLS_TAGS),
666 "prejoin" => expected.extend(PREJOIN_TAGS),
667 _ => {}
668 }
669 let mut found = violations(&tags, window, &expected);
670 if status_menu {
671 let menu = tags
672 .iter()
673 .find(|(path, _)| *path == MENU)
674 .map(|(_, bounds)| *bounds);
675 let button = tags
676 .iter()
677 .find(|(path, _)| *path == OWN_STATUS)
678 .map(|(_, bounds)| *bounds);
679 if let (Some(menu), Some(button)) = (menu, button) {
680 if overlaps(menu, button) {
681 found.push((
682 format!("{MENU}:covers:{OWN_STATUS}"),
683 format!(
684 "{MENU} {} covers {OWN_STATUS} {}",
685 describe(menu),
686 describe(button)
687 ),
688 ));
689 }
690 }
691 visual.simulate_keystrokes("escape");
692 visual.run_until_parked();
693 }
694 if is_call {
695 visual.update(|_, cx| {
696 app.update(cx, |state, cx| {
697 state.call = None;
698 state.held_call = None;
699 cx.notify();
700 })
701 });
702 }
703 if screen_name == "prejoin" {
704 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
705 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
706 }
707 for (key, message) in found {
708 let full_key = format!("{screen_name}@{width}x{height}:{key}");
709 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
710 seen_known.insert(full_key);
711 } else {
712 unexpected.push(format!("{full_key}: {message}"));
713 }
714 }
715 }
716 }
717 let stale: Vec<String> = KNOWN_VIOLATIONS
718 .iter()
719 .filter(|key| !seen_known.contains(**key))
720 .map(|key| format!("stale known violation, remove it: {key}"))
721 .collect();
722 assert!(
723 unexpected.is_empty() && stale.is_empty(),
724 "{}",
725 unexpected
726 .into_iter()
727 .chain(stale)
728 .collect::<Vec<_>>()
729 .join("\n")
730 );
731 }
732 #[gpui_kit::test]
733 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
734 let (handle, app) = mount(cx);
735 let mut visual = VisualTestContext::from_window(handle, cx);
736 for (width, height) in SIZES {
737 visual.simulate_resize(size(px(width), px(height)));
738 visual.update(|_, cx| {
739 app.update(cx, |state, cx| {
740 let mut call = gallery_call();
741 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
742 call.chat_open = true;
743 state.call = Some(call);
744 cx.notify();
745 })
746 });
747 collect(&mut visual, Some(CHAT_PANEL_TAG));
748 let panel = visual
749 .debug_bounds(CHAT_PANEL_TAG)
750 .expect("chat panel rendered");
751 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
752 .iter()
753 .enumerate()
754 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
755 .collect();
756 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
757 let found: Vec<String> = bubbles
758 .into_iter()
759 .filter(|(_, bounds)| !contains(panel, *bounds))
760 .map(|(index, bounds)| {
761 format!(
762 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
763 describe(bounds),
764 describe(panel)
765 )
766 })
767 .collect();
768 visual.update(|_, cx| {
769 app.update(cx, |state, cx| {
770 state.call = None;
771 cx.notify();
772 })
773 });
774 assert!(found.is_empty(), "{}", found.join("\n"));
775 }
776 }
777
778 #[gpui_kit::test]
779 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
780 let (handle, state) = mount(cx);
781 let mut visual = VisualTestContext::from_window(handle, cx);
782 for (width, height) in SIZES {
783 visual.simulate_resize(size(px(width), px(height)));
784 let window = Bounds {
785 origin: point(px(0.), px(0.)),
786 size: size(px(width), px(height)),
787 };
788 visual.update(|_, cx| {
789 state.update(cx, |state, cx| {
790 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
791 })
792 });
793 collect(&mut visual, Some(RECAP_TAB));
794 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
795 visual.simulate_click(tab.center(), Default::default());
796 let tags = collect(&mut visual, Some(RECAP_REGION));
797 let mut expected = GUARDED.to_vec();
798 expected.extend([RECAP_TAB, RECAP_REGION]);
799 let found: Vec<String> = violations(&tags, window, &expected)
800 .into_iter()
801 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
802 .collect();
803 assert!(found.is_empty(), "{}", found.join("\n"));
804 }
805 }
806
807 #[gpui_kit::test]
808 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
809 let (handle, state) = mount_with(cx, true);
810 let mut visual = VisualTestContext::from_window(handle, cx);
811 for (width, height) in SIZES {
812 visual.simulate_resize(size(px(width), px(height)));
813 let window = Bounds {
814 origin: point(px(0.), px(0.)),
815 size: size(px(width), px(height)),
816 };
817 for (chat, expected_tags) in [
818 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
819 (REACTION_CHAT, &AGENT_TAGS[3..]),
820 ] {
821 visual.update(|_, cx| {
822 state.update(cx, |state, cx| {
823 state.select(Selection::Chat(chat.to_owned()), cx)
824 })
825 });
826 let tags = collect(&mut visual, Some(expected_tags[0]));
827 let mut expected = GUARDED.to_vec();
828 expected.extend(expected_tags);
829 let found: Vec<String> = violations(&tags, window, &expected)
830 .into_iter()
831 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
832 .collect();
833 assert!(found.is_empty(), "{}", found.join("\n"));
834 }
835 }
836 }
837}
838
839#[test]
840fn lines_are_solid() {
841 let mut files = Vec::new();
842 for root in source_roots() {
843 source_files(&root, &mut files);
844 }
845 let violations: Vec<String> = files
846 .iter()
847 .filter(|file| !file.ends_with("layout_guard.rs"))
848 .flat_map(|file| {
849 let source = fs::read_to_string(file).expect("read source file");
850 source
851 .lines()
852 .enumerate()
853 .filter(|(_, line)| {
854 line.contains(".border_dashed(") || line.contains(".border_dotted(")
855 })
856 .map(|(index, line)| {
857 format!(
858 "{}:{}: lines are always solid: {}",
859 file.display(),
860 index + 1,
861 line.trim()
862 )
863 })
864 .collect::<Vec<_>>()
865 })
866 .collect();
867 assert!(violations.is_empty(), "{}", violations.join("\n"));
868}