import { html, nothing, css, type PropertyValueMap } from "lit";
import { customElement } from "../utils/decorators/custom-element";
import { property, state } from "lit/decorators.js";
import { AppTypeGuid, type AppType, PermissionType } from "../types/app.types";
import type { MessageType, MessagesResultType, MutateMessageProps } from "../types/messages.types";
import { getMessagesOptions, getAddMessageMutationOptions } from "../data/messages";
import { InfiniteQueryController } from "../controllers/infinite-query-controller";
import { ReverseInfiniteScrollController } from "../controllers/infinite-scroll-controller";
import { MutationController } from "../controllers/mutation-controller";
import {
getNextPositionedChild,
getScrollParent,
hasScroll,
isParentAtBottom,
isScrolledToBottom,
scrollParentTo,
} from "../utils/scroll-position";
import {
addCacheItem,
getCacheItem,
getFlatInfiniteResultData,
getPendingCacheItem,
isInfiniteResultDataEmpty,
keepPages,
updateCacheItem,
updateCacheItems,
} from "../utils/query-cache";
import { localized, msg, str } from "@lit/localize";
import { Ref, createRef, ref } from "lit/directives/ref.js";
import type {
RealtimeAppMarkedEventType,
RealtimeMessageEventType,
RealtimeReactionEventType,
RealtimeVoteEventType,
} from "../types/realtime.types";
import { whenConnected, whenDocumentVisible, whenElementVisible } from "../utils/dom";
import { ReactableType } from "../types/reactions.types";
import { PollMutationType, getPollMutation, handleRealtimeVote } from "../data/poll";
import { hasAnyPermission } from "../utils/permission";
import {
MarkConversationMutationType,
UpdateConversationMutationType,
getMarkConversationMutation,
getUpdateConversationMutation,
} from "../data/conversation";
import { WeavySubAppComponent } from "../classes/weavy-sub-app-component";
import { AppContext } from "../contexts/apps-context";
import { provide } from "@lit/context";
import { ShadowPartsController } from "../controllers/shadow-parts-controller";
import { QueryController } from "../controllers/query-controller";
import { MemberDetailType, MembersResultType } from "../types/members.types";
import { getMemberOptions } from "../data/members";
import { Feature } from "../types/features.types";
import { ifDefined } from "lit/directives/if-defined.js";
import { MetadataType } from "../types/lists.types";
import { getTitleFromText, truncateText } from "../utils/strings";
import {
getBlockedUserIdsOptions,
getUserBlockMutationOptions,
type MutateUserBlockContextType,
type MutateUserBlockProps,
} from "../data/blocks";
import { TypingEventType } from "../types/typing.events";
import { MsgEditorSubmitEventType } from "../types/editor.events";
import { PollVoteEventType } from "../types/polls.events";
import { repeat } from "lit/directives/repeat.js";
import { keyed } from "lit/directives/keyed.js";
import { clickOnEnterAndConsumeOnSpace, clickOnSpace } from "../utils/keyboard";
import messagesCss from "../scss/components/messages.scss";
import footerbarCss from "../scss/components/footerbar.scss";
import paneCss from "../scss/components/pane.scss";
import pagerCss from "../scss/components/pager.scss";
import bannerCss from "../scss/components/banner.scss";
import "./ui/wy-avatar";
import "./wy-empty";
import { WyEditorMessage } from "./wy-editor-message";
import "./wy-message-typing";
import "./ui/wy-progress-circular";
import "./ui/wy-item";
import "./ui/wy-icon";
import "./ui/wy-button";
import "./ui/wy-dropdown";
import "./ui/wy-skeleton";
import "./wy-message";
import { ActionType } from "../types/action.types";
declare global {
interface HTMLElementTagNameMap {
"wy-conversation": WyConversation;
}
}
/**
* Displays a single conversation with a message editor and an optional start avatar.
*
* **Used sub components**
*
* - [``](./ui/wy-avatar.ts)
* - [``](./ui/wy-avatar.ts)
* - [``](./ui/wy-avatar.ts)
* - [``](./ui/wy-button.ts)
* - [``](./ui/wy-dropdown.ts)
* - [``](./wy-empty.ts)
* - [``](./wy-editor-message.ts)
* - [``](./ui/wy-icon.ts)
* - [``](./ui/wy-item.ts)
* - [``](./wy-message.ts)
* - [``](./wy-message-typing.ts)
* - [``](./ui/wy-progress-circular.ts)
* - [``](./ui/wy-skeleton.ts)
*
* @slot empty - Content in the empty state.
* @slot footerbar - Content in the footerbar.
*
* @csspart wy-pager - Pager for message infinite scroll.
* @csspart wy-pager-top - Pager styling for top placement.
* @csspart wy-messages - Wrapper for the conversation messages.
* @csspart wy-pane - Pane for the empty state.
* @csspart wy-footerbar - The footerbar where the editor is placed.
* @csspart wy-footerbar-sticky - Styles for making the footerbar sticky.
* @csspart wy-footerbar-floating - Styles for making the footerbar floating.
* @csspart wy-messages - Wrapper for the messages list.
* @csspart wy-message-date-separator - Date separator shown between message days.
* @csspart wy-banner - Unread marker toast wrapper.
* @csspart wy-banner-action - Modifier part for the unread marker action.
* @csspart wy-fade - Modifier part used when fading the unread marker.
* @csspart wy-show - Modifier part used when the unread marker is shown.
*
* @fires {WyActionEventType} wy-action - Emitted when an embed action button is triggered.
* @fires {WyPreviewOpenEventType} wy-preview-open - Fired when a preview overlay is about to open.
* @fires {WyPreviewCloseEventType} wy-preview-close - Fired when a preview overlay is closed.
*/
@customElement("wy-conversation")
@localized()
export class WyConversation extends WeavySubAppComponent {
static override styles = [
messagesCss,
pagerCss,
paneCss,
footerbarCss,
bannerCss,
css`
:host {
position: relative;
display: flex;
flex-direction: column;
flex: 1 1 auto;
}
`,
];
/**
* Controller for exporting named shadow parts.
*
* @internal
*/
protected exportParts = new ShadowPartsController(this);
/**
* Conversation object provided to the component (overrides AppContext).
*
* @type {AppType | undefined}
*/
@provide({ context: AppContext })
@property({ attribute: false, type: Object })
conversation?: AppType;
/**
* Id of the conversation to load and display.
*/
@property({ type: Number })
conversationId?: number;
/**
* Any Message to edit
*/
@property({ attribute: false })
editMessage?: MessageType;
/**
* Whether to render the header area for the conversation.
*/
@property({ type: Boolean })
header: boolean = false;
/**
* Disables the message editor. Used by hosts such as `` when no conversation is selected, since a missing
* conversation alone can't disable it: Messenger creates the conversation on the first submit.
*/
@property({ type: Boolean })
disabled: boolean = false;
/**
* Optional instructions passed to an AI agent for the conversation.
*/
@property()
agentInstructions?: string;
/**
* Placeholder text for the message editor.
*/
@property()
placeholder?: string;
/**
* Position of the unread marker in the message list.
*
* @internal
*/
@state()
lastReadMessagePosition: "above" | "below" = "below";
/**
* The id of the last read message used for rendering the unread marker.
*
* @internal
*/
@state()
lastReadMessageId?: number;
/**
* Whether the "new messages" banner should be shown.
*
* @internal
*/
@state()
showNewMessages: boolean = false;
/**
* Temporarily set when creating a conversation (optimistic UI).
*
* @internal
*/
@state()
isCreatingConversation: boolean = false;
/**
* Whether to show read receipts (presence of receivers).
*
* @internal
*/
@state()
showReadReceipts: boolean = false;
/**
* Optional factory to create a conversation when sending the first message.
*
* @internal
* @type {(payload: Omit) => Promise | undefined}
*/
createConversation?: (payload: Omit) => Promise;
/**
* Optional function to request metadata for a message before sending.
*
* @internal
* @type {(payload: MutateMessageProps) => Promise | undefined}
*/
requestMetadata?: (payload: MutateMessageProps) => Promise;
/**
* Intersection observer used to detect when the bottom sentinel is visible (for marking/scrolling).
*
* @internal
*/
protected bottomObserver: IntersectionObserver | undefined;
/**
* Resize observer used to keep the viewport pinned to the bottom while
* message content grows asynchronously (images, embeds, attachments).
*
* @internal
*/
protected contentResizeObserver: ResizeObserver | undefined;
/**
* The scroll area currently being tracked for user scroll, cached so we can
* detach the listener when it changes or the component disconnects.
*
* @internal
*/
#scrollArea: HTMLElement | undefined;
/**
* The content element currently observed for height changes.
*
* @internal
*/
#observedContent: Element | undefined;
/**
* The conversation id we have already settled at the bottom for. Until this
* matches the current {@link conversationId}, we keep forcing the viewport to
* the bottom and ignore the (transitional) scroll position while the new
* conversation's messages load and render.
*
* @internal
*/
#bottomPinnedForConversation: number | undefined;
/**
* Whether a scroll-to-bottom is already in flight, to avoid stacking
* overlapping scroll loops when content resizes rapidly.
*
* @internal
*/
#isScrollingToBottom = false;
/**
* Updates {@link shouldBeAtBottom} from the live scroll position so manual
* user scrolling immediately disengages the auto-pin behavior.
*
* @internal
*/
#handleAreaScroll = () => {
// Ignore transitional scroll events fired while a freshly opened
// conversation is still loading/rendering, otherwise the persistent scroll
// element's stale position would disengage the forced scroll-to-bottom.
if (this.needsInitialScroll) {
return;
}
// Use the cached scroll area to avoid re-resolving it via getScrollParent on
// every scroll event (this handler runs at scroll frequency).
this.shouldBeAtBottom = this.#scrollArea ? isScrolledToBottom(this.#scrollArea) : this.isAtBottom;
};
isPrivateChat(conversation?: AppType) {
return (conversation ?? this.conversation)?.type === AppTypeGuid.PrivateChat;
}
/**
* Whether this is a private chat with a user the authenticated user has blocked.
*
* Private chats only -- blocks govern directed contact, not shared spaces, so the server never sets `is_blocked` on
* a group. The view has to act on it: the server still delivers realtime, so nothing quiets an open conversation
* unless this component does.
*/
isBlocked(conversation?: AppType) {
const app = conversation ?? this.conversation;
return Boolean(app && this.isPrivateChat(app) && app.is_blocked);
}
isChatRoom(conversation?: AppType) {
return (conversation ?? this.conversation)?.type === AppTypeGuid.ChatRoom;
}
/**
* Infinite query controller for loading messages.
*
* @internal
*/
protected messagesQuery = new InfiniteQueryController(this);
/**
* Query controller for loading members for the conversation.
*
* @internal
*/
protected membersQuery = new QueryController(this);
/**
* Query controller for the ids of the users the viewer has blocked.
*
* Not per conversation -- the query key is shared, so every conversation and every message reads one cached answer.
*
* @internal
*/
protected blockedUsersQuery = new QueryController(this);
/**
* Mutation for marking conversation as read/unread.
*
* @internal
*/
protected markConversationMutation?: MarkConversationMutationType;
/**
* Mutation for updating conversation properties (name/avatar).
*
* @internal
*/
protected updateConversationMutation?: UpdateConversationMutationType;
/**
* Mutation controller for poll votes used within this conversation.
*
* @internal
*/
protected pollMutation?: PollMutationType;
/**
* Controller for adding messages.
*
* @internal
*/
protected addMessageMutation = new MutationController(this);
/**
* Mutation for unblocking the other member from the blocked notice.
*
* Built per user when the notice renders, since the endpoint is keyed on the user being unblocked.
*
* @internal
*/
#userBlockMutation = new MutationController(this);
/**
* Reverse infinite scroll controller (loads newest messages at bottom).
*
* @internal
*/
protected infiniteScroll = new ReverseInfiniteScrollController(this);
/**
* Ref to the top pager element used for loading older messages.
*
* @internal
*/
protected pagerRef: Ref = createRef();
/**
* Ref to the bottom sentinel element used for scrolling/marking behavior.
*
* @internal
*/
protected bottomRef: Ref = createRef();
/**
* Ref to the message editor instance.
*
* @internal
*/
protected editorRef: Ref = createRef();
/**
* Whether the viewport should stay pinned to bottom on updates.
*
* @internal
*/
protected shouldBeAtBottom = true;
/**
* Whether another user is currently typing.
*
* @internal
*/
protected isTyping = false;
/**
* Read-only helper returning whether the viewport is currently scrolled to the bottom.
*
* @internal
*/
get isAtBottom() {
return this.bottomRef.value ? isParentAtBottom(this.bottomRef.value) : true;
}
/**
* Whether we still need to perform the initial scroll-to-bottom for the
* current conversation (i.e. we just switched conversation and haven't yet
* settled at the bottom). While true, the transitional scroll position must
* not be allowed to disengage the auto-pin.
*
* @internal
*/
get needsInitialScroll() {
return Boolean(this.conversationId && this.conversationId > 0 && this.#bottomPinnedForConversation !== this.conversationId);
}
/**
* Scroll the conversation to the bottom.
*
* @param smooth - Whether to perform a smooth scroll.
* @returns Promise
*
* @internal
*/
async scrollToBottom(smooth: boolean = false) {
// A non-smooth scroll already re-pins each frame while content settles, so a
// single in-flight scroll follows growth without stacking overlapping loops.
if (this.#isScrollingToBottom && !smooth) {
return;
}
this.#isScrollingToBottom = true;
try {
if (this.bottomRef.value) {
await whenElementVisible(this.bottomRef.value);
}
if (hasScroll(this.bottomRef.value) && this.conversationId && this.conversationId > 0) {
requestAnimationFrame(() => {
keepPages(this.weavy?.queryClient, ["messages", this.conversationId], undefined, 1, true);
});
await scrollParentTo("bottom", this.bottomRef.value, smooth);
}
// Once the conversation's messages have loaded we've either scrolled to
// the bottom or there was nothing to scroll. Either way the initial scroll
// is satisfied, so stop forcing it and resume normal pin tracking.
if (this.conversationId && this.conversationId > 0 && this.messagesQuery.result && !this.messagesQuery.result.isPending) {
this.#bottomPinnedForConversation = this.conversationId;
}
} finally {
this.#isScrollingToBottom = false;
}
}
/**
* Handle typing indicator events from child components.
*
* @internal
* @param e - Typing event
*/
protected handleTyping(e: TypingEventType) {
this.isTyping = Boolean(e.detail.count);
if (this.isTyping && this.isAtBottom) {
requestAnimationFrame(() => {
void this.scrollToBottom(true);
});
}
}
/**
* Submit handler for the message editor. Adds a message and optionally creates a conversation first.
*
* @internal
* @param e - Editor submit event
* @returns Promise
*/
protected async handleSubmit(e: MsgEditorSubmitEventType) {
// TODO: refactor outside of conv?
if (!this.user) {
throw new Error("Error submitting message. Missing user.");
}
const initialPayload: Omit = {
text: e.detail.text,
meeting_id: e.detail.meetingId,
poll_options: e.detail.pollOptions,
embed_id: e.detail.embedId,
blobs: e.detail.blobs,
user: this.user,
context: e.detail.contextData,
};
if (this.agentInstructions) {
initialPayload.metadata = {
instructions: this.agentInstructions,
};
}
if (!this.conversation && this.weavy && this.createConversation) {
this.isCreatingConversation = true;
// Create new agent conversation
await this.createConversation(initialPayload);
await this.updateComplete;
}
if (!this.conversation) {
throw new Error("Error submitting message. Missing conversation.");
}
const messageData: MessageType = await this.addMessageMutation.mutate({
...initialPayload,
app_id: this.conversation.id,
});
this.showNewMessages = false;
requestAnimationFrame(() => {
void this.scrollToBottom();
});
this.isCreatingConversation = false;
return messageData;
}
protected async handleEditLast(_e: CustomEvent) {
if (!this.user) {
return;
}
const messages = getFlatInfiniteResultData(this.messagesQuery.result.data);
// REVIEW: special handing of agent chat?
const lastTextMessage = messages.findLast(
(message) => this.user && message.created_by.id === this.user.id && message.text,
);
if (lastTextMessage) {
const lastMessageAge = Date.now() - new Date(lastTextMessage.created_at).getTime();
if (lastMessageAge < 1000 * 60 * 60 * 24) {
//console.log("editing last message", lastTextMessage)
this.editMessage = lastTextMessage;
await this.setEditorText(lastTextMessage.text);
await this.selectAllInEditor();
} else {
console.warn("Last message is too old to edit.", lastMessageAge);
}
}
}
/**
* Set the editor text programmatically.
*
* @param text - Text to set in the editor.
* @returns Promise
*
* @internal
*/
async setEditorText(text: string) {
if (this.editorRef.value) {
this.editorRef.value.text = text;
await this.editorRef.value.updateComplete;
await new Promise((r) => requestAnimationFrame(r));
}
}
/**
* Set metadata on the editor instance.
*
* @param metadata - Optional metadata object.
* @returns Promise
*
* @internal
*/
async setEditorMetadata(metadata: MetadataType = {}) {
await this.updateComplete;
if (this.editorRef.value) {
this.editorRef.value.metadata = metadata;
}
}
/**
* Select all content in the editor.
*
* @internal
*/
async selectAllInEditor() {
if (this.editorRef.value) {
await this.updateComplete;
await this.editorRef.value.updateComplete;
await this.editorRef.value?.selectAllContent();
}
}
/**
* Move the editor cursor to the end of the content.
*
* @internal
*/
async setCursorLastInEditor() {
if (this.editorRef.value) {
await this.updateComplete;
await this.editorRef.value.updateComplete;
await this.editorRef.value?.setCursorLast();
}
}
/**
* Focus the editor input.
*
* @internal
*/
async focusEditor() {
if (this.editorRef.value) {
await this.editorRef.value?.focusInput();
}
}
/**
* Sets the conversation title when the conversation is empty, based on message text.
*
* @internal
* @param name - Title string to set.
* @returns Promise
*/
async setEmptyConversationTitle(name: string) {
if (!this.conversation || this.conversation.name) {
return;
}
name = truncateText(name);
await this.updateConversationMutation?.mutate({ appId: this.conversation.id, name: name });
}
/**
* Realtime handler for 'message_created' events.
*
* Updates local cache and handles read/unread logic.
*
* @internal
*/
private handleRealtimeMessage = async (realtimeEvent: RealtimeMessageEventType) => {
if (!this.weavy || !this.conversation || !(this.conversationId && this.conversationId > 0) || !this.user) {
return;
}
await this.messagesQuery.observer?.getCurrentQuery().promise;
const appUidOrId = realtimeEvent.message.app.uid ?? realtimeEvent.message.app.id;
// set message in messages cache
const queryKey = ["messages", realtimeEvent.message.app.id];
let existing = getCacheItem(this.weavy.queryClient, queryKey, realtimeEvent.message.id);
if (!existing) {
if (realtimeEvent.message.created_by.id === this.user.id) {
// replace (oldest) pending message with the
existing = getPendingCacheItem(this.weavy.queryClient, queryKey, true);
if (existing) {
updateCacheItem(this.weavy.queryClient, queryKey, existing.id, () => realtimeEvent.message);
}
}
if (!existing) {
// add to cache
addCacheItem(this.weavy.queryClient, queryKey, realtimeEvent.message);
}
}
// set last_message in cache
this.weavy.queryClient.setQueryData(["apps", appUidOrId], (app: AppType) =>
app ? { ...app, last_message: realtimeEvent.message } : app,
);
// 3. mark as read/unread (including updating both details and list cache)
if (realtimeEvent.actor.id !== this.user.id) {
if (this.isAtBottom) {
// mark as read
void this.markAsRead(realtimeEvent.message.id);
requestAnimationFrame(() => {
void this.scrollToBottom();
});
} else {
// set is_unread in cache
this.weavy.queryClient.setQueryData(["apps", appUidOrId], (app: AppType) =>
app ? { ...app, is_unread: true } : app,
);
this.lastReadMessagePosition = "above";
this.lastReadMessageId = realtimeEvent.message.id;
this.showNewMessages = true;
}
// update members cache to indicate that creator has seen the message
updateCacheItems(
this.weavy.queryClient,
{ queryKey: ["members", realtimeEvent.message.app.id], exact: false },
realtimeEvent.actor.id,
(item) => ({ ...item, marked_id: realtimeEvent.message.id, marked_at: realtimeEvent.message.created_at }),
);
}
};
/**
* Realtime handler for added reactions. Updates message reactions cache.
*
* @internal
*/
private handleRealtimeReactionAdded = (realtimeEvent: RealtimeReactionEventType) => {
if (!this.weavy || !this.user || !this.conversation) {
return;
}
updateCacheItems(
this.weavy.queryClient,
{ queryKey: ["messages"], exact: false },
realtimeEvent.entity.id,
(item) => {
if (!item.reactions) {
item.reactions = { count: 0 };
}
item.reactions.data = [
...(item.reactions.data || []).filter((r: ReactableType) => r.created_by?.id !== realtimeEvent.actor.id),
{ content: realtimeEvent.reaction, created_by: realtimeEvent.actor },
];
return item;
},
);
};
/**
* Realtime handler for added and removed poll votes. Refreshes the options of the voted message.
*
* @internal
*/
private handleRealtimeVote = (realtimeEvent: RealtimeVoteEventType) => {
if (!this.weavy || !this.conversationId) {
return;
}
void handleRealtimeVote(this.weavy, "messages", ["messages", this.conversationId], realtimeEvent);
};
/**
* Realtime handler for removed reactions. Updates message reactions cache.
*
* @internal
*/
private handleRealtimeReactionDeleted = (realtimeEvent: RealtimeReactionEventType) => {
if (!this.weavy || !this.conversation || !this.user) {
return;
}
updateCacheItems(
this.weavy.queryClient,
{ queryKey: ["messages"], exact: false },
realtimeEvent.entity.id,
(item) => {
if (item.reactions) {
if (item.reactions.data) {
item.reactions.data = item.reactions.data.filter((item) => item.created_by?.id !== realtimeEvent.actor.id);
}
}
return item;
},
);
};
/**
* Realtime handler for app marked events (read receipts).
*
* @internal
*/
private handleRealtimeMarked = (realtimeEvent: RealtimeAppMarkedEventType) => {
if (!this.weavy || !this.conversation) {
return;
}
updateCacheItems(
this.weavy.queryClient,
{ queryKey: ["members", this.conversation.id] },
realtimeEvent.actor.id,
(item) => ({
...item,
marked_id: realtimeEvent.marked_id,
marked_at: realtimeEvent.marked_at,
}),
);
};
/**
* Mark the conversation as read. Respects visibility and component lifecycle.
*
* @param messageId - Optional message id to mark as read.
* @returns Promise
*
* @internal
*/
async markAsRead(messageId?: number) {
await whenDocumentVisible();
await Promise.race([whenElementVisible(this), whenConnected(this, false)]);
if (!this.componentFeatures?.allowsFeature(Feature.Receipts) || !this.isConnected) {
return;
}
// a read receipt is the only thing that would reach the blocked user -- signalling attention to someone you
// muted. Guarded here rather than at the render, so it holds however the conversation gets mounted.
if (this.isBlocked()) {
return;
}
if (this.conversation && this.conversation.last_message) {
await this.markConversationMutation?.mutate({
app: this.conversation,
messageId: messageId ?? this.conversation.last_message.id,
userId: this.user?.id,
});
}
}
/**
* Handler bound to document visibility/scroll events that triggers markAsRead when appropriate.
*
* @internal
*/
protected markAsReadHandler = () => {
if (!document.hidden && this.isAtBottom) {
void this.markAsRead();
}
};
/**
* Unsubscribe function for realtime subscriptions.
*
* @internal
*/
#unsubscribeToRealtime?: () => void;
protected override async willUpdate(changedProperties: PropertyValueMap): Promise {
super.willUpdate(changedProperties);
// if context updated
if (changedProperties.has("weavy") && this.weavy) {
this.updateConversationMutation = getUpdateConversationMutation(this.weavy);
this.markConversationMutation = getMarkConversationMutation(this.weavy);
}
// Tracked only where the host allows blocking. A component with the feature off offers no way to block or unblock
// anyone, so the set would only ever be the empty answer to a question nobody asked -- not worth a request, and
// not worth a cache entry to keep in sync. The member list still carries `is_blocked` where there is one, so a
// block made elsewhere is still honoured in a group conversation.
if ((changedProperties.has("weavy") || changedProperties.has("componentFeatures")) && this.weavy) {
if (this.componentFeatures?.allowsFeature(Feature.Block)) {
await this.blockedUsersQuery.trackQuery(getBlockedUserIdsOptions(this.weavy));
} else {
this.blockedUsersQuery.untrackQuery();
}
}
// conversationId is changed
if (
(changedProperties.has("weavy") ||
changedProperties.has("conversationId") ||
changedProperties.has("componentFeatures")) &&
this.weavy
) {
this.#unsubscribeToRealtime?.();
// Optimize pages cache for the conversation we're leaving
const lastConversationId = changedProperties.get("conversationId");
if (lastConversationId && lastConversationId > 0) {
requestAnimationFrame(() => {
keepPages(this.weavy?.queryClient, ["messages", lastConversationId], undefined, 1, true);
});
}
if (this.conversationId && this.conversationId > 0) {
await this.messagesQuery.trackInfiniteQuery(getMessagesOptions(this.weavy, this.conversationId));
await this.addMessageMutation.trackMutation(
getAddMessageMutationOptions(this.weavy, ["messages", this.conversationId]),
);
await this.membersQuery.trackQuery(getMemberOptions(this.weavy, this.conversationId, {}));
this.pollMutation = getPollMutation(this.weavy, this.conversationId, ["messages", this.conversationId]);
// set initial value of unread messages banner
this.lastReadMessageId = undefined;
this.showNewMessages = false;
const subscribeGroup = `a${this.conversationId}`;
void this.weavy.subscribe(subscribeGroup, "message_created", this.handleRealtimeMessage);
if (this.componentFeatures?.allowsFeature(Feature.Reactions)) {
void this.weavy.subscribe(subscribeGroup, "reaction_added", this.handleRealtimeReactionAdded);
void this.weavy.subscribe(subscribeGroup, "reaction_removed", this.handleRealtimeReactionDeleted);
}
if (this.componentFeatures?.allowsFeature(Feature.Polls)) {
void this.weavy.subscribe(subscribeGroup, "vote_added", this.handleRealtimeVote);
void this.weavy.subscribe(subscribeGroup, "vote_removed", this.handleRealtimeVote);
}
if (this.componentFeatures?.allowsFeature(Feature.Receipts)) {
void this.weavy
.subscribe(subscribeGroup, "app_marked", this.handleRealtimeMarked, true)
.then((showReceipts) => {
this.showReadReceipts = showReceipts;
});
}
this.#unsubscribeToRealtime = () => {
void this.weavy?.unsubscribe(subscribeGroup, "message_created", this.handleRealtimeMessage);
void this.weavy?.unsubscribe(subscribeGroup, "reaction_added", this.handleRealtimeReactionAdded);
void this.weavy?.unsubscribe(subscribeGroup, "reaction_removed", this.handleRealtimeReactionDeleted);
void this.weavy?.unsubscribe(subscribeGroup, "vote_added", this.handleRealtimeVote);
void this.weavy?.unsubscribe(subscribeGroup, "vote_removed", this.handleRealtimeVote);
void this.weavy?.unsubscribe(subscribeGroup, "app_marked", this.handleRealtimeMarked, true);
this.showReadReceipts = false;
this.#unsubscribeToRealtime = undefined;
};
} else {
this.messagesQuery.untrackInfiniteQuery();
this.addMessageMutation.untrackMutation();
this.membersQuery.untrackQuery();
}
}
if (changedProperties.has("conversationId") && changedProperties.get("conversationId") !== this.conversationId) {
// New conversation: forget the previous pin so we force a scroll to the
// bottom, and keep forcing it until the new messages have rendered.
this.#bottomPinnedForConversation = undefined;
}
// While we still need the initial scroll for a freshly opened conversation,
// always force the bottom. The scroll position is transitional while messages
// load (the scroll element is reused and still holds the previous
// conversation's scrollTop), so we must not read isAtBottom here. Otherwise
// keep pinned to the bottom only when the user is already there.
this.shouldBeAtBottom = this.needsInitialScroll ? Boolean(this.conversationId) : this.isAtBottom;
// handle "new messages" and mark as read
if (changedProperties.has("conversation")) {
const oldConversation = changedProperties.get("conversation");
if (
oldConversation?.id !== this.conversation?.id ||
oldConversation?.is_unread !== this.conversation?.is_unread
) {
if (this.componentFeatures?.allowsFeature(Feature.Receipts) && this.conversation?.is_unread) {
// show new messages (before we mark as read)?
const markedId = this.membersQuery.result.data?.data?.find(
(member) => member.id === this.user?.id,
)?.marked_id;
if (markedId && markedId < this.conversation.last_message.id) {
this.lastReadMessagePosition = "below";
this.lastReadMessageId = markedId;
this.showNewMessages = true;
}
// mark as read?
if (
oldConversation?.id !== this.conversation?.id ||
(oldConversation?.last_message.id !== this.conversation?.last_message.id &&
(this.shouldBeAtBottom || this.isAtBottom))
) {
void this.markAsRead();
}
} else if (oldConversation?.id !== this.conversation?.id) {
// hide new messages
this.showNewMessages = false;
}
}
}
// Update title
if (this.conversation && !this.conversation?.name && !isInfiniteResultDataEmpty(this.messagesQuery.result.data)) {
const messages = getFlatInfiniteResultData(this.messagesQuery.result.data);
// REVIEW: special handing of agent chat?
const lastPlainMessage = messages.find((message) => message.plain);
if (lastPlainMessage) {
void this.setEmptyConversationTitle(getTitleFromText(lastPlainMessage.plain));
}
}
}
renderConversationHeader() {
if (!this.header) {
return html` `;
}
const { isPending: messagesIsPending, hasPreviousPage } = this.messagesQuery.result ?? {};
if (!this.conversation || messagesIsPending || hasPreviousPage) {
return nothing;
}
const { data: membersData } = this.membersQuery.result ?? {};
const otherMember =
this.user && this.isPrivateChat()
? ((this.conversation?.members?.data || []).filter((member) => member.id !== this.user?.id)?.[0] ?? this.user)
: null;
// In a one-to-one the header avatar is a person, so it opens their profile card -- the same thing the small avatar
// beside a message does. A group avatar is not one person, so it stays inert; otherMember is null there anyway.
const profile = otherMember;
return html`
${this.conversation.avatar_url
? html` profile && this.dispatchAction({ action: ActionType.Preview, user: profile })}
@keydown=${clickOnEnterAndConsumeOnSpace}
@keyup=${clickOnSpace}
>`
: this.isChatRoom()
? html` `
: otherMember?.avatar_url
? html`
profile && this.dispatchAction({ action: ActionType.Preview, user: profile })}
@keydown=${clickOnEnterAndConsumeOnSpace}
@keyup=${clickOnSpace}
>
`
: nothing}
`;
}
/**
* Renders the notice shown in place of the messages in a blocked private chat.
*
* Carries the unblock action itself: `wy-chat` has no conversation list, so the header avatar would otherwise be the
* only way out. The wording promises the history back, since hiding every message otherwise reads as data loss.
*
* @internal
*/
private renderBlocked() {
const otherMember =
(this.conversation?.members?.data || []).filter((member) => member.id !== this.user?.id)?.[0] ?? undefined;
return html`
${otherMember?.name ? msg(str`You have blocked ${otherMember.name}`) : msg("You have blocked this user")}
${msg("Messages are hidden until unblocked. Nothing has been deleted.")}
${flattenedPages && this.conversation && this.user
? repeat(
flattenedPages,
(message) => message.id,
(message, _index) => {
const messageDate = new Date(message.created_at);
let dateContent = html``;
if (lastDate?.toDateString() !== messageDate.toDateString()) {
const messageDateShort = new Intl.DateTimeFormat(this.weavy?.locale, {
dateStyle: "short",
}).format(messageDate);
lastDate = messageDate;
dateContent = html``;
}
let unreadMarkerContent = html``;
if (this.lastReadMessageId && this.lastReadMessageId === message.id) {
unreadMarkerContent = html`
{
let selector = `#message-${this.lastReadMessageId}`;
if (this.lastReadMessagePosition === "below") {
selector += "~ wy-message";
}
const message = this.renderRoot.querySelector(selector);
// `wy-message` hosts use `display: contents` and have no box of
// their own, so resolve the first real child box to scroll to.
const scrollTarget =
message instanceof HTMLElement ? getNextPositionedChild(message, true) ?? message : message;
scrollTarget?.scrollIntoView({
block: "start",
inline: "nearest",
behavior: "smooth",
});
}}
@keydown=${clickOnEnterAndConsumeOnSpace}
@keyup=${clickOnSpace}
>
${msg("New messages")}
`;
}
// Get additional member data
// The member record is the better identity -- it carries presence and the app-specific access.
const member = members?.data?.find((m) => m.id === message.created_by.id);
const createdBy = member || message.created_by;
// Blocked if *either* source says so, rather than picking one. The member record carries the flag
// but exists only where the app has a member list, and only once it has loaded; the block list
// answers for every message however it arrived, but is tracked only where Feature.Block is on.
// `message.created_by` never answers at all -- authors are mapped minimally. A union errs toward
// holding a message back rather than showing one that should have been hidden.
const authorIsBlocked = Boolean(blockedUserIds?.includes(createdBy.id) || member?.is_blocked);
return html`${[
html`${dateContent}`,
html`${this.lastReadMessagePosition === "above" ? unreadMarkerContent : nothing}`,
keyed(
`message-${message.id}`,
html` 0
? members.data.filter((member) => {
return member.marked_id === message.id && member.id !== this.user?.id;
})
: []}
@vote=${(e: PollVoteEventType) => {
if (e.detail.parentId) {
if (e.detail.parentType && e.detail.parentId) {
void this.pollMutation?.mutate({
optionId: e.detail.optionId,
parentType: e.detail.parentType,
parentId: e.detail.parentId,
});
}
//this.dispatchVote(e.detail.optionId, e.detail.parentId);
}
}}
>`,
),
html`${this.lastReadMessagePosition === "below" ? unreadMarkerContent : nothing}`,
]}`;
},
)
: nothing}
${this.componentFeatures?.allowsFeature(Feature.Typing)
? html`
this.handleTyping(e)}
>
`
: nothing}
`;
}
override render() {
// keeps the header (the avatar is the route to the profile) and swaps the messages for the notice, which drops
// the typing indicator living inside them.
const blocked = this.isBlocked();
return html`
${this.renderConversationHeader()} ${blocked ? this.renderBlocked() : this.renderMessages()}