A platform for community discussion. Free, open, simple.
UX: allow links in pinned chat messages, update livestream (#42322)
Krisda11a72df06d
diff --git a/plugins/chat/app/models/chat/message.rb b/plugins/chat/app/models/chat/message.rbindex 7baa7083c29..66fd8ae618c 100644--- a/plugins/chat/app/models/chat/message.rb+++ b/plugins/chat/app/models/chat/message.rb@@ -161,14 +161,20 @@ module Chatendend- def build_excerpt+ def build_excerpt(strip_links: true)# just show the URL if the whole message is a URL, because we cannot excerpt oneboxesurls = PrettyText.extract_links(cooked).map(&:url)if urls.present?regex = %r{^[^:]+://}clean_urls = urls.map { |url| url.sub(regex, "") }if message.gsub(regex, "").split.sort == clean_urls.sort- return PrettyText.excerpt(urls.join(" "), EXCERPT_LENGTH)+ return(+ if strip_links+ PrettyText.excerpt(urls.join(" "), EXCERPT_LENGTH)+ else+ PrettyText.excerpt(urls_as_links(urls), EXCERPT_LENGTH, strip_links: false)+ end+ )endend@@ -176,7 +182,7 @@ module Chatreturn uploads.first.original_filename if cooked.blank? && uploads.present?# this may return blank for some complex things like quotes, that is acceptable- PrettyText.excerpt(cooked, EXCERPT_LENGTH, strip_links: true, keep_mentions: true)+ PrettyText.excerpt(cooked, EXCERPT_LENGTH, strip_links:, keep_mentions: true)enddef cooked_for_excerpt@@ -403,6 +409,17 @@ module Chatprivate+ def urls_as_links(urls)+ html =+ urls.map { |url| "<a href=\"#{CGI.escapeHTML(url)}\">#{CGI.escapeHTML(url)}</a>" }.join(" ")+ doc = Nokogiri::HTML5.fragment(html)+ PrettyText.add_rel_attributes_to_user_content(+ doc,+ SiteSetting.add_rel_nofollow_to_user_content,+ )+ doc.to_html+ end+def delete_mentions(mention_type, target_ids)chat_mentions.where(type: mention_type, target_id: target_ids).destroy_allenddiff --git a/plugins/chat/app/serializers/chat/pinned_message_serializer.rb b/plugins/chat/app/serializers/chat/pinned_message_serializer.rbindex a718d9b11af..ccb1cdfc9a2 100644--- a/plugins/chat/app/serializers/chat/pinned_message_serializer.rb+++ b/plugins/chat/app/serializers/chat/pinned_message_serializer.rb@@ -2,7 +2,7 @@module Chatclass PinnedMessageSerializer < ::ApplicationSerializer- attributes :id, :chat_message_id, :pinned_at+ attributes :id, :chat_message_id, :pinned_at, :excerpthas_one :pinned_by, serializer: ::BasicUserSerializer, embed: :objectshas_one :message, serializer: Chat::MessageSerializer, embed: :objects@@ -11,6 +11,12 @@ module Chatobject.created_atend+ # the stored excerpt strips links because most surfaces showing it are+ # themselves links or buttons; the pinned bar can host them, so it gets its own+ def excerpt+ object.chat_message.build_excerpt(strip_links: false)+ end+def pinned_byobject.userenddiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjsindex 4aa7065cf29..2489907dacc 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs@@ -124,6 +124,11 @@ export default class ChatChannel extends Component {return this.args.channel?.id ? `channel:${this.args.channel.id}` : null;}+ @cached+ get hiddenMessageIds() {+ return new Set((this.args.hiddenMessageIds ?? []).map(Number));+ }+@actionteardown() {document.removeEventListener("keydown", this._captureKeystroke);@@ -377,11 +382,8 @@ export default class ChatChannel extends Component {const messages = [];let foundFirstNew = false;- const hiddenMessageIds = new Set(- (this.args.hiddenMessageIds ?? []).map(Number)- );const messagesData = (result?.messages ?? []).filter(- (messageData) => !hiddenMessageIds.has(messageData.id)+ (messageData) => !this.hiddenMessageIds.has(messageData.id));// Only compute the newest message marker on a full load.@@ -824,6 +826,7 @@ export default class ChatChannel extends Component {@channel={{@channel}}@onJumpToMessage={{this.jumpToPinnedMessage}}@viewportBottomMessageId={{this.lastVisibleMessageId}}+ @hiddenMessageIds={{this.hiddenMessageIds}}/><ChatMessagesScrollerdiff --git a/plugins/chat/assets/javascripts/discourse/components/chat/pinned-message-bar.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/pinned-message-bar.gjsindex e8c9c9e72db..7672f6fa0ad 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/pinned-message-bar.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/pinned-message-bar.gjs@@ -47,10 +47,10 @@ export default class ChatPinnedMessageBar extends Component {return false;}const dismissedAbove = pinsDismissedAboveId(this.args.channel);- if (dismissedAbove == null || this.pins.length === 0) {+ if (dismissedAbove == null || this.visiblePins.length === 0) {return false;}- return newestPinId(this.pins) <= dismissedAbove;+ return newestPinId(this.visiblePins) <= dismissedAbove;}get showBar() {@@ -60,8 +60,16 @@ export default class ChatPinnedMessageBar extends Component {);}+ get visiblePins() {+ const hidden = this.args.hiddenMessageIds;+ if (!hidden?.size) {+ return this.pins;+ }+ return this.pins.filter((pin) => !hidden.has(pin.message.id));+ }+get orderedPins() {- return [...this.pins].sort((a, b) => a.message.id - b.message.id);+ return [...this.visiblePins].sort((a, b) => a.message.id - b.message.id);}// the newest pin at or above the viewport bottom — the one governing the view@@ -97,11 +105,11 @@ export default class ChatPinnedMessageBar extends Component {}get hasMultiplePins() {- return this.pins.length > 1;+ return this.visiblePins.length > 1;}get indicatorTop() {- const total = this.pins.length;+ const total = this.visiblePins.length;if (total <= INDICATOR_WINDOW) {return 0;}@@ -110,7 +118,7 @@ export default class ChatPinnedMessageBar extends Component {}get visibleSegments() {- return Math.min(this.pins.length, INDICATOR_WINDOW);+ return Math.min(this.visiblePins.length, INDICATOR_WINDOW);}get indicatorStyle() {@@ -121,7 +129,8 @@ export default class ChatPinnedMessageBar extends Component {const height = segment * visible + SEGMENT_GAP_PX * (visible - 1);const top = this.indicatorTop;const fadeTop = top > 0 ? INDICATOR_FADE_PX : 0;- const fadeBottom = top < this.pins.length - visible ? INDICATOR_FADE_PX : 0;+ const fadeBottom =+ top < this.visiblePins.length - visible ? INDICATOR_FADE_PX : 0;return trustHTML(`--chat-pinned-bar-seg: ${segment}px; ` +`--chat-pinned-bar-gap: ${SEGMENT_GAP_PX}px; ` +@@ -152,13 +161,15 @@ export default class ChatPinnedMessageBar extends Component {}get currentExcerpt() {- const message = this.currentPin?.message;- if (message?.excerpt) {+ const pin = this.currentPin;+ // the pin's own excerpt keeps links; the message's is the stripped fallback+ const excerpt = pin?.excerpt || pin?.message?.excerpt;+ if (excerpt) {// excerpt is server-escaped HTML — trust it so entities/emoji aren't re-escaped- return trustHTML(message.excerpt);+ return trustHTML(excerpt);}// media-only fallback: leave untrusted so the template escapes it- return message?.message ?? "";+ return pin?.message?.message ?? "";}@action@@ -175,11 +186,10 @@ export default class ChatPinnedMessageBar extends Component {}#updatePinnedMessage(updated) {- const pin = updated && this.pins.find((p) => p.message?.id === updated.id);- if (pin) {- pin.message.message = updated.message;- pin.message.excerpt = updated.excerpt;+ if (!updated || !this.pins.some((pin) => pin.message?.id === updated.id)) {+ return;}+ this.loadPins();}@action@@ -203,7 +213,10 @@ export default class ChatPinnedMessageBar extends Component {#reconcileDismissal() {const dismissedAbove = pinsDismissedAboveId(this.args.channel);- if (dismissedAbove != null && newestPinId(this.pins) > dismissedAbove) {+ if (+ dismissedAbove != null &&+ newestPinId(this.visiblePins) > dismissedAbove+ ) {resetPinsDismissal(this.args.channel);}}@@ -224,7 +237,7 @@ export default class ChatPinnedMessageBar extends Component {@actiondismiss() {- dismissPinsUpTo(this.args.channel, newestPinId(this.pins));+ dismissPinsUpTo(this.args.channel, newestPinId(this.visiblePins));}<template>@@ -238,12 +251,14 @@ export default class ChatPinnedMessageBar extends Component {{{this.subscribe @channel.id}}>{{#if this.currentPin}}- <button- type="button"- class="chat-pinned-bar__main"- aria-label={{i18n "chat.pinned_bar.jump_to_pinned"}}- {{on "click" this.jumpToCurrentPin}}- >+ <div class="chat-pinned-bar__main">+ <button+ type="button"+ class="chat-pinned-bar__jump"+ aria-label={{i18n "chat.pinned_bar.jump_to_pinned"}}+ {{on "click" this.jumpToCurrentPin}}+ ></button>+{{#if this.hasMultiplePins}}<spanclass="chat-pinned-bar__indicator"@@ -271,7 +286,7 @@ export default class ChatPinnedMessageBar extends Component {{{dReplaceEmoji this.currentExcerpt}}</span></span>- </button>+ </div>{{/if}}{{#if this.showInlineDismiss}}diff --git a/plugins/chat/assets/stylesheets/common/chat-pinned-bar.scss b/plugins/chat/assets/stylesheets/common/chat-pinned-bar.scssindex f74d4d5a31c..76f53362d93 100644--- a/plugins/chat/assets/stylesheets/common/chat-pinned-bar.scss+++ b/plugins/chat/assets/stylesheets/common/chat-pinned-bar.scss@@ -22,24 +22,33 @@}&__main {+ position: relative;flex: 1 1 auto;display: flex;align-items: center;gap: var(--space-2);min-width: 0;padding: var(--space-1) var(--space-2);- background: transparent;- border: 0;- border-radius: 4px;text-align: start;- cursor: pointer;- .no-touch &:hover {+ .no-touch &:hover .chat-pinned-bar__jump {background: var(--d-hover);}}+ &__jump {+ position: absolute;+ inset: 0;+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 4px;+ cursor: pointer;+ }+&__indicator {+ position: relative;+ pointer-events: none;align-self: center;flex-shrink: 0;width: 3px;@@ -105,6 +114,9 @@}&__content {+ // clicks still fall through to the overlay, except on links+ position: relative;+ pointer-events: none;display: flex;flex-direction: column;min-width: 0;@@ -129,6 +141,11 @@@include ellipsis;color: var(--primary);font-size: var(--font-down-1);++ // only links opt back into clicks; the rest of the bar jumps to the pin+ a {+ pointer-events: auto;+ }}&__see-all,diff --git a/plugins/chat/spec/requests/chat/api/channel_pins_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channel_pins_controller_spec.rbindex 1187170348d..227d9cd8612 100644--- a/plugins/chat/spec/requests/chat/api/channel_pins_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/channel_pins_controller_spec.rb@@ -24,6 +24,29 @@ RSpec.describe Chat::Api::ChannelPinsController doexpect(response.parsed_body["pinned_messages"][0]["chat_message_id"]).to eq(message.id)end+ it "keeps links in the pin excerpt, unlike the message's own excerpt" do+ linked = Fabricate(:chat_message, chat_channel: channel, message: "see [the docs](/faq)")+ Fabricate(:chat_pinned_message, chat_message: linked, chat_channel: channel)++ get "/chat/api/channels/#{channel.id}/pins"++ pin = response.parsed_body["pinned_messages"][0]+ expect(pin["excerpt"]).to include("<a href=\"/faq\"")+ expect(pin["message"]["excerpt"]).not_to include("<a")+ end++ it "keeps a link for a pin whose message is only a URL" do+ url_only =+ Fabricate(:chat_message, chat_channel: channel, message: "https://example.com/docs")+ Fabricate(:chat_pinned_message, chat_message: url_only, chat_channel: channel)++ get "/chat/api/channels/#{channel.id}/pins"++ pin = response.parsed_body["pinned_messages"][0]+ expect(pin["excerpt"]).to include("<a href=\"https://example.com/docs\"")+ expect(pin["excerpt"]).to include("rel=\"noopener nofollow ugc\"")+ end+it "returns an empty list when there are no pinned messages" doget "/chat/api/channels/#{channel.id}/pins"diff --git a/plugins/chat/spec/system/pinned_messages_spec.rb b/plugins/chat/spec/system/pinned_messages_spec.rbindex 8ca0a3af22e..5d6a057a620 100644--- a/plugins/chat/spec/system/pinned_messages_spec.rb+++ b/plugins/chat/spec/system/pinned_messages_spec.rb@@ -124,10 +124,10 @@ RSpec.describe "Chat pinned messages" do# newest pin is shown firstexpect(page).to have_css(".chat-pinned-bar__excerpt", text: "Second message")- find(".chat-pinned-bar__main").click+ find(".chat-pinned-bar__jump").clickexpect(page).to have_css(".chat-pinned-bar__excerpt", text: "Important message")- find(".chat-pinned-bar__main").click+ find(".chat-pinned-bar__jump").clickexpect(page).to have_css(".chat-pinned-bar__excerpt", text: "Second message")enddiff --git a/plugins/chat/test/javascripts/components/chat-pinned-message-bar-test.gjs b/plugins/chat/test/javascripts/components/chat-pinned-message-bar-test.gjsindex 1d96159952f..5c21e025b12 100644--- a/plugins/chat/test/javascripts/components/chat-pinned-message-bar-test.gjs+++ b/plugins/chat/test/javascripts/components/chat-pinned-message-bar-test.gjs@@ -41,6 +41,22 @@ function pinsResponse(ids) {});}+function excerptPinResponse(excerpt) {+ return response({+ pinned_messages: [+ {+ id: 100,+ chat_message_id: 200,+ pinned_at: moment().toISOString(),+ pinned_by: { id: 1, username: "alice" },+ excerpt,+ message: { id: 200, excerpt: "Stripped excerpt", message: "x" },+ },+ ],+ membership: null,+ });+}+// a single pin whose pin-record id is `pinId` (the value the bar compares// against the dismissed-above id)function dismissablePinResponse(pinId) {@@ -121,6 +137,98 @@ module("Component | ChatPinnedMessageBar", function (hooks) {assert.dom(".chat-pinned-bar__indicator").doesNotExist();});+ test("renders the links the pin excerpt keeps", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ excerptPinResponse("See <a href='/t/topic/1'>the topic</a> for details")+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText("See the topic for details");+ assert+ .dom(".chat-pinned-bar__excerpt a")+ .hasAttribute("href", "/t/topic/1", "the link survives");+ });++ test("renders a URL-only pin as a link", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ excerptPinResponse(+ '<a href="https://example.com/docs" rel="noopener nofollow ugc">https://example.com/docs</a>'+ )+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar__excerpt a")+ .hasAttribute("href", "https://example.com/docs")+ .hasAttribute("rel", "noopener nofollow ugc");+ });++ test("skips pins whose message the host hides from the list", async function (assert) {+ this.channel.pinnedMessagesCount = 2;+ this.hiddenMessageIds = new Set([201]);+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 2)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ @hiddenMessageIds={{this.hiddenMessageIds}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText("Pinned excerpt 1", "falls back to the newest visible pin");+ assert+ .dom(".chat-pinned-bar__indicator")+ .doesNotExist("the hidden pin is not counted");+ });++ test("shows nothing when every pin is hidden", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ this.hiddenMessageIds = new Set([200]);+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 1)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ @hiddenMessageIds={{this.hiddenMessageIds}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar").hasClass("--loading");+ assert.dom(".chat-pinned-bar__main").doesNotExist();+ });+test("shows a position indicator for multiple pins", async function (assert) {this.channel.pinnedMessagesCount = 3;pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>@@ -149,7 +257,7 @@ module("Component | ChatPinnedMessageBar", function (hooks) {"starts on the newest pin, in the bottom slot");- await click(".chat-pinned-bar__main");+ await click(".chat-pinned-bar__jump");assert.dom(".chat-pinned-bar__indicator")@@ -188,7 +296,7 @@ module("Component | ChatPinnedMessageBar", function (hooks) {// advance toward older pins — the window scrolls upfor (let i = 0; i < 6; i++) {- await click(".chat-pinned-bar__main");+ await click(".chat-pinned-bar__jump");}// 6 taps back => active index 1 => top = 1 - 2 clamps to 0@@ -222,14 +330,14 @@ module("Component | ChatPinnedMessageBar", function (hooks) {// opens on the newest pin (message 201)assert.dom(".chat-pinned-bar__excerpt").hasText("Pinned excerpt 0");- await click(".chat-pinned-bar__main");+ await click(".chat-pinned-bar__jump");assert.strictEqual(jumpedTo, 201, "jumps to the pin that was shown");assert.dom(".chat-pinned-bar__excerpt").hasText("Pinned excerpt 1", "and previews the next older pin");- await click(".chat-pinned-bar__main");+ await click(".chat-pinned-bar__jump");assert.strictEqual(jumpedTo, 200, "jumps to that previewed pin");assert@@ -431,8 +539,11 @@ module("Component | ChatPinnedMessageBar", function (hooks) {test("updates the preview when a pinned message is edited", async function (assert) {this.channel.pinnedMessagesCount = 1;+ let edited = false;pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>- pinResponse(this.channel, 1)+ edited+ ? excerptPinResponse("Edited <a href='/t/1'>excerpt</a>")+ : pinResponse(this.channel, 1));await render(@@ -447,6 +558,7 @@ module("Component | ChatPinnedMessageBar", function (hooks) {assert.dom(".chat-pinned-bar__excerpt").hasText("Pinned excerpt 0");// the pinned message (id 200) is edited+ edited = true;await publishToMessageBus(`/chat/${this.channel.id}`, {type: "edit",chat_message: { id: 200, message: "edited", excerpt: "Edited excerpt" },@@ -455,7 +567,10 @@ module("Component | ChatPinnedMessageBar", function (hooks) {assert.dom(".chat-pinned-bar__excerpt")- .hasText("Edited excerpt", "reflects the edited message");+ .hasText("Edited excerpt", "refetches instead of using the stripped one");+ assert+ .dom(".chat-pinned-bar__excerpt a")+ .hasAttribute("href", "/t/1", "and keeps the links the refetch returned");});test("ignores edits to messages that are not pinned", async function (assert) {