BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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