Search parameters
A route's second type parameter types its query string, and a statement or an action can change the URL in the address bar without loading a page.
A typed query string
A route's second type, Route<P, Q>, types its query string. Q is a struct with #[derive(Signals, Search)], which implements Search. link_with, url, and the handler then take (P, Q), or Q alone for a path without parameters. A field can come from a signal, so a link to the next page of results reads the page the visitor is on.
use hypersig::{Expr, PathSegment, Route, Search, Signals};
#[derive(Signals, Search, Serialize, Deserialize)]
struct Filter {
q: String,
page: i32,
tag: Option<String>,
}
hypersig::routes! {
fn pages(Router<()>);
// `team` receives `(PathSegment, Filter)`.
const TEAM: Route<PathSegment, Filter> = "/teams/{team}" => team;
}
let first = Filter { q: "rust".to_owned(), page: 1, tag: None };
const RED: PathSegment = PathSegment::new("red");
let link = a::<Filter>().href(TEAM.link_with((RED, &first)));
assert_eq!(link.render(), r#"<a href="/teams/red?page=1&q=rust"></a>"#);
// A field can come from a signal, here the page the reader is on.
let next = Expr::lit(&first).with(Filter::page(), Filter::page() + 1);
let _ = a().href(TEAM.link_with((RED, next)));How the fields are written
#[derive(Search)] requires each field's type to be a SearchValue: a SearchScalar, or an Option or a Vec of one. The query string lists the fields in the order of their names, compared byte by byte, on the server and in the browser alike, and percent-encodes each name and value as encodeURIComponent does.
| Field type | Written as |
|---|---|
String, f64, f32, bool, i32, i64, u32, u64, PathSegment, an enum with #[derive(Segment)] | name=value, the value written as JavaScript's String writes it |
Option<T> | name=value, or nothing for None |
Vec<T> | name=a&name=b, once per item in item order, or nothing when empty |
- An
i64oru64past 2^53 is written with its exact digits, so the handler receives it exactly. Stringwrites-0.0as0, so anf64of-0.0arrives as0.0. serde writes a NaN or an infinity asnull, so its field is left out, and a required field then gets a 400 where anOptionarrives asNone.- The server compares names by their UTF-8 bytes and the browser by their UTF-16 units, which agree for ASCII names. A
#[serde(rename)]to a name outside ASCII can put two fields in a different order on the two sides.
How the server reads them
The server reads the query string back into Q before the handler runs. A key that appears more than once fills a Vec field, + reads as a space, and a key the struct does not have is ignored. A query string that does not deserialize into Q gets a 400: a missing field that is not an Option or a Vec, a repeated key for a field that is not a Vec, or a value the field's Deserialize rejects. Without an else handler, the body of that 400 is the text "the query string does not deserialize into the page's search parameters".
So a field whose type checks its value in Deserialize, such as a newtype with #[serde(try_from = "i32")], validates the query string, and an Option field with unwrap_or or map_or in the handler gives a default. A newtype that serde writes as one value becomes a SearchScalar with impl SearchScalar for PageNumber {}:
use hypersig::{Route, Search, SearchScalar, Segment, Signals};
use serde::{Deserialize, Serialize};
#[derive(Segment, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "lowercase")]
enum Color {
Red,
Blue,
}
// A page number of 1 or more. Reading the query string checks it.
#[derive(Serialize, Deserialize, Clone, Copy)]
#[serde(try_from = "i32", into = "i32")]
struct PageNumber(i32);
impl TryFrom<i32> for PageNumber {
type Error = &'static str;
fn try_from(number: i32) -> Result<Self, Self::Error> {
if number >= 1 { Ok(Self(number)) } else { Err("a page number starts at 1") }
}
}
impl From<PageNumber> for i32 {
fn from(number: PageNumber) -> Self {
number.0
}
}
// serde writes `PageNumber` as an `i32`, so one value of the query string holds it.
impl SearchScalar for PageNumber {}
#[derive(Signals, Search, Serialize, Deserialize)]
struct Filter {
q: String,
page: Option<PageNumber>,
color: Vec<Color>,
}
hypersig::routes! {
fn pages(Router<()>);
const SHOP: Route<(), Filter> = "/shop" => shop;
}
// `/shop?q=tea` reaches the handler with `page: None`, and `/shop?page=0` gets a 400.
async fn shop((): (), filter: Filter) -> Page<Shop> {
let page = filter.page.map_or(1, i32::from);
Page::new("Shop", Shop { page })
}
let filter = Filter {
q: "green tea".to_owned(),
page: None,
color: vec![Color::Red, Color::Blue],
};
assert_eq!(SHOP.url(filter).as_str(), "/shop?color=red&color=blue&q=green%20tea");What the compiler checks
A query string holds text values under each key, so a struct in a field, a list of lists, and an Option of a list are compile errors:
use hypersig::{Search, Signals};
#[derive(Signals, Serialize, Deserialize)]
struct Range {
min: i32,
max: i32,
}
// error[E0277]: `Range` cannot be a field of search parameters
#[derive(Signals, Search, Serialize, Deserialize)]
struct Filter {
price: Range,
}The compiler does not check an impl SearchScalar of your own. A type that serde writes as a list or an object gives links whose query string the server answers with 400.
Changing the URL without loading a page
A list whose filter, sort, and page live in the query string can keep the page loaded while they change. Link::push_url(self) -> Stmt<S> is a statement that shows the link's URL in the address bar as a new history entry. Link::replace_url(self) -> Stmt<S> shows it in place of the current one, for a change the Back button should skip, such as each letter typed into a search field. A URL equal to the current one adds no entry.
The page keeps its signals, its focus, and its scroll position, so the statement runs beside the call that loads the rows. An action does the same with Patches::push_url(url: Url) and Patches::replace_url(url: Url). Unlike navigate, the patches after them are applied. When the visitor presses Back or Forward, the browser loads the page at that entry's URL from the server, which renders it from the query string.
use hypersig::{Action, Expr, Page, Patches, Route, Search, Signals};
// `/fruit` without a query string leaves `q` as `None`.
#[derive(Signals, Search, Serialize, Deserialize, Default)]
struct Filter {
q: Option<String>,
}
#[derive(Signals, Serialize, Deserialize)]
struct Fruit {
query: String,
matches: Vec<String>,
}
hypersig::routes! {
fn pages(Router<()>);
const FRUIT: Route<(), Filter> = "/fruit" => fruit;
action SEARCH: Action<Fruit, String> = post "/search" => search;
action CLEAR: Action<Fruit> = post "/clear" => clear;
}
fn find(q: &str) -> Vec<String> {
["apple", "fig", "kiwi"].into_iter().filter(|name| name.contains(q)).map(String::from).collect()
}
// The page renders what the query string names, so Back and Forward load it again.
async fn fruit((): (), filter: Filter) -> Page<Fruit> {
let q = filter.q.unwrap_or_default();
let matches = find(&q);
let query = Fruit::query();
let shown = Expr::lit(&Filter::default()).with(Filter::q(), query.some());
Page::new("Fruit", Fruit { query: q, matches }).child(
input().bind(query).on_debounced(
Event::Input,
Duration::from_millis(250),
// Each pause in typing replaces the URL rather than adding an entry.
SEARCH.call_with(query).then(FRUIT.link_with(shown).replace_url()),
),
)
}
// An action changes the URL too, here as a new entry after emptying the search.
async fn clear((): (), (): ()) -> Patches<Fruit> {
let empty = Fruit::query().patch(String::new()).and(Fruit::matches().patch(find("")));
Patches::from(empty).push_url(FRUIT.url(Filter::default()))
}Nothing checks that the URL push_url or replace_url shows belongs to the page on screen. The URL of another page shows over this page's content, and reloading it loads the other page.
Next
- Error pages shows a page of your own with the 400 for a query string that does not deserialize.
- Links and redirects covers
navigate, which loads the next page.