BlueGit

ict rusty-teams

Files

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

demo.rs

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