Compare commits

..

31 Commits

Author SHA1 Message Date
e8c58bdbd0 server: handle multipart/mixed with an html or text subpart 2023-11-26 21:09:56 -08:00
87d687cde5 server: sanitize html using ammonia 2023-11-26 21:00:44 -08:00
c8147ded60 web & server: add handling for google calendar and wellsfargo emails. 2023-11-26 20:51:53 -08:00
1261bdf8a9 web & server: improved debug printing of unhandled mime types 2023-11-26 18:50:32 -08:00
11366b6fac web & server: implement handling for text and html bodies. 2023-11-26 16:37:29 -08:00
1cdabc348b web: better date formatting 2023-11-26 16:01:22 -08:00
02e16b4547 web: more compact output on desktop and mobile 2023-11-26 15:46:03 -08:00
d5a001bf03 web: refresh tags on thread view in addition to search results. 2023-11-26 15:31:51 -08:00
0ae72b63d0 web: add basic graphql view thread, no body support. 2023-11-26 15:27:19 -08:00
447a4a3387 server: basic graphql thread show, no body support yet. 2023-11-26 13:13:04 -08:00
0737f5aac5 web: rewrite frontend to use graphql for search results 2023-11-25 09:06:24 -08:00
3e3024dd5c server: handle search with no first/last better 2023-11-25 09:05:53 -08:00
24414b04bb server: fix backward pagination 2023-11-25 08:39:56 -08:00
f7df834325 notmuch: default empty search to wildcard 2023-11-25 08:39:30 -08:00
bce2c741c4 web: add non-functional graphql. 2023-11-21 14:06:48 -08:00
1b44bc57bb web: Initial commit of graphql schema and helper to update it. 2023-11-21 13:36:11 -08:00
ff6675b08f server: add unread field to tag query.
Optionally fill out unread, as it's expensive.
2023-11-21 13:17:11 -08:00
64912be4eb Hide quoted emails 2023-11-21 12:37:58 -08:00
57ccef18cb Make clicking search results on mobile easier. 2023-11-21 12:27:58 -08:00
2a24a20529 Revert stub show_pretty that will be obsoleted by graphql. 2023-11-21 08:35:35 -08:00
e6692059b4 Fix search pagination and add count RPC. 2023-11-20 21:18:40 -08:00
a7b172099b And graphql search with pagination. 2023-11-20 20:56:16 -08:00
f52a76dba3 Added graphql endpoint and tested with tags implementation. 2023-11-20 18:38:10 -08:00
43e4334890 Set default page size on server to match client side page size. 2023-11-20 17:57:07 -08:00
1d00bdb757 Squelch logging and remove unused variable. 2023-11-20 17:54:50 -08:00
6901c9fde9 Formate today and yesterday better. 2023-11-20 17:53:49 -08:00
6251c54873 Show time of email >1 week 2023-11-20 17:47:06 -08:00
f6c1835b18 Custom formatting of the age string, widen subject column. 2023-11-20 17:41:58 -08:00
95976c2860 Mobile style tweaks. 2023-11-20 15:49:30 -08:00
01589d7136 Add favicon 2023-11-20 15:40:07 -08:00
a2664473c8 Improve density on mobile. 2023-11-14 21:33:09 -08:00
20 changed files with 3694 additions and 295 deletions

730
Cargo.lock generated

File diff suppressed because it is too large Load Diff

2
dev.sh
View File

@@ -3,5 +3,5 @@ tmux new-session -d -s letterbox-dev
tmux rename-window web
tmux send-keys "cd web; trunk serve -w ../shared -w ../notmuch -w ./" C-m
tmux new-window -n server
tmux send-keys "cd server; cargo watch -x run -w ../shared -w ../notmuch -w ./" C-m
tmux send-keys "cd server; cargo watch -c -x run -w ../shared -w ../notmuch -w ./" C-m
tmux attach -d -t letterbox-dev

View File

@@ -6,8 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.75"
clap = { version = "4.4.7", features = ["derive"] }
log = "0.4.14"
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["unbounded_depth"] }

View File

@@ -480,12 +480,19 @@ impl Notmuch {
self.run_notmuch(std::iter::empty::<&str>())
}
pub fn tags(&self) -> Result<Vec<String>, NotmuchError> {
let res = self.run_notmuch(["search", "--format=json", "--output=tags", "*"])?;
Ok(serde_json::from_slice(&res)?)
}
pub fn search(
&self,
query: &str,
offset: usize,
limit: usize,
) -> Result<SearchSummary, NotmuchError> {
let query = if query.is_empty() { "*" } else { query };
let res = self.run_notmuch([
"search",
"--format=json",
@@ -554,7 +561,10 @@ impl Notmuch {
Ok(BufReader::new(child.stdout.take().unwrap()).lines())
}
// TODO(wathiede): implement tags() based on "notmuch search --output=tags '*'"
pub fn files(&self, query: &str) -> Result<Lines<BufReader<ChildStdout>>, NotmuchError> {
let mut child = self.run_notmuch_pipe(["search", "--output=files", query])?;
Ok(BufReader::new(child.stdout.take().unwrap()).lines())
}
fn run_notmuch<I, S>(&self, args: I) -> Result<Vec<u8>, NotmuchError>
where

View File

@@ -1,46 +0,0 @@
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use notmuch::Notmuch;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
/// Optional notmuch config file
#[arg(short, long)]
config: Option<PathBuf>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Show given search term
Show { search_term: String },
/// Search for given search term
Search { search_term: String },
}
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
let nm = if let Some(config_path) = cli.config {
Notmuch::with_config(config_path)
} else {
Notmuch::default()
};
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level cmd
match &cli.command {
Commands::Search { search_term } => {
println!("{:#?}", nm.search(&search_term, 0, 10)?);
}
Commands::Show { search_term } => {
println!("{:#?}", nm.show(&search_term)?);
}
}
Ok(())
}

View File

@@ -8,7 +8,6 @@ default-bin = "server"
[dependencies]
rocket = { version = "0.5.0-rc.2", features = [ "json" ] }
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
notmuch = { path = "../notmuch" }
shared = { path = "../shared" }
serde_json = "1.0.87"
@@ -18,6 +17,13 @@ log = "0.4.17"
tokio = "1.26.0"
glog = "0.1.0"
urlencoding = "2.1.3"
async-graphql = { version = "6.0.11", features = ["log"] }
async-graphql-rocket = "6.0.11"
rocket_cors = "0.6.0"
rayon = "1.8.0"
memmap = "0.7.0"
mailparse = "0.14.0"
ammonia = "3.3.0"
[dependencies.rocket_contrib]
version = "0.4.11"

View File

@@ -1,26 +1,25 @@
#[macro_use]
extern crate rocket;
use std::{error::Error, io::Cursor, str::FromStr};
use async_graphql::{http::GraphiQLSource, EmptyMutation, EmptySubscription, Schema};
use async_graphql_rocket::{GraphQLQuery, GraphQLRequest, GraphQLResponse};
use glog::Flags;
use notmuch::{Notmuch, NotmuchError, ThreadSet};
use rocket::{
http::{ContentType, Header},
request::Request,
response::{Debug, Responder},
response::{content, Debug, Responder},
serde::json::Json,
Response, State,
};
use rocket_cors::{AllowedHeaders, AllowedOrigins};
use server::{error::ServerError, nm::threadset_to_messages};
use server::{
error::ServerError,
graphql::{GraphqlSchema, QueryRoot},
};
use shared::Message;
#[get("/")]
fn hello() -> &'static str {
"Hello, world!"
}
#[get("/refresh")]
async fn refresh(nm: &State<Notmuch>) -> Result<Json<String>, Debug<NotmuchError>> {
Ok(Json(String::from_utf8_lossy(&nm.new()?).to_string()))
@@ -41,7 +40,7 @@ async fn search(
results_per_page: Option<usize>,
) -> Result<Json<shared::SearchResult>, Debug<NotmuchError>> {
let page = page.unwrap_or(0);
let results_per_page = results_per_page.unwrap_or(10);
let results_per_page = results_per_page.unwrap_or(20);
let query = urlencoding::decode(query).map_err(NotmuchError::from)?;
info!(" search '{query}'");
let res = shared::SearchResult {
@@ -58,9 +57,9 @@ async fn search(
async fn show_pretty(
nm: &State<Notmuch>,
query: &str,
) -> Result<Json<Vec<Message>>, Debug<ServerError>> {
) -> Result<Json<ThreadSet>, Debug<ServerError>> {
let query = urlencoding::decode(query).map_err(|e| ServerError::from(NotmuchError::from(e)))?;
let res = threadset_to_messages(nm.show(&query).map_err(ServerError::from)?)?;
let res = nm.show(&query).map_err(ServerError::from)?;
Ok(Json(res))
}
@@ -125,6 +124,24 @@ async fn original(
Ok((ContentType::Plain, res))
}
#[rocket::get("/")]
fn graphiql() -> content::RawHtml<String> {
content::RawHtml(GraphiQLSource::build().endpoint("/graphql").finish())
}
#[rocket::get("/graphql?<query..>")]
async fn graphql_query(schema: &State<GraphqlSchema>, query: GraphQLQuery) -> GraphQLResponse {
query.execute(schema.inner()).await
}
#[rocket::post("/graphql", data = "<request>", format = "application/json")]
async fn graphql_request(
schema: &State<GraphqlSchema>,
request: GraphQLRequest,
) -> GraphQLResponse {
request.execute(schema.inner()).await
}
#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
glog::new()
@@ -148,21 +165,29 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
.to_cors()?;
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.data(Notmuch::default())
.extension(async_graphql::extensions::Logger)
.finish();
let _ = rocket::build()
.mount(
"/",
routes![
original_part,
original,
hello,
refresh,
search_all,
search,
show_pretty,
show
show,
graphql_query,
graphql_request,
graphiql
],
)
.attach(cors)
.manage(schema)
.manage(Notmuch::default())
//.manage(Notmuch::with_config("../notmuch/testdata/notmuch.config"))
.launch()

423
server/src/graphql.rs Normal file
View File

@@ -0,0 +1,423 @@
use std::{
fs::File,
hash::{DefaultHasher, Hash, Hasher},
};
use async_graphql::{
connection::{self, Connection, Edge},
Context, EmptyMutation, EmptySubscription, Error, FieldResult, Object, Schema, SimpleObject,
Union,
};
use log::{error, info, warn};
use mailparse::{parse_mail, MailHeaderMap, ParsedMail};
use memmap::MmapOptions;
use notmuch::Notmuch;
use rayon::prelude::*;
pub struct QueryRoot;
/// # Number of seconds since the Epoch
pub type UnixTime = isize;
/// # Thread ID, sans "thread:"
pub type ThreadId = String;
#[derive(Debug, SimpleObject)]
pub struct ThreadSummary {
pub thread: ThreadId,
pub timestamp: UnixTime,
/// user-friendly timestamp
pub date_relative: String,
/// number of matched messages
pub matched: isize,
/// total messages in thread
pub total: isize,
/// comma-separated names with | between matched and unmatched
pub authors: String,
pub subject: String,
pub tags: Vec<String>,
}
#[derive(Debug, SimpleObject)]
pub struct Thread {
subject: String,
messages: Vec<Message>,
}
#[derive(Debug, SimpleObject)]
pub struct Message {
// First From header found in email
pub from: Option<Email>,
// All To headers found in email
pub to: Vec<Email>,
// All CC headers found in email
pub cc: Vec<Email>,
// First Subject header found in email
pub subject: Option<String>,
// Parsed Date header, if found and valid
pub timestamp: Option<i64>,
// The body contents
pub body: Body,
// On disk location of message
pub path: String,
}
#[derive(Debug)]
struct UnhandledContentType {
text: String,
}
#[Object]
impl UnhandledContentType {
async fn contents(&self) -> &str {
&self.text
}
}
#[derive(Debug)]
struct PlainText {
text: String,
}
#[Object]
impl PlainText {
async fn contents(&self) -> &str {
&self.text
}
}
#[derive(Debug)]
struct Html {
html: String,
}
#[Object]
impl Html {
async fn contents(&self) -> &str {
&self.html
}
}
#[derive(Debug, Union)]
pub enum Body {
UnhandledContentType(UnhandledContentType),
PlainText(PlainText),
Html(Html),
}
#[derive(Debug, SimpleObject)]
pub struct Email {
pub name: Option<String>,
pub addr: Option<String>,
}
#[derive(SimpleObject)]
struct Tag {
name: String,
fg_color: String,
bg_color: String,
unread: usize,
}
#[Object]
impl QueryRoot {
async fn count<'ctx>(&self, ctx: &Context<'ctx>, query: String) -> Result<usize, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
Ok(nm.count(&query)?)
}
async fn search<'ctx>(
&self,
ctx: &Context<'ctx>,
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
query: String,
) -> Result<Connection<usize, ThreadSummary>, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
connection::query(
after,
before,
first,
last,
|after, before, first, last| async move {
info!("{after:?} {before:?} {first:?} {last:?} {query}");
let total = nm.count(&query)?;
let (first, last) = if let (None, None) = (first, last) {
info!("neither first nor last set, defaulting to 20");
(Some(20), Some(20))
} else {
(first, last)
};
let mut start = after.map(|after| after + 1).unwrap_or(0);
let mut end = before.unwrap_or(total);
if let Some(first) = first {
end = (start + first).min(end);
}
if let Some(last) = last {
start = if last > end - start { end } else { end - last };
}
let count = end - start;
let slice: Vec<ThreadSummary> = nm
.search(&query, start, count)?
.0
.into_iter()
.map(|ts| ThreadSummary {
thread: ts.thread,
timestamp: ts.timestamp,
date_relative: ts.date_relative,
matched: ts.matched,
total: ts.total,
authors: ts.authors,
subject: ts.subject,
tags: ts.tags,
})
.collect();
let mut connection = Connection::new(start > 0, end < total);
connection.edges.extend(
slice
.into_iter()
.enumerate()
.map(|(idx, item)| Edge::new(start + idx, item)),
);
Ok::<_, Error>(connection)
},
)
.await
}
async fn tags<'ctx>(&self, ctx: &Context<'ctx>) -> FieldResult<Vec<Tag>> {
let nm = ctx.data_unchecked::<Notmuch>();
Ok(nm
.tags()?
.into_par_iter()
.map(|tag| {
let mut hasher = DefaultHasher::new();
tag.hash(&mut hasher);
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
let unread = if ctx.look_ahead().field("unread").exists() {
nm.count(&format!("tag:{tag} is:unread")).unwrap_or(0)
} else {
0
};
Tag {
name: tag,
fg_color: "white".to_string(),
bg_color: hex,
unread,
}
})
.collect())
}
async fn thread<'ctx>(&self, ctx: &Context<'ctx>, thread_id: String) -> Result<Thread, Error> {
// TODO(wathiede): normalize all email addresses through an address book with preferred
// display names (that default to the most commonly seen name).
let nm = ctx.data_unchecked::<Notmuch>();
let mut messages = Vec::new();
for path in nm.files(&thread_id)? {
let path = path?;
let file = File::open(&path)?;
let mmap = unsafe { MmapOptions::new().map(&file)? };
let m = parse_mail(&mmap)?;
let from = email_addresses(&path, &m, "from")?;
let from = match from.len() {
0 => None,
1 => from.into_iter().next(),
_ => {
warn!(
"Got {} from addresses in message, truncating: {:?}",
from.len(),
from
);
from.into_iter().next()
}
};
let to = email_addresses(&path, &m, "to")?;
let cc = email_addresses(&path, &m, "cc")?;
let subject = m.headers.get_first_value("subject");
let timestamp = m
.headers
.get_first_value("date")
.and_then(|d| mailparse::dateparse(&d).ok());
let body = match extract_body(&m)? {
Body::Html(Html { html }) => Body::Html(Html {
html: ammonia::clean(&html),
}),
b => b,
};
messages.push(Message {
from,
to,
cc,
subject,
timestamp,
body,
path,
});
}
messages.reverse();
// Find the first subject that's set. After reversing the vec, this should be the oldest
// message.
let subject: String = messages
.iter()
.skip_while(|m| m.subject.is_none())
.next()
.and_then(|m| m.subject.clone())
.unwrap_or("(NO SUBJECT)".to_string());
Ok(Thread { subject, messages })
}
}
fn extract_body(m: &ParsedMail) -> Result<Body, Error> {
let body = m.get_body()?;
let ret = match m.ctype.mimetype.as_str() {
"text/plain" => return Ok(Body::PlainText(PlainText { text: body })),
"text/html" => return Ok(Body::Html(Html { html: body })),
"multipart/mixed" => extract_mixed(m),
"multipart/alternative" => extract_alternative(m),
_ => extract_unhandled(m),
};
if let Err(err) = ret {
error!("Failed to extract body: {err:?}");
return Ok(extract_unhandled(m)?);
}
ret
}
fn extract_unhandled(m: &ParsedMail) -> Result<Body, Error> {
let msg = format!(
"Unhandled body content type:\n{}",
render_content_type_tree(m)
);
warn!("{}", msg);
Ok(Body::UnhandledContentType(UnhandledContentType {
text: msg,
}))
}
fn extract_alternative(m: &ParsedMail) -> Result<Body, Error> {
for sp in &m.subparts {
if sp.ctype.mimetype == "text/html" {
let body = sp.get_body()?;
return Ok(Body::Html(Html { html: body }));
}
}
for sp in &m.subparts {
if sp.ctype.mimetype == "text/plain" {
let body = sp.get_body()?;
return Ok(Body::PlainText(PlainText { text: body }));
}
}
Err("extract_alternative".into())
}
fn extract_mixed(m: &ParsedMail) -> Result<Body, Error> {
for sp in &m.subparts {
if sp.ctype.mimetype == "multipart/alternative" {
return extract_alternative(sp);
}
}
for sp in &m.subparts {
if sp.ctype.mimetype == "multipart/related" {
return extract_related(sp);
}
}
for sp in &m.subparts {
let body = sp.get_body()?;
match sp.ctype.mimetype.as_str() {
"text/plain" => return Ok(Body::PlainText(PlainText { text: body })),
"text/html" => return Ok(Body::Html(Html { html: body })),
_ => (),
}
}
Err("extract_mixed".into())
}
fn extract_related(m: &ParsedMail) -> Result<Body, Error> {
// TODO(wathiede): collect related things and change return type to new Body arm.
for sp in &m.subparts {
if sp.ctype.mimetype == "text/html" {
let body = sp.get_body()?;
return Ok(Body::Html(Html { html: body }));
}
}
for sp in &m.subparts {
if sp.ctype.mimetype == "text/plain" {
let body = sp.get_body()?;
return Ok(Body::PlainText(PlainText { text: body }));
}
}
Err("extract_related".into())
}
fn render_content_type_tree(m: &ParsedMail) -> String {
const WIDTH: usize = 4;
fn render_rec(m: &ParsedMail, depth: usize) -> String {
let mut parts = Vec::new();
let msg = format!("{} {}", "-".repeat(depth * WIDTH), m.ctype.mimetype);
parts.push(msg);
if !m.ctype.charset.is_empty() {
parts.push(format!(
"{} Character Set: {}",
" ".repeat(depth * WIDTH),
m.ctype.charset
));
}
for (k, v) in m.ctype.params.iter() {
parts.push(format!("{} {k}: {v}", " ".repeat(depth * WIDTH),));
}
for sp in &m.subparts {
parts.push(render_rec(sp, depth + 1))
}
parts.join("\n")
}
render_rec(m, 1)
}
pub type GraphqlSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
fn email_addresses(path: &str, m: &ParsedMail, header_name: &str) -> Result<Vec<Email>, Error> {
let mut addrs = Vec::new();
for header_value in m.headers.get_all_values(header_name) {
match mailparse::addrparse(&header_value) {
Ok(mal) => {
for ma in mal.into_inner() {
match ma {
mailparse::MailAddr::Group(gi) => {
if !gi.group_name.contains("ndisclosed") {
println!("[{path}][{header_name}] Group: {gi}");
}
}
mailparse::MailAddr::Single(s) => addrs.push(Email {
name: s.display_name,
addr: Some(s.addr),
}), //println!("Single: {s}"),
}
}
}
Err(_) => {
let v = header_value;
if v.matches('@').count() == 1 {
if v.matches('<').count() == 1 && v.ends_with('>') {
let idx = v.find('<').unwrap();
let addr = &v[idx + 1..v.len() - 1].trim();
let name = &v[..idx].trim();
addrs.push(Email {
name: Some(name.to_string()),
addr: Some(addr.to_string()),
});
}
} else {
addrs.push(Email {
name: Some(v),
addr: None,
});
}
}
}
}
Ok(addrs)
}

View File

@@ -1,2 +1,3 @@
pub mod error;
pub mod graphql;
pub mod nm;

View File

@@ -7,9 +7,7 @@ pub fn threadset_to_messages(
thread_set: notmuch::ThreadSet,
) -> Result<Vec<Message>, error::ServerError> {
for t in thread_set.0 {
for tn in t.0 {
todo!()
}
for _tn in t.0 {}
}
Ok(Vec::new())
}

View File

@@ -9,5 +9,6 @@ pub struct SearchResult {
pub results_per_page: usize,
pub total: usize,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {}

View File

@@ -27,6 +27,9 @@ itertools = "0.10.5"
serde_json = { version = "1.0.93", features = ["unbounded_depth"] }
wasm-timer = "0.2.5"
css-inline = "0.8.5"
chrono = "0.4.31"
graphql_client = "0.13.0"
thiserror = "1.0.50"
[package.metadata.wasm-pack.profile.release]
wasm-opt = ['-Os']

View File

@@ -9,3 +9,7 @@ port = 6758
[[proxy]]
backend = "http://localhost:9345/"
rewrite= "/api/"
[[proxy]]
backend="http://localhost:9345/graphiql"
[[proxy]]
backend="http://localhost:9345/graphql"

View File

@@ -0,0 +1,23 @@
query FrontPageQuery($query: String!, $after: String $before: String, $first: Int, $last: Int) {
count(query: $query)
search(query: $query, after: $after, before: $before, first: $first, last: $last) {
pageInfo {
hasPreviousPage
hasNextPage
startCursor
endCursor
}
nodes {
thread
timestamp
subject
authors
tags
}
}
tags {
name
bgColor
fgColor
}
}

1854
web/graphql/schema.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
query ShowThreadQuery($threadId: String!) {
thread(threadId: $threadId) {
subject
messages {
subject
from {
name
addr
}
to {
name
addr
}
cc {
name
addr
}
timestamp
body {
__typename
... on UnhandledContentType {
contents
}
... on PlainText {
contents
}
... on Html {
contents
}
}
path
}
}
tags {
name
bgColor
fgColor
}
}

4
web/graphql/update_schema.sh Executable file
View File

@@ -0,0 +1,4 @@
DEV_HOST=localhost
DEV_PORT=9345
graphql-client introspect-schema http://${DEV_HOST:?}:${DEV_PORT:?}/graphql --output schema.json
git diff schema.json

View File

@@ -6,7 +6,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet", href="https://jenil.github.io/bulmaswatch/cyborg/bulmaswatch.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="icon" href="https://static.xinu.tv/favicon/letterbox.svg" />
<style>
.message {
padding: 0.5em;*/
}
@@ -37,7 +39,7 @@ iframe {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 15em;
width: 10em;
}
.index .subject {
overflow: hidden;
@@ -45,8 +47,9 @@ iframe {
white-space: nowrap;
}
.index .date {
width: 8em;
width: 10em;
white-space: nowrap;
text-align: right;
}
.footer {
background-color: #eee;
@@ -91,6 +94,58 @@ input, .input {
input::placeholder, .input::placeholder{
color: #555;
}
.mobile .search-results,
.mobile .thread {
padding: 1em;
}
.search-results .row {
border-bottom: 1px #444 solid;
padding-bottom: .5em;
padding-top: .5em;
}
.search-results .row .subject {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-results .row .from {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-results .row .tag {
height: 1.5em;
padding-left: .5em;
padding-right: .5em;
}
.float-right {
float: right;
}
/* Hide quoted emails */
/*
div[name="quote"],
blockquote[type="cite"],
.gmail_quote {
background-color: red;
display: none;
}
*/
.desktop-main-content {
display: grid;
grid-template-columns: 12rem 1fr;
}
.tags-menu {
padding: 1rem;
}
.tags-menu .menu-list a {
padding: 0.25em 0.5em;
}
.navbar {
border: none;
}
</style>
</head>

43
web/src/graphql.rs Normal file
View File

@@ -0,0 +1,43 @@
use graphql_client::GraphQLQuery;
use seed::{
fetch,
fetch::{Header, Method, Request},
};
use serde::{de::DeserializeOwned, Serialize};
// The paths are relative to the directory where your `Cargo.toml` is located.
// Both json and the GraphQL schema language are supported as sources for the schema
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/schema.json",
query_path = "graphql/front_page.graphql",
response_derives = "Debug"
)]
pub struct FrontPageQuery;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/schema.json",
query_path = "graphql/show_thread.graphql",
response_derives = "Debug"
)]
pub struct ShowThreadQuery;
pub async fn send_graphql<Body, Resp>(body: Body) -> fetch::Result<graphql_client::Response<Resp>>
where
Body: Serialize,
Resp: DeserializeOwned + 'static,
{
use web_sys::RequestMode;
Request::new("/graphql/")
.method(Method::Post)
.header(Header::content_type("application/json"))
.mode(RequestMode::Cors)
.json(&body)?
.fetch()
.await?
.check_status()?
.json()
.await
}

View File

@@ -7,14 +7,34 @@ use std::{
hash::{Hash, Hasher},
};
use chrono::{DateTime, Datelike, Duration, Local, Utc};
use graphql_client::GraphQLQuery;
use itertools::Itertools;
use log::{debug, error, info, Level};
use notmuch::{Content, Part, Thread, ThreadNode, ThreadSet};
use seed::{prelude::*, *};
use serde::de::Deserialize;
use thiserror::Error;
use wasm_timer::Instant;
use crate::graphql::{front_page_query::*, send_graphql, show_thread_query::*};
mod graphql;
const SEARCH_RESULTS_PER_PAGE: usize = 20;
const USE_GRAPHQL: bool = true;
#[derive(Error, Debug)]
enum UIError {
#[error("No error, this should never be presented to user")]
NoError,
#[error("failed to fetch {0}: {1:?}")]
FetchError(&'static str, FetchError),
#[error("{0} error decoding: {1:?}")]
FetchDecodeError(&'static str, Vec<graphql_client::Error>),
#[error("no data or errors for {0}")]
NoData(&'static str),
}
// ------ ------
// Init
@@ -33,6 +53,8 @@ fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
context: Context::None,
query: "".to_string(),
refreshing_state: RefreshingState::None,
ui_error: UIError::NoError,
tags: None,
}
}
@@ -45,32 +67,70 @@ fn on_url_changed(uc: subs::UrlChanged) -> Msg {
);
let hpp = url.remaining_hash_path_parts();
match hpp.as_slice() {
["t", tid] => Msg::ShowPrettyRequest(tid.to_string()),
["t", tid] => {
if USE_GRAPHQL {
Msg::ShowThreadRequest {
thread_id: tid.to_string(),
}
} else {
Msg::ShowPrettyRequest(tid.to_string())
}
}
["s", query] => {
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
Msg::SearchRequest {
query,
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
if USE_GRAPHQL {
Msg::FrontPageRequest {
query,
after: None,
before: None,
first: None,
last: None,
}
} else {
Msg::SearchRequest {
query,
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
}
}
}
["s", query, page] => {
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
let page = page[1..].parse().unwrap_or(0);
Msg::SearchRequest {
query,
page,
results_per_page: SEARCH_RESULTS_PER_PAGE,
if USE_GRAPHQL {
Msg::FrontPageRequest {
query,
after: Some(page.to_string()),
before: None,
first: None,
last: None,
}
} else {
Msg::SearchRequest {
query,
page,
results_per_page: SEARCH_RESULTS_PER_PAGE,
}
}
}
p => {
if !p.is_empty() {
info!("Unhandled path '{p:?}'");
}
Msg::SearchRequest {
query: "".to_string(),
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
if USE_GRAPHQL {
Msg::FrontPageRequest {
query: "".to_string(),
after: None,
before: None,
first: None,
last: None,
}
} else {
Msg::SearchRequest {
query: "".to_string(),
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
}
}
}
}
@@ -97,7 +157,14 @@ mod urls {
enum Context {
None,
Search(shared::SearchResult),
Thread(Vec<shared::Message>),
SearchResult {
query: String,
results: Vec<FrontPageQuerySearchNodes>,
count: usize,
pager: FrontPageQuerySearchPageInfo,
},
Thread(ThreadSet),
ThreadResult(ShowThreadQueryThread),
}
// `Model` describes our app state.
@@ -105,6 +172,14 @@ struct Model {
query: String,
context: Context,
refreshing_state: RefreshingState,
ui_error: UIError,
tags: Option<Vec<Tag>>,
}
struct Tag {
name: String,
bg_color: String,
fg_color: String,
}
#[derive(Debug, PartialEq)]
@@ -136,9 +211,26 @@ enum Msg {
ShowRequest(String),
ShowResult(fetch::Result<ThreadSet>),
ShowPrettyRequest(String),
ShowPrettyResult(fetch::Result<Vec<shared::Message>>),
ShowPrettyResult(fetch::Result<ThreadSet>),
NextPage,
PreviousPage,
FrontPageRequest {
query: String,
after: Option<String>,
before: Option<String>,
first: Option<i64>,
last: Option<i64>,
},
FrontPageResult(
fetch::Result<graphql_client::Response<graphql::front_page_query::ResponseData>>,
),
ShowThreadRequest {
thread_id: String,
},
ShowThreadResult(
fetch::Result<graphql_client::Response<graphql::show_thread_query::ResponseData>>,
),
}
// `update` describes how to handle each `Msg`.
@@ -185,10 +277,9 @@ fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
.skip()
.perform_cmd(async move { Msg::ShowResult(show_request(&tid).await) });
}
// TODO(wathiede): remove
Msg::ShowResult(Ok(response_data)) => {
debug!("fetch ok {:#?}", response_data);
//model.context = Context::Thread(response_data);
model.context = Context::Thread(response_data);
}
Msg::ShowResult(Err(fetch_error)) => {
error!("fetch failed {:?}", fetch_error);
@@ -200,7 +291,7 @@ fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
.perform_cmd(async move { Msg::ShowPrettyResult(show_pretty_request(&tid).await) });
}
Msg::ShowPrettyResult(Ok(response_data)) => {
info!("fetch ok {:#?}", response_data);
debug!("fetch ok {:#?}", response_data);
model.context = Context::Thread(response_data);
}
Msg::ShowPrettyResult(Err(fetch_error)) => {
@@ -211,8 +302,22 @@ fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
Context::Search(sr) => {
orders.request_url(urls::search(&sr.query, sr.page + 1));
}
Context::Thread(_) => (), // do nothing (yet?)
Context::None => (), // do nothing (yet?)
Context::SearchResult { query, pager, .. } => {
let query = query.to_string();
let after = pager.end_cursor.clone();
orders.perform_cmd(async move {
Msg::FrontPageRequest {
query,
after,
before: None,
first: Some(SEARCH_RESULTS_PER_PAGE as i64),
last: None,
}
});
}
Context::Thread(_) => (), // do nothing (yet?)
Context::ThreadResult(_) => (), // do nothing (yet?)
Context::None => (), // do nothing (yet?)
};
}
Msg::PreviousPage => {
@@ -220,10 +325,114 @@ fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
Context::Search(sr) => {
orders.request_url(urls::search(&sr.query, sr.page.saturating_sub(1)));
}
Context::Thread(_) => (), // do nothing (yet?)
Context::None => (), // do nothing (yet?)
Context::SearchResult { query, pager, .. } => {
let query = query.to_string();
let before = pager.start_cursor.clone();
orders.perform_cmd(async move {
Msg::FrontPageRequest {
query,
after: None,
before,
first: None,
last: Some(SEARCH_RESULTS_PER_PAGE as i64),
}
});
}
Context::Thread(_) => (), // do nothing (yet?)
Context::ThreadResult(_) => (), // do nothing (yet?)
Context::None => (), // do nothing (yet?)
};
}
Msg::FrontPageRequest {
query,
after,
before,
first,
last,
} => {
info!("making FrontPageRequest: {query} after:{after:?} before:{before:?} first:{first:?} last:{last:?}");
model.query = query.clone();
orders.skip().perform_cmd(async move {
Msg::FrontPageResult(
send_graphql(graphql::FrontPageQuery::build_query(
graphql::front_page_query::Variables {
query,
after,
before,
first,
last,
},
))
.await,
)
});
}
Msg::FrontPageResult(Err(e)) => error!("error FrontPageResult: {e:?}"),
Msg::FrontPageResult(Ok(graphql_client::Response {
data: None,
errors: None,
..
})) => {
error!("FrontPageResult no data or errors, should not happen");
}
Msg::FrontPageResult(Ok(graphql_client::Response {
data: None,
errors: Some(e),
..
})) => {
error!("FrontPageResult error: {e:?}");
}
Msg::FrontPageResult(Ok(graphql_client::Response {
data: Some(data), ..
})) => {
model.tags = Some(
data.tags
.into_iter()
.map(|t| Tag {
name: t.name,
bg_color: t.bg_color,
fg_color: t.fg_color,
})
.collect(),
);
model.context = Context::SearchResult {
query: model.query.clone(),
results: data.search.nodes,
count: data.count as usize,
pager: data.search.page_info,
};
}
Msg::ShowThreadRequest { thread_id } => {
orders.skip().perform_cmd(async move {
Msg::ShowThreadResult(
send_graphql(graphql::ShowThreadQuery::build_query(
graphql::show_thread_query::Variables { thread_id },
))
.await,
)
});
}
Msg::ShowThreadResult(Ok(graphql_client::Response {
data: Some(data), ..
})) => {
model.tags = Some(
data.tags
.into_iter()
.map(|t| Tag {
name: t.name,
bg_color: t.bg_color,
fg_color: t.fg_color,
})
.collect(),
);
model.context = Context::ThreadResult(data.thread);
}
Msg::ShowThreadResult(bad) => {
error!("show_thread_query error: {bad:?}");
}
}
}
@@ -289,7 +498,7 @@ async fn show_request(tid: &str) -> fetch::Result<ThreadSet> {
.map_err(|_| FetchError::JsonError(fetch::JsonError::Serde(JsValue::NULL)))?)
}
async fn show_pretty_request(tid: &str) -> fetch::Result<Vec<shared::Message>> {
async fn show_pretty_request(tid: &str) -> fetch::Result<ThreadSet> {
Request::new(api::show_pretty(tid))
.method(Method::Get)
.fetch()
@@ -482,7 +691,73 @@ fn pretty_authors(authors: &str) -> impl Iterator<Item = Node<Msg>> + '_ {
)
}
fn view_mobile_search_results(query: &str, search_results: &shared::SearchResult) -> Node<Msg> {
fn human_age(timestamp: i64) -> String {
let now = Local::now();
let yesterday = now - Duration::days(1);
let ts = DateTime::<Utc>::from_timestamp(timestamp, 0)
.unwrap()
.with_timezone(&Local);
let age = now - ts;
let datetime = if age < Duration::minutes(1) {
format!("{} min. ago", age.num_seconds())
} else if age < Duration::hours(1) {
format!("{} min. ago", age.num_minutes())
} else if ts.date_naive() == now.date_naive() {
ts.format("Today %H:%M").to_string()
} else if ts.date_naive() == yesterday.date_naive() {
ts.format("Yest. %H:%M").to_string()
} else if age < Duration::weeks(1) {
ts.format("%a %H:%M").to_string()
} else if ts.year() == now.year() {
ts.format("%b %d %H:%M").to_string()
} else {
ts.format("%b %d, %Y %H:%M").to_string()
};
datetime
}
fn view_mobile_search_results(
query: &str,
results: &[FrontPageQuerySearchNodes],
count: usize,
pager: &FrontPageQuerySearchPageInfo,
) -> Node<Msg> {
if query.is_empty() {
set_title("all mail");
} else {
set_title(query);
}
let rows = results.iter().map(|r| {
let tid = r.thread.clone();
let datetime = human_age(r.timestamp as i64);
a![
C!["has-text-light"],
attrs! {
At::Href => urls::thread(&tid)
},
div![
C!["row"],
div![C!["subject"], &r.subject],
span![C!["from", "is-size-7"], pretty_authors(&r.authors)],
div![
span![C!["is-size-7"], tags_chiclet(&r.tags, true)],
span![C!["is-size-7", "float-right", "date"], datetime]
]
]
]
});
div![
C!["search-results"],
view_search_pager(count, pager),
rows,
view_search_pager(count, pager),
]
}
fn view_mobile_search_results_legacy(
query: &str,
search_results: &shared::SearchResult,
) -> Node<Msg> {
if query.is_empty() {
set_title("all mail");
} else {
@@ -504,29 +779,94 @@ fn view_mobile_search_results(query: &str, search_results: &shared::SearchResult
]
*/
let tid = r.thread.clone();
div![
let datetime = human_age(r.timestamp as i64);
a![
C!["has-text-light"],
attrs! {
At::Href => urls::thread(&tid)
},
div![
C!["subject"],
&r.subject,
ev(Ev::Click, move |_| Msg::ShowPrettyRequest(tid)),
],
div![
span![C!["from"], pretty_authors(&r.authors)],
span![C!["tags"], tags_chiclet(&r.tags, true)],
],
span![C!["date"], &r.date_relative],
C!["row"],
div![C!["subject"], &r.subject],
span![C!["from", "is-size-7"], pretty_authors(&r.authors)],
div![
span![C!["is-size-7"], tags_chiclet(&r.tags, true)],
span![C!["is-size-7", "float-right", "date"], datetime]
]
]
]
});
let first = search_results.page * search_results.results_per_page;
div![
h1!["Search results"],
view_search_pager(first, summaries.len(), search_results.total),
C!["search-results"],
view_search_pager_legacy(first, summaries.len(), search_results.total),
rows,
view_search_pager(first, summaries.len(), search_results.total)
view_search_pager_legacy(first, summaries.len(), search_results.total)
]
}
fn view_search_results(query: &str, search_results: &shared::SearchResult) -> Node<Msg> {
fn view_search_results(
query: &str,
results: &[FrontPageQuerySearchNodes],
count: usize,
pager: &FrontPageQuerySearchPageInfo,
) -> Node<Msg> {
info!("pager {pager:?}");
if query.is_empty() {
set_title("all mail");
} else {
set_title(query);
}
let rows = results.iter().map(|r| {
let tid = r.thread.clone();
let datetime = human_age(r.timestamp as i64);
tr![
td![
C!["from"],
pretty_authors(&r.authors),
// TODO(wathiede): visualize message count if more than one message is in the
// thread
//IF!(r.total>1 => small![" ", r.total.to_string()]),
],
td![
C!["subject"],
tags_chiclet(&r.tags, false),
" ",
a![
C!["has-text-light"],
attrs! {
At::Href => urls::thread(&tid)
},
&r.subject,
]
],
td![C!["date"], datetime]
]
});
div![
view_search_pager(count, pager),
table![
C![
"table",
"index",
"is-fullwidth",
"is-hoverable",
"is-narrow",
"is-striped",
],
thead![tr![
th![C!["from"], "From"],
th![C!["subject"], "Subject"],
th![C!["date"], "Date"]
]],
tbody![rows]
],
view_search_pager(count, pager)
]
}
fn view_search_results_legacy(query: &str, search_results: &shared::SearchResult) -> Node<Msg> {
if query.is_empty() {
set_title("all mail");
} else {
@@ -535,6 +875,7 @@ fn view_search_results(query: &str, search_results: &shared::SearchResult) -> No
let summaries = &search_results.summary.0;
let rows = summaries.iter().map(|r| {
let tid = r.thread.clone();
let datetime = human_age(r.timestamp as i64);
tr![
td![
C!["from"],
@@ -553,12 +894,12 @@ fn view_search_results(query: &str, search_results: &shared::SearchResult) -> No
&r.subject,
]
],
td![C!["date"], &r.date_relative]
td![C!["date"], datetime]
]
});
let first = search_results.page * search_results.results_per_page;
div![
view_search_pager(first, summaries.len(), search_results.total),
view_search_pager_legacy(first, summaries.len(), search_results.total),
table![
C![
"table",
@@ -575,11 +916,51 @@ fn view_search_results(query: &str, search_results: &shared::SearchResult) -> No
]],
tbody![rows]
],
view_search_pager(first, summaries.len(), search_results.total)
view_search_pager_legacy(first, summaries.len(), search_results.total)
]
}
fn view_search_pager(start: usize, count: usize, total: usize) -> Node<Msg> {
fn view_search_pager(count: usize, pager: &FrontPageQuerySearchPageInfo) -> Node<Msg> {
let start = pager
.start_cursor
.as_ref()
.map(|i| i.parse().unwrap_or(0))
.unwrap_or(0);
nav![
C!["pagination"],
a![
C![
"pagination-previous",
"button",
//IF!(!pager.has_previous_page => "is-static"),
],
IF!(!pager.has_previous_page => attrs!{ At::Disabled=>true }),
"<",
IF!(pager.has_previous_page => ev(Ev::Click, |_| Msg::PreviousPage)),
],
a![
C![
"pagination-next",
"button",
//IF!(!pager.has_next_page => "is-static")
],
IF!(!pager.has_next_page => attrs!{ At::Disabled=>true }),
">",
IF!(pager.has_next_page => ev(Ev::Click, |_| Msg::NextPage))
],
ul![
C!["pagination-list"],
li![format!(
"{} - {} of {}",
start,
count.min(start + SEARCH_RESULTS_PER_PAGE),
count
)],
],
]
}
fn view_search_pager_legacy(start: usize, count: usize, total: usize) -> Node<Msg> {
let is_first = start <= 0;
let is_last = (start + SEARCH_RESULTS_PER_PAGE) >= total;
nav![
@@ -603,32 +984,135 @@ fn view_search_pager(start: usize, count: usize, total: usize) -> Node<Msg> {
]
}
fn view_thread(messages: &[shared::Message]) -> Node<Msg> {
div!["TODO(wathiede): view_thread(messages)"]
/*
assert_eq!(thread_set.0.len(), 1);
let thread = &thread_set.0[0];
assert_eq!(thread.0.len(), 1);
let thread_node = &thread.0[0];
let subject = first_subject(&thread_node).unwrap_or("<No subject>".to_string());
set_title(&subject);
div![
C!["container"],
h1![C!["title"], subject],
view_message(&thread_node),
a![
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
"Original"
],
/*
trait Email {
fn name(&self) -> &Option<String>;
fn addr(&self) -> &Option<String>;
}
impl<T: Email> Email for &'_ T {
fn name(&self) -> &Option<String> {
return (*self).name();
}
fn addr(&self) -> &Option<String> {
return (*self).addr();
}
}
impl Email for ShowThreadQueryThreadMessagesCc {
fn name(&self) -> &Option<String> {
return &self.name;
}
fn addr(&self) -> &Option<String> {
return &self.addr;
}
}
impl Email for ShowThreadQueryThreadMessagesFrom {
fn name(&self) -> &Option<String> {
return &self.name;
}
fn addr(&self) -> &Option<String> {
return &self.addr;
}
}
impl Email for ShowThreadQueryThreadMessagesTo {
fn name(&self) -> &Option<String> {
return &self.name;
}
fn addr(&self) -> &Option<String> {
return &self.addr;
}
}
fn view_addresses<E: Email>(addrs: &[E]) -> Vec<Node<Msg>> {
addrs
.into_iter()
.map(|address| {
span![
C!["tag", "is-black"],
address.addr().as_ref().map(|a| attrs! {At::Title=>a}),
address
.name()
.as_ref()
.unwrap_or(address.addr().as_ref().unwrap_or(&"(UNKNOWN)".to_string()))
]
})
.collect::<Vec<_>>()
}
fn view_thread(thread: &ShowThreadQueryThread) -> Node<Msg> {
// TODO(wathiede): show per-message subject if it changes significantly from top-level subject
set_title(&thread.subject);
let messages = thread.messages.iter().map(|msg| {
div![
C!["message"],
/* TODO(wathiede): collect all the tags and show them here. */
/* TODO(wathiede): collect all the attachments from all the subparts */
msg.from
.as_ref()
.map(|from| div![C!["header"], "From: ", view_addresses(&[from])]),
msg.timestamp
.map(|ts| div![C!["header"], "Date: ", human_age(ts)]),
IF!(!msg.to.is_empty() => div![C!["header"], "To: ", view_addresses(&msg.to)]),
IF!(!msg.cc.is_empty() => div![C!["header"], "CC: ", view_addresses(&msg.cc)]),
div![
C!["body"],
match &msg.body {
ShowThreadQueryThreadMessagesBody::UnhandledContentType(
ShowThreadQueryThreadMessagesBodyOnUnhandledContentType { contents },
) => pre![C!["error"], contents],
ShowThreadQueryThreadMessagesBody::PlainText(
ShowThreadQueryThreadMessagesBodyOnPlainText { contents },
) => div![C!["view-part-text-plain"], contents],
ShowThreadQueryThreadMessagesBody::Html(
ShowThreadQueryThreadMessagesBodyOnHtml { contents },
) => div![C!["view-part-text-html"], raw![contents]],
}
],
]
});
div![
C!["debug"],
"Add zippy for debug dump",
view_debug_thread_set(thread_set)
] /* pre![format!("Thread: {:#?}", thread_set).replace(" ", " ")] */
*/
C!["thread"],
p![C!["is-size-4"], &thread.subject],
messages,
/* TODO(wathiede): plumb in orignal id
a![
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
"Original"
],
*/
/*
div![
C!["debug"],
"Add zippy for debug dump",
view_debug_thread_set(thread_set)
] /* pre![format!("Thread: {:#?}", thread_set).replace(" ", " ")] */
*/
]
}
fn view_thread_legacy(thread_set: &ThreadSet) -> Node<Msg> {
assert_eq!(thread_set.0.len(), 1);
let thread = &thread_set.0[0];
assert_eq!(thread.0.len(), 1);
let thread_node = &thread.0[0];
let subject = first_subject(&thread_node).unwrap_or("<No subject>".to_string());
set_title(&subject);
div![
C!["container"],
h1![C!["title"], subject],
view_message(&thread_node),
a![
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
"Original"
],
/*
div![
C!["debug"],
"Add zippy for debug dump",
view_debug_thread_set(thread_set)
] /* pre![format!("Thread: {:#?}", thread_set).replace(" ", " ")] */
*/
]
*/
}
fn view_debug_thread_set(thread_set: &ThreadSet) -> Node<Msg> {
@@ -704,7 +1188,11 @@ fn view_header(query: &str, refresh_request: &RefreshingState) -> Node<Msg> {
At::Value => query,
},
input_ev(Ev::Input, |q| Msg::SearchRequest {
query: Url::encode_uri_component(q),
query: Url::encode_uri_component(if q.is_empty() {
"*".to_string()
} else {
q
}),
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
}),
@@ -734,27 +1222,64 @@ fn view_footer(render_time_ms: u128) -> Node<Msg> {
}
fn view_desktop(model: &Model) -> Node<Msg> {
// Do two queries, one without `unread` so it loads fast, then a second with unread.
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::Thread(messages) => view_thread(messages),
Context::Search(search_results) => view_search_results(&model.query, search_results),
Context::Thread(thread_set) => view_thread_legacy(thread_set),
Context::ThreadResult(thread) => view_thread(thread),
Context::Search(search_results) => view_search_results_legacy(&model.query, search_results),
Context::SearchResult {
query,
results,
count,
pager,
} => view_search_results(&query, results.as_slice(), *count, pager),
};
div![
view_header(&model.query, &model.refreshing_state),
section![C!["section"], content],
view_header(&model.query, &model.refreshing_state),
C!["desktop-main-content"],
aside![
C!["tags-menu", "menu"],
p![C!["menu-label"], "Tags"],
ul![
C!["menu-list"],
model.tags.as_ref().map(|tags| tags.iter().map(|t| li![a![
attrs! {
At::Href => urls::search(&format!("tag:{}", t.name), 0)
},
style! {
St::BackgroundColor => t.bg_color,
St::Color => t.fg_color,
},
&t.name
]]))
]
],
div![
view_header(&model.query, &model.refreshing_state),
content,
view_header(&model.query, &model.refreshing_state),
]
]
}
fn view_mobile(model: &Model) -> Node<Msg> {
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::Thread(messages) => view_thread(messages),
Context::Search(search_results) => view_mobile_search_results(&model.query, search_results),
Context::Thread(thread_set) => view_thread_legacy(thread_set),
Context::ThreadResult(thread) => view_thread(thread),
Context::Search(search_results) => {
view_mobile_search_results_legacy(&model.query, search_results)
}
Context::SearchResult {
query,
results,
count,
pager,
} => view_mobile_search_results(&query, results.as_slice(), *count, pager),
};
div![
view_header(&model.query, &model.refreshing_state),
section![C!["section"], div![C!["content"], content]],
content,
view_header(&model.query, &model.refreshing_state),
]
}
@@ -771,6 +1296,11 @@ fn view(model: &Model) -> Node<Msg> {
let start = Instant::now();
info!("view called");
div![
if is_mobile {
C!["mobile"]
} else {
C!["desktop"]
},
if is_mobile {
view_mobile(model)
} else {