Skip to content

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

FEATURE: Improved event oneboxes for inter-Discourse-site linking and chat (#44991)

Martin Brennan8f1e016cf178
diff --git a/app/assets/stylesheets/common/base/onebox.scss b/app/assets/stylesheets/common/base/onebox.scss
index c07989b863d..72fabf84f35 100644
--- a/app/assets/stylesheets/common/base/onebox.scss
+++ b/app/assets/stylesheets/common/base/onebox.scss
@@ -172,7 +172,12 @@ aside.onebox {
color: var(--tertiary);
}
- img:not(.avatar, .onebox-avatar-inline, .emoji) {
+ img:not(
+ .avatar,
+ .onebox-avatar-inline,
+ .emoji,
+ .discourse-event-onebox__image
+ ) {
max-height: 170px;
max-width: 20%;
height: auto;
@@ -332,6 +337,223 @@ aside.onebox {
}
}
+// The color, ratio and height are set client-side from the image when they're known. The frame is
+// 16:9 at most, but never taller than the image itself, so small or very wide images don't sit in
+// large bars.
+@mixin letterboxed-event-image {
+ background: var(--event-onebox-image-color, var(--primary-very-low));
+ height: min(
+ calc(100cqi * 9 / 16),
+ calc(100cqi * var(--event-onebox-image-ratio, 1)),
+ var(--event-onebox-image-height, 100cqi)
+ );
+
+ // Shrinks images that don't fit, but never enlarges small ones
+ object-fit: scale-down;
+ object-position: center;
+}
+
+aside.onebox:has(.discourse-event-onebox) {
+ container: event-onebox / inline-size;
+}
+
+.discourse-event-onebox {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ gap: var(--space-4);
+
+ &__media {
+ align-self: start;
+ height: 5rem;
+ overflow: hidden;
+ position: relative;
+ width: 5rem;
+
+ &:not(:has(.discourse-event-onebox__image)) {
+ height: auto;
+ width: auto;
+
+ .discourse-event-onebox__date {
+ position: static;
+ }
+ }
+ }
+
+ &__image.thumbnail {
+ float: none;
+ height: 100%;
+ margin: 0;
+ max-height: 100%;
+ max-width: 100%;
+ object-fit: cover;
+
+ // Only affects images taller than their box, where the subject tends to sit high
+ object-position: 50% 0;
+ width: 100%;
+ }
+
+ &__date {
+ align-items: center;
+ background: var(--secondary);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ display: flex;
+ flex-direction: column;
+ height: 3em;
+ inset: 0;
+ justify-content: center;
+ margin: auto;
+ padding: 0;
+ position: absolute;
+ width: 3em;
+ }
+
+ &__month {
+ color: var(--primary);
+ font-size: var(--font-down-2);
+ font-weight: 400;
+ text-align: center;
+ text-transform: uppercase;
+ }
+
+ &__day {
+ font-size: var(--font-up-1);
+ font-weight: 400;
+ text-align: center;
+ }
+
+ &__content {
+ min-width: 0;
+ }
+
+ &__time {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+ margin-block: var(--space-3) var(--space-1);
+
+ .d-icon {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ flex: 0 0 auto;
+ }
+ }
+
+ &__description {
+ align-items: flex-start;
+ display: flex;
+ gap: var(--space-2);
+ overflow-wrap: anywhere;
+
+ .d-icon {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ flex: 0 0 auto;
+ margin-top: 0.2em;
+ }
+
+ p {
+ margin: 0;
+ }
+ }
+
+ &__metadata {
+ display: flex;
+ justify-content: space-between;
+ }
+
+ &.--banner-image {
+ container-type: inline-size;
+
+ // Lets the image span the full width above the date and content
+ .discourse-event-onebox__media {
+ display: contents;
+ }
+
+ // Matches the event widget's 16:9 image. The height is derived from the width rather than
+ // set with aspect-ratio, which cooked images carry inline from their dimensions.
+ .discourse-event-onebox__image.thumbnail {
+ border-radius: var(--d-border-radius);
+ grid-column: 1 / -1;
+ height: calc(100cqi * 9 / 16);
+ }
+
+ .discourse-event-onebox__date {
+ margin: 0;
+ position: static;
+ }
+ }
+
+ &.--letterboxed-image .discourse-event-onebox__image.thumbnail {
+ @include letterboxed-event-image;
+ }
+
+ &.--portrait-image {
+ // Flattens both wrappers so the date can sit beside the title while the image keeps its own column
+ grid-template:
+ "image date title" auto
+ "image time time" auto
+ "image description description" auto
+ "image metadata metadata" auto
+ "image . ." 1fr / 8rem auto minmax(0, 1fr);
+ row-gap: 0;
+
+ .discourse-event-onebox__media,
+ .discourse-event-onebox__content {
+ display: contents;
+ }
+
+ // Shows a 2:3 poster whole; anything taller is cropped from the bottom
+ .discourse-event-onebox__image.thumbnail {
+ border-radius: var(--d-border-radius);
+ grid-area: image;
+ height: auto;
+ max-height: 12rem;
+ }
+
+ .discourse-event-onebox__date {
+ grid-area: date;
+ margin: 0;
+ position: static;
+ }
+
+ .title-wrapper {
+ align-self: center;
+ grid-area: title;
+ }
+
+ .discourse-event-onebox__time {
+ grid-area: time;
+ }
+
+ .discourse-event-onebox__description {
+ grid-area: description;
+ }
+
+ .discourse-event-onebox__metadata {
+ grid-area: metadata;
+ }
+
+ // Two columns leave too little room for long titles in narrow spaces like phones or the chat
+ // drawer, so the image goes above, letterboxed into the same 16:9 frame as banner images
+ @container event-onebox (width < 30rem) {
+ container-type: inline-size;
+ grid-template:
+ "image image" auto
+ "date title" auto
+ ". time" auto
+ ". description" auto
+ ". metadata" auto / auto minmax(0, 1fr);
+
+ .discourse-event-onebox__image.thumbnail {
+ @include letterboxed-event-image;
+ margin-bottom: var(--space-4);
+ max-height: none;
+ }
+ }
+ }
+}
+
.chat-drawer-container .chat-message aside.onebox {
@include onebox-shadow(3px);
}
@@ -1065,7 +1287,8 @@ aside.onebox.xkcd .onebox-body img {
// allowlistedgeneric twitter labels
.onebox.allowlistedgeneric,
.onebox.whitelistedgeneric,
-.onebox.discoursetopic {
+.onebox.discoursetopic,
+.onebox.discoursetopic_with_event {
.label1,
.label2 {
color: var(--primary-med-or-secondary-med);
@@ -1107,7 +1330,8 @@ aside.onebox.xkcd .onebox-body img {
}
}
-.onebox.discoursetopic {
+.onebox.discoursetopic,
+.onebox.discoursetopic_with_event {
h3 {
width: 100%;
margin-bottom: 0.2rem !important;
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 773bb8c935f..06b66cbb1fc 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -6405,6 +6405,7 @@ en:
onebox:
discourse:
+ event_all_day: "All day"
user_joined_community: "Joined %{date}"
google_meet:
title: "Google Meet meeting"
diff --git a/lib/onebox/engine/discourse_topic_onebox.rb b/lib/onebox/engine/discourse_topic_onebox.rb
index 0247299d13e..30c22fb2d6e 100644
--- a/lib/onebox/engine/discourse_topic_onebox.rb
+++ b/lib/onebox/engine/discourse_topic_onebox.rb
@@ -9,6 +9,10 @@ module Onebox
matches_regexp(%r{/t/.*(/\d+)?})
+ def layout
+ @layout ||= Layout.new(event? ? "discoursetopic_with_event" : self.class.onebox_name, data)
+ end
+
def data
@data ||= {
categories: categories,
@@ -16,7 +20,17 @@ module Onebox
article_published_time: published_time.strftime("%-d %b %y"),
article_published_time_title: published_time.strftime("%I:%M%p - %d %B %Y"),
domain: html_entities.decode(raw[:site_name].truncate(80, separator: " ")),
- description: html_entities.decode(raw[:description].truncate(250, separator: " ")),
+ description: description,
+ is_event: event?,
+ event_all_day: event_all_day?,
+ event_date_day: event_date&.strftime("%-d"),
+ event_date_month: event_date&.strftime("%b"),
+ event_description: event_description,
+ event_ends_at: raw[:event_ends_at],
+ event_onebox_classes: event_onebox_classes,
+ event_starts_at: raw[:event_starts_at],
+ event_time: event_time,
+ event_timezone: event_timezone,
title: html_entities.decode(raw[:title].truncate(80, separator: " ")),
image: image,
render_tags?: render_tags?,
@@ -27,6 +41,101 @@ module Onebox
private
+ def description
+ value = event? ? event_description : raw[:description]
+ return if value.blank?
+
+ html_entities.decode(value.to_s.truncate(250, separator: " "))
+ end
+
+ def event?
+ raw[:event_starts_at].present?
+ end
+
+ def event_all_day?
+ event? && ActiveModel::Type::Boolean.new.cast(raw[:event_all_day])
+ end
+
+ def event_date
+ return unless event?
+
+ if event_all_day?
+ Date.iso8601(raw[:event_starts_at])
+ else
+ event_time_value(raw[:event_starts_at]).to_date
+ end
+ rescue ArgumentError
+ nil
+ end
+
+ def event_description
+ return unless event?
+
+ raw[:event_description]
+ end
+
+ def event_has_banner_image?
+ width, height = event_image_dimensions
+ width.present? && width >= height
+ end
+
+ # Too far from 16:9 to crop without losing much of the image, so it's shown whole inside the banner
+ def event_has_letterboxed_image?
+ width, height = event_image_dimensions
+ width.present? && width >= height && (width < height * 4 / 3 || width > height * 2)
+ end
+
+ def event_has_portrait_image?
+ width, height = event_image_dimensions
+ width.present? && height > width
+ end
+
+ def event_onebox_classes
+ [
+ "discourse-event-onebox",
+ ("--banner-image" if event_has_banner_image?),
+ ("--letterboxed-image" if event_has_letterboxed_image?),
+ ("--portrait-image" if event_has_portrait_image?),
+ ].compact.join(" ")
+ end
+
+ def event_image_dimensions
+ width = raw[:event_image_width].to_f
+ height = raw[:event_image_height].to_f
+ return if !event? || raw[:event_image].blank? || !width.positive? || !height.positive?
+
+ [width, height]
+ end
+
+ def event_time
+ return unless event?
+ return I18n.t("onebox.discourse.event_all_day") if event_all_day?
+
+ starts_at = event_time_value(raw[:event_starts_at])
+ ends_at = event_time_value(raw[:event_ends_at])
+
+ time = starts_at.strftime("%-I:%M %p")
+ time = "#{time} → #{ends_at.strftime("%-I:%M %p")}" if ends_at
+ "#{time} (#{event_timezone})"
+ rescue ArgumentError
+ nil
+ end
+
+ def event_time_value(value)
+ return if value.blank?
+
+ Time.iso8601(value)
+ end
+
+ def event_timezone
+ starts_at = event_time_value(raw[:event_starts_at])
+ return "UTC" if starts_at.blank? || starts_at.utc_offset.zero?
+
+ "UTC#{starts_at.formatted_offset}"
+ rescue ArgumentError
+ "UTC"
+ end
+
def categories
Array
.wrap(raw[:article_sections])
@@ -43,7 +152,11 @@ module Onebox
end
def image
- image = Onebox::Helpers.get_absolute_image_url(raw[:image], @url)
+ # Events only show their own image; the page's og:image can be a site-wide fallback like the logo
+ url = event? ? raw[:event_image] : raw[:image]
+ return if url.blank?
+
+ image = Onebox::Helpers.get_absolute_image_url(url, @url)
Onebox::Helpers.normalize_url_for_output(html_entities.decode(image))
end
diff --git a/lib/onebox/json_ld.rb b/lib/onebox/json_ld.rb
index 24de0eefb9b..e8d2e143ec3 100644
--- a/lib/onebox/json_ld.rb
+++ b/lib/onebox/json_ld.rb
@@ -3,8 +3,9 @@
module Onebox
class JsonLd < Normalizer
# Full schema.org hierarchy can be found here: https://schema.org/docs/full.html
+ EVENT_JSON_LD_TYPE = "Event"
MOVIE_JSON_LD_TYPE = "Movie"
- SUPPORTED_TYPES = [MOVIE_JSON_LD_TYPE]
+ SUPPORTED_TYPES = [EVENT_JSON_LD_TYPE, MOVIE_JSON_LD_TYPE]
def initialize(doc)
@data = extract(doc)
@@ -26,6 +27,8 @@ module Onebox
end
case parsed_json["@type"]
+ when EVENT_JSON_LD_TYPE
+ return event_data(parsed_json)
when MOVIE_JSON_LD_TYPE
return Onebox::Movie.new(parsed_json).to_h
end
@@ -34,6 +37,53 @@ module Onebox
{}
end
+ def event_data(json)
+ starts_at = json["startDate"]
+ image = event_image(json["image"])
+
+ {
+ event_starts_at: starts_at,
+ event_ends_at: json["endDate"],
+ event_all_day: date_only?(starts_at).to_s,
+ event_description: json["description"],
+ **{
+ event_image: image[:url],
+ event_image_width: image[:width],
+ event_image_height: image[:height],
+ }.compact,
+ }
+ end
+
+ # Schema.org allows a URL, an ImageObject, or a list of either
+ def event_image(value)
+ value = value.first if value.is_a?(Array)
+
+ case value
+ when String
+ { url: value }
+ when Hash
+ {
+ url: [value["url"], value["contentUrl"]].find { |url| url.is_a?(String) },
+ width: dimension(value["width"]),
+ height: dimension(value["height"]),
+ }
+ else
+ {}
+ end
+ end
+
+ # Kept as strings like the rest of the normalized data; QuantitativeValue wraps the number
+ def dimension(value)
+ value = value["value"] if value.is_a?(Hash)
+ value.to_s if value.to_s.to_i.positive?
+ end
+
+ def date_only?(value)
+ Date.iso8601(value.to_s).iso8601 == value.to_s
+ rescue Date::Error
+ false
+ end
+
def parse_json(json)
JSON[json]
rescue JSON::ParserError => e
diff --git a/lib/onebox/templates/discoursetopic.mustache b/lib/onebox/templates/discoursetopic.mustache
index 706b91b9fb2..d838fc84bbd 100644
--- a/lib/onebox/templates/discoursetopic.mustache
+++ b/lib/onebox/templates/discoursetopic.mustache
@@ -1,4 +1,4 @@
-{{#image}}<img src="{{image}}" class="thumbnail"/>{{/image}}
+{{#image}}<img src="{{image}}" class="thumbnail" alt=""/>{{/image}}
<div class="title-wrapper">
<h3><a href="{{link}}" target="_blank" rel="noopener">{{title}}</a></h3>
diff --git a/lib/onebox/templates/discoursetopic_with_event.mustache b/lib/onebox/templates/discoursetopic_with_event.mustache
new file mode 100644
index 00000000000..ecf6505ca9e
--- /dev/null
+++ b/lib/onebox/templates/discoursetopic_with_event.mustache
@@ -0,0 +1,64 @@
+<div class="{{event_onebox_classes}}"
+ data-event-all-day="{{event_all_day}}"
+ data-event-ends-at="{{event_ends_at}}"
+ data-event-starts-at="{{event_starts_at}}"
+ data-event-timezone="{{event_timezone}}">
+ <div class="discourse-event-onebox__media">
+ {{#image}}<img src="{{image}}" class="thumbnail discourse-event-onebox__image" alt=""/>{{/image}}
+ <time class="discourse-event-onebox__date" datetime="{{event_starts_at}}">
+ <span class="discourse-event-onebox__month">{{event_date_month}}</span>
+ <span class="discourse-event-onebox__day">{{event_date_day}}</span>
+ </time>
+ </div>
+
+ <div class="discourse-event-onebox__content">
+ <div class="title-wrapper">
+ <h3><a href="{{link}}" target="_blank" rel="noopener">{{title}}</a></h3>
+ {{#render_category_block?}}
+ <div class="topic-category">
+ {{#categories}}
+ <span class="badge-wrapper bullet">
+ <span class="badge-category-bg" style="background-color: #{{color}};"></span>
+ <span class="badge-category clear-badge">
+ <span class="category-name">{{name}}</span>
+ </span>
+ </span>
+ {{/categories}}
+ {{#render_tags?}}
+ <div class="topic-header-extra">
+ <div class="list-tags">
+ <div class="discourse-tags">
+ <svg class="fa d-icon d-icon-tag svg-icon svg-string" xmlns="http://www.w3.org/2000/svg"><use href="#tag" /></svg>
+ {{#article_tags}}
+ <span class="discourse-tag simple">{{.}}</span>
+ {{/article_tags}}
+ </div>
+ </div>
+ </div>
+ {{/render_tags?}}
+ </div>
+ {{/render_category_block?}}
+ </div>
+
+ <div class="discourse-event-onebox__time">
+ <svg class="fa d-icon d-icon-clock svg-icon svg-string" xmlns="http://www.w3.org/2000/svg"><use href="#clock" /></svg>
+ <span class="discourse-event-onebox__time-text">{{event_time}}</span>
+ </div>
+
+ {{#description}}
+ <div class="discourse-event-onebox__description">
+ <svg class="fa d-icon d-icon-file-lines svg-icon svg-string" xmlns="http://www.w3.org/2000/svg"><use href="#file-lines" /></svg>
+ <p>{{description}}</p>
+ </div>
+ {{/description}}
+
+ {{#data1}}
+ <p class="discourse-event-onebox__metadata">
+ <span class="label1">{{label1}}: {{data1}}</span>
+ {{#data2}}
+ <span class="label2">{{label2}}: {{data2}}</span>
+ {{/data2}}
+ </p>
+ {{/data1}}
+ </div>
+</div>
diff --git a/plugins/chat/assets/stylesheets/common/chat-message-images.scss b/plugins/chat/assets/stylesheets/common/chat-message-images.scss
index 5b7af038b16..bd253a60129 100644
--- a/plugins/chat/assets/stylesheets/common/chat-message-images.scss
+++ b/plugins/chat/assets/stylesheets/common/chat-message-images.scss
@@ -4,7 +4,12 @@ $max_video_height: 250px;
.chat-message {
// append selectors to set images to a
// max height of $max_image_height
- .onebox img:not(.ytp-thumbnail-image, .onebox-avatar-inline),
+ .onebox
+ img:not(
+ .ytp-thumbnail-image,
+ .onebox-avatar-inline,
+ .discourse-event-onebox__image
+ ),
img.onebox,
.chat-uploads img,
p img,
@@ -41,6 +46,16 @@ $max_video_height: 250px;
}
}
+ // Event images are sized by the onebox width, so match the width used in posts
+ aside.onebox:has(.discourse-event-onebox) {
+ max-width: var(--topic-body-width);
+ }
+
+ // Keeps event banner images compact in chat; cropped images lose more and letterboxed ones get wider bars
+ .discourse-event-onebox.--banner-image .discourse-event-onebox__image {
+ max-height: 12rem;
+ }
+
.onebox:not(.githubpullrequest, .githubcommit, .githubissue) {
@container (width < 400px) {
.onebox-body {
@@ -53,7 +68,7 @@ $max_video_height: 250px;
margin-right: 0.5rem;
}
- .thumbnail {
+ .thumbnail:not(.discourse-event-onebox__image) {
max-width: 100% !important;
margin: 0;
}
diff --git a/plugins/discourse-events/app/services/discourse_events/events/action/generate_schema_json.rb b/plugins/discourse-events/app/services/discourse_events/events/action/generate_schema_json.rb
new file mode 100644
index 00000000000..c63a64d71e9
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/action/generate_schema_json.rb
@@ -0,0 +1,121 @@
+# frozen_string_literal: true
+
+# Generates Schema.org JSON-LD for an event topic.
+#
+# Structure: Event
+#
+# - Event times include their configured timezone; all-day events use dates
+# - Events without a location or URL use the topic URL as their virtual location
+# - Descriptions are reduced to plain text suitable for structured data
+# - The event's own image is included so link previews don't fall back to the topic's
+#
+# Spec: https://schema.org/Event
+# Validator: https://validator.schema.org/
+class DiscourseEvents::Events::Action::GenerateSchemaJson < Service::ActionBase
+ option :event
+ option :first_post
+ option :topic
+
+ def call
+ MultiJson.dump(schema)
+ end
+
+ private
+
+ def schema
+ event_locations = locations
+
+ {
+ "@context" => "https://schema.org",
+ "@type" => "Event",
+ "name" => event.name.presence || topic.title,
+ "description" => description,
+ "startDate" => serialize_time(event.starts_at),
+ "endDate" => serialize_time(event.ends_at),
+ "eventStatus" => "https://schema.org/EventScheduled",
+ "eventAttendanceMode" => attendance_mode(event_locations),
+ "location" => event_locations.one? ? event_locations.first : event_locations,
+ "url" => topic.url,
+ "image" => image,
+ }.compact
+ end
+
+ def locations
+ event_locations = []
+ place = plain_text(event.location)
+
+ # A location that's only a link is where the event streams, not a place
+ if place&.match?(%r{\Ahttps?://\S+\z}i)
+ event_locations << { "@type" => "VirtualLocation", "url" => place }
+ elsif place.present?
+ event_locations << { "@type" => "Place", "name" => place, "address" => place }
+ end
+
+ if event.url&.match?(%r{\Ahttps?://\S+\z}i) &&
+ event_locations.none? { |location| location["url"] == event.url }
+ event_locations << { "@type" => "VirtualLocation", "url" => event.url }
+ end
+
+ if event_locations.empty?
+ event_locations << { "@type" => "VirtualLocation", "url" => topic.url }
+ end
+
+ event_locations
+ end
+
+ def attendance_mode(event_locations)
+ types = event_locations.map { |location| location["@type"] }
+
+ mode =
+ if types.include?("Place") && types.include?("VirtualLocation")
+ "Mixed"
+ elsif types.include?("Place")
+ "Offline"
+ else
+ "Online"
+ end
+
+ "https://schema.org/#{mode}EventAttendanceMode"
+ end
+
+ def image
+ upload = event.image_upload
+ return if upload.blank? || upload.secure?
+
+ # The topic image is synced from the event image and has a share-sized thumbnail
+ url =
+ if topic.image_upload_id == upload.id
+ topic.image_url
+ else
+ UrlHelper.cook_url(upload.url, local: true)
+ end
+ return if url.blank?
+
+ {
+ "@type" => "ImageObject",
+ "url" => ApplicationController.helpers.get_absolute_image_url(url),
+ "width" => upload.width,
+ "height" => upload.height,
+ }.compact
+ end
+
+ def description
+ plain_text(event.description)&.truncate(250, separator: " ")
+ end
+
+ def plain_text(value)
+ return if value.blank?
+
+ cooked = DiscourseEvents::Events::Parser.cook_inline(value, post: first_post)
+ Nokogiri::HTML5.fragment(cooked).text.squish.presence
+ end
+
+ def serialize_time(time)
+ return if time.blank?
+ return time.utc.strftime("%Y-%m-%d") if event.all_day
+
+ zoned_time =
+ time.in_time_zone(event.timezone.presence || DiscourseEvents::Events::Event::DEFAULT_TIMEZONE)
+ zoned_time.iso8601(3)
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/build_schema_markup.rb b/plugins/discourse-events/app/services/discourse_events/events/build_schema_markup.rb
new file mode 100644
index 00000000000..3d4a138ad6a
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/build_schema_markup.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+# Builds the Schema.org script element for an event attached to a topic's first post.
+class DiscourseEvents::Events::BuildSchemaMarkup
+ include Service::Base
+
+ params do
+ attribute :topic_id, :integer
+ validates :topic_id, presence: true
+ end
+
+ policy :schema_markup_enabled
+ model :topic
+ policy :can_see_topic
+ model :first_post
+ model :event
+ model :html
+
+ private
+
+ def schema_markup_enabled
+ SiteSetting.enable_event_schema_for_topics && SiteSetting.discourse_post_event_enabled
+ end
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def can_see_topic(guardian:, topic:)
+ guardian.can_see_topic?(topic)
+ end
+
+ def fetch_first_post(topic:)
+ topic.posts.includes(event: %i[image_upload event_dates]).find_by(post_number: 1)
+ end
+
+ def fetch_event(first_post:)
+ event = first_post.event
+ event if event&.deleted_at.nil?
+ end
+
+ def fetch_html(topic:, first_post:, event:)
+ json = DiscourseEvents::Events::Action::GenerateSchemaJson.call(topic:, first_post:, event:)
+
+ "<script type=\"application/ld+json\">#{ERB::Util.json_escape(json)}</script>"
+ end
+end
diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/image.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/image.gjs
index f1e2ac1f80d..e88e92fc4b9 100644
--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/image.gjs
+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/image.gjs
@@ -1,3 +1,4 @@
+import { trustHTML } from "@ember/template";
import { modifier } from "ember-modifier";
import getURL from "discourse/lib/get-url";
import lightbox from "discourse/lib/lightbox";
@@ -9,9 +10,46 @@ const setupLightbox = modifier((element, _positional, { post }) => {
return () => window.pswp?.close();
});
+const HEX_COLOR = /^[0-9a-f]{6}$/i;
+
+const isSideImage = (upload) =>
+ upload?.width > 0 && upload?.height > upload.width;
+
+// Too far from 16:9 to crop without losing much of the image, so it's shown whole inside the banner
+const isLetterboxed = (upload) =>
+ upload?.height > 0 &&
+ upload.width >= upload.height &&
+ (upload.width * 3 < upload.height * 4 || upload.width > upload.height * 2);
+
+// Lets letterboxed images fill their frame with their own color and fit it to their size
+const letterboxStyle = (upload) => {
+ const properties = [];
+
+ if (HEX_COLOR.test(upload?.dominant_color ?? "")) {
+ properties.push(`--event-image-color: #${upload.dominant_color}`);
+ }
+
+ const width = Number(upload?.width);
+ const height = Number(upload?.height);
+ if (width > 0 && height > 0) {
+ properties.push(`--event-image-ratio: ${height / width}`);
+ properties.push(`--event-image-height: ${height}px`);
+ }
+
+ return properties.length ? trustHTML(properties.join("; ")) : null;
+};
+
export default <template>
{{#if @imageUpload}}
- <section class="event__section event-image">
+ <section
+ class="event__section event-image
+ {{if (isSideImage @imageUpload) '--side'}}
+ {{if (isLetterboxed @imageUpload) '--letterboxed'}}"
+ style={{if
+ (or (isLetterboxed @imageUpload) (isSideImage @imageUpload))
+ (letterboxStyle @imageUpload)
+ }}
+ >
{{#if @linkToPost}}
<a href={{getURL @postUrl}} rel="noopener noreferrer">
<img alt={{@alt}} src={{@imageUpload.url}} />
diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/onebox-preview.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/onebox-preview.gjs
index 5e1e760cae7..95e7ebb5e63 100644
--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/onebox-preview.gjs
+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/onebox-preview.gjs
@@ -26,12 +26,13 @@ export default class DiscoursePostEventOneboxPreview extends Component {
<template>
{{#if this.event}}
- <DiscoursePostEvent
- class="discourse-post-event--preview"
- @event={{this.event}}
- @linkToPost={{true}}
- @readOnly={{true}}
- />
+ <div class="discourse-post-event-onebox">
+ <DiscoursePostEvent
+ @event={{this.event}}
+ @linkToPost={{true}}
+ @readOnly={{@readOnly}}
+ />
+ </div>
{{else}}
{{this.fallback}}
{{/if}}
diff --git a/plugins/discourse-events/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs b/plugins/discourse-events/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
index 439a068f990..3ce6c18e567 100644
--- a/plugins/discourse-events/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
+++ b/plugins/discourse-events/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
@@ -1,8 +1,10 @@
+import moment from "moment";
import { withPluginApi } from "discourse/lib/plugin-api";
import { i18n } from "discourse-i18n";
import ComposerEventEditor from "discourse/plugins/discourse-events/discourse/components/composer-event-editor";
import DiscoursePostEvent from "discourse/plugins/discourse-events/discourse/components/discourse-post-event";
import DiscoursePostEventOneboxPreview from "discourse/plugins/discourse-events/discourse/components/discourse-post-event/onebox-preview";
+import decorateEventOneboxes from "discourse/plugins/discourse-events/discourse/lib/decorate-event-oneboxes";
import DiscoursePostEventEvent from "discourse/plugins/discourse-events/discourse/models/discourse-post-event-event";
const ComposerEventEditorTemplate = <template>
@@ -52,11 +54,9 @@ function _decorateEventOneboxes(cooked, helper) {
});
}
-function _decorateEventPreviewOneboxes(cooked, helper) {
- // In the composer preview there's no post model / preloaded data, so we fetch
- // the event by topic id and render a read-only card. The original quote is
- // passed as a fallback so non-event links (and the loading state) keep showing
- // the normal onebox.
+function _decorateInternalEventOneboxes(cooked, helper, readOnly) {
+ // Composer previews and chat only have cooked onebox markup, so resolve events
+ // by topic id and retain the original onebox as the loading and non-event fallback.
cooked
.querySelectorAll(
"aside.quote[data-topic][data-post='1']:not([data-username])"
@@ -69,7 +69,6 @@ function _decorateEventPreviewOneboxes(cooked, helper) {
const fallbackHtml = aside.outerHTML;
const wrapper = document.createElement("div");
- wrapper.className = "discourse-post-event-onebox";
aside.replaceWith(wrapper);
helper.renderGlimmer(
@@ -77,6 +76,7 @@ function _decorateEventPreviewOneboxes(cooked, helper) {
<template>
<DiscoursePostEventOneboxPreview
@fallbackHtml={{fallbackHtml}}
+ @readOnly={{readOnly}}
@topicId={{topicId}}
/>
</template>
@@ -99,14 +99,19 @@ function _decorateEventPreview(api, cooked, helper) {
}
function initializeDiscoursePostEventDecorator(api) {
+ const currentUser = api.container.lookup("service:current-user");
+ const timezone = currentUser?.user_option?.timezone || moment.tz.guess();
+
api.addTrackedPostProperties("event_oneboxes");
api.decorateCookedElement(
(cooked, helper) => {
+ decorateEventOneboxes(cooked, timezone);
+
if (cooked.classList.contains("d-editor-preview")) {
_decorateEventPreview(api, cooked, helper);
if (helper) {
- _decorateEventPreviewOneboxes(cooked, helper);
+ _decorateInternalEventOneboxes(cooked, helper, true);
}
return;
}
@@ -157,6 +162,16 @@ function initializeDiscoursePostEventDecorator(api) {
}
);
+ if (api.decorateChatMessage) {
+ api.decorateChatMessage(
+ (cooked, helper) => {
+ decorateEventOneboxes(cooked, timezone);
+ _decorateInternalEventOneboxes(cooked, helper, false);
+ },
+ { id: "discourse-post-event-onebox" }
+ );
+ }
+
api.replaceIcon(
"notification.discourse_post_event.notifications.invite_user_notification",
"calendar-day"
diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/decorate-event-oneboxes.js b/plugins/discourse-events/assets/javascripts/discourse/lib/decorate-event-oneboxes.js
new file mode 100644
index 00000000000..70653139966
--- /dev/null
+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/decorate-event-oneboxes.js
@@ -0,0 +1,84 @@
+import moment from "moment";
+import { i18n } from "discourse-i18n";
+
+const HEX_COLOR = /^[0-9a-f]{6}$/i;
+
+export default function decorateEventOneboxes(element, timezone) {
+ element.querySelectorAll(".discourse-event-onebox").forEach((onebox) => {
+ applyImageStyles(onebox);
+
+ const allDay = onebox.dataset.eventAllDay === "true";
+ const startsAt = parseDate(onebox.dataset.eventStartsAt, {
+ allDay,
+ timezone,
+ });
+ if (!startsAt?.isValid()) {
+ return;
+ }
+
+ const endsAt = parseDate(onebox.dataset.eventEndsAt, {
+ allDay,
+ timezone,
+ });
+
+ onebox.querySelector(".discourse-event-onebox__month").textContent =
+ startsAt.format("MMM");
+ onebox.querySelector(".discourse-event-onebox__day").textContent =
+ startsAt.format("D");
+ onebox.querySelector(".discourse-event-onebox__time-text").textContent =
+ allDay
+ ? formatAllDay(startsAt, endsAt)
+ : formatTimed(startsAt, endsAt, timezone);
+ });
+}
+
+function applyImageStyles(onebox) {
+ const image = onebox.querySelector(".discourse-event-onebox__image");
+ if (!image) {
+ return;
+ }
+
+ const color = image.dataset.dominantColor;
+ if (HEX_COLOR.test(color ?? "")) {
+ onebox.style.setProperty("--event-onebox-image-color", `#${color}`);
+ }
+
+ const width = parseInt(image.getAttribute("width"), 10);
+ const height = parseInt(image.getAttribute("height"), 10);
+ if (width > 0 && height > 0) {
+ onebox.style.setProperty("--event-onebox-image-ratio", height / width);
+ onebox.style.setProperty("--event-onebox-image-height", `${height}px`);
+ }
+}
+
+function formatAllDay(startsAt, endsAt) {
+ if (!endsAt?.isValid() || startsAt.isSame(endsAt, "day")) {
+ return i18n("discourse_post_event.onebox.all_day");
+ }
+
+ return i18n("discourse_post_event.onebox.all_day_range", {
+ start: startsAt.format("ll"),
+ end: endsAt.format("ll"),
+ });
+}
+
+function formatTimed(startsAt, endsAt, timezone) {
+ let value = startsAt.format("LT");
+
+ if (endsAt?.isValid()) {
+ const format = startsAt.isSame(endsAt, "day") ? "LT" : "ll LT";
+ value = `${value} → ${endsAt.format(format)}`;
+ }
+
+ return `${value} (${timezone})`;
+}
+
+function parseDate(value, { allDay, timezone }) {
+ if (!value) {
+ return null;
+ }
+
+ return allDay
+ ? moment(value, "YYYY-MM-DD", true)
+ : moment.parseZone(value).tz(timezone);
+}
diff --git a/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scss b/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scss
index b448b506cc1..3abe16ce669 100644
--- a/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scss
+++ b/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scss
@@ -1,3 +1,39 @@
+@use "lib/viewport";
+
+// Fits the frame to the image: 16:9 at most, but never taller than the image itself, so small or
+// very wide images don't sit in large bars
+@mixin letterboxed-image {
+ aspect-ratio: auto;
+ container-type: inline-size;
+
+ img {
+ background: var(--event-image-color, var(--primary-very-low));
+ display: block;
+ height: min(
+ calc(100cqi * 9 / 16),
+ calc(100cqi * var(--event-image-ratio, 1)),
+ var(--event-image-height, 100cqi)
+ );
+
+ // Shrinks images that don't fit, but never enlarges small ones
+ object-fit: scale-down;
+ object-position: center;
+ }
+}
+
+@mixin stacked-side-image {
+ @include letterboxed-image;
+ float: none;
+ margin: 0;
+ padding: 1px;
+ width: 100%;
+
+ img {
+ border-radius: var(--d-border-radius) var(--d-border-radius) 0 0;
+ max-height: none;
+ }
+}
+
$interested: #fb985d;
$show-interested: inherit;
@@ -5,11 +41,36 @@ $show-interested: inherit;
display: none;
}
+// Only where the width comes from the page; elsewhere, like popovers, containment would collapse it
+.cooked .discourse-post-event,
+.chat-message-text .discourse-post-event {
+ container: post-event / inline-size;
+}
+
.discourse-post-event-onebox {
display: block;
margin: var(--space-4) 0;
}
+.chat-message-text .discourse-post-event-onebox {
+ max-width: var(--topic-body-width);
+
+ // Matches the chat cap on event onebox images; the image carries the ratio so it can be capped
+ .event-image:not(.--side) {
+ aspect-ratio: auto;
+
+ img {
+ display: block;
+ max-height: 12rem;
+ }
+
+ &:not(.--letterboxed) img {
+ aspect-ratio: 16 / 9;
+ height: auto;
+ }
+ }
+}
+
.discourse-post-event-onebox .discourse-post-event-widget,
.discourse-post-event--preview .discourse-post-event-widget {
box-shadow: 0 0 0 3px var(--primary-100);
@@ -52,9 +113,44 @@ $show-interested: inherit;
width: 100%;
height: 100%;
object-fit: cover;
+
+ // Only affects images taller than their box, where the subject tends to sit high
+ object-position: 50% 0;
border-top-left-radius: var(--d-border-radius);
border-top-right-radius: var(--d-border-radius);
}
+
+ &.--letterboxed {
+ @include letterboxed-image;
+ }
+
+ // Floated so the header and details wrap beside it, then take the full width once past it
+ &.--side {
+ aspect-ratio: auto;
+ float: left;
+ margin: 0.75em 0 0.75em 0.75em;
+ padding: 0;
+ width: 8rem;
+
+ img {
+ border-radius: var(--d-border-radius);
+ display: block;
+ height: auto;
+ max-height: 12rem;
+ }
+
+ // Two columns leave too little room for long titles in narrow spaces like phones or the chat
+ // drawer, so the image goes above, letterboxed into the usual 16:9 banner. The viewport check
+ // covers places that size the widget to its content, like the calendar popover, which can't
+ // be containers.
+ @include viewport.until(sm) {
+ @include stacked-side-image;
+ }
+
+ @container post-event (width < 30rem) {
+ @include stacked-side-image;
+ }
+ }
}
.discourse-post-event-widget {
@@ -77,6 +173,16 @@ $show-interested: inherit;
padding-bottom: 0.75em;
}
+ // Floats don't apply to flex items
+ &:has(> .event-image.--side) {
+ display: flow-root;
+
+ // Keeps the RSVP buttons from being squeezed beside the image
+ .event-actions {
+ clear: both;
+ }
+ }
+
&.is-ended {
background: var(--primary-very-low);
@@ -166,6 +272,7 @@ $show-interested: inherit;
.name {
font-size: var(--font-up-2);
font-weight: 400;
+ line-height: var(--line-height-medium);
}
.status-and-creators {
diff --git a/plugins/discourse-events/config/locales/client.en.yml b/plugins/discourse-events/config/locales/client.en.yml
index 87da513190f..4965829c710 100644
--- a/plugins/discourse-events/config/locales/client.en.yml
+++ b/plugins/discourse-events/config/locales/client.en.yml
@@ -369,6 +369,9 @@ en:
topic_id_description: "Only trigger for events in this topic. Leave empty to match all events."
discourse_post_event:
new_event: "New Event"
+ onebox:
+ all_day: "All day"
+ all_day_range: "All day · %{start} → %{end}"
notifications:
before_event_reminder: "An event is about to start"
after_event_reminder: "An event has ended"
diff --git a/plugins/discourse-events/config/locales/server.en.yml b/plugins/discourse-events/config/locales/server.en.yml
index f3107054bb9..c24817dd9c6 100644
--- a/plugins/discourse-events/config/locales/server.en.yml
+++ b/plugins/discourse-events/config/locales/server.en.yml
@@ -63,6 +63,7 @@ en:
map_events_title: "Overwrites 'Events' in the 'Upcoming Events' sidebar title per category."
discourse_events_enabled: "Enable the Discourse Events plugin. This will add support for a [calendar][/calendar] tag in the first post of a topic."
discourse_post_event_enabled: "Enables the Event features. Note: also needs {{setting:discourse_events_enabled}} to be enabled."
+ enable_event_schema_for_topics: "Add Schema.org Event data to event topic pages."
displayed_invitees_limit: "Limits the numbers of invitees displayed on an event."
display_post_event_date_on_topic_title: "Displays the date of the event after the topic title."
use_local_event_date: "Use local date after topic title instead of relative time."
diff --git a/plugins/discourse-events/config/settings.yml b/plugins/discourse-events/config/settings.yml
index 435bdd06f07..81d319a6b11 100644
--- a/plugins/discourse-events/config/settings.yml
+++ b/plugins/discourse-events/config/settings.yml
@@ -72,6 +72,9 @@ discourse_events:
discourse_post_event_enabled:
default: false
client: true
+ enable_event_schema_for_topics:
+ default: false
+ hidden: true
discourse_post_event_allowed_on_groups:
client: true
type: group_list
diff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rb
index f6bb659a9b8..7b9b0d52def 100644
--- a/plugins/discourse-events/plugin.rb
+++ b/plugins/discourse-events/plugin.rb
@@ -228,11 +228,26 @@ require_relative "lib/discourse_events/livestream/allowed_hosts_validator"
require_relative "lib/discourse_events/livestream/topic_extension"
require_relative "lib/discourse_events/livestream/chat_channel_extension"
require_relative "lib/discourse_events/livestream/zoom_url_parser"
-
Dir
.glob(File.expand_path("../lib/discourse_events/configuration/*.rb", __FILE__))
.each { |f| require(f) }
+event_schema_markup =
+ lambda do |controller|
+ topic_view = controller.instance_variable_get(:@topic_view)
+ result =
+ DiscourseEvents::Events::BuildSchemaMarkup.call(
+ params: {
+ topic_id: topic_view&.topic&.id,
+ },
+ guardian: controller.guardian,
+ )
+ result[:html] if result.success?
+ end
+
+register_html_builder("server:before-head-close", &event_schema_markup)
+register_html_builder("server:before-head-close-crawler", &event_schema_markup)
+
after_initialize do
UserOption.prepend DiscourseEvents::UserOptionExtension
UserUpdater::OPTION_ATTR.push(:event_reminder_preference)
diff --git a/plugins/discourse-events/spec/requests/topics_controller_spec.rb b/plugins/discourse-events/spec/requests/topics_controller_spec.rb
new file mode 100644
index 00000000000..5e987c975a5
--- /dev/null
+++ b/plugins/discourse-events/spec/requests/topics_controller_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+RSpec.describe TopicsController do
+ fab!(:admin)
+
+ before do
+ SiteSetting.discourse_events_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ SiteSetting.enable_event_schema_for_topics = true
+ end
+
+ describe "#show" do
+ let(:post) { PostCreator.create!(admin, title: "Community hangout", raw: <<~RAW) }
+ [event start="2026-10-22T13:00:00.000Z" end="2026-10-22T14:00:00.000Z" timezone="America/New_York" location="Town hall"]
+ Meet **the community**
+ [/event]
+ RAW
+
+ it "does not publish event schema when disabled" do
+ SiteSetting.enable_event_schema_for_topics = false
+
+ get post.topic.url
+
+ expect(response.status).to eq(200)
+ expect(response.body).not_to include('"@type":"Event"')
+ end
+
+ it "publishes event schema for ordinary and crawler HTML requests" do
+ [nil, "Googlebot"].each do |user_agent|
+ headers = user_agent ? { "HTTP_USER_AGENT" => user_agent } : {}
+ get post.topic.url, headers: headers
+
+ expect(response.status).to eq(200)
+ script =
+ Nokogiri
+ .HTML5(response.body)
+ .css('script[type="application/ld+json"]')
+ .find { |element| element.text.include?('"@type":"Event"') }
+ expect(script).to be_present, "missing Event schema for #{user_agent || "ordinary request"}"
+ schema = JSON.parse(script.text)
+ expect(schema).to include(
+ "@context" => "https://schema.org",
+ "@type" => "Event",
+ "name" => "Community hangout",
+ "description" => "Meet the community",
+ "startDate" => "2026-10-22T09:00:00.000-04:00",
+ "endDate" => "2026-10-22T10:00:00.000-04:00",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/spec/services/discourse_events/events/action/generate_schema_json_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/action/generate_schema_json_spec.rb
new file mode 100644
index 00000000000..c68ee173a67
--- /dev/null
+++ b/plugins/discourse-events/spec/services/discourse_events/events/action/generate_schema_json_spec.rb
@@ -0,0 +1,202 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseEvents::Events::Action::GenerateSchemaJson do
+ describe ".call" do
+ subject(:schema) { JSON.parse(described_class.call(topic:, first_post:, event:)) }
+
+ fab!(:user)
+ fab!(:topic) { Fabricate(:topic_with_op, user:, title: "Community hangout") }
+ fab!(:event) do
+ Fabricate(
+ :event,
+ post: topic.first_post,
+ name: "Community hangout",
+ description: "[Meet the community](https://example.com)",
+ original_starts_at: Time.iso8601("2026-10-22T13:00:00Z"),
+ original_ends_at: Time.iso8601("2026-10-22T14:00:00Z"),
+ timezone: "America/New_York",
+ url: "https://meet.example.com/hangout",
+ )
+ end
+
+ let(:first_post) { topic.first_post }
+
+ it "generates the complete Schema.org Event document" do
+ expect(schema).to include(
+ "@context" => "https://schema.org",
+ "@type" => "Event",
+ "name" => "Community hangout",
+ "description" => "Meet the community",
+ "startDate" => "2026-10-22T09:00:00.000-04:00",
+ "endDate" => "2026-10-22T10:00:00.000-04:00",
+ "eventStatus" => "https://schema.org/EventScheduled",
+ "eventAttendanceMode" => "https://schema.org/OnlineEventAttendanceMode",
+ "location" => {
+ "@type" => "VirtualLocation",
+ "url" => "https://meet.example.com/hangout",
+ },
+ "url" => topic.url,
+ )
+ end
+
+ it "uses the topic title when the event has no name" do
+ event.update!(name: nil)
+
+ expect(schema["name"]).to eq(topic.title)
+ end
+
+ it "cooks the description to plain text" do
+ event.update!(description: "Meet [the community](https://example.com) today")
+
+ expect(schema["description"]).to eq("Meet the community today")
+ end
+
+ it "returns unsafe strings as JSON data" do
+ unsafe_name = "Community meetup </script><script>alert('hello')</script>"
+ event.update!(name: unsafe_name)
+
+ expect(schema["name"]).to eq(unsafe_name)
+ end
+
+ it "keeps all-day event dates independent of positive and negative UTC offsets" do
+ event.update!(
+ all_day: true,
+ original_starts_at: Time.utc(2026, 10, 22),
+ original_ends_at: Time.utc(2026, 10, 23, 23, 59, 59),
+ )
+
+ %w[America/New_York Pacific/Kiritimati].each do |timezone|
+ event.update!(timezone:)
+ generated_schema = JSON.parse(described_class.call(topic:, first_post:, event:))
+
+ expect(generated_schema).to include("startDate" => "2026-10-22", "endDate" => "2026-10-23")
+ end
+ end
+
+ context "with a physical location" do
+ before { event.update!(location: "[Town hall](https://example.com/hall)", url: nil) }
+
+ it "generates offline event data" do
+ expect(schema).to include(
+ "eventAttendanceMode" => "https://schema.org/OfflineEventAttendanceMode",
+ "location" => {
+ "@type" => "Place",
+ "name" => "Town hall",
+ "address" => "Town hall",
+ },
+ )
+ end
+ end
+
+ context "with physical and virtual locations" do
+ before { event.update!(location: "Town hall") }
+
+ it "generates mixed event data" do
+ expect(schema["eventAttendanceMode"]).to eq("https://schema.org/MixedEventAttendanceMode")
+ expect(schema["location"].map { |location| location["@type"] }).to eq(
+ %w[Place VirtualLocation],
+ )
+ end
+ end
+
+ context "with the same stream URL as its location and event URL" do
+ before do
+ event.update!(
+ location: "https://stream.example.com/live",
+ url: "https://stream.example.com/live",
+ )
+ end
+
+ it "generates one virtual location" do
+ expect(schema).to include(
+ "eventAttendanceMode" => "https://schema.org/OnlineEventAttendanceMode",
+ "location" => {
+ "@type" => "VirtualLocation",
+ "url" => "https://stream.example.com/live",
+ },
+ )
+ end
+ end
+
+ context "with an invalid event URL" do
+ before do
+ event.update!(location: "Town hall")
+ event.update_column(:url, "javascript:alert(1)")
+ end
+
+ it "omits the invalid virtual location" do
+ expect(schema).to include(
+ "eventAttendanceMode" => "https://schema.org/OfflineEventAttendanceMode",
+ "location" => {
+ "@type" => "Place",
+ "name" => "Town hall",
+ "address" => "Town hall",
+ },
+ )
+ end
+ end
+
+ context "without an event location or URL" do
+ before { event.update!(location: nil, url: nil) }
+
+ it "uses the topic as a virtual location" do
+ expect(schema).to include(
+ "eventAttendanceMode" => "https://schema.org/OnlineEventAttendanceMode",
+ "location" => {
+ "@type" => "VirtualLocation",
+ "url" => topic.url,
+ },
+ )
+ end
+ end
+
+ context "with an event image synced to the topic" do
+ fab!(:upload) { Fabricate(:upload, width: 800, height: 1200) }
+
+ before do
+ event.update!(image_upload: upload)
+ topic.update!(image_upload_id: upload.id)
+ end
+
+ it "uses the topic image URL" do
+ expect(schema["image"]).to eq(
+ "@type" => "ImageObject",
+ "url" => ApplicationController.helpers.get_absolute_image_url(topic.reload.image_url),
+ "width" => 800,
+ "height" => 1200,
+ )
+ end
+ end
+
+ context "with an event image that differs from the topic image" do
+ fab!(:upload) { Fabricate(:upload, width: 800, height: 1200) }
+
+ before { event.update!(image_upload: upload) }
+
+ it "uses the event upload URL" do
+ expect(schema["image"]).to eq(
+ "@type" => "ImageObject",
+ "url" => ApplicationController.helpers.get_absolute_image_url(upload.url),
+ "width" => 800,
+ "height" => 1200,
+ )
+ end
+ end
+
+ context "with a secure event image" do
+ fab!(:secure_upload) { Fabricate(:secure_upload, width: 800, height: 1200) }
+
+ before { event.update!(image_upload: secure_upload) }
+
+ it "omits the image" do
+ expect(schema).not_to have_key("image")
+ end
+ end
+
+ context "without an event image" do
+ it "omits the image" do
+ expect(schema).not_to have_key("image")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/spec/services/discourse_events/events/build_schema_markup_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/build_schema_markup_spec.rb
new file mode 100644
index 00000000000..4b940787d03
--- /dev/null
+++ b/plugins/discourse-events/spec/services/discourse_events/events/build_schema_markup_spec.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseEvents::Events::BuildSchemaMarkup do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:topic_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+ fab!(:topic) { Fabricate(:topic_with_op, user:, title: "Community hangout") }
+ fab!(:event) { Fabricate(:event, post: topic.first_post) }
+
+ let(:params) { { topic_id: } }
+ let(:dependencies) { { guardian: } }
+ let(:topic_id) { topic.id }
+ let(:guardian) { user.guardian }
+
+ before do
+ SiteSetting.enable_event_schema_for_topics = true
+ SiteSetting.discourse_post_event_enabled = true
+ end
+
+ context "without a topic ID" do
+ let(:topic_id) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when event schema markup is disabled" do
+ before { SiteSetting.enable_event_schema_for_topics = false }
+
+ it { is_expected.to fail_a_policy(:schema_markup_enabled) }
+ end
+
+ context "when post events are disabled" do
+ before { SiteSetting.discourse_post_event_enabled = false }
+
+ it { is_expected.to fail_a_policy(:schema_markup_enabled) }
+ end
+
+ context "when the topic does not exist" do
+ let(:topic_id) { 0 }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when the user cannot see the topic" do
+ fab!(:private_group, :group)
+ fab!(:private_category) { Fabricate(:private_category, group: private_group) }
+ fab!(:private_author, :user)
+ fab!(:private_topic) do
+ Fabricate(:topic_with_op, user: private_author, category: private_category)
+ end
+
+ let(:topic_id) { private_topic.id }
+
+ it { is_expected.to fail_a_policy(:can_see_topic) }
+ end
+
+ context "when the topic has no first post" do
+ fab!(:empty_topic, :topic)
+
+ let(:topic_id) { empty_topic.id }
+
+ it { is_expected.to fail_to_find_a_model(:first_post) }
+ end
+
+ context "when the first post has no event" do
+ fab!(:ordinary_topic, :topic_with_op)
+
+ let(:topic_id) { ordinary_topic.id }
+
+ it { is_expected.to fail_to_find_a_model(:event) }
+ end
+
+ context "with a deleted event" do
+ before { event.update_column(:deleted_at, 1.day.ago) }
+
+ it { is_expected.to fail_to_find_a_model(:event) }
+ end
+
+ context "when the event is eligible" do
+ it { is_expected.to run_successfully }
+
+ it "generates JSON with the loaded event models and wraps it in a script element" do
+ json = MultiJson.dump("name" => "Community hangout")
+ DiscourseEvents::Events::Action::GenerateSchemaJson
+ .expects(:call)
+ .with(topic:, first_post: topic.first_post, event:)
+ .returns(json)
+
+ expect(result[:html]).to eq(
+ "<script type=\"application/ld+json\">#{ERB::Util.json_escape(json)}</script>",
+ )
+ end
+
+ it "safely embeds unsafe JSON data in one script element" do
+ unsafe_name = "Community meetup </script><script>alert('hello')</script>"
+ json = MultiJson.dump("name" => unsafe_name)
+ DiscourseEvents::Events::Action::GenerateSchemaJson.stubs(:call).returns(json)
+
+ fragment = Nokogiri::HTML5.fragment(result[:html])
+ script = fragment.at_css('script[type="application/ld+json"]')
+
+ expect(fragment.css('script[type="application/ld+json"]').count).to eq(1)
+ expect(JSON.parse(script.text)["name"]).to eq(unsafe_name)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/spec/system/chat_event_onebox_spec.rb b/plugins/discourse-events/spec/system/chat_event_onebox_spec.rb
new file mode 100644
index 00000000000..a1dce7cd230
--- /dev/null
+++ b/plugins/discourse-events/spec/system/chat_event_onebox_spec.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+RSpec.describe "Event topic links in chat" do
+ fab!(:current_user, :user)
+ fab!(:channel, :category_channel)
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }
+ let(:event_onebox) { PageObjects::Components::DiscourseEvents::ChatEventOnebox.new }
+ let(:event_post) { PostCreator.create!(current_user, title: "Community meetup", raw: <<~RAW) }
+ [event start="2026-11-12 11:00" end="2026-11-12 12:00" status="public" timezone="Australia/Brisbane"]
+ Join us for the community meetup.
+ [/event]
+ RAW
+ let(:event) { DiscourseEvents::Events::Event.find(event_post.id) }
+
+ before do
+ SiteSetting.discourse_events_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ SiteSetting.discourse_post_event_allowed_on_groups = Group::AUTO_GROUPS[:everyone].to_s
+ chat_system_bootstrap(current_user, [channel])
+ sign_in(current_user)
+ end
+
+ it "shows the event widget after the user links an event topic",
+ time: Time.zone.parse("2026-10-23 12:00:00") do
+ chat_page.visit_channel(channel)
+ channel_page.send_message(event_post.topic.url)
+
+ expect(event_onebox).to have_event(event)
+ end
+end
diff --git a/plugins/discourse-events/spec/system/page_objects/discourse_events/chat_event_onebox.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/chat_event_onebox.rb
new file mode 100644
index 00000000000..c3faf98a4fd
--- /dev/null
+++ b/plugins/discourse-events/spec/system/page_objects/discourse_events/chat_event_onebox.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ module DiscourseEvents
+ class ChatEventOnebox < PageObjects::Components::Base
+ SELECTOR = ".chat-message-text .discourse-post-event-onebox"
+
+ def has_event?(event)
+ topic = event.post.topic
+ title = event.name.presence || topic.title
+
+ has_css?("#{SELECTOR} .event-date") &&
+ has_css?("#{SELECTOR} .name a[href='#{event.post.relative_url}']", text: title) &&
+ has_css?("#{SELECTOR} .going-button")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/test/javascripts/acceptance/event-onebox-test.js b/plugins/discourse-events/test/javascripts/acceptance/event-onebox-test.js
index 7b584b615df..48fbecbf903 100644
--- a/plugins/discourse-events/test/javascripts/acceptance/event-onebox-test.js
+++ b/plugins/discourse-events/test/javascripts/acceptance/event-onebox-test.js
@@ -5,8 +5,9 @@ import topicFixtures from "discourse/tests/fixtures/topic";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
acceptance("Event onebox", function (needs) {
- needs.user();
+ needs.user({ has_chat_enabled: true });
needs.settings({
+ chat_enabled: true,
discourse_events_enabled: true,
discourse_post_event_enabled: true,
enable_markdown_linkify: true,
@@ -33,6 +34,64 @@ acceptance("Event onebox", function (needs) {
topicJson = cloneJSON(topicFixtures["/t/280/1.json"]);
});
needs.pretender((server, helper) => {
+ server.get("/chat/api/me/channels", () =>
+ helper.response({
+ direct_message_channels: [],
+ public_channels: [
+ {
+ id: 11,
+ title: "Events",
+ chatable_id: 1,
+ chatable_type: "Category",
+ meta: { message_bus_last_ids: {} },
+ current_user_membership: {
+ following: true,
+ last_read_message_id: 2,
+ },
+ chatable: { id: 1, color: "0088CC", name: "Events" },
+ },
+ ],
+ meta: { message_bus_last_ids: {} },
+ tracking: {
+ channel_tracking: {
+ 11: { unread_count: 0, mention_count: 0 },
+ },
+ thread_tracking: {},
+ },
+ })
+ );
+ server.get("/chat/api/channels/11/messages", () =>
+ helper.response({
+ messages: [
+ {
+ id: 1,
+ message: "Event topic",
+ cooked: `
+ <aside class="quote" data-topic="123" data-post="1">
+ <div class="title">Event topic</div>
+ <blockquote>Board game night</blockquote>
+ </aside>
+ `,
+ created_at: "2026-09-01T10:00:00.000Z",
+ user: { id: 5, username: "bob" },
+ },
+ {
+ id: 2,
+ message: "Ordinary topic",
+ cooked: `
+ <aside class="quote" data-topic="124" data-post="1">
+ <div class="title">Ordinary topic</div>
+ <blockquote>Preview text</blockquote>
+ </aside>
+ `,
+ created_at: "2026-09-01T10:01:00.000Z",
+ user: { id: 5, username: "bob" },
+ },
+ ],
+ meta: { can_delete_self: true },
+ })
+ );
+ server.post("/chat/api/channels/11/drafts", () => helper.response({}));
server.get("/t/280.json", () => helper.response(topicJson));
server.get("/t/280/:post_number.json", () => helper.response(topicJson));
server.get("/discourse-post-event/events/900", () =>
@@ -151,4 +210,25 @@ acceptance("Event onebox", function (needs) {
"ordinary topic previews retain core rendering"
);
});
+
+ test("event topics show the interactive event card in chat", async function (assert) {
+ await visit("/chat/c/events/11");
+ await waitFor(".discourse-post-event-onebox .discourse-post-event-widget");
+
+ assert
+ .dom(".discourse-post-event-onebox .event-date .day")
+ .exists("the chat card renders the event date");
+ assert
+ .dom(".discourse-post-event-onebox .name")
+ .hasText(event.name, "the chat card links to the event");
+ assert
+ .dom(".discourse-post-event-onebox .going-button")
+ .exists("the chat card keeps its RSVP controls");
+ assert
+ .dom('aside.quote[data-topic="124"]')
+ .includesText(
+ "Preview text",
+ "ordinary topic oneboxes retain core rendering"
+ );
+ });
});
diff --git a/plugins/discourse-events/test/javascripts/integration/components/image-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/image-test.gjs
new file mode 100644
index 00000000000..56e58511f18
--- /dev/null
+++ b/plugins/discourse-events/test/javascripts/integration/components/image-test.gjs
@@ -0,0 +1,138 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import Image from "discourse/plugins/discourse-events/discourse/components/discourse-post-event/image";
+
+function upload(width, height, dominantColor = "2A292A") {
+ return {
+ dominant_color: dominantColor,
+ height,
+ url: "/uploads/default/original/1X/event.jpeg",
+ width,
+ };
+}
+
+module("Integration | Component | Image", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("crops images between 4:3 and 2:1 into the banner", async function (assert) {
+ const imageUpload = upload(1600, 900);
+
+ await render(
+ <template>
+ <Image
+ @imageUpload={{imageUpload}}
+ @linkToPost={{true}}
+ @postUrl="/t/1"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".event-image")
+ .doesNotHaveClass("--side", "the image stays in the banner")
+ .doesNotHaveClass("--letterboxed", "the image is cropped")
+ .doesNotHaveAttribute("style");
+ });
+
+ test("letterboxes near-square images on their dominant color", async function (assert) {
+ const imageUpload = upload(800, 800);
+
+ await render(
+ <template>
+ <Image
+ @imageUpload={{imageUpload}}
+ @linkToPost={{true}}
+ @postUrl="/t/1"
+ />
+ </template>
+ );
+
+ assert.dom(".event-image").hasClass("--letterboxed").hasStyle({
+ "--event-image-color": "#2A292A",
+ "--event-image-height": "800px",
+ "--event-image-ratio": "1",
+ });
+ });
+
+ test("letterboxes images wider than 2:1", async function (assert) {
+ const imageUpload = upload(1500, 500);
+
+ await render(
+ <template>
+ <Image
+ @imageUpload={{imageUpload}}
+ @linkToPost={{true}}
+ @postUrl="/t/1"
+ />
+ </template>
+ );
+
+ assert.dom(".event-image").hasClass("--letterboxed");
+ });
+
+ test("puts portrait images in the side column", async function (assert) {
+ const imageUpload = upload(800, 1200);
+
+ await render(
+ <template>
+ <Image
+ @imageUpload={{imageUpload}}
+ @linkToPost={{true}}
+ @postUrl="/t/1"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".event-image")
+ .hasClass("--side")
+ .doesNotHaveClass("--letterboxed")
+ .hasStyle(
+ { "--event-image-color": "#2A292A" },
+ "the color is ready for the letterboxed layout on narrow screens"
+ );
+ });
+
+ test("ignores a malformed dominant color", async function (assert) {
+ const imageUpload = upload(800, 800, "red; display: none");
+
+ await render(
+ <template>
+ <Image
+ @imageUpload={{imageUpload}}
+ @linkToPost={{true}}
+ @postUrl="/t/1"
+ />
+ </template>
+ );
+
+ assert.dom(".event-image").hasClass("--letterboxed");
+ assert.strictEqual(
+ document
+ .querySelector(".event-image")
+ .style.getPropertyValue("--event-image-color"),
+ "",
+ "no color is applied"
+ );
+ });
+
+ test("keeps the banner crop when the image size is unknown", async function (assert) {
+ const imageUpload = { url: "/uploads/default/original/1X/event.jpeg" };
+
+ await render(
+ <template>
+ <Image
+ @imageUpload={{imageUpload}}
+ @linkToPost={{true}}
+ @postUrl="/t/1"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".event-image")
+ .doesNotHaveClass("--side")
+ .doesNotHaveClass("--letterboxed");
+ });
+});
diff --git a/plugins/discourse-events/test/javascripts/unit/lib/decorate-event-oneboxes-test.js b/plugins/discourse-events/test/javascripts/unit/lib/decorate-event-oneboxes-test.js
new file mode 100644
index 00000000000..c5a12eccce9
--- /dev/null
+++ b/plugins/discourse-events/test/javascripts/unit/lib/decorate-event-oneboxes-test.js
@@ -0,0 +1,132 @@
+import { module, test } from "qunit";
+import decorateEventOneboxes from "discourse/plugins/discourse-events/discourse/lib/decorate-event-oneboxes";
+
+module("Unit | Lib | decorate-event-oneboxes", function () {
+ test("localizes timed event oneboxes to the viewer's timezone", function (assert) {
+ const element = buildOnebox({
+ startsAt: "2026-10-22T13:00:00.000Z",
+ endsAt: "2026-10-22T14:00:00.000Z",
+ });
+
+ decorateEventOneboxes(element, "Australia/Brisbane");
+
+ assert
+ .dom(".discourse-event-onebox__month", element)
+ .hasText("Oct", "the month follows the localized date");
+ assert
+ .dom(".discourse-event-onebox__day", element)
+ .hasText("22", "the day follows the localized date");
+ assert
+ .dom(".discourse-event-onebox__time-text", element)
+ .hasText(
+ "11:00 PM → Oct 23, 2026 12:00 AM (Australia/Brisbane)",
+ "the time and timezone are localized"
+ );
+ });
+
+ test("keeps all-day event dates timezone-independent", function (assert) {
+ const element = buildOnebox({
+ allDay: true,
+ startsAt: "2026-10-22",
+ endsAt: "2026-10-22",
+ });
+
+ decorateEventOneboxes(element, "Pacific/Honolulu");
+
+ assert
+ .dom(".discourse-event-onebox__month", element)
+ .hasText("Oct", "the month remains on the authored date");
+ assert
+ .dom(".discourse-event-onebox__day", element)
+ .hasText("22", "the day remains on the authored date");
+ assert
+ .dom(".discourse-event-onebox__time-text", element)
+ .hasText("All day", "the event is identified as all day");
+ });
+
+ test("exposes the image's dominant color for the letterbox", function (assert) {
+ const element = buildOnebox({
+ dominantColor: "2A292A",
+ startsAt: "2026-10-22T13:00:00.000Z",
+ });
+
+ decorateEventOneboxes(element, "UTC");
+
+ assert.strictEqual(
+ element
+ .querySelector(".discourse-event-onebox")
+ .style.getPropertyValue("--event-onebox-image-color"),
+ "#2A292A",
+ "the color is available to the image styles"
+ );
+ });
+
+ test("exposes the image's size so the letterbox can fit it", function (assert) {
+ const element = buildOnebox({
+ dominantColor: "2A292A",
+ imageHeight: 300,
+ imageWidth: 600,
+ startsAt: "2026-10-22T13:00:00.000Z",
+ });
+
+ decorateEventOneboxes(element, "UTC");
+
+ const style = element.querySelector(".discourse-event-onebox").style;
+ assert.strictEqual(
+ style.getPropertyValue("--event-onebox-image-ratio"),
+ "0.5",
+ "the ratio is available to the image styles"
+ );
+ assert.strictEqual(
+ style.getPropertyValue("--event-onebox-image-height"),
+ "300px",
+ "the height is available to the image styles"
+ );
+ });
+
+ test("ignores a malformed dominant color", function (assert) {
+ const element = buildOnebox({
+ dominantColor: "red; display: none",
+ startsAt: "2026-10-22T13:00:00.000Z",
+ });
+
+ decorateEventOneboxes(element, "UTC");
+
+ assert.strictEqual(
+ element
+ .querySelector(".discourse-event-onebox")
+ .style.getPropertyValue("--event-onebox-image-color"),
+ "",
+ "no color is applied"
+ );
+ });
+});
+
+function buildOnebox({
+ allDay = false,
+ dominantColor,
+ imageHeight,
+ imageWidth,
+ startsAt,
+ endsAt,
+}) {
+ const element = document.createElement("div");
+ element.innerHTML = `
+ <div
+ class="discourse-event-onebox"
+ data-event-all-day="${allDay}"
+ data-event-starts-at="${startsAt}"
+ data-event-ends-at="${endsAt}"
+ >
+ ${
+ dominantColor
+ ? `<img class="discourse-event-onebox__image" data-dominant-color="${dominantColor}" width="${imageWidth ?? ""}" height="${imageHeight ?? ""}">`
+ : ""
+ }
+ <span class="discourse-event-onebox__month"></span>
+ <span class="discourse-event-onebox__day"></span>
+ <span class="discourse-event-onebox__time-text"></span>
+ </div>
+ `;
+ return element;
+}
diff --git a/spec/lib/onebox/engine/discourse_topic_onebox_spec.rb b/spec/lib/onebox/engine/discourse_topic_onebox_spec.rb
index 7b8450c7e7e..f4e51150b15 100644
--- a/spec/lib/onebox/engine/discourse_topic_onebox_spec.rb
+++ b/spec/lib/onebox/engine/discourse_topic_onebox_spec.rb
@@ -47,5 +47,166 @@ RSpec.describe Onebox::Engine::DiscourseTopicOnebox do
it "returns the expected data" do
expect(data).to include expected_data
end
+
+ context "with Schema.org Event data" do
+ let(:url) { "https://example.com/t/community-hangout/123" }
+ let(:event_image_json) { %("image": "https://example.com/event.png",) }
+ let(:event_description_json) { %("description": "Meet the community",) }
+ let(:html) { <<~HTML }
+ <html>
+ <head>
+ <meta property="og:site_name" content="Example community">
+ <meta property="og:title" content="Community hangout">
+ <meta property="og:description" content="The ordinary topic excerpt">
+ <meta property="og:image" content="https://example.com/site-logo.png">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="article:published_time" content="2026-10-19T00:00:00Z">
+ <meta name="twitter:label1" value="Reading time">
+ <meta name="twitter:data1" value="1 min 🕑">
+ <meta name="twitter:label2" value="Likes">
+ <meta name="twitter:data2" value="2 ❤">
+ <script type="application/ld+json">
+ {
+ "@context": "https://schema.org",
+ "@type": "Event",
+ "name": "Community hangout",
+ #{event_description_json}
+ #{event_image_json}
+ "startDate": "2026-10-22T09:00:00.000-04:00",
+ "endDate": "2026-10-22T10:00:00.000-04:00"
+ }
+ </script>
+ </head>
+ </html>
+ HTML
+
+ before { stub_request(:get, url).to_return(status: 200, body: html) }
+
+ it "uses the event description and exposes event display data" do
+ expect(data).to include(
+ description: "Meet the community",
+ is_event: true,
+ event_all_day: false,
+ event_date_day: "22",
+ event_date_month: "Oct",
+ event_onebox_classes: "discourse-event-onebox",
+ event_starts_at: "2026-10-22T09:00:00.000-04:00",
+ event_ends_at: "2026-10-22T10:00:00.000-04:00",
+ event_timezone: "UTC-04:00",
+ )
+ end
+
+ it "renders event data for client-side localization" do
+ html = onebox.to_html
+
+ expect(html).to include('class="discourse-event-onebox"')
+ expect(html).not_to include("--banner-image")
+ expect(html).to include('data-event-starts-at="2026-10-22T09:00:00.000-04:00"')
+ expect(html).to include('class="discourse-event-onebox__date"')
+ expect(html).to include("Meet the community")
+ expect(html).to include("Reading time: 1 min 🕑")
+ expect(html).to include("Likes: 2 ❤")
+ expect(html).not_to include("The ordinary topic excerpt")
+ end
+
+ context "without an event description" do
+ let(:event_description_json) { "" }
+
+ it "does not fall back to the topic excerpt" do
+ expect(data[:description]).to be_nil
+ expect(onebox.to_html).not_to include('class="discourse-event-onebox__description"')
+ expect(onebox.to_html).not_to include("The ordinary topic excerpt")
+ end
+ end
+
+ it "uses the event's image rather than the page's" do
+ expect(data[:image]).to eq("https://example.com/event.png")
+ expect(onebox.to_html).not_to include("site-logo.png")
+ end
+
+ context "without an event image" do
+ let(:event_image_json) { "" }
+
+ it "does not fall back to the page's image" do
+ expect(data[:image]).to be_nil
+ expect(onebox.to_html).not_to include("<img")
+ end
+ end
+
+ context "with a square event image" do
+ let(:event_image_json) { image_object_json(500, 500) }
+
+ it "letterboxes the image in the banner layout" do
+ expect(data[:event_onebox_classes]).to eq(
+ "discourse-event-onebox --banner-image --letterboxed-image",
+ )
+ expect(onebox.to_html).to include("--banner-image --letterboxed-image")
+ end
+ end
+
+ context "with a portrait event image" do
+ let(:event_image_json) { image_object_json(800, 1200) }
+
+ it "uses the portrait image layout" do
+ expect(data[:event_onebox_classes]).to eq("discourse-event-onebox --portrait-image")
+ expect(onebox.to_html).to include("--portrait-image")
+ end
+ end
+
+ context "with a 4:3 event image" do
+ let(:event_image_json) { image_object_json(800, 600) }
+
+ it "uses the banner image layout" do
+ expect(data[:event_onebox_classes]).to eq("discourse-event-onebox --banner-image")
+ end
+ end
+
+ context "with a landscape event image" do
+ let(:event_image_json) { image_object_json(690, 362) }
+
+ it "uses the banner image layout" do
+ expect(data[:event_onebox_classes]).to eq("discourse-event-onebox --banner-image")
+ expect(onebox.to_html).to include("--banner-image")
+ expect(onebox.to_html).not_to include("--letterboxed-image")
+ end
+ end
+
+ context "with an event image wider than 2:1" do
+ let(:event_image_json) { image_object_json(1500, 500) }
+
+ it "letterboxes the image in the banner layout" do
+ expect(data[:event_onebox_classes]).to eq(
+ "discourse-event-onebox --banner-image --letterboxed-image",
+ )
+ end
+ end
+
+ context "with image dimensions given as QuantitativeValues" do
+ let(:event_image_json) { <<~JSON }
+ "image": {
+ "@type": "ImageObject",
+ "url": "https://example.com/event.png",
+ "width": { "@type": "QuantitativeValue", "value": 800 },
+ "height": { "@type": "QuantitativeValue", "value": 1200 }
+ },
+ JSON
+
+ it "reads the dimensions" do
+ expect(data[:event_onebox_classes]).to eq("discourse-event-onebox --portrait-image")
+ end
+ end
+
+ def image_object_json(width, height)
+ <<~JSON
+ "image": {
+ "@type": "ImageObject",
+ "url": "https://example.com/event.png",
+ "width": #{width},
+ "height": #{height}
+ },
+ JSON
+ end
+ end
end
end
diff --git a/spec/lib/onebox/json_ld_spec.rb b/spec/lib/onebox/json_ld_spec.rb
index 15ce2b522fb..5a69c7732b0 100644
--- a/spec/lib/onebox/json_ld_spec.rb
+++ b/spec/lib/onebox/json_ld_spec.rb
@@ -27,7 +27,7 @@ RSpec.describe Onebox::JsonLd do
expect(json_ld.data).to eq({})
end
- it "returns an empty hash if the type of JSON-LD data is not Movie" do
+ it "returns an empty hash if the JSON-LD type is unsupported" do
doc =
Nokogiri.HTML(
"<script type=\"application/ld+json\">{\"@type\":\"Something Else\",\"aggregateRating\":{\"@type\":\"AggregateRating\",\"ratingCount\":806928,\"bestRating\":10,\"worstRating\":1}}</script>",
@@ -36,6 +36,80 @@ RSpec.describe Onebox::JsonLd do
expect(json_ld.data).to eq({})
end
+ it "normalizes Event data" do
+ doc = Nokogiri.HTML(<<~HTML)
+ <script type="application/ld+json">
+ {
+ "@context": "https://schema.org",
+ "@type": "Event",
+ "description": "Meet the community",
+ "startDate": "2026-10-22T09:00:00-04:00",
+ "endDate": "2026-10-22T10:00:00-04:00"
+ }
+ </script>
+ HTML
+
+ expect(described_class.new(doc).data).to eq(
+ event_starts_at: "2026-10-22T09:00:00-04:00",
+ event_ends_at: "2026-10-22T10:00:00-04:00",
+ event_all_day: "false",
+ event_description: "Meet the community",
+ )
+ end
+
+ it "reads an Event image given as an ImageObject" do
+ doc = Nokogiri.HTML(<<~HTML)
+ <script type="application/ld+json">
+ {
+ "@type": "Event",
+ "startDate": "2026-10-22",
+ "image": { "@type": "ImageObject", "url": "https://example.com/event.png", "width": 800, "height": 600 }
+ }
+ </script>
+ HTML
+
+ expect(described_class.new(doc).data).to include(
+ event_image: "https://example.com/event.png",
+ event_image_width: "800",
+ event_image_height: "600",
+ )
+ end
+
+ it "reads the first of several Event images given as URLs" do
+ doc = Nokogiri.HTML(<<~HTML)
+ <script type="application/ld+json">
+ {
+ "@type": "Event",
+ "startDate": "2026-10-22",
+ "image": ["https://example.com/first.png", "https://example.com/second.png"]
+ }
+ </script>
+ HTML
+
+ expect(described_class.new(doc).data).to include(event_image: "https://example.com/first.png")
+ expect(described_class.new(doc).data).not_to have_key(:event_image_width)
+ end
+
+ it "recognizes date-only Events as all-day" do
+ doc = Nokogiri.HTML(<<~HTML)
+ <script type="application/ld+json">
+ { "@context": "https://schema.org", "@type": "Event", "startDate": "2026-10-22" }
+ </script>
+ HTML
+
+ expect(described_class.new(doc).data).to include(event_all_day: "true")
+ end
+
+ it "does not treat invalid Event dates as all-day" do
+ doc = Nokogiri.HTML(<<~HTML)
+ <script type="application/ld+json">
+ { "@context": "https://schema.org", "@type": "Event", "startDate": "not-a-date" }
+ </script>
+ HTML
+
+ expect(described_class.new(doc).data).to include(event_all_day: "false")
+ end
+
it "correctly normalizes the properties" do
doc = Nokogiri.HTML(onebox_response("imdb"))
json_ld = described_class.new(doc)