@jant/core 1.0.1 → 1.2.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 (148) hide show
  1. package/bin/lib/site-snapshot.js +10 -0
  2. package/dist/{app-Gt7_skt6.js → app-CbOZ2Irh.js} +8704 -5180
  3. package/dist/client/.vite/manifest.json +125 -85
  4. package/dist/client/_assets/chunks/{confirm-D7GrwsCN.js → confirm-CMe01lne.js} +1 -1
  5. package/dist/client/_assets/chunks/{create-editor-5Y49x7h5.js → create-editor-hWapNE40.js} +26 -26
  6. package/dist/client/_assets/chunks/footnote-rail-9zwl6jtV.js +2 -0
  7. package/dist/client/_assets/chunks/{jant-locale-picker-DL6mIOT5.js → jant-locale-picker-2L4rkDaz.js} +1 -1
  8. package/dist/client/_assets/chunks/lit-Bw_voPoW.js +2 -0
  9. package/dist/client/_assets/chunks/preload-helper-Czpn1I53.js +1 -0
  10. package/dist/client/_assets/chunks/runtime-paths-y0_gHowM.js +1 -0
  11. package/dist/client/_assets/chunks/{settings-paths-h6RjIe3C.js → settings-paths-BBVT8zKj.js} +1 -1
  12. package/dist/client/_assets/chunks/slug-format-BuCPjSrB.js +1 -0
  13. package/dist/client/_assets/chunks/sortable-list-DJXwkaOv.js +2 -0
  14. package/dist/client/_assets/chunks/types-DrYFqJH2.js +1 -0
  15. package/dist/client/_assets/chunks/{unsafe-html-B5ZEXaxg.js → unsafe-html-CWos3v6N.js} +1 -1
  16. package/dist/client/_assets/chunks/unsafe-svg-CUrgo4Xg.js +1 -0
  17. package/dist/client/_assets/client-BO8GOFfT.js +354 -0
  18. package/dist/client/_assets/client-D8Rrsd73.css +2 -0
  19. package/dist/client/_assets/client-auth-CsUGM718.js +859 -0
  20. package/dist/client/_assets/client-author-QPm1whbO.css +2 -0
  21. package/dist/client/_assets/client-compose-BB4U7Wz0.js +2004 -0
  22. package/dist/client/_assets/{client-manage-C1eDB1Rc.js → client-manage-CI9-eh-8.js} +176 -176
  23. package/dist/client/_assets/{client-settings-DIM44Zqh.js → client-settings-BnGPuqwc.js} +166 -166
  24. package/dist/client/_assets/client-share-0DICJjAc.css +1 -0
  25. package/dist/client/_assets/client-share-C59mOLJ1.js +149 -0
  26. package/dist/index.js +1 -1
  27. package/dist/node.js +3 -2
  28. package/package.json +2 -1
  29. package/src/app.tsx +9 -0
  30. package/src/client/components/compose-types.ts +1 -0
  31. package/src/client/components/jant-compose-dialog.ts +1 -0
  32. package/src/client/components/jant-compose-editor.ts +30 -0
  33. package/src/client/components/jant-compose-fullscreen.ts +1 -0
  34. package/src/client/components/jant-post-menu.ts +80 -13
  35. package/src/client/components/jant-share-dialog.ts +422 -0
  36. package/src/client/components/jant-share-menu.ts +188 -0
  37. package/src/client/compose-bridge.ts +61 -1
  38. package/src/client/feed-video-player.ts +6 -0
  39. package/src/client/lazy-entries.ts +21 -1
  40. package/src/client/post-menu-shared.ts +100 -0
  41. package/src/client/share-capture.ts +443 -0
  42. package/src/client/share-launch.ts +133 -0
  43. package/src/client/tiptap/bubble-menu.ts +25 -2
  44. package/src/client/tiptap/create-editor.ts +2 -0
  45. package/src/client/tiptap/extensions.ts +4 -0
  46. package/src/client/video-processor.ts +106 -52
  47. package/src/client/view-confirm.ts +108 -0
  48. package/src/client-share.ts +8 -0
  49. package/src/client.ts +2 -0
  50. package/src/db/migrations/0035_brainy_next_avengers.sql +9 -0
  51. package/src/db/migrations/0036_gorgeous_smasher.sql +7 -0
  52. package/src/db/migrations/meta/0035_snapshot.json +2877 -0
  53. package/src/db/migrations/meta/0036_snapshot.json +2924 -0
  54. package/src/db/migrations/meta/_journal.json +14 -0
  55. package/src/db/migrations/pg/0033_cute_magdalene.sql +10 -0
  56. package/src/db/migrations/pg/0034_material_agent_brand.sql +8 -0
  57. package/src/db/migrations/pg/meta/0033_snapshot.json +3719 -0
  58. package/src/db/migrations/pg/meta/0034_snapshot.json +3766 -0
  59. package/src/db/migrations/pg/meta/_journal.json +14 -0
  60. package/src/db/pg/schema.ts +40 -0
  61. package/src/db/schema.ts +61 -0
  62. package/src/i18n/locales/public/en.po +5 -0
  63. package/src/i18n/locales/public/en.ts +1 -1
  64. package/src/i18n/locales/public/zh-Hans.po +5 -0
  65. package/src/i18n/locales/public/zh-Hans.ts +1 -1
  66. package/src/i18n/locales/public/zh-Hant.po +5 -0
  67. package/src/i18n/locales/public/zh-Hant.ts +1 -1
  68. package/src/i18n/locales/settings/en.po +149 -0
  69. package/src/i18n/locales/settings/en.ts +1 -1
  70. package/src/i18n/locales/settings/zh-Hans.po +149 -0
  71. package/src/i18n/locales/settings/zh-Hans.ts +1 -1
  72. package/src/i18n/locales/settings/zh-Hant.po +149 -0
  73. package/src/i18n/locales/settings/zh-Hant.ts +1 -1
  74. package/src/lib/discover.ts +31 -0
  75. package/src/lib/env.ts +20 -0
  76. package/src/lib/github-app-state.ts +1 -1
  77. package/src/lib/github-app.ts +183 -1
  78. package/src/lib/markdown-manager.ts +129 -1
  79. package/src/lib/post-meta.ts +13 -3
  80. package/src/lib/referrer-aliases.ts +311 -0
  81. package/src/lib/render.tsx +10 -0
  82. package/src/lib/resolve-config.ts +14 -0
  83. package/src/lib/share-card.ts +653 -0
  84. package/src/lib/summary.ts +152 -54
  85. package/src/lib/tiptap-render.ts +1 -0
  86. package/src/lib/upload.ts +21 -1
  87. package/src/lib/version.ts +2 -0
  88. package/src/lib/video-playback.ts +55 -0
  89. package/src/lib/view-buffer.ts +201 -0
  90. package/src/lib/view-counting.ts +539 -0
  91. package/src/lib/view-token.ts +177 -0
  92. package/src/lib/view.ts +13 -1
  93. package/src/middleware/view-counter.ts +140 -0
  94. package/src/node/runtime.ts +4 -0
  95. package/src/preset.css +31 -14
  96. package/src/routes/api/media.ts +21 -3
  97. package/src/routes/auth/setup.tsx +37 -1
  98. package/src/routes/dash/settings.tsx +433 -168
  99. package/src/routes/pages/archive.tsx +1 -0
  100. package/src/routes/pages/collection.tsx +6 -0
  101. package/src/routes/pages/collections.tsx +1 -0
  102. package/src/routes/pages/featured.tsx +1 -0
  103. package/src/routes/pages/home.tsx +1 -0
  104. package/src/routes/pages/page.tsx +3 -0
  105. package/src/routes/pages/partials.tsx +23 -0
  106. package/src/routes/pages/smart-collection.tsx +2 -0
  107. package/src/routes/pages/subscribe.tsx +1 -0
  108. package/src/routes/view-confirm.ts +63 -0
  109. package/src/services/export-theme/assets/client-site.js +1 -1
  110. package/src/services/export-theme/styles/main.css +39 -21
  111. package/src/services/export.ts +2 -0
  112. package/src/services/index.ts +17 -0
  113. package/src/services/mcp.ts +31 -1
  114. package/src/services/media.ts +63 -0
  115. package/src/services/stats.ts +1130 -0
  116. package/src/style-share.css +16 -0
  117. package/src/styles/components-author.css +177 -0
  118. package/src/styles/components.css +25 -3
  119. package/src/styles/share.css +1103 -0
  120. package/src/styles/tokens.css +65 -30
  121. package/src/styles/ui.css +62 -13
  122. package/src/types/app-context.ts +9 -0
  123. package/src/types/bindings.ts +5 -0
  124. package/src/types/config.ts +54 -0
  125. package/src/types/views.ts +6 -0
  126. package/src/ui/compose/ComposeDialog.tsx +6 -0
  127. package/src/ui/dash/settings/SettingsRootContent.tsx +24 -6
  128. package/src/ui/dash/settings/StatsContent.tsx +855 -0
  129. package/src/ui/font-themes.ts +39 -6
  130. package/src/ui/layouts/BaseLayout.tsx +11 -2
  131. package/src/ui/layouts/SiteLayout.tsx +9 -3
  132. package/src/ui/share/ShareCard.tsx +298 -0
  133. package/src/ui/shared/Icon.tsx +23 -3
  134. package/src/ui/shared/MediaGallery.tsx +31 -4
  135. package/src/ui/shared/PostFooter.tsx +20 -4
  136. package/src/ui/shared/icon-collector.ts +28 -0
  137. package/src/ui/shared/post-article-attributes.ts +3 -0
  138. package/dist/client/_assets/chunks/footnote-rail-BJwswtVQ.js +0 -1
  139. package/dist/client/_assets/chunks/lit-DW8VmJAT.js +0 -2
  140. package/dist/client/_assets/chunks/slug-format-Dsi0e9Xn.js +0 -1
  141. package/dist/client/_assets/chunks/sortable-list-DWNKv782.js +0 -2
  142. package/dist/client/_assets/chunks/types-D5iF3H1a.js +0 -1
  143. package/dist/client/_assets/chunks/unsafe-svg-DTZZEvLU.js +0 -2
  144. package/dist/client/_assets/client-BaqmpPQ-.css +0 -2
  145. package/dist/client/_assets/client-C6melOtG.js +0 -296
  146. package/dist/client/_assets/client-auth-Ccq8kSqq.js +0 -828
  147. package/dist/client/_assets/client-author-CGVvrNZ8.css +0 -2
  148. package/dist/client/_assets/client-compose-oxzPb3SS.js +0 -2004
@@ -0,0 +1,653 @@
1
+ /**
2
+ * Share card assembly.
3
+ *
4
+ * The author's "Share as image" turns a post into a PNG in the browser; the
5
+ * server decides what the card says. The card is its own design — a sheet
6
+ * of paper mounted on a mat tinted from the site's theme — but it speaks
7
+ * the site's language: its fonts and colors, each format's own marks (a
8
+ * link's domain, a quote's quotation mark), and the summary the timeline
9
+ * shows, cut where the author's "read more" break or the summary limits
10
+ * cut it. Every image is read from this origin, because the browser can
11
+ * only paint images it is allowed to read onto a canvas.
12
+ *
13
+ * A post in a Thread is set on the Thread's rail, as the timeline sets a
14
+ * Thread's newest post: the Thread's first post in up to three lines, the
15
+ * run between folded to a few dots, a line of the post after, and its place
16
+ * in the Thread: just enough to say which Thread this is and that it is one
17
+ * post of several, however long the Thread runs.
18
+ */
19
+
20
+ import type { Context } from "hono";
21
+ import { renderSVG } from "uqr";
22
+ import type { Bindings, Media, Post, PostView } from "../types.js";
23
+ import type { AppVariables } from "../types/app-context.js";
24
+ import { buildMediaMap } from "./media-helpers.js";
25
+ import {
26
+ ARTICLE_SUMMARY_MAX_BLOCKS,
27
+ ARTICLE_SUMMARY_MAX_CHARS,
28
+ NOTE_SUMMARY_MAX_BLOCKS,
29
+ NOTE_SUMMARY_MAX_CHARS,
30
+ NOTE_SUMMARY_MIN_HIDDEN_CHARS,
31
+ extractSummaryHtml,
32
+ } from "./summary.js";
33
+ import {
34
+ buildSiteUrl,
35
+ extractDisplayDomain,
36
+ sanitizeUrl,
37
+ toPublicPath,
38
+ } from "./url.js";
39
+ import { createMediaContext, toPostView } from "./view.js";
40
+
41
+ type Env = { Bindings: Bindings; Variables: AppVariables };
42
+
43
+ /** Images at the top of a card; beyond these the last one counts the rest. */
44
+ export const SHARE_CARD_MAX_IMAGES = 4;
45
+
46
+ /**
47
+ * Images a wordless post of the Thread shows around the shared one; beyond
48
+ * these the last one counts the rest.
49
+ */
50
+ export const SHARE_CARD_CONTEXT_IMAGES = 3;
51
+
52
+ /** Files listed under a card; beyond these a line counts the rest. */
53
+ export const SHARE_CARD_MAX_FILES = 3;
54
+
55
+ /**
56
+ * Characters of a context post's text the card carries. The card shows up
57
+ * to three lines of it; this only keeps the markup small.
58
+ */
59
+ const CONTEXT_TEXT_CHARS = 200;
60
+
61
+ /** Quotes up to this many characters are set larger. */
62
+ const SHORT_QUOTE_CHARS = 30;
63
+ /** Quotes past this many characters are set smaller. */
64
+ const LONG_QUOTE_CHARS = 90;
65
+
66
+ /**
67
+ * Which card a post gets. Notes split on the title: a titled note reads as
68
+ * an article and leads with its title.
69
+ */
70
+ export type ShareCardLayout = "note" | "article" | "link" | "quote";
71
+
72
+ export interface ShareCardImage {
73
+ /** Same-origin URL, so the capture can read its pixels. */
74
+ url: string;
75
+ /** A video's poster: the card marks it as one. */
76
+ video: boolean;
77
+ /**
78
+ * Pixel size, when stored. A lone image keeps its own shape on the card,
79
+ * and the size lets the card lay it out before the image loads.
80
+ */
81
+ width?: number;
82
+ height?: number;
83
+ }
84
+
85
+ /**
86
+ * An attachment the card cannot show as a picture: a document, a sound, a
87
+ * text, or a video without a poster. Listed by name, with its format and
88
+ * the one number that says how much of it there is.
89
+ */
90
+ export interface ShareCardFile {
91
+ kind: "document" | "audio" | "video" | "text";
92
+ /** Format in capitals — "PDF", "EPUB", "M4A", "MD". */
93
+ format: string;
94
+ title: string;
95
+ /** Bytes, for a document. */
96
+ size?: number;
97
+ /** Seconds, for a sound or a video. */
98
+ durationSeconds?: number;
99
+ /** Characters, for a text. */
100
+ chars?: number;
101
+ }
102
+
103
+ /**
104
+ * The Thread's first post or the post after the shared one, shown quieter
105
+ * than it: its title and words, or, for a post with no words, its images.
106
+ */
107
+ export interface ShareCardThreadPost {
108
+ format: Post["format"];
109
+ /** A titled note's or a link's title, or an untitled link's domain. */
110
+ title?: string;
111
+ /**
112
+ * Its words: a note's or a link's text, or a quote's words; for a post
113
+ * with no words and no images, its first file ("PDF · Annual report").
114
+ */
115
+ text?: string;
116
+ /** A quote's source: who said it, and where. */
117
+ source?: string;
118
+ /**
119
+ * Its images, when it has no words: what the post is, as the timeline
120
+ * shows it, a few of them at a size that reads.
121
+ */
122
+ images?: ShareCardImage[];
123
+ /** Images beyond the ones shown. */
124
+ moreImages?: number;
125
+ }
126
+
127
+ /**
128
+ * Where the shared post sits in its Thread: the Thread's first post above
129
+ * it, as the timeline leads a Thread, the posts between folded away, and
130
+ * the post after it below.
131
+ */
132
+ export interface ShareCardThread {
133
+ /** 1-based place among the Thread's published posts. */
134
+ position: number;
135
+ /** Published posts in the Thread. */
136
+ total: number;
137
+ /** The Thread's first post, unless that is the shared post. */
138
+ root: ShareCardThreadPost | null;
139
+ /** Posts between `root` and the shared one, folded away. */
140
+ hidden: number;
141
+ /** The post just after the shared one. */
142
+ next: ShareCardThreadPost | null;
143
+ }
144
+
145
+ export interface ShareCardView {
146
+ layout: ShareCardLayout;
147
+ siteName: string;
148
+ /** Same-origin URL of the site avatar, or null when the site has none. */
149
+ avatarUrl: string | null;
150
+ /** Publish date as the timeline formats it. */
151
+ date: string;
152
+ /** Article title (titled notes only). */
153
+ title?: string;
154
+ /** Summary HTML from the TipTap renderer; trusted. */
155
+ bodyHtml?: string;
156
+ /** Whether the post continues past `bodyHtml`. */
157
+ hasMore: boolean;
158
+ /** Quote posts: the quoted text, how large to set it, and its source. */
159
+ quote?: {
160
+ text: string;
161
+ size: "short" | "medium" | "long";
162
+ attribution?: string;
163
+ source?: string;
164
+ };
165
+ /** Link posts: the page the post points at. */
166
+ link?: { title?: string; domain?: string };
167
+ /**
168
+ * Images at the top of the card: attachments (video posters included),
169
+ * or a link's preview image when it has none.
170
+ */
171
+ images: ShareCardImage[];
172
+ /** Images beyond the ones shown. */
173
+ moreImages: number;
174
+ /** Attachments listed under the text, in post order. */
175
+ files: ShareCardFile[];
176
+ /** Attachments beyond the ones listed. */
177
+ moreFiles: number;
178
+ /** Absolute address of the post, what the QR code encodes. */
179
+ permalink: string;
180
+ /**
181
+ * The site's address under its name, as a reader would type it: host and
182
+ * path prefix, no scheme. The post's own address is the QR code's to
183
+ * carry; a slug is too long to type from a picture. Null when the site's
184
+ * name already is its address.
185
+ */
186
+ siteAddress: string | null;
187
+ /** QR code for `permalink`, as SVG markup from `uqr`. */
188
+ qrSvg: string;
189
+ /** Name for the saved PNG, without extension: the post's slug. */
190
+ fileName: string;
191
+ /** Content language of the post, for the card's `lang`. */
192
+ language?: string;
193
+ /** The Thread around the post; absent when the post stands alone. */
194
+ thread?: ShareCardThread;
195
+ }
196
+
197
+ /** What the card builder needs to know about the site. */
198
+ export interface ShareCardSite {
199
+ siteName: string;
200
+ /** Storage key of the site avatar; empty when none is set. */
201
+ siteAvatar: string;
202
+ siteOrigin: string;
203
+ sitePathPrefix: string;
204
+ }
205
+
206
+ /**
207
+ * Whether a post can be shared as an image: a reader has to be able to open
208
+ * the address its QR code points at.
209
+ *
210
+ * @param post - Post record
211
+ * @returns True for published posts that are not Private
212
+ *
213
+ * @example
214
+ * ```ts
215
+ * canShareAsImage({ status: "published", visibility: "latest_hidden" }); // true
216
+ * canShareAsImage({ status: "draft", visibility: "public" }); // false
217
+ * ```
218
+ */
219
+ export function canShareAsImage(
220
+ post: Pick<Post, "status" | "visibility">,
221
+ ): boolean {
222
+ return post.status === "published" && post.visibility !== "private";
223
+ }
224
+
225
+ /**
226
+ * Same-origin path for a storage key. `/media/*` and `/sites/*` serve the
227
+ * site's public objects whatever CDN host the timeline links to.
228
+ */
229
+ function storagePath(storageKey: string, sitePathPrefix: string): string {
230
+ return toPublicPath(`/${storageKey}`, sitePathPrefix);
231
+ }
232
+
233
+ /** The stored pixel size of an image or a video, when it has one. */
234
+ function imageSize(item: Media): Pick<ShareCardImage, "width" | "height"> {
235
+ return item.width && item.height
236
+ ? { width: item.width, height: item.height }
237
+ : {};
238
+ }
239
+
240
+ function cardImages(
241
+ media: Media[],
242
+ previewImageKey: string | null,
243
+ sitePathPrefix: string,
244
+ ): { images: ShareCardImage[]; moreImages: number } {
245
+ const visuals: ShareCardImage[] = [];
246
+ for (const item of media) {
247
+ if (item.mimeType.startsWith("image/")) {
248
+ visuals.push({
249
+ url: storagePath(item.storageKey, sitePathPrefix),
250
+ video: false,
251
+ ...imageSize(item),
252
+ });
253
+ } else if (item.mimeType.startsWith("video/") && item.posterKey) {
254
+ visuals.push({
255
+ url: storagePath(item.posterKey, sitePathPrefix),
256
+ video: true,
257
+ ...imageSize(item),
258
+ });
259
+ }
260
+ }
261
+ if (visuals.length === 0 && previewImageKey) {
262
+ visuals.push({
263
+ url: storagePath(previewImageKey, sitePathPrefix),
264
+ video: false,
265
+ });
266
+ }
267
+ return {
268
+ images: visuals.slice(0, SHARE_CARD_MAX_IMAGES),
269
+ moreImages: Math.max(0, visuals.length - SHARE_CARD_MAX_IMAGES),
270
+ };
271
+ }
272
+
273
+ /** Formats whose file extension is not the name a reader knows them by. */
274
+ const FORMAT_BY_MIME: Record<string, string> = {
275
+ "application/pdf": "PDF",
276
+ "application/epub+zip": "EPUB",
277
+ "text/markdown": "MD",
278
+ "text/plain": "TXT",
279
+ };
280
+
281
+ /** The file's extension in capitals, or a name for its MIME type. */
282
+ function fileFormat(item: Media): string {
283
+ const extension = /\.([a-z0-9]{1,5})$/i.exec(item.originalName)?.[1];
284
+ if (extension) return extension.toUpperCase();
285
+ return (
286
+ FORMAT_BY_MIME[item.mimeType] ??
287
+ (item.mimeType.split("/")[1] ?? "").slice(0, 4).toUpperCase()
288
+ );
289
+ }
290
+
291
+ function withoutExtension(name: string): string {
292
+ return name.replace(/\.[a-z0-9]{1,5}$/i, "");
293
+ }
294
+
295
+ /**
296
+ * Attachments a picture cannot show. Images and videos with a poster are at
297
+ * the top of the card; everything else is listed, so a post whose point is
298
+ * a PDF or a recording does not lose it.
299
+ */
300
+ function cardFiles(media: Media[]): {
301
+ files: ShareCardFile[];
302
+ moreFiles: number;
303
+ } {
304
+ const files: ShareCardFile[] = [];
305
+ for (const item of media) {
306
+ if (item.mimeType.startsWith("image/")) continue;
307
+ const isVideo = item.mimeType.startsWith("video/");
308
+ if (isVideo && item.posterKey) continue;
309
+ const name = withoutExtension(item.originalName) || item.alt || "";
310
+ if (item.mimeType.startsWith("text/")) {
311
+ files.push({
312
+ kind: "text",
313
+ format: fileFormat(item),
314
+ title: item.summary?.trim().split("\n")[0] || name,
315
+ chars: item.chars ?? undefined,
316
+ });
317
+ } else if (isVideo || item.mimeType.startsWith("audio/")) {
318
+ files.push({
319
+ kind: isVideo ? "video" : "audio",
320
+ format: fileFormat(item),
321
+ title: name,
322
+ durationSeconds: item.durationSeconds ?? undefined,
323
+ });
324
+ } else {
325
+ files.push({
326
+ kind: "document",
327
+ format: fileFormat(item),
328
+ title: name,
329
+ size: item.size,
330
+ });
331
+ }
332
+ }
333
+ return {
334
+ files: files.slice(0, SHARE_CARD_MAX_FILES),
335
+ moreFiles: Math.max(0, files.length - SHARE_CARD_MAX_FILES),
336
+ };
337
+ }
338
+
339
+ /**
340
+ * A context post's text as one run of lines, cut short. Paragraphs join
341
+ * with a space, except after CJK punctuation, which carries its own.
342
+ */
343
+ function clipContextText(text: string | undefined): string | undefined {
344
+ const normalized = text
345
+ ?.replace(/\s+/g, " ")
346
+ .replace(/([\u3000-\u303f\uff00-\uffef]) /g, "$1")
347
+ .trim();
348
+ if (!normalized) return undefined;
349
+ const characters = Array.from(normalized);
350
+ if (characters.length <= CONTEXT_TEXT_CHARS) return normalized;
351
+ return `${characters.slice(0, CONTEXT_TEXT_CHARS).join("").trimEnd()}…`;
352
+ }
353
+
354
+ /**
355
+ * Which posts of a Thread the card shows around the one at `index`.
356
+ *
357
+ * @param posts - The Thread's published posts, in Thread order
358
+ * @param index - Position of the shared post in `posts`
359
+ * @returns The Thread's first post, how many posts fold between it and the
360
+ * shared one, the post after, and the shared post's place; null when the
361
+ * post stands alone
362
+ *
363
+ * @example
364
+ * ```ts
365
+ * threadWindow([p1, p2, p3, p4, p5, p6, p7], 5);
366
+ * // { root: p1, hidden: 4, next: p7, position: 6, total: 7 }
367
+ * ```
368
+ */
369
+ export function threadWindow<T>(
370
+ posts: T[],
371
+ index: number,
372
+ ): {
373
+ root: T | null;
374
+ hidden: number;
375
+ next: T | null;
376
+ position: number;
377
+ total: number;
378
+ } | null {
379
+ if (posts.length < 2 || index < 0 || index >= posts.length) return null;
380
+ return {
381
+ root: index > 0 ? (posts[0] ?? null) : null,
382
+ hidden: Math.max(0, index - 1),
383
+ next: posts[index + 1] ?? null,
384
+ position: index + 1,
385
+ total: posts.length,
386
+ };
387
+ }
388
+
389
+ /**
390
+ * The Thread's first post or the post after the shared one as the card
391
+ * shows it: its title and words, a quote's words and source, or, for a post
392
+ * with no words, its images, or its first file by format and name.
393
+ *
394
+ * @param post - Post record; `previewImageKey` stands in for a link's image
395
+ * @param view - The same post as the timeline renders it
396
+ * @param media - The post's attachments, in order
397
+ * @param sitePathPrefix - Path prefix for same-origin URLs
398
+ * @returns The context post
399
+ */
400
+ export function buildShareCardThreadPost(
401
+ post: Pick<Post, "format" | "previewImageKey">,
402
+ view: PostView,
403
+ media: Media[],
404
+ sitePathPrefix: string,
405
+ ): ShareCardThreadPost {
406
+ let title: string | undefined;
407
+ let text: string | undefined;
408
+ const safeUrl = view.url ? sanitizeUrl(view.url) : "";
409
+ const domain = safeUrl
410
+ ? (extractDisplayDomain(safeUrl) ?? undefined)
411
+ : undefined;
412
+ if (post.format === "quote") {
413
+ text = clipContextText(view.quoteText);
414
+ // Who said it and where, as the shared post's own quote card shows it.
415
+ const source = [view.title, domain].filter(Boolean).join(" · ");
416
+ if (text) {
417
+ return { format: post.format, text, source: source || undefined };
418
+ }
419
+ } else if (post.format === "link") {
420
+ title = view.title || domain;
421
+ // A link with no words of its own summarizes as its address.
422
+ text =
423
+ view.summary && view.summary !== view.url?.trim()
424
+ ? clipContextText(view.summary)
425
+ : undefined;
426
+ } else {
427
+ title = view.title || undefined;
428
+ text = clipContextText(view.summary);
429
+ }
430
+ if (title || text) return { format: post.format, title, text };
431
+ const { images, moreImages } = cardImages(
432
+ media,
433
+ post.previewImageKey,
434
+ sitePathPrefix,
435
+ );
436
+ if (images.length === 0) {
437
+ const file = cardFiles(media).files[0];
438
+ return file
439
+ ? { format: post.format, text: `${file.format} · ${file.title}` }
440
+ : { format: post.format };
441
+ }
442
+ const shown = images.slice(0, SHARE_CARD_CONTEXT_IMAGES);
443
+ return {
444
+ format: post.format,
445
+ images: shown,
446
+ moreImages: moreImages + images.length - shown.length,
447
+ };
448
+ }
449
+
450
+ function quoteSize(text: string): "short" | "medium" | "long" {
451
+ const length = Array.from(text).length;
452
+ if (length <= SHORT_QUOTE_CHARS) return "short";
453
+ if (length > LONG_QUOTE_CHARS) return "long";
454
+ return "medium";
455
+ }
456
+
457
+ /**
458
+ * The site's address as a reader would type it: host and path prefix,
459
+ * percent-decoded, without a trailing slash. Null when the site's name
460
+ * already says it, such as a site named `example.com` at
461
+ * `www.example.com`.
462
+ */
463
+ function toSiteAddress(site: ShareCardSite): string | null {
464
+ const url = new URL(buildSiteUrl(site.siteOrigin, site.sitePathPrefix));
465
+ let path = url.pathname;
466
+ try {
467
+ path = decodeURI(path);
468
+ } catch {
469
+ // Keep the encoded path when it does not decode.
470
+ }
471
+ const address = `${url.host}${path}`.replace(/\/$/, "");
472
+ const bare = (text: string) =>
473
+ text
474
+ .trim()
475
+ .toLowerCase()
476
+ .replace(/^www\./, "");
477
+ return bare(site.siteName) === bare(address) ? null : address;
478
+ }
479
+
480
+ /**
481
+ * Builds the share card for a post: layout, text, images, and the QR code
482
+ * for its address.
483
+ *
484
+ * @param post - Post record; `body` is the TipTap JSON the summary is cut from
485
+ * @param view - The same post as the timeline renders it
486
+ * @param media - The post's attachments, in order
487
+ * @param site - Site name, avatar, and the origin the QR code points at
488
+ * @returns Render-ready share card view
489
+ *
490
+ * @example
491
+ * ```ts
492
+ * const card = buildShareCardView(post, postView, media, site);
493
+ * card.layout; // "article" for a titled note
494
+ * ```
495
+ */
496
+ export function buildShareCardView(
497
+ post: Pick<Post, "id" | "format" | "body" | "previewImageKey">,
498
+ view: PostView,
499
+ media: Media[],
500
+ site: ShareCardSite,
501
+ ): ShareCardView {
502
+ const layout: ShareCardLayout =
503
+ post.format === "note" ? (view.title ? "article" : "note") : post.format;
504
+
505
+ // The timeline's limits: an untitled note shows most of itself, anything
506
+ // else a short teaser. An author's read-more break wins over both.
507
+ const summary = post.body
508
+ ? layout === "note"
509
+ ? extractSummaryHtml(
510
+ post.body,
511
+ NOTE_SUMMARY_MAX_BLOCKS,
512
+ NOTE_SUMMARY_MAX_CHARS,
513
+ NOTE_SUMMARY_MIN_HIDDEN_CHARS,
514
+ { namespace: post.id },
515
+ )
516
+ : extractSummaryHtml(
517
+ post.body,
518
+ ARTICLE_SUMMARY_MAX_BLOCKS,
519
+ ARTICLE_SUMMARY_MAX_CHARS,
520
+ 0,
521
+ { namespace: post.id },
522
+ )
523
+ : null;
524
+
525
+ const permalink = new URL(view.permalink, site.siteOrigin).toString();
526
+ const safeUrl = view.url ? sanitizeUrl(view.url) : "";
527
+ const domain = safeUrl
528
+ ? (extractDisplayDomain(safeUrl) ?? undefined)
529
+ : undefined;
530
+
531
+ return {
532
+ layout,
533
+ siteName: site.siteName,
534
+ avatarUrl: site.siteAvatar
535
+ ? storagePath(site.siteAvatar, site.sitePathPrefix)
536
+ : null,
537
+ date: view.publishedAtFormatted,
538
+ title: layout === "article" ? view.title : undefined,
539
+ bodyHtml: summary?.html || undefined,
540
+ hasMore: summary?.hasMore ?? false,
541
+ quote:
542
+ layout === "quote" && view.quoteText
543
+ ? {
544
+ text: view.quoteText,
545
+ size: quoteSize(view.quoteText),
546
+ attribution: view.title || undefined,
547
+ source: domain,
548
+ }
549
+ : undefined,
550
+ link:
551
+ layout === "link"
552
+ ? { title: view.title || undefined, domain }
553
+ : undefined,
554
+ ...cardImages(media, post.previewImageKey, site.sitePathPrefix),
555
+ ...cardFiles(media),
556
+ permalink,
557
+ siteAddress: toSiteAddress(site),
558
+ qrSvg: renderSVG(permalink, { ecc: "M", border: 2 }),
559
+ fileName: view.slug,
560
+ language: view.language,
561
+ };
562
+ }
563
+
564
+ /**
565
+ * Loads a post, and the posts of its Thread the card shows around it, and
566
+ * builds its share card.
567
+ *
568
+ * @param c - Hono context (services + appConfig)
569
+ * @param postId - TypeID of the post
570
+ * @returns The card, or null when the post is missing or cannot be shared
571
+ */
572
+ export async function assembleShareCard(
573
+ c: Context<Env>,
574
+ postId: string,
575
+ ): Promise<ShareCardView | null> {
576
+ const post = await c.var.services.posts.getById(postId);
577
+ if (!post || !canShareAsImage(post)) return null;
578
+
579
+ // Published posts only: the card shows what a reader opening the QR code
580
+ // finds there, never an unpublished reply.
581
+ const threadPosts = (
582
+ await c.var.services.posts.getThread(post.threadId)
583
+ ).filter((threadPost) => threadPost.status === "published");
584
+ const window = threadWindow(
585
+ threadPosts,
586
+ threadPosts.findIndex((threadPost) => threadPost.id === post.id),
587
+ );
588
+ const contextPosts = window
589
+ ? [window.root, window.next].filter(
590
+ (contextPost): contextPost is Post => contextPost !== null,
591
+ )
592
+ : [];
593
+
594
+ const appConfig = c.var.appConfig;
595
+ const mediaCtx = createMediaContext(appConfig);
596
+ const [rawMediaMap, aliasesMap] = await Promise.all([
597
+ c.var.services.media.getByPostIds([
598
+ post.id,
599
+ ...contextPosts.map((contextPost) => contextPost.id),
600
+ ]),
601
+ c.var.services.paths.getPostAliases([post.id]),
602
+ ]);
603
+ const mediaMap = buildMediaMap(
604
+ rawMediaMap,
605
+ mediaCtx.r2PublicUrl,
606
+ mediaCtx.imageTransformUrl,
607
+ mediaCtx.s3PublicUrl,
608
+ mediaCtx.localPublicUrl,
609
+ mediaCtx.sitePathPrefix,
610
+ );
611
+ const view = toPostView(
612
+ { ...post, mediaAttachments: mediaMap.get(post.id) ?? [] },
613
+ mediaCtx,
614
+ undefined,
615
+ true,
616
+ aliasesMap.get(post.id)?.[0],
617
+ );
618
+
619
+ const card = buildShareCardView(post, view, rawMediaMap.get(post.id) ?? [], {
620
+ siteName: appConfig.siteName,
621
+ siteAvatar: appConfig.siteAvatar,
622
+ // A site without SITE_ORIGIN is reached at whatever host serves it.
623
+ siteOrigin: appConfig.siteOrigin || new URL(c.req.url).origin,
624
+ sitePathPrefix: appConfig.sitePathPrefix,
625
+ });
626
+ if (!window) return card;
627
+
628
+ const context = (contextPost: Post | null): ShareCardThreadPost | null =>
629
+ contextPost
630
+ ? buildShareCardThreadPost(
631
+ contextPost,
632
+ toPostView(
633
+ {
634
+ ...contextPost,
635
+ mediaAttachments: mediaMap.get(contextPost.id) ?? [],
636
+ },
637
+ mediaCtx,
638
+ ),
639
+ rawMediaMap.get(contextPost.id) ?? [],
640
+ appConfig.sitePathPrefix,
641
+ )
642
+ : null;
643
+ return {
644
+ ...card,
645
+ thread: {
646
+ position: window.position,
647
+ total: window.total,
648
+ root: context(window.root),
649
+ hidden: window.hidden,
650
+ next: context(window.next),
651
+ },
652
+ };
653
+ }