BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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