Stop parsing Url in markdown

CommonMark accepts any URI.

Co-authored-by: nico2sh <mail@nico2sh.com>
This commit is contained in:
Héctor Ramón Jiménez 2025-11-21 04:40:41 +01:00
parent a9c1b81b58
commit 918e45824a
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
6 changed files with 71 additions and 60 deletions

4
Cargo.lock generated
View file

@ -2598,7 +2598,6 @@ dependencies = [
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
"thiserror 2.0.17", "thiserror 2.0.17",
"unicode-segmentation", "unicode-segmentation",
"url",
] ]
[[package]] [[package]]
@ -3203,9 +3202,10 @@ version = "0.1.0"
dependencies = [ dependencies = [
"iced", "iced",
"image", "image",
"open",
"reqwest", "reqwest",
"tokio", "tokio",
"url",
"webbrowser",
] ]
[[package]] [[package]]

View file

@ -44,7 +44,7 @@ enum Message {
Result<(Changelog, Vec<changelog::Contribution>), changelog::Error>, Result<(Changelog, Vec<changelog::Contribution>), changelog::Error>,
), ),
PullRequestFetched(Result<changelog::PullRequest, changelog::Error>), PullRequestFetched(Result<changelog::PullRequest, changelog::Error>),
UrlClicked(markdown::Url), LinkClicked(markdown::Uri),
TitleChanged(String), TitleChanged(String),
CategorySelected(changelog::Category), CategorySelected(changelog::Category),
Next, Next,
@ -113,7 +113,7 @@ impl Generator {
Task::none() Task::none()
} }
Message::UrlClicked(url) => { Message::LinkClicked(url) => {
let _ = webbrowser::open(url.as_str()); let _ = webbrowser::open(url.as_str());
Task::none() Task::none()
@ -281,7 +281,7 @@ impl Generator {
let description = let description =
markdown(description, self.theme()) markdown(description, self.theme())
.map(Message::UrlClicked); .map(Message::LinkClicked);
let labels = let labels =
row(pull_request.labels.iter().map(|label| { row(pull_request.labels.iter().map(|label| {
@ -351,7 +351,7 @@ impl Generator {
self.theme(), self.theme(),
), ),
) )
.map(Message::UrlClicked), .map(Message::LinkClicked),
) )
.spacing(10), .spacing(10),
) )

View file

@ -12,10 +12,13 @@ iced.features = ["markdown", "highlighter", "image", "tokio", "debug"]
reqwest.version = "0.12" reqwest.version = "0.12"
reqwest.features = ["json"] reqwest.features = ["json"]
image.workspace = true
tokio.workspace = true tokio.workspace = true
tokio.features = ["fs"]
open = "5.3" image.workspace = true
url.workspace = true
webbrowser = "1"
# Disabled to keep amount of build dependencies low # Disabled to keep amount of build dependencies low
# This can be re-enabled on demand # This can be re-enabled on demand

View file

@ -32,7 +32,7 @@ pub fn main() -> iced::Result {
struct Markdown { struct Markdown {
content: markdown::Content, content: markdown::Content,
raw: text_editor::Content, raw: text_editor::Content,
images: HashMap<markdown::Url, Image>, images: HashMap<markdown::Uri, Image>,
mode: Mode, mode: Mode,
theme: Theme, theme: Theme,
now: Instant, now: Instant,
@ -57,9 +57,9 @@ enum Image {
enum Message { enum Message {
Edit(text_editor::Action), Edit(text_editor::Action),
Copy(String), Copy(String),
LinkClicked(markdown::Url), LinkClicked(markdown::Uri),
ImageShown(markdown::Url), ImageShown(markdown::Uri),
ImageDownloaded(markdown::Url, Result<image::Handle, Error>), ImageDownloaded(markdown::Uri, Result<image::Handle, Error>),
ToggleStream(bool), ToggleStream(bool),
NextToken, NextToken,
Tick, Tick,
@ -100,20 +100,19 @@ impl Markdown {
} }
Message::Copy(content) => clipboard::write(content), Message::Copy(content) => clipboard::write(content),
Message::LinkClicked(link) => { Message::LinkClicked(link) => {
let _ = open::that_in_background(link.to_string()); let _ = webbrowser::open(&link);
Task::none() Task::none()
} }
Message::ImageShown(url) => { Message::ImageShown(uri) => {
if self.images.contains_key(&url) { if self.images.contains_key(&uri) {
return Task::none(); return Task::none();
} }
let _ = self.images.insert(url.clone(), Image::Loading); let _ = self.images.insert(uri.clone(), Image::Loading);
Task::perform( Task::perform(
download_image(url.clone()), download_image(uri.clone()),
Message::ImageDownloaded.with(url), Message::ImageDownloaded.with(uri),
) )
} }
Message::ImageDownloaded(url, result) => { Message::ImageDownloaded(url, result) => {
@ -240,19 +239,19 @@ impl Markdown {
} }
struct CustomViewer<'a> { struct CustomViewer<'a> {
images: &'a HashMap<markdown::Url, Image>, images: &'a HashMap<markdown::Uri, Image>,
now: Instant, now: Instant,
} }
impl<'a> markdown::Viewer<'a, Message> for CustomViewer<'a> { impl<'a> markdown::Viewer<'a, Message> for CustomViewer<'a> {
fn on_link_click(url: markdown::Url) -> Message { fn on_link_click(url: markdown::Uri) -> Message {
Message::LinkClicked(url) Message::LinkClicked(url)
} }
fn image( fn image(
&self, &self,
_settings: markdown::Settings, _settings: markdown::Settings,
url: &'a markdown::Url, url: &'a markdown::Uri,
_title: &'a str, _title: &'a str,
_alt: &markdown::Text, _alt: &markdown::Text,
) -> Element<'a, Message> { ) -> Element<'a, Message> {
@ -295,21 +294,31 @@ impl<'a> markdown::Viewer<'a, Message> for CustomViewer<'a> {
} }
} }
async fn download_image(url: markdown::Url) -> Result<image::Handle, Error> { async fn download_image(uri: markdown::Uri) -> Result<image::Handle, Error> {
use std::io; use std::io;
use tokio::task; use tokio::task;
use url::Url;
println!("Trying to download image: {url}"); let bytes = match Url::parse(&uri) {
Ok(url) if url.scheme() == "http" || url.scheme() == "https" => {
println!("Trying to download image: {url}");
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let bytes = client client
.get(url) .get(url)
.send() .send()
.await? .await?
.error_for_status()? .error_for_status()?
.bytes() .bytes()
.await?; .await?
}
_ => {
return Err(Error::IOFailed(Arc::new(io::Error::other(format!(
"unsupported uri: {uri}"
)))));
}
};
let image = task::spawn_blocking(move || { let image = task::spawn_blocking(move || {
Ok::<_, Error>( Ok::<_, Error>(

View file

@ -24,7 +24,7 @@ svg = ["iced_renderer/svg"]
canvas = ["iced_renderer/geometry"] canvas = ["iced_renderer/geometry"]
qr_code = ["canvas", "dep:qrcode"] qr_code = ["canvas", "dep:qrcode"]
wgpu = ["iced_renderer/wgpu-bare"] wgpu = ["iced_renderer/wgpu-bare"]
markdown = ["dep:pulldown-cmark", "dep:url"] markdown = ["dep:pulldown-cmark"]
highlighter = ["dep:iced_highlighter"] highlighter = ["dep:iced_highlighter"]
advanced = [] advanced = []
crisp = [] crisp = []
@ -49,6 +49,3 @@ pulldown-cmark.optional = true
iced_highlighter.workspace = true iced_highlighter.workspace = true
iced_highlighter.optional = true iced_highlighter.optional = true
url.workspace = true
url.optional = true

View file

@ -18,7 +18,7 @@
//! } //! }
//! //!
//! enum Message { //! enum Message {
//! LinkClicked(markdown::Url), //! LinkClicked(markdown::Uri),
//! } //! }
//! //!
//! impl State { //! impl State {
@ -63,7 +63,11 @@ use std::sync::Arc;
pub use core::text::Highlight; pub use core::text::Highlight;
pub use pulldown_cmark::HeadingLevel; pub use pulldown_cmark::HeadingLevel;
pub use url::Url;
/// A [`String`] representing a [URI] in a Markdown document
///
/// [URI]: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
pub type Uri = String;
/// A bunch of Markdown that has been parsed. /// A bunch of Markdown that has been parsed.
#[derive(Debug, Default)] #[derive(Debug, Default)]
@ -176,7 +180,7 @@ impl Content {
} }
/// Returns the URLs of the Markdown images present in the [`Content`]. /// Returns the URLs of the Markdown images present in the [`Content`].
pub fn images(&self) -> &HashSet<Url> { pub fn images(&self) -> &HashSet<Uri> {
&self.state.images &self.state.images
} }
} }
@ -209,7 +213,7 @@ pub enum Item {
/// An image. /// An image.
Image { Image {
/// The destination URL of the image. /// The destination URL of the image.
url: Url, url: Uri,
/// The title of the image. /// The title of the image.
title: String, title: String,
/// The alternative text of the image. /// The alternative text of the image.
@ -249,7 +253,7 @@ pub struct Row {
pub struct Text { pub struct Text {
spans: Vec<Span>, spans: Vec<Span>,
last_style: Cell<Option<Style>>, last_style: Cell<Option<Style>>,
last_styled_spans: RefCell<Arc<[text::Span<'static, Url>]>>, last_styled_spans: RefCell<Arc<[text::Span<'static, Uri>]>>,
} }
impl Text { impl Text {
@ -265,7 +269,7 @@ impl Text {
/// ///
/// This method performs caching for you. It will only reallocate if the [`Style`] /// This method performs caching for you. It will only reallocate if the [`Style`]
/// provided changes. /// provided changes.
pub fn spans(&self, style: Style) -> Arc<[text::Span<'static, Url>]> { pub fn spans(&self, style: Style) -> Arc<[text::Span<'static, Uri>]> {
if Some(style) != self.last_style.get() { if Some(style) != self.last_style.get() {
*self.last_styled_spans.borrow_mut() = *self.last_styled_spans.borrow_mut() =
self.spans.iter().map(|span| span.view(&style)).collect(); self.spans.iter().map(|span| span.view(&style)).collect();
@ -282,7 +286,7 @@ enum Span {
Standard { Standard {
text: String, text: String,
strikethrough: bool, strikethrough: bool,
link: Option<Url>, link: Option<Uri>,
strong: bool, strong: bool,
emphasis: bool, emphasis: bool,
code: bool, code: bool,
@ -296,7 +300,7 @@ enum Span {
} }
impl Span { impl Span {
fn view(&self, style: &Style) -> text::Span<'static, Url> { fn view(&self, style: &Style) -> text::Span<'static, Uri> {
match self { match self {
Span::Standard { Span::Standard {
text, text,
@ -361,7 +365,7 @@ impl Span {
/// } /// }
/// ///
/// enum Message { /// enum Message {
/// LinkClicked(markdown::Url), /// LinkClicked(markdown::Uri),
/// } /// }
/// ///
/// impl State { /// impl State {
@ -395,7 +399,7 @@ pub fn parse(markdown: &str) -> impl Iterator<Item = Item> + '_ {
struct State { struct State {
leftover: String, leftover: String,
references: HashMap<String, String>, references: HashMap<String, String>,
images: HashSet<Url>, images: HashSet<Uri>,
#[cfg(feature = "highlighter")] #[cfg(feature = "highlighter")]
highlighter: Option<Highlighter>, highlighter: Option<Highlighter>,
} }
@ -603,15 +607,13 @@ fn parse_with<'a>(
None None
} }
pulldown_cmark::Tag::Link { dest_url, .. } if !metadata => { pulldown_cmark::Tag::Link { dest_url, .. } if !metadata => {
link = Url::parse(&dest_url).ok(); link = Some(dest_url.into_string());
None None
} }
pulldown_cmark::Tag::Image { pulldown_cmark::Tag::Image {
dest_url, title, .. dest_url, title, ..
} if !metadata => { } if !metadata => {
image = Url::parse(&dest_url) image = Some((dest_url.into_string(), title.into_string()));
.ok()
.map(|url| (url, title.into_string()));
None None
} }
pulldown_cmark::Tag::List(first_item) if !metadata => { pulldown_cmark::Tag::List(first_item) if !metadata => {
@ -1104,7 +1106,7 @@ impl From<Theme> for Style {
/// } /// }
/// ///
/// enum Message { /// enum Message {
/// LinkClicked(markdown::Url), /// LinkClicked(markdown::Uri),
/// } /// }
/// ///
/// impl State { /// impl State {
@ -1132,7 +1134,7 @@ impl From<Theme> for Style {
pub fn view<'a, Theme, Renderer>( pub fn view<'a, Theme, Renderer>(
items: impl IntoIterator<Item = &'a Item>, items: impl IntoIterator<Item = &'a Item>,
settings: impl Into<Settings>, settings: impl Into<Settings>,
) -> Element<'a, Url, Theme, Renderer> ) -> Element<'a, Uri, Theme, Renderer>
where where
Theme: Catalog + 'a, Theme: Catalog + 'a,
Renderer: core::text::Renderer<Font = Font> + 'a, Renderer: core::text::Renderer<Font = Font> + 'a,
@ -1209,7 +1211,7 @@ pub fn heading<'a, Message, Theme, Renderer>(
level: &'a HeadingLevel, level: &'a HeadingLevel,
text: &'a Text, text: &'a Text,
index: usize, index: usize,
on_link_click: impl Fn(Url) -> Message + 'a, on_link_click: impl Fn(Uri) -> Message + 'a,
) -> Element<'a, Message, Theme, Renderer> ) -> Element<'a, Message, Theme, Renderer>
where where
Message: 'a, Message: 'a,
@ -1251,7 +1253,7 @@ where
pub fn paragraph<'a, Message, Theme, Renderer>( pub fn paragraph<'a, Message, Theme, Renderer>(
settings: Settings, settings: Settings,
text: &Text, text: &Text,
on_link_click: impl Fn(Url) -> Message + 'a, on_link_click: impl Fn(Uri) -> Message + 'a,
) -> Element<'a, Message, Theme, Renderer> ) -> Element<'a, Message, Theme, Renderer>
where where
Message: 'a, Message: 'a,
@ -1337,7 +1339,7 @@ where
pub fn code_block<'a, Message, Theme, Renderer>( pub fn code_block<'a, Message, Theme, Renderer>(
settings: Settings, settings: Settings,
lines: &'a [Text], lines: &'a [Text],
on_link_click: impl Fn(Url) -> Message + Clone + 'a, on_link_click: impl Fn(Uri) -> Message + Clone + 'a,
) -> Element<'a, Message, Theme, Renderer> ) -> Element<'a, Message, Theme, Renderer>
where where
Message: 'a, Message: 'a,
@ -1486,8 +1488,8 @@ where
Theme: Catalog + 'a, Theme: Catalog + 'a,
Renderer: core::text::Renderer<Font = Font> + 'a, Renderer: core::text::Renderer<Font = Font> + 'a,
{ {
/// Produces a message when a link is clicked with the given [`Url`]. /// Produces a message when a link is clicked with the given [`Uri`].
fn on_link_click(url: Url) -> Message; fn on_link_click(url: Uri) -> Message;
/// Displays an image. /// Displays an image.
/// ///
@ -1495,7 +1497,7 @@ where
fn image( fn image(
&self, &self,
settings: Settings, settings: Settings,
url: &'a Url, url: &'a Uri,
title: &'a str, title: &'a str,
alt: &Text, alt: &Text,
) -> Element<'a, Message, Theme, Renderer> { ) -> Element<'a, Message, Theme, Renderer> {
@ -1611,12 +1613,12 @@ where
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
struct DefaultViewer; struct DefaultViewer;
impl<'a, Theme, Renderer> Viewer<'a, Url, Theme, Renderer> for DefaultViewer impl<'a, Theme, Renderer> Viewer<'a, Uri, Theme, Renderer> for DefaultViewer
where where
Theme: Catalog + 'a, Theme: Catalog + 'a,
Renderer: core::text::Renderer<Font = Font> + 'a, Renderer: core::text::Renderer<Font = Font> + 'a,
{ {
fn on_link_click(url: Url) -> Url { fn on_link_click(url: Uri) -> Uri {
url url
} }
} }