Render event content readably in the approval dialog

A sign_event's content was shown as one plain label, so a JSON payload (kind 0
profile metadata, NIP-78 app data, …) appeared as raw, unformatted JSON. Show
it as labelled key/value rows instead — kind-aware labels for kind 0, a generic
dictionary otherwise — capped, with a "+N more fields" row rather than silently
dropping anything.

A structured view is lossy (key order, duplicate keys, whitespace), so the
content stays one click away in a "View full content" preview: a plain
AdwDialog (not the alert dialog, which is not resizable) with Formatted and
Original pages, closed on the same absolute deadline as the approval itself so
it cannot outlive the request. List kinds whose payload is in the tags (kind 3,
10002) get a note pointing at Details instead of an empty card.

Request::Sign now carries the bounded full content rather than a 280-char
preview, and the plain label/field helpers move to ui::plain so both dialogs
share them. meson.build lists the new source file.
This commit is contained in:
raucao committed 2026-11-26 14:58:29 +04:00
1 parent bf737880be
commit ab41b29669
8 files changed
+684 -62

No files matched your search

+1
View File
@@ -41,6 +41,7 @@ cargo_build = custom_target(binary_name,
'src/ui/apps_view.rs',
'src/ui/approval.rs',
'src/ui/connect.rs',
'src/ui/content.rs',
'src/ui/kind.rs',
'src/ui/keys_view.rs',
'src/ui/mod.rs',
+5 -2
View File
@@ -42,7 +42,7 @@ pub struct SigningKey {
/// What is being asked for.
///
/// Everything the dialog shows beyond the client identity is already reduced to
/// plain text here: `preview` and `tags` are derived from client-supplied
/// plain text here: `content` and `tags` are derived from client-supplied
/// content and must only ever be rendered as text, never as markup.
#[derive(Debug, Clone)]
pub enum Request {
@@ -56,7 +56,10 @@ pub enum Request {
/// An event would be signed with an identity key.
Sign {
kind: u16,
preview: String,
/// The full event content, bounded. The UI renders it readably and can
/// 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 message would be encrypted to someone.
+34 -5
View File
@@ -768,7 +768,7 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
let kind = incoming.kind.as_u16();
let request = Request::Sign {
kind,
preview: preview(&incoming.content),
content: content(&incoming.content),
tags: tag_summary(&incoming.tags),
};
let keys = authorize(
@@ -1186,6 +1186,35 @@ fn preview(text: &str) -> String {
shown
}
/// How much event content is kept for the approval dialog.
///
/// Much larger than [`PREVIEW_CHARS`]: the dialog renders the content readably
/// (and can show it in full on request), so it must not be reduced to a snippet.
/// Still bounded, so a hostile payload cannot travel unbounded over the channel.
const CONTENT_LIMIT: usize = 32 * 1024;
/// A plain, bounded copy of attacker-controlled event content.
///
/// Carriage returns are dropped (they break single-line rendering); nothing else
/// is changed, because the original bytes are what gets signed. The UI is what
/// decides how to present it.
fn content(text: &str) -> String {
let mut shown = String::new();
let mut count = 0;
for character in text.chars() {
if character == '\r' {
continue;
}
if count >= CONTENT_LIMIT {
shown.push('…');
break;
}
shown.push(character);
count += 1;
}
shown
}
/// A short, plain summary of an event's tags: `name=value, name=value, …`.
fn tag_summary(tags: &[Tag]) -> String {
if tags.is_empty() {
@@ -1466,7 +1495,7 @@ mod tests {
let signed = seen
.iter()
.find_map(|request| match request {
Request::Sign { kind, preview, .. } => Some((*kind, preview.clone())),
Request::Sign { kind, content, .. } => Some((*kind, content.clone())),
_ => None,
})
.expect("the signer must have asked before signing");
@@ -1862,14 +1891,14 @@ mod tests {
let shown = seen
.iter()
.find_map(|request| match request {
Request::Sign { kind, preview, tags } => {
Some((*kind, preview.clone(), tags.clone()))
Request::Sign { kind, content, tags } => {
Some((*kind, content.clone(), tags.clone()))
}
_ => None,
})
.expect("the user was asked");
assert_eq!(shown.0, 1);
assert!(shown.1.contains("hello world"), "preview was {:?}", shown.1);
assert!(shown.1.contains("hello world"), "content was {:?}", shown.1);
assert!(shown.2.contains("t=nostr"), "tags were {:?}", shown.2);
}
+20 -54
View File
@@ -22,7 +22,7 @@ use crate::runtime;
use crate::signer::approval::{Decision, Notice, Prompt, Question, Request};
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::{kind, plain};
use crate::ui::{content, kind, plain};
use crate::APP_ID;
/// One notification id, so a second prompt replaces the first rather than
@@ -183,7 +183,7 @@ fn user_is_away(window: &gtk::Window) -> bool {
///
/// `None` means no deadline at all; `Some(Duration::ZERO)` means it has already
/// passed.
fn remaining(deadline: Option<Instant>) -> Option<Duration> {
pub(crate) fn remaining(deadline: Option<Instant>) -> Option<Duration> {
deadline.map(|deadline| {
deadline
.checked_duration_since(Instant::now())
@@ -250,7 +250,7 @@ pub async fn present_question(
let dialog = adw::AlertDialog::builder()
.heading(heading(request))
.body(story(request))
.extra_child(&details(question))
.extra_child(&details(question, widget, deadline))
.build();
// Heading and body are plain text too: the heading carries no client data
// today, but the extra child is where all of it belongs.
@@ -434,7 +434,11 @@ fn story(request: &Request) -> &'static str {
/// are verifiable but not needed to decide — the client's key, the URL it
/// declares, the raw kind and tags — are collapsed. Client metadata is
/// decoration: the name and URL are supplied by the application itself.
fn details(question: &Question) -> gtk::Box {
fn details(
question: &Question,
widget: &impl IsA<gtk::Widget>,
deadline: Option<Instant>,
) -> gtk::Box {
let client = &question.client;
let content = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
@@ -442,14 +446,20 @@ fn details(question: &Question) -> gtk::Box {
.build();
content.append(&identity_field(&question.identity));
content.append(&field(
content.append(&plain::text_field(
"Application",
client.name.as_deref().unwrap_or("(unnamed)"),
));
match &question.request {
Request::Pair { .. } => {}
Request::Sign { preview, .. } => content.append(&block("Content", preview)),
// The content is the decision, so it gets a structured, readable view
// rather than raw JSON — with the original one click away.
Request::Sign {
kind,
content: signed,
..
} => content.append(&content::card(signed, *kind, widget, deadline)),
Request::Encrypt { preview, .. } => content.append(&block("Message", preview)),
Request::Decrypt { preview, .. } => content.append(&block("Ciphertext", preview)),
}
@@ -551,37 +561,12 @@ fn identity_field(identity: &crate::signer::approval::SigningKey) -> gtk::Box {
npub_label.set_tooltip_text(Some(&npub));
match name {
Some(name) => {
value.append(&plain(name));
value.append(&plain::label(name));
value.append(&npub_label);
}
None => value.append(&npub_label),
}
field_widget("Signing as", &value)
}
/// A label/value row. Both halves are plain and selectable.
fn field(title: &str, value: &str) -> gtk::Box {
field_widget(title, &plain(value))
}
/// [`field`] with an arbitrary value widget, e.g. one that stacks the name and
/// the npub.
fn field_widget(title: &str, value: &impl IsA<gtk::Widget>) -> gtk::Box {
let row = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(12)
.build();
let title = gtk::Label::builder()
.label(title)
.xalign(0.0)
.valign(gtk::Align::Start)
.width_chars(12)
.css_classes(["dim-label"])
.build();
value.set_hexpand(true);
row.append(&title);
row.append(value);
row
plain::field("Signing as", &value)
}
/// A titled block for text that may be long, laid out like a quote.
@@ -601,7 +586,7 @@ fn block(title: &str, value: &str) -> gtk::Box {
.build(),
);
let body = plain(value);
let body = plain::label(value);
body.set_margin_top(8);
body.set_margin_bottom(8);
body.set_margin_start(8);
@@ -622,30 +607,11 @@ fn block(title: &str, value: &str) -> gtk::Box {
}
fn note(text: &str) -> gtk::Label {
let label = plain(text);
let label = plain::label(text);
label.add_css_class("dim-label");
label
}
/// The one way client-supplied text reaches the screen.
///
/// `WordChar` wrapping matters: the values include long tokens with no spaces
/// (an `npub`, a URL). With the default `Word` mode a long token cannot be
/// broken, so the label's *minimum* width becomes the whole token — which makes
/// the whole dialog wider than the window, and the floating dialog gets clipped.
fn plain(text: &str) -> gtk::Label {
gtk::Label::builder()
.label(text)
.use_markup(false)
.selectable(true)
.wrap(true)
.wrap_mode(gtk::pango::WrapMode::WordChar)
.xalign(0.0)
.max_width_chars(48)
.halign(gtk::Align::Start)
.build()
}
#[cfg(test)]
mod tests {
use super::*;
+495
View File
@@ -0,0 +1,495 @@
//! A readable view of the content a client asked Regent to sign.
//!
//! The content is client-supplied and attacker-controlled. It is shown as
//! **plain text only** — never Pango markup — and every view is bounded, so a
//! hostile payload cannot stretch the dialog or make it unreadable.
//!
//! When the content is JSON the dialog shows labelled key/value rows instead of
//! raw JSON. That is a lossy transformation (key order, duplicate keys and
//! whitespace all change), and the user is deciding whether to sign the original
//! bytes — so the content text is always one click away, in the preview's
//! **Original** page.
use std::time::{Duration, Instant};
use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use serde_json::Value;
use crate::ui::approval::remaining;
use crate::ui::{kind, plain};
/// How many top-level fields the inline card shows before the "+N more" row.
const INLINE_FIELDS: usize = 8;
/// How deep the renderer walks before it stops and says so.
const MAX_DEPTH: usize = 8;
/// How many rows the preview's formatted page materialises per level.
const PREVIEW_ROWS: usize = 200;
/// How long a single rendered value may be before it is cut.
const VALUE_CHARS: usize = 400;
/// The most the inline card grows to before it scrolls instead.
const INLINE_HEIGHT: i32 = 200;
/// The most the preview grows to before it scrolls instead.
const PREVIEW_HEIGHT: i32 = 560;
/// What the content turned out to be.
#[derive(Debug, PartialEq)]
enum View {
/// A JSON object: one field per top-level key.
Fields(Vec<Field>),
/// JSON that is not an object (an array or a scalar): pretty-printed.
Json(String),
/// Not JSON at all: shown as plain text.
Text(String),
/// Nothing (or only whitespace): a kind-aware note or "(empty)".
Empty,
}
#[derive(Debug, PartialEq)]
struct Field {
label: String,
value: Value,
}
/// Classify the content for display.
fn view(content: &str, kind_number: u16) -> View {
let trimmed = content.trim();
if trimmed.is_empty() {
return View::Empty;
}
match serde_json::from_str::<Value>(trimmed) {
Ok(Value::Object(map)) => View::Fields(
map.iter()
.map(|(key, value)| Field {
label: kind::field_label(kind_number, key)
.map(str::to_string)
.unwrap_or_else(|| key.clone()),
value: value.clone(),
})
.collect(),
),
Ok(other) => View::Json(pretty(&other)),
// Keep the original spacing: it is what will be signed.
Err(_) => View::Text(content.to_string()),
}
}
/// The fields shown inline, and how many were left out.
fn inline_slice(fields: &[Field]) -> (&[Field], usize) {
let shown = fields.len().min(INLINE_FIELDS);
(&fields[..shown], fields.len() - shown)
}
/// The inline card: a header with a "View full content" button, then a bounded
/// structured body.
///
/// The card stays non-interactive and bounded, so it never changes the
/// `AdwAlertDialog`'s size (an alert dialog is not resizable). Anything the user
/// needs to explore lives in the separate preview dialog.
pub fn card(
content: &str,
kind_number: u16,
parent: &impl IsA<gtk::Widget>,
deadline: Option<Instant>,
) -> gtk::Box {
let container = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(4)
.build();
let header = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(12)
.build();
header.append(
&gtk::Label::builder()
.label("Content")
.xalign(0.0)
.hexpand(true)
.css_classes(["dim-label"])
.build(),
);
// A `GtkButton` shows either a label or an icon: setting both replaces one
// with the other, so the label and the go-next arrow are an explicit child.
let view_button = gtk::Button::builder()
.css_classes(["flat"])
.valign(gtk::Align::Center)
.build();
view_button.set_tooltip_text(Some("Show the full content and its original text"));
let view_content = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(6)
.build();
view_content.append(&gtk::Image::from_icon_name("go-next-symbolic"));
view_content.append(&gtk::Label::new(Some("View full content")));
view_button.set_child(Some(&view_content));
header.append(&view_button);
container.append(&header);
let body = inline(content, kind_number);
body.set_margin_top(8);
body.set_margin_bottom(8);
body.set_margin_start(8);
body.set_margin_end(8);
body.set_hexpand(true);
let scrolled = gtk::ScrolledWindow::builder()
.child(&body)
.propagate_natural_height(true)
.max_content_height(INLINE_HEIGHT)
.hscrollbar_policy(gtk::PolicyType::Never)
.build();
let frame = gtk::Box::builder().css_classes(["card"]).build();
frame.append(&scrolled);
container.append(&frame);
// The preview is a separate dialog, so a structure that grows on click can
// never be clipped by this one. `parent.root()` is the window it presents in.
let window = parent.root().and_downcast::<gtk::Window>();
let content = content.to_string();
view_button.connect_clicked(move |_| {
present_preview(window.as_ref(), &content, kind_number, deadline);
});
container
}
/// The inline body: labelled rows for a JSON object, otherwise pretty or plain
/// text.
fn inline(content: &str, kind_number: u16) -> gtk::Widget {
match view(content, kind_number) {
View::Fields(fields) => {
let boxed = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(6)
.build();
let (shown, omitted) = inline_slice(&fields);
for field in shown {
boxed.append(&field_row(&field.label, &field.value));
}
if omitted > 0 {
let more = plain::label(&format!(
"+{omitted} more field{}",
if omitted == 1 { "" } else { "s" }
));
more.add_css_class("dim-label");
boxed.append(&more);
}
boxed.upcast()
}
View::Json(pretty) => monospace(&pretty),
View::Text(text) => plain::label(&text).upcast(),
View::Empty => empty_body(kind_number),
}
}
/// 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(),
}
}
/// One inline field: a scalar value, or a summary for a nested object/array.
fn field_row(label: &str, value: &Value) -> gtk::Box {
match value {
Value::Object(_) | Value::Array(_) => plain::text_field(label, &summary(value)),
other => plain::field(label, &plain::label(&scalar(other))),
}
}
/// A rendered scalar: a string unquoted, anything else as JSON, then cut.
fn scalar(value: &Value) -> String {
let text = match value {
Value::String(text) => text.clone(),
other => other.to_string(),
};
cut(&text)
}
/// A short summary of a nested object or array.
fn summary(value: &Value) -> String {
match value {
Value::Object(map) => format!("{} field{}", map.len(), plural(map.len())),
Value::Array(items) => format!("{} item{}", items.len(), plural(items.len())),
other => scalar(other),
}
}
fn plural(count: usize) -> &'static str {
if count == 1 { "" } else { "s" }
}
/// `text` cut to [`VALUE_CHARS`], with a marker when it was.
fn cut(text: &str) -> String {
let mut shown = String::new();
for (index, character) in text.chars().enumerate() {
if index >= VALUE_CHARS {
shown.push('…');
break;
}
shown.push(character);
}
shown
}
/// The pretty-printed form of JSON that is not a plain object.
fn pretty(value: &Value) -> String {
serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string())
}
/// A selectable, monospace, word-char-wrapped block.
fn monospace(text: &str) -> gtk::Widget {
let label = plain::label(text);
label.add_css_class("monospace");
label.upcast()
}
/// The full, click-through view: formatted structure and the original text.
///
/// A plain `AdwDialog` — **not** an `AdwAlertDialog` — with
/// `follows_content_size` and the width pinned on the child, so it can grow with
/// its content up to the window and then scroll (the measured "Connect an app"
/// recipe). It closes itself at the same absolute deadline as the approval
/// dialog, so it cannot outlive the request as an orphan.
fn present_preview(
parent: Option<&gtk::Window>,
content: &str,
kind_number: u16,
deadline: Option<Instant>,
) {
let classified = view(content, kind_number);
// A plain-text (or empty) payload reads the same in both pages, so it gets a
// 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 header = adw::HeaderBar::new();
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&header);
if structured {
let original = scroller(&monospace(content));
let stack = gtk::Stack::builder().build();
stack.add_titled(&formatted, Some("formatted"), "Formatted");
stack.add_titled(&original, Some("original"), "Original");
header.set_title_widget(Some(&gtk::StackSwitcher::builder().stack(&stack).build()));
toolbar.set_content(Some(&stack));
} else {
toolbar.set_content(Some(&formatted));
}
// Pin the width on the child: with `follows_content_size` the dialog ignores
// `content-width` and would use the content's natural width instead.
toolbar.set_size_request(plain::DIALOG_WIDTH, -1);
let dialog = adw::Dialog::builder()
.title("Event content")
.follows_content_size(true)
.child(&toolbar)
.build();
dialog.present(parent);
if let Some(left) = remaining(deadline) {
let dialog = dialog.clone();
glib::timeout_add_local_once(left.max(Duration::from_millis(1)), move || {
dialog.force_close();
});
}
}
/// A bounded, natural-height scroller for one preview page.
fn scroller(child: &impl IsA<gtk::Widget>) -> gtk::ScrolledWindow {
gtk::ScrolledWindow::builder()
.child(child)
.propagate_natural_height(true)
.max_content_height(PREVIEW_HEIGHT)
.hscrollbar_policy(gtk::PolicyType::Never)
.build()
}
/// 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 {
match classified {
View::Fields(fields) => {
let boxed = vertical();
let (shown, omitted) = fields.split_at(fields.len().min(PREVIEW_ROWS));
for field in shown {
boxed.append(&full_field(&field.label, &field.value, 1));
}
if !omitted.is_empty() {
boxed.append(&dim(&format!("… and {} more fields", omitted.len())));
}
boxed.upcast()
}
View::Json(pretty) => monospace(&pretty),
View::Text(text) => plain::label(&text).upcast(),
View::Empty => empty_body(kind_number),
}
}
/// One preview field, recursing into nested objects and arrays.
fn full_field(label: &str, value: &Value, depth: usize) -> gtk::Box {
match value {
Value::Object(_) | Value::Array(_) if depth <= MAX_DEPTH => {
plain::field(label, &nested(value, depth))
}
Value::Object(_) | Value::Array(_) => plain::text_field(
label,
&format!("{} (shown as text in Original)", summary(value)),
),
other => plain::field(label, &plain::label(&scalar(other))),
}
}
fn nested(value: &Value, depth: usize) -> gtk::Box {
let boxed = vertical();
match value {
Value::Object(map) => {
let (shown, omitted) = split_rows(map.len());
for (key, value) in map.iter().take(shown) {
boxed.append(&full_field(key, value, depth + 1));
}
if omitted > 0 {
boxed.append(&dim(&format!("… and {omitted} more")));
}
}
Value::Array(items) => {
if items.iter().all(is_scalar) {
// A list of simple values reads better as one block than as N
// rows.
let joined = items.iter().map(scalar).collect::<Vec<_>>().join("\n");
boxed.append(&plain::label(&joined));
} else {
let (shown, omitted) = split_rows(items.len());
for (index, value) in items.iter().take(shown).enumerate() {
boxed.append(&full_field(&(index + 1).to_string(), value, depth + 1));
}
if omitted > 0 {
boxed.append(&dim(&format!("… and {omitted} more")));
}
}
}
other => boxed.append(&plain::label(&scalar(other))),
}
boxed
}
fn is_scalar(value: &Value) -> bool {
!matches!(value, Value::Object(_) | Value::Array(_))
}
fn split_rows(total: usize) -> (usize, usize) {
let shown = total.min(PREVIEW_ROWS);
(shown, total - shown)
}
fn vertical() -> gtk::Box {
gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(6)
.build()
}
fn dim(text: &str) -> gtk::Label {
let label = plain::label(text);
label.add_css_class("dim-label");
label
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn fields(content: &str) -> Vec<Field> {
match view(content, 0) {
View::Fields(fields) => fields,
other => panic!("expected fields, got {other:?}"),
}
}
/// A JSON object becomes labelled rows, and known keys get human labels.
#[test]
fn an_object_becomes_labelled_fields() {
let parsed = fields(r#"{"name":"Alice","about":"hi"}"#);
assert_eq!(parsed.len(), 2);
assert!(
parsed.iter().any(|field| field.label == "Display name"),
"the kind-specific label is used, got {parsed:?}"
);
assert_eq!(
parsed
.iter()
.find(|f| f.label == "Display name")
.unwrap()
.value,
json!("Alice")
);
}
/// Only a bounded number of fields is shown inline, and the rest are counted
/// rather than silently dropped.
#[test]
fn inline_shows_a_capped_number_of_fields() {
let parsed = fields(r#"{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10}"#);
assert_eq!(parsed.len(), 10);
let (shown, omitted) = inline_slice(&parsed);
assert_eq!(shown.len(), INLINE_FIELDS);
assert_eq!(omitted, 10 - INLINE_FIELDS);
}
/// An array or a bare scalar is pretty-printed, not turned into rows.
#[test]
fn non_objects_are_pretty_printed() {
assert!(matches!(view("[1,2,3]", 1), View::Json(_)));
assert!(matches!(view("42", 1), View::Json(_)));
}
/// Anything that is not JSON stays exactly as sent — it is what gets signed.
#[test]
fn plain_text_is_kept_verbatim() {
assert_eq!(
view("hello world", 1),
View::Text("hello world".to_string())
);
}
/// Empty content still says something rather than rendering a blank card.
#[test]
fn empty_content_is_its_own_view() {
assert_eq!(view(" ", 1), View::Empty);
}
/// A nested value is summarised, not expanded, inline.
#[test]
fn nested_values_are_summarised() {
assert_eq!(summary(&json!({"a": 1, "b": 2})), "2 fields");
assert_eq!(summary(&json!([1, 2, 3])), "3 items");
assert_eq!(summary(&json!({"a": 1})), "1 field");
}
/// A very long scalar is cut, so one field cannot dominate the dialog.
#[test]
fn long_values_are_cut() {
let long = "x".repeat(VALUE_CHARS + 50);
let cut = scalar(&json!(long));
assert_eq!(cut.chars().count(), VALUE_CHARS + 1, "cut plus the marker");
assert!(cut.ends_with('…'));
}
/// The preview caps how many rows it materialises per level.
#[test]
fn preview_rows_are_capped() {
assert_eq!(split_rows(5), (5, 0));
assert_eq!(split_rows(PREVIEW_ROWS + 3), (PREVIEW_ROWS, 3));
}
}
+74
View File
@@ -16,3 +16,77 @@ pub fn name(kind: u16) -> &'static str {
_ => "event",
}
}
/// A human label for a well-known content field, if we have one.
///
/// Kind-specific labels come first: the same key can mean different things in
/// different kinds. The generic dictionary below catches keys that recur
/// 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"),
(0, "about") => Some("About"),
(0, "picture") => Some("Picture"),
(0, "banner") => Some("Banner"),
(0, "nip05") => Some("NIP-05 address"),
(0, "lud16") | (0, "lud06") => Some("Lightning address"),
(0, "website") => Some("Website"),
_ => None,
};
specific.or_else(|| generic_field_label(key))
}
fn generic_field_label(key: &str) -> Option<&'static str> {
match key {
"name" | "display_name" | "displayName" => Some("Name"),
"about" | "description" => Some("About"),
"picture" | "avatar" | "image" => Some("Picture"),
"banner" => Some("Banner"),
"nip05" => Some("NIP-05 identifier"),
"lud16" | "lud06" => Some("Lightning address"),
"website" | "url" => Some("Website"),
_ => None,
}
}
/// A one-line note for kinds whose payload is not in the content.
///
/// 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."),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A kind-specific label wins over the generic dictionary, and unknown keys
/// 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(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.
#[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);
}
}
+1
View File
@@ -4,6 +4,7 @@ pub mod activity_view;
pub mod approval;
pub mod apps_view;
pub mod connect;
pub mod content;
pub mod kind;
pub mod keys_view;
pub mod plain;
+54 -1
View File
@@ -8,7 +8,8 @@
//! text forge formatting that looks like our UI.
//!
//! These constructors make "plain" the obvious choice. `gtk::Label` already
//! defaults to plain text, so it needs no wrapper.
//! defaults to plain text, so it needs no markup wrapper — [`label`] exists for
//! the wrapping behaviour, not for markup.
use adw::prelude::*;
use gtk::prelude::*;
@@ -51,6 +52,58 @@ pub fn row(title: &str, subtitle: &str) -> adw::ActionRow {
row
}
/// A plain, selectable, word-char-wrapped label.
///
/// `WordChar` wrapping matters: the values include long tokens with no spaces
/// (an `npub`, a URL, a JSON key). With the default `Word` mode a long token
/// cannot be broken, so the label's *minimum* width becomes the whole token —
/// 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.
pub fn label(text: &str) -> gtk::Label {
gtk::Label::builder()
.label(text)
.use_markup(false)
.selectable(true)
.wrap(true)
.wrap_mode(gtk::pango::WrapMode::WordChar)
.xalign(0.0)
.max_width_chars(48)
.halign(gtk::Align::Start)
.build()
}
/// A label/value row: a dim, fixed-width title beside a value widget.
///
/// The title wraps and is width-bounded so an attacker-controlled JSON key
/// cannot stretch the dialog; the value widget is expected to be plain too.
pub fn field(title: &str, value: &impl IsA<gtk::Widget>) -> gtk::Box {
let row = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(12)
.build();
let title = gtk::Label::builder()
.label(title)
.use_markup(false)
.xalign(0.0)
.valign(gtk::Align::Start)
.width_chars(12)
.max_width_chars(20)
.wrap(true)
.wrap_mode(gtk::pango::WrapMode::WordChar)
.css_classes(["dim-label"])
.build();
value.set_hexpand(true);
row.append(&title);
row.append(value);
row
}
/// [`field`] with a plain-text value.
pub fn text_field(title: &str, value: &str) -> gtk::Box {
field(title, &label(value))
}
/// An `ExpanderRow` whose title and subtitle are plain text.
///
/// The enable switch is hidden: on an expander it only hides the child rows,