A local-first multi-agent app development platform, built on PenguinHarness
/**
* One channel: its header, the stream of the loaded days — a separator per day, one bubble per
* message, each body rendered as Markdown with its @-mentions kept as chips (stronger when
* they address the reader), `system` messages as centred banners in the reader's own language,
* ticket and session references as chips that open them, an unread divider at the read
* cursor — and the composer beneath it. The view follows the stream while it is at the bottom;
* scrolled up, new messages collect behind a pill that returns to the latest. Sitting at the
* bottom of today marks this channel read, which is what clears its badge in the sidebar and
* the rail. Nothing here delivers to an employee unless it is @-mentioned, and only inside
* this channel's membership; the empty state and the header's "?" say so.
*
* Opening a channel assembles its whole first screen before the first render — today's day
* file, then earlier ones until the stream holds enough messages or the day budget runs out
* (initialDaysToLoad) — so the reader lands at the bottom of real history rather than on a
* blank day, and without the scroll jump a prepend after the first paint would cost. Anything
* older stays behind "earlier", which prepends one day file per click.
*
* The stream is drawn the way every chat client draws one, because a channel is read the way
* every chat is: the UI package's ChannelRun and ChannelBubble draw a run and its messages —
* somebody else's on the left under its avatar and name, the reader's own on the right in its
* own tint, each bubble with its own time — and this view decides who is speaking, which side a
* run stands on, and what hangs beside the name: the relay chip from the second hop on, the
* whole @-chain rule in its tooltip.
*
* A `system` line is one sentence, so it stays one muted line rather than a Markdown body: the
* server writes it twice — as English text and as a structured notice — and the notice is what
* this renders (channel-notices.ts), falling back to the text for a line written before that
* field existed.
*
* A channel the reader has not joined offers Join instead of the composer — people may read
* every channel but post only in the ones they are in; joining asks first, because it is what
* puts this channel's @-mentions in front of the reader from then on, and a refused join keeps
* that card standing with the server's words inside it. An archived channel says
* it is read-only. Only the messages are essential: the chart and the Project's member list feed
* names and the invite picker, so a hiccup there degrades names to ids rather than blocking
* the page.
*/
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router";
import type { OrgChannelDetail, OrgChannelMessage } from "@adelie/server/api";
import {
Button,
ChannelBubble,
ChannelRun,
EmptyState,
GlyphIcon,
ICON_GAP,
ICON_SIZE,
NoticeStrip,
Skeleton,
toastError,
toastSuccess,
} from "@adelie/ui";
import type { ChannelSender } from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatDateTime } from "../../lib/format";
import { useDocumentTitle } from "../../lib/use-document-title";
import { toneDot, toneInk } from "../../lib/tone";
import { useAuth } from "../../state/auth";
import { useCompany, useCompanyEvents } from "../../state/company";
import { NAV_ICONS } from "../../lib/nav-icons";
import { createStreamFollow, stickToBottom } from "../chat/stream-follow";
import { useOrg } from "./org-layout";
import { principalLabel } from "./shared";
import { orgKey } from "./company-nav";
import { ChannelComposer } from "./channel-composer";
import { useChannelDraft } from "./channel-draft";
import { ChannelHeader } from "./channel-header";
import { ChannelMessageBody, ChannelReaderProvider, MentionChip } from "./channel-markdown";
import { noticeText } from "./channel-notices";
import { JoinChannelConfirm } from "./channel-dialogs";
import { DEFAULT_CHANNEL_ID, channelLabel } from "./channel-list";
import {
channelMentionCandidates,
mentionCandidates,
mentionIsMe,
mentionLabel,
mentionRuns,
} from "./channel-mentions";
import {
appendMessage,
bubbleShape,
buildStream,
clockTime,
dayKind,
earlierDay,
hopChipShown,
initialDaysToLoad,
isOwnRun,
joinedElsewhere,
lastMessageId,
messageCount,
} from "./channel-stream";
import type { ChannelDay, StreamItem } from "./channel-stream";
import { parsePrincipal } from "./principals";
/** What the first response fixes for this channel: today, the day list, and the read cursor the divider is drawn at. */
interface StreamMeta {
today: string;
/** Every day of this channel with a file, newest first. */
days: string[];
unreadAfterId: string | null;
}
/** Downward arrow on the return-to-latest pill (lucide arrow-down). */
const ARROW_DOWN_ICON = "M12 5v14M6 13l6 6 6-6";
export function ChannelView() {
const { projectId, orgId, org } = useOrg();
const params = useParams<{ channelId: string }>();
const channelId = params.channelId ?? DEFAULT_CHANNEL_ID;
const navigate = useNavigate();
const company = useCompany();
const { user } = useAuth();
const [detail, setDetail] = useState<OrgChannelDetail | null>(null);
const [detailError, setDetailError] = useState<string | null>(null);
const [days, setDays] = useState<ChannelDay[] | null>(null);
const [meta, setMeta] = useState<StreamMeta | null>(null);
const [error, setError] = useState<string | null>(null);
const [employees, setEmployees] = useState<
ReadonlyArray<{ agentId: string; name: string; title: string }>
>([]);
const [members, setMembers] = useState<string[]>([]);
const [loadingEarlier, setLoadingEarlier] = useState(false);
const [joining, setJoining] = useState(false);
const [confirmJoin, setConfirmJoin] = useState(false);
/** The server's own words for a refused join, drawn in the card that asked, next to its retry. */
const [joinRefusal, setJoinRefusal] = useState<string | null>(null);
/** Messages that arrived while the view was scrolled up; shown on the pill. */
const [pendingNew, setPendingNew] = useState(0);
const [showJump, setShowJump] = useState(false);
const [atBottom, setAtBottom] = useState(true);
const listRef = useRef<HTMLDivElement>(null);
const follow = useMemo(createStreamFollow, []);
/** The newest id already posted as read: the cursor is written once per new tail, not per render. */
const markedRef = useRef<string | null>(null);
/** Scroll anchoring across a prepend: the height before the earlier day landed, and which day was first. */
const heightRef = useRef(0);
const firstDayRef = useRef<string | null>(null);
/**
* Which opening load is still the current one. The walk back through earlier days is several
* round trips long, and a channel switched during it would otherwise be overwritten by the
* stream of the channel the reader left.
*/
const loadSeq = useRef(0);
/** What the sidebar's listing last said about this reader's membership (see joinedElsewhere). */
const listedMemberRef = useRef<boolean | null>(null);
const me = user?.userId ?? "";
const myPrincipal = `user:${me}`;
const myKey = orgKey(projectId, orgId);
const label = detail === null ? channelId : channelLabel(detail, S.company.channels.allHands);
useDocumentTitle(org ? `${org.name} · ${label}` : label);
// Another channel's stream must not linger while this one loads: everything the stream
// holds is keyed on the channel, the read marker included.
useEffect(() => {
setDays(null);
setMeta(null);
setError(null);
setDetail(null);
setDetailError(null);
setPendingNew(0);
setConfirmJoin(false);
setJoinRefusal(null);
markedRef.current = null;
firstDayRef.current = null;
listedMemberRef.current = null;
follow.resume();
}, [projectId, orgId, channelId, follow]);
const loadDetail = useCallback(async () => {
try {
const res = await api.getOrgChannel(projectId, orgId, channelId);
setDetail(res);
setDetailError(null);
} catch (e) {
setDetailError(apiErrorText(e));
}
}, [projectId, orgId, channelId]);
const load = useCallback(async () => {
const seq = ++loadSeq.current;
/** Still the load this channel wants: a later one (or another channel) supersedes it. */
const current = () => loadSeq.current === seq;
// Names and invite candidates are best effort: the stream must not wait on them.
void api
.getOrgChart(projectId, orgId)
.then((ch) =>
setEmployees(
ch.employees.map((e) => ({ agentId: e.agentId, name: e.name, title: e.title })),
),
)
.catch(() => undefined);
void api
.listMembers(projectId)
.then((res) => setMembers(res.members.map((m) => m.userId)))
.catch(() => undefined);
void loadDetail();
try {
const res = await api.getOrgChannelMessages(projectId, orgId, channelId);
if (!current()) return;
let loaded: ChannelDay[] = [{ date: res.date, messages: res.messages }];
try {
// Walk back one day file at a time until the first screen holds history. Sequential
// rather than parallel: how far back to go depends on how much each day turned out
// to hold, and a quiet channel would otherwise pay for seven requests it does not need.
for (;;) {
const target = initialDaysToLoad(res.days, res.date, loaded);
if (target === null) break;
const older = await api.getOrgChannelMessages(projectId, orgId, channelId, target);
if (!current()) return;
loaded = [{ date: target, messages: older.messages }, ...loaded];
}
} catch {
// An earlier day that fails is not fatal — today is already in hand and "earlier"
// stays for another attempt — so the stream renders with what the walk did reach.
}
setDays(loaded);
setMeta((prev) => ({
today: res.date,
days: res.days,
// The divider stays where the first load put it: marking read must not move it out
// from under the reader.
unreadAfterId: prev?.unreadAfterId ?? res.lastReadId ?? null,
}));
setError(null);
} catch (e) {
if (!current()) return;
setError(apiErrorText(e));
}
}, [projectId, orgId, channelId, loadDetail]);
useEffect(() => {
void load();
}, [load]);
// A Join from the sidebar's own row reloads the listing, not this detail: without this the
// view would keep offering Join under a channel the reader is already in (joinedElsewhere).
const listedMember = company.channels?.find((c) => c.channelId === channelId)?.isMember ?? null;
useEffect(() => {
// Only once there is a detail to compare against: a listing read before the first detail
// landed is not a membership this view has ever shown.
if (detail === null) return;
const previous = listedMemberRef.current;
listedMemberRef.current = listedMember;
if (joinedElsewhere(previous, listedMember, detail.isMember)) void loadDetail();
}, [listedMember, detail, loadDetail]);
const loadEarlier = async () => {
if (days === null || meta === null || loadingEarlier) return;
const target = earlierDay(meta.days, days[0]?.date ?? meta.today);
if (target === null) return;
setLoadingEarlier(true);
try {
const res = await api.getOrgChannelMessages(projectId, orgId, channelId, target);
setDays((prev) =>
prev === null || prev.some((d) => d.date === target)
? prev
: [{ date: target, messages: res.messages }, ...prev],
);
} catch (e) {
toastError(apiErrorText(e));
} finally {
setLoadingEarlier(false);
}
};
// A new message in THIS channel lands in the stream without a refetch. While the view is
// at the bottom it simply appears; scrolled up, it counts towards the pill. Another
// channel's message only moves its own badge, which the store owns. The append is decided
// here, not inside a setDays updater: bumping the pill is a side effect and an updater must
// stay pure. It reads the latest list through a ref rather than this render's `days`, so
// two messages arriving before React re-renders both land instead of the second
// overwriting the first.
const latestDays = useRef(days);
latestDays.current = days;
useCompanyEvents((ev) => {
if (ev.type !== "org_channel" || orgKey(ev.projectId, ev.orgId) !== myKey) return;
if (ev.channelId !== channelId) return;
const current = latestDays.current;
if (meta === null || current === null) return;
const next = appendMessage(current, meta.today, ev.message);
// Unchanged means the message is already in the stream — the reader's own, appended on send.
if (next === current) return;
latestDays.current = next;
setDays(next);
if (!follow.stick) setPendingNew((n) => n + 1);
});
const syncScrollState = () => {
const el = listRef.current;
const stick = follow.stick;
setAtBottom(stick);
setShowJump(!stick && el !== null && el.scrollHeight - el.scrollTop - el.clientHeight > 1);
if (stick) setPendingNew(0);
};
const onScroll = () => {
const el = listRef.current;
if (!el) return;
follow.scrolled({
scrollTop: el.scrollTop,
scrollHeight: el.scrollHeight,
clientHeight: el.clientHeight,
});
syncScrollState();
};
// Before paint: keep the reader's place when an earlier day lands above the viewport, and
// otherwise stick to the bottom while following.
useLayoutEffect(() => {
const el = listRef.current;
if (!el || days === null) return;
const firstDay = days[0]?.date ?? null;
const prepended = firstDayRef.current !== null && firstDay !== firstDayRef.current;
if (prepended && !follow.stick) el.scrollTop += el.scrollHeight - heightRef.current;
firstDayRef.current = firstDay;
heightRef.current = el.scrollHeight;
if (follow.stick) stickToBottom(el, follow);
syncScrollState();
// syncScrollState is recreated per render; the effect keys on the stream's content only.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [days, follow]);
// The composer growing, or the window resizing, shrinks the stream: re-snap while following.
useEffect(() => {
const el = listRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(() => {
heightRef.current = el.scrollHeight;
if (follow.stick) stickToBottom(el, follow);
});
ro.observe(el);
if (el.firstElementChild) ro.observe(el.firstElementChild);
return () => ro.disconnect();
}, [follow, days === null]);
// Sitting at the bottom of the newest day marks this channel's tail as read and clears its
// badge; the store's copy is cleared first so the sidebar does not wait for the round trip.
const lastId = days === null ? null : lastMessageId(days);
const { markChannelRead } = company;
useEffect(() => {
if (!atBottom || lastId === null || lastId === markedRef.current) return;
markedRef.current = lastId;
markChannelRead(channelId);
void api
.readOrgChannel(projectId, orgId, channelId, { upTo: lastId })
.then(() => markChannelRead(channelId))
.catch(() => undefined);
}, [atBottom, lastId, markChannelRead, projectId, orgId, channelId]);
const jumpToLatest = () => {
const el = listRef.current;
if (!el) return;
follow.resume();
stickToBottom(el, follow);
syncScrollState();
};
// The unsent text outlives the view: leaving a channel (or reloading) must not lose it.
const draft = useChannelDraft(projectId, orgId, channelId);
const send = async (text: string): Promise<boolean> => {
try {
const msg = await api.sendOrgChannelMessage(projectId, orgId, channelId, { text });
draft.discard();
follow.resume();
setDays((prev) =>
prev === null ? prev : appendMessage(prev, meta?.today ?? msg.time.slice(0, 10), msg),
);
return true;
} catch (e) {
toastError(apiErrorText(e));
return false;
}
};
const join = async () => {
if (joining) return;
setJoining(true);
try {
await api.addOrgChannelMember(projectId, orgId, channelId, { principal: myPrincipal });
// The card goes with its own join landing, never before: a refusal has to stay readable
// next to the button that retries it.
setConfirmJoin(false);
setJoinRefusal(null);
toastSuccess(S.company.channels.joined);
await loadDetail();
void company.reloadChannels();
} catch (e) {
setJoinRefusal(apiErrorText(e));
} finally {
setJoining(false);
}
};
const names = useMemo(() => new Map(employees.map((e) => [e.agentId, e.name])), [employees]);
const employeeIds = useMemo(() => new Set(employees.map((e) => e.agentId)), [employees]);
// Who the mention chips inside the rendered bodies are measured against. Memoized because it
// is a context value: a fresh object per render would re-render every message body.
const reader = useMemo(() => ({ names, me, employeeIds }), [names, me, employeeIds]);
const memberPrincipals = useMemo(
() => (detail === null ? null : new Set(detail.members.map((m) => m.principal))),
[detail],
);
const candidates = useMemo(
() =>
channelMentionCandidates(
mentionCandidates(employees, members, S.company.channels.mentionAll),
memberPrincipals,
),
[employees, members, memberPrincipals],
);
const stream = useMemo(
() => (days === null ? [] : buildStream(days, { unreadAfterId: meta?.unreadAfterId ?? null })),
[days, meta],
);
const earlier =
days !== null && meta !== null ? earlierDay(meta.days, days[0]?.date ?? meta.today) : null;
// A ticket named in a message opens as the dialog over the channel: the reader stays in
// the conversation they were reading. A session has no in-place form and still navigates.
const openTicket = (ticketId: string) => company.openTicket(projectId, orgId, ticketId);
const scrollToMessage = (id: string) =>
document.getElementById(id)?.scrollIntoView({ block: "center" });
const renderText = (m: OrgChannelMessage) =>
mentionRuns(m.text).map((run, i) =>
run.mention === null ? (
<span key={i}>{run.text}</span>
) : (
<MentionChip
key={i}
raw={run.text}
label={mentionLabel(run.mention, names, S.company.principalAll)}
me={mentionIsMe(run.mention, me, employeeIds)}
/>
),
);
const renderRefs = (m: OrgChannelMessage) => {
// Destructured, so each id narrows to `string` inside the chips' closures too.
const { ticket, session, replyTo } = m.refs ?? {};
if (ticket === undefined && session === undefined && replyTo === undefined) return null;
return (
<span className={`mt-1 flex flex-wrap items-center ${ICON_GAP.row}`}>
{ticket !== undefined && (
<RefChip
onClick={() => openTicket(ticket)}
icon={NAV_ICONS.orgTickets}
title={S.company.channels.openTicketRef}
>
{S.company.channels.ticketRef(ticket)}
</RefChip>
)}
{session !== undefined && (
<RefChip
onClick={() => navigate(`/chat/${session}`)}
title={S.company.channels.sessionRef}
>
{S.company.channels.sessionRef}
</RefChip>
)}
{replyTo !== undefined && (
<RefChip onClick={() => scrollToMessage(replyTo)} title={S.company.channels.replyToJump}>
{S.company.channels.replyTo}
</RefChip>
)}
</span>
);
};
const renderItem = (item: StreamItem, i: number) => {
if (item.kind === "day") {
const kind = meta === null ? "other" : dayKind(item.date, meta.today);
const dayLabel =
kind === "today"
? S.company.channels.today
: kind === "yesterday"
? S.company.channels.yesterday
: null;
return (
<div key={`day-${item.date}`} className={`flex items-center ${ICON_GAP.menu} py-3`}>
<span className="h-px flex-1 bg-divider" />
<span className="text-xs font-medium text-fg-muted">
{dayLabel !== null ? `${dayLabel} · ${item.date}` : item.date}
</span>
<span className="h-px flex-1 bg-divider" />
</div>
);
}
if (item.kind === "unread") {
return (
<div
key={`unread-${i}`}
className={`flex items-center ${ICON_GAP.menu} py-2`}
role="separator"
aria-label={S.company.channels.unreadDivider}
>
<span className={`h-px flex-1 ${toneDot.attention}`} />
<span className={`text-xs font-medium ${toneInk.attention}`}>
{S.company.channels.unreadDivider}
</span>
<span className={`h-px flex-1 ${toneDot.attention}`} />
</div>
);
}
if (item.kind === "system") {
const m = item.message;
// The structured notice in the reader's language; a line from before that field, or of a
// kind this build does not know, keeps the server's English sentence with its mentions.
const notice =
m.notice === undefined ? null : noticeText(m.notice, names, S.company.channels.notices);
return (
<div key={m.id} id={m.id} className="my-2 flex justify-center">
<p
data-tooltip={formatDateTime(m.time)}
data-tooltip-extra
className="max-w-[85%] rounded-md border border-gray-200 bg-gray-50 px-3 py-1.5 text-center text-xs leading-relaxed text-gray-500 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-400"
>
<span className="sr-only">{S.company.channels.systemMessage} </span>
{notice === null ? renderText(m) : notice}
{/* A notice addressed to people keeps their chips: the sentence names the event,
the chips say who has to act on it. */}
{notice !== null &&
m.mentions.map((principal) => (
<span key={principal} className="ml-1">
<MentionChip
raw={`@${principal}`}
label={mentionLabel(principal, names, S.company.principalAll)}
me={mentionIsMe(principal, me, employeeIds)}
/>
</span>
))}
<span className="ml-2 text-gray-400 dark:text-gray-500">{clockTime(m.time)}</span>
{renderRefs(m)}
</p>
</div>
);
}
const first = item.messages[0]!;
const p = parsePrincipal(item.sender);
// An employee's tile colour hashes its agent id, so a rename keeps the colour; every other
// sender is drawn as a person's initial tile.
const sender: ChannelSender = {
kind: p.kind === "agent" ? "agent" : "user",
id: p.kind === "agent" || p.kind === "user" ? p.id : item.sender,
name: principalLabel(item.sender, names),
};
return (
<ChannelRun
key={first.id}
sender={sender}
own={isOwnRun(item.sender, me)}
ownLabel={S.company.channels.you}
meta={
// The relay chip names what it is and carries the @-chain rule in its tooltip: "hop 3"
// alone tells a reader nothing about why a message arrived.
hopChipShown(item.hop) ? (
<span
data-tooltip={S.company.channels.hopInfo}
data-tooltip-extra
className="text-fg-muted"
>
{S.company.channels.hop(item.hop)}
</span>
) : undefined
}
>
{item.messages.map((m, i) => {
const shape = bubbleShape(item, i, me);
const at = formatDateTime(m.time);
return (
<ChannelBubble
key={m.id}
id={m.id}
own={shape.own}
last={shape.last}
time={clockTime(m.time)}
timeTooltip={at}
timeLabel={S.company.channels.sentAt(at)}
footer={renderRefs(m)}
>
<ChannelMessageBody text={m.text} />
</ChannelBubble>
);
})}
</ChannelRun>
);
};
const canPost = detail !== null && detail.isMember && !detail.archived;
return (
<ChannelReaderProvider reader={reader}>
<div className="flex h-full min-h-0 flex-col bg-white dark:bg-gray-950">
<ChannelHeader
projectId={projectId}
orgId={orgId}
me={myPrincipal}
detail={detail}
employees={employees}
projectMembers={members}
onChanged={() => {
void loadDetail();
void company.reloadChannels();
}}
/>
{detailError !== null && detail === null && (
<NoticeStrip
banner
tone="danger"
as="p"
role="alert"
className="border-b px-4 py-1.5 text-xs"
>
{S.company.channels.channelLoadFailed} · {detailError}
</NoticeStrip>
)}
<div className="flex min-h-0 flex-1 flex-col px-3 pb-3 md:px-4 md:pb-4">
<div className="relative mx-auto flex min-h-0 w-full max-w-5xl flex-1 flex-col">
<div
ref={listRef}
role="log"
aria-label={S.company.channels.streamLabel(label)}
onScroll={onScroll}
onWheel={(e) => follow.wheel(e.deltaY)}
onTouchStart={(e) => follow.touchStart(e.touches[0]?.clientY ?? 0)}
onTouchMove={(e) => follow.touchMove(e.touches[0]?.clientY ?? 0)}
onTouchEnd={() => follow.touchEnd()}
className="min-h-0 flex-1 overflow-y-auto pr-1"
>
<div>
{days === null && error !== null ? (
<EmptyState
title={error}
action={<Button onClick={() => void load()}>{S.common.retry}</Button>}
/>
) : days === null ? (
<StreamSkeleton />
) : (
<>
{earlier !== null ? (
<div className="flex justify-center py-2">
<Button
size="sm"
disabled={loadingEarlier}
onClick={() => void loadEarlier()}
>
{loadingEarlier ? S.common.loading : S.company.channels.earlierDays}
</Button>
</div>
) : (
messageCount(days) > 0 && (
<p className="py-2 text-center text-xs text-fg-subtle">
{S.company.channels.noEarlier}
</p>
)
)}
{messageCount(days) === 0 ? (
<EmptyState
title={S.company.channels.empty}
description={S.company.channels.emptyHint}
/>
) : (
stream.map(renderItem)
)}
</>
)}
</div>
</div>
{showJump && (
<button
type="button"
aria-label={S.chat.jumpToLatest}
data-tooltip={S.chat.jumpToLatest}
onClick={jumpToLatest}
className={`anim-pop absolute bottom-3 left-1/2 z-10 inline-flex -translate-x-1/2 items-center ${ICON_GAP.tight} rounded-full border border-gray-300 bg-white py-1 pl-2.5 pr-2 text-xs text-gray-600 shadow-sm transition-colors duration-150 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}
>
{pendingNew > 0 ? S.company.channels.newMessages(pendingNew) : S.chat.jumpToLatest}
<GlyphIcon d={ARROW_DOWN_ICON} size={ICON_SIZE.inlineGlyph} />
</button>
)}
</div>
<div className="mx-auto w-full max-w-5xl">
{canPost ? (
<ChannelComposer
// Remounted per draft: the box starts from the text this channel was left with.
key={draft.key ?? channelId}
candidates={candidates}
names={names}
initialText={draft.initial}
onTextChange={draft.onTextChange}
onSend={send}
/>
) : detail !== null && detail.archived ? (
<NoticeStrip
tone="neutral"
as="p"
className="mt-3 rounded-md border px-3 py-2 text-xs"
role="status"
>
{S.company.channels.archivedNotice}
</NoticeStrip>
) : detail !== null ? (
<NoticeStrip
tone="attention"
className="mt-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 rounded-md border px-3 py-2 text-xs"
>
<span>{S.company.channels.notMemberNotice}</span>
<Button
size="sm"
variant="primary"
disabled={joining}
onClick={() => {
// A new question, not the last one: the previous refusal is not its answer.
setJoinRefusal(null);
setConfirmJoin(true);
}}
>
{joining ? S.company.channels.joining : S.company.channels.join}
</Button>
</NoticeStrip>
) : null}
</div>
</div>
<JoinChannelConfirm
open={confirmJoin}
busy={joining}
onClose={() => {
if (!joining) setConfirmJoin(false);
}}
onConfirm={() => void join()}
{...(joinRefusal !== null ? { refusal: S.common.refused(joinRefusal) } : {})}
/>
</div>
</ChannelReaderProvider>
);
}
/**
* A small bordered chip that opens what a message refers to. The message bubble itself is inert
* — these chips are the only way out of it — so each says in its tooltip where it lands, which
* the chip's own text alone ("工单 T-3", "回复") does not.
*/
function RefChip({
onClick,
icon,
title,
children,
}: {
onClick: () => void;
icon?: string;
/** Where the chip goes, as its tooltip reads it. */
title: string;
children: string;
}) {
return (
<button
type="button"
data-tooltip={title}
data-tooltip-extra
onClick={onClick}
className={`inline-flex items-center ${ICON_GAP.tight} rounded-full border border-gray-200 bg-white px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}
>
{icon !== undefined && <GlyphIcon d={icon} size={ICON_SIZE.inlineGlyph} />}
{children}
</button>
);
}
/** Three bubble-shaped bands while the first day loads, on the side each will land on. */
function StreamSkeleton() {
return (
<div className="space-y-4 py-2">
{[0, 1, 2].map((i) => {
const own = i === 1;
return (
<div key={i} className={`flex items-start ${ICON_GAP.card}`}>
{!own && <Skeleton className="h-7 w-7 shrink-0 rounded-md" />}
<div className={`flex flex-1 flex-col gap-1 ${own ? "items-end" : "items-start"}`}>
{!own && <Skeleton className="h-3 w-24" />}
<Skeleton className={`h-8 rounded-2xl ${own ? "w-1/2" : "w-3/5"}`} />
</div>
</div>
);
})}
</div>
);
}