BlueGit

ict rusty-teams

Files

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

layout_guard.rs

merge: meeting recap tab
metis Daniel Däschle · pushed by metis · 7 weeks ago
ffc96243 History
layout_guard.rs 18.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, RosterEntry, call_channel};
126 use gpui_kit::Entity;
127
128 use crate::app_state::{AppState, Mode, Selection};
129 use crate::call::{ActiveCall, CallModel};
130 use crate::demo;
131 use crate::user_activity::UserInput;
132 use crate::views::recap_tab::RECAP_REGION;
133 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals};
134 use crate::views::shortcuts::{OpenActivity, OpenCallsTab, OpenChannelsTab, OpenSaved};
135
136 const GUARDED: &[&str] = &[
137 "shell",
138 "shell/title-bar",
139 "shell/title-bar/search",
140 "shell/title-bar/own-status",
141 "shell/title-bar/own-status/avatar",
142 "shell/islands",
143 "shell/islands/rail",
144 "shell/islands/sidebar",
145 "shell/islands/main",
146 "shell/status-bar",
147 ];
148 const CALL_GUARDED: &[&str] = &[
149 "shell/islands/main/call-header",
150 "shell/islands/main/call-stage",
151 "shell/islands/main/call-controls",
152 ];
153 const MENU: &str = "popup-menu";
154 const OWN_STATUS: &str = "shell/title-bar/own-status";
155 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
156 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
157 const SIZES: [(f32, f32); 2] = [(640., 480.), (1920., 1080.)];
158 const TOLERANCE: f32 = 0.5;
159 const KNOWN_VIOLATIONS: &[&str] = &[];
160
161 type Tag = (&'static str, Bounds<Pixels>);
162
163 enum Screen {
164 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
165 StatusMenu,
166 Call,
167 }
168
169 fn parent_of(path: &str) -> Option<&str> {
170 path.rsplit_once('/').map(|(parent, _)| parent)
171 }
172
173 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
174 let tolerance = px(TOLERANCE);
175 inner.left() >= outer.left() - tolerance
176 && inner.top() >= outer.top() - tolerance
177 && inner.right() <= outer.right() + tolerance
178 && inner.bottom() <= outer.bottom() + tolerance
179 }
180
181 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
182 let tolerance = px(TOLERANCE);
183 first.left() < second.right() - tolerance
184 && second.left() < first.right() - tolerance
185 && first.top() < second.bottom() - tolerance
186 && second.top() < first.bottom() - tolerance
187 }
188
189 fn describe(bounds: Bounds<Pixels>) -> String {
190 format!(
191 "[{:.1},{:.1} {:.1}x{:.1}]",
192 f32::from(bounds.origin.x),
193 f32::from(bounds.origin.y),
194 f32::from(bounds.size.width),
195 f32::from(bounds.size.height)
196 )
197 }
198
199 fn violations(
200 tags: &[Tag],
201 window: Bounds<Pixels>,
202 expected: &[&str],
203 ) -> Vec<(String, String)> {
204 let mut found = Vec::new();
205 let bounds_of = |path: &str| {
206 tags.iter()
207 .find(|(tag, _)| *tag == path)
208 .map(|(_, bounds)| *bounds)
209 };
210 for path in expected {
211 if bounds_of(path).is_none() {
212 found.push((
213 format!("{path}:missing"),
214 format!("{path} was not rendered"),
215 ));
216 }
217 }
218 for (path, bounds) in tags {
219 if !contains(window, *bounds) {
220 found.push((
221 format!("{path}:outside-window"),
222 format!(
223 "{path} {} leaves the window {}",
224 describe(*bounds),
225 describe(window)
226 ),
227 ));
228 }
229 if let Some(parent) =
230 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
231 {
232 if !contains(parent.1, *bounds) {
233 found.push((
234 format!("{path}:outside-parent"),
235 format!(
236 "{path} {} leaves {} {}",
237 describe(*bounds),
238 parent.0,
239 describe(parent.1)
240 ),
241 ));
242 }
243 }
244 for (other, other_bounds) in tags {
245 let siblings = path < other
246 && parent_of(path).is_some()
247 && parent_of(path) == parent_of(other);
248 if siblings && overlaps(*bounds, *other_bounds) {
249 found.push((
250 format!("{path}:overlaps:{other}"),
251 format!(
252 "{path} {} overlaps {other} {}",
253 describe(*bounds),
254 describe(*other_bounds)
255 ),
256 ));
257 }
258 }
259 }
260 found
261 }
262
263 const SETTLE_FRAMES: usize = 2;
264 const SETTLE_LIMIT: usize = 60;
265 const SETTLE_STEP: Duration = Duration::from_millis(50);
266
267 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
268 let mut frames = 0;
269 while frames < SETTLE_FRAMES
270 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
271 {
272 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
273 visual.executor().advance_clock(SETTLE_STEP);
274 std::thread::sleep(SETTLE_STEP);
275 visual.run_until_parked();
276 visual.update(|window, cx| window.render_frame(cx));
277 frames += 1;
278 }
279 GUARDED
280 .iter()
281 .chain(CALL_GUARDED)
282 .chain([&MENU, &RECAP_TAB, &RECAP_REGION])
283 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
284 .collect()
285 }
286
287 fn gallery_call() -> ActiveCall {
288 let (handle, _control) = call_channel();
289 let mut model = CallModel::meeting("Standup", false);
290 model.apply(CallUpdate::State(CallState::Connected {
291 since: Instant::now(),
292 }));
293 model.apply(CallUpdate::Roster(
294 (0..11)
295 .map(|index| RosterEntry {
296 mri: format!("8:orgid:guard-{index}"),
297 display_name: format!("Guest {index}"),
298 muted: false,
299 in_lobby: false,
300 has_video: false,
301 sharing: false,
302 hand: None,
303 spotlight: None,
304 organizer: false,
305 })
306 .collect(),
307 ));
308 ActiveCall::new(1, model, handle.commands, None, handle.video)
309 }
310
311 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
312 cx.update(gpui_kit::init);
313 cx.update(|cx| {
314 crate::theme::apply(cx);
315 bind_keys(cx);
316 let store = Store::open_in_memory().expect("in-memory store");
317 demo::seed(&store);
318 let mode = Mode {
319 demo: true,
320 read_only: false,
321 demo_sync: None,
322 };
323 let state = cx.new(|_| AppState::new(Arc::new(store), mode));
324 install_globals(&state, UserInput::new(), cx);
325 demo::start_session(&state, cx);
326 let shared_state = state.clone();
327 let startup = Startup {
328 switcher_query: None,
329 composer_text: None,
330 reply_to_last: false,
331 };
332 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
333 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
334 })
335 .expect("open test window")
336 .0;
337 (window, shared_state)
338 })
339 }
340
341 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
342 Bounds {
343 origin: point(px(left), px(top)),
344 size: size(px(width), px(height)),
345 }
346 }
347
348 #[test]
349 fn rules_flag_overlap_and_overflow() {
350 let window = rectangle(0., 0., 100., 100.);
351 let tags: Vec<Tag> = vec![
352 ("shell", rectangle(0., 0., 100., 100.)),
353 ("shell/islands", rectangle(0., 0., 100., 50.)),
354 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
355 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
356 ];
357 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
358 .into_iter()
359 .map(|(key, _)| key)
360 .collect();
361 assert_eq!(
362 keys,
363 [
364 "shell/status-bar:missing",
365 "shell/islands/rail:overlaps:shell/islands/sidebar",
366 "shell/islands/sidebar:outside-window",
367 "shell/islands/sidebar:outside-parent",
368 ]
369 );
370 }
371
372 #[gpui_kit::test]
373 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
374 let (handle, app) = mount(cx);
375 let mut visual = VisualTestContext::from_window(handle, cx);
376 let mut seen_known = HashSet::new();
377 let mut unexpected = Vec::new();
378 for (width, height) in SIZES {
379 visual.simulate_resize(size(px(width), px(height)));
380 let window = Bounds {
381 origin: point(px(0.), px(0.)),
382 size: size(px(width), px(height)),
383 };
384 let screens = [
385 Screen::Tab("chats", None),
386 Screen::Tab(
387 "activity",
388 Some(|visual| visual.dispatch_action(OpenActivity)),
389 ),
390 Screen::Tab(
391 "channels",
392 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
393 ),
394 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
395 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
396 Screen::StatusMenu,
397 Screen::Call,
398 ];
399 for screen in screens {
400 let (screen_name, status_menu) = match screen {
401 Screen::Tab(name, open) => {
402 if let Some(open) = open {
403 open(&mut visual);
404 }
405 (name, false)
406 }
407 Screen::Call => {
408 visual.update(|_, cx| {
409 app.update(cx, |state, cx| {
410 state.call = Some(gallery_call());
411 cx.notify();
412 })
413 });
414 ("call", false)
415 }
416 Screen::StatusMenu => {
417 let tags = collect(&mut visual, None);
418 let button = tags
419 .iter()
420 .find(|(path, _)| *path == OWN_STATUS)
421 .map(|(_, bounds)| *bounds)
422 .expect("own status button rendered");
423 visual.simulate_click(button.center(), Default::default());
424 ("status-menu", true)
425 }
426 };
427 let tags = collect(&mut visual, status_menu.then_some(MENU));
428 let mut expected = GUARDED.to_vec();
429 if screen_name == "call" {
430 expected.extend(CALL_GUARDED);
431 }
432 if status_menu {
433 expected.push(MENU);
434 }
435 let mut found = violations(&tags, window, &expected);
436 if status_menu {
437 let menu = tags
438 .iter()
439 .find(|(path, _)| *path == MENU)
440 .map(|(_, bounds)| *bounds);
441 let button = tags
442 .iter()
443 .find(|(path, _)| *path == OWN_STATUS)
444 .map(|(_, bounds)| *bounds);
445 if let (Some(menu), Some(button)) = (menu, button) {
446 if overlaps(menu, button) {
447 found.push((
448 format!("{MENU}:covers:{OWN_STATUS}"),
449 format!(
450 "{MENU} {} covers {OWN_STATUS} {}",
451 describe(menu),
452 describe(button)
453 ),
454 ));
455 }
456 }
457 visual.simulate_keystrokes("escape");
458 visual.run_until_parked();
459 }
460 if screen_name == "call" {
461 visual.update(|_, cx| {
462 app.update(cx, |state, cx| {
463 state.call = None;
464 cx.notify();
465 })
466 });
467 }
468 for (key, message) in found {
469 let full_key = format!("{screen_name}@{width}x{height}:{key}");
470 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
471 seen_known.insert(full_key);
472 } else {
473 unexpected.push(format!("{full_key}: {message}"));
474 }
475 }
476 }
477 }
478 let stale: Vec<String> = KNOWN_VIOLATIONS
479 .iter()
480 .filter(|key| !seen_known.contains(**key))
481 .map(|key| format!("stale known violation, remove it: {key}"))
482 .collect();
483 assert!(
484 unexpected.is_empty() && stale.is_empty(),
485 "{}",
486 unexpected
487 .into_iter()
488 .chain(stale)
489 .collect::<Vec<_>>()
490 .join("\n")
491 );
492 }
493 #[gpui_kit::test]
494 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
495 let (handle, state) = mount(cx);
496 let mut visual = VisualTestContext::from_window(handle, cx);
497 for (width, height) in SIZES {
498 visual.simulate_resize(size(px(width), px(height)));
499 let window = Bounds {
500 origin: point(px(0.), px(0.)),
501 size: size(px(width), px(height)),
502 };
503 visual.update(|_, cx| {
504 state.update(cx, |state, cx| {
505 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
506 })
507 });
508 collect(&mut visual, Some(RECAP_TAB));
509 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
510 visual.simulate_click(tab.center(), Default::default());
511 let tags = collect(&mut visual, Some(RECAP_REGION));
512 let mut expected = GUARDED.to_vec();
513 expected.extend([RECAP_TAB, RECAP_REGION]);
514 let found: Vec<String> = violations(&tags, window, &expected)
515 .into_iter()
516 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
517 .collect();
518 assert!(found.is_empty(), "{}", found.join("\n"));
519 }
520 }
521}