BlueGit

ict rusty-teams

Files

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

demo.rs

271952ed History
demo.rs 34.2 KiB Download Raw
1use std::path::PathBuf;
2use std::sync::Arc;
3
4use chrono::{DateTime, Duration, Local, TimeZone, Utc};
5use gpui_kit::Image;
6use store::{
7 ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,
8 TeamLayoutRecord, TeamRecord,
9};
10use teams_core::{MentionCandidate, PersonCandidate, PersonSource};
11
12use crate::app_state::{AppState, Selection};
13use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
14
15pub const DEMO_USER_ID: &str = "demo-me";
16const DEMO_USER_NAME: &str = "Dana Demo";
17const PHOTO_SIZE: usize = 48;
18const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
19const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
20const STAGING_SIZE: (usize, usize) = (960, 540);
21const PRIORITY_CHAT: &str = "demo-chat-priya";
22const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
23const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
24 (
25 MARA_ID,
26 "Mara Lindqvist",
27 "Product Owner",
28 "mara.lindqvist@example.com",
29 ),
30 (
31 JONAS_ID,
32 "Jonas Ortega",
33 "Backend Engineer",
34 "jonas.ortega@example.com",
35 ),
36 (
37 PRIYA_ID,
38 "Priya Nair",
39 "Engineering Manager",
40 "priya.nair@example.com",
41 ),
42 (
43 LEA_ID,
44 "Lea Schneider",
45 "Customer Success",
46 "lea.schneider@example.com",
47 ),
48 (
49 TOBIAS_ID,
50 "Tobias Klein",
51 "Support Engineer",
52 "tobias.klein@example.com",
53 ),
54];
55
56struct Palette {
57 background: [u8; 3],
58 skin: [u8; 3],
59 hair: [u8; 3],
60 shirt: [u8; 3],
61}
62
63const MARA: Palette = Palette {
64 background: [0x3f, 0x5f, 0x7a],
65 skin: [0xe0, 0xb2, 0x93],
66 hair: [0xd9, 0xa4, 0x41],
67 shirt: [0x1e, 0x29, 0x3b],
68};
69const PRIYA: Palette = Palette {
70 background: [0x4b, 0x3b, 0x5c],
71 skin: [0x9a, 0x6a, 0x4a],
72 hair: [0x1c, 0x19, 0x17],
73 shirt: [0xbe, 0x12, 0x3c],
74};
75const TOBIAS: Palette = Palette {
76 background: [0x3b, 0x4a, 0x3f],
77 skin: [0xf1, 0xc7, 0xa5],
78 hair: [0x57, 0x53, 0x4e],
79 shirt: [0x0f, 0x76, 0x6e],
80};
81
82const MARA_ID: &str = "demo-mara";
83const JONAS_ID: &str = "demo-jonas";
84const PRIYA_ID: &str = "demo-priya";
85const LEA_ID: &str = "demo-lea";
86const TOBIAS_ID: &str = "demo-tobias";
87
88const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
89 (
90 "demo-team-1",
91 "Platform",
92 ["General", "Incidents", "Releases"],
93 ),
94 ("demo-team-2", "Product", ["General", "Roadmap", "Feedback"]),
95 (
96 "demo-team-3",
97 "Operations",
98 ["General", "On call", "Runbooks"],
99 ),
100 (
101 "demo-team-4",
102 "Archive 2025",
103 ["General", "Trade fair", "Office move"],
104 ),
105];
106const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
107const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
108const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
109
110const UNREAD_CHAT: &str = "demo-chat-atlas";
111const RELEASE_CHAT: &str = "demo-chat-release";
112const FAVORITES_ID: &str = "demo-folder-favorites";
113const CUSTOMERS_FOLDER: &str = "demo-folder-customers";
114const ATLAS_FOLDER: &str = "demo-folder-atlas";
115const TODO_FOLDER: &str = "demo-folder-todo";
116
117fn member(user_id: &str, name: &str) -> MemberRecord {
118 MemberRecord {
119 user_id: Some(user_id.to_owned()),
120 display_name: name.to_owned(),
121 }
122}
123
124fn people(extra: &[(&str, &str)]) -> Vec<MemberRecord> {
125 std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
126 .chain(extra.iter().map(|(id, name)| member(id, name)))
127 .collect()
128}
129
130pub fn at(days_ago: i64, hour: u32, minute: u32) -> DateTime<Utc> {
131 let day = Local::now().date_naive() - Duration::days(days_ago);
132 let local = day.and_hms_opt(hour, minute, 0).expect("valid time");
133 Local
134 .from_local_datetime(&local)
135 .earliest()
136 .map_or_else(Utc::now, |time| time.with_timezone(&Utc))
137}
138
139struct DemoChat {
140 id: &'static str,
141 kind: &'static str,
142 title: &'static str,
143 members: Vec<MemberRecord>,
144 time: DateTime<Utc>,
145 unread: bool,
146 preview: Option<(&'static str, &'static str, &'static str)>,
147 deleted: bool,
148}
149
150fn demo_chats() -> Vec<DemoChat> {
151 let group = |extra: &[(&str, &str)]| people(extra);
152 vec![
153 DemoChat {
154 id: "demo-chat-mara",
155 kind: "oneOnOne",
156 title: "Mara Lindqvist",
157 members: people(&[(MARA_ID, "Mara Lindqvist")]),
158 time: at(0, 13, 40),
159 unread: false,
160 preview: Some((MARA_ID, "Mara Lindqvist", "Sure, 2 pm works")),
161 deleted: false,
162 },
163 DemoChat {
164 id: RELEASE_CHAT,
165 kind: "group",
166 title: "Release planning",
167 members: group(&[
168 (MARA_ID, "Mara Lindqvist"),
169 (JONAS_ID, "Jonas Ortega"),
170 (PRIYA_ID, "Priya Nair"),
171 (LEA_ID, "Lea Schneider"),
172 ]),
173 time: at(0, 13, 35),
174 unread: false,
175 preview: Some((
176 DEMO_USER_ID,
177 DEMO_USER_NAME,
178 "Build 42 is green, see pipeline",
179 )),
180 deleted: false,
181 },
182 DemoChat {
183 id: "demo-chat-customer-1",
184 kind: "group",
185 title: "Customer North - Operations",
186 members: group(&[(LEA_ID, "Lea Schneider"), (TOBIAS_ID, "Tobias Klein")]),
187 time: at(0, 12, 50),
188 unread: true,
189 preview: Some((LEA_ID, "Lea Schneider", "Access is enabled now")),
190 deleted: false,
191 },
192 DemoChat {
193 id: "demo-chat-customer-2",
194 kind: "group",
195 title: "Customer South - Rollout",
196 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
197 time: at(0, 9, 5),
198 unread: true,
199 preview: Some((JONAS_ID, "Jonas Ortega", "Meeting is set for Friday")),
200 deleted: false,
201 },
202 DemoChat {
203 id: "demo-chat-customer-3",
204 kind: "group",
205 title: "Customer West - Support",
206 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
207 time: at(1, 16, 0),
208 unread: false,
209 preview: Some((TOBIAS_ID, "Tobias Klein", "Ticket is closed")),
210 deleted: false,
211 },
212 DemoChat {
213 id: "demo-chat-customer-4",
214 kind: "group",
215 title: "Customer East - Pilot",
216 members: group(&[(MARA_ID, "Mara Lindqvist"), (PRIYA_ID, "Priya Nair")]),
217 time: at(3, 10, 0),
218 unread: false,
219 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "I'll send the documents")),
220 deleted: false,
221 },
222 DemoChat {
223 id: "demo-chat-atlas",
224 kind: "group",
225 title: "Atlas core team",
226 members: group(&[
227 (PRIYA_ID, "Priya Nair"),
228 (LEA_ID, "Lea Schneider"),
229 (MARA_ID, "Mara Lindqvist"),
230 ]),
231 time: at(0, 13, 12),
232 unread: true,
233 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
234 deleted: false,
235 },
236 DemoChat {
237 id: "demo-chat-jonas",
238 kind: "oneOnOne",
239 title: "Jonas Ortega",
240 members: people(&[(JONAS_ID, "Jonas Ortega")]),
241 time: at(0, 11, 2),
242 unread: false,
243 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Thanks, it's merged")),
244 deleted: false,
245 },
246 DemoChat {
247 id: "demo-chat-priya",
248 kind: "oneOnOne",
249 title: "Priya Nair",
250 members: people(&[(PRIYA_ID, "Priya Nair")]),
251 time: at(0, 10, 47),
252 unread: false,
253 preview: Some((PRIYA_ID, "Priya Nair", "Image")),
254 deleted: false,
255 },
256 DemoChat {
257 id: "demo-chat-tobias",
258 kind: "oneOnOne",
259 title: "Tobias Klein",
260 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
261 time: at(2, 9, 30),
262 unread: false,
263 preview: Some((TOBIAS_ID, "Tobias Klein", "ok")),
264 deleted: false,
265 },
266 DemoChat {
267 id: "demo-chat-allhands",
268 kind: "group",
269 title: "All-hands announcements",
270 members: group(&[(LEA_ID, "Lea Schneider"), (MARA_ID, "Mara Lindqvist")]),
271 time: at(0, 9, 0),
272 unread: true,
273 preview: Some((LEA_ID, "Lea Schneider", "New vacation policy from November")),
274 deleted: false,
275 },
276 DemoChat {
277 id: "demo-chat-design",
278 kind: "group",
279 title: "Design review",
280 members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
281 time: at(2, 15, 0),
282 unread: false,
283 preview: Some((MARA_ID, "Mara Lindqvist", "alt")),
284 deleted: true,
285 },
286 DemoChat {
287 id: "demo-chat-quarterly",
288 kind: "group",
289 title: "Quarterly numbers, finance review and planning 2027",
290 members: group(&[(LEA_ID, "Lea Schneider"), (JONAS_ID, "Jonas Ortega")]),
291 time: at(4, 11, 0),
292 unread: false,
293 preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),
294 deleted: false,
295 },
296 ]
297}
298
299pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCandidate> {
300 let needle = query.trim().to_lowercase();
301 let matches = |name: &str| needle.is_empty() || name.to_lowercase().contains(&needle);
302 let people = PEOPLE_DIRECTORY
303 .iter()
304 .filter(|(_, name, _, _)| matches(name))
305 .map(|(user_id, name, job_title, mail)| {
306 MentionCandidate::Person(PersonCandidate {
307 user_id: (*user_id).to_owned(),
308 display_name: (*name).to_owned(),
309 mail: Some((*mail).to_owned()),
310 job_title: Some((*job_title).to_owned()),
311 source: PersonSource::Member,
312 })
313 });
314 let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {
315 [
316 MentionCandidate::Channel {
317 channel_id: conversation_id.to_owned(),
318 name: "General".to_owned(),
319 },
320 MentionCandidate::Team {
321 team_id: "demo-team-1".to_owned(),
322 name: "Platform".to_owned(),
323 },
324 ]
325 .into_iter()
326 .filter(|candidate| matches(candidate.display_name()))
327 .collect()
328 } else {
329 Vec::new()
330 };
331 people.chain(scope).collect()
332}
333
334pub fn send_in_chat(
335 chat: &ChatRecord,
336 text: &str,
337 now: DateTime<Utc>,
338) -> (ChatRecord, MessageRecord) {
339 let mut chat = chat.clone();
340 chat.last_message_at = Some(now);
341 chat.last_message_preview = Some(text.to_owned());
342 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
343 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
344 chat.last_message_deleted = false;
345 chat.unread = false;
346 let record = message(
347 &chat.id,
348 &format!("demo-sent-{}", now.timestamp_millis()),
349 None,
350 (DEMO_USER_ID, DEMO_USER_NAME),
351 now,
352 &teams_core::markdown_to_html(text),
353 "[]",
354 false,
355 );
356 (chat, record)
357}
358
359pub fn new_chat(
360 existing: &[ChatRecord],
361 people: &[(String, String)],
362 topic: Option<&str>,
363 text: &str,
364 now: DateTime<Utc>,
365) -> (ChatRecord, MessageRecord) {
366 let number = existing
367 .iter()
368 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
369 .count()
370 + 1;
371 let one_on_one = people.len() == 1;
372 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
373 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
374 .collect();
375 let chat = ChatRecord {
376 id: format!("{NEW_CHAT_PREFIX}{number}"),
377 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
378 title: if one_on_one {
379 String::new()
380 } else {
381 topic.unwrap_or_default().to_owned()
382 },
383 member_summary: people
384 .iter()
385 .map(|(_, name)| name.as_str())
386 .collect::<Vec<_>>()
387 .join(", "),
388 members,
389 ..Default::default()
390 };
391 send_in_chat(&chat, text, now)
392}
393
394fn image_directory() -> PathBuf {
395 std::env::temp_dir().join("rusty-teams-demo")
396}
397
398pub fn first_unread(conversation_id: &str) -> Option<String> {
399 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
400}
401
402pub fn read_message_ids(records: &[MessageRecord]) -> std::collections::HashSet<String> {
403 let newest = records.iter().max_by_key(|record| record.created_at);
404 records
405 .iter()
406 .filter(|record| {
407 Some(record.message_id.as_str()) != newest.map(|newest| newest.message_id.as_str())
408 })
409 .map(|record| record.message_id.clone())
410 .collect()
411}
412
413pub fn first_selection() -> Selection {
414 Selection::Chat(RELEASE_CHAT.to_owned())
415}
416
417pub fn seed(store: &Store) {
418 let chats: Vec<ChatRecord> = demo_chats()
419 .into_iter()
420 .map(|demo| ChatRecord {
421 id: demo.id.to_owned(),
422 kind: demo.kind.to_owned(),
423 title: if demo.kind == "oneOnOne" {
424 String::new()
425 } else {
426 demo.title.to_owned()
427 },
428 member_summary: demo.title.to_owned(),
429 last_message_at: Some(demo.time),
430 unread: demo.unread,
431 members: demo.members,
432 last_message_preview: demo.preview.map(|(_, _, text)| text.to_owned()),
433 last_message_sender_id: demo.preview.map(|(id, _, _)| id.to_owned()),
434 last_message_sender_name: demo.preview.map(|(_, name, _)| name.to_owned()),
435 last_message_deleted: demo.deleted,
436 ..Default::default()
437 })
438 .collect();
439 let _ = store.upsert_chats(&chats);
440 let teams: Vec<TeamRecord> = DEMO_TEAMS
441 .iter()
442 .map(|(id, name, _)| TeamRecord {
443 id: (*id).to_owned(),
444 name: (*name).to_owned(),
445 })
446 .collect();
447 let _ = store.upsert_teams(&teams);
448 let mut channels = Vec::new();
449 for (team_index, (team_id, _, names)) in DEMO_TEAMS.iter().enumerate() {
450 for (channel_index, name) in names.iter().enumerate() {
451 channels.push(ChannelRecord {
452 id: format!("demo-channel-{}-{}", team_index + 1, channel_index + 1),
453 team_id: (*team_id).to_owned(),
454 name: (*name).to_owned(),
455 membership_type: None,
456 last_message_at: Some(at(channel_index as i64, 12, 10)),
457 unread: (team_index == 0 && channel_index == 1)
458 || (team_index == 1 && channel_index == 0),
459 });
460 }
461 }
462 let _ = store.upsert_channels(&channels);
463 let _ = store.replace_team_layout(&demo_team_layout(&channels));
464 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
465 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
466 let _ = store.upsert_messages(&release_messages());
467 let _ = store.upsert_messages(&unread_messages());
468 let _ = store.upsert_messages(&channel_messages());
469 let _ = store.upsert_messages(&priority_messages());
470}
471
472fn photo(palette: &Palette) -> Arc<Image> {
473 crate::data::avatar_image_from("image/png", encode_png(palette))
474}
475
476pub fn seed_directory(state: &mut AppState) {
477 let directory = &mut state.directory;
478 directory.me = Some(Person {
479 user_id: DEMO_USER_ID.to_owned(),
480 display_name: DEMO_USER_NAME.to_owned(),
481 });
482 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
483 directory.folders = vec![
484 FolderInfo {
485 id: FAVORITES_ID.to_owned(),
486 name: String::new(),
487 kind: FolderKind::Favorites,
488 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
489 },
490 FolderInfo {
491 id: CUSTOMERS_FOLDER.to_owned(),
492 name: "Customers".to_owned(),
493 kind: FolderKind::UserCreated,
494 conversation_ids: ids(&[
495 "demo-chat-customer-1",
496 "demo-chat-customer-2",
497 "demo-chat-customer-3",
498 "demo-chat-customer-4",
499 ]),
500 },
501 FolderInfo {
502 id: ATLAS_FOLDER.to_owned(),
503 name: "Project Atlas".to_owned(),
504 kind: FolderKind::UserCreated,
505 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
506 },
507 FolderInfo {
508 id: TODO_FOLDER.to_owned(),
509 name: "To do".to_owned(),
510 kind: FolderKind::UserCreated,
511 conversation_ids: Vec::new(),
512 },
513 ];
514 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
515 directory
516 .unread_counts
517 .insert("demo-chat-atlas".to_owned(), 5);
518 directory
519 .unread_counts
520 .insert("demo-chat-customer-1".to_owned(), 2);
521 directory
522 .unread_counts
523 .insert("demo-chat-customer-2".to_owned(), 1);
524 directory
525 .unread_counts
526 .insert("demo-chat-allhands".to_owned(), 120);
527 directory.set_avatar(MARA_ID, Some(photo(&MARA)));
528 directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
529 directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
530 for (user_id, kind) in [
531 (MARA_ID, PresenceKind::Available),
532 (JONAS_ID, PresenceKind::DoNotDisturb),
533 (PRIYA_ID, PresenceKind::Away),
534 (TOBIAS_ID, PresenceKind::Offline),
535 (LEA_ID, PresenceKind::DoNotDisturb),
536 (DEMO_USER_ID, PresenceKind::Available),
537 ] {
538 directory.set_presence(user_id, kind);
539 }
540 let directory_path = image_directory();
541 if std::fs::create_dir_all(&directory_path).is_ok() {
542 let path = directory_path.join("staging-dashboard.png");
543 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
544 if std::fs::write(&path, png).is_ok() {
545 state.directory.set_image(STAGING_IMAGE_KEY, &path);
546 }
547 }
548 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
549 state.last_sync = Some(Utc::now());
550}
551
552#[allow(clippy::too_many_arguments)]
553fn message(
554 conversation: &str,
555 id: &str,
556 reply_to: Option<&str>,
557 sender: (&str, &str),
558 time: DateTime<Utc>,
559 html: &str,
560 reactions_json: &str,
561 edited: bool,
562) -> MessageRecord {
563 MessageRecord {
564 conversation_id: conversation.to_owned(),
565 message_id: id.to_owned(),
566 reply_to_id: reply_to.map(str::to_owned),
567 sender_id: Some(sender.0.to_owned()),
568 sender_name: Some(sender.1.to_owned()),
569 created_at: time,
570 edited_at: edited.then_some(time + Duration::minutes(2)),
571 deleted: false,
572 body_html: html.to_owned(),
573 attachments_json: "[]".to_owned(),
574 reactions_json: reactions_json.to_owned(),
575 mentions_json: "[]".to_owned(),
576 }
577}
578
579fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
580 record.attachments_json = attachments_json.to_owned();
581 record
582}
583
584fn priority_messages() -> Vec<MessageRecord> {
585 let priya = (PRIYA_ID, "Priya Nair");
586 let me = (DEMO_USER_ID, DEMO_USER_NAME);
587 vec![
588 message(
589 PRIORITY_CHAT,
590 "p1",
591 None,
592 me,
593 at(0, 10, 40),
594 "<p>Have you seen the error on staging yet?</p>",
595 "[]",
596 false,
597 ),
598 message(
599 PRIORITY_CHAT,
600 "p2",
601 None,
602 priya,
603 at(0, 10, 47),
604 &format!(
605 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
606 ),
607 "[]",
608 false,
609 ),
610 ]
611}
612
613fn reaction(kind: &str, users: &[&str]) -> String {
614 users
615 .iter()
616 .map(|user| format!(r#"{{"reaction_type":"{kind}","user_id":"{user}","user_name":null}}"#))
617 .collect::<Vec<_>>()
618 .join(",")
619}
620
621fn release_messages() -> Vec<MessageRecord> {
622 let chat = RELEASE_CHAT;
623 let mara = (MARA_ID, "Mara Lindqvist");
624 let jonas = (JONAS_ID, "Jonas Ortega");
625 let me = (DEMO_USER_ID, DEMO_USER_NAME);
626 let likes = format!("[{}]", reaction("like", &[JONAS_ID, PRIYA_ID, LEA_ID]));
627 let hearts = format!("[{}]", reaction("heart", &[DEMO_USER_ID, JONAS_ID]));
628 vec![
629 message(
630 chat,
631 "m1",
632 None,
633 mara,
634 at(1, 16, 20),
635 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
636 "[]",
637 false,
638 ),
639 message(
640 chat,
641 "m2",
642 None,
643 mara,
644 at(1, 16, 22),
645 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
646 &likes,
647 false,
648 ),
649 message(
650 chat,
651 "m2b",
652 None,
653 mara,
654 at(1, 16, 40),
655 &format!(
656 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
657 STAGING_SIZE.0, STAGING_SIZE.1
658 ),
659 "[]",
660 false,
661 ),
662 with_attachments(
663 message(
664 chat,
665 "m2c",
666 None,
667 mara,
668 at(1, 16, 41),
669 "<p>Checklist and rollout plan attached.</p>",
670 "[]",
671 false,
672 ),
673 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}]"#,
674 ),
675 message(
676 chat,
677 "m3",
678 None,
679 me,
680 at(0, 9, 2),
681 "<p>I'll take the changelog.</p>",
682 "[]",
683 false,
684 ),
685 message(
686 chat,
687 "m4",
688 None,
689 jonas,
690 at(0, 10, 14),
691 "<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>",
692 "[]",
693 false,
694 ),
695 message(
696 chat,
697 "m5",
698 None,
699 mara,
700 at(0, 10, 31),
701 "<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>",
702 &hearts,
703 true,
704 ),
705 message(
706 chat,
707 "m5b",
708 None,
709 mara,
710 at(0, 10, 40),
711 "<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>",
712 "[]",
713 false,
714 ),
715 message(
716 chat,
717 "m5c",
718 None,
719 jonas,
720 at(0, 11, 5),
721 "<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>",
722 "[]",
723 false,
724 ),
725 message(
726 chat,
727 "m6",
728 None,
729 me,
730 at(0, 13, 35),
731 "<p>Thanks, renamed. Tagging now.</p>",
732 "[]",
733 false,
734 ),
735 message(
736 chat,
737 "m7",
738 None,
739 me,
740 at(0, 13, 36),
741 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
742 "[]",
743 false,
744 ),
745 ]
746}
747
748fn unread_messages() -> Vec<MessageRecord> {
749 let me = (DEMO_USER_ID, DEMO_USER_NAME);
750 let lea = (LEA_ID, "Lea Schneider");
751 let tobias = (TOBIAS_ID, "Tobias Klein");
752 let rows = [
753 (
754 "u1",
755 me,
756 at(1, 17, 5),
757 "<p>Can you enable access for North?</p>",
758 ),
759 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
760 (
761 "u3",
762 lea,
763 at(0, 12, 40),
764 "<p>Good morning, access is ready.</p>",
765 ),
766 (
767 "u4",
768 lea,
769 at(0, 12, 41),
770 "<p>Sign in with your company ID, no password needed.</p>",
771 ),
772 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
773 ];
774 rows.into_iter()
775 .map(|(id, sender, time, html)| {
776 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
777 })
778 .collect()
779}
780
781fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
782 DEMO_TEAM_ORDER
783 .iter()
784 .map(|team_id| TeamLayoutRecord {
785 team_id: (*team_id).to_owned(),
786 hidden: *team_id == DEMO_HIDDEN_TEAM,
787 channels: channels
788 .iter()
789 .filter(|channel| channel.team_id == *team_id)
790 .map(|channel| ChannelLayoutRecord {
791 channel_id: channel.id.clone(),
792 general: channel.name == "General",
793 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
794 })
795 .collect(),
796 })
797 .collect()
798}
799
800fn channel_messages() -> Vec<MessageRecord> {
801 let channel = "demo-channel-1-1";
802 let mara = (MARA_ID, "Mara Lindqvist");
803 let tobias = (TOBIAS_ID, "Tobias Klein");
804 vec![
805 message(
806 channel,
807 "t1",
808 None,
809 mara,
810 at(0, 8, 0),
811 "<p>Weekly sync notes are up.</p>",
812 "[]",
813 false,
814 ),
815 message(
816 channel,
817 "t1r1",
818 Some("t1"),
819 tobias,
820 at(0, 8, 20),
821 "<p>Thanks, adding my items.</p>",
822 "[]",
823 false,
824 ),
825 message(
826 channel,
827 "t3",
828 None,
829 tobias,
830 at(0, 11, 30),
831 "<p>Release build 42 is green, deploying to staging now.</p>",
832 "[]",
833 false,
834 ),
835 message(
836 channel,
837 "t2",
838 None,
839 tobias,
840 at(0, 11, 0),
841 "<p>Who owns the on-call handover?</p>",
842 "[]",
843 false,
844 ),
845 message(
846 channel,
847 "t4",
848 None,
849 mara,
850 at(3, 8, 42),
851 "<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>",
852 "[]",
853 false,
854 ),
855 message(
856 channel,
857 "t4r1",
858 Some("t4"),
859 tobias,
860 at(0, 9, 15),
861 "<p>Yes, all done.</p>",
862 "[]",
863 false,
864 ),
865 ]
866}
867
868fn crc32(bytes: &[u8]) -> u32 {
869 let mut crc = 0xffff_ffffu32;
870 for byte in bytes {
871 crc ^= u32::from(*byte);
872 for _ in 0..8 {
873 crc = if crc & 1 == 1 {
874 (crc >> 1) ^ 0xedb8_8320
875 } else {
876 crc >> 1
877 };
878 }
879 }
880 !crc
881}
882
883fn adler32(bytes: &[u8]) -> u32 {
884 let (mut low, mut high) = (1u32, 0u32);
885 for byte in bytes {
886 low = (low + u32::from(*byte)) % 65521;
887 high = (high + low) % 65521;
888 }
889 (high << 16) | low
890}
891
892fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
893 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
894 let mut body = kind.to_vec();
895 body.extend_from_slice(data);
896 output.extend_from_slice(&body);
897 output.extend_from_slice(&crc32(&body).to_be_bytes());
898}
899
900fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
901 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
902}
903
904fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
905 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
906 let (x, y) = (column as f32, row as f32);
907 let shade = y / height;
908 let background = [
909 (30. - 14. * shade) as u8,
910 (41. - 16. * shade) as u8,
911 (59. - 14. * shade) as u8,
912 ];
913 let bar_width = width / 14.;
914 let slot = (x / bar_width) as usize;
915 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
916 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
917 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
918 let header = y < height * 0.1;
919 if header {
920 [22, 30, 45]
921 } else if on_bars {
922 if slot % 4 == 3 {
923 [226, 87, 47]
924 } else {
925 [88, 133, 196]
926 }
927 } else if (y - height * 0.86).abs() < 1.5 {
928 [71, 85, 105]
929 } else {
930 background
931 }
932}
933
934fn encode_png(palette: &Palette) -> Vec<u8> {
935 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
936 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
937 if inside(x, y, (24., 21.), (8.5, 9.5)) {
938 palette.skin
939 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
940 palette.hair
941 } else if inside(x, y, (24., 50.), (22., 19.)) {
942 palette.shirt
943 } else {
944 palette.background
945 }
946 })
947}
948
949fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
950 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
951 for row in 0..height {
952 raw.push(0);
953 for column in 0..width {
954 raw.extend_from_slice(&pixel(column, row));
955 }
956 }
957 let mut zlib = vec![0x78, 0x01];
958 let mut blocks = raw.chunks(65535).peekable();
959 while let Some(block) = blocks.next() {
960 zlib.push(u8::from(blocks.peek().is_none()));
961 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
962 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
963 zlib.extend_from_slice(block);
964 }
965 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
966 let mut header = Vec::new();
967 header.extend_from_slice(&(width as u32).to_be_bytes());
968 header.extend_from_slice(&(height as u32).to_be_bytes());
969 header.extend_from_slice(&[8, 2, 0, 0, 0]);
970 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
971 png_chunk(&mut png, b"IHDR", &header);
972 png_chunk(&mut png, b"IDAT", &zlib);
973 png_chunk(&mut png, b"IEND", &[]);
974 png
975}
976
977#[cfg(test)]
978mod tests {
979 use super::*;
980
981 #[test]
982 fn png_has_signature_and_ends_with_iend() {
983 let png = encode_png(&MARA);
984 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
985 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
986 }
987
988 #[test]
989 fn crc_and_adler_match_known_values() {
990 assert_eq!(crc32(b"IEND"), 0xae42_6082);
991 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
992 }
993
994 #[test]
995 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
996 let chat = mention_candidates("demo-chat-release", "ma");
997 assert_eq!(chat.len(), 1);
998 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
999 let channel = mention_candidates("demo-channel-1-1", "gen");
1000 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
1001 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
1002 }
1003
1004 #[test]
1005 fn new_group_chat_gets_a_title_and_the_first_message() {
1006 let people = vec![
1007 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
1008 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1009 ];
1010 let now = Utc::now();
1011 let (chat, record) = new_chat(&[], &people, Some("Crew"), "Hello *all*", now);
1012 assert_eq!(chat.id, "demo-chat-new-1");
1013 assert_eq!(chat.kind, "group");
1014 assert_eq!(chat.title, "Crew");
1015 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1016 assert_eq!(chat.members.len(), 3);
1017 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1018 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello *all*"));
1019 assert_eq!(chat.last_message_at, Some(now));
1020 assert_eq!(record.conversation_id, chat.id);
1021 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1022 assert!(record.body_html.contains("Hello"));
1023 }
1024
1025 #[test]
1026 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1027 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1028 let (first, _) = new_chat(&[], &people, None, "Hi", Utc::now());
1029 assert_eq!(first.kind, "oneOnOne");
1030 assert!(first.title.is_empty());
1031 let (second, _) = new_chat(&[first], &people, None, "Hi again", Utc::now());
1032 assert_eq!(second.id, "demo-chat-new-2");
1033 }
1034
1035 #[test]
1036 fn sending_into_a_chat_refreshes_its_preview() {
1037 let base = ChatRecord {
1038 id: "demo-chat-x".to_owned(),
1039 unread: true,
1040 ..Default::default()
1041 };
1042 let (chat, record) = send_in_chat(&base, "Ping", Utc::now());
1043 assert!(!chat.unread);
1044 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1045 assert_eq!(record.conversation_id, "demo-chat-x");
1046 }
1047
1048 #[test]
1049 fn demo_covers_the_sidebar_edge_cases() {
1050 let chats = demo_chats();
1051 assert!(chats.iter().any(|chat| chat.deleted));
1052 assert!(chats.iter().any(|chat| chat.title.len() > 40));
1053 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
1054 }
1055}