Skip to content

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

FIX: Cook event location and description as inline markdown (#41994)

Régis Hanolf91d7a99768b
diff --git a/db/structure.sql b/db/structure.sql
index 0b7f7d2c48c..1ced7f6af8f 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -23056,6 +23056,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260727085824'),
('20260727035337'),
('20260723100008'),
+('20260723094850'),
('20260723013754'),
('20260722140539'),
('20260722140536'),
diff --git a/frontend/discourse/app/lib/text.js b/frontend/discourse/app/lib/text.js
index faefe061d43..a80a068f26f 100644
--- a/frontend/discourse/app/lib/text.js
+++ b/frontend/discourse/app/lib/text.js
@@ -8,6 +8,8 @@ import { helperContext } from "discourse/lib/helpers";
import { i18n } from "discourse-i18n";
import { QUOTATION_MARKS } from "discourse-markdown-it/features/bbcode-block";
+export { parseBBCodeTag } from "discourse-markdown-it/features/bbcode-block";
+
async function withEngine(name, ...args) {
const engine = await waitForPromise(import("discourse/static/markdown-it"));
return engine[name](...args);
diff --git a/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb b/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb
index 63de3564d2d..211603c519f 100644
--- a/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb
+++ b/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb
@@ -26,6 +26,7 @@ module DiscoursePostEvent
attributes :description
attributes :description_html
attributes :location
+ attributes :location_html
attributes :watching_invitee
attributes :chat_enabled
attributes :livestream
@@ -214,9 +215,20 @@ module DiscoursePostEvent
object.url.present?
end
+ def include_description_html?
+ object.description.present?
+ end
+
def description_html
- return if object.description.blank?
- EventParser.linkify_description(object.description, post: object.post)
+ EventParser.cook_inline(object.description, post: object.post)
+ end
+
+ def include_location_html?
+ object.location.present?
+ end
+
+ def location_html
+ EventParser.cook_inline(object.location, post: object.post)
end
end
end
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/compact-event-editor.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/compact-event-editor.gjs
index ca2b71b7ae1..c0162ed6309 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/compact-event-editor.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/compact-event-editor.gjs
@@ -9,6 +9,7 @@ import { service } from "@ember/service";
import PluginOutlet from "discourse/components/plugin-outlet";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import lazyHash from "discourse/helpers/lazy-hash";
+import { generateLinkifyFunction } from "discourse/lib/text";
import DButton from "discourse/ui-kit/d-button";
import DExpandingTextArea from "discourse/ui-kit/d-expanding-text-area";
import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
@@ -51,6 +52,7 @@ export default class CompactEventEditor extends Component {
@tracked allowedGroups;
@tracked closed;
@tracked customFields;
+ @tracked linkify;
#previousRsvpStatus = "public";
#lastInitialStateRef;
@tracked _maxAttendeesOverride;
@@ -58,6 +60,9 @@ export default class CompactEventEditor extends Component {
constructor() {
super(...arguments);
this.#syncFromInitialState();
+ generateLinkifyFunction({ siteSettings: this.siteSettings }).then(
+ (linkify) => (this.linkify = linkify)
+ );
}
@action
@@ -198,10 +203,7 @@ export default class CompactEventEditor extends Component {
}
get isLocationUrl() {
- if (!this.hasLocation) {
- return false;
- }
- return this.args.urlTester?.(this.location) ?? false;
+ return !!(this.hasLocation && this.linkify?.test(this.location));
}
get isLivestreamUrl() {
@@ -216,13 +218,7 @@ export default class CompactEventEditor extends Component {
if (!this.hasLocation) {
return null;
}
- if (this.isLocationUrl) {
- const location = this.location.trim();
- return location.includes("://") || location.includes("mailto:")
- ? location
- : `https://${location}`;
- }
- return this.location;
+ return this.linkify?.match(this.location)?.[0]?.url ?? this.location;
}
get statusText() {
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/composer-event-editor.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/composer-event-editor.gjs
index 050a7396b54..a90ac7e8cf5 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/composer-event-editor.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/composer-event-editor.gjs
@@ -37,11 +37,6 @@ export default class ComposerEventEditor extends Component {
};
}
- @action
- urlTester(value) {
- return /^(https?:\/\/|www\.|mailto:)/i.test(value);
- }
-
@action
onChange(state) {
this.#pendingState = state;
@@ -90,7 +85,6 @@ export default class ComposerEventEditor extends Component {
stateToEventInput(state),
this.siteSettings
);
- delete params.description;
const newBlock = buildEventBlock(params, state.description);
if (newBlock === parsed.full) {
@@ -122,7 +116,6 @@ export default class ComposerEventEditor extends Component {
>
<CompactEventEditor
@initialState={{this.initialState}}
- @urlTester={{this.urlTester}}
@onChange={{this.onChange}}
@onCommit={{this.flush}}
@onDelete={{this.onDelete}}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/description.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/description.gjs
index d8edcef2102..194e6dce7c9 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/description.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/description.gjs
@@ -6,6 +6,7 @@ import { modifier } from "ember-modifier";
import { or } from "discourse/truth-helpers";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+import openLinksInNewTab from "discourse/plugins/discourse-calendar/discourse/modifiers/open-links-in-new-tab";
export default class DiscoursePostEventDescription extends Component {
@tracked expanded = false;
@@ -57,13 +58,16 @@ export default class DiscoursePostEventDescription extends Component {
class="event-description__content"
{{(if this.clamp this.detectOverflow)}}
>
- <p class="event-description__text">
+ <div
+ class="event-description__text"
+ {{openLinksInNewTab @descriptionHtml}}
+ >
{{#if @descriptionHtml}}
{{trustHTML @descriptionHtml}}
{{else}}
{{@description}}
{{/if}}
- </p>
+ </div>
{{#if this.showToggle}}
<a
href
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 d486fecadb8..cf3d6386d15 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
@@ -352,12 +352,10 @@ export default class DiscoursePostEvent extends Component {
Url=(component Url url=event.url)
Description=(component
Description
- description=event.description
+ descriptionHtml=event.descriptionHtml
clamp=this.clampDescription
)
- Location=(component
- DiscoursePostEventLocation event=event location=event.location
- )
+ Location=(component DiscoursePostEventLocation event=event)
Dates=(component
Dates event=event expiredAndRecurring=this.expiredAndRecurring
)
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 21716b6d71e..d8b28575941 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,70 +1,32 @@
import Component from "@glimmer/component";
+import { trustHTML } from "@ember/template";
import dIcon from "discourse/ui-kit/helpers/d-icon";
+import openLinksInNewTab from "discourse/plugins/discourse-calendar/discourse/modifiers/open-links-in-new-tab";
-const URL_SPLIT_REGEX = /(https?:\/\/\S+)/;
-const URL_TEST_REGEX = /^https?:\/\/\S+$/;
+const BARE_URL_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 locationSegments() {
- return (this.location || "")
- .split(URL_SPLIT_REGEX)
- .filter((part) => part.length)
- .map((part) => ({ text: part, isUrl: URL_TEST_REGEX.test(part) }));
+ get isBareLivestreamUrl() {
+ return (
+ this.args.event?.isZoomLivestream &&
+ BARE_URL_REGEX.test(this.args.event.location ?? "")
+ );
}
- get location() {
- return this.args.event.location;
- }
-
- get isSingleUrlLocation() {
- return this.locationSegments.length === 1 && this.locationSegments[0].isUrl;
- }
-
- get singleUrl() {
- return this.isSingleUrlLocation ? this.locationSegments[0].text : null;
+ get locationHtml() {
+ return this.isBareLivestreamUrl ? null : this.args.event?.locationHtml;
}
<template>
- {{#if this.location}}
- {{#if this.isSingleUrlLocation}}
- {{#unless @event.isZoomLivestream}}
- <section class="event__section event-location">
- {{dIcon "location-pin"}}
-
- <span class="event-location__text">
- <a
- href={{this.singleUrl}}
- target="_blank"
- rel="noopener noreferrer"
- >{{this.singleUrl}}</a>
- </span>
- </section>
- {{/unless}}
- {{else}}
- <section class="event__section event-location">
- {{dIcon "location-pin"}}
-
- <span class="event-location__text">
- {{~#each this.locationSegments 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}}
+ {{#if this.locationHtml}}
+ <section class="event__section event-location">
+ {{dIcon "location-pin"}}
+
+ <span
+ class="event-location__text"
+ {{openLinksInNewTab this.locationHtml}}
+ >{{trustHTML this.locationHtml}}</span>
+ </section>
{{/if}}
</template>
}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjs
index f46de890e84..412c686ab93 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjs
@@ -41,11 +41,6 @@ export default class EventNodeView extends Component {
this.args.onSetup?.(this);
}
- @action
- testLocationUrl(value) {
- return this.args.pluginParams.utils.getLinkify().test(value);
- }
-
get eventDescription() {
return this.args.view.state.doc.textBetween(
this.args.getPos() + 1,
@@ -162,7 +157,6 @@ export default class EventNodeView extends Component {
<template>
<CompactEventEditor
@initialState={{this.initialState}}
- @urlTester={{this.testLocationUrl}}
@onChange={{this.onChange}}
@onDelete={{this.onDelete}}
/>
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjs
index c5734bd0da0..18a230aa932 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjs
@@ -21,6 +21,7 @@ import { i18n } from "discourse-i18n";
import { recurrenceContext } from "../../lib/event-recurrence";
import {
attendanceTransition,
+ buildEventBlock,
buildParams,
customFieldFormName,
defaultEventState,
@@ -451,11 +452,6 @@ export default class PostEventBuilder extends Component {
};
}
- @action
- urlTester(value) {
- return /^(https?:\/\/|www\.|mailto:)/i.test(value);
- }
-
@action
onCompactChange(state) {
this.event.name = state.name;
@@ -722,19 +718,8 @@ export default class PostEventBuilder extends Component {
this.siteSettings
);
- const description = eventParams.description
- ? `${eventParams.description}\n`
- : "";
- delete eventParams.description;
-
- const markdownParams = [];
- Object.keys(eventParams).forEach((key) => {
- let value = eventParams[key];
- markdownParams.push(`${key}="${value}"`);
- });
-
this.args.model.toolbarEvent.addText(
- `[event ${markdownParams.join(" ")}]\n${description}[/event]`
+ buildEventBlock(eventParams, eventParams.description)
);
this.args.closeModal();
}
@@ -1296,7 +1281,6 @@ export default class PostEventBuilder extends Component {
<div class="composer-event-node">
<CompactEventEditor
@initialState={{this.compactInitialState}}
- @urlTester={{this.urlTester}}
@onChange={{this.onCompactChange}}
@namePlaceholder={{this.namePlaceholder}}
@hideAdvanced={{true}}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
index 57f09a9aac2..245b888250d 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
@@ -1,3 +1,5 @@
+import { buildBBCodeAttrs, parseBBCodeTag } from "discourse/lib/text";
+
// `([\w-]+\.)*` allows any subdomain, since livestream hosts routinely use them
// (us06web.zoom.us, www.youtube.com). It cannot match a host that merely ends in
// one of these names, because each captured label must be followed by a dot:
@@ -232,9 +234,7 @@ export function buildParams(startsAt, endsAt, event, siteSettings) {
return params;
}
-const EVENT_BBCODE_REGEX = /\[event (.*?)\](.*?)\[\/event\]/s;
-const EVENT_BLOCK_REGEX = /\[event\b([^\]]*)\](.*?)\[\/event\]/s;
-const ATTR_REGEX = /([-\w]+)=(?:"([^"]*)"|'([^']*)'|([^\s\]]+))/g;
+const EVENT_CLOSE_TAG = "[/event]";
function dashedToCamel(key) {
return key.replace(/-([a-zA-Z0-9])/g, (_, c) => c.toUpperCase());
@@ -244,26 +244,52 @@ export function parseEventBlock(raw) {
if (!raw) {
return null;
}
- const match = raw.match(EVENT_BLOCK_REGEX);
- if (!match) {
- return null;
- }
- const attrs = {};
- for (const m of match[1].matchAll(ATTR_REGEX)) {
- const [, key, dq, sq, unq] = m;
- const value = dq ?? sq ?? unq ?? "";
- attrs[dashedToCamel(key)] = value;
+
+ let start = raw.indexOf("[event");
+ while (start !== -1) {
+ const parsed = parseBBCodeTag(raw, start, raw.length);
+
+ if (parsed?.tag === "event" && !parsed.closing) {
+ const bodyStart = start + parsed.length;
+ const close = raw.indexOf(EVENT_CLOSE_TAG, bodyStart);
+ if (close === -1) {
+ return null;
+ }
+
+ const attrs = {};
+ for (const [key, value] of Object.entries(parsed.attrs || {})) {
+ if (key !== "_default") {
+ attrs[dashedToCamel(key)] = value;
+ }
+ }
+
+ const description = raw
+ .slice(bodyStart, close)
+ .replace(/^\n/, "")
+ .replace(/\n$/, "");
+
+ return {
+ full: raw.slice(start, close + EVENT_CLOSE_TAG.length),
+ attrs,
+ description,
+ };
+ }
+
+ start = raw.indexOf("[event", start + 1);
}
- const description = (match[2] || "").replace(/^\n/, "").replace(/\n$/, "");
- return { full: match[0], attrs, description };
+
+ return null;
}
export function buildEventBlock(params, description) {
- const parts = Object.entries(params)
- .filter(([, v]) => v != null && v !== "" && String(v).trim() !== "")
- .map(([k, v]) => `${k}="${String(v).replace(/"/g, "")}"`);
+ const attrs = Object.fromEntries(
+ Object.entries(params).filter(
+ ([key, value]) =>
+ key !== "description" && value != null && String(value).trim() !== ""
+ )
+ );
const desc = description ? `${description}\n` : "";
- return `[event ${parts.join(" ")}]\n${desc}[/event]`;
+ return `[event ${buildBBCodeAttrs(attrs)}]\n${desc}[/event]`;
}
export function getCustomFieldNames(siteSettings) {
@@ -384,11 +410,13 @@ export function parseReminders(reminders) {
}
export function replaceRaw(params, raw) {
- if (!EVENT_BBCODE_REGEX.test(raw)) {
+ const parsed = parseEventBlock(raw);
+ if (!parsed) {
return false;
}
- const { description, ...attrs } = params;
- return raw.replace(EVENT_BBCODE_REGEX, buildEventBlock(attrs, description));
+ return raw.replace(parsed.full, () =>
+ buildEventBlock(params, params.description)
+ );
}
export function camelCase(input) {
@@ -401,7 +429,8 @@ export function camelCase(input) {
}
export function removeEvent(raw) {
- return raw.replace(/\[event (.*?)\](.*?)\[\/event\]/s, "");
+ const parsed = parseEventBlock(raw);
+ return parsed ? raw.replace(parsed.full, "") : raw;
}
export function buildEventSkeleton(currentUser) {
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js b/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js
index f8df2613546..4759eb418d1 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js
@@ -51,6 +51,7 @@ export default class DiscoursePostEventEvent {
@tracked duration;
@tracked rawInvitees;
@tracked location;
+ @tracked locationHtml;
@tracked url;
@tracked description;
@tracked descriptionHtml;
@@ -97,6 +98,7 @@ export default class DiscoursePostEventEvent {
this.rawInvitees = args.raw_invitees;
this.sampleInvitees = args.sample_invitees || [];
this.location = args.location;
+ this.locationHtml = args.location_html;
this.url = args.url;
this.description = args.description;
this.descriptionHtml = args.description_html;
@@ -211,6 +213,7 @@ export default class DiscoursePostEventEvent {
this.allDay = event.allDay;
this.duration = event.duration;
this.location = event.location;
+ this.locationHtml = event.locationHtml;
this.url = event.url;
this.timezone = event.timezone;
this.showLocalTime = event.showLocalTime;
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/modifiers/open-links-in-new-tab.js b/plugins/discourse-calendar/assets/javascripts/discourse/modifiers/open-links-in-new-tab.js
new file mode 100644
index 00000000000..cf8584ed5b4
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/modifiers/open-links-in-new-tab.js
@@ -0,0 +1,12 @@
+import { modifier } from "ember-modifier";
+
+export default modifier((element, [html]) => {
+ if (!html) {
+ return;
+ }
+
+ element.querySelectorAll("a[href]").forEach((link) => {
+ link.target = "_blank";
+ link.relList.add("noopener");
+ });
+});
diff --git a/plugins/discourse-calendar/db/post_migrate/20260723094850_unescape_event_location.rb b/plugins/discourse-calendar/db/post_migrate/20260723094850_unescape_event_location.rb
new file mode 100644
index 00000000000..acce0ea0e7e
--- /dev/null
+++ b/plugins/discourse-calendar/db/post_migrate/20260723094850_unescape_event_location.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+class UnescapeEventLocation < ActiveRecord::Migration[8.0]
+ def up
+ DB
+ .query("SELECT id, location FROM discourse_post_event_events WHERE location LIKE '%&%'")
+ .each do |event|
+ unescaped = CGI.unescapeHTML(CGI.unescapeHTML(event.location))
+ next if unescaped == event.location
+
+ DB.exec(
+ "UPDATE discourse_post_event_events SET location = :location WHERE id = :id",
+ location: unescaped,
+ id: event.id,
+ )
+ end
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/email_renderer.rb b/plugins/discourse-calendar/lib/discourse_post_event/email_renderer.rb
index 79616b863be..095b49ec145 100644
--- a/plugins/discourse-calendar/lib/discourse_post_event/email_renderer.rb
+++ b/plugins/discourse-calendar/lib/discourse_post_event/email_renderer.rb
@@ -93,14 +93,14 @@ module DiscoursePostEvent
location = event_node["data-location"]
return "" if location.blank?
- muted_row(PrettyText.cook(location))
+ muted_row(EventParser.cook_inline(location, post:))
end
def url_row
url = event_node["data-url"].to_s.strip
return "" if url.blank?
- href = web_url?(url) ? url : "https://#{url}"
+ href = EventParser.linkable_url?(url) ? url : "https://#{url}"
<<~HTML
<tr>
<td style="padding: 0 12px 12px;"><a href="#{CGI.escape_html(href)}">#{CGI.escape_html(url)}</a></td>
@@ -108,10 +108,6 @@ module DiscoursePostEvent
HTML
end
- def web_url?(url)
- url.match?(%r{\A(?:https?://|mailto:)}i)
- end
-
def invitees_row
return "" if @event.nil? || @event.standalone? || @event.minimal
@@ -123,7 +119,7 @@ module DiscoursePostEvent
def description_row
return "" if @event&.description.blank?
- muted_row(DiscoursePostEvent::EventParser.linkify_description(@event.description, post:))
+ muted_row(EventParser.cook_inline(@event.description, post:))
end
def dates
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/event_excerpt.rb b/plugins/discourse-calendar/lib/discourse_post_event/event_excerpt.rb
index 958576a0457..29dd9bd85d3 100644
--- a/plugins/discourse-calendar/lib/discourse_post_event/event_excerpt.rb
+++ b/plugins/discourse-calendar/lib/discourse_post_event/event_excerpt.rb
@@ -24,6 +24,7 @@ module DiscoursePostEvent
def summary(event_node)
event_name = event_node["data-name"].presence
location = event_node["data-location"].presence
+ location = EventParser.inline_text(location) if location
parts = []
# only repeat the name when it differs from the topic title, which is
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rb b/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rb
index ebc9564c4ea..774ac3ef1e3 100644
--- a/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rb
+++ b/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rb
@@ -2,8 +2,6 @@
module DiscoursePostEvent
class EventParser
- HTTP_URL_REGEXP = URI::DEFAULT_PARSER.make_regexp(%w[http https])
-
VALID_OPTIONS = [
:start,
:end,
@@ -26,6 +24,8 @@ module DiscoursePostEvent
:image,
]
+ LEGACY_ESCAPED_ATTRS = %w[data-location]
+
def self.extract_events(post)
cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
valid_options = valid_option_attributes
@@ -49,9 +49,9 @@ module DiscoursePostEvent
if value && valid_options.include?(name)
event ||= {}
- event[name.sub("data-", "").to_sym] = if %w[data-name data-url data-image].include?(
- name,
- )
+ value = CGI.unescapeHTML(value) if LEGACY_ESCAPED_ATTRS.include?(name)
+ event[name.sub("data-", "").to_sym] = case name
+ when "data-name", "data-url", "data-image", "data-location"
value
else
CGI.escapeHTML(value)
@@ -65,7 +65,7 @@ module DiscoursePostEvent
end
end
end
- event[:description] = doc.text.strip if event
+ event[:description] = to_markdown(doc) if event
event
end
.compact
@@ -81,26 +81,62 @@ module DiscoursePostEvent
"data-#{dasherized}"
end
- def self.linkify_description(text, post: nil)
+ INLINE_MARKDOWN_FEATURES = %w[emoji linkify]
+ INLINE_MARKDOWN_IT_RULES = %w[link linkify entity escape newline]
+ INLINE_CACHE_VERSION = 2
+
+ def self.cook_inline(text, post: nil)
text = text.to_s
+ add_nofollow = post.nil? || post.add_nofollow?
+
+ Discourse
+ .cache
+ .fetch(
+ "post-event-inline:#{INLINE_CACHE_VERSION}:#{Digest::SHA1.hexdigest(text)}:#{add_nofollow}",
+ expires_in: 1.week,
+ ) do
+ cooked =
+ PrettyText.cook(
+ text,
+ features_override: INLINE_MARKDOWN_FEATURES,
+ markdown_it_rules: INLINE_MARKDOWN_IT_RULES,
+ omit_nofollow: !add_nofollow,
+ )
+ fragment = Nokogiri::HTML5.fragment(cooked)
+ content = fragment.children.reject(&:blank?)
+ if content.length == 1 && content.first.name == "p"
+ content.first.inner_html
+ else
+ fragment.to_html
+ end
+ end
+ end
- html = +""
- cursor = 0
- text.scan(HTTP_URL_REGEXP) do
- match = Regexp.last_match
- html << ERB::Util.html_escape(text[cursor...match.begin(0)])
- escaped_url = ERB::Util.html_escape(match[0])
- html << "<a href=\"#{escaped_url}\">#{escaped_url}</a>"
- cursor = match.end(0)
- end
- html << ERB::Util.html_escape(text[cursor..])
- html.gsub!(/\r\n?|\n/, "<br>")
+ def self.inline_text(text)
+ cooked = cook_inline(text)
+ PrettyText.excerpt(cooked, cooked.length, strip_links: true, text_entities: true)
+ end
- doc = Nokogiri::HTML5.fragment(html)
- add_nofollow = post.nil? || post.add_nofollow?
- PrettyText.add_rel_attributes_to_user_content(doc, add_nofollow)
+ def self.linkable_url?(url)
+ url = url.to_s.downcase
+ schemes = %w[http https mailto] | SiteSetting.allowed_href_schemes.split("|")
+ schemes.any? { |scheme| url.start_with?("#{scheme}:") }
+ end
- doc.to_html
+ def self.to_markdown(node)
+ fragment = node.dup
+ fragment
+ .css("img.emoji")
+ .each { |img| img.replace(img.document.create_text_node(img["alt"].to_s)) }
+ fragment
+ .css("a[href]")
+ .each do |a|
+ href = a["href"].to_s
+ next if !linkable_url?(href)
+ markdown = a.text == href ? href : "[#{a.text}](#{href})"
+ a.replace(a.document.create_text_node(markdown))
+ end
+ fragment.text.strip
end
end
end
diff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb
index 447b215e2dd..341387f8c41 100644
--- a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb
+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb
@@ -123,7 +123,27 @@ describe DiscoursePostEvent::EventParser do
expect(events[0][:image]).to eq("upload://6c4fsAgNM6Npo7raNCPqVm2whzz.jpeg")
end
- it "extracts description as plain text" do
+ it "doesn't escape location" do
+ post_event = build_post user, <<~TXT
+ [event start="2020" location="Joe & Sons (downtown)"]
+ [/event]
+ TXT
+
+ events = parser.extract_events(post_event)
+ expect(events[0][:location]).to eq("Joe & Sons (downtown)")
+ end
+
+ it "decodes entities in location so escaped legacy raws self-heal" do
+ post_event = build_post user, <<~TXT
+ [event start="2020" location="Joe &amp; Sons"]
+ [/event]
+ TXT
+
+ events = parser.extract_events(post_event)
+ expect(events[0][:location]).to eq("Joe & Sons")
+ end
+
+ it "extracts description as inline markdown" do
post_event = build_post user, <<~TXT
[event start="2020"]
Check out https://example.com for details
@@ -134,45 +154,91 @@ describe DiscoursePostEvent::EventParser do
expect(events[0][:description]).to eq("Check out https://example.com for details")
end
- describe ".linkify_description" do
- it "wraps URLs in anchor tags" do
- expect(parser.linkify_description("Visit https://example.com for info")).to eq(
- 'Visit <a href="https://example.com" rel="noopener nofollow ugc">https://example.com</a> for info',
+ it "preserves markdown links, emoji and mentions in the description" do
+ post_event = build_post user, <<~TXT
+ [event start="2020"]
+ See [the agenda](https://agenda.example.com) :tada: with @system
+ [/event]
+ TXT
+
+ events = parser.extract_events(post_event)
+ expect(events[0][:description]).to eq(
+ "See [the agenda](https://agenda.example.com) :tada: with @system",
+ )
+ end
+
+ describe ".cook_inline" do
+ it "keeps plain text as plain text" do
+ expect(parser.cook_inline("Conference Room A")).to eq("Conference Room A")
+ end
+
+ it "renders markdown links" do
+ expect(parser.cook_inline("[RSVP](https://zoom.example.com/j/123)")).to eq(
+ '<a href="https://zoom.example.com/j/123" rel="noopener nofollow ugc">RSVP</a>',
)
end
- it "handles multiple URLs" do
- expect(parser.linkify_description("See https://a.com and https://b.com")).to eq(
- 'See <a href="https://a.com" rel="noopener nofollow ugc">https://a.com</a> and <a href="https://b.com" rel="noopener nofollow ugc">https://b.com</a>',
+ it "supports urls with balanced parentheses" do
+ result = parser.cook_inline("[Map](https://en.wikipedia.org/wiki/Sting_(musician))")
+
+ expect(Nokogiri::HTML5.fragment(result).at_css("a")["href"]).to eq(
+ "https://en.wikipedia.org/wiki/Sting_(musician)",
)
end
- it "leaves text without URLs unchanged" do
- expect(parser.linkify_description("No links here")).to eq("No links here")
+ it "links bare urls without onebox markup" do
+ result = parser.cook_inline("https://www.youtube.com/watch?v=abc")
+
+ link = Nokogiri::HTML5.fragment(result).at_css("a")
+ expect(link["href"]).to eq("https://www.youtube.com/watch?v=abc")
+ expect(link["class"]).to be_blank
end
- it "escapes HTML in description text" do
- expect(parser.linkify_description("Use <b>bold</b> & more at https://example.com")).to eq(
- 'Use &lt;b&gt;bold&lt;/b&gt; &amp; more at <a href="https://example.com" rel="noopener nofollow ugc">https://example.com</a>',
- )
+ it "links scheme-less urls" do
+ result = parser.cook_inline("zoom.us/j/123")
+
+ expect(Nokogiri::HTML5.fragment(result).at_css("a")["href"]).to eq("http://zoom.us/j/123")
+ end
+
+ it "does not render markdown beyond links and emoji" do
+ expect(parser.cook_inline("**Room 4** # not a heading")).to eq("**Room 4** # not a heading")
+ end
+
+ it "renders emoji" do
+ expect(parser.cook_inline("Party :tada:")).to include("images/emoji")
+ end
+
+ it "renders newlines as line breaks" do
+ expect(parser.cook_inline("line one\nline two")).to eq("line one<br>\nline two")
+ end
+
+ it "escapes html" do
+ result = parser.cook_inline("<script>alert(1)</script> & <b>Room</b>")
+
+ expect(result).not_to include("<script>")
+ expect(result).not_to include("<b>")
+ expect(result).to include("&amp;")
end
- it "omits nofollow for staff posts" do
+ it "rejects non-http link destinations" do
+ expect(parser.cook_inline("[click](javascript:alert(1))")).not_to include("href")
+ end
+
+ it "omits nofollow for posts that do not require it" do
staff_user = Fabricate(:admin)
post = Fabricate(:post, user: staff_user)
- expect(parser.linkify_description("See https://example.com", post: post)).to eq(
+ expect(parser.cook_inline("See https://example.com", post: post)).to eq(
'See <a href="https://example.com">https://example.com</a>',
)
end
+ end
- it "does not leak markup out of the generated href when a url is followed by html" do
- result = parser.linkify_description('http://example.com/"><script>alert(1)</script>')
-
- doc = Nokogiri::HTML5.fragment(result)
- expect(doc.css("script")).to be_empty
- expect(doc.at_css("a")["href"]).to eq("http://example.com/")
- expect(result).not_to include("<script>")
+ describe ".inline_text" do
+ it "flattens markdown links to their label" do
+ expect(parser.inline_text("[RSVP](https://zoom.example.com) at Joe & Sons :tada:")).to eq(
+ "RSVP at Joe & Sons :tada:",
+ )
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 4c9a649a783..3ee2545d7a6 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
@@ -85,6 +85,9 @@ describe PrettyText do
context "when the event has a location" do
let(:post_1) { create_post_with_event(user_1, 'location="Conference Room A"') }
let(:post_2) { create_post_with_event(user_1, 'location="https://maps.example.com"') }
+ let(:post_3) do
+ create_post_with_event(user_1, 'location="[RSVP](https://zoom.example.com/j/123)"')
+ end
it "displays the location" do
cooked = PrettyText.cook(post_1.raw)
@@ -93,12 +96,20 @@ describe PrettyText do
expect(result).to include("Conference Room A")
end
- it "cooks links in the location (matching the on-site card)" do
+ it "links bare urls in the location (matching the on-site card)" do
cooked = PrettyText.cook(post_2.raw)
result = PrettyText.format_for_email(cooked, post_2)
expect(result).to include('href="https://maps.example.com"')
end
+
+ it "renders markdown links in the location (matching the on-site card)" do
+ cooked = PrettyText.cook(post_3.raw)
+ result = PrettyText.format_for_email(cooked, post_3)
+
+ expect(result).to include('href="https://zoom.example.com/j/123"')
+ expect(result).to include(">RSVP</a>")
+ end
end
context "when the event has a url" do
diff --git a/plugins/discourse-calendar/spec/migrations/unescape_event_location_spec.rb b/plugins/discourse-calendar/spec/migrations/unescape_event_location_spec.rb
new file mode 100644
index 00000000000..fb5193c1a67
--- /dev/null
+++ b/plugins/discourse-calendar/spec/migrations/unescape_event_location_spec.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+require Rails.root.join(
+ "plugins/discourse-calendar/db/post_migrate/20260723094850_unescape_event_location.rb",
+ )
+
+RSpec.describe UnescapeEventLocation do
+ subject(:migrate) { described_class.new.up }
+
+ before do
+ @original_verbose = ActiveRecord::Migration.verbose
+ ActiveRecord::Migration.verbose = false
+ end
+
+ after { ActiveRecord::Migration.verbose = @original_verbose }
+
+ it "unescapes stored locations exactly two levels, matching re-derivation from raw" do
+ escaped = Fabricate(:event, location: "Joe &amp; Sons (downtown)")
+ escalated = Fabricate(:event, location: "Joe &amp;amp; Sons")
+ plain = Fabricate(:event, location: "Tom & Jerry")
+ no_entities = Fabricate(:event, location: "Conference Room A")
+ no_location = Fabricate(:event)
+
+ migrate
+
+ expect(escaped.reload.location).to eq("Joe & Sons (downtown)")
+ expect(escalated.reload.location).to eq("Joe & Sons")
+ expect(plain.reload.location).to eq("Tom & Jerry")
+ expect(no_entities.reload.location).to eq("Conference Room A")
+ expect(no_location.reload.location).to be_nil
+ end
+end
diff --git a/plugins/discourse-calendar/spec/requests/events_controller_spec.rb b/plugins/discourse-calendar/spec/requests/events_controller_spec.rb
index a4881c62d62..1efd4d2cb14 100644
--- a/plugins/discourse-calendar/spec/requests/events_controller_spec.rb
+++ b/plugins/discourse-calendar/spec/requests/events_controller_spec.rb
@@ -75,7 +75,7 @@ module DiscoursePostEvent
"description_html"
]
expect(description_html).to include('<a href="https://example.com"')
- expect(description_html).to include("<br>")
+ expect(description_html).to include("<p>Bring snacks</p>")
end
it "should return events in ics format" do
diff --git a/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb b/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb
index b534091220d..0c725618ecd 100644
--- a/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb
+++ b/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb
@@ -11,6 +11,26 @@ describe DiscoursePostEvent::EventSerializer do
fab!(:topic) { Fabricate(:topic, category: category) }
fab!(:post) { Fabricate(:post, topic: topic) }
+ context "with a location" do
+ fab!(:event) { Fabricate(:event, post: post, location: "[RSVP](https://zoom.example.com)") }
+
+ it "serializes location_html with rendered links" do
+ json = DiscoursePostEvent::EventSerializer.new(event, scope: Guardian.new).as_json
+
+ expect(json[:event][:location_html]).to eq(
+ DiscoursePostEvent::EventParser.cook_inline(event.location, post: event.post),
+ )
+ expect(json[:event][:location_html]).to include('href="https://zoom.example.com"')
+ end
+
+ it "omits location_html without a location" do
+ event.update_columns(location: nil)
+ json = DiscoursePostEvent::EventSerializer.new(event, scope: Guardian.new).as_json
+
+ expect(json[:event]).not_to have_key(:location_html)
+ end
+ end
+
context "with a private event" do
fab!(:private_event) do
Fabricate(:event, post: post, status: DiscoursePostEvent::Event.statuses[:private])
diff --git a/plugins/discourse-calendar/spec/system/composer/event_location_spec.rb b/plugins/discourse-calendar/spec/system/composer/event_location_spec.rb
new file mode 100644
index 00000000000..66671236b75
--- /dev/null
+++ b/plugins/discourse-calendar/spec/system/composer/event_location_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+describe "Composer - Event location" do
+ fab!(:admin)
+
+ let(:composer) { PageObjects::Components::Composer.new }
+ let(:markdown_location) { "[RSVP](https://zoom.example.com/j/123)" }
+ let(:event_markup) { <<~MD.strip }
+ [event start="2026-08-01 18:00" status="public" timezone="UTC" location="#{markdown_location}"]
+ [/event]
+ MD
+
+ before do
+ SiteSetting.calendar_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ sign_in(admin)
+ end
+
+ it "renders a markdown-link location on the posted card and keeps it stable when edited in the markdown composer" do
+ visit("/new-topic")
+ composer.fill_title("Event with a markdown location")
+ composer.fill_content(event_markup)
+
+ expect(page.find(".composer-event__location-input").value).to eq(markdown_location)
+
+ composer.create
+
+ expect(page).to have_css(
+ ".event-location a[href='https://zoom.example.com/j/123']",
+ text: "RSVP",
+ )
+
+ topic = Topic.find_by(title: "Event with a markdown location")
+ find("#post_1 .show-more-actions").click
+ find("#post_1 .edit").click
+
+ expect(page.find(".composer-event__location-input").value).to eq(markdown_location)
+
+ composer.create
+
+ expect(page).to have_css(".event-location a", text: "RSVP")
+ expect(DiscoursePostEvent::Event.find(topic.first_post.id).location).to eq(markdown_location)
+ end
+
+ it "shows the link affordance for scheme-less urls, matching what the card links" do
+ visit("/new-topic")
+ composer.fill_title("Event with a scheme-less location")
+ composer.fill_content(<<~MD.strip)
+ [event start="2026-08-01 18:00" status="public" timezone="UTC" location="zoom.us/j/123"]
+ [/event]
+ MD
+
+ expect(page).to have_css(".composer-event__location-external-link[href='http://zoom.us/j/123']")
+
+ composer.create
+
+ expect(page).to have_css(".event-location a", text: "zoom.us/j/123")
+ end
+
+ context "with the rich editor" do
+ include_context "with prosemirror editor"
+
+ it "round-trips a markdown-link location through the event node" do
+ open_composer
+ composer.toggle_rich_editor
+ composer.fill_content(event_markup)
+ composer.toggle_rich_editor
+
+ expect(rich.find(".composer-event__location-input").value).to eq(markdown_location)
+
+ composer.toggle_rich_editor
+
+ expect(composer).to have_value(%r{location="\[RSVP\]\(https://zoom\.example\.com/j/123\)"})
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/spec/system/post_event_spec.rb b/plugins/discourse-calendar/spec/system/post_event_spec.rb
index 5e043fa3f27..0689d97c22a 100644
--- a/plugins/discourse-calendar/spec/system/post_event_spec.rb
+++ b/plugins/discourse-calendar/spec/system/post_event_spec.rb
@@ -83,7 +83,7 @@ describe "Post event" do
find(".d-editor-input").click
expect(composer).to have_value <<~EVENT.strip
- [event start="2025-06-15 15:00" status="public" timezone="#{timezone}" end="2025-06-15 16:00" reminders="notification.15.minutes"]
+ [event start="2025-06-15 15:00" status=public timezone=#{timezone} end="2025-06-15 16:00" reminders=notification.15.minutes]
foo
bar
[/event]
@@ -120,8 +120,8 @@ describe "Post event" do
preview.find(".composer-event__all-day-toggle .d-toggle-switch__label").click
find(".d-editor-input").click
- expect(composer).to have_value(/start="2024-06-01"/)
- expect(composer).to have_value(/end="2024-06-03"/)
+ expect(composer).to have_value(/start=2024-06-01/)
+ expect(composer).to have_value(/end=2024-06-03/)
end
context "when showLocalTime is set and the event crosses midnight relative to the viewer",
diff --git a/plugins/discourse-calendar/spec/system/upcoming_events_spec.rb b/plugins/discourse-calendar/spec/system/upcoming_events_spec.rb
index dbdbd7dfe1f..5caa2e9c496 100644
--- a/plugins/discourse-calendar/spec/system/upcoming_events_spec.rb
+++ b/plugins/discourse-calendar/spec/system/upcoming_events_spec.rb
@@ -117,9 +117,8 @@ describe "Upcoming Events" do
find("a", text: "Event with long description").click
expect(post_event_page).to have_description_clamped
- expect(post_event_page).to have_description(
- "Join us for a great event with bold text and more details!",
- )
+ expect(post_event_page).to have_description("Join us for a great event")
+ expect(post_event_page).to have_description("with bold text and more details!")
expect(post_event_page).to have_description_toggle
post_event_page.click_description_toggle
diff --git a/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.js b/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.js
index 3cb78543cd7..c077579af90 100644
--- a/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.js
+++ b/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.js
@@ -65,7 +65,7 @@ acceptance("Post event - composer", function (needs) {
assert
.dom(".d-editor-input")
.hasValue(
- `[event start="2022-07-01 12:00" status="public" timezone="Europe/Paris" end="2022-07-01 13:00" reminders="notification.15.minutes"]\n[/event]`,
+ `[event start="2022-07-01 12:00" status=public timezone=Europe/Paris end="2022-07-01 13:00" reminders=notification.15.minutes]\n[/event]`,
"bbcode is correct"
);
});
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
index a920997be83..0251b717faf 100644
--- 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
@@ -9,7 +9,10 @@ module(
setupRenderingTest(hooks);
test("renders a plain-text location", async function (assert) {
- this.event = { location: "Conference Room A" };
+ this.event = {
+ location: "Conference Room A",
+ locationHtml: "Conference Room A",
+ };
await render(
<template>
@@ -22,8 +25,12 @@ module(
.includesText("Conference Room A", "shows the location text");
});
- test("renders a URL location as a plain link, never a onebox", async function (assert) {
- this.event = { location: "https://youtube.com/watch?v=123" };
+ test("renders server-rendered links and opens them in a new tab", async function (assert) {
+ this.event = {
+ location: "[RSVP](https://zoom.us/j/123) (room 2)",
+ locationHtml:
+ '<a href="https://zoom.us/j/123" rel="nofollow ugc">RSVP</a> (room 2)',
+ };
await render(
<template>
@@ -33,19 +40,38 @@ module(
assert
.dom(".event-location a")
- .hasAttribute("href", "https://youtube.com/watch?v=123")
- .hasText("https://youtube.com/watch?v=123", "shows the raw url");
+ .hasAttribute("href", "https://zoom.us/j/123")
+ .hasAttribute("target", "_blank")
+ .hasAttribute("rel", "nofollow ugc noopener")
+ .hasText("RSVP", "shows the link label");
+ assert
+ .dom(".event-location")
+ .includesText("(room 2)", "keeps the text around the link");
+ });
+
+ test("renders a URL-only location for non-Zoom events", async function (assert) {
+ this.event = {
+ location: "https://youtube.com/watch?v=123",
+ locationHtml:
+ '<a href="https://youtube.com/watch?v=123" rel="nofollow ugc">https://youtube.com/watch?v=123</a>',
+ };
+
+ await render(
+ <template>
+ <DiscoursePostEventLocation @event={{this.event}} />
+ </template>
+ );
+
assert
.dom(".event-location a")
- .doesNotHaveClass(
- "onebox",
- "leaves no onebox markup for the composer's onebox pass to hydrate"
- );
+ .hasAttribute("href", "https://youtube.com/watch?v=123");
});
test("does not render the URL for Zoom-only livestreams", async function (assert) {
this.event = {
location: "https://zoom.us/j/123",
+ locationHtml:
+ '<a href="https://zoom.us/j/123" rel="nofollow ugc">https://zoom.us/j/123</a>',
isZoomLivestream: true,
};
@@ -56,12 +82,17 @@ module(
);
assert
- .dom(".event-location a")
+ .dom(".event-location")
.doesNotExist("does not show the location URL");
});
- test("links URLs inside surrounding text", async function (assert) {
- this.event = { location: "Zoom: https://zoom.us/j/123 (room 2)" };
+ test("renders a Zoom livestream location that is more than the URL", async function (assert) {
+ this.event = {
+ location: "Zoom: https://zoom.us/j/123 (room 2)",
+ locationHtml:
+ 'Zoom: <a href="https://zoom.us/j/123" rel="nofollow ugc">https://zoom.us/j/123</a> (room 2)',
+ isZoomLivestream: true,
+ };
await render(
<template>
@@ -69,15 +100,19 @@ module(
</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");
+ assert.dom(".event-location").includesText("(room 2)");
+ });
+
+ test("renders nothing without a location", async function (assert) {
+ this.event = {};
+
+ await render(
+ <template>
+ <DiscoursePostEventLocation @event={{this.event}} />
+ </template>
+ );
+
+ assert.dom(".event-location").doesNotExist();
});
}
);
diff --git a/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js b/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js
index d63817417eb..ac9d74cf23e 100644
--- a/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js
+++ b/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js
@@ -70,7 +70,7 @@ module("Unit | Lib | raw-event-helper", function () {
assert.strictEqual(
replaceRaw(params, raw),
- 'Some text \n[event param1="newValue1" param2="value2"]\n[/event]\n more text',
+ "Some text \n[event param1=newValue1 param2=value2]\n[/event]\n more text",
"updates existing parameters and adds new ones"
);
@@ -79,12 +79,6 @@ module("Unit | Lib | raw-event-helper", function () {
"returns false when no event tag is found"
);
- assert.strictEqual(
- replaceRaw({ foo: 'bar"quoted' }, '[event original="value"]\n[/event]'),
- '[event foo="barquoted"]\n[/event]',
- "escapes double quotes in parameter values"
- );
-
assert.strictEqual(
replaceRaw({}, '[event param1="value1"]\n[/event]'),
"[event ]\n[/event]",
@@ -96,7 +90,7 @@ module("Unit | Lib | raw-event-helper", function () {
{ name: "", location: "Paris" },
'[event original="value"]\n[/event]'
),
- '[event location="Paris"]\n[/event]',
+ "[event location=Paris]\n[/event]",
"omits empty name parameter"
);
@@ -105,7 +99,7 @@ module("Unit | Lib | raw-event-helper", function () {
{ name: " ", location: "Berlin" },
'[event original="value"]\n[/event]'
),
- '[event location="Berlin"]\n[/event]',
+ "[event location=Berlin]\n[/event]",
"omits whitespace-only name parameter"
);
});
@@ -122,13 +116,47 @@ module("Unit | Lib | raw-event-helper", function () {
'[event start="2024-06-15 10:00" name="Demo"]\nbody line\n[/event]'
);
- assert.strictEqual(
- buildEventBlock(parsed.attrs, parsed.description),
- parsed.full,
+ const rebuilt = buildEventBlock(parsed.attrs, parsed.description);
+ assert.deepEqual(
+ parseEventBlock(rebuilt).attrs,
+ parsed.attrs,
"buildEventBlock round-trips parsed values"
);
});
+ test("parseEventBlock keeps brackets inside quoted attr values", function (assert) {
+ const parsed = parseEventBlock(
+ '[event start="2024-06-15" location="[RSVP](https://zoom.example.com/j/123)"]\n[/event]'
+ );
+
+ assert.deepEqual(parsed.attrs, {
+ start: "2024-06-15",
+ location: "[RSVP](https://zoom.example.com/j/123)",
+ });
+ });
+
+ test("parseEventBlock reads the quote pairs the rich editor emits", function (assert) {
+ const parsed = parseEventBlock(
+ '[event start=«2024-06-15 10:00» location=“Sam\'s "Release"”]\n[/event]'
+ );
+
+ assert.deepEqual(parsed.attrs, {
+ start: "2024-06-15 10:00",
+ location: 'Sam\'s "Release"',
+ });
+ });
+
+ test("buildEventBlock preserves values containing quotes", function (assert) {
+ const attrs = { location: 'Sam\'s "Release" party' };
+ const rebuilt = buildEventBlock(attrs, "");
+
+ assert.deepEqual(
+ parseEventBlock(rebuilt).attrs,
+ attrs,
+ "quotes survive the serialize/parse round-trip"
+ );
+ });
+
test("parseEventBlock returns null when no event tag", function (assert) {
assert.strictEqual(parseEventBlock("no event here"), null);
assert.strictEqual(parseEventBlock(""), null);