A platform for community discussion. Free, open, simple.
UX: add recurrence info to event oneboxes (#45321)
Kris9e2f64043cb5
diff --git a/app/assets/stylesheets/common/base/onebox.scss b/app/assets/stylesheets/common/base/onebox.scssindex 005aeda114d..094050a1dc8 100644--- a/app/assets/stylesheets/common/base/onebox.scss+++ b/app/assets/stylesheets/common/base/onebox.scss@@ -426,11 +426,11 @@ aside.onebox:has(.discourse-event-onebox) {min-width: 0;}- &__time {+ &__time,+ &__recurrence {align-items: center;display: flex;gap: var(--space-2);- margin-block: var(--space-3) var(--space-1);.d-icon {color: var(--primary-high);@@ -439,6 +439,14 @@ aside.onebox:has(.discourse-event-onebox) {}}+ &__time {+ margin-block: var(--space-3) var(--space-1);+ }++ &__recurrence {+ margin-block-end: var(--space-1);+ }+&__description {align-items: flex-start;display: flex;@@ -488,6 +496,7 @@ aside.onebox:has(.discourse-event-onebox) {grid-template:"image date title" auto"image time time" auto+ "image recurrence recurrence" auto"image description description" auto"image . ." 1fr / 8rem auto minmax(0, 1fr);row-gap: 0;@@ -520,6 +529,10 @@ aside.onebox:has(.discourse-event-onebox) {grid-area: time;}+ .discourse-event-onebox__recurrence {+ grid-area: recurrence;+ }+.discourse-event-onebox__description {grid-area: description;}@@ -532,6 +545,7 @@ aside.onebox:has(.discourse-event-onebox) {"image image" auto"date title" auto". time" auto+ ". recurrence" auto". description" auto / auto minmax(0, 1fr);.discourse-event-onebox__image.thumbnail {diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex c6085b83b9e..a5106d03e58 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -6404,6 +6404,28 @@ en:onebox:discourse:event_all_day: "All day"+ recurrence:+ every_day: "Every day"+ every_weekday: "Every weekday"+ every_week: "Every %{weekday}"+ every_two_weeks: "Every other %{weekday}"+ every_four_weeks: "Every 4 weeks on %{weekday}"+ every_month: "The %{ordinal} %{weekday} of every month"+ until: "%{recurrence} until %{date}"+ ordinals:+ first: "first"+ second: "second"+ third: "third"+ fourth: "fourth"+ last: "last"+ weekdays:+ sunday: "Sunday"+ monday: "Monday"+ tuesday: "Tuesday"+ wednesday: "Wednesday"+ thursday: "Thursday"+ friday: "Friday"+ saturday: "Saturday"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.rbindex e2e6302206b..770e0246021 100644--- a/lib/onebox/engine/discourse_topic_onebox.rb+++ b/lib/onebox/engine/discourse_topic_onebox.rb@@ -9,6 +9,33 @@ module Oneboxmatches_regexp(%r{/t/.*(/\d+)?})+ WEEKDAYS = %w[sunday monday tuesday wednesday thursday friday saturday]+ WORKWEEK = %w[Monday Tuesday Wednesday Thursday Friday]+ WEEKLY_SCHEDULES = {+ "P1W" => ["every_week", 1],+ "P2W" => ["every_two_weeks", 2],+ "P4W" => ["every_four_weeks", 4],+ }+ MONTH_WEEK_ORDINALS = {+ "1" => "first",+ "2" => "second",+ "3" => "third",+ "4" => "fourth",+ "-1" => "last",+ }+ # Pages give the upcoming occurrence, so an older start isn't a live schedule+ MAX_SCHEDULE_AGE = 1.year++ def self.format_event_time(starts_at, ends_at = nil)+ time = starts_at.strftime("%-I:%M %p")+ time = "#{time} → #{ends_at.strftime("%-I:%M %p")}" if ends_at+ "#{time} (#{format_utc_offset(starts_at)})"+ end++ def self.format_utc_offset(time)+ time.utc_offset.zero? ? "UTC" : "UTC#{time.formatted_offset}"+ end+def layout@layout ||= Layout.new(event? ? "discoursetopic_with_event" : self.class.onebox_name, data)end@@ -29,6 +56,8 @@ module Oneboxevent_date_month: event_date&.strftime("%b"),event_description: event_description,event_ends_at: raw[:event_ends_at],+ event_recurrence: event_recurrence,+ event_rrule: event_rrule,event_onebox_classes: event_onebox_classes,event_starts_at: raw[:event_starts_at],event_time: event_time,@@ -113,16 +142,78 @@ module Oneboxreturn 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})"+ self.class.format_event_time(+ event_time_value(raw[:event_starts_at]),+ event_time_value(raw[:event_ends_at]),+ )rescue ArgumentErrornilend+ def event_recurrence+ return if (schedule = event_schedule).nil?++ label = I18n.t("onebox.discourse.recurrence.#{schedule[:key]}", **schedule[:options])+ return label if (until_date = event_repeat_until).blank?++ I18n.t(+ "onebox.discourse.recurrence.until",+ recurrence: label,+ date: until_date.strftime(I18n.t("datetime_formats.formats.date_only")),+ )+ end++ # Expressed as a recurrence rule so later occurrences can be found from the cooked onebox+ def event_rrule+ return if (schedule = event_schedule).nil?+ return schedule[:rule] if (until_date = event_repeat_until).blank?++ "#{schedule[:rule]};UNTIL=#{until_date.strftime("%Y%m%d")}T235959"+ end++ # Only the schedules that have a label are recognised, so the rule and label always agree+ def event_schedule+ return @event_schedule if defined?(@event_schedule)+ return @event_schedule = nil if !event? || (date = event_date).nil?+ return @event_schedule = nil if date < MAX_SCHEDULE_AGE.ago.to_date++ weekday = I18n.t("onebox.discourse.recurrence.weekdays.#{WEEKDAYS[date.wday]}")+ day = WEEKDAYS[date.wday][0, 2].upcase+ by_day = raw[:event_repeat_by_day].to_s.split(",")+ frequency = raw[:event_repeat_frequency]++ @event_schedule =+ case frequency+ when "P1D"+ if by_day.empty?+ { key: "every_day", options: {}, rule: "FREQ=DAILY" }+ elsif by_day.sort == WORKWEEK.sort+ { key: "every_weekday", options: {}, rule: "FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR" }+ end+ when *WEEKLY_SCHEDULES.keys+ key, interval = WEEKLY_SCHEDULES[frequency]+ { key:, options: { weekday: }, rule: "FREQ=WEEKLY;INTERVAL=#{interval};BYDAY=#{day}" }+ when "P1M"+ month_week = raw[:event_repeat_by_month_week]+ if (ordinal = MONTH_WEEK_ORDINALS[month_week])+ {+ key: "every_month",+ options: {+ weekday:,+ ordinal: I18n.t("onebox.discourse.recurrence.ordinals.#{ordinal}"),+ },+ rule: "FREQ=MONTHLY;BYDAY=#{month_week}#{day}",+ }+ end+ end+ end++ def event_repeat_until+ Date.iso8601(raw[:event_repeat_until].to_s) if raw[:event_repeat_until].present?+ rescue Date::Error+ nil+ end+def event_time_value(value)return if value.blank?@@ -131,9 +222,9 @@ module Oneboxdef event_timezonestarts_at = event_time_value(raw[:event_starts_at])- return "UTC" if starts_at.blank? || starts_at.utc_offset.zero?+ return "UTC" if starts_at.blank?- "UTC#{starts_at.formatted_offset}"+ self.class.format_utc_offset(starts_at)rescue ArgumentError"UTC"enddiff --git a/lib/onebox/json_ld.rb b/lib/onebox/json_ld.rbindex e8d2e143ec3..82d9a328e7b 100644--- a/lib/onebox/json_ld.rb+++ b/lib/onebox/json_ld.rb@@ -51,9 +51,25 @@ module Oneboxevent_image_width: image[:width],event_image_height: image[:height],}.compact,+ **event_schedule(json["eventSchedule"]),}end+ def event_schedule(value)+ value = value.first if value.is_a?(Array)+ return {} if !value.is_a?(Hash) || !value["repeatFrequency"].is_a?(String)++ {+ event_repeat_frequency: value["repeatFrequency"],+ # Days are DayOfWeek URLs like https://schema.org/Monday, though bare names are common+ event_repeat_by_day:+ Array.wrap(value["byDay"]).map { it.to_s.split("/").last }.join(",").presence,+ event_repeat_by_month_week: value["byMonthWeek"]&.to_s,+ event_repeat_until: value["endDate"]&.to_s,+ event_schedule_timezone: value["scheduleTimezone"]&.to_s,+ }.compact+ end+# Schema.org allows a URL, an ImageObject, or a list of eitherdef event_image(value)value = value.first if value.is_a?(Array)diff --git a/lib/onebox/templates/discoursetopic_with_event.mustache b/lib/onebox/templates/discoursetopic_with_event.mustacheindex 7bf127f4858..7f482d3626d 100644--- a/lib/onebox/templates/discoursetopic_with_event.mustache+++ b/lib/onebox/templates/discoursetopic_with_event.mustache@@ -1,6 +1,8 @@<div class="{{event_onebox_classes}}"data-event-all-day="{{event_all_day}}"data-event-ends-at="{{event_ends_at}}"+ data-event-rrule="{{event_rrule}}"+ data-event-schedule-timezone="{{event_schedule_timezone}}"data-event-starts-at="{{event_starts_at}}"data-event-timezone="{{event_timezone}}"><div class="discourse-event-onebox__media">@@ -45,6 +47,13 @@<span class="discourse-event-onebox__time-text">{{event_time}}</span></div>+ {{#event_recurrence}}+ <div class="discourse-event-onebox__recurrence">+ <svg class="fa d-icon d-icon-arrows-rotate svg-icon svg-string" xmlns="http://www.w3.org/2000/svg"><use href="#arrows-rotate" /></svg>+ <span class="discourse-event-onebox__recurrence-text">{{event_recurrence}}</span>+ </div>+ {{/event_recurrence}}+{{#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>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.rbindex c63a64d71e9..63b743c94f8 100644--- 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@@ -8,6 +8,7 @@# - 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+# - Recurring events describe their pattern with a Schedule, anchored on the current occurrence## Spec: https://schema.org/Event# Validator: https://validator.schema.org/@@ -37,9 +38,52 @@ class DiscourseEvents::Events::Action::GenerateSchemaJson < Service::ActionBase"location" => event_locations.one? ? event_locations.first : event_locations,"url" => topic.url,"image" => image,+ "eventSchedule" => schedule,}.compactend+ def schedule+ return if !event.recurring?++ # The recurrence rule is anchored on the original start, which sets the week of the month+ original_starts_at =+ if event.all_day+ event.original_starts_at.utc+ else+ event.original_starts_at.in_time_zone(event.rrule_timezone)+ end+ weekday = "https://schema.org/#{original_starts_at.strftime("%A")}"++ {+ "@type" => "Schedule",+ **schedule_pattern(original_starts_at, weekday),+ "endDate" => event.recurrence_until&.in_time_zone(event.rrule_timezone)&.strftime("%Y-%m-%d"),+ "scheduleTimezone" => (event.rrule_timezone if !event.all_day),+ }.compact+ end++ def schedule_pattern(starts_at, weekday)+ case event.recurrence+ when "every_day"+ { "repeatFrequency" => "P1D" }+ when "every_weekday"+ {+ "repeatFrequency" => "P1D",+ "byDay" => %w[Monday Tuesday Wednesday Thursday Friday].map { "https://schema.org/#{it}" },+ }+ when "every_two_weeks"+ { "repeatFrequency" => "P2W", "byDay" => weekday }+ when "every_four_weeks"+ { "repeatFrequency" => "P4W", "byDay" => weekday }+ when "every_month"+ # Mirrors the recurrence rule, where a fifth weekday is expressed as the last+ nth = ((starts_at.day - 1) / 7) + 1+ { "repeatFrequency" => "P1M", "byDay" => weekday, "byMonthWeek" => nth == 5 ? -1 : nth }+ else+ { "repeatFrequency" => "P1W", "byDay" => weekday }+ end+ end+def locationsevent_locations = []place = plain_text(event.location)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.gjsindex 3ce6c18e567..8eeb653b200 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@@ -102,11 +102,15 @@ 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.addTrackedPostProperties("event_oneboxes", "event_onebox_occurrences");api.decorateCookedElement((cooked, helper) => {- decorateEventOneboxes(cooked, timezone);+ decorateEventOneboxes(+ cooked,+ timezone,+ helper?.getModel()?.event_onebox_occurrences+ );if (cooked.classList.contains("d-editor-preview")) {_decorateEventPreview(api, cooked, helper);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.jsindex ce23246515f..1be119daa42 100644--- a/plugins/discourse-events/assets/javascripts/discourse/lib/decorate-event-oneboxes.js+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/decorate-event-oneboxes.js@@ -3,23 +3,42 @@ import { i18n } from "discourse-i18n";const HEX_COLOR = /^[0-9a-f]{6}$/i;-export default function decorateEventOneboxes(element, timezone) {+/**+ * @param {Element} element+ * @param {string} timezone - the viewer's timezone+ * @param {Object} [occurrences] - current occurrences of recurring events, keyed by+ * onebox source URL, for oneboxes whose cooked occurrence has passed+ */+export default function decorateEventOneboxes(+ element,+ timezone,+ occurrences = {}+) {element.querySelectorAll(".discourse-event-onebox").forEach((onebox) => {applyImageStyles(onebox);+ const src = onebox.closest("aside.onebox")?.dataset.oneboxSrc;+ const occurrence = (src && occurrences?.[src]) || {+ starts_at: onebox.dataset.eventStartsAt,+ ends_at: onebox.dataset.eventEndsAt,+ };+const allDay = onebox.dataset.eventAllDay === "true";- const startsAt = parseDate(onebox.dataset.eventStartsAt, {- allDay,- timezone,- });+ let startsAt = parseDate(occurrence.starts_at, allDay);if (!startsAt?.isValid()) {return;}- const endsAt = parseDate(onebox.dataset.eventEndsAt, {- allDay,- timezone,- });+ let endsAt = parseDate(occurrence.ends_at, allDay);++ onebox+ .querySelector(".discourse-event-onebox__date")+ ?.setAttribute("datetime", occurrence.starts_at);++ if (!allDay) {+ startsAt = startsAt.tz(timezone);+ endsAt = endsAt?.tz(timezone);+ }onebox.querySelector(".discourse-event-onebox__month").textContent =startsAt.format("MMM");@@ -83,12 +102,10 @@ function timezoneLabel(date, timezone) {return timezone.split("/").pop().replaceAll("_", " ");}-function parseDate(value, { allDay, timezone }) {+function parseDate(value, allDay) {if (!value) {return null;}- return allDay- ? moment(value, "YYYY-MM-DD", true)- : moment.parseZone(value).tz(timezone);+ return allDay ? moment(value, "YYYY-MM-DD", true) : moment.parseZone(value);}diff --git a/plugins/discourse-events/lib/discourse_events/events/onebox_occurrence.rb b/plugins/discourse-events/lib/discourse_events/events/onebox_occurrence.rbnew file mode 100644index 00000000000..d246b26bbfd--- /dev/null+++ b/plugins/discourse-events/lib/discourse_events/events/onebox_occurrence.rb@@ -0,0 +1,141 @@+# frozen_string_literal: true++require "rrule"++module DiscourseEvents+ module Events+ # Cooked event oneboxes keep whichever occurrence was next when they were fetched.+ # This finds the occurrence that's current now from the recurrence rule they carry,+ # so posts and emails don't show a date that has already passed.+ class OneboxOccurrence+ # The longest gap between occurrences, for monthly events, is five weeks+ MAX_GAP = 5.weeks++ # Only the rules the topic onebox writes, as others (e.g. with COUNT) can't skip ahead safely+ DAY = "(SU|MO|TU|WE|TH|FR|SA)"+ SUPPORTED_RRULE =+ /\AFREQ=(DAILY(;BYDAY=MO,TU,WE,TH,FR)?|WEEKLY;INTERVAL=[124];BYDAY=#{DAY}|MONTHLY;BYDAY=(-1|[1-4])#{DAY})(;UNTIL=\d{8}T\d{6})?\z/++ # Returns { onebox source URL => { starts_at:, ends_at: } } for oneboxes that have moved on+ def self.for_cooked(cooked)+ return {} if !cooked&.include?("discourse-event-onebox")++ Nokogiri::HTML5+ .fragment(cooked)+ .css(".discourse-event-onebox")+ .each_with_object({}) do |node, occurrences|+ src = node.ancestors("aside.onebox").first&.[]("data-onebox-src")+ occurrence = new(node).current if src.present?+ occurrences[src] = occurrence if occurrence+ end+ end++ def initialize(node, now: Time.current)+ @node = node+ @now = now+ end++ def current+ return if !SUPPORTED_RRULE.match?(@node["data-event-rrule"].to_s)++ # The earliest start whose occurrence hasn't finished yet+ earliest = @now - duration - (all_day? ? 1.day : 0) + 1.second++ finishes = repeat_until+ rule = rrule(anchor: finishes ? [earliest, finishes - MAX_GAP].min : earliest)++ # `between` rather than `from`, which returns nothing for rules with an interval+ upcoming = rule.between(earliest, earliest + MAX_GAP).first || final_occurrence(rule)+ return if upcoming.nil? || upcoming <= starts_at++ { starts_at: serialize(upcoming), ends_at: (serialize(upcoming + duration) if ends_at) }+ rescue ArgumentError, ::RRule::InvalidRRule+ nil+ end++ def apply!+ return if (occurrence = current).nil?++ starts_at = parse_time(occurrence[:starts_at])++ @node["data-event-starts-at"] = occurrence[:starts_at]+ @node["data-event-ends-at"] = occurrence[:ends_at].to_s+ @node.at_css(".discourse-event-onebox__date")&.[]=("datetime", occurrence[:starts_at])+ @node.at_css(".discourse-event-onebox__month")&.content = starts_at.strftime("%b")+ @node.at_css(".discourse-event-onebox__day")&.content = starts_at.strftime("%-d")++ if !all_day?+ ends_at = parse_time(occurrence[:ends_at]) if occurrence[:ends_at]+ @node.at_css(".discourse-event-onebox__time-text")&.content =+ Onebox::Engine::DiscourseTopicOnebox.format_event_time(starts_at, ends_at)+ end+ end++ private++ # Rules with an interval are stepped through from their start, which is untrusted and can be+ # ages ago, so it's moved up to just before `anchor` by whole periods, keeping the same series.+ # One period is held back so a DST change can't push the start past `anchor`.+ def rrule(anchor:)+ pattern = @node["data-event-rrule"]+ period = [pattern[/INTERVAL=(\d)/, 1].to_i, 1].max.weeks+ periods = [((anchor - starts_at) / period.to_i).floor - 1, 0].max++ ::RRule::Rule.new(+ pattern,+ dtstart: starts_at + (periods * period),+ tzid: timezone.tzinfo.name,+ )+ end++ def final_occurrence(rule)+ return if (finishes = repeat_until).nil?++ rule.between(finishes - MAX_GAP, finishes).last+ end++ def repeat_until+ value = @node["data-event-rrule"].to_s[/UNTIL=(\d{8}T\d{6})/, 1]+ timezone.strptime(value, "%Y%m%dT%H%M%S") if value+ end++ def all_day?+ @node["data-event-all-day"] == "true"+ end++ # Stepping in the event's own timezone keeps its wall-clock time across DST changes+ def timezone+ @timezone ||=+ (!all_day? && ActiveSupport::TimeZone[@node["data-event-schedule-timezone"].to_s]) ||+ ActiveSupport::TimeZone["UTC"]+ end++ def starts_at+ @starts_at ||= parse_time(@node["data-event-starts-at"])+ end++ def ends_at+ return @ends_at if defined?(@ends_at)++ value = @node["data-event-ends-at"]+ @ends_at = (parse_time(value) if value.present?)+ end++ def duration+ ends_at ? ends_at - starts_at : 0+ end++ def parse_time(value)+ if all_day?+ timezone.parse(Date.iso8601(value).iso8601)+ else+ Time.iso8601(value).in_time_zone(timezone)+ end+ end++ def serialize(time)+ all_day? ? time.strftime("%Y-%m-%d") : time.iso8601(3)+ end+ end+ end+enddiff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rbindex 7b9b0d52def..8a6c38c5770 100644--- a/plugins/discourse-events/plugin.rb+++ b/plugins/discourse-events/plugin.rb@@ -320,6 +320,7 @@ after_initialize dorequire_relative "lib/discourse_events/events/excerpt"require_relative "lib/discourse_events/events/finder"require_relative "lib/discourse_events/events/onebox_data"+ require_relative "lib/discourse_events/events/onebox_occurrence"require_relative "lib/discourse_events/events/parser"require_relative "lib/discourse_events/events/validator"require_relative "lib/discourse_events/events/export_csv_controller_extension"@@ -459,6 +460,17 @@ after_initialize doendend+ add_to_serializer(+ :post,+ :event_onebox_occurrences,+ include_condition: -> do+ SiteSetting.discourse_post_event_enabled && event_onebox_occurrences.present?+ end,+ ) do+ @event_onebox_occurrences ||=+ DiscourseEvents::Events::OneboxOccurrence.for_cooked(object.cooked)+ end+sync_event_from_post = ->(post) doDiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id }) do |result|on_failure do@@ -833,6 +845,10 @@ after_initialize doon(:reduce_cooked) do |fragment, post|if SiteSetting.discourse_post_event_enabled+ fragment+ .css(".discourse-event-onebox")+ .each { |node| DiscourseEvents::Events::OneboxOccurrence.new(node).apply! }+fragment.css(".discourse-post-event").each do |event_node|diff --git a/plugins/discourse-events/spec/lib/discourse_events/events/onebox_occurrence_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/onebox_occurrence_spec.rbnew file mode 100644index 00000000000..948993ac8bf--- /dev/null+++ b/plugins/discourse-events/spec/lib/discourse_events/events/onebox_occurrence_spec.rb@@ -0,0 +1,248 @@+# frozen_string_literal: true++RSpec.describe DiscourseEvents::Events::OneboxOccurrence do+ def onebox_html(+ starts_at:,+ ends_at: nil,+ all_day: false,+ src: "https://other.example.com/t/1",+ rrule: nil,+ timezone: "America/New_York"+ )+ <<~HTML+ <aside class="onebox discoursetopic_with_event" data-onebox-src="#{src}">+ <div class="discourse-event-onebox"+ data-event-all-day="#{all_day}"+ data-event-starts-at="#{starts_at}"+ data-event-ends-at="#{ends_at}"+ data-event-rrule="#{rrule}"+ data-event-schedule-timezone="#{timezone}">+ <time class="discourse-event-onebox__date" datetime="#{starts_at}">+ <span class="discourse-event-onebox__month">Oct</span>+ <span class="discourse-event-onebox__day">22</span>+ </time>+ <span class="discourse-event-onebox__time-text">9:00 AM → 10:00 AM (UTC-04:00)</span>+ </div>+ </aside>+ HTML+ end++ def current(**options)+ node = Nokogiri::HTML5.fragment(onebox_html(**options)).at_css(".discourse-event-onebox")+ described_class.new(node).current+ end++ let(:weekly) do+ {+ starts_at: "2026-10-22T09:00:00.000-04:00",+ ends_at: "2026-10-22T10:00:00.000-04:00",+ rrule: "FREQ=WEEKLY;INTERVAL=1;BYDAY=TH",+ }+ end++ describe "#current" do+ it "moves on to the upcoming occurrence at the same wall-clock time across DST" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(current(**weekly)).to eq(+ starts_at: "2026-11-12T09:00:00.000-05:00",+ ends_at: "2026-11-12T10:00:00.000-05:00",+ )+ end++ it "keeps an occurrence that is still underway" do+ freeze_time Time.utc(2026, 10, 22, 13, 30)++ expect(current(**weekly)).to be_nil+ end++ it "stops at the final occurrence of the series" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(+ current(**weekly, rrule: "FREQ=WEEKLY;INTERVAL=1;BYDAY=TH;UNTIL=20261101T235959"),+ ).to include(starts_at: "2026-10-29T09:00:00.000-04:00")+ end++ it "keeps the week of the month for a monthly event" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(+ current(starts_at: "2026-10-29T09:00:00.000-04:00", rrule: "FREQ=MONTHLY;BYDAY=-1TH"),+ ).to include(starts_at: "2026-11-26T09:00:00.000-05:00")+ end++ it "skips weekends for a weekday event" do+ freeze_time Time.utc(2026, 10, 24, 12)++ expect(+ current(+ starts_at: "2026-10-23T09:00:00.000-04:00",+ rrule: "FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR",+ ),+ ).to include(starts_at: "2026-10-26T09:00:00.000-04:00")+ end++ it "keeps alternate weeks for a fortnightly event" do+ freeze_time Time.utc(2027, 6, 1, 12)++ expect(current(**weekly, rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=TH")).to include(+ starts_at: "2027-06-03T09:00:00.000-04:00",+ )+ end++ it "catches up on a daily event fetched years ago" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(current(starts_at: "2020-01-01T09:00:00.000-05:00", rrule: "FREQ=DAILY")).to include(+ starts_at: "2026-11-10T09:00:00.000-05:00",+ )+ end++ it "skips ahead from an ancient start rather than stepping through every occurrence" do+ freeze_time Time.utc(2026, 11, 10, 12)+ dtstarts = []+ allow(RRule::Rule).to receive(:new).and_wrap_original do |original, pattern, **options|+ dtstarts << options[:dtstart]+ original.call(pattern, **options)+ end++ expect(+ current(+ starts_at: "1000-01-01T09:00:00.000+00:00",+ rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=WE",+ timezone: "UTC",+ ),+ ).to include(starts_at: "2026-11-18T09:00:00.000Z")+ expect(dtstarts).to all(be > Time.utc(2026, 9, 1))+ end++ it "skips ahead to the final occurrence of a series that ended long ago" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(+ current(+ starts_at: "1000-01-01T09:00:00.000+00:00",+ rrule: "FREQ=WEEKLY;INTERVAL=4;BYDAY=WE;UNTIL=20200101T235959",+ timezone: "UTC",+ ),+ ).to include(starts_at: "2019-12-25T09:00:00.000Z")+ end++ it "ignores rules the onebox doesn't write" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(current(**weekly, rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=TH;COUNT=100000")).to be_nil+ expect(current(**weekly, rrule: "FREQ=SECONDLY")).to be_nil+ end++ it "moves an all-day event by whole days once its day is over" do+ freeze_time Time.utc(2026, 10, 23, 12)++ expect(+ current(+ all_day: true,+ starts_at: "2026-10-22",+ ends_at: "2026-10-22",+ rrule: "FREQ=WEEKLY;INTERVAL=1;BYDAY=TH",+ timezone: "",+ ),+ ).to eq(starts_at: "2026-10-29", ends_at: "2026-10-29")+ end++ it "ignores a malformed rule" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(current(**weekly, rrule: "FREQ=SOMETIMES")).to be_nil+ end++ it "ignores one-off events" do+ freeze_time Time.utc(2026, 11, 10, 12)++ expect(current(**weekly, rrule: "")).to be_nil+ end+ end++ describe ".for_cooked" do+ it "keys the occurrences that have moved on by onebox source" do+ freeze_time Time.utc(2026, 11, 10, 12)+ cooked =+ onebox_html(**weekly) + onebox_html(**weekly, rrule: "", src: "https://one-off.example.com")++ expect(described_class.for_cooked(cooked)).to eq(+ "https://other.example.com/t/1" => {+ starts_at: "2026-11-12T09:00:00.000-05:00",+ ends_at: "2026-11-12T10:00:00.000-05:00",+ },+ )+ end++ it "skips cooked content without event oneboxes" do+ allow(Nokogiri::HTML5).to receive(:fragment).and_call_original++ expect(described_class.for_cooked("<p>Hello</p>")).to eq({})+ expect(Nokogiri::HTML5).not_to have_received(:fragment)+ end+ end++ describe "#apply!" do+ it "rewrites the onebox to show the upcoming occurrence" do+ freeze_time Time.utc(2026, 11, 10, 12)+ fragment = Nokogiri::HTML5.fragment(onebox_html(**weekly))+ described_class.new(fragment.at_css(".discourse-event-onebox")).apply!++ expect(fragment.at_css(".discourse-event-onebox__date")["datetime"]).to eq(+ "2026-11-12T09:00:00.000-05:00",+ )+ expect(fragment.at_css(".discourse-event-onebox__month").text).to eq("Nov")+ expect(fragment.at_css(".discourse-event-onebox__day").text).to eq("12")+ expect(fragment.at_css(".discourse-event-onebox__time-text").text).to eq(+ "9:00 AM → 10:00 AM (UTC-05:00)",+ )+ end+ end++ describe "in the post serializer" do+ fab!(:post)++ before do+ SiteSetting.discourse_events_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ end++ it "includes the occurrences that have moved on" do+ freeze_time Time.utc(2026, 11, 10, 12)+ post.update_columns(cooked: onebox_html(**weekly))++ json = PostSerializer.new(post, scope: Guardian.new, root: false).as_json++ expect(json[:event_onebox_occurrences]).to eq(+ "https://other.example.com/t/1" => {+ starts_at: "2026-11-12T09:00:00.000-05:00",+ ends_at: "2026-11-12T10:00:00.000-05:00",+ },+ )+ end++ it "omits them for posts without event oneboxes" do+ json = PostSerializer.new(post, scope: Guardian.new, root: false).as_json++ expect(json).not_to have_key(:event_onebox_occurrences)+ end+ end++ describe "in emails" do+ before do+ SiteSetting.discourse_events_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ end++ it "shows the upcoming occurrence" do+ freeze_time Time.utc(2026, 11, 10, 12)++ html = PrettyText.format_for_email(onebox_html(**weekly))++ expect(html).to include('<span class="discourse-event-onebox__day">12</span>')+ end+ end+enddiff --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.rbindex c68ee173a67..5190228c478 100644--- 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@@ -198,5 +198,87 @@ RSpec.describe DiscourseEvents::Events::Action::GenerateSchemaJson doexpect(schema).not_to have_key("image")endend++ it "omits the schedule for a one-off event" do+ expect(schema).not_to have_key("eventSchedule")+ end++ context "with a recurring event" do+ before { freeze_time Time.utc(2026, 10, 1) }++ it "describes a weekly recurrence on the event's local weekday" do+ # 01:00 UTC on Friday is still Thursday evening in New York+ event.update!(+ recurrence: "every_week",+ original_starts_at: Time.iso8601("2026-10-23T01:00:00Z"),+ original_ends_at: Time.iso8601("2026-10-23T02:00:00Z"),+ recurrence_until: Time.iso8601("2026-12-31T23:59:00-05:00"),+ )++ expect(schema["eventSchedule"]).to eq(+ "@type" => "Schedule",+ "repeatFrequency" => "P1W",+ "byDay" => "https://schema.org/Thursday",+ "endDate" => "2026-12-31",+ "scheduleTimezone" => "America/New_York",+ )+ end++ it "describes the weekdays of a weekday recurrence" do+ event.update!(recurrence: "every_weekday")++ expect(schema["eventSchedule"]).to include(+ "repeatFrequency" => "P1D",+ "byDay" =>+ %w[Monday Tuesday Wednesday Thursday Friday].map { "https://schema.org/#{it}" },+ )+ end++ it "describes the week of the month for a monthly recurrence" do+ event.update!(recurrence: "every_month")++ expect(schema["eventSchedule"]).to include(+ "repeatFrequency" => "P1M",+ "byDay" => "https://schema.org/Thursday",+ "byMonthWeek" => 4,+ )+ end++ it "describes a fifth weekday as the last of the month" do+ event.update!(+ recurrence: "every_month",+ original_starts_at: Time.iso8601("2026-10-29T13:00:00Z"),+ original_ends_at: Time.iso8601("2026-10-29T14:00:00Z"),+ )++ expect(schema["eventSchedule"]).to include("byMonthWeek" => -1)+ end++ it "takes the week of the month from the start of the series" do+ # The series runs on the last Thursday, even when the current one is also the fourth+ event.update!(+ recurrence: "every_month",+ original_starts_at: Time.iso8601("2026-10-29T13:00:00Z"),+ original_ends_at: Time.iso8601("2026-10-29T14:00:00Z"),+ )+ event.event_dates.create!(+ starts_at: Time.iso8601("2026-11-26T14:00:00Z"),+ ends_at: Time.iso8601("2026-11-26T15:00:00Z"),+ )++ expect(schema).to include("startDate" => "2026-11-26T09:00:00.000-05:00")+ expect(schema["eventSchedule"]).to include("byMonthWeek" => -1)+ end++ it "describes multi-week intervals" do+ event.update!(recurrence: "every_two_weeks")+ expect(schema["eventSchedule"]).to include("repeatFrequency" => "P2W")++ event.update!(recurrence: "every_four_weeks")+ expect(+ JSON.parse(described_class.call(topic:, first_post:, event:))["eventSchedule"],+ ).to include("repeatFrequency" => "P4W")+ end+ endendenddiff --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.jsindex aff1b6f482c..1c9dd844a8d 100644--- 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@@ -1,6 +1,8 @@import { module, test } from "qunit";import decorateEventOneboxes from "discourse/plugins/discourse-events/discourse/lib/decorate-event-oneboxes";+const ONEBOX_SRC = "https://other.example.com/t/community-hangout/123";+module("Unit | Lib | decorate-event-oneboxes", function () {test("localizes timed event oneboxes to the viewer's timezone", function (assert) {const element = buildOnebox({@@ -64,6 +66,52 @@ module("Unit | Lib | decorate-event-oneboxes", function () {.hasText("All day", "the event is identified as all day");});+ test("shows the current occurrence from the server", function (assert) {+ const element = buildOnebox({+ startsAt: "2026-10-22T09:00:00.000-04:00",+ endsAt: "2026-10-22T10:00:00.000-04:00",+ });++ decorateEventOneboxes(element, "America/New_York", {+ [ONEBOX_SRC]: {+ starts_at: "2026-11-12T09:00:00.000-05:00",+ ends_at: "2026-11-12T10:00:00.000-05:00",+ },+ });++ assert+ .dom(".discourse-event-onebox__month", element)+ .hasText("Nov", "the month follows the current occurrence");+ assert+ .dom(".discourse-event-onebox__day", element)+ .hasText("12", "the day follows the current occurrence");+ assert+ .dom(".discourse-event-onebox__date", element)+ .hasAttribute(+ "datetime",+ "2026-11-12T09:00:00.000-05:00",+ "the machine-readable date matches the visible one"+ );+ assert+ .dom(".discourse-event-onebox__time-text", element)+ .hasText("9:00 AM → 10:00 AM (EST)", "the time is localized");+ });++ test("keeps the cooked occurrence without server data", function (assert) {+ const element = buildOnebox({+ startsAt: "2026-10-22T09:00:00.000-04:00",+ });++ decorateEventOneboxes(element, "America/New_York");++ assert+ .dom(".discourse-event-onebox__day", element)+ .hasText("22", "the cooked occurrence is shown");+ assert+ .dom(".discourse-event-onebox__date", element)+ .hasAttribute("datetime", "2026-10-22T09:00:00.000-04:00");+ });+test("exposes the image's dominant color for the letterbox", function (assert) {const element = buildOnebox({dominantColor: "2A292A",@@ -132,21 +180,25 @@ function buildOnebox({}) {const element = document.createElement("div");element.innerHTML = `+ <aside class="onebox" data-onebox-src="${ONEBOX_SRC}"><divclass="discourse-event-onebox"data-event-all-day="${allDay}"data-event-starts-at="${startsAt}"- data-event-ends-at="${endsAt}"+ 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>+ <time class="discourse-event-onebox__date" datetime="${startsAt}">+ <span class="discourse-event-onebox__month"></span>+ <span class="discourse-event-onebox__day"></span>+ </time><span class="discourse-event-onebox__time-text"></span></div>+ </aside>`;return element;}diff --git a/spec/lib/onebox/engine/discourse_topic_onebox_spec.rb b/spec/lib/onebox/engine/discourse_topic_onebox_spec.rbindex d717a842761..3c17ec309d8 100644--- a/spec/lib/onebox/engine/discourse_topic_onebox_spec.rb+++ b/spec/lib/onebox/engine/discourse_topic_onebox_spec.rb@@ -52,6 +52,7 @@ RSpec.describe Onebox::Engine::DiscourseTopicOnebox dolet(: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(:event_schedule_json) { "" }let(:html) { <<~HTML }<html><head>@@ -73,6 +74,7 @@ RSpec.describe Onebox::Engine::DiscourseTopicOnebox do"name": "Community hangout",#{event_description_json}#{event_image_json}+ #{event_schedule_json}"startDate": "2026-10-22T09:00:00.000-04:00","endDate": "2026-10-22T10:00:00.000-04:00"}@@ -81,7 +83,10 @@ RSpec.describe Onebox::Engine::DiscourseTopicOnebox do</html>HTML- before { stub_request(:get, url).to_return(status: 200, body: html) }+ before do+ freeze_time Time.utc(2026, 10, 20, 12)+ stub_request(:get, url).to_return(status: 200, body: html)+ endit "uses the event description and exposes event display data" doexpect(data).to include(@@ -117,6 +122,81 @@ RSpec.describe Onebox::Engine::DiscourseTopicOnebox do)end+ it "does not render a recurrence for a one-off event" do+ expect(data[:event_recurrence]).to be_nil+ expect(onebox.to_html).not_to include("discourse-event-onebox__recurrence")+ end++ context "with a weekly schedule" do+ let(:event_schedule_json) { <<~JSON }+ "eventSchedule": {+ "@type": "Schedule",+ "repeatFrequency": "P1W",+ "byDay": "https://schema.org/Thursday",+ "endDate": "2026-12-31",+ "scheduleTimezone": "America/New_York"+ },+ JSON++ it "labels the recurrence and exposes it as a rule for finding later occurrences" do+ html = onebox.to_html++ expect(data[:event_recurrence]).to eq("Every Thursday until December 31, 2026")+ expect(html).to include(+ '<span class="discourse-event-onebox__recurrence-text">Every Thursday until December 31, 2026</span>',+ )+ expect(html).to include(+ 'data-event-rrule="FREQ=WEEKLY;INTERVAL=1;BYDAY=TH;UNTIL=20261231T235959"',+ )+ expect(html).to include('data-event-schedule-timezone="America/New_York"')+ end+ end++ context "with a monthly schedule" do+ let(:event_schedule_json) { <<~JSON }+ "eventSchedule": { "repeatFrequency": "P1M", "byDay": "Thursday", "byMonthWeek": -1 },+ JSON++ it "labels the week of the month" do+ expect(data[:event_recurrence]).to eq("The last Thursday of every month")+ expect(data[:event_rrule]).to eq("FREQ=MONTHLY;BYDAY=-1TH")+ end+ end++ context "with a weekday schedule" do+ let(:event_schedule_json) { <<~JSON }+ "eventSchedule": {+ "repeatFrequency": "P1D",+ "byDay": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]+ },+ JSON++ it "labels the weekdays" do+ expect(data[:event_recurrence]).to eq("Every weekday")+ expect(data[:event_rrule]).to eq("FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR")+ end+ end++ context "with a schedule that started long ago" do+ let(:event_schedule_json) { %("eventSchedule": { "repeatFrequency": "P1D" },) }++ before { freeze_time Time.utc(2028, 1, 1) }++ it "does not keep the schedule" do+ expect(data[:event_recurrence]).to be_nil+ expect(data[:event_rrule]).to be_nil+ end+ end++ context "with an unsupported schedule" do+ let(:event_schedule_json) { %("eventSchedule": { "repeatFrequency": "P3W" },) }++ it "does not label the recurrence" do+ expect(data[:event_recurrence]).to be_nil+ expect(data[:event_rrule]).to be_nil+ end+ end+context "without an event description" dolet(:event_description_json) { "" }diff --git a/spec/lib/onebox/json_ld_spec.rb b/spec/lib/onebox/json_ld_spec.rbindex 5a69c7732b0..ca7f9b4f1da 100644--- a/spec/lib/onebox/json_ld_spec.rb+++ b/spec/lib/onebox/json_ld_spec.rb@@ -57,6 +57,43 @@ RSpec.describe Onebox::JsonLd do)end+ it "normalizes an Event's recurrence schedule" do+ doc = Nokogiri.HTML(<<~HTML)+ <script type="application/ld+json">+ {+ "@type": "Event",+ "startDate": "2026-10-22T09:00:00-04:00",+ "eventSchedule": {+ "@type": "Schedule",+ "repeatFrequency": "P1M",+ "byDay": ["https://schema.org/Thursday", "Friday"],+ "byMonthWeek": -1,+ "endDate": "2026-12-31",+ "scheduleTimezone": "America/New_York"+ }+ }+ </script>+ HTML++ expect(described_class.new(doc).data).to include(+ event_repeat_frequency: "P1M",+ event_repeat_by_day: "Thursday,Friday",+ event_repeat_by_month_week: "-1",+ event_repeat_until: "2026-12-31",+ event_schedule_timezone: "America/New_York",+ )+ end++ it "ignores a schedule without a repeat frequency" do+ doc = Nokogiri.HTML(<<~HTML)+ <script type="application/ld+json">+ { "@type": "Event", "startDate": "2026-10-22", "eventSchedule": { "byDay": "Monday" } }+ </script>+ HTML++ expect(described_class.new(doc).data.keys).not_to include(:event_repeat_by_day)+ end+it "reads an Event image given as an ImageObject" dodoc = Nokogiri.HTML(<<~HTML)<script type="application/ld+json">