@karimsa/mdxserve 0.5.1 → 0.6.0-rc.1
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.
- package/README.md +3 -0
- package/client/DocView.tsx +3 -8
- package/client/ListingView.tsx +3 -3
- package/client/Settings.tsx +26 -21
- package/client/app.css +20 -0
- package/client/comments/CommentsPanel.tsx +163 -0
- package/client/comments/CommentsPopover.tsx +197 -0
- package/client/comments/CommentsSheet.tsx +63 -0
- package/client/comments/CommentsSidebar.tsx +18 -0
- package/client/comments/CtlButton.tsx +33 -0
- package/client/comments/DraftThread.tsx +83 -0
- package/client/comments/GutterCounters.tsx +113 -0
- package/client/comments/ReplyField.tsx +98 -0
- package/client/comments/SelectionButton.tsx +142 -0
- package/client/comments/Thread.tsx +278 -0
- package/client/comments/anchor.ts +204 -0
- package/client/comments/data.ts +98 -0
- package/client/comments/dom.ts +212 -0
- package/client/comments/drafts.ts +36 -0
- package/client/comments/highlights.ts +83 -0
- package/client/comments/model.ts +241 -0
- package/client/comments/pins.ts +37 -0
- package/client/comments/self-writes.ts +22 -0
- package/client/comments/state.ts +60 -0
- package/client/comments/time.ts +21 -0
- package/client/hooks.ts +19 -0
- package/client/platform.ts +8 -0
- package/client/router.ts +5 -0
- package/client/shell/AppShell.tsx +60 -14
- package/client/shell/StandaloneShell.tsx +3 -2
- package/client/shell/TopBar.tsx +25 -0
- package/client/ui/ConfirmDeleteDialog.tsx +1 -1
- package/client/ui/Toast.tsx +5 -1
- package/client/ui/icon-set.ts +10 -0
- package/dist/cli.js +872 -229
- package/package.json +1 -1
- package/skills/mdxserve/SKILL.md +86 -0
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { useAtom } from "jotai";
|
|
2
|
+
import { useEffect, useRef, useState, type ReactNode } from "react";
|
|
3
|
+
import type { CommentMessage, CommentThread } from "../../src/comments/schema";
|
|
4
|
+
import { Icon } from "../ui/Icon";
|
|
5
|
+
import { CtlButton } from "./CtlButton";
|
|
6
|
+
import { replyDraftOf, withReplyDraft } from "./drafts";
|
|
7
|
+
import type { CommentsModel, ThreadView } from "./model";
|
|
8
|
+
import { ReplyField } from "./ReplyField";
|
|
9
|
+
import { pendingReplyKey, pendingSendsAtom, replyDraftsAtom, withPendingSend } from "./state";
|
|
10
|
+
import { relativeTime } from "./time";
|
|
11
|
+
|
|
12
|
+
/** Where a thread is drawn: a sidebar row, the sheet's row, or the popover's body. */
|
|
13
|
+
export type ThreadVariant = "sidebar" | "sheet" | "popover";
|
|
14
|
+
|
|
15
|
+
const ACTIVE_QUOTE = "bg-[color-mix(in_oklab,var(--status-warn-fg)_32%,var(--status-warn-bg))]";
|
|
16
|
+
|
|
17
|
+
export function Avatar({ author }: { author: CommentMessage["author"] }) {
|
|
18
|
+
const agent = author === "agent";
|
|
19
|
+
return (
|
|
20
|
+
<span
|
|
21
|
+
aria-hidden
|
|
22
|
+
className={
|
|
23
|
+
"grid h-6 w-6 place-items-center rounded-full " +
|
|
24
|
+
(agent ? "bg-surface-accent-soft text-text-accent" : "bg-surface-hover text-text-muted")
|
|
25
|
+
}
|
|
26
|
+
>
|
|
27
|
+
<Icon name={agent ? "sparkles" : "user"} size={13} />
|
|
28
|
+
</span>
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The quoted text, in the doc highlight's amber, on one line. */
|
|
33
|
+
export function QuoteText({ text, active }: { text: string; active: boolean }) {
|
|
34
|
+
return (
|
|
35
|
+
<span className="block truncate text-[12.5px] leading-[1.6] text-text-body">
|
|
36
|
+
<mark className={"text-inherit " + (active ? ACTIVE_QUOTE : "bg-status-warn-bg")}>
|
|
37
|
+
{text}
|
|
38
|
+
</mark>
|
|
39
|
+
</span>
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function Message({
|
|
44
|
+
message,
|
|
45
|
+
last,
|
|
46
|
+
reserveTools,
|
|
47
|
+
canEdit,
|
|
48
|
+
editDisabled,
|
|
49
|
+
onEdit,
|
|
50
|
+
}: {
|
|
51
|
+
message: CommentMessage;
|
|
52
|
+
last: boolean;
|
|
53
|
+
/** Leaves room for the popover's tool buttons beside the first header. */
|
|
54
|
+
reserveTools: boolean;
|
|
55
|
+
canEdit: boolean;
|
|
56
|
+
editDisabled: boolean;
|
|
57
|
+
onEdit: (body: string) => Promise<boolean>;
|
|
58
|
+
}) {
|
|
59
|
+
const [editing, setEditing] = useState(false);
|
|
60
|
+
const [draft, setDraft] = useState(message.body);
|
|
61
|
+
const [pending, setPending] = useState(false);
|
|
62
|
+
const agent = message.author === "agent";
|
|
63
|
+
|
|
64
|
+
async function save() {
|
|
65
|
+
setPending(true);
|
|
66
|
+
const saved = await onEdit(draft);
|
|
67
|
+
setPending(false);
|
|
68
|
+
if (saved) setEditing(false);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return (
|
|
72
|
+
<div className="group relative grid grid-cols-[24px_1fr] gap-x-2.5 not-first:mt-3.5">
|
|
73
|
+
{last ? null : (
|
|
74
|
+
<span
|
|
75
|
+
aria-hidden
|
|
76
|
+
className="absolute top-7 -bottom-3 left-[11.5px] w-px bg-border-default"
|
|
77
|
+
/>
|
|
78
|
+
)}
|
|
79
|
+
<Avatar author={message.author} />
|
|
80
|
+
<div className="min-w-0">
|
|
81
|
+
<div
|
|
82
|
+
className={
|
|
83
|
+
"flex items-baseline gap-[7px] pt-[3px] text-[12.5px] leading-[1.3] " +
|
|
84
|
+
(reserveTools ? "pr-[84px]" : "")
|
|
85
|
+
}
|
|
86
|
+
>
|
|
87
|
+
<span className={"font-bold " + (agent ? "text-text-accent" : "text-text-heading")}>
|
|
88
|
+
{agent ? "Agent" : "You"}
|
|
89
|
+
</span>
|
|
90
|
+
<time
|
|
91
|
+
className="text-[11.5px] text-text-subtle tabular-nums"
|
|
92
|
+
dateTime={message.createdAt}
|
|
93
|
+
title={message.createdAt ? new Date(message.createdAt).toLocaleString() : undefined}
|
|
94
|
+
>
|
|
95
|
+
{relativeTime(message.createdAt)}
|
|
96
|
+
{message.editedAt ? " · edited" : ""}
|
|
97
|
+
</time>
|
|
98
|
+
{canEdit && !editing ? (
|
|
99
|
+
<button
|
|
100
|
+
type="button"
|
|
101
|
+
disabled={editDisabled}
|
|
102
|
+
aria-label="Edit comment"
|
|
103
|
+
onClick={() => {
|
|
104
|
+
setDraft(message.body);
|
|
105
|
+
setEditing(true);
|
|
106
|
+
}}
|
|
107
|
+
className="ml-auto inline-flex cursor-pointer items-center gap-1 rounded-sm border-0 bg-transparent p-0 text-[11.5px] font-semibold text-text-subtle opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 hover:text-text-heading focus-visible:opacity-100 disabled:cursor-not-allowed disabled:opacity-0 group-hover:disabled:opacity-45 [@media(hover:none)]:opacity-100"
|
|
108
|
+
>
|
|
109
|
+
<Icon name="pencil" size={11} />
|
|
110
|
+
Edit
|
|
111
|
+
</button>
|
|
112
|
+
) : null}
|
|
113
|
+
</div>
|
|
114
|
+
{editing ? (
|
|
115
|
+
<div className="mt-1.5" data-comment-edit>
|
|
116
|
+
<ReplyField
|
|
117
|
+
label="Edit comment"
|
|
118
|
+
sendLabel="Save comment"
|
|
119
|
+
placeholder=""
|
|
120
|
+
value={draft}
|
|
121
|
+
onChange={setDraft}
|
|
122
|
+
onSubmit={() => void save()}
|
|
123
|
+
onCancel={() => setEditing(false)}
|
|
124
|
+
disabled={editDisabled}
|
|
125
|
+
pending={pending}
|
|
126
|
+
focusNonce={0}
|
|
127
|
+
/>
|
|
128
|
+
</div>
|
|
129
|
+
) : (
|
|
130
|
+
<p className="m-0 mt-[3px] text-[13.5px] leading-[1.55] break-words whitespace-pre-wrap text-text-body">
|
|
131
|
+
{message.body}
|
|
132
|
+
</p>
|
|
133
|
+
)}
|
|
134
|
+
</div>
|
|
135
|
+
</div>
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* One thread as a conversation timeline: the quote and a resolve (or reopen)
|
|
141
|
+
* checkmark, the messages, and on the active thread a reply field.
|
|
142
|
+
*/
|
|
143
|
+
export function Thread({
|
|
144
|
+
thread,
|
|
145
|
+
view,
|
|
146
|
+
active,
|
|
147
|
+
variant,
|
|
148
|
+
model,
|
|
149
|
+
}: {
|
|
150
|
+
thread: CommentThread;
|
|
151
|
+
view: ThreadView | undefined;
|
|
152
|
+
active: boolean;
|
|
153
|
+
variant: ThreadVariant;
|
|
154
|
+
model: CommentsModel;
|
|
155
|
+
}) {
|
|
156
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
157
|
+
const [drafts, setDrafts] = useAtom(replyDraftsAtom);
|
|
158
|
+
const [pendingSends, setPendingSends] = useAtom(pendingSendsAtom);
|
|
159
|
+
const replyKey = pendingReplyKey(model.path, thread.id);
|
|
160
|
+
const replying = pendingSends.has(replyKey);
|
|
161
|
+
const setReplying = (active: boolean) =>
|
|
162
|
+
setPendingSends((previous) => withPendingSend(previous, replyKey, active));
|
|
163
|
+
const [resolving, setResolving] = useState(false);
|
|
164
|
+
const { readOnly, writesDisabled, actions } = model;
|
|
165
|
+
const popover = variant === "popover";
|
|
166
|
+
const reply = replyDraftOf(drafts, thread.id);
|
|
167
|
+
|
|
168
|
+
useEffect(() => {
|
|
169
|
+
if (active && !popover) ref.current?.scrollIntoView({ block: "nearest" });
|
|
170
|
+
}, [active, popover]);
|
|
171
|
+
|
|
172
|
+
async function sendReply() {
|
|
173
|
+
setReplying(true);
|
|
174
|
+
const submitted = reply;
|
|
175
|
+
const saved = await actions.reply(thread.id, submitted);
|
|
176
|
+
setReplying(false);
|
|
177
|
+
// Text typed while the request ran stays.
|
|
178
|
+
if (saved)
|
|
179
|
+
setDrafts((previous) =>
|
|
180
|
+
replyDraftOf(previous, thread.id) === submitted
|
|
181
|
+
? withReplyDraft(previous, thread.id, "")
|
|
182
|
+
: previous,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function toggleResolved() {
|
|
187
|
+
setResolving(true);
|
|
188
|
+
await actions.setResolved(thread.id, !thread.resolved);
|
|
189
|
+
setResolving(false);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const state = view?.resolution.state;
|
|
193
|
+
const showReply = active && !readOnly && !thread.resolved;
|
|
194
|
+
const note =
|
|
195
|
+
state === "section"
|
|
196
|
+
? "Original text not found. Showing on the section."
|
|
197
|
+
: state === "detached"
|
|
198
|
+
? "Original section not found."
|
|
199
|
+
: null;
|
|
200
|
+
|
|
201
|
+
let toolbar: ReactNode = null;
|
|
202
|
+
if (!popover && !readOnly) {
|
|
203
|
+
toolbar = (
|
|
204
|
+
<CtlButton
|
|
205
|
+
tone="resolve"
|
|
206
|
+
icon={thread.resolved ? "rotate-ccw" : "check"}
|
|
207
|
+
label={thread.resolved ? "Reopen thread" : "Resolve thread"}
|
|
208
|
+
disabled={writesDisabled || resolving}
|
|
209
|
+
onClick={() => void toggleResolved()}
|
|
210
|
+
/>
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return (
|
|
215
|
+
<div
|
|
216
|
+
ref={ref}
|
|
217
|
+
data-thread-id={thread.id}
|
|
218
|
+
data-active={active || undefined}
|
|
219
|
+
onClick={
|
|
220
|
+
popover
|
|
221
|
+
? undefined
|
|
222
|
+
: (event) => {
|
|
223
|
+
if (!(event.target as Element).closest("textarea, button, a")) {
|
|
224
|
+
model.selectThread(thread.id);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
className={
|
|
229
|
+
"flex flex-col gap-3 " +
|
|
230
|
+
(popover ? "" : "pt-4 pr-3.5 pb-[18px] pl-4 ") +
|
|
231
|
+
(variant === "sidebar" && active ? "bg-surface-card" : "")
|
|
232
|
+
}
|
|
233
|
+
>
|
|
234
|
+
{popover ? null : (
|
|
235
|
+
<div className="flex items-center gap-2">
|
|
236
|
+
<button
|
|
237
|
+
type="button"
|
|
238
|
+
title="Show in the doc"
|
|
239
|
+
onClick={() => model.selectThread(thread.id)}
|
|
240
|
+
className="m-0 min-w-0 flex-1 cursor-pointer border-0 bg-transparent p-0 text-left"
|
|
241
|
+
>
|
|
242
|
+
<QuoteText text={thread.anchor.quote} active={active} />
|
|
243
|
+
</button>
|
|
244
|
+
{toolbar}
|
|
245
|
+
</div>
|
|
246
|
+
)}
|
|
247
|
+
{note ? <p className="m-0 text-xs text-status-warn-fg">{note}</p> : null}
|
|
248
|
+
<div>
|
|
249
|
+
{thread.messages.map((message, index) => (
|
|
250
|
+
<Message
|
|
251
|
+
key={message.id}
|
|
252
|
+
message={message}
|
|
253
|
+
last={index === thread.messages.length - 1}
|
|
254
|
+
reserveTools={popover && index === 0}
|
|
255
|
+
canEdit={!readOnly && message.author === "human"}
|
|
256
|
+
editDisabled={writesDisabled}
|
|
257
|
+
onEdit={async (body) => (await actions.edit(thread.id, message.id, body)) !== null}
|
|
258
|
+
/>
|
|
259
|
+
))}
|
|
260
|
+
</div>
|
|
261
|
+
{showReply ? (
|
|
262
|
+
<div className="grid grid-cols-[24px_1fr] items-end gap-x-2.5">
|
|
263
|
+
<Avatar author="human" />
|
|
264
|
+
<ReplyField
|
|
265
|
+
label="Reply"
|
|
266
|
+
sendLabel="Send reply"
|
|
267
|
+
placeholder={writesDisabled ? "Close the section editor to reply" : "Reply…"}
|
|
268
|
+
value={reply}
|
|
269
|
+
onChange={(next) => setDrafts((previous) => withReplyDraft(previous, thread.id, next))}
|
|
270
|
+
onSubmit={() => void sendReply()}
|
|
271
|
+
disabled={writesDisabled}
|
|
272
|
+
pending={replying}
|
|
273
|
+
/>
|
|
274
|
+
</div>
|
|
275
|
+
) : null}
|
|
276
|
+
</div>
|
|
277
|
+
);
|
|
278
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure anchor logic: no DOM types, so it runs under plain Node in tests.
|
|
3
|
+
*
|
|
4
|
+
* `client/` may only `import type` from `src/`, so the limits and
|
|
5
|
+
* `normalizeText` below repeat `src/comments/schema.ts` and
|
|
6
|
+
* `src/comments/anchor.ts`; tests/client/comments-limits.test.ts asserts the
|
|
7
|
+
* two copies agree.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const MAX_ANCHOR_TEXT = 500;
|
|
11
|
+
export const MAX_ANCHOR_HEADING = 300;
|
|
12
|
+
export const MAX_MESSAGE_BODY = 4000;
|
|
13
|
+
|
|
14
|
+
/** Collapse runs of whitespace to one space, then trim. Must match `src/comments/anchor.ts`. */
|
|
15
|
+
export function normalizeText(text: string): string {
|
|
16
|
+
return text.replace(/\s+/g, " ").trim();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The comparable form of a heading's text: normalized and cut to the schema's
|
|
21
|
+
* heading limit, so a very long heading still matches its stored anchor.
|
|
22
|
+
*/
|
|
23
|
+
export function headingKey(text: string): string {
|
|
24
|
+
return normalizeText(text).slice(0, MAX_ANCHOR_HEADING).trimEnd();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface AnchorFields {
|
|
28
|
+
heading: string | null;
|
|
29
|
+
block: string;
|
|
30
|
+
quote: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ── offset mapping ──────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
export interface NormalizedText {
|
|
36
|
+
/** `normalizeText(nodes.join(""))`. */
|
|
37
|
+
text: string;
|
|
38
|
+
/** For each normalized character, its index in the joined raw text. */
|
|
39
|
+
rawIndex: number[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Normalizes the concatenated text nodes and remembers where each character came from. */
|
|
43
|
+
export function normalizeWithMap(nodes: readonly string[]): NormalizedText {
|
|
44
|
+
const raw = nodes.join("");
|
|
45
|
+
let text = "";
|
|
46
|
+
const rawIndex: number[] = [];
|
|
47
|
+
let pendingSpace = -1;
|
|
48
|
+
for (let index = 0; index < raw.length; index++) {
|
|
49
|
+
const char = raw[index];
|
|
50
|
+
if (/\s/.test(char)) {
|
|
51
|
+
if (text.length > 0 && pendingSpace === -1) pendingSpace = index;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (pendingSpace !== -1) {
|
|
55
|
+
text += " ";
|
|
56
|
+
rawIndex.push(pendingSpace);
|
|
57
|
+
pendingSpace = -1;
|
|
58
|
+
}
|
|
59
|
+
text += char;
|
|
60
|
+
rawIndex.push(index);
|
|
61
|
+
}
|
|
62
|
+
return { text, rawIndex };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface NodePoint {
|
|
66
|
+
node: number;
|
|
67
|
+
offset: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface NodeRange {
|
|
71
|
+
start: NodePoint;
|
|
72
|
+
end: NodePoint;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function pointAt(nodes: readonly string[], rawIndex: number): NodePoint {
|
|
76
|
+
let remaining = rawIndex;
|
|
77
|
+
for (let node = 0; node < nodes.length; node++) {
|
|
78
|
+
if (remaining < nodes[node].length) return { node, offset: remaining };
|
|
79
|
+
remaining -= nodes[node].length;
|
|
80
|
+
}
|
|
81
|
+
return { node: Math.max(0, nodes.length - 1), offset: nodes[nodes.length - 1]?.length ?? 0 };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Maps the normalized-text span [start, end) back to text-node points. The start
|
|
86
|
+
* sits on the first character of the span and the end just after its last one, so
|
|
87
|
+
* a boundary between two nodes never gets ambiguous. Null for an empty or
|
|
88
|
+
* out-of-bounds span.
|
|
89
|
+
*/
|
|
90
|
+
export function mapNormalizedRange(
|
|
91
|
+
nodes: readonly string[],
|
|
92
|
+
start: number,
|
|
93
|
+
end: number,
|
|
94
|
+
): NodeRange | null {
|
|
95
|
+
const { text, rawIndex } = normalizeWithMap(nodes);
|
|
96
|
+
if (start < 0 || end > text.length || start >= end) return null;
|
|
97
|
+
const first = pointAt(nodes, rawIndex[start]);
|
|
98
|
+
const last = pointAt(nodes, rawIndex[end - 1]);
|
|
99
|
+
return { start: first, end: { node: last.node, offset: last.offset + 1 } };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── capture ─────────────────────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
export interface BlockDescription {
|
|
105
|
+
/** Heading text of the block's section (already `headingKey`ed), or null before the first heading. */
|
|
106
|
+
heading: string | null;
|
|
107
|
+
/** The text-node strings of the block, in document order. */
|
|
108
|
+
nodes: string[];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface SelectionDescription {
|
|
112
|
+
blockIndex: number;
|
|
113
|
+
start: NodePoint;
|
|
114
|
+
/** Null clips the selection to the end of the block. */
|
|
115
|
+
end: NodePoint | null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function rawOffset(nodes: readonly string[], point: NodePoint): number {
|
|
119
|
+
let total = 0;
|
|
120
|
+
for (let node = 0; node < point.node && node < nodes.length; node++) total += nodes[node].length;
|
|
121
|
+
return total + point.offset;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The anchor for a selection, clipped to the block holding its start. Null when it has no text. */
|
|
125
|
+
export function captureAnchor(
|
|
126
|
+
blocks: readonly BlockDescription[],
|
|
127
|
+
selection: SelectionDescription,
|
|
128
|
+
): AnchorFields | null {
|
|
129
|
+
const block = blocks[selection.blockIndex];
|
|
130
|
+
if (!block) return null;
|
|
131
|
+
const raw = block.nodes.join("");
|
|
132
|
+
const startRaw = rawOffset(block.nodes, selection.start);
|
|
133
|
+
const endRaw = selection.end ? rawOffset(block.nodes, selection.end) : raw.length;
|
|
134
|
+
if (endRaw <= startRaw) return null;
|
|
135
|
+
|
|
136
|
+
const quote = normalizeText(raw.slice(startRaw, endRaw)).slice(0, MAX_ANCHOR_TEXT).trimEnd();
|
|
137
|
+
if (!quote) return null;
|
|
138
|
+
const blockText = normalizeText(raw).slice(-MAX_ANCHOR_TEXT).trimStart();
|
|
139
|
+
return { heading: block.heading, block: blockText, quote };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ── resolve ─────────────────────────────────────────────────────────────────
|
|
143
|
+
|
|
144
|
+
export interface ResolveBlock {
|
|
145
|
+
/** Normalized text of the block. */
|
|
146
|
+
text: string;
|
|
147
|
+
/** Index into `headings` of the block's section, or -1 before the first heading. */
|
|
148
|
+
section: number;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface ResolveHeading {
|
|
152
|
+
/** `headingKey` of the heading's text. */
|
|
153
|
+
key: string;
|
|
154
|
+
/** Index into `blocks` of the heading's own block. */
|
|
155
|
+
block: number;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface ResolveIndex {
|
|
159
|
+
headings: readonly ResolveHeading[];
|
|
160
|
+
blocks: readonly ResolveBlock[];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export type Resolution =
|
|
164
|
+
| { state: "exact"; block: number; start: number; end: number }
|
|
165
|
+
| { state: "block"; block: number }
|
|
166
|
+
/** `block` is the heading's block, or -1 for the top of the article. */
|
|
167
|
+
| { state: "section"; block: number }
|
|
168
|
+
| { state: "detached" };
|
|
169
|
+
|
|
170
|
+
export type AnchorState = Resolution["state"];
|
|
171
|
+
|
|
172
|
+
/** Where the thread sorts in the document: a block index, -1 for the top, Infinity when detached. */
|
|
173
|
+
export function resolutionPosition(resolution: Resolution): number {
|
|
174
|
+
return resolution.state === "detached" ? Infinity : resolution.block;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Finds the anchor in the document: exact, whole block, section heading, or detached. */
|
|
178
|
+
export function resolveAnchor(anchor: AnchorFields, index: ResolveIndex): Resolution {
|
|
179
|
+
const wantedBlock = normalizeText(anchor.block);
|
|
180
|
+
const wantedQuote = normalizeText(anchor.quote);
|
|
181
|
+
const sections: number[] = [];
|
|
182
|
+
if (anchor.heading === null) {
|
|
183
|
+
sections.push(-1);
|
|
184
|
+
} else {
|
|
185
|
+
const wantedHeading = headingKey(anchor.heading);
|
|
186
|
+
index.headings.forEach((heading, position) => {
|
|
187
|
+
if (heading.key === wantedHeading) sections.push(position);
|
|
188
|
+
});
|
|
189
|
+
if (sections.length === 0) return { state: "detached" };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
for (const section of sections) {
|
|
193
|
+
for (let position = 0; position < index.blocks.length; position++) {
|
|
194
|
+
const block = index.blocks[position];
|
|
195
|
+
if (block.section !== section || !block.text.endsWith(wantedBlock)) continue;
|
|
196
|
+
const found = block.text.indexOf(wantedQuote);
|
|
197
|
+
if (found === -1) return { state: "block", block: position };
|
|
198
|
+
return { state: "exact", block: position, start: found, end: found + wantedQuote.length };
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const headingBlock = sections[0] === -1 ? -1 : index.headings[sections[0]].block;
|
|
203
|
+
return { state: "section", block: headingBlock };
|
|
204
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { useQuery } from "@tanstack/react-query";
|
|
2
|
+
import { useMemo } from "react";
|
|
3
|
+
import type { CommentThread } from "../../src/comments/schema";
|
|
4
|
+
import { queryClient, trpc, trpcClient } from "../api";
|
|
5
|
+
import { pushToast } from "../ui/Toast";
|
|
6
|
+
import { markSelfWrite } from "./self-writes";
|
|
7
|
+
|
|
8
|
+
const NO_THREADS: CommentThread[] = [];
|
|
9
|
+
|
|
10
|
+
/** The doc's threads, from the same query the `mdxserve:doc-changed` handler invalidates. */
|
|
11
|
+
export function useDocThreads(path: string | null): { threads: CommentThread[]; loaded: boolean } {
|
|
12
|
+
const { data } = useQuery(
|
|
13
|
+
trpc.getDocComments.queryOptions({ path: path ?? "" }, { enabled: path !== null }),
|
|
14
|
+
);
|
|
15
|
+
return useMemo(
|
|
16
|
+
() => ({ threads: data?.threads ?? NO_THREADS, loaded: data !== undefined }),
|
|
17
|
+
[data],
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function errorText(error: unknown): string {
|
|
22
|
+
return error instanceof Error && error.message ? error.message : "Could not save the comment";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CommentActions {
|
|
26
|
+
/** Resolves to the id of the thread it created, or null when the write failed. */
|
|
27
|
+
addThread(anchor: CommentAnchorInput, body: string): Promise<string | null>;
|
|
28
|
+
reply(threadId: string, body: string): Promise<CommentThread[] | null>;
|
|
29
|
+
edit(threadId: string, messageId: string, body: string): Promise<CommentThread[] | null>;
|
|
30
|
+
setResolved(threadId: string, resolved: boolean): Promise<CommentThread[] | null>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type CommentAnchorInput = { heading: string | null; block: string; quote: string };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Runs one comment mutation. The response carries the full thread list, which
|
|
37
|
+
* replaces the cached one at once. A failure becomes a danger toast with the
|
|
38
|
+
* server's message and resolves to null, so callers keep their draft text.
|
|
39
|
+
*/
|
|
40
|
+
async function runWrite(
|
|
41
|
+
path: string,
|
|
42
|
+
call: () => Promise<{ threads: CommentThread[] }>,
|
|
43
|
+
): Promise<CommentThread[] | null> {
|
|
44
|
+
markSelfWrite(path);
|
|
45
|
+
try {
|
|
46
|
+
const result = await call();
|
|
47
|
+
markSelfWrite(path);
|
|
48
|
+
queryClient.setQueryData(trpc.getDocComments.queryKey({ path }), (cached) => ({
|
|
49
|
+
diagnostics: cached?.diagnostics ?? [],
|
|
50
|
+
threads: result.threads,
|
|
51
|
+
}));
|
|
52
|
+
return result.threads;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
pushToast({ tone: "danger", text: errorText(error), dedupeKey: "comment-error" });
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Each response is a snapshot of the whole thread list. Two writes in flight
|
|
60
|
+
// for one doc could land out of order and roll the cache back, so a doc's
|
|
61
|
+
// writes run one after another.
|
|
62
|
+
const writeQueues = new Map<string, Promise<unknown>>();
|
|
63
|
+
|
|
64
|
+
function write(
|
|
65
|
+
path: string,
|
|
66
|
+
call: () => Promise<{ threads: CommentThread[] }>,
|
|
67
|
+
): Promise<CommentThread[] | null> {
|
|
68
|
+
const previous = writeQueues.get(path) ?? Promise.resolve();
|
|
69
|
+
// runWrite never rejects, so the chain cannot break.
|
|
70
|
+
const run = previous.then(() => runWrite(path, call));
|
|
71
|
+
writeQueues.set(path, run);
|
|
72
|
+
void run.then(() => {
|
|
73
|
+
if (writeQueues.get(path) === run) writeQueues.delete(path);
|
|
74
|
+
});
|
|
75
|
+
return run;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function commentActions(path: string): CommentActions {
|
|
79
|
+
return {
|
|
80
|
+
addThread: async (anchor, body) => {
|
|
81
|
+
// The server names the thread it created; the returned list can also hold
|
|
82
|
+
// threads someone else added since this tab last fetched.
|
|
83
|
+
let created: string | null = null;
|
|
84
|
+
const threads = await write(path, async () => {
|
|
85
|
+
const result = await trpcClient.addCommentThread.mutate({ path, anchor, body });
|
|
86
|
+
created = result.threadId;
|
|
87
|
+
return result;
|
|
88
|
+
});
|
|
89
|
+
return threads ? created : null;
|
|
90
|
+
},
|
|
91
|
+
reply: (threadId, body) =>
|
|
92
|
+
write(path, () => trpcClient.addCommentReply.mutate({ path, threadId, body })),
|
|
93
|
+
edit: (threadId, messageId, body) =>
|
|
94
|
+
write(path, () => trpcClient.editComment.mutate({ path, threadId, messageId, body })),
|
|
95
|
+
setResolved: (threadId, resolved) =>
|
|
96
|
+
write(path, () => trpcClient.setCommentThreadResolved.mutate({ path, threadId, resolved })),
|
|
97
|
+
};
|
|
98
|
+
}
|