@karimsa/mdxserve 0.6.0-rc.1 → 0.6.0-rc.3

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.
@@ -1,4 +1,4 @@
1
- import { useLayoutEffect, useMemo, useRef } from "react";
1
+ import { memo, useLayoutEffect, useMemo, useRef, type ComponentType, type ReactNode } from "react";
2
2
  import { useAtomValue, useSetAtom } from "jotai";
3
3
  import { DocContext } from "./DocContext";
4
4
  import { ErrorBox } from "./ErrorBox";
@@ -10,7 +10,7 @@ import { DOC_MAX_WIDTH, DOC_MIN_WIDTH, docWidthAtom, openSectionAtom } from "./s
10
10
 
11
11
  // Each Component a re-import produces (including an HMR re-import after a
12
12
  // fix) is a distinct function identity, so this assigns it a stable, unique
13
- // key the RenderErrorBoundary below can be keyed on to reset itself.
13
+ // number the RenderErrorBoundary below resets itself on.
14
14
  const moduleKeys = new WeakMap<object, number>();
15
15
  let nextModuleKey = 0;
16
16
  function keyForComponent(Component: object): number {
@@ -22,7 +22,24 @@ function keyForComponent(Component: object): number {
22
22
  return key;
23
23
  }
24
24
 
25
- export function DocView({
25
+ /**
26
+ * Calls the doc's compiled content function instead of mounting it. A re-import
27
+ * after an edit yields a new function; mounted as a component, React would see
28
+ * a new type and rebuild the whole article. Called from this one long-lived
29
+ * component, only the elements it returns are diffed, so unchanged blocks keep
30
+ * their DOM and state. The content function's own hooks (`useMDXComponents`)
31
+ * are the same on every import, so they are safe to run as this component's.
32
+ */
33
+ function DocContent({ render }: { render: ComponentType }) {
34
+ return (render as (props: Record<string, never>) => ReactNode)({});
35
+ }
36
+
37
+ /**
38
+ * Memoized: the shell re-renders on every frame of a width change (the
39
+ * comments sidebar opening, a window resize), and without this each of those
40
+ * would re-run the whole doc's content function.
41
+ */
42
+ export const DocView = memo(function DocView({
26
43
  path,
27
44
  module,
28
45
  onRendered,
@@ -99,11 +116,11 @@ export function DocView({
99
116
  )}
100
117
  <article className="mdx-prose min-w-0 max-w-full">
101
118
  <DocContext value={docContext}>
102
- <RenderErrorBoundary key={keyForComponent(Content)}>
103
- <Content />
119
+ <RenderErrorBoundary resetKey={keyForComponent(Content)}>
120
+ <DocContent render={Content} />
104
121
  </RenderErrorBoundary>
105
122
  </DocContext>
106
123
  </article>
107
124
  </div>
108
125
  );
109
- }
126
+ });
@@ -58,14 +58,11 @@ export interface MdSectionProps {
58
58
  * it's invisible — same children, same DOM — until hovered, when a pencil
59
59
  * appears to swap it into an inline Tiptap editor seeded from the raw file.
60
60
  *
61
- * This outer component only resolves `path` and re-keys the inner `Section`
62
- * on `path:startLine:endLine`. That key matters after a save: Vite's HMR
63
- * re-executes the doc module and React Fast Refresh re-renders this
64
- * component in place with *new* startLine/endLine props (the edited range
65
- * shifted). Without the key, Fast Refresh would preserve `Section`'s local
66
- * state across that update and leave it holding an editor pointed at
67
- * now-stale line numbers; keying on the range forces a clean remount back to
68
- * read mode instead.
61
+ * This outer component only resolves `path`. `Section` is deliberately not
62
+ * keyed on its line range: anything that adds lines above it — a comment
63
+ * growing the frontmatter, an edit to an earlier section — shifts the range,
64
+ * and a key would remount every section below, diagrams included. `Section`
65
+ * drops back to read mode itself when its range moves.
69
66
  */
70
67
  export function MdSection({ index, startLine, endLine, rawJsx, children }: MdSectionProps) {
71
68
  const ctxPath = useContext(DocContext)?.path;
@@ -78,7 +75,6 @@ export function MdSection({ index, startLine, endLine, rawJsx, children }: MdSec
78
75
 
79
76
  return (
80
77
  <Section
81
- key={`${path}:${startLine}:${endLine}`}
82
78
  path={path}
83
79
  index={index}
84
80
  startLine={Number(startLine)}
@@ -112,6 +108,15 @@ function Section({
112
108
  const [openSection, setOpenSection] = useAtom(openSectionAtom);
113
109
  const key = `${path}:${startLine}:${endLine}`;
114
110
 
111
+ // The range moved under this section (a save or an outside write shifted
112
+ // it), so an open editor now points at stale line numbers: back to read
113
+ // mode. Reset during render so the editor never commits with the new range.
114
+ const [renderedKey, setRenderedKey] = useState(key);
115
+ if (renderedKey !== key) {
116
+ setRenderedKey(key);
117
+ setMode("read");
118
+ }
119
+
115
120
  // Only one section edits (or loads) at a time. The atom is claimed the
116
121
  // moment a section starts opening, so if a different section claims it
117
122
  // while this one is mid-fetch or mid-edit, this one drops back to read
@@ -4,6 +4,8 @@ import { ErrorBox } from "./ErrorBox";
4
4
  type RenderErrorBoundaryState = {
5
5
  error: Error | null;
6
6
  componentStack: string | null;
7
+ /** The `resetKey` this state belongs to. */
8
+ resetKey: number;
7
9
  };
8
10
 
9
11
  /**
@@ -12,15 +14,28 @@ type RenderErrorBoundaryState = {
12
14
  * shows ErrorBox instead of leaving the page blank. React error boundaries
13
15
  * only work as class components — there is no hook equivalent.
14
16
  *
15
- * The parent keys this component on the cached module's identity, so an HMR
16
- * re-import after a fix remounts the boundary and clears the stale error
17
- * rather than getting stuck on the first throw.
17
+ * The parent passes the cached module's identity as `resetKey`, so an HMR
18
+ * re-import after a fix clears the stale error rather than getting stuck on
19
+ * the first throw. It is a prop and not a React `key`: a key would remount the
20
+ * whole article on every re-import, error or not.
18
21
  */
19
22
  export class RenderErrorBoundary extends Component<
20
- { children: ReactNode },
23
+ { resetKey: number; children: ReactNode },
21
24
  RenderErrorBoundaryState
22
25
  > {
23
- state: RenderErrorBoundaryState = { error: null, componentStack: null };
26
+ state: RenderErrorBoundaryState = {
27
+ error: null,
28
+ componentStack: null,
29
+ resetKey: this.props.resetKey,
30
+ };
31
+
32
+ static getDerivedStateFromProps(
33
+ props: { resetKey: number },
34
+ state: RenderErrorBoundaryState,
35
+ ): RenderErrorBoundaryState | null {
36
+ if (props.resetKey === state.resetKey) return null;
37
+ return { error: null, componentStack: null, resetKey: props.resetKey };
38
+ }
24
39
 
25
40
  static getDerivedStateFromError(error: Error): Partial<RenderErrorBoundaryState> {
26
41
  return { error };
@@ -1,9 +1,11 @@
1
+ import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
1
2
  import { useAtomValue } from "jotai";
2
- import { useEffect, useMemo, useRef, useState } from "react";
3
+ import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
3
4
  import type { CommentThread } from "../../src/comments/schema";
4
5
  import { CtlButton } from "./CtlButton";
5
6
  import { DraftThread } from "./DraftThread";
6
7
  import type { CommentsModel } from "./model";
8
+ import { rowMotion } from "./motion";
7
9
  import { activeThreadAtom, draftAtom } from "./state";
8
10
  import { Thread } from "./Thread";
9
11
 
@@ -48,7 +50,31 @@ function Tabs({
48
50
  );
49
51
  }
50
52
 
51
- /** Header and thread list shared by the docked sidebar and the phone sheet. */
53
+ /**
54
+ * One thread's place in the list. It expands in when the thread joins the tab
55
+ * (a new comment, a reopen) and collapses when it leaves (a resolve), so the
56
+ * rows around it move aside instead of jumping.
57
+ */
58
+ function ThreadRow({ active, children }: { active: boolean; children: ReactNode }) {
59
+ const ref = useRef<HTMLDivElement>(null);
60
+ const reducedMotion = useReducedMotion();
61
+ return (
62
+ <motion.div
63
+ ref={ref}
64
+ {...rowMotion(reducedMotion)}
65
+ // Thread scrolls itself into view when it becomes active, but a new one
66
+ // is still collapsed then; bring it fully into view once it has opened.
67
+ onAnimationComplete={() => {
68
+ if (active) ref.current?.scrollIntoView({ block: "nearest" });
69
+ }}
70
+ className="overflow-hidden"
71
+ >
72
+ {children}
73
+ </motion.div>
74
+ );
75
+ }
76
+
77
+ /** Header and thread list shared by the desktop sidebar and the phone sheet. */
52
78
  export function CommentsPanel({
53
79
  model,
54
80
  variant,
@@ -95,14 +121,15 @@ export function CommentsPanel({
95
121
 
96
122
  function renderThread(thread: CommentThread) {
97
123
  return (
98
- <Thread
99
- key={`${model.path}:${thread.id}`}
100
- thread={thread}
101
- view={views.get(thread.id)}
102
- active={thread.id === activeId}
103
- variant={variant}
104
- model={model}
105
- />
124
+ <ThreadRow key={`${model.path}:${thread.id}`} active={thread.id === activeId}>
125
+ <Thread
126
+ thread={thread}
127
+ view={views.get(thread.id)}
128
+ active={thread.id === activeId}
129
+ variant={variant}
130
+ model={model}
131
+ />
132
+ </ThreadRow>
106
133
  );
107
134
  }
108
135
 
@@ -134,14 +161,18 @@ export function CommentsPanel({
134
161
  <DraftThread model={model} sidebarOpen={false} reserveTools={false} padded />
135
162
  </div>
136
163
  ) : null}
137
- <div className="divide-y divide-border-default">
138
- {shown.map(renderThread)}
164
+ {/* Keyed by tab and doc: switching either swaps the whole list at once,
165
+ and only a thread joining or leaving the list on screen animates. */}
166
+ <div key={`${model.path}:${tab}`} className="divide-y divide-border-default">
167
+ <AnimatePresence initial={false}>{shown.map(renderThread)}</AnimatePresence>
139
168
  {tab === "open" && detached.length > 0 ? (
140
169
  <div>
141
170
  <h3 className="m-0 px-4 pt-3.5 text-[length:var(--size-2xs)] font-semibold tracking-wide text-text-subtle uppercase">
142
171
  Detached
143
172
  </h3>
144
- <div className="divide-y divide-border-default">{detached.map(renderThread)}</div>
173
+ <div className="divide-y divide-border-default">
174
+ <AnimatePresence initial={false}>{detached.map(renderThread)}</AnimatePresence>
175
+ </div>
145
176
  </div>
146
177
  ) : null}
147
178
  </div>
@@ -1,18 +1,36 @@
1
+ import { motion } from "framer-motion";
1
2
  import { CommentsPanel } from "./CommentsPanel";
2
3
  import type { CommentsModel } from "./model";
4
+ import { SLIDE, SLIDE_BLEED, SLIDE_OUT } from "./motion";
3
5
 
4
6
  /**
5
- * Desktop column: 348px, full height under the top bar, flush to the window's
6
- * right edge. A sibling of `<main>` in AppShell, so the doc column narrows to make room.
7
+ * Desktop panel: 348px, full height under the top bar, fixed to the window's
8
+ * right edge. It slides in over the right-hand track AppShell reserves beside
9
+ * the doc (the one the table-of-contents rail sits in), so it never covers
10
+ * the doc. Render it inside an `AnimatePresence` for the exit.
11
+ *
12
+ * The slide is a spring that overshoots slightly, so the panel is wider than
13
+ * it looks: `SLIDE_BLEED` of padding hangs off the window's right edge and
14
+ * comes into view only while the spring is past its resting point.
7
15
  */
16
+ export const COMMENTS_SIDEBAR_WIDTH = 348;
8
17
  export function CommentsSidebar({ model, onClose }: { model: CommentsModel; onClose: () => void }) {
9
18
  return (
10
- <aside
19
+ <motion.aside
11
20
  data-print-hide
12
21
  aria-label="Comments"
13
- className="sticky top-topbar flex h-[calc(100vh-var(--topbar-height))] w-[348px] shrink-0 flex-col border-l border-border-default bg-surface-page"
22
+ initial={{ x: "100%" }}
23
+ animate={{ x: 0 }}
24
+ exit={{ x: "100%", transition: SLIDE_OUT }}
25
+ transition={SLIDE}
26
+ style={{
27
+ width: COMMENTS_SIDEBAR_WIDTH + SLIDE_BLEED,
28
+ right: -SLIDE_BLEED,
29
+ paddingRight: SLIDE_BLEED,
30
+ }}
31
+ className="fixed top-topbar bottom-0 z-[var(--z-sticky)] flex flex-col border-l border-border-default bg-surface-page shadow-lg"
14
32
  >
15
33
  <CommentsPanel model={model} variant="sidebar" onClose={onClose} />
16
- </aside>
34
+ </motion.aside>
17
35
  );
18
36
  }
@@ -4,6 +4,7 @@ import { ReplyField } from "./ReplyField";
4
4
  import {
5
5
  activeThreadAtom,
6
6
  draftAtom,
7
+ freshThreadAtom,
7
8
  pendingSendsAtom,
8
9
  popoverThreadAtom,
9
10
  withPendingSend,
@@ -26,6 +27,7 @@ export function DraftThread({
26
27
  const [draft, setDraft] = useAtom(draftAtom);
27
28
  const setActive = useSetAtom(activeThreadAtom);
28
29
  const setPopover = useSetAtom(popoverThreadAtom);
30
+ const setFresh = useSetAtom(freshThreadAtom);
29
31
  // Shared, so a composer that remounts mid-save (the sheet closed and reopened)
30
32
  // still shows its send as pending and cannot post the comment twice.
31
33
  const [pendingSends, setPendingSends] = useAtom(pendingSendsAtom);
@@ -47,6 +49,7 @@ export function DraftThread({
47
49
  if (created === null) return;
48
50
  // The user moved on to another comment (or another doc) while this one saved.
49
51
  if (store.get(draftAtom)?.nonce !== submitted) return;
52
+ setFresh(created);
50
53
  setDraft(null);
51
54
  setActive(created);
52
55
  // The popover follows the new thread unless the sidebar shows it.
@@ -1,5 +1,7 @@
1
+ import { AnimatePresence, motion } from "framer-motion";
1
2
  import { useAtomValue } from "jotai";
2
3
  import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { TRANSITIONS } from "../motion";
3
5
  import { Icon } from "../ui/Icon";
4
6
  import { findArticle } from "./dom";
5
7
  import type { CommentsModel, ThreadView } from "./model";
@@ -70,8 +72,7 @@ export function GutterCounters({ model }: { model: CommentsModel }) {
70
72
 
71
73
  useLayoutEffect(measure, [measure]);
72
74
 
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
+ // The doc reflows with the window and with late fonts and images; anything that moves an anchor resizes the article. The
75
76
  // navigation sidebar and TOC rail shift the centred doc without resizing it,
76
77
  // but they do resize the content area around it.
77
78
  useEffect(() => {
@@ -89,25 +90,31 @@ export function GutterCounters({ model }: { model: CommentsModel }) {
89
90
 
90
91
  return (
91
92
  <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
- ))}
93
+ <AnimatePresence>
94
+ {pins.map((pin) => (
95
+ <motion.button
96
+ key={pin.id}
97
+ initial={{ opacity: 0, scale: 0.85 }}
98
+ animate={{ opacity: 1, scale: 1 }}
99
+ exit={{ opacity: 0, transition: TRANSITIONS.fast }}
100
+ transition={TRANSITIONS.snap}
101
+ type="button"
102
+ data-comments-keep
103
+ aria-label={`Open comment thread, ${pin.count} ${pin.count === 1 ? "message" : "messages"}`}
104
+ onClick={() => model.showPopover(pin.id)}
105
+ style={{ top: pin.top, left: pin.left, height: PIN_HEIGHT }}
106
+ className={
107
+ "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 " +
108
+ (pin.id === activeId
109
+ ? "border-border-strong bg-surface-hover text-text-heading"
110
+ : "border-border-default bg-surface-card text-text-muted hover:text-text-heading")
111
+ }
112
+ >
113
+ <Icon name="message-square" size={12} />
114
+ {pin.count}
115
+ </motion.button>
116
+ ))}
117
+ </AnimatePresence>
111
118
  </div>
112
119
  );
113
120
  }
@@ -85,7 +85,7 @@ export function ReplyField({
85
85
  disabled={!ready}
86
86
  onClick={onSubmit}
87
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 " +
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
89
  (ready
90
90
  ? "bg-surface-accent text-text-inverse"
91
91
  : "bg-surface-hover text-text-subtle group-focus-within/field:bg-surface-accent group-focus-within/field:text-text-inverse")
@@ -1,12 +1,20 @@
1
- import { useAtom } from "jotai";
1
+ import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
2
+ import { useAtom, useStore } from "jotai";
2
3
  import { useEffect, useRef, useState, type ReactNode } from "react";
3
4
  import type { CommentMessage, CommentThread } from "../../src/comments/schema";
4
5
  import { Icon } from "../ui/Icon";
5
6
  import { CtlButton } from "./CtlButton";
6
7
  import { replyDraftOf, withReplyDraft } from "./drafts";
7
8
  import type { CommentsModel, ThreadView } from "./model";
9
+ import { rowMotion } from "./motion";
8
10
  import { ReplyField } from "./ReplyField";
9
- import { pendingReplyKey, pendingSendsAtom, replyDraftsAtom, withPendingSend } from "./state";
11
+ import {
12
+ freshThreadAtom,
13
+ pendingReplyKey,
14
+ pendingSendsAtom,
15
+ replyDraftsAtom,
16
+ withPendingSend,
17
+ } from "./state";
10
18
  import { relativeTime } from "./time";
11
19
 
12
20
  /** Where a thread is drawn: a sidebar row, the sheet's row, or the popover's body. */
@@ -42,6 +50,7 @@ export function QuoteText({ text, active }: { text: string; active: boolean }) {
42
50
 
43
51
  function Message({
44
52
  message,
53
+ first,
45
54
  last,
46
55
  reserveTools,
47
56
  canEdit,
@@ -49,6 +58,7 @@ function Message({
49
58
  onEdit,
50
59
  }: {
51
60
  message: CommentMessage;
61
+ first: boolean;
52
62
  last: boolean;
53
63
  /** Leaves room for the popover's tool buttons beside the first header. */
54
64
  reserveTools: boolean;
@@ -60,6 +70,7 @@ function Message({
60
70
  const [draft, setDraft] = useState(message.body);
61
71
  const [pending, setPending] = useState(false);
62
72
  const agent = message.author === "agent";
73
+ const reducedMotion = useReducedMotion();
63
74
 
64
75
  async function save() {
65
76
  setPending(true);
@@ -68,71 +79,79 @@ function Message({
68
79
  if (saved) setEditing(false);
69
80
  }
70
81
 
82
+ // The gap above a message is drawn inside it (the timeline's connector, then
83
+ // 2px of air) instead of as a margin, so a new message's whole footprint
84
+ // grows from nothing and the reply field below is pushed down smoothly.
71
85
  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
- />
86
+ <motion.div {...rowMotion(reducedMotion)} className="group overflow-hidden">
87
+ {first ? null : (
88
+ <span aria-hidden className="mb-0.5 ml-[11.5px] block h-3 w-px bg-border-default" />
78
89
  )}
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}
90
+ <div className="relative grid grid-cols-[24px_1fr] gap-x-2.5">
91
+ {last ? null : (
92
+ <span
93
+ aria-hidden
94
+ className="absolute top-7 bottom-0 left-[11.5px] w-px bg-border-default"
95
+ />
96
+ )}
97
+ <Avatar author={message.author} />
98
+ <div className="min-w-0">
99
+ <div
100
+ className={
101
+ "flex items-baseline gap-[7px] pt-[3px] text-[12.5px] leading-[1.3] " +
102
+ (reserveTools ? "pr-[84px]" : "")
103
+ }
94
104
  >
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"
105
+ <span className={"font-bold " + (agent ? "text-text-accent" : "text-text-heading")}>
106
+ {agent ? "Agent" : "You"}
107
+ </span>
108
+ <time
109
+ className="text-[11.5px] text-text-subtle tabular-nums"
110
+ dateTime={message.createdAt}
111
+ title={message.createdAt ? new Date(message.createdAt).toLocaleString() : undefined}
108
112
  >
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
- />
113
+ {relativeTime(message.createdAt)}
114
+ {message.editedAt ? " · edited" : ""}
115
+ </time>
116
+ {canEdit && !editing ? (
117
+ <button
118
+ type="button"
119
+ disabled={editDisabled}
120
+ aria-label="Edit comment"
121
+ onClick={() => {
122
+ setDraft(message.body);
123
+ setEditing(true);
124
+ }}
125
+ 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"
126
+ >
127
+ <Icon name="pencil" size={11} />
128
+ Edit
129
+ </button>
130
+ ) : null}
128
131
  </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
- )}
132
+ {editing ? (
133
+ <div className="mt-1.5" data-comment-edit>
134
+ <ReplyField
135
+ label="Edit comment"
136
+ sendLabel="Save comment"
137
+ placeholder=""
138
+ value={draft}
139
+ onChange={setDraft}
140
+ onSubmit={() => void save()}
141
+ onCancel={() => setEditing(false)}
142
+ disabled={editDisabled}
143
+ pending={pending}
144
+ focusNonce={0}
145
+ />
146
+ </div>
147
+ ) : (
148
+ <p className="m-0 mt-[3px] text-[13.5px] leading-[1.55] break-words whitespace-pre-wrap text-text-body">
149
+ {message.body}
150
+ </p>
151
+ )}
152
+ </div>
134
153
  </div>
135
- </div>
154
+ </motion.div>
136
155
  );
137
156
  }
138
157
 
@@ -165,6 +184,14 @@ export function Thread({
165
184
  const popover = variant === "popover";
166
185
  const reply = replyDraftOf(drafts, thread.id);
167
186
 
187
+ // A thread this tab just created shows its message arriving in the popover.
188
+ // In the panel the whole row expands in instead (CommentsPanel).
189
+ const store = useStore();
190
+ const [animateFirst] = useState(() => popover && store.get(freshThreadAtom) === thread.id);
191
+ useEffect(() => {
192
+ if (store.get(freshThreadAtom) === thread.id) store.set(freshThreadAtom, null);
193
+ }, [store, thread.id]);
194
+
168
195
  useEffect(() => {
169
196
  if (active && !popover) ref.current?.scrollIntoView({ block: "nearest" });
170
197
  }, [active, popover]);
@@ -246,17 +273,20 @@ export function Thread({
246
273
  )}
247
274
  {note ? <p className="m-0 text-xs text-status-warn-fg">{note}</p> : null}
248
275
  <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
- ))}
276
+ <AnimatePresence initial={animateFirst}>
277
+ {thread.messages.map((message, index) => (
278
+ <Message
279
+ key={message.id}
280
+ message={message}
281
+ first={index === 0}
282
+ last={index === thread.messages.length - 1}
283
+ reserveTools={popover && index === 0}
284
+ canEdit={!readOnly && message.author === "human"}
285
+ editDisabled={writesDisabled}
286
+ onEdit={async (body) => (await actions.edit(thread.id, message.id, body)) !== null}
287
+ />
288
+ ))}
289
+ </AnimatePresence>
260
290
  </div>
261
291
  {showReply ? (
262
292
  <div className="grid grid-cols-[24px_1fr] items-end gap-x-2.5">
@@ -0,0 +1,46 @@
1
+ import type { Transition } from "framer-motion";
2
+ import { TRANSITIONS } from "../motion";
3
+
4
+ const INSTANT: Transition = { duration: 0 };
5
+
6
+ /**
7
+ * A row that makes room for itself: threads in the panel and messages in a
8
+ * thread. The element needs `overflow-hidden`, and its spacing has to be
9
+ * padding inside it, or the list jumps by the margin when the row appears.
10
+ * With reduced motion the height change is instant and only the fade remains.
11
+ */
12
+ export function rowMotion(reducedMotion: boolean | null) {
13
+ return {
14
+ initial: { opacity: 0, height: 0 },
15
+ animate: { opacity: 1, height: "auto" },
16
+ exit: {
17
+ opacity: 0,
18
+ height: 0,
19
+ transition: reducedMotion ? INSTANT : TRANSITIONS.base,
20
+ },
21
+ transition: reducedMotion
22
+ ? { height: INSTANT, opacity: TRANSITIONS.base }
23
+ : { height: TRANSITIONS.glide, opacity: TRANSITIONS.slow },
24
+ };
25
+ }
26
+
27
+ /**
28
+ * The comments sidebar's slide: slower and looser than `TRANSITIONS.glide`, so
29
+ * the panel visibly travels and settles with a small overshoot (about 3% of
30
+ * its width). The sidebar bleeds past the window edge by `SLIDE_BLEED` so the
31
+ * overshoot never opens a gap there.
32
+ */
33
+ export const SLIDE: Transition = { type: "spring", stiffness: 170, damping: 19, mass: 1 };
34
+ export const SLIDE_BLEED = 32;
35
+ /**
36
+ * How far the spring carries the sidebar past its resting edge, rounded up
37
+ * (measured: 13px). The layout keeps this much clear beside the sidebar so
38
+ * the overshoot never crosses a doc that fills its column.
39
+ */
40
+ export const SLIDE_OVERSHOOT = 16;
41
+ /**
42
+ * Leaving is a plain accelerate-out: a spring's settling would happen off
43
+ * screen, and the layout waits for the exit to finish before it reclaims the
44
+ * sidebar's track.
45
+ */
46
+ export const SLIDE_OUT: Transition = { duration: 0.3, ease: [0.4, 0, 0.6, 1] };
@@ -3,7 +3,7 @@ import { atomWithStorage } from "jotai/utils";
3
3
  import type { AnchorFields } from "./anchor";
4
4
  import type { ReplyDrafts } from "./drafts";
5
5
 
6
- /** Desktop sidebar open state; persisted. Takes the table-of-contents rail's place while open. */
6
+ /** Desktop sidebar open state; persisted. Covers the table-of-contents rail while open. */
7
7
  export const commentsOpenAtom = atomWithStorage<boolean>(
8
8
  "mdxserve.comments.open",
9
9
  false,
@@ -36,6 +36,13 @@ export interface CommentDraft {
36
36
 
37
37
  export const draftAtom = atom<CommentDraft | null>(null);
38
38
 
39
+ /**
40
+ * The thread this tab just created, until something draws it. The popover
41
+ * animates that thread's first message in, so a sent comment visibly lands;
42
+ * a thread opened any other way appears as it is.
43
+ */
44
+ export const freshThreadAtom = atom<string | null>(null);
45
+
39
46
  /**
40
47
  * Replies and new comments being saved, by key (`pendingReplyKey`, `pendingDraftKey`).
41
48
  * Shared, not component state: a thread or composer that remounts mid-save must
package/client/entry.tsx CHANGED
@@ -49,5 +49,15 @@ function main() {
49
49
  main();
50
50
 
51
51
  if (import.meta.hot) {
52
+ // Every doc module exports `__mdxserveMetadata` (src/rendering/mdx/remark-metadata.ts)
53
+ // beside its component. Fast Refresh rejects a module with a non-component
54
+ // export whose value changed, and a doc has no static importer to fall back
55
+ // on, so without this every write to a doc — a comment included — reloads
56
+ // the whole page. The router's `mdxserve:doc-changed` handler re-imports the
57
+ // doc, so new metadata still arrives.
58
+ (
59
+ window as Window & { __getReactRefreshIgnoredExports?: () => string[] }
60
+ ).__getReactRefreshIgnoredExports = () => ["__mdxserveMetadata"];
61
+
52
62
  import.meta.hot.accept();
53
63
  }
@@ -2,7 +2,15 @@ import { DiagramPreferences } from "../diagrams/Preferences";
2
2
  import { AnimatePresence, motion, useSpring } from "framer-motion";
3
3
  import { useAtomValue } from "jotai";
4
4
  import { keepPreviousData, useQuery } from "@tanstack/react-query";
5
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
5
+ import {
6
+ useCallback,
7
+ useEffect,
8
+ useLayoutEffect,
9
+ useMemo,
10
+ useRef,
11
+ useState,
12
+ type CSSProperties,
13
+ } from "react";
6
14
  import { trpc } from "../api";
7
15
  import { DocView } from "../DocView";
8
16
  import { HomeView } from "../HomeView";
@@ -24,9 +32,10 @@ import { exportDocFromViewer } from "../export-doc";
24
32
  import { Breadcrumb, type BreadcrumbItem } from "../ui/Breadcrumb";
25
33
  import { CommentsPopover } from "../comments/CommentsPopover";
26
34
  import { CommentsSheet } from "../comments/CommentsSheet";
27
- import { CommentsSidebar } from "../comments/CommentsSidebar";
35
+ import { COMMENTS_SIDEBAR_WIDTH, CommentsSidebar } from "../comments/CommentsSidebar";
28
36
  import { GutterCounters } from "../comments/GutterCounters";
29
37
  import { useCommentsModel, useCommentsPanel } from "../comments/model";
38
+ import { SLIDE_OVERSHOOT } from "../comments/motion";
30
39
  import { SelectionButton } from "../comments/SelectionButton";
31
40
  import { PageNav, type PageNavLink } from "../ui/PageNav";
32
41
  import { SearchDialog, type SearchResult } from "../ui/SearchDialog";
@@ -218,11 +227,15 @@ export function AppShell({ route, navigate }: { route: Route; navigate: (path: s
218
227
 
219
228
  const comments = useCommentsModel(route.kind === "doc" ? route.path : null, tocVersion);
220
229
  const commentsPanel = useCommentsPanel();
221
- // The sidebar is docked beside <main>; the table-of-contents rail is hidden while it is open.
230
+ // The sidebar slides in over the right-hand track, covering the table-of-contents rail.
222
231
  const commentsOpen = comments.available && commentsPanel.open;
223
232
  const commentsSidebarOpen = comments.available && commentsPanel.sidebarOpen;
224
233
  const setCommentsOpen = commentsPanel.setOpen;
225
234
  const closeComments = useCallback(() => setCommentsOpen(false), [setCommentsOpen]);
235
+ // The sidebar is still on screen while it slides out, so the track it covers
236
+ // stays reserved until that exit finishes.
237
+ const [commentsTrackHeld, setCommentsTrackHeld] = useState(commentsSidebarOpen);
238
+ if (commentsSidebarOpen && !commentsTrackHeld) setCommentsTrackHeld(true);
226
239
 
227
240
  useEffect(() => {
228
241
  try {
@@ -439,13 +452,38 @@ export function AppShell({ route, navigate }: { route: Route; navigate: (path: s
439
452
  </motion.div>
440
453
  </AnimatePresence>
441
454
  </div>
442
- {route.kind === "doc" && !commentsSidebarOpen ? (
443
- <TocRail path={route.path} version={tocVersion} />
455
+ {/* The right-hand track, shared by the table-of-contents rail and the
456
+ comments sidebar. It is as wide as the sidebar (less <main>'s own
457
+ right padding, plus room for the slide's overshoot), so the sidebar slides in over the rail and can never
458
+ cover the doc. Where the rail already holds the track open (xl and
459
+ up, in a doc with headings) opening the sidebar moves nothing;
460
+ elsewhere the track opens in one step as the sidebar starts to
461
+ slide and closes in one step once it has left. Inert while covered, or focus could land on hidden links. */}
462
+ {route.kind === "doc" ? (
463
+ <div
464
+ data-print-hide
465
+ inert={commentsSidebarOpen}
466
+ style={
467
+ {
468
+ "--comments-track": `${COMMENTS_SIDEBAR_WIDTH - 32 + SLIDE_OVERSHOOT}px`,
469
+ } as CSSProperties
470
+ }
471
+ className={
472
+ "flex shrink-0 justify-end self-stretch " +
473
+ (commentsTrackHeld
474
+ ? "min-w-[var(--comments-track)]"
475
+ : "xl:has-[[data-toc-rail]]:min-w-[var(--comments-track)]")
476
+ }
477
+ >
478
+ <TocRail path={route.path} version={tocVersion} />
479
+ </div>
444
480
  ) : null}
445
481
  </main>
446
- {route.kind === "doc" && commentsSidebarOpen ? (
447
- <CommentsSidebar model={comments} onClose={closeComments} />
448
- ) : null}
482
+ <AnimatePresence initial={false} onExitComplete={() => setCommentsTrackHeld(false)}>
483
+ {route.kind === "doc" && commentsSidebarOpen ? (
484
+ <CommentsSidebar key="comments-sidebar" model={comments} onClose={closeComments} />
485
+ ) : null}
486
+ </AnimatePresence>
449
487
  </div>
450
488
  {route.kind === "doc" && comments.available && !commentsPanel.isDesktop ? (
451
489
  <CommentsSheet model={comments} open={commentsPanel.open} onClose={closeComments} />
@@ -27,6 +27,7 @@ export function TocRail({ path, version }: { path: string; version: number }) {
27
27
  return (
28
28
  <div
29
29
  ref={railRef}
30
+ data-toc-rail
30
31
  data-print-hide
31
32
  className="hidden xl:block shrink-0 self-start ml-10 sticky top-[calc(var(--topbar-height)+40px)]"
32
33
  style={{ width: clampWidth(width) }}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@karimsa/mdxserve",
3
- "version": "0.6.0-rc.1",
3
+ "version": "0.6.0-rc.3",
4
4
  "description": "Serve a directory of Markdown/MDX files, like `serve` but for docs",
5
5
  "license": "MIT",
6
6
  "repository": {