BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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