@jant/core 1.0.1 → 1.1.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 (58) hide show
  1. package/dist/{app-Gt7_skt6.js → app-CKQ9PqAr.js} +791 -89
  2. package/dist/client/.vite/manifest.json +115 -75
  3. package/dist/client/_assets/chunks/{confirm-D7GrwsCN.js → confirm-CMe01lne.js} +1 -1
  4. package/dist/client/_assets/chunks/{create-editor-5Y49x7h5.js → create-editor-BQkrw8Ax.js} +4 -4
  5. package/dist/client/_assets/chunks/footnote-rail-B08scyhW.js +2 -0
  6. package/dist/client/_assets/chunks/{jant-locale-picker-DL6mIOT5.js → jant-locale-picker-2L4rkDaz.js} +1 -1
  7. package/dist/client/_assets/chunks/lit-Bw_voPoW.js +2 -0
  8. package/dist/client/_assets/chunks/preload-helper-Czpn1I53.js +1 -0
  9. package/dist/client/_assets/chunks/runtime-paths-y0_gHowM.js +1 -0
  10. package/dist/client/_assets/chunks/{settings-paths-h6RjIe3C.js → settings-paths-B0bNUaih.js} +1 -1
  11. package/dist/client/_assets/chunks/slug-format-CYmQE5ln.js +1 -0
  12. package/dist/client/_assets/chunks/{sortable-list-DWNKv782.js → sortable-list-t11Ma1Ek.js} +1 -1
  13. package/dist/client/_assets/chunks/{unsafe-html-B5ZEXaxg.js → unsafe-html-CWos3v6N.js} +1 -1
  14. package/dist/client/_assets/chunks/unsafe-svg-DZl-yjas.js +1 -0
  15. package/dist/client/_assets/client-B0-s9sqx.css +2 -0
  16. package/dist/client/_assets/client-Dp46QSht.js +354 -0
  17. package/dist/client/_assets/client-auth-CG55rWb5.js +859 -0
  18. package/dist/client/_assets/{client-compose-oxzPb3SS.js → client-compose-DkUTuavR.js} +261 -261
  19. package/dist/client/_assets/{client-manage-C1eDB1Rc.js → client-manage-DnYdQAhf.js} +176 -176
  20. package/dist/client/_assets/{client-settings-DIM44Zqh.js → client-settings-CHgsIqXJ.js} +166 -166
  21. package/dist/client/_assets/client-share-0DICJjAc.css +1 -0
  22. package/dist/client/_assets/client-share-C59mOLJ1.js +149 -0
  23. package/dist/index.js +1 -1
  24. package/dist/node.js +2 -2
  25. package/package.json +2 -1
  26. package/src/client/components/jant-post-menu.ts +80 -13
  27. package/src/client/components/jant-share-dialog.ts +422 -0
  28. package/src/client/components/jant-share-menu.ts +188 -0
  29. package/src/client/lazy-entries.ts +21 -1
  30. package/src/client/post-menu-shared.ts +100 -0
  31. package/src/client/share-capture.ts +443 -0
  32. package/src/client/share-launch.ts +133 -0
  33. package/src/client-share.ts +8 -0
  34. package/src/client.ts +1 -0
  35. package/src/lib/discover.ts +31 -0
  36. package/src/lib/share-card.ts +653 -0
  37. package/src/lib/version.ts +2 -0
  38. package/src/routes/auth/setup.tsx +37 -1
  39. package/src/routes/pages/partials.tsx +23 -0
  40. package/src/style-share.css +16 -0
  41. package/src/styles/components.css +14 -0
  42. package/src/styles/share.css +1103 -0
  43. package/src/styles/ui.css +6 -0
  44. package/src/ui/layouts/BaseLayout.tsx +7 -0
  45. package/src/ui/layouts/SiteLayout.tsx +1 -0
  46. package/src/ui/share/ShareCard.tsx +298 -0
  47. package/src/ui/shared/Icon.tsx +23 -3
  48. package/src/ui/shared/MediaGallery.tsx +12 -1
  49. package/src/ui/shared/PostFooter.tsx +20 -4
  50. package/src/ui/shared/icon-collector.ts +28 -0
  51. package/src/ui/shared/post-article-attributes.ts +3 -0
  52. package/dist/client/_assets/chunks/footnote-rail-BJwswtVQ.js +0 -1
  53. package/dist/client/_assets/chunks/lit-DW8VmJAT.js +0 -2
  54. package/dist/client/_assets/chunks/slug-format-Dsi0e9Xn.js +0 -1
  55. package/dist/client/_assets/chunks/unsafe-svg-DTZZEvLU.js +0 -2
  56. package/dist/client/_assets/client-BaqmpPQ-.css +0 -2
  57. package/dist/client/_assets/client-C6melOtG.js +0 -296
  58. package/dist/client/_assets/client-auth-Ccq8kSqq.js +0 -828
@@ -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
+ };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Opens the "Share as image" dialog from a post menu, the author's or a
3
+ * reader's.
4
+ *
5
+ * The dialog and snapdom ship in their own bundle, and their styles in their
6
+ * own stylesheet. The menu starts loading both when it opens; picking the
7
+ * item asks the server for the card at the same time as it waits for them,
8
+ * and only then talks to the element.
9
+ */
10
+
11
+ import type { JantShareDialog } from "./components/jant-share-dialog.js";
12
+ import { ensureShare } from "./lazy-entries.js";
13
+ import { publicPath } from "./runtime-paths.js";
14
+ import { showToast } from "./toast.js";
15
+
16
+ async function fetchShareCard(postId: string): Promise<string> {
17
+ const response = await fetch(
18
+ publicPath(`/_/share-card/${encodeURIComponent(postId)}`),
19
+ );
20
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
21
+ return response.text();
22
+ }
23
+
24
+ let styles: Promise<void> | undefined;
25
+
26
+ /**
27
+ * Link the share stylesheet, which `<html data-share-stylesheet>` names, and
28
+ * resolve once it has loaded. A load that fails is forgotten, so the next
29
+ * call links it again.
30
+ */
31
+ function ensureShareStyles(): Promise<void> {
32
+ return (styles ??= new Promise<void>((resolve, reject) => {
33
+ const href = document.documentElement.dataset.shareStylesheet;
34
+ if (!href) {
35
+ resolve();
36
+ return;
37
+ }
38
+ const link = document.createElement("link");
39
+ link.rel = "stylesheet";
40
+ link.href = href;
41
+ link.addEventListener("load", () => resolve(), { once: true });
42
+ link.addEventListener(
43
+ "error",
44
+ () => {
45
+ link.remove();
46
+ styles = undefined;
47
+ reject(new Error(`Could not load ${href}`));
48
+ },
49
+ { once: true },
50
+ );
51
+ document.head.appendChild(link);
52
+ }));
53
+ }
54
+
55
+ /** Wait for the bundle and the stylesheet, and return what failed. */
56
+ async function settleShareLoads(): Promise<unknown[]> {
57
+ const results = await Promise.allSettled([
58
+ ensureShare(),
59
+ ensureShareStyles(),
60
+ ]);
61
+ return results.flatMap((result) =>
62
+ result.status === "rejected" ? [result.reason] : [],
63
+ );
64
+ }
65
+
66
+ /**
67
+ * Load the share bundle and its styles, trying once more what fails: a
68
+ * dropped request is the usual cause, and both loads forget a failure. Both
69
+ * settle before the retry, so neither is still on its first try.
70
+ *
71
+ * @returns Whether both loaded
72
+ */
73
+ async function loadShare(): Promise<boolean> {
74
+ let failures = await settleShareLoads();
75
+ if (failures.length > 0) {
76
+ // eslint-disable-next-line no-console -- the toast names no cause; the console keeps it
77
+ console.warn("[jant] share: loading failed, trying again", ...failures);
78
+ failures = await settleShareLoads();
79
+ }
80
+ if (failures.length > 0) {
81
+ // eslint-disable-next-line no-console -- the toast names no cause; the console keeps it
82
+ console.error("[jant] share: could not load", ...failures);
83
+ return false;
84
+ }
85
+ return true;
86
+ }
87
+
88
+ /**
89
+ * Start loading the share bundle and its styles, so the dialog opens without
90
+ * waiting for them. Out of the way of the menu's first frame; a failure is
91
+ * left for {@link openShareImage} to retry and report.
92
+ */
93
+ export function warmShareImage(): void {
94
+ setTimeout(() => {
95
+ ensureShare().catch(() => {});
96
+ ensureShareStyles().catch(() => {});
97
+ }, 0);
98
+ }
99
+
100
+ /**
101
+ * Show the share dialog for a post.
102
+ *
103
+ * @param postId - TypeID of the post to share
104
+ * @param returnFocus - Element to focus again when the dialog closes
105
+ */
106
+ export async function openShareImage(
107
+ postId: string,
108
+ returnFocus?: HTMLElement | null,
109
+ ): Promise<void> {
110
+ // The first card is asked for now, alongside the bundle; "Try again" in
111
+ // the dialog asks again.
112
+ let first: Promise<string> | null = fetchShareCard(postId);
113
+ first.catch(() => {});
114
+ const loadCard = () => {
115
+ const card = first ?? fetchShareCard(postId);
116
+ first = null;
117
+ return card;
118
+ };
119
+
120
+ if (!(await loadShare())) {
121
+ showToast(
122
+ "Could not open sharing. Check your connection and try again.",
123
+ "error",
124
+ );
125
+ return;
126
+ }
127
+ let dialog = document.querySelector<JantShareDialog>("jant-share-dialog");
128
+ if (!dialog) {
129
+ dialog = document.createElement("jant-share-dialog") as JantShareDialog;
130
+ document.body.appendChild(dialog);
131
+ }
132
+ await dialog.open(loadCard, returnFocus ?? null);
133
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Share entry: the "Share as image" dialog, and snapdom with it.
3
+ *
4
+ * Loaded by `client/share-launch.ts` the first time an author picks "Share as
5
+ * image" from a post menu. Never referenced from a script tag.
6
+ */
7
+
8
+ import "./client/components/jant-share-dialog.js";
package/src/client.ts CHANGED
@@ -14,6 +14,7 @@ import "./client/form-enter-submit.js";
14
14
  import "./client/copy-field.js";
15
15
  import "./client/components/jant-media-lightbox.js";
16
16
  import "./client/components/jant-text-preview.js";
17
+ import "./client/components/jant-share-menu.js";
17
18
  // First-run setup is a signed-out page, so the language picker it shares with
18
19
  // the settings page has to ship in the public bundle.
19
20
  import "./client/components/jant-locale-picker.js";
@@ -340,6 +340,37 @@ export function getDiscoverSubmitUrl(
340
340
  }
341
341
  }
342
342
 
343
+ /**
344
+ * Where the Jant author group's WeChat QR code is, derived from the
345
+ * directory's base address.
346
+ *
347
+ * The group is a Chinese-language WeChat group for people who write on Jant,
348
+ * and its QR code lives on the contact page of the same control plane that
349
+ * runs the directory — so, like the submission form, it is found from the one
350
+ * address this deployment already has. The path is the Chinese page at its
351
+ * WeChat section, because only Chinese screens link to it.
352
+ *
353
+ * @param directoryBaseUrl - The directory this deployment belongs to, from
354
+ * `getDiscoverDirectoryBaseUrl`
355
+ * @returns Absolute URL of the group's section, or `null` when there is no
356
+ * directory
357
+ * @example
358
+ * ```ts
359
+ * getAuthorGroupUrl("https://jant.me/");
360
+ * // "https://jant.me/zh-hans/contact#wechat"
361
+ * ```
362
+ */
363
+ export function getAuthorGroupUrl(
364
+ directoryBaseUrl: string | undefined | null,
365
+ ): string | null {
366
+ if (!directoryBaseUrl) return null;
367
+ try {
368
+ return new URL("/zh-hans/contact#wechat", directoryBaseUrl).toString();
369
+ } catch {
370
+ return null;
371
+ }
372
+ }
373
+
343
374
  /** One run of a sentence, and where it links when it is a link. */
344
375
  export interface TextRun {
345
376
  text: string;