You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [8f6be6d0] Add copy button for garden rankings (markdown clipboard) (#168) * Add garden ranking markdown copy button via POST /ui Introduce HtmlUiAction::CopyGardenRank that rebuilds the visible child ranking and returns JsBuilder clipboard JS (fetch → eval), matching CopyThread. Place a copy control on garden ranking headings; clipboard text is a concise markdown numbered list with unranked bullets. Co-authored-by: tommy * Fix paren balance in garden ranking copy browser test Co-authored-by: tommy --------- Co-authored-by: Cursor Agent Side A — unified diff (full patch): diff --git a/agents.md b/agents.md index 7d6fea5791f7c95677e17e8975a14df83f998fd6..1dc989e4b23071f2eef69f2479c9a1ca2bd04b32 100644 --- a/agents.md +++ b/agents.md @@ -40,6 +40,8 @@ Strict **CSP** that blocks `eval` would break the current app. Other projects ma - **Non-morph `POST /ui` responses:** **`SetGardenPin`** returns **`303 See Other`** and **`Set-Cookie`** (same as **`POST /theme`**). Garden pin/unpin is a normal **`
`** — browser navigation applies cookies reliably (see **`test/browser_garden_pin.clj`**). Each **`__rpc__`** payload includes **`form_action: "/ui"`**; **`post_ui_html`** rejects mismatches to bind tokens to the UI endpoint. +- **`CopyGardenRank`:** Browser copy control on garden ranking headings. Returns **`text/javascript`** via **`JsBuilder::clipboard_write_text_and_label_btn`** (same **`fetch` → `eval`** loop as **`CopyThread`**). Payload includes **`room`**, **`parent_path`**, **`depth`**, **`copy_btn_id`**, and optional **`external_hosts`** (for **`/-/`** host-root indexes). Clipboard text is a concise markdown numbered list of display paths (plus unranked bullets). + - **`VoteComparePost`:** On success returns **`text/javascript`** that **morphs** **`#vote-edge-history-region`** (recomputed **`
    `** — ratios match **`left`/`right`** query order, bullets, sorted by strength toward **`left`** then newer) and **`.vote-compare-nav`** (fresh next-pair link). The compare **`GET`** page uses **`layout_full_bleed_chromeless`** (no breadcrumbs, no **`#controls`**, no **`slug-pin-hud`**; **`view-vote-compare-fullscreen`** full-width **`body`**). **`__rpc__`** carries **`form_action: "/ui"`**; **`thread_tag`** and ratio fields come from the same form as **`$form`** holes. **Guests** on a shared pair see the compose UI with **`post vote`** as a link to **`/login?next=`** (class **`vote-compare-login-cta`**); after OAuth / username selection they return to that matchup. An unauthenticated **`VoteComparePost`** (forged/stale form) still JS-redirects to the same **`/login?next=`** target. - **`ThreadGraduate` / `GraduateThread`:** Private-room forum threads with **Manage** can be published to the public site under the same tag. The writer replays non-redacted ingests into **`room: public`** (chronological order), then appends a durable **`ThreadGraduated`** marker. Graduated private threads show a banner linking to public **`/t/:tag`**, block further private posts, and cannot be graduated twice. CLI: **`npx slugsocial private forum graduate `**; RPC: **`ThreadGraduate`**. diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs index b4a0c9e87e462050bd52728e49e0d6781bf1cfc8..611956d0a46062b49ce350be176e4be139312ff0 100644 --- a/server/src/api/ui_html.rs +++ b/server/src/api/ui_html.rs @@ -24,9 +24,9 @@ use crate::{ external_resolver_status_markup, fragment_new_thread_slot, login_to_post_hint_markup, parse_html_ui_from_form, room_members_section_markup, thread_feed_html, thread_feed_html_for_room, thread_feed_region_markup, thread_ui_collapse_redacted_post, - thread_ui_copy_thread, - thread_ui_expand_post_full, thread_ui_expand_redacted_post, ui_js_warn, user_can_post_room, - user_can_view_room, HtmlUiAction, JsBuilder, ThreadNav, + garden_ui_copy_rank, thread_ui_copy_thread, thread_ui_expand_post_full, + thread_ui_expand_redacted_post, ui_js_warn, user_can_post_room, user_can_view_room, + HtmlUiAction, JsBuilder, ThreadNav, }, reducer::{scope_from_room_wire, ScopeId}, state::AppState, @@ -575,6 +575,25 @@ async fn dispatch_ui_action( let viewer = session.map(|s| s.username.as_str()); thread_ui_copy_thread(state, &room, &thread_tag, ©_btn_id, viewer).await } + HtmlUiAction::CopyGardenRank { + room, + parent_path, + depth, + copy_btn_id, + external_hosts, + } => { + let viewer = session.map(|s| s.username.as_str()); + garden_ui_copy_rank( + state, + &room, + &parent_path, + depth, + ©_btn_id, + external_hosts, + viewer, + ) + .await + } HtmlUiAction::GraduateThread { room, thread_tag } => { let Some(session) = session else { return js_redirect("/login").into_response(); diff --git a/server/src/html/garden/copy.rs b/server/src/html/garden/copy.rs new file mode 100644 index 0000000000000000000000000000000000000000..271ea87c34c99e23ab1b0d8572632fdc41380b78 --- /dev/null +++ b/server/src/html/garden/copy.rs @@ -0,0 +1,199 @@ +//! Copy garden rankings to the clipboard as concise markdown (POST /ui + JsBuilder eval). + +use crate::form_template::template_json_compact; +use crate::html::forum::ThreadNav; +use crate::html::js_string_literal; +use crate::html::ui_action::HtmlUiAction; +use crate::html::{JsBuilder, ui_js_warn}; +use crate::path_types::ItemId; +use crate::reducer::scope_from_room_wire; +use crate::scope_rank::{ + build_children_rankings, build_rankings_for_item_set, external_root_host_items, + resolve_scope_recursive, ChildrenRankings, +}; +use crate::state::AppState; +use maud::{html, Markup}; + +use super::access::user_can_view_room; +use super::item::item_display_path; +use crate::reducer::{ContentState, ScopeId}; + +const COPY_BTN_ID: &str = "garden-rank-copy"; + +/// `POST /ui` + `__rpc__` from an inline button; response body is `eval`'d (same as forum copy). +fn garden_ui_fetch_onclick(rpc_compact_json: &str) -> String { + format!( + "fetch('/ui',{{method:'POST',headers:{{'Content-Type':'application/x-www-form-urlencoded'}},body:new URLSearchParams({{__rpc__:{}}}).toString(),credentials:'same-origin'}}).then(r=>r.text()).then(eval);return false", + js_string_literal(rpc_compact_json) + ) +} + +/// Concise markdown for ranked child groups (numbered lists + unranked bullets). +pub(crate) fn format_garden_rank_markdown(rankings: &ChildrenRankings) -> String { + let mut out = String::new(); + let multi = rankings.component_rankings.len() > 1; + for (ci, comp) in rankings.component_rankings.iter().enumerate() { + if ci > 0 { + out.push('\n'); + } + if multi { + out.push_str(&format!("### ordering {}\n\n", ci + 1)); + } + for (i, r) in comp.ranked.iter().enumerate() { + out.push_str(&format!( + "{}. {}\n", + i + 1, + item_display_path(r.item.as_str()) + )); + } + } + if !rankings.unranked_items.is_empty() { + if !out.is_empty() { + out.push('\n'); + } + for name in &rankings.unranked_items { + out.push_str(&format!("- {}\n", item_display_path(name.as_str()))); + } + } + out +} + +fn rankings_for_copy( + state_content: &crate::reducer::ContentState, + parent_path: &str, + depth: usize, + external_hosts: bool, +) -> ChildrenRankings { + if external_hosts { + let hosts = external_root_host_items(state_content); + return build_rankings_for_item_set(state_content, &hosts); + } + let parent = ItemId::parse(parent_path.trim()) + .unwrap_or_else(|| ItemId::ontology_root()) + .normalized_storage(); + let depth = depth.clamp(1, 5); + if depth > 1 { + let items = resolve_scope_recursive(state_content, &[parent.as_str().to_string()], depth); + build_rankings_for_item_set(state_content, &items) + } else { + build_children_rankings(state_content, &parent) + } +} + +pub(crate) async fn garden_ui_copy_rank( + state: &AppState, + room: &str, + parent_path: &str, + depth: usize, + copy_btn_id: &str, + external_hosts: bool, + viewer: Option<&str>, +) -> axum::response::Response { + let room = room.trim(); + let scope = scope_from_room_wire(room); + if let ScopeId::Room(ref rid) = scope { + let reduced = state.reduced.read().await; + if !user_can_view_room(&reduced, rid, viewer) { + return ui_js_warn("forbidden"); + } + } + + let reduced = state.reduced.read().await; + let empty = ContentState::default(); + let content = match &scope { + ScopeId::Public => reduced.public(), + ScopeId::Room(_) => reduced.content_for_scope(&scope).unwrap_or(&empty), + }; + let rankings = rankings_for_copy(content, parent_path, depth, external_hosts); + let text = format_garden_rank_markdown(&rankings); + drop(reduced); + + if text.is_empty() { + return ui_js_warn("nothing to copy"); + } + + JsBuilder::new() + .clipboard_write_text_and_label_btn(&text, copy_btn_id, "copied") + .into_response() +} + +pub(super) fn garden_rank_copy_button_markup( + nav: &ThreadNav, + parent_path: &str, + depth: usize, + external_hosts: bool, +) -> Markup { + let rpc = template_json_compact(&HtmlUiAction::CopyGardenRank { + room: nav.room_wire.clone(), + parent_path: parent_path.to_string(), + depth, + copy_btn_id: COPY_BTN_ID.to_string(), + external_hosts, + }) + .expect("CopyGardenRank serializes"); + html! { + button type="button" id=(COPY_BTN_ID) class="post-nav-btn ont-rank-copy-btn" title="Copy ranking as markdown" + onclick=(garden_ui_fetch_onclick(&rpc)) { + "copy" + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::path_types::ItemId; + use crate::ranking::RankedItem; + use crate::scope_rank::ScopedComponent; + + #[test] + fn markdown_single_component_and_unranked() { + let rankings = ChildrenRankings { + component_rankings: vec![ScopedComponent { + pairs: 1, + ranked: vec![ + RankedItem { + item: ItemId::parse("~/a").unwrap(), + score: 0.9, + }, + RankedItem { + item: ItemId::parse("~/b").unwrap(), + score: 0.1, + }, + ], + }], + unranked_items: vec![ItemId::parse("~/c").unwrap()], + }; + assert_eq!( + format_garden_rank_markdown(&rankings), + "1. ~/a\n2. ~/b\n\n- ~/c\n" + ); + } + + #[test] + fn markdown_multi_component_headers() { + let rankings = ChildrenRankings { + component_rankings: vec![ + ScopedComponent { + pairs: 1, + ranked: vec![RankedItem { + item: ItemId::parse("~/a").unwrap(), + score: 1.0, + }], + }, + ScopedComponent { + pairs: 1, + ranked: vec![RankedItem { + item: ItemId::parse("~/b").unwrap(), + score: 1.0, + }], + }, + ], + unranked_items: vec![], + }; + assert_eq!( + format_garden_rank_markdown(&rankings), + "### ordering 1\n\n1. ~/a\n\n### ordering 2\n\n1. ~/b\n" + ); + } +} diff --git a/server/src/html/garden/mod.rs b/server/src/html/garden/mod.rs index ee8696727e5473fe1fa913b8a7b9f3cb9c32d12f..69012a2c1d069e47fa611d63d3bd2a329fd6255d 100644 --- a/server/src/html/garden/mod.rs +++ b/server/src/html/garden/mod.rs @@ -2,6 +2,7 @@ mod access; mod browse; +mod copy; mod external; mod item; mod item_page; @@ -13,6 +14,7 @@ mod vote; #[cfg(test)] mod tests; +pub(crate) use copy::garden_ui_copy_rank; pub(crate) use external::external_resolver_status_markup; pub(crate) use pin::{encode_pin_cookie_value, GARDEN_PIN_COOKIE}; pub(crate) use vote::vote_compare_post_success_js; diff --git a/server/src/html/garden/render.rs b/server/src/html/garden/render.rs index ca546693ecb2bb9ae5fb370f02b860c943f604b9..eed80e807d77e6b4eeeb0c3f38d6372e91ad2852 100644 --- a/server/src/html/garden/render.rs +++ b/server/src/html/garden/render.rs @@ -25,6 +25,7 @@ use crate::{ use super::{ access::content_for_garden_view, browse::{garden_layout_meta, scoped_bc_path_for, GardenBrowsePath}, + copy::garden_rank_copy_button_markup, external::{external_frame_allowed, external_source_href, github_resolver_controls}, item::{child_depth_from_uri, item_code_label, item_display_path, item_href}, item_page::{build_item_page_view_model, sibling_nav_markup}, @@ -196,6 +197,15 @@ pub(super) async fn render_scope_view( " " span class="muted" { (format!("(depth {})", model.child_depth)) } } + @if total_children > 0 { + " " + (garden_rank_copy_button_markup( + &nav, + &item_display_path(&model.item), + model.child_depth, + false, + )) + } @if total_children >= 2 { " " a class="ont-vote-children-btn" href=(vote_pool_href(&nav, &model.item)) { diff --git a/server/src/html/garden/routes.rs b/server/src/html/garden/routes.rs index 8a0499576d9093dbac0fffa1cf2ed88187e14acb..31b61355b1ec75645d405e16ab6abf8205c66380 100644 --- a/server/src/html/garden/routes.rs +++ b/server/src/html/garden/routes.rs @@ -28,6 +28,7 @@ use crate::{ use super::{ access::{content_for_garden_view, room_not_found_page, room_scope_has_garden_content, user_can_view_room}, browse::{GardenBrowsePath, scoped_bc_path_external}, + copy::garden_rank_copy_button_markup, item::{item_display_path, item_href}, render::render_scope_view, }; @@ -52,7 +53,13 @@ pub async fn garden_index( html! { @let root_path = OntologyPath::root(); nav class="breadcrumb" { (bc_path(&root_path)) } - h2 { "paths" } + h2 { + "paths" + @if !(child_rankings.component_rankings.is_empty() && child_rankings.unranked_items.is_empty()) { + " " + (garden_rank_copy_button_markup(&nav, "~/", 1, false)) + } + } @if child_rankings.component_rankings.is_empty() && child_rankings.unranked_items.is_empty() { p class="muted" { "no items yet" } } @else { @@ -137,7 +144,13 @@ pub async fn external_garden_index( "view-ontology view-ontology-light", html! { nav class="breadcrumb" { (bc_path_external(&ext_path)) } - h2 { "external paths" } + h2 { + "external paths" + @if !(child_rankings.component_rankings.is_empty() && child_rankings.unranked_items.is_empty()) { + " " + (garden_rank_copy_button_markup(&nav, "", 1, true)) + } + } p class="muted" { "Items outside slug.social use the " code { "-/" } " prefix followed by the full " code { "https://…" } " URL (legacy " code { "-/host/path" } " still works)." } @if child_rankings.component_rankings.is_empty() && child_rankings.unranked_items.is_empty() { p class="muted" { "no external items indexed yet" } @@ -272,7 +285,13 @@ pub async fn room_external_garden_index( "view-ontology view-ontology-light", html! { nav class="breadcrumb" { (scoped_bc_path_external(&ext_path, &nav)) } - h2 { "external paths" } + h2 { + "external paths" + @if !(child_rankings.component_rankings.is_empty() && child_rankings.unranked_items.is_empty()) { + " " + (garden_rank_copy_button_markup(&nav, "", 1, true)) + } + } @if child_rankings.component_rankings.is_empty() && child_rankings.unranked_items.is_empty() { p class="muted" { "no external items indexed yet" } } @else { diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs index d7014fc7f934e5b0c7fb47ebf00cb4ef50d306c2..645d54f2e117ba901e02ed958ada6ff69a78ae34 100644 --- a/server/src/html/mod.rs +++ b/server/src/html/mod.rs @@ -37,8 +37,8 @@ pub(crate) use forum::{ user_can_post_room, user_can_view_room, }; pub(crate) use garden::{ - encode_pin_cookie_value, external_resolver_status_markup, vote_compare_post_success_js, - GARDEN_PIN_COOKIE, + encode_pin_cookie_value, external_resolver_status_markup, garden_ui_copy_rank, + vote_compare_post_success_js, GARDEN_PIN_COOKIE, }; pub use garden::{ external_garden_index, external_ontology_path, garden_index, ontology_path, diff --git a/server/src/html/ui_action.rs b/server/src/html/ui_action.rs index 5cf3168fb74e7654215cd9ff8942c6ed63fd0002..7dc3db062954370b5504fc311c0ab24bab569f80 100644 --- a/server/src/html/ui_action.rs +++ b/server/src/html/ui_action.rs @@ -118,6 +118,18 @@ pub enum HtmlUiAction { thread_tag: String, copy_btn_id: String, }, + /// Copy garden child ranking as a concise markdown list to the clipboard. + CopyGardenRank { + room: String, + /// Parent item path (storage or display). Ignored when `external_hosts` is true. + parent_path: String, + #[serde(default = "default_garden_rank_depth")] + depth: usize, + copy_btn_id: String, + /// When true, copy rankings for external host roots (`/-/` index), not parent children. + #[serde(default)] + external_hosts: bool, + }, /// Publish a private-room thread to the public forum (Manage only). GraduateThread { room: String, @@ -125,6 +137,10 @@ pub enum HtmlUiAction { }, } +fn default_garden_rank_depth() -> usize { + 1 +} + #[derive(Debug, Error)] pub enum HtmlUiParseError { #[error("missing __rpc__ field")] @@ -272,4 +288,57 @@ mod tests { } ); } + + #[test] + fn copy_garden_rank_round_trip() { + let template = serde_json::json!({ + "action": "copy_garden_rank", + "room": "public", + "parent_path": "~/topic", + "depth": 2, + "copy_btn_id": "garden-rank-copy", + }); + let mut form = HashMap::new(); + form.insert( + UI_RPC_FIELD.to_string(), + serde_json::to_string(&template).unwrap(), + ); + let a = parse_html_ui_from_form(&form).unwrap(); + assert_eq!( + a, + HtmlUiAction::CopyGardenRank { + room: "public".into(), + parent_path: "~/topic".into(), + depth: 2, + copy_btn_id: "garden-rank-copy".into(), + external_hosts: false, + } + ); + } + + #[test] + fn copy_garden_rank_defaults_depth_and_external_hosts() { + let template = serde_json::json!({ + "action": "copy_garden_rank", + "room": "public", + "parent_path": "~/", + "copy_btn_id": "garden-rank-copy", + }); + let mut form = HashMap::new(); + form.insert( + UI_RPC_FIELD.to_string(), + serde_json::to_string(&template).unwrap(), + ); + let a = parse_html_ui_from_form(&form).unwrap(); + assert_eq!( + a, + HtmlUiAction::CopyGardenRank { + room: "public".into(), + parent_path: "~/".into(), + depth: 1, + copy_btn_id: "garden-rank-copy".into(), + external_hosts: false, + } + ); + } } diff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs index d242abff5769cc704b3c8070d7456e5788c31a45..6b1475b773106a2dd3f326475c9fb4cc727f6b4b 100644 --- a/server/tests/integration_ui.rs +++ b/server/tests/integration_ui.rs @@ -490,3 +490,71 @@ async fn test_vote_compare_post_rejects_over_max_ratio() { ); } +#[tokio::test] +async fn test_copy_garden_rank_returns_clipboard_js_with_markdown() { + let (addr, _tmp, _log, _handle) = create_test_server().await; + let client = reqwest::Client::new(); + let bearer = test_bearer(); + + let seed = rpc_batch( + &client, + addr, + Some(&bearer), + serde_json::json!([{ + "Post": { + "room": "public", + "thread_tag": "copy-rank-ui", + "text": "# copy-rank-ui\n\n~/copy-a {a}\n~/copy-b {b}\n~/copy-c {c}\n{vote}\n~/copy-a 2:1 ~/copy-b\n", + "return_rank_diff": false + } + }]), + ) + .await; + assert_eq!(seed["results"][0]["ok"], true, "seed: {:?}", seed); + + let page = client + .get(format!("http://{addr}/~")) + .send() + .await + .unwrap(); + assert!(page.status().is_success()); + let html = page.text().await.unwrap(); + assert!( + html.contains("id=\"garden-rank-copy\"") && html.contains("copy_garden_rank"), + "garden index should include copy button + action payload" + ); + + let rpc = serde_json::json!({ + "action": "copy_garden_rank", + "room": "public", + "parent_path": "~/", + "depth": 1, + "copy_btn_id": "garden-rank-copy", + }) + .to_string(); + let resp = client + .post(format!("http://{addr}/ui")) + .header("Authorization", format!("Bearer {bearer}")) + .form(&[("__rpc__", rpc.as_str())]) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), reqwest::StatusCode::OK); + assert_eq!( + resp.headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()), + Some("text/javascript; charset=utf-8") + ); + let js = resp.text().await.unwrap(); + assert!( + js.contains("navigator.clipboard.writeText") && js.contains("garden-rank-copy"), + "expected clipboard JsBuilder snippet, got: {js}" + ); + assert!( + js.contains("1. ~/copy-a") && js.contains("2. ~/copy-b") && js.contains("- ~/copy-c"), + "expected concise markdown ranking in clipboard payload, got: {js}" + ); + assert!(js.contains("\"copied\""), "expected button label flip to copied"); +} + diff --git a/test/browser_public_garden.clj b/test/browser_public_garden.clj index 5dd49f1f70c870e25a2a9f5348f0bdb85647e897..8ceb532c664f9fc3d6f66a451e5ea5eaa1671007 100644 --- a/test/browser_public_garden.clj +++ b/test/browser_public_garden.clj @@ -73,6 +73,7 @@ (core/with-playwright [pw] (core/with-browser [browser (core/launch-chromium pw {:headless true :channel "chrome"})] (core/with-context [ctx (core/new-context browser)] + (core/context-grant-permissions! ctx ["clipboard-read" "clipboard-write"]) (core/with-page [pg (core/new-page-from-context ctx)] (page/navigate pg (str base-url "/login")) (is (wait-for-text pg "body" "@alice" 15000) "alice session after login") @@ -84,7 +85,12 @@ (is (wait-for-text pg "body" "~/br-pub-b" 10000) "ranked list shows ~/br-pub-b") (is (wait-for-text pg "body" "unranked" 10000) "unranked section present") (is (wait-for-text pg "body" "~/br-pub-c" 10000) - "unranked list shows ~/br-pub-c")))))) + "unranked list shows ~/br-pub-c") + (is (wait-for-text pg "#garden-rank-copy" "copy" 5000) + "garden ranking copy button visible") + (locator/click (page/locator pg "#garden-rank-copy")) + (is (wait-for-text pg "#garden-rank-copy" "copied" 10000) + "copy button flips to copied after POST /ui eval")))))) (finally (when-some [s @!server] (common/kill-server s)) Side B — contributor: tommy-mor Side B — commit message: [674964ef] refactor: Deref for href newtypes, CanonicalItemUrl through resolve_item - Implement Deref for GardenItemUrl, ForumThreadUrl, TildeOntologyPath - resolve_item returns CanonicalItemUrl; validate uses HashSet - compute_scope_rank_changes keys are CanonicalItemUrl; pair RPC uses Vec pool - pick_random_distinct_canonical; connectivity stats on &[CanonicalItemUrl] - Global rank unranked uses stored ids before GardenItemUrl mapping Made-with: Cursor Side B — unified diff (full patch): diff --git a/server/src/api/helpers.rs b/server/src/api/helpers.rs index 03b3e77911ccd662bec8635345dafe2593cf242e..1b291db83df7364a026f2e147e0a29a70a399371 100644 --- a/server/src/api/helpers.rs +++ b/server/src/api/helpers.rs @@ -30,13 +30,13 @@ pub fn now_ms() -> i64 { t.as_millis() as i64 } -/// Resolve an item path as a first-class canonical path. -pub fn resolve_item(item: &str) -> Result { +/// Resolve DSL/user input to a stored canonical item id. +pub fn resolve_item(item: &str) -> Result { let canonical = canonicalize_item(item); if canonical.is_empty() { return Err(format!("empty item path: `{}`", item)); } - Ok(canonical) + Ok(CanonicalItemUrl(canonical)) } pub fn parse_parent_specs(parent: Option<&String>) -> Vec { @@ -94,7 +94,7 @@ pub fn paginate_rankings( (out_components, out_unranked) } -pub fn pick_random_distinct(items: &[String]) -> Option<(String, String)> { +pub fn pick_random_distinct_canonical(items: &[CanonicalItemUrl]) -> Option<(CanonicalItemUrl, CanonicalItemUrl)> { use rand::seq::SliceRandom; if items.len() < 2 { return None; @@ -123,15 +123,12 @@ pub fn is_pair_voted(group: &crate::reducer::GroupState, a: &str, b: &str) -> bo group.voted_pairs.contains(&(i, j)) } -pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[String]) -> ConnectivityStats { +pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[CanonicalItemUrl]) -> ConnectivityStats { let n = pool.len(); let global_idxs: Vec> = pool .iter() - .map(|it| { - let key = CanonicalItemUrl(it.clone()); - group.item_to_idx.get(&key).copied() - }) + .map(|it| group.item_to_idx.get(it).copied()) .collect(); let present: Vec = global_idxs.iter().filter_map(|x| *x).collect(); diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index cf22cb0129366c3aed031bc86f3197a4321cb806..a10ce662105cff8fad949c6b83f7035ce79bed18 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -24,7 +24,7 @@ pub use auth::{ pub use helpers::{ api_error, compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings, - parse_parent_specs, pick_random_distinct, resolve_item, sha256_hex, vote_touches_path, + parse_parent_specs, pick_random_distinct_canonical, resolve_item, sha256_hex, vote_touches_path, }; pub use rpc::handle_rpc_batch; diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs index 5f7d50188f1381267402f2e57e671234ef5db2fd..de0955d0887d32740e1fd18365205c5bdb53c247 100644 --- a/server/src/api/rpc.rs +++ b/server/src/api/rpc.rs @@ -29,7 +29,7 @@ use crate::{ use super::auth::verify_bearer_principal; use super::helpers::{ compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings, parse_parent_specs, - pick_random_distinct, resolve_item, vote_touches_path, + pick_random_distinct_canonical, resolve_item, vote_touches_path, }; use super::validate::{normalize_room_and_thread, validate_ingest_document}; @@ -146,21 +146,21 @@ fn authorize_room_read(reduced: &ReducerState, headers: &HeaderMap, room: &str) } fn compute_scope_rank_changes( - parent: &str, + parent: &CanonicalItemUrl, before: &crate::scope_rank::ChildrenRankings, after: &crate::scope_rank::ChildrenRankings, room_wire: &str, ) -> Option { - fn build_positions(rankings: &crate::scope_rank::ChildrenRankings) -> HashMap> { + fn build_positions(rankings: &crate::scope_rank::ChildrenRankings) -> HashMap> { let mut map = HashMap::new(); for comp in &rankings.component_rankings { let total = comp.ranked.len(); for (i, item) in comp.ranked.iter().enumerate() { - map.insert(item.item.as_str().to_string(), Some(RankPosition { rank: i + 1, of: total })); + map.insert(item.item.clone(), Some(RankPosition { rank: i + 1, of: total })); } } for item in &rankings.unranked_items { - map.insert(item.as_str().to_string(), None); + map.insert(item.clone(), None); } map } @@ -168,7 +168,7 @@ fn compute_scope_rank_changes( let before_pos = build_positions(before); let after_pos = build_positions(after); - let all_items: std::collections::BTreeSet = before_pos.keys().cloned() + let all_items: std::collections::BTreeSet = before_pos.keys().cloned() .chain(after_pos.keys().cloned()) .collect(); @@ -184,7 +184,7 @@ fn compute_scope_rank_changes( }; if changed { changes.push(RankChange { - item: GardenItemUrl::from_storage_str(&item, room_wire), + item: GardenItemUrl::from_stored(&item, room_wire), before: b, after: a, }); @@ -203,11 +203,7 @@ fn compute_scope_rank_changes( }); Some(ScopeRankChanges { - parent: if parent.is_empty() { - "/".to_string() - } else { - GardenItemUrl::from_storage_str(parent, room_wire).into_inner() - }, + parent: GardenItemUrl::from_stored(parent, room_wire).into_inner(), changes, }) } @@ -473,8 +469,8 @@ async fn rpc_post( for s in &v.doc.statements { if let dsl::Stmt::Vote { item1, item2, .. } = s { if let (Ok(a), Ok(b)) = (resolve_item(item1), resolve_item(item2)) { - if let Some(p) = CanonicalItemUrl::parse(&a).and_then(|c| c.parent()) { parents.insert(p); } - if let Some(p) = CanonicalItemUrl::parse(&b).and_then(|c| c.parent()) { parents.insert(p); } + if let Some(p) = a.parent() { parents.insert(p); } + if let Some(p) = b.parent() { parents.insert(p); } } } } @@ -525,7 +521,7 @@ async fn rpc_post( .filter_map(|p| { let before = pre_rankings.get(p)?; let after = crate::scope_rank::build_children_rankings(content, p); - compute_scope_rank_changes(p.as_str(), before, &after, &room_key) + compute_scope_rank_changes(p, before, &after, &room_key) }) .collect(); if v.is_empty() { None } else { Some(v) } @@ -638,8 +634,8 @@ async fn rpc_check( for s in &v.doc.statements { if let dsl::Stmt::Vote { item1, item2, .. } = s { if let (Ok(a), Ok(b)) = (resolve_item(item1), resolve_item(item2)) { - if let Some(p) = CanonicalItemUrl::parse(&a).and_then(|c| c.parent()) { parents.insert(p); } - if let Some(p) = CanonicalItemUrl::parse(&b).and_then(|c| c.parent()) { parents.insert(p); } + if let Some(p) = a.parent() { parents.insert(p); } + if let Some(p) = b.parent() { parents.insert(p); } } } } @@ -961,7 +957,7 @@ fn rpc_search(reduced: &ReducerState, q: &str, limit: usize, principal: Option<& async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Result { let scope = scope_from_room_wire(&room); let reduced_arc = state.reduced.clone(); - let pool: Vec = { + let pool: Vec = { let reduced = reduced_arc.read().await; let content = content_for_room(&reduced, &room); let tmp = if parent_path.trim().is_empty() { @@ -970,12 +966,11 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re Some(parent_path.clone()) }; let specs = parse_parent_specs(tmp.as_ref()); - let raw_pool: Vec = if specs.is_empty() { + if specs.is_empty() { content.ranking_group.idx_to_item.clone() } else { crate::scope_rank::resolve_scope(content, &specs) - }; - raw_pool.into_iter().map(|it| it.0).collect() + } }; if pool.len() < 2 { return Err(( @@ -983,31 +978,30 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re Some("add items via ingest".into()), )); } - let selected: Option<(String, String)> = { + let selected: Option<(CanonicalItemUrl, CanonicalItemUrl)> = { let mut reduced = reduced_arc.write().await; let content = reduced.content.entry(scope.clone()).or_default(); let group = &mut content.ranking_group; if group.idx_to_item.is_empty() { - pick_random_distinct(&pool) + pick_random_distinct_canonical(&pool) } else { let mut rng = rand::thread_rng(); - let idxs: Vec = pool.iter() - .filter_map(|it| { - let key = CanonicalItemUrl(it.clone()); - group.item_to_idx.get(&key).copied() - }) + let idxs: Vec = pool + .iter() + .filter_map(|it| group.item_to_idx.get(it).copied()) .collect(); let ranked = ranked_items_subset(group, &idxs, 10000, 1e-8); - let ranked_set: HashSet = ranked.iter().map(|r| r.item.as_str().to_string()).collect(); - let unsorted: Vec = pool.iter() + let ranked_set: HashSet = ranked.iter().map(|r| r.item.clone()).collect(); + let unsorted: Vec = pool + .iter() .filter(|it| !ranked_set.contains(*it)) .cloned() .collect(); - let mut pick: Option<(String, String)> = None; + let mut pick: Option<(CanonicalItemUrl, CanonicalItemUrl)> = None; if !unsorted.is_empty() { if let Some(left) = unsorted.choose(&mut rng).cloned() { - let mut candidates: Vec = if !ranked.is_empty() { - ranked.iter().map(|r| r.item.as_str().to_string()).collect() + let mut candidates: Vec = if !ranked.is_empty() { + ranked.iter().map(|r| r.item.clone()).collect() } else { pool.clone() }; @@ -1021,21 +1015,21 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re let a = ranked[i].item.as_str(); let b = ranked[i + 1].item.as_str(); if a != b && !is_pair_voted(group, a, b) { - pick = Some((a.to_string(), b.to_string())); + pick = Some((ranked[i].item.clone(), ranked[i + 1].item.clone())); break; } } if pick.is_none() { for _ in 0..64 { let (Some(a), Some(b)) = (pool.choose(&mut rng).cloned(), pool.choose(&mut rng).cloned()) else { break; }; - if a != b && !is_pair_voted(group, &a, &b) { + if a != b && !is_pair_voted(group, a.as_str(), b.as_str()) { pick = Some((a, b)); break; } } } } - pick.or_else(|| pick_random_distinct(&pool)) + pick.or_else(|| pick_random_distinct_canonical(&pool)) } }; let Some((left, right)) = selected else { @@ -1043,8 +1037,8 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re }; let reduced = reduced_arc.read().await; let content = content_for_room(&reduced, &room); - let left_key = CanonicalItemUrl(left.clone()); - let right_key = CanonicalItemUrl(right.clone()); + let left_key = left.clone(); + let right_key = right.clone(); let lb = content.item_bodies.get(&left_key).cloned(); let rb = content.item_bodies.get(&right_key).cloned(); let th: Vec = content @@ -1058,8 +1052,8 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re .collect(); let cs = compute_connectivity_stats(&content.ranking_group, &pool); Ok(RpcResult::Pair(PairResponse { - left: GardenItemUrl::from_storage_str(&left, &room), - right: GardenItemUrl::from_storage_str(&right, &room), + left: GardenItemUrl::from_stored(&left, &room), + right: GardenItemUrl::from_stored(&right, &room), left_body: lb, right_body: rb, threads: th, @@ -1554,7 +1548,7 @@ pub async fn handle_rpc_batch( for r in items { let pct = want_percent.then(|| ((r.score - bot) / range * 100.0).clamp(0.0, 100.0)); ranked.push(RankRow { - item: GardenItemUrl::from_storage_str(r.item.as_str(), &room), + item: GardenItemUrl::from_stored(&r.item, &room), score: r.score, percent: pct, }); @@ -1562,11 +1556,11 @@ pub async fn handle_rpc_batch( } let ranked_total = ranked.len(); - let mut unranked: Vec = content + let mut unranked: Vec = content .items .iter() .filter(|it| !group.item_to_idx.contains_key(*it)) - .map(|it| it.as_str().to_string()) + .cloned() .collect(); unranked.sort(); let unranked_total = unranked.len(); @@ -1574,7 +1568,7 @@ pub async fn handle_rpc_batch( let page: Vec = ranked .into_iter() .chain(unranked.into_iter().map(|it| RankRow { - item: GardenItemUrl::from_storage_str(&it, &room), + item: GardenItemUrl::from_stored(&it, &room), score: 0.0, percent: want_percent.then_some(0.0), })) @@ -1722,7 +1716,7 @@ pub async fn handle_rpc_batch( .filter(|p| !parents.contains(p.as_str())) .map(|p| GardenItemUrl::from_stored(p, &room)) .collect(); - paths.sort_by(|a, b| a.as_str().cmp(b.as_str())); + paths.sort(); line_ok(RpcResult::Leaves(LeavesResponse { paths })) } }, diff --git a/server/src/api/validate.rs b/server/src/api/validate.rs index a51c783ee9785569b5a44c0b1572471fe00d174b..3c7aa80fd485cf247231fe5c5c7e6fea62f22534 100644 --- a/server/src/api/validate.rs +++ b/server/src/api/validate.rs @@ -52,7 +52,7 @@ pub fn validate_ingest_document( }; let ts = super::helpers::now_ms(); - let mut defined_in_doc: HashSet = HashSet::new(); + let mut defined_in_doc: HashSet = HashSet::new(); for s in &doc.statements { match s { @@ -66,14 +66,14 @@ pub fn validate_ingest_document( let Some(body_text) = body else { return Err(( StatusCode::BAD_REQUEST, - format!("item missing body: {}", GardenItemUrl::from_storage_str(&item, room_wire)), + format!("item missing body: {}", GardenItemUrl::from_stored(&item, room_wire)), Some("items must be declared with bodies, e.g. `~/path/item { ... }`".to_string()), )); }; if body_text.trim().is_empty() { return Err(( StatusCode::BAD_REQUEST, - format!("item body is empty: {}", GardenItemUrl::from_storage_str(&item, room_wire)), + format!("item body is empty: {}", GardenItemUrl::from_stored(&item, room_wire)), Some("write at least one sentence inside `{ ... }`".to_string()), )); } @@ -102,11 +102,8 @@ pub fn validate_ingest_document( }; let missing: Vec = [&a, &b] .into_iter() - .filter(|it| { - let key = CanonicalItemUrl((*it).clone()); - !defined_in_doc.contains(*it) && !item_exists(&key) - }) - .map(|it| GardenItemUrl::from_storage_str(it, room_wire).into_inner()) + .filter(|it| !defined_in_doc.contains(*it) && !item_exists(it)) + .map(|it| GardenItemUrl::from_stored(it, room_wire).into_inner()) .collect(); if !missing.is_empty() { return Err(( @@ -120,11 +117,8 @@ pub fn validate_ingest_document( } let missing_body: Vec = [&a, &b] .into_iter() - .filter(|it| { - let key = CanonicalItemUrl((*it).clone()); - !defined_in_doc.contains(*it) && !body_exists(&key) - }) - .map(|it| GardenItemUrl::from_storage_str(it, room_wire).into_inner()) + .filter(|it| !defined_in_doc.contains(*it) && !body_exists(it)) + .map(|it| GardenItemUrl::from_stored(it, room_wire).into_inner()) .collect(); if !missing_body.is_empty() { return Err(( diff --git a/server/src/html/editor.rs b/server/src/html/editor.rs index ecdd226b1b17d5f11d1b79f99add5759ef918281..26d648d7c8d6e5d53ce5ed7a051b44856fca2fcf 100644 --- a/server/src/html/editor.rs +++ b/server/src/html/editor.rs @@ -130,8 +130,8 @@ pub async fn editor_check( for s in &v.doc.statements { if let crate::dsl::Stmt::Vote { item1, item2, .. } = s { if let (Ok(a), Ok(b)) = (resolve_item(item1), resolve_item(item2)) { - if let Some(p) = crate::path_types::CanonicalItemUrl::parse(&a).and_then(|c| c.parent()) { parents.insert(p); } - if let Some(p) = crate::path_types::CanonicalItemUrl::parse(&b).and_then(|c| c.parent()) { parents.insert(p); } + if let Some(p) = a.parent() { parents.insert(p); } + if let Some(p) = b.parent() { parents.insert(p); } } } } diff --git a/types/src/paths.rs b/types/src/paths.rs index 2950a7502255927583fbacdfd2adb700f0b0c221..839684dfa0ecdd6c2572e2d8132ecee4d5c41bf8 100644 --- a/types/src/paths.rs +++ b/types/src/paths.rs @@ -3,6 +3,7 @@ use std::borrow::Borrow; use std::fmt; +use std::ops::Deref; use serde::{Deserialize, Serialize}; @@ -319,6 +320,14 @@ impl fmt::Display for GardenItemUrl { } } +impl Deref for GardenItemUrl { + type Target = str; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + fn garden_href_string(item: &str, room_wire: &str) -> String { let room = room_wire.trim(); if room.is_empty() || room == "public" { @@ -386,6 +395,14 @@ impl fmt::Display for ForumThreadUrl { } } +impl Deref for ForumThreadUrl { + type Target = str; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + /// `~/a/b` style path for list UIs (paths index `path` field). #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] @@ -412,6 +429,14 @@ impl fmt::Display for TildeOntologyPath { } } +impl Deref for TildeOntologyPath { + type Target = str; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + #[cfg(test)] mod tests { use super::*; @@ -452,6 +477,13 @@ mod tests { assert_eq!(c.tilde_segments(), Vec::<&str>::new()); } + #[test] + fn garden_item_url_deref_to_str() { + let g = GardenItemUrl::from_storage_str("https://slug.social/~/x", "public"); + let s: &str = &*g; + assert_eq!(s, "https://slug.social/~/x"); + } + #[test] fn garden_public_passthrough_https() { let u = "https://slug.social/~/a/b";