BlueGit

ict rusty-teams

Files

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

demo.rs

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