BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 59.9 KiB Download Raw
1use std::collections::HashSet;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6
7const WIDGETS_FILE: &str = "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::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};
181 use crate::views::message_row::BUBBLE_TAGS;
182 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
183 use crate::views::reaction_proposal_pill::REACTION_PILL;
184 use crate::views::recap_tab::RECAP_REGION;
185 use crate::views::shell::{
186 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
187 };
188 use crate::views::shortcuts::{
189 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
190 };
191
192 const GUARDED: &[&str] = &[
193 "shell",
194 "shell/title-bar",
195 "shell/title-bar/search",
196 "shell/title-bar/own-status",
197 "shell/title-bar/own-status/avatar",
198 "shell/islands",
199 "shell/islands/rail",
200 "shell/islands/sidebar",
201 "shell/islands/main",
202 ];
203 const CALL_GUARDED: &[&str] = &[
204 "shell/islands/main/call-header",
205 "shell/islands/main/call-stage",
206 "shell/islands/main/call-controls",
207 "shell/islands/main/call-controls/mic",
208 "shell/islands/main/call-controls/leave",
209 ];
210 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
211 const CALLS_TAGS: &[&str] = &[
212 "shell/islands/sidebar/calls-actions",
213 "shell/islands/sidebar/calls-actions/meet-now",
214 "shell/islands/sidebar/calls-actions/new-meeting",
215 ];
216 const PREJOIN_TAGS: &[&str] = &[
217 "shell/islands/main/prejoin",
218 "shell/islands/main/prejoin/preview",
219 "shell/islands/main/prejoin/controls",
220 "shell/islands/main/prejoin/devices",
221 "shell/islands/main/prejoin/audio",
222 "shell/islands/main/prejoin/actions",
223 ];
224 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";
225 const CONSULT_GUARDED: &[&str] = &[
226 "shell/islands/main/call-header/call-consult",
227 "shell/islands/main/call-header/call-consult/transfer",
228 "shell/islands/main/call-header/call-consult/resume",
229 ];
230 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
231 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
232 const SHARE_GUARDED: &[&str] = &[
233 "shell/islands/main/call-stage/share-content",
234 "shell/islands/main/call-stage/share-content/zoom-chip",
235 "shell/islands/main/call-stage/share-divider",
236 "shell/islands/main/call-stage/share-strip",
237 ];
238 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
239 const OVERLAY_CHROME: &[&str] = &[
240 "shell/islands/main/call-header",
241 "shell/islands/main/call-stage",
242 ];
243 const MENU: &str = "popup-menu";
244 const OWN_STATUS: &str = "shell/title-bar/own-status";
245 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
246 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
247 const PROPOSAL_CHAT: &str = "demo-chat-release";
248 const REACTION_CHAT: &str = "demo-chat-mara";
249 const AGENT_TAGS: [&str; 4] = [
250 PROPOSAL_CARD,
251 PROPOSAL_THUMBNAILS,
252 PROPOSAL_BUTTONS,
253 REACTION_PILL,
254 ];
255 const SETTINGS_TAGS: &[&str] = &[
256 "settings",
257 "settings/nav",
258 "settings/nav/divider",
259 "settings/nav/about",
260 "settings/main",
261 "settings/main/header",
262 "settings/main/header/close",
263 "settings/main/body",
264 ];
265 const SETTINGS_BODY: &str = "settings/main/body";
266 const SETTINGS_CONTENT: &str = "settings/main/body/content";
267 const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
268 const MEMBERS_CHAT: &str = "demo-chat-release";
269 const DIVIDER_SEGMENT: &str = "divider";
270 const DIVIDER_THICKNESS: f32 = 1.;
271 const INSET_TOLERANCE: f32 = 1.;
272 const INSET_RULES: &[InsetRule] = &[
273 InsetRule {
274 panel: "settings/nav",
275 content: "settings/nav/about",
276 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
277 },
278 InsetRule {
279 panel: "settings/main",
280 content: "settings/main/header/close",
281 edges: &[Edge::Top, Edge::Right],
282 },
283 ];
284 const SCROLLED_INSET_RULE: InsetRule = InsetRule {
285 panel: SETTINGS_BODY,
286 content: SETTINGS_CONTENT,
287 edges: &[Edge::Left, Edge::Bottom],
288 };
289 const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
290 SettingsSection::Agents,
291 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
292 )];
293 const SETTINGS_SECTIONS: [SettingsSection; 8] = [
294 SettingsSection::General,
295 SettingsSection::Notifications,
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 const TITLE_SEARCH: &str = "shell/title-bar/search";
933 const TITLE_NEIGHBOURS: &[&str] = &[
934 "shell/title-bar/leading",
935 "shell/title-bar/mode-pill",
936 "shell/title-bar/trailing",
937 "shell/title-bar/update",
938 OWN_STATUS,
939 ];
940 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
941 (1920., 1080., true),
942 (1280., 800., true),
943 (640., 480., false),
944 ];
945
946 #[gpui_kit::test]
947 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
948 let (handle, _) = mount(cx);
949 let mut visual = VisualTestContext::from_window(handle, cx);
950 let shell = visual.update(|window, cx| {
951 window
952 .root::<gpui_kit::base::Root>()
953 .flatten()
954 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
955 .expect("app shell is the root view")
956 });
957 visual.update(|_, cx| {
958 shell.update(cx, |shell, cx| {
959 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
960 })
961 });
962 let mut found = Vec::new();
963 for (width, height, centered) in TITLE_SEARCH_SIZES {
964 visual.simulate_resize(size(px(width), px(height)));
965 collect(&mut visual, Some(TITLE_SEARCH));
966 let search = visual
967 .debug_bounds(TITLE_SEARCH)
968 .expect("title search rendered");
969 let search_center = f32::from(search.center().x);
970 eprintln!(
971 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
972 describe(search),
973 width / 2.
974 );
975 if centered && (search_center - width / 2.).abs() > 1. {
976 found.push(format!(
977 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
978 width / 2.
979 ));
980 }
981 if !contains(rectangle(0., 0., width, height), search) {
982 found.push(format!(
983 "@{width}x{height}: search {} leaves the window",
984 describe(search)
985 ));
986 }
987 for neighbour in TITLE_NEIGHBOURS {
988 match visual.debug_bounds(neighbour) {
989 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
990 Some(bounds) if overlaps(search, bounds) => found.push(format!(
991 "@{width}x{height}: search {} overlaps {neighbour} {}",
992 describe(search),
993 describe(bounds)
994 )),
995 Some(_) => {}
996 }
997 }
998 }
999 assert!(found.is_empty(), "{}", found.join("\n"));
1000 }
1001
1002 #[gpui_kit::test]
1003 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
1004 let (handle, app) = mount(cx);
1005 let mut visual = VisualTestContext::from_window(handle, cx);
1006 for (width, height) in SIZES {
1007 visual.simulate_resize(size(px(width), px(height)));
1008 visual.update(|_, cx| {
1009 app.update(cx, |state, cx| {
1010 let mut call = gallery_call();
1011 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
1012 call.chat_open = true;
1013 state.call = Some(call);
1014 cx.notify();
1015 })
1016 });
1017 collect(&mut visual, Some(CHAT_PANEL_TAG));
1018 let panel = visual
1019 .debug_bounds(CHAT_PANEL_TAG)
1020 .expect("chat panel rendered");
1021 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
1022 .iter()
1023 .enumerate()
1024 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
1025 .collect();
1026 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
1027 let found: Vec<String> = bubbles
1028 .into_iter()
1029 .filter(|(_, bounds)| !contains(panel, *bounds))
1030 .map(|(index, bounds)| {
1031 format!(
1032 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
1033 describe(bounds),
1034 describe(panel)
1035 )
1036 })
1037 .collect();
1038 visual.update(|_, cx| {
1039 app.update(cx, |state, cx| {
1040 state.call = None;
1041 cx.notify();
1042 })
1043 });
1044 assert!(found.is_empty(), "{}", found.join("\n"));
1045 }
1046 }
1047
1048 #[gpui_kit::test]
1049 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1050 let (handle, state) = mount(cx);
1051 let mut visual = VisualTestContext::from_window(handle, cx);
1052 for (width, height) in SIZES {
1053 visual.simulate_resize(size(px(width), px(height)));
1054 let window = Bounds {
1055 origin: point(px(0.), px(0.)),
1056 size: size(px(width), px(height)),
1057 };
1058 visual.update(|_, cx| {
1059 state.update(cx, |state, cx| {
1060 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1061 })
1062 });
1063 collect(&mut visual, Some(RECAP_TAB));
1064 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1065 visual.simulate_click(tab.center(), Default::default());
1066 let tags = collect(&mut visual, Some(RECAP_REGION));
1067 let mut expected = GUARDED.to_vec();
1068 expected.extend([RECAP_TAB, RECAP_REGION]);
1069 let found: Vec<String> = violations(&tags, window, &expected)
1070 .into_iter()
1071 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1072 .collect();
1073 assert!(found.is_empty(), "{}", found.join("\n"));
1074 }
1075 }
1076
1077 #[gpui_kit::test]
1078 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1079 let (handle, state) = mount_with(cx, true);
1080 let mut visual = VisualTestContext::from_window(handle, cx);
1081 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1082 visual.simulate_resize(size(px(width), px(height)));
1083 let window = Bounds {
1084 origin: point(px(0.), px(0.)),
1085 size: size(px(width), px(height)),
1086 };
1087 let inset = metrics(width, height).inset;
1088 for section in SETTINGS_SECTIONS {
1089 visual
1090 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1091 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1092 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1093 .into_iter()
1094 .filter(|(key, _)| key.starts_with("settings"))
1095 .chain(inset_violations(&tags, INSET_RULES))
1096 .collect();
1097 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1098 .iter()
1099 .any(|(exempt, _)| *exempt == section);
1100 if !scrolled_exempt {
1101 found.extend(scrolled_inset_violation(&mut visual));
1102 }
1103 let found: Vec<String> = found
1104 .into_iter()
1105 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1106 .collect();
1107 assert!(found.is_empty(), "{}", found.join("\n"));
1108 let dialog = visual
1109 .debug_bounds(SETTINGS_TAGS[0])
1110 .expect("settings dialog");
1111 let edges = [
1112 f32::from(dialog.left()),
1113 f32::from(dialog.top()),
1114 width - f32::from(dialog.right()),
1115 height - f32::from(dialog.bottom()),
1116 ];
1117 assert!(
1118 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1119 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1120 );
1121 }
1122 }
1123 }
1124
1125 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1126 let body = visual.debug_bounds(SETTINGS_BODY)?;
1127 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1128 if content.bottom() <= body.bottom() {
1129 return None;
1130 }
1131 visual.simulate_event(ScrollWheelEvent {
1132 position: body.center(),
1133 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1134 ..Default::default()
1135 });
1136 collect(visual, None);
1137 let body = visual.debug_bounds(SETTINGS_BODY)?;
1138 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1139 inset_violation(&SCROLLED_INSET_RULE, body, content)
1140 }
1141
1142 #[gpui_kit::test]
1143 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1144 let (handle, state) = mount(cx);
1145 let mut visual = VisualTestContext::from_window(handle, cx);
1146 for (width, height) in SIZES {
1147 visual.simulate_resize(size(px(width), px(height)));
1148 let window = Bounds {
1149 origin: point(px(0.), px(0.)),
1150 size: size(px(width), px(height)),
1151 };
1152 visual.update(|_, cx| {
1153 state.update(cx, |state, cx| {
1154 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1155 })
1156 });
1157 collect(&mut visual, Some(MEMBERS_BUTTON));
1158 let button = visual
1159 .debug_bounds(MEMBERS_BUTTON)
1160 .expect("members button rendered");
1161 visual.simulate_click(button.center(), Default::default());
1162 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1163 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1164 .into_iter()
1165 .filter(|(key, _)| key.starts_with("chat-members"))
1166 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1167 .collect();
1168 visual.simulate_keystrokes("escape");
1169 visual.run_until_parked();
1170 assert!(found.is_empty(), "{}", found.join("\n"));
1171 }
1172 }
1173
1174 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1175 collect(visual, Some(COMPOSER_SEND_TAG));
1176 let mut bounds_of = |path: &'static str| {
1177 visual
1178 .debug_bounds(path)
1179 .unwrap_or_else(|| panic!("{path} rendered"))
1180 };
1181 let composer = bounds_of(COMPOSER_BOX_TAG);
1182 let leading = bounds_of(COMPOSER_LEADING_TAG);
1183 let send = bounds_of(COMPOSER_SEND_TAG);
1184 [
1185 f32::from(leading.left() - composer.left()),
1186 f32::from(leading.top() - composer.top()),
1187 f32::from(composer.bottom() - leading.bottom()),
1188 f32::from(composer.right() - send.right()),
1189 f32::from(send.top() - composer.top()),
1190 f32::from(composer.bottom() - send.bottom()),
1191 ]
1192 }
1193
1194 #[gpui_kit::test]
1195 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
1196 let (handle, _) = mount(cx);
1197 let mut visual = VisualTestContext::from_window(handle, cx);
1198 visual.simulate_resize(size(px(1280.), px(800.)));
1199 let single_line = composer_button_insets(&mut visual);
1200 let left = single_line[0];
1201 assert!(
1202 single_line
1203 .iter()
1204 .all(|inset| (inset - left).abs() < TOLERANCE),
1205 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
1206 );
1207 let leading = visual
1208 .debug_bounds(COMPOSER_LEADING_TAG)
1209 .expect("leading buttons");
1210 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
1211 visual.simulate_click(
1212 point((leading.right() + send.left()) / 2., send.center().y),
1213 Default::default(),
1214 );
1215 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
1216 let three_lines = composer_button_insets(&mut visual);
1217 assert!(
1218 three_lines[1] > single_line[1] + 30.,
1219 "three lines did not grow the composer: {three_lines:?}"
1220 );
1221 for inset in [
1222 three_lines[0],
1223 three_lines[2],
1224 three_lines[3],
1225 three_lines[5],
1226 ] {
1227 assert!(
1228 (inset - left).abs() < TOLERANCE,
1229 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
1230 );
1231 }
1232 }
1233
1234 #[gpui_kit::test]
1235 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1236 let (handle, state) = mount_with(cx, true);
1237 let mut visual = VisualTestContext::from_window(handle, cx);
1238 for (width, height) in SIZES {
1239 visual.simulate_resize(size(px(width), px(height)));
1240 let window = Bounds {
1241 origin: point(px(0.), px(0.)),
1242 size: size(px(width), px(height)),
1243 };
1244 for (chat, expected_tags) in [
1245 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
1246 (REACTION_CHAT, &AGENT_TAGS[3..]),
1247 ] {
1248 visual.update(|_, cx| {
1249 state.update(cx, |state, cx| {
1250 state.select(Selection::Chat(chat.to_owned()), cx)
1251 })
1252 });
1253 let tags = collect(&mut visual, Some(expected_tags[0]));
1254 let mut expected = GUARDED.to_vec();
1255 expected.extend(expected_tags);
1256 let found: Vec<String> = violations(&tags, window, &expected)
1257 .into_iter()
1258 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
1259 .collect();
1260 assert!(found.is_empty(), "{}", found.join("\n"));
1261 }
1262 }
1263 }
1264}
1265
1266#[test]
1267fn lines_are_solid() {
1268 let mut files = Vec::new();
1269 for root in source_roots() {
1270 source_files(&root, &mut files);
1271 }
1272 let violations: Vec<String> = files
1273 .iter()
1274 .filter(|file| !file.ends_with("layout_guard.rs"))
1275 .flat_map(|file| {
1276 let source = fs::read_to_string(file).expect("read source file");
1277 source
1278 .lines()
1279 .enumerate()
1280 .filter(|(_, line)| {
1281 line.contains(".border_dashed(") || line.contains(".border_dotted(")
1282 })
1283 .map(|(index, line)| {
1284 format!(
1285 "{}:{}: lines are always solid: {}",
1286 file.display(),
1287 index + 1,
1288 line.trim()
1289 )
1290 })
1291 .collect::<Vec<_>>()
1292 })
1293 .collect();
1294 assert!(violations.is_empty(), "{}", violations.join("\n"));
1295}
1296
1297const STATE_RING_COLORS: &[&str] = &[
1298 "if focused",
1299 "if selected",
1300 "if speaking",
1301 "if current",
1302 "if open",
1303 "if state.failed",
1304];
1305const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
1306 (
1307 "notify/ring_view.rs",
1308 "theme::green()",
1309 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1310 ),
1311 (
1312 "notify/meeting_view.rs",
1313 "theme::accent()",
1314 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1315 ),
1316 (
1317 "notify/meeting_view.rs",
1318 "theme::border_strong()",
1319 "outlined button, not a surface",
1320 ),
1321 (
1322 "notify/toast.rs",
1323 "border)",
1324 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1325 ),
1326 (
1327 "notify/toast.rs",
1328 "theme::border_strong()",
1329 "OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1330 ),
1331 (
1332 "settings/mcp.rs",
1333 "theme::border_strong()",
1334 "outlined button, not a surface",
1335 ),
1336 (
1337 "settings/rows.rs",
1338 "theme::border_strong()",
1339 "outlined button, not a surface",
1340 ),
1341 (
1342 "views/card_widgets.rs",
1343 "border)",
1344 "message content drawn as Teams renders it",
1345 ),
1346 (
1347 "views/card_widgets.rs",
1348 "theme::border_strong()",
1349 "message content drawn as Teams renders it",
1350 ),
1351 ("views/shared_tab.rs", "theme::accent()", "input field"),
1352 ("views/card_input.rs", "if error.is_some()", "input field"),
1353 ("views/format_toolbar.rs", "if refused", "input field"),
1354 (
1355 "views/card_code_block.rs",
1356 "theme::code_header_border()",
1357 "message content drawn as Teams renders it",
1358 ),
1359 ("views/call_transcript.rs", "theme::border()", "input field"),
1360 (
1361 "views/conversation.rs",
1362 "theme::accent()",
1363 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1364 ),
1365 (
1366 "views/attachment_tray.rs",
1367 "theme::accent()",
1368 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1369 ),
1370 (
1371 "views/card_carousel.rs",
1372 "theme::border_strong()",
1373 "message content drawn as Teams renders it",
1374 ),
1375 (
1376 "views/card_table.rs",
1377 "grid_color",
1378 "message content drawn as Teams renders it",
1379 ),
1380 (
1381 "views/activity_panel.rs",
1382 "theme::surface()",
1383 "cutout ring in the background color, invisible against its surface",
1384 ),
1385 (
1386 "views/avatar.rs",
1387 "theme::surface()",
1388 "cutout ring in the background color, invisible against its surface",
1389 ),
1390 (
1391 "views/avatar.rs",
1392 "theme::text_muted()",
1393 "offline presence glyph, Teams icon",
1394 ),
1395 (
1396 "views/message_row.rs",
1397 "theme::border_strong()",
1398 "deleted message placeholder, Teams look",
1399 ),
1400 (
1401 "views/message_row.rs",
1402 "theme::red()",
1403 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1404 ),
1405 (
1406 "views/message_row.rs",
1407 "if row.delivery",
1408 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1409 ),
1410 (
1411 "views/new_meeting_dialog.rs",
1412 "theme::border()",
1413 "input field",
1414 ),
1415 (
1416 "views/call_mini_window.rs",
1417 "theme::border_strong()",
1418 "self view over live video, needs an edge on any picture",
1419 ),
1420 ("views/transfer_picker.rs", "theme::border()", "input field"),
1421 (
1422 "views/call_notice.rs",
1423 "theme::border_strong()",
1424 "outlined button, not a surface",
1425 ),
1426 (
1427 "views/composer/schedule.rs",
1428 "theme::accent()",
1429 "input field",
1430 ),
1431 (
1432 "views/call_mini.rs",
1433 "border)",
1434 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1435 ),
1436 (
1437 "views/sidebar.rs",
1438 "theme::accent()",
1439 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1440 ),
1441 (
1442 "views/adaptive_card.rs",
1443 "theme::border()",
1444 "message content drawn as Teams renders it",
1445 ),
1446 (
1447 "views/adaptive_card.rs",
1448 "border)",
1449 "message content drawn as Teams renders it",
1450 ),
1451 (
1452 "views/share_bar.rs",
1453 "theme::red()",
1454 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1455 ),
1456 ("settings_controls.rs", "if invalid", "input field"),
1457];
1458
1459fn outlines(source: &str) -> Vec<(usize, String)> {
1460 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
1461 pattern
1462 .find_iter(source)
1463 .map(|found| {
1464 let line_number = source[..found.start()].matches('\n').count() + 1;
1465 let after = &source[found.end()..];
1466 let color = after
1467 .find(".border_color(")
1468 .filter(|position| *position < 120)
1469 .map(|position| {
1470 let start = &after[position + ".border_color(".len()..];
1471 start
1472 .lines()
1473 .map(str::trim)
1474 .find(|line| !line.is_empty())
1475 .unwrap_or_default()
1476 .to_owned()
1477 })
1478 .unwrap_or_default();
1479 (line_number, color)
1480 })
1481 .collect()
1482}
1483
1484#[test]
1485fn outline_matcher_reads_the_border_color() {
1486 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
1487 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
1488}
1489
1490#[test]
1491fn surfaces_are_soft() {
1492 let mut matched_allowlist = HashSet::new();
1493 let mut violations = Vec::new();
1494 for root in source_roots() {
1495 let mut files = Vec::new();
1496 source_files(&root, &mut files);
1497 for file in files {
1498 let relative = file
1499 .strip_prefix(&root)
1500 .expect("inside src")
1501 .to_string_lossy()
1502 .replace('\\', "/");
1503 if relative == "layout_guard.rs" {
1504 continue;
1505 }
1506 let source = fs::read_to_string(&file).expect("read source file");
1507 for (line_number, color) in outlines(&source) {
1508 if STATE_RING_COLORS
1509 .iter()
1510 .any(|prefix| color.starts_with(prefix))
1511 {
1512 continue;
1513 }
1514 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
1515 *allowed_file == relative && color.starts_with(prefix)
1516 }) {
1517 Some(position) => {
1518 matched_allowlist.insert(position);
1519 }
1520 None => violations.push(format!(
1521 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
1522 )),
1523 }
1524 }
1525 }
1526 }
1527 let stale = OUTLINE_ALLOWLIST
1528 .iter()
1529 .enumerate()
1530 .filter(|(position, _)| !matched_allowlist.contains(position))
1531 .map(|(_, (file, prefix, _))| {
1532 format!("stale outline allowlist entry, remove it: {file} {prefix}")
1533 });
1534 let report: Vec<String> = violations.into_iter().chain(stale).collect();
1535 assert!(report.is_empty(), "{}", report.join("\n"));
1536}
1537
1538fn indentation(line: &str) -> usize {
1539 line.len() - line.trim_start().len()
1540}
1541
1542fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
1543 let indent = indentation(lines[index]);
1544 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
1545 let start = lines[..index]
1546 .iter()
1547 .rposition(|line| !belongs(line))
1548 .map_or(0, |position| position + 1);
1549 let end = lines[index..]
1550 .iter()
1551 .position(|line| !belongs(line))
1552 .map_or(lines.len(), |position| index + position);
1553 lines[start..end]
1554 .iter()
1555 .filter(|line| indentation(line) == indent)
1556 .copied()
1557 .collect()
1558}
1559
1560fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
1561 let lines: Vec<&str> = source.lines().collect();
1562 (0..lines.len())
1563 .filter(|&index| row_height.is_match(lines[index]))
1564 .filter(|&index| {
1565 !chain_lines(&lines, index).iter().any(|line| {
1566 let line = line.trim();
1567 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
1568 })
1569 })
1570 .map(|index| index + 1)
1571 .collect()
1572}
1573
1574fn row_height_pattern() -> Regex {
1575 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
1576}
1577
1578#[test]
1579fn matcher_finds_rows_without_flex_none() {
1580 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";
1581 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
1582}
1583
1584#[test]
1585fn fixed_height_rows_never_shrink() {
1586 let row_height = row_height_pattern();
1587 let mut files = Vec::new();
1588 for root in source_roots() {
1589 source_files(&root, &mut files);
1590 }
1591 let violations: Vec<String> = files
1592 .iter()
1593 .filter(|file| !file.ends_with("layout_guard.rs"))
1594 .flat_map(|file| {
1595 let source = fs::read_to_string(file).expect("read source file");
1596 shrinking_rows(&row_height, &source)
1597 .into_iter()
1598 .map(|line| format!("{}:{line}", file.display()))
1599 .collect::<Vec<_>>()
1600 })
1601 .collect();
1602 assert!(
1603 violations.is_empty(),
1604 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
1605 );
1606}