From 54d0e8ddfba064118cba78ebdcbaa7e81b4e1ae3 Mon Sep 17 00:00:00 2001 From: Jonathan Cornaz Date: Fri, 1 Nov 2024 19:57:04 +0100 Subject: [PATCH] add download with name --- CHANGELOG.md | 2 +- src/attributes.rs | 30 ++++++++++++++++++++++++++++++ tests/render_spec.rs | 7 +++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47acf1d..8caaaa7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). * Meta (`meta`, `title`) * Text (`h1` to `h6`, and `text`) * Container (`div`) - * Anchor (`a`) and related attributes (`href`, `download`) + * Anchor (`a`) and related attributes (`href`, `target` and `download`) * Escape hatches (`raw` and `raw_unsafe`) * implement `From<(&'static str, Cow<'static, str)>` for `Attribute` * implement `From<&'static str>` and `From` for `Element` diff --git a/src/attributes.rs b/src/attributes.rs index aa6b8a8..c31bbdb 100644 --- a/src/attributes.rs +++ b/src/attributes.rs @@ -2,6 +2,32 @@ use alloc::{borrow::Cow, string::String}; use crate::Attribute; +pub enum Target { + Blank, + Self_, + Parent, + Top, + Frame(Cow<'static, str>), +} + +pub fn target(target: Target) -> Attribute { + Attribute::new( + "target", + match target { + Target::Blank => "_blank".into(), + Target::Self_ => "_self".into(), + Target::Parent => "_parent".into(), + Target::Top => "_top".into(), + Target::Frame(name) => name, + }, + ) +} + +/// Alias for `target(Target::Blank)` +pub fn target_blank() -> Attribute { + target(Target::Blank) +} + impl>> From<(&'static str, T)> for Attribute { fn from((key, value): (&'static str, T)) -> Self { Attribute::new(key, value) @@ -24,6 +50,10 @@ pub fn download() -> Attribute { Attribute::new_flag("download") } +pub fn download_with_name(name: impl Into>) -> Attribute { + Attribute::new("download", name) +} + pub fn class<'a>(classes: impl IntoIterator) -> Attribute { let mut values = String::new(); let mut iter = classes.into_iter(); diff --git a/tests/render_spec.rs b/tests/render_spec.rs index c3c9d25..b30a65e 100644 --- a/tests/render_spec.rs +++ b/tests/render_spec.rs @@ -33,6 +33,13 @@ fn should_render_html_document() { #[case(class(["foo", "bar"]), "class=\"foo bar\"")] #[case(href("foo"), "href=\"foo\"")] #[case(download(), "download")] +#[case(download_with_name("myfile.txt"), "download=\"myfile.txt\"")] +#[case(target(Target::Blank), "target=\"_blank\"")] +#[case(target_blank(), "target=\"_blank\"")] +#[case(target(Target::Self_), "target=\"_self\"")] +#[case(target(Target::Top), "target=\"_top\"")] +#[case(target(Target::Parent), "target=\"_parent\"")] +#[case(target(Target::Frame("myframe".into())), "target=\"myframe\"")] fn should_render_attribute(#[case] attr: Attribute, #[case] expected: &str) { let string = div([attr], []).to_string(); assert_eq!(string, format!("
"));