BlueGit

ict rusty-teams

Files

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

demo.rs

62bd9112 History
demo.rs 35.9 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 preview: &str,
337 html: &str,
338 now: DateTime<Utc>,
339) -> (ChatRecord, MessageRecord) {
340 let mut chat = chat.clone();
341 chat.last_message_at = Some(now);
342 chat.last_message_preview = Some(preview.to_owned());
343 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
344 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
345 chat.last_message_deleted = false;
346 chat.unread = false;
347 let record = message(
348 &chat.id,
349 &format!("demo-sent-{}", now.timestamp_millis()),
350 None,
351 (DEMO_USER_ID, DEMO_USER_NAME),
352 now,
353 html,
354 "[]",
355 false,
356 );
357 (chat, record)
358}
359
360pub fn new_chat(
361 existing: &[ChatRecord],
362 people: &[(String, String)],
363 topic: Option<&str>,
364 preview: &str,
365 html: &str,
366 now: DateTime<Utc>,
367) -> (ChatRecord, MessageRecord) {
368 let number = existing
369 .iter()
370 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
371 .count()
372 + 1;
373 let one_on_one = people.len() == 1;
374 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
375 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
376 .collect();
377 let chat = ChatRecord {
378 id: format!("{NEW_CHAT_PREFIX}{number}"),
379 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
380 title: if one_on_one {
381 String::new()
382 } else {
383 topic.unwrap_or_default().to_owned()
384 },
385 member_summary: people
386 .iter()
387 .map(|(_, name)| name.as_str())
388 .collect::<Vec<_>>()
389 .join(", "),
390 members,
391 ..Default::default()
392 };
393 send_in_chat(&chat, preview, html, now)
394}
395
396fn image_directory() -> PathBuf {
397 std::env::temp_dir().join("rusty-teams-demo")
398}
399
400pub fn first_unread(conversation_id: &str) -> Option<String> {
401 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
402}
403
404pub fn read_message_ids(records: &[MessageRecord]) -> std::collections::HashSet<String> {
405 let newest = records.iter().max_by_key(|record| record.created_at);
406 records
407 .iter()
408 .filter(|record| {
409 Some(record.message_id.as_str()) != newest.map(|newest| newest.message_id.as_str())
410 })
411 .map(|record| record.message_id.clone())
412 .collect()
413}
414
415pub fn first_selection() -> Selection {
416 Selection::Chat(RELEASE_CHAT.to_owned())
417}
418
419pub fn seed(store: &Store) {
420 let chats: Vec<ChatRecord> = demo_chats()
421 .into_iter()
422 .map(|demo| ChatRecord {
423 id: demo.id.to_owned(),
424 kind: demo.kind.to_owned(),
425 title: if demo.kind == "oneOnOne" {
426 String::new()
427 } else {
428 demo.title.to_owned()
429 },
430 member_summary: demo.title.to_owned(),
431 last_message_at: Some(demo.time),
432 unread: demo.unread,
433 members: demo.members,
434 last_message_preview: demo.preview.map(|(_, _, text)| text.to_owned()),
435 last_message_sender_id: demo.preview.map(|(id, _, _)| id.to_owned()),
436 last_message_sender_name: demo.preview.map(|(_, name, _)| name.to_owned()),
437 last_message_deleted: demo.deleted,
438 ..Default::default()
439 })
440 .collect();
441 let _ = store.upsert_chats(&chats);
442 let teams: Vec<TeamRecord> = DEMO_TEAMS
443 .iter()
444 .map(|(id, name, _)| TeamRecord {
445 id: (*id).to_owned(),
446 name: (*name).to_owned(),
447 })
448 .collect();
449 let _ = store.upsert_teams(&teams);
450 let mut channels = Vec::new();
451 for (team_index, (team_id, _, names)) in DEMO_TEAMS.iter().enumerate() {
452 for (channel_index, name) in names.iter().enumerate() {
453 channels.push(ChannelRecord {
454 id: format!("demo-channel-{}-{}", team_index + 1, channel_index + 1),
455 team_id: (*team_id).to_owned(),
456 name: (*name).to_owned(),
457 membership_type: None,
458 last_message_at: Some(at(channel_index as i64, 12, 10)),
459 unread: (team_index == 0 && channel_index == 1)
460 || (team_index == 1 && channel_index == 0),
461 });
462 }
463 }
464 let _ = store.upsert_channels(&channels);
465 let _ = store.replace_team_layout(&demo_team_layout(&channels));
466 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
467 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
468 let _ = store.upsert_messages(&release_messages());
469 let _ = store.upsert_messages(&unread_messages());
470 let _ = store.upsert_messages(&channel_messages());
471 let _ = store.upsert_messages(&priority_messages());
472}
473
474fn photo(palette: &Palette) -> Arc<Image> {
475 crate::data::avatar_image_from("image/png", encode_png(palette))
476}
477
478pub fn seed_directory(state: &mut AppState) {
479 let directory = &mut state.directory;
480 directory.me = Some(Person {
481 user_id: DEMO_USER_ID.to_owned(),
482 display_name: DEMO_USER_NAME.to_owned(),
483 });
484 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
485 directory.folders = vec![
486 FolderInfo {
487 id: FAVORITES_ID.to_owned(),
488 name: String::new(),
489 kind: FolderKind::Favorites,
490 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
491 },
492 FolderInfo {
493 id: CUSTOMERS_FOLDER.to_owned(),
494 name: "Customers".to_owned(),
495 kind: FolderKind::UserCreated,
496 conversation_ids: ids(&[
497 "demo-chat-customer-1",
498 "demo-chat-customer-2",
499 "demo-chat-customer-3",
500 "demo-chat-customer-4",
501 ]),
502 },
503 FolderInfo {
504 id: ATLAS_FOLDER.to_owned(),
505 name: "Project Atlas".to_owned(),
506 kind: FolderKind::UserCreated,
507 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
508 },
509 FolderInfo {
510 id: TODO_FOLDER.to_owned(),
511 name: "To do".to_owned(),
512 kind: FolderKind::UserCreated,
513 conversation_ids: Vec::new(),
514 },
515 ];
516 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
517 directory
518 .unread_counts
519 .insert("demo-chat-atlas".to_owned(), 5);
520 directory
521 .unread_counts
522 .insert("demo-chat-customer-1".to_owned(), 2);
523 directory
524 .unread_counts
525 .insert("demo-chat-customer-2".to_owned(), 1);
526 directory
527 .unread_counts
528 .insert("demo-chat-allhands".to_owned(), 120);
529 directory.set_avatar(MARA_ID, Some(photo(&MARA)));
530 directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
531 directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
532 for (user_id, kind) in [
533 (MARA_ID, PresenceKind::Available),
534 (JONAS_ID, PresenceKind::DoNotDisturb),
535 (PRIYA_ID, PresenceKind::Away),
536 (TOBIAS_ID, PresenceKind::Offline),
537 (LEA_ID, PresenceKind::DoNotDisturb),
538 (DEMO_USER_ID, PresenceKind::Available),
539 ] {
540 directory.set_presence(user_id, kind);
541 }
542 let directory_path = image_directory();
543 if std::fs::create_dir_all(&directory_path).is_ok() {
544 let path = directory_path.join("staging-dashboard.png");
545 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
546 if std::fs::write(&path, png).is_ok() {
547 state.directory.set_image(STAGING_IMAGE_KEY, &path);
548 }
549 }
550 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
551 state.last_sync = Some(Utc::now());
552}
553
554#[allow(clippy::too_many_arguments)]
555fn message(
556 conversation: &str,
557 id: &str,
558 reply_to: Option<&str>,
559 sender: (&str, &str),
560 time: DateTime<Utc>,
561 html: &str,
562 reactions_json: &str,
563 edited: bool,
564) -> MessageRecord {
565 MessageRecord {
566 conversation_id: conversation.to_owned(),
567 message_id: id.to_owned(),
568 reply_to_id: reply_to.map(str::to_owned),
569 sender_id: Some(sender.0.to_owned()),
570 sender_name: Some(sender.1.to_owned()),
571 created_at: time,
572 edited_at: edited.then_some(time + Duration::minutes(2)),
573 deleted: false,
574 body_html: html.to_owned(),
575 attachments_json: "[]".to_owned(),
576 reactions_json: reactions_json.to_owned(),
577 mentions_json: "[]".to_owned(),
578 }
579}
580
581fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
582 record.attachments_json = attachments_json.to_owned();
583 record
584}
585
586fn priority_messages() -> Vec<MessageRecord> {
587 let priya = (PRIYA_ID, "Priya Nair");
588 let me = (DEMO_USER_ID, DEMO_USER_NAME);
589 vec![
590 message(
591 PRIORITY_CHAT,
592 "p1",
593 None,
594 me,
595 at(0, 10, 40),
596 "<p>Have you seen the error on staging yet?</p>",
597 "[]",
598 false,
599 ),
600 message(
601 PRIORITY_CHAT,
602 "p2",
603 None,
604 priya,
605 at(0, 10, 47),
606 &format!(
607 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
608 ),
609 "[]",
610 false,
611 ),
612 ]
613}
614
615fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
616 users
617 .iter()
618 .map(|(user_id, user_name, created_at)| {
619 serde_json::json!({
620 "reaction_type": kind,
621 "user_id": user_id,
622 "user_name": user_name,
623 "created_at": created_at,
624 })
625 })
626 .collect()
627}
628
629fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
630 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
631}
632
633fn release_messages() -> Vec<MessageRecord> {
634 let chat = RELEASE_CHAT;
635 let mara = (MARA_ID, "Mara Lindqvist");
636 let jonas = (JONAS_ID, "Jonas Ortega");
637 let me = (DEMO_USER_ID, DEMO_USER_NAME);
638 let jonas_name = "Jonas Ortega";
639 let priya_name = "Priya Nair";
640 let lea_name = "Lea Schneider";
641 let mara_name = "Mara Lindqvist";
642 let tobias_name = "Tobias Klein";
643 let likes = reactions_json(vec![reaction(
644 "like",
645 &[
646 (JONAS_ID, jonas_name, at(1, 16, 30)),
647 (PRIYA_ID, priya_name, at(1, 17, 2)),
648 (LEA_ID, lea_name, at(0, 8, 15)),
649 ],
650 )]);
651 let hearts = reactions_json(vec![reaction(
652 "heart",
653 &[
654 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
655 (JONAS_ID, jonas_name, at(0, 10, 33)),
656 ],
657 )]);
658 let single = reactions_json(vec![reaction(
659 "laugh",
660 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
661 )]);
662 let many = reactions_json(vec![
663 reaction(
664 "like",
665 &[
666 (MARA_ID, mara_name, at(0, 13, 37)),
667 (JONAS_ID, jonas_name, at(0, 13, 38)),
668 (PRIYA_ID, priya_name, at(0, 13, 40)),
669 (LEA_ID, lea_name, at(0, 13, 45)),
670 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
671 ],
672 ),
673 reaction(
674 "heart",
675 &[
676 (LEA_ID, lea_name, at(0, 13, 46)),
677 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
678 ],
679 ),
680 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
681 ]);
682 vec![
683 message(
684 chat,
685 "m1",
686 None,
687 mara,
688 at(1, 16, 20),
689 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
690 "[]",
691 false,
692 ),
693 message(
694 chat,
695 "m2",
696 None,
697 mara,
698 at(1, 16, 22),
699 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
700 &likes,
701 false,
702 ),
703 message(
704 chat,
705 "m2b",
706 None,
707 mara,
708 at(1, 16, 40),
709 &format!(
710 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
711 STAGING_SIZE.0, STAGING_SIZE.1
712 ),
713 "[]",
714 false,
715 ),
716 with_attachments(
717 message(
718 chat,
719 "m2c",
720 None,
721 mara,
722 at(1, 16, 41),
723 "<p>Checklist and rollout plan attached.</p>",
724 "[]",
725 false,
726 ),
727 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}]"#,
728 ),
729 message(
730 chat,
731 "m3",
732 None,
733 me,
734 at(0, 9, 2),
735 "<p>I'll take the changelog.</p>",
736 &single,
737 false,
738 ),
739 message(
740 chat,
741 "m4",
742 None,
743 jonas,
744 at(0, 10, 14),
745 "<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>",
746 "[]",
747 false,
748 ),
749 message(
750 chat,
751 "m5",
752 None,
753 mara,
754 at(0, 10, 31),
755 "<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>",
756 &hearts,
757 true,
758 ),
759 message(
760 chat,
761 "m5b",
762 None,
763 mara,
764 at(0, 10, 40),
765 "<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>",
766 "[]",
767 false,
768 ),
769 message(
770 chat,
771 "m5c",
772 None,
773 jonas,
774 at(0, 11, 5),
775 "<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>",
776 "[]",
777 false,
778 ),
779 message(
780 chat,
781 "m6",
782 None,
783 me,
784 at(0, 13, 35),
785 "<p>Thanks, renamed. Tagging now.</p>",
786 "[]",
787 false,
788 ),
789 message(
790 chat,
791 "m7",
792 None,
793 me,
794 at(0, 13, 36),
795 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
796 &many,
797 false,
798 ),
799 ]
800}
801
802fn unread_messages() -> Vec<MessageRecord> {
803 let me = (DEMO_USER_ID, DEMO_USER_NAME);
804 let lea = (LEA_ID, "Lea Schneider");
805 let tobias = (TOBIAS_ID, "Tobias Klein");
806 let rows = [
807 (
808 "u1",
809 me,
810 at(1, 17, 5),
811 "<p>Can you enable access for North?</p>",
812 ),
813 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
814 (
815 "u3",
816 lea,
817 at(0, 12, 40),
818 "<p>Good morning, access is ready.</p>",
819 ),
820 (
821 "u4",
822 lea,
823 at(0, 12, 41),
824 "<p>Sign in with your company ID, no password needed.</p>",
825 ),
826 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
827 ];
828 rows.into_iter()
829 .map(|(id, sender, time, html)| {
830 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
831 })
832 .collect()
833}
834
835fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
836 DEMO_TEAM_ORDER
837 .iter()
838 .map(|team_id| TeamLayoutRecord {
839 team_id: (*team_id).to_owned(),
840 hidden: *team_id == DEMO_HIDDEN_TEAM,
841 channels: channels
842 .iter()
843 .filter(|channel| channel.team_id == *team_id)
844 .map(|channel| ChannelLayoutRecord {
845 channel_id: channel.id.clone(),
846 general: channel.name == "General",
847 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
848 })
849 .collect(),
850 })
851 .collect()
852}
853
854fn channel_messages() -> Vec<MessageRecord> {
855 let channel = "demo-channel-1-1";
856 let mara = (MARA_ID, "Mara Lindqvist");
857 let tobias = (TOBIAS_ID, "Tobias Klein");
858 vec![
859 message(
860 channel,
861 "t1",
862 None,
863 mara,
864 at(0, 8, 0),
865 "<p>Weekly sync notes are up.</p>",
866 "[]",
867 false,
868 ),
869 message(
870 channel,
871 "t1r1",
872 Some("t1"),
873 tobias,
874 at(0, 8, 20),
875 "<p>Thanks, adding my items.</p>",
876 "[]",
877 false,
878 ),
879 message(
880 channel,
881 "t3",
882 None,
883 tobias,
884 at(0, 11, 30),
885 "<p>Release build 42 is green, deploying to staging now.</p>",
886 "[]",
887 false,
888 ),
889 message(
890 channel,
891 "t2",
892 None,
893 tobias,
894 at(0, 11, 0),
895 "<p>Who owns the on-call handover?</p>",
896 "[]",
897 false,
898 ),
899 message(
900 channel,
901 "t4",
902 None,
903 mara,
904 at(3, 8, 42),
905 "<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>",
906 "[]",
907 false,
908 ),
909 message(
910 channel,
911 "t4r1",
912 Some("t4"),
913 tobias,
914 at(0, 9, 15),
915 "<p>Yes, all done.</p>",
916 "[]",
917 false,
918 ),
919 ]
920}
921
922fn crc32(bytes: &[u8]) -> u32 {
923 let mut crc = 0xffff_ffffu32;
924 for byte in bytes {
925 crc ^= u32::from(*byte);
926 for _ in 0..8 {
927 crc = if crc & 1 == 1 {
928 (crc >> 1) ^ 0xedb8_8320
929 } else {
930 crc >> 1
931 };
932 }
933 }
934 !crc
935}
936
937fn adler32(bytes: &[u8]) -> u32 {
938 let (mut low, mut high) = (1u32, 0u32);
939 for byte in bytes {
940 low = (low + u32::from(*byte)) % 65521;
941 high = (high + low) % 65521;
942 }
943 (high << 16) | low
944}
945
946fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
947 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
948 let mut body = kind.to_vec();
949 body.extend_from_slice(data);
950 output.extend_from_slice(&body);
951 output.extend_from_slice(&crc32(&body).to_be_bytes());
952}
953
954fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
955 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
956}
957
958fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
959 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
960 let (x, y) = (column as f32, row as f32);
961 let shade = y / height;
962 let background = [
963 (30. - 14. * shade) as u8,
964 (41. - 16. * shade) as u8,
965 (59. - 14. * shade) as u8,
966 ];
967 let bar_width = width / 14.;
968 let slot = (x / bar_width) as usize;
969 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
970 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
971 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
972 let header = y < height * 0.1;
973 if header {
974 [22, 30, 45]
975 } else if on_bars {
976 if slot % 4 == 3 {
977 [226, 87, 47]
978 } else {
979 [88, 133, 196]
980 }
981 } else if (y - height * 0.86).abs() < 1.5 {
982 [71, 85, 105]
983 } else {
984 background
985 }
986}
987
988fn encode_png(palette: &Palette) -> Vec<u8> {
989 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
990 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
991 if inside(x, y, (24., 21.), (8.5, 9.5)) {
992 palette.skin
993 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
994 palette.hair
995 } else if inside(x, y, (24., 50.), (22., 19.)) {
996 palette.shirt
997 } else {
998 palette.background
999 }
1000 })
1001}
1002
1003fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
1004 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
1005 for row in 0..height {
1006 raw.push(0);
1007 for column in 0..width {
1008 raw.extend_from_slice(&pixel(column, row));
1009 }
1010 }
1011 let mut zlib = vec![0x78, 0x01];
1012 let mut blocks = raw.chunks(65535).peekable();
1013 while let Some(block) = blocks.next() {
1014 zlib.push(u8::from(blocks.peek().is_none()));
1015 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
1016 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
1017 zlib.extend_from_slice(block);
1018 }
1019 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
1020 let mut header = Vec::new();
1021 header.extend_from_slice(&(width as u32).to_be_bytes());
1022 header.extend_from_slice(&(height as u32).to_be_bytes());
1023 header.extend_from_slice(&[8, 2, 0, 0, 0]);
1024 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
1025 png_chunk(&mut png, b"IHDR", &header);
1026 png_chunk(&mut png, b"IDAT", &zlib);
1027 png_chunk(&mut png, b"IEND", &[]);
1028 png
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033 use super::*;
1034
1035 #[test]
1036 fn png_has_signature_and_ends_with_iend() {
1037 let png = encode_png(&MARA);
1038 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
1039 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
1040 }
1041
1042 #[test]
1043 fn crc_and_adler_match_known_values() {
1044 assert_eq!(crc32(b"IEND"), 0xae42_6082);
1045 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
1046 }
1047
1048 #[test]
1049 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
1050 let chat = mention_candidates("demo-chat-release", "ma");
1051 assert_eq!(chat.len(), 1);
1052 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
1053 let channel = mention_candidates("demo-channel-1-1", "gen");
1054 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
1055 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
1056 }
1057
1058 #[test]
1059 fn new_group_chat_gets_a_title_and_the_first_message() {
1060 let people = vec![
1061 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
1062 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1063 ];
1064 let now = Utc::now();
1065 let (chat, record) = new_chat(
1066 &[],
1067 &people,
1068 Some("Crew"),
1069 "Hello all",
1070 "Hello <i>all</i>",
1071 now,
1072 );
1073 assert_eq!(chat.id, "demo-chat-new-1");
1074 assert_eq!(chat.kind, "group");
1075 assert_eq!(chat.title, "Crew");
1076 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1077 assert_eq!(chat.members.len(), 3);
1078 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1079 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
1080 assert_eq!(chat.last_message_at, Some(now));
1081 assert_eq!(record.conversation_id, chat.id);
1082 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1083 assert!(record.body_html.contains("Hello"));
1084 }
1085
1086 #[test]
1087 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1088 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1089 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
1090 assert_eq!(first.kind, "oneOnOne");
1091 assert!(first.title.is_empty());
1092 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
1093 assert_eq!(second.id, "demo-chat-new-2");
1094 }
1095
1096 #[test]
1097 fn sending_into_a_chat_refreshes_its_preview() {
1098 let base = ChatRecord {
1099 id: "demo-chat-x".to_owned(),
1100 unread: true,
1101 ..Default::default()
1102 };
1103 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
1104 assert!(!chat.unread);
1105 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1106 assert_eq!(record.conversation_id, "demo-chat-x");
1107 }
1108
1109 #[test]
1110 fn demo_covers_the_sidebar_edge_cases() {
1111 let chats = demo_chats();
1112 assert!(chats.iter().any(|chat| chat.deleted));
1113 assert!(chats.iter().any(|chat| chat.title.len() > 40));
1114 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
1115 }
1116}