Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-dbg-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
absolute-paths-max-segments = 4

[[disallowed-types]]
Expand Down
2 changes: 1 addition & 1 deletion src/atom.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
mod feed;
pub use feed::{ATOM_NAMESPACE, AtomId, Content, Entry, Feed, Link};
pub use feed::Feed;
37 changes: 9 additions & 28 deletions src/atom/feed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use uuid::Uuid;
use crate::{
db::{self, Bookmark},
response_error::ResponseError,
views::content::bookmark_title,
views::common::bookmark_title,
};

/// XML namespace of the Atom syndication format.
Expand All @@ -27,11 +27,9 @@ pub static ATOM_NAMESPACE: &str = "http://www.w3.org/2005/Atom";
/// Permanent, universally unique identifier of a feed or entry.
///
/// Serialized as a [`urn:uuid`] IRI, which stays valid even when the
/// server's base URL changes. See [RFC 4287] for the requirements on
/// `atom:id`.
/// server's base URL changes.
///
/// [`urn:uuid`]: https://www.rfc-editor.org/rfc/rfc8141
/// [RFC 4287]: https://www.rfc-editor.org/rfc/rfc4287#section-4.2.6
#[derive(Debug, Clone)]
pub struct AtomId(pub Uuid);

Expand Down Expand Up @@ -141,6 +139,7 @@ impl Feed {
.map(|l| Entry::from_link(l, base_url))
.filter_map(|e| e.ok())
.collect();

Ok(Feed {
xmlns: ATOM_NAMESPACE,
id: AtomId(list.id),
Expand Down Expand Up @@ -189,7 +188,6 @@ impl IntoResponse for Feed {
///
/// [XML specification]: https://www.w3.org/TR/xml/#charsets
fn remove_illegal_xml_chars(text: &mut String) {
/// Whether `character` is allowed in XML documents.
fn is_legal_xml_char(character: char) -> bool {
matches!(
character,
Expand All @@ -216,15 +214,15 @@ impl Entry {
updated: bookmark.created_at,
links: vec![
// Primary "external link" shown by feed readers
Link {
rel: "via",
href: base_url.join(&bookmark.show_path())?,
},
// Secondary "external link" shown by feed readers
Link {
rel: "alternate",
href: bookmark_url,
},
// Secondary "external link", shown only by some feed readers
Link {
rel: "via",
href: base_url.join(&bookmark.show_path())?,
},
],
content: None,
})
Expand Down Expand Up @@ -327,7 +325,6 @@ mod tests {
let xml = feed.to_xml()?;

assert_eq!(xml.matches("<entry>").count(), 2);
assert!(xml.find("<title>First</title>") < xml.find("<title>Second</title>"));

Ok(())
}
Expand All @@ -336,11 +333,7 @@ mod tests {
fn falls_back_to_generic_title() -> anyhow::Result<()> {
let feed = feed_for(&[bookmark_link(None, "https://ties.pub/")?])?;

assert!(
feed.entries
.iter()
.all(|entry| entry.title == "Untitled Bookmark")
);
assert_eq!(feed.entries[0].title, "Untitled Bookmark");

Ok(())
}
Expand All @@ -357,9 +350,7 @@ mod tests {
assert!(xml.contains(
r#"<title>&lt;script&gt;alert("xss &amp; fun")&lt;/script&gt; &gt; 1 &amp; 1</title>"#
));
// The user-defined title cannot break out of the title element.
assert!(!xml.contains("<script>"));
assert!(!xml.contains("</title><script"));

Ok(())
}
Expand All @@ -383,16 +374,6 @@ mod tests {
Ok(())
}

#[test]
fn leaves_content_empty() -> anyhow::Result<()> {
let feed = feed_for(&[bookmark_link(Some("Example"), "https://ties.pub/")?])?;

assert!(feed.entries.iter().all(|entry| entry.content.is_none()));
assert!(!feed.to_xml()?.contains("<content"));

Ok(())
}

#[test]
fn escapes_user_defined_content() -> anyhow::Result<()> {
let mut feed = feed_for(&[bookmark_link(Some("Example"), "https://ties.pub/")?])?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ expression: feed.to_xml()?
<id>urn:uuid:00000000-0000-0000-0000-000000001234</id>
<title>Example</title>
<updated>1970-01-01T00:00:00Z</updated>
<link rel="via" href="https://ties.pub/bookmarks/00000000-0000-0000-0000-000000001234"/>
<link rel="alternate" href="https://ties.pub/"/>
<link rel="via" href="https://ties.pub/bookmarks/00000000-0000-0000-0000-000000001234"/>
</entry>
</feed>
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ pub mod server;
mod session;
mod views;

pub mod atom;
mod atom;

mod built_version;
mod date_time;
mod federation;
Expand Down
5 changes: 4 additions & 1 deletion src/routes/lists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ async fn get_show(
auth_user: Option<AuthUser>,
extract::Tx(mut tx): extract::Tx,
Path(list_id): Path<Uuid>,
State(state): State<AppState>,
) -> ResponseResult<HtmfResponse> {
let maybe_ap_user_id = auth_user.as_ref().map(|u| u.ap_user_id);
let links = db::links::list_by_list(&mut tx, list_id, maybe_ap_user_id).await?;
Expand All @@ -61,7 +62,9 @@ async fn get_show(
}

Ok(HtmfResponse(views::list::view(&views::list::Data {
layout: layout::Template::from_db(&mut tx, auth_user.as_ref()).await?,
layout: layout::Template::from_db(&mut tx, auth_user.as_ref())
.await?
.with_feed_link(state.base_url.join(&list.feed_path())?),
links,
list,
metadata: db::lists::metadata_by_id(&mut tx, list_id).await?,
Expand Down
2 changes: 1 addition & 1 deletion src/views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#![allow(clippy::too_many_lines)]
pub mod accept_invite;
pub mod base_document;
pub mod content;
pub mod common;
pub mod create_bookmark;
pub mod create_invite;
pub mod create_link;
Expand Down
78 changes: 41 additions & 37 deletions src/views/base_document.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,51 @@
use htmf::{declare::*, element::Element, into_attrs::IntoAttrs, into_elements::IntoElements};

pub fn base_document(children: impl IntoElements) -> Element {
pub fn base_document(children: impl IntoElements, head_elements: impl IntoElements) -> Element {
document().with(
html(class("w-full h-full"))
.with(head([]).with([
// icons & title
link([
rel("icon"),
href("/assets/favicon.svg"),
attr("type", "image/svg+xml"),
]),
link([
rel("apple-touch-icon"),
href("/assets/apple-touch-icon.png"),
]),
title_tag([]).with("ties"),
// styling
link([rel("stylesheet"), href("/assets/preflight.css")]),
link([rel("stylesheet"), href("/assets/railwind.css")]),
link([rel("stylesheet"), href("/assets/prose.css")]),
// Hide .js-only elements when JS is disabled.
noscript([]).with(Element::Tag {
tag: "style",
attrs: ().into_attrs(),
children: ".js-only{display: none;}".into_elements(),
}),
// htmx
script(src("/assets/htmx.1.9.9.js")),
meta([
name("htmx-config"),
content(
r#"{
.with(
head([])
.with([
// icons & title
link([
rel("icon"),
href("/assets/favicon.svg"),
attr("type", "image/svg+xml"),
]),
link([
rel("apple-touch-icon"),
href("/assets/apple-touch-icon.png"),
]),
title_tag([]).with("ties"),
// styling
link([rel("stylesheet"), href("/assets/preflight.css")]),
link([rel("stylesheet"), href("/assets/railwind.css")]),
link([rel("stylesheet"), href("/assets/prose.css")]),
// Hide .js-only elements when JS is disabled.
noscript([]).with(Element::Tag {
tag: "style",
attrs: ().into_attrs(),
children: ".js-only{display: none;}".into_elements(),
}),
// htmx
script(src("/assets/htmx.1.9.9.js")),
meta([
name("htmx-config"),
content(
r#"{
"scrollIntoViewOnBoost": false,
"historyCacheSize": 0
}"#,
),
]),
meta([name("color-scheme"), content("dark light")]),
meta([
name("viewport"),
content("width=device-width,initial-scale=1"),
]),
]))
),
]),
meta([name("color-scheme"), content("dark light")]),
meta([
name("viewport"),
content("width=device-width,initial-scale=1"),
]),
])
.with(head_elements),
)
.with(
body(class(
"w-full h-full dark:text-gray-200 text-gray-700 dark:bg-neutral-800
Expand Down
23 changes: 23 additions & 0 deletions src/views/content.rs → src/views/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,29 @@ pub fn help_icon() -> Element {
)
}

pub fn clipboard_button(
attrs: htmf::attr::Attrs,
text_to_copy: &str,
description: &str,
) -> Element {
button(
[
attr(
"onclick",
format!(
"navigator.clipboard.writeText('{text_to_copy}')
.then(() => {{
event.target.textContent='Copied!';
setTimeout(() => event.target.textContent = '{description}', 4000)
}})",
),
),
attrs,
],
description,
)
}

/// Return the title, or if it's None, a generic "untitled" title description.
#[expect(clippy::ref_option, reason = "It's easier to call this way.")]
pub fn bookmark_title(title: &Option<String>) -> &str {
Expand Down
38 changes: 13 additions & 25 deletions src/views/create_invite.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use htmf::prelude::*;
use url::Url;

use crate::{db, response_error::ResponseResult, views::layout};
use crate::{
db,
response_error::ResponseResult,
views::{common, layout},
};

pub struct Created {
pub layout: layout::Template,
Expand Down Expand Up @@ -41,7 +45,14 @@ pub fn created(
),
invite_url.clone(),
),
clipboard_button(&invite_url),
common::clipboard_button(
class(
"js-only px-4 py-2 bg-neutral-200 hover:bg-neutral-300 \
dark:bg-neutral-700 dark:hover:bg-neutral-600 rounded",
),
&invite_url,
"Copy to clipboard",
),
p(
[],
format!(
Expand All @@ -55,26 +66,3 @@ pub fn created(
&layout,
))
}

fn clipboard_button(invite_url: &str) -> Element {
let description = "Copy to clipboard";
button(
[
class(
"js-only px-4 py-2 bg-neutral-200 hover:bg-neutral-300 dark:bg-neutral-700 \
dark:hover:bg-neutral-600 rounded",
),
attr(
"onclick",
format!(
"navigator.clipboard.writeText('{invite_url}')
.then(() => {{
event.target.textContent='Copied!';
setTimeout(() => event.target.textContent = '{description}', 4000)
}})",
),
),
],
description,
)
}
6 changes: 3 additions & 3 deletions src/views/create_link.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use htmf::prelude::*;

use super::content;
use super::common;
use crate::{
db::{self, LinkDestination},
form_errors::FormErrors,
Expand Down Expand Up @@ -162,9 +162,9 @@ fn link_dest(link_dest: &db::LinkDestination) -> Element {
db::LinkDestination::Bookmark(bookmark) => fragment([
p(
class("dark:text-orange-100 text-orange-900"),
format!("📄 {}", content::bookmark_title(&bookmark.title)),
format!("📄 {}", common::bookmark_title(&bookmark.title)),
),
content::link_url(&bookmark.url),
common::link_url(&bookmark.url),
]),
db::LinkDestination::List(list) => p(
class("dark:text-fuchsia-100 text-fuchsia-800"),
Expand Down
2 changes: 1 addition & 1 deletion src/views/edit_bookmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
form_errors::FormErrors,
forms::{self, bookmarks::EditQuery},
response_error::ResponseResult,
views::content::help_icon,
views::common::help_icon,
};

/// Base data that is always needed, without form inputs, errors, search results
Expand Down
2 changes: 1 addition & 1 deletion src/views/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
built_version,
db::{AppTx, layout::AuthedInfo},
response_error::ResponseResult,
views::content::BULLET,
views::common::BULLET,
};

pub struct Data<'a> {
Expand Down
Loading
Loading