import { html, nothing, type PropertyValueMap } from "lit"; import { customElement } from "../utils/decorators/custom-element"; import { property, state } from "lit/decorators.js"; import { Ref, createRef, ref } from "lit/directives/ref.js"; import { InfiniteScrollController } from "../controllers/infinite-scroll-controller"; import { InfiniteQueryController } from "../controllers/infinite-query-controller"; import { CommentType, CommentsResultType, MutateCommentProps } from "../types/comments.types"; import { getAddCommentMutationOptions, getCommentsOptions } from "../data/comments"; import { EntityTypeString, PermissionType } from "../types/app.types"; import { hasAnyPermission } from "../utils/permission"; import { repeat } from "lit/directives/repeat.js"; import { localized, msg } from "@lit/localize"; import { updateReaction } from "../data/reactions"; import { ShadowPartsController } from "../controllers/shadow-parts-controller"; import { MutationController } from "../controllers/mutation-controller"; import { RemoveCommentMutationType, getRestoreCommentMutation, getTrashCommentMutation } from "../data/comment-remove"; import { PollMutationType, getPollMutation, handleRealtimeVote } from "../data/poll"; import { getFlatInfiniteResultData, updateCacheItems } from "../utils/query-cache"; import { WeavySubAppComponent } from "../classes/weavy-sub-app-component"; import type { RealtimeGroupType, RealtimeReactionEventType, RealtimeVoteEventType } from "../types/realtime.types"; import type { MsgType } from "../types/msg.types"; import { Feature } from "../types/features.types"; import type { MsgEditorSubmitEventType } from "../types/editor.events"; import type { CommentRestoreEventType, CommentTrashEventType } from "../types/comments.events"; import type { PollVoteEventType } from "../types/polls.events"; import { getEntityChildType } from "../utils/notifications"; import commentsCss from "../scss/components/comments.scss"; import pagerStyles from "../scss/components/pager.scss"; import "./ui/wy-button"; import "./ui/wy-progress-circular"; import "./wy-comment"; import "./wy-editor-comment"; import "./wy-empty"; declare global { interface HTMLElementTagNameMap { "wy-comment-list": WyCommentList; } } /** * Comment list component rendering a list of comments and an editor to create comments. * * **Used sub components:** * * - [``](./ui/wy-button.ts) * - [``](./ui/wy-progress-circular.ts) * - [``](./wy-comment.ts) * - [``](./wy-editor-comment.ts) * - [``](./wy-empty.ts) * * @csspart wy-comments - Container for the comments list * @csspart wy-pager - Pager container element * @csspart wy-pager-bottom - Bottom pager modifier * * @slot empty - Content when no comments are available. * * @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-comment-list") @localized() export class WyCommentList extends WeavySubAppComponent { static override styles = [commentsCss, pagerStyles]; /** * Controller for exporting named shadow parts. * * @internal */ protected exportParts = new ShadowPartsController(this); /** * Id of the parent entity (post/file/app) to which comments belong. * * Set this to load comments for a specific parent. */ @property({ type: Number }) parentId?: number; /** * Location where the comments are stored. */ @property({ attribute: false }) location: "posts" | "files" | "apps" = "apps"; /** * Placeholder text for the comment editor input. */ @property() placeholder?: string; /** * Whether comments should be revealed (expanded) by default. */ @property({ type: Boolean, reflect: true }) reveal: boolean = false; /** * Adds padding to the comment list container. */ @property({ type: Boolean, reflect: true }) padded: boolean = false; /** * Paging behavior for loading previous comments. * * - "infinite" is recommended when the component is placed in an overflowing/scrollable area. **/ @property() previousPaging: "infinite" | "paged" = "paged"; /** * Paging behavior for loading next comments. * * - "infinite" is recommended when the component is placed in an overflowing/scrollable area. **/ @property() nextPaging: "infinite" | "paged" = "paged"; /** * Comment id that should be highlighted and scrolled into view. * * @internal */ @state() highlightId?: number = NaN; /** * Internal promise resolver used to wait for parentId to become available. * * @internal */ #resolveParentId?: (parentId: number) => void; #whenParentId = new Promise((r) => { this.#resolveParentId = r; }); /** * Resolves when `parentId` is available. * * @returns Promise */ async whenParentId() { return await this.#whenParentId; } /** * Infinite query controller for loading paged comments. * * @internal */ commentsQuery = new InfiniteQueryController(this); /** * Mutation controller used to add comments. * * @internal */ private addCommentMutation = new MutationController(this); /** * Mutation controller used to trash a comment. * * @internal */ private removeCommentMutation?: RemoveCommentMutationType; /** * Mutation controller used to restore a comment. * * @internal */ private restoreCommentMutation?: RemoveCommentMutationType; /** * Mutation controller used for poll voting. * * @internal */ private pollMutation?: PollMutationType; /** * Infinite scroll controller instance used to observe the pager node. * * @internal */ private infiniteScroll = new InfiniteScrollController(this); /** * Reverse infinite scroll controller instance used to observe the pager node. * * @internal */ private reverseInfiniteScroll = new InfiniteScrollController(this, true); /** * Ref for pager element used by the reverse infinite scroll controller. * * @internal */ private previousPagerRef: Ref = createRef(); /** * Ref for pager element used by the infinite scroll controller. * * @internal */ private nextPagerRef: Ref = createRef(); /** * Unsubscribe function for realtime subscriptions. * * @internal */ #unsubscribeToRealtime?: () => void; /** * Handler invoked when a realtime comment is created. * * @internal */ handleRealtimeCommentCreated = () => { void this.weavy?.queryClient.invalidateQueries({ queryKey: [this.location, "comments", this.parentId] }); }; /** * Handler invoked when a realtime reaction is added. * * Updates the local cache for the affected comment. * * @internal */ handleRealtimeReactionAdded = (realtimeEvent: RealtimeReactionEventType) => { if (!this.weavy || realtimeEvent.entity.type !== EntityTypeString.Comment) { return; } updateCacheItems( this.weavy.queryClient, { queryKey: [this.location, "comments", this.parentId] }, realtimeEvent.entity.id, (item) => updateReaction(item, realtimeEvent.reaction, realtimeEvent.actor), ); }; /** * Handler invoked when a realtime reaction is removed. * * Updates the local cache for the affected comment. * * @internal */ handleRealtimeReactionDeleted = (realtimeEvent: RealtimeReactionEventType) => { if (!this.weavy || realtimeEvent.entity.type !== EntityTypeString.Comment) { return; } updateCacheItems( this.weavy.queryClient, { queryKey: [this.location, "comments", this.parentId] }, realtimeEvent.entity.id, (item) => updateReaction(item, undefined, realtimeEvent.actor), ); }; /** * Handler invoked when a poll vote is added or removed. Refreshes the options of the voted comment. * * @internal */ handleRealtimeVote = (realtimeEvent: RealtimeVoteEventType) => { if (!this.weavy || !this.parentId) { return; } void handleRealtimeVote(this.weavy, "comments", [this.location, "comments", this.parentId], realtimeEvent); }; /** * Handle submit from the comment editor and trigger add comment mutation. * * @internal */ private async handleSubmit(e: MsgEditorSubmitEventType) { if (this.app && this.parentId && this.user) { await this.addCommentMutation.mutate({ app_id: this.app.id, parent_id: this.parentId, type: this.location, text: e.detail.text, meeting_id: e.detail.meetingId, blobs: e.detail.blobs, poll_options: e.detail.pollOptions, embed_id: e.detail.embedId, context: e.detail.contextData, user: this.user, }); } } override async willUpdate(changedProperties: PropertyValueMap): Promise { super.willUpdate(changedProperties); if (changedProperties.has("parentId") && this.parentId) { this.#resolveParentId?.(this.parentId); } if (changedProperties.has("link")) { const parentType = this.location === "files" ? EntityTypeString.File : this.location === "posts" ? EntityTypeString.Post : EntityTypeString.App; this.highlightId = this.link && this.parentId && getEntityChildType(this.link, parentType, { id: this.parentId }, EntityTypeString.Comment)?.id; } if ( (changedProperties.has("parentId") || changedProperties.has("weavy") || changedProperties.has("componentFeatures") || changedProperties.has("highlightId")) && this.parentId && this.weavy ) { await this.commentsQuery.trackInfiniteQuery( getCommentsOptions(this.weavy, this.location, this.parentId, this.highlightId), ); } if ( (changedProperties.has("parentId") || changedProperties.has("weavy") || changedProperties.has("componentFeatures")) && this.parentId && this.weavy ) { await this.addCommentMutation.trackMutation(getAddCommentMutationOptions(this.weavy)); this.removeCommentMutation = getTrashCommentMutation(this.weavy, this.location, this.parentId); this.restoreCommentMutation = getRestoreCommentMutation(this.weavy, this.location, this.parentId); } if ( (changedProperties.has("weavy") || changedProperties.has("app") || changedProperties.has("componentFeatures") || changedProperties.has("parentId")) && this.weavy && this.app && this.parentId ) { this.pollMutation = getPollMutation(this.weavy, this.app.id, [this.location, "comments", this.parentId]); // realtime this.#unsubscribeToRealtime?.(); const subscribeGroup: RealtimeGroupType = `a${this.app.id}`; void this.weavy.subscribe(subscribeGroup, "comment_created", this.handleRealtimeCommentCreated); 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); } this.#unsubscribeToRealtime = () => { void this.weavy?.unsubscribe(subscribeGroup, "comment_created", this.handleRealtimeCommentCreated); 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); this.#unsubscribeToRealtime = undefined; }; } } /** * Render comment items from a flattened page array. * * @internal */ private renderComments(flattenedPages?: MsgType[]) { if (flattenedPages) { return repeat( flattenedPages, (comment) => comment.id, (comment) => { return this.parentId ? html` { const app = await this.whenApp(); const parentId = await this.whenParentId(); void this.removeCommentMutation?.mutate({ id: e.detail.id, appId: app.id, parentId: parentId, type: this.location, }); }} @restore=${async (e: CommentRestoreEventType) => { const app = await this.whenApp(); const parentId = await this.whenParentId(); void this.restoreCommentMutation?.mutate({ id: e.detail.id, appId: app.id, parentId: parentId, type: this.location, }); }} @vote=${(e: PollVoteEventType) => { if (e.detail.parentId && e.detail.parentType) { void this.pollMutation?.mutate({ optionId: e.detail.optionId, parentType: e.detail.parentType, parentId: e.detail.parentId, }); } }} >` : nothing; }, ); } return nothing; } override render() { const { data: infiniteData, hasPreviousPage, hasNextPage, isPending, isFetchingNextPage, isFetchingPreviousPage, } = this.commentsQuery.result ?? {}; const flattenedPages = getFlatInfiniteResultData(infiniteData); return html` ${flattenedPages && flattenedPages.length && this.componentFeatures?.allowsFeature(Feature.Comments) ? html`
${hasPreviousPage ? this.previousPaging === "infinite" ? html`
` : !isFetchingPreviousPage ? html`
{ void this.commentsQuery.loadPrevious(); }} ?disabled=${isFetchingPreviousPage} >${isFetchingPreviousPage ? html`` : nothing} ${msg("Show more comments")}
` : nothing : nothing} ${this.renderComments(flattenedPages)} ${hasNextPage ? this.nextPaging === "infinite" ? html`
` : html`
{ void this.commentsQuery.loadNext(); }} ?disabled=${isFetchingNextPage} >${isFetchingNextPage ? html`` : nothing} ${msg("Show more comments")}
` : nothing}
` : isPending ? html`` : html``} ${this.componentFeatures?.allowsFeature(Feature.Comments, Feature.Comment) ? html` this.handleSubmit(e)} > ` : !flattenedPages.length ? html`${msg("Commenting is not enabled for this.")}` : nothing} `; } protected override updated(): void { this.reverseInfiniteScroll.observe(this.commentsQuery.result, this.previousPagerRef.value); this.infiniteScroll.observe(this.commentsQuery.result, this.nextPagerRef.value); } override disconnectedCallback(): void { this.#unsubscribeToRealtime?.(); super.disconnectedCallback(); } }