Show tags above the fold and fill the content preview

Four fixes from review of the content rendering:

- Tags move out of the collapsed Details expander to just below the content.
  For a follow list or a relay list the tags are the payload, so hiding them
  behind Details was wrong. Request::Sign.tags is now Option<String>, so the
  row is left out when there are none instead of showing "No tags".
- Empty content hides the Content group entirely rather than showing a note;
  the kind-aware content_note goes with it.
- The shared plain label now fills its allocation. It was start-aligned, so
  wrapped lines stopped at the label's natural width and never spanned the
  dialog; measured under Broadway, the preview text now fills the 480 px
  content area. The preview pages also get padding so the content is not
  flush against the edges.
- Kind 0 collapses synonymous keys (name / display_name / displayName /
  username) into one row when their values agree; differing values are all
  kept, so a discrepancy stays visible. The preview's Formatted page never
  collapses and Original keeps the raw JSON. name and display_name also get
  distinct labels now (NIP-24), so they cannot read as one duplicated field.
This commit is contained in:
raucao committed 2026-11-26 15:23:46 +04:00
1 parent ab41b29669
commit 97a27fa518
6 files changed
+163 -53

No files matched your search

+4 -1
View File
@@ -60,7 +60,10 @@ pub enum Request {
/// show it in full; it is **not** reduced to a short preview, because
/// the original bytes are what gets signed.
content: String,
tags: String,
/// A short, plain summary of the event's tags, or `None` when there are
/// none. Shown below the content, because for some kinds (a follow list,
/// a relay list) the tags *are* the payload.
tags: Option<String>,
},
/// A message would be encrypted to someone.
Encrypt {
+11 -4
View File
@@ -1216,9 +1216,12 @@ fn content(text: &str) -> String {
}
/// A short, plain summary of an event's tags: `name=value, name=value, …`.
fn tag_summary(tags: &[Tag]) -> String {
///
/// `None` when there are no tags, so the dialog leaves the row out rather than
/// showing "No tags".
fn tag_summary(tags: &[Tag]) -> Option<String> {
if tags.is_empty() {
return "No tags".to_string();
return None;
}
let mut parts = Vec::new();
for tag in tags.iter().take(6) {
@@ -1241,7 +1244,7 @@ fn tag_summary(tags: &[Tag]) -> String {
if tags.len() > 6 {
summary.push_str(", …");
}
summary
Some(summary)
}
/// Trim a single tag value so a wall of text cannot flood the dialog.
@@ -1899,7 +1902,11 @@ mod tests {
.expect("the user was asked");
assert_eq!(shown.0, 1);
assert!(shown.1.contains("hello world"), "content was {:?}", shown.1);
assert!(shown.2.contains("t=nostr"), "tags were {:?}", shown.2);
assert!(
shown.2.as_deref().unwrap_or_default().contains("t=nostr"),
"tags were {:?}",
shown.2
);
}
#[tokio::test]
+15 -5
View File
@@ -454,12 +454,23 @@ fn details(
match &question.request {
Request::Pair { .. } => {}
// The content is the decision, so it gets a structured, readable view
// rather than raw JSON — with the original one click away.
// rather than raw JSON — with the original one click away. Empty content
// leaves the group out entirely: for a follow or relay list the tags
// below are the payload.
Request::Sign {
kind,
content: signed,
..
} => content.append(&content::card(signed, *kind, widget, deadline)),
tags,
} => {
if content::has_content(signed) {
content.append(&content::card(signed, *kind, widget, deadline));
}
// Tags stay in view rather than collapsed under Details, because for
// some kinds they are the payload itself.
if let Some(tags) = tags {
content.append(&plain::text_field("Tags", tags));
}
}
Request::Encrypt { preview, .. } => content.append(&block("Message", preview)),
Request::Decrypt { preview, .. } => content.append(&block("Ciphertext", preview)),
}
@@ -505,12 +516,11 @@ fn more_details(question: &Question) -> gtk::ListBox {
row.add_row(&plain::row("Asked for", requested));
}
}
Request::Sign { kind, tags, .. } => {
Request::Sign { kind, .. } => {
row.add_row(&plain::row(
"Kind",
&format!("{} ({})", kind, kind::name(*kind)),
));
row.add_row(&plain::row("Tags", tags));
}
Request::Encrypt { method, peer, .. } | Request::Decrypt { method, peer, .. } => {
row.add_row(&plain::row("Method", method));
+99 -21
View File
@@ -10,6 +10,7 @@
//! bytes — so the content text is always one click away, in the preview's
//! **Original** page.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use adw::prelude::*;
@@ -53,10 +54,20 @@ enum View {
#[derive(Debug, PartialEq)]
struct Field {
/// The raw JSON key, kept so synonymous keys can be grouped.
key: String,
label: String,
value: Value,
}
/// Whether there is any content to show at all.
///
/// Empty content leaves the Content group out entirely: for a follow or relay
/// list the payload is in the tags, and an empty card would only be noise.
pub fn has_content(content: &str) -> bool {
!content.trim().is_empty()
}
/// Classify the content for display.
fn view(content: &str, kind_number: u16) -> View {
let trimmed = content.trim();
@@ -67,6 +78,7 @@ fn view(content: &str, kind_number: u16) -> View {
Ok(Value::Object(map)) => View::Fields(
map.iter()
.map(|(key, value)| Field {
key: key.clone(),
label: kind::field_label(kind_number, key)
.map(str::to_string)
.unwrap_or_else(|| key.clone()),
@@ -86,6 +98,53 @@ fn inline_slice(fields: &[Field]) -> (&[Field], usize) {
(&fields[..shown], fields.len() - shown)
}
/// Collapse synonymous keys whose values agree into a single row.
///
/// A client may send `name`, `display_name`, `displayName` and `username` for
/// the same profile. Four identical rows are noise; when the values differ they
/// are all kept, so a discrepancy stays visible. The preview's formatted page
/// does not collapse, so the full set is always one click away.
fn collapse(fields: Vec<Field>) -> Vec<Field> {
let mut by_group: HashMap<&'static str, Vec<usize>> = HashMap::new();
for (index, field) in fields.iter().enumerate() {
if let Some(group) = kind::field_group(&field.key) {
by_group.entry(group).or_default().push(index);
}
}
let mut keep = vec![true; fields.len()];
let mut relabel: HashMap<usize, &'static str> = HashMap::new();
for (group, indices) in &by_group {
if indices.len() < 2 {
continue;
}
let first = indices[0];
if indices
.iter()
.all(|&index| fields[index].value == fields[first].value)
{
relabel.insert(first, group);
for &index in &indices[1..] {
keep[index] = false;
}
}
}
fields
.into_iter()
.enumerate()
.filter_map(|(index, mut field)| {
if !keep[index] {
return None;
}
if let Some(group) = relabel.get(&index) {
field.label = (*group).to_string();
}
Some(field)
})
.collect()
}
/// The inline card: a header with a "View full content" button, then a bounded
/// structured body.
///
@@ -170,6 +229,7 @@ fn inline(content: &str, kind_number: u16) -> gtk::Widget {
.orientation(gtk::Orientation::Vertical)
.spacing(6)
.build();
let fields = collapse(fields);
let (shown, omitted) = inline_slice(&fields);
for field in shown {
boxed.append(&field_row(&field.label, &field.value));
@@ -186,17 +246,16 @@ fn inline(content: &str, kind_number: u16) -> gtk::Widget {
}
View::Json(pretty) => monospace(&pretty),
View::Text(text) => plain::label(&text).upcast(),
View::Empty => empty_body(kind_number),
View::Empty => empty_body(),
}
}
/// What to show when the content is empty: a kind-aware note if we have one,
/// otherwise a plain "(empty)".
fn empty_body(kind_number: u16) -> gtk::Widget {
match kind::content_note(kind_number) {
Some(note) => dim(note).upcast(),
None => plain::label("(empty)").upcast(),
}
/// What to show if empty content ever reaches the renderer.
///
/// The dialog hides the Content group when there is nothing to show, so this is
/// only a defensive fallback.
fn empty_body() -> gtk::Widget {
plain::label("(empty)").upcast()
}
/// One inline field: a scalar value, or a summary for a nested object/array.
@@ -272,12 +331,12 @@ fn present_preview(
// single page rather than a switcher between two identical views.
let structured = matches!(classified, View::Fields(_) | View::Json(_));
let formatted = scroller(&formatted_page(classified, kind_number));
let formatted = padded_scroller(&formatted_page(classified));
let header = adw::HeaderBar::new();
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&header);
if structured {
let original = scroller(&monospace(content));
let original = padded_scroller(&monospace(content));
let stack = gtk::Stack::builder().build();
stack.add_titled(&formatted, Some("formatted"), "Formatted");
stack.add_titled(&original, Some("original"), "Original");
@@ -305,10 +364,19 @@ fn present_preview(
}
}
/// A bounded, natural-height scroller for one preview page.
fn scroller(child: &impl IsA<gtk::Widget>) -> gtk::ScrolledWindow {
/// A bounded, natural-height scroller for one preview page, with the content
/// inset so it is not flush against the dialog edges.
fn padded_scroller(child: &impl IsA<gtk::Widget>) -> gtk::ScrolledWindow {
let padded = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.margin_top(18)
.margin_bottom(18)
.margin_start(12)
.margin_end(12)
.build();
padded.append(child);
gtk::ScrolledWindow::builder()
.child(child)
.child(&padded)
.propagate_natural_height(true)
.max_content_height(PREVIEW_HEIGHT)
.hscrollbar_policy(gtk::PolicyType::Never)
@@ -317,7 +385,7 @@ fn scroller(child: &impl IsA<gtk::Widget>) -> gtk::ScrolledWindow {
/// The preview's formatted page: every field, with nested structure shown in
/// place, so nothing hides behind a collapsed expander.
fn formatted_page(classified: View, kind_number: u16) -> gtk::Widget {
fn formatted_page(classified: View) -> gtk::Widget {
match classified {
View::Fields(fields) => {
let boxed = vertical();
@@ -332,7 +400,7 @@ fn formatted_page(classified: View, kind_number: u16) -> gtk::Widget {
}
View::Json(pretty) => monospace(&pretty),
View::Text(text) => plain::label(&text).upcast(),
View::Empty => empty_body(kind_number),
View::Empty => empty_body(),
}
}
@@ -423,15 +491,11 @@ mod tests {
let parsed = fields(r#"{"name":"Alice","about":"hi"}"#);
assert_eq!(parsed.len(), 2);
assert!(
parsed.iter().any(|field| field.label == "Display name"),
parsed.iter().any(|field| field.label == "Name"),
"the kind-specific label is used, got {parsed:?}"
);
assert_eq!(
parsed
.iter()
.find(|f| f.label == "Display name")
.unwrap()
.value,
parsed.iter().find(|f| f.label == "Name").unwrap().value,
json!("Alice")
);
}
@@ -492,4 +556,18 @@ mod tests {
assert_eq!(split_rows(5), (5, 0));
assert_eq!(split_rows(PREVIEW_ROWS + 3), (PREVIEW_ROWS, 3));
}
/// Synonymous keys with equal values collapse to one row; differing values
/// are all kept so a discrepancy stays visible.
#[test]
fn equal_synonyms_collapse_and_differing_ones_do_not() {
let same = collapse(fields(
r#"{"name":"Alice","display_name":"Alice","displayName":"Alice"}"#,
));
assert_eq!(same.len(), 1, "equal synonyms collapse: {same:?}");
assert_eq!(same[0].label, "Name");
let different = collapse(fields(r#"{"name":"alice","display_name":"Alice"}"#));
assert_eq!(different.len(), 2, "differing synonyms stay: {different:?}");
}
}
+29 -21
View File
@@ -24,8 +24,13 @@ pub fn name(kind: u16) -> &'static str {
/// everywhere (`name`, `about`, `picture`, …).
pub fn field_label(kind: u16, key: &str) -> Option<&'static str> {
let specific = match (kind, key) {
// Kind 0 (profile metadata) — the common JSON-content case.
(0, "name") | (0, "display_name") => Some("Display name"),
// Kind 0 (profile metadata) — the common JSON-content case. `name` is
// the username and `display_name` the display name (NIP-24); they get
// distinct labels so a client sending both with different values cannot
// make them look like one duplicated field.
(0, "name") => Some("Name"),
(0, "display_name") | (0, "displayName") => Some("Display name"),
(0, "username") => Some("Username"),
(0, "about") => Some("About"),
(0, "picture") => Some("Picture"),
(0, "banner") => Some("Banner"),
@@ -50,19 +55,20 @@ fn generic_field_label(key: &str) -> Option<&'static str> {
}
}
/// A one-line note for kinds whose payload is not in the content.
/// The canonical field a key belongs to, for collapsing synonymous keys.
///
/// Shown when the content is empty, so an empty card is not mistaken for an
/// empty event: for a follow list or a relay list the meaningful data is in the
/// tags, which the dialog lists under Details.
pub fn content_note(kind: u16) -> Option<&'static str> {
match kind {
3 => Some("This is a follow list. The accounts it follows are listed under Details."),
10002 => Some("This is a relay list. The relays are listed under Details."),
10000 | 10001 | 10003 | 10004 | 10005 | 10006 | 10007 | 10009 | 10015 => {
Some("This is a list event. Its entries are listed under Details.")
}
30078 => Some("This is application-specific data."),
/// A client may send `name`, `display_name`, `displayName` and `username` for
/// the same profile; the dialog shows them as one row when their values agree,
/// so four identical rows do not crowd the decision.
pub fn field_group(key: &str) -> Option<&'static str> {
match key {
"name" | "display_name" | "displayName" | "username" => Some("Name"),
"about" | "description" => Some("About"),
"picture" | "image" | "avatar" => Some("Picture"),
"banner" => Some("Banner"),
"nip05" => Some("NIP-05"),
"lud16" | "lud06" => Some("Lightning address"),
"website" | "url" => Some("Website"),
_ => None,
}
}
@@ -75,18 +81,20 @@ mod tests {
/// fall through to no label (the renderer then shows the raw key).
#[test]
fn kind_specific_labels_win_over_generic_ones() {
assert_eq!(field_label(0, "name"), Some("Display name"));
assert_eq!(field_label(0, "name"), Some("Name"));
assert_eq!(field_label(0, "display_name"), Some("Display name"));
assert_eq!(field_label(30078, "name"), Some("Name"));
assert_eq!(field_label(0, "nip05"), Some("NIP-05 address"));
assert_eq!(field_label(0, "something_odd"), None);
}
/// Kinds whose payload is in the tags say where to look rather than showing
/// an empty card.
/// Synonymous keys share a group, so equal values can collapse to one row.
#[test]
fn list_kinds_explain_where_their_payload_is() {
assert!(content_note(3).is_some());
assert!(content_note(10002).is_some());
assert_eq!(content_note(1), None);
fn synonymous_keys_share_a_group() {
assert_eq!(field_group("name"), Some("Name"));
assert_eq!(field_group("display_name"), Some("Name"));
assert_eq!(field_group("displayName"), Some("Name"));
assert_eq!(field_group("about"), Some("About"));
assert_eq!(field_group("something_odd"), None);
}
}
+5 -1
View File
@@ -60,6 +60,11 @@ pub fn row(title: &str, subtitle: &str) -> adw::ActionRow {
/// which makes the whole dialog wider than the window, and the floating dialog
/// gets clipped. The full value stays reachable as a plain tooltip where the
/// caller sets one.
///
/// The label **fills** its allocation (no `halign(Start)`): a start-aligned
/// label is sized to its natural width, so wrapped lines stop early instead of
/// spanning the dialog. `max_width_chars` still caps the natural width, so the
/// label cannot make the dialog grow.
pub fn label(text: &str) -> gtk::Label {
gtk::Label::builder()
.label(text)
@@ -69,7 +74,6 @@ pub fn label(text: &str) -> gtk::Label {
.wrap_mode(gtk::pango::WrapMode::WordChar)
.xalign(0.0)
.max_width_chars(48)
.halign(gtk::Align::Start)
.build()
}