BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 55.0 KiB Download Raw
1use std::path::PathBuf;
2use std::sync::{Arc, OnceLock};
3use std::time::Instant;
4
5use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6use gpui_kit::Image;
7use store::{
8 ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,
9 TeamLayoutRecord, TeamRecord,
10};
11use teams_core::{
12 CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13 PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind,
14};
15
16use crate::activity::{Actor, Entry, Kind};
17use crate::app_state::{AppState, Selection};
18use crate::card_actions::{CardAnswer, CardTask};
19use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
20use crate::demo_gifs;
21use crate::message_actions::ForwardSource;
22
23static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
24
25pub const DEMO_USER_ID: &str = "demo-me";
26const DEMO_USER_NAME: &str = "Dana Demo";
27const PHOTO_SIZE: usize = 48;
28const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
29const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
30const STAGING_SIZE: (usize, usize) = (960, 540);
31const LINK_IMAGE_KEY: &str =
32 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo";
33const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
34const PRIORITY_CHAT: &str = "demo-chat-priya";
35const BOT_CHAT: &str = "demo-chat-wiki-bot";
36const BOT_NAME: &str = "Wiki Bot";
37const BOT_APP_NAME: &str = "Wiki Cloud";
38const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
39const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
40const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
41const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
42const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
43const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
44 (
45 MARA_ID,
46 "Mara Lindqvist",
47 "Product Owner",
48 "mara.lindqvist@example.com",
49 ),
50 (
51 JONAS_ID,
52 "Jonas Ortega",
53 "Backend Engineer",
54 "jonas.ortega@example.com",
55 ),
56 (
57 PRIYA_ID,
58 "Priya Nair",
59 "Engineering Manager",
60 "priya.nair@example.com",
61 ),
62 (
63 LEA_ID,
64 "Lea Schneider",
65 "Customer Success",
66 "lea.schneider@example.com",
67 ),
68 (
69 TOBIAS_ID,
70 "Tobias Klein",
71 "Support Engineer",
72 "tobias.klein@example.com",
73 ),
74];
75
76struct Palette {
77 background: [u8; 3],
78 skin: [u8; 3],
79 hair: [u8; 3],
80 shirt: [u8; 3],
81}
82
83const MARA: Palette = Palette {
84 background: [0x3f, 0x5f, 0x7a],
85 skin: [0xe0, 0xb2, 0x93],
86 hair: [0xd9, 0xa4, 0x41],
87 shirt: [0x1e, 0x29, 0x3b],
88};
89const PRIYA: Palette = Palette {
90 background: [0x4b, 0x3b, 0x5c],
91 skin: [0x9a, 0x6a, 0x4a],
92 hair: [0x1c, 0x19, 0x17],
93 shirt: [0xbe, 0x12, 0x3c],
94};
95const TOBIAS: Palette = Palette {
96 background: [0x3b, 0x4a, 0x3f],
97 skin: [0xf1, 0xc7, 0xa5],
98 hair: [0x57, 0x53, 0x4e],
99 shirt: [0x0f, 0x76, 0x6e],
100};
101
102const MARA_ID: &str = "demo-mara";
103const JONAS_ID: &str = "demo-jonas";
104const PRIYA_ID: &str = "demo-priya";
105const LEA_ID: &str = "demo-lea";
106const TOBIAS_ID: &str = "demo-tobias";
107
108const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
109 (
110 "demo-team-1",
111 "Platform",
112 ["General", "Incidents", "Releases"],
113 ),
114 ("demo-team-2", "Product", ["General", "Roadmap", "Feedback"]),
115 (
116 "demo-team-3",
117 "Operations",
118 ["General", "On call", "Runbooks"],
119 ),
120 (
121 "demo-team-4",
122 "Archive 2025",
123 ["General", "Trade fair", "Office move"],
124 ),
125];
126const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
127const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
128const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
129
130const UNREAD_CHAT: &str = "demo-chat-atlas";
131const RELEASE_CHAT: &str = "demo-chat-release";
132const PINNED_MESSAGE: &str = "m5b";
133const SAVED_MESSAGES: [&str; 2] = ["m4", "m5c"];
134const FORWARD_ITEMTYPE: &str = "http://schema.skype.com/Forward";
135const FAVORITES_ID: &str = "demo-folder-favorites";
136const CUSTOMERS_FOLDER: &str = "demo-folder-customers";
137const ATLAS_FOLDER: &str = "demo-folder-atlas";
138const TODO_FOLDER: &str = "demo-folder-todo";
139
140fn member(user_id: &str, name: &str) -> MemberRecord {
141 MemberRecord {
142 user_id: Some(user_id.to_owned()),
143 display_name: name.to_owned(),
144 }
145}
146
147fn people(extra: &[(&str, &str)]) -> Vec<MemberRecord> {
148 std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
149 .chain(extra.iter().map(|(id, name)| member(id, name)))
150 .collect()
151}
152
153pub fn at(days_ago: i64, hour: u32, minute: u32) -> DateTime<Utc> {
154 let day = Local::now().date_naive() - Duration::days(days_ago);
155 let local = day.and_hms_opt(hour, minute, 0).expect("valid time");
156 Local
157 .from_local_datetime(&local)
158 .earliest()
159 .map_or_else(Utc::now, |time| time.with_timezone(&Utc))
160}
161
162struct DemoChat {
163 id: &'static str,
164 kind: &'static str,
165 title: &'static str,
166 members: Vec<MemberRecord>,
167 time: DateTime<Utc>,
168 unread: bool,
169 preview: Option<(&'static str, &'static str, &'static str)>,
170 deleted: bool,
171}
172
173fn demo_chats() -> Vec<DemoChat> {
174 let group = |extra: &[(&str, &str)]| people(extra);
175 vec![
176 DemoChat {
177 id: BOT_CHAT,
178 kind: "oneOnOne",
179 title: BOT_NAME,
180 members: people(&[]),
181 time: at(0, 13, 45),
182 unread: true,
183 preview: Some(("", BOT_NAME, "Mara Lindqvist edited your page")),
184 deleted: false,
185 },
186 DemoChat {
187 id: "demo-chat-mara",
188 kind: "oneOnOne",
189 title: "Mara Lindqvist",
190 members: people(&[(MARA_ID, "Mara Lindqvist")]),
191 time: at(0, 13, 40),
192 unread: false,
193 preview: Some((MARA_ID, "Mara Lindqvist", "Sure, 2 pm works")),
194 deleted: false,
195 },
196 DemoChat {
197 id: RELEASE_CHAT,
198 kind: "group",
199 title: "Release planning",
200 members: group(&[
201 (MARA_ID, "Mara Lindqvist"),
202 (JONAS_ID, "Jonas Ortega"),
203 (PRIYA_ID, "Priya Nair"),
204 (LEA_ID, "Lea Schneider"),
205 ]),
206 time: at(0, 13, 35),
207 unread: false,
208 preview: Some((
209 DEMO_USER_ID,
210 DEMO_USER_NAME,
211 "Build 42 is green, see pipeline",
212 )),
213 deleted: false,
214 },
215 DemoChat {
216 id: "demo-chat-customer-1",
217 kind: "group",
218 title: "Customer North - Operations",
219 members: group(&[(LEA_ID, "Lea Schneider"), (TOBIAS_ID, "Tobias Klein")]),
220 time: at(0, 12, 50),
221 unread: true,
222 preview: Some((LEA_ID, "Lea Schneider", "Access is enabled now")),
223 deleted: false,
224 },
225 DemoChat {
226 id: "demo-chat-customer-2",
227 kind: "group",
228 title: "Customer South - Rollout",
229 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
230 time: at(0, 9, 5),
231 unread: true,
232 preview: Some((JONAS_ID, "Jonas Ortega", "Meeting is set for Friday")),
233 deleted: false,
234 },
235 DemoChat {
236 id: "demo-chat-customer-3",
237 kind: "group",
238 title: "Customer West - Support",
239 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
240 time: at(1, 16, 0),
241 unread: false,
242 preview: Some((TOBIAS_ID, "Tobias Klein", "Ticket is closed")),
243 deleted: false,
244 },
245 DemoChat {
246 id: "demo-chat-customer-4",
247 kind: "group",
248 title: "Customer East - Pilot",
249 members: group(&[(MARA_ID, "Mara Lindqvist"), (PRIYA_ID, "Priya Nair")]),
250 time: at(3, 10, 0),
251 unread: false,
252 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "I'll send the documents")),
253 deleted: false,
254 },
255 DemoChat {
256 id: "demo-chat-atlas",
257 kind: "group",
258 title: "Atlas core team",
259 members: group(&[
260 (PRIYA_ID, "Priya Nair"),
261 (LEA_ID, "Lea Schneider"),
262 (MARA_ID, "Mara Lindqvist"),
263 ]),
264 time: at(0, 13, 12),
265 unread: true,
266 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
267 deleted: false,
268 },
269 DemoChat {
270 id: "demo-chat-jonas",
271 kind: "oneOnOne",
272 title: "Jonas Ortega",
273 members: people(&[(JONAS_ID, "Jonas Ortega")]),
274 time: at(0, 11, 2),
275 unread: false,
276 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Thanks, it's merged")),
277 deleted: false,
278 },
279 DemoChat {
280 id: "demo-chat-priya",
281 kind: "oneOnOne",
282 title: "Priya Nair",
283 members: people(&[(PRIYA_ID, "Priya Nair")]),
284 time: at(0, 10, 47),
285 unread: false,
286 preview: Some((PRIYA_ID, "Priya Nair", "Image")),
287 deleted: false,
288 },
289 DemoChat {
290 id: "demo-chat-tobias",
291 kind: "oneOnOne",
292 title: "Tobias Klein",
293 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
294 time: at(2, 9, 30),
295 unread: false,
296 preview: Some((TOBIAS_ID, "Tobias Klein", "ok")),
297 deleted: false,
298 },
299 DemoChat {
300 id: "demo-chat-allhands",
301 kind: "group",
302 title: "All-hands announcements",
303 members: group(&[(LEA_ID, "Lea Schneider"), (MARA_ID, "Mara Lindqvist")]),
304 time: at(0, 9, 0),
305 unread: true,
306 preview: Some((LEA_ID, "Lea Schneider", "New vacation policy from November")),
307 deleted: false,
308 },
309 DemoChat {
310 id: "demo-chat-design",
311 kind: "group",
312 title: "Design review",
313 members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
314 time: at(2, 15, 0),
315 unread: false,
316 preview: Some((MARA_ID, "Mara Lindqvist", "alt")),
317 deleted: true,
318 },
319 DemoChat {
320 id: "demo-chat-quarterly",
321 kind: "group",
322 title: "Quarterly numbers, finance review and planning 2027",
323 members: group(&[(LEA_ID, "Lea Schneider"), (JONAS_ID, "Jonas Ortega")]),
324 time: at(4, 11, 0),
325 unread: false,
326 preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),
327 deleted: false,
328 },
329 ]
330}
331
332pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCandidate> {
333 let needle = query.trim().to_lowercase();
334 let matches = |name: &str| needle.is_empty() || name.to_lowercase().contains(&needle);
335 let people = PEOPLE_DIRECTORY
336 .iter()
337 .filter(|(_, name, _, _)| matches(name))
338 .map(|(user_id, name, job_title, mail)| {
339 MentionCandidate::Person(PersonCandidate {
340 user_id: (*user_id).to_owned(),
341 display_name: (*name).to_owned(),
342 mail: Some((*mail).to_owned()),
343 job_title: Some((*job_title).to_owned()),
344 source: PersonSource::Member,
345 })
346 });
347 let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {
348 [
349 MentionCandidate::Channel {
350 channel_id: conversation_id.to_owned(),
351 name: "General".to_owned(),
352 },
353 MentionCandidate::Team {
354 team_id: "demo-team-1".to_owned(),
355 name: "Platform".to_owned(),
356 },
357 ]
358 .into_iter()
359 .filter(|candidate| matches(candidate.display_name()))
360 .collect()
361 } else {
362 Vec::new()
363 };
364 people.chain(scope).collect()
365}
366
367pub fn send_in_chat(
368 chat: &ChatRecord,
369 preview: &str,
370 html: &str,
371 now: DateTime<Utc>,
372) -> (ChatRecord, MessageRecord) {
373 let mut chat = chat.clone();
374 chat.last_message_at = Some(now);
375 chat.last_message_preview = Some(preview.to_owned());
376 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
377 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
378 chat.last_message_deleted = false;
379 chat.unread = false;
380 let record = message(
381 &chat.id,
382 &format!("demo-sent-{}", now.timestamp_millis()),
383 None,
384 (DEMO_USER_ID, DEMO_USER_NAME),
385 now,
386 html,
387 "[]",
388 false,
389 );
390 (chat, record)
391}
392
393pub fn new_chat(
394 existing: &[ChatRecord],
395 people: &[(String, String)],
396 topic: Option<&str>,
397 preview: &str,
398 html: &str,
399 now: DateTime<Utc>,
400) -> (ChatRecord, MessageRecord) {
401 let number = existing
402 .iter()
403 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
404 .count()
405 + 1;
406 let one_on_one = people.len() == 1;
407 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
408 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
409 .collect();
410 let chat = ChatRecord {
411 id: format!("{NEW_CHAT_PREFIX}{number}"),
412 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
413 title: if one_on_one {
414 String::new()
415 } else {
416 topic.unwrap_or_default().to_owned()
417 },
418 member_summary: people
419 .iter()
420 .map(|(_, name)| name.as_str())
421 .collect::<Vec<_>>()
422 .join(", "),
423 members,
424 ..Default::default()
425 };
426 send_in_chat(&chat, preview, html, now)
427}
428
429fn image_directory() -> PathBuf {
430 std::env::temp_dir().join("rusty-teams-demo")
431}
432
433pub fn search_gifs(query: &str) -> Vec<Gif> {
434 let query = query.trim().to_lowercase();
435 SEARCHABLE_GIFS
436 .get()
437 .into_iter()
438 .flatten()
439 .filter(|gif| gif.title.to_lowercase().contains(&query))
440 .cloned()
441 .collect()
442}
443
444pub fn first_unread(conversation_id: &str) -> Option<String> {
445 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
446}
447
448pub fn read_message_ids(records: &[MessageRecord]) -> std::collections::HashSet<String> {
449 let newest = records.iter().max_by_key(|record| record.created_at);
450 records
451 .iter()
452 .filter(|record| {
453 Some(record.message_id.as_str()) != newest.map(|newest| newest.message_id.as_str())
454 })
455 .map(|record| record.message_id.clone())
456 .collect()
457}
458
459pub fn first_selection() -> Selection {
460 Selection::Chat(RELEASE_CHAT.to_owned())
461}
462
463pub fn activity_entries() -> Vec<Entry> {
464 let actor = |user_id: &str, name: &str| Actor {
465 user_id: Some(user_id.to_owned()),
466 name: name.to_owned(),
467 };
468 let entry = |conversation_id: &str,
469 kind: Kind,
470 message_id: &str,
471 actors: Vec<Actor>,
472 preview: &str,
473 count: u32,
474 updated_at: DateTime<Utc>,
475 read: bool| Entry {
476 id: 0,
477 conversation_id: conversation_id.to_owned(),
478 kind,
479 message_id: message_id.to_owned(),
480 actors,
481 preview: preview.to_owned(),
482 glyphs: Vec::new(),
483 count,
484 updated_at,
485 read,
486 };
487 let reaction = Entry {
488 glyphs: vec!["\u{1F602}".to_owned(), "\u{1F44D}".to_owned()],
489 ..entry(
490 RELEASE_CHAT,
491 Kind::Reaction,
492 "m3",
493 vec![
494 actor(PRIYA_ID, "Priya Nair"),
495 actor(LEA_ID, "Lea Schneider"),
496 ],
497 "I'll take the changelog.",
498 2,
499 at(0, 13, 20),
500 false,
501 )
502 };
503 vec![
504 entry(
505 UNREAD_CHAT,
506 Kind::Messages,
507 "u3",
508 vec![
509 actor(LEA_ID, "Lea Schneider"),
510 actor(PRIYA_ID, "Priya Nair"),
511 ],
512 "Who is taking the review?",
513 3,
514 at(0, 13, 12),
515 false,
516 ),
517 entry(
518 "demo-channel-1-1",
519 Kind::Mention,
520 "t1",
521 vec![actor(MARA_ID, "Mara Lindqvist")],
522 "@Dana can you approve the merge? The pipeline is waiting.",
523 1,
524 at(0, 11, 40),
525 false,
526 ),
527 reaction,
528 entry(
529 "demo-chat-customer-3",
530 Kind::Messages,
531 "demo-customer-3-closed",
532 vec![actor(TOBIAS_ID, "Tobias Klein")],
533 "Ticket is closed",
534 1,
535 at(1, 16, 0),
536 true,
537 ),
538 ]
539}
540
541pub fn seed(store: &Store) {
542 let chats: Vec<ChatRecord> = demo_chats()
543 .into_iter()
544 .map(|demo| ChatRecord {
545 id: demo.id.to_owned(),
546 kind: demo.kind.to_owned(),
547 title: if demo.kind == "oneOnOne" {
548 String::new()
549 } else {
550 demo.title.to_owned()
551 },
552 member_summary: demo.title.to_owned(),
553 last_message_at: Some(demo.time),
554 unread: demo.unread,
555 members: demo.members,
556 last_message_preview: demo.preview.map(|(_, _, text)| text.to_owned()),
557 last_message_sender_id: demo.preview.map(|(id, _, _)| id.to_owned()),
558 last_message_sender_name: demo.preview.map(|(_, name, _)| name.to_owned()),
559 last_message_deleted: demo.deleted,
560 ..Default::default()
561 })
562 .collect();
563 let _ = store.upsert_chats(&chats);
564 let teams: Vec<TeamRecord> = DEMO_TEAMS
565 .iter()
566 .map(|(id, name, _)| TeamRecord {
567 id: (*id).to_owned(),
568 name: (*name).to_owned(),
569 })
570 .collect();
571 let _ = store.upsert_teams(&teams);
572 let mut channels = Vec::new();
573 for (team_index, (team_id, _, names)) in DEMO_TEAMS.iter().enumerate() {
574 for (channel_index, name) in names.iter().enumerate() {
575 channels.push(ChannelRecord {
576 id: format!("demo-channel-{}-{}", team_index + 1, channel_index + 1),
577 team_id: (*team_id).to_owned(),
578 name: (*name).to_owned(),
579 membership_type: None,
580 last_message_at: Some(at(channel_index as i64, 12, 10)),
581 unread: (team_index == 0 && channel_index == 1)
582 || (team_index == 1 && channel_index == 0),
583 });
584 }
585 }
586 let _ = store.upsert_channels(&channels);
587 let _ = store.replace_team_layout(&demo_team_layout(&channels));
588 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
589 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
590 let _ = store.upsert_messages(&release_messages());
591 let _ = store.upsert_messages(&unread_messages());
592 let _ = store.upsert_messages(&channel_messages());
593 let _ = store.upsert_messages(&priority_messages());
594 let _ = store.upsert_messages(&bot_messages());
595}
596
597fn photo(palette: &Palette) -> Arc<Image> {
598 crate::data::avatar_image_from("image/png", encode_png(palette))
599}
600
601pub fn seed_directory(state: &mut AppState) {
602 let directory = &mut state.directory;
603 directory.me = Some(Person {
604 user_id: DEMO_USER_ID.to_owned(),
605 display_name: DEMO_USER_NAME.to_owned(),
606 });
607 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
608 directory.folders = vec![
609 FolderInfo {
610 id: FAVORITES_ID.to_owned(),
611 name: String::new(),
612 kind: FolderKind::Favorites,
613 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
614 },
615 FolderInfo {
616 id: CUSTOMERS_FOLDER.to_owned(),
617 name: "Customers".to_owned(),
618 kind: FolderKind::UserCreated,
619 conversation_ids: ids(&[
620 "demo-chat-customer-1",
621 "demo-chat-customer-2",
622 "demo-chat-customer-3",
623 "demo-chat-customer-4",
624 ]),
625 },
626 FolderInfo {
627 id: ATLAS_FOLDER.to_owned(),
628 name: "Project Atlas".to_owned(),
629 kind: FolderKind::UserCreated,
630 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
631 },
632 FolderInfo {
633 id: TODO_FOLDER.to_owned(),
634 name: "To do".to_owned(),
635 kind: FolderKind::UserCreated,
636 conversation_ids: Vec::new(),
637 },
638 ];
639 state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);
640 let directory = &mut state.directory;
641 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
642 directory
643 .unread_counts
644 .insert("demo-chat-atlas".to_owned(), 5);
645 directory
646 .unread_counts
647 .insert("demo-chat-customer-1".to_owned(), 2);
648 directory
649 .unread_counts
650 .insert("demo-chat-customer-2".to_owned(), 1);
651 directory
652 .unread_counts
653 .insert("demo-chat-allhands".to_owned(), 120);
654 directory.set_avatar(MARA_ID, Some(photo(&MARA)));
655 directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
656 directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
657 for (user_id, kind) in [
658 (MARA_ID, PresenceKind::Available),
659 (JONAS_ID, PresenceKind::DoNotDisturb),
660 (PRIYA_ID, PresenceKind::Away),
661 (TOBIAS_ID, PresenceKind::Offline),
662 (LEA_ID, PresenceKind::DoNotDisturb),
663 (DEMO_USER_ID, PresenceKind::Available),
664 ] {
665 directory.set_presence(user_id, kind);
666 }
667 let directory_path = image_directory();
668 if std::fs::create_dir_all(&directory_path).is_ok() {
669 let path = directory_path.join("staging-dashboard.png");
670 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
671 if std::fs::write(&path, png).is_ok() {
672 state.directory.set_image(STAGING_IMAGE_KEY, &path);
673 state.directory.set_image(LINK_IMAGE_KEY, &path);
674 }
675 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
676 state.directory.set_image(
677 demo_gifs::RECEIVED_GIF_KEY,
678 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
679 );
680 }
681 state.typing.start(
682 "demo-chat-mara",
683 MARA_ID,
684 "Mara Lindqvist",
685 Instant::now(),
686 Utc::now(),
687 );
688 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
689 state.last_sync = Some(Utc::now());
690 state.apply_bot_titles();
691 seed_message_actions(state);
692}
693
694fn seed_message_actions(state: &mut AppState) {
695 state.pins.insert(
696 RELEASE_CHAT.to_owned(),
697 vec![PinnedMessage {
698 message_id: PINNED_MESSAGE.to_owned(),
699 pinned_at: Some(at(0, 11, 30)),
700 parent_id: None,
701 }],
702 );
703 let ids: Vec<String> = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect();
704 let records = state
705 .store
706 .messages_by_id(RELEASE_CHAT, &ids)
707 .unwrap_or_default();
708 let saved = SAVED_MESSAGES
709 .iter()
710 .enumerate()
711 .filter_map(|(position, id)| {
712 let record = records.get(*id)?;
713 Some(SavedMessage {
714 conversation_id: record.conversation_id.clone(),
715 message_id: record.message_id.clone(),
716 root_id: record.message_id.clone(),
717 author_id: record.sender_id.clone(),
718 author_name: record.sender_name.clone(),
719 preview: crate::rows::reply_excerpt(record),
720 saved_at: at(position as i64, 15, 20),
721 topic: None,
722 })
723 })
724 .collect();
725 state.saved.replace(saved);
726}
727
728pub fn forwarded_message(
729 chat: &ChatRecord,
730 source: &ForwardSource,
731 comment: &str,
732 now: DateTime<Utc>,
733) -> (ChatRecord, MessageRecord) {
734 let comment_html = if comment.is_empty() {
735 String::new()
736 } else {
737 format!("<p>{}</p>", teams_core::escape_html(comment))
738 };
739 let html = format!(
740 "{comment_html}<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
741 teams_core::escape_html(&source.message_id),
742 teams_core::escape_html(&source.author),
743 teams_core::escape_html(&source.text),
744 );
745 send_in_chat(chat, &source.text, &html, now)
746}
747
748#[allow(clippy::too_many_arguments)]
749fn message(
750 conversation: &str,
751 id: &str,
752 reply_to: Option<&str>,
753 sender: (&str, &str),
754 time: DateTime<Utc>,
755 html: &str,
756 reactions_json: &str,
757 edited: bool,
758) -> MessageRecord {
759 MessageRecord {
760 conversation_id: conversation.to_owned(),
761 message_id: id.to_owned(),
762 reply_to_id: reply_to.map(str::to_owned),
763 sender_id: Some(sender.0.to_owned()),
764 sender_name: Some(sender.1.to_owned()),
765 sender_application_id: None,
766 links_json: "[]".to_owned(),
767 created_at: time,
768 edited_at: edited.then_some(time + Duration::minutes(2)),
769 deleted: false,
770 body_html: html.to_owned(),
771 attachments_json: "[]".to_owned(),
772 reactions_json: reactions_json.to_owned(),
773 mentions_json: "[]".to_owned(),
774 subject: None,
775 }
776}
777
778fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
779 record.subject = Some(subject.to_owned());
780 record
781}
782
783fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
784 record.attachments_json = attachments_json.to_owned();
785 record
786}
787
788fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
789 record.links_json = links_json;
790 record
791}
792
793pub fn link_preview(url: &str) -> Option<LinkPreview> {
794 Some(LinkPreview {
795 url: url.to_owned(),
796 title: Some("Release checklist Q4".to_owned()),
797 description: Some(
798 "Everything that has to be green before the release candidate goes out on Friday."
799 .to_owned(),
800 ),
801 image_url: Some(LINK_IMAGE_KEY.to_owned()),
802 image_width: Some(LINK_IMAGE_SIZE.0),
803 image_height: Some(LINK_IMAGE_SIZE.1),
804 })
805}
806
807fn bot_messages() -> Vec<MessageRecord> {
808 let card = serde_json::json!({
809 "type": "AdaptiveCard",
810 "body": [
811 {"type": "ColumnSet", "columns": [
812 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
813 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
814 ]},
815 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
816 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
817 ]}
818 ]},
819 {"type": "ColumnSet", "separator": true, "columns": [
820 {"type": "Column", "width": "auto", "items": [
821 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
822 ]},
823 {"type": "Column", "width": "stretch", "items": [
824 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
825 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
826 ]}
827 ]},
828 {"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},
829 {"type": "ActionSet", "actions": [
830 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
831 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
832 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
833 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},
834 {"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},
835 {"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},
836 {"type": "Action.ShowCard", "title": "Details", "card": {"body": [
837 {"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}
838 ]}}
839 ]}
840 ]
841 });
842 vec![
843 bot_card_message("b1", at(0, 13, 45), &card),
844 bot_card_message("b2", at(0, 13, 52), &input_card()),
845 ]
846}
847
848fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
849 let attachments = serde_json::json!([{
850 "content_type": "application/vnd.microsoft.card.adaptive",
851 "name": null,
852 "url": null,
853 "text": null,
854 "content": card.to_string()
855 }]);
856 let mut record = with_attachments(
857 message(
858 BOT_CHAT,
859 id,
860 None,
861 ("", BOT_NAME),
862 time,
863 &format!("<attachment id=\"{id}\"></attachment>"),
864 "[]",
865 false,
866 ),
867 &attachments.to_string(),
868 );
869 record.sender_id = None;
870 record.sender_application_id = Some(BOT_ID.to_owned());
871 record
872}
873
874fn input_card() -> serde_json::Value {
875 serde_json::json!({
876 "type": "AdaptiveCard",
877 "body": [
878 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
879 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
880 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
881 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
882 {"type": "ColumnSet", "columns": [
883 {"type": "Column", "width": "stretch", "items": [
884 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
885 ]},
886 {"type": "Column", "width": "stretch", "items": [
887 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
888 ]},
889 {"type": "Column", "width": "stretch", "items": [
890 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
891 ]}
892 ]},
893 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
894 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
895 ]},
896 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
897 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
898 ]},
899 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
900 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
901 ]},
902 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
903 ],
904 "actions": [
905 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
906 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
907 ]
908 })
909}
910
911fn bot_app() -> ChatApp {
912 ChatApp {
913 app_id: "demo-app-wiki".to_owned(),
914 name: BOT_APP_NAME.to_owned(),
915 bot_ids: vec![BOT_ID.to_owned()],
916 small_image_url: None,
917 accent_color: None,
918 web_application_resource: None,
919 }
920}
921
922pub async fn card_answer(task: CardTask) -> CardAnswer {
923 tokio::time::sleep(CARD_ANSWER_DELAY).await;
924 let data = match task {
925 CardTask::Submit(_) => {
926 return Ok((
927 CardActionOutcome::Message("Settings saved".into()),
928 Some((bot_app(), BOT_ID.to_owned())),
929 ));
930 }
931 CardTask::Action(action) => match action.invoke_payload() {
932 Some(payload) => payload.value,
933 None => return Err("Not supported".to_owned()),
934 },
935 };
936 let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")
937 {
938 CardActionOutcome::Dialog(TaskDialog {
939 title: None,
940 width: 520,
941 height: 300,
942 kind: TaskDialogKind::Card(settings_card().to_string()),
943 })
944 } else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {
945 CardActionOutcome::Failed("The app answered 500: demo failure".into())
946 } else {
947 CardActionOutcome::Sent
948 };
949 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
950}
951
952fn settings_card() -> serde_json::Value {
953 serde_json::json!({
954 "type": "AdaptiveCard",
955 "body": [
956 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
957 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
958 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
959 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
960 ]},
961 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
962 ],
963 "actions": [
964 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
965 ]
966 })
967}
968
969fn priority_messages() -> Vec<MessageRecord> {
970 let priya = (PRIYA_ID, "Priya Nair");
971 let me = (DEMO_USER_ID, DEMO_USER_NAME);
972 vec![
973 message(
974 PRIORITY_CHAT,
975 "p1",
976 None,
977 me,
978 at(0, 10, 40),
979 "<p>Have you seen the error on staging yet?</p>",
980 "[]",
981 false,
982 ),
983 message(
984 PRIORITY_CHAT,
985 "p2",
986 None,
987 priya,
988 at(0, 10, 47),
989 &format!(
990 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
991 ),
992 "[]",
993 false,
994 ),
995 ]
996}
997
998fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
999 users
1000 .iter()
1001 .map(|(user_id, user_name, created_at)| {
1002 serde_json::json!({
1003 "reaction_type": kind,
1004 "user_id": user_id,
1005 "user_name": user_name,
1006 "created_at": created_at,
1007 })
1008 })
1009 .collect()
1010}
1011
1012fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
1013 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
1014}
1015
1016fn release_messages() -> Vec<MessageRecord> {
1017 let chat = RELEASE_CHAT;
1018 let mara = (MARA_ID, "Mara Lindqvist");
1019 let jonas = (JONAS_ID, "Jonas Ortega");
1020 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1021 let jonas_name = "Jonas Ortega";
1022 let priya_name = "Priya Nair";
1023 let lea_name = "Lea Schneider";
1024 let mara_name = "Mara Lindqvist";
1025 let tobias_name = "Tobias Klein";
1026 let likes = reactions_json(vec![reaction(
1027 "like",
1028 &[
1029 (JONAS_ID, jonas_name, at(1, 16, 30)),
1030 (PRIYA_ID, priya_name, at(1, 17, 2)),
1031 (LEA_ID, lea_name, at(0, 8, 15)),
1032 ],
1033 )]);
1034 let hearts = reactions_json(vec![reaction(
1035 "heart",
1036 &[
1037 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
1038 (JONAS_ID, jonas_name, at(0, 10, 33)),
1039 ],
1040 )]);
1041 let single = reactions_json(vec![reaction(
1042 "laugh",
1043 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
1044 )]);
1045 let many = reactions_json(vec![
1046 reaction(
1047 "like",
1048 &[
1049 (MARA_ID, mara_name, at(0, 13, 37)),
1050 (JONAS_ID, jonas_name, at(0, 13, 38)),
1051 (PRIYA_ID, priya_name, at(0, 13, 40)),
1052 (LEA_ID, lea_name, at(0, 13, 45)),
1053 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
1054 ],
1055 ),
1056 reaction(
1057 "heart",
1058 &[
1059 (LEA_ID, lea_name, at(0, 13, 46)),
1060 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
1061 ],
1062 ),
1063 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
1064 ]);
1065 vec![
1066 message(
1067 chat,
1068 "m1",
1069 None,
1070 mara,
1071 at(1, 16, 20),
1072 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
1073 "[]",
1074 false,
1075 ),
1076 message(
1077 chat,
1078 "m2",
1079 None,
1080 mara,
1081 at(1, 16, 22),
1082 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
1083 &likes,
1084 false,
1085 ),
1086 with_links(
1087 message(
1088 chat,
1089 "m2a",
1090 None,
1091 mara,
1092 at(1, 16, 23),
1093 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1094 "[]",
1095 false,
1096 ),
1097 link_preview("https://example.com/checklist")
1098 .map(|preview| preview.links_json())
1099 .unwrap_or_default(),
1100 ),
1101 message(
1102 chat,
1103 "m2b",
1104 None,
1105 mara,
1106 at(1, 16, 40),
1107 &format!(
1108 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
1109 STAGING_SIZE.0, STAGING_SIZE.1
1110 ),
1111 "[]",
1112 false,
1113 ),
1114 with_attachments(
1115 message(
1116 chat,
1117 "m2c",
1118 None,
1119 mara,
1120 at(1, 16, 41),
1121 "<p>Checklist and rollout plan attached.</p>",
1122 "[]",
1123 false,
1124 ),
1125 r#"[{"content_type":"reference","name":"Release-Checklist-Q4.xlsx","url":"https://example.com/files/checklist.xlsx","text":null,"size":48213},{"content_type":"reference","name":"Rollout-Plan.pdf","url":"https://example.com/files/plan.pdf","text":null,"size":2306867}]"#,
1126 ),
1127 message(
1128 chat,
1129 "m3",
1130 None,
1131 me,
1132 at(0, 9, 2),
1133 "<p>I'll take the changelog.</p>",
1134 &single,
1135 false,
1136 ),
1137 message(
1138 chat,
1139 "m4",
1140 None,
1141 jonas,
1142 at(0, 10, 14),
1143 "<p><at id=\"0\">Mara Lindqvist</at> can you take a quick look at this? It runs before <code>cargo test</code>.</p><pre><code class=\"language-rust\">// only release branches\nfn freeze(branch: &amp;str) -&gt; bool {\n branch.starts_with(\"release/\")\n}</code></pre>",
1144 "[]",
1145 false,
1146 ),
1147 message(
1148 chat,
1149 "m5",
1150 None,
1151 mara,
1152 at(0, 10, 31),
1153 "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m4\"><strong itemprop=\"mri\">Jonas Ortega</strong><p itemprop=\"preview\">can you take a quick look at this?</p></blockquote><p>Looks good. Small thing: the name could say what it checks.</p>",
1154 &hearts,
1155 true,
1156 ),
1157 message(
1158 chat,
1159 "m5b",
1160 None,
1161 mara,
1162 at(0, 10, 40),
1163 "<p>Rollout for Friday:</p><ul><li>Freeze the release branch</li><li>Run the smoke tests on staging, then post the results in the channel</li><li>Ship<ul><li>Windows installer</li><li>Linux <code>.AppImage</code></li></ul></li></ul><p>Order:</p><ol><li>Tag</li><li>Build</li><li>Announce</li></ol>",
1164 "[]",
1165 false,
1166 ),
1167 message(
1168 chat,
1169 "m5c",
1170 None,
1171 jonas,
1172 at(0, 11, 5),
1173 "<h2>Release notes 0.2</h2><p>The <s>old sync path</s> <u>is gone</u>.</p><table><thead><tr><th>Area</th><th>Owner</th></tr></thead><tbody><tr><td>Sync</td><td>Priya</td></tr><tr><td>Render</td><td>Jonas</td></tr></tbody></table><hr><blockquote>Measure twice, cut once.</blockquote><p><span style=\"background-color: rgb(255, 255, 0)\">Important:</span> <span style=\"color: #c00000\">backup first</span>.</p>",
1174 "[]",
1175 false,
1176 ),
1177 message(
1178 chat,
1179 "m5d",
1180 None,
1181 (PRIYA_ID, priya_name),
1182 at(0, 12, 20),
1183 &format!(
1184 "<p>FYI, the customer asked for this.</p><blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"1790000000000\"><strong>Tobias Klein</strong><p>Can we move the freeze to Thursday? The customer demo is on Friday morning.</p></blockquote>"
1185 ),
1186 "[]",
1187 false,
1188 ),
1189 message(
1190 chat,
1191 "m6",
1192 None,
1193 me,
1194 at(0, 13, 35),
1195 "<p>Thanks, renamed. Tagging now.</p>",
1196 "[]",
1197 false,
1198 ),
1199 message(
1200 chat,
1201 "m7",
1202 None,
1203 me,
1204 at(0, 13, 36),
1205 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
1206 &many,
1207 false,
1208 ),
1209 with_links(
1210 message(
1211 chat,
1212 "m7a",
1213 None,
1214 me,
1215 at(0, 13, 37),
1216 "<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1217 "[]",
1218 false,
1219 ),
1220 LinkPreview {
1221 url: "https://example.com/notes".to_owned(),
1222 title: Some("Release notes 0.2".to_owned()),
1223 description: None,
1224 image_url: None,
1225 image_width: None,
1226 image_height: None,
1227 }
1228 .links_json(),
1229 ),
1230 message(
1231 chat,
1232 "m8",
1233 None,
1234 jonas,
1235 at(0, 13, 40),
1236 "<p>Formula check: H<sub>2</sub>O and x<sup>2</sup> + y<sup>2</sup>. <span style=\"font-size:xx-small;\">Small print, reviewed by <at id=\"0\">Mara Lindqvist</at>.</span> <span style=\"font-size:x-large;\">Big news:</span> the <span style=\"font-size:x-large;\"><a href=\"https://example.com/notes\">release notes</a></span> are out.</p>",
1237 "[]",
1238 false,
1239 ),
1240 message(
1241 chat,
1242 "m9",
1243 None,
1244 (PRIYA_ID, priya_name),
1245 at(0, 13, 45),
1246 &format!(
1247 "<p>Ship it!</p><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"Party\" itemtype=\"http://schema.skype.com/Giphy\">",
1248 demo_gifs::RECEIVED_GIF_KEY,
1249 demo_gifs::RECEIVED_GIF_SIZE.0,
1250 demo_gifs::RECEIVED_GIF_SIZE.1
1251 ),
1252 "[]",
1253 false,
1254 ),
1255 ]
1256}
1257
1258fn unread_messages() -> Vec<MessageRecord> {
1259 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1260 let lea = (LEA_ID, "Lea Schneider");
1261 let tobias = (TOBIAS_ID, "Tobias Klein");
1262 let rows = [
1263 (
1264 "u1",
1265 me,
1266 at(1, 17, 5),
1267 "<p>Can you enable access for North?</p>",
1268 ),
1269 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
1270 (
1271 "u3",
1272 lea,
1273 at(0, 12, 40),
1274 "<p>Good morning, access is ready.</p>",
1275 ),
1276 (
1277 "u4",
1278 lea,
1279 at(0, 12, 41),
1280 "<p>Sign in with your company ID, no password needed.</p>",
1281 ),
1282 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
1283 ];
1284 rows.into_iter()
1285 .map(|(id, sender, time, html)| {
1286 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1287 })
1288 .collect()
1289}
1290
1291fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1292 DEMO_TEAM_ORDER
1293 .iter()
1294 .map(|team_id| TeamLayoutRecord {
1295 team_id: (*team_id).to_owned(),
1296 hidden: *team_id == DEMO_HIDDEN_TEAM,
1297 channels: channels
1298 .iter()
1299 .filter(|channel| channel.team_id == *team_id)
1300 .map(|channel| ChannelLayoutRecord {
1301 channel_id: channel.id.clone(),
1302 general: channel.name == "General",
1303 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1304 })
1305 .collect(),
1306 })
1307 .collect()
1308}
1309
1310const ROLLOUT_REPLIES: [(&str, &str); 12] = [
1311 (MARA_ID, "Staging looks good on my side."),
1312 (JONAS_ID, "Smoke tests passed, no regressions."),
1313 (PRIYA_ID, "Docs for the new settings page are merged."),
1314 (LEA_ID, "Support is briefed, nothing blocking."),
1315 (MARA_ID, "Can we keep the old export for one more release?"),
1316 (JONAS_ID, "Yes, behind a flag. I will add it today."),
1317 (PRIYA_ID, "Changelog draft is ready for review."),
1318 (LEA_ID, "Customer success wants a heads-up the day before."),
1319 (MARA_ID, "I will send that mail on Thursday."),
1320 (JONAS_ID, "Flag is in, rebuilding staging now."),
1321 (PRIYA_ID, "Rollback steps are in the runbook."),
1322 (LEA_ID, "All green from QA. Go for Friday."),
1323];
1324
1325fn channel_messages() -> Vec<MessageRecord> {
1326 let channel = "demo-channel-1-1";
1327 let mara = (MARA_ID, "Mara Lindqvist");
1328 let tobias = (TOBIAS_ID, "Tobias Klein");
1329 let people = [
1330 (MARA_ID, "Mara Lindqvist"),
1331 (JONAS_ID, "Jonas Ortega"),
1332 (PRIYA_ID, "Priya Nair"),
1333 (LEA_ID, "Lea Schneider"),
1334 ];
1335 let rollout_replies = ROLLOUT_REPLIES
1336 .iter()
1337 .enumerate()
1338 .map(|(index, (sender, text))| {
1339 let sender = people
1340 .iter()
1341 .copied()
1342 .find(|(id, _)| id == sender)
1343 .expect("known person");
1344 message(
1345 channel,
1346 &format!("t3r{}", index + 1),
1347 Some("t3"),
1348 sender,
1349 at(0, 9, 40) + Duration::minutes(6 * index as i64),
1350 &format!("<p>{text}</p>"),
1351 "[]",
1352 false,
1353 )
1354 });
1355 let mut records = vec![
1356 message(
1357 channel,
1358 "t1",
1359 None,
1360 mara,
1361 at(0, 8, 0),
1362 "<p>Weekly sync notes are up.</p>",
1363 "[]",
1364 false,
1365 ),
1366 message(
1367 channel,
1368 "t1r1",
1369 Some("t1"),
1370 tobias,
1371 at(0, 8, 20),
1372 "<p>Thanks, adding my items.</p>",
1373 "[]",
1374 false,
1375 ),
1376 with_subject(
1377 message(
1378 channel,
1379 "t3",
1380 None,
1381 tobias,
1382 at(0, 9, 30),
1383 "<p>Release build 42 is green, deploying to staging now.</p>",
1384 "[]",
1385 false,
1386 ),
1387 "Release 42 rollout",
1388 ),
1389 message(
1390 channel,
1391 "t2",
1392 None,
1393 tobias,
1394 at(0, 10, 0),
1395 "<p>Who owns the on-call handover?</p>",
1396 "[]",
1397 false,
1398 ),
1399 message(
1400 channel,
1401 "t4",
1402 None,
1403 mara,
1404 at(3, 8, 42),
1405 "<p>Sprint Demos.</p><p>I added you both to the sprint. <at id=\"0\">Tobias Klein</at> did you present everything about the migration tool? The spec is at <a href=\"https://wiki.example.com/display/TEAM/Settings+types+and+password+policies\">https://wiki.example.com/display/TEAM/Settings+types+and+password+policies</a>Can you please review it?</p>",
1406 "[]",
1407 false,
1408 ),
1409 message(
1410 channel,
1411 "t4r1",
1412 Some("t4"),
1413 tobias,
1414 at(0, 9, 15),
1415 "<p>Yes, all done.</p>",
1416 "[]",
1417 false,
1418 ),
1419 ];
1420 records.extend(rollout_replies);
1421 records
1422}
1423
1424fn crc32(bytes: &[u8]) -> u32 {
1425 let mut crc = 0xffff_ffffu32;
1426 for byte in bytes {
1427 crc ^= u32::from(*byte);
1428 for _ in 0..8 {
1429 crc = if crc & 1 == 1 {
1430 (crc >> 1) ^ 0xedb8_8320
1431 } else {
1432 crc >> 1
1433 };
1434 }
1435 }
1436 !crc
1437}
1438
1439fn adler32(bytes: &[u8]) -> u32 {
1440 let (mut low, mut high) = (1u32, 0u32);
1441 for byte in bytes {
1442 low = (low + u32::from(*byte)) % 65521;
1443 high = (high + low) % 65521;
1444 }
1445 (high << 16) | low
1446}
1447
1448fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
1449 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
1450 let mut body = kind.to_vec();
1451 body.extend_from_slice(data);
1452 output.extend_from_slice(&body);
1453 output.extend_from_slice(&crc32(&body).to_be_bytes());
1454}
1455
1456fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
1457 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
1458}
1459
1460fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
1461 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
1462 let (x, y) = (column as f32, row as f32);
1463 let shade = y / height;
1464 let background = [
1465 (30. - 14. * shade) as u8,
1466 (41. - 16. * shade) as u8,
1467 (59. - 14. * shade) as u8,
1468 ];
1469 let bar_width = width / 14.;
1470 let slot = (x / bar_width) as usize;
1471 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
1472 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
1473 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
1474 let header = y < height * 0.1;
1475 if header {
1476 [22, 30, 45]
1477 } else if on_bars {
1478 if slot % 4 == 3 {
1479 [226, 87, 47]
1480 } else {
1481 [88, 133, 196]
1482 }
1483 } else if (y - height * 0.86).abs() < 1.5 {
1484 [71, 85, 105]
1485 } else {
1486 background
1487 }
1488}
1489
1490fn encode_png(palette: &Palette) -> Vec<u8> {
1491 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
1492 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
1493 if inside(x, y, (24., 21.), (8.5, 9.5)) {
1494 palette.skin
1495 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
1496 palette.hair
1497 } else if inside(x, y, (24., 50.), (22., 19.)) {
1498 palette.shirt
1499 } else {
1500 palette.background
1501 }
1502 })
1503}
1504
1505fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
1506 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
1507 for row in 0..height {
1508 raw.push(0);
1509 for column in 0..width {
1510 raw.extend_from_slice(&pixel(column, row));
1511 }
1512 }
1513 let mut zlib = vec![0x78, 0x01];
1514 let mut blocks = raw.chunks(65535).peekable();
1515 while let Some(block) = blocks.next() {
1516 zlib.push(u8::from(blocks.peek().is_none()));
1517 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
1518 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
1519 zlib.extend_from_slice(block);
1520 }
1521 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
1522 let mut header = Vec::new();
1523 header.extend_from_slice(&(width as u32).to_be_bytes());
1524 header.extend_from_slice(&(height as u32).to_be_bytes());
1525 header.extend_from_slice(&[8, 2, 0, 0, 0]);
1526 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
1527 png_chunk(&mut png, b"IHDR", &header);
1528 png_chunk(&mut png, b"IDAT", &zlib);
1529 png_chunk(&mut png, b"IEND", &[]);
1530 png
1531}
1532
1533#[cfg(test)]
1534mod tests {
1535 use super::*;
1536
1537 #[test]
1538 fn png_has_signature_and_ends_with_iend() {
1539 let png = encode_png(&MARA);
1540 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
1541 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
1542 }
1543
1544 #[test]
1545 fn crc_and_adler_match_known_values() {
1546 assert_eq!(crc32(b"IEND"), 0xae42_6082);
1547 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
1548 }
1549
1550 #[test]
1551 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
1552 let chat = mention_candidates("demo-chat-release", "ma");
1553 assert_eq!(chat.len(), 1);
1554 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
1555 let channel = mention_candidates("demo-channel-1-1", "gen");
1556 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
1557 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
1558 }
1559
1560 #[test]
1561 fn new_group_chat_gets_a_title_and_the_first_message() {
1562 let people = vec![
1563 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
1564 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1565 ];
1566 let now = Utc::now();
1567 let (chat, record) = new_chat(
1568 &[],
1569 &people,
1570 Some("Crew"),
1571 "Hello all",
1572 "Hello <i>all</i>",
1573 now,
1574 );
1575 assert_eq!(chat.id, "demo-chat-new-1");
1576 assert_eq!(chat.kind, "group");
1577 assert_eq!(chat.title, "Crew");
1578 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1579 assert_eq!(chat.members.len(), 3);
1580 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1581 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
1582 assert_eq!(chat.last_message_at, Some(now));
1583 assert_eq!(record.conversation_id, chat.id);
1584 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1585 assert!(record.body_html.contains("Hello"));
1586 }
1587
1588 #[test]
1589 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1590 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1591 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
1592 assert_eq!(first.kind, "oneOnOne");
1593 assert!(first.title.is_empty());
1594 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
1595 assert_eq!(second.id, "demo-chat-new-2");
1596 }
1597
1598 #[test]
1599 fn sending_into_a_chat_refreshes_its_preview() {
1600 let base = ChatRecord {
1601 id: "demo-chat-x".to_owned(),
1602 unread: true,
1603 ..Default::default()
1604 };
1605 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
1606 assert!(!chat.unread);
1607 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1608 assert_eq!(record.conversation_id, "demo-chat-x");
1609 }
1610
1611 #[test]
1612 fn demo_covers_the_sidebar_edge_cases() {
1613 let chats = demo_chats();
1614 assert!(chats.iter().any(|chat| chat.deleted));
1615 assert!(chats.iter().any(|chat| chat.title.len() > 40));
1616 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
1617 }
1618}