Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add event summaries to markdown endpoints (#44122)

Penar Musaraj995155b8c539
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 38496544b8d..d3dcf60d13a 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -8,9 +8,16 @@ en:
next_page: "Next page"
empty: "No entries to display."
replies: "Replies"
- post_author: "Author: %{author}"
- post_date: "Post date: %{timestamp}"
+ post_author: "**Author:** %{author}"
+ post_date: "**Post date:** %{timestamp}"
last_updated: "Last updated"
+ event:
+ name: "Event"
+ start: "Starts"
+ end: "Ends"
+ location: "Location"
+ link: "Link"
+ date_with_timezone: "%{date} (%{timezone})"
mcp:
errors:
draft_sequence_conflict: "Draft sequence conflict"
diff --git a/lib/markdown_endpoint/cooked_processor.rb b/lib/markdown_endpoint/cooked_processor.rb
index 383505eb36e..d15fc8b81a8 100644
--- a/lib/markdown_endpoint/cooked_processor.rb
+++ b/lib/markdown_endpoint/cooked_processor.rb
@@ -4,7 +4,7 @@ module MarkdownEndpoint
class CookedProcessor
BLOCK_TAG = "discourse-markdown-block"
INLINE_TAG = "discourse-markdown-inline"
- VERSION = 4
+ VERSION = 5
class PreservedBlockConverter < ReverseMarkdown::Converters::Base
def convert(node, _state = {})
@@ -42,6 +42,7 @@ module MarkdownEndpoint
replace_oneboxes
replace_details
replace_polls
+ replace_events
absolutize_urls
ReverseMarkdown.convert(@fragment.to_html, github_flavored: true, unknown_tags: :bypass).strip
@@ -191,6 +192,57 @@ module MarkdownEndpoint
end
end
+ def replace_events
+ @fragment
+ .css("div.discourse-post-event")
+ .each do |event|
+ name = event["data-name"].presence || I18n.t("markdown_endpoints.event.name")
+ sections = ["**#{escape_text(EmojiConverter.convert(name))}**"]
+ fields = []
+ %w[start end].each do |attribute|
+ next if event["data-#{attribute}"].blank?
+
+ value = event_date(event["data-#{attribute}"], event)
+ fields << "**#{I18n.t("markdown_endpoints.event.#{attribute}")}:** #{escape_text(value)}"
+ end
+ if event["data-location"].present?
+ location = CGI.unescapeHTML(event["data-location"])
+ fields << "**#{I18n.t("markdown_endpoints.event.location")}:** #{escape_text(location)}"
+ end
+ if event["data-url"].present?
+ url = event["data-url"].strip
+ url = "https://#{url}" unless url.match?(%r{\A(?:[a-z][a-z0-9+.-]*:|/)}i)
+ if url.match?(%r{\A(?:https?://|/)}i)
+ url = URI::DEFAULT_PARSER.escape(absolute_url(url), /[\s<>"()\\]/)
+ fields << "**#{I18n.t("markdown_endpoints.event.link")}:** <#{url}>"
+ end
+ end
+ sections << fields.join("\\\n") if fields.present?
+ body = convert_html(event.inner_html)
+ sections << body if body.present?
+ content = sections.join("\n\n").lines.map { |line| "> #{line.chomp}".rstrip }.join("\n")
+ event.replace(preserved_block(content))
+ end
+ end
+
+ def event_date(value, event)
+ all_day = event["data-all-day"] == "true"
+ format = all_day ? :date_only : :long
+ formatted =
+ begin
+ I18n.l(DateTime.parse(value), format:)
+ rescue ArgumentError
+ value
+ end
+ return formatted if all_day
+
+ I18n.t(
+ "markdown_endpoints.event.date_with_timezone",
+ date: formatted,
+ timezone: event["data-timezone"].presence || "UTC",
+ )
+ end
+
def absolutize_urls
@fragment
.css("[href], [src]")
diff --git a/lib/markdown_endpoint/topic_renderer.rb b/lib/markdown_endpoint/topic_renderer.rb
index 07a49b13741..d5bfc0a9a54 100644
--- a/lib/markdown_endpoint/topic_renderer.rb
+++ b/lib/markdown_endpoint/topic_renderer.rb
@@ -59,7 +59,7 @@ module MarkdownEndpoint
def header(visible_post_count)
title = ContentLocalization.translated_topic_title(@topic, @guardian) || @topic.title
- lines = ["# #{escape_text(EmojiConverter.convert(title))}", "", "**URL:** #{@topic.url}"]
+ lines = ["**URL:** <#{@topic.url}>"]
lines << "**Category:** #{escape_text(@topic.category.name)}" if @topic.category
tags = @topic_view.visible_tags.map(&:name)
lines << "**Tags:** #{tags.map { |tag| escape_text(tag) }.join(", ")}" if tags.present?
@@ -67,7 +67,7 @@ module MarkdownEndpoint
lines << "**Posts on this page:** #{visible_post_count}"
lines << "**Page:** #{@topic_view.page}" unless single_post?
lines << "**Showing post:** #{@post_number}" if single_post?
- lines.join("\n")
+ "# #{escape_text(EmojiConverter.convert(title))}\n\n#{lines.join("\\\n")}"
end
def render_post(post)
@@ -75,15 +75,20 @@ module MarkdownEndpoint
serializer.topic_view = @topic_view
cooked = serializer.cooked.to_s
lines = ['<div class="post-metadata">', ""]
+ metadata = []
if post.user
avatar_url = UrlHelper.absolute(post.user.avatar_template.gsub("{size}", "32"))
avatar_url = "#{Discourse.base_protocol}:#{avatar_url}" if avatar_url.start_with?("//")
avatar_url = URI::DEFAULT_PARSER.escape(avatar_url, /[^\x21-\x7E]|[<>"()\\]/)
author = escape_text(post.user.username)
author_link = "![#{author}](#{avatar_url}) [@#{author}](#{post.user.full_url})"
- lines << "### #{I18n.t("markdown_endpoints.post_author", author: author_link)}"
+ metadata << I18n.t("markdown_endpoints.post_author", author: author_link)
end
- lines << "#### #{I18n.t("markdown_endpoints.post_date", timestamp: @timestamp.render(post.created_at, url: post.full_url))}"
+ metadata << I18n.t(
+ "markdown_endpoints.post_date",
+ timestamp: @timestamp.render(post.created_at, url: post.full_url),
+ )
+ lines << metadata.join("\\\n")
lines.concat(["", "</div>", ""])
lines << cached_body(cooked, post_url: post.full_url)
lines.join("\n")
diff --git a/spec/lib/markdown_endpoint/cooked_processor_spec.rb b/spec/lib/markdown_endpoint/cooked_processor_spec.rb
index ce1eb7480cd..9c3dfa4e600 100644
--- a/spec/lib/markdown_endpoint/cooked_processor_spec.rb
+++ b/spec/lib/markdown_endpoint/cooked_processor_spec.rb
@@ -78,6 +78,87 @@ RSpec.describe MarkdownEndpoint::CookedProcessor do
expect(markdown).to include("> _Poll ([view on site](#{post_url}))_")
end
+ it "renders event details and formatted descriptions without repeating the post link" do
+ html = <<~HTML
+ <p>Before</p>
+ <div class="discourse-post-event" data-name="Community [meetup]"
+ data-start="2026-10-15 18:00" data-end="2026-10-15 20:00"
+ data-timezone="America/Toronto" data-location="Hall &amp;amp; garden"
+ data-url="https://example.com/meetup">
+ <p>Join us for <strong>project updates</strong> and a <a href="/faq">Q&amp;A</a>.</p>
+ </div>
+ <p>After</p>
+ HTML
+ post_url = "#{Discourse.base_url}/t/community-meetup/123"
+
+ markdown = described_class.to_markdown(html, post_url:)
+
+ expect(markdown).to eq(<<~MARKDOWN.strip)
+ Before
+
+ > **Community \\[meetup\\]**
+ >
+ > **Starts:** October 15, 2026, 6:00pm (America/Toronto)\\
+ > **Ends:** October 15, 2026, 8:00pm (America/Toronto)\\
+ > **Location:** Hall & garden\\
+ > **Link:** <https://example.com/meetup>
+ >
+ > Join us for **project updates** and a [Q&A](#{Discourse.base_url}/faq).
+
+ After
+ MARKDOWN
+ end
+
+ it "renders all-day events inside details and omits missing fields" do
+ html = <<~HTML
+ <details><summary>Schedule</summary>
+ <div class="discourse-post-event" data-start="2026-10-15"
+ data-end="2026-10-16" data-all-day="true" data-timezone="America/Toronto"></div>
+ </details>
+ HTML
+
+ expect(described_class.to_markdown(html)).to eq(<<~MARKDOWN.strip)
+ > **Schedule**
+ >
+ > > **Event**
+ > >
+ > > **Starts:** October 15, 2026\\
+ > > **Ends:** October 16, 2026
+ MARKDOWN
+ end
+
+ it "keeps malformed event dates readable and defaults the timezone to UTC" do
+ html = <<~HTML
+ <div class="discourse-post-event" data-start="not-a-date"></div>
+ <div class="discourse-post-event" data-start="2026-10-15 18:00"></div>
+ HTML
+
+ expect(described_class.to_markdown(html)).to include(
+ "> **Starts:** not-a-date (UTC)",
+ "> **Starts:** October 15, 2026, 6:00pm (UTC)",
+ )
+ end
+
+ it "normalizes event links and omits unsafe schemes" do
+ html = <<~HTML
+ <div class="discourse-post-event" data-url="example.com/meet(up)"></div>
+ <div class="discourse-post-event" data-url="/events"></div>
+ <div class="discourse-post-event" data-url="javascript:alert(1)"></div>
+ HTML
+
+ expect(described_class.to_markdown(html)).to eq(<<~MARKDOWN.strip)
+ > **Event**
+ >
+ > **Link:** <https://example.com/meet%28up%29>
+
+ > **Event**
+ >
+ > **Link:** <#{Discourse.base_url}/events>
+
+ > **Event**
+ MARKDOWN
+ end
+
it "preserves quotes, oneboxes, lightboxes, and nested formatting" do
html = <<~HTML
<aside class="quote" data-username="alice">
diff --git a/spec/requests/markdown_endpoints_spec.rb b/spec/requests/markdown_endpoints_spec.rb
index 1dc8a20084d..a7f6d89b459 100644
--- a/spec/requests/markdown_endpoints_spec.rb
+++ b/spec/requests/markdown_endpoints_spec.rb
@@ -248,6 +248,35 @@ RSpec.describe "Markdown endpoints" do
expect(response).to have_http_status(:not_found)
end
+ it "separates topic metadata rows with hard line breaks" do
+ SiteSetting.tagging_enabled = true
+ topic.tags << Fabricate(:tag)
+
+ ["/t/#{topic.slug}/#{topic.id}.md", "/t/#{topic.slug}/#{topic.id}/1.md"].each do |path|
+ get path
+
+ expect(response).to have_http_status(:ok)
+ heading, metadata = response.body.split("\n\n", 3)
+ expect(heading).to eq("# #{topic.title}")
+ rows = metadata.lines.map(&:chomp)
+ expect(rows.map { |row| row[/\A\*\*(.+):\*\*/, 1] }).to eq(
+ [
+ "URL",
+ "Category",
+ "Tags",
+ "Created",
+ "Posts on this page",
+ path.end_with?("/1.md") ? "Showing post" : "Page",
+ ],
+ )
+ expect(rows[0...-1]).to all(end_with("\\"))
+ expect(rows.last).to eq(path.end_with?("/1.md") ? "**Showing post:** 1" : "**Page:** 1")
+ expect(rows.first).to eq("**URL:** <#{topic.url}>\\")
+ rendered_metadata = Nokogiri::HTML5.fragment(PrettyText.cook(metadata))
+ expect(rendered_metadata.at_css("a")["href"]).to eq(topic.url)
+ end
+ end
+
it "paginates rendered posts with translated Markdown navigation links" do
TranslationOverride.upsert!("en", "markdown_endpoints.previous_page", "Earlier posts")
TranslationOverride.upsert!("en", "markdown_endpoints.next_page", "Later posts")
@@ -302,8 +331,8 @@ RSpec.describe "Markdown endpoints" do
get "/t/#{topic.slug}/#{topic.id}.md"
expect(response.body).to include(
"[@#{user.username}](#{Discourse.base_url}/u/#{user.encoded_username})",
- "### Author: ![reply\\_author](#{Discourse.base_url}/letter_avatar/reply_author/32/#{LetterAvatar.version}.png) [@reply\\_author](#{Discourse.base_url}/u/#{author.encoded_username})",
- "\n#### Post date: ",
+ "**Author:** ![reply\\_author](#{Discourse.base_url}/letter_avatar/reply_author/32/#{LetterAvatar.version}.png) [@reply\\_author](#{Discourse.base_url}/u/#{author.encoded_username})",
+ "\n**Post date:** ",
)
get "/t/#{topic.slug}/#{topic.id}/#{reply.post_number}.md"
@@ -314,8 +343,8 @@ RSpec.describe "Markdown endpoints" do
reply.update_columns(user_id: nil)
get "/t/#{topic.slug}/#{topic.id}/#{reply.post_number}.md"
expect(response).to have_http_status(:ok)
- expect(response.body).to include("#### Post date: ")
- expect(response.body).not_to include("### Author:")
+ expect(response.body).to include("**Post date:** ")
+ expect(response.body).not_to include("**Author:**")
end
it "wraps list metadata separately from titles and excerpts with Markdown block boundaries" do
@@ -334,7 +363,7 @@ RSpec.describe "Markdown endpoints" do
)
end
- it "wraps each post's headings separately from its body with Markdown block boundaries" do
+ it "wraps each post's metadata separately from its body with Markdown block boundaries" do
reply = Fabricate(:post, topic: topic, user: user, raw: "Another visible body")
[
@@ -349,7 +378,9 @@ RSpec.describe "Markdown endpoints" do
posts
.zip(metadata)
.each do |rendered_post, block|
- expect(block).to include("### Author: ![", "\n#### Post date: ")
+ expect(block).to include("**Author:** ![", "\\\n**Post date:** ")
+ rendered_metadata = Nokogiri::HTML5.fragment(PrettyText.cook(block))
+ expect(rendered_metadata.css("br").size).to eq(1)
expect(block).not_to include(rendered_post.raw)
expect(response.body).to include("</div>\n\n#{rendered_post.raw}")
end
@@ -366,7 +397,7 @@ RSpec.describe "Markdown endpoints" do
expect(response).to have_http_status(:ok)
expect(response.body).to include(
- "### Author: ![依云](#{Discourse.base_url}/letter_avatar/%E4%BE%9D%E4%BA%91/32/#{LetterAvatar.version}.png) [@依云](#{user.full_url})",
+ "**Author:** ![依云](#{Discourse.base_url}/letter_avatar/%E4%BE%9D%E4%BA%91/32/#{LetterAvatar.version}.png) [@依云](#{user.full_url})",
post.raw,
)
end
@@ -377,7 +408,7 @@ RSpec.describe "Markdown endpoints" do
get "/t/#{topic.slug}/#{topic.id}.md"
expect(response.body).to include(
- "### Author: ![#{user.username}](#{Discourse.base_protocol}://cdn.example.com/avatar%281%29.png)",
+ "**Author:** ![#{user.username}](#{Discourse.base_protocol}://cdn.example.com/avatar%281%29.png)",
)
end
@@ -390,7 +421,7 @@ RSpec.describe "Markdown endpoints" do
get "/t/#{topic.slug}/#{topic.id}.md"
expect(response.body).to include(
- %(#### Post date: [July 15, 2026, 12:30pm EDT](#{post.full_url} "2026-07-15T12:30:45-04:00")),
+ %(**Post date:** [July 15, 2026, 12:30pm EDT](#{post.full_url} "2026-07-15T12:30:45-04:00")),
)
get "/latest.md"