BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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