BlueGit

ict rusty-teams

Files

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

demo.rs

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