BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 52.7 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::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::conversation::MEMBERS_BUTTON;
180 use crate::views::message_row::BUBBLE_TAGS;
181 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
182 use crate::views::reaction_proposal_pill::REACTION_PILL;
183 use crate::views::recap_tab::RECAP_REGION;
184 use crate::views::shell::{
185 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
186 };
187 use crate::views::shortcuts::{
188 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
189 };
190
191 const GUARDED: &[&str] = &[
192 "shell",
193 "shell/title-bar",
194 "shell/title-bar/search",
195 "shell/title-bar/own-status",
196 "shell/title-bar/own-status/avatar",
197 "shell/islands",
198 "shell/islands/rail",
199 "shell/islands/sidebar",
200 "shell/islands/main",
201 ];
202 const CALL_GUARDED: &[&str] = &[
203 "shell/islands/main/call-header",
204 "shell/islands/main/call-stage",
205 "shell/islands/main/call-controls",
206 "shell/islands/main/call-controls/mic",
207 "shell/islands/main/call-controls/leave",
208 ];
209 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
210 const CALLS_TAGS: &[&str] = &[
211 "shell/islands/sidebar/calls-actions",
212 "shell/islands/sidebar/calls-actions/meet-now",
213 "shell/islands/sidebar/calls-actions/new-meeting",
214 ];
215 const PREJOIN_TAGS: &[&str] = &[
216 "shell/islands/main/prejoin",
217 "shell/islands/main/prejoin/preview",
218 "shell/islands/main/prejoin/controls",
219 "shell/islands/main/prejoin/devices",
220 "shell/islands/main/prejoin/audio",
221 "shell/islands/main/prejoin/actions",
222 ];
223 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";
224 const CONSULT_GUARDED: &[&str] = &[
225 "shell/islands/main/call-header/call-consult",
226 "shell/islands/main/call-header/call-consult/transfer",
227 "shell/islands/main/call-header/call-consult/resume",
228 ];
229 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
230 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
231 const SHARE_GUARDED: &[&str] = &[
232 "shell/islands/main/call-stage/share-content",
233 "shell/islands/main/call-stage/share-content/zoom-chip",
234 "shell/islands/main/call-stage/share-divider",
235 "shell/islands/main/call-stage/share-strip",
236 ];
237 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
238 const OVERLAY_CHROME: &[&str] = &[
239 "shell/islands/main/call-header",
240 "shell/islands/main/call-stage",
241 ];
242 const MENU: &str = "popup-menu";
243 const OWN_STATUS: &str = "shell/title-bar/own-status";
244 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
245 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
246 const PROPOSAL_CHAT: &str = "demo-chat-release";
247 const REACTION_CHAT: &str = "demo-chat-mara";
248 const AGENT_TAGS: [&str; 4] = [
249 PROPOSAL_CARD,
250 PROPOSAL_THUMBNAILS,
251 PROPOSAL_BUTTONS,
252 REACTION_PILL,
253 ];
254 const SETTINGS_TAGS: &[&str] = &[
255 "settings",
256 "settings/nav",
257 "settings/nav/divider",
258 "settings/nav/about",
259 "settings/main",
260 "settings/main/header",
261 "settings/main/header/close",
262 "settings/main/body",
263 ];
264 const SETTINGS_BODY: &str = "settings/main/body";
265 const SETTINGS_CONTENT: &str = "settings/main/body/content";
266 const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
267 const MEMBERS_CHAT: &str = "demo-chat-release";
268 const DIVIDER_SEGMENT: &str = "divider";
269 const DIVIDER_THICKNESS: f32 = 1.;
270 const INSET_TOLERANCE: f32 = 1.;
271 const INSET_RULES: &[InsetRule] = &[
272 InsetRule {
273 panel: "settings/nav",
274 content: "settings/nav/about",
275 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
276 },
277 InsetRule {
278 panel: "settings/main",
279 content: "settings/main/header/close",
280 edges: &[Edge::Top, Edge::Right],
281 },
282 ];
283 const SCROLLED_INSET_RULE: InsetRule = InsetRule {
284 panel: SETTINGS_BODY,
285 content: SETTINGS_CONTENT,
286 edges: &[Edge::Left, Edge::Bottom],
287 };
288 const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
289 SettingsSection::Agents,
290 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
291 )];
292 const SETTINGS_SECTIONS: [SettingsSection; 9] = [
293 SettingsSection::General,
294 SettingsSection::Notifications,
295 SettingsSection::Appearance,
296 SettingsSection::Chats,
297 SettingsSection::Calls,
298 SettingsSection::Devices,
299 SettingsSection::Agents,
300 SettingsSection::Mcp,
301 SettingsSection::About,
302 ];
303 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
304 const TOLERANCE: f32 = 0.5;
305 const KNOWN_VIOLATIONS: &[&str] = &[];
306
307 type Tag = (&'static str, Bounds<Pixels>);
308
309 #[derive(Clone, Copy, Debug)]
310 enum Edge {
311 Top,
312 Right,
313 Bottom,
314 Left,
315 }
316
317 struct InsetRule {
318 panel: &'static str,
319 content: &'static str,
320 edges: &'static [Edge],
321 }
322
323 fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {
324 f32::from(match edge {
325 Edge::Top => content.top() - panel.top(),
326 Edge::Right => panel.right() - content.right(),
327 Edge::Bottom => panel.bottom() - content.bottom(),
328 Edge::Left => content.left() - panel.left(),
329 })
330 }
331
332 fn inset_violation(
333 rule: &InsetRule,
334 panel: Bounds<Pixels>,
335 content: Bounds<Pixels>,
336 ) -> Option<(String, String)> {
337 let insets: Vec<(Edge, f32)> = rule
338 .edges
339 .iter()
340 .map(|edge| (*edge, inset(panel, content, *edge)))
341 .collect();
342 let values = insets.iter().map(|(_, value)| *value);
343 let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);
344 (spread > INSET_TOLERANCE).then(|| {
345 (
346 format!("{}:uneven-inset", rule.panel),
347 format!(
348 "{} insets {} by {insets:?}, they must match",
349 rule.panel, rule.content
350 ),
351 )
352 })
353 }
354
355 fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {
356 let bounds_of = |path: &str| {
357 tags.iter()
358 .find(|(tag, _)| *tag == path)
359 .map(|(_, bounds)| *bounds)
360 };
361 rules
362 .iter()
363 .filter_map(
364 |rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {
365 (Some(panel), Some(content)) => inset_violation(rule, panel, content),
366 _ => None,
367 },
368 )
369 .collect()
370 }
371
372 fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {
373 let mut found = Vec::new();
374 for (path, bounds) in tags {
375 let Some((parent, segment)) = path.rsplit_once('/') else {
376 continue;
377 };
378 if !segment.starts_with(DIVIDER_SEGMENT) {
379 continue;
380 }
381 let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {
382 found.push((
383 format!("{path}:no-panel"),
384 format!("{path} needs its panel {parent} tagged"),
385 ));
386 continue;
387 };
388 let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;
389 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
390 let spans = if thin(bounds.size.height) {
391 near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())
392 } else if thin(bounds.size.width) {
393 near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())
394 } else {
395 false
396 };
397 if !spans {
398 found.push((
399 format!("{path}:short-divider"),
400 format!(
401 "{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",
402 describe(*bounds),
403 describe(*panel)
404 ),
405 ));
406 }
407 }
408 found
409 }
410
411 enum Screen {
412 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
413 StatusMenu,
414 Call,
415 Prejoin,
416 CallTranscript,
417 CallPeople,
418 CallShare,
419 CallConsult,
420 }
421
422 fn parent_of(path: &str) -> Option<&str> {
423 path.rsplit_once('/').map(|(parent, _)| parent)
424 }
425
426 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
427 let tolerance = px(TOLERANCE);
428 inner.left() >= outer.left() - tolerance
429 && inner.top() >= outer.top() - tolerance
430 && inner.right() <= outer.right() + tolerance
431 && inner.bottom() <= outer.bottom() + tolerance
432 }
433
434 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
435 let tolerance = px(TOLERANCE);
436 first.left() < second.right() - tolerance
437 && second.left() < first.right() - tolerance
438 && first.top() < second.bottom() - tolerance
439 && second.top() < first.bottom() - tolerance
440 }
441
442 fn describe(bounds: Bounds<Pixels>) -> String {
443 format!(
444 "[{:.1},{:.1} {:.1}x{:.1}]",
445 f32::from(bounds.origin.x),
446 f32::from(bounds.origin.y),
447 f32::from(bounds.size.width),
448 f32::from(bounds.size.height)
449 )
450 }
451
452 fn violations(
453 tags: &[Tag],
454 window: Bounds<Pixels>,
455 expected: &[&str],
456 ) -> Vec<(String, String)> {
457 let mut found = Vec::new();
458 let bounds_of = |path: &str| {
459 tags.iter()
460 .find(|(tag, _)| *tag == path)
461 .map(|(_, bounds)| *bounds)
462 };
463 for path in expected {
464 if bounds_of(path).is_none() {
465 found.push((
466 format!("{path}:missing"),
467 format!("{path} was not rendered"),
468 ));
469 }
470 }
471 for (path, bounds) in tags {
472 if !contains(window, *bounds) {
473 found.push((
474 format!("{path}:outside-window"),
475 format!(
476 "{path} {} leaves the window {}",
477 describe(*bounds),
478 describe(window)
479 ),
480 ));
481 }
482 if let Some(parent) =
483 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
484 {
485 if !contains(parent.1, *bounds) {
486 found.push((
487 format!("{path}:outside-parent"),
488 format!(
489 "{path} {} leaves {} {}",
490 describe(*bounds),
491 parent.0,
492 describe(parent.1)
493 ),
494 ));
495 }
496 }
497 for (other, other_bounds) in tags {
498 let overlays = |first: &str, second: &str| {
499 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
500 };
501 let siblings = path < other
502 && parent_of(path).is_some()
503 && parent_of(path) == parent_of(other)
504 && !overlays(path, other)
505 && !overlays(other, path);
506 if siblings && overlaps(*bounds, *other_bounds) {
507 found.push((
508 format!("{path}:overlaps:{other}"),
509 format!(
510 "{path} {} overlaps {other} {}",
511 describe(*bounds),
512 describe(*other_bounds)
513 ),
514 ));
515 }
516 }
517 }
518 found.extend(divider_violations(tags));
519 found
520 }
521
522 const SETTLE_FRAMES: usize = 2;
523 const SETTLE_LIMIT: usize = 60;
524 const SETTLE_STEP: Duration = Duration::from_millis(50);
525
526 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
527 let mut frames = 0;
528 while frames < SETTLE_FRAMES
529 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
530 {
531 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
532 visual.executor().advance_clock(SETTLE_STEP);
533 std::thread::sleep(SETTLE_STEP);
534 visual.run_until_parked();
535 visual.update(|window, cx| window.render_frame(cx));
536 frames += 1;
537 }
538 GUARDED
539 .iter()
540 .chain(CALL_GUARDED)
541 .chain(CALLS_TAGS)
542 .chain(PREJOIN_TAGS)
543 .chain(SHARE_GUARDED)
544 .chain(CONSULT_GUARDED)
545 .chain([
546 &AGENTS_LIST,
547 &CALL_TRANSCRIPT,
548 &MENU,
549 &RECAP_TAB,
550 &RECAP_REGION,
551 &PEOPLE_PANEL,
552 ])
553 .chain(&AGENT_TAGS)
554 .chain(SETTINGS_TAGS)
555 .chain(MEMBERS_TAGS)
556 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
557 .collect()
558 }
559
560 fn sharing_call() -> ActiveCall {
561 let mut call = gallery_call();
562 call.model
563 .apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
564 call.share_stage.view.step_in((800., 450.));
565 call
566 }
567
568 fn gallery_call() -> ActiveCall {
569 let (handle, _control) = call_channel();
570 let mut model = CallModel::meeting("Standup", false);
571 model.apply(CallUpdate::State(CallState::Connected {
572 since: Instant::now(),
573 }));
574 model.apply(CallUpdate::Roster(
575 (0..11)
576 .map(|index| RosterEntry {
577 mri: format!("8:orgid:guard-{index}"),
578 display_name: format!("Guest {index}"),
579 muted: false,
580 in_lobby: false,
581 has_video: false,
582 sharing: false,
583 hand: None,
584 spotlight: None,
585 organizer: false,
586 ..Default::default()
587 })
588 .collect(),
589 ));
590 ActiveCall::new(1, model, handle.commands, None, handle.video)
591 }
592
593 fn consult_calls() -> (ActiveCall, ActiveCall) {
594 let connected = |id: u64, name: &str, mri: &str| {
595 let (handle, _control) = call_channel();
596 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
597 model.apply(CallUpdate::State(CallState::Connected {
598 since: Instant::now(),
599 }));
600 ActiveCall::new(id, model, handle.commands, None, handle.video)
601 };
602 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
603 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
604 consult.consult = Some(ConsultCall::new(
605 (
606 "8:orgid:guard-consult".to_owned(),
607 "Jonas Ortega".to_owned(),
608 ),
609 held.model.peer_name.clone(),
610 ));
611 (consult, held)
612 }
613
614 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
615 mount_with(cx, false)
616 }
617
618 fn mount_with(
619 cx: &mut TestAppContext,
620 agent_api: bool,
621 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
622 cx.update(gpui_kit::init);
623 cx.update(|cx| {
624 crate::theme::apply(cx);
625 bind_keys(cx);
626 let store = Store::open_in_memory().expect("in-memory store");
627 demo::seed(&store);
628 let store = Arc::new(store);
629 if agent_api {
630 crate::agent_api::init(store.clone(), true, cx);
631 }
632 let mode = Mode {
633 demo: true,
634 read_only: false,
635 demo_sync: None,
636 };
637 let state = cx.new(|_| AppState::new(store, mode));
638 install_globals(&state, UserInput::new(), cx);
639 crate::agents::install(state.clone(), cx);
640 demo::start_session(&state, cx);
641 let shared_state = state.clone();
642 let startup = Startup {
643 switcher_query: None,
644 composer_text: None,
645 reply_to_last: false,
646 };
647 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
648 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
649 })
650 .expect("open test window")
651 .0;
652 (window, shared_state)
653 })
654 }
655
656 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
657 Bounds {
658 origin: point(px(left), px(top)),
659 size: size(px(width), px(height)),
660 }
661 }
662
663 #[test]
664 fn rules_flag_overlap_and_overflow() {
665 let window = rectangle(0., 0., 100., 100.);
666 let tags: Vec<Tag> = vec![
667 ("shell", rectangle(0., 0., 100., 100.)),
668 ("shell/islands", rectangle(0., 0., 100., 50.)),
669 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
670 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
671 ];
672 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
673 .into_iter()
674 .map(|(key, _)| key)
675 .collect();
676 let line_tags: Vec<Tag> = vec![
677 ("panel", rectangle(0., 0., 100., 100.)),
678 ("panel/divider", rectangle(0., 50., 100., 1.)),
679 ("panel/divider-inset", rectangle(12., 60., 76., 1.)),
680 ("panel/divider-side", rectangle(40., 0., 1., 100.)),
681 ("panel/about", rectangle(12., 76., 76., 12.)),
682 ("panel/footer", rectangle(12., 64., 76., 12.)),
683 ];
684 let line_keys: Vec<String> = divider_violations(&line_tags)
685 .into_iter()
686 .chain(inset_violations(
687 &line_tags,
688 &[
689 InsetRule {
690 panel: "panel",
691 content: "panel/about",
692 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
693 },
694 InsetRule {
695 panel: "panel",
696 content: "panel/footer",
697 edges: &[Edge::Left, Edge::Bottom],
698 },
699 ],
700 ))
701 .map(|(key, _)| key)
702 .collect();
703 assert_eq!(
704 line_keys,
705 ["panel/divider-inset:short-divider", "panel:uneven-inset"]
706 );
707 assert_eq!(
708 keys,
709 [
710 "shell/status-bar:missing",
711 "shell/islands/rail:overlaps:shell/islands/sidebar",
712 "shell/islands/sidebar:outside-window",
713 "shell/islands/sidebar:outside-parent",
714 ]
715 );
716 }
717
718 #[gpui_kit::test]
719 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
720 let (handle, app) = mount(cx);
721 let mut visual = VisualTestContext::from_window(handle, cx);
722 let mut seen_known = HashSet::new();
723 let mut unexpected = Vec::new();
724 for (width, height) in SIZES {
725 visual.simulate_resize(size(px(width), px(height)));
726 let window = Bounds {
727 origin: point(px(0.), px(0.)),
728 size: size(px(width), px(height)),
729 };
730 let screens = [
731 Screen::Tab("chats", None),
732 Screen::Tab(
733 "activity",
734 Some(|visual| visual.dispatch_action(OpenActivity)),
735 ),
736 Screen::Tab(
737 "channels",
738 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
739 ),
740 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
741 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
742 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
743 Screen::Prejoin,
744 Screen::StatusMenu,
745 Screen::Call,
746 Screen::CallTranscript,
747 Screen::CallPeople,
748 Screen::CallShare,
749 Screen::CallConsult,
750 ];
751 for screen in screens {
752 let (screen_name, status_menu) = match screen {
753 Screen::Tab(name, open) => {
754 if let Some(open) = open {
755 open(&mut visual);
756 }
757 (name, false)
758 }
759 Screen::Call | Screen::CallPeople => {
760 let people_open = matches!(screen, Screen::CallPeople);
761 visual.update(|_, cx| {
762 app.update(cx, |state, cx| {
763 let mut call = gallery_call();
764 call.people_open = people_open;
765 state.call = Some(call);
766 cx.notify();
767 })
768 });
769 (if people_open { "call-people" } else { "call" }, false)
770 }
771 Screen::Prejoin => {
772 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
773 visual.update(|_, cx| {
774 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
775 });
776 ("prejoin", false)
777 }
778 Screen::CallTranscript => {
779 visual.update(|window, cx| {
780 app.update(cx, |state, cx| {
781 let mut call = gallery_call();
782 call.model.apply(CallUpdate::Captions(CaptionState::On));
783 for index in 0..40 {
784 call.model.note_caption(
785 CaptionEntry {
786 id: format!("guard-{index}"),
787 user_id: "8:orgid:guard-0".into(),
788 display_name: "Guest 0".into(),
789 text: "A long guarded sentence that has to wrap inside the panel".into(),
790 is_final: true,
791 },
792 Instant::now(),
793 );
794 }
795 call.transcript_open = true;
796 state.call = Some(call);
797 let app_entity = cx.entity();
798 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
799 cx.notify();
800 })
801 });
802 ("call-transcript", false)
803 }
804 Screen::CallShare => {
805 visual.update(|_, cx| {
806 app.update(cx, |state, cx| {
807 state.call = Some(sharing_call());
808 cx.notify();
809 })
810 });
811 ("call-share", false)
812 }
813 Screen::CallConsult => {
814 visual.update(|_, cx| {
815 app.update(cx, |state, cx| {
816 let (consult, held) = consult_calls();
817 state.call = Some(consult);
818 state.held_call = Some(held);
819 cx.notify();
820 })
821 });
822 ("call-consult", false)
823 }
824 Screen::StatusMenu => {
825 let tags = collect(&mut visual, None);
826 let button = tags
827 .iter()
828 .find(|(path, _)| *path == OWN_STATUS)
829 .map(|(_, bounds)| *bounds)
830 .expect("own status button rendered");
831 visual.simulate_click(button.center(), Default::default());
832 ("status-menu", true)
833 }
834 };
835 let is_call = matches!(
836 screen_name,
837 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
838 );
839 let tags = collect(&mut visual, status_menu.then_some(MENU));
840 let mut expected = GUARDED.to_vec();
841 if is_call {
842 expected.extend(CALL_GUARDED);
843 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
844 if sidebar_hidden_in_call(width, panel_open) {
845 expected.retain(|path| *path != "shell/islands/sidebar");
846 }
847 }
848 if screen_name == "call-transcript" {
849 expected.push(CALL_TRANSCRIPT);
850 }
851 if screen_name == "call-people" {
852 expected.push(PEOPLE_PANEL);
853 }
854 if screen_name == "call-share" {
855 expected.extend(SHARE_GUARDED);
856 }
857 if screen_name == "call-consult" {
858 expected.extend(CONSULT_GUARDED);
859 }
860 if status_menu {
861 expected.push(MENU);
862 }
863 match screen_name {
864 "calls" => expected.extend(CALLS_TAGS),
865 "agents" => expected.push(AGENTS_LIST),
866 "prejoin" => expected.extend(PREJOIN_TAGS),
867 _ => {}
868 }
869 let mut found = violations(&tags, window, &expected);
870 if status_menu {
871 let menu = tags
872 .iter()
873 .find(|(path, _)| *path == MENU)
874 .map(|(_, bounds)| *bounds);
875 let button = tags
876 .iter()
877 .find(|(path, _)| *path == OWN_STATUS)
878 .map(|(_, bounds)| *bounds);
879 if let (Some(menu), Some(button)) = (menu, button) {
880 if overlaps(menu, button) {
881 found.push((
882 format!("{MENU}:covers:{OWN_STATUS}"),
883 format!(
884 "{MENU} {} covers {OWN_STATUS} {}",
885 describe(menu),
886 describe(button)
887 ),
888 ));
889 }
890 }
891 visual.simulate_keystrokes("escape");
892 visual.run_until_parked();
893 }
894 if is_call {
895 visual.update(|_, cx| {
896 app.update(cx, |state, cx| {
897 state.call = None;
898 state.held_call = None;
899 cx.notify();
900 })
901 });
902 }
903 if screen_name == "prejoin" {
904 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
905 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
906 }
907 for (key, message) in found {
908 let full_key = format!("{screen_name}@{width}x{height}:{key}");
909 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
910 seen_known.insert(full_key);
911 } else {
912 unexpected.push(format!("{full_key}: {message}"));
913 }
914 }
915 }
916 }
917 let stale: Vec<String> = KNOWN_VIOLATIONS
918 .iter()
919 .filter(|key| !seen_known.contains(**key))
920 .map(|key| format!("stale known violation, remove it: {key}"))
921 .collect();
922 assert!(
923 unexpected.is_empty() && stale.is_empty(),
924 "{}",
925 unexpected
926 .into_iter()
927 .chain(stale)
928 .collect::<Vec<_>>()
929 .join("\n")
930 );
931 }
932 #[gpui_kit::test]
933 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
934 let (handle, app) = mount(cx);
935 let mut visual = VisualTestContext::from_window(handle, cx);
936 for (width, height) in SIZES {
937 visual.simulate_resize(size(px(width), px(height)));
938 visual.update(|_, cx| {
939 app.update(cx, |state, cx| {
940 let mut call = gallery_call();
941 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
942 call.chat_open = true;
943 state.call = Some(call);
944 cx.notify();
945 })
946 });
947 collect(&mut visual, Some(CHAT_PANEL_TAG));
948 let panel = visual
949 .debug_bounds(CHAT_PANEL_TAG)
950 .expect("chat panel rendered");
951 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
952 .iter()
953 .enumerate()
954 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
955 .collect();
956 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
957 let found: Vec<String> = bubbles
958 .into_iter()
959 .filter(|(_, bounds)| !contains(panel, *bounds))
960 .map(|(index, bounds)| {
961 format!(
962 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
963 describe(bounds),
964 describe(panel)
965 )
966 })
967 .collect();
968 visual.update(|_, cx| {
969 app.update(cx, |state, cx| {
970 state.call = None;
971 cx.notify();
972 })
973 });
974 assert!(found.is_empty(), "{}", found.join("\n"));
975 }
976 }
977
978 #[gpui_kit::test]
979 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
980 let (handle, state) = mount(cx);
981 let mut visual = VisualTestContext::from_window(handle, cx);
982 for (width, height) in SIZES {
983 visual.simulate_resize(size(px(width), px(height)));
984 let window = Bounds {
985 origin: point(px(0.), px(0.)),
986 size: size(px(width), px(height)),
987 };
988 visual.update(|_, cx| {
989 state.update(cx, |state, cx| {
990 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
991 })
992 });
993 collect(&mut visual, Some(RECAP_TAB));
994 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
995 visual.simulate_click(tab.center(), Default::default());
996 let tags = collect(&mut visual, Some(RECAP_REGION));
997 let mut expected = GUARDED.to_vec();
998 expected.extend([RECAP_TAB, RECAP_REGION]);
999 let found: Vec<String> = violations(&tags, window, &expected)
1000 .into_iter()
1001 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1002 .collect();
1003 assert!(found.is_empty(), "{}", found.join("\n"));
1004 }
1005 }
1006
1007 #[gpui_kit::test]
1008 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1009 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1010 }
1011
1012 #[gpui_kit::test]
1013 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1014 crate::theme::set_thread_scheme(Some("teams"));
1015 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1016 crate::theme::set_thread_scheme(None);
1017 }
1018
1019 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1020 let (handle, state) = mount_with(cx, true);
1021 let mut visual = VisualTestContext::from_window(handle, cx);
1022 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1023 visual.simulate_resize(size(px(width), px(height)));
1024 let window = Bounds {
1025 origin: point(px(0.), px(0.)),
1026 size: size(px(width), px(height)),
1027 };
1028 let inset = metrics(width, height).inset;
1029 for &section in sections {
1030 visual
1031 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1032 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1033 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1034 .into_iter()
1035 .filter(|(key, _)| key.starts_with("settings"))
1036 .chain(inset_violations(&tags, INSET_RULES))
1037 .collect();
1038 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1039 .iter()
1040 .any(|(exempt, _)| *exempt == section);
1041 if !scrolled_exempt {
1042 found.extend(scrolled_inset_violation(&mut visual));
1043 }
1044 let found: Vec<String> = found
1045 .into_iter()
1046 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1047 .collect();
1048 assert!(found.is_empty(), "{}", found.join("\n"));
1049 let dialog = visual
1050 .debug_bounds(SETTINGS_TAGS[0])
1051 .expect("settings dialog");
1052 let edges = [
1053 f32::from(dialog.left()),
1054 f32::from(dialog.top()),
1055 width - f32::from(dialog.right()),
1056 height - f32::from(dialog.bottom()),
1057 ];
1058 assert!(
1059 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1060 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1061 );
1062 }
1063 }
1064 }
1065
1066 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1067 let body = visual.debug_bounds(SETTINGS_BODY)?;
1068 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1069 if content.bottom() <= body.bottom() {
1070 return None;
1071 }
1072 visual.simulate_event(ScrollWheelEvent {
1073 position: body.center(),
1074 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1075 ..Default::default()
1076 });
1077 collect(visual, None);
1078 let body = visual.debug_bounds(SETTINGS_BODY)?;
1079 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1080 inset_violation(&SCROLLED_INSET_RULE, body, content)
1081 }
1082
1083 #[gpui_kit::test]
1084 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1085 let (handle, state) = mount(cx);
1086 let mut visual = VisualTestContext::from_window(handle, cx);
1087 for (width, height) in SIZES {
1088 visual.simulate_resize(size(px(width), px(height)));
1089 let window = Bounds {
1090 origin: point(px(0.), px(0.)),
1091 size: size(px(width), px(height)),
1092 };
1093 visual.update(|_, cx| {
1094 state.update(cx, |state, cx| {
1095 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1096 })
1097 });
1098 collect(&mut visual, Some(MEMBERS_BUTTON));
1099 let button = visual
1100 .debug_bounds(MEMBERS_BUTTON)
1101 .expect("members button rendered");
1102 visual.simulate_click(button.center(), Default::default());
1103 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1104 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1105 .into_iter()
1106 .filter(|(key, _)| key.starts_with("chat-members"))
1107 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1108 .collect();
1109 visual.simulate_keystrokes("escape");
1110 visual.run_until_parked();
1111 assert!(found.is_empty(), "{}", found.join("\n"));
1112 }
1113 }
1114
1115 #[gpui_kit::test]
1116 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1117 let (handle, state) = mount_with(cx, true);
1118 let mut visual = VisualTestContext::from_window(handle, cx);
1119 for (width, height) in SIZES {
1120 visual.simulate_resize(size(px(width), px(height)));
1121 let window = Bounds {
1122 origin: point(px(0.), px(0.)),
1123 size: size(px(width), px(height)),
1124 };
1125 for (chat, expected_tags) in [
1126 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
1127 (REACTION_CHAT, &AGENT_TAGS[3..]),
1128 ] {
1129 visual.update(|_, cx| {
1130 state.update(cx, |state, cx| {
1131 state.select(Selection::Chat(chat.to_owned()), cx)
1132 })
1133 });
1134 let tags = collect(&mut visual, Some(expected_tags[0]));
1135 let mut expected = GUARDED.to_vec();
1136 expected.extend(expected_tags);
1137 let found: Vec<String> = violations(&tags, window, &expected)
1138 .into_iter()
1139 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
1140 .collect();
1141 assert!(found.is_empty(), "{}", found.join("\n"));
1142 }
1143 }
1144 }
1145}
1146
1147#[test]
1148fn lines_are_solid() {
1149 let mut files = Vec::new();
1150 for root in source_roots() {
1151 source_files(&root, &mut files);
1152 }
1153 let violations: Vec<String> = files
1154 .iter()
1155 .filter(|file| !file.ends_with("layout_guard.rs"))
1156 .flat_map(|file| {
1157 let source = fs::read_to_string(file).expect("read source file");
1158 source
1159 .lines()
1160 .enumerate()
1161 .filter(|(_, line)| {
1162 line.contains(".border_dashed(") || line.contains(".border_dotted(")
1163 })
1164 .map(|(index, line)| {
1165 format!(
1166 "{}:{}: lines are always solid: {}",
1167 file.display(),
1168 index + 1,
1169 line.trim()
1170 )
1171 })
1172 .collect::<Vec<_>>()
1173 })
1174 .collect();
1175 assert!(violations.is_empty(), "{}", violations.join("\n"));
1176}
1177
1178const STATE_RING_COLORS: &[&str] = &[
1179 "if focused",
1180 "if selected",
1181 "if speaking",
1182 "if current",
1183 "if open",
1184 "if state.failed",
1185];
1186const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
1187 (
1188 "notify/ring_view.rs",
1189 "theme::green()",
1190 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1191 ),
1192 (
1193 "notify/meeting_view.rs",
1194 "theme::accent()",
1195 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1196 ),
1197 (
1198 "notify/meeting_view.rs",
1199 "theme::border_strong()",
1200 "outlined button, not a surface",
1201 ),
1202 (
1203 "notify/toast.rs",
1204 "border)",
1205 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1206 ),
1207 (
1208 "notify/toast.rs",
1209 "theme::border_strong()",
1210 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1211 ),
1212 (
1213 "settings/mcp.rs",
1214 "theme::border_strong()",
1215 "outlined button, not a surface",
1216 ),
1217 (
1218 "settings/rows.rs",
1219 "theme::border_strong()",
1220 "outlined button, not a surface",
1221 ),
1222 (
1223 "views/card_widgets.rs",
1224 "border)",
1225 "message content drawn as Teams renders it",
1226 ),
1227 (
1228 "views/card_widgets.rs",
1229 "theme::border_strong()",
1230 "message content drawn as Teams renders it",
1231 ),
1232 ("views/shared_tab.rs", "theme::accent()", "input field"),
1233 ("views/card_input.rs", "if error.is_some()", "input field"),
1234 ("views/format_toolbar.rs", "if refused", "input field"),
1235 (
1236 "views/card_code_block.rs",
1237 "theme::code_header_border()",
1238 "message content drawn as Teams renders it",
1239 ),
1240 ("views/call_transcript.rs", "theme::border()", "input field"),
1241 (
1242 "views/conversation.rs",
1243 "theme::accent()",
1244 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1245 ),
1246 (
1247 "views/attachment_tray.rs",
1248 "theme::accent()",
1249 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1250 ),
1251 (
1252 "views/card_carousel.rs",
1253 "theme::border_strong()",
1254 "message content drawn as Teams renders it",
1255 ),
1256 (
1257 "views/card_table.rs",
1258 "grid_color",
1259 "message content drawn as Teams renders it",
1260 ),
1261 (
1262 "views/activity_panel.rs",
1263 "theme::surface()",
1264 "cutout ring in the background color, invisible against its surface",
1265 ),
1266 (
1267 "views/avatar.rs",
1268 "theme::surface()",
1269 "cutout ring in the background color, invisible against its surface",
1270 ),
1271 (
1272 "views/avatar.rs",
1273 "theme::text_muted()",
1274 "offline presence glyph, Teams icon",
1275 ),
1276 (
1277 "views/message_row.rs",
1278 "theme::border_strong()",
1279 "deleted message placeholder, Teams look",
1280 ),
1281 (
1282 "views/message_row.rs",
1283 "theme::red()",
1284 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1285 ),
1286 (
1287 "views/message_row.rs",
1288 "if row.delivery",
1289 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1290 ),
1291 (
1292 "views/new_meeting_dialog.rs",
1293 "theme::border()",
1294 "input field",
1295 ),
1296 (
1297 "views/call_mini_window.rs",
1298 "theme::border_strong()",
1299 "self view over live video, needs an edge on any picture",
1300 ),
1301 ("views/transfer_picker.rs", "theme::border()", "input field"),
1302 (
1303 "views/call_notice.rs",
1304 "theme::border_strong()",
1305 "outlined button, not a surface",
1306 ),
1307 (
1308 "views/composer/schedule.rs",
1309 "theme::accent()",
1310 "input field",
1311 ),
1312 (
1313 "views/call_mini.rs",
1314 "border)",
1315 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1316 ),
1317 (
1318 "views/sidebar.rs",
1319 "theme::accent()",
1320 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1321 ),
1322 (
1323 "views/adaptive_card.rs",
1324 "theme::border()",
1325 "message content drawn as Teams renders it",
1326 ),
1327 (
1328 "views/adaptive_card.rs",
1329 "border)",
1330 "message content drawn as Teams renders it",
1331 ),
1332 (
1333 "views/share_bar.rs",
1334 "theme::red()",
1335 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1336 ),
1337 ("settings_controls.rs", "if invalid", "input field"),
1338];
1339
1340fn outlines(source: &str) -> Vec<(usize, String)> {
1341 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
1342 pattern
1343 .find_iter(source)
1344 .map(|found| {
1345 let line_number = source[..found.start()].matches('\n').count() + 1;
1346 let after = &source[found.end()..];
1347 let color = after
1348 .find(".border_color(")
1349 .filter(|position| *position < 120)
1350 .map(|position| {
1351 let start = &after[position + ".border_color(".len()..];
1352 start
1353 .lines()
1354 .map(str::trim)
1355 .find(|line| !line.is_empty())
1356 .unwrap_or_default()
1357 .to_owned()
1358 })
1359 .unwrap_or_default();
1360 (line_number, color)
1361 })
1362 .collect()
1363}
1364
1365#[test]
1366fn outline_matcher_reads_the_border_color() {
1367 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
1368 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
1369}
1370
1371#[test]
1372fn surfaces_are_soft() {
1373 let mut matched_allowlist = HashSet::new();
1374 let mut violations = Vec::new();
1375 for root in source_roots() {
1376 let mut files = Vec::new();
1377 source_files(&root, &mut files);
1378 for file in files {
1379 let relative = file
1380 .strip_prefix(&root)
1381 .expect("inside src")
1382 .to_string_lossy()
1383 .replace('\\', "/");
1384 if relative == "layout_guard.rs" {
1385 continue;
1386 }
1387 let source = fs::read_to_string(&file).expect("read source file");
1388 for (line_number, color) in outlines(&source) {
1389 if STATE_RING_COLORS
1390 .iter()
1391 .any(|prefix| color.starts_with(prefix))
1392 {
1393 continue;
1394 }
1395 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
1396 *allowed_file == relative && color.starts_with(prefix)
1397 }) {
1398 Some(position) => {
1399 matched_allowlist.insert(position);
1400 }
1401 None => violations.push(format!(
1402 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
1403 )),
1404 }
1405 }
1406 }
1407 }
1408 let stale = OUTLINE_ALLOWLIST
1409 .iter()
1410 .enumerate()
1411 .filter(|(position, _)| !matched_allowlist.contains(position))
1412 .map(|(_, (file, prefix, _))| {
1413 format!("stale outline allowlist entry, remove it: {file} {prefix}")
1414 });
1415 let report: Vec<String> = violations.into_iter().chain(stale).collect();
1416 assert!(report.is_empty(), "{}", report.join("\n"));
1417}