import { type PropertyValueMap, html, nothing } from "lit"; import { customElement } from "../utils/decorators/custom-element"; import { property, state } from "lit/decorators.js"; import { unsafeHTML } from "lit/directives/unsafe-html.js"; import { Ref, createRef, ref } from "lit/directives/ref.js"; import type { WyPreview } from "./wy-preview"; import type { FileType } from "../types/files.types"; import { localized, msg, str } from "@lit/localize"; import { relativeDays } from "../utils/datetime"; import { WeavySubAppComponent } from "../classes/weavy-sub-app-component"; import { ShadowPartsController } from "../controllers/shadow-parts-controller"; import { EntityTypeString, PermissionType } from "../types/app.types"; import { hasEntityChildType, isEntityChainMatch } from "../utils/notifications"; import { partMap } from "../utils/directives/shadow-part-map"; import { Feature } from "../types/features.types"; import { PostEditEventType, PostSubscribeEventType, PostTrashEventType } from "../types/posts.events"; import { NamedEvent } from "../types/generic.types"; import { PollVoteEventType } from "../types/polls.events"; import type { PostType } from "../types/posts.types"; import { hasPermission } from "../utils/permission"; import { MutationController } from "../controllers/mutation-controller"; import { getReportMutationOptions, MutateReportProps } from "../data/reports"; import { WyActionEventType } from "../types/action.events"; import { ActionType } from "../types/action.types"; import rebootCss from "../scss/reboot.scss"; import postCss from "../scss/components/post.scss"; import highlightCss from "../scss/base/_highlight.scss"; import contentCss from "../scss/components/content.scss"; import hostContentsCss from "../scss/host-contents.scss"; import placeholderCss from "../scss/components/placeholder.scss"; import messagesCss from "../scss/components/messages.scss"; import textCss from "../scss/components/text.scss"; import "./ui/wy-avatar"; import "./ui/wy-image-grid"; import "./ui/wy-item"; import "./ui/wy-skeleton"; import "./wy-attachment"; import "./wy-reactions"; import "./wy-meeting-card"; import "./wy-poll"; import "./wy-embed"; import "./wy-comment-list"; import "./wy-preview"; declare global { interface HTMLElementTagNameMap { "wy-post-view": WyPostView; } } /** * Post view that renders the post content, attachments, polls, embeds and footer/meta. * * **Used sub components:** * * - [``](./ui/wy-avatar.ts) * - [``](./ui/wy-image-grid.ts) * - [``](./ui/wy-item.ts) * - [``](./ui/wy-skeleton.ts) * - [``](./wy-annotation.ts) * - [``](./wy-attachment.ts) * - [``](./wy-embed.ts) * - [``](./wy-poll.ts) * - [``](./wy-meeting-card.ts) * - [``](./wy-comment-list.ts) * - [``](./wy-preview.ts) * * @csspart wy-post - Root post container. * @csspart wy-highlight - Highlight modifier for linked posts. * @csspart wy-post-header - Main post header wrapper. * @csspart wy-post-body - Main post body wrapper. * @csspart wy-post-footer - Footer meta/actions area. * @csspart wy-content - HTML/content area. * @csspart wy-post-comments - Comments container. * @csspart wy-post-attachment-list - Attachments area list. * @csspart wy-post-reported - The filled flag in the header shown once the reader has reported the post. Hide it with `::part(wy-post-reported)` if reporting should be fire-and-forget. * * @fires {PollVoteEventType} vote - Emitted when a poll option is voted. * @fires {PostSubscribeEventType} subscribe - Emitted when subscribe/unsubscribe is requested. * @fires {PostTrashEventType} trash - Emitted when the post should be trashed. * @fires {PostEditEventType} edit - Emitted when edit mode is requested. * @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-post-view") @localized() export class WyPostView extends WeavySubAppComponent { static override styles = [ rebootCss, postCss, highlightCss, contentCss, placeholderCss, messagesCss, textCss, hostContentsCss, ]; protected exportParts = new ShadowPartsController(this); /** * Post data. */ @property({ attribute: false }) post!: PostType; /** * Highlight the post when it matches the active deep link. */ @property({ type: Boolean }) highlight: boolean = false; /** * Placeholder text for the comment editor input. */ @property() placeholder?: string; /** * Toggle indicating whether comments are currently visible. * * @internal */ @state() private showComments: boolean = false; /** * Guard used to lazy-load comments when expanded. * * @internal */ @state() private loadComments: boolean = false; /** * True when a linked comment targets this post. * * @internal */ @state() isCommentLinked: boolean = false; /** * Preview instance handling annotation files. * * @internal */ private previewAnnotationsRef: Ref = createRef(); /** * Preview instance handling attachment files. * * @internal */ private previewAttachmentsRef: Ref = createRef(); /** * DOM reference used to scroll highlighted posts into view. * * @internal */ private highlightRef: Ref = createRef(); /** * Emit a `vote` event for the specified poll option. * * @internal * @param optionId - Identifier of the selected poll option. * @returns {boolean} True if the event was not canceled. */ private dispatchVote(optionId: number) { const event: PollVoteEventType = new (CustomEvent as NamedEvent)("vote", { detail: { optionId, parentType: "posts" }, }); return this.dispatchEvent(event); } /** * Emit a `subscribe` event toggling post subscription state. * * @internal * @param subscribe - Desired subscription state. * @returns {boolean} True if the event was not canceled. */ private dispatchSubscribe(subscribe: boolean) { const event: PostSubscribeEventType = new (CustomEvent as NamedEvent)("subscribe", { detail: { id: this.post.id, subscribe }, }); return this.dispatchEvent(event); } /** * Emit a `trash` event requesting the post to move into trash. * * @internal * @returns {boolean} True if the event was not canceled. */ private dispatchTrash() { const event: PostTrashEventType = new (CustomEvent as NamedEvent)("trash", { detail: { id: this.post.id } }); return this.dispatchEvent(event); } /** * Emit an `edit` event toggling edit mode for this post. * * @internal * @param edit - Desired edit state. * @returns {boolean} True if the event was not canceled. */ private dispatchEdit(edit: boolean) { const event: PostEditEventType = new (CustomEvent as NamedEvent)("edit", { detail: { edit: edit } }); return this.dispatchEvent(event); } /** * @internal */ #reportMutation = new MutationController(this); /** * Confirm and report the post for moderation. * * Uses the native confirm rather than an in-app dialog, matching how reporting a message works: reporting cannot be * undone and there is no report to look up afterwards, so the interruption is the point. * * @internal */ private confirmReport() { const confirmed = window.confirm( msg("Report this post for review? The author is not notified, and reporting cannot be undone."), ); if (confirmed) { // the post carries its own app ref so the cache patch works in the feed too, where this.app is not the post's app void this.#reportMutation.mutate({ entityType: "posts", entityId: this.post.id, appId: this.post.app?.id ?? this.app?.id, }); } } /** * Toggle comment visibility and ensure comment data is loaded. * * @internal * @param e - Click event originating from the comment button. */ private handleCommentsClick(e: Event) { e.preventDefault(); this.showComments = !this.showComments; this.loadComments = true; } protected override willUpdate(changedProperties: PropertyValueMap): void { super.willUpdate(changedProperties); if (changedProperties.has("link")) { this.highlight = Boolean(this.link && isEntityChainMatch(this.link, EntityTypeString.Post, { id: this.post.id })); this.isCommentLinked = Boolean( this.link && hasEntityChildType(this.link, EntityTypeString.Post, { id: this.post.id }, EntityTypeString.Comment), ); } if (changedProperties.has("isCommentLinked") && this.isCommentLinked) { this.loadComments = true; this.showComments = true; } if (changedProperties.has("weavy") && this.weavy) { void this.#reportMutation.trackMutation(getReportMutationOptions(this.weavy)); } } override render() { const images = this.post.attachments?.data?.filter((a: FileType) => a.kind === "image" && a.thumbnail_url) ?? []; const files = this.post.attachments?.data?.filter((a: FileType) => a.kind !== "image" || !a.thumbnail_url) ?? []; const annotations = this.post.annotations?.data; const pollOptions = this.post.options?.data; const commentCount = this.post.comments?.count || 0; const reactions = this.post.reactions?.data; const { embed, meeting } = this.post; const dateFull = new Intl.DateTimeFormat(this.weavy?.locale, { dateStyle: "full", timeStyle: "short", }).format(new Date(this.post.created_at)); const dateFromNow = relativeDays(this.weavy?.locale, new Date(this.post.created_at)); const modifiedDateFull = this.post.updated_at && this.weavy ? new Intl.DateTimeFormat(this.weavy.locale, { dateStyle: "full", timeStyle: "short" }).format( new Date(this.post.updated_at), ) : ""; // same wording and format as the flag on a reported message, so the two read the same across components. // "by you" because the flag is caller-relative: weavy keeps no report counts, so it can only ever say that this // reader reported the post. Falls back to the label without a date when the report was patched into the cache by // the mutation and the next fetch has not brought the real timestamp yet. const reportedAtFull = this.post.reported_at ? new Intl.DateTimeFormat(this.weavy?.locale, { dateStyle: "full", timeStyle: "short" }).format( new Date(this.post.reported_at), ) : ""; const reportedTitle = this.post.reported_at ? msg(str`Reported by you on ${reportedAtFull}`) : msg("Reported by you"); // Reporting your own post is rejected by the server, and there is nothing to moderate about it anyway. // Skeleton posts (negative id) are not on the server yet, so there is nothing to report either. const isAuthor = Boolean(this.user && this.user.id === this.post.created_by.id); const canReport = Boolean( this.componentFeatures?.allowsFeature(Feature.Report) && !isAuthor && this.post.id > 0 && !this.post.is_reported, ); const hasImages = images && Boolean(images.length); const hasText = this.post.html && Boolean(this.post.html); const hasAnnotations = annotations && Boolean(annotations.length); const hasPoll = pollOptions && Boolean(pollOptions.length); const hasEmbed = embed && this.componentFeatures?.allowsFeature(Feature.Embeds); const hasFiles = files && Boolean(files.length); const hasMeeting = meeting && Boolean(meeting); const hasBody = hasText || hasAnnotations || hasPoll || hasEmbed || hasFiles || hasMeeting; return this.post.id < 0 ? html`
${this.post.created_by.name}
` : html`
this.dispatchAction({ action: ActionType.Preview, user: this.post.created_by })} > this.dispatchAction({ action: ActionType.Preview, user: this.post.created_by })} >${this.post.created_by.name} ${ this.post.updated_at ? html`` : nothing } ${ // the filled flag is the only record of the report the reporter ever sees, which is why it stays // visible rather than disappearing once set. Not interactive: a report cannot be undone or re-filed. this.post.is_reported ? html` · ` : nothing } ${ this.post.is_subscribed ? html` this.dispatchSubscribe(false)}> ${msg("Unsubscribe")} ` : html` this.dispatchSubscribe(true)}> ${msg("Subscribe")} ` } ${ // a menu item rather than the hover flag messages use: the post already has a menu, and the flag was // chosen for messages only because their menu would otherwise have held a single item. Once reported // the item goes away -- a report cannot be undone or re-filed -- and the flag in the meta row is the // record of it, the same way the filled flag is on a message. canReport ? html` this.confirmReport()}> ${msg("Report")} ` : nothing } ${ this.user && this.user.id === this.post.created_by.id ? html` this.dispatchEdit(true)}> ${msg("Edit")} ` : nothing } ${ (this.user && this.user.id === this.post.created_by.id) || hasPermission(PermissionType.Admin, this.app?.permissions) ? html` this.dispatchTrash()}> ${msg("Trash")} ` : nothing } ${ hasImages ? html` { if (e.detail.action === ActionType.Preview && e.detail.file) { void this.previewAttachmentsRef.value?.open(e.detail.file.id); } }} >` : `` } ${ hasBody ? html`
${hasText ? html`
{ if ( e.target instanceof HTMLElement && e.target.matches('.wy-mention, [part~="wy-mention"]') ) { const uid = e.target.dataset.eid?.startsWith("u") && parseInt(e.target.dataset.eid.substring(1)); if (uid) { this.dispatchAction({ action: ActionType.Preview, user: { id: uid, name: e.target.innerText }}); } } }} >${ // eslint-disable-next-line lit-a11y/click-events-have-key-events unsafeHTML(this.post.html) }
` : ``} ${hasAnnotations ? html` { if (e.detail.action === ActionType.Preview && e.detail.file) { void this.previewAnnotationsRef.value?.open(e.detail.file.id); } }} >` : nothing} ${hasPoll ? html` this.dispatchVote(e.detail.optionId)} > ` : nothing} ${hasEmbed ? html` ` : nothing} ${hasFiles ? html` { if (e.detail.action === ActionType.Preview && e.detail.file) { void this.previewAttachmentsRef.value?.open(e.detail.file.id); } }} >` : nothing} ${hasMeeting ? html`` : nothing}
` : nothing }
${ this.componentFeatures?.allowsFeature(Feature.Comments) ? html` this.handleCommentsClick(e)} > ${commentCount !== 1 ? msg(str`${commentCount} comments`) : msg("1 comment")} ` : nothing } ${ this.componentFeatures?.allowsFeature(Feature.Reactions) && this.app ? html` ` : nothing }
${ this.loadComments ? html` ` : nothing }
${ hasAnnotations ? html` ` : nothing } ${ hasImages || hasFiles ? html` ` : nothing } `; } protected override updated(changedProperties: PropertyValueMap) { if (changedProperties.has("highlight") && this.highlight) { this.highlightRef.value?.scrollIntoView({ block: "nearest" }); } } }