Files
multica/packages/views/issues/components/reply-input.tsx
Jiayuan Zhang 7803a5b9ea feat(ui): establish a role-named type scale and migrate ad-hoc font sizes (MUL-5451) (#6136)
tokens.css defined colours, radii and font families but not a single --text-*
step, so font sizes had no baseline to align to and grew wherever they were
needed: 51 distinct sizes across web + desktop, 370 written as arbitrary
values, six at half a pixel (10.5 / 11.5 / 12.5 / 13.5 / 14.5 / 15.5px).
text-xs and text-sm carried nearly all UI text while the range between them —
11, 13, 15px — could only be reached with arbitrary values. Hierarchy does not
come from having more sizes; past a handful, each extra size makes the
hierarchy blurrier.

Add ten role-named steps, each with its own line-height so leading cannot
fragment the way size did, and move every product-UI call site onto them.
Steps are named for what the text is for, not for a t-shirt size, because
that is what keeps the scale from drifting again.

Six steps deliberately keep the exact size/line-height pairs of the Tailwind
defaults they replace, so the ~1,900-call-site rename moves nothing on screen.
The visible changes are confined to former arbitrary values snapping to a step:
8/9/10px -> micro (11px) on badges and overlines; 17 -> 18; 22 -> 24; 30
(text-3xl) -> 36 on headings and stat numbers; 12.8px -> label (13px) on small
buttons and toggles. Half-pixel sizes are gone.

This supersedes #6108, which was reverted by #6116 because the sidebar group
labels rendered at the inherited 16px. The cause was not the scale but cn():
`text-<x>` is ambiguous in Tailwind, and tailwind-merge resolves it against a
table listing only the default sizes, so it filed every role step under
text-colour and dropped whichever of `text-caption` /
`text-sidebar-foreground/70` came first. Registering the steps as a font-size
class group restores the real conflict groups — size beats size, colour beats
colour, the two coexist — and a test pins the list against the scale, since
the failure is silent in source.

Hand-written CSS is covered too. The transcript kept a 12.5px body long after
every Tailwind call site was on the scale, so the "no half-pixel sizes" claim
was true of the classes and false of the product; the editor's prose, code and
mermaid ramps had the same blind spot, and seven of their eight values already
equalled a step exactly. All now reference var(--text-*). The guard test reads
raw `font-size:` declarations as well as class names, exempting only the 16px
iOS input-zoom workaround in base.css and the landing pages' marketing ramp.

apps/mobile (own NativeWind config) and apps/docs (fumadocs' own type system)
keep Tailwind's default scale and are untouched. Landing display type
(rem/clamp, 2.2-6.4rem) stays on its separate ramp, as do four decorative
emoji / serif-hero sizes.

Verified on a running local stack: pinned sidebar rows and group labels
measure 12px/16px, nav items 14px/20px — identical to pre-migration. An audit
of every rendered font size across the product surfaces finds nothing off the
scale; the only exceptions are avatar initials and emoji, which
actor-avatar.tsx sizes proportionally to the avatar diameter by design.

Co-authored-by: Lambda <lambda@multica.ai>
Co-authored-by: multica-agent <github@multica.ai>
2026-07-30 13:42:33 +08:00

311 lines
12 KiB
TypeScript

"use client";
import { useRef, useState, useCallback, useEffect } from "react";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { ActorAvatar } from "../../common/actor-avatar";
import { contentReferencesAttachment } from "@multica/core/types";
import { formatShortcut, useShortcut } from "@multica/core/shortcuts";
import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";
import { cn } from "@multica/ui/lib/utils";
import type { AvatarSize } from "@multica/ui/lib/avatar-size";
import { useT } from "../../i18n";
import { CommentTriggerChips } from "./comment-trigger-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
import { useCommentUploads } from "./use-comment-uploads";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface ReplyInputProps {
issueId: string;
parentId: string;
placeholder?: string;
avatarType: string;
avatarId: string;
/** Resolves true on success, false on failure — the reply box keeps its text
* (locked + spinning) until then, clearing only on success. */
onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<boolean>;
size?: "sm" | "default";
/** When set, hydrates/persists the in-progress reply via the draft store.
* Required for replies inside virtualized timeline threads, where the
* enclosing CommentCard may unmount on scroll-out. */
draftKey?: CommentDraftKey;
}
// ---------------------------------------------------------------------------
// ReplyInput
// ---------------------------------------------------------------------------
function ReplyInput({
issueId,
parentId,
placeholder,
avatarType,
avatarId,
onSubmit,
size = "default",
draftKey,
}: ReplyInputProps) {
const { t } = useT("issues");
const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const placeholderText = placeholder ?? t(($) => $.reply.placeholder);
const editorRef = useRef<ContentEditorRef>(null);
const composerRef = useRef<HTMLDivElement>(null);
// See CommentInput — replying mid-upload posts without the file.
const uploadGate = useUploadGate(editorRef);
// If a draft key is provided, hydrate from store on mount (defaultValue is
// the only injection point on ContentEditorRef) and flush on every onUpdate.
const [initialDraft] = useState(() =>
draftKey ? useCommentDraftStore.getState().getDraft(draftKey) : undefined,
);
const [content, setContent] = useState(initialDraft ?? "");
const setDraft = useCommentDraftStore((s) => s.setDraft);
const [isEmpty, setIsEmpty] = useState(!initialDraft?.trim());
const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());
const triggerPreview = useCommentTriggerPreview({ issueId, parentId, content });
// Uploads for this reply session (MUL-5181) — owned by the coordinator. With
// a draftKey they persist in the draft store so scroll-out/close no longer
// drops an in-flight upload; without one (no persistence context) they fall
// back to session-local state inside the hook.
// `gate` widens the editor gate with coordinator-owned placeholders — see
// CommentInput.
const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate } =
useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);
// Readonly-first: static shell until intent; an unsent draft mounts the
// real editor immediately (see CommentInput). This is also what keeps the
// reply box working across Virtuoso scroll-out — a typed draft rehydrates
// into a live editor when the card remounts, an untouched box folds back
// to the shell.
const lazy = useLazyEditor({
initialActive:
!!initialDraft?.trim() ||
(draftKey ? useCommentDraftStore.getState().getUploads(draftKey).length > 0 : false),
editorRef,
});
const { isDragOver, dropZoneProps } = useFileDropZone({
onDrop: lazy.uploadOrQueue,
});
// Flush on tab close / mobile background — same rationale as CommentInput.
useEffect(() => {
if (!draftKey) return;
const flush = () => {
const md = editorRef.current?.getMarkdown();
if (md && md.trim().length > 0) setDraft(draftKey, md);
};
const onVis = () => { if (document.visibilityState === "hidden") flush(); };
document.addEventListener("visibilitychange", onVis);
window.addEventListener("pagehide", flush);
return () => {
document.removeEventListener("visibilitychange", onVis);
window.removeEventListener("pagehide", flush);
};
}, [draftKey, setDraft]);
useEffect(() => {
setSuppressedAgentIds(new Set());
}, [issueId, parentId]);
useEffect(() => {
const visible = new Set(triggerPreview.agents.map((agent) => agent.id));
setSuppressedAgentIds((prev) => {
const next = new Set([...prev].filter((id) => visible.has(id)));
return next.size === prev.size ? prev : next;
});
}, [triggerPreview.agents]);
const toggleSuppressedAgent = useCallback((agentId: string) => {
setSuppressedAgentIds((prev) => {
const next = new Set(prev);
if (next.has(agentId)) next.delete(agentId);
else next.add(agentId);
return next;
});
}, []);
// Await-then-render send (see CommentInput): the shared hook keeps the text,
// locks + spins, and clears only once the server accepts it.
// Stale-submit guard — see CommentInput.
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const submittedEntryRef = useRef<unknown>(null);
// See CommentInput: bound to the branch that actually wiped the editor, so a
// draft the stale-submit guard kept is never disturbed.
const editorScrubbedRef = useRef(false);
const { submitting, submit } = useComposerSubmit({
editorRef,
uploadGate: gate,
containerRef: composerRef,
// A thread reply is rarely the last thing the user has to say, so the caret
// stays in the box for the next one. Unlike a top-level comment, the posted
// reply lands directly above the box that is still focused — nothing needs
// to pull the eye elsewhere. `containerRef` keeps this from stealing focus
// if the user moved to another composer while the reply was in flight.
afterAccepted: () => (editorScrubbedRef.current ? "refocus" : "none"),
onSubmit: (content) => {
editorScrubbedRef.current = false;
if (draftKey) {
// Flush pending debounce before snapshotting — see CommentInput.
const pending = editorRef.current?.flushPendingUpdate?.();
if (pending != null) setDraft(draftKey, pending);
submittedEntryRef.current = useCommentDraftStore.getState().drafts[draftKey];
}
// Bind only uploads the body still references (see CommentInput):
// deleting an inline image really unbinds it; close-surviving uploads
// are written back into the body by the settle handler.
const activeIds = pendingAttachments
.filter((a) => contentReferencesAttachment(content, a))
.map((a) => a.id);
const suppressAgentIds = triggerPreview.agents
.filter((agent) => suppressedAgentIds.has(agent.id))
.map((agent) => agent.id);
return onSubmit(
content,
activeIds.length > 0 ? activeIds : undefined,
suppressAgentIds.length > 0 ? suppressAgentIds : undefined,
);
},
onAccepted: () => {
// Success may only consume the entry it submitted — see CommentInput.
if (draftKey) {
const lateMd = editorRef.current?.flushPendingUpdate?.();
if (lateMd != null) setDraft(draftKey, lateMd);
const store = useCommentDraftStore.getState();
const live = store.drafts[draftKey];
const untouched = live === undefined || live === submittedEntryRef.current;
if (untouched) store.clearDraft(draftKey);
if (!mountedRef.current || !untouched) return;
} else {
if (!mountedRef.current) return;
uploads.forEach((u) => removeUpload(u.clientUploadId));
}
editorRef.current?.clearContent();
setContent("");
setIsEmpty(true);
setSuppressedAgentIds(new Set());
editorScrubbedRef.current = true;
},
});
const avatarSize: AvatarSize = size === "sm" ? "sm" : "md";
return (
<div className="group/editor flex items-start gap-2.5">
<ActorAvatar
actorType={avatarType}
actorId={avatarId}
size={avatarSize}
className="mt-0.5 shrink-0"
/>
<div
{...dropZoneProps}
ref={composerRef}
className={cn(
"relative min-w-0 flex-1 flex flex-col",
!isEmpty && "pb-9",
)}
>
{/* Lock the editor while the reply is in flight — see CommentInput. */}
{lazy.active && (
<div
className={cn(
"flex-1 min-h-0 overflow-y-auto",
submitting && "pointer-events-none opacity-60",
!lazy.ready && "hidden",
)}
aria-busy={submitting || undefined}
>
<ContentEditor
ref={editorRef}
defaultValue={initialDraft}
onReady={lazy.onReady}
placeholder={placeholderText}
onUpdate={(md) => {
setContent(md);
setIsEmpty(!md.trim());
// setDraft keeps any pending attachments and drops the entry only
// when text AND attachments are both empty.
if (draftKey) setDraft(draftKey, md);
}}
onSubmit={submit}
onUploadFile={handleUpload}
onUploadingChange={uploadGate.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
attachments={pendingAttachments}
enableSlashCommands
slashCommandMode="command"
/>
</div>
)}
{/* Static shell — clones the empty single-line reply box (see
CommentInput for the pattern). */}
{!lazy.ready && (
<div
data-testid="reply-composer-shell"
role="button"
tabIndex={0}
aria-label={placeholderText}
className="flex-1 min-h-0 cursor-text rich-text-editor text-body"
onClick={() => lazy.activate()}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
lazy.activate();
}
}}
>
{/* <p> under rich-text-editor: same type metrics as the real
editor's empty paragraph — no height jump on swap. */}
<p className="text-muted-foreground">{placeholderText}</p>
</div>
)}
<div className="absolute bottom-0 left-0 right-24 min-w-0">
<CommentTriggerChips
agents={triggerPreview.agents}
blocked={triggerPreview.blocked}
draftContent={content}
suppressedAgentIds={suppressedAgentIds}
onToggle={toggleSuppressedAgent}
/>
</div>
<div className="absolute bottom-0 right-0 flex items-center gap-1">
<FileUploadButton
size="sm"
multiple
onSelect={(file) => lazy.uploadOrQueue([file])}
/>
<SubmitButton
onClick={submit}
disabled={isEmpty}
loading={submitting}
busy={gate.uploading}
tooltip={gate.uploading
? tEditor(($) => $.upload.in_progress)
: sendShortcut
? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`
: t(($) => $.comment.send_tooltip)}
ariaLabel={gate.uploading
? tEditor(($) => $.upload.in_progress)
: t(($) => $.comment.send_tooltip)}
/>
</div>
{isDragOver && <FileDropOverlay />}
</div>
</div>
);
}
export { ReplyInput, type ReplyInputProps };