BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 75.8 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, ScrollDelta, ScrollWheelEvent, TestAppContext,
162 VisualTestContext, WindowOptions, point, 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::call::{ActiveCall, CallModel, ConsultCall};
173 use crate::demo;
174 use crate::settings::{item_selector, label, label_selector, metrics};
175 use crate::settings_section::SettingsSection;
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::composer::{
180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 };
183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
185 use crate::views::message_row::BUBBLE_TAGS;
186 use crate::views::pin_banner::PIN_BANNER_TAG;
187 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
188 use crate::views::reaction_proposal_pill::REACTION_PILL;
189 use crate::views::recap_tab::RECAP_REGION;
190 use crate::views::shell::{
191 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
192 };
193 use crate::views::shortcuts::{
194 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
195 };
196 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
197 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
198
199 const GUARDED: &[&str] = &[
200 "shell",
201 "shell/title-bar",
202 "shell/title-bar/search",
203 "shell/title-bar/own-status",
204 "shell/title-bar/own-status/avatar",
205 OWN_AVATAR_DISC,
206 "shell/islands",
207 "shell/islands/rail",
208 "shell/islands/sidebar",
209 "shell/islands/main",
210 ];
211 const CALL_GUARDED: &[&str] = &[
212 "shell/islands/main/call-header",
213 "shell/islands/main/call-stage",
214 "shell/islands/main/call-controls",
215 "shell/islands/main/call-controls/mic",
216 "shell/islands/main/call-controls/leave",
217 ];
218 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
219 const CALLS_TAGS: &[&str] = &[
220 "shell/islands/sidebar/calls-actions",
221 "shell/islands/sidebar/calls-actions/meet-now",
222 "shell/islands/sidebar/calls-actions/new-meeting",
223 ];
224 const PREJOIN_TAGS: &[&str] = &[
225 "shell/islands/main/prejoin",
226 "shell/islands/main/prejoin/preview",
227 "shell/islands/main/prejoin/controls",
228 "shell/islands/main/prejoin/devices",
229 "shell/islands/main/prejoin/audio",
230 "shell/islands/main/prejoin/actions",
231 ];
232 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";
233 const CONSULT_GUARDED: &[&str] = &[
234 "shell/islands/main/call-header/call-consult",
235 "shell/islands/main/call-header/call-consult/transfer",
236 "shell/islands/main/call-header/call-consult/resume",
237 ];
238 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
239 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
240 const SHARE_GUARDED: &[&str] = &[
241 "shell/islands/main/call-stage/share-content",
242 "shell/islands/main/call-stage/share-content/zoom-chip",
243 "shell/islands/main/call-stage/share-divider",
244 "shell/islands/main/call-stage/share-strip",
245 ];
246 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
247 const OVERLAY_CHROME: &[&str] = &[
248 "shell/islands/main/call-header",
249 "shell/islands/main/call-stage",
250 ];
251 const MENU: &str = "popup-menu";
252 const OWN_STATUS: &str = "shell/title-bar/own-status";
253 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
254 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
255 const PROPOSAL_CHAT: &str = "demo-chat-release";
256 const REACTION_CHAT: &str = "demo-chat-mara";
257 const AGENT_TAGS: [&str; 4] = [
258 PROPOSAL_CARD,
259 PROPOSAL_THUMBNAILS,
260 PROPOSAL_BUTTONS,
261 REACTION_PILL,
262 ];
263 const SETTINGS_TAGS: &[&str] = &[
264 "settings",
265 "settings/nav",
266 "settings/nav/divider",
267 "settings/nav/about",
268 "settings/main",
269 "settings/main/header",
270 "settings/main/header/close",
271 "settings/main/body",
272 ];
273 const SETTINGS_BODY: &str = "settings/main/body";
274 const SETTINGS_NAV: &str = "settings/nav";
275 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
276 const NAV_LABEL_SIZE: f32 = 14.;
277 const NAV_LINE_HEIGHT: f32 = 20.;
278 const SETTINGS_CONTENT: &str = "settings/main/body/content";
279 const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
280 const MEMBERS_CHAT: &str = "demo-chat-release";
281 const SIDEBAR: &str = "shell/islands/sidebar";
282 const MAIN: &str = "shell/islands/main";
283 const EDGE_DIVIDERS: &[&str] = &[SIDEBAR_SCROLL_DIVIDER, HEADER_DIVIDER];
284 const DIVIDER_SEGMENT: &str = "divider";
285 const DIVIDER_THICKNESS: f32 = 1.;
286 const INSET_TOLERANCE: f32 = 1.;
287 const INSET_RULES: &[InsetRule] = &[
288 InsetRule {
289 panel: "settings/nav",
290 content: "settings/nav/about",
291 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
292 },
293 InsetRule {
294 panel: "settings/main",
295 content: "settings/main/header/close",
296 edges: &[Edge::Top, Edge::Right],
297 },
298 ];
299 const SCROLLED_INSET_RULE: InsetRule = InsetRule {
300 panel: SETTINGS_BODY,
301 content: SETTINGS_CONTENT,
302 edges: &[Edge::Left, Edge::Bottom],
303 };
304 const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
305 SettingsSection::Agents,
306 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
307 )];
308 const SETTINGS_SECTIONS: [SettingsSection; 9] = [
309 SettingsSection::General,
310 SettingsSection::Notifications,
311 SettingsSection::Appearance,
312 SettingsSection::Chats,
313 SettingsSection::Calls,
314 SettingsSection::Devices,
315 SettingsSection::Agents,
316 SettingsSection::Mcp,
317 SettingsSection::About,
318 ];
319 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
320 const TOLERANCE: f32 = 0.5;
321 const KNOWN_VIOLATIONS: &[&str] = &[];
322 const ZOOM_STEP: f32 = 1.25;
323
324 type Tag = (&'static str, Bounds<Pixels>);
325
326 #[derive(Clone, Copy, Debug)]
327 enum Edge {
328 Top,
329 Right,
330 Bottom,
331 Left,
332 }
333
334 struct InsetRule {
335 panel: &'static str,
336 content: &'static str,
337 edges: &'static [Edge],
338 }
339
340 fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {
341 f32::from(match edge {
342 Edge::Top => content.top() - panel.top(),
343 Edge::Right => panel.right() - content.right(),
344 Edge::Bottom => panel.bottom() - content.bottom(),
345 Edge::Left => content.left() - panel.left(),
346 })
347 }
348
349 fn inset_violation(
350 rule: &InsetRule,
351 panel: Bounds<Pixels>,
352 content: Bounds<Pixels>,
353 ) -> Option<(String, String)> {
354 let insets: Vec<(Edge, f32)> = rule
355 .edges
356 .iter()
357 .map(|edge| (*edge, inset(panel, content, *edge)))
358 .collect();
359 let values = insets.iter().map(|(_, value)| *value);
360 let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);
361 (spread > INSET_TOLERANCE).then(|| {
362 (
363 format!("{}:uneven-inset", rule.panel),
364 format!(
365 "{} insets {} by {insets:?}, they must match",
366 rule.panel, rule.content
367 ),
368 )
369 })
370 }
371
372 fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {
373 let bounds_of = |path: &str| {
374 tags.iter()
375 .find(|(tag, _)| *tag == path)
376 .map(|(_, bounds)| *bounds)
377 };
378 rules
379 .iter()
380 .filter_map(
381 |rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {
382 (Some(panel), Some(content)) => inset_violation(rule, panel, content),
383 _ => None,
384 },
385 )
386 .collect()
387 }
388
389 fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {
390 let mut found = Vec::new();
391 for (path, bounds) in tags {
392 let Some((parent, segment)) = path.rsplit_once('/') else {
393 continue;
394 };
395 if !segment.starts_with(DIVIDER_SEGMENT) {
396 continue;
397 }
398 let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {
399 found.push((
400 format!("{path}:no-panel"),
401 format!("{path} needs its panel {parent} tagged"),
402 ));
403 continue;
404 };
405 let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;
406 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
407 let spans = if thin(bounds.size.height) {
408 near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())
409 } else if thin(bounds.size.width) {
410 near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())
411 } else {
412 false
413 };
414 if !spans {
415 found.push((
416 format!("{path}:short-divider"),
417 format!(
418 "{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",
419 describe(*bounds),
420 describe(*panel)
421 ),
422 ));
423 }
424 }
425 found
426 }
427
428 enum Screen {
429 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
430 StatusMenu,
431 Call,
432 Prejoin,
433 CallTranscript,
434 CallPeople,
435 CallShare,
436 CallConsult,
437 }
438
439 fn parent_of(path: &str) -> Option<&str> {
440 path.rsplit_once('/').map(|(parent, _)| parent)
441 }
442
443 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
444 let tolerance = px(TOLERANCE);
445 inner.left() >= outer.left() - tolerance
446 && inner.top() >= outer.top() - tolerance
447 && inner.right() <= outer.right() + tolerance
448 && inner.bottom() <= outer.bottom() + tolerance
449 }
450
451 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
452 let tolerance = px(TOLERANCE);
453 first.left() < second.right() - tolerance
454 && second.left() < first.right() - tolerance
455 && first.top() < second.bottom() - tolerance
456 && second.top() < first.bottom() - tolerance
457 }
458
459 fn describe(bounds: Bounds<Pixels>) -> String {
460 format!(
461 "[{:.1},{:.1} {:.1}x{:.1}]",
462 f32::from(bounds.origin.x),
463 f32::from(bounds.origin.y),
464 f32::from(bounds.size.width),
465 f32::from(bounds.size.height)
466 )
467 }
468
469 fn violations(
470 tags: &[Tag],
471 window: Bounds<Pixels>,
472 expected: &[&str],
473 ) -> Vec<(String, String)> {
474 let mut found = Vec::new();
475 let bounds_of = |path: &str| {
476 tags.iter()
477 .find(|(tag, _)| *tag == path)
478 .map(|(_, bounds)| *bounds)
479 };
480 for path in expected {
481 if bounds_of(path).is_none() {
482 found.push((
483 format!("{path}:missing"),
484 format!("{path} was not rendered"),
485 ));
486 }
487 }
488 for (path, bounds) in tags {
489 if !contains(window, *bounds) {
490 found.push((
491 format!("{path}:outside-window"),
492 format!(
493 "{path} {} leaves the window {}",
494 describe(*bounds),
495 describe(window)
496 ),
497 ));
498 }
499 if let Some(parent) =
500 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
501 {
502 if !contains(parent.1, *bounds) {
503 found.push((
504 format!("{path}:outside-parent"),
505 format!(
506 "{path} {} leaves {} {}",
507 describe(*bounds),
508 parent.0,
509 describe(parent.1)
510 ),
511 ));
512 }
513 }
514 for (other, other_bounds) in tags {
515 let overlays = |first: &str, second: &str| {
516 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
517 };
518 let siblings = path < other
519 && parent_of(path).is_some()
520 && parent_of(path) == parent_of(other)
521 && !overlays(path, other)
522 && !overlays(other, path);
523 if siblings && overlaps(*bounds, *other_bounds) {
524 found.push((
525 format!("{path}:overlaps:{other}"),
526 format!(
527 "{path} {} overlaps {other} {}",
528 describe(*bounds),
529 describe(*other_bounds)
530 ),
531 ));
532 }
533 }
534 }
535 found.extend(divider_violations(tags));
536 found
537 }
538
539 const SETTLE_FRAMES: usize = 2;
540 const SETTLE_LIMIT: usize = 60;
541 const SETTLE_STEP: Duration = Duration::from_millis(50);
542
543 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
544 let mut frames = 0;
545 while frames < SETTLE_FRAMES
546 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
547 {
548 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
549 visual.executor().advance_clock(SETTLE_STEP);
550 std::thread::sleep(SETTLE_STEP);
551 visual.run_until_parked();
552 visual.update(|window, cx| window.render_frame(cx));
553 frames += 1;
554 }
555 GUARDED
556 .iter()
557 .chain(CALL_GUARDED)
558 .chain(CALLS_TAGS)
559 .chain(PREJOIN_TAGS)
560 .chain(SHARE_GUARDED)
561 .chain(CONSULT_GUARDED)
562 .chain([
563 &AGENTS_LIST,
564 &CALL_TRANSCRIPT,
565 &MENU,
566 &RECAP_TAB,
567 &RECAP_REGION,
568 &PEOPLE_PANEL,
569 ])
570 .chain(&AGENT_TAGS)
571 .chain(SETTINGS_TAGS)
572 .chain(MEMBERS_TAGS)
573 .chain(EDGE_DIVIDERS)
574 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
575 .collect()
576 }
577
578 fn sharing_call() -> ActiveCall {
579 let mut call = gallery_call();
580 call.model
581 .apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
582 call.share_stage.view.step_in((800., 450.));
583 call
584 }
585
586 fn gallery_call() -> ActiveCall {
587 let (handle, _control) = call_channel();
588 let mut model = CallModel::meeting("Standup", false);
589 model.apply(CallUpdate::State(CallState::Connected {
590 since: Instant::now(),
591 }));
592 model.apply(CallUpdate::Roster(
593 (0..11)
594 .map(|index| RosterEntry {
595 mri: format!("8:orgid:guard-{index}"),
596 display_name: format!("Guest {index}"),
597 muted: false,
598 in_lobby: false,
599 has_video: false,
600 sharing: false,
601 hand: None,
602 spotlight: None,
603 organizer: false,
604 ..Default::default()
605 })
606 .collect(),
607 ));
608 ActiveCall::new(1, model, handle.commands, None, handle.video)
609 }
610
611 fn consult_calls() -> (ActiveCall, ActiveCall) {
612 let connected = |id: u64, name: &str, mri: &str| {
613 let (handle, _control) = call_channel();
614 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
615 model.apply(CallUpdate::State(CallState::Connected {
616 since: Instant::now(),
617 }));
618 ActiveCall::new(id, model, handle.commands, None, handle.video)
619 };
620 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
621 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
622 consult.consult = Some(ConsultCall::new(
623 (
624 "8:orgid:guard-consult".to_owned(),
625 "Jonas Ortega".to_owned(),
626 ),
627 held.model.peer_name.clone(),
628 ));
629 (consult, held)
630 }
631
632 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
633 mount_with(cx, false)
634 }
635
636 fn mount_with(
637 cx: &mut TestAppContext,
638 agent_api: bool,
639 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
640 cx.update(gpui_kit::init);
641 cx.update(|cx| {
642 crate::theme::apply(cx);
643 bind_keys(cx);
644 let store = Store::open_in_memory().expect("in-memory store");
645 demo::seed(&store);
646 let store = Arc::new(store);
647 if agent_api {
648 crate::agent_api::init(store.clone(), true, cx);
649 }
650 let mode = Mode {
651 demo: true,
652 read_only: false,
653 demo_sync: None,
654 };
655 let state = cx.new(|_| AppState::new(store, mode));
656 install_globals(&state, UserInput::new(), cx);
657 crate::agents::install(state.clone(), cx);
658 demo::start_session(&state, cx);
659 let shared_state = state.clone();
660 let startup = Startup {
661 switcher_query: None,
662 composer_text: None,
663 reply_to_last: false,
664 };
665 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
666 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
667 })
668 .expect("open test window")
669 .0;
670 (window, shared_state)
671 })
672 }
673
674 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
675 Bounds {
676 origin: point(px(left), px(top)),
677 size: size(px(width), px(height)),
678 }
679 }
680
681 #[test]
682 fn rules_flag_overlap_and_overflow() {
683 let window = rectangle(0., 0., 100., 100.);
684 let tags: Vec<Tag> = vec![
685 ("shell", rectangle(0., 0., 100., 100.)),
686 ("shell/islands", rectangle(0., 0., 100., 50.)),
687 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
688 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
689 ];
690 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
691 .into_iter()
692 .map(|(key, _)| key)
693 .collect();
694 let line_tags: Vec<Tag> = vec![
695 ("panel", rectangle(0., 0., 100., 100.)),
696 ("panel/divider", rectangle(0., 50., 100., 1.)),
697 ("panel/divider-inset", rectangle(12., 60., 76., 1.)),
698 ("panel/divider-side", rectangle(40., 0., 1., 100.)),
699 ("panel/about", rectangle(12., 76., 76., 12.)),
700 ("panel/footer", rectangle(12., 64., 76., 12.)),
701 ];
702 let line_keys: Vec<String> = divider_violations(&line_tags)
703 .into_iter()
704 .chain(inset_violations(
705 &line_tags,
706 &[
707 InsetRule {
708 panel: "panel",
709 content: "panel/about",
710 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
711 },
712 InsetRule {
713 panel: "panel",
714 content: "panel/footer",
715 edges: &[Edge::Left, Edge::Bottom],
716 },
717 ],
718 ))
719 .map(|(key, _)| key)
720 .collect();
721 assert_eq!(
722 line_keys,
723 ["panel/divider-inset:short-divider", "panel:uneven-inset"]
724 );
725 assert_eq!(
726 keys,
727 [
728 "shell/status-bar:missing",
729 "shell/islands/rail:overlaps:shell/islands/sidebar",
730 "shell/islands/sidebar:outside-window",
731 "shell/islands/sidebar:outside-parent",
732 ]
733 );
734 }
735
736 #[gpui_kit::test]
737 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
738 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
739 }
740
741 #[gpui_kit::test]
742 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
743 let (width, height) = SIZES[1];
744 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
745 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
746 }
747
748 fn check_layout(
749 cx: &mut TestAppContext,
750 sizes: &[(f32, f32)],
751 zoom: f32,
752 known_violations: &[&str],
753 ) {
754 let (handle, app) = mount(cx);
755 let platform_scale = cx
756 .update_window(handle, |_, window, _| window.scale_factor())
757 .expect("test window");
758 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
759 let mut visual = VisualTestContext::from_window(handle, cx);
760 let mut seen_known = HashSet::new();
761 let mut unexpected = Vec::new();
762 for &(width, height) in sizes {
763 visual.simulate_resize(size(px(width), px(height)));
764 let window = Bounds {
765 origin: point(px(0.), px(0.)),
766 size: size(px(width), px(height)),
767 };
768 let screens = [
769 Screen::Tab("chats", None),
770 Screen::Tab(
771 "activity",
772 Some(|visual| visual.dispatch_action(OpenActivity)),
773 ),
774 Screen::Tab(
775 "channels",
776 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
777 ),
778 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
779 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
780 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
781 Screen::Prejoin,
782 Screen::StatusMenu,
783 Screen::Call,
784 Screen::CallTranscript,
785 Screen::CallPeople,
786 Screen::CallShare,
787 Screen::CallConsult,
788 ];
789 for screen in screens {
790 let (screen_name, status_menu) = match screen {
791 Screen::Tab(name, open) => {
792 if let Some(open) = open {
793 open(&mut visual);
794 }
795 (name, false)
796 }
797 Screen::Call | Screen::CallPeople => {
798 let people_open = matches!(screen, Screen::CallPeople);
799 visual.update(|_, cx| {
800 app.update(cx, |state, cx| {
801 let mut call = gallery_call();
802 call.people_open = people_open;
803 state.call = Some(call);
804 cx.notify();
805 })
806 });
807 (if people_open { "call-people" } else { "call" }, false)
808 }
809 Screen::Prejoin => {
810 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
811 visual.update(|_, cx| {
812 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
813 });
814 ("prejoin", false)
815 }
816 Screen::CallTranscript => {
817 visual.update(|window, cx| {
818 app.update(cx, |state, cx| {
819 let mut call = gallery_call();
820 call.model.apply(CallUpdate::Captions(CaptionState::On));
821 for index in 0..40 {
822 call.model.note_caption(
823 CaptionEntry {
824 id: format!("guard-{index}"),
825 user_id: "8:orgid:guard-0".into(),
826 display_name: "Guest 0".into(),
827 text: "A long guarded sentence that has to wrap inside the panel".into(),
828 is_final: true,
829 },
830 Instant::now(),
831 );
832 }
833 call.transcript_open = true;
834 state.call = Some(call);
835 let app_entity = cx.entity();
836 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
837 cx.notify();
838 })
839 });
840 ("call-transcript", false)
841 }
842 Screen::CallShare => {
843 visual.update(|_, cx| {
844 app.update(cx, |state, cx| {
845 state.call = Some(sharing_call());
846 cx.notify();
847 })
848 });
849 ("call-share", false)
850 }
851 Screen::CallConsult => {
852 visual.update(|_, cx| {
853 app.update(cx, |state, cx| {
854 let (consult, held) = consult_calls();
855 state.call = Some(consult);
856 state.held_call = Some(held);
857 cx.notify();
858 })
859 });
860 ("call-consult", false)
861 }
862 Screen::StatusMenu => {
863 let tags = collect(&mut visual, None);
864 let button = tags
865 .iter()
866 .find(|(path, _)| *path == OWN_STATUS)
867 .map(|(_, bounds)| *bounds)
868 .expect("own status button rendered");
869 visual.simulate_click(button.center(), Default::default());
870 ("status-menu", true)
871 }
872 };
873 let is_call = matches!(
874 screen_name,
875 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
876 );
877 let tags = collect(&mut visual, status_menu.then_some(MENU));
878 let mut expected = GUARDED.to_vec();
879 if is_call {
880 expected.extend(CALL_GUARDED);
881 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
882 if sidebar_hidden_in_call(width, panel_open) {
883 expected.retain(|path| *path != "shell/islands/sidebar");
884 }
885 }
886 if screen_name == "call-transcript" {
887 expected.push(CALL_TRANSCRIPT);
888 }
889 if screen_name == "call-people" {
890 expected.push(PEOPLE_PANEL);
891 }
892 if screen_name == "call-share" {
893 expected.extend(SHARE_GUARDED);
894 }
895 if screen_name == "call-consult" {
896 expected.extend(CONSULT_GUARDED);
897 }
898 if status_menu {
899 expected.push(MENU);
900 }
901 match screen_name {
902 "calls" => expected.extend(CALLS_TAGS),
903 "agents" => expected.push(AGENTS_LIST),
904 "prejoin" => expected.extend(PREJOIN_TAGS),
905 _ => {}
906 }
907 let mut found = violations(&tags, window, &expected);
908 if status_menu {
909 let menu = tags
910 .iter()
911 .find(|(path, _)| *path == MENU)
912 .map(|(_, bounds)| *bounds);
913 let button = tags
914 .iter()
915 .find(|(path, _)| *path == OWN_STATUS)
916 .map(|(_, bounds)| *bounds);
917 if let (Some(menu), Some(button)) = (menu, button) {
918 if overlaps(menu, button) {
919 found.push((
920 format!("{MENU}:covers:{OWN_STATUS}"),
921 format!(
922 "{MENU} {} covers {OWN_STATUS} {}",
923 describe(menu),
924 describe(button)
925 ),
926 ));
927 }
928 }
929 visual.simulate_keystrokes("escape");
930 visual.run_until_parked();
931 }
932 if is_call {
933 visual.update(|_, cx| {
934 app.update(cx, |state, cx| {
935 state.call = None;
936 state.held_call = None;
937 cx.notify();
938 })
939 });
940 }
941 if screen_name == "prejoin" {
942 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
943 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
944 }
945 for (key, message) in found {
946 let full_key = format!("{screen_name}@{width}x{height}:{key}");
947 if known_violations.contains(&full_key.as_str()) {
948 seen_known.insert(full_key);
949 } else {
950 unexpected.push(format!("{full_key}: {message}"));
951 }
952 }
953 }
954 }
955 let stale: Vec<String> = known_violations
956 .iter()
957 .filter(|key| !seen_known.contains(**key))
958 .map(|key| format!("stale known violation, remove it: {key}"))
959 .collect();
960 assert!(
961 unexpected.is_empty() && stale.is_empty(),
962 "{}",
963 unexpected
964 .into_iter()
965 .chain(stale)
966 .collect::<Vec<_>>()
967 .join("\n")
968 );
969 }
970 #[gpui_kit::test]
971 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
972 let (handle, _) = mount(cx);
973 let mut visual = VisualTestContext::from_window(handle, cx);
974 visual.simulate_resize(size(px(1280.), px(800.)));
975 collect(&mut visual, Some(OWN_AVATAR_DISC));
976 let disc = visual
977 .debug_bounds(OWN_AVATAR_DISC)
978 .expect("own avatar rendered");
979 let bar = visual
980 .debug_bounds("shell/title-bar")
981 .expect("title bar rendered");
982 assert_eq!(
983 f32::from(disc.size.width),
984 TITLE_AVATAR_SIZE,
985 "{}",
986 describe(disc)
987 );
988 assert_eq!(
989 f32::from(disc.size.height),
990 TITLE_AVATAR_SIZE,
991 "{}",
992 describe(disc)
993 );
994 let top = f32::from(disc.top() - bar.top());
995 let bottom = f32::from(bar.bottom() - disc.bottom());
996 assert!(
997 (top - bottom).abs() <= 1.,
998 "own avatar {} is not centered in the title bar {}",
999 describe(disc),
1000 describe(bar)
1001 );
1002 }
1003
1004 const TITLE_SEARCH: &str = "shell/title-bar/search";
1005 const TITLE_NEIGHBOURS: &[&str] = &[
1006 "shell/title-bar/leading",
1007 "shell/title-bar/mode-pill",
1008 "shell/title-bar/trailing",
1009 "shell/title-bar/update",
1010 OWN_STATUS,
1011 ];
1012 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
1013 (1920., 1080., true),
1014 (1280., 800., true),
1015 (640., 480., false),
1016 ];
1017
1018 #[gpui_kit::test]
1019 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
1020 let (handle, _) = mount(cx);
1021 let mut visual = VisualTestContext::from_window(handle, cx);
1022 let shell = visual.update(|window, cx| {
1023 window
1024 .root::<gpui_kit::base::Root>()
1025 .flatten()
1026 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
1027 .expect("app shell is the root view")
1028 });
1029 visual.update(|_, cx| {
1030 shell.update(cx, |shell, cx| {
1031 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
1032 })
1033 });
1034 let mut found = Vec::new();
1035 for (width, height, centered) in TITLE_SEARCH_SIZES {
1036 visual.simulate_resize(size(px(width), px(height)));
1037 collect(&mut visual, Some(TITLE_SEARCH));
1038 let search = visual
1039 .debug_bounds(TITLE_SEARCH)
1040 .expect("title search rendered");
1041 let search_center = f32::from(search.center().x);
1042 eprintln!(
1043 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
1044 describe(search),
1045 width / 2.
1046 );
1047 if centered && (search_center - width / 2.).abs() > 1. {
1048 found.push(format!(
1049 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
1050 width / 2.
1051 ));
1052 }
1053 if !contains(rectangle(0., 0., width, height), search) {
1054 found.push(format!(
1055 "@{width}x{height}: search {} leaves the window",
1056 describe(search)
1057 ));
1058 }
1059 for neighbour in TITLE_NEIGHBOURS {
1060 match visual.debug_bounds(neighbour) {
1061 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
1062 Some(bounds) if overlaps(search, bounds) => found.push(format!(
1063 "@{width}x{height}: search {} overlaps {neighbour} {}",
1064 describe(search),
1065 describe(bounds)
1066 )),
1067 Some(_) => {}
1068 }
1069 }
1070 }
1071 assert!(found.is_empty(), "{}", found.join("\n"));
1072 }
1073
1074 #[gpui_kit::test]
1075 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
1076 let (handle, app) = mount(cx);
1077 let mut visual = VisualTestContext::from_window(handle, cx);
1078 for (width, height) in SIZES {
1079 visual.simulate_resize(size(px(width), px(height)));
1080 visual.update(|_, cx| {
1081 app.update(cx, |state, cx| {
1082 let mut call = gallery_call();
1083 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
1084 call.chat_open = true;
1085 state.call = Some(call);
1086 cx.notify();
1087 })
1088 });
1089 collect(&mut visual, Some(CHAT_PANEL_TAG));
1090 let panel = visual
1091 .debug_bounds(CHAT_PANEL_TAG)
1092 .expect("chat panel rendered");
1093 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
1094 .iter()
1095 .enumerate()
1096 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
1097 .collect();
1098 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
1099 let found: Vec<String> = bubbles
1100 .into_iter()
1101 .filter(|(_, bounds)| {
1102 !inside_horizontally(panel, *bounds) || !overlaps(panel, *bounds)
1103 })
1104 .map(|(index, bounds)| {
1105 format!(
1106 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
1107 describe(bounds),
1108 describe(panel)
1109 )
1110 })
1111 .collect();
1112 visual.update(|_, cx| {
1113 app.update(cx, |state, cx| {
1114 state.call = None;
1115 cx.notify();
1116 })
1117 });
1118 assert!(found.is_empty(), "{}", found.join("\n"));
1119 }
1120 }
1121
1122 fn inside_horizontally(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
1123 let tolerance = px(TOLERANCE);
1124 inner.left() >= outer.left() - tolerance && inner.right() <= outer.right() + tolerance
1125 }
1126
1127 fn scroll_sidebar(visual: &mut VisualTestContext, delta: f32) {
1128 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1129 visual.simulate_event(ScrollWheelEvent {
1130 position: sidebar.center(),
1131 delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1132 ..Default::default()
1133 });
1134 }
1135
1136 #[gpui_kit::test]
1137 fn chat_list_line_shows_only_while_scrolled(cx: &mut TestAppContext) {
1138 let (handle, _) = mount(cx);
1139 let mut visual = VisualTestContext::from_window(handle, cx);
1140 for (width, height) in SIZES {
1141 visual.simulate_resize(size(px(width), px(height)));
1142 let window = Bounds {
1143 origin: point(px(0.), px(0.)),
1144 size: size(px(width), px(height)),
1145 };
1146 collect(&mut visual, None);
1147 scroll_sidebar(&mut visual, 100_000.);
1148 let tags = collect(&mut visual, None);
1149 assert!(
1150 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1151 "chat list at its top must not show the line at {width}x{height}"
1152 );
1153 scroll_sidebar(&mut visual, -120.);
1154 let scrolled = collect(&mut visual, Some(SIDEBAR_SCROLL_DIVIDER));
1155 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1156 let line = visual
1157 .debug_bounds(SIDEBAR_SCROLL_DIVIDER)
1158 .expect("scrolled chat list shows the line");
1159 assert!(
1160 line.top() > sidebar.top() + px(TOLERANCE),
1161 "the line sits under the Chats header, not on the island edge: {} in {}",
1162 describe(line),
1163 describe(sidebar)
1164 );
1165 let found: Vec<String> = violations(&scrolled, window, &[SIDEBAR_SCROLL_DIVIDER])
1166 .into_iter()
1167 .chain(violations(&tags, window, &[]))
1168 .map(|(key, message)| format!("chat-list@{width}x{height}:{key}: {message}"))
1169 .collect();
1170 assert!(found.is_empty(), "{}", found.join("\n"));
1171 scroll_sidebar(&mut visual, 100_000.);
1172 collect(&mut visual, None);
1173 assert!(
1174 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1175 "the line goes away once the chat list is back at its top"
1176 );
1177 }
1178 }
1179
1180 #[gpui_kit::test]
1181 fn header_tabs_sit_above_the_header_line(cx: &mut TestAppContext) {
1182 let (handle, state) = mount(cx);
1183 let mut visual = VisualTestContext::from_window(handle, cx);
1184 for (width, height) in SIZES {
1185 visual.simulate_resize(size(px(width), px(height)));
1186 let window = Bounds {
1187 origin: point(px(0.), px(0.)),
1188 size: size(px(width), px(height)),
1189 };
1190 visual.update(|_, cx| {
1191 state.update(cx, |state, cx| {
1192 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1193 })
1194 });
1195 let tags = collect(&mut visual, Some(RECAP_TAB));
1196 let main = visual.debug_bounds(MAIN).expect("main island rendered");
1197 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1198 let line = visual
1199 .debug_bounds(HEADER_DIVIDER)
1200 .expect("the header line is always shown");
1201 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
1202 assert!(
1203 tab.top() >= main.top() && near(tab.bottom(), line.top()),
1204 "tab {} must sit in the top bar above the line {}",
1205 describe(tab),
1206 describe(line)
1207 );
1208 let found: Vec<String> = violations(&tags, window, &[HEADER_DIVIDER, RECAP_TAB])
1209 .into_iter()
1210 .map(|(key, message)| format!("header@{width}x{height}:{key}: {message}"))
1211 .collect();
1212 assert!(found.is_empty(), "{}", found.join("\n"));
1213 }
1214 }
1215
1216 #[gpui_kit::test]
1217 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1218 let (handle, state) = mount(cx);
1219 let mut visual = VisualTestContext::from_window(handle, cx);
1220 for (width, height) in SIZES {
1221 visual.simulate_resize(size(px(width), px(height)));
1222 let window = Bounds {
1223 origin: point(px(0.), px(0.)),
1224 size: size(px(width), px(height)),
1225 };
1226 visual.update(|_, cx| {
1227 state.update(cx, |state, cx| {
1228 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1229 })
1230 });
1231 collect(&mut visual, Some(RECAP_TAB));
1232 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1233 visual.simulate_click(tab.center(), Default::default());
1234 let tags = collect(&mut visual, Some(RECAP_REGION));
1235 let mut expected = GUARDED.to_vec();
1236 expected.extend([RECAP_TAB, RECAP_REGION]);
1237 let found: Vec<String> = violations(&tags, window, &expected)
1238 .into_iter()
1239 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1240 .collect();
1241 assert!(found.is_empty(), "{}", found.join("\n"));
1242 }
1243 }
1244
1245 #[gpui_kit::test]
1246 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1247 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1248 }
1249
1250 #[gpui_kit::test]
1251 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1252 crate::theme::set_thread_scheme(Some("teams"));
1253 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1254 crate::theme::set_thread_scheme(None);
1255 }
1256
1257 #[gpui_kit::test]
1258 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1259 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1260 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1261 crate::theme::set_thread_shade(None);
1262 }
1263
1264 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1265 let (handle, state) = mount_with(cx, true);
1266 let mut visual = VisualTestContext::from_window(handle, cx);
1267 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1268 visual.simulate_resize(size(px(width), px(height)));
1269 let window = Bounds {
1270 origin: point(px(0.), px(0.)),
1271 size: size(px(width), px(height)),
1272 };
1273 let inset = metrics(width, height).inset;
1274 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1275 for &section in sections {
1276 visual
1277 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1278 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1279 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1280 .into_iter()
1281 .filter(|(key, _)| key.starts_with("settings"))
1282 .chain(inset_violations(&tags, INSET_RULES))
1283 .collect();
1284 if label_sizes {
1285 found.extend(nav_label_violations(&mut visual));
1286 }
1287 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1288 .iter()
1289 .any(|(exempt, _)| *exempt == section);
1290 if !scrolled_exempt {
1291 found.extend(scrolled_inset_violation(&mut visual));
1292 }
1293 let found: Vec<String> = found
1294 .into_iter()
1295 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1296 .collect();
1297 assert!(found.is_empty(), "{}", found.join("\n"));
1298 let dialog = visual
1299 .debug_bounds(SETTINGS_TAGS[0])
1300 .expect("settings dialog");
1301 let edges = [
1302 f32::from(dialog.left()),
1303 f32::from(dialog.top()),
1304 width - f32::from(dialog.right()),
1305 height - f32::from(dialog.bottom()),
1306 ];
1307 assert!(
1308 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1309 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1310 );
1311 }
1312 }
1313 }
1314
1315 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1316
1317 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1318 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1319 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1320 };
1321 let mut found = Vec::new();
1322 for section in SETTINGS_SECTIONS {
1323 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1324 let item_path: &'static str = if section == SettingsSection::About {
1325 SETTINGS_NAV_ABOUT
1326 } else {
1327 Box::leak(item_selector(section).into_boxed_str())
1328 };
1329 let (Some(label_bounds), Some(item)) = (
1330 visual.debug_bounds(label_path),
1331 visual.debug_bounds(item_path),
1332 ) else {
1333 if section != SettingsSection::Agents {
1334 found.push((label_path.to_owned(), "not rendered".to_owned()));
1335 }
1336 continue;
1337 };
1338 let text = label(section);
1339 let text_width = visual.update(|window, _| {
1340 let run = window.text_style().to_run(text.len());
1341 f32::from(
1342 window
1343 .text_system()
1344 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1345 .width,
1346 )
1347 });
1348 let label_width = f32::from(label_bounds.size.width);
1349 let label_height = f32::from(label_bounds.size.height);
1350 if text_width > label_width + TOLERANCE
1351 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1352 {
1353 found.push((
1354 label_path.to_owned(),
1355 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1356 ));
1357 }
1358 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1359 inner.left() < outer.left() - px(TOLERANCE)
1360 || inner.right() > outer.right() + px(TOLERANCE)
1361 || inner.top() < outer.top() - px(TOLERANCE)
1362 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1363 };
1364 if outside(label_bounds, item) {
1365 found.push((
1366 label_path.to_owned(),
1367 format!("label {label_bounds:?} outside item {item:?}"),
1368 ));
1369 }
1370 if item.left() < nav.left() || item.right() > nav.right() {
1371 found.push((
1372 item_path.to_owned(),
1373 format!("item {item:?} outside nav {nav:?}"),
1374 ));
1375 }
1376 }
1377 found
1378 }
1379
1380 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1381 let body = visual.debug_bounds(SETTINGS_BODY)?;
1382 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1383 if content.bottom() <= body.bottom() {
1384 return None;
1385 }
1386 visual.simulate_event(ScrollWheelEvent {
1387 position: body.center(),
1388 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1389 ..Default::default()
1390 });
1391 collect(visual, None);
1392 let body = visual.debug_bounds(SETTINGS_BODY)?;
1393 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1394 inset_violation(&SCROLLED_INSET_RULE, body, content)
1395 }
1396
1397 #[gpui_kit::test]
1398 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1399 let (handle, state) = mount(cx);
1400 let mut visual = VisualTestContext::from_window(handle, cx);
1401 for (width, height) in SIZES {
1402 visual.simulate_resize(size(px(width), px(height)));
1403 let window = Bounds {
1404 origin: point(px(0.), px(0.)),
1405 size: size(px(width), px(height)),
1406 };
1407 visual.update(|_, cx| {
1408 state.update(cx, |state, cx| {
1409 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1410 })
1411 });
1412 collect(&mut visual, Some(MEMBERS_BUTTON));
1413 let button = visual
1414 .debug_bounds(MEMBERS_BUTTON)
1415 .expect("members button rendered");
1416 visual.simulate_click(button.center(), Default::default());
1417 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1418 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1419 .into_iter()
1420 .filter(|(key, _)| key.starts_with("chat-members"))
1421 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1422 .collect();
1423 visual.simulate_keystrokes("escape");
1424 visual.run_until_parked();
1425 assert!(found.is_empty(), "{}", found.join("\n"));
1426 }
1427 }
1428
1429 const PINNED_CHAT: &str = "demo-chat-release";
1430 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1431
1432 #[gpui_kit::test]
1433 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
1434 let (handle, state) = mount(cx);
1435 let mut visual = VisualTestContext::from_window(handle, cx);
1436 let mut found = Vec::new();
1437 for (width, height) in SIZES {
1438 visual.simulate_resize(size(px(width), px(height)));
1439 visual.update(|_, cx| {
1440 state.update(cx, |state, cx| {
1441 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1442 })
1443 });
1444 collect(&mut visual, Some(PIN_BANNER_TAG));
1445 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1446 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1447 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1448 let gaps = [
1449 ("top", f32::from(banner.top() - timeline.top())),
1450 ("left", f32::from(banner.left() - timeline.left())),
1451 ("right", f32::from(timeline.right() - banner.right())),
1452 ("below divider", f32::from(banner.top() - divider.bottom())),
1453 ];
1454 let side = gaps[1].1;
1455 if gaps
1456 .iter()
1457 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1458 {
1459 found.push(format!(
1460 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1461 ));
1462 }
1463 }
1464 assert!(found.is_empty(), "{}", found.join("\n"));
1465 }
1466
1467 #[gpui_kit::test]
1468 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1469 let (handle, state) = mount(cx);
1470 let mut visual = VisualTestContext::from_window(handle, cx);
1471 visual.simulate_resize(size(px(1280.), px(800.)));
1472 visual.update(|_, cx| {
1473 state.update(cx, |state, cx| {
1474 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1475 })
1476 });
1477 collect(&mut visual, Some(TIMELINE_TAG));
1478 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1479 }
1480
1481 #[gpui_kit::test]
1482 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1483 let (handle, state) = mount(cx);
1484 let mut visual = VisualTestContext::from_window(handle, cx);
1485 visual.simulate_resize(size(px(1280.), px(800.)));
1486 visual.update(|_, cx| {
1487 state.update(cx, |state, cx| {
1488 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1489 })
1490 });
1491 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1492 let button = visual
1493 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1494 .expect("channel details button");
1495 visual.simulate_click(button.center(), Default::default());
1496 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1497 let pane = visual
1498 .debug_bounds(CHANNEL_DETAILS_TAG)
1499 .expect("details pane");
1500 let main = visual.debug_bounds(MAIN).expect("main island");
1501 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1502 assert!(
1503 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1504 "pane {pane:?} must end at the main island edge {main:?}"
1505 );
1506 assert!(
1507 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1508 "pane {pane:?} must start under the header divider {divider:?}"
1509 );
1510 }
1511
1512 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1513 collect(visual, Some(COMPOSER_SEND_TAG));
1514 let mut bounds_of = |path: &'static str| {
1515 visual
1516 .debug_bounds(path)
1517 .unwrap_or_else(|| panic!("{path} rendered"))
1518 };
1519 let composer = bounds_of(COMPOSER_BOX_TAG);
1520 let leading = bounds_of(COMPOSER_LEADING_TAG);
1521 let send = bounds_of(COMPOSER_SEND_TAG);
1522 [
1523 f32::from(leading.left() - composer.left()),
1524 f32::from(leading.top() - composer.top()),
1525 f32::from(composer.bottom() - leading.bottom()),
1526 f32::from(composer.right() - send.right()),
1527 f32::from(send.top() - composer.top()),
1528 f32::from(composer.bottom() - send.bottom()),
1529 ]
1530 }
1531
1532 #[gpui_kit::test]
1533 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
1534 let (handle, _) = mount(cx);
1535 let mut visual = VisualTestContext::from_window(handle, cx);
1536 visual.simulate_resize(size(px(1280.), px(800.)));
1537 let single_line = composer_button_insets(&mut visual);
1538 let left = single_line[0];
1539 assert!(
1540 single_line
1541 .iter()
1542 .all(|inset| (inset - left).abs() < TOLERANCE),
1543 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
1544 );
1545 let leading = visual
1546 .debug_bounds(COMPOSER_LEADING_TAG)
1547 .expect("leading buttons");
1548 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
1549 visual.simulate_click(
1550 point((leading.right() + send.left()) / 2., send.center().y),
1551 Default::default(),
1552 );
1553 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
1554 let three_lines = composer_button_insets(&mut visual);
1555 assert!(
1556 three_lines[1] > single_line[1] + 30.,
1557 "three lines did not grow the composer: {three_lines:?}"
1558 );
1559 for inset in [
1560 three_lines[0],
1561 three_lines[2],
1562 three_lines[3],
1563 three_lines[5],
1564 ] {
1565 assert!(
1566 (inset - left).abs() < TOLERANCE,
1567 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
1568 );
1569 }
1570 }
1571
1572 #[gpui_kit::test]
1573 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
1574 const FORMAT_TAGS: [&str; 6] = [
1575 COMPOSER_BOX_TAG,
1576 COMPOSER_FORMAT_BAR_TAG,
1577 COMPOSER_FORMAT_DIVIDER_TAG,
1578 COMPOSER_LEADING_TAG,
1579 COMPOSER_FORMAT_TAG,
1580 COMPOSER_SEND_TAG,
1581 ];
1582 let (handle, _) = mount(cx);
1583 let mut visual = VisualTestContext::from_window(handle, cx);
1584 for (width, height) in SIZES {
1585 visual.simulate_resize(size(px(width), px(height)));
1586 let window = Bounds {
1587 origin: point(px(0.), px(0.)),
1588 size: size(px(width), px(height)),
1589 };
1590 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
1591 let toggle = visual
1592 .debug_bounds(COMPOSER_FORMAT_TAG)
1593 .expect("format button");
1594 visual.simulate_click(toggle.center(), Default::default());
1595 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
1596 let tags: Vec<Tag> = FORMAT_TAGS
1597 .iter()
1598 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1599 .collect();
1600 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
1601 .into_iter()
1602 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
1603 .collect();
1604 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
1605 let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");
1606 let toggle = visual
1607 .debug_bounds(COMPOSER_FORMAT_TAG)
1608 .expect("format button");
1609 visual.simulate_click(toggle.center(), Default::default());
1610 collect(&mut visual, None);
1611 assert!(found.is_empty(), "{}", found.join("\n"));
1612 assert!(
1613 bar.bottom() <= leading.top(),
1614 "bar {bar:?} over the buttons {leading:?}"
1615 );
1616 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
1617 }
1618 }
1619
1620 #[gpui_kit::test]
1621 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1622 let (handle, state) = mount_with(cx, true);
1623 let mut visual = VisualTestContext::from_window(handle, cx);
1624 for (width, height) in SIZES {
1625 visual.simulate_resize(size(px(width), px(height)));
1626 let window = Bounds {
1627 origin: point(px(0.), px(0.)),
1628 size: size(px(width), px(height)),
1629 };
1630 for (chat, expected_tags) in [
1631 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
1632 (REACTION_CHAT, &AGENT_TAGS[3..]),
1633 ] {
1634 visual.update(|_, cx| {
1635 state.update(cx, |state, cx| {
1636 state.select(Selection::Chat(chat.to_owned()), cx)
1637 })
1638 });
1639 let tags = collect(&mut visual, Some(expected_tags[0]));
1640 let mut expected = GUARDED.to_vec();
1641 expected.extend(expected_tags);
1642 let found: Vec<String> = violations(&tags, window, &expected)
1643 .into_iter()
1644 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
1645 .collect();
1646 assert!(found.is_empty(), "{}", found.join("\n"));
1647 }
1648 }
1649 }
1650}
1651
1652#[test]
1653fn lines_are_solid() {
1654 let mut files = Vec::new();
1655 for root in source_roots() {
1656 source_files(&root, &mut files);
1657 }
1658 let violations: Vec<String> = files
1659 .iter()
1660 .filter(|file| !file.ends_with("layout_guard.rs"))
1661 .flat_map(|file| {
1662 let source = fs::read_to_string(file).expect("read source file");
1663 source
1664 .lines()
1665 .enumerate()
1666 .filter(|(_, line)| {
1667 line.contains(".border_dashed(") || line.contains(".border_dotted(")
1668 })
1669 .map(|(index, line)| {
1670 format!(
1671 "{}:{}: lines are always solid: {}",
1672 file.display(),
1673 index + 1,
1674 line.trim()
1675 )
1676 })
1677 .collect::<Vec<_>>()
1678 })
1679 .collect();
1680 assert!(violations.is_empty(), "{}", violations.join("\n"));
1681}
1682
1683const STATE_RING_COLORS: &[&str] = &[
1684 "if focused",
1685 "if selected",
1686 "if speaking",
1687 "if current",
1688 "if open",
1689 "if state.failed",
1690];
1691const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
1692 (
1693 "notify/ring_view.rs",
1694 "theme::green()",
1695 "state signal (pulsing ring around the caller while it rings), not a resting outline",
1696 ),
1697 (
1698 "notify/meeting_view.rs",
1699 "theme::border_strong()",
1700 "outlined button, not a surface",
1701 ),
1702 (
1703 "settings/mcp.rs",
1704 "theme::border_strong()",
1705 "outlined button, not a surface",
1706 ),
1707 (
1708 "settings/rows.rs",
1709 "theme::border_strong()",
1710 "outlined button, not a surface",
1711 ),
1712 (
1713 "views/card_widgets.rs",
1714 "border)",
1715 "message content drawn as Teams renders it",
1716 ),
1717 (
1718 "views/card_widgets.rs",
1719 "theme::border_strong()",
1720 "message content drawn as Teams renders it",
1721 ),
1722 ("views/shared_tab.rs", "theme::accent()", "input field"),
1723 ("views/card_input.rs", "if error.is_some()", "input field"),
1724 ("views/format_toolbar.rs", "if refused", "input field"),
1725 (
1726 "views/card_code_block.rs",
1727 "theme::code_header_border()",
1728 "message content drawn as Teams renders it",
1729 ),
1730 ("views/call_transcript.rs", "theme::border()", "input field"),
1731 (
1732 "views/conversation.rs",
1733 "theme::accent()",
1734 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1735 ),
1736 (
1737 "views/attachment_tray.rs",
1738 "theme::accent()",
1739 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1740 ),
1741 (
1742 "views/card_carousel.rs",
1743 "theme::border_strong()",
1744 "message content drawn as Teams renders it",
1745 ),
1746 (
1747 "views/card_table.rs",
1748 "grid_color",
1749 "message content drawn as Teams renders it",
1750 ),
1751 (
1752 "views/activity_panel.rs",
1753 "theme::surface()",
1754 "cutout ring in the background color, invisible against its surface",
1755 ),
1756 (
1757 "views/avatar.rs",
1758 "theme::surface()",
1759 "cutout ring in the background color, invisible against its surface",
1760 ),
1761 (
1762 "views/avatar.rs",
1763 "theme::text_muted()",
1764 "offline presence glyph, Teams icon",
1765 ),
1766 (
1767 "views/message_row.rs",
1768 "theme::border_strong()",
1769 "deleted message placeholder, Teams look",
1770 ),
1771 (
1772 "views/message_row.rs",
1773 "theme::red()",
1774 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1775 ),
1776 (
1777 "views/message_row.rs",
1778 "if row.delivery",
1779 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1780 ),
1781 (
1782 "views/new_meeting_dialog.rs",
1783 "theme::border()",
1784 "input field",
1785 ),
1786 (
1787 "views/call_mini_window.rs",
1788 "theme::border_strong()",
1789 "self view over live video, needs an edge on any picture",
1790 ),
1791 ("views/transfer_picker.rs", "theme::border()", "input field"),
1792 (
1793 "views/call_notice.rs",
1794 "theme::border_strong()",
1795 "outlined button, not a surface",
1796 ),
1797 (
1798 "views/composer/schedule.rs",
1799 "theme::accent()",
1800 "input field",
1801 ),
1802 (
1803 "views/call_mini.rs",
1804 "border)",
1805 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1806 ),
1807 (
1808 "views/sidebar.rs",
1809 "theme::accent()",
1810 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1811 ),
1812 (
1813 "views/adaptive_card.rs",
1814 "theme::border()",
1815 "message content drawn as Teams renders it",
1816 ),
1817 (
1818 "views/adaptive_card.rs",
1819 "border)",
1820 "message content drawn as Teams renders it",
1821 ),
1822 (
1823 "views/share_bar.rs",
1824 "theme::red()",
1825 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1826 ),
1827 ("settings_controls.rs", "if invalid", "input field"),
1828];
1829
1830fn outlines(source: &str) -> Vec<(usize, String)> {
1831 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
1832 pattern
1833 .find_iter(source)
1834 .map(|found| {
1835 let line_number = source[..found.start()].matches('\n').count() + 1;
1836 let after = &source[found.end()..];
1837 let color = after
1838 .find(".border_color(")
1839 .filter(|position| *position < 120)
1840 .map(|position| {
1841 let start = &after[position + ".border_color(".len()..];
1842 start
1843 .lines()
1844 .map(str::trim)
1845 .find(|line| !line.is_empty())
1846 .unwrap_or_default()
1847 .to_owned()
1848 })
1849 .unwrap_or_default();
1850 (line_number, color)
1851 })
1852 .collect()
1853}
1854
1855#[test]
1856fn outline_matcher_reads_the_border_color() {
1857 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
1858 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
1859}
1860
1861#[test]
1862fn surfaces_are_soft() {
1863 let mut matched_allowlist = HashSet::new();
1864 let mut violations = Vec::new();
1865 for root in source_roots() {
1866 let mut files = Vec::new();
1867 source_files(&root, &mut files);
1868 for file in files {
1869 let relative = file
1870 .strip_prefix(&root)
1871 .expect("inside src")
1872 .to_string_lossy()
1873 .replace('\\', "/");
1874 if relative == "layout_guard.rs" {
1875 continue;
1876 }
1877 let source = fs::read_to_string(&file).expect("read source file");
1878 for (line_number, color) in outlines(&source) {
1879 if STATE_RING_COLORS
1880 .iter()
1881 .any(|prefix| color.starts_with(prefix))
1882 {
1883 continue;
1884 }
1885 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
1886 *allowed_file == relative && color.starts_with(prefix)
1887 }) {
1888 Some(position) => {
1889 matched_allowlist.insert(position);
1890 }
1891 None => violations.push(format!(
1892 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
1893 )),
1894 }
1895 }
1896 }
1897 }
1898 let stale = OUTLINE_ALLOWLIST
1899 .iter()
1900 .enumerate()
1901 .filter(|(position, _)| !matched_allowlist.contains(position))
1902 .map(|(_, (file, prefix, _))| {
1903 format!("stale outline allowlist entry, remove it: {file} {prefix}")
1904 });
1905 let report: Vec<String> = violations.into_iter().chain(stale).collect();
1906 assert!(report.is_empty(), "{}", report.join("\n"));
1907}
1908
1909fn indentation(line: &str) -> usize {
1910 line.len() - line.trim_start().len()
1911}
1912
1913fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
1914 let indent = indentation(lines[index]);
1915 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
1916 let start = lines[..index]
1917 .iter()
1918 .rposition(|line| !belongs(line))
1919 .map_or(0, |position| position + 1);
1920 let end = lines[index..]
1921 .iter()
1922 .position(|line| !belongs(line))
1923 .map_or(lines.len(), |position| index + position);
1924 lines[start..end]
1925 .iter()
1926 .filter(|line| indentation(line) == indent)
1927 .copied()
1928 .collect()
1929}
1930
1931fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
1932 let lines: Vec<&str> = source.lines().collect();
1933 (0..lines.len())
1934 .filter(|&index| row_height.is_match(lines[index]))
1935 .filter(|&index| {
1936 !chain_lines(&lines, index).iter().any(|line| {
1937 let line = line.trim();
1938 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
1939 })
1940 })
1941 .map(|index| index + 1)
1942 .collect()
1943}
1944
1945fn row_height_pattern() -> Regex {
1946 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
1947}
1948
1949#[test]
1950fn matcher_finds_rows_without_flex_none() {
1951 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";
1952 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
1953}
1954
1955#[test]
1956fn fixed_height_rows_never_shrink() {
1957 let row_height = row_height_pattern();
1958 let mut files = Vec::new();
1959 for root in source_roots() {
1960 source_files(&root, &mut files);
1961 }
1962 let violations: Vec<String> = files
1963 .iter()
1964 .filter(|file| !file.ends_with("layout_guard.rs"))
1965 .flat_map(|file| {
1966 let source = fs::read_to_string(file).expect("read source file");
1967 shrinking_rows(&row_height, &source)
1968 .into_iter()
1969 .map(|line| format!("{}:{line}", file.display()))
1970 .collect::<Vec<_>>()
1971 })
1972 .collect();
1973 assert!(
1974 violations.is_empty(),
1975 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
1976 );
1977}