username.rs (2259B)
1 use crate::fonts::NamedFontFamily; 2 use egui::{Color32, Label, 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<'a> Widget for Username<'a> { 36 fn ui(self, ui: &mut egui::Ui) -> egui::Response { 37 ui.horizontal(|ui| { 38 //ui.spacing_mut().item_spacing.x = 0.0; 39 if let Some(profile) = self.profile { 40 if let Some(prof) = profile.record.profile() { 41 let color = if self.pk_colored { 42 Some(pk_color(self.pk)) 43 } else { 44 None 45 }; 46 47 if prof.display_name().is_some() && prof.display_name().unwrap() != "" { 48 ui_abbreviate_name(ui, prof.display_name().unwrap(), self.abbrev, color); 49 } else if let Some(name) = prof.name() { 50 ui_abbreviate_name(ui, name, self.abbrev, color); 51 } 52 } 53 } else { 54 ui.strong("nostrich"); 55 } 56 }) 57 .response 58 } 59 } 60 61 fn ui_abbreviate_name(ui: &mut egui::Ui, name: &str, len: usize, color: Option<Color32>) { 62 if name.len() > len { 63 let closest = crate::abbrev::floor_char_boundary(name, len); 64 ui.strong(&name[..closest]); 65 ui.strong("..."); 66 } else { 67 let mut txt = RichText::new(name).family(NamedFontFamily::Medium.as_family()); 68 if let Some(c) = color { 69 txt = txt.color(c); 70 } 71 ui.add(Label::new(txt)); 72 } 73 } 74 75 fn pk_color(pk: &[u8; 32]) -> Color32 { 76 Color32::from_rgb(pk[8], pk[10], pk[12]) 77 }