import m from '@garage44/mithril' import {Button, FieldSegmented, FieldText} from '@garage44/mithril/components' import {signupApi} from '@/app' import {ApiError} from '@/lib/api' import type {CommunityView} from '@/lib/chat' import {Icon} from '@/lib/icons' import {parsePlace, placeParam, suggestHandle, webLink} from '@/lib/posts' import type { FollowLink, NoticeKind, PostDto, PostNotices, PostPlace, PostReport, PostThread, PublicInfo, WhoPosts, } from '@/types' /** * A community's public posts (`docs/notes/fediverse.md`, * `docs/mockups/communities/v4-public-posts.html`). * * The other half of a community page from its topics: public where they are * encrypted, and on the fediverse where they never are. Plain HTTP against the * simulator (`/api/communities/{id}/posts`), not the chat worker, because there * is nothing to seal: the server stores posts readable on purpose, to send * them to other servers. * * Laid out as a feed, as Mastodon's is: a box to write in at the top, then * each post as a card with its author, its words, its picture and its place, * and its replies opening underneath it rather than on a page of their own. * What is done rarely (hide, block, delete) sits behind a ⋯ menu. * * A post always has a place. The app takes it from the camera; here it is the * community's own place, where this browser is, or a Cartopolis place link * pasted in (Copy link in the app, or any `/go?place=` link). A post's place * opens in World, flown to the view it was written from. */ export type Tab = 'posts' | 'topics' interface Draft { community: string text: string /** What was typed into the place field: a link or "lat, lng". */ where: string place: PostPlace | null picture: string | null /** What the picture shows, in words, for somebody who cannot see it. */ alt: string /** Blur the picture until a reader asks to see it. */ sensitive: boolean /** A content warning, shown in place of the post until it is opened; null when off. */ warning: string | null /** Whether the place field is showing. */ placing: boolean } /** * Where a card is drawn: which community, and whether the reader moderates it * and is signed in. A community page passes its own; the public pages * (`pages/public`) a reader who may be nobody. */ export interface Where { id: string mod: boolean signedIn: boolean } /** What the page lends this view: pictures, faces, and the World frame. */ export interface PostsCtx { pictureUrl: (hash: string | null | undefined) => string | null avatar: (address: string, size: number) => m.Children /** Open World at a place, given as a link's `place=` value. */ onMap: (place: string) => void } /** Everything the posts half holds, across communities. */ const st = { busy: false, draft: null as Draft | null, /** The post being edited, and its words so far. */ editing: null as {id: string; text: string} | null, error: '', feed: new Map(), follow: '', handle: '', info: new Map(), loaded: null as string | null, reply: '', /** The reply being answered, when it is one rather than the post. */ replyTo: null as PostDto | null, /** The post being reported, and what the reporter says. */ reporting: null as {id: string; reason: string; forward: boolean} | null, /** Posts behind a content warning, or with a sensitive picture, that the reader opened. */ shown: new Set(), /** Reports from other servers, per community, for its moderators. */ reports: new Map(), settingsOpen: false, tab: new Map(), thread: null as PostThread | null, threadOpen: null as string | null, } function failed(e: unknown): void { st.busy = false st.error = e instanceof ApiError ? e.message : `Not done: ${(e as Error).message}` m.redraw() } /** What has been read of a community's public half, for the public pages. */ export function readOf(id: string): {info: PublicInfo | undefined; feed: PostDto[]} { return {feed: st.feed.get(id) ?? [], info: st.info.get(id)} } /** Read a community's public half and its newest posts. */ export async function load(id: string): Promise { try { const [info, feed] = await Promise.all([ signupApi.get(`/api/communities/${id}/public`), signupApi.get(`/api/communities/${id}/posts`), ]) st.info.set(id, info) st.feed.set(id, feed) if (!st.handle && info.settings.handle) st.handle = info.settings.handle if (info.open_reports > 0) st.reports.set(id, await signupApi.get(`/api/communities/${id}/reports`)) else st.reports.delete(id) } catch (e) { failed(e) } m.redraw() } /** Open (or close) a post's replies under it. */ export async function toggleThread(post: string): Promise { if (st.threadOpen === post) { st.threadOpen = null st.thread = null return } st.threadOpen = post st.thread = null st.reply = '' st.replyTo = null try { st.thread = await signupApi.get(`/api/posts/${post}`) } catch (e) { failed(e) } m.redraw() } export function ago(ms: number): string { const s = Math.max(0, (Date.now() - ms) / 1000) if (s < 60) return 'now' if (s < 3600) return `${Math.floor(s / 60)} min` if (s < 86400) return `${Math.floor(s / 3600)} h` if (s < 604800) return `${Math.floor(s / 86400)} d` return new Date(ms).toLocaleDateString() } /** A picked picture, at most 1600 px on its longest edge, as a JPEG in the picture store. */ async function uploadPicture(file: File, d: Draft): Promise { st.busy = true m.redraw() try { const bitmap = await createImageBitmap(file) const scale = Math.min(1, 1600 / Math.max(bitmap.width, bitmap.height)) const canvas = document.createElement('canvas') canvas.width = Math.round(bitmap.width * scale) canvas.height = Math.round(bitmap.height * scale) canvas.getContext('2d')!.drawImage(bitmap, 0, 0, canvas.width, canvas.height) const blob = await new Promise((ok, fail) => canvas.toBlob((b) => (b ? ok(b) : fail(new Error('could not encode it'))), 'image/jpeg', 0.85)) const {hash} = await signupApi.upload<{hash: string}>('/api/pictures', await blob.arrayBuffer(), 'application/octet-stream') d.picture = hash st.busy = false } catch (e) { failed(e) } m.redraw() } /** Which half of a community page is showing; the posts, unless chosen otherwise. */ export function tabOf(id: string): Tab { return st.tab.get(id) ?? 'posts' } /** The two halves of a community page, side by side. */ export function Tabs(id: string, topics: number) { if (st.loaded !== id) { st.loaded = id st.threadOpen = null st.thread = null st.settingsOpen = false st.handle = '' st.error = '' st.draft = null void load(id) } return (
) } /** The public half of a community page. */ export function Posts(community: CommunityView, me: string, ctx: PostsCtx) { const id = community.id const mod = community.role === 'owner' || community.role === 'moderator' const info = st.info.get(id) const error = st.error && (

{st.error}

) if (!info) return [error,

Reading the posts…

] if (!info.settings.enabled) { return [ error,
No public posts yet

With them on, anybody can read what members post here: on the map, and on the fediverse (Mastodon, Lemmy and others), where people can follow the community and reply. {mod ? '' : ' Its owner or a moderator can switch them on.'}

, mod && Settings(community, info), ] } const feed = st.feed.get(id) ?? [] const where: Where = {id, mod, signedIn: true} return [
{Icon('public')} Public · {info.followers} follower{info.followers === 1 ? '' : 's'} on the fediverse {info.address && · @{info.address}} {mod && ( )}
, error, info.address && info.federating && FollowFrom(info.address, true), mod && st.settingsOpen && Settings(community, info), mod && Reports(id), info.may_post && Composer(community, info, me, ctx), feed.length === 0 && (
Nothing posted yet

{info.may_post ? 'Write the first: it is pinned on the map where it is about.' : 'Posts from members and from the fediverse appear here.'}

), feed.map((p) => Card(where, p, ctx, true)), ] } /** What the box asking for somebody's own server holds, per address. */ const fromServer = new Map() /** * "Follow from your own server": somebody on Mastodon, Lemmy or elsewhere * types their server, and is sent to the page there that follows this address * — Mastodon's follow screen, Lemmy's search, Misskey's — which the simulator * picks by asking their server what it runs (`/api/fediverse/follow-link`). */ export function FollowFrom(address: string, group: boolean) { const typed = fromServer.get(address) ?? '' const go = async () => { const server = typed.trim() if (!server) return try { const link = await signupApi.get( `/api/fediverse/follow-link?server=${encodeURIComponent(server)}&address=${encodeURIComponent(address)}`, ) const url = webLink(link.url) if (url) window.open(url, '_blank', 'noopener') } catch (e) { failed(e) } } return (
{ e.preventDefault() void go() }} > Follow {group ? `@${address} (on Lemmy: !${address})` : `@${address}`} from your own server fromServer.set(address, (e.target as HTMLInputElement).value)} placeholder="mastodon.social, lemmy.world, …" value={typed} />
) } /** Reports from other servers about posts here, for the moderators. */ function Reports(id: string) { const reports = st.reports.get(id) ?? [] if (reports.length === 0) return null const resolve = async (report: string, action: 'hide' | 'dismiss') => { try { await signupApi.post(`/api/communities/${id}/reports/${report}`, {action}) await load(id) } catch (e) { failed(e) } } return (

{Icon('flag')} {reports.length} report{reports.length === 1 ? '' : 's'} from other servers

{reports.map((r) => (

{r.reporter} · {ago(r.created_ms)}

{r.reason &&

{r.reason}

}
{r.post.author.address} {r.post.text}
))}
) } /** A post's place, as a chip that opens it in World. */ function PlaceChip(place: PostPlace | undefined, ctx: PostsCtx) { if (!place) return Not on the map return ( ) } export function Card(where: Where, p: PostDto, ctx: PostsCtx, top: boolean) { const mod = where.mod const url = ctx.pictureUrl(p.picture) const snapshot = ctx.pictureUrl(p.snapshot) const open = top && st.threadOpen === p.id const act = async (run: () => Promise) => { try { await run() if (st.threadOpen === p.id) st.threadOpen = null await load(where.id) } catch (e) { failed(e) } } const editing = st.editing?.id === p.id ? st.editing : null const saveEdit = async () => { const text = editing?.text.trim() if (!text || st.busy) return st.busy = true try { const changed = await signupApi.put(`/api/posts/${p.id}`, {text}) Object.assign(p, changed) st.editing = null st.busy = false } catch (e) { failed(e) } m.redraw() } const menu = [ p.mine && ( ), p.mine && ( ), mod && !p.mine && ( ), mod && !p.author.local && ( ), !p.author.local && webLink(p.url) && ( Open where it was posted ), where.signedIn && !p.mine && ( ), ].filter(Boolean) // Behind a content warning, the words and pictures wait until opened; a // sensitive picture is blurred until clicked. const hidden = !!p.warning && !p.mine && !st.shown.has(p.id) const blurred = p.sensitive && !p.mine && !st.shown.has(p.id) const pictures = [ url && {alt: p.picture_alt ?? '', src: url}, ...(p.more_pictures ?? []).map((x) => { const src = ctx.pictureUrl(x.hash) return src && {alt: x.alt ?? '', src} }), ].filter(Boolean) as {alt: string; src: string}[] return (
{ctx.avatar(p.author.address, top ? 36 : 28)}
{p.author.name} {p.author.local ? 'member' : `@${p.author.address}`} {ago(p.created_ms)} {p.edited_ms && · edited} {menu.length > 0 && (
{Icon('more_horiz')}
{menu}
)}
{p.via &&
via {p.via}
} {p.answers &&
{Icon('reply')} to {p.answers}
} {p.warning && (
{Icon('warning')} {p.warning} {!p.mine && ( )}
)} {hidden ? null : editing ? (
{ e.preventDefault() void saveEdit() }} >