BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 35.8 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, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
614 users
615 .iter()
616 .map(|(user_id, user_name, created_at)| {
617 serde_json::json!({
618 "reaction_type": kind,
619 "user_id": user_id,
620 "user_name": user_name,
621 "created_at": created_at,
622 })
623 })
624 .collect()
625}
626
627fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
628 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
629}
630
631fn release_messages() -> Vec<MessageRecord> {
632 let chat = RELEASE_CHAT;
633 let mara = (MARA_ID, "Mara Lindqvist");
634 let jonas = (JONAS_ID, "Jonas Ortega");
635 let me = (DEMO_USER_ID, DEMO_USER_NAME);
636 let jonas_name = "Jonas Ortega";
637 let priya_name = "Priya Nair";
638 let lea_name = "Lea Schneider";
639 let mara_name = "Mara Lindqvist";
640 let tobias_name = "Tobias Klein";
641 let likes = reactions_json(vec![reaction(
642 "like",
643 &[
644 (JONAS_ID, jonas_name, at(1, 16, 30)),
645 (PRIYA_ID, priya_name, at(1, 17, 2)),
646 (LEA_ID, lea_name, at(0, 8, 15)),
647 ],
648 )]);
649 let hearts = reactions_json(vec![reaction(
650 "heart",
651 &[
652 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
653 (JONAS_ID, jonas_name, at(0, 10, 33)),
654 ],
655 )]);
656 let single = reactions_json(vec![reaction(
657 "laugh",
658 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
659 )]);
660 let many = reactions_json(vec![
661 reaction(
662 "like",
663 &[
664 (MARA_ID, mara_name, at(0, 13, 37)),
665 (JONAS_ID, jonas_name, at(0, 13, 38)),
666 (PRIYA_ID, priya_name, at(0, 13, 40)),
667 (LEA_ID, lea_name, at(0, 13, 45)),
668 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
669 ],
670 ),
671 reaction(
672 "heart",
673 &[
674 (LEA_ID, lea_name, at(0, 13, 46)),
675 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
676 ],
677 ),
678 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
679 ]);
680 vec![
681 message(
682 chat,
683 "m1",
684 None,
685 mara,
686 at(1, 16, 20),
687 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
688 "[]",
689 false,
690 ),
691 message(
692 chat,
693 "m2",
694 None,
695 mara,
696 at(1, 16, 22),
697 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
698 &likes,
699 false,
700 ),
701 message(
702 chat,
703 "m2b",
704 None,
705 mara,
706 at(1, 16, 40),
707 &format!(
708 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
709 STAGING_SIZE.0, STAGING_SIZE.1
710 ),
711 "[]",
712 false,
713 ),
714 with_attachments(
715 message(
716 chat,
717 "m2c",
718 None,
719 mara,
720 at(1, 16, 41),
721 "<p>Checklist and rollout plan attached.</p>",
722 "[]",
723 false,
724 ),
725 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}]"#,
726 ),
727 message(
728 chat,
729 "m3",
730 None,
731 me,
732 at(0, 9, 2),
733 "<p>I'll take the changelog.</p>",
734 &single,
735 false,
736 ),
737 message(
738 chat,
739 "m4",
740 None,
741 jonas,
742 at(0, 10, 14),
743 "<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>",
744 "[]",
745 false,
746 ),
747 message(
748 chat,
749 "m5",
750 None,
751 mara,
752 at(0, 10, 31),
753 "<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>",
754 &hearts,
755 true,
756 ),
757 message(
758 chat,
759 "m5b",
760 None,
761 mara,
762 at(0, 10, 40),
763 "<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>",
764 "[]",
765 false,
766 ),
767 message(
768 chat,
769 "m5c",
770 None,
771 jonas,
772 at(0, 11, 5),
773 "<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>",
774 "[]",
775 false,
776 ),
777 message(
778 chat,
779 "m6",
780 None,
781 me,
782 at(0, 13, 35),
783 "<p>Thanks, renamed. Tagging now.</p>",
784 "[]",
785 false,
786 ),
787 message(
788 chat,
789 "m7",
790 None,
791 me,
792 at(0, 13, 36),
793 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
794 &many,
795 false,
796 ),
797 ]
798}
799
800fn unread_messages() -> Vec<MessageRecord> {
801 let me = (DEMO_USER_ID, DEMO_USER_NAME);
802 let lea = (LEA_ID, "Lea Schneider");
803 let tobias = (TOBIAS_ID, "Tobias Klein");
804 let rows = [
805 (
806 "u1",
807 me,
808 at(1, 17, 5),
809 "<p>Can you enable access for North?</p>",
810 ),
811 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
812 (
813 "u3",
814 lea,
815 at(0, 12, 40),
816 "<p>Good morning, access is ready.</p>",
817 ),
818 (
819 "u4",
820 lea,
821 at(0, 12, 41),
822 "<p>Sign in with your company ID, no password needed.</p>",
823 ),
824 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
825 ];
826 rows.into_iter()
827 .map(|(id, sender, time, html)| {
828 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
829 })
830 .collect()
831}
832
833fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
834 DEMO_TEAM_ORDER
835 .iter()
836 .map(|team_id| TeamLayoutRecord {
837 team_id: (*team_id).to_owned(),
838 hidden: *team_id == DEMO_HIDDEN_TEAM,
839 channels: channels
840 .iter()
841 .filter(|channel| channel.team_id == *team_id)
842 .map(|channel| ChannelLayoutRecord {
843 channel_id: channel.id.clone(),
844 general: channel.name == "General",
845 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
846 })
847 .collect(),
848 })
849 .collect()
850}
851
852fn channel_messages() -> Vec<MessageRecord> {
853 let channel = "demo-channel-1-1";
854 let mara = (MARA_ID, "Mara Lindqvist");
855 let tobias = (TOBIAS_ID, "Tobias Klein");
856 vec![
857 message(
858 channel,
859 "t1",
860 None,
861 mara,
862 at(0, 8, 0),
863 "<p>Weekly sync notes are up.</p>",
864 "[]",
865 false,
866 ),
867 message(
868 channel,
869 "t1r1",
870 Some("t1"),
871 tobias,
872 at(0, 8, 20),
873 "<p>Thanks, adding my items.</p>",
874 "[]",
875 false,
876 ),
877 message(
878 channel,
879 "t3",
880 None,
881 tobias,
882 at(0, 11, 30),
883 "<p>Release build 42 is green, deploying to staging now.</p>",
884 "[]",
885 false,
886 ),
887 message(
888 channel,
889 "t2",
890 None,
891 tobias,
892 at(0, 11, 0),
893 "<p>Who owns the on-call handover?</p>",
894 "[]",
895 false,
896 ),
897 message(
898 channel,
899 "t4",
900 None,
901 mara,
902 at(3, 8, 42),
903 "<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>",
904 "[]",
905 false,
906 ),
907 message(
908 channel,
909 "t4r1",
910 Some("t4"),
911 tobias,
912 at(0, 9, 15),
913 "<p>Yes, all done.</p>",
914 "[]",
915 false,
916 ),
917 ]
918}
919
920fn crc32(bytes: &[u8]) -> u32 {
921 let mut crc = 0xffff_ffffu32;
922 for byte in bytes {
923 crc ^= u32::from(*byte);
924 for _ in 0..8 {
925 crc = if crc & 1 == 1 {
926 (crc >> 1) ^ 0xedb8_8320
927 } else {
928 crc >> 1
929 };
930 }
931 }
932 !crc
933}
934
935fn adler32(bytes: &[u8]) -> u32 {
936 let (mut low, mut high) = (1u32, 0u32);
937 for byte in bytes {
938 low = (low + u32::from(*byte)) % 65521;
939 high = (high + low) % 65521;
940 }
941 (high << 16) | low
942}
943
944fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
945 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
946 let mut body = kind.to_vec();
947 body.extend_from_slice(data);
948 output.extend_from_slice(&body);
949 output.extend_from_slice(&crc32(&body).to_be_bytes());
950}
951
952fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
953 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
954}
955
956fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
957 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
958 let (x, y) = (column as f32, row as f32);
959 let shade = y / height;
960 let background = [
961 (30. - 14. * shade) as u8,
962 (41. - 16. * shade) as u8,
963 (59. - 14. * shade) as u8,
964 ];
965 let bar_width = width / 14.;
966 let slot = (x / bar_width) as usize;
967 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
968 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
969 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
970 let header = y < height * 0.1;
971 if header {
972 [22, 30, 45]
973 } else if on_bars {
974 if slot % 4 == 3 {
975 [226, 87, 47]
976 } else {
977 [88, 133, 196]
978 }
979 } else if (y - height * 0.86).abs() < 1.5 {
980 [71, 85, 105]
981 } else {
982 background
983 }
984}
985
986fn encode_png(palette: &Palette) -> Vec<u8> {
987 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
988 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
989 if inside(x, y, (24., 21.), (8.5, 9.5)) {
990 palette.skin
991 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
992 palette.hair
993 } else if inside(x, y, (24., 50.), (22., 19.)) {
994 palette.shirt
995 } else {
996 palette.background
997 }
998 })
999}
1000
1001fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
1002 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
1003 for row in 0..height {
1004 raw.push(0);
1005 for column in 0..width {
1006 raw.extend_from_slice(&pixel(column, row));
1007 }
1008 }
1009 let mut zlib = vec![0x78, 0x01];
1010 let mut blocks = raw.chunks(65535).peekable();
1011 while let Some(block) = blocks.next() {
1012 zlib.push(u8::from(blocks.peek().is_none()));
1013 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
1014 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
1015 zlib.extend_from_slice(block);
1016 }
1017 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
1018 let mut header = Vec::new();
1019 header.extend_from_slice(&(width as u32).to_be_bytes());
1020 header.extend_from_slice(&(height as u32).to_be_bytes());
1021 header.extend_from_slice(&[8, 2, 0, 0, 0]);
1022 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
1023 png_chunk(&mut png, b"IHDR", &header);
1024 png_chunk(&mut png, b"IDAT", &zlib);
1025 png_chunk(&mut png, b"IEND", &[]);
1026 png
1027}
1028
1029#[cfg(test)]
1030mod tests {
1031 use super::*;
1032
1033 #[test]
1034 fn png_has_signature_and_ends_with_iend() {
1035 let png = encode_png(&MARA);
1036 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
1037 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
1038 }
1039
1040 #[test]
1041 fn crc_and_adler_match_known_values() {
1042 assert_eq!(crc32(b"IEND"), 0xae42_6082);
1043 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
1044 }
1045
1046 #[test]
1047 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
1048 let chat = mention_candidates("demo-chat-release", "ma");
1049 assert_eq!(chat.len(), 1);
1050 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
1051 let channel = mention_candidates("demo-channel-1-1", "gen");
1052 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
1053 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
1054 }
1055
1056 #[test]
1057 fn new_group_chat_gets_a_title_and_the_first_message() {
1058 let people = vec![
1059 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
1060 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1061 ];
1062 let now = Utc::now();
1063 let (chat, record) = new_chat(&[], &people, Some("Crew"), "Hello *all*", now);
1064 assert_eq!(chat.id, "demo-chat-new-1");
1065 assert_eq!(chat.kind, "group");
1066 assert_eq!(chat.title, "Crew");
1067 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1068 assert_eq!(chat.members.len(), 3);
1069 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1070 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello *all*"));
1071 assert_eq!(chat.last_message_at, Some(now));
1072 assert_eq!(record.conversation_id, chat.id);
1073 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1074 assert!(record.body_html.contains("Hello"));
1075 }
1076
1077 #[test]
1078 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1079 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1080 let (first, _) = new_chat(&[], &people, None, "Hi", Utc::now());
1081 assert_eq!(first.kind, "oneOnOne");
1082 assert!(first.title.is_empty());
1083 let (second, _) = new_chat(&[first], &people, None, "Hi again", Utc::now());
1084 assert_eq!(second.id, "demo-chat-new-2");
1085 }
1086
1087 #[test]
1088 fn sending_into_a_chat_refreshes_its_preview() {
1089 let base = ChatRecord {
1090 id: "demo-chat-x".to_owned(),
1091 unread: true,
1092 ..Default::default()
1093 };
1094 let (chat, record) = send_in_chat(&base, "Ping", Utc::now());
1095 assert!(!chat.unread);
1096 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1097 assert_eq!(record.conversation_id, "demo-chat-x");
1098 }
1099
1100 #[test]
1101 fn demo_covers_the_sidebar_edge_cases() {
1102 let chats = demo_chats();
1103 assert!(chats.iter().any(|chat| chat.deleted));
1104 assert!(chats.iter().any(|chat| chat.title.len() > 40));
1105 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
1106 }
1107}