Skip to content

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

DEV: Reuse the event card for composer onebox previews (#43847)

Renato Atilio7f22f56e1b82
diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjs
index 2158357dad6..17818e2bdc8 100644
--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjs
+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjs
@@ -93,7 +93,7 @@ export default class DiscoursePostEvent extends Component {
setupMessageBus = modifier(() => {
const topicId = this.event?.post?.topic?.id;
- if (!topicId) {
+ if (this.readOnly || !topicId) {
return;
}
@@ -108,7 +108,7 @@ export default class DiscoursePostEvent extends Component {
constructor() {
super(...arguments);
- if (this.isPartialEvent) {
+ if (this.isPartialEvent && !this.readOnly) {
this.loadEvent();
}
}
@@ -145,6 +145,10 @@ export default class DiscoursePostEvent extends Component {
return this.args.withDescription ?? true;
}
+ get readOnly() {
+ return this.args.readOnly ?? false;
+ }
+
get startsAtMonth() {
const displayTime = this.getDisplayTime(this.event.startsAt);
return displayTime.format("MMM");
@@ -264,7 +268,7 @@ export default class DiscoursePostEvent extends Component {
<template>
{{#let this.event as |event|}}
- <div class="discourse-post-event">
+ <div class="discourse-post-event" ...attributes>
<div class="discourse-post-event-widget">
{{#if event}}
<Image
@@ -295,6 +299,7 @@ export default class DiscoursePostEvent extends Component {
@name="discourse-post-event-status-and-creators"
@outletArgs={{lazyHash
event=event
+ readOnly=this.readOnly
Separator=StatusSeparator
Status=(component EventStatus event=event)
Creator=(component
@@ -314,15 +319,17 @@ export default class DiscoursePostEvent extends Component {
</div>
<div class="event-header__controls">
- {{#if event.creator}}
- <MoreMenu
- @composePrivateMessage={{routeAction
- "composePrivateMessage"
- }}
- @event={{event}}
- @isStandaloneEvent={{this.isStandaloneEvent}}
- />
- {{/if}}
+ {{#unless this.readOnly}}
+ {{#if event.creator}}
+ <MoreMenu
+ @composePrivateMessage={{routeAction
+ "composePrivateMessage"
+ }}
+ @event={{event}}
+ @isStandaloneEvent={{this.isStandaloneEvent}}
+ />
+ {{/if}}
+ {{/unless}}
{{#if @onClose}}
<DButton
@@ -338,6 +345,7 @@ export default class DiscoursePostEvent extends Component {
@name="discourse-post-event-info"
@outletArgs={{lazyHash
event=event
+ readOnly=this.readOnly
Section=(component InfoSection event=event)
Url=(component Url url=this.displayUrl)
Description=(component
@@ -374,11 +382,13 @@ export default class DiscoursePostEvent extends Component {
<Url @url={{this.displayUrl}} />
<ChatChannel @event={{event}} />
- {{#if event.stats}}
- <Invitees @event={{event}} />
- {{else if this.loadingDetails}}
- <InviteesPlaceholder />
- {{/if}}
+ {{#unless this.readOnly}}
+ {{#if event.stats}}
+ <Invitees @event={{event}} />
+ {{else if this.loadingDetails}}
+ <InviteesPlaceholder />
+ {{/if}}
+ {{/unless}}
{{#if this.withDescription}}
<Description
@@ -387,14 +397,16 @@ export default class DiscoursePostEvent extends Component {
/>
{{/if}}
- {{#if this.showStatus}}
- <Status @event={{event}} />
- {{else if this.loadingDetails}}
- <StatusPlaceholder />
- {{/if}}
+ {{#unless this.readOnly}}
+ {{#if this.showStatus}}
+ <Status @event={{event}} />
+ {{else if this.loadingDetails}}
+ <StatusPlaceholder />
+ {{/if}}
- {{#unless @hideLivestreamVideo}}
- <Livestream @event={{event}} @post={{@post}} />
+ {{#unless @hideLivestreamVideo}}
+ <Livestream @event={{event}} @post={{@post}} />
+ {{/unless}}
{{/unless}}
</PluginOutlet>
{{/if}}
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 38cb8177c57..5e1e760cae7 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
@@ -2,9 +2,7 @@ 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.gjs";
-import DiscoursePostEventLocation from "./location.gjs";
+import DiscoursePostEvent from "discourse/plugins/discourse-events/discourse/components/discourse-post-event";
export default class DiscoursePostEventOneboxPreview extends Component {
@service discoursePostEventApi;
@@ -16,18 +14,6 @@ export default class DiscoursePostEventOneboxPreview extends Component {
this.load();
}
- 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);
}
@@ -38,32 +24,14 @@ export default class DiscoursePostEventOneboxPreview extends Component {
);
}
- #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}} />
- <DiscoursePostEventLocation @event={{this.event}} />
- </div>
- </div>
+ <DiscoursePostEvent
+ class="discourse-post-event--preview"
+ @event={{this.event}}
+ @linkToPost={{true}}
+ @readOnly={{true}}
+ />
{{else}}
{{this.fallback}}
{{/if}}
diff --git a/plugins/discourse-events/lib/discourse_events/events/excerpt.rb b/plugins/discourse-events/lib/discourse_events/events/excerpt.rb
index 48023d1771b..08ece5b8179 100644
--- a/plugins/discourse-events/lib/discourse_events/events/excerpt.rb
+++ b/plugins/discourse-events/lib/discourse_events/events/excerpt.rb
@@ -44,6 +44,7 @@ module DiscourseEvents
all_day = event_node["data-all-day"] == "true"
ends_at = event_node["data-end"]
+ ends_at = nil if all_day && same_day?(starts_at, ends_at)
timezone = event_node["data-timezone"] || "UTC"
dates = format_date(starts_at, all_day)
@@ -52,6 +53,13 @@ module DiscourseEvents
dates
end
+ def same_day?(starts_at, ends_at)
+ return false if ends_at.blank?
+ Date.parse(starts_at) == Date.parse(ends_at)
+ rescue ArgumentError
+ false
+ end
+
def format_date(value, all_day)
I18n.l(DateTime.parse(value), format: t(all_day ? "date_format" : "datetime_format"))
rescue StandardError
diff --git a/plugins/discourse-events/spec/lib/discourse_events/events/excerpt_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/excerpt_spec.rb
index 4a77286b241..aa0380c36df 100644
--- a/plugins/discourse-events/spec/lib/discourse_events/events/excerpt_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/excerpt_spec.rb
@@ -34,6 +34,13 @@ describe DiscourseEvents::Events::Excerpt do
expect(html).to include("June 5, 2018 6:39 PM (America/New_York)")
end
+ it "does not repeat the date of a single-day all-day event" do
+ html = excerpt(start: "2018-06-05", end: "2018-06-05", all_day: "true")
+
+ expect(html).to include("πŸ“… June 5, 2018")
+ expect(html).not_to include("β†’")
+ end
+
it "uses a date-only format without timezone for all-day events" do
html = excerpt(start: "2018-06-05", all_day: "true")
@@ -69,6 +76,12 @@ describe DiscourseEvents::Events::Excerpt do
expect(html).to include("πŸ“… not-a-date (UTC)")
end
+ it "keeps the range when an all-day date is too long to parse" do
+ html = excerpt(start: "2018-06-05", end: "2" * 200, all_day: "true")
+
+ expect(html).to include("πŸ“… June 5, 2018 β†’ #{"2" * 200}")
+ end
+
it "removes the event node when there is nothing to summarize" do
html = excerpt
diff --git a/plugins/discourse-events/test/javascripts/acceptance/event-onebox-test.js b/plugins/discourse-events/test/javascripts/acceptance/event-onebox-test.js
new file mode 100644
index 00000000000..185d737f454
--- /dev/null
+++ b/plugins/discourse-events/test/javascripts/acceptance/event-onebox-test.js
@@ -0,0 +1,157 @@
+import { click, fillIn, visit, waitFor } from "@ember/test-helpers";
+import { test } from "qunit";
+import { cloneJSON } from "discourse/lib/object";
+import topicFixtures from "discourse/tests/fixtures/topic";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Event onebox", function (needs) {
+ needs.user();
+ needs.settings({
+ discourse_events_enabled: true,
+ discourse_post_event_enabled: true,
+ enable_markdown_linkify: true,
+ });
+
+ let eventRequests;
+ let topicJson;
+ const event = {
+ id: 900,
+ name: "Board game night",
+ starts_at: "2026-09-20T18:00:00Z",
+ ends_at: "2026-09-20T20:00:00Z",
+ timezone: "UTC",
+ status: "public",
+ post: { id: 900, url: "/t/example/123", topic: { id: 123 } },
+ creator: { username: "bob", id: 5 },
+ can_update_attendance: true,
+ should_display_invitees: true,
+ sample_invitees: [],
+ stats: { going: 1, interested: 0, invited: 0, not_going: 0 },
+ };
+ needs.hooks.beforeEach(() => {
+ eventRequests = 0;
+ topicJson = cloneJSON(topicFixtures["/t/280/1.json"]);
+ });
+ needs.pretender((server, helper) => {
+ 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", () =>
+ helper.response({ event })
+ );
+ server.get("/onebox", (request) => {
+ const topicId = request.queryParams.url.split("/").pop();
+ return [
+ 200,
+ { "Content-Type": "text/html" },
+ `
+ <aside class="quote" data-topic="${topicId}" data-post="1">
+ <div class="title">Example topic</div>
+ <blockquote>Preview text</blockquote>
+ </aside>
+ `,
+ ];
+ });
+ server.get("/discourse-post-event/events", (request) => {
+ eventRequests++;
+ const events = request.queryParams.topic_id === "123" ? [event] : [];
+ return helper.response({ events });
+ });
+ });
+
+ test("event topics show the read-only event card in both composer modes", async function (assert) {
+ const url = `${window.location.origin}/t/example/123`;
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .btn.create");
+ await fillIn(".d-editor-input", `${url}\n\nEditable text`);
+ // the decorator sees the onebox only after the next preview update
+ await waitFor(".d-editor-preview aside.quote");
+ await fillIn(".d-editor-input", `${url}\n\nEditable text!`);
+ await waitFor(".d-editor-preview .discourse-post-event-widget");
+
+ assert
+ .dom(".d-editor-preview .discourse-post-event-widget .event-date .day")
+ .exists("the markdown preview renders the event card's date box");
+ assert
+ .dom(".d-editor-preview .discourse-post-event-widget .name")
+ .hasText(event.name);
+ assert
+ .dom(".d-editor-preview .going-button")
+ .doesNotExist("the preview card has no RSVP controls");
+
+ await click(".composer-toggle-switch");
+ await waitFor(".onebox-wrapper .discourse-post-event-widget");
+
+ assert
+ .dom(".onebox-wrapper .discourse-post-event-widget .event-date .day")
+ .exists("the rich editor renders the same card");
+ assert
+ .dom(".onebox-wrapper .discourse-post-event-widget .name")
+ .hasText(event.name);
+ assert.strictEqual(
+ eventRequests,
+ 1,
+ "the event is fetched once per topic across both modes"
+ );
+
+ await click(".composer-toggle-switch");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ `${url}\n\nEditable text!`,
+ "switching modes preserves the source URL"
+ );
+ });
+
+ test("ordinary topics keep the standard onebox in both composer modes", async function (assert) {
+ const url = `${window.location.origin}/t/example/124`;
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .btn.create");
+ await fillIn(".d-editor-input", `${url}\n\nEditable text`);
+
+ assert
+ .dom(".d-editor-preview aside.quote")
+ .exists("the markdown preview keeps the server onebox");
+ assert.dom(".d-editor-preview .discourse-post-event-widget").doesNotExist();
+
+ await click(".composer-toggle-switch");
+
+ assert
+ .dom(".ProseMirror aside.quote")
+ .hasStyle(
+ { whiteSpace: "normal" },
+ "the rich editor keeps the server onebox, without editor whitespace"
+ );
+ assert.dom(".ProseMirror .discourse-post-event-widget").doesNotExist();
+ });
+
+ test("published event oneboxes retain the interactive event card", async function (assert) {
+ const post = topicJson.post_stream.posts[0];
+ post.cooked = `
+ <aside class="quote" data-topic="123" data-post="1">
+ <div class="title">Event topic</div><blockquote>Board game night</blockquote>
+ </aside>
+ <aside class="quote" data-topic="124" data-post="1">
+ <div class="title">Ordinary topic</div><blockquote>Preview text</blockquote>
+ </aside>
+ `;
+ post.event_oneboxes = { 123: event };
+
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom("#post_1 .discourse-post-event-onebox .discourse-post-event-widget")
+ .exists("the confirmed event is decorated with its interactive card");
+ assert
+ .dom("#post_1 .discourse-post-event-onebox .going-button")
+ .exists("the published card keeps its RSVP controls");
+ assert
+ .dom("#post_1 .discourse-post-event-onebox .name a")
+ .hasText(event.name, "the card links to the event");
+ assert
+ .dom('#post_1 aside.quote[data-topic="124"]')
+ .includesText(
+ "Preview text",
+ "ordinary topic previews retain core rendering"
+ );
+ });
+});
diff --git a/plugins/discourse-events/test/javascripts/integration/components/discourse-post-event-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/discourse-post-event-test.gjs
index 9797b21b6c2..b619eca756a 100644
--- a/plugins/discourse-events/test/javascripts/integration/components/discourse-post-event-test.gjs
+++ b/plugins/discourse-events/test/javascripts/integration/components/discourse-post-event-test.gjs
@@ -38,6 +38,76 @@ module("Integration | Component | DiscoursePostEvent", function (hooks) {
);
}
+ test("read-only mode keeps the card but drops its controls", async function (assert) {
+ const attrs = {
+ can_update_attendance: true,
+ stats: { going: 1, interested: 0, invited: 0, not_going: 0 },
+ should_display_invitees: true,
+ };
+
+ const event = buildEvent(attrs);
+ await render(<template><DiscoursePostEvent @event={{event}} /></template>);
+
+ assert.dom(".going-button").exists("the interactive card offers an RSVP");
+ assert.dom(".event-invitees").exists();
+ assert
+ .dom(
+ '.event-header__controls [data-identifier="discourse-post-event-more-menu"]'
+ )
+ .exists();
+
+ const readOnlyEvent = buildEvent(attrs);
+ await render(
+ <template>
+ <DiscoursePostEvent @event={{readOnlyEvent}} @readOnly={{true}} />
+ </template>
+ );
+
+ assert.dom(".event-date .day").exists("the date box is still shown");
+ assert.dom(".event-dates").exists("the dates are still listed");
+ assert.dom(".going-button").doesNotExist();
+ assert.dom(".event-invitees").doesNotExist();
+ assert
+ .dom(
+ '.event-header__controls [data-identifier="discourse-post-event-more-menu"]'
+ )
+ .doesNotExist();
+ });
+
+ test("read-only mode neither fetches details nor subscribes to updates", async function (assert) {
+ let fetched = 0;
+ getOwner(this).unregister("service:discourse-post-event-api");
+ getOwner(this).register(
+ "service:discourse-post-event-api",
+ {
+ async event() {
+ fetched++;
+ return buildEvent();
+ },
+ },
+ { instantiate: false }
+ );
+ const messageBus = getOwner(this).lookup("service:message-bus");
+ const subscribed = [];
+ const originalSubscribe = messageBus.subscribe;
+ messageBus.subscribe = (path) => subscribed.push(path);
+
+ try {
+ const event = buildEvent({ creator: null });
+ await render(
+ <template>
+ <DiscoursePostEvent @event={{event}} @readOnly={{true}} />
+ </template>
+ );
+
+ assert.dom(".event-date .day").exists("the card still renders");
+ assert.strictEqual(fetched, 0, "a creator-less event is not refetched");
+ assert.deepEqual(subscribed, [], "no message-bus subscription is made");
+ } finally {
+ messageBus.subscribe = originalSubscribe;
+ }
+ });
+
test("interpolates the weekday into the recurrence label", async function (assert) {
stubApi.call(this, buildEvent({ recurrence: "every_week" }));