BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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