BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 25.9 KiB Download Raw
1use std::collections::HashSet;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6
7const WIDGETS_FILE: &str = "views/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_files(directory: &Path, files: &mut Vec<PathBuf>) {
14 for entry in fs::read_dir(directory).expect("read source directory") {
15 let path = entry.expect("directory entry").path();
16 if path.is_dir() {
17 source_files(&path, files);
18 } else if path.extension().is_some_and(|extension| extension == "rs") {
19 files.push(path);
20 }
21 }
22}
23
24fn negative_offsets(
25 pattern: &Regex,
26 source: &str,
27 relative: &str,
28) -> Vec<(usize, Option<usize>, String)> {
29 pattern
30 .find_iter(source)
31 .map(|found| {
32 let line_number = source[..found.start()].matches('\n').count() + 1;
33 let from_match = &source[found.start()..];
34 let allowed = SCAN_ALLOWLIST.iter().position(|(allowed_file, snippet)| {
35 *allowed_file == relative && from_match.starts_with(snippet)
36 });
37 let line_end = from_match.find('\n').unwrap_or(from_match.len());
38 (
39 line_number,
40 allowed,
41 from_match[..line_end].trim().to_owned(),
42 )
43 })
44 .collect()
45}
46
47fn offset_pattern() -> Regex {
48 Regex::new(r"\.(top|right|bottom|left|inset)\(\s*(px\(\s*)?-").expect("pattern")
49}
50
51#[test]
52fn matcher_catches_wrapped_offsets() {
53 let source = "let a = 1;\nlet b = div()\n .top(\n px(-4.))\n .left(px(2.));\n";
54 let found = negative_offsets(&offset_pattern(), source, "views/other.rs");
55 assert_eq!(found, [(3, None, ".top(".to_owned())]);
56}
57
58#[test]
59fn matcher_matches_allowlist_from_match_start() {
60 let source = "x\n .bottom(px(-1.))\n";
61 let found = negative_offsets(&offset_pattern(), source, "views/conversation.rs");
62 assert_eq!(found, [(2, Some(1), ".bottom(px(-1.))".to_owned())]);
63}
64
65#[test]
66fn negative_offsets_go_through_corner_badge() {
67 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
68 let pattern = offset_pattern();
69 let mut files = Vec::new();
70 source_files(&root, &mut files);
71 let mut matched_allowlist = HashSet::new();
72 let mut violations = Vec::new();
73 for file in files {
74 let relative = file
75 .strip_prefix(&root)
76 .expect("inside src")
77 .to_string_lossy()
78 .replace('\\', "/");
79 if relative == WIDGETS_FILE || relative == "layout_guard.rs" {
80 continue;
81 }
82 let source = fs::read_to_string(&file).expect("read source file");
83 for (line_number, position, text) in negative_offsets(&pattern, &source, &relative) {
84 match position {
85 Some(position) => {
86 matched_allowlist.insert(position);
87 }
88 None => violations.push(format!(
89 "{relative}:{line_number}: negative absolute offset, use widgets::corner_badge: {text}"
90 )),
91 }
92 }
93 }
94 let stale: Vec<String> = SCAN_ALLOWLIST
95 .iter()
96 .enumerate()
97 .filter(|(position, _)| !matched_allowlist.contains(position))
98 .map(|(_, (file, snippet))| format!("stale allowlist entry, remove it: {file} {snippet}"))
99 .collect();
100 assert!(
101 violations.is_empty() && stale.is_empty(),
102 "{}",
103 violations
104 .into_iter()
105 .chain(stale)
106 .collect::<Vec<_>>()
107 .join("\n")
108 );
109}
110
111mod frames {
112 use std::collections::HashSet;
113 use std::sync::Arc;
114 use std::time::Duration;
115
116 use gpui_kit::test::TestWindowExt as _;
117 use gpui_kit::{
118 AppContext as _, Bounds, Pixels, TestAppContext, VisualTestContext, WindowOptions, point,
119 px, size,
120 };
121 use store::Store;
122
123 use std::time::Instant;
124
125 use calling::{CallState, CallUpdate, CaptionEntry, CaptionState, RosterEntry, call_channel};
126 use gpui_kit::Entity;
127
128 use crate::app_state::{AppHandle, AppState, Mode, Selection};
129 use crate::call::{ActiveCall, CallModel};
130 use crate::demo;
131 use crate::user_activity::UserInput;
132 use crate::views::call_transcript::TranscriptPanel;
133 use crate::views::recap_tab::RECAP_REGION;
134 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call};
135 use crate::views::shortcuts::{OpenActivity, OpenCallsTab, OpenChannelsTab, OpenSaved};
136
137 const GUARDED: &[&str] = &[
138 "shell",
139 "shell/title-bar",
140 "shell/title-bar/search",
141 "shell/title-bar/own-status",
142 "shell/title-bar/own-status/avatar",
143 "shell/islands",
144 "shell/islands/rail",
145 "shell/islands/sidebar",
146 "shell/islands/main",
147 "shell/status-bar",
148 ];
149 const CALL_GUARDED: &[&str] = &[
150 "shell/islands/main/call-header",
151 "shell/islands/main/call-stage",
152 "shell/islands/main/call-controls",
153 "shell/islands/main/call-controls/mic",
154 "shell/islands/main/call-controls/leave",
155 ];
156 const CALLS_TAGS: &[&str] = &[
157 "shell/islands/sidebar/calls-actions",
158 "shell/islands/sidebar/calls-actions/meet-now",
159 "shell/islands/sidebar/calls-actions/new-meeting",
160 ];
161 const PREJOIN_TAGS: &[&str] = &[
162 "shell/islands/main/prejoin",
163 "shell/islands/main/prejoin/preview",
164 "shell/islands/main/prejoin/controls",
165 "shell/islands/main/prejoin/devices",
166 "shell/islands/main/prejoin/audio",
167 "shell/islands/main/prejoin/actions",
168 ];
169 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";
170 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
171 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
172 const SHARE_GUARDED: &[&str] = &[
173 "shell/islands/main/call-stage/share-content",
174 "shell/islands/main/call-stage/share-content/zoom-chip",
175 "shell/islands/main/call-stage/share-divider",
176 "shell/islands/main/call-stage/share-strip",
177 ];
178 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
179 const OVERLAY_CHROME: &[&str] = &[
180 "shell/islands/main/call-header",
181 "shell/islands/main/call-stage",
182 ];
183 const MENU: &str = "popup-menu";
184 const OWN_STATUS: &str = "shell/title-bar/own-status";
185 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
186 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
187 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
188 const TOLERANCE: f32 = 0.5;
189 const KNOWN_VIOLATIONS: &[&str] = &[];
190
191 type Tag = (&'static str, Bounds<Pixels>);
192
193 enum Screen {
194 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
195 StatusMenu,
196 Call,
197 Prejoin,
198 CallTranscript,
199 CallPeople,
200 CallShare,
201 }
202
203 fn parent_of(path: &str) -> Option<&str> {
204 path.rsplit_once('/').map(|(parent, _)| parent)
205 }
206
207 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
208 let tolerance = px(TOLERANCE);
209 inner.left() >= outer.left() - tolerance
210 && inner.top() >= outer.top() - tolerance
211 && inner.right() <= outer.right() + tolerance
212 && inner.bottom() <= outer.bottom() + tolerance
213 }
214
215 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
216 let tolerance = px(TOLERANCE);
217 first.left() < second.right() - tolerance
218 && second.left() < first.right() - tolerance
219 && first.top() < second.bottom() - tolerance
220 && second.top() < first.bottom() - tolerance
221 }
222
223 fn describe(bounds: Bounds<Pixels>) -> String {
224 format!(
225 "[{:.1},{:.1} {:.1}x{:.1}]",
226 f32::from(bounds.origin.x),
227 f32::from(bounds.origin.y),
228 f32::from(bounds.size.width),
229 f32::from(bounds.size.height)
230 )
231 }
232
233 fn violations(
234 tags: &[Tag],
235 window: Bounds<Pixels>,
236 expected: &[&str],
237 ) -> Vec<(String, String)> {
238 let mut found = Vec::new();
239 let bounds_of = |path: &str| {
240 tags.iter()
241 .find(|(tag, _)| *tag == path)
242 .map(|(_, bounds)| *bounds)
243 };
244 for path in expected {
245 if bounds_of(path).is_none() {
246 found.push((
247 format!("{path}:missing"),
248 format!("{path} was not rendered"),
249 ));
250 }
251 }
252 for (path, bounds) in tags {
253 if !contains(window, *bounds) {
254 found.push((
255 format!("{path}:outside-window"),
256 format!(
257 "{path} {} leaves the window {}",
258 describe(*bounds),
259 describe(window)
260 ),
261 ));
262 }
263 if let Some(parent) =
264 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
265 {
266 if !contains(parent.1, *bounds) {
267 found.push((
268 format!("{path}:outside-parent"),
269 format!(
270 "{path} {} leaves {} {}",
271 describe(*bounds),
272 parent.0,
273 describe(parent.1)
274 ),
275 ));
276 }
277 }
278 for (other, other_bounds) in tags {
279 let overlays = |first: &str, second: &str| {
280 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
281 };
282 let siblings = path < other
283 && parent_of(path).is_some()
284 && parent_of(path) == parent_of(other)
285 && !overlays(path, other)
286 && !overlays(other, path);
287 if siblings && overlaps(*bounds, *other_bounds) {
288 found.push((
289 format!("{path}:overlaps:{other}"),
290 format!(
291 "{path} {} overlaps {other} {}",
292 describe(*bounds),
293 describe(*other_bounds)
294 ),
295 ));
296 }
297 }
298 }
299 found
300 }
301
302 const SETTLE_FRAMES: usize = 2;
303 const SETTLE_LIMIT: usize = 60;
304 const SETTLE_STEP: Duration = Duration::from_millis(50);
305
306 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
307 let mut frames = 0;
308 while frames < SETTLE_FRAMES
309 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
310 {
311 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
312 visual.executor().advance_clock(SETTLE_STEP);
313 std::thread::sleep(SETTLE_STEP);
314 visual.run_until_parked();
315 visual.update(|window, cx| window.render_frame(cx));
316 frames += 1;
317 }
318 GUARDED
319 .iter()
320 .chain(CALL_GUARDED)
321 .chain(CALLS_TAGS)
322 .chain(PREJOIN_TAGS)
323 .chain(SHARE_GUARDED)
324 .chain([&CALL_TRANSCRIPT, &MENU, &RECAP_TAB, &RECAP_REGION, &PEOPLE_PANEL])
325 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
326 .collect()
327 }
328
329 fn sharing_call() -> ActiveCall {
330 let mut call = gallery_call();
331 call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
332 call.share_stage.view.step_in((800., 450.));
333 call
334 }
335
336 fn gallery_call() -> ActiveCall {
337 let (handle, _control) = call_channel();
338 let mut model = CallModel::meeting("Standup", false);
339 model.apply(CallUpdate::State(CallState::Connected {
340 since: Instant::now(),
341 }));
342 model.apply(CallUpdate::Roster(
343 (0..11)
344 .map(|index| RosterEntry {
345 mri: format!("8:orgid:guard-{index}"),
346 display_name: format!("Guest {index}"),
347 muted: false,
348 in_lobby: false,
349 has_video: false,
350 sharing: false,
351 hand: None,
352 spotlight: None,
353 organizer: false,
354 ..Default::default()
355 })
356 .collect(),
357 ));
358 ActiveCall::new(1, model, handle.commands, None, handle.video)
359 }
360
361 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
362 cx.update(gpui_kit::init);
363 cx.update(|cx| {
364 crate::theme::apply(cx);
365 bind_keys(cx);
366 let store = Store::open_in_memory().expect("in-memory store");
367 demo::seed(&store);
368 let mode = Mode {
369 demo: true,
370 read_only: false,
371 demo_sync: None,
372 };
373 let state = cx.new(|_| AppState::new(Arc::new(store), mode));
374 install_globals(&state, UserInput::new(), cx);
375 demo::start_session(&state, cx);
376 let shared_state = state.clone();
377 let startup = Startup {
378 switcher_query: None,
379 composer_text: None,
380 reply_to_last: false,
381 };
382 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
383 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
384 })
385 .expect("open test window")
386 .0;
387 (window, shared_state)
388 })
389 }
390
391 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
392 Bounds {
393 origin: point(px(left), px(top)),
394 size: size(px(width), px(height)),
395 }
396 }
397
398 #[test]
399 fn rules_flag_overlap_and_overflow() {
400 let window = rectangle(0., 0., 100., 100.);
401 let tags: Vec<Tag> = vec![
402 ("shell", rectangle(0., 0., 100., 100.)),
403 ("shell/islands", rectangle(0., 0., 100., 50.)),
404 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
405 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
406 ];
407 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
408 .into_iter()
409 .map(|(key, _)| key)
410 .collect();
411 assert_eq!(
412 keys,
413 [
414 "shell/status-bar:missing",
415 "shell/islands/rail:overlaps:shell/islands/sidebar",
416 "shell/islands/sidebar:outside-window",
417 "shell/islands/sidebar:outside-parent",
418 ]
419 );
420 }
421
422 #[gpui_kit::test]
423 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
424 let (handle, app) = mount(cx);
425 let mut visual = VisualTestContext::from_window(handle, cx);
426 let mut seen_known = HashSet::new();
427 let mut unexpected = Vec::new();
428 for (width, height) in SIZES {
429 visual.simulate_resize(size(px(width), px(height)));
430 let window = Bounds {
431 origin: point(px(0.), px(0.)),
432 size: size(px(width), px(height)),
433 };
434 let screens = [
435 Screen::Tab("chats", None),
436 Screen::Tab(
437 "activity",
438 Some(|visual| visual.dispatch_action(OpenActivity)),
439 ),
440 Screen::Tab(
441 "channels",
442 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
443 ),
444 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
445 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
446 Screen::Prejoin,
447 Screen::StatusMenu,
448 Screen::Call,
449 Screen::CallTranscript,
450 Screen::CallPeople,
451 Screen::CallShare,
452 ];
453 for screen in screens {
454 let (screen_name, status_menu) = match screen {
455 Screen::Tab(name, open) => {
456 if let Some(open) = open {
457 open(&mut visual);
458 }
459 (name, false)
460 }
461 Screen::Call | Screen::CallPeople => {
462 let people_open = matches!(screen, Screen::CallPeople);
463 visual.update(|_, cx| {
464 app.update(cx, |state, cx| {
465 let mut call = gallery_call();
466 call.people_open = people_open;
467 state.call = Some(call);
468 cx.notify();
469 })
470 });
471 (if people_open { "call-people" } else { "call" }, false)
472 }
473 Screen::Prejoin => {
474 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
475 visual.update(|_, cx| {
476 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
477 });
478 ("prejoin", false)
479 }
480 Screen::CallTranscript => {
481 visual.update(|window, cx| {
482 app.update(cx, |state, cx| {
483 let mut call = gallery_call();
484 call.model.apply(CallUpdate::Captions(CaptionState::On));
485 for index in 0..40 {
486 call.model.note_caption(
487 CaptionEntry {
488 id: format!("guard-{index}"),
489 user_id: "8:orgid:guard-0".into(),
490 display_name: "Guest 0".into(),
491 text: "A long guarded sentence that has to wrap inside the panel".into(),
492 is_final: true,
493 },
494 Instant::now(),
495 );
496 }
497 call.transcript_open = true;
498 state.call = Some(call);
499 let app_entity = cx.entity();
500 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)));
501 cx.notify();
502 })
503 });
504 ("call-transcript", false)
505 }
506 Screen::CallShare => {
507 visual.update(|_, cx| {
508 app.update(cx, |state, cx| {
509 state.call = Some(sharing_call());
510 cx.notify();
511 })
512 });
513 ("call-share", false)
514 }
515 Screen::StatusMenu => {
516 let tags = collect(&mut visual, None);
517 let button = tags
518 .iter()
519 .find(|(path, _)| *path == OWN_STATUS)
520 .map(|(_, bounds)| *bounds)
521 .expect("own status button rendered");
522 visual.simulate_click(button.center(), Default::default());
523 ("status-menu", true)
524 }
525 };
526 let is_call = matches!(screen_name, "call" | "call-people" | "call-transcript" | "call-share");
527 let tags = collect(&mut visual, status_menu.then_some(MENU));
528 let mut expected = GUARDED.to_vec();
529 if is_call {
530 expected.extend(CALL_GUARDED);
531 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
532 if sidebar_hidden_in_call(width, panel_open) {
533 expected.retain(|path| *path != "shell/islands/sidebar");
534 }
535 }
536 if screen_name == "call-transcript" {
537 expected.push(CALL_TRANSCRIPT);
538 }
539 if screen_name == "call-people" {
540 expected.push(PEOPLE_PANEL);
541 }
542 if screen_name == "call-share" {
543 expected.extend(SHARE_GUARDED);
544 }
545 if status_menu {
546 expected.push(MENU);
547 }
548 match screen_name {
549 "calls" => expected.extend(CALLS_TAGS),
550 "prejoin" => expected.extend(PREJOIN_TAGS),
551 _ => {}
552 }
553 let mut found = violations(&tags, window, &expected);
554 if status_menu {
555 let menu = tags
556 .iter()
557 .find(|(path, _)| *path == MENU)
558 .map(|(_, bounds)| *bounds);
559 let button = tags
560 .iter()
561 .find(|(path, _)| *path == OWN_STATUS)
562 .map(|(_, bounds)| *bounds);
563 if let (Some(menu), Some(button)) = (menu, button) {
564 if overlaps(menu, button) {
565 found.push((
566 format!("{MENU}:covers:{OWN_STATUS}"),
567 format!(
568 "{MENU} {} covers {OWN_STATUS} {}",
569 describe(menu),
570 describe(button)
571 ),
572 ));
573 }
574 }
575 visual.simulate_keystrokes("escape");
576 visual.run_until_parked();
577 }
578 if is_call {
579 visual.update(|_, cx| {
580 app.update(cx, |state, cx| {
581 state.call = None;
582 cx.notify();
583 })
584 });
585 }
586 if screen_name == "prejoin" {
587 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
588 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
589 }
590 for (key, message) in found {
591 let full_key = format!("{screen_name}@{width}x{height}:{key}");
592 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
593 seen_known.insert(full_key);
594 } else {
595 unexpected.push(format!("{full_key}: {message}"));
596 }
597 }
598 }
599 }
600 let stale: Vec<String> = KNOWN_VIOLATIONS
601 .iter()
602 .filter(|key| !seen_known.contains(**key))
603 .map(|key| format!("stale known violation, remove it: {key}"))
604 .collect();
605 assert!(
606 unexpected.is_empty() && stale.is_empty(),
607 "{}",
608 unexpected
609 .into_iter()
610 .chain(stale)
611 .collect::<Vec<_>>()
612 .join("\n")
613 );
614 }
615 #[gpui_kit::test]
616 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
617 let (handle, state) = mount(cx);
618 let mut visual = VisualTestContext::from_window(handle, cx);
619 for (width, height) in SIZES {
620 visual.simulate_resize(size(px(width), px(height)));
621 let window = Bounds {
622 origin: point(px(0.), px(0.)),
623 size: size(px(width), px(height)),
624 };
625 visual.update(|_, cx| {
626 state.update(cx, |state, cx| {
627 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
628 })
629 });
630 collect(&mut visual, Some(RECAP_TAB));
631 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
632 visual.simulate_click(tab.center(), Default::default());
633 let tags = collect(&mut visual, Some(RECAP_REGION));
634 let mut expected = GUARDED.to_vec();
635 expected.extend([RECAP_TAB, RECAP_REGION]);
636 let found: Vec<String> = violations(&tags, window, &expected)
637 .into_iter()
638 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
639 .collect();
640 assert!(found.is_empty(), "{}", found.join("\n"));
641 }
642 }
643}
644
645#[test]
646fn lines_are_solid() {
647 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
648 let mut files = Vec::new();
649 source_files(&root, &mut files);
650 let violations: Vec<String> = files
651 .iter()
652 .filter(|file| !file.ends_with("layout_guard.rs"))
653 .flat_map(|file| {
654 let source = fs::read_to_string(file).expect("read source file");
655 source
656 .lines()
657 .enumerate()
658 .filter(|(_, line)| {
659 line.contains(".border_dashed(") || line.contains(".border_dotted(")
660 })
661 .map(|(index, line)| {
662 format!(
663 "{}:{}: lines are always solid: {}",
664 file.display(),
665 index + 1,
666 line.trim()
667 )
668 })
669 .collect::<Vec<_>>()
670 })
671 .collect();
672 assert!(violations.is_empty(), "{}", violations.join("\n"));
673}