@xsynaptic/share-kit 0.0.0-stage → 0.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1392 @@
1
+ // src/actions.ts
2
+ const shareCapabilities = [
3
+ "files",
4
+ "link",
5
+ "copy-image",
6
+ "handheld"
7
+ ];
8
+ const pngType = "image/png";
9
+ function canShareFiles() {
10
+ if (!("canShare" in navigator)) return false;
11
+ return navigator.canShare({ files: [new File([], "probe.jpg", { type: "image/jpeg" })] });
12
+ }
13
+ function canCopyImage() {
14
+ if (!("clipboard" in navigator) || !("ClipboardItem" in globalThis)) return false;
15
+ return "supports" in ClipboardItem && ClipboardItem.supports(pngType);
16
+ }
17
+ const capabilityTests = {
18
+ "copy-image": canCopyImage,
19
+ files: canShareFiles,
20
+ handheld: () => matchMedia("(pointer: coarse)").matches,
21
+ link: () => "share" in navigator
22
+ };
23
+ function isShareCapability(value) {
24
+ return shareCapabilities.some((capability) => capability === value);
25
+ }
26
+ function getShareCapabilities(preset) {
27
+ if (preset !== void 0) return preset.split(" ").filter(isShareCapability);
28
+ return shareCapabilities.filter((capability) => capabilityTests[capability]());
29
+ }
30
+ function isDomError(error, name) {
31
+ return error instanceof DOMException && error.name === name;
32
+ }
33
+ async function fetchFile({ filename, src, type }, signal) {
34
+ const response = await fetch(src, {
35
+ cache: "no-cache",
36
+ signal
37
+ });
38
+ if (!response.ok) throw new Error(`${String(response.status)} for ${src}`);
39
+ return new File([await response.blob()], filename, { type });
40
+ }
41
+ function saveFile(file) {
42
+ const objectUrl = URL.createObjectURL(file);
43
+ const link = document.createElement("a");
44
+ link.download = file.name;
45
+ link.href = objectUrl;
46
+ link.hidden = true;
47
+ document.body.append(link);
48
+ link.click();
49
+ link.remove();
50
+ return objectUrl;
51
+ }
52
+ async function toPngBlob(pending) {
53
+ const file = await pending;
54
+ if (!file) throw new Error("The image did not load");
55
+ const bitmap = await createImageBitmap(file);
56
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
57
+ const context = canvas.getContext("2d");
58
+ if (!context) throw new Error("No 2D context for the PNG conversion");
59
+ context.drawImage(bitmap, 0, 0);
60
+ bitmap.close();
61
+ return canvas.convertToBlob({ type: pngType });
62
+ }
63
+ function copyImage(file) {
64
+ return navigator.clipboard.write([new ClipboardItem({ [pngType]: toPngBlob(file) })]);
65
+ }
66
+ function isOpenHash(openHash) {
67
+ return openHash !== void 0 && location.hash === `#${openHash}`;
68
+ }
69
+ function clearOpenHash(openHash) {
70
+ if (!isOpenHash(openHash)) return;
71
+ history.replaceState(history.state, "", `${location.pathname}${location.search}`);
72
+ }
73
+ // src/assets.ts
74
+ function isFile(file) {
75
+ return file !== void 0;
76
+ }
77
+ var ShareAssetFiles = class {
78
+ #files = /* @__PURE__ */ new Map();
79
+ #loads = /* @__PURE__ */ new Map();
80
+ #objectUrls = /* @__PURE__ */ new Set();
81
+ #options;
82
+ constructor(options) {
83
+ this.#options = options;
84
+ }
85
+ dispose() {
86
+ for (const objectUrl of this.#objectUrls) URL.revokeObjectURL(objectUrl);
87
+ this.#objectUrls.clear();
88
+ this.#files.clear();
89
+ this.#loads.clear();
90
+ }
91
+ load(tile) {
92
+ const pending = this.#loads.get(tile);
93
+ if (pending) return pending;
94
+ const promise = this.#fetch(tile);
95
+ this.#loads.set(tile, promise);
96
+ return promise;
97
+ }
98
+ async save(tile) {
99
+ const file = await this.load(tile);
100
+ return file ? this.#saveFiles([file]) : "unsaved";
101
+ }
102
+ async share(tiles) {
103
+ const ready = tiles.map((tile) => this.#files.get(tile));
104
+ if (ready.every(isFile)) return this.#shareFiles(ready);
105
+ const loaded = await Promise.all(tiles.map((tile) => this.load(tile)));
106
+ return loaded.every(isFile) ? this.#shareFiles(loaded) : "error";
107
+ }
108
+ warm(target) {
109
+ if (!(target instanceof Element)) return;
110
+ const tile = target.closest("[data-share-kit-action=\"share\"]")?.closest("[data-share-kit-asset]");
111
+ if (tile) this.load(tile);
112
+ }
113
+ async #fetch(tile) {
114
+ const source = this.#options.getSource(tile);
115
+ if (!source) return;
116
+ try {
117
+ const file = await fetchFile(source, this.#options.signal);
118
+ this.#files.set(tile, file);
119
+ return file;
120
+ } catch {
121
+ this.#loads.delete(tile);
122
+ return;
123
+ }
124
+ }
125
+ #saveFiles(files) {
126
+ for (const file of files) this.#objectUrls.add(saveFile(file));
127
+ return "saved";
128
+ }
129
+ async #shareFiles(files) {
130
+ if (!this.#options.canShare || !navigator.canShare({ files })) return this.#saveFiles(files);
131
+ try {
132
+ await navigator.share({ files });
133
+ return "shared";
134
+ } catch (error) {
135
+ if (isDomError(error, "AbortError") || this.#options.signal.aborted) return "dismissed";
136
+ if (isDomError(error, "NotAllowedError")) return "retry";
137
+ return this.#saveFiles(files);
138
+ }
139
+ }
140
+ };
141
+ // src/count.ts
142
+ const urlFixedCost = 23;
143
+ const urlPattern = /https?:\/\/[\w!#$%&'()*+,./:;=?@~-]+/giu;
144
+ const urlTrailingPunctuation = /[!'),.:;?]+$/u;
145
+ const graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
146
+ const utf8Encoder = new TextEncoder();
147
+ const latinCombiningMarkRanges = [
148
+ [768, 879],
149
+ [6832, 6911],
150
+ [7616, 7679],
151
+ [8400, 8447],
152
+ [65056, 65071]
153
+ ];
154
+ function getEmojiPattern() {
155
+ try {
156
+ return new RegExp(String.raw`^\p{RGI_Emoji}$`, "v");
157
+ } catch {
158
+ return;
159
+ }
160
+ }
161
+ const emojiPattern = getEmojiPattern();
162
+ function getGraphemes(text) {
163
+ return Array.from(graphemeSegmenter.segment(text), ({ segment }) => segment);
164
+ }
165
+ function isLightCodePoint(codePoint) {
166
+ return codePoint <= 4351 || codePoint >= 8192 && codePoint <= 8205 || codePoint >= 8208 && codePoint <= 8223 || codePoint >= 8242 && codePoint <= 8247;
167
+ }
168
+ function getWeightedLength(text) {
169
+ const graphemes = getGraphemes(text.normalize("NFC"));
170
+ let total = 0;
171
+ for (const grapheme of graphemes) {
172
+ if (emojiPattern?.test(grapheme)) {
173
+ total += 2;
174
+ continue;
175
+ }
176
+ for (const character of grapheme) total += isLightCodePoint(character.codePointAt(0) ?? 0) ? 1 : 2;
177
+ }
178
+ return total;
179
+ }
180
+ function isLatinCombiningMark(codePoint) {
181
+ return latinCombiningMarkRanges.some(([start, end]) => codePoint >= start && codePoint <= end);
182
+ }
183
+ function getStringzLength(text) {
184
+ let total = 0;
185
+ for (const character of text) if (!isLatinCombiningMark(character.codePointAt(0) ?? 0)) total += 1;
186
+ return total;
187
+ }
188
+ function getShortenedUrlLength(url) {
189
+ if (!URL.canParse(url)) return getGraphemes(url).length;
190
+ const { hash, host, pathname, search } = new URL(url);
191
+ const path = `${pathname === "/" ? "" : pathname}${search}${hash}`;
192
+ return host.length + Math.min(path.length, 16);
193
+ }
194
+ const textCounters = {
195
+ graphemes: (text) => getGraphemes(text).length,
196
+ length: (text) => text.length,
197
+ stringz: getStringzLength,
198
+ utf8: (text) => utf8Encoder.encode(text).length,
199
+ weighted: getWeightedLength
200
+ };
201
+ function splitLinks(text) {
202
+ const links = [];
203
+ return {
204
+ links,
205
+ rest: text.replaceAll(urlPattern, (match) => {
206
+ const trailing = urlTrailingPunctuation.exec(match)?.[0] ?? "";
207
+ links.push(match.slice(0, match.length - trailing.length));
208
+ return trailing;
209
+ })
210
+ };
211
+ }
212
+ function countText(text, { counter, urlCost }) {
213
+ const count = textCounters[counter];
214
+ if (urlCost === "actual") return count(text);
215
+ const { links, rest } = splitLinks(text);
216
+ let total = count(rest);
217
+ for (const link of links) total += urlCost === "fixed" ? urlFixedCost : getShortenedUrlLength(link);
218
+ return total;
219
+ }
220
+ // src/destinations.ts
221
+ function withQuery(base, parameters) {
222
+ const url = new URL(base);
223
+ for (const [name, value] of Object.entries(parameters)) if (value) url.searchParams.set(name, value);
224
+ return url.href;
225
+ }
226
+ const shareDestinations = {
227
+ bluesky: {
228
+ assetRole: "portrait",
229
+ counter: "graphemes",
230
+ getComposerUrl: ({ text }) => withQuery("https://bsky.app/intent/compose", { text }),
231
+ isImagePost: true,
232
+ limit: 300,
233
+ shape: "full",
234
+ urlCost: "shortened"
235
+ },
236
+ facebook: {
237
+ assetRole: "landscape",
238
+ counter: "length",
239
+ getComposerUrl: ({ url }) => withQuery("https://www.facebook.com/sharer/sharer.php", { u: url }),
240
+ isImagePost: false,
241
+ isLinkOnly: true,
242
+ limit: 63206,
243
+ shape: "full",
244
+ urlCost: "actual"
245
+ },
246
+ instagram: {
247
+ assetRole: "portrait",
248
+ counter: "length",
249
+ isImagePost: true,
250
+ limit: 2200,
251
+ shape: "text",
252
+ urlCost: "actual"
253
+ },
254
+ "instagram-story": {
255
+ assetRole: "story",
256
+ counter: "length",
257
+ isImagePost: true,
258
+ shape: "url",
259
+ urlCost: "actual"
260
+ },
261
+ linkedin: {
262
+ assetRole: "landscape",
263
+ counter: "length",
264
+ getComposerUrl: ({ url }) => withQuery("https://www.linkedin.com/sharing/share-offsite/", { url }),
265
+ isImagePost: false,
266
+ isLinkOnly: true,
267
+ limit: 3e3,
268
+ shape: "full",
269
+ urlCost: "actual"
270
+ },
271
+ mastodon: {
272
+ assetRole: "portrait",
273
+ counter: "stringz",
274
+ isImagePost: true,
275
+ limit: 500,
276
+ shape: "full",
277
+ urlCost: "fixed"
278
+ },
279
+ messages: {
280
+ assetRole: "landscape",
281
+ counter: "length",
282
+ isImagePost: false,
283
+ shape: "full",
284
+ urlCost: "actual"
285
+ },
286
+ pinterest: {
287
+ assetRole: "portrait",
288
+ counter: "length",
289
+ getComposerUrl: ({ media, text, url }) => withQuery("https://www.pinterest.com/pin/create/button/", {
290
+ description: text,
291
+ media,
292
+ url
293
+ }),
294
+ isImagePost: false,
295
+ limit: 800,
296
+ shape: "text",
297
+ urlCost: "actual"
298
+ },
299
+ reddit: {
300
+ assetRole: "landscape",
301
+ counter: "length",
302
+ getComposerUrl: ({ text, url }) => withQuery("https://www.reddit.com/submit", {
303
+ title: text,
304
+ url
305
+ }),
306
+ isImagePost: false,
307
+ limit: 300,
308
+ shape: "title",
309
+ urlCost: "actual"
310
+ },
311
+ ["any"]: {
312
+ assetRole: "landscape",
313
+ counter: "length",
314
+ isImagePost: false,
315
+ shape: "full",
316
+ urlCost: "actual"
317
+ },
318
+ threads: {
319
+ assetRole: "portrait",
320
+ counter: "utf8",
321
+ getComposerUrl: ({ text }) => withQuery("https://www.threads.com/intent/post", { text }),
322
+ isImagePost: true,
323
+ limit: 500,
324
+ shape: "full",
325
+ urlCost: "actual"
326
+ },
327
+ x: {
328
+ assetRole: "landscape",
329
+ counter: "weighted",
330
+ getComposerUrl: ({ text }) => withQuery("https://x.com/intent/tweet", { text }),
331
+ isImagePost: false,
332
+ limit: 280,
333
+ shape: "full",
334
+ urlCost: "fixed"
335
+ }
336
+ };
337
+ function isShareDestinationId(id) {
338
+ return Object.hasOwn(shareDestinations, id);
339
+ }
340
+ function getShareDestination(id) {
341
+ return shareDestinations[id];
342
+ }
343
+ function getDestinationUrl(url, id, utmMedium) {
344
+ if (!utmMedium || id === "any" || !URL.canParse(url)) return url;
345
+ return withQuery(url, {
346
+ utm_medium: utmMedium,
347
+ utm_source: id
348
+ });
349
+ }
350
+ function getHandheldAction({ canShareFiles, canShareText, id }) {
351
+ const { isImagePost, isLinkOnly } = getShareDestination(id);
352
+ if (isImagePost && canShareFiles) return "share-image";
353
+ if (isLinkOnly === true && canShareText) return "share-link";
354
+ if (id === "any" && canShareText) return "share-text";
355
+ }
356
+ function getPrimaryAction(input) {
357
+ const handheldAction = input.isHandheld ? getHandheldAction(input) : void 0;
358
+ if (handheldAction) return handheldAction;
359
+ if (input.hasComposerUrl) return "open-composer";
360
+ if (input.id === "messages" && input.canShareText) return "share-text";
361
+ return "copy-caption";
362
+ }
363
+ // src/caption.ts
364
+ const separator = "\n\n";
365
+ const ellipsis = "…";
366
+ function createSegmenter(locale, granularity) {
367
+ try {
368
+ return new Intl.Segmenter(locale, { granularity });
369
+ } catch {
370
+ return new Intl.Segmenter(void 0, { granularity });
371
+ }
372
+ }
373
+ function getSegmentEnds(text, granularity, locale) {
374
+ const segments = createSegmenter(locale, granularity).segment(text);
375
+ return Array.from(segments, ({ index, segment }) => index + segment.length);
376
+ }
377
+ function getGraphemeEnds(text) {
378
+ let end = 0;
379
+ return getGraphemes(text).map((grapheme) => end += grapheme.length);
380
+ }
381
+ function join(parts) {
382
+ return parts.filter(Boolean).join(separator);
383
+ }
384
+ function findCut({ canFit, ends, suffix, text }) {
385
+ let fitted;
386
+ for (const end of ends) {
387
+ const cut = text.slice(0, end).trimEnd();
388
+ if (cut.length === 0 || cut.length === text.length) continue;
389
+ const candidate = `${cut}${suffix}`;
390
+ if (!canFit(candidate)) break;
391
+ fitted = candidate;
392
+ }
393
+ return fitted;
394
+ }
395
+ function fitBody({ body, canFit, link, locale, title }) {
396
+ if (!body) return;
397
+ const canFitBody = (candidate) => canFit(join([
398
+ title,
399
+ candidate,
400
+ link
401
+ ]));
402
+ return findCut({
403
+ canFit: canFitBody,
404
+ ends: getSegmentEnds(body, "sentence", locale),
405
+ suffix: "",
406
+ text: body
407
+ }) ?? findCut({
408
+ canFit: canFitBody,
409
+ ends: getSegmentEnds(body, "word", locale),
410
+ suffix: ellipsis,
411
+ text: body
412
+ });
413
+ }
414
+ function fitTitle({ canFit, link, locale, title }) {
415
+ const canFitTitle = (candidate) => canFit(join([candidate, link]));
416
+ return findCut({
417
+ canFit: canFitTitle,
418
+ ends: getSegmentEnds(title, "word", locale),
419
+ suffix: ellipsis,
420
+ text: title
421
+ }) ?? findCut({
422
+ canFit: canFitTitle,
423
+ ends: getGraphemeEnds(title),
424
+ suffix: ellipsis,
425
+ text: title
426
+ }) ?? title;
427
+ }
428
+ function fitParts(input) {
429
+ const { canFit, link, title } = input;
430
+ const body = fitBody(input);
431
+ if (body) return join([
432
+ title,
433
+ body,
434
+ link
435
+ ]);
436
+ const bare = join([title, link]);
437
+ return canFit(bare) ? bare : join([fitTitle(input), link]);
438
+ }
439
+ function countCaption(text, id) {
440
+ return countText(text, getShareDestination(id));
441
+ }
442
+ function fitCaption({ description, title, url }, id, locale = "en") {
443
+ const { limit, shape } = getShareDestination(id);
444
+ const link = shape === "full" ? url : void 0;
445
+ const body = shape === "title" ? void 0 : description?.trim() || void 0;
446
+ const whole = shape === "url" ? url : join([
447
+ title,
448
+ body,
449
+ link
450
+ ]);
451
+ const canFit = (text) => limit === void 0 || countCaption(text, id) <= limit;
452
+ const text = canFit(whole) ? whole : fitParts({
453
+ body,
454
+ canFit,
455
+ link,
456
+ locale,
457
+ title
458
+ });
459
+ return {
460
+ count: countCaption(text, id),
461
+ isTruncated: text !== whole,
462
+ limit,
463
+ text
464
+ };
465
+ }
466
+ // src/dom.ts
467
+ function createElement(tag, attributes = {}, children = []) {
468
+ const element = document.createElement(tag);
469
+ for (const [name, value] of Object.entries(attributes)) if (value !== void 0) element.setAttribute(name, value);
470
+ element.append(...children.filter((child) => child !== void 0));
471
+ return element;
472
+ }
473
+ function joinClasses(...classes) {
474
+ return classes.filter(Boolean).join(" ");
475
+ }
476
+ const svgNamespace = "http://www.w3.org/2000/svg";
477
+ function createIcon(path, size) {
478
+ const svg = document.createElementNS(svgNamespace, "svg");
479
+ const shape = document.createElementNS(svgNamespace, "path");
480
+ svg.setAttribute("aria-hidden", "true");
481
+ svg.setAttribute("height", String(size));
482
+ svg.setAttribute("viewBox", "0 0 24 24");
483
+ svg.setAttribute("width", String(size));
484
+ shape.setAttribute("d", path);
485
+ shape.setAttribute("fill", "currentColor");
486
+ svg.append(shape);
487
+ return svg;
488
+ }
489
+ function isOnBackdrop(dialog, event) {
490
+ if (event.target !== dialog) return false;
491
+ const rect = dialog.getBoundingClientRect();
492
+ return event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom;
493
+ }
494
+ function polyfillLightDismiss(dialog, signal) {
495
+ if ("closedBy" in HTMLDialogElement.prototype) return;
496
+ let isBackdropPress = false;
497
+ dialog.addEventListener("pointerdown", (event) => {
498
+ isBackdropPress = isOnBackdrop(dialog, event);
499
+ }, { signal });
500
+ dialog.addEventListener("pointerup", (event) => {
501
+ if (isBackdropPress && isOnBackdrop(dialog, event)) dialog.close();
502
+ isBackdropPress = false;
503
+ }, { signal });
504
+ }
505
+ const radioKeys = {
506
+ ArrowDown: (index, count) => (index + 1) % count,
507
+ ArrowLeft: (index, count) => (index - 1 + count) % count,
508
+ ArrowRight: (index, count) => (index + 1) % count,
509
+ ArrowUp: (index, count) => (index - 1 + count) % count,
510
+ End: (_index, count) => count - 1,
511
+ Home: () => 0
512
+ };
513
+ // src/feedback.ts
514
+ const statusDurationMs = 4e3;
515
+ const flashDurationMs = 2e3;
516
+ var ShareFeedback = class {
517
+ #flashing = /* @__PURE__ */ new WeakSet();
518
+ #getStatus;
519
+ #strings;
520
+ #timeout;
521
+ constructor(getStatus, strings) {
522
+ this.#getStatus = getStatus;
523
+ this.#strings = strings;
524
+ }
525
+ announce(message) {
526
+ const status = this.#getStatus();
527
+ if (!status) return;
528
+ status.textContent = message;
529
+ clearTimeout(this.#timeout);
530
+ this.#timeout = setTimeout(() => {
531
+ status.textContent = "";
532
+ }, statusDurationMs);
533
+ }
534
+ async copyImage(file, button) {
535
+ try {
536
+ await copyImage(file);
537
+ this.#flash(button);
538
+ } catch {
539
+ this.announce(this.#strings.error);
540
+ }
541
+ }
542
+ async copyText(text, button, fallback) {
543
+ try {
544
+ await navigator.clipboard.writeText(text);
545
+ this.#flash(button);
546
+ } catch {
547
+ fallback?.select();
548
+ this.announce(fallback ? this.#strings.copyManual : this.#strings.error);
549
+ }
550
+ }
551
+ dispose() {
552
+ clearTimeout(this.#timeout);
553
+ }
554
+ #flash(button) {
555
+ this.announce(this.#strings.copied);
556
+ if (!button || this.#flashing.has(button)) return;
557
+ const label = button.textContent;
558
+ this.#flashing.add(button);
559
+ button.textContent = this.#strings.copied;
560
+ setTimeout(() => {
561
+ button.textContent = label;
562
+ this.#flashing.delete(button);
563
+ }, flashDurationMs);
564
+ }
565
+ };
566
+ // src/icons.ts
567
+ const instagram = "M7.0301.084c-1.2768.0602-2.1487.264-2.911.5634-.7888.3075-1.4575.72-2.1228 1.3877-.6652.6677-1.075 1.3368-1.3802 2.127-.2954.7638-.4956 1.6365-.552 2.914-.0564 1.2775-.0689 1.6882-.0626 4.947.0062 3.2586.0206 3.6671.0825 4.9473.061 1.2765.264 2.1482.5635 2.9107.308.7889.72 1.4573 1.388 2.1228.6679.6655 1.3365 1.0743 2.1285 1.38.7632.295 1.6361.4961 2.9134.552 1.2773.056 1.6884.069 4.9462.0627 3.2578-.0062 3.668-.0207 4.9478-.0814 1.28-.0607 2.147-.2652 2.9098-.5633.7889-.3086 1.4578-.72 2.1228-1.3881.665-.6682 1.0745-1.3378 1.3795-2.1284.2957-.7632.4966-1.636.552-2.9124.056-1.2809.0692-1.6898.063-4.948-.0063-3.2583-.021-3.6668-.0817-4.9465-.0607-1.2797-.264-2.1487-.5633-2.9117-.3084-.7889-.72-1.4568-1.3876-2.1228C21.2982 1.33 20.628.9208 19.8378.6165 19.074.321 18.2017.1197 16.9244.0645 15.6471.0093 15.236-.005 11.977.0014 8.718.0076 8.31.0215 7.0301.0839m.1402 21.6932c-1.17-.0509-1.8053-.2453-2.2287-.408-.5606-.216-.96-.4771-1.3819-.895-.422-.4178-.6811-.8186-.9-1.378-.1644-.4234-.3624-1.058-.4171-2.228-.0595-1.2645-.072-1.6442-.079-4.848-.007-3.2037.0053-3.583.0607-4.848.05-1.169.2456-1.805.408-2.2282.216-.5613.4762-.96.895-1.3816.4188-.4217.8184-.6814 1.3783-.9003.423-.1651 1.0575-.3614 2.227-.4171 1.2655-.06 1.6447-.072 4.848-.079 3.2033-.007 3.5835.005 4.8495.0608 1.169.0508 1.8053.2445 2.228.408.5608.216.96.4754 1.3816.895.4217.4194.6816.8176.9005 1.3787.1653.4217.3617 1.056.4169 2.2263.0602 1.2655.0739 1.645.0796 4.848.0058 3.203-.0055 3.5834-.061 4.848-.051 1.17-.245 1.8055-.408 2.2294-.216.5604-.4763.96-.8954 1.3814-.419.4215-.8181.6811-1.3783.9-.4224.1649-1.0577.3617-2.2262.4174-1.2656.0595-1.6448.072-4.8493.079-3.2045.007-3.5825-.006-4.848-.0608M16.953 5.5864A1.44 1.44 0 1 0 18.39 4.144a1.44 1.44 0 0 0-1.437 1.4424M5.8385 12.012c.0067 3.4032 2.7706 6.1557 6.173 6.1493 3.4026-.0065 6.157-2.7701 6.1506-6.1733-.0065-3.4032-2.771-6.1565-6.174-6.1498-3.403.0067-6.156 2.771-6.1496 6.1738M8 12.0077a4 4 0 1 1 4.008 3.9921A3.9996 3.9996 0 0 1 8 12.0077";
568
+ const shareKitIcons = {
569
+ any: "M3.16 14.47L5.99 11.65A4.5 4.5 0 0 1 12.35 18.01L9.53 20.84A4.5 4.5 0 0 1 3.16 14.47ZM4.58 15.89A2.5 2.5 0 0 0 8.11 19.42L10.94 16.6A2.5 2.5 0 0 0 7.4 13.06ZM11.65 5.99L14.47 3.16A4.5 4.5 0 0 1 20.84 9.53L18.01 12.35A4.5 4.5 0 0 1 11.65 5.99ZM13.06 7.4A2.5 2.5 0 0 0 16.6 10.94L19.42 8.11A2.5 2.5 0 0 0 15.89 4.58ZM8.46 14.12L14.12 8.46L15.54 9.88L9.88 15.54Z",
570
+ bluesky: "M5.202 2.857C7.954 4.922 10.913 9.11 12 11.358c1.087-2.247 4.046-6.436 6.798-8.501C20.783 1.366 24 .213 24 3.883c0 .732-.42 6.156-.667 7.037-.856 3.061-3.978 3.842-6.755 3.37 4.854.826 6.089 3.562 3.422 6.299-5.065 5.196-7.28-1.304-7.847-2.97-.104-.305-.152-.448-.153-.327 0-.121-.05.022-.153.327-.568 1.666-2.782 8.166-7.847 2.97-2.667-2.737-1.432-5.473 3.422-6.3-2.777.473-5.899-.308-6.755-3.369C.42 10.04 0 4.615 0 3.883c0-3.67 3.217-2.517 5.202-1.026",
571
+ close: "M6 7.41 7.41 6 12 10.59 16.59 6 18 7.41 13.41 12 18 16.59 16.59 18 12 13.41 7.41 18 6 16.59 10.59 12Z",
572
+ facebook: "M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z",
573
+ instagram,
574
+ "instagram-story": instagram,
575
+ linkedin: "M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z",
576
+ mastodon: "M23.268 5.313c-.35-2.578-2.617-4.61-5.304-5.004C17.51.242 15.792 0 11.813 0h-.03c-3.98 0-4.835.242-5.288.309C3.882.692 1.496 2.518.917 5.127.64 6.412.61 7.837.661 9.143c.074 1.874.088 3.745.26 5.611.118 1.24.325 2.47.62 3.68.55 2.237 2.777 4.098 4.96 4.857 2.336.792 4.849.923 7.256.38.265-.061.527-.132.786-.213.585-.184 1.27-.39 1.774-.753a.057.057 0 0 0 .023-.043v-1.809a.052.052 0 0 0-.02-.041.053.053 0 0 0-.046-.01 20.282 20.282 0 0 1-4.709.545c-2.73 0-3.463-1.284-3.674-1.818a5.593 5.593 0 0 1-.319-1.433.053.053 0 0 1 .066-.054c1.517.363 3.072.546 4.632.546.376 0 .75 0 1.125-.01 1.57-.044 3.224-.124 4.768-.422.038-.008.077-.015.11-.024 2.435-.464 4.753-1.92 4.989-5.604.008-.145.03-1.52.03-1.67.002-.512.167-3.63-.024-5.545zm-3.748 9.195h-2.561V8.29c0-1.309-.55-1.976-1.67-1.976-1.23 0-1.846.79-1.846 2.35v3.403h-2.546V8.663c0-1.56-.617-2.35-1.848-2.35-1.112 0-1.668.668-1.67 1.977v6.218H4.822V8.102c0-1.31.337-2.35 1.011-3.12.696-.77 1.608-1.164 2.74-1.164 1.311 0 2.302.5 2.962 1.498l.638 1.06.638-1.06c.66-.999 1.65-1.498 2.96-1.498 1.13 0 2.043.395 2.74 1.164.675.77 1.012 1.81 1.012 3.12z",
577
+ messages: "M5 4h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2ZM5 6v9h14V6ZM7 17v4l4-4Z",
578
+ more: "M4 12a2 2 0 1 0 4 0a2 2 0 1 0-4 0ZM10 12a2 2 0 1 0 4 0a2 2 0 1 0-4 0ZM16 12a2 2 0 1 0 4 0a2 2 0 1 0-4 0Z",
579
+ pinterest: "M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z",
580
+ qr: "M3 3h7v7H3ZM4.5 4.5v4h4v-4ZM5.5 5.5h2v2h-2ZM14 3h7v7h-7ZM15.5 4.5v4h4v-4ZM16.5 5.5h2v2h-2ZM3 14h7v7H3ZM4.5 15.5v4h4v-4ZM5.5 16.5h2v2h-2ZM14 14h2v2h-2ZM18 14h3v2h-3ZM16 16h2v2h-2ZM14 18h2v3h-2ZM18 18h3v3h-3Z",
581
+ reddit: "M12 0C5.373 0 0 5.373 0 12c0 3.314 1.343 6.314 3.515 8.485l-2.286 2.286C.775 23.225 1.097 24 1.738 24H12c6.627 0 12-5.373 12-12S18.627 0 12 0Zm4.388 3.199c1.104 0 1.999.895 1.999 1.999 0 1.105-.895 2-1.999 2-.946 0-1.739-.657-1.947-1.539v.002c-1.147.162-2.032 1.15-2.032 2.341v.007c1.776.067 3.4.567 4.686 1.363.473-.363 1.064-.58 1.707-.58 1.547 0 2.802 1.254 2.802 2.802 0 1.117-.655 2.081-1.601 2.531-.088 3.256-3.637 5.876-7.997 5.876-4.361 0-7.905-2.617-7.998-5.87-.954-.447-1.614-1.415-1.614-2.538 0-1.548 1.255-2.802 2.803-2.802.645 0 1.239.218 1.712.585 1.275-.79 2.881-1.291 4.64-1.365v-.01c0-1.663 1.263-3.034 2.88-3.207.188-.911.993-1.595 1.959-1.595Zm-8.085 8.376c-.784 0-1.459.78-1.506 1.797-.047 1.016.64 1.429 1.426 1.429.786 0 1.371-.369 1.418-1.385.047-1.017-.553-1.841-1.338-1.841Zm7.406 0c-.786 0-1.385.824-1.338 1.841.047 1.017.634 1.385 1.418 1.385.785 0 1.473-.413 1.426-1.429-.046-1.017-.721-1.797-1.506-1.797Zm-3.703 4.013c-.974 0-1.907.048-2.77.135-.147.015-.241.168-.183.305.483 1.154 1.622 1.964 2.953 1.964 1.33 0 2.47-.81 2.953-1.964.057-.137-.037-.29-.184-.305-.863-.087-1.795-.135-2.769-.135Z",
582
+ threads: "M12.186 24h-.007c-3.581-.024-6.334-1.205-8.184-3.509C2.35 18.44 1.5 15.586 1.472 12.01v-.017c.03-3.579.879-6.43 2.525-8.482C5.845 1.205 8.6.024 12.18 0h.014c2.746.02 5.043.725 6.826 2.098 1.677 1.29 2.858 3.13 3.509 5.467l-2.04.569c-1.104-3.96-3.898-5.984-8.304-6.015-2.91.022-5.11.936-6.54 2.717C4.307 6.504 3.616 8.914 3.589 12c.027 3.086.718 5.496 2.057 7.164 1.43 1.783 3.631 2.698 6.54 2.717 2.623-.02 4.358-.631 5.8-2.045 1.647-1.613 1.618-3.593 1.09-4.798-.31-.71-.873-1.3-1.634-1.75-.192 1.352-.622 2.446-1.284 3.272-.886 1.102-2.14 1.704-3.73 1.79-1.202.065-2.361-.218-3.259-.801-1.063-.689-1.685-1.74-1.752-2.964-.065-1.19.408-2.285 1.33-3.082.88-.76 2.119-1.207 3.583-1.291a13.853 13.853 0 0 1 3.02.142c-.126-.742-.375-1.332-.75-1.757-.513-.586-1.308-.883-2.359-.89h-.029c-.844 0-1.992.232-2.721 1.32L7.734 7.847c.98-1.454 2.568-2.256 4.478-2.256h.044c3.194.02 5.097 1.975 5.287 5.388.108.046.216.094.321.142 1.49.7 2.58 1.761 3.154 3.07.797 1.82.871 4.79-1.548 7.158-1.85 1.81-4.094 2.628-7.277 2.65Zm1.003-11.69c-.242 0-.487.007-.739.021-1.836.103-2.98.946-2.916 2.143.067 1.256 1.452 1.839 2.784 1.767 1.224-.065 2.818-.543 3.086-3.71a10.5 10.5 0 0 0-2.215-.221z",
583
+ x: "M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z"
584
+ };
585
+ // src/strings.ts
586
+ const shareKitStringDefaults = {
587
+ assetCopy: "Copy",
588
+ assetSave: "Save",
589
+ assetShare: "Share",
590
+ captionCopy: "Copy caption",
591
+ captionOver: "{count} over the limit for {destination}",
592
+ captionReset: "Reset",
593
+ captionTitle: "Caption",
594
+ close: "Close",
595
+ copied: "Copied",
596
+ copyManual: "Couldn't copy. The caption is selected, so you can copy it yourself.",
597
+ "destination.any": "Anywhere",
598
+ "destination.bluesky": "Bluesky",
599
+ "destination.facebook": "Facebook",
600
+ "destination.instagram": "Instagram",
601
+ "destination.instagram-story": "Story",
602
+ "destination.linkedin": "LinkedIn",
603
+ "destination.mastodon": "Mastodon",
604
+ "destination.messages": "Messages",
605
+ "destination.pinterest": "Pinterest",
606
+ "destination.reddit": "Reddit",
607
+ "destination.threads": "Threads",
608
+ "destination.x": "X",
609
+ destinationsMore: "More",
610
+ destinationsTitle: "Post to",
611
+ error: "Something went wrong. Try saving instead.",
612
+ "hint.facebook": "Facebook only takes the link. Your caption is copied, so paste it into your post.",
613
+ "hint.instagram": "Links in Instagram captions aren't clickable. Point people to the link in your bio.",
614
+ "hint.instagram-story": "Add the link to your Story with a link sticker.",
615
+ "hint.linkedin": "LinkedIn only takes the link. Your caption is copied, so paste it into your post.",
616
+ "hint.reddit": "Reddit takes a title and the link.",
617
+ imagesTitle: "Images",
618
+ linkCopy: "Copy link",
619
+ linkTitle: "Link",
620
+ primaryCopy: "Copy caption",
621
+ primaryOpen: "Open {destination}",
622
+ primaryShareImage: "Share image",
623
+ primaryShareLink: "Share link",
624
+ primaryShareText: "Share",
625
+ qrAlt: "QR code for this page",
626
+ qrTitle: "Scan to continue on your phone",
627
+ qrToggle: "Continue on your phone",
628
+ retry: "Ready. Tap again to share.",
629
+ saved: "Saved",
630
+ saveError: "Couldn't save. Try again.",
631
+ suggested: "Suggested",
632
+ title: "Share this page"
633
+ };
634
+ function isShareStringKey(key) {
635
+ return Object.hasOwn(shareKitStringDefaults, key);
636
+ }
637
+ function formatShareString(template, values) {
638
+ return template.replaceAll(/\{(\w+)\}/gu, (match, name) => values[name] ?? match);
639
+ }
640
+ // src/payload.ts
641
+ function isPayload(value) {
642
+ if (typeof value !== "object" || value === null) return false;
643
+ const { assets, settings, title, url } = value;
644
+ return typeof title === "string" && typeof url === "string" && Array.isArray(assets) && typeof settings === "object" && settings !== null;
645
+ }
646
+ function serializeShareKitPayload(payload) {
647
+ return JSON.stringify(payload).replaceAll("<", String.raw`\u003c`);
648
+ }
649
+ function readSharePayload(host) {
650
+ const source = host.querySelector(":scope > script[type=\"application/json\"]")?.textContent;
651
+ if (!source) return;
652
+ try {
653
+ const value = JSON.parse(source);
654
+ return isPayload(value) ? value : void 0;
655
+ } catch {
656
+ return;
657
+ }
658
+ }
659
+ function getShareStrings(overrides = {}) {
660
+ const strings = { ...shareKitStringDefaults };
661
+ for (const [key, value] of Object.entries(overrides)) if (value !== void 0 && isShareStringKey(key)) strings[key] = value;
662
+ return strings;
663
+ }
664
+ function getIds(value) {
665
+ if (!Array.isArray(value)) return [];
666
+ return [...new Set(value)].filter((id) => typeof id === "string" && isShareDestinationId(id));
667
+ }
668
+ function getDestinationLists({ destinations, destinationsMore }) {
669
+ const shown = getIds(destinations);
670
+ const main = shown.length > 0 ? shown : ["any"];
671
+ return {
672
+ main,
673
+ more: getIds(destinationsMore).filter((id) => !main.includes(id))
674
+ };
675
+ }
676
+ // src/qr.ts
677
+ const iconSize = 24;
678
+ const qrSize = 200;
679
+ async function createQrSource(text) {
680
+ const [{ generate }, { toSvgDataURL }] = await Promise.all([import("lean-qr"), import("lean-qr/extras/svg")]);
681
+ return toSvgDataURL(generate(text), {
682
+ off: "#ffffff",
683
+ on: "#000000",
684
+ pad: 4,
685
+ scale: 8
686
+ });
687
+ }
688
+ var ShareQrDialog = class {
689
+ dialog;
690
+ #image;
691
+ #url;
692
+ constructor({ closeIcon, id, signal, strings, url }) {
693
+ const titleId = `${id}-title`;
694
+ this.#url = url;
695
+ this.#image = createElement("img", {
696
+ alt: strings.qrAlt,
697
+ class: "share-kit-qr-image",
698
+ height: String(qrSize),
699
+ width: String(qrSize)
700
+ });
701
+ this.dialog = createElement("dialog", {
702
+ "aria-labelledby": titleId,
703
+ class: "share-kit-qr-dialog",
704
+ closedby: "any",
705
+ id
706
+ }, [createElement("form", {
707
+ class: "share-kit-header",
708
+ method: "dialog"
709
+ }, [createElement("h2", {
710
+ class: "share-kit-title",
711
+ id: titleId
712
+ }, [strings.qrTitle]), createElement("button", {
713
+ "aria-label": strings.close,
714
+ class: "share-kit-icon-button",
715
+ title: strings.close,
716
+ type: "submit"
717
+ }, [closeIcon ? createIcon(closeIcon, iconSize) : "×"])]), this.#image]);
718
+ polyfillLightDismiss(this.dialog, signal);
719
+ }
720
+ async open() {
721
+ if (!this.#image.getAttribute("src")) this.#image.src = await createQrSource(this.#url);
722
+ this.dialog.showModal();
723
+ }
724
+ };
725
+ function getQrUrl(url, openHash) {
726
+ if (!openHash || !URL.canParse(url)) return url;
727
+ const target = new URL(url);
728
+ target.hash = openHash;
729
+ return target.href;
730
+ }
731
+ function createShareQr({ capabilities, payload, ...input }) {
732
+ if (capabilities.has("handheld")) return;
733
+ return new ShareQrDialog({
734
+ ...input,
735
+ url: getQrUrl(payload.url, payload.settings.openHash)
736
+ });
737
+ }
738
+ // src/render.ts
739
+ const destinationIconSize = 24;
740
+ function renderAction({ classNames }, { action, describedBy, label }) {
741
+ return createElement("button", {
742
+ "aria-describedby": describedBy,
743
+ class: joinClasses("share-kit-action", classNames.action),
744
+ "data-share-kit-action": action,
745
+ type: "button"
746
+ }, [label]);
747
+ }
748
+ function renderHeading({ classNames }, children, id) {
749
+ return createElement("h3", {
750
+ class: joinClasses("share-kit-heading", classNames.heading),
751
+ id
752
+ }, children);
753
+ }
754
+ function renderIconButton({ action, attributes, fallback, icon, label }) {
755
+ return createElement("button", {
756
+ ...attributes,
757
+ "aria-label": label,
758
+ class: "share-kit-icon-button",
759
+ "data-share-kit-action": action,
760
+ title: label,
761
+ type: "button"
762
+ }, [icon ? createIcon(icon, destinationIconSize) : fallback]);
763
+ }
764
+ function renderHeader(context) {
765
+ const { capabilities, icons, id, strings } = context;
766
+ const heading = createElement("h2", {
767
+ class: "share-kit-title",
768
+ id: `${id}-title`,
769
+ tabindex: "-1"
770
+ }, [strings.title]);
771
+ return {
772
+ header: createElement("header", { class: "share-kit-header" }, [heading, createElement("div", { class: "share-kit-header-actions" }, [capabilities.has("handheld") ? void 0 : renderIconButton({
773
+ action: "qr",
774
+ attributes: { "aria-haspopup": "dialog" },
775
+ fallback: "QR",
776
+ icon: icons.qr,
777
+ label: strings.qrToggle
778
+ }), renderIconButton({
779
+ action: "close",
780
+ fallback: "×",
781
+ icon: icons.close,
782
+ label: strings.close
783
+ })])]),
784
+ heading
785
+ };
786
+ }
787
+ function renderDestination(context, destination) {
788
+ const { classNames, icons, strings } = context;
789
+ const icon = icons[destination];
790
+ return createElement("button", {
791
+ "aria-checked": "false",
792
+ class: joinClasses("share-kit-destination", classNames.destination),
793
+ "data-share-kit-action": "destination",
794
+ "data-share-kit-destination": destination,
795
+ role: "radio",
796
+ tabindex: "-1",
797
+ type: "button"
798
+ }, [icon ? createIcon(icon, destinationIconSize) : void 0, createElement("span", {}, [strings[`destination.${destination}`]])]);
799
+ }
800
+ function renderDestinations(context) {
801
+ const { destinations, destinationsMore, icons, id, strings } = context;
802
+ const headingId = `${id}-destinations`;
803
+ const more = destinationsMore.length > 0 ? createElement("button", {
804
+ class: joinClasses("share-kit-destination", context.classNames.destination),
805
+ "data-share-kit-action": "more",
806
+ type: "button"
807
+ }, [icons.more ? createIcon(icons.more, destinationIconSize) : void 0, createElement("span", {}, [strings.destinationsMore])]) : void 0;
808
+ const extra = destinationsMore.map((destination) => {
809
+ const button = renderDestination(context, destination);
810
+ button.hidden = true;
811
+ return button;
812
+ });
813
+ const group = createElement("div", {
814
+ "aria-labelledby": headingId,
815
+ class: "share-kit-destinations",
816
+ role: "radiogroup"
817
+ }, [...destinations.map((destination) => renderDestination(context, destination)), ...extra]);
818
+ return {
819
+ more,
820
+ section: createElement("section", { class: "share-kit-section" }, [renderHeading(context, [strings.destinationsTitle], headingId), createElement("div", { class: "share-kit-destinations-row" }, [group, more])])
821
+ };
822
+ }
823
+ function renderCaption(context) {
824
+ const { classNames, id, payload, strings } = context;
825
+ const captionId = `${id}-caption`;
826
+ const countId = `${id}-count`;
827
+ const hintId = `${id}-hint`;
828
+ const caption = createElement("textarea", {
829
+ "aria-describedby": `${countId} ${hintId}`,
830
+ class: joinClasses("share-kit-caption", classNames.input),
831
+ dir: "auto",
832
+ id: captionId,
833
+ lang: payload.locale,
834
+ rows: "6"
835
+ });
836
+ const count = createElement("span", {
837
+ class: "share-kit-count",
838
+ id: countId
839
+ });
840
+ const captionCopy = renderAction(context, {
841
+ action: "copy-caption",
842
+ label: strings.captionCopy
843
+ });
844
+ const hint = createElement("p", {
845
+ class: "share-kit-hint",
846
+ id: hintId
847
+ });
848
+ return {
849
+ caption,
850
+ captionCopy,
851
+ count,
852
+ hint,
853
+ section: createElement("section", { class: "share-kit-section" }, [
854
+ renderHeading(context, [createElement("label", { for: captionId }, [strings.captionTitle])]),
855
+ caption,
856
+ createElement("div", { class: "share-kit-caption-meta" }, [count, createElement("span", { class: "share-kit-actions" }, [renderAction(context, {
857
+ action: "reset",
858
+ label: strings.captionReset
859
+ }), captionCopy])]),
860
+ hint
861
+ ])
862
+ };
863
+ }
864
+ function renderTile(context, { actions, asset, key }) {
865
+ const labelId = `${context.id}-asset-${key}`;
866
+ const badge = createElement("span", { class: "share-kit-badge" }, [context.strings.suggested]);
867
+ badge.hidden = true;
868
+ return createElement("li", {
869
+ class: "share-kit-tile",
870
+ "data-share-kit-asset": key,
871
+ "data-share-kit-role": asset.role
872
+ }, [
873
+ createElement("img", {
874
+ alt: asset.alt,
875
+ class: "share-kit-preview",
876
+ decoding: "async",
877
+ height: String(asset.height),
878
+ loading: "lazy",
879
+ src: asset.previewSrc,
880
+ width: String(asset.width)
881
+ }),
882
+ createElement("div", { class: "share-kit-tile-label" }, [createElement("span", { id: labelId }, [asset.label]), badge]),
883
+ createElement("div", { class: "share-kit-actions" }, actions.map(([action, label]) => renderAction(context, {
884
+ action,
885
+ describedBy: labelId,
886
+ label
887
+ })))
888
+ ]);
889
+ }
890
+ function getAssetActions({ capabilities, strings }) {
891
+ const actions = [];
892
+ const canShare = capabilities.has("files");
893
+ if (canShare) actions.push(["share", strings.assetShare]);
894
+ if (capabilities.has("copy-image") && !(canShare && capabilities.has("handheld"))) actions.push(["copy", strings.assetCopy]);
895
+ actions.push(["save", strings.assetSave]);
896
+ return actions;
897
+ }
898
+ function renderImages(context) {
899
+ const { payload, strings } = context;
900
+ const actions = getAssetActions(context);
901
+ const counts = /* @__PURE__ */ new Map();
902
+ const assets = /* @__PURE__ */ new Map();
903
+ for (const asset of payload.assets) {
904
+ const number = (counts.get(asset.role) ?? 0) + 1;
905
+ const key = asset.role === "photo" ? `photo-${String(number)}` : asset.role;
906
+ counts.set(asset.role, number);
907
+ assets.set(renderTile(context, {
908
+ actions,
909
+ asset,
910
+ key
911
+ }), asset);
912
+ }
913
+ const grid = createElement("ul", { class: "share-kit-grid" }, [...assets.keys()]);
914
+ return {
915
+ assets,
916
+ grid,
917
+ section: createElement("section", { class: "share-kit-section" }, [renderHeading(context, [strings.imagesTitle]), grid])
918
+ };
919
+ }
920
+ function renderLink(context) {
921
+ const { payload, strings } = context;
922
+ return createElement("section", { class: "share-kit-section" }, [renderHeading(context, [strings.linkTitle]), createElement("div", { class: "share-kit-link-row" }, [createElement("p", { class: "share-kit-link" }, [payload.url]), renderAction(context, {
923
+ action: "copy-link",
924
+ label: strings.linkCopy
925
+ })])]);
926
+ }
927
+ function renderShareKit(input) {
928
+ const context = {
929
+ ...input,
930
+ classNames: input.payload.settings.classNames ?? {}
931
+ };
932
+ const { header, heading } = renderHeader(context);
933
+ const destinations = renderDestinations(context);
934
+ const caption = renderCaption(context);
935
+ const images = renderImages(context);
936
+ const status = createElement("p", {
937
+ class: "share-kit-status",
938
+ role: "status"
939
+ });
940
+ const primary = createElement("button", {
941
+ class: joinClasses("share-kit-primary", context.classNames.primary),
942
+ "data-share-kit-action": "primary",
943
+ type: "button"
944
+ });
945
+ const dialog = createElement("dialog", {
946
+ "aria-labelledby": heading.id,
947
+ class: "share-kit-dialog",
948
+ closedby: "any",
949
+ id: input.id
950
+ }, [createElement("div", { class: "share-kit-body" }, [
951
+ header,
952
+ createElement("div", { class: "share-kit-scroll" }, [
953
+ destinations.section,
954
+ caption.section,
955
+ images.section,
956
+ renderLink(context)
957
+ ]),
958
+ createElement("footer", { class: "share-kit-footer" }, [status, primary])
959
+ ])]);
960
+ return {
961
+ assets: images.assets,
962
+ caption: caption.caption,
963
+ captionCopy: caption.captionCopy,
964
+ count: caption.count,
965
+ dialog,
966
+ grid: images.grid,
967
+ heading,
968
+ hint: caption.hint,
969
+ more: destinations.more,
970
+ primary,
971
+ status,
972
+ tiles: [...images.assets.keys()]
973
+ };
974
+ }
975
+ // src/sync.ts
976
+ const primaryLabels = {
977
+ "copy-caption": "primaryCopy",
978
+ "open-composer": "primaryOpen",
979
+ "share-image": "primaryShareImage",
980
+ "share-link": "primaryShareLink",
981
+ "share-text": "primaryShareText"
982
+ };
983
+ function getSuggestedAsset(assets, destination) {
984
+ const { assetRole } = getShareDestination(destination);
985
+ return assets.find((asset) => asset.dataset.shareKitRole === assetRole) ?? assets.find((asset) => asset.dataset.shareKitRole === "landscape") ?? assets[0];
986
+ }
987
+ function syncCaptionView({ destination, parts, primaryAction, strings }) {
988
+ const { limit } = getShareDestination(destination);
989
+ const count = countCaption(parts.caption.value, destination);
990
+ const isOver = limit !== void 0 && count > limit;
991
+ const label = strings[`destination.${destination}`];
992
+ parts.count.textContent = limit === void 0 ? String(count) : `${String(count)} / ${String(limit)}`;
993
+ parts.count.toggleAttribute("data-share-kit-over", isOver);
994
+ parts.caption.setAttribute("aria-invalid", String(isOver));
995
+ parts.captionCopy.hidden = primaryAction === "copy-caption";
996
+ parts.primary.textContent = formatShareString(strings[primaryLabels[primaryAction]], { destination: label });
997
+ return {
998
+ isOver,
999
+ message: formatShareString(strings.captionOver, {
1000
+ count: String(count - (limit ?? 0)),
1001
+ destination: label
1002
+ })
1003
+ };
1004
+ }
1005
+ function syncDestinationView({ assets, destination, parts, strings, suggested }) {
1006
+ for (const radio of parts.dialog.querySelectorAll("[role=\"radio\"]")) {
1007
+ const isSelected = radio.dataset.shareKitDestination === destination;
1008
+ radio.setAttribute("aria-checked", String(isSelected));
1009
+ radio.tabIndex = isSelected ? 0 : -1;
1010
+ }
1011
+ const hintKey = `hint.${destination}`;
1012
+ parts.hint.textContent = isShareStringKey(hintKey) ? strings[hintKey] : "";
1013
+ parts.hint.hidden = parts.hint.textContent === "";
1014
+ for (const asset of assets) {
1015
+ const badge = asset.querySelector(".share-kit-badge");
1016
+ if (badge) badge.hidden = asset !== suggested;
1017
+ }
1018
+ parts.grid.append(...parts.tiles);
1019
+ if (suggested) parts.grid.prepend(suggested);
1020
+ }
1021
+ // src/types.ts
1022
+ const shareKitActionEventName = "share-kit:action";
1023
+ // src/element.ts
1024
+ const outcomeMessages = {
1025
+ error: "error",
1026
+ retry: "retry",
1027
+ saved: "saved",
1028
+ unsaved: "saveError"
1029
+ };
1030
+ let dialogCount = 0;
1031
+ function isKeyOf(record, key) {
1032
+ return Object.hasOwn(record, key);
1033
+ }
1034
+ const BaseElement = typeof HTMLElement === "undefined" ? Object : HTMLElement;
1035
+ var ShareKitElement = class extends BaseElement {
1036
+ icons = shareKitIcons;
1037
+ #abortController;
1038
+ #actions = {
1039
+ close: () => {
1040
+ this.#parts?.dialog.close();
1041
+ },
1042
+ copy: (button, tile) => {
1043
+ if (!tile) return;
1044
+ this.#track("copy", tile);
1045
+ this.#feedback?.copyImage(this.#files?.load(tile) ?? Promise.resolve(void 0), button);
1046
+ },
1047
+ "copy-caption": (button) => {
1048
+ this.#track("copy-caption");
1049
+ this.#copyCaption(button);
1050
+ },
1051
+ "copy-link": (button) => {
1052
+ this.#track("copy-link");
1053
+ this.#feedback?.copyText(this.#payload?.url ?? "", button);
1054
+ },
1055
+ destination: (button) => {
1056
+ const id = button.dataset.shareKitDestination;
1057
+ if (!id || !isShareDestinationId(id)) return;
1058
+ this.#selectDestination(id);
1059
+ this.#track("destination");
1060
+ },
1061
+ more: (button) => {
1062
+ this.#showMore(button);
1063
+ },
1064
+ primary: () => {
1065
+ this.#primaryActions[this.#getPrimaryAction()]();
1066
+ },
1067
+ qr: () => {
1068
+ this.#openQr();
1069
+ },
1070
+ reset: () => {
1071
+ this.#isCaptionEdited = false;
1072
+ this.#syncDestination();
1073
+ },
1074
+ save: (_button, tile) => {
1075
+ if (tile) this.#saveAsset(tile);
1076
+ },
1077
+ share: (_button, tile) => {
1078
+ if (tile) this.#shareAssets([tile]);
1079
+ }
1080
+ };
1081
+ #capabilities = /* @__PURE__ */ new Set();
1082
+ #destination = "any";
1083
+ #feedback;
1084
+ #files;
1085
+ #isCaptionEdited = false;
1086
+ #isOver = false;
1087
+ #parts;
1088
+ #payload;
1089
+ #primaryActions = {
1090
+ "copy-caption": () => {
1091
+ this.#track("copy-caption");
1092
+ this.#copyCaption();
1093
+ },
1094
+ "open-composer": () => {
1095
+ const url = this.#getComposerUrl();
1096
+ if (!url) return;
1097
+ this.#track("open-composer");
1098
+ this.#copyCaption();
1099
+ window.open(url, "_blank", "noopener");
1100
+ },
1101
+ "share-image": () => {
1102
+ const tile = this.#getSuggestedAsset();
1103
+ if (!tile) return;
1104
+ this.#copyCaption();
1105
+ this.#shareAssets([tile]);
1106
+ },
1107
+ "share-link": () => {
1108
+ this.#copyCaption();
1109
+ this.#shareData("share-link", { url: this.#getUrl() });
1110
+ },
1111
+ "share-text": () => {
1112
+ const text = this.#parts?.caption.value;
1113
+ if (text) this.#shareData("share-text", { text });
1114
+ }
1115
+ };
1116
+ #qr;
1117
+ #strings = shareKitStringDefaults;
1118
+ connectedCallback() {
1119
+ if (this.#abortController) return;
1120
+ const payload = readSharePayload(this);
1121
+ if (!payload) {
1122
+ this.#retryWhenParsed();
1123
+ return;
1124
+ }
1125
+ this.#abortController = new AbortController();
1126
+ this.#payload = payload;
1127
+ this.#strings = getShareStrings(payload.strings);
1128
+ this.#feedback = new ShareFeedback(() => this.#parts?.status, this.#strings);
1129
+ const { signal } = this.#abortController;
1130
+ this.#capabilities = new Set(getShareCapabilities(this.dataset.can));
1131
+ this.#files = new ShareAssetFiles({
1132
+ canShare: this.#capabilities.has("files"),
1133
+ getSource: (tile) => this.#parts?.assets.get(tile),
1134
+ signal
1135
+ });
1136
+ this.addEventListener("click", this.#handleClick, { signal });
1137
+ this.addEventListener("input", this.#handleInput, { signal });
1138
+ this.addEventListener("keydown", this.#handleKeydown, { signal });
1139
+ this.addEventListener("error", this.#handlePreviewError, {
1140
+ capture: true,
1141
+ signal
1142
+ });
1143
+ this.addEventListener("pointerover", ({ target }) => this.#files?.warm(target), { signal });
1144
+ window.addEventListener("hashchange", this.#handleHashChange, { signal });
1145
+ this.querySelector("[data-share-kit-trigger]")?.toggleAttribute("disabled", false);
1146
+ if (isOpenHash(payload.settings.openHash)) this.#open();
1147
+ }
1148
+ disconnectedCallback() {
1149
+ this.#parts?.dialog.remove();
1150
+ this.#parts = void 0;
1151
+ this.#qr = void 0;
1152
+ this.#abortController?.abort();
1153
+ this.#abortController = void 0;
1154
+ this.#feedback?.dispose();
1155
+ this.#feedback = void 0;
1156
+ this.#files?.dispose();
1157
+ this.#files = void 0;
1158
+ this.#destination = "any";
1159
+ this.#isCaptionEdited = false;
1160
+ this.#isOver = false;
1161
+ }
1162
+ async #copyCaption(button) {
1163
+ const caption = this.#parts?.caption;
1164
+ if (caption) await this.#feedback?.copyText(caption.value, button, caption);
1165
+ }
1166
+ #getAssets() {
1167
+ return (this.#parts?.tiles ?? []).filter((tile) => tile.dataset.shareKitState !== "failed");
1168
+ }
1169
+ #getComposerUrl() {
1170
+ const parts = this.#parts;
1171
+ if (!parts) return;
1172
+ const suggested = this.#getSuggestedAsset();
1173
+ const media = suggested ? parts.assets.get(suggested)?.src : void 0;
1174
+ return getShareDestination(this.#destination).getComposerUrl?.({
1175
+ media: media ? new URL(media, location.href).href : void 0,
1176
+ text: parts.caption.value,
1177
+ url: this.#getUrl()
1178
+ });
1179
+ }
1180
+ #getPrimaryAction() {
1181
+ return getPrimaryAction({
1182
+ canShareFiles: this.#capabilities.has("files") && this.#getSuggestedAsset() !== void 0,
1183
+ canShareText: this.#capabilities.has("link"),
1184
+ hasComposerUrl: this.#getComposerUrl() !== void 0,
1185
+ id: this.#destination,
1186
+ isHandheld: this.#capabilities.has("handheld")
1187
+ });
1188
+ }
1189
+ #getSuggestedAsset() {
1190
+ return getSuggestedAsset(this.#getAssets(), this.#destination);
1191
+ }
1192
+ #getUrl() {
1193
+ const payload = this.#payload;
1194
+ if (!payload) return "";
1195
+ return getDestinationUrl(payload.url, this.#destination, payload.settings.utmMedium);
1196
+ }
1197
+ #handleClick = (event) => {
1198
+ if (!(event.target instanceof Element)) return;
1199
+ if (event.target.closest("[data-share-kit-trigger]")) {
1200
+ this.#open();
1201
+ return;
1202
+ }
1203
+ const button = event.target.closest("[data-share-kit-action]");
1204
+ const action = button?.dataset.shareKitAction;
1205
+ if (!button || !action || !isKeyOf(this.#actions, action)) return;
1206
+ this.#actions[action](button, button.closest("[data-share-kit-asset]") ?? void 0);
1207
+ };
1208
+ #handleClose = () => {
1209
+ clearOpenHash(this.#payload?.settings.openHash);
1210
+ };
1211
+ #handleHashChange = () => {
1212
+ if (isOpenHash(this.#payload?.settings.openHash)) this.#open();
1213
+ };
1214
+ #handleInput = (event) => {
1215
+ if (event.target === this.#parts?.caption) this.#isCaptionEdited = true;
1216
+ this.#syncCaption();
1217
+ };
1218
+ #handleKeydown = (event) => {
1219
+ const move = radioKeys[event.key];
1220
+ if (!move || !(event.target instanceof HTMLElement) || event.target.role !== "radio") return;
1221
+ const radios = [...this.querySelectorAll("[role=\"radio\"]:not([hidden])")];
1222
+ const next = radios[move(radios.indexOf(event.target), radios.length)];
1223
+ const id = next?.dataset.shareKitDestination;
1224
+ if (!next || !id || !isShareDestinationId(id)) return;
1225
+ event.preventDefault();
1226
+ this.#selectDestination(id);
1227
+ next.focus();
1228
+ };
1229
+ #handlePreviewError = (event) => {
1230
+ if (!(event.target instanceof HTMLImageElement)) return;
1231
+ const tile = event.target.closest("[data-share-kit-asset]");
1232
+ if (!tile) return;
1233
+ tile.dataset.shareKitState = "failed";
1234
+ this.#syncDestination();
1235
+ };
1236
+ #open() {
1237
+ const parts = this.#parts ?? this.#render();
1238
+ if (!parts || parts.dialog.open) return;
1239
+ parts.dialog.showModal();
1240
+ parts.heading.focus();
1241
+ this.#track("open");
1242
+ this.#isOver = false;
1243
+ this.#syncCaption();
1244
+ }
1245
+ async #openQr() {
1246
+ this.#track("qr");
1247
+ try {
1248
+ await this.#qr?.open();
1249
+ } catch {
1250
+ this.#feedback?.announce(this.#strings.error);
1251
+ }
1252
+ }
1253
+ #prefetch() {
1254
+ if (!this.#capabilities.has("files") || !this.#capabilities.has("handheld")) return;
1255
+ const tile = this.#getSuggestedAsset();
1256
+ if (tile) this.#files?.load(tile);
1257
+ }
1258
+ #render() {
1259
+ const payload = this.#payload;
1260
+ const signal = this.#abortController?.signal;
1261
+ if (!payload || !signal) return;
1262
+ const { main, more } = getDestinationLists(payload.settings);
1263
+ dialogCount += 1;
1264
+ const id = `share-kit-${String(dialogCount)}`;
1265
+ const parts = renderShareKit({
1266
+ capabilities: this.#capabilities,
1267
+ destinations: main,
1268
+ destinationsMore: more,
1269
+ icons: this.icons,
1270
+ id,
1271
+ payload,
1272
+ strings: this.#strings
1273
+ });
1274
+ this.#qr = createShareQr({
1275
+ capabilities: this.#capabilities,
1276
+ closeIcon: this.icons.close,
1277
+ id: `${id}-qr`,
1278
+ payload,
1279
+ signal,
1280
+ strings: this.#strings
1281
+ });
1282
+ if (this.#qr) parts.dialog.append(this.#qr.dialog);
1283
+ parts.dialog.addEventListener("close", this.#handleClose, { signal });
1284
+ polyfillLightDismiss(parts.dialog, signal);
1285
+ this.append(parts.dialog);
1286
+ this.#parts = parts;
1287
+ this.#destination = main[0] ?? "any";
1288
+ this.#syncDestination();
1289
+ return parts;
1290
+ }
1291
+ #report(outcome) {
1292
+ if (outcome && isKeyOf(outcomeMessages, outcome)) this.#feedback?.announce(this.#strings[outcomeMessages[outcome]]);
1293
+ }
1294
+ #retryWhenParsed() {
1295
+ if (document.readyState !== "loading") return;
1296
+ document.addEventListener("DOMContentLoaded", () => {
1297
+ if (this.isConnected) this.connectedCallback();
1298
+ }, { once: true });
1299
+ }
1300
+ async #saveAsset(tile) {
1301
+ this.#track("save", tile);
1302
+ this.#report(await this.#files?.save(tile));
1303
+ }
1304
+ #selectDestination(id) {
1305
+ const previousUrl = this.#getUrl();
1306
+ const caption = this.#parts?.caption;
1307
+ this.#destination = id;
1308
+ if (caption && this.#isCaptionEdited) {
1309
+ const url = this.#getUrl();
1310
+ caption.value = caption.value.replaceAll(previousUrl, () => url);
1311
+ }
1312
+ this.#syncDestination();
1313
+ }
1314
+ async #shareAssets(tiles) {
1315
+ const [first] = tiles;
1316
+ if (!first) return;
1317
+ this.#track("share", first);
1318
+ this.#report(await this.#files?.share(tiles));
1319
+ }
1320
+ async #shareData(action, data) {
1321
+ this.#track(action);
1322
+ try {
1323
+ await navigator.share(data);
1324
+ } catch (error) {
1325
+ if (!isDomError(error, "AbortError")) this.#feedback?.announce(this.#strings.error);
1326
+ }
1327
+ }
1328
+ #showMore(button) {
1329
+ const hidden = [...this.querySelectorAll("[role=\"radio\"][hidden]")];
1330
+ for (const radio of hidden) radio.hidden = false;
1331
+ button.hidden = true;
1332
+ hidden[0]?.focus();
1333
+ }
1334
+ #syncCaption() {
1335
+ const parts = this.#parts;
1336
+ if (!parts) return;
1337
+ const { isOver, message } = syncCaptionView({
1338
+ destination: this.#destination,
1339
+ parts,
1340
+ primaryAction: this.#getPrimaryAction(),
1341
+ strings: this.#strings
1342
+ });
1343
+ if (isOver && !this.#isOver && parts.dialog.open) this.#feedback?.announce(message);
1344
+ this.#isOver = isOver;
1345
+ }
1346
+ #syncDestination() {
1347
+ const parts = this.#parts;
1348
+ const payload = this.#payload;
1349
+ if (!parts || !payload) return;
1350
+ syncDestinationView({
1351
+ assets: this.#getAssets(),
1352
+ destination: this.#destination,
1353
+ parts,
1354
+ strings: this.#strings,
1355
+ suggested: this.#getSuggestedAsset()
1356
+ });
1357
+ if (!this.#isCaptionEdited) parts.caption.value = fitCaption({
1358
+ description: payload.description,
1359
+ title: payload.title,
1360
+ url: this.#getUrl()
1361
+ }, this.#destination, payload.locale).text;
1362
+ this.#syncCaption();
1363
+ this.#prefetch();
1364
+ }
1365
+ #track(action, tile) {
1366
+ const detail = {
1367
+ action,
1368
+ destination: this.#destination
1369
+ };
1370
+ if (tile?.dataset.shareKitAsset) detail.asset = tile.dataset.shareKitAsset;
1371
+ this.dispatchEvent(new CustomEvent(shareKitActionEventName, {
1372
+ bubbles: true,
1373
+ composed: true,
1374
+ detail
1375
+ }));
1376
+ }
1377
+ };
1378
+ // src/define.ts
1379
+ const tagName = "share-kit";
1380
+ function defineShareKit({ icons } = {}) {
1381
+ if (customElements.get(tagName)) return;
1382
+ const resolvedIcons = {
1383
+ ...shareKitIcons,
1384
+ ...icons
1385
+ };
1386
+ customElements.define(tagName, class extends ShareKitElement {
1387
+ icons = resolvedIcons;
1388
+ });
1389
+ }
1390
+ export { defineShareKit, serializeShareKitPayload, shareKitActionEventName, shareKitStringDefaults };
1391
+
1392
+ //# sourceMappingURL=index.mjs.map