@tdacorp/hyle-sdk 0.17.0 → 0.21.0

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 (86) hide show
  1. package/README.md +155 -28
  2. package/dist/check-routes-bin.js +38 -13
  3. package/dist/chunk-56Y24XBV.js +840 -0
  4. package/dist/{chunk-MGSUQBDW.js → chunk-75JFLML4.js} +176 -14
  5. package/dist/chunk-HJX57NLI.js +1105 -0
  6. package/dist/chunk-K5VDLROQ.js +145 -0
  7. package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
  8. package/dist/chunk-U74B7AUG.js +398 -0
  9. package/dist/{chunk-6VOHFFA5.js → chunk-X2TLYM7Y.js} +2 -2
  10. package/dist/client-41fU6OY2.d.cts +201 -0
  11. package/dist/client-LwzHwqpM.d.ts +201 -0
  12. package/dist/code-copy.cjs +72 -0
  13. package/dist/code-copy.d.cts +15 -0
  14. package/dist/code-copy.d.ts +15 -0
  15. package/dist/code-copy.js +48 -0
  16. package/dist/comments.cjs +728 -275
  17. package/dist/comments.d.cts +66 -3
  18. package/dist/comments.d.ts +66 -3
  19. package/dist/comments.js +409 -326
  20. package/dist/{diagram-viewer-FJPED4SN.js → diagram-viewer-XY3CG75U.js} +62 -21
  21. package/dist/{embed-BmdwA2G9.d.cts → embed-BUFRQboD.d.ts} +2 -2
  22. package/dist/{embed-DNTZ2UXv.d.ts → embed-CYt-q13P.d.cts} +2 -2
  23. package/dist/fragment-alias.cjs +51 -0
  24. package/dist/fragment-alias.d.cts +7 -0
  25. package/dist/fragment-alias.d.ts +7 -0
  26. package/dist/fragment-alias.js +27 -0
  27. package/dist/html.cjs +881 -0
  28. package/dist/html.d.cts +20 -0
  29. package/dist/html.d.ts +20 -0
  30. package/dist/html.js +45 -0
  31. package/dist/index.cjs +181 -14
  32. package/dist/index.d.cts +14 -62
  33. package/dist/index.d.ts +14 -62
  34. package/dist/index.js +11 -1
  35. package/dist/{labels-nmukKYgL.d.ts → labels-CrA-iqTN.d.cts} +9 -0
  36. package/dist/{labels-nmukKYgL.d.cts → labels-CrA-iqTN.d.ts} +9 -0
  37. package/dist/mermaid-diagram.cjs +401 -125
  38. package/dist/mermaid-diagram.d.cts +23 -7
  39. package/dist/mermaid-diagram.d.ts +23 -7
  40. package/dist/mermaid-diagram.js +204 -51
  41. package/dist/mermaid-image.cjs +134 -60
  42. package/dist/mermaid-image.d.cts +4 -3
  43. package/dist/mermaid-image.d.ts +4 -3
  44. package/dist/mermaid-image.js +27 -28
  45. package/dist/next.cjs +627 -264
  46. package/dist/next.d.cts +11 -8
  47. package/dist/next.d.ts +11 -8
  48. package/dist/next.js +39 -12
  49. package/dist/print-coordinator.cjs +157 -0
  50. package/dist/print-coordinator.d.cts +27 -0
  51. package/dist/print-coordinator.d.ts +27 -0
  52. package/dist/print-coordinator.js +83 -0
  53. package/dist/react.cjs +556 -226
  54. package/dist/react.d.cts +136 -29
  55. package/dist/react.d.ts +136 -29
  56. package/dist/react.js +23 -3
  57. package/dist/reactions.cjs +653 -0
  58. package/dist/reactions.d.cts +27 -0
  59. package/dist/reactions.d.ts +27 -0
  60. package/dist/reactions.js +364 -0
  61. package/dist/{resolve-Ae7UFjsQ.d.ts → resolve-BjAK0k_Y.d.ts} +2 -2
  62. package/dist/{resolve-euZ4-aC9.d.cts → resolve-eI1muCKL.d.cts} +2 -2
  63. package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
  64. package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
  65. package/dist/sanitize-ijiWjEm9.d.cts +23 -0
  66. package/dist/sanitize-ijiWjEm9.d.ts +23 -0
  67. package/dist/styles.css +96 -25
  68. package/dist/toc-spy.cjs +59 -0
  69. package/dist/toc-spy.d.cts +15 -0
  70. package/dist/toc-spy.d.ts +15 -0
  71. package/dist/toc-spy.js +35 -0
  72. package/dist/{types-Czt887Iv.d.cts → types-3F0wqD-o.d.cts} +26 -2
  73. package/dist/{types-Czt887Iv.d.ts → types-3F0wqD-o.d.ts} +26 -2
  74. package/dist/use-cache.cjs +37 -11
  75. package/dist/use-cache.d.cts +12 -5
  76. package/dist/use-cache.d.ts +12 -5
  77. package/dist/use-cache.js +7 -7
  78. package/dist/youtube-facade.cjs +50 -0
  79. package/dist/youtube-facade.d.cts +17 -0
  80. package/dist/youtube-facade.d.ts +17 -0
  81. package/dist/youtube-facade.js +26 -0
  82. package/package.json +16 -3
  83. package/dist/chunk-DMK4XQLU.js +0 -1556
  84. package/dist/chunk-PJMJMP66.js +0 -63
  85. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  86. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
package/dist/comments.js CHANGED
@@ -1,134 +1,114 @@
1
1
  "use client";
2
+ import {
3
+ Icon,
4
+ ReactionBar,
5
+ arrangeThread,
6
+ arrivesAs,
7
+ call,
8
+ fetchNext,
9
+ fetchPages,
10
+ isObject,
11
+ isSortable,
12
+ kindName,
13
+ nextVote,
14
+ stillUnseen,
15
+ useReactions
16
+ } from "./chunk-U74B7AUG.js";
2
17
 
3
18
  // src/react/comments.tsx
4
- import { useCallback, useEffect as useEffect2, useId, useRef as useRef2, useState as useState2 } from "react";
19
+ import { useEffect as useEffect3, useId, useRef as useRef4, useState as useState4 } from "react";
5
20
 
6
- // src/react/comments-api.ts
7
- var CSRF_HEADER = "x-hyle-engage";
8
- var TIMEOUT_MS = 15e3;
9
- async function call(endpoint, method, path, body) {
10
- try {
11
- const res = await fetch(`${endpoint}${path}`, {
12
- method,
13
- credentials: "same-origin",
14
- cache: "no-store",
15
- headers: { accept: "application/json", [CSRF_HEADER]: "1", ...body ? { "content-type": "application/json" } : {} },
16
- ...body ? { body: JSON.stringify(body) } : {},
17
- signal: AbortSignal.timeout(TIMEOUT_MS)
18
- });
19
- let data;
20
- try {
21
- data = (await res.json()).data;
22
- } catch {
23
- }
24
- const retry = Number(res.headers.get("retry-after"));
25
- return { status: res.status, data, retryAfter: Number.isFinite(retry) && retry > 0 ? retry : void 0 };
26
- } catch {
27
- return { status: 0, data: void 0, retryAfter: void 0 };
28
- }
29
- }
30
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
31
- var count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.trunc(v) : 0;
32
- function toComment(raw) {
33
- if (!isObject(raw) || typeof raw.id !== "string" || typeof raw.created_at !== "string") return void 0;
34
- const depth = typeof raw.depth === "number" ? Math.min(4, Math.max(1, Math.trunc(raw.depth))) : 1;
35
- const author = isObject(raw.author) && typeof raw.author.name === "string" ? raw.author.name : void 0;
36
- const name = typeof raw.author_name === "string" ? raw.author_name : author;
37
- const body = isObject(raw.body) && raw.body.format === "hast" ? { format: "hast", tree: raw.body.tree } : null;
38
- const removed = raw.removed === true || body === null;
39
- return {
40
- id: raw.id,
41
- parent_id: typeof raw.parent_id === "string" ? raw.parent_id : null,
42
- depth,
43
- author_name: name ?? null,
44
- created_at: raw.created_at,
45
- edited_at: typeof raw.edited_at === "string" ? raw.edited_at : null,
46
- like_count: count(raw.like_count),
47
- removed,
48
- ...removed && (raw.removed_by === "moderator" || raw.removed_by === "author") ? { removed_by: raw.removed_by } : {},
49
- body,
50
- // Viewer members exist only on a live comment of a viewer-aware listing; a tombstone never carries them.
51
- ...!removed && typeof raw.mine === "boolean" ? { mine: raw.mine, liked_by_me: raw.liked_by_me === true, can_edit_until: typeof raw.can_edit_until === "string" ? raw.can_edit_until : null } : {}
52
- };
53
- }
54
- function toHeld(raw) {
55
- if (!isObject(raw) || typeof raw.id !== "string" || typeof raw.created_at !== "string" || !isObject(raw.body) || raw.body.format !== "hast") return void 0;
56
- const author = isObject(raw.author) && typeof raw.author.name === "string" ? raw.author.name : null;
57
- return {
58
- id: raw.id,
59
- parent_id: typeof raw.parent_id === "string" ? raw.parent_id : null,
60
- depth: typeof raw.depth === "number" ? Math.min(4, Math.max(1, Math.trunc(raw.depth))) : 1,
61
- author_name: author,
62
- created_at: raw.created_at,
63
- edited_at: typeof raw.edited_at === "string" ? raw.edited_at : null,
64
- can_edit_until: typeof raw.can_edit_until === "string" ? raw.can_edit_until : null,
65
- body: { format: "hast", tree: raw.body.tree }
66
- };
67
- }
68
- function parseListing(data) {
69
- if (!isObject(data) || data.kind !== "comments" || !Array.isArray(data.comments)) return void 0;
70
- const comments = data.comments.map(toComment).filter((c) => c !== void 0);
71
- const viewer = Array.isArray(data.mine_held) ? { liked_by_me: data.liked_by_me === true, mine_held: data.mine_held.slice(0, 5).map(toHeld).filter((h) => h !== void 0) } : {};
72
- return { cp: 1, kind: "comments", publication_id: String(data.publication_id ?? ""), comment_count: count(data.comment_count), like_count: count(data.like_count), truncated: data.truncated === true, comments, ...viewer };
73
- }
74
- var untilMs = (iso) => {
75
- const t = iso ? Date.parse(iso) : NaN;
76
- return Number.isFinite(t) ? t : void 0;
77
- };
78
- function buildThread(listing, localHeld) {
79
- const byId = /* @__PURE__ */ new Map();
80
- const roots = [];
81
- const place = (node, parentId) => {
82
- const parent = parentId ? byId.get(parentId) : void 0;
83
- (parent ? parent.kids : roots).push(node);
84
- };
85
- for (const c of listing.comments) {
86
- if (byId.has(c.id)) continue;
87
- const removed = c.removed;
88
- const node = {
89
- id: c.id,
90
- depth: c.depth,
91
- status: removed ? "removed" : "visible",
92
- removedBy: removed ? c.removed_by : void 0,
93
- mine: !removed && c.mine === true,
94
- canEditUntil: untilMs(c.can_edit_until),
95
- likedByMe: !removed && c.liked_by_me === true,
96
- name: removed ? null : c.author_name ?? null,
97
- createdAt: c.created_at,
98
- editedAt: c.edited_at,
99
- likes: c.like_count,
100
- tree: c.body?.tree,
101
- text: void 0,
102
- kids: []
103
- };
104
- place(node, c.parent_id === c.id ? null : c.parent_id);
105
- byId.set(c.id, node);
106
- }
107
- const mine = [];
108
- const addHeld = (node, parentId, oldestFirst) => {
109
- const parent = parentId ? byId.get(parentId) : void 0;
110
- if (parent) parent.kids.push(node);
111
- else if (oldestFirst) mine.unshift(node);
112
- else mine.push(node);
113
- };
114
- const heldIds = /* @__PURE__ */ new Set();
115
- for (const h of listing.mine_held ?? []) {
116
- heldIds.add(h.id);
117
- const parent = h.parent_id ? byId.get(h.parent_id) : void 0;
118
- addHeld({ id: h.id, depth: Math.min(4, (parent?.depth ?? h.depth - 1) + 1), status: "held", removedBy: void 0, mine: true, canEditUntil: untilMs(h.can_edit_until), likedByMe: false, name: h.author_name, createdAt: h.created_at, editedAt: h.edited_at, likes: 0, tree: h.body?.tree, text: void 0, kids: [] }, h.parent_id, true);
119
- }
120
- if (listing.mine_held === void 0) {
121
- for (const h of localHeld) {
122
- if (byId.has(h.id) || heldIds.has(h.id)) continue;
123
- const parent = h.parentId ? byId.get(h.parentId) : void 0;
124
- addHeld({ id: h.id, depth: Math.min(4, (parent?.depth ?? 0) + 1), status: "held", removedBy: void 0, mine: true, canEditUntil: void 0, likedByMe: false, name: h.name, createdAt: h.createdAt, editedAt: null, likes: 0, tree: void 0, text: h.text, kids: [] }, h.parentId, false);
125
- }
126
- }
127
- return [...mine, ...roots];
21
+ // src/react/comments-listing.ts
22
+ import { useCallback, useEffect, useRef, useState } from "react";
23
+ function useCommentListing(endpoint, path, initial, active, onFresh, onReset) {
24
+ const [listing, setListing] = useState(initial ?? "loading");
25
+ const [order, setOrder] = useState("newest");
26
+ const [served, setServed] = useState(void 0);
27
+ const data = useRef({ listing: initial, order: "newest", pages: 1, sort: void 0 });
28
+ const legacy = useRef(false);
29
+ const queue = useRef(Promise.resolve());
30
+ const generation = useRef(0);
31
+ const callbacks = useRef({ onFresh, onReset });
32
+ callbacks.current = { onFresh, onReset };
33
+ const enqueue = useCallback((op) => {
34
+ const mine = generation.current;
35
+ const stale = () => mine !== generation.current;
36
+ const job = queue.current.then(() => stale() ? void 0 : op(stale));
37
+ queue.current = job.catch(() => void 0);
38
+ return job;
39
+ }, []);
40
+ const commit = useCallback((next) => {
41
+ data.current = next;
42
+ setListing(next.listing);
43
+ setOrder(next.order);
44
+ setServed(next.sort);
45
+ }, []);
46
+ const learn = useCallback((asked, r) => {
47
+ if (asked === "newest" && r.listing && r.sort === void 0) legacy.current = true;
48
+ return r;
49
+ }, []);
50
+ const reload = useCallback(
51
+ (silent) => enqueue(async (stale) => {
52
+ const { order: current, pages } = data.current;
53
+ const r = learn(current, await fetchPages(endpoint, path, current, pages, legacy.current));
54
+ if (stale()) return void 0;
55
+ if (r.status === 404) setListing("off");
56
+ else if (r.listing) {
57
+ commit({ listing: r.listing, order: current, pages: r.pages, sort: r.sort });
58
+ callbacks.current.onFresh(r.listing);
59
+ } else if (!silent) setListing("error");
60
+ return r.listing;
61
+ }),
62
+ [endpoint, path, enqueue, commit, learn]
63
+ );
64
+ const sort = useCallback(
65
+ (next) => enqueue(async (stale) => {
66
+ if (next === data.current.order) return next;
67
+ const r = learn(next, await fetchPages(endpoint, path, next, 1, legacy.current));
68
+ if (stale()) return void 0;
69
+ if (!r.listing) return data.current.order;
70
+ commit({ listing: r.listing, order: next, pages: 1, sort: r.sort });
71
+ callbacks.current.onFresh(r.listing);
72
+ return next;
73
+ }),
74
+ [endpoint, path, enqueue, commit, learn]
75
+ );
76
+ const more = useCallback(
77
+ () => enqueue(async (stale) => {
78
+ const { listing: before, order: current, pages, sort: wire } = data.current;
79
+ if (!before?.next_cursor) return void 0;
80
+ const r = await fetchNext(endpoint, path, current, { listing: before, pages, sort: wire }, legacy.current);
81
+ if (stale()) return void 0;
82
+ if (r.restarted) learn(current, r);
83
+ if (!r.listing) return { ok: false };
84
+ const known = new Set(before.comments.map((c) => c.id));
85
+ commit({ listing: r.listing, order: current, pages: r.pages, sort: r.sort });
86
+ if (r.restarted) callbacks.current.onFresh(r.listing);
87
+ return { ok: true, listing: r.listing, sort: r.sort, added: new Set(r.listing.comments.filter((c) => !c.removed && !known.has(c.id)).map((c) => c.id)) };
88
+ }),
89
+ [endpoint, path, enqueue, commit, learn]
90
+ );
91
+ useEffect(() => {
92
+ data.current = { listing: initial, order: "newest", pages: 1, sort: void 0 };
93
+ legacy.current = false;
94
+ queue.current = Promise.resolve();
95
+ setListing(initial ?? "loading");
96
+ setOrder("newest");
97
+ setServed(void 0);
98
+ callbacks.current.onReset();
99
+ return () => void (generation.current += 1);
100
+ }, [endpoint, path, initial]);
101
+ useEffect(() => {
102
+ if (active) void reload(initial !== void 0);
103
+ }, [active, reload, initial]);
104
+ return { listing, order, served, reload, sort, more, retry: () => {
105
+ setListing("loading");
106
+ void reload(false);
107
+ } };
128
108
  }
129
109
 
130
110
  // src/react/comments-parts.tsx
131
- import { useEffect, useRef, useState } from "react";
111
+ import { useEffect as useEffect2, useRef as useRef3, useState as useState3 } from "react";
132
112
 
133
113
  // src/react/comments-body.tsx
134
114
  import { toJsxRuntime } from "hast-util-to-jsx-runtime";
@@ -164,8 +144,15 @@ var isScalar = (v) => typeof v === "string" || typeof v === "number" || typeof v
164
144
  var matches = (re) => (v) => typeof v === "string" && re.test(v);
165
145
  var ID_PREFIX = "user-content-";
166
146
  var scopeId = (id) => id.startsWith(ID_PREFIX) ? id : ID_PREFIX + id;
167
- var ID_BODY = /^[\p{L}\p{N}_:.-]{1,180}$/u;
168
- var isIdValue = (v) => typeof v === "string" && ID_BODY.test(v.startsWith(ID_PREFIX) ? v.slice(ID_PREFIX.length) : v);
147
+ var ID_BODY = /^[\p{L}\p{M}\p{N}\p{Pc}:.-]{1,180}$/u;
148
+ function isIdValue(v) {
149
+ if (typeof v !== "string") return false;
150
+ try {
151
+ return ID_BODY.test(decodeURIComponent(v.startsWith(ID_PREFIX) ? v.slice(ID_PREFIX.length) : v));
152
+ } catch {
153
+ return false;
154
+ }
155
+ }
169
156
  var CLASS_TOKEN = /^[A-Za-z_][\w:-]*$/;
170
157
  var classTokens = (v) => {
171
158
  const tokens = Array.isArray(v) ? v : typeof v === "string" ? v.split(/\s+/) : [];
@@ -178,6 +165,7 @@ var isLength = matches(/^[\d.]+(em|px|%)?$/);
178
165
  var STYLE_PROPS = /* @__PURE__ */ new Set(["height", "vertical-align", "margin-left", "margin-right", "margin-top", "margin-bottom", "top", "width", "min-width", "border-bottom-width", "padding-left"]);
179
166
  var STYLE_LENGTH = /^(-?\d+(?:\.\d+)?)(em|px|%)?$/;
180
167
  var MAX_STYLE_MAGNITUDE = 100;
168
+ var MAX_MARGIN_MAGNITUDE = 20;
181
169
  function isKatexStyle(v, ctx) {
182
170
  if (typeof v !== "string" || !ctx.katex) return false;
183
171
  return v.split(";").filter((d) => d !== "").every((decl) => {
@@ -185,7 +173,8 @@ function isKatexStyle(v, ctx) {
185
173
  if (extra.length > 0 || prop === void 0 || value === void 0) return false;
186
174
  if (prop === "position") return value === "relative";
187
175
  const m = STYLE_LENGTH.exec(value);
188
- return STYLE_PROPS.has(prop) && m !== null && Math.abs(Number(m[1])) <= MAX_STYLE_MAGNITUDE;
176
+ const max = prop.startsWith("margin-") ? MAX_MARGIN_MAGNITUDE : MAX_STYLE_MAGNITUDE;
177
+ return STYLE_PROPS.has(prop) && m !== null && Math.abs(Number(m[1])) <= max;
189
178
  });
190
179
  }
191
180
  function isSafeUrl(value, kind) {
@@ -210,6 +199,8 @@ var MERMAID_SRCDOC = new RegExp(
210
199
  var isMermaidSrcdoc = (v) => typeof v === "string" && v.length <= MAX_SRCDOC && MERMAID_SRCDOC.test(v);
211
200
  var RENDER_REF = /^(\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.svg) ([1-9]\d{0,5}) ([1-9]\d{0,5})$/;
212
201
  var isRenderRef = matches(RENDER_REF);
202
+ var YOUTUBE_WATCH = /^https:\/\/www\.youtube\.com\/watch\?v=([A-Za-z0-9_-]{11})$/;
203
+ var youtubeId = (href) => typeof href === "string" ? YOUTUBE_WATCH.exec(href)?.[1] : void 0;
213
204
  var heading = { id: isIdValue, className: isClass };
214
205
  var ATTRS = new Map(
215
206
  Object.entries({
@@ -225,6 +216,7 @@ var ATTRS = new Map(
225
216
  tbody: {},
226
217
  tr: {},
227
218
  ol: {},
219
+ kbd: {},
228
220
  ul: { className: isClass },
229
221
  li: { id: isIdValue, className: isClass },
230
222
  h1: heading,
@@ -233,8 +225,8 @@ var ATTRS = new Map(
233
225
  h4: heading,
234
226
  h5: heading,
235
227
  h6: heading,
236
- a: { href: isHref, id: isIdValue, ariaDescribedBy: isIdValue, ariaLabel: isString, dataFootnoteRef: isScalar, dataFootnoteBackref: isScalar, className: isClass },
237
- img: { src: isSrc, alt: isString, width: isPixels, height: isPixels },
228
+ a: { href: isHref, id: isIdValue, ariaDescribedBy: isIdValue, ariaLabel: isString, dataFootnoteRef: isScalar, dataFootnoteBackref: isScalar, dataEmbed: matches(/^youtube$/), className: isClass },
229
+ img: { src: isSrc, alt: isString, title: isString, width: isPixels, height: isPixels },
238
230
  table: {},
239
231
  th: { scope: matches(/^(row|col|rowgroup|colgroup)$/), align: isAlign },
240
232
  td: { align: isAlign },
@@ -257,8 +249,10 @@ function textOf(node, depth = 0) {
257
249
  if (node.type === "text") return typeof node.value === "string" ? node.value : "";
258
250
  return Array.isArray(node.children) ? node.children.map((c) => textOf(c, depth + 1)).join("") : "";
259
251
  }
252
+ var holdsEmbed = (node, depth = 0) => isObject2(node) && depth <= MAX_DEPTH && (isObject2(node.properties) && "dataEmbed" in node.properties || Array.isArray(node.children) && node.children.some((c) => holdsEmbed(c, depth + 1)));
253
+ var collapse = (text) => text.replace(/\s+/g, " ").trim();
260
254
  var CALLOUT_MARKER = /^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*/i;
261
- var CALLOUT_KIND = { note: "note", tip: "tip", important: "warning", warning: "warning", caution: "caution" };
255
+ var CALLOUT_KIND = { note: "note", tip: "tip", important: "important", warning: "warning", caution: "caution" };
262
256
  function toCallout(children) {
263
257
  const first = children.find((c) => c.type === "element");
264
258
  const lead = first?.tagName === "p" ? first.children[0] : void 0;
@@ -270,6 +264,21 @@ function toCallout(children) {
270
264
  const kind = CALLOUT_KIND[(marker[1] ?? "note").toLowerCase()] ?? "note";
271
265
  return { type: "element", tagName: "callout", properties: { kind }, children: [...body, ...children.slice(children.indexOf(first) + 1)] };
272
266
  }
267
+ var isBlank = (node) => node.type === "text" && node.value.trim() === "";
268
+ function soleElement(children) {
269
+ const [only, ...more] = children.filter((c) => !isBlank(c));
270
+ return more.length === 0 && only?.type === "element" ? only : void 0;
271
+ }
272
+ function toFigure(children) {
273
+ const only = soleElement(children);
274
+ const img = only?.tagName === "a" ? soleElement(only.children) : only;
275
+ if (!only || img?.tagName !== "img" || typeof img.properties.src !== "string") return void 0;
276
+ const { title, ...properties } = img.properties;
277
+ const bare = { ...img, properties };
278
+ const media = only === img ? bare : { ...only, children: [bare] };
279
+ const caption = typeof title === "string" && title.trim() ? [{ type: "element", tagName: "figcaption", properties: {}, children: [{ type: "text", value: title }] }] : [];
280
+ return { type: "element", tagName: "figure", properties: { dataSlotComponent: "Image" }, children: [media, ...caption] };
281
+ }
273
282
  function clean(node, depth, ctx, budget) {
274
283
  if (!isObject2(node) || depth > MAX_DEPTH) return [];
275
284
  if (++budget.nodes > MAX_NODES) throw new HastLimitError("content has too many nodes");
@@ -303,6 +312,11 @@ function clean(node, depth, ctx, budget) {
303
312
  }
304
313
  for (const key of ["id", "ariaDescribedBy"]) if (typeof properties[key] === "string") properties[key] = scopeId(properties[key]);
305
314
  if (tag === "a" && typeof properties.href === "string" && properties.href.trim().startsWith("#")) properties.href = `#${scopeId(properties.href.trim().slice(1))}`;
315
+ if (tag === "a" && properties.dataEmbed !== void 0 && youtubeId(properties.href) === void 0) delete properties.dataEmbed;
316
+ if (tag === "p") {
317
+ const figure = toFigure(children);
318
+ if (figure) return [figure];
319
+ }
306
320
  if (tag === "blockquote") {
307
321
  const callout = toCallout(children);
308
322
  if (callout) return [callout];
@@ -314,9 +328,9 @@ function sanitizeHast(tree, title, description) {
314
328
  const raw = isObject2(tree) && tree.type === "root" && Array.isArray(tree.children) ? tree.children : [];
315
329
  const elements = raw.filter((n) => isObject2(n) && n.type === "element");
316
330
  const [first] = elements;
317
- const skip = title !== void 0 && isObject2(first) && first.tagName === "h1" && textOf(first).trim() === title.trim() ? first : void 0;
331
+ const skip = title !== void 0 && isObject2(first) && first.tagName === "h1" && collapse(textOf(first)) === collapse(title) ? first : void 0;
318
332
  const lead = elements[skip ? 1 : 0];
319
- const repeat = description && isObject2(lead) && lead.tagName === "p" && textOf(lead).trim().startsWith(description.trim()) ? lead : void 0;
333
+ const repeat = description && isObject2(lead) && lead.tagName === "p" && collapse(textOf(lead)).startsWith(collapse(description)) && !holdsEmbed(lead) ? lead : void 0;
320
334
  const budget = { nodes: 0, text: 0 };
321
335
  return { type: "root", children: raw.filter((n) => n !== skip && n !== repeat).flatMap((n) => clean(n, 0, { katex: false }, budget)) };
322
336
  }
@@ -401,56 +415,58 @@ function hastToMarkdown(tree) {
401
415
  }
402
416
  }
403
417
 
404
- // src/react/icons.tsx
405
- import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
406
- var SHAPES = {
407
- info: /* @__PURE__ */ jsxs2(Fragment2, { children: [
408
- /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
409
- /* @__PURE__ */ jsx3("path", { d: "M8 7.3V11M8 5v.1" })
410
- ] }),
411
- "check-circle": /* @__PURE__ */ jsxs2(Fragment2, { children: [
412
- /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
413
- /* @__PURE__ */ jsx3("path", { d: "m5.3 8.3 1.9 1.9 3.5-3.9" })
414
- ] }),
415
- alert: /* @__PURE__ */ jsx3("path", { d: "M8 2 1.8 13h12.4zM8 6.5v3M8 11.3v.1" }),
416
- "x-circle": /* @__PURE__ */ jsxs2(Fragment2, { children: [
417
- /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
418
- /* @__PURE__ */ jsx3("path", { d: "m5.8 5.8 4.4 4.4M10.2 5.8l-4.4 4.4" })
419
- ] }),
420
- calendar: /* @__PURE__ */ jsxs2(Fragment2, { children: [
421
- /* @__PURE__ */ jsx3("rect", { x: "2", y: "3", width: "12", height: "11", rx: "1.3" }),
422
- /* @__PURE__ */ jsx3("path", { d: "M2 6.5h12M5.5 1.7v2.6M10.5 1.7v2.6" })
423
- ] }),
424
- globe: /* @__PURE__ */ jsxs2(Fragment2, { children: [
425
- /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
426
- /* @__PURE__ */ jsx3("path", { d: "M2 8h12M8 2c2 1.7 2.8 3.7 2.8 6S10 12.3 8 14M8 2C6 3.7 5.2 5.7 5.2 8S6 12.3 8 14" })
427
- ] }),
428
- file: /* @__PURE__ */ jsxs2(Fragment2, { children: [
429
- /* @__PURE__ */ jsx3("path", { d: "M4 1.8h5l3 3v8.4a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2.8a1 1 0 0 1 1-1z" }),
430
- /* @__PURE__ */ jsx3("path", { d: "M9 1.8v3h3" })
431
- ] }),
432
- chev: /* @__PURE__ */ jsx3("path", { d: "m6 3.5 4.5 4.5L6 12.5" }),
433
- "chev-down": /* @__PURE__ */ jsx3("path", { d: "m3.5 6 4.5 4.5L12.5 6" }),
434
- "chev-left": /* @__PURE__ */ jsx3("path", { d: "M10 3.5 5.5 8 10 12.5" }),
435
- x: /* @__PURE__ */ jsx3("path", { d: "m4 4 8 8M12 4l-8 8" }),
436
- heart: /* @__PURE__ */ jsx3("path", { d: "M8 13.5S2.2 10 2.2 6.1A3 3 0 0 1 8 5a3 3 0 0 1 5.8 1.1C13.8 10 8 13.5 8 13.5z" }),
437
- reply: /* @__PURE__ */ jsx3("path", { d: "M6.5 3.5 2.5 7.5l4 4M2.5 7.5h6a5 5 0 0 1 5 5" }),
438
- clock: /* @__PURE__ */ jsxs2(Fragment2, { children: [
439
- /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
440
- /* @__PURE__ */ jsx3("path", { d: "M8 4.5V8l2.3 1.5" })
441
- ] }),
442
- ban: /* @__PURE__ */ jsxs2(Fragment2, { children: [
443
- /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
444
- /* @__PURE__ */ jsx3("path", { d: "m3.8 12.2 8.4-8.4" })
445
- ] }),
446
- refresh: /* @__PURE__ */ jsx3("path", { d: "M13 8a5 5 0 1 1-1.6-3.7M13 2.5v2.8h-2.8" })
447
- };
448
- function Icon({ name, className }) {
449
- return /* @__PURE__ */ jsx3("svg", { className: className ? `hyle-ic ${className}` : "hyle-ic", viewBox: "0 0 16 16", "aria-hidden": "true", children: SHAPES[name] });
418
+ // src/react/comments-votes.tsx
419
+ import { useRef as useRef2, useState as useState2 } from "react";
420
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
421
+ function useVotes(endpoint) {
422
+ const [overlay, setOverlay] = useState2({});
423
+ const pending = useRef2(/* @__PURE__ */ new Set());
424
+ async function cast(id, current, clicked) {
425
+ if (pending.current.has(id)) return void 0;
426
+ const next = nextVote(current, clicked);
427
+ pending.current.add(id);
428
+ setOverlay((o) => ({ ...o, [id]: next }));
429
+ const r = await call(endpoint, next.value === null ? "DELETE" : "PUT", "/votes", next.value === null ? { comment_id: id } : { comment_id: id, value: next.value });
430
+ pending.current.delete(id);
431
+ const vote = r.status === 200 && isObject(r.data) && isObject(r.data.vote) ? r.data.vote : void 0;
432
+ if (vote && Number.isSafeInteger(vote.score)) {
433
+ const state = { value: vote.value === 1 || vote.value === -1 ? vote.value : null, score: vote.score };
434
+ setOverlay((o) => ({ ...o, [id]: state }));
435
+ return { ok: true, state };
436
+ }
437
+ setOverlay((o) => ({ ...o, [id]: current }));
438
+ return { ok: false, status: r.status };
439
+ }
440
+ function settle(listing) {
441
+ const known = new Set(listing.comments.filter((c) => c.my_vote !== void 0).map((c) => c.id));
442
+ setOverlay((o) => Object.fromEntries(Object.entries(o).flatMap(([id, v]) => pending.current.has(id) ? [[id, v]] : v.value !== null && !known.has(id) ? [[id, { value: v.value }]] : [])));
443
+ }
444
+ return { overlay, cast, settle, reset: () => setOverlay({}) };
445
+ }
446
+ function VoteButtons({ s, name, state, own, access, signInHref, onVote }) {
447
+ function arrow(value) {
448
+ if (own) return null;
449
+ const icon = /* @__PURE__ */ jsx3(Icon, { name: value === 1 ? "chev-up" : "chev-down" });
450
+ const label = value === 1 ? s.upvote : s.downvote;
451
+ if (access === "out") return /* @__PURE__ */ jsxs2("a", { className: "hyle-cm-btn", href: signInHref, children: [
452
+ icon,
453
+ /* @__PURE__ */ jsx3("span", { className: "hyle-sr", children: value === 1 ? s.upvoteSignIn : s.downvoteSignIn })
454
+ ] });
455
+ if (access !== "in") return /* @__PURE__ */ jsx3("button", { className: "hyle-cm-btn", type: "button", "aria-disabled": "true", "aria-label": label, children: icon });
456
+ return /* @__PURE__ */ jsx3("button", { className: "hyle-cm-btn", type: "button", "aria-label": label, "aria-pressed": state.value === value, onClick: () => onVote(value), children: icon });
457
+ }
458
+ return /* @__PURE__ */ jsxs2("span", { className: "hyle-cm-votes", role: "group", "aria-label": s.votesOn.replace("{name}", () => name), children: [
459
+ arrow(1),
460
+ /* @__PURE__ */ jsxs2("span", { className: "hyle-cm-score", children: [
461
+ /* @__PURE__ */ jsx3("span", { className: "hyle-sr", children: s.score.replace("{n}", String(state.score)) }),
462
+ /* @__PURE__ */ jsx3("span", { "aria-hidden": "true", children: state.score })
463
+ ] }),
464
+ arrow(-1)
465
+ ] });
450
466
  }
451
467
 
452
468
  // src/react/comments-parts.tsx
453
- import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
469
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
454
470
  var MAX_CHARS = 4e3;
455
471
  var EDIT_WINDOW_MS = 10 * 60 * 1e3;
456
472
  var MAX_DEPTH2 = 4;
@@ -458,6 +474,7 @@ var fill = (template, values) => template.replace(/\{(\w+)\}/g, (_, k) => String
458
474
  var initials = (name) => name.trim().split(/\s+/).slice(0, 2).map((w) => [...w][0] ?? "").join("").toUpperCase() || "?";
459
475
  var replyButtonId = (ui, id) => `${ui.idp}-reply-${id}`;
460
476
  var nameId = (ui, id) => `${ui.idp}-${id}-n`;
477
+ var accessOf = (ui) => !ui.ready ? "pending" : !ui.me ? "out" : ui.banned ? "blocked" : "in";
461
478
  function relative(iso, now, locale, s) {
462
479
  const seconds = Math.round((now - Date.parse(iso)) / 1e3);
463
480
  if (!Number.isFinite(seconds)) return iso;
@@ -485,51 +502,14 @@ function Avatar({ name }) {
485
502
  function SignInLink({ ui, className, children }) {
486
503
  return /* @__PURE__ */ jsx4("a", { className, href: `#${ui.signInId}`, children });
487
504
  }
488
- function LikeButton({ ui, itemKey, serverCount, serverOn, scope }) {
489
- const { s } = ui;
490
- const state = ui.likes[itemKey];
491
- const count2 = state?.count ?? serverCount;
492
- const on = state?.on ?? serverOn;
493
- const cls = scope === "article" ? "hyle-btn" : "hyle-cm-btn cnt";
494
- const lead = scope === "article" ? on ? s.likedArticle : s.likeArticle : null;
495
- const sr = scope === "article" ? ", " : s.likeComment;
496
- const icon = /* @__PURE__ */ jsx4(Icon, { name: "heart" });
497
- if (ui.ready && !ui.me) {
498
- return /* @__PURE__ */ jsxs3(SignInLink, { ui, className: cls, children: [
499
- icon,
500
- lead ?? null,
501
- scope === "article" ? /* @__PURE__ */ jsxs3(Fragment3, { children: [
502
- " ",
503
- /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: s.likeArticleSignIn })
504
- ] }) : /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: s.likeCommentSignIn }),
505
- /* @__PURE__ */ jsx4("span", { children: count2 })
506
- ] });
507
- }
508
- if (ui.banned || !ui.ready) {
509
- return /* @__PURE__ */ jsxs3("button", { className: cls, type: "button", "aria-disabled": "true", children: [
510
- icon,
511
- lead,
512
- scope === "article" ? " " : null,
513
- /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: sr }),
514
- /* @__PURE__ */ jsx4("span", { children: count2 })
515
- ] });
516
- }
517
- return /* @__PURE__ */ jsxs3("button", { className: cls, type: "button", "aria-pressed": on, onClick: () => ui.actions.like(itemKey, serverCount, serverOn), children: [
518
- icon,
519
- lead,
520
- scope === "article" ? " " : null,
521
- /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: sr }),
522
- /* @__PURE__ */ jsx4("span", { children: count2 })
523
- ] });
524
- }
525
505
  function Composer({ ui, id, parentId, name, autoFocus, onCancel }) {
526
506
  const { s } = ui;
527
- const [text, setText] = useState("");
528
- const [busy, setBusy] = useState(false);
529
- const [error, setError] = useState(null);
530
- const area = useRef(null);
507
+ const [text, setText] = useState3("");
508
+ const [busy, setBusy] = useState3(false);
509
+ const [error, setError] = useState3(null);
510
+ const area = useRef3(null);
531
511
  const limited = ui.rateLeft > 0;
532
- useEffect(() => {
512
+ useEffect2(() => {
533
513
  if (autoFocus) area.current?.focus();
534
514
  }, [autoFocus]);
535
515
  async function submit() {
@@ -607,11 +587,11 @@ function Composer({ ui, id, parentId, name, autoFocus, onCancel }) {
607
587
  }
608
588
  function EditForm({ ui, node, initial }) {
609
589
  const { s } = ui;
610
- const [text, setText] = useState(initial);
611
- const [busy, setBusy] = useState(false);
612
- const [error, setError] = useState(null);
613
- const area = useRef(null);
614
- useEffect(() => area.current?.focus(), []);
590
+ const [text, setText] = useState3(initial);
591
+ const [busy, setBusy] = useState3(false);
592
+ const [error, setError] = useState3(null);
593
+ const area = useRef3(null);
594
+ useEffect2(() => area.current?.focus(), []);
615
595
  const id = `${ui.idp}-edit-${node.id}`;
616
596
  async function save() {
617
597
  if (busy) return;
@@ -669,15 +649,18 @@ function Actions({ ui, node }) {
669
649
  const until = node.canEditUntil ?? (local ? local.at + EDIT_WINDOW_MS : void 0);
670
650
  const minutes = until === void 0 ? 0 : Math.min(10, Math.ceil((until - Math.max(ui.now, local?.at ?? 0)) / 6e4));
671
651
  const canReply = node.depth < MAX_DEPTH2 && node.status === "visible";
652
+ const vote = ui.votes[node.id];
653
+ const shownVote = { value: vote ? vote.value : node.myVote ?? null, score: vote?.score ?? node.score ?? 0 };
672
654
  if (ui.confirming === node.id) {
673
655
  return /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-acts", role: "group", "aria-label": s.deleteConfirm, children: [
674
656
  /* @__PURE__ */ jsx4("span", { className: "hyle-cm-depth", children: s.deleteConfirm }),
675
657
  /* @__PURE__ */ jsx4("button", { className: "hyle-cm-btn danger", type: "button", onClick: () => ui.actions.remove(node.id), children: s.delete }),
676
658
  /* @__PURE__ */ jsx4("button", { className: "hyle-cm-btn", type: "button", autoFocus: true, onClick: () => ui.actions.confirm(null), children: s.keep })
677
- ] });
659
+ ] }, "confirm");
678
660
  }
679
661
  return /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-acts", children: [
680
- node.status === "visible" ? /* @__PURE__ */ jsx4(LikeButton, { ui, itemKey: node.id, serverCount: node.likes, serverOn: node.likedByMe, scope: "comment" }) : null,
662
+ node.status === "visible" && node.score !== void 0 ? /* @__PURE__ */ jsx4(VoteButtons, { s, name: node.name ?? "", state: shownVote, own: mine, access: accessOf(ui), signInHref: `#${ui.signInId}`, onVote: (clicked) => ui.actions.vote(node.id, shownVote, clicked) }) : null,
663
+ node.status === "visible" ? /* @__PURE__ */ jsx4(ReactionBar, { s, scope: "comment", subject: node.id, likes: node.likes, counts: node.reactions, likedByMe: node.likedByMe, mine: node.myReactions, overlay: ui.reactions, access: accessOf(ui), signInHref: `#${ui.signInId}`, onToggle: (kind, count, on) => ui.actions.react(node.id, kind, count, on) }) : null,
681
664
  canReply && ui.me && !ui.banned ? /* @__PURE__ */ jsxs3("button", { className: "hyle-cm-btn", type: "button", id: replyButtonId(ui, node.id), "aria-label": fill(s.replyTo, { name: node.name ?? "" }), "aria-expanded": ui.replyOpen === node.id, onClick: () => ui.actions.reply(ui.replyOpen === node.id ? null : node.id), children: [
682
665
  /* @__PURE__ */ jsx4(Icon, { name: "reply" }),
683
666
  s.reply
@@ -725,7 +708,7 @@ function CommentItem({ ui, node }) {
725
708
  mine ? /* @__PURE__ */ jsx4("span", { className: "hyle-cm-tag", children: s.you }) : null,
726
709
  /* @__PURE__ */ jsxs3("span", { children: [
727
710
  /* @__PURE__ */ jsx4("time", { dateTime: node.createdAt, title: absolute(node.createdAt, ui.locale), children: relative(node.createdAt, ui.now, ui.locale, s) }),
728
- node.editedAt ? /* @__PURE__ */ jsxs3(Fragment3, { children: [
711
+ node.editedAt ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
729
712
  " ",
730
713
  /* @__PURE__ */ jsx4("span", { "aria-hidden": "true", children: "\xB7" }),
731
714
  " ",
@@ -733,7 +716,7 @@ function CommentItem({ ui, node }) {
733
716
  ] }) : null
734
717
  ] })
735
718
  ] }),
736
- editing ? /* @__PURE__ */ jsx4(EditForm, { ui, node, initial: local?.text ?? node.text ?? hastToMarkdown(node.tree) }) : node.text !== void 0 ? /* @__PURE__ */ jsx4("div", { className: "hyle-cm-body", children: /* @__PURE__ */ jsx4("p", { style: { whiteSpace: "pre-wrap" }, children: node.text }) }) : /* @__PURE__ */ jsx4(CommentBody, { tree: node.tree }),
719
+ editing ? /* @__PURE__ */ jsx4(EditForm, { ui, node, initial: local?.text ?? node.text ?? hastToMarkdown(node.tree) }) : node.text !== void 0 ? /* @__PURE__ */ jsx4("div", { className: "hyle-cm-body", children: /* @__PURE__ */ jsx4("p", { style: { whiteSpace: "pre-wrap" }, children: node.text }) }) : node.unrenderable ? /* @__PURE__ */ jsx4("div", { className: "hyle-cm-body", children: /* @__PURE__ */ jsx4("p", { children: s.unrenderable }) }) : /* @__PURE__ */ jsx4(CommentBody, { tree: node.tree }),
737
720
  node.status === "held" ? /* @__PURE__ */ jsxs3("p", { className: "hyle-cm-held", role: "status", children: [
738
721
  /* @__PURE__ */ jsx4(Icon, { name: "clock" }),
739
722
  /* @__PURE__ */ jsxs3("span", { children: [
@@ -751,114 +734,179 @@ function CommentItem({ ui, node }) {
751
734
  }
752
735
 
753
736
  // src/react/comments.tsx
754
- import { Fragment as Fragment4, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
737
+ import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
755
738
  var PAGE = 20;
756
739
  var TICK_MS = 1e4;
757
- var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
740
+ var NEAR = "600px 0px";
741
+ var firstOf = (nodes, wanted) => {
742
+ for (const n of nodes) {
743
+ const found = wanted.has(n.id) ? n.id : firstOf(n.kids, wanted);
744
+ if (found) return found;
745
+ }
746
+ return void 0;
747
+ };
758
748
  var fill2 = (t, n) => t.replace("{n}", String(n));
759
- function Comments({ path, endpoint, signInHref, locale, labels: s, initial, initialAt }) {
749
+ var readerOf = (data) => {
750
+ const reader = isObject(data) && isObject(data.reader) ? data.reader : void 0;
751
+ if (typeof reader?.name !== "string") return void 0;
752
+ return { id: typeof reader.id === "string" ? reader.id : reader.name, name: reader.name };
753
+ };
754
+ function Comments(props) {
755
+ const [readers, setReaders] = useState4(0);
756
+ return /* @__PURE__ */ jsx5(ArticleComments, { ...props, onNewReader: () => setReaders((n) => n + 1) }, `${props.endpoint}
757
+ ${props.path}
758
+ ${readers}`);
759
+ }
760
+ function ArticleComments({ path, endpoint, signInHref, locale, labels: s, initial, initialAt, lazy = false, articleReactions = true, onNewReader }) {
760
761
  const idp = `hc${useId().replace(/[^A-Za-z0-9]/g, "")}`;
761
- const [session, setSession] = useState2("loading");
762
- const [listing, setListing] = useState2(initial ?? "loading");
763
- const [own, setOwn] = useState2({});
764
- const [held, setHeld] = useState2([]);
765
- const [likes, setLikes] = useState2({});
766
- const [replyOpen, setReplyOpen] = useState2(null);
767
- const [editing, setEditing] = useState2(null);
768
- const [confirming, setConfirming] = useState2(null);
769
- const [banned, setBanned] = useState2(false);
770
- const [expired, setExpired] = useState2(false);
771
- const [rateUntil, setRateUntil] = useState2(0);
772
- const [now, setNow] = useState2(() => initialAt ?? Date.now());
773
- const [live, setLive] = useState2("");
774
- const [actionError, setActionError] = useState2(null);
775
- const [shown, setShown] = useState2(PAGE);
776
- const [focusId, setFocusId] = useState2(null);
777
- const pending = useRef2(/* @__PURE__ */ new Set());
778
- const alive = useRef2(true);
779
- const write404 = useRef2(0);
780
- useEffect2(() => {
762
+ const [session, setSession] = useState4("loading");
763
+ const [own, setOwn] = useState4({});
764
+ const [held, setHeld] = useState4([]);
765
+ const [unseen, setUnseen] = useState4([]);
766
+ const [replyOpen, setReplyOpen] = useState4(null);
767
+ const [editing, setEditing] = useState4(null);
768
+ const [confirming, setConfirming] = useState4(null);
769
+ const [banned, setBanned] = useState4(false);
770
+ const [expired, setExpired] = useState4(false);
771
+ const [rateUntil, setRateUntil] = useState4(0);
772
+ const [now, setNow] = useState4(() => initialAt ?? Date.now());
773
+ const [live, setLive] = useState4("");
774
+ const [actionError, setActionError] = useState4(null);
775
+ const [shown, setShown] = useState4(PAGE);
776
+ const [focusId, setFocusId] = useState4(null);
777
+ const [near, setNear] = useState4(!lazy);
778
+ const [chosen, setChosen] = useState4("newest");
779
+ const [loadingMore, setLoadingMore] = useState4(false);
780
+ const [moreFailed, setMoreFailed] = useState4(false);
781
+ const root = useRef4(null);
782
+ const sortClicks = useRef4(0);
783
+ const reactions = useReactions(endpoint, path);
784
+ const votes = useVotes(endpoint);
785
+ const { listing, order, served, reload, sort, more, retry } = useCommentListing(
786
+ endpoint,
787
+ path,
788
+ initial,
789
+ near,
790
+ (fresh) => {
791
+ reactions.settle(fresh);
792
+ votes.settle(fresh);
793
+ },
794
+ () => {
795
+ reactions.reset();
796
+ votes.reset();
797
+ setUnseen([]);
798
+ setChosen("newest");
799
+ setLoadingMore(false);
800
+ setMoreFailed(false);
801
+ }
802
+ );
803
+ const alive = useRef4(true);
804
+ const write404 = useRef4(0);
805
+ useEffect3(() => {
781
806
  alive.current = true;
782
807
  return () => void (alive.current = false);
783
808
  }, []);
784
- useEffect2(() => {
809
+ useEffect3(() => {
785
810
  if (initialAt !== void 0) setNow(Date.now());
786
811
  const t = setInterval(() => setNow(Date.now()), TICK_MS);
787
812
  return () => clearInterval(t);
788
813
  }, [initialAt]);
789
- useEffect2(() => {
814
+ useEffect3(() => {
790
815
  if (rateUntil <= Date.now()) return;
791
816
  const t = setTimeout(() => setNow(Date.now()), rateUntil - Date.now() + 50);
792
817
  return () => clearTimeout(t);
793
818
  }, [rateUntil]);
794
- const load = useCallback(async (silent) => {
795
- const r = await call(endpoint, "GET", `/comments?path=${encodeURIComponent(path)}`);
796
- if (!alive.current) return void 0;
797
- const parsed = r.status === 200 ? parseListing(r.data) : void 0;
798
- if (r.status === 404) setListing("off");
799
- else if (parsed) {
800
- setListing(parsed);
801
- setLikes((l) => Object.fromEntries(Object.entries(l).filter(([k]) => pending.current.has(k))));
802
- } else if (!silent) setListing("error");
803
- return parsed;
804
- }, [endpoint, path]);
805
- useEffect2(() => {
806
- setListing(initial ?? "loading");
807
- void load(initial !== void 0);
819
+ useEffect3(() => {
820
+ if (near) return;
821
+ const el = root.current;
822
+ if (!el || typeof IntersectionObserver === "undefined") return setNear(true);
823
+ const observer = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && setNear(true), { rootMargin: NEAR });
824
+ observer.observe(el);
825
+ return () => observer.disconnect();
826
+ }, [near]);
827
+ useEffect3(() => {
828
+ if (!near) return;
808
829
  void call(endpoint, "GET", "/session").then((r) => {
809
830
  if (!alive.current) return;
810
- const reader = isObject3(r.data) && isObject3(r.data.reader) ? r.data.reader : void 0;
811
- setSession(r.status === 404 ? "off" : r.status === 200 && typeof reader?.name === "string" ? { name: reader.name } : null);
831
+ const reader = r.status === 200 ? readerOf(r.data) : void 0;
832
+ setSession(r.status === 404 ? "off" : reader ?? null);
812
833
  });
813
- }, [endpoint, load, initial]);
814
- useEffect2(() => {
834
+ }, [endpoint, near]);
835
+ useEffect3(() => {
836
+ if (typeof listing === "object") setUnseen((u) => stillUnseen(u, listing));
837
+ }, [listing]);
838
+ useEffect3(() => {
815
839
  if (!focusId) return;
816
840
  const el = document.getElementById(`${idp}-${focusId}-n`);
817
841
  if (el) {
818
842
  el.focus();
819
843
  setFocusId(null);
820
844
  }
821
- }, [focusId, listing, held, idp]);
822
- const me = typeof session === "object" && session ? session.name : null;
845
+ }, [focusId, listing, held, unseen, idp]);
846
+ const signedIn = typeof session === "object" ? session : null;
847
+ const me = signedIn?.name ?? null;
823
848
  const rateLeft = Math.max(0, Math.ceil((rateUntil - now) / 1e3));
824
849
  const signInId = `${idp}-signin`;
825
- function failed(status) {
850
+ async function recheck(status) {
851
+ if (status !== 401 && !expired) return;
852
+ const r = await call(endpoint, "GET", "/session");
853
+ const reader = r.status === 200 ? readerOf(r.data) : void 0;
854
+ if (alive.current && reader && reader.id !== signedIn?.id) onNewReader();
855
+ }
856
+ function failed(status, refusal) {
826
857
  if (status === 401) setExpired(true);
827
- setActionError(status === 401 ? s.expired : s.actionError);
858
+ setActionError(status === 401 ? s.expired : status === 429 ? s.slowDown : refusal ?? s.actionError);
828
859
  }
829
- async function like(key, serverCount, serverOn) {
830
- if (!me || banned || pending.current.has(key)) return;
831
- const prev = likes[key] ?? { on: serverOn, count: serverCount };
832
- const count2 = prev.count ?? serverCount;
833
- pending.current.add(key);
860
+ async function react(subject, kind, count, on) {
861
+ if (!me || banned) return;
834
862
  setActionError(null);
835
- setLikes((l) => ({ ...l, [key]: { on: !prev.on, count: Math.max(0, count2 + (prev.on ? -1 : 1)) } }));
836
- const r = await call(endpoint, prev.on ? "DELETE" : "PUT", "/reactions", key === "article" ? { subject_type: "article", path } : { subject_type: "comment", comment_id: key });
837
- pending.current.delete(key);
838
- if (!alive.current) return;
839
- const reaction = r.status === 200 && isObject3(r.data) && isObject3(r.data.reaction) ? r.data.reaction : void 0;
840
- if (reaction && typeof reaction.like_count === "number") {
841
- setLikes((l) => ({ ...l, [key]: { on: reaction.active === true, count: reaction.like_count } }));
842
- return;
863
+ const r = await reactions.toggle(subject, kind, count, on);
864
+ if (!r || !alive.current) return;
865
+ void recheck(r.ok ? 200 : r.status);
866
+ if (!r.ok) return failed(r.status);
867
+ setLive((r.on ? s.reactionAddedLive : s.reactionRemovedLive).replace("{kind}", kindName(s, kind)));
868
+ }
869
+ async function vote(id, current, clicked) {
870
+ if (!me || banned) return;
871
+ setActionError(null);
872
+ const r = await votes.cast(id, current, clicked);
873
+ if (!r || !alive.current) return;
874
+ void recheck(r.ok ? 200 : r.status);
875
+ if (!r.ok) return failed(r.status, r.status === 400 ? s.voteRefused : void 0);
876
+ setLive(fill2(r.state.value === 1 ? s.upvotedLive : r.state.value === -1 ? s.downvotedLive : s.voteRemovedLive, r.state.score));
877
+ }
878
+ async function choose(next) {
879
+ if (next === chosen) return;
880
+ const click = sortClicks.current += 1;
881
+ setChosen(next);
882
+ setActionError(null);
883
+ setMoreFailed(false);
884
+ const showing = await sort(next);
885
+ if (!alive.current || click !== sortClicks.current || showing === void 0) return;
886
+ if (showing !== next) {
887
+ setChosen(showing);
888
+ return setActionError(s.sortError);
843
889
  }
844
- setLikes((l) => ({ ...l, [key]: { on: prev.on, count: count2 } }));
845
- failed(r.status);
890
+ setShown(PAGE);
891
+ setLive(next === "top" ? s.sortedTopLive : s.sortedNewestLive);
846
892
  }
847
893
  async function post(text, parentId) {
848
894
  const r = await call(endpoint, "POST", "/comments", { path, body: text, ...parentId ? { parent_id: parentId } : {} });
849
- const created = r.status === 201 && isObject3(r.data) && isObject3(r.data.comment) ? r.data.comment : void 0;
895
+ void recheck(r.status);
896
+ const created = r.status === 201 && isObject(r.data) && isObject(r.data.comment) ? r.data.comment : void 0;
850
897
  if (typeof created?.id === "string" && alive.current) {
851
898
  const id = created.id;
852
899
  write404.current = 0;
853
900
  setOwn((o) => ({ ...o, [id]: { text, at: Date.now(), parentId } }));
854
901
  setExpired(false);
855
- if (created.status === "held") {
856
- setHeld((h) => [{ id, parentId, text, name: me ?? "", createdAt: (/* @__PURE__ */ new Date()).toISOString() }, ...h]);
857
- setLive(s.heldLive);
858
- } else setLive(s.postedLive);
902
+ const status = created.status === "held" ? "held" : "visible";
903
+ const local = { id, parentId, text, name: me ?? "", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
904
+ setUnseen((u) => [{ ...local, status }, ...u]);
905
+ if (status === "held") setHeld((h) => [local, ...h]);
906
+ setLive(status === "held" ? s.heldLive : s.postedLive);
859
907
  setShown(Number.MAX_SAFE_INTEGER);
860
908
  setFocusId(id);
861
- await load(true);
909
+ await reload(true);
862
910
  return { ok: true };
863
911
  }
864
912
  if (r.status === 429) {
@@ -867,10 +915,11 @@ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, init
867
915
  return { ok: false, reason: "rate" };
868
916
  }
869
917
  if (r.status === 404) {
870
- const [again, who] = await Promise.all([load(true), call(endpoint, "GET", "/session")]);
918
+ const [again, who] = await Promise.all([reload(true), call(endpoint, "GET", "/session")]);
871
919
  write404.current += 1;
872
- const valid = who.status === 200 && isObject3(who.data) && isObject3(who.data.reader) && typeof who.data.reader.name === "string";
873
- if (alive.current && valid && again && write404.current >= 2) setBanned(true);
920
+ const reader = who.status === 200 ? readerOf(who.data) : void 0;
921
+ if (alive.current && reader && reader.id !== signedIn?.id) onNewReader();
922
+ else if (alive.current && reader && again && write404.current >= 2) setBanned(true);
874
923
  return { ok: false, reason: "error" };
875
924
  }
876
925
  if (r.status === 401) setExpired(true);
@@ -878,15 +927,20 @@ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, init
878
927
  }
879
928
  async function save(id, text) {
880
929
  const r = await call(endpoint, "PATCH", `/comments/${id}`, { body: text });
930
+ void recheck(r.status);
881
931
  if (r.status === 200 && alive.current) {
882
932
  const meta = own[id];
883
933
  setOwn((o) => ({ ...o, [id]: { text, at: o[id]?.at ?? Date.now(), parentId: o[id]?.parentId ?? null } }));
884
934
  setHeld((h) => h.map((c) => c.id === id ? { ...c, text } : c));
935
+ setUnseen((u) => u.map((c) => c.id === id ? { ...c, text } : c));
885
936
  setEditing(null);
886
937
  setLive(s.savedLive);
887
938
  setFocusId(id);
888
- const fresh = await load(true);
889
- if (fresh && !fresh.comments.some((c) => c.id === id)) setHeld((h) => h.some((c) => c.id === id) ? h : [{ id, parentId: meta?.parentId ?? null, text, name: me ?? "", createdAt: (/* @__PURE__ */ new Date()).toISOString() }, ...h]);
939
+ const fresh = await reload(true);
940
+ if (fresh && !fresh.truncated && !fresh.next_cursor && !fresh.comments.some((c) => c.id === id)) {
941
+ setUnseen((u) => u.filter((c) => c.id !== id));
942
+ setHeld((h) => h.some((c) => c.id === id) ? h : [{ id, parentId: meta?.parentId ?? null, text, name: me ?? "", createdAt: (/* @__PURE__ */ new Date()).toISOString() }, ...h]);
943
+ }
890
944
  return { ok: true };
891
945
  }
892
946
  if (r.status === 429) {
@@ -901,15 +955,38 @@ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, init
901
955
  setActionError(null);
902
956
  const r = await call(endpoint, "DELETE", `/comments/${id}`);
903
957
  if (!alive.current) return;
958
+ void recheck(r.status);
904
959
  setConfirming(null);
905
960
  if (r.status !== 200) return failed(r.status);
906
961
  setHeld((h) => h.filter((c) => c.id !== id));
962
+ setUnseen((u) => u.filter((c) => c.id !== id));
907
963
  setOwn(({ [id]: _gone, ...rest }) => rest);
908
964
  setLive(s.deletedLive);
909
- await load(true);
965
+ await reload(true);
910
966
  }
911
- if (session === "off" || listing === "off") return null;
912
967
  const loaded = typeof listing === "object" ? listing : void 0;
968
+ const sortable = !!loaded && isSortable(loaded);
969
+ const thread = loaded ? arrangeThread(loaded, served, held, unseen) : [];
970
+ const oldestFirstPages = !!loaded && arrivesAs(loaded, served) === void 0;
971
+ async function showMore() {
972
+ if (thread.length > shown) {
973
+ setShown(shown + PAGE);
974
+ setFocusId(thread.slice(shown).find((n) => n.status !== "removed")?.id ?? null);
975
+ return;
976
+ }
977
+ if (loadingMore) return;
978
+ setLoadingMore(true);
979
+ setMoreFailed(false);
980
+ const r = await more();
981
+ if (!alive.current) return;
982
+ setLoadingMore(false);
983
+ if (!r) return;
984
+ if (!r.ok) return setMoreFailed(true);
985
+ setShown(arrivesAs(r.listing, r.sort) === void 0 ? Number.MAX_SAFE_INTEGER : Math.min(shown, thread.length) + PAGE);
986
+ setFocusId(firstOf(arrangeThread(r.listing, r.sort, held, unseen), r.added) ?? null);
987
+ setLive(fill2(s.loadedLive, r.added.size));
988
+ }
989
+ if (session === "off" || listing === "off") return null;
913
990
  const ui = {
914
991
  s,
915
992
  locale,
@@ -917,17 +994,18 @@ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, init
917
994
  ready: session !== "loading",
918
995
  me,
919
996
  banned,
920
- signInHref,
921
997
  signInId,
922
998
  idp,
923
999
  rateLeft,
924
1000
  own,
925
- likes,
1001
+ reactions: reactions.overlay,
1002
+ votes: votes.overlay,
926
1003
  replyOpen,
927
1004
  editing,
928
1005
  confirming,
929
1006
  actions: {
930
- like: (k, c, on) => void like(k, c, on),
1007
+ react: (subject, kind, count, on) => void react(subject, kind, count, on),
1008
+ vote: (id, current, clicked) => void vote(id, current, clicked),
931
1009
  reply: (id) => {
932
1010
  const previous = replyOpen;
933
1011
  setReplyOpen(id);
@@ -940,17 +1018,20 @@ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, init
940
1018
  remove: (id) => void remove(id)
941
1019
  }
942
1020
  };
943
- const thread = loaded ? buildThread(loaded, held) : [];
944
1021
  const hid = `${idp}-h`;
945
1022
  const canWrite = !!me && !banned;
946
- return /* @__PURE__ */ jsxs4("section", { className: "hyle-comments", "aria-labelledby": hid, "data-slot-component": "Comments", children: [
947
- /* @__PURE__ */ jsx5("div", { className: "hyle-cm-head", children: /* @__PURE__ */ jsxs4("h2", { id: hid, children: [
948
- s.heading,
949
- loaded ? /* @__PURE__ */ jsxs4(Fragment4, { children: [
950
- " ",
951
- /* @__PURE__ */ jsx5("span", { className: "hyle-cm-count", "aria-label": fill2(s.countLabel, loaded.comment_count), children: loaded.comment_count })
952
- ] }) : null
953
- ] }) }),
1023
+ const unfetched = !!loaded?.next_cursor;
1024
+ return /* @__PURE__ */ jsxs4("section", { className: "hyle-comments", ref: root, "aria-labelledby": hid, "data-slot-component": "Comments", children: [
1025
+ /* @__PURE__ */ jsxs4("div", { className: "hyle-cm-head", children: [
1026
+ /* @__PURE__ */ jsxs4("h2", { id: hid, children: [
1027
+ s.heading,
1028
+ loaded ? /* @__PURE__ */ jsxs4(Fragment3, { children: [
1029
+ " ",
1030
+ /* @__PURE__ */ jsx5("span", { className: "hyle-cm-count", "aria-label": fill2(s.countLabel, loaded.comment_count), children: loaded.comment_count })
1031
+ ] }) : null
1032
+ ] }),
1033
+ sortable && (order === "top" || thread.length > 1) ? /* @__PURE__ */ jsx5("div", { className: "hyle-cm-sort", role: "group", "aria-label": s.sort, children: ["newest", "top"].map((o) => /* @__PURE__ */ jsx5("button", { className: "hyle-cm-btn", type: "button", "aria-pressed": chosen === o, onClick: () => void choose(o), children: o === "top" ? s.sortTop : s.sortNewest }, o)) }) : null
1034
+ ] }),
954
1035
  /* @__PURE__ */ jsx5("p", { className: "hyle-sr", role: "status", "aria-live": "polite", children: live }),
955
1036
  actionError ? /* @__PURE__ */ jsxs4("p", { className: "hyle-cm-err", role: "alert", children: [
956
1037
  /* @__PURE__ */ jsx5(Icon, { name: "alert" }),
@@ -962,15 +1043,12 @@ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, init
962
1043
  /* @__PURE__ */ jsx5("b", { children: s.loadError }),
963
1044
  /* @__PURE__ */ jsx5("p", { children: s.loadErrorBody })
964
1045
  ] }),
965
- /* @__PURE__ */ jsxs4("button", { className: "hyle-btn sm", type: "button", onClick: () => {
966
- setListing("loading");
967
- void load(false);
968
- }, children: [
1046
+ /* @__PURE__ */ jsxs4("button", { className: "hyle-btn sm", type: "button", onClick: retry, children: [
969
1047
  /* @__PURE__ */ jsx5(Icon, { name: "refresh" }),
970
1048
  s.retry
971
1049
  ] })
972
- ] }) : /* @__PURE__ */ jsxs4(Fragment4, { children: [
973
- loaded ? /* @__PURE__ */ jsx5("div", { className: "hyle-react", children: /* @__PURE__ */ jsx5(LikeButton, { ui, itemKey: "article", serverCount: loaded.like_count, serverOn: loaded.liked_by_me === true, scope: "article" }) }) : null,
1050
+ ] }) : /* @__PURE__ */ jsxs4(Fragment3, { children: [
1051
+ loaded && articleReactions ? /* @__PURE__ */ jsx5("div", { className: "hyle-react", children: /* @__PURE__ */ jsx5(ReactionBar, { s, scope: "article", subject: "article", likes: loaded.like_count, counts: loaded.reaction_counts, likedByMe: loaded.liked_by_me === true, mine: loaded.my_reactions, overlay: reactions.overlay, access: accessOf(ui), signInHref: `#${signInId}`, onToggle: (kind, count, on) => void react("article", kind, count, on) }) }) : null,
974
1052
  held.length > 0 || (loaded?.mine_held?.length ?? 0) > 0 ? /* @__PURE__ */ jsxs4("div", { className: "hyle-banner", "data-kind": "warn", role: "status", children: [
975
1053
  /* @__PURE__ */ jsx5(Icon, { name: "clock" }),
976
1054
  /* @__PURE__ */ jsxs4("div", { className: "hyle-bt", children: [
@@ -1013,10 +1091,15 @@ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, init
1013
1091
  ] }) : thread.length === 0 ? /* @__PURE__ */ jsxs4("div", { className: "hyle-cm-empty", children: [
1014
1092
  /* @__PURE__ */ jsx5("b", { children: s.empty }),
1015
1093
  /* @__PURE__ */ jsx5("span", { children: s.emptyBody })
1016
- ] }) : /* @__PURE__ */ jsxs4(Fragment4, { children: [
1094
+ ] }) : /* @__PURE__ */ jsxs4(Fragment3, { children: [
1095
+ sortable && oldestFirstPages && unfetched ? /* @__PURE__ */ jsx5("p", { className: "hyle-cm-note", children: s.newerLater }) : null,
1017
1096
  /* @__PURE__ */ jsx5(Thread, { ui, nodes: thread.slice(0, shown) }),
1018
- thread.length > shown ? /* @__PURE__ */ jsx5("div", { className: "hyle-cm-more", children: /* @__PURE__ */ jsx5("button", { className: "hyle-btn", type: "button", onClick: () => setShown((n) => n + PAGE), children: s.more }) }) : null,
1019
- loaded.truncated ? /* @__PURE__ */ jsx5("p", { className: "hyle-cm-note", children: s.truncated }) : null
1097
+ moreFailed ? /* @__PURE__ */ jsxs4("p", { className: "hyle-cm-err", role: "alert", children: [
1098
+ /* @__PURE__ */ jsx5(Icon, { name: "alert" }),
1099
+ /* @__PURE__ */ jsx5("span", { children: s.moreError })
1100
+ ] }) : null,
1101
+ thread.length > shown || unfetched ? /* @__PURE__ */ jsx5("div", { className: "hyle-cm-more", children: /* @__PURE__ */ jsx5("button", { className: "hyle-btn", type: "button", "aria-disabled": loadingMore || void 0, "aria-busy": loadingMore || void 0, onClick: () => void showMore(), children: s.more }) }) : null,
1102
+ loaded.truncated && !unfetched ? /* @__PURE__ */ jsx5("p", { className: "hyle-cm-note", children: s.truncated }) : null
1020
1103
  ] })
1021
1104
  ] })
1022
1105
  ] });