@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
@@ -12,6 +12,9 @@
12
12
  * - `client-settings.ts` — the settings pages' components.
13
13
  * - `client-manage.ts` — navigation manager, collection directory, and the
14
14
  * collection page menus.
15
+ * - `client-share.ts` — the "Share as image" dialog and snapdom. Loaded
16
+ * when a post menu that offers it opens (`share-launch.ts`), so picking
17
+ * the item has nothing left to wait for; no page needs it up front.
15
18
  *
16
19
  * The page decides: {@link loadEntriesForPage} looks for the elements and
17
20
  * hooks the server renders only where an entry is needed, and keeps looking
@@ -19,9 +22,20 @@
19
22
  * `docs/internal/lit-guide.md` says which entry a new component belongs in.
20
23
  */
21
24
 
25
+ /**
26
+ * Share one load between callers. A load that fails is forgotten, so the
27
+ * next call tries again instead of repeating the failure until a reload.
28
+ */
22
29
  function once(load: () => Promise<unknown>): () => Promise<void> {
23
30
  let loading: Promise<void> | undefined;
24
- return () => (loading ??= load().then(() => undefined));
31
+ return () =>
32
+ (loading ??= load().then(
33
+ () => undefined,
34
+ (error: unknown) => {
35
+ loading = undefined;
36
+ throw error;
37
+ },
38
+ ));
25
39
  }
26
40
 
27
41
  /** Load the composer entry; resolves once its elements are defined. */
@@ -33,6 +47,12 @@ export const ensureSettings = once(() => import("../client-settings.js"));
33
47
  /** Load the management entry; resolves once its elements are defined. */
34
48
  export const ensureManage = once(() => import("../client-manage.js"));
35
49
 
50
+ /**
51
+ * Load the share entry — the "Share as image" dialog and snapdom — the first
52
+ * time a post menu offers it.
53
+ */
54
+ export const ensureShare = once(() => import("../client-share.js"));
55
+
36
56
  /**
37
57
  * Markup the server renders only on pages that need an entry. A selector
38
58
  * matching means the page cannot work without that entry, so it loads at
@@ -0,0 +1,100 @@
1
+ /**
2
+ * What the author's post menu (`jant-post-menu`) and a reader's
3
+ * (`jant-share-menu`) share: where the menu opens, the icons of the two items
4
+ * both offer, and copying a post's link.
5
+ */
6
+
7
+ import { html } from "lit";
8
+ import { showToast } from "./toast.js";
9
+
10
+ /** The trigger's box, as `getBoundingClientRect()` gives it. */
11
+ export interface MenuTriggerRect {
12
+ top: number;
13
+ bottom: number;
14
+ }
15
+
16
+ const MENU_VIEWPORT_MARGIN = 12;
17
+
18
+ /**
19
+ * Whether a menu should open above its trigger: when it would not fit below
20
+ * and there is more room above.
21
+ *
22
+ * @param rect - The trigger's box
23
+ * @param menuHeight - The menu's height, estimated before it renders
24
+ * @returns True to open above the trigger
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * menuOpensAbove(trigger.getBoundingClientRect(), 360);
29
+ * ```
30
+ */
31
+ export function menuOpensAbove(
32
+ rect: MenuTriggerRect,
33
+ menuHeight: number,
34
+ ): boolean {
35
+ const spaceBelow = window.innerHeight - rect.bottom - MENU_VIEWPORT_MARGIN;
36
+ const spaceAbove = rect.top - MENU_VIEWPORT_MARGIN;
37
+ return spaceBelow < menuHeight && spaceAbove > spaceBelow;
38
+ }
39
+
40
+ /**
41
+ * Copy a post's own address and say whether it worked. The address is the
42
+ * article's `data-post-permalink`, where the post's date links to, made
43
+ * absolute: the post's own wherever it is listed, never the page's.
44
+ *
45
+ * @param permalink - The post's permalink, as the article carries it
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * await copyPostLink(article.dataset.postPermalink);
50
+ * ```
51
+ */
52
+ export async function copyPostLink(permalink: string): Promise<void> {
53
+ const url = new URL(permalink, globalThis.location.href).href;
54
+ try {
55
+ // Absent on an insecure origin, and the browser may refuse it.
56
+ if (!globalThis.navigator.clipboard?.writeText) {
57
+ throw new Error("Clipboard unavailable");
58
+ }
59
+ await globalThis.navigator.clipboard.writeText(url);
60
+ showToast("Link copied.");
61
+ } catch {
62
+ showToast(
63
+ "Could not copy the link. Open the post and copy it from the address bar.",
64
+ "error",
65
+ );
66
+ }
67
+ }
68
+
69
+ /** Lucide "link", for Copy link. */
70
+ export function iconLink() {
71
+ return html`<svg
72
+ xmlns="http://www.w3.org/2000/svg"
73
+ viewBox="0 0 24 24"
74
+ fill="none"
75
+ stroke="currentColor"
76
+ stroke-width="1.75"
77
+ stroke-linecap="round"
78
+ stroke-linejoin="round"
79
+ >
80
+ <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
81
+ <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
82
+ </svg>`;
83
+ }
84
+
85
+ /** Lucide "image", for Share as image. */
86
+ export function iconImage() {
87
+ return html`<svg
88
+ xmlns="http://www.w3.org/2000/svg"
89
+ viewBox="0 0 24 24"
90
+ fill="none"
91
+ stroke="currentColor"
92
+ stroke-width="1.75"
93
+ stroke-linecap="round"
94
+ stroke-linejoin="round"
95
+ >
96
+ <rect width="18" height="18" x="3" y="3" rx="2" />
97
+ <circle cx="9" cy="9" r="2" />
98
+ <path d="m21 15-3.09-3.09a2 2 0 0 0-2.82 0L6 21" />
99
+ </svg>`;
100
+ }
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Turns a share card into a PNG in the browser of whoever shares it.
3
+ *
4
+ * The server renders the card (`/_/share-card/{id}`); this lays it out off
5
+ * screen with the page's own theme and fonts, waits for them, cuts the body
6
+ * if the card is taller than one phone screen, and has snapdom paint it at
7
+ * 3x, with the paper's shadow painted on the canvas afterwards. Two steps,
8
+ * so the dialog can show the laid-out card while the picture is painted.
9
+ */
10
+
11
+ import { snapdom } from "@zumer/snapdom";
12
+
13
+ /**
14
+ * Tallest card, in CSS px: one 9:19.5 phone screen viewed at full width
15
+ * (1620×3510 in the image).
16
+ */
17
+ const MAX_CARD_HEIGHT = 1170;
18
+ /**
19
+ * 540 CSS px at 3x is 1620 px: pixel for pixel on a 3x phone held upright,
20
+ * where 2x (1080 px) was enlarged by a fifth and read soft. A chat that
21
+ * shrinks the picture starts from a sharper one.
22
+ */
23
+ const SCALE = 3;
24
+ /** Lines of a paragraph that may run under the fade at the cut. */
25
+ const FADE_MIN_LINES = 3;
26
+ /**
27
+ * Blocks a cut may end between, wherever they sit: a list or a quotation is
28
+ * cut between the paragraphs inside it, so a body that is one long list
29
+ * still shows how it starts.
30
+ */
31
+ const CUT_BLOCKS = "p, h1, h2, h3, h4, h5, h6, pre, table";
32
+ /** Blocks whose lines may run on under the fade. */
33
+ const RUN_ON_BLOCKS = new Set(["P", "PRE"]);
34
+ const FONTS_SETTLE_CAP_MS = 2_000;
35
+ /** How long one of snapdom's reads of `fonts.ready` may wait. */
36
+ const SNAPDOM_FONTS_CAP_MS = 1_000;
37
+ const CAPTURE_TIMEOUT_MS = 30_000;
38
+
39
+ export interface ShareImage {
40
+ blob: Blob;
41
+ width: number;
42
+ height: number;
43
+ fileName: string;
44
+ }
45
+
46
+ /** `promise`, or a rejection once `ms` have passed. */
47
+ function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
48
+ let timer: ReturnType<typeof setTimeout> | undefined;
49
+ const timeout = new Promise<never>((_, reject) => {
50
+ timer = setTimeout(
51
+ () => reject(new Error("Creating the image took too long.")),
52
+ ms,
53
+ );
54
+ });
55
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
56
+ }
57
+
58
+ /**
59
+ * Resolves once no font face is loading, or after `ms`.
60
+ *
61
+ * Not `document.fonts.ready`: WebKit can leave the font set "loading" for
62
+ * good while no face is loading at all, and `ready` then never settles. On a
63
+ * Mac the trigger is text in a CJK serif stack with a character no local
64
+ * font covers (an emoji): WebKit tries the Noto Serif SC face for U+20-5D
65
+ * through its `local()` source, which fails without a request. On an iPhone
66
+ * the set stuck with `local()` removed too, during snapdom's own font
67
+ * warm-up. Faces that really are downloading are still waited for.
68
+ */
69
+ function fontsSettled(ms: number): Promise<void> {
70
+ const deadline = Date.now() + ms;
71
+ return new Promise((resolve) => {
72
+ const check = () => {
73
+ const loading = Array.from(document.fonts).some(
74
+ (face) => face.status === "loading",
75
+ );
76
+ if (!loading || Date.now() >= deadline) resolve();
77
+ else setTimeout(check, 30);
78
+ };
79
+ // A frame for layout to start the loads the card needs.
80
+ setTimeout(check, 16);
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Run `fn` with every read of `document.fonts.ready` settling as soon as no
86
+ * face is loading (see {@link fontsSettled}). On Safari snapdom awaits
87
+ * `fonts.ready` before it captures, with no timeout; a stuck set would stop
88
+ * the capture forever, and capping each read at a second cost an iPhone
89
+ * about two seconds a picture. The patch lives only as long as `fn`.
90
+ */
91
+ async function withSettledFontsReady<T>(fn: () => Promise<T>): Promise<T> {
92
+ const prototype = globalThis.FontFaceSet.prototype;
93
+ const real = Object.getOwnPropertyDescriptor(prototype, "ready");
94
+ if (!real?.get) return fn();
95
+ const read = real.get;
96
+ Object.defineProperty(prototype, "ready", {
97
+ configurable: true,
98
+ get(this: globalThis.FontFaceSet) {
99
+ const ready = read.call(this) as Promise<globalThis.FontFaceSet>;
100
+ return Promise.race([
101
+ ready.catch(() => this),
102
+ fontsSettled(SNAPDOM_FONTS_CAP_MS),
103
+ ]).then(() => this);
104
+ },
105
+ });
106
+ try {
107
+ return await fn();
108
+ } finally {
109
+ Object.defineProperty(prototype, "ready", real);
110
+ }
111
+ }
112
+
113
+ function familyOf(face: globalThis.FontFace): string {
114
+ return face.family.replace(/^["']|["']$/g, "");
115
+ }
116
+
117
+ /**
118
+ * Web font families none of whose faces the page has loaded or is loading.
119
+ *
120
+ * A browser downloads a face only when no earlier font in the stack covers
121
+ * the text, so these are declared but unused — on a Mac, Songti SC renders
122
+ * what Noto Serif SC would. snapdom would embed them anyway, which took a
123
+ * card from 180 KB to 2 MB and its capture from 80 to 350 ms.
124
+ */
125
+ function unusedFontFamilies(): string[] {
126
+ const used = new Set<string>();
127
+ const declared = new Set<string>();
128
+ for (const face of document.fonts) {
129
+ const family = familyOf(face);
130
+ declared.add(family);
131
+ if (face.status === "loaded" || face.status === "loading") used.add(family);
132
+ }
133
+ return [...declared].filter((family) => !used.has(family));
134
+ }
135
+
136
+ /** Fonts the card uses, then every image in it, decoded. */
137
+ async function settle(card: HTMLElement): Promise<void> {
138
+ void card.offsetHeight;
139
+ await fontsSettled(FONTS_SETTLE_CAP_MS);
140
+ await Promise.all(
141
+ Array.from(card.querySelectorAll("img"), (image) =>
142
+ image.decode().catch(() => {}),
143
+ ),
144
+ );
145
+ }
146
+
147
+ /**
148
+ * Cut the body so the card fits one screen. The summary already decided the
149
+ * text; this only steps in when the summary is still too tall, as a long
150
+ * untitled note can be, or a titled one whose first block is a long list.
151
+ * The cut lands between blocks ({@link CUT_BLOCKS}): a paragraph or code may
152
+ * run on under a fade, but the card never ends on a heading.
153
+ */
154
+ function cutToScreen(card: HTMLElement): void {
155
+ const body = card.querySelector<HTMLElement>("[data-share-card-body]");
156
+ if (!body) return;
157
+ const overflow = card.offsetHeight - MAX_CARD_HEIGHT;
158
+ if (overflow <= 0) return;
159
+
160
+ const lineHeight = Number.parseFloat(getComputedStyle(body).lineHeight) || 30;
161
+ const budget = body.offsetHeight - overflow;
162
+ // When images or a long title take the screen, cutting the text away would
163
+ // leave a card with nothing to read; let it run taller instead.
164
+ if (budget < FADE_MIN_LINES * lineHeight) return;
165
+
166
+ const bodyTop = body.getBoundingClientRect().top;
167
+ const blocks = Array.from(body.querySelectorAll<HTMLElement>(CUT_BLOCKS))
168
+ .filter((block) => !block.parentElement?.closest("pre, table"))
169
+ .map((block) => {
170
+ const rect = block.getBoundingClientRect();
171
+ return {
172
+ tagName: block.tagName,
173
+ top: rect.top - bodyTop,
174
+ bottom: rect.bottom - bodyTop,
175
+ };
176
+ })
177
+ // Hidden ones, such as the footnotes, take no room.
178
+ .filter((block) => block.bottom > block.top);
179
+ const overflowing = blocks.findIndex((block) => block.bottom > budget);
180
+ const visible = overflowing === -1 ? blocks : blocks.slice(0, overflowing);
181
+ const next = overflowing === -1 ? undefined : blocks[overflowing];
182
+
183
+ let cut: number;
184
+ if (
185
+ next &&
186
+ RUN_ON_BLOCKS.has(next.tagName) &&
187
+ budget - next.top >= FADE_MIN_LINES * lineHeight
188
+ ) {
189
+ cut = budget;
190
+ } else {
191
+ while (/^H[1-6]$/.test(visible.at(-1)?.tagName ?? "")) visible.pop();
192
+ // A body that opens with a block taller than the screen shows its start.
193
+ cut = visible.at(-1)?.bottom ?? budget;
194
+ }
195
+
196
+ body.classList.add("is-cut");
197
+ body.style.maxHeight = `${Math.max(0, Math.floor(cut))}px`;
198
+ const fade = document.createElement("div");
199
+ fade.className = "share-card-fade";
200
+ body.appendChild(fade);
201
+ }
202
+
203
+ /** One layer of a CSS `box-shadow`, lengths in CSS px. */
204
+ interface ShadowLayer {
205
+ x: number;
206
+ y: number;
207
+ blur: number;
208
+ spread: number;
209
+ color: string;
210
+ }
211
+
212
+ /** `text` split on `separator` where it is not inside parentheses. */
213
+ function splitOutsideParens(text: string, separator: RegExp): string[] {
214
+ const parts: string[] = [];
215
+ let depth = 0;
216
+ let start = 0;
217
+ for (let index = 0; index < text.length; index++) {
218
+ const char = text.charAt(index);
219
+ if (char === "(") depth++;
220
+ else if (char === ")") depth--;
221
+ else if (depth === 0 && separator.test(char)) {
222
+ parts.push(text.slice(start, index));
223
+ start = index + 1;
224
+ }
225
+ }
226
+ parts.push(text.slice(start));
227
+ return parts.map((part) => part.trim()).filter(Boolean);
228
+ }
229
+
230
+ /**
231
+ * The outer layers of a `box-shadow` value, as `getComputedStyle` writes it
232
+ * (color first, lengths in px) or as it is written in CSS (color anywhere).
233
+ * Inset layers are dropped: they paint inside the box, which the capture
234
+ * already holds.
235
+ */
236
+ function parseBoxShadow(value: string): ShadowLayer[] {
237
+ if (!value || value === "none") return [];
238
+ return splitOutsideParens(value, /,/).flatMap((layer) => {
239
+ const tokens = splitOutsideParens(layer, /\s/);
240
+ if (tokens.includes("inset")) return [];
241
+ const isLength = (token: string) => /^-?[\d.]+(px)?$/.test(token);
242
+ const [x = 0, y = 0, blur = 0, spread = 0] = tokens
243
+ .filter(isLength)
244
+ .map((token) => Number.parseFloat(token));
245
+ const color = tokens.find((token) => !isLength(token));
246
+ return color ? [{ x, y, blur, spread, color }] : [];
247
+ });
248
+ }
249
+
250
+ /** The paper's box on the card, in CSS px, and the shadow it casts. */
251
+ interface PaperShadow {
252
+ x: number;
253
+ y: number;
254
+ width: number;
255
+ height: number;
256
+ radius: number;
257
+ layers: ShadowLayer[];
258
+ }
259
+
260
+ /** Read the paper's shadow while the page still draws it. */
261
+ function readPaperShadow(card: HTMLElement): PaperShadow | null {
262
+ const paper = card.querySelector<HTMLElement>(".share-card-paper");
263
+ if (!paper) return null;
264
+ const style = getComputedStyle(paper);
265
+ const layers = parseBoxShadow(style.boxShadow);
266
+ if (layers.length === 0) return null;
267
+ const cardBox = card.getBoundingClientRect();
268
+ const box = paper.getBoundingClientRect();
269
+ return {
270
+ x: box.left - cardBox.left,
271
+ y: box.top - cardBox.top,
272
+ width: box.width,
273
+ height: box.height,
274
+ radius: Number.parseFloat(style.borderTopLeftRadius) || 0,
275
+ layers,
276
+ };
277
+ }
278
+
279
+ /** A rounded rectangle's path; `roundRect` is newer than this needs. */
280
+ function roundedRectPath(
281
+ context: CanvasRenderingContext2D,
282
+ x: number,
283
+ y: number,
284
+ width: number,
285
+ height: number,
286
+ radius: number,
287
+ ): void {
288
+ const r = Math.max(0, Math.min(radius, width / 2, height / 2));
289
+ context.moveTo(x + r, y);
290
+ context.arcTo(x + width, y, x + width, y + height, r);
291
+ context.arcTo(x + width, y + height, x, y + height, r);
292
+ context.arcTo(x, y + height, x, y, r);
293
+ context.arcTo(x, y, x + width, y, r);
294
+ context.closePath();
295
+ }
296
+
297
+ /**
298
+ * Paint the paper's shadow onto the mat, outside the paper, as CSS paints an
299
+ * outer box-shadow. The capture leaves shadows out (see the
300
+ * `.share-card-host[data-capturing]` rule): in Safari snapdom draws any card
301
+ * holding one at 1x and stretches it to the scale asked for. A canvas
302
+ * shadow is sharp at any scale.
303
+ *
304
+ * Each layer is cast by a shape drawn off the canvas, its shadow offset back
305
+ * into place, so only the shadow lands; the clip keeps it off the paper.
306
+ */
307
+ function paintPaperShadow(
308
+ context: CanvasRenderingContext2D,
309
+ shadow: PaperShadow,
310
+ scale: number,
311
+ ): void {
312
+ const { canvas } = context;
313
+ const away = canvas.width + (shadow.width + 200) * scale;
314
+ context.save();
315
+ context.beginPath();
316
+ context.rect(0, 0, canvas.width, canvas.height);
317
+ roundedRectPath(
318
+ context,
319
+ shadow.x * scale,
320
+ shadow.y * scale,
321
+ shadow.width * scale,
322
+ shadow.height * scale,
323
+ shadow.radius * scale,
324
+ );
325
+ context.clip("evenodd");
326
+ // CSS paints the first layer on top.
327
+ for (const layer of [...shadow.layers].reverse()) {
328
+ context.shadowColor = layer.color;
329
+ // Both are twice the Gaussian's standard deviation.
330
+ context.shadowBlur = layer.blur * scale;
331
+ context.shadowOffsetX = layer.x * scale + away;
332
+ context.shadowOffsetY = layer.y * scale;
333
+ context.fillStyle = "#000";
334
+ context.beginPath();
335
+ roundedRectPath(
336
+ context,
337
+ (shadow.x - layer.spread) * scale - away,
338
+ (shadow.y - layer.spread) * scale,
339
+ (shadow.width + layer.spread * 2) * scale,
340
+ (shadow.height + layer.spread * 2) * scale,
341
+ Math.max(0, shadow.radius + layer.spread) * scale,
342
+ );
343
+ context.fill();
344
+ }
345
+ context.restore();
346
+ }
347
+
348
+ function canvasToBlob(canvas: HTMLCanvasElement): Promise<Blob> {
349
+ return new Promise((resolve, reject) => {
350
+ canvas.toBlob(
351
+ (blob) =>
352
+ blob ? resolve(blob) : reject(new Error("The image came out empty.")),
353
+ "image/png",
354
+ );
355
+ });
356
+ }
357
+
358
+ export interface PreparedShareCard {
359
+ /** The card as it will be painted — fonts in, cut to one screen. */
360
+ html: string;
361
+ /** Its size in CSS px; the image is {@link SCALE} times this. */
362
+ width: number;
363
+ height: number;
364
+ /** Paint it. Removes the off-screen card whether or not it succeeds. */
365
+ capture(): Promise<ShareImage>;
366
+ /** Remove the off-screen card without painting it. */
367
+ dispose(): void;
368
+ }
369
+
370
+ /**
371
+ * Lay out a server-rendered share card off screen, ready to paint: fonts
372
+ * and images loaded, the body cut to one screen.
373
+ *
374
+ * @param cardHtml - Markup from `/_/share-card/{id}`
375
+ * @returns The laid-out card's markup and the step that paints it
376
+ */
377
+ export async function prepareShareCard(
378
+ cardHtml: string,
379
+ ): Promise<PreparedShareCard> {
380
+ const host = document.createElement("div");
381
+ host.className = "share-card-host";
382
+ host.setAttribute("aria-hidden", "true");
383
+ host.innerHTML = cardHtml;
384
+ document.body.appendChild(host);
385
+ const dispose = () => host.remove();
386
+ try {
387
+ const card = host.querySelector<HTMLElement>("[data-share-card]");
388
+ if (!card) throw new Error("The share card is missing.");
389
+ await settle(card);
390
+ const excludedFamilies = unusedFontFamilies();
391
+ cutToScreen(card);
392
+ return {
393
+ html: card.outerHTML,
394
+ width: card.offsetWidth,
395
+ height: card.offsetHeight,
396
+ dispose,
397
+ async capture() {
398
+ try {
399
+ const paperShadow = readPaperShadow(card);
400
+ host.dataset.capturing = "";
401
+ const canvas = await withTimeout(
402
+ withSettledFontsReady(async () => {
403
+ const capture = await snapdom(card, {
404
+ scale: SCALE,
405
+ dpr: 1,
406
+ reconcile: true,
407
+ excludeFonts: { families: excludedFamilies },
408
+ });
409
+ return capture.toCanvas();
410
+ }),
411
+ CAPTURE_TIMEOUT_MS,
412
+ );
413
+ const context = canvas.getContext("2d");
414
+ if (paperShadow && context) {
415
+ paintPaperShadow(context, paperShadow, SCALE);
416
+ }
417
+ const blob = await canvasToBlob(canvas);
418
+ const { width, height } = canvas;
419
+ canvas.width = 0;
420
+ canvas.height = 0;
421
+ return {
422
+ blob,
423
+ width,
424
+ height,
425
+ fileName: `${card.dataset.fileName || "post"}.png`,
426
+ };
427
+ } finally {
428
+ dispose();
429
+ }
430
+ },
431
+ };
432
+ } catch (error) {
433
+ dispose();
434
+ throw error;
435
+ }
436
+ }
437
+
438
+ export const __testOnly = {
439
+ cutToScreen,
440
+ paintPaperShadow,
441
+ parseBoxShadow,
442
+ MAX_CARD_HEIGHT,
443
+ };