@karimsa/mdxserve 0.5.1 → 0.6.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +3 -0
  2. package/client/DocView.tsx +26 -14
  3. package/client/ListingView.tsx +3 -3
  4. package/client/MdSection.tsx +14 -9
  5. package/client/RenderErrorBoundary.tsx +20 -5
  6. package/client/Settings.tsx +26 -21
  7. package/client/app.css +20 -0
  8. package/client/comments/CommentsPanel.tsx +194 -0
  9. package/client/comments/CommentsPopover.tsx +197 -0
  10. package/client/comments/CommentsSheet.tsx +63 -0
  11. package/client/comments/CommentsSidebar.tsx +24 -0
  12. package/client/comments/CtlButton.tsx +33 -0
  13. package/client/comments/DraftThread.tsx +86 -0
  14. package/client/comments/GutterCounters.tsx +121 -0
  15. package/client/comments/ReplyField.tsx +98 -0
  16. package/client/comments/SelectionButton.tsx +142 -0
  17. package/client/comments/Thread.tsx +308 -0
  18. package/client/comments/anchor.ts +204 -0
  19. package/client/comments/data.ts +98 -0
  20. package/client/comments/dom.ts +212 -0
  21. package/client/comments/drafts.ts +36 -0
  22. package/client/comments/highlights.ts +83 -0
  23. package/client/comments/model.ts +241 -0
  24. package/client/comments/motion.ts +44 -0
  25. package/client/comments/pins.ts +37 -0
  26. package/client/comments/self-writes.ts +22 -0
  27. package/client/comments/state.ts +67 -0
  28. package/client/comments/time.ts +21 -0
  29. package/client/entry.tsx +10 -0
  30. package/client/hooks.ts +19 -0
  31. package/client/platform.ts +8 -0
  32. package/client/router.ts +5 -0
  33. package/client/shell/AppShell.tsx +85 -15
  34. package/client/shell/StandaloneShell.tsx +3 -2
  35. package/client/shell/TopBar.tsx +25 -0
  36. package/client/ui/ConfirmDeleteDialog.tsx +1 -1
  37. package/client/ui/Toast.tsx +5 -1
  38. package/client/ui/icon-set.ts +10 -0
  39. package/dist/cli.js +872 -229
  40. package/package.json +1 -1
  41. package/skills/mdxserve/SKILL.md +86 -0
@@ -0,0 +1,197 @@
1
+ import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
2
+ import { useAtom } from "jotai";
3
+ import { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from "react";
4
+ import { CtlButton } from "./CtlButton";
5
+ import { DraftThread } from "./DraftThread";
6
+ import { threadAtPoint } from "./highlights";
7
+ import type { CommentsModel } from "./model";
8
+ import { draftAtom } from "./state";
9
+ import { Thread } from "./Thread";
10
+
11
+ const GAP = 8;
12
+ const EDGE = 16;
13
+
14
+ /** Where the popover hangs: the thread's range when it has one, else its block. */
15
+ function useReference(range: Range | null, element: Element | null) {
16
+ return useMemo(() => {
17
+ if (!range && !element) return null;
18
+ return {
19
+ getBoundingClientRect: () =>
20
+ range?.getBoundingClientRect() ?? element?.getBoundingClientRect() ?? new DOMRect(),
21
+ getClientRects: () => (range ? range.getClientRects() : element?.getClientRects()) ?? [],
22
+ contextElement: element ?? undefined,
23
+ };
24
+ }, [range, element]);
25
+ }
26
+
27
+ /**
28
+ * A 360px card under the highlight with the thread's timeline. Placed with
29
+ * floating-ui against the range, and follows scroll and resize. Escape or a
30
+ * click outside closes it.
31
+ */
32
+ function PopoverFrame({
33
+ reference,
34
+ onClose,
35
+ keepOpen,
36
+ focusFrame,
37
+ label,
38
+ tools,
39
+ children,
40
+ }: {
41
+ reference: ReturnType<typeof useReference>;
42
+ onClose: () => void;
43
+ /** An outside click leaves it open (a draft with text in it). */
44
+ keepOpen: boolean;
45
+ focusFrame: boolean;
46
+ label: string;
47
+ tools: ReactNode;
48
+ children: ReactNode;
49
+ }) {
50
+ const frameRef = useRef<HTMLDivElement>(null);
51
+
52
+ useLayoutEffect(() => {
53
+ const floating = frameRef.current;
54
+ if (!reference || !floating) return;
55
+ return autoUpdate(reference, floating, () => {
56
+ void computePosition(reference, floating, {
57
+ strategy: "fixed",
58
+ placement: "bottom-start",
59
+ middleware: [offset(GAP), flip({ padding: EDGE }), shift({ padding: EDGE })],
60
+ }).then(({ x, y }) => {
61
+ floating.style.left = `${x}px`;
62
+ floating.style.top = `${y}px`;
63
+ floating.style.visibility = "visible";
64
+ });
65
+ });
66
+ }, [reference]);
67
+
68
+ useEffect(() => {
69
+ if (focusFrame) frameRef.current?.focus({ preventScroll: true });
70
+ }, [focusFrame]);
71
+
72
+ useEffect(() => {
73
+ function onKeyDown(event: KeyboardEvent) {
74
+ if (event.key === "Escape" && !event.defaultPrevented) onClose();
75
+ }
76
+ function onPointerDown(event: PointerEvent) {
77
+ const target = event.target instanceof Element ? event.target : null;
78
+ if (!target || frameRef.current?.contains(target)) return;
79
+ if (keepOpen || target.closest("[data-comments-keep]")) return;
80
+ // A comment being edited holds unsaved text: Escape or Close ends it, a stray click does not.
81
+ if (frameRef.current?.querySelector("[data-comment-edit]")) return;
82
+ // A click on another highlight is handled there: it swaps the thread.
83
+ if (threadAtPoint(event.clientX, event.clientY)) return;
84
+ onClose();
85
+ }
86
+ window.addEventListener("keydown", onKeyDown);
87
+ document.addEventListener("pointerdown", onPointerDown, true);
88
+ return () => {
89
+ window.removeEventListener("keydown", onKeyDown);
90
+ document.removeEventListener("pointerdown", onPointerDown, true);
91
+ };
92
+ }, [onClose, keepOpen]);
93
+
94
+ return (
95
+ <div
96
+ ref={frameRef}
97
+ role="dialog"
98
+ aria-label={label}
99
+ tabIndex={-1}
100
+ data-print-hide
101
+ style={{ position: "fixed", left: 0, top: 0, visibility: "hidden" }}
102
+ className="z-[var(--z-dropdown)] w-[360px] max-w-[calc(100vw-32px)] rounded-xl border border-border-default bg-surface-card shadow-lg outline-0"
103
+ >
104
+ <span className="absolute top-2 right-2 z-[1] flex">{tools}</span>
105
+ <div className="max-h-[min(70vh,560px)] overflow-y-auto p-3.5 [scrollbar-color:var(--border-strong)_transparent] [scrollbar-width:thin]">
106
+ {children}
107
+ </div>
108
+ </div>
109
+ );
110
+ }
111
+
112
+ /**
113
+ * The popover for desktop with the sidebar closed: an existing thread (opened
114
+ * from a highlight or a gutter counter) or a new comment's composer. A new
115
+ * comment opens it whether or not the sidebar is open.
116
+ */
117
+ export function CommentsPopover({
118
+ model,
119
+ sidebarOpen,
120
+ }: {
121
+ model: CommentsModel;
122
+ sidebarOpen: boolean;
123
+ }) {
124
+ const [draft, setDraft] = useAtom(draftAtom);
125
+ const thread = draft ? undefined : model.threads.find((entry) => entry.id === model.popoverId);
126
+ const view = thread ? model.views.get(thread.id) : undefined;
127
+ const reference = useReference(
128
+ draft ? draft.range : (view?.range ?? null),
129
+ draft ? null : (view?.scrollTarget ?? null),
130
+ );
131
+
132
+ const close = model.closePopover;
133
+ const discardDraft = () => setDraft(null);
134
+ const writing = draft !== null && draft.body.trim() !== "";
135
+ // Read when a request finishes, so a newer popover is not dismissed by an older resolve.
136
+ const shownId = useRef(model.popoverId);
137
+ shownId.current = model.popoverId;
138
+
139
+ if (draft) {
140
+ return (
141
+ <PopoverFrame
142
+ reference={reference}
143
+ onClose={discardDraft}
144
+ keepOpen={writing}
145
+ focusFrame={false}
146
+ label="New comment"
147
+ tools={<CtlButton icon="x" label="Discard comment" onClick={discardDraft} />}
148
+ >
149
+ <DraftThread model={model} sidebarOpen={sidebarOpen} reserveTools padded={false} />
150
+ </PopoverFrame>
151
+ );
152
+ }
153
+ if (!thread || thread.resolved) return null;
154
+
155
+ return (
156
+ <PopoverFrame
157
+ key={thread.id}
158
+ reference={reference}
159
+ onClose={close}
160
+ keepOpen={false}
161
+ focusFrame
162
+ label="Comment thread"
163
+ tools={
164
+ <>
165
+ {model.readOnly ? null : (
166
+ <CtlButton
167
+ tone="resolve"
168
+ icon="check"
169
+ label="Resolve thread"
170
+ disabled={model.writesDisabled}
171
+ onClick={() => {
172
+ void model.actions.setResolved(thread.id, true).then((saved) => {
173
+ if (saved && shownId.current === thread.id) close();
174
+ });
175
+ }}
176
+ />
177
+ )}
178
+ <CtlButton
179
+ icon="panel-right"
180
+ label="Open in sidebar"
181
+ onClick={() => model.openInSidebar(thread.id)}
182
+ />
183
+ <CtlButton icon="x" label="Close" onClick={close} />
184
+ </>
185
+ }
186
+ >
187
+ <Thread
188
+ key={`${model.path}:${thread.id}`}
189
+ thread={thread}
190
+ view={view}
191
+ active
192
+ variant="popover"
193
+ model={model}
194
+ />
195
+ </PopoverFrame>
196
+ );
197
+ }
@@ -0,0 +1,63 @@
1
+ import { AnimatePresence, motion } from "framer-motion";
2
+ import { useAtomValue } from "jotai";
3
+ import { useEffect } from "react";
4
+ import { TRANSITIONS } from "../motion";
5
+ import { CommentsPanel } from "./CommentsPanel";
6
+ import type { CommentsModel } from "./model";
7
+ import { draftAtom } from "./state";
8
+
9
+ /** Phone-width panel: rises from the bottom, 70% of the screen at most, list scrolls inside. Same header and threads as the sidebar. */
10
+ export function CommentsSheet({
11
+ model,
12
+ open,
13
+ onClose,
14
+ }: {
15
+ model: CommentsModel;
16
+ open: boolean;
17
+ onClose: () => void;
18
+ }) {
19
+ const hasDraft = useAtomValue(draftAtom) !== null;
20
+
21
+ // Escape discards a draft first (SelectionButton); the sheet closes on the next one.
22
+ useEffect(() => {
23
+ if (!open || hasDraft) return;
24
+ function onKeyDown(event: KeyboardEvent) {
25
+ if (event.key === "Escape") onClose();
26
+ }
27
+ window.addEventListener("keydown", onKeyDown);
28
+ return () => window.removeEventListener("keydown", onKeyDown);
29
+ }, [open, hasDraft, onClose]);
30
+
31
+ // Reserve scroll room so text at the end of the doc can be scrolled above the sheet.
32
+ useEffect(() => {
33
+ if (!open) return;
34
+ const previous = document.body.style.paddingBottom;
35
+ document.body.style.paddingBottom = "70vh";
36
+ return () => {
37
+ document.body.style.paddingBottom = previous;
38
+ };
39
+ }, [open]);
40
+
41
+ return (
42
+ <AnimatePresence>
43
+ {open ? (
44
+ <motion.aside
45
+ key="comments-sheet"
46
+ data-print-hide
47
+ aria-label="Comments"
48
+ initial={{ y: "100%" }}
49
+ animate={{ y: 0 }}
50
+ exit={{ y: "100%" }}
51
+ transition={TRANSITIONS.glide}
52
+ className="fixed inset-x-0 bottom-0 z-[var(--z-modal)] flex max-h-[70vh] flex-col rounded-t-[16px] bg-surface-card shadow-lg md:hidden"
53
+ >
54
+ <span
55
+ aria-hidden
56
+ className="mx-auto mt-2 mb-0.5 h-1 w-9 shrink-0 rounded-full bg-border-strong"
57
+ />
58
+ <CommentsPanel model={model} variant="sheet" onClose={onClose} />
59
+ </motion.aside>
60
+ ) : null}
61
+ </AnimatePresence>
62
+ );
63
+ }
@@ -0,0 +1,24 @@
1
+ import { CommentsPanel } from "./CommentsPanel";
2
+ import type { CommentsModel } from "./model";
3
+
4
+ export const COMMENTS_SIDEBAR_WIDTH = 348;
5
+
6
+ /**
7
+ * Desktop column: 348px, full height under the top bar, flush to the window's
8
+ * right edge. AppShell docks it beside `<main>` in a wrapper whose width opens
9
+ * and closes, so the doc column narrows to make room. The column itself keeps
10
+ * its full width throughout and is clipped by that wrapper: its contents slide
11
+ * in from the right edge without reflowing.
12
+ */
13
+ export function CommentsSidebar({ model, onClose }: { model: CommentsModel; onClose: () => void }) {
14
+ return (
15
+ <aside
16
+ data-print-hide
17
+ aria-label="Comments"
18
+ style={{ width: COMMENTS_SIDEBAR_WIDTH }}
19
+ className="sticky top-topbar flex h-[calc(100vh-var(--topbar-height))] shrink-0 flex-col border-l border-border-default bg-surface-page"
20
+ >
21
+ <CommentsPanel model={model} variant="sidebar" onClose={onClose} />
22
+ </aside>
23
+ );
24
+ }
@@ -0,0 +1,33 @@
1
+ import { forwardRef, type ButtonHTMLAttributes } from "react";
2
+ import { Icon } from "../ui/Icon";
3
+
4
+ export interface CtlButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
5
+ icon: string;
6
+ /** Accessible name; also the tooltip. */
7
+ label: string;
8
+ /** `resolve` turns green on hover: the checkmark that closes a thread. */
9
+ tone?: "plain" | "resolve";
10
+ }
11
+
12
+ /** The 26px borderless icon button used in thread headers and the panel header. */
13
+ export const CtlButton = forwardRef<HTMLButtonElement, CtlButtonProps>(function CtlButton(
14
+ { icon, label, tone = "plain", className, ...rest },
15
+ ref,
16
+ ) {
17
+ return (
18
+ <button
19
+ ref={ref}
20
+ type="button"
21
+ aria-label={label}
22
+ title={label}
23
+ className={
24
+ "inline-grid h-[26px] w-[26px] shrink-0 cursor-pointer place-items-center rounded-md border-0 bg-transparent p-0 text-text-subtle transition-colors hover:bg-surface-hover hover:text-text-heading disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:bg-transparent disabled:hover:text-text-subtle " +
25
+ (tone === "resolve" ? "hover:bg-status-ok-bg hover:text-status-ok-fg " : "") +
26
+ (className ?? "")
27
+ }
28
+ {...rest}
29
+ >
30
+ <Icon name={icon} size={15} />
31
+ </button>
32
+ );
33
+ });
@@ -0,0 +1,86 @@
1
+ import { useAtom, useSetAtom, useStore } from "jotai";
2
+ import type { CommentsModel } from "./model";
3
+ import { ReplyField } from "./ReplyField";
4
+ import {
5
+ activeThreadAtom,
6
+ draftAtom,
7
+ freshThreadAtom,
8
+ pendingSendsAtom,
9
+ popoverThreadAtom,
10
+ withPendingSend,
11
+ } from "./state";
12
+ import { Avatar, QuoteText } from "./Thread";
13
+
14
+ /** The new-comment composer: the selected quote and an empty field, in the popover or the sheet. */
15
+ export function DraftThread({
16
+ model,
17
+ sidebarOpen,
18
+ reserveTools,
19
+ padded,
20
+ }: {
21
+ model: CommentsModel;
22
+ sidebarOpen: boolean;
23
+ /** Leaves room for the popover's tool buttons beside the quote. */
24
+ reserveTools: boolean;
25
+ padded: boolean;
26
+ }) {
27
+ const [draft, setDraft] = useAtom(draftAtom);
28
+ const setActive = useSetAtom(activeThreadAtom);
29
+ const setPopover = useSetAtom(popoverThreadAtom);
30
+ const setFresh = useSetAtom(freshThreadAtom);
31
+ // Shared, so a composer that remounts mid-save (the sheet closed and reopened)
32
+ // still shows its send as pending and cannot post the comment twice.
33
+ const [pendingSends, setPendingSends] = useAtom(pendingSendsAtom);
34
+ const pendingKey = draft ? `draft:${draft.nonce}` : "";
35
+ const pending = pendingSends.has(pendingKey);
36
+ const setPending = (active: boolean) =>
37
+ setPendingSends((previous) => withPendingSend(previous, pendingKey, active));
38
+ const store = useStore();
39
+ if (!draft) return null;
40
+
41
+ async function submit() {
42
+ if (!draft) return;
43
+ // This draft, by the press that opened it: a later one must survive our completion.
44
+ const submitted = draft.nonce;
45
+ setPending(true);
46
+ const created = await model.actions.addThread(draft.anchor, draft.body);
47
+ setPending(false);
48
+ // On failure the draft, with its text, stays.
49
+ if (created === null) return;
50
+ // The user moved on to another comment (or another doc) while this one saved.
51
+ if (store.get(draftAtom)?.nonce !== submitted) return;
52
+ setFresh(created);
53
+ setDraft(null);
54
+ setActive(created);
55
+ // The popover follows the new thread unless the sidebar shows it.
56
+ if (!sidebarOpen) setPopover(created);
57
+ }
58
+
59
+ return (
60
+ <div
61
+ data-draft
62
+ className={"flex flex-col gap-3 " + (padded ? "pt-4 pr-3.5 pb-[18px] pl-4" : "")}
63
+ >
64
+ <div className={reserveTools ? "pr-[84px]" : ""}>
65
+ <QuoteText text={draft.anchor.quote} active />
66
+ </div>
67
+ <div className="grid grid-cols-[24px_1fr] items-end gap-x-2.5">
68
+ <Avatar author="human" />
69
+ <ReplyField
70
+ label="New comment"
71
+ sendLabel="Send comment"
72
+ placeholder={
73
+ model.writesDisabled ? "Close the section editor to comment" : "Add a comment…"
74
+ }
75
+ value={draft.body}
76
+ onChange={(body) => setDraft({ ...draft, body })}
77
+ onSubmit={() => void submit()}
78
+ onCancel={() => setDraft(null)}
79
+ disabled={model.writesDisabled}
80
+ pending={pending}
81
+ focusNonce={draft.nonce}
82
+ />
83
+ </div>
84
+ </div>
85
+ );
86
+ }
@@ -0,0 +1,121 @@
1
+ import { AnimatePresence, motion } from "framer-motion";
2
+ import { useAtomValue } from "jotai";
3
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { TRANSITIONS } from "../motion";
5
+ import { Icon } from "../ui/Icon";
6
+ import { findArticle } from "./dom";
7
+ import type { CommentsModel, ThreadView } from "./model";
8
+ import { layoutPins, pinLeft, type PinAnchor } from "./pins";
9
+ import { activeThreadAtom } from "./state";
10
+
11
+ const PIN_HEIGHT = 22;
12
+ const PIN_WIDTH_ESTIMATE = 44;
13
+ const LINE_HEIGHT = 24;
14
+
15
+ interface Pin {
16
+ id: string;
17
+ top: number;
18
+ left: number;
19
+ count: number;
20
+ }
21
+
22
+ /** The first line of the thread's anchor, or the start of its block. */
23
+ function anchorLine(view: ThreadView): { top: number; height: number } | null {
24
+ const rect = view.range?.getClientRects()[0];
25
+ if (rect && (rect.width > 0 || rect.height > 0)) return { top: rect.top, height: rect.height };
26
+ const block = view.scrollTarget?.getBoundingClientRect();
27
+ if (!block) return null;
28
+ return { top: block.top, height: Math.min(block.height, LINE_HEIGHT) };
29
+ }
30
+
31
+ /**
32
+ * Small pills at the right edge of the doc column, level with each open
33
+ * thread's anchor, showing its message count. Desktop with the sidebar closed
34
+ * only; a click opens the popover.
35
+ */
36
+ export function GutterCounters({ model }: { model: CommentsModel }) {
37
+ const containerRef = useRef<HTMLDivElement>(null);
38
+ const [pins, setPins] = useState<Pin[]>([]);
39
+ const activeId = useAtomValue(activeThreadAtom);
40
+ const { threads, views } = model;
41
+
42
+ const measure = useCallback(() => {
43
+ const origin = containerRef.current?.getBoundingClientRect();
44
+ const article = findArticle();
45
+ if (!origin || !article) {
46
+ setPins([]);
47
+ return;
48
+ }
49
+ const left = pinLeft(
50
+ article.getBoundingClientRect().right,
51
+ PIN_WIDTH_ESTIMATE,
52
+ window.innerWidth,
53
+ );
54
+ const counts = new Map<string, number>();
55
+ const anchors: PinAnchor[] = [];
56
+ for (const thread of threads) {
57
+ const view = thread.resolved ? undefined : views.get(thread.id);
58
+ const line = view ? anchorLine(view) : null;
59
+ if (!line) continue;
60
+ counts.set(thread.id, thread.messages.length);
61
+ anchors.push({ id: thread.id, top: line.top - origin.top, height: line.height });
62
+ }
63
+ setPins(
64
+ layoutPins(anchors, PIN_HEIGHT, 4).map((placed) => ({
65
+ id: placed.id,
66
+ top: placed.top,
67
+ left: left - origin.left,
68
+ count: counts.get(placed.id) ?? 0,
69
+ })),
70
+ );
71
+ }, [threads, views]);
72
+
73
+ useLayoutEffect(measure, [measure]);
74
+
75
+ // The doc reflows with the window, with late fonts and images, and with the
76
+ // sidebar closing; anything that moves an anchor resizes the article. The
77
+ // navigation sidebar and TOC rail shift the centred doc without resizing it,
78
+ // but they do resize the content area around it.
79
+ useEffect(() => {
80
+ const article = findArticle();
81
+ const contentArea = article?.closest("[data-content-area]") ?? null;
82
+ const observer = article ? new ResizeObserver(measure) : null;
83
+ if (article) observer?.observe(article);
84
+ if (contentArea) observer?.observe(contentArea);
85
+ window.addEventListener("resize", measure);
86
+ return () => {
87
+ observer?.disconnect();
88
+ window.removeEventListener("resize", measure);
89
+ };
90
+ }, [measure]);
91
+
92
+ return (
93
+ <div ref={containerRef} data-print-hide className="pointer-events-none absolute top-0 left-0">
94
+ <AnimatePresence>
95
+ {pins.map((pin) => (
96
+ <motion.button
97
+ key={pin.id}
98
+ initial={{ opacity: 0, scale: 0.85 }}
99
+ animate={{ opacity: 1, scale: 1 }}
100
+ exit={{ opacity: 0, transition: TRANSITIONS.fast }}
101
+ transition={TRANSITIONS.snap}
102
+ type="button"
103
+ data-comments-keep
104
+ aria-label={`Open comment thread, ${pin.count} ${pin.count === 1 ? "message" : "messages"}`}
105
+ onClick={() => model.showPopover(pin.id)}
106
+ style={{ top: pin.top, left: pin.left, height: PIN_HEIGHT }}
107
+ className={
108
+ "pointer-events-auto absolute z-[1] inline-flex cursor-pointer items-center gap-1 rounded-full border px-[7px] font-sans text-[11.5px] leading-none font-semibold tabular-nums " +
109
+ (pin.id === activeId
110
+ ? "border-border-strong bg-surface-hover text-text-heading"
111
+ : "border-border-default bg-surface-card text-text-muted hover:text-text-heading")
112
+ }
113
+ >
114
+ <Icon name="message-square" size={12} />
115
+ {pin.count}
116
+ </motion.button>
117
+ ))}
118
+ </AnimatePresence>
119
+ </div>
120
+ );
121
+ }
@@ -0,0 +1,98 @@
1
+ import { useEffect, useLayoutEffect, useRef, type KeyboardEvent } from "react";
2
+ import { Icon } from "../ui/Icon";
3
+ import { MAX_MESSAGE_BODY } from "./anchor";
4
+ import { canSend, fieldHeight, FIELD_MIN_HEIGHT } from "./drafts";
5
+
6
+ /**
7
+ * One-line field that grows to 120px, with a round send button. Enter sends,
8
+ * Shift+Enter adds a line, Escape cancels when `onCancel` is given. Controlled:
9
+ * the caller keeps the text when a send fails.
10
+ */
11
+ export function ReplyField({
12
+ value,
13
+ onChange,
14
+ onSubmit,
15
+ onCancel,
16
+ placeholder,
17
+ label,
18
+ sendLabel,
19
+ disabled,
20
+ pending,
21
+ focusNonce,
22
+ }: {
23
+ value: string;
24
+ onChange: (next: string) => void;
25
+ onSubmit: () => void;
26
+ onCancel?: () => void;
27
+ placeholder: string;
28
+ label: string;
29
+ sendLabel: string;
30
+ disabled: boolean;
31
+ pending: boolean;
32
+ /** Focuses the field (caret at the end) on mount and whenever this changes, when defined. */
33
+ focusNonce?: number;
34
+ }) {
35
+ const ref = useRef<HTMLTextAreaElement>(null);
36
+
37
+ useEffect(() => {
38
+ const field = ref.current;
39
+ if (focusNonce === undefined || !field) return;
40
+ field.focus({ preventScroll: true });
41
+ field.setSelectionRange(field.value.length, field.value.length);
42
+ }, [focusNonce]);
43
+
44
+ useLayoutEffect(() => {
45
+ const field = ref.current;
46
+ if (!field) return;
47
+ field.style.height = `${FIELD_MIN_HEIGHT}px`;
48
+ field.style.height = `${fieldHeight(field.scrollHeight)}px`;
49
+ }, [value]);
50
+
51
+ const ready = canSend(value, disabled, pending);
52
+
53
+ function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
54
+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
55
+ event.preventDefault();
56
+ if (ready) onSubmit();
57
+ } else if (event.key === "Escape" && onCancel) {
58
+ event.preventDefault();
59
+ event.stopPropagation();
60
+ onCancel();
61
+ }
62
+ }
63
+
64
+ return (
65
+ <div className="group/field flex items-end gap-1.5 rounded-[9px] border border-border-default bg-surface-card py-[5px] pr-[5px] pl-[11px] focus-within:border-border-accent">
66
+ <textarea
67
+ ref={ref}
68
+ data-bare-focus
69
+ aria-label={label}
70
+ value={value}
71
+ rows={1}
72
+ maxLength={MAX_MESSAGE_BODY}
73
+ disabled={disabled}
74
+ // Locked while a send is in flight: text typed then would be cleared with the sent draft.
75
+ readOnly={pending}
76
+ placeholder={placeholder}
77
+ onChange={(event) => onChange(event.target.value)}
78
+ onKeyDown={handleKeyDown}
79
+ className="h-6 max-h-[120px] min-w-0 flex-1 resize-none rounded-sm border-0 bg-transparent px-0 py-0.5 font-sans text-[13.5px] leading-normal font-medium text-text-body caret-surface-accent outline-0 placeholder:text-text-subtle disabled:cursor-not-allowed disabled:opacity-60"
80
+ />
81
+ <button
82
+ type="button"
83
+ aria-label={sendLabel}
84
+ title={pending ? "Saving…" : sendLabel}
85
+ disabled={!ready}
86
+ onClick={onSubmit}
87
+ className={
88
+ "grid h-6 w-6 shrink-0 cursor-pointer place-items-center rounded-full border-0 p-0 transition-[color,background-color,scale] duration-150 ease-out enabled:active:scale-90 disabled:cursor-not-allowed motion-reduce:enabled:active:scale-100 " +
89
+ (ready
90
+ ? "bg-surface-accent text-text-inverse"
91
+ : "bg-surface-hover text-text-subtle group-focus-within/field:bg-surface-accent group-focus-within/field:text-text-inverse")
92
+ }
93
+ >
94
+ <Icon name="arrow-up" size={13} />
95
+ </button>
96
+ </div>
97
+ );
98
+ }