BlueGit

ict rusty-teams

Files

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

demo.rs

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