A platform for community discussion. Free, open, simple.
FEATURE: Sticky bar for pinned messages in chat channels (#41091)
Renato Atilio7f9005681164
diff --git a/plugins/chat/app/services/chat/list_channel_pins.rb b/plugins/chat/app/services/chat/list_channel_pins.rbindex 9e07d350e82..77a1005ce4a 100644--- a/plugins/chat/app/services/chat/list_channel_pins.rb+++ b/plugins/chat/app/services/chat/list_channel_pins.rb@@ -37,19 +37,23 @@ module Chat%i[user_option primary_group]end- Chat::PinnedMessage.for_channel(channel).includes(- chat_message: [- :revisions,- :bookmarks,- { uploads: { optimized_videos: :optimized_upload } },- { chat_channel: :chatable },- :thread,- { user: user_includes },- { user_mentions: { user: user_includes } },- { reactions: :user },- { in_reply_to: [:user] },- ],- )+ # timeline order (oldest message first), so the list reads like the channel+ Chat::PinnedMessage+ .for_channel(channel)+ .reorder(chat_message_id: :asc)+ .includes(+ chat_message: [+ :revisions,+ :bookmarks,+ { uploads: { optimized_videos: :optimized_upload } },+ { chat_channel: :chatable },+ :thread,+ { user: user_includes },+ { user_mentions: { user: user_includes } },+ { reactions: :user },+ { in_reply_to: [:user] },+ ],+ )endendenddiff --git a/plugins/chat/app/services/chat/publisher.rb b/plugins/chat/app/services/chat/publisher.rbindex 5a635995297..ed943b6a393 100644--- a/plugins/chat/app/services/chat/publisher.rb+++ b/plugins/chat/app/services/chat/publisher.rb@@ -470,6 +470,9 @@ module Chatchat_message_id: chat_message.id,pinned_at: pin.created_at.iso8601(3),pinned_by_id: pin.pinned_by_id,+ # authoritative count so clients assign instead of incrementing,+ # keeping them correct even if events are replayed or double-handled+ pinned_message_count: chat_channel.pinned_messages.count,},)end@@ -477,7 +480,12 @@ module Chatdef self.publish_unpin!(chat_channel, chat_message, unpinned_by)publish_to_channel!(chat_channel,- { type: :unpin, chat_message_id: chat_message.id, unpinned_by_id: unpinned_by.id },+ {+ type: :unpin,+ chat_message_id: chat_message.id,+ unpinned_by_id: unpinned_by.id,+ pinned_message_count: chat_channel.pinned_messages.count,+ },)enddiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjsindex 7eeca8a5cdf..4aa7065cf29 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs@@ -34,6 +34,7 @@ import {import ChatMessage from "discourse/plugins/chat/discourse/models/chat-message";import ChatChannelEmptyState from "./chat/channel/empty-state";import ChatComposerChannel from "./chat/composer/channel";+import ChatPinnedMessageBar from "./chat/pinned-message-bar";import ChatScrollToBottomArrow from "./chat/scroll-to-bottom-arrow";import ChatSelectionManager from "./chat/selection-manager";import ChatChannelFilter from "./chat-channel-filter";@@ -63,6 +64,8 @@ export default class ChatChannel extends Component {@tracked atBottom = true;@tracked uploadDropZone;@tracked isScrolling = false;+ // bottom-most visible message, so the pinned bar can anchor to the view+ @tracked lastVisibleMessageId = null;scroller = null;@@ -71,6 +74,16 @@ export default class ChatChannel extends Component {onUserPresent: this.maybeDebouncedUpdateLastReadMessage,});+ jumpToPinnedMessage = (messageId) => {+ this.highlightOrFetchMessage(messageId, { position: "center" });+ };+ // real user input flips this, so onScroll drops the pinned-bar tap override+ // only on a scroll the user drove — not the programmatic jump that set it+ #userScrolled = false;+ #markUserScroll = () => {+ this.#userScrolled = true;+ };+ #userScrollEvents = ["wheel", "touchmove", "pointerdown"];_mentionWarningsSeen = {};_unreachableGroupMentions = [];_overMembersLimitGroupMentions = [];@@ -78,6 +91,9 @@ export default class ChatChannel extends Component {@actionregisterScroller(element) {this.scroller = element;+ this.#userScrollEvents.forEach((event) =>+ element.addEventListener(event, this.#markUserScroll, { passive: true })+ );}@cached@@ -111,6 +127,11 @@ export default class ChatChannel extends Component {@actionteardown() {document.removeEventListener("keydown", this._captureKeystroke);+ this.#userScrollEvents.forEach((event) =>+ this.scroller?.removeEventListener(event, this.#markUserScroll)+ );+ // cleared on teardown (not setup) so a pins-panel click can set it pre-mount+ this.args.channel.activePinnedMessageId = null;this.#cancelHandlers();this.paneState.teardown();this.subscriptionManager.teardown();@@ -432,6 +453,9 @@ export default class ChatChannel extends Component {}highlightOrFetchMessage(messageId, options = {}) {+ // this jump's own scrolling must not drop a pinned-bar override set for it,+ // so clear any stale user-scroll flag before it starts+ this.#userScrolled = false;const message = this.messagesManager.findMessage(messageId);if (message) {this.scrollToMessageId(@@ -529,6 +553,15 @@ export default class ChatChannel extends Component {return;}+ // re-anchor to the view; drop the tap override only on a user-driven+ // scroll, not the programmatic jump that set it (which fires scroll events+ // too — repeatedly on iOS smooth-scroll and via the fetch reflow)+ this.lastVisibleMessageId = firstVisibleMessageId(this.scroller);+ if (this.#userScrolled) {+ this.#userScrolled = false;+ this.args.channel.activePinnedMessageId = null;+ }+DatesSeparatorsPositioner.apply(this.scroller);this.paneState.updatePendingContentFromScrollState({scroller: this.scroller,@@ -556,6 +589,8 @@ export default class ChatChannel extends Component {onScrollEnd(state) {this.isScrolling = false;this.atBottom = state.atBottom;+ this.lastVisibleMessageId =+ state.firstVisibleId ?? this.lastVisibleMessageId;this.paneState.updateLiveEdgeFromScrollState(state);if (state.atBottom) {@@ -785,6 +820,12 @@ export default class ChatChannel extends Component {@onLoadTargetMessageId={{this.onLoadTargetMessageId}}/>+ <ChatPinnedMessageBar+ @channel={{@channel}}+ @onJumpToMessage={{this.jumpToPinnedMessage}}+ @viewportBottomMessageId={{this.lastVisibleMessageId}}+ />+<ChatMessagesScroller@onRegisterScroller={{this.registerScroller}}@onScroll={{this.onScroll}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-pinned-messages-list.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-pinned-messages-list.gjsindex 5468ebea042..c4d3dbcaf43 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-pinned-messages-list.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-pinned-messages-list.gjs@@ -1,16 +1,27 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { service } from "@ember/service";import { modifier as modifierFn } from "ember-modifier";+import DButton from "discourse/ui-kit/d-button";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";import ChatMessage from "discourse/plugins/chat/discourse/components/chat-message";+import {+ dismissPinsUpTo,+ hasPinsDismissal,+ newestPinId,+ resetPinsDismissal,+} from "discourse/plugins/chat/discourse/lib/chat-pinned-bar-dismissal";export default class ChatPinnedMessagesList extends Component {@service messageBus;@service chatApi;@service currentUser;+ @service router;@tracked pinnedMessages = this.args.pinnedMessages || [];@@ -30,7 +41,6 @@ export default class ChatPinnedMessagesList extends Component {this.#markPinsAsRead(channel);};});-onMessage = (busData) => {switch (busData.type) {case "pin":@@ -41,7 +51,6 @@ export default class ChatPinnedMessagesList extends Component {break;}};-isUnseen = (pin) => {if (pin.pinned_by?.id === this.currentUser?.id) {return false;@@ -55,12 +64,10 @@ export default class ChatPinnedMessagesList extends Component {const lastViewed = new Date(this.#lastViewedPinsAtSnapshot);return pinnedAt > lastViewed;};-decorateMessage = (pin) => {pin.message.isUnseen = this.isUnseen(pin);return pin.message;};-pinnedByText = (pin) => {if (pin.pinned_by?.id === this.currentUser?.id) {return i18n("chat.pinned_messages.pinned_by_you");@@ -69,14 +76,41 @@ export default class ChatPinnedMessagesList extends Component {username: pin.pinned_by?.username,});};-routeModels = (pin) => {return [...this.args.channel.routeModels, pin.message.id];};-#lastViewedPinsAtSnapshot =this.args.channel.currentUserMembership?.lastViewedPinsAt;+ // not managers — "Dismiss pinned messages" would read as unpinning for all+ get canToggleDismissal() {+ return this.pinnedMessages.length > 0 && !this.args.channel.canManagePins;+ }++ get barDismissed() {+ return hasPinsDismissal(this.args.channel);+ }++ // mirror the visited pin in the bar (the jump's scroll wouldn't update it)+ @action+ visitPin(pin) {+ this.args.channel.activePinnedMessageId = pin.message.id;+ }++ @action+ dismissBar() {+ const channel = this.args.channel;+ dismissPinsUpTo(channel, newestPinId(this.pinnedMessages));+ this.router.transitionTo("chat.channel", ...channel.routeModels);+ }++ @action+ showBar() {+ const channel = this.args.channel;+ resetPinsDismissal(channel);+ this.router.transitionTo("chat.channel", ...channel.routeModels);+ }+handlePinMessage(data) {const existingPin = this.pinnedMessages.find((pin) => pin.message.id === data.chat_message_id@@ -124,6 +158,7 @@ export default class ChatPinnedMessagesList extends Component {@route="chat.channel.near-message"@models={{this.routeModels pin}}class="chat-pinned-message"+ {{on "click" (fn this.visitPin pin)}}><ChatMessage@message={{this.decorateMessage pin}}@@ -150,6 +185,24 @@ export default class ChatPinnedMessagesList extends Component {</div>{{/each}}</div>++ {{#if this.canToggleDismissal}}+ <div class="chat-pinned-messages-list__footer">+ {{#if this.barDismissed}}+ <DButton+ @action={{this.showBar}}+ @label="chat.pinned_messages.show"+ class="btn-flat chat-pinned-messages-list__show"+ />+ {{else}}+ <DButton+ @action={{this.dismissBar}}+ @label="chat.pinned_messages.dismiss"+ class="btn-flat chat-pinned-messages-list__dismiss"+ />+ {{/if}}+ </div>+ {{/if}}</div></template>}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjsindex 391353015c1..2c85da45f6c 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs@@ -53,8 +53,8 @@ export default class ChatDrawerRoutesChannel extends Component {/>{{/if}}- <a.ThreadsListButton @channel={{@model.channel}} /><a.PinnedMessagesButton @channel={{@model.channel}} />+ <a.ThreadsListButton @channel={{@model.channel}} /><a.ToggleDrawerButton /><a.FullPageButton /><a.CloseDrawerButton />diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/pinned-messages-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/pinned-messages-button.gjsindex 6704ab4fe9a..8ed2cdcf59f 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/pinned-messages-button.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/pinned-messages-button.gjs@@ -4,6 +4,7 @@ import { LinkTo } from "@ember/routing";import { service } from "@ember/service";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";+import { hasPinsDismissal } from "discourse/plugins/chat/discourse/lib/chat-pinned-bar-dismissal";export default class ChatNavbarPinnedMessagesButton extends Component {@service router;@@ -15,10 +16,13 @@ export default class ChatNavbarPinnedMessagesButton extends Component {event.stopPropagation();};+ // only the way back to the pins panel while the bar itself is dismissedget showButton() {return (this.siteSettings.chat_pinned_messages &&this.args.channel?.hasPinnedMessages &&+ !this.args.channel.canManagePins &&+ hasPinsDismissal(this.args.channel) &&this.router.currentRoute?.name !== "chat.channel.pins");}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/pinned-message-bar.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/pinned-message-bar.gjsnew file mode 100644index 00000000000..e8c9c9e72db--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/pinned-message-bar.gjs@@ -0,0 +1,306 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { modifier as modifierFn } from "ember-modifier";+import DButton from "discourse/ui-kit/d-button";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";+import { i18n } from "discourse-i18n";+import {+ dismissPinsUpTo,+ newestPinId,+ pinsDismissedAboveId,+ resetPinsDismissal,+} from "discourse/plugins/chat/discourse/lib/chat-pinned-bar-dismissal";++const INDICATOR_WINDOW = 4;+const INDICATOR_HEIGHT_PX = 30;+const SEGMENT_GAP_PX = 2;+const INDICATOR_FADE_PX = 8;++export default class ChatPinnedMessageBar extends Component {+ @service chatApi;+ @service messageBus;+ @service router;+ @service siteSettings;++ @tracked pins = [];+ subscribe = modifierFn((_element, [channelId]) => {+ const key = `/chat/${channelId}`;+ this.messageBus.subscribe(+ key,+ this.onBusMessage,+ this.args.channel.channelMessageBusLastId+ );+ this.loadPins();+ return () => this.messageBus.unsubscribe(key, this.onBusMessage);+ });+ #loadSequence = 0;++ get dismissed() {+ if (this.args.channel.canManagePins) {+ return false;+ }+ const dismissedAbove = pinsDismissedAboveId(this.args.channel);+ if (dismissedAbove == null || this.pins.length === 0) {+ return false;+ }+ return newestPinId(this.pins) <= dismissedAbove;+ }++ get showBar() {+ return (+ this.siteSettings.chat_pinned_messages &&+ this.args.channel?.hasPinnedMessages+ );+ }++ get orderedPins() {+ return [...this.pins].sort((a, b) => a.message.id - b.message.id);+ }++ // the newest pin at or above the viewport bottom — the one governing the view+ get currentPin() {+ const pins = this.orderedPins;+ if (pins.length === 0) {+ return null;+ }+ // a tapped pin overrides the anchor until chat-channel clears it on scroll+ const tappedId = this.args.channel.activePinnedMessageId;+ if (tappedId != null) {+ const tapped = pins.find((pin) => pin.message.id === tappedId);+ if (tapped) {+ return tapped;+ }+ }+ const bottomId = this.args.viewportBottomMessageId;+ if (bottomId == null) {+ return pins[pins.length - 1];+ }+ let active = pins[0];+ for (const pin of pins) {+ if (pin.message.id > bottomId) {+ break;+ }+ active = pin;+ }+ return active;+ }++ get currentIndex() {+ return Math.max(0, this.orderedPins.indexOf(this.currentPin));+ }++ get hasMultiplePins() {+ return this.pins.length > 1;+ }++ get indicatorTop() {+ const total = this.pins.length;+ if (total <= INDICATOR_WINDOW) {+ return 0;+ }+ const top = this.currentIndex - Math.floor(INDICATOR_WINDOW / 2);+ return Math.max(0, Math.min(top, total - INDICATOR_WINDOW));+ }++ get visibleSegments() {+ return Math.min(this.pins.length, INDICATOR_WINDOW);+ }++ get indicatorStyle() {+ const visible = this.visibleSegments;+ const segment = Math.floor(+ (INDICATOR_HEIGHT_PX - SEGMENT_GAP_PX * (visible - 1)) / visible+ );+ 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;+ return trustHTML(+ `--chat-pinned-bar-seg: ${segment}px; ` ++ `--chat-pinned-bar-gap: ${SEGMENT_GAP_PX}px; ` ++ `--chat-pinned-bar-indicator-height: ${height}px; ` ++ `--chat-pinned-bar-indicator-top: ${top}; ` ++ `--chat-pinned-bar-active: ${this.currentIndex}; ` ++ `--chat-pinned-bar-fade-top: ${fadeTop}px; ` ++ `--chat-pinned-bar-fade-bottom: ${fadeBottom}px`+ );+ }++ get showInlineDismiss() {+ return !this.hasMultiplePins && !this.args.channel.canManagePins;+ }++ get pinsPanelOpen() {+ return this.router.currentRoute?.name === "chat.channel.pins";+ }++ get seeAllRoute() {+ return this.pinsPanelOpen ? "chat.channel" : "chat.channel.pins";+ }++ get seeAllLabel() {+ return this.pinsPanelOpen+ ? i18n("chat.pinned_messages.close")+ : i18n("chat.pinned_bar.see_all");+ }++ get currentExcerpt() {+ const message = this.currentPin?.message;+ if (message?.excerpt) {+ // excerpt is server-escaped HTML — trust it so entities/emoji aren't re-escaped+ return trustHTML(message.excerpt);+ }+ // media-only fallback: leave untrusted so the template escapes it+ return message?.message ?? "";+ }++ @action+ onBusMessage(busData) {+ switch (busData.type) {+ case "pin":+ case "unpin":+ this.loadPins();+ break;+ case "edit":+ this.#updatePinnedMessage(busData.chat_message);+ break;+ }+ }++ #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;+ }+ }++ @action+ async loadPins() {+ if (!this.showBar) {+ this.pins = [];+ return;+ }++ const sequence = ++this.#loadSequence;+ try {+ const pins = await this.chatApi.pinnedMessages(this.args.channel);+ if (sequence === this.#loadSequence) {+ this.pins = pins;+ this.#reconcileDismissal();+ }+ } catch {+ // keep the previously loaded pins on a transient failure+ }+ }++ #reconcileDismissal() {+ const dismissedAbove = pinsDismissedAboveId(this.args.channel);+ if (dismissedAbove != null && newestPinId(this.pins) > dismissedAbove) {+ resetPinsDismissal(this.args.channel);+ }+ }++ @action+ jumpToCurrentPin() {+ // jump to the shown pin, then preview the next older one (wraps oldest -> newest)+ const pins = this.orderedPins;+ const current = this.currentPin;+ if (!current) {+ return;+ }+ this.args.onJumpToMessage?.(current.message.id);+ const index = pins.indexOf(current);+ const next = index <= 0 ? pins[pins.length - 1] : pins[index - 1];+ this.args.channel.activePinnedMessageId = next.message.id;+ }++ @action+ dismiss() {+ dismissPinsUpTo(this.args.channel, newestPinId(this.pins));+ }++ <template>+ {{#if this.showBar}}+ <div+ class={{dConcatClass+ "chat-pinned-bar"+ (if this.currentPin "" "--loading")+ (if this.dismissed "--dismissed")+ }}+ {{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}}+ >+ {{#if this.hasMultiplePins}}+ <span+ class="chat-pinned-bar__indicator"+ aria-hidden="true"+ style={{this.indicatorStyle}}+ >+ <span class="chat-pinned-bar__indicator-track">+ {{#each this.orderedPins as |pin|}}+ <span+ class="chat-pinned-bar__indicator-segment"+ data-pin-id={{pin.id}}+ ></span>+ {{/each}}+ <span class="chat-pinned-bar__indicator-thumb"></span>+ </span>+ </span>+ {{/if}}++ <span class="chat-pinned-bar__content">+ <span class="chat-pinned-bar__label">+ {{dIcon "thumbtack"}}+ {{i18n "chat.pinned_bar.title"}}+ </span>+ <span class="chat-pinned-bar__excerpt">+ {{dReplaceEmoji this.currentExcerpt}}+ </span>+ </span>+ </button>+ {{/if}}++ {{#if this.showInlineDismiss}}+ <DButton+ @action={{this.dismiss}}+ @icon="xmark"+ @title="chat.pinned_bar.dismiss"+ @ariaLabel="chat.pinned_bar.dismiss"+ class="chat-pinned-bar__dismiss btn-transparent no-text"+ />+ {{else}}+ <LinkTo+ @route={{this.seeAllRoute}}+ @models={{@channel.routeModels}}+ class={{if+ this.pinsPanelOpen+ "chat-pinned-bar__see-all btn no-text btn-transparent --active"+ "chat-pinned-bar__see-all btn no-text btn-transparent"+ }}+ aria-label={{this.seeAllLabel}}+ title={{this.seeAllLabel}}+ >+ {{dIcon "list"}}+ {{#if @channel.hasUnseenPins}}+ <span class="chat-pinned-bar__unread-indicator"></span>+ {{/if}}+ </LinkTo>+ {{/if}}+ </div>+ {{/if}}+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.jsindex 15afe1074db..a62fe5667b4 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js@@ -274,9 +274,7 @@ export default class ChatChannelSubscriptionManager {message.pinned = true;}- if (!alreadyApplied) {- this.channel.pinnedMessagesCount++;- }+ this.#syncPinnedMessagesCount(data, alreadyApplied, 1);if (this.channel.currentUserMembership &&@@ -296,10 +294,18 @@ export default class ChatChannelSubscriptionManager {message.pinned = false;}- if (!alreadyApplied) {+ this.#syncPinnedMessagesCount(data, alreadyApplied, -1);+ }++ // assign the authoritative count (idempotent under replayed/duplicate+ // events); delta path is only a fallback for older events without a count+ #syncPinnedMessagesCount(data, alreadyApplied, delta) {+ if (data.pinned_message_count !== undefined) {+ this.channel.pinnedMessagesCount = data.pinned_message_count;+ } else if (!alreadyApplied) {this.channel.pinnedMessagesCount = Math.max(0,- this.channel.pinnedMessagesCount - 1+ this.channel.pinnedMessagesCount + delta);}}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-pinned-bar-dismissal.js b/plugins/chat/assets/javascripts/discourse/lib/chat-pinned-bar-dismissal.jsnew file mode 100644index 00000000000..6b5f53619f8--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-pinned-bar-dismissal.js@@ -0,0 +1,30 @@+import KeyValueStore from "discourse/lib/key-value-store";++// Per-device dismissal: we record the newest dismissed pin id and reveal the+// bar again once a higher id arrives. Kept on the channel (reactive) and+// mirrored to local storage (survives reloads).+export const STORE_NAMESPACE = "discourse_chat_pinned_bar_";++const store = new KeyValueStore(STORE_NAMESPACE);++export function newestPinId(pins) {+ return pins.length ? Math.max(...pins.map((pin) => pin.id)) : null;+}++export function dismissPinsUpTo(channel, pinId) {+ channel.pinsDismissedAboveId = pinId;+ store.setObject({ key: String(channel.id), value: pinId });+}++export function pinsDismissedAboveId(channel) {+ return channel.pinsDismissedAboveId ?? store.getObject(String(channel.id));+}++export function hasPinsDismissal(channel) {+ return pinsDismissedAboveId(channel) != null;+}++export function resetPinsDismissal(channel) {+ channel.pinsDismissedAboveId = null;+ store.remove(String(channel.id));+}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.jsindex f0873cc7f0f..4a4c745e4e0 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js@@ -73,6 +73,11 @@ export default class ChatChannel {@tracked draft;@tracked newestMessage;@tracked pinnedMessagesCount;+ // newest pin id the current user dismissed the bar above (per-device); the+ // bar reappears once a pin newer than this exists+ @tracked pinsDismissedAboveId;+ // pin the user tapped in the bar; overrides scroll anchoring until they scroll+ @tracked activePinnedMessageId = null;threadsManager = new ChatThreadsManager(getOwnerWithFallback(this));messagesManager = new ChatMessagesManager(getOwnerWithFallback(this));diff --git a/plugins/chat/assets/stylesheets/common/chat-notices.scss b/plugins/chat/assets/stylesheets/common/chat-notices.scssindex 8757b0ff13e..fb88839297a 100644--- a/plugins/chat/assets/stylesheets/common/chat-notices.scss+++ b/plugins/chat/assets/stylesheets/common/chat-notices.scss@@ -13,6 +13,11 @@top: 2rem;}+ // float notices below the pinned bar only while it's actually visible+ .chat-channel:has(.chat-pinned-bar:not(.--dismissed, .--loading)) & {+ top: var(--chat-pinned-bar-height);+ }+&__notice,.chat-retention-reminder {display: flex;diff --git a/plugins/chat/assets/stylesheets/common/chat-pinned-bar.scss b/plugins/chat/assets/stylesheets/common/chat-pinned-bar.scssnew file mode 100644index 00000000000..f74d4d5a31c--- /dev/null+++ b/plugins/chat/assets/stylesheets/common/chat-pinned-bar.scss@@ -0,0 +1,159 @@+.chat-channel {+ // shared by the bar (its height) and the floating notices (their top offset)+ --chat-pinned-bar-height: 2.75rem;+}++.chat-pinned-bar {+ display: flex;+ align-items: stretch;+ gap: var(--space-1);+ min-width: 0; // allow the bar to shrink instead of forcing a min width on the channel/drawer+ min-height: var(--chat-pinned-bar-height);+ box-sizing: border-box;+ padding: var(--space-1) var(--space-2);+ border-bottom: 1px solid var(--content-border-color);+ background: var(--secondary);+ flex-shrink: 0;+ z-index: 2;++ &.--loading,+ &.--dismissed {+ display: none;+ }++ &__main {+ 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 {+ background: var(--d-hover);+ }+ }++ &__indicator {+ align-self: center;+ flex-shrink: 0;+ width: 3px;+ height: var(--chat-pinned-bar-indicator-height, 1.875rem);+ overflow: hidden;+ mask-image: linear-gradient(+ to bottom,+ transparent 0,+ black var(--chat-pinned-bar-fade-top, 0),+ black calc(100% - var(--chat-pinned-bar-fade-bottom, 0px)),+ transparent 100%+ );+ }++ &__indicator-track {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: var(--chat-pinned-bar-gap, 2px);++ // scroll by one slot (bar + gap) per step+ transform: translateY(+ calc(+ var(--chat-pinned-bar-indicator-top, 0) *+ (var(--chat-pinned-bar-seg, 6px) + var(--chat-pinned-bar-gap, 2px)) *+ -1+ )+ );++ @media (prefers-reduced-motion: no-preference) {+ transition: transform 150ms ease;+ }+ }++ &__indicator-segment {+ flex: 0 0 auto;+ height: var(--chat-pinned-bar-seg, 6px);++ // translucent tint of the active colour so dim bars keep contrast in both+ // schemes (--tertiary-low collapses into the dark-mode background)+ background: var(--tertiary);+ opacity: 0.4;+ border-radius: 3px;+ }++ &__indicator-thumb {+ position: absolute;+ inset-inline: 0;+ inset-block-start: 0;+ height: var(--chat-pinned-bar-seg, 6px);+ background: var(--tertiary);+ border-radius: 3px;+ transform: translateY(+ calc(+ var(--chat-pinned-bar-active, 0) *+ (var(--chat-pinned-bar-seg, 6px) + var(--chat-pinned-bar-gap, 2px))+ )+ );++ @media (prefers-reduced-motion: no-preference) {+ transition: transform 150ms ease;+ }+ }++ &__content {+ display: flex;+ flex-direction: column;+ min-width: 0;+ overflow: hidden;+ }++ &__label {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ color: var(--tertiary);+ font-size: var(--font-down-2);+ font-weight: 700;++ .d-icon {+ font-size: var(--font-down-2);+ transform: rotate(45deg);+ }+ }++ &__excerpt {+ @include ellipsis;+ color: var(--primary);+ font-size: var(--font-down-1);+ }++ &__see-all,+ &__dismiss {+ position: relative;+ align-self: center;+ flex-shrink: 0;++ .d-icon {+ color: var(--primary-medium);+ }+ }++ &__see-all {+ &.--active .d-icon {+ color: var(--tertiary);+ }+ }++ &__unread-indicator {+ @include chat-unread-indicator;+ position: absolute;+ inset-block-start: 0;+ inset-inline-end: 0;+ transform: translate(calc(-50% + 2px), calc(50% - 2px));+ border: 2px solid var(--secondary);+ }+}diff --git a/plugins/chat/assets/stylesheets/common/chat-pinned-messages.scss b/plugins/chat/assets/stylesheets/common/chat-pinned-messages.scssindex 0258334b6b2..50178ed8757 100644--- a/plugins/chat/assets/stylesheets/common/chat-pinned-messages.scss+++ b/plugins/chat/assets/stylesheets/common/chat-pinned-messages.scss@@ -3,6 +3,22 @@transform: rotate(45deg);}+.c-navbar__pinned-messages-btn {+ position: relative;++ .d-icon {+ transform: rotate(45deg);+ }++ &__unread-indicator {+ @include chat-unread-indicator;+ position: absolute;+ inset-block-start: 5px;+ inset-inline-end: 5px;+ border: 2px solid var(--secondary);+ }+}+.chat-pinned-messages-list {display: flex;flex-direction: column;@@ -26,6 +42,21 @@color: var(--primary-medium);}+.chat-pinned-messages-list__footer {+ position: sticky;+ inset-block-end: 0;+ margin-block-start: auto;+ padding: var(--space-2);+ background: var(--secondary);+ border-top: 1px solid var(--content-border-color);+}++.chat-pinned-messages-list__dismiss,+.chat-pinned-messages-list__show {+ width: 100%;+ color: var(--primary-medium);+}+.chat-pinned-message {display: block;margin-inline: 1rem 0.75rem;@@ -82,22 +113,3 @@transform: rotate(45deg);}}--.c-navbar__pinned-messages-btn {- position: relative;-- .d-icon {- transform: rotate(45deg);- }-- &__unread-indicator {- position: absolute;- top: 5px;- right: 5px;- width: 8px;- height: 8px;- background: var(--tertiary);- border-radius: 50%;- border: 2px solid var(--secondary);- }-}diff --git a/plugins/chat/assets/stylesheets/common/index.scss b/plugins/chat/assets/stylesheets/common/index.scssindex c261ee7cf7f..3245fe9b892 100644--- a/plugins/chat/assets/stylesheets/common/index.scss+++ b/plugins/chat/assets/stylesheets/common/index.scss@@ -77,3 +77,4 @@@import "chat-search";@import "edit-category-chat";@import "chat-pinned-messages";+@import "chat-pinned-bar";diff --git a/plugins/chat/assets/stylesheets/desktop/chat-side-panel.scss b/plugins/chat/assets/stylesheets/desktop/chat-side-panel.scssindex 98524bfea61..d4814599dd3 100644--- a/plugins/chat/assets/stylesheets/desktop/chat-side-panel.scss+++ b/plugins/chat/assets/stylesheets/desktop/chat-side-panel.scss@@ -2,7 +2,11 @@min-height: 0;display: grid;grid-template-areas: "main threads";- grid-template-columns: 1fr auto;++ // minmax(0, …) lets the main area shrink below its content's min-content+ // (e.g. the pinned-message bar's text), so the side-panel divider can be+ // dragged freely instead of stopping at the widest no-wrap content.+ grid-template-columns: minmax(0, 1fr) auto;}.chat-side-panel {diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex 07872c451b7..a75dfec4ea7 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -68,8 +68,15 @@ en:pinned_messages:title: "Pinned messages"close: "Close pinned messages"+ dismiss: "Dismiss pinned messages"+ show: "Show pinned messages"pinned_by_you: "Pinned by you"pinned_by_user: "Pinned by %{username}"+ pinned_bar:+ title: "Pinned"+ see_all: "See all pinned messages"+ jump_to_pinned: "Jump to pinned message"+ dismiss: "Dismiss pinned message"no_pinned_messages: "No pinned messages in this channel."pin_message: "Pin message"unpin_message: "Unpin message"diff --git a/plugins/chat/spec/models/chat/pinned_message_spec.rb b/plugins/chat/spec/models/chat/pinned_message_spec.rbindex 2e915c6c7d8..51939cfbc8e 100644--- a/plugins/chat/spec/models/chat/pinned_message_spec.rb+++ b/plugins/chat/spec/models/chat/pinned_message_spec.rb@@ -26,9 +26,8 @@ RSpec.describe Chat::PinnedMessage doFabricate(:chat_pinned_message, chat_message: other_message, chat_channel: other_channel)end- it "returns pins for the specified channel ordered by created_at desc" do+ it "returns pins for the specified channel" dopins = described_class.for_channel(channel)- expect(pins.count).to eq(2)expect(pins.map(&:chat_message_id)).to contain_exactly(message_1.id, message_2.id)endenddiff --git a/plugins/chat/spec/services/chat/list_channel_pins_spec.rb b/plugins/chat/spec/services/chat/list_channel_pins_spec.rbindex 86d796678ed..74c5813f709 100644--- a/plugins/chat/spec/services/chat/list_channel_pins_spec.rb+++ b/plugins/chat/spec/services/chat/list_channel_pins_spec.rb@@ -52,6 +52,10 @@ RSpec.describe Chat::ListChannelPins doexpect(result[:pins]).to contain_exactly(pin_1, pin_2)end+ it "orders pins by timeline (oldest message first)" do+ expect(result[:pins].map(&:chat_message_id)).to eq([message_1.id, message_2.id])+ end+it "returns membership" doexpect(result[:membership]).to eq(membership)enddiff --git a/plugins/chat/spec/services/chat/pin_message_spec.rb b/plugins/chat/spec/services/chat/pin_message_spec.rbindex ea2ebcfa4fa..0ffbe326bd0 100644--- a/plugins/chat/spec/services/chat/pin_message_spec.rb+++ b/plugins/chat/spec/services/chat/pin_message_spec.rb@@ -70,6 +70,7 @@ RSpec.describe Chat::PinMessage doexpect(pin_event).to be_presentexpect(pin_event.channel).to eq("/chat/#{channel.id}")expect(pin_event.data["chat_message_id"]).to eq(message.id)+ expect(pin_event.data["pinned_message_count"]).to eq(1)endendenddiff --git a/plugins/chat/spec/services/chat/unpin_message_spec.rb b/plugins/chat/spec/services/chat/unpin_message_spec.rbindex 173cb470b7d..0f1b0a5aabb 100644--- a/plugins/chat/spec/services/chat/unpin_message_spec.rb+++ b/plugins/chat/spec/services/chat/unpin_message_spec.rb@@ -58,6 +58,7 @@ RSpec.describe Chat::UnpinMessage doexpect(unpin_event).to be_presentexpect(unpin_event.channel).to eq("/chat/#{channel.id}")expect(unpin_event.data["chat_message_id"]).to eq(message.id)+ expect(unpin_event.data["pinned_message_count"]).to eq(0)endendenddiff --git a/plugins/chat/spec/system/pinned_messages_spec.rb b/plugins/chat/spec/system/pinned_messages_spec.rbindex fd39da8e6d8..8ca0a3af22e 100644--- a/plugins/chat/spec/system/pinned_messages_spec.rb+++ b/plugins/chat/spec/system/pinned_messages_spec.rb@@ -21,9 +21,9 @@ RSpec.describe "Chat pinned messages" dochannel_page.messages.find(id: message.id).secondary_action("pin")expect(page).to have_css(".chat-message-info__pinned")- expect(page).to have_css(".c-navbar__pinned-messages-btn")+ expect(page).to have_css(".chat-pinned-bar__see-all")- find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")expect(page).to have_content("Important message")@@ -45,14 +45,14 @@ RSpec.describe "Chat pinned messages" do)Chat::Publisher.publish_pin!(channel, message, pin)- expect(page).to have_css(".c-navbar__pinned-messages-btn__unread-indicator")+ expect(page).to have_css(".chat-pinned-bar__unread-indicator")- find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")find(".c-navbar__close-pins-button").click- expect(page).to have_no_css(".c-navbar__pinned-messages-btn__unread-indicator")+ expect(page).to have_no_css(".chat-pinned-bar__unread-indicator")endit "marks pins as read when viewing the panel" do@@ -63,16 +63,16 @@ RSpec.describe "Chat pinned messages" do)chat_page.visit_channel(channel)- expect(page).to have_css(".c-navbar__pinned-messages-btn__unread-indicator")+ expect(page).to have_css(".chat-pinned-bar__unread-indicator")- find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")# Reload while panel is open — pins should stay marked as readpage.refreshchat_page.visit_channel(channel)- expect(page).to have_no_css(".c-navbar__pinned-messages-btn__unread-indicator")+ expect(page).to have_no_css(".chat-pinned-bar__unread-indicator")endit "shows unseen pin icon in the panel for pins not yet viewed" do@@ -80,21 +80,167 @@ RSpec.describe "Chat pinned messages" doChat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: other_user)chat_page.visit_channel(channel)- find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")expect(page).to have_css(".chat-pinned-message__pinned-by-icon")find(".c-navbar__close-pins-button").click- find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")expect(page).to have_no_css(".chat-pinned-message__pinned-by-icon")end+ it "keeps the sticky bar in sync as messages are pinned and unpinned" do+ other_message = Fabricate(:chat_message, chat_channel: channel, message: "Second message")++ chat_page.visit_channel(channel)++ # first pin: bar appears, no position indicator for a single pin+ channel_page.messages.find(id: message.id).secondary_action("pin")+ expect(page).to have_css(".chat-pinned-bar")+ expect(page).to have_no_css(".chat-pinned-bar__indicator")++ # second pin: position indicator appears with a segment per pin+ channel_page.messages.find(id: other_message.id).secondary_action("pin")+ expect(page).to have_css(".chat-pinned-bar__indicator-segment", count: 2)++ # unpin one: bar stays, back to a single pin+ channel_page.messages.find(id: other_message.id).secondary_action("unpin")+ expect(page).to have_css(".chat-pinned-bar")+ expect(page).to have_no_css(".chat-pinned-bar__indicator")++ # unpin the last one: bar disappears+ channel_page.messages.find(id: message.id).secondary_action("unpin")+ expect(page).to have_no_css(".chat-pinned-bar")+ end++ it "cycles through pins when clicking the sticky bar" do+ other_message = Fabricate(:chat_message, chat_channel: channel, message: "Second message")+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)+ Chat::PinnedMessage.create!(chat_message: other_message, chat_channel: channel, user: admin)++ chat_page.visit_channel(channel)++ # newest pin is shown first+ expect(page).to have_css(".chat-pinned-bar__excerpt", text: "Second message")++ find(".chat-pinned-bar__main").click+ expect(page).to have_css(".chat-pinned-bar__excerpt", text: "Important message")++ find(".chat-pinned-bar__main").click+ expect(page).to have_css(".chat-pinned-bar__excerpt", text: "Second message")+ end++ it "shows the visited pin in the sticky bar when clicking a pin in the panel" do+ other_message = Fabricate(:chat_message, chat_channel: channel, message: "Second message")+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)+ Chat::PinnedMessage.create!(chat_message: other_message, chat_channel: channel, user: admin)++ chat_page.visit_channel(channel)+ expect(page).to have_css(".chat-pinned-bar__excerpt", text: "Second message")++ find(".chat-pinned-bar__see-all").click+ find(".chat-pinned-message", text: "Important message").click++ expect(page).to have_css(".chat-pinned-bar__excerpt", text: "Important message")+ end++ it "lists pins oldest-first in the panel (channel timeline order)" do+ other_message = Fabricate(:chat_message, chat_channel: channel, message: "Second message")+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)+ Chat::PinnedMessage.create!(chat_message: other_message, chat_channel: channel, user: admin)++ chat_page.visit_channel(channel)+ find(".chat-pinned-bar__see-all").click++ expect(page).to have_css(".chat-pinned-message:first-child", text: "Important message")+ expect(page).to have_css(".chat-pinned-message:last-child", text: "Second message")+ end++ it "removes a pinned message from the bar when it is deleted" do+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)++ chat_page.visit_channel(channel)+ expect(page).to have_css(".chat-pinned-bar")++ # deleting unpins server-side and broadcasts an unpin event+ channel_page.messages.delete(message)++ expect(page).to have_no_css(".chat-pinned-bar")+ end++ it "toggles the pinned messages panel from the bar's see-all button" do+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)++ chat_page.visit_channel(channel)++ find(".chat-pinned-bar__see-all").click+ expect(page).to have_css(".c-routes.--channel-pins")++ # clicking again closes the panel+ find(".chat-pinned-bar__see-all").click+ expect(page).to have_no_css(".c-routes.--channel-pins")+ end++ it "lets a user without pin permissions hide the bar from the pins panel" do+ user = Fabricate(:user)+ channel.add(user)+ other_message = Fabricate(:chat_message, chat_channel: channel, message: "Second message")+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)+ Chat::PinnedMessage.create!(chat_message: other_message, chat_channel: channel, user: admin)++ sign_in(user)+ chat_page.visit_channel(channel)+ expect(page).to have_css(".chat-pinned-bar")++ find(".chat-pinned-bar__see-all").click+ find(".chat-pinned-messages-list__dismiss").click++ # the panel closes and the bar is dismissed (hidden) until a newer pin+ expect(page).to have_no_css(".c-routes.--channel-pins")+ expect(page).to have_no_css(".chat-pinned-bar")+ end++ it "lets a user without pin permissions dismiss a single pin from the bar and show it again" do+ user = Fabricate(:user)+ channel.add(user)+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)++ sign_in(user)+ chat_page.visit_channel(channel)++ # a single pin offers an inline dismiss instead of the see-all button+ expect(page).to have_no_css(".chat-pinned-bar__see-all")+ find(".chat-pinned-bar__dismiss").click+ expect(page).to have_no_css(".chat-pinned-bar")++ # the navbar button reappears as the way back to the pins panel+ find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-messages-list__show").click++ expect(page).to have_no_css(".c-routes.--channel-pins")+ expect(page).to have_css(".chat-pinned-bar")+ expect(page).to have_no_css(".c-navbar__pinned-messages-btn")+ end++ it "does not offer the dismiss button to users who can manage pins" do+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: admin)++ chat_page.visit_channel(channel)+ find(".chat-pinned-bar__see-all").click++ expect(page).to have_css(".c-routes.--channel-pins")+ expect(page).to have_content("Important message")+ expect(page).to have_no_css(".chat-pinned-messages-list__dismiss")+ end+context "when viewing pinned messages attribution" doit "shows 'Pinned by you' when current user pinned the message" dochat_page.visit_channel(channel)channel_page.messages.find(id: message.id).secondary_action("pin")- find(".c-navbar__pinned-messages-btn").click++ expect(page).to have_css(".chat-message-info__pinned")+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")expect(page).to have_css(@@ -117,7 +263,7 @@ RSpec.describe "Chat pinned messages" doit "shows 'Pinned by [username]'" dochat_page.visit_channel(channel)- find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")expect(page).to have_css(diff --git a/plugins/chat/spec/system/shortcuts/full_page_spec.rb b/plugins/chat/spec/system/shortcuts/full_page_spec.rbindex 22a3cbf3f0b..cef160fc556 100644--- a/plugins/chat/spec/system/shortcuts/full_page_spec.rb+++ b/plugins/chat/spec/system/shortcuts/full_page_spec.rb@@ -27,12 +27,16 @@ RSpec.describe "Shortcuts | full page" docontext "when pressing Esc" dofab!(:message) { Fabricate(:chat_message, chat_channel: channel_1, use_service: true) }fab!(:pin) { Fabricate(:chat_pinned_message, chat_message: message, user: current_user) }+ fab!(:other_message) { Fabricate(:chat_message, chat_channel: channel_1, use_service: true) }+ fab!(:other_pin) do+ Fabricate(:chat_pinned_message, chat_message: other_message, user: current_user)+ endbefore { SiteSetting.chat_pinned_messages = true }it "closes the pinned messages list" dochat.visit_channel(channel_1)- find(".c-navbar__pinned-messages-btn").click+ find(".chat-pinned-bar__see-all").clickexpect(page).to have_css(".c-routes.--channel-pins")diff --git a/plugins/chat/test/javascripts/components/chat-pinned-message-bar-test.gjs b/plugins/chat/test/javascripts/components/chat-pinned-message-bar-test.gjsnew file mode 100644index 00000000000..1d96159952f--- /dev/null+++ b/plugins/chat/test/javascripts/components/chat-pinned-message-bar-test.gjs@@ -0,0 +1,652 @@+import { tracked } from "@glimmer/tracking";+import { getOwner } from "@ember/owner";+import { click, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import KeyValueStore from "discourse/lib/key-value-store";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { publishToMessageBus } from "discourse/tests/helpers/qunit-helpers";+import ChatPinnedMessageBar from "discourse/plugins/chat/discourse/components/chat/pinned-message-bar";+import { STORE_NAMESPACE } from "discourse/plugins/chat/discourse/lib/chat-pinned-bar-dismissal";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++function pinResponse(channel, count) {+ const pinned_messages = [];+ for (let i = 0; i < count; i++) {+ // newest first (i=0), and message ids descend with i so the newest pin+ // sits on the highest-id (bottom-most) message — matching the timeline+ const messageId = 200 + (count - 1 - i);+ pinned_messages.push({+ id: 100 + i,+ chat_message_id: messageId,+ pinned_at: moment().subtract(i, "minute").toISOString(),+ pinned_by: { id: 1, username: "alice" },+ message: { id: messageId, excerpt: `Pinned excerpt ${i}`, message: "x" },+ });+ }+ return response({ pinned_messages, membership: null });+}++// pins from the given ids (the bar orders by message id itself)+function pinsResponse(ids) {+ return response({+ pinned_messages: ids.map((id, i) => ({+ id,+ chat_message_id: 200 + id,+ pinned_at: moment().subtract(i, "minute").toISOString(),+ pinned_by: { id: 1, username: "alice" },+ message: { id: 200 + id, excerpt: `Pin ${id}` },+ })),+ membership: null,+ });+}++// a single pin whose pin-record id is `pinId` (the value the bar compares+// against the dismissed-above id)+function dismissablePinResponse(pinId) {+ return response({+ pinned_messages: [+ {+ id: pinId,+ chat_message_id: 200,+ pinned_at: moment().toISOString(),+ pinned_by: { id: 1, username: "alice" },+ message: { id: 200, excerpt: "Pinned excerpt", message: "x" },+ },+ ],+ membership: null,+ });+}++module("Component | ChatPinnedMessageBar", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.siteSettings.chat_pinned_messages = true;+ this.channel = new ChatFabricators(getOwner(this)).channel();+ this.noop = () => {};+ });++ test("does not render when the channel has no pins", async function (assert) {+ this.channel.pinnedMessagesCount = 0;++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar").doesNotExist();+ });++ test("does not render when the site setting is disabled", async function (assert) {+ this.siteSettings.chat_pinned_messages = false;+ this.channel.pinnedMessagesCount = 2;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 2)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar").doesNotExist();+ });++ test("renders the most recent pin with no indicator for a single pin", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 1)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar").exists();+ assert.dom(".chat-pinned-bar__excerpt").hasText("Pinned excerpt 0");+ assert.dom(".chat-pinned-bar__indicator").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`, () =>+ pinResponse(this.channel, 3)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar__indicator-segment").exists({ count: 3 });+ assert+ .dom(".chat-pinned-bar__indicator-thumb")+ .exists({ count: 1 }, "a single bright bar marks the active pin");+ // oldest-first layout: the newest pin is active at the last index (2 of 3)+ assert+ .dom(".chat-pinned-bar__indicator")+ .hasAttribute(+ "style",+ /--chat-pinned-bar-active:\s*2/,+ "starts on the newest pin, in the bottom slot"+ );++ await click(".chat-pinned-bar__main");++ assert+ .dom(".chat-pinned-bar__indicator")+ .hasAttribute(+ "style",+ /--chat-pinned-bar-active:\s*1/,+ "advancing to an older pin moves the highlight up a slot"+ );+ });++ test("scrolls the indicator window when there are more pins than fit", async function (assert) {+ this.channel.pinnedMessagesCount = 8;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 8)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ // newest pin is active at index 7; the 4-wide window centres on it:+ // top = min(7 - 2, 8 - 4) = 4 (scrolled to the bottom)+ assert.dom(".chat-pinned-bar__indicator-segment").exists({ count: 8 });+ assert+ .dom(".chat-pinned-bar__indicator")+ .hasAttribute(+ "style",+ /indicator-top:\s*4/,+ "window starts at the bottom"+ );++ // advance toward older pins — the window scrolls up+ for (let i = 0; i < 6; i++) {+ await click(".chat-pinned-bar__main");+ }++ // 6 taps back => active index 1 => top = 1 - 2 clamps to 0+ assert+ .dom(".chat-pinned-bar__indicator")+ .hasAttribute(+ "style",+ /indicator-top:\s*0/,+ "rail scrolled toward the oldest pin"+ );+ });++ test("tapping jumps to the shown pin and previews the next", async function (assert) {+ this.channel.pinnedMessagesCount = 2;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 2)+ );++ let jumpedTo = null;+ this.onJump = (messageId) => (jumpedTo = messageId);++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.onJump}}+ />+ </template>+ );++ // opens on the newest pin (message 201)+ assert.dom(".chat-pinned-bar__excerpt").hasText("Pinned excerpt 0");++ await click(".chat-pinned-bar__main");++ 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");++ assert.strictEqual(jumpedTo, 200, "jumps to that previewed pin");+ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText("Pinned excerpt 0", "and previews back to the newest (wraps)");+ });++ test("anchors the active pin to the scroll position", async function (assert) {+ this.channel.pinnedMessagesCount = 3;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 3)+ );+ // message ids: 202 (excerpt 0, newest) / 201 (excerpt 1) / 200 (excerpt 2)+ const view = new (class {+ @tracked bottomId = null;+ })();++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ @viewportBottomMessageId={{view.bottomId}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText("Pinned excerpt 0", "defaults to the newest pin");++ view.bottomId = 201;+ await settled();+ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText("Pinned excerpt 1", "follows the pin governing the view");++ view.bottomId = 100; // above every pin+ await settled();+ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText("Pinned excerpt 2", "falls back to the oldest pin");+ });++ test("links to the full pinned messages list via the see-all icon", async function (assert) {+ this.channel.pinnedMessagesCount = 2;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 2)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar__see-all").exists();+ assert+ .dom(".chat-pinned-bar__see-all")+ .hasAttribute("href", new RegExp(`/${this.channel.id}/pins$`));+ });++ test("shows an inline dismiss instead of the see-all icon for a single pin", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 1)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar__see-all").doesNotExist();+ assert.dom(".chat-pinned-bar__dismiss").exists();++ await click(".chat-pinned-bar__dismiss");++ assert.dom(".chat-pinned-bar").hasClass("--dismissed");+ });++ test("keeps the see-all icon for pin managers with a single pin", async function (assert) {+ this.channel.meta.can_manage_pins = true;+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 1)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar__dismiss").doesNotExist();+ assert.dom(".chat-pinned-bar__see-all").exists();+ });++ test("shows an unread indicator when there are unseen pins", async function (assert) {+ this.channel.pinnedMessagesCount = 2;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 2)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar__unread-indicator").doesNotExist();++ this.channel.currentUserMembership = { has_unseen_pins: true };+ await settled();++ assert.dom(".chat-pinned-bar__unread-indicator").exists();+ });++ test("renders the server excerpt as decoded HTML, not double-escaped", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ response({+ pinned_messages: [+ {+ id: 100,+ chat_message_id: 200,+ pinned_at: moment().toISOString(),+ pinned_by: { id: 1, username: "alice" },+ // server excerpts arrive as entity-encoded HTML+ message: { id: 200, excerpt: "Rules & etiquette…" },+ },+ ],+ membership: null,+ })+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText(+ "Rules & etiquette…",+ "decodes entities rather than escaping them"+ );+ });++ test("reloads pins on a pin/unpin message bus event", async function (assert) {+ let count = 1;+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, count)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar__indicator")+ .doesNotExist("starts with a single pin and no indicator");++ // another message gets pinned elsewhere+ count = 2;+ await publishToMessageBus(`/chat/${this.channel.id}`, {+ type: "pin",+ chat_message_id: 201,+ });+ await settled();++ assert+ .dom(".chat-pinned-bar__indicator-segment")+ .exists({ count: 2 }, "refetches and reflects both pins");+ });++ test("updates the preview when a pinned message is edited", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 1)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar__excerpt").hasText("Pinned excerpt 0");++ // the pinned message (id 200) is edited+ await publishToMessageBus(`/chat/${this.channel.id}`, {+ type: "edit",+ chat_message: { id: 200, message: "edited", excerpt: "Edited excerpt" },+ });+ await settled();++ assert+ .dom(".chat-pinned-bar__excerpt")+ .hasText("Edited excerpt", "reflects the edited message");+ });++ test("ignores edits to messages that are not pinned", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinResponse(this.channel, 1)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ // a different (unpinned) message is edited+ await publishToMessageBus(`/chat/${this.channel.id}`, {+ type: "edit",+ chat_message: { id: 999, message: "x", excerpt: "Should not appear" },+ });+ await settled();++ assert.dom(".chat-pinned-bar__excerpt").hasText("Pinned excerpt 0");+ });++ test("hides the bar when dismissed above the newest pin", async function (assert) {+ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ dismissablePinResponse(100)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar").doesNotHaveClass("--dismissed");++ this.channel.pinsDismissedAboveId = 100; // the newest pin's id+ await settled();++ assert.dom(".chat-pinned-bar").hasClass("--dismissed");+ });++ test("reappears once a pin newer than the dismissed one is added", async function (assert) {+ let pinId = 100;+ this.channel.pinnedMessagesCount = 1;+ this.channel.pinsDismissedAboveId = 100;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ dismissablePinResponse(pinId)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar")+ .hasClass("--dismissed", "stays hidden while no newer pin exists");++ // a newer pin (higher id) is added+ pinId = 101;+ await publishToMessageBus(`/chat/${this.channel.id}`, {+ type: "pin",+ chat_message_id: 201,+ });+ await settled();++ assert+ .dom(".chat-pinned-bar")+ .doesNotHaveClass("--dismissed", "reappears for the newer pin");+ assert.strictEqual(+ this.channel.pinsDismissedAboveId,+ null,+ "clears the stale dismissal so the navbar re-show button doesn't linger"+ );+ });++ test("stays dismissed after reload via stored state", async function (assert) {+ // simulate a previous dismissal persisted to local storage+ const store = new KeyValueStore(STORE_NAMESPACE);+ store.setObject({ key: String(this.channel.id), value: 100 });++ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ dismissablePinResponse(100)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar").hasClass("--dismissed");+ });++ test("pin managers bypass a stored dismissal", async function (assert) {+ // a dismissal recorded before the user could manage pins+ const store = new KeyValueStore(STORE_NAMESPACE);+ store.setObject({ key: String(this.channel.id), value: 100 });+ this.channel.meta.can_manage_pins = true;++ this.channel.pinnedMessagesCount = 1;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ dismissablePinResponse(100)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar")+ .doesNotHaveClass("--dismissed", "managers always see the bar");+ });++ test("stays dismissed when the dismissed pin is unpinned", async function (assert) {+ let ids = [101, 100]; // newest-first+ this.channel.pinnedMessagesCount = 2;+ this.channel.pinsDismissedAboveId = 101;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinsResponse(ids)+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert.dom(".chat-pinned-bar").hasClass("--dismissed");++ // the newest pin is unpinned, leaving only an older (lower-id) pin+ ids = [100];+ await publishToMessageBus(`/chat/${this.channel.id}`, {+ type: "unpin",+ chat_message_id: 301,+ });+ await settled();++ assert+ .dom(".chat-pinned-bar")+ .hasClass("--dismissed", "stays hidden — a removal is not a new pin");+ });++ test("uses the highest pin id, not the first pin, for dismissal", async function (assert) {+ // pins[0] is first by display order but has a LOWER id than another pin+ // (e.g. created_at not monotonic with id) — the bar must compare the max id+ this.channel.pinnedMessagesCount = 2;+ this.channel.pinsDismissedAboveId = 5;+ pretender.get(`/chat/api/channels/${this.channel.id}/pins`, () =>+ pinsResponse([5, 100])+ );++ await render(+ <template>+ <ChatPinnedMessageBar+ @channel={{this.channel}}+ @onJumpToMessage={{this.noop}}+ />+ </template>+ );++ assert+ .dom(".chat-pinned-bar")+ .doesNotHaveClass(+ "--dismissed",+ "shown because a pin with a higher id than the dismissed value exists"+ );+ });+});