Skip to content

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

FEATURE: Implement chat transcripts in rich editor (#31819)

Martin Brennand3c2bd015dd0
diff --git a/app/assets/javascripts/discourse/app/lib/text.js b/app/assets/javascripts/discourse/app/lib/text.js
index 68be2ed800e..ca8808fa26f 100644
--- a/app/assets/javascripts/discourse/app/lib/text.js
+++ b/app/assets/javascripts/discourse/app/lib/text.js
@@ -152,3 +152,21 @@ export function humanizeList(listItems) {
].join(" ");
}
}
+
+export function buildBBCodeAttrs(attrs, opts = {}) {
+ opts.skipAttrs = opts.skipAttrs ?? [];
+
+ return Object.keys(attrs)
+ .map((key) => {
+ if (
+ attrs[key] === null ||
+ attrs[key] === undefined ||
+ opts.skipAttrs.includes(key)
+ ) {
+ return null;
+ }
+ return `${key}="${attrs[key]}"`;
+ })
+ .filter(Boolean)
+ .join(" ");
+}
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js
index 27151455868..abc32460012 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js
@@ -3,6 +3,8 @@ import { StepMap } from "prosemirror-transform";
export { getLinkify, isBoundary, isWhiteSpace } from "../lib/markdown-it";
+export { buildBBCodeAttrs } from "discourse/lib/text";
+
// https://discuss.prosemirror.net/t/input-rules-for-wrapping-marks/537
export function markInputRule(regexp, markType, getAttrs) {
return new InputRule(
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js
index b0b5d6ee660..50ad0ac9aca 100644
--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js
@@ -9,6 +9,7 @@ import { withPluginApi } from "discourse/lib/plugin-api";
import { i18n } from "discourse-i18n";
import { clearChatComposerButtons } from "discourse/plugins/chat/discourse/lib/chat-composer-buttons";
import ChannelHashtagType from "discourse/plugins/chat/discourse/lib/hashtag-types/channel";
+import richEditorExtension from "../../lib/rich-editor-extension";
import ChatHeaderIcon from "../components/chat/header/icon";
import chatStyleguide from "../components/styleguide/organisms/chat";
@@ -177,6 +178,8 @@ class ChatSetupInit {
category: "organisms",
id: "chat",
});
+
+ api.registerRichEditorExtension(richEditorExtension);
});
}
diff --git a/plugins/chat/assets/javascripts/lib/discourse-markdown/chat-transcript.js b/plugins/chat/assets/javascripts/lib/discourse-markdown/chat-transcript.js
index e323b9a48bc..ea75ea44c5e 100644
--- a/plugins/chat/assets/javascripts/lib/discourse-markdown/chat-transcript.js
+++ b/plugins/chat/assets/javascripts/lib/discourse-markdown/chat-transcript.js
@@ -1,13 +1,16 @@
import { performEmojiUnescape } from "pretty-text/emoji";
import { i18n } from "discourse-i18n";
+// NOTE: When updating this file you also must consider the ProseMirror rich editor extension
+// for chat transcripts, because it manually constructs the same HTML structure as this rule.
+
let customMarkdownCookFn;
const chatTranscriptRule = {
tag: "chat",
replace: function (state, tagInfo, content) {
- // shouldn't really happen but we don't want to break rendering if it does
+ // Shouldn't really happen but we don't want to break rendering if it does
if (!customMarkdownCookFn) {
return;
}
@@ -15,6 +18,8 @@ const chatTranscriptRule = {
const options = state.md.options.discourse;
const [username, messageIdStart, messageTimeStart] =
(tagInfo.attrs.quote && tagInfo.attrs.quote.split(";")) || [];
+
+ // NOTE: Reactions are only included when archiving a channel, not when quoting a message
const reactions = tagInfo.attrs.reactions;
const multiQuote = !!tagInfo.attrs.multiQuote;
const noLink = !!tagInfo.attrs.noLink;
@@ -31,14 +36,15 @@ const chatTranscriptRule = {
}
const isThread = threadId && content.includes("[chat");
- let wrapperDivToken = state.push("div_chat_transcript_wrap", "div", 1);
-
- if (channelName && multiQuote) {
- let metaDivToken = state.push("div_chat_transcript_meta", "div", 1);
- metaDivToken.attrs = [["class", "chat-transcript-meta"]];
- const channelToken = state.push("html_inline", "", 0);
+ const wrapperDivToken = state.push(
+ "div_chat_transcript_wrap_open",
+ "div",
+ 1
+ );
- const unescapedChannelName = performEmojiUnescape(channelName, {
+ let unescapedChannelName;
+ if (channelName) {
+ unescapedChannelName = performEmojiUnescape(channelName, {
getURL: options.getURL,
emojiSet: options.emojiSet,
emojiCDNUrl: options.emojiCDNUrl,
@@ -46,12 +52,22 @@ const chatTranscriptRule = {
inlineEmoji: options.inlineEmoji,
lazy: true,
});
+ }
+
+ if (channelName && multiQuote) {
+ const metaDivToken = state.push(
+ "div_chat_transcript_meta_open",
+ "div",
+ 1
+ );
+ metaDivToken.attrs = [["class", "chat-transcript-meta"]];
+ const channelToken = state.push("html_inline", "", 0);
channelToken.content = i18n("chat.quote.original_channel", {
channel: unescapedChannelName,
channelLink,
});
- state.push("div_chat_transcript_meta", "div", -1);
+ state.push("div_chat_transcript_meta_close", "div", -1);
}
if (isThread) {
@@ -64,18 +80,17 @@ const chatTranscriptRule = {
const threadHeaderToken = state.push("div_thread_header_open", "div", 1);
threadHeaderToken.attrs = [["class", "chat-transcript-thread-header"]];
- const thread_svg = state.push("svg_thread_header_open", "svg", 1);
- thread_svg.block = false;
- thread_svg.attrs = [
+ const threadSvgHeader = state.push("svg_thread_header_open", "svg", 1);
+ threadSvgHeader.block = false;
+ threadSvgHeader.attrs = [
["class", "fa d-icon d-icon-discourse-threads svg-icon svg-node"],
];
- state.push(thread_svg);
- let thread_use = state.push("use_svg_thread_open", "use", 1);
- thread_use.block = false;
- thread_use.attrs = [["href", "#discourse-threads"]];
- state.push(thread_use);
- state.push(state.push("use_svg_thread_close", "use", -1));
- state.push(state.push("svg_thread_header_close", "svg", -1));
+
+ const threadUseSvg = state.push("use_svg_thread_open", "use", 1);
+ threadUseSvg.block = false;
+ threadUseSvg.attrs = [["href", "#discourse-threads"]];
+ state.push("use_svg_thread_close", "use", -1);
+ state.push("svg_thread_header_close", "svg", -1);
const threadTitleContainerToken = state.push(
"span_thread_title_open",
@@ -104,17 +119,22 @@ const chatTranscriptRule = {
state.push("div_thread_header_close", "div", -1);
}
- let wrapperClasses = ["chat-transcript"];
+ const wrapperClasses = ["chat-transcript"];
if (tagInfo.attrs.chained) {
wrapperClasses.push("chat-transcript-chained");
}
+ wrapperDivToken.content = content;
wrapperDivToken.attrs = [["class", wrapperClasses.join(" ")]];
wrapperDivToken.attrs.push(["data-message-id", messageIdStart]);
wrapperDivToken.attrs.push(["data-username", username]);
wrapperDivToken.attrs.push(["data-datetime", messageTimeStart]);
+ if (tagInfo.attrs.chained) {
+ wrapperDivToken.attrs.push(["data-chained", "true"]);
+ }
+
if (reactions) {
wrapperDivToken.attrs.push(["data-reactions", reactions]);
}
@@ -127,12 +147,24 @@ const chatTranscriptRule = {
wrapperDivToken.attrs.push(["data-channel-id", channelId]);
}
- let userDivToken = state.push("div_chat_transcript_user", "div", 1);
+ if (multiQuote) {
+ wrapperDivToken.attrs.push(["data-multiquote", "true"]);
+ }
+
+ if (threadId) {
+ wrapperDivToken.attrs.push(["data-thread-id", threadId]);
+ }
+
+ if (threadTitle) {
+ wrapperDivToken.attrs.push(["data-thread-title", threadTitle]);
+ }
+
+ const userDivToken = state.push("div_chat_transcript_user_open", "div", 1);
userDivToken.attrs = [["class", "chat-transcript-user"]];
// start: user avatar
- let avatarDivToken = state.push(
- "div_chat_transcript_user_avatar",
+ const avatarDivToken = state.push(
+ "div_chat_transcript_user_avatar_open",
"div",
1
);
@@ -148,11 +180,15 @@ const chatTranscriptRule = {
avatarImgToken.content = avatarImg;
}
- state.push("div_chat_transcript_user_avatar", "div", -1);
+ state.push("div_chat_transcript_user_avatar_close", "div", -1);
// end: user avatar
// start: username
- let usernameDivToken = state.push("div_chat_transcript_username", "div", 1);
+ const usernameDivToken = state.push(
+ "div_chat_transcript_username_open",
+ "div",
+ 1
+ );
usernameDivToken.attrs = [["class", "chat-transcript-username"]];
let displayName;
@@ -165,11 +201,15 @@ const chatTranscriptRule = {
const usernameToken = state.push("html_inline", "", 0);
usernameToken.content = displayName;
- state.push("div_chat_transcript_username", "div", -1);
+ state.push("div_chat_transcript_username_close", "div", -1);
// end: username
// start: time + link to message
- let datetimeDivToken = state.push("div_chat_transcript_datetime", "div", 1);
+ const datetimeDivToken = state.push(
+ "div_chat_transcript_datetime_open",
+ "div",
+ 1
+ );
datetimeDivToken.attrs = [["class", "chat-transcript-datetime"]];
// for some cases, like archiving, we don't want the link to the
@@ -206,7 +246,7 @@ const chatTranscriptRule = {
linkToken.block = false;
}
- state.push("div_chat_transcript_datetime", "div", -1);
+ state.push("div_chat_transcript_datetime_close", "div", -1);
// end: time + link to message
// start: channel link for !multiQuote
@@ -217,15 +257,19 @@ const chatTranscriptRule = {
["href", channelLink],
];
let inlineTextToken = state.push("html_inline", "", 0);
- inlineTextToken.content = `#${channelName}`;
+ inlineTextToken.content = `#${unescapedChannelName}`;
channelLinkToken = state.push("link_close", "a", -1);
channelLinkToken.block = false;
}
// end: channel link for !multiQuote
- state.push("div_chat_transcript_user", "div", -1);
+ state.push("div_chat_transcript_user_close", "div", -1);
- let messagesToken = state.push("div_chat_transcript_messages", "div", 1);
+ const messagesToken = state.push(
+ "div_chat_transcript_messages_open",
+ "div",
+ 1
+ );
messagesToken.attrs = [["class", "chat-transcript-messages"]];
if (isThread) {
@@ -256,8 +300,8 @@ const chatTranscriptRule = {
}
if (reactions) {
- let emojiHtmlCache = {};
- let reactionsToken = state.push(
+ const emojiHtmlCache = {};
+ const reactionsToken = state.push(
"div_chat_transcript_reactions",
"div",
1
@@ -290,8 +334,8 @@ const chatTranscriptRule = {
state.push("div_chat_transcript_reactions", "div", -1);
}
- state.push("div_chat_transcript_messages", "div", -1);
- state.push("div_chat_transcript_wrap", "div", -1);
+ state.push("div_chat_transcript_messages_close", "div", -1);
+ state.push("div_chat_transcript_wrap_close", "div", -1);
return true;
},
};
@@ -341,7 +385,7 @@ export function setup(helper) {
const chatAdditionalOpts = opts.discourse.additionalOptions.chat;
- // we need to be able to quote images from chat, but the image rule is usually
+ // We need to be able to quote images from chat, but the image rule is usually
// banned for chat messages
const markdownItRules =
chatAdditionalOpts.limited_pretty_text_markdown_rules.concat("image");
diff --git a/plugins/chat/assets/javascripts/lib/rich-editor-extension.js b/plugins/chat/assets/javascripts/lib/rich-editor-extension.js
new file mode 100644
index 00000000000..b2d67465994
--- /dev/null
+++ b/plugins/chat/assets/javascripts/lib/rich-editor-extension.js
@@ -0,0 +1,244 @@
+import getURL from "discourse/lib/get-url";
+import { emojiUnescape } from "discourse/lib/text";
+import { i18n } from "discourse-i18n";
+
+/** @type {RichEditorExtension} */
+const extension = {
+ nodeSpec: {
+ chat: {
+ attrs: {
+ messageId: {},
+ username: {},
+ datetime: {},
+ channel: {},
+ channelId: {},
+ html: {},
+ rawContent: {},
+ multiQuote: {},
+ chained: {},
+ threadId: { default: null },
+ threadTitle: { default: null },
+ threadHtml: { default: null },
+ },
+ group: "block",
+ isolating: true,
+ selectable: true,
+ parseDOM: [{ tag: "div.chat-transcript" }],
+ toDOM(node) {
+ // NOTE: This HTML representation of the node in a lot of ways is duplicated from
+ // the chat transcript markdown-it rule, this is unavoidable unless we completely
+ // decouple the token generation from the HTML generation, which is a lot of work,
+ // so this is acceptable for now.
+
+ const wrapperElement = document.createElement("div");
+ wrapperElement.classList.add("chat-transcript");
+
+ if (node.attrs.chained) {
+ wrapperElement.classList.add("chat-transcript-chained");
+ }
+
+ let metaElement;
+ let channelLinkElement;
+ if (node.attrs.channel) {
+ if (node.attrs.multiQuote) {
+ metaElement = document.createElement("div");
+ metaElement.classList.add("chat-transcript-meta");
+
+ const channelLink = node.attrs.channelId
+ ? getURL(`/chat/c/-/${node.attrs.channelId}`)
+ : null;
+
+ metaElement.innerHTML = i18n("chat.quote.original_channel", {
+ channel: emojiUnescape(node.attrs.channel),
+ channelLink,
+ });
+ } else {
+ channelLinkElement = document.createElement("a");
+ channelLinkElement.classList.add("chat-transcript-channel");
+ channelLinkElement.href = getURL(
+ `/chat/c/-/${node.attrs.channelId}`
+ );
+ channelLinkElement.innerHTML = `#${emojiUnescape(
+ node.attrs.channel
+ )}`;
+ }
+ }
+
+ const userElement = document.createElement("div");
+ userElement.classList.add("chat-transcript-user");
+
+ // TODO (martin) Need to use current user's timezone here when we have
+ // that available.
+ const formattedDateTime = moment(node.attrs.datetime).format(
+ i18n("dates.long_no_year")
+ );
+ userElement.innerHTML = `
+ <span class="chat-transcript-username">${node.attrs.username}</span>
+ <span class="chat-transcript-datetime">${formattedDateTime}</span>
+ `;
+
+ const messagesElement = document.createElement("div");
+ messagesElement.classList.add("chat-transcript-messages");
+ messagesElement.innerHTML = node.attrs.html;
+
+ if (metaElement) {
+ wrapperElement.appendChild(metaElement);
+ }
+
+ if (node.attrs.threadId) {
+ const threadDetailsElement = document.createElement("details");
+ const threadSummaryElement = document.createElement("summary");
+
+ const threadElement = document.createElement("div");
+ threadElement.classList.add("chat-transcript-thread");
+
+ const threadHeaderElement = document.createElement("div");
+ threadHeaderElement.classList.add("chat-transcript-thread-header");
+ threadHeaderElement.innerHTML = `
+ <svg class="fa d-icon d-icon-discourse-threads svg-icon svg-node">
+ <use href="#discourse-threads"></use>
+ </svg>`;
+
+ const threadTitleElement = document.createElement("span");
+ threadTitleElement.classList.add(
+ "chat-transcript-thread-header__title"
+ );
+ threadTitleElement.innerHTML = node.attrs.threadTitle
+ ? emojiUnescape(node.attrs.threadTitle)
+ : i18n("chat.quote.default_thread_title");
+
+ threadHeaderElement.appendChild(threadTitleElement);
+ threadElement.appendChild(threadHeaderElement);
+ threadElement.appendChild(userElement);
+
+ if (channelLinkElement) {
+ userElement.appendChild(channelLinkElement);
+ }
+
+ threadElement.appendChild(messagesElement);
+ threadSummaryElement.appendChild(threadElement);
+ threadDetailsElement.appendChild(threadSummaryElement);
+
+ if (node.attrs.threadHtml) {
+ threadDetailsElement.innerHTML += node.attrs.threadHtml;
+ }
+
+ wrapperElement.appendChild(threadDetailsElement);
+ } else {
+ wrapperElement.appendChild(userElement);
+
+ if (channelLinkElement) {
+ userElement.appendChild(channelLinkElement);
+ }
+
+ wrapperElement.appendChild(messagesElement);
+ }
+
+ return wrapperElement;
+ },
+ },
+ },
+ serializeNode({ utils: { buildBBCodeAttrs } }) {
+ return {
+ chat(state, node) {
+ let bbCodeAttrs = `quote="${node.attrs.username};${node.attrs.messageId};${node.attrs.datetime}"`;
+ bbCodeAttrs +=
+ " " +
+ buildBBCodeAttrs(node.attrs, {
+ skipAttrs: [
+ "username",
+ "messageId",
+ "datetime",
+ "rawContent",
+ "html",
+ "threadHtml",
+ ],
+ });
+
+ state.write(`[chat ${bbCodeAttrs}]\n`);
+ state.write(node.attrs.rawContent);
+ state.write("\n[/chat]\n");
+ },
+ };
+ },
+ parse: {
+ div_chat_transcript_wrap_open(state, token, tokens, i) {
+ // The slice here makes sure we get the html_raw content
+ // only for the current [chat] bbcode block based on the
+ // token index.
+ const nextHtmlRaw = tokens
+ .slice(i)
+ .find((t) => t.type === "html_raw" && t.nesting === 1);
+ const messagesHtml = nextHtmlRaw?.content;
+
+ let threadHtmlRaw;
+ if (token.attrGet("data-thread-id")) {
+ threadHtmlRaw = tokens
+ .slice(tokens.indexOf(nextHtmlRaw) + 1)
+ .find((t) => t.type === "html_raw" && t.nesting === 1);
+ }
+
+ // So this content and the whole wrap_open happens for every single instance of
+ // the `[chat]` bbcode, including nested which is the case for threads.
+ //
+ // Only the first one will have multiQuote and chained
+ //
+ // Multiquote is > 1 message
+ // Chained is > 1 message by different users
+ state.openNode(state.schema.nodes.chat, {
+ messageId: token.attrGet("data-message-id"),
+ username: token.attrGet("data-username"),
+ datetime: token.attrGet("data-datetime"),
+ channel: token.attrGet("data-channel-name"),
+ channelId: token.attrGet("data-channel-id"),
+ chained: token.attrGet("data-chained"),
+ multiQuote: token.attrGet("data-multiquote"),
+ threadId: token.attrGet("data-thread-id"),
+ threadTitle: token.attrGet("data-thread-title"),
+ threadHtml: threadHtmlRaw ? threadHtmlRaw.content : null,
+ html: messagesHtml,
+ rawContent: token.content,
+ });
+ return true;
+ },
+ div_chat_transcript_wrap_close(state) {
+ state.closeNode();
+ return true;
+ },
+ div_chat_transcript_user: { ignore: true },
+ div_chat_transcript_user_avatar: { ignore: true },
+ div_chat_transcript_username: { ignore: true },
+ div_chat_transcript_datetime: { ignore: true },
+ div_chat_transcript_messages: { ignore: true },
+ div_chat_transcript_reaction: { ignore: true },
+
+ // Reaction-related tokens are not used in the live preview,
+ // they are only used when archiving a channel, not needed here.
+ div_chat_transcript_reactions: { ignore: true },
+ div_chat_transcript_meta: { ignore: true },
+
+ // Thread-related tokens
+ details_chat_transcript_wrap: { ignore: true },
+ summary_chat_transcript: { ignore: true },
+ div_thread: { ignore: true },
+ div_thread_header: { ignore: true },
+ svg_thread_header: { ignore: true },
+ use_svg_thread: { ignore: true },
+ span_thread_title: { ignore: true },
+
+ html_raw: { ignore: true, noCloseToken: true },
+
+ span_open(state) {
+ if (state.top().type.name === "chat") {
+ return true;
+ }
+ },
+ span_close(state) {
+ if (state.top().type.name === "chat") {
+ return true;
+ }
+ },
+ },
+};
+
+export default extension;
diff --git a/plugins/chat/assets/stylesheets/common/chat-transcript.scss b/plugins/chat/assets/stylesheets/common/chat-transcript.scss
index 09868ad8e5a..fe176368b1a 100644
--- a/plugins/chat/assets/stylesheets/common/chat-transcript.scss
+++ b/plugins/chat/assets/stylesheets/common/chat-transcript.scss
@@ -127,3 +127,9 @@
box-sizing: border-box;
}
}
+
+.ProseMirror {
+ .chat-transcript {
+ white-space: normal;
+ }
+}
diff --git a/plugins/chat/spec/integration/post_chat_quote_spec.rb b/plugins/chat/spec/integration/post_chat_transcript_spec.rb
similarity index 97%
rename from plugins/chat/spec/integration/post_chat_quote_spec.rb
rename to plugins/chat/spec/integration/post_chat_transcript_spec.rb
index d64f9fbd28b..7dc63f5b2f1 100644
--- a/plugins/chat/spec/integration/post_chat_quote_spec.rb
+++ b/plugins/chat/spec/integration/post_chat_transcript_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe "chat bbcode quoting in posts" do
+describe "chat transcripts in posts" do
fab!(:post)
before { SiteSetting.chat_enabled = true }
@@ -30,7 +30,7 @@ describe "chat bbcode quoting in posts" do
"[chat quote=\"martin;2321;2022-01-25T05:40:39Z\" channel=\"Cool Cats Club\" channelId=\"1234\" multiQuote=\"true\"]\nThis is a chat message.\n[/chat]",
)
expect(post.cooked.chomp).to eq(<<~COOKED.chomp)
- <div class="chat-transcript" data-message-id="2321" data-username="martin" data-datetime="2022-01-25T05:40:39Z" data-channel-name="Cool Cats Club" data-channel-id="1234">
+ <div class="chat-transcript" data-message-id="2321" data-username="martin" data-datetime="2022-01-25T05:40:39Z" data-channel-name="Cool Cats Club" data-channel-id="1234" data-multiquote="true">
<div class="chat-transcript-meta">
Originally sent in <a href="/chat/c/-/1234">Cool Cats Club</a></div>
<div class="chat-transcript-user">
@@ -73,7 +73,7 @@ describe "chat bbcode quoting in posts" do
"[chat quote=\"martin;2321;2022-01-25T05:40:39Z\" channel=\"Cool Cats Club\" channelId=\"1234\" chained=\"true\"]\nThis is a chat message.\n[/chat]",
)
expect(post.cooked.chomp).to eq(<<~COOKED.chomp)
- <div class="chat-transcript chat-transcript-chained" data-message-id="2321" data-username="martin" data-datetime="2022-01-25T05:40:39Z" data-channel-name="Cool Cats Club" data-channel-id="1234">
+ <div class="chat-transcript chat-transcript-chained" data-message-id="2321" data-username="martin" data-datetime="2022-01-25T05:40:39Z" data-chained="true" data-channel-name="Cool Cats Club" data-channel-id="1234">
<div class="chat-transcript-user">
<div class="chat-transcript-user-avatar"></div>
<div class="chat-transcript-username">
@@ -94,7 +94,7 @@ describe "chat bbcode quoting in posts" do
"[chat quote=\"martin;2321;2022-01-25T05:40:39Z\" channel=\"Cool Cats Club\" channelId=\"1234\" multiQuote=\"true\" noLink=\"true\"]\nThis is a chat message.\n[/chat]",
)
expect(post.cooked.chomp).to eq(<<~COOKED.chomp)
- <div class="chat-transcript" data-message-id="2321" data-username="martin" data-datetime="2022-01-25T05:40:39Z" data-channel-name="Cool Cats Club" data-channel-id="1234">
+ <div class="chat-transcript" data-message-id="2321" data-username="martin" data-datetime="2022-01-25T05:40:39Z" data-channel-name="Cool Cats Club" data-channel-id="1234" data-multiquote="true">
<div class="chat-transcript-meta">
Originally sent in <a href="/chat/c/-/1234">Cool Cats Club</a></div>
<div class="chat-transcript-user">
diff --git a/plugins/chat/spec/models/chat/message_spec.rb b/plugins/chat/spec/models/chat/message_spec.rb
index 9fa26a67aef..378038238ff 100644
--- a/plugins/chat/spec/models/chat/message_spec.rb
+++ b/plugins/chat/spec/models/chat/message_spec.rb
@@ -322,7 +322,7 @@ describe Chat::Message do
COOKED
end
- it "supports chat quote bbcode" do
+ it "supports chat transcripts" do
chat_channel = Fabricate(:category_channel, name: "testchannel")
user = Fabricate(:user, username: "chatbbcodeuser")
user2 = Fabricate(:user, username: "otherbbcodeuser")
@@ -355,7 +355,7 @@ describe Chat::Message do
)
expect(cooked).to eq(<<~COOKED.chomp)
- <div class="chat-transcript chat-transcript-chained" data-message-id="#{msg1.id}" data-username="chatbbcodeuser" data-datetime="#{msg1.created_at.iso8601}" data-channel-name="testchannel" data-channel-id="#{chat_channel.id}">
+ <div class="chat-transcript chat-transcript-chained" data-message-id="#{msg1.id}" data-username="chatbbcodeuser" data-datetime="#{msg1.created_at.iso8601}" data-chained="true" data-channel-name="testchannel" data-channel-id="#{chat_channel.id}" data-multiquote="true">
<div class="chat-transcript-meta">
Originally sent in <a href="/chat/c/-/#{chat_channel.id}">testchannel</a></div>
<div class="chat-transcript-user">
@@ -369,7 +369,7 @@ describe Chat::Message do
<div class="chat-transcript-messages">
<p>this is the first message</p></div>
</div>
- <div class="chat-transcript chat-transcript-chained" data-message-id="#{msg2.id}" data-username="otherbbcodeuser" data-datetime="#{msg2.created_at.iso8601}">
+ <div class="chat-transcript chat-transcript-chained" data-message-id="#{msg2.id}" data-username="otherbbcodeuser" data-datetime="#{msg2.created_at.iso8601}" data-chained="true">
<div class="chat-transcript-user">
<div class="chat-transcript-user-avatar">
<img alt="" width="24" height="24" src="#{avatar_src2}" class="avatar"></div>
diff --git a/plugins/chat/spec/requests/chat_controller_spec.rb b/plugins/chat/spec/requests/chat_controller_spec.rb
index b0200afea82..a3ab04156b4 100644
--- a/plugins/chat/spec/requests/chat_controller_spec.rb
+++ b/plugins/chat/spec/requests/chat_controller_spec.rb
@@ -428,7 +428,7 @@ RSpec.describe Chat::ChatController do
expect(response.status).to eq(404)
end
- it "quotes the message ids provided" do
+ it "makes transcripts for the message ids provided" do
sign_in(user)
post "/chat/#{channel.id}/quote.json",
params: {
diff --git a/plugins/chat/spec/system/rich_editor_extension_transcript_spec.rb b/plugins/chat/spec/system/rich_editor_extension_transcript_spec.rb
new file mode 100644
index 00000000000..592889b7ea6
--- /dev/null
+++ b/plugins/chat/spec/system/rich_editor_extension_transcript_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+describe "chat transcripts in rich editor", type: :system do
+ fab!(:current_user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:channel) { Fabricate(:chat_channel) }
+ fab!(:message_1) do
+ Fabricate(:chat_message, user: current_user, chat_channel: channel, created_at: 2.days.ago)
+ end
+ fab!(:message_2) { Fabricate(:chat_message, chat_channel: channel, created_at: 1.day.ago) }
+
+ let(:cdp) { PageObjects::CDP.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+ let(:rich) { composer.rich_editor }
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.rich_editor = true
+ sign_in(current_user)
+ end
+
+ it "works for single messages" do
+ page.visit "/new-topic"
+ expect(composer).to be_opened
+ composer.toggle_rich_editor
+ composer.focus
+
+ markdown =
+ Chat::TranscriptService.new(
+ channel,
+ current_user,
+ messages_or_ids: [message_1],
+ ).generate_markdown
+
+ cdp.copy_paste(markdown)
+
+ expect(rich).to have_css(".chat-transcript", text: channel.name)
+ expect(rich).to have_css(
+ ".chat-transcript .chat-transcript-user .chat-transcript-username",
+ text: message_1.user.username,
+ )
+ expect(rich).to have_css(".chat-transcript .chat-transcript-messages", text: message_1.message)
+ end
+
+ it "works for multiple messages" do
+ page.visit "/new-topic"
+ expect(composer).to be_opened
+ composer.toggle_rich_editor
+ composer.focus
+
+ markdown =
+ Chat::TranscriptService.new(
+ channel,
+ current_user,
+ messages_or_ids: [message_1, message_2],
+ ).generate_markdown
+
+ cdp.copy_paste(markdown)
+
+ expect(rich).to have_css(".chat-transcript.chat-transcript-chained", count: 2)
+ expect(rich).to have_css(
+ ".chat-transcript .chat-transcript-meta",
+ text: "Originally sent in #{channel.name}",
+ )
+ expect(rich).to have_css(
+ ".chat-transcript:nth-of-type(1) .chat-transcript-user .chat-transcript-username",
+ text: message_1.user.username,
+ )
+ expect(rich).to have_css(
+ ".chat-transcript:nth-of-type(2) .chat-transcript-user .chat-transcript-username",
+ text: message_2.user.username,
+ )
+ expect(rich).to have_css(
+ ".chat-transcript:nth-of-type(1) .chat-transcript-messages",
+ text: message_1.message,
+ )
+ expect(rich).to have_css(
+ ".chat-transcript:nth-of-type(2) .chat-transcript-messages",
+ text: message_2.message,
+ )
+ end
+end
diff --git a/plugins/chat/test/javascripts/components/rich-editor-extension-test.gjs b/plugins/chat/test/javascripts/components/rich-editor-extension-test.gjs
new file mode 100644
index 00000000000..96572b7c1ad
--- /dev/null
+++ b/plugins/chat/test/javascripts/components/rich-editor-extension-test.gjs
@@ -0,0 +1,176 @@
+import { getOwner } from "@ember/owner";
+import { module, test } from "qunit";
+import {
+ registerRichEditorExtension,
+ resetRichEditorExtensions,
+} from "discourse/lib/composer/rich-editor-extensions";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { setupRichEditor } from "discourse/tests/helpers/rich-editor-helper";
+import richEditorExtension from "discourse/plugins/chat/lib/rich-editor-extension";
+
+module(
+ "Integration | Component | prosemirror-editor - chat transcript extension",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.rich_editor = true;
+ this.siteSettings.chat_enabled = true;
+
+ // This is necessary for the chat transcripts to work in JS, because this
+ // is necessary for the markdown-it rule to run, this tells chat what
+ // pretty text features and markdown rules are allowed in chat transcripts.
+ const site = getOwner(this).lookup("service:site");
+ site.set(
+ "markdown_additional_options",
+ JSON.parse(
+ '{"chat":{"limited_pretty_text_features":["anchor","bbcode-block","bbcode-inline","code","category-hashtag","censored","chat-transcript","discourse-local-dates","emoji","emojiShortcuts","inlineEmoji","html-img","hashtag-autocomplete","mentions","unicodeUsernames","onebox","quotes","spoiler-alert","table","text-post-process","upload-protocol","watched-words","chat-html-inline"],"limited_pretty_text_markdown_rules":["autolink","list","backticks","newline","code","fence","image","table","linkify","link","strikethrough","blockquote","emphasis","replacements","escape"],"hashtag_configurations":{"topic-composer":["category","tag","channel"],"chat-composer":["channel","category","tag"]}}}'
+ )
+ );
+
+ resetRichEditorExtensions().then(() => {
+ registerRichEditorExtension(richEditorExtension);
+ });
+ });
+
+ test("single message from single user transcript", async function (assert) {
+ const singleMessageSingleUserMarkdown = `[chat quote="hunter;29856;2025-03-20T07:13:04Z" channel="design gems :tada:" channelId="95"]
+haha **ok** _cool_
+[/chat]
+`;
+ const [{ value }] = await setupRichEditor(
+ assert,
+ singleMessageSingleUserMarkdown
+ );
+ const rootElement = document.querySelector(
+ ".ProseMirror .chat-transcript"
+ );
+ assert
+ .dom(".chat-transcript-messages", rootElement)
+ .hasHtml("<p>haha <strong>ok</strong> <em>cool</em></p>");
+ assert
+ .dom(".chat-transcript-user .chat-transcript-username", rootElement)
+ .hasText("hunter");
+ assert
+ .dom(".chat-transcript-user .chat-transcript-datetime", rootElement)
+ .exists();
+ assert
+ .dom(".chat-transcript-channel", rootElement)
+ .hasText("#design gems");
+ assert
+ .dom(".chat-transcript-channel", rootElement)
+ .hasAttribute("href", "/chat/c/-/95");
+ assert.dom(".chat-transcript-channel img[title='tada']").exists();
+
+ assert.strictEqual(value, singleMessageSingleUserMarkdown);
+ });
+
+ test("multiple messages from multiple different users", async function (assert) {
+ const multiMessagesMultiUserMarkdown = `[chat quote="martin;29853;2025-03-20T07:12:55Z" channel="design gems :tada:" channelId="95" multiQuote="true" chained="true"]
+test
+[/chat]
+[chat quote="hunter;29856;2025-03-20T07:13:04Z" chained="true"]
+haha **ok** _cool_
+[/chat]
+`;
+ const [{ value }] = await setupRichEditor(
+ assert,
+ multiMessagesMultiUserMarkdown
+ );
+
+ assert.dom(".chat-transcript").exists({ count: 2 });
+ assert.dom(".chat-transcript-messages").exists({ count: 2 });
+ assert.dom(".chat-transcript-user").exists({ count: 2 });
+ assert
+ .dom(".chat-transcript:nth-of-type(1)")
+ .hasClass("chat-transcript-chained");
+ assert
+ .dom(".chat-transcript-meta")
+ .hasText("Originally sent in design gems");
+ assert.dom(".chat-transcript-meta img[title='tada']").exists();
+
+ let rootElement = document.querySelector(
+ ".ProseMirror .chat-transcript:nth-of-type(1)"
+ );
+ assert
+ .dom(".chat-transcript-messages", rootElement)
+ .hasHtml("<p>test</p>");
+ assert
+ .dom(".chat-transcript-user .chat-transcript-username", rootElement)
+ .hasText("martin");
+
+ rootElement = document.querySelector(
+ ".ProseMirror .chat-transcript:nth-of-type(2)"
+ );
+ assert
+ .dom(".chat-transcript-messages", rootElement)
+ .hasHtml("<p>haha <strong>ok</strong> <em>cool</em></p>");
+ assert
+ .dom(".chat-transcript-user .chat-transcript-username", rootElement)
+ .hasText("hunter");
+
+ assert.strictEqual(value, multiMessagesMultiUserMarkdown);
+ });
+
+ test("messages in a thread", async function (assert) {
+ const threadMessagesMarkdown = `[chat quote="martin;29854;2025-03-20T07:12:57Z" channel="design gems :tada:" channelId="95" multiQuote="true" threadId="124" threadTitle="Some cool thread title"]
+thread op message
+
+[chat quote="martin;29857;2025-03-24T07:08:01Z"]
+thread other message
+[/chat]
+
+[/chat]
+`;
+ const [{ value }] = await setupRichEditor(assert, threadMessagesMarkdown);
+ assert
+ .dom(".chat-transcript-meta")
+ .hasText("Originally sent in design gems");
+ assert.dom(".chat-transcript-meta img[title='tada']").exists();
+ assert
+ .dom(".chat-transcript details summary .chat-transcript-thread")
+ .exists();
+
+ let rootElement = document.querySelector(
+ ".ProseMirror .chat-transcript details summary .chat-transcript-thread"
+ );
+ assert
+ .dom(
+ ".chat-transcript-thread-header svg.d-icon-discourse-threads",
+ rootElement
+ )
+ .exists();
+ assert
+ .dom(
+ ".chat-transcript-thread-header .chat-transcript-thread-header__title",
+ rootElement
+ )
+ .hasText("Some cool thread title");
+
+ assert
+ .dom(".chat-transcript-messages", rootElement)
+ .hasHtml(
+ "<p>thread op message</p>",
+ "the thread op message is inside the summary element"
+ );
+ assert
+ .dom(".chat-transcript-user .chat-transcript-username", rootElement)
+ .hasText("martin");
+
+ rootElement = document.querySelector(
+ ".ProseMirror .chat-transcript details .chat-transcript"
+ );
+ assert
+ .dom(".chat-transcript-messages", rootElement)
+ .hasHtml(
+ "<p>thread other message</p>",
+ "the other thread messages are inside the details element"
+ );
+ assert
+ .dom(".chat-transcript-user .chat-transcript-username", rootElement)
+ .hasText("martin");
+
+ assert.strictEqual(value, threadMessagesMarkdown);
+ });
+ }
+);
diff --git a/spec/system/page_objects/cdp.rb b/spec/system/page_objects/cdp.rb
index 855e0770fbe..8005f2b35ba 100644
--- a/spec/system/page_objects/cdp.rb
+++ b/spec/system/page_objects/cdp.rb
@@ -56,6 +56,12 @@ module PageObjects
end
end
+ def copy_paste(text, html: false)
+ allow_clipboard
+ write_clipboard(text, html: html)
+ page.send_keys([PLATFORM_KEY_MODIFIER, "v"])
+ end
+
def with_network_disconnected
begin
page.driver.browser.network_conditions = { offline: true }