@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.
Files changed (37) hide show
  1. package/README.md +3 -0
  2. package/client/DocView.tsx +3 -8
  3. package/client/ListingView.tsx +3 -3
  4. package/client/Settings.tsx +26 -21
  5. package/client/app.css +20 -0
  6. package/client/comments/CommentsPanel.tsx +163 -0
  7. package/client/comments/CommentsPopover.tsx +197 -0
  8. package/client/comments/CommentsSheet.tsx +63 -0
  9. package/client/comments/CommentsSidebar.tsx +18 -0
  10. package/client/comments/CtlButton.tsx +33 -0
  11. package/client/comments/DraftThread.tsx +83 -0
  12. package/client/comments/GutterCounters.tsx +113 -0
  13. package/client/comments/ReplyField.tsx +98 -0
  14. package/client/comments/SelectionButton.tsx +142 -0
  15. package/client/comments/Thread.tsx +278 -0
  16. package/client/comments/anchor.ts +204 -0
  17. package/client/comments/data.ts +98 -0
  18. package/client/comments/dom.ts +212 -0
  19. package/client/comments/drafts.ts +36 -0
  20. package/client/comments/highlights.ts +83 -0
  21. package/client/comments/model.ts +241 -0
  22. package/client/comments/pins.ts +37 -0
  23. package/client/comments/self-writes.ts +22 -0
  24. package/client/comments/state.ts +60 -0
  25. package/client/comments/time.ts +21 -0
  26. package/client/hooks.ts +19 -0
  27. package/client/platform.ts +8 -0
  28. package/client/router.ts +5 -0
  29. package/client/shell/AppShell.tsx +60 -14
  30. package/client/shell/StandaloneShell.tsx +3 -2
  31. package/client/shell/TopBar.tsx +25 -0
  32. package/client/ui/ConfirmDeleteDialog.tsx +1 -1
  33. package/client/ui/Toast.tsx +5 -1
  34. package/client/ui/icon-set.ts +10 -0
  35. package/dist/cli.js +872 -229
  36. package/package.json +1 -1
  37. package/skills/mdxserve/SKILL.md +86 -0
@@ -0,0 +1,83 @@
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
+ pendingSendsAtom,
8
+ popoverThreadAtom,
9
+ withPendingSend,
10
+ } from "./state";
11
+ import { Avatar, QuoteText } from "./Thread";
12
+
13
+ /** The new-comment composer: the selected quote and an empty field, in the popover or the sheet. */
14
+ export function DraftThread({
15
+ model,
16
+ sidebarOpen,
17
+ reserveTools,
18
+ padded,
19
+ }: {
20
+ model: CommentsModel;
21
+ sidebarOpen: boolean;
22
+ /** Leaves room for the popover's tool buttons beside the quote. */
23
+ reserveTools: boolean;
24
+ padded: boolean;
25
+ }) {
26
+ const [draft, setDraft] = useAtom(draftAtom);
27
+ const setActive = useSetAtom(activeThreadAtom);
28
+ const setPopover = useSetAtom(popoverThreadAtom);
29
+ // Shared, so a composer that remounts mid-save (the sheet closed and reopened)
30
+ // still shows its send as pending and cannot post the comment twice.
31
+ const [pendingSends, setPendingSends] = useAtom(pendingSendsAtom);
32
+ const pendingKey = draft ? `draft:${draft.nonce}` : "";
33
+ const pending = pendingSends.has(pendingKey);
34
+ const setPending = (active: boolean) =>
35
+ setPendingSends((previous) => withPendingSend(previous, pendingKey, active));
36
+ const store = useStore();
37
+ if (!draft) return null;
38
+
39
+ async function submit() {
40
+ if (!draft) return;
41
+ // This draft, by the press that opened it: a later one must survive our completion.
42
+ const submitted = draft.nonce;
43
+ setPending(true);
44
+ const created = await model.actions.addThread(draft.anchor, draft.body);
45
+ setPending(false);
46
+ // On failure the draft, with its text, stays.
47
+ if (created === null) return;
48
+ // The user moved on to another comment (or another doc) while this one saved.
49
+ if (store.get(draftAtom)?.nonce !== submitted) return;
50
+ setDraft(null);
51
+ setActive(created);
52
+ // The popover follows the new thread unless the sidebar shows it.
53
+ if (!sidebarOpen) setPopover(created);
54
+ }
55
+
56
+ return (
57
+ <div
58
+ data-draft
59
+ className={"flex flex-col gap-3 " + (padded ? "pt-4 pr-3.5 pb-[18px] pl-4" : "")}
60
+ >
61
+ <div className={reserveTools ? "pr-[84px]" : ""}>
62
+ <QuoteText text={draft.anchor.quote} active />
63
+ </div>
64
+ <div className="grid grid-cols-[24px_1fr] items-end gap-x-2.5">
65
+ <Avatar author="human" />
66
+ <ReplyField
67
+ label="New comment"
68
+ sendLabel="Send comment"
69
+ placeholder={
70
+ model.writesDisabled ? "Close the section editor to comment" : "Add a comment…"
71
+ }
72
+ value={draft.body}
73
+ onChange={(body) => setDraft({ ...draft, body })}
74
+ onSubmit={() => void submit()}
75
+ onCancel={() => setDraft(null)}
76
+ disabled={model.writesDisabled}
77
+ pending={pending}
78
+ focusNonce={draft.nonce}
79
+ />
80
+ </div>
81
+ </div>
82
+ );
83
+ }
@@ -0,0 +1,113 @@
1
+ import { useAtomValue } from "jotai";
2
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
3
+ import { Icon } from "../ui/Icon";
4
+ import { findArticle } from "./dom";
5
+ import type { CommentsModel, ThreadView } from "./model";
6
+ import { layoutPins, pinLeft, type PinAnchor } from "./pins";
7
+ import { activeThreadAtom } from "./state";
8
+
9
+ const PIN_HEIGHT = 22;
10
+ const PIN_WIDTH_ESTIMATE = 44;
11
+ const LINE_HEIGHT = 24;
12
+
13
+ interface Pin {
14
+ id: string;
15
+ top: number;
16
+ left: number;
17
+ count: number;
18
+ }
19
+
20
+ /** The first line of the thread's anchor, or the start of its block. */
21
+ function anchorLine(view: ThreadView): { top: number; height: number } | null {
22
+ const rect = view.range?.getClientRects()[0];
23
+ if (rect && (rect.width > 0 || rect.height > 0)) return { top: rect.top, height: rect.height };
24
+ const block = view.scrollTarget?.getBoundingClientRect();
25
+ if (!block) return null;
26
+ return { top: block.top, height: Math.min(block.height, LINE_HEIGHT) };
27
+ }
28
+
29
+ /**
30
+ * Small pills at the right edge of the doc column, level with each open
31
+ * thread's anchor, showing its message count. Desktop with the sidebar closed
32
+ * only; a click opens the popover.
33
+ */
34
+ export function GutterCounters({ model }: { model: CommentsModel }) {
35
+ const containerRef = useRef<HTMLDivElement>(null);
36
+ const [pins, setPins] = useState<Pin[]>([]);
37
+ const activeId = useAtomValue(activeThreadAtom);
38
+ const { threads, views } = model;
39
+
40
+ const measure = useCallback(() => {
41
+ const origin = containerRef.current?.getBoundingClientRect();
42
+ const article = findArticle();
43
+ if (!origin || !article) {
44
+ setPins([]);
45
+ return;
46
+ }
47
+ const left = pinLeft(
48
+ article.getBoundingClientRect().right,
49
+ PIN_WIDTH_ESTIMATE,
50
+ window.innerWidth,
51
+ );
52
+ const counts = new Map<string, number>();
53
+ const anchors: PinAnchor[] = [];
54
+ for (const thread of threads) {
55
+ const view = thread.resolved ? undefined : views.get(thread.id);
56
+ const line = view ? anchorLine(view) : null;
57
+ if (!line) continue;
58
+ counts.set(thread.id, thread.messages.length);
59
+ anchors.push({ id: thread.id, top: line.top - origin.top, height: line.height });
60
+ }
61
+ setPins(
62
+ layoutPins(anchors, PIN_HEIGHT, 4).map((placed) => ({
63
+ id: placed.id,
64
+ top: placed.top,
65
+ left: left - origin.left,
66
+ count: counts.get(placed.id) ?? 0,
67
+ })),
68
+ );
69
+ }, [threads, views]);
70
+
71
+ useLayoutEffect(measure, [measure]);
72
+
73
+ // The doc reflows with the window, with late fonts and images, and with the
74
+ // sidebar closing; anything that moves an anchor resizes the article. The
75
+ // navigation sidebar and TOC rail shift the centred doc without resizing it,
76
+ // but they do resize the content area around it.
77
+ useEffect(() => {
78
+ const article = findArticle();
79
+ const contentArea = article?.closest("[data-content-area]") ?? null;
80
+ const observer = article ? new ResizeObserver(measure) : null;
81
+ if (article) observer?.observe(article);
82
+ if (contentArea) observer?.observe(contentArea);
83
+ window.addEventListener("resize", measure);
84
+ return () => {
85
+ observer?.disconnect();
86
+ window.removeEventListener("resize", measure);
87
+ };
88
+ }, [measure]);
89
+
90
+ return (
91
+ <div ref={containerRef} data-print-hide className="pointer-events-none absolute top-0 left-0">
92
+ {pins.map((pin) => (
93
+ <button
94
+ key={pin.id}
95
+ type="button"
96
+ data-comments-keep
97
+ aria-label={`Open comment thread, ${pin.count} ${pin.count === 1 ? "message" : "messages"}`}
98
+ onClick={() => model.showPopover(pin.id)}
99
+ style={{ top: pin.top, left: pin.left, height: PIN_HEIGHT }}
100
+ className={
101
+ "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 " +
102
+ (pin.id === activeId
103
+ ? "border-border-strong bg-surface-hover text-text-heading"
104
+ : "border-border-default bg-surface-card text-text-muted hover:text-text-heading")
105
+ }
106
+ >
107
+ <Icon name="message-square" size={12} />
108
+ {pin.count}
109
+ </button>
110
+ ))}
111
+ </div>
112
+ );
113
+ }
@@ -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-colors disabled:cursor-not-allowed " +
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
+ }
@@ -0,0 +1,142 @@
1
+ import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
2
+ import { useAtom, useSetAtom } from "jotai";
3
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { Icon } from "../ui/Icon";
5
+ import type { AnchorFields } from "./anchor";
6
+ import { captureSelection } from "./dom";
7
+ import { useCommentsPanel, type CommentsModel } from "./model";
8
+ import { draftAtom, popoverThreadAtom } from "./state";
9
+
10
+ const SETTLE_MS = 60;
11
+
12
+ interface Pending {
13
+ anchor: AnchorFields;
14
+ range: Range;
15
+ }
16
+
17
+ /** The "Comment" button floating next to a selection. */
18
+ // Never reused, so a finished submission can tell its own draft from a later one
19
+ // even after the draft was discarded in between.
20
+ let draftNonce = 0;
21
+ function nextDraftNonce(): number {
22
+ draftNonce += 1;
23
+ return draftNonce;
24
+ }
25
+
26
+ export function SelectionButton({ model }: { model: CommentsModel }) {
27
+ const [pending, setPending] = useState<Pending | null>(null);
28
+ const [draft, setDraft] = useAtom(draftAtom);
29
+ const setPopover = useSetAtom(popoverThreadAtom);
30
+ const { isDesktop, setOpen } = useCommentsPanel();
31
+ const buttonRef = useRef<HTMLButtonElement>(null);
32
+ const pointerType = useRef("mouse");
33
+ const pointerDown = useRef(false);
34
+ const enabled = !model.writesDisabled && model.path !== "";
35
+
36
+ const refresh = useCallback(() => {
37
+ const selection = window.getSelection();
38
+ const anchor = enabled && !pointerDown.current ? captureSelection(selection) : null;
39
+ if (!anchor || !selection) {
40
+ setPending(null);
41
+ return;
42
+ }
43
+ setPending({ anchor, range: selection.getRangeAt(0).cloneRange() });
44
+ }, [enabled]);
45
+
46
+ useEffect(() => {
47
+ if (!enabled) {
48
+ setPending(null);
49
+ return;
50
+ }
51
+ let timer: ReturnType<typeof setTimeout> | undefined;
52
+ function onSelectionChange() {
53
+ clearTimeout(timer);
54
+ timer = setTimeout(refresh, SETTLE_MS);
55
+ }
56
+ function onPointerDown(event: PointerEvent) {
57
+ pointerType.current = event.pointerType;
58
+ if (event.pointerType === "mouse") pointerDown.current = true;
59
+ }
60
+ function onPointerUp(event: PointerEvent) {
61
+ pointerType.current = event.pointerType;
62
+ pointerDown.current = false;
63
+ // Let the browser finish the selection this release completes.
64
+ requestAnimationFrame(refresh);
65
+ }
66
+ document.addEventListener("selectionchange", onSelectionChange);
67
+ document.addEventListener("pointerdown", onPointerDown, true);
68
+ document.addEventListener("pointerup", onPointerUp, true);
69
+ refresh();
70
+ return () => {
71
+ clearTimeout(timer);
72
+ document.removeEventListener("selectionchange", onSelectionChange);
73
+ document.removeEventListener("pointerdown", onPointerDown, true);
74
+ document.removeEventListener("pointerup", onPointerUp, true);
75
+ };
76
+ }, [enabled, refresh]);
77
+
78
+ // Above the selection with a pointer, below it on touch, where the system menu sits above.
79
+ useLayoutEffect(() => {
80
+ const floating = buttonRef.current;
81
+ if (!pending || !floating) return;
82
+ const reference = {
83
+ getBoundingClientRect: () => pending.range.getBoundingClientRect(),
84
+ getClientRects: () => pending.range.getClientRects(),
85
+ };
86
+ const touch = pointerType.current === "touch" || window.matchMedia("(pointer: coarse)").matches;
87
+ return autoUpdate(reference, floating, () => {
88
+ void computePosition(reference, floating, {
89
+ strategy: "fixed",
90
+ placement: touch ? "bottom" : "top",
91
+ middleware: [offset(8), flip(), shift({ padding: 8 })],
92
+ }).then(({ x, y }) => {
93
+ floating.style.left = `${x}px`;
94
+ floating.style.top = `${y}px`;
95
+ floating.style.visibility = "visible";
96
+ });
97
+ });
98
+ }, [pending]);
99
+
100
+ // Escape discards the draft.
101
+ useEffect(() => {
102
+ if (!draft) return;
103
+ function onKeyDown(event: KeyboardEvent) {
104
+ if (event.key === "Escape") setDraft(null);
105
+ }
106
+ window.addEventListener("keydown", onKeyDown);
107
+ return () => window.removeEventListener("keydown", onKeyDown);
108
+ }, [draft, setDraft]);
109
+
110
+ if (!pending) return null;
111
+ const { anchor, range } = pending;
112
+
113
+ return (
114
+ <button
115
+ ref={buttonRef}
116
+ type="button"
117
+ data-print-hide
118
+ data-comments-keep
119
+ // Keep the selection alive through the press.
120
+ onPointerDown={(event) => event.preventDefault()}
121
+ onMouseDown={(event) => event.preventDefault()}
122
+ onClick={() => {
123
+ setDraft((previous) => ({
124
+ anchor,
125
+ range,
126
+ body: previous?.body ?? "",
127
+ nonce: nextDraftNonce(),
128
+ }));
129
+ // Desktop: the composer opens in a popover, whether or not the sidebar is
130
+ // open. Phone: it opens in the sheet.
131
+ setPopover(null);
132
+ if (!isDesktop) setOpen(true);
133
+ setPending(null);
134
+ }}
135
+ style={{ position: "fixed", left: 0, top: 0, visibility: "hidden" }}
136
+ className="z-[var(--z-dropdown)] inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-md border border-border-default bg-surface-raised px-2.5 font-sans text-[length:var(--size-sm)] font-semibold text-text-heading shadow-md hover:bg-surface-hover"
137
+ >
138
+ <Icon name="message-square" size="sm" />
139
+ Comment
140
+ </button>
141
+ );
142
+ }