username.rs (2585B)
1 use crate::fonts::NamedFontFamily; 2 use egui::{Color32, RichText, Widget}; 3 use nostrdb::ProfileRecord; 4 5 pub struct Username<'a> { 6 profile: Option<&'a ProfileRecord<'a>>, 7 pk: &'a [u8; 32], 8 pk_colored: bool, 9 abbrev: usize, 10 } 11 12 impl<'a> Username<'a> { 13 pub fn pk_colored(mut self, pk_colored: bool) -> Self { 14 self.pk_colored = pk_colored; 15 self 16 } 17 18 pub fn abbreviated(mut self, amount: usize) -> Self { 19 self.abbrev = amount; 20 self 21 } 22 23 pub fn new(profile: Option<&'a ProfileRecord>, pk: &'a [u8; 32]) -> Self { 24 let pk_colored = false; 25 let abbrev: usize = 1000; 26 Username { 27 profile, 28 pk, 29 pk_colored, 30 abbrev, 31 } 32 } 33 } 34 35 impl Widget for Username<'_> { 36 fn ui(self, ui: &mut egui::Ui) -> egui::Response { 37 ui.horizontal(|ui| { 38 ui.spacing_mut().item_spacing.x = 0.0; 39 40 let color = if self.pk_colored { 41 Some(pk_color(self.pk)) 42 } else { 43 None 44 }; 45 46 if let Some(profile) = self.profile { 47 if let Some(prof) = profile.record().profile() { 48 if prof.display_name().is_some() && prof.display_name().unwrap() != "" { 49 ui_abbreviate_name(ui, prof.display_name().unwrap(), self.abbrev, color); 50 } else if let Some(name) = prof.name() { 51 ui_abbreviate_name(ui, name, self.abbrev, color); 52 } 53 } 54 } else { 55 let mut txt = RichText::new("nostrich").family(NamedFontFamily::Medium.as_family()); 56 if let Some(col) = color { 57 txt = txt.color(col) 58 } 59 ui.label(txt); 60 } 61 }) 62 .response 63 } 64 } 65 66 fn colored_name(name: &str, color: Option<Color32>) -> RichText { 67 let mut txt = RichText::new(name).family(NamedFontFamily::Medium.as_family()); 68 69 if let Some(color) = color { 70 txt = txt.color(color); 71 } 72 73 txt 74 } 75 76 fn ui_abbreviate_name(ui: &mut egui::Ui, name: &str, len: usize, color: Option<Color32>) { 77 let should_abbrev = name.len() > len; 78 let name = if should_abbrev { 79 let closest = crate::abbrev::floor_char_boundary(name, len); 80 &name[..closest] 81 } else { 82 name 83 }; 84 85 ui.label(colored_name(name, color)); 86 87 if should_abbrev { 88 ui.label(colored_name("..", color)); 89 } 90 } 91 92 fn pk_color(pk: &[u8; 32]) -> Color32 { 93 Color32::from_rgb(pk[8], pk[10], pk[12]) 94 }