BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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