From 464bb498ca0bb961d69c49bff68b78d7c14de07b Mon Sep 17 00:00:00 2001 From: rob thijssen Date: Wed, 7 Oct 2026 16:13:14 +0300 Subject: [PATCH] feat: search box in the chain header A pasted hash, address or account now opens its page. On this chain one string can be several things: 0x and 64 hex is a block hash, a transaction hash, an account id or a miner's preimage; 64 hex without the prefix is also a NEAR implicit account. So nothing is decided by shape. GET /v1/chains/{chain}/search?q= looks for every kind the string could be, and offers a page only when the data confirms it exists: - a block that is recorded or that the node has; - an indexed transaction hash; - an account with a balance or with activity; - a miner with blocks; - a telemetry node; - a cached runtime version; - a NEAR Intents account the contract knows. A NEAR transaction hash is the one exception. It is offered as a candidate and labelled as looked up when opened, because confirming it would spend a public RPC call on every search. The header box searches on Enter, never while typing. One hit opens it; several are listed to choose from with the arrow keys, never chosen for the reader; none says what the string was checked as, and a transaction hash missed while the #48 backfill runs says so. The masthead's right-hand group now takes the free width, right aligned, so the search box no longer wraps the connection light and theme toggle onto a second line. Closes #49 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015tyzzRVjH9AdwGtYwsH5VC --- ...f7ce40fce3a20b1787fe9a07d55f17fb85bda.json | 23 ++ crates/blackbeard-api/src/main.rs | 1 + crates/blackbeard-api/src/neartx.rs | 8 + crates/blackbeard-api/src/routes.rs | 20 ++ crates/blackbeard-api/src/search.rs | 271 ++++++++++++++++++ crates/blackbeard-data/src/store.rs | 18 ++ crates/blackbeard-entities/src/chain.rs | 34 +++ crates/blackbeard-entities/src/lib.rs | 4 +- web/src/App.tsx | 5 + web/src/api/generated/SearchHit.ts | 24 ++ web/src/api/generated/SearchResults.ts | 30 ++ web/src/api/rest.ts | 13 + web/src/components/SearchBox.tsx | 200 +++++++++++++ web/src/index.css | 82 ++++++ 14 files changed, 731 insertions(+), 2 deletions(-) create mode 100644 .sqlx/query-01b1f50b17b150bd3a374ee04c9f7ce40fce3a20b1787fe9a07d55f17fb85bda.json create mode 100644 crates/blackbeard-api/src/search.rs create mode 100644 web/src/api/generated/SearchHit.ts create mode 100644 web/src/api/generated/SearchResults.ts create mode 100644 web/src/components/SearchBox.tsx diff --git a/.sqlx/query-01b1f50b17b150bd3a374ee04c9f7ce40fce3a20b1787fe9a07d55f17fb85bda.json b/.sqlx/query-01b1f50b17b150bd3a374ee04c9f7ce40fce3a20b1787fe9a07d55f17fb85bda.json new file mode 100644 index 0000000..57662ca --- /dev/null +++ b/.sqlx/query-01b1f50b17b150bd3a374ee04c9f7ce40fce3a20b1787fe9a07d55f17fb85bda.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "select height from block where chain = $1 and hash = $2 limit 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "height", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "01b1f50b17b150bd3a374ee04c9f7ce40fce3a20b1787fe9a07d55f17fb85bda" +} diff --git a/crates/blackbeard-api/src/main.rs b/crates/blackbeard-api/src/main.rs index e5d685a..070a7cf 100644 --- a/crates/blackbeard-api/src/main.rs +++ b/crates/blackbeard-api/src/main.rs @@ -21,6 +21,7 @@ mod refdcl; mod refv1; mod registry; mod routes; +mod search; mod state; mod ws; diff --git a/crates/blackbeard-api/src/neartx.rs b/crates/blackbeard-api/src/neartx.rs index 9a33b0b..32d039c 100644 --- a/crates/blackbeard-api/src/neartx.rs +++ b/crates/blackbeard-api/src/neartx.rs @@ -546,6 +546,14 @@ impl NearReader { }) } + /// A view call on the Intents contract, through our own node. + pub async fn intents_view(&self, method: &str, args: Value) -> Option { + self.intents_node + .view_live(&self.intents.contract, method, args) + .await + .ok() + } + /// Every non-zero balance, from our own node. `None` when the contract /// could not be asked — never an empty list standing in for "could not /// tell". diff --git a/crates/blackbeard-api/src/routes.rs b/crates/blackbeard-api/src/routes.rs index 36ba34e..8902ae8 100644 --- a/crates/blackbeard-api/src/routes.rs +++ b/crates/blackbeard-api/src/routes.rs @@ -58,6 +58,7 @@ pub fn router(state: AppState, allowed_origins: &[String]) -> Router { .route("/v1/chains/{chain}/series", get(series)) .route("/v1/chains/{chain}/blocks/{block}", get(block)) .route("/v1/chains/{chain}/tx/{hash}", get(tx)) + .route("/v1/chains/{chain}/search", get(search)) .route("/v1/chains/{chain}/miners/{miner}", get(miner)) .route("/v1/chains/{chain}/network", get(network)) .route("/v1/chains/{chain}/vesting", get(vesting)) @@ -5344,6 +5345,25 @@ async fn tx( })) } +#[derive(Debug, Deserialize)] +struct SearchQuery { + /// What was pasted. + q: String, +} + +/// `GET /v1/chains/{chain}/search?q=`: every page a pasted string resolves to, +/// each confirmed against data (blackbeard/observer#49). +async fn search( + State(state): State, + Path(chain): Path, + Query(query): Query, +) -> Result, Failure> { + let runtime = state.chain(&chain).ok_or_else(|| unknown_chain(&chain))?; + Ok(Json( + crate::search::resolve(&state, &runtime, &query.q).await, + )) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/blackbeard-api/src/search.rs b/crates/blackbeard-api/src/search.rs new file mode 100644 index 0000000..12d5f8d --- /dev/null +++ b/crates/blackbeard-api/src/search.rs @@ -0,0 +1,271 @@ +//! What a pasted string is (blackbeard/observer#49). +//! +//! The same text can be several things here. `0x` and 64 hex is a block hash, +//! an extrinsic hash, an account id or a miner's preimage; 64 hex without the +//! `0x` is also a NEAR implicit account; a short number is a height and maybe a +//! runtime version. So nothing is decided by shape. Shape only says what to +//! look for, and a page is offered when the data says it exists: the block is +//! recorded or the node has it, the extrinsic hash is indexed, the account +//! holds something or has done something. The one exception is a NEAR +//! transaction hash, which would cost a public RPC call per search to confirm; +//! it is offered as a candidate and says so. +//! +//! Input never reaches a node verbatim: every candidate passes the same check +//! its route does first. + +use blackbeard_entities::{SearchHit, SearchResults}; +use serde_json::json; + +use crate::state::{AppState, ChainRuntime}; + +/// The longest string worth looking at. A NEAR account id is at most 64 +/// characters; anything far longer is not an address of any kind. +const MAX_QUERY: usize = 128; + +fn hit( + kind: &str, + value: impl Into, + label: impl Into, + detail: Option, +) -> SearchHit { + SearchHit { + kind: kind.into(), + value: value.into(), + label: label.into(), + detail, + } +} + +fn thousands(n: u64) -> String { + let s = n.to_string(); + let mut out = String::new(); + for (i, c) in s.chars().enumerate() { + if i > 0 && (s.len() - i) % 3 == 0 { + out.push(','); + } + out.push(c); + } + out +} + +fn is_hex(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Resolve `raw` on one chain. +pub async fn resolve(state: &AppState, runtime: &ChainRuntime, raw: &str) -> SearchResults { + let id = runtime.id(); + let q = raw.trim(); + let mut hits = Vec::new(); + let mut checked: Vec = Vec::new(); + let mut note = None; + let store = &state.store; + + if q.is_empty() || q.len() > MAX_QUERY { + return SearchResults { + chain: id, + query: q.chars().take(MAX_QUERY).collect(), + hits, + checked: vec!["nothing: the text is empty or far longer than any address".into()], + note, + }; + } + + // A number: a height, and perhaps a runtime version. + if q.bytes().all(|b| b.is_ascii_digit()) { + if let Ok(n) = q.parse::() { + checked.push("a block height".into()); + let tip = runtime.read().height; + if tip.is_some_and(|t| n <= t) { + hits.push(hit( + "block", + n.to_string(), + format!("block #{}", thousands(n)), + None, + )); + } + checked.push("a runtime version".into()); + if let (Ok(spec), Ok(cached)) = (u32::try_from(n), store.cached_runtimes(&id).await) { + if cached.iter().any(|r| r.spec_version == spec) { + hits.push(hit( + "runtime", + n.to_string(), + format!("runtime version {n}"), + None, + )); + } + } + } + } + + // 32 bytes of hex, with or without `0x`. + let bare = q + .strip_prefix("0x") + .or_else(|| q.strip_prefix("0X")) + .unwrap_or(q); + if bare.len() == 64 && is_hex(bare) { + let hex = format!("0x{}", bare.to_ascii_lowercase()); + + checked.push("a block hash".into()); + let recorded = store.block_height_by_hash(&id, &hex).await.ok().flatten(); + let height = match recorded { + Some(h) => Some(h), + None => match runtime.rpc.header(Some(&hex)).await { + Ok(Some(header)) => header.height(), + _ => None, + }, + }; + if let Some(h) = height { + hits.push(hit( + "block", + hex.clone(), + format!("block #{}", thousands(h)), + None, + )); + } + + checked.push("a transaction hash".into()); + match store.extrinsic_at_hash(&id, &hex).await { + Ok(Some((h, i))) => hits.push(hit( + "tx", + hex.clone(), + format!("transaction: extrinsic {i} of block #{}", thousands(h)), + None, + )), + Ok(None) => { + let remaining = store.unhashed_count(&id).await.unwrap_or(0); + if remaining > 0 { + note = Some(format!( + "{} older transactions are still being hashed; if this is one of them, it will be found once the backfill reaches it", + thousands(remaining) + )); + } + } + Err(_) => {} + } + + checked.push("an account".into()); + if let Some(address) = blackbeard_core::wormhole::ss58_of(&hex) { + let (balance, _) = crate::routes::read_balance(runtime, &hex).await; + let active = store + .account_activity(&id, &hex, None, 1) + .await + .map(|a| !a.is_empty()) + .unwrap_or(false); + if balance.is_some() || active { + let short = format!("{}…{}", &address[..8], &address[address.len() - 4..]); + hits.push(hit("account", address, format!("account {short}"), None)); + } + } + + checked.push("a miner's reward preimage".into()); + if let Ok((blocks, _, _, _)) = store + .miner_totals(&id, &blackbeard_entities::MinerId(hex.clone())) + .await + { + if blocks > 0 { + hits.push(hit( + "miner", + hex.clone(), + format!("miner who won {} blocks", thousands(blocks)), + None, + )); + } + } + } + + // A Quantus address: the checksum and network prefix are the confirmation. + if let Some(account) = blackbeard_core::wormhole::account_id(q) { + checked.push("a Quantus address".into()); + let active = store + .account_activity(&id, &account, None, 1) + .await + .map(|a| !a.is_empty()) + .unwrap_or(false); + let detail = (!active).then(|| "a valid address with no activity indexed".to_owned()); + let short = format!("{}…{}", &q[..8], &q[q.len() - 4..]); + hits.push(hit("account", q, format!("account {short}"), detail)); + } + + // A telemetry node, by peer id. + if (40..=64).contains(&q.len()) && q.bytes().all(|b| b.is_ascii_alphanumeric()) { + checked.push("a telemetry node".into()); + if let Ok(Some(_)) = store.node_telemetry(q).await { + hits.push(hit("node", q, format!("node {}…", &q[..12]), None)); + } + } + + // The NEAR side, where the chain follows a token there. + if let Some(reader) = crate::neartx::reader(runtime).await { + if crate::neartx::valid_tx_hash(q) { + checked.push("a NEAR transaction hash".into()); + let kept = store.near_tx(q).await.ok().flatten().is_some(); + hits.push(hit( + "near_tx", + q, + format!("NEAR transaction {}…", &q[..10]), + (!kept).then(|| "looked up on NEAR when opened".to_owned()), + )); + } + // An Intents account: an implicit one (64 hex, or `0x` and 40) or a + // named one with a dot. Offered only if the Intents contract knows it. + let lower = q.to_ascii_lowercase(); + let implicit = (lower.len() == 64 && is_hex(&lower)) + || (lower.len() == 42 && lower.starts_with("0x") && is_hex(&lower[2..])); + let named = lower.contains('.'); + if (implicit || named) && crate::neartx::valid_account(&lower) { + checked.push("a NEAR Intents account".into()); + if reader.intents_account_known(&lower).await { + hits.push(hit( + "intents_account", + lower.clone(), + format!("NEAR Intents account {}", short_near(&lower)), + None, + )); + } + } + } + + // One page, one hit: the same block found by height and by hash is not two. + hits.dedup_by(|a, b| a.kind == b.kind && a.value == b.value); + SearchResults { + chain: id, + query: q.to_owned(), + hits, + checked, + note, + } +} + +fn short_near(a: &str) -> String { + if a.len() > 24 { + format!("{}…{}", &a[..8], &a[a.len() - 6..]) + } else { + a.to_owned() + } +} + +impl crate::neartx::NearReader { + /// Whether the Intents contract knows an account: it holds a token there, + /// or has registered a key to sign intents with. + pub async fn intents_account_known(&self, account: &str) -> bool { + let tokens = self + .intents_view( + "mt_tokens_for_owner", + json!({"account_id": account, "limit": 1}), + ) + .await; + if tokens + .as_ref() + .and_then(|v| v.as_array()) + .is_some_and(|a| !a.is_empty()) + { + return true; + } + self.intents_view("public_keys_of", json!({"account_id": account})) + .await + .as_ref() + .and_then(|v| v.as_array()) + .is_some_and(|a| !a.is_empty()) + } +} diff --git a/crates/blackbeard-data/src/store.rs b/crates/blackbeard-data/src/store.rs index 849462e..cbc182e 100644 --- a/crates/blackbeard-data/src/store.rs +++ b/crates/blackbeard-data/src/store.rs @@ -4666,3 +4666,21 @@ impl Store { Ok(row.map(|r| (r.height.max(0) as u64, r.extrinsic_index.max(0) as u32))) } } + +impl Store { + /// A recorded block's height, by its hash (blackbeard/observer#49). + pub async fn block_height_by_hash( + &self, + chain: &ChainId, + hash: &str, + ) -> Result, DataError> { + let h = sqlx::query_scalar!( + "select height from block where chain = $1 and hash = $2 limit 1", + chain.as_str(), + hash, + ) + .fetch_optional(&self.pool) + .await?; + Ok(h.map(|h| h.max(0) as u64)) + } +} diff --git a/crates/blackbeard-entities/src/chain.rs b/crates/blackbeard-entities/src/chain.rs index c0efc79..111e4e1 100644 --- a/crates/blackbeard-entities/src/chain.rs +++ b/crates/blackbeard-entities/src/chain.rs @@ -829,3 +829,37 @@ pub struct DailyWormhole { #[ts(type = "number")] pub exits: u64, } + +/// One page a pasted string resolves to (blackbeard/observer#49). +#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[ts(export, export_to = "SearchHit.ts")] +pub struct SearchHit { + /// `block`, `tx`, `account`, `miner`, `node`, `runtime`, `near_tx` or + /// `intents_account`: the route the page lives at. + pub kind: String, + /// The route's value: a block hash or height, an SS58 address, a preimage, + /// a peer id, a spec version, a NEAR hash or account. + pub value: String, + /// What it is, in a line: "block #180,029". + pub label: String, + /// What confirmed it, or what is not yet known about it. + pub detail: Option, +} + +/// What a pasted string resolved to. +#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[ts(export, export_to = "SearchResults.ts")] +pub struct SearchResults { + /// Which chain was searched. + pub chain: ChainId, + /// The query, trimmed. + pub query: String, + /// Every page it resolves to, each confirmed against data rather than + /// guessed from its shape. More than one means the string really is + /// ambiguous, and the reader chooses. + pub hits: Vec, + /// What the string was checked as, for saying so when nothing matched. + pub checked: Vec, + /// Anything the reader should know about a miss: a backfill still running. + pub note: Option, +} diff --git a/crates/blackbeard-entities/src/lib.rs b/crates/blackbeard-entities/src/lib.rs index 3c07032..c317191 100644 --- a/crates/blackbeard-entities/src/lib.rs +++ b/crates/blackbeard-entities/src/lib.rs @@ -41,8 +41,8 @@ pub use call::{CallIndex, CallSummary, EventSummary}; pub use chain::{ AccountFlows, ChainId, ChainInfo, ChainStatus, ChainSummary, ClientVersion, Concentration, DailyActivity, DailyWormhole, Distribution, ExitCohort, LockCounts, MinerFlow, NetworkSummary, - PalletPot, Tracking, TransferRoute, VestingPoint, VestingSchedule, VestingSummary, - WormholeDeposit, WormholeDeposits, WormholeSummary, + PalletPot, SearchHit, SearchResults, Tracking, TransferRoute, VestingPoint, VestingSchedule, + VestingSummary, WormholeDeposit, WormholeDeposits, WormholeSummary, }; pub use error::{ApiError, EntityError}; pub use intents::{ diff --git a/web/src/App.tsx b/web/src/App.tsx index 1d20e52..b276053 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -28,6 +28,7 @@ import { WormholePanel } from './components/WormholePanel' import { IntentsAccountPanel } from './components/IntentsAccountPanel' import { NearTxPanel } from './components/NearTxPanel' import { NodeRoute } from './components/NodeRoute' +import { SearchBox } from './components/SearchBox' import { TxPanel } from './components/TxPanel' import { NodesIndex } from './components/NodesIndex' import { MarketPage } from './components/MarketPage' @@ -179,6 +180,10 @@ export default function App() { )} + {/* First in the row: the way in for someone holding a hash or an + address, rather than a link (#49). Searches the chain on view. */} + {chain && } + {/* Before the connection light and the toggle, as the last thing in the header that is about the site rather than about the chain. */} {chain && ( diff --git a/web/src/api/generated/SearchHit.ts b/web/src/api/generated/SearchHit.ts new file mode 100644 index 0000000..7325ed7 --- /dev/null +++ b/web/src/api/generated/SearchHit.ts @@ -0,0 +1,24 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * One page a pasted string resolves to (blackbeard/observer#49). + */ +export type SearchHit = { +/** + * `block`, `tx`, `account`, `miner`, `node`, `runtime`, `near_tx` or + * `intents_account`: the route the page lives at. + */ +kind: string, +/** + * The route's value: a block hash or height, an SS58 address, a preimage, + * a peer id, a spec version, a NEAR hash or account. + */ +value: string, +/** + * What it is, in a line: "block #180,029". + */ +label: string, +/** + * What confirmed it, or what is not yet known about it. + */ +detail: string | null, }; diff --git a/web/src/api/generated/SearchResults.ts b/web/src/api/generated/SearchResults.ts new file mode 100644 index 0000000..c9cdc6d --- /dev/null +++ b/web/src/api/generated/SearchResults.ts @@ -0,0 +1,30 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ChainId } from "./ChainId"; +import type { SearchHit } from "./SearchHit"; + +/** + * What a pasted string resolved to. + */ +export type SearchResults = { +/** + * Which chain was searched. + */ +chain: ChainId, +/** + * The query, trimmed. + */ +query: string, +/** + * Every page it resolves to, each confirmed against data rather than + * guessed from its shape. More than one means the string really is + * ambiguous, and the reader chooses. + */ +hits: Array, +/** + * What the string was checked as, for saying so when nothing matched. + */ +checked: Array, +/** + * Anything the reader should know about a miss: a backfill still running. + */ +note: string | null, }; diff --git a/web/src/api/rest.ts b/web/src/api/rest.ts index e906150..2188242 100644 --- a/web/src/api/rest.ts +++ b/web/src/api/rest.ts @@ -31,6 +31,7 @@ import type { IntentsSwaps } from './generated/IntentsSwaps' import type { IntentsAccount } from './generated/IntentsAccount' import type { Markets } from './generated/Markets' import type { NearTx } from './generated/NearTx' +import type { SearchResults } from './generated/SearchResults' import type { TxDetail } from './generated/TxDetail' import type { QuoteProbes } from './generated/QuoteProbes' import type { RefPools } from './generated/RefPools' @@ -478,3 +479,15 @@ export async function fetchTx( signal, ) } + +/** Every page a pasted string resolves to (blackbeard/observer#49). */ +export async function fetchSearch( + chain: string, + q: string, + signal?: AbortSignal, +): Promise { + return get( + `/chains/${encodeURIComponent(chain)}/search?q=${encodeURIComponent(q)}`, + signal, + ) +} diff --git a/web/src/components/SearchBox.tsx b/web/src/components/SearchBox.tsx new file mode 100644 index 0000000..7219a16 --- /dev/null +++ b/web/src/components/SearchBox.tsx @@ -0,0 +1,200 @@ +/** + * Paste a hash, an address or an account and land on its page + * (blackbeard/observer#49). + * + * The site's pages were reachable only by following links. This is the front + * door for someone who arrives holding a transaction hash from a wallet or an + * address from a chat message. + * + * It searches on Enter, never while typing: every search costs lookups, one of + * them on the node, and half-typed hashes resolve to nothing. The server + * confirms each candidate against data rather than guessing from shape — one + * string can honestly be a block hash and a miner's preimage both — so: + * + * - **one hit** goes straight there; + * - **several** are listed for the reader to choose, never chosen for them; + * - **none** says what the string was checked as, so a miss reads as an answer + * and not as the site being broken. + */ + +import { useEffect, useRef, useState } from 'react' +import { useNavigate } from 'react-router-dom' + +import type { SearchHit } from '../api/generated/SearchHit' +import type { SearchResults } from '../api/generated/SearchResults' +import { RequestFailed, fetchSearch } from '../api/rest' +import { href } from '../lib/routes' + +/** Where a hit's page is. */ +function hitHref(chain: string, h: SearchHit): string { + switch (h.kind) { + case 'block': + return href({ chain, block: h.value }) + case 'tx': + return href({ chain, tx: h.value }) + case 'account': + return href({ chain, account: h.value }) + case 'miner': + return href({ chain, miner: h.value }) + case 'node': + return href({ chain, node: h.value }) + case 'runtime': + return href({ chain, runtime: Number(h.value) }) + case 'near_tx': + return href({ chain, nearTx: h.value }) + case 'intents_account': + return href({ chain, intentsAccount: h.value }) + default: + return href({ chain }) + } +} + +export function SearchBox({ chain }: { chain: string }) { + const navigate = useNavigate() + const [text, setText] = useState('') + const [busy, setBusy] = useState(false) + const [results, setResults] = useState(null) + const [error, setError] = useState(null) + const [active, setActive] = useState(0) + const box = useRef(null) + const pending = useRef(null) + + const close = () => { + setResults(null) + setError(null) + } + + // A click anywhere else closes the list, as a menu would. + useEffect(() => { + if (!results && !error) return + const outside = (e: MouseEvent) => { + if (box.current && !box.current.contains(e.target as Node)) close() + } + document.addEventListener('mousedown', outside) + return () => document.removeEventListener('mousedown', outside) + }, [results, error]) + + const go = (h: SearchHit) => { + navigate(hitHref(chain, h)) + setText('') + close() + } + + const search = () => { + const q = text.trim() + if (!q) return + pending.current?.abort() + const controller = new AbortController() + pending.current = controller + setBusy(true) + setError(null) + fetchSearch(chain, q, controller.signal) + .then((r) => { + if (r.hits.length === 1 && r.hits[0]) { + go(r.hits[0]) + return + } + setResults(r) + setActive(0) + }) + .catch((e: unknown) => { + if (controller.signal.aborted) return + setResults(null) + setError(e instanceof RequestFailed ? e.message : 'Could not reach the observer.') + }) + .finally(() => setBusy(false)) + } + + const onKey = (e: React.KeyboardEvent) => { + const hits = results?.hits ?? [] + if (e.key === 'Escape') { + if (results || error) close() + else setText('') + return + } + if (e.key === 'ArrowDown' && hits.length > 0) { + e.preventDefault() + setActive((a) => (a + 1) % hits.length) + return + } + if (e.key === 'ArrowUp' && hits.length > 0) { + e.preventDefault() + setActive((a) => (a - 1 + hits.length) % hits.length) + return + } + if (e.key === 'Enter') { + e.preventDefault() + const chosen = hits[active] + // Enter on an open list picks the highlighted hit; otherwise it searches. + if (results && hits.length > 1 && chosen) go(chosen) + else search() + } + } + + const listId = 'search-results' + const open = results !== null || error !== null + + return ( +
+ { + setText(e.target.value) + if (open) close() + }} + onKeyDown={onKey} + aria-expanded={open} + aria-controls={listId} + aria-busy={busy} + role="combobox" + aria-autocomplete="none" + aria-activedescendant={ + results && results.hits.length > 1 ? `${listId}-${active}` : undefined + } + spellCheck={false} + autoComplete="off" + /> + {open && ( +
+ {error &&

{error}

} + {results && results.hits.length > 1 && ( + <> +

This could be any of these:

+
    + {results.hits.map((h, i) => ( +
  • setActive(i)} + onMouseDown={(e) => { + // Before the input blurs, so the click lands. + e.preventDefault() + go(h) + }} + > + {h.label} + {h.detail && {h.detail}} +
  • + ))} +
+ + )} + {results && results.hits.length === 0 && ( +

+ Nothing found + {results.checked.length > 0 && <> — checked as {results.checked.join(', ')}}. + {results.note && {results.note}.} +

+ )} +
+ )} +
+ ) +} diff --git a/web/src/index.css b/web/src/index.css index 8621063..40011a4 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -296,6 +296,10 @@ a { align-items: center; gap: 16px; flex-wrap: wrap; + /* The free width beside the mark, right-aligned: sized to its content it + wrapped the light and the toggle under the search box (#49). */ + flex: 1 1 auto; + justify-content: flex-end; } /* ---- node panel ---------------------------------------------------------- */ @@ -2200,3 +2204,81 @@ tr.mine .share-bar > i { .row-target td { background: var(--data-wash); } + +/* The search box (blackbeard/observer#49). In the masthead row, where it + wraps onto its own line on a phone rather than squeezing the input. */ +.search { + position: relative; + /* A fixed basis and no grow: the row is only as wide as its content, so a + growing box claims the space the light and the toggle need and pushes them + onto a second line. */ + flex: 0 1 300px; + min-width: 0; +} + +.search-input { + width: 100%; + box-sizing: border-box; + padding: 6px 10px; + font: inherit; + font-size: 12px; + color: var(--text-primary); + background: var(--surface-1); + border: 1px solid var(--border); + border-radius: 2px; +} + +.search-input:focus { + outline: none; + border-color: var(--border-strong); +} + +.search-results { + position: absolute; + z-index: 20; + top: calc(100% + 4px); + left: 0; + right: 0; + min-width: 280px; + background: var(--surface-1); + border: 1px solid var(--border-strong); + box-shadow: var(--shadow); + font-size: 12px; +} + +.search-results ul { + list-style: none; + margin: 0; + padding: 4px 0; +} + +.search-results li { + display: flex; + flex-direction: column; + gap: 2px; + padding: 7px 12px; + cursor: pointer; +} + +.search-results li.is-active { + background: var(--surface-2); +} + +.search-head, +.search-empty { + margin: 0; + padding: 8px 12px; + color: var(--text-secondary); +} + +.search-detail { + color: var(--text-muted); + font-size: 11px; +} + +@media (max-width: 720px) { + .search { + flex: 1 1 100%; + order: 10; + } +}