BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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