Skip to content

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

FEATURE: render links to event topics as interactive cards (#40953)

Kris2f9f4e840180
diff --git a/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb b/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb
index b8509d8728f..d5050aa77ff 100644
--- a/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb
+++ b/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb
@@ -167,10 +167,12 @@ module DiscoursePostEvent
def filtered_events_params
params.permit(
:post_id,
+ :topic_id,
:category_id,
:include_subcategories,
:include_interested,
:include_ongoing,
+ :include_closed,
:limit,
:attending_user,
:before,
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs
index 9f87e582803..149873819e5 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs
@@ -376,10 +376,7 @@ export default class DiscoursePostEvent extends Component {
{{this.recurrenceLabel}}
</InfoSection>
{{/if}}
- <Location
- @location={{event.location}}
- @livestream={{event.livestream}}
- />
+ <Location @location={{event.location}} />
<Url @url={{event.url}} />
<ChatChannel @event={{event}} />
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/location.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/location.gjs
index 256b5133c77..e92550356d2 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/location.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/location.gjs
@@ -1,14 +1,21 @@
import Component from "@glimmer/component";
-import DCookText from "discourse/ui-kit/d-cook-text";
import dIcon from "discourse/ui-kit/helpers/d-icon";
-import { isLivestreamUrl } from "discourse/plugins/discourse-calendar/discourse/lib/raw-event-helper";
-// For livestream events the location is the stream URL: show it as a plain link
-// (the playable video renders separately at the bottom of the card) rather than
-// letting DCookText onebox it into a thumbnail here.
+const URL_SPLIT_REGEX = /(https?:\/\/\S+)/;
+const URL_TEST_REGEX = /^https?:\/\/\S+$/;
+
+// The location is a plain-text field, so it is deliberately not cooked as
+// markdown: cooking tags a bare URL as a onebox, and the composer's onebox
+// pass then embeds a full preview (e.g. a youtube player) inside the event
+// card. Bare URLs — including livestream URLs, whose playable video renders
+// separately at the bottom of the card — are rendered as plain links showing
+// the raw URL instead.
export default class DiscoursePostEventLocation extends Component {
- get showAsLink() {
- return this.args.livestream && isLivestreamUrl(this.args.location);
+ get segments() {
+ return (this.args.location || "")
+ .split(URL_SPLIT_REGEX)
+ .filter((part) => part.length)
+ .map((part) => ({ text: part, isUrl: URL_TEST_REGEX.test(part) }));
}
<template>
@@ -16,13 +23,19 @@ export default class DiscoursePostEventLocation extends Component {
<section class="event__section event-location">
{{dIcon "location-pin"}}
- {{#if this.showAsLink}}
- <a href={{@location}} target="_blank" rel="noopener noreferrer">
- {{@location}}
- </a>
- {{else}}
- <DCookText @rawText={{@location}} />
- {{/if}}
+ <span class="event-location__text">
+ {{~#each this.segments as |segment|~}}
+ {{~#if segment.isUrl~}}
+ <a
+ href={{segment.text}}
+ target="_blank"
+ rel="noopener noreferrer"
+ >{{segment.text}}</a>
+ {{~else~}}
+ {{segment.text}}
+ {{~/if~}}
+ {{~/each~}}
+ </span>
</section>
{{/if}}
</template>
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/onebox-node-view.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/onebox-node-view.gjs
new file mode 100644
index 00000000000..c19dfec5c0e
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/onebox-node-view.gjs
@@ -0,0 +1,67 @@
+import Component from "@glimmer/component";
+import { TOPIC_URL_REGEXP } from "discourse/lib/url";
+import DiscoursePostEventOneboxPreview from "./onebox-preview";
+
+// Returns the topic id for a topic-level / first-post onebox link, or null for
+// anything else (including a link to a specific reply, post number > 1) — the
+// event lives on the first post, so only that link should render the card.
+//
+// Only relative or same-origin URLs are considered: an absolute link to another
+// Discourse site (e.g. https://meta.discourse.org/t/foo/123) must keep its
+// external onebox rather than resolve to an unrelated local topic with id 123.
+export function topicIdFromUrl(url) {
+ if (!url) {
+ return null;
+ }
+
+ let path;
+ try {
+ const parsed = new URL(url, window.location.origin);
+ if (parsed.origin !== window.location.origin) {
+ return null;
+ }
+ path = parsed.pathname;
+ } catch {
+ return null;
+ }
+
+ const match = path.match(TOPIC_URL_REGEXP);
+ if (!match) {
+ return null;
+ }
+ if (match[3] && parseInt(match[3], 10) !== 1) {
+ return null;
+ }
+ return parseInt(match[2], 10);
+}
+
+// NodeView for the rich text editor's `onebox` node. For internal-topic oneboxes
+// (gated by shouldRender in the rich-editor extension) it renders the read-only
+// event card, falling back to the original onebox HTML for non-event topics.
+// Only the visual rendering is overridden — the node's attrs and markdown
+// serialization are untouched, so saving/copy-paste are unaffected.
+export default class DiscoursePostEventOneboxNodeView extends Component {
+ constructor() {
+ super(...arguments);
+ this.args.onSetup?.(this);
+ }
+
+ get topicId() {
+ return topicIdFromUrl(this.args.node.attrs.url);
+ }
+
+ selectNode() {
+ this.args.dom.classList.add("ProseMirror-selectednode");
+ }
+
+ deselectNode() {
+ this.args.dom.classList.remove("ProseMirror-selectednode");
+ }
+
+ <template>
+ <DiscoursePostEventOneboxPreview
+ @topicId={{this.topicId}}
+ @fallbackHtml={{@node.attrs.html}}
+ />
+ </template>
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/onebox-preview.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/onebox-preview.gjs
new file mode 100644
index 00000000000..3b198e8e9e2
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/onebox-preview.gjs
@@ -0,0 +1,71 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";
+import Dates from "./dates";
+import Location from "./location";
+
+export default class DiscoursePostEventOneboxPreview extends Component {
+ @service discoursePostEventApi;
+
+ @tracked event = null;
+
+ constructor() {
+ super(...arguments);
+ this.load();
+ }
+
+ async load() {
+ this.event = await this.discoursePostEventApi.cachedEventByTopicId(
+ this.args.topicId
+ );
+ }
+
+ get eventName() {
+ return this.event.name || this.event.post?.topic?.title;
+ }
+
+ get startsAtMonth() {
+ return this.#displayTime(this.event.startsAt).format("MMM");
+ }
+
+ get startsAtDay() {
+ return this.#displayTime(this.event.startsAt).format("D");
+ }
+
+ get fallback() {
+ return trustHTML(this.args.fallbackHtml);
+ }
+
+ #displayTime(time) {
+ if (this.event.allDay) {
+ return moment(time, "YYYY-MM-DD");
+ } else if (this.event.showLocalTime) {
+ return moment.tz(time, this.event.timezone || "UTC");
+ }
+ return moment.utc(time).tz(moment.tz.guess());
+ }
+
+ <template>
+ {{#if this.event}}
+ <div class="discourse-post-event discourse-post-event--preview">
+ <div class="discourse-post-event-widget">
+ <header class="event-header">
+ <div class="event-date">
+ <div class="month">{{this.startsAtMonth}}</div>
+ <div class="day">{{this.startsAtDay}}</div>
+ </div>
+ <div class="event-info">
+ <span class="name">{{dReplaceEmoji this.eventName}}</span>
+ </div>
+ </header>
+ <Dates @event={{this.event}} />
+ <Location @location={{this.event.location}} />
+ </div>
+ </div>
+ {{else}}
+ {{this.fallback}}
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
index 76ee09c97aa..6ecd16b9ce4 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
@@ -2,6 +2,7 @@ import { withPluginApi } from "discourse/lib/plugin-api";
import { i18n } from "discourse-i18n";
import ComposerEventEditor from "discourse/plugins/discourse-calendar/discourse/components/composer-event-editor";
import DiscoursePostEvent from "discourse/plugins/discourse-calendar/discourse/components/discourse-post-event";
+import DiscoursePostEventOneboxPreview from "discourse/plugins/discourse-calendar/discourse/components/discourse-post-event/onebox-preview";
import DiscoursePostEventEvent from "discourse/plugins/discourse-calendar/discourse/models/discourse-post-event-event";
const ComposerEventEditorTemplate = <template>
@@ -20,6 +21,69 @@ function _invalidEventPreview(eventContainer) {
);
}
+function _decorateEventOneboxes(cooked, helper) {
+ const oneboxes = helper.getModel()?.event_oneboxes;
+ if (!oneboxes) {
+ return;
+ }
+
+ cooked
+ .querySelectorAll(
+ "aside.quote[data-topic][data-post='1']:not([data-username])"
+ )
+ .forEach((aside) => {
+ const topicId = parseInt(aside.dataset.topic, 10);
+ const data = topicId && oneboxes[topicId];
+ if (!data) {
+ return;
+ }
+
+ const wrapper = document.createElement("div");
+ wrapper.className = "discourse-post-event-onebox";
+ aside.replaceWith(wrapper);
+
+ const event = DiscoursePostEventEvent.create(data);
+ helper.renderGlimmer(
+ wrapper,
+ <template>
+ <DiscoursePostEvent @event={{event}} @linkToPost={{true}} />
+ </template>
+ );
+ });
+}
+
+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.
+ cooked
+ .querySelectorAll(
+ "aside.quote[data-topic][data-post='1']:not([data-username])"
+ )
+ .forEach((aside) => {
+ const topicId = parseInt(aside.dataset.topic, 10);
+ if (!topicId) {
+ return;
+ }
+
+ const fallbackHtml = aside.outerHTML;
+ const wrapper = document.createElement("div");
+ wrapper.className = "discourse-post-event-onebox";
+ aside.replaceWith(wrapper);
+
+ helper.renderGlimmer(
+ wrapper,
+ <template>
+ <DiscoursePostEventOneboxPreview
+ @topicId={{topicId}}
+ @fallbackHtml={{fallbackHtml}}
+ />
+ </template>
+ );
+ });
+}
+
function _decorateEventPreview(api, cooked, helper) {
const eventContainers = cooked.querySelectorAll(".discourse-post-event");
@@ -35,14 +99,21 @@ function _decorateEventPreview(api, cooked, helper) {
}
function initializeDiscoursePostEventDecorator(api) {
+ api.addTrackedPostProperties("event_oneboxes");
+
api.decorateCookedElement(
(cooked, helper) => {
if (cooked.classList.contains("d-editor-preview")) {
_decorateEventPreview(api, cooked, helper);
+ if (helper) {
+ _decorateEventPreviewOneboxes(cooked, helper);
+ }
return;
}
if (helper) {
+ _decorateEventOneboxes(cooked, helper);
+
const post = helper.getModel();
if (!post?.event) {
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js b/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js
index a0c93ab10e4..be2e497968c 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js
@@ -1,5 +1,8 @@
import { withPluginApi } from "discourse/lib/plugin-api";
import { buildBBCodeAttrs } from "discourse/lib/text";
+import DiscoursePostEventOneboxNodeView, {
+ topicIdFromUrl,
+} from "../components/discourse-post-event/onebox-node-view";
import EventNodeView from "../components/event-node-view";
import { buildEventPreview } from "../lib/event-preview";
import {
@@ -35,6 +38,14 @@ const buildExtension = (siteSettings) => ({
event: {
component: EventNodeView,
},
+ // render event-topic oneboxes as the read-only event card; non-event topic
+ // oneboxes (shouldRender false) keep the default onebox rendering
+ ...(siteSettings.discourse_post_event_enabled && {
+ onebox: {
+ component: DiscoursePostEventOneboxNodeView,
+ shouldRender: ({ node }) => topicIdFromUrl(node.attrs.url) !== null,
+ },
+ }),
},
nodeSpec: {
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/services/discourse-post-event-api.js b/plugins/discourse-calendar/assets/javascripts/discourse/services/discourse-post-event-api.js
index e53dcfc1e91..d5a3fea16b7 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/services/discourse-post-event-api.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/services/discourse-post-event-api.js
@@ -13,11 +13,40 @@ import DiscoursePostEventInvitees from "discourse/plugins/discourse-calendar/dis
export default class DiscoursePostEventApi extends Service {
eventsPromise = null;
+ #eventsByTopicId = new Map();
+
+ // cached per topic id so the live composer preview (which re-cooks on every
+ // keystroke) only hits the endpoint once per linked topic; failed requests
+ // are evicted so a transient error doesn't hide the card until a full reload
+ cachedEventByTopicId(topicId) {
+ if (!this.#eventsByTopicId.has(topicId)) {
+ this.#eventsByTopicId.set(
+ topicId,
+ this.eventByTopicId(topicId).catch(() => {
+ this.#eventsByTopicId.delete(topicId);
+ return null;
+ })
+ );
+ }
+ return this.#eventsByTopicId.get(topicId);
+ }
+
async event(id, data = {}) {
const result = await this.#getRequest(`/events/${id}`, data);
return DiscoursePostEventEvent.create(result.event);
}
+ async eventByTopicId(topicId) {
+ const result = await this.#getRequest("/events", {
+ topic_id: topicId,
+ include_details: true,
+ include_closed: true,
+ limit: 1,
+ });
+ const eventData = (result.events || [])[0];
+ return eventData ? DiscoursePostEventEvent.create(eventData) : null;
+ }
+
async events(data = {}) {
if (this.eventsPromise) {
this.eventsPromise.abort();
diff --git a/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss b/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss
index caee5bbf42e..1e164706f0b 100644
--- a/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss
+++ b/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss
@@ -5,6 +5,23 @@ $show-interested: inherit;
display: none;
}
+.discourse-post-event-onebox {
+ display: block;
+ margin: var(--space-4) 0;
+}
+
+.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);
+ border: 1px solid var(--primary-300);
+ border-radius: var(--d-border-radius);
+ margin: var(--space-1) 0;
+}
+
+.composer-onebox-node {
+ white-space: normal;
+}
+
.discourse-post-event {
display: flex;
justify-content: center;
diff --git a/plugins/discourse-calendar/config/locales/server.en.yml b/plugins/discourse-calendar/config/locales/server.en.yml
index f09feff6863..beb69a17f80 100644
--- a/plugins/discourse-calendar/config/locales/server.en.yml
+++ b/plugins/discourse-calendar/config/locales/server.en.yml
@@ -113,6 +113,13 @@ en:
holiday_status:
description: "On holiday"
discourse_post_event:
+ event_excerpt:
+ summary: "📅 %{summary}"
+ separator: " · "
+ date_range: "%{from} → %{to}"
+ date_with_timezone: "%{date} (%{timezone})"
+ date_format: "%B %-d, %Y"
+ datetime_format: "%B %-d, %Y %-I:%M %p"
notifications:
before_event_reminder: "%{title} is about to start."
after_event_reminder: "%{title} has ended."
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/event_excerpt.rb b/plugins/discourse-calendar/lib/discourse_post_event/event_excerpt.rb
new file mode 100644
index 00000000000..958576a0457
--- /dev/null
+++ b/plugins/discourse-calendar/lib/discourse_post_event/event_excerpt.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+module DiscoursePostEvent
+ # Replaces each event node in an excerpt fragment (see PrettyText.excerpt)
+ # with a short plain-text summary — "📅 name · dates · location"
+ class EventExcerpt
+ def self.call(fragment, post: nil)
+ new(fragment, post: post).call
+ end
+
+ def initialize(fragment, post: nil)
+ @fragment = fragment
+ @topic_title = post&.topic&.title
+ end
+
+ def call
+ @fragment
+ .css(".discourse-post-event")
+ .each { |event_node| event_node.replace(CGI.escape_html(summary(event_node))) }
+ end
+
+ private
+
+ def summary(event_node)
+ event_name = event_node["data-name"].presence
+ location = event_node["data-location"].presence
+
+ parts = []
+ # only repeat the name when it differs from the topic title, which is
+ # already shown alongside the excerpt (e.g. in the topic onebox)
+ parts << event_name if event_name && event_name != @topic_title
+ parts << dates(event_node)
+ parts << location
+
+ summary = parts.compact.join(t("separator"))
+ summary.present? ? t("summary", summary: summary) : ""
+ end
+
+ def dates(event_node)
+ starts_at = event_node["data-start"]
+ return if starts_at.blank?
+
+ all_day = event_node["data-all-day"] == "true"
+ ends_at = event_node["data-end"]
+ timezone = event_node["data-timezone"] || "UTC"
+
+ dates = format_date(starts_at, all_day)
+ dates = t("date_range", from: dates, to: format_date(ends_at, all_day)) if ends_at.present?
+ dates = t("date_with_timezone", date: dates, timezone: timezone) unless all_day
+ dates
+ end
+
+ def format_date(value, all_day)
+ I18n.l(DateTime.parse(value), format: t(all_day ? "date_format" : "datetime_format"))
+ rescue StandardError
+ value
+ end
+
+ def t(key, **args)
+ I18n.t("discourse_post_event.event_excerpt.#{key}", **args)
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb b/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb
index 7cdf03d429d..f70c6746b03 100644
--- a/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb
+++ b/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb
@@ -5,8 +5,9 @@ module DiscoursePostEvent
def self.search(user, params = {})
guardian = Guardian.new(user)
- build_base_query(guardian, user)
+ build_base_query(guardian, user, params)
.then { |query| filter_by_post_id(query, params) }
+ .then { |query| filter_by_topic_id(query, params) }
.then { |query| filter_by_attending_user(query, params, guardian, user) }
.then { |query| filter_by_dates(query, params) }
.then { |query| filter_by_category(query, params) }
@@ -16,13 +17,14 @@ module DiscoursePostEvent
private
- def self.build_base_query(guardian, user)
+ def self.build_base_query(guardian, user, params)
topics = listable_topics(guardian)
pms = private_messages(user)
- DiscoursePostEvent::Event
- .visible
- .open
+ scope = DiscoursePostEvent::Event.visible
+ scope = scope.open if params[:include_closed].blank?
+
+ scope
.joins(post: :topic)
.merge(Post.secured(guardian))
.merge(topics.or(pms))
@@ -57,6 +59,11 @@ module DiscoursePostEvent
events.where(id: params[:post_id])
end
+ def self.filter_by_topic_id(events, params)
+ return events if params[:topic_id].blank?
+ events.where(topics: { id: params[:topic_id] })
+ end
+
def self.filter_by_attending_user(events, params, guardian, user)
return events if params[:attending_user].blank?
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/event_onebox_data.rb b/plugins/discourse-calendar/lib/discourse_post_event/event_onebox_data.rb
new file mode 100644
index 00000000000..f2f1aa421f6
--- /dev/null
+++ b/plugins/discourse-calendar/lib/discourse_post_event/event_onebox_data.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+module DiscoursePostEvent
+ # Builds, per post, the data needed to render an interactive event card for the
+ # internal topic oneboxes that point at an event topic. Mirrors
+ # ContentLocalization::OneboxLocalizer: batched via TopicLink and surfaced on
+ # the post serializer (see TopicView.on_preload + PostSerializer#event_oneboxes)
+ # so the client renders the card from inline data instead of fetching each
+ # event individually.
+ #
+ # Returns { source_post_id => { linked_topic_id => serialized_event } }. It's
+ # keyed by topic id so the client can match each `aside.quote[data-topic]`
+ # onebox to its event (mirrors how core's localized_oneboxes are matched).
+ class EventOneboxData
+ def self.build(posts:, guardian:)
+ new(posts:, guardian:).build
+ end
+
+ def initialize(posts:, guardian:)
+ @posts = posts
+ @guardian = guardian
+ end
+
+ def build
+ return {} if @posts.blank?
+
+ # cross-topic internal links (indexed lookup, no cooked scan). TopicLink
+ # does not record a topic that links itself, so same-topic oneboxes are
+ # detected from cooked further down.
+ links =
+ TopicLink
+ .where(post_id: @posts.map(&:id), internal: true, reflection: false)
+ .where.not(link_topic_id: nil)
+ .pluck(:post_id, :link_topic_id)
+ .uniq
+
+ # the topic being viewed, only when it's itself an event (cheap custom-field
+ # check, so non-event topic views do no extra work)
+ topic = @posts.first.topic
+ own_topic_id = topic&.event_starts_at ? topic.id : nil
+
+ topic_ids = links.map(&:last)
+ topic_ids << own_topic_id if own_topic_id
+ topic_ids.uniq!
+ return {} if topic_ids.empty?
+
+ first_post_ids = Post.where(topic_id: topic_ids, post_number: 1, deleted_at: nil).pluck(:id)
+ return {} if first_post_ids.empty?
+
+ events_by_topic =
+ DiscoursePostEvent::Event
+ .where(id: first_post_ids)
+ .includes(:image_upload, post: [:user, { topic: :category }])
+ .index_by { |event| event.post.topic_id }
+ return {} if events_by_topic.empty?
+
+ @serialized = {}
+ result = {}
+
+ links.each do |source_post_id, link_topic_id|
+ event = events_by_topic[link_topic_id]
+ next if event.nil? || [email protected]_see?(event.post)
+ (result[source_post_id] ||= {})[link_topic_id] = serialize(event)
+ end
+
+ own_event = own_topic_id && events_by_topic[own_topic_id]
+ if own_event && @guardian.can_see?(own_event.post)
+ each_self_onebox_post(own_topic_id) do |post_id|
+ (result[post_id] ||= {})[own_topic_id] = serialize(own_event)
+ end
+ end
+
+ result
+ end
+
+ private
+
+ def serialize(event)
+ @serialized[event.id] ||= DiscoursePostEvent::EventSerializer.new(
+ event,
+ scope: @guardian,
+ root: false,
+ ).as_json
+ end
+
+ # yields the id of each post whose cooked oneboxes its own (event) topic. A
+ # same-topic onebox is `aside.quote[data-post="1"]` without a data-username
+ # (which would mark a manual quote); the cheap include? skips parsing posts
+ # that don't reference the topic at all.
+ def each_self_onebox_post(topic_id)
+ marker = %{data-topic="#{topic_id}"}
+ @posts.each do |post|
+ next if post.cooked.blank? || !post.cooked.include?(marker)
+
+ onebox =
+ Nokogiri::HTML5
+ .fragment(post.cooked)
+ .css(%{aside.quote[data-topic="#{topic_id}"][data-post="1"]})
+ .any? { |aside| aside["data-username"].blank? }
+
+ yield(post.id) if onebox
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rb
index d2615155200..7fd66612b73 100644
--- a/plugins/discourse-calendar/plugin.rb
+++ b/plugins/discourse-calendar/plugin.rb
@@ -179,7 +179,9 @@ after_initialize do
require_relative "jobs/regular/discourse_post_event/warm_livestream_onebox"
require_relative "lib/discourse_post_event/email_renderer"
require_relative "lib/discourse_post_event/engine"
+ require_relative "lib/discourse_post_event/event_excerpt"
require_relative "lib/discourse_post_event/event_finder"
+ require_relative "lib/discourse_post_event/event_onebox_data"
require_relative "lib/discourse_post_event/event_parser"
require_relative "lib/discourse_post_event/event_validator"
require_relative "lib/discourse_post_event/export_csv_controller_extension"
@@ -289,6 +291,40 @@ after_initialize do
end,
) { DiscoursePostEvent::EventSerializer.new(object.event, scope: scope, root: false) }
+ TopicView.on_preload do |topic_view|
+ if SiteSetting.discourse_post_event_enabled
+ # always set the store (even when empty) and avoid a per-post query for every post in the topic
+ topic_view.set_preloaded_post_data(
+ :event_oneboxes,
+ DiscoursePostEvent::EventOneboxData.build(
+ posts: topic_view.posts,
+ guardian: topic_view.guardian,
+ ),
+ )
+ end
+ end
+
+ add_to_serializer(
+ :post,
+ :event_oneboxes,
+ include_condition: -> { SiteSetting.discourse_post_event_enabled && event_oneboxes.present? },
+ ) do
+ # use the batched topic-view preload on the common read path
+ # otherwise compute just this post so the event card shows without a page refresh
+ @event_oneboxes ||=
+ begin
+ preloaded = topic_view&.preloaded_post_data(:event_oneboxes)
+ if preloaded
+ preloaded[object.id] || {}
+ elsif object.cooked&.include?("data-topic")
+ DiscoursePostEvent::EventOneboxData.build(posts: [object], guardian: scope)[object.id] ||
+ {}
+ else
+ {}
+ end
+ end
+ end
+
on(:post_created) do |post|
DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
post.association(:event).reload
@@ -665,6 +701,12 @@ after_initialize do
end
end
+ on(:reduce_excerpt) do |fragment, options|
+ if SiteSetting.discourse_post_event_enabled
+ DiscoursePostEvent::EventExcerpt.call(fragment, post: options[:post])
+ end
+ end
+
on(:user_destroyed) { |user| DiscoursePostEvent::Invitee.where(user_id: user.id).destroy_all }
add_post_revision_notifier_recipients do |post_revision|
diff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_excerpt_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_excerpt_spec.rb
new file mode 100644
index 00000000000..a82817a174b
--- /dev/null
+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_excerpt_spec.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+describe DiscoursePostEvent::EventExcerpt do
+ def excerpt(post: nil, **attributes)
+ fragment = Nokogiri::HTML5.fragment(<<~HTML)
+ <p>intro</p>
+ <div class="discourse-post-event"></div>
+ HTML
+
+ event_node = fragment.at_css(".discourse-post-event")
+ attributes.each { |name, value| event_node["data-#{name.to_s.tr("_", "-")}"] = value }
+
+ described_class.call(fragment, post: post)
+ fragment.to_html
+ end
+
+ describe ".call" do
+ it "replaces the event node with a summary of the start date" do
+ html = excerpt(start: "2018-06-05 18:39:00")
+
+ expect(html).to include("📅 June 5, 2018 6:39 PM (UTC)")
+ expect(html).not_to include("discourse-post-event")
+ end
+
+ it "appends the end date when present" do
+ html = excerpt(start: "2018-06-05 18:39:00", end: "2018-06-22 10:00:00")
+
+ expect(html).to include("June 5, 2018 6:39 PM → June 22, 2018 10:00 AM (UTC)")
+ end
+
+ it "uses the event timezone" do
+ html = excerpt(start: "2018-06-05 18:39:00", timezone: "America/New_York")
+
+ expect(html).to include("June 5, 2018 6:39 PM (America/New_York)")
+ end
+
+ it "uses a date-only format without timezone for all-day events" do
+ html = excerpt(start: "2018-06-05", all_day: "true")
+
+ expect(html).to include("📅 June 5, 2018")
+ expect(html).not_to include("(UTC)")
+ end
+
+ it "joins the name, dates, and location" do
+ html = excerpt(name: "Pancakes", start: "2018-06-05 18:39:00", location: "Room A")
+
+ expect(html).to include("📅 Pancakes · June 5, 2018 6:39 PM (UTC) · Room A")
+ end
+
+ it "omits the name when it matches the topic title" do
+ post = Fabricate(:post)
+
+ html = excerpt(post: post, name: post.topic.title, start: "2018-06-05 18:39:00")
+
+ expect(html).not_to include(post.topic.title)
+ expect(html).to include("📅 June 5, 2018 6:39 PM (UTC)")
+ end
+
+ it "escapes html in the event data" do
+ html = excerpt(name: "Pancakes <b>bold</b>")
+
+ expect(html).not_to include("<b>")
+ expect(html).to include("Pancakes")
+ end
+
+ it "keeps unparseable dates as-is" do
+ html = excerpt(start: "not-a-date")
+
+ expect(html).to include("📅 not-a-date (UTC)")
+ end
+
+ it "removes the event node when there is nothing to summarize" do
+ html = excerpt
+
+ expect(html).not_to include("discourse-post-event")
+ expect(html).not_to include("📅")
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_finder_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_finder_spec.rb
index 0a3b529b14a..7caaedb2774 100644
--- a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_finder_spec.rb
+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_finder_spec.rb
@@ -423,4 +423,38 @@ describe DiscoursePostEvent::EventFinder do
end
end
end
+
+ describe "by topic id" do
+ fab!(:event_one) { Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public]) }
+ fab!(:event_two) { Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public]) }
+
+ it "returns only the event in the given topic" do
+ expect(finder.search(current_user, { topic_id: event_one.post.topic_id })).to match_array(
+ [event_one],
+ )
+ end
+
+ it "returns nothing for a topic without an event" do
+ expect(finder.search(current_user, { topic_id: Fabricate(:topic).id })).to be_empty
+ end
+
+ context "with a closed event" do
+ fab!(:closed_event) do
+ Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public], closed: true)
+ end
+
+ it "excludes the closed event by default" do
+ expect(finder.search(current_user, { topic_id: closed_event.post.topic_id })).to be_empty
+ end
+
+ it "includes the closed event when include_closed is set" do
+ expect(
+ finder.search(
+ current_user,
+ { topic_id: closed_event.post.topic_id, include_closed: true },
+ ),
+ ).to match_array([closed_event])
+ end
+ end
+ end
end
diff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_onebox_data_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_onebox_data_spec.rb
new file mode 100644
index 00000000000..68fddca0346
--- /dev/null
+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_onebox_data_spec.rb
@@ -0,0 +1,148 @@
+# frozen_string_literal: true
+
+describe DiscoursePostEvent::EventOneboxData do
+ fab!(:author, :user) { Fabricate(:user, admin: true) }
+ fab!(:reader, :user)
+
+ before do
+ freeze_time Time.utc(2018, 6, 5, 18, 40)
+ SiteSetting.calendar_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ end
+
+ def link_to(post, target_topic)
+ post.update!(raw: "see #{target_topic.url}")
+ TopicLink.extract_from(post)
+ post
+ end
+
+ # a self-onebox (a reply linking the topic it's in) produces no TopicLink row,
+ # so we craft the cooked aside the way the onebox would
+ def with_self_onebox(post, topic, extra = "")
+ post.update_columns(
+ cooked:
+ "<aside class=\"quote\" data-post=\"1\" data-topic=\"#{topic.id}\"#{extra}><blockquote>x</blockquote></aside>",
+ )
+ post
+ end
+
+ it "returns the serialized event keyed by source post and linked topic id" do
+ event_post = create_post_with_event(author, 'name="Pancakes"')
+ linking_post = link_to(Fabricate(:post), event_post.topic)
+
+ result = described_class.build(posts: [linking_post], guardian: Guardian.new(reader))
+
+ expect(result.keys).to eq([linking_post.id])
+ event = result[linking_post.id][event_post.topic_id]
+ expect(event).to be_present
+ expect(event[:name]).to eq("Pancakes")
+ expect(event[:starts_at]).to be_present
+ end
+
+ it "ignores links to non-event topics" do
+ linking_post = link_to(Fabricate(:post), Fabricate(:post).topic)
+
+ result = described_class.build(posts: [linking_post], guardian: Guardian.new(reader))
+
+ expect(result).to be_empty
+ end
+
+ it "omits events the reader cannot see" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ event_post =
+ create_post_with_event(author).tap { |p| p.topic.update!(category: private_category) }
+ linking_post = link_to(Fabricate(:post), event_post.topic)
+
+ result = described_class.build(posts: [linking_post], guardian: Guardian.new(reader))
+
+ expect(result).to be_empty
+ end
+
+ it "returns nothing without posts" do
+ expect(described_class.build(posts: [], guardian: Guardian.new(reader))).to eq({})
+ end
+
+ context "with a same-topic onebox (a reply linking the event topic it's in)" do
+ it "includes the event keyed by the topic id" do
+ event_post = create_post_with_event(author, 'name="Pancakes"')
+ reply = with_self_onebox(Fabricate(:post, topic: event_post.topic), event_post.topic)
+
+ result = described_class.build(posts: [reply], guardian: Guardian.new(reader))
+
+ expect(result[reply.id][event_post.topic_id]).to be_present
+ end
+
+ it "ignores a same-topic quote (which carries a data-username)" do
+ event_post = create_post_with_event(author)
+ reply =
+ with_self_onebox(
+ Fabricate(:post, topic: event_post.topic),
+ event_post.topic,
+ ' data-username="bob"',
+ )
+
+ result = described_class.build(posts: [reply], guardian: Guardian.new(reader))
+
+ expect(result).to be_empty
+ end
+
+ it "does nothing for a self-link in a non-event topic" do
+ topic = Fabricate(:topic)
+ reply = with_self_onebox(Fabricate(:post, topic: topic), topic)
+
+ result = described_class.build(posts: [reply], guardian: Guardian.new(reader))
+
+ expect(result).to be_empty
+ end
+ end
+
+ describe "delivered through the post serializer" do
+ it "preloads event_oneboxes onto posts in a topic view" do
+ event_post = create_post_with_event(author, 'name="Pancakes"')
+ linking_post = link_to(Fabricate(:post), event_post.topic)
+
+ topic_view = TopicView.new(linking_post.topic_id, reader)
+ serializer = PostSerializer.new(linking_post, scope: Guardian.new(reader), root: false)
+ serializer.topic_view = topic_view
+ json = serializer.as_json
+
+ expect(json[:event_oneboxes]).to be_present
+ expect(json[:event_oneboxes][event_post.topic_id]).to be_present
+ end
+
+ it "computes event_oneboxes on demand when serialized without a topic view" do
+ # mirrors a freshly cooked-post-processed post (message bus update): the
+ # fallback only pays its queries once the cooked onebox markup is present
+ event_post = create_post_with_event(author, 'name="Pancakes"')
+ linking_post = link_to(Fabricate(:post), event_post.topic)
+ linking_post.update_columns(
+ cooked:
+ "<aside class=\"quote\" data-topic=\"#{event_post.topic_id}\" data-post=\"1\"><blockquote>x</blockquote></aside>",
+ )
+
+ json = PostSerializer.new(linking_post, scope: Guardian.new(reader), root: false).as_json
+
+ expect(json[:event_oneboxes]).to be_present
+ expect(json[:event_oneboxes][event_post.topic_id]).to be_present
+ end
+
+ it "skips the on-demand computation when cooked has no onebox markup" do
+ event_post = create_post_with_event(author)
+ linking_post = link_to(Fabricate(:post), event_post.topic)
+
+ queries =
+ track_sql_queries do
+ json = PostSerializer.new(linking_post, scope: Guardian.new(reader), root: false).as_json
+ expect(json).not_to have_key(:event_oneboxes)
+ end
+
+ expect(queries).not_to include(match(/topic_links/))
+ end
+
+ it "omits event_oneboxes for a post that links nothing" do
+ json = PostSerializer.new(Fabricate(:post), scope: Guardian.new(reader), root: false).as_json
+
+ expect(json).not_to have_key(:event_oneboxes)
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rb
index cfc5c9706f9..4c9a649a783 100644
--- a/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rb
+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rb
@@ -312,5 +312,58 @@ describe PrettyText do
end
end
end
+
+ describe "An event is summarized in an excerpt (used by oneboxes)" do
+ fab!(:user_1, :user) { Fabricate(:user, admin: true) }
+
+ def excerpt_for(post)
+ PrettyText.excerpt(post.cooked, SiteSetting.post_onebox_maxlength, post: post)
+ end
+
+ it "summarizes the event with its formatted start date" do
+ excerpt = excerpt_for(create_post_with_event(user_1))
+
+ expect(excerpt).to include("📅")
+ expect(excerpt).to include("June 5, 2018 6:39 PM (UTC)")
+ end
+
+ it "includes the end date when present" do
+ excerpt = excerpt_for(create_post_with_event(user_1, 'end="2018-06-22"'))
+
+ expect(excerpt).to include("→")
+ expect(excerpt).to include("June 22, 2018 12:00 AM (UTC)")
+ end
+
+ it "uses the event timezone" do
+ excerpt = excerpt_for(create_post_with_event(user_1, 'timezone="America/New_York"'))
+
+ expect(excerpt).to include("(America/New_York)")
+ end
+
+ it "includes the location" do
+ excerpt = excerpt_for(create_post_with_event(user_1, 'location="Conference Room A"'))
+
+ expect(excerpt).to include("Conference Room A")
+ end
+
+ it "includes the event name when it differs from the topic title" do
+ excerpt = excerpt_for(create_post_with_event(user_1, 'name="Pancakes event"'))
+
+ expect(excerpt).to include("Pancakes event")
+ end
+
+ it "escapes html in the event data" do
+ excerpt = excerpt_for(create_post_with_event(user_1, 'name="Pancakes <b>bold</b>"'))
+
+ expect(excerpt).not_to include("<b>")
+ end
+
+ it "does nothing when the plugin is disabled" do
+ post = create_post_with_event(user_1)
+ SiteSetting.discourse_post_event_enabled = false
+
+ expect(excerpt_for(post)).not_to include("📅")
+ end
+ end
end
end
diff --git a/plugins/discourse-calendar/test/javascripts/integration/components/discourse-post-event-location-test.gjs b/plugins/discourse-calendar/test/javascripts/integration/components/discourse-post-event-location-test.gjs
new file mode 100644
index 00000000000..1b9ce212249
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/integration/components/discourse-post-event-location-test.gjs
@@ -0,0 +1,58 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import Location from "discourse/plugins/discourse-calendar/discourse/components/discourse-post-event/location";
+
+module(
+ "Integration | Component | DiscoursePostEventLocation",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders a plain-text location", async function (assert) {
+ await render(
+ <template><Location @location="Conference Room A" /></template>
+ );
+
+ assert
+ .dom(".event-location")
+ .includesText("Conference Room A", "shows the location text");
+ });
+
+ test("renders a URL location as a plain link, never a onebox", async function (assert) {
+ await render(
+ <template>
+ <Location @location="https://youtube.com/watch?v=123" />
+ </template>
+ );
+
+ assert
+ .dom(".event-location a")
+ .hasAttribute("href", "https://youtube.com/watch?v=123")
+ .hasText("https://youtube.com/watch?v=123", "shows the raw url");
+ assert
+ .dom(".event-location a")
+ .doesNotHaveClass(
+ "onebox",
+ "leaves no onebox markup for the composer's onebox pass to hydrate"
+ );
+ });
+
+ test("links urls inside surrounding text", async function (assert) {
+ await render(
+ <template>
+ <Location @location="Zoom: https://zoom.us/j/123 (room 2)" />
+ </template>
+ );
+
+ assert
+ .dom(".event-location a")
+ .hasText("https://zoom.us/j/123", "links only the url part");
+ assert
+ .dom(".event-location")
+ .includesText("Zoom:", "keeps the text before the url");
+ assert
+ .dom(".event-location")
+ .includesText("(room 2)", "keeps the text after the url");
+ });
+ }
+);
diff --git a/plugins/discourse-calendar/test/javascripts/unit/topic-id-from-url-test.js b/plugins/discourse-calendar/test/javascripts/unit/topic-id-from-url-test.js
new file mode 100644
index 00000000000..cec1c964e1c
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/unit/topic-id-from-url-test.js
@@ -0,0 +1,40 @@
+import { module, test } from "qunit";
+import { topicIdFromUrl } from "discourse/plugins/discourse-calendar/discourse/components/discourse-post-event/onebox-node-view";
+
+const ORIGIN = window.location.origin;
+
+module("Unit | discourse-post-event | topicIdFromUrl", function () {
+ test("extracts the topic id for a topic / first-post link", function (assert) {
+ assert.strictEqual(topicIdFromUrl("/t/some-slug/123"), 123);
+ assert.strictEqual(topicIdFromUrl(`${ORIGIN}/t/some-slug/123`), 123);
+ assert.strictEqual(
+ topicIdFromUrl(`${ORIGIN}/t/some-slug/123/1`),
+ 123,
+ "treats an explicit first post as the topic"
+ );
+ });
+
+ test("returns null for a link to a specific reply", function (assert) {
+ assert.strictEqual(topicIdFromUrl(`${ORIGIN}/t/some-slug/123/4`), null);
+ });
+
+ test("returns null for an off-site Discourse url", function (assert) {
+ assert.strictEqual(
+ topicIdFromUrl("https://meta.discourse.org/t/foo/123"),
+ null,
+ "does not treat another Discourse site's topic as a local topic"
+ );
+ });
+
+ test("returns null for slugless urls instead of misreading the post number", function (assert) {
+ assert.strictEqual(topicIdFromUrl(`${ORIGIN}/t/123/2`), null);
+ assert.strictEqual(topicIdFromUrl(`${ORIGIN}/t/123`), null);
+ });
+
+ test("returns null for non-topic urls", function (assert) {
+ assert.strictEqual(topicIdFromUrl(`${ORIGIN}/c/cat/5`), null);
+ assert.strictEqual(topicIdFromUrl(ORIGIN), null);
+ assert.strictEqual(topicIdFromUrl(null), null);
+ assert.strictEqual(topicIdFromUrl(undefined), null);
+ });
+});