@xsynaptic/share-kit 0.2.1 → 0.4.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 CHANGED
@@ -1,9 +1,99 @@
1
+ // src/count.ts
2
+ const urlPattern = /https?:\/\/[\w!#$%&'()*+,./:;=?@~-]+/giu;
3
+ const xLinkPattern = /https?:\/\/[\w!#$%&'()*+,./:;=?@~-]+|(?<![\w#./@-])(?:[\da-z][\da-z-]*\.)+(?:[a-z]{2}|com|org|net|edu|gov|info|biz|app|dev|xyz|site|online|blog|news|shop|store|page|tech|art|link|live|social|club|world|asia)(?![\w-])(?:\/[\w!#$%&'()*+,./:;=?@~-]*)?/giu;
4
+ const urlTrailingPunctuation = /[!'),.:;?]+$/u;
5
+ const graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
6
+ const utf8Encoder = new TextEncoder();
7
+ const latinCombiningMarkRanges = [
8
+ [768, 879],
9
+ [6832, 6911],
10
+ [7616, 7679],
11
+ [8400, 8447],
12
+ [65056, 65071]
13
+ ];
14
+ function getEmojiPattern() {
15
+ try {
16
+ return new RegExp(String.raw`^\p{RGI_Emoji}$`, "v");
17
+ } catch {
18
+ return;
19
+ }
20
+ }
21
+ const emojiPattern = getEmojiPattern();
22
+ function getGraphemes(text) {
23
+ return Array.from(graphemeSegmenter.segment(text), ({ segment }) => segment);
24
+ }
25
+ function isLightCodePoint(codePoint) {
26
+ return codePoint <= 4351 || codePoint >= 8192 && codePoint <= 8205 || codePoint >= 8208 && codePoint <= 8223 || codePoint >= 8242 && codePoint <= 8247;
27
+ }
28
+ function shareKitCountWeighted(text) {
29
+ const graphemes = getGraphemes(text.normalize("NFC"));
30
+ let total = 0;
31
+ for (const grapheme of graphemes) {
32
+ if (emojiPattern?.test(grapheme)) {
33
+ total += 2;
34
+ continue;
35
+ }
36
+ for (const character of grapheme) total += isLightCodePoint(character.codePointAt(0) ?? 0) ? 1 : 2;
37
+ }
38
+ return total;
39
+ }
40
+ function isLatinCombiningMark(codePoint) {
41
+ return latinCombiningMarkRanges.some(([start, end]) => codePoint >= start && codePoint <= end);
42
+ }
43
+ function shareKitCountStringz(text) {
44
+ let total = 0;
45
+ for (const grapheme of getGraphemes(text)) {
46
+ if (emojiPattern?.test(grapheme)) {
47
+ total += 1;
48
+ continue;
49
+ }
50
+ for (const character of grapheme) if (!isLatinCombiningMark(character.codePointAt(0) ?? 0)) total += 1;
51
+ }
52
+ return total;
53
+ }
54
+ function shareKitShortenedLinkCost(url) {
55
+ if (!URL.canParse(url)) return getGraphemes(url).length;
56
+ const { hash, host, pathname, search } = new URL(url);
57
+ const path = `${pathname === "/" ? "" : pathname}${search}${hash}`;
58
+ return host.length + Math.min(path.length, 16);
59
+ }
60
+ function shareKitCountLength(text) {
61
+ return text.length;
62
+ }
63
+ function shareKitCountGraphemes(text) {
64
+ return getGraphemes(text).length;
65
+ }
66
+ function shareKitCountUtf8(text) {
67
+ return utf8Encoder.encode(text).length;
68
+ }
69
+ function splitLinks(text, pattern) {
70
+ const links = [];
71
+ return {
72
+ links,
73
+ rest: text.replaceAll(pattern, (match) => {
74
+ const trailing = urlTrailingPunctuation.exec(match)?.[0] ?? "";
75
+ links.push(match.slice(0, match.length - trailing.length));
76
+ return trailing;
77
+ })
78
+ };
79
+ }
80
+ function withLinkCost(count, cost, pattern) {
81
+ return (text) => {
82
+ const { links, rest } = splitLinks(text, pattern);
83
+ let total = count(rest);
84
+ for (const link of links) total += typeof cost === "number" ? cost : cost(link);
85
+ return total;
86
+ };
87
+ }
88
+ function shareKitWithLinkCost(count, cost) {
89
+ return withLinkCost(count, cost, urlPattern);
90
+ }
1
91
  // src/actions.ts
2
92
  const shareCapabilities = [
3
93
  "files",
4
94
  "link",
5
95
  "copy-image",
6
- "handheld"
96
+ "mobile"
7
97
  ];
8
98
  const pngType = "image/png";
9
99
  function canShareFiles() {
@@ -17,19 +107,32 @@ function canCopyImage() {
17
107
  const capabilityTests = {
18
108
  "copy-image": canCopyImage,
19
109
  files: canShareFiles,
20
- handheld: () => matchMedia("(pointer: coarse)").matches,
21
- link: () => "share" in navigator
110
+ link: () => "share" in navigator,
111
+ mobile: () => matchMedia("(pointer: coarse)").matches
22
112
  };
23
113
  function isShareCapability(value) {
24
114
  return shareCapabilities.some((capability) => capability === value);
25
115
  }
26
116
  function getShareCapabilities(preset) {
27
- if (preset !== void 0) return preset.split(" ").filter(isShareCapability);
117
+ if (preset !== void 0) {
118
+ const tokens = preset.split(/\s+/u).filter(Boolean);
119
+ const unknown = tokens.filter((token) => !isShareCapability(token));
120
+ if (unknown.length > 0) console.warn(`share-kit: unknown data-can tokens ignored: ${unknown.join(", ")}`);
121
+ return tokens.filter(isShareCapability);
122
+ }
28
123
  return shareCapabilities.filter((capability) => capabilityTests[capability]());
29
124
  }
30
125
  function isDomError(error, name) {
31
126
  return error instanceof DOMException && error.name === name;
32
127
  }
128
+ async function shareData(data) {
129
+ try {
130
+ await navigator.share(data);
131
+ return "shared";
132
+ } catch (error) {
133
+ return isDomError(error, "AbortError") ? "dismissed" : "error";
134
+ }
135
+ }
33
136
  async function fetchFile({ filename, src, type }, signal) {
34
137
  const response = await fetch(src, {
35
138
  cache: "no-cache",
@@ -70,6 +173,14 @@ function clearOpenHash(openHash) {
70
173
  if (!isOpenHash(openHash)) return;
71
174
  history.replaceState(history.state, "", `${location.pathname}${location.search}`);
72
175
  }
176
+ function openComposer(href) {
177
+ const { protocol } = new URL(href, location.href);
178
+ if (protocol !== "http:" && protocol !== "https:") {
179
+ location.assign(href);
180
+ return;
181
+ }
182
+ window.open(href, "_blank", "noopener");
183
+ }
73
184
  // src/assets.ts
74
185
  function isFile(file) {
75
186
  return file !== void 0;
@@ -138,234 +249,6 @@ var ShareAssetFiles = class {
138
249
  }
139
250
  }
140
251
  };
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 grapheme of getGraphemes(text)) {
186
- if (emojiPattern?.test(grapheme)) {
187
- total += 1;
188
- continue;
189
- }
190
- for (const character of grapheme) if (!isLatinCombiningMark(character.codePointAt(0) ?? 0)) total += 1;
191
- }
192
- return total;
193
- }
194
- function getShortenedUrlLength(url) {
195
- if (!URL.canParse(url)) return getGraphemes(url).length;
196
- const { hash, host, pathname, search } = new URL(url);
197
- const path = `${pathname === "/" ? "" : pathname}${search}${hash}`;
198
- return host.length + Math.min(path.length, 16);
199
- }
200
- const textCounters = {
201
- graphemes: (text) => getGraphemes(text).length,
202
- length: (text) => text.length,
203
- stringz: getStringzLength,
204
- utf8: (text) => utf8Encoder.encode(text).length,
205
- weighted: getWeightedLength
206
- };
207
- function splitLinks(text) {
208
- const links = [];
209
- return {
210
- links,
211
- rest: text.replaceAll(urlPattern, (match) => {
212
- const trailing = urlTrailingPunctuation.exec(match)?.[0] ?? "";
213
- links.push(match.slice(0, match.length - trailing.length));
214
- return trailing;
215
- })
216
- };
217
- }
218
- function countText(text, { counter, urlCost }) {
219
- const count = textCounters[counter];
220
- if (urlCost === "actual") return count(text);
221
- const { links, rest } = splitLinks(text);
222
- let total = count(rest);
223
- for (const link of links) total += urlCost === "fixed" ? urlFixedCost : getShortenedUrlLength(link);
224
- return total;
225
- }
226
- // src/destinations.ts
227
- function withQuery(base, parameters) {
228
- const url = new URL(base);
229
- for (const [name, value] of Object.entries(parameters)) if (value) url.searchParams.set(name, value);
230
- return url.href;
231
- }
232
- const shareDestinations = {
233
- bluesky: {
234
- assetRole: "portrait",
235
- counter: "graphemes",
236
- getComposerUrl: ({ text }) => withQuery("https://bsky.app/intent/compose", { text }),
237
- isImagePost: true,
238
- limit: 300,
239
- shape: "full",
240
- urlCost: "shortened"
241
- },
242
- facebook: {
243
- assetRole: "landscape",
244
- counter: "length",
245
- getComposerUrl: ({ url }) => withQuery("https://www.facebook.com/sharer/sharer.php", { u: url }),
246
- isImagePost: false,
247
- isLinkOnly: true,
248
- limit: 63206,
249
- shape: "full",
250
- urlCost: "actual"
251
- },
252
- instagram: {
253
- assetRole: "portrait",
254
- counter: "length",
255
- isImagePost: true,
256
- limit: 2200,
257
- shape: "text",
258
- urlCost: "actual"
259
- },
260
- "instagram-story": {
261
- assetRole: "story",
262
- counter: "length",
263
- isImagePost: true,
264
- shape: "url",
265
- urlCost: "actual"
266
- },
267
- linkedin: {
268
- assetRole: "landscape",
269
- counter: "length",
270
- getComposerUrl: ({ url }) => withQuery("https://www.linkedin.com/sharing/share-offsite/", { url }),
271
- isImagePost: false,
272
- isLinkOnly: true,
273
- limit: 3e3,
274
- shape: "full",
275
- urlCost: "actual"
276
- },
277
- mastodon: {
278
- assetRole: "portrait",
279
- counter: "stringz",
280
- isImagePost: true,
281
- limit: 500,
282
- shape: "full",
283
- urlCost: "fixed"
284
- },
285
- messages: {
286
- assetRole: "landscape",
287
- counter: "length",
288
- isImagePost: false,
289
- shape: "full",
290
- urlCost: "actual"
291
- },
292
- pinterest: {
293
- assetRole: "portrait",
294
- counter: "length",
295
- getComposerUrl: ({ media, text, url }) => withQuery("https://www.pinterest.com/pin/create/button/", {
296
- description: text,
297
- media,
298
- url
299
- }),
300
- isImagePost: false,
301
- limit: 800,
302
- shape: "text",
303
- urlCost: "actual"
304
- },
305
- reddit: {
306
- assetRole: "landscape",
307
- counter: "length",
308
- getComposerUrl: ({ text, url }) => withQuery("https://www.reddit.com/submit", {
309
- title: text,
310
- url
311
- }),
312
- isImagePost: false,
313
- limit: 300,
314
- shape: "title",
315
- urlCost: "actual"
316
- },
317
- ["any"]: {
318
- assetRole: "landscape",
319
- counter: "length",
320
- isImagePost: false,
321
- shape: "full",
322
- urlCost: "actual"
323
- },
324
- threads: {
325
- assetRole: "portrait",
326
- counter: "utf8",
327
- getComposerUrl: ({ text }) => withQuery("https://www.threads.com/intent/post", { text }),
328
- isImagePost: true,
329
- limit: 500,
330
- shape: "full",
331
- urlCost: "actual"
332
- },
333
- x: {
334
- assetRole: "landscape",
335
- counter: "weighted",
336
- getComposerUrl: ({ text }) => withQuery("https://x.com/intent/tweet", { text }),
337
- isImagePost: false,
338
- limit: 280,
339
- shape: "full",
340
- urlCost: "fixed"
341
- }
342
- };
343
- function isShareDestinationId(id) {
344
- return Object.hasOwn(shareDestinations, id);
345
- }
346
- function getShareDestination(id) {
347
- return shareDestinations[id];
348
- }
349
- function getDestinationUrl(url, id, utmMedium) {
350
- if (!utmMedium || id === "any" || !URL.canParse(url)) return url;
351
- return withQuery(url, {
352
- utm_medium: utmMedium,
353
- utm_source: id
354
- });
355
- }
356
- function getHandheldAction({ canShareFiles, canShareText, id }) {
357
- const { isImagePost, isLinkOnly } = getShareDestination(id);
358
- if (isImagePost && canShareFiles) return "share-image";
359
- if (isLinkOnly === true && canShareText) return "share-link";
360
- if (id === "any" && canShareText) return "share-text";
361
- }
362
- function getPrimaryAction(input) {
363
- const handheldAction = input.isHandheld ? getHandheldAction(input) : void 0;
364
- if (handheldAction) return handheldAction;
365
- if (input.hasComposerUrl) return "open-composer";
366
- if (input.id === "messages" && input.canShareText) return "share-text";
367
- return "copy-caption";
368
- }
369
252
  // src/caption.ts
370
253
  const separator = "\n\n";
371
254
  const ellipsis = "…";
@@ -442,11 +325,7 @@ function fitParts(input) {
442
325
  const bare = join([title, link]);
443
326
  return canFit(bare) ? bare : join([fitTitle(input), link]);
444
327
  }
445
- function countCaption(text, id) {
446
- return countText(text, getShareDestination(id));
447
- }
448
- function fitCaption({ description, title, url }, id, locale = "en") {
449
- const { limit, shape } = getShareDestination(id);
328
+ function fitCaption({ description, title, url }, { count, limit, shape }, locale = "en") {
450
329
  const link = shape === "full" ? url : void 0;
451
330
  const body = shape === "title" ? void 0 : description?.trim() || void 0;
452
331
  const whole = shape === "url" ? url : join([
@@ -454,7 +333,7 @@ function fitCaption({ description, title, url }, id, locale = "en") {
454
333
  body,
455
334
  link
456
335
  ]);
457
- const canFit = (text) => limit === void 0 || countCaption(text, id) <= limit;
336
+ const canFit = (text) => limit === void 0 || count(text) <= limit;
458
337
  const text = canFit(whole) ? whole : fitParts({
459
338
  body,
460
339
  canFit,
@@ -463,12 +342,263 @@ function fitCaption({ description, title, url }, id, locale = "en") {
463
342
  title
464
343
  });
465
344
  return {
466
- count: countCaption(text, id),
345
+ count: count(text),
467
346
  isTruncated: text !== whole,
468
347
  limit,
469
348
  text
470
349
  };
471
350
  }
351
+ // src/formats.ts
352
+ const shareKitLandscapeFormat = {
353
+ height: 630,
354
+ id: "landscape",
355
+ width: 1200
356
+ };
357
+ const shareKitPortraitFormat = {
358
+ height: 1350,
359
+ id: "portrait",
360
+ width: 1080
361
+ };
362
+ const shareKitStoryFormat = {
363
+ height: 1920,
364
+ id: "story",
365
+ width: 1080
366
+ };
367
+ const shareKitPinFormat = {
368
+ height: 1500,
369
+ id: "pin",
370
+ width: 1e3
371
+ };
372
+ const fitTolerance = .02;
373
+ function getRatioDistance(image, format) {
374
+ return Math.abs(Math.log(image.width / image.height / (format.width / format.height)));
375
+ }
376
+ function isFormatFit(image, format) {
377
+ return getRatioDistance(image, format) <= fitTolerance;
378
+ }
379
+ function getSuggestedImage(images, formats) {
380
+ const candidates = images.filter((image) => image.isSuggestable !== false);
381
+ for (const format of formats) {
382
+ const match = candidates.find((image) => isFormatFit(image, format));
383
+ if (match) return match;
384
+ }
385
+ let nearest;
386
+ let nearestDistance = 1e400;
387
+ for (const image of candidates) {
388
+ const distance = getRatioDistance(image, formats[0]);
389
+ if (!(distance < nearestDistance)) continue;
390
+ nearest = image;
391
+ nearestDistance = distance;
392
+ }
393
+ return nearest;
394
+ }
395
+ function getShareKitImageFormats(destinations) {
396
+ const formats = /* @__PURE__ */ new Map();
397
+ for (const { images } of destinations) if (!formats.has(images[0].id)) formats.set(images[0].id, images[0]);
398
+ return [...formats.values()];
399
+ }
400
+ // src/destinations.ts
401
+ function defineShareKitDestination(destination) {
402
+ return destination;
403
+ }
404
+ function withQuery(base, parameters) {
405
+ const url = new URL(base);
406
+ for (const [name, value] of Object.entries(parameters)) if (value) url.searchParams.set(name, value);
407
+ return url.href;
408
+ }
409
+ const fixedLinkCost = 23;
410
+ const shareKitAnywhere = {
411
+ actions: {
412
+ desktop: [],
413
+ mobile: ["share-text"]
414
+ },
415
+ count: shareKitCountLength,
416
+ id: "any",
417
+ images: [shareKitLandscapeFormat],
418
+ label: "Anywhere",
419
+ shape: "full",
420
+ utmSource: false
421
+ };
422
+ const shareKitBluesky = {
423
+ actions: {
424
+ desktop: ["open-composer"],
425
+ mobile: ["share-image", "open-composer"]
426
+ },
427
+ composer: ({ text }) => withQuery("https://bsky.app/intent/compose", { text }),
428
+ count: shareKitWithLinkCost(shareKitCountGraphemes, shareKitShortenedLinkCost),
429
+ id: "bluesky",
430
+ images: [shareKitPortraitFormat],
431
+ label: "Bluesky",
432
+ limit: 300,
433
+ shape: "full"
434
+ };
435
+ const shareKitFacebook = {
436
+ actions: {
437
+ desktop: ["open-composer"],
438
+ mobile: ["share-link", "open-composer"]
439
+ },
440
+ composer: ({ url }) => withQuery("https://www.facebook.com/sharer/sharer.php", { u: url }),
441
+ count: shareKitCountLength,
442
+ hint: "Facebook only takes the link. Your caption is copied, so paste it into your post.",
443
+ id: "facebook",
444
+ images: [shareKitLandscapeFormat, shareKitPortraitFormat],
445
+ label: "Facebook",
446
+ limit: 63206,
447
+ shape: "full"
448
+ };
449
+ const shareKitInstagram = {
450
+ actions: {
451
+ desktop: [],
452
+ mobile: ["share-image"]
453
+ },
454
+ count: shareKitCountLength,
455
+ hint: "Links in Instagram captions aren't clickable. Point people to the link in your bio.",
456
+ id: "instagram",
457
+ images: [shareKitPortraitFormat],
458
+ label: "Instagram",
459
+ limit: 2200,
460
+ shape: "text"
461
+ };
462
+ const shareKitInstagramStory = {
463
+ actions: {
464
+ desktop: [],
465
+ mobile: ["share-image"]
466
+ },
467
+ count: shareKitCountLength,
468
+ hint: "Add the link to your Story with a link sticker.",
469
+ id: "instagram-story",
470
+ images: [shareKitStoryFormat, shareKitPortraitFormat],
471
+ label: "Story",
472
+ shape: "url"
473
+ };
474
+ const shareKitLinkedin = {
475
+ actions: {
476
+ desktop: ["open-composer"],
477
+ mobile: ["share-link", "open-composer"]
478
+ },
479
+ composer: ({ url }) => withQuery("https://www.linkedin.com/sharing/share-offsite/", { url }),
480
+ count: shareKitCountLength,
481
+ hint: "LinkedIn only takes the link. Your caption is copied, so paste it into your post.",
482
+ id: "linkedin",
483
+ images: [shareKitLandscapeFormat],
484
+ label: "LinkedIn",
485
+ limit: 3e3,
486
+ shape: "full"
487
+ };
488
+ const shareKitLine = {
489
+ actions: {
490
+ desktop: ["open-composer"],
491
+ mobile: ["open-composer"]
492
+ },
493
+ composer: ({ device, text, url }) => device === "mobile" ? `https://line.me/R/share?text=${encodeURIComponent(text)}` : `https://social-plugins.line.me/lineit/share?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text)}`,
494
+ count: shareKitCountLength,
495
+ id: "line",
496
+ images: [shareKitLandscapeFormat],
497
+ label: "LINE",
498
+ shape: "full"
499
+ };
500
+ const shareKitMastodon = {
501
+ actions: {
502
+ desktop: [],
503
+ mobile: ["share-image"]
504
+ },
505
+ count: shareKitWithLinkCost(shareKitCountStringz, fixedLinkCost),
506
+ id: "mastodon",
507
+ images: [shareKitPortraitFormat],
508
+ label: "Mastodon",
509
+ limit: 500,
510
+ shape: "full"
511
+ };
512
+ const shareKitMessages = {
513
+ actions: {
514
+ desktop: ["share-text"],
515
+ mobile: ["share-text"]
516
+ },
517
+ count: shareKitCountLength,
518
+ id: "messages",
519
+ images: [shareKitLandscapeFormat],
520
+ label: "Messages",
521
+ shape: "full"
522
+ };
523
+ const shareKitPinterest = {
524
+ actions: {
525
+ desktop: ["open-composer"],
526
+ mobile: ["open-composer"]
527
+ },
528
+ composer: ({ media, text, url }) => withQuery("https://www.pinterest.com/pin/create/button/", {
529
+ description: text,
530
+ media,
531
+ url
532
+ }),
533
+ count: shareKitCountLength,
534
+ id: "pinterest",
535
+ images: [shareKitPinFormat, shareKitPortraitFormat],
536
+ label: "Pinterest",
537
+ limit: 800,
538
+ shape: "text"
539
+ };
540
+ const shareKitReddit = {
541
+ actions: {
542
+ desktop: ["open-composer"],
543
+ mobile: ["open-composer"]
544
+ },
545
+ composer: ({ text, url }) => withQuery("https://www.reddit.com/submit", {
546
+ title: text,
547
+ url
548
+ }),
549
+ count: shareKitCountLength,
550
+ hint: "Reddit takes a title and the link.",
551
+ id: "reddit",
552
+ images: [shareKitLandscapeFormat],
553
+ label: "Reddit",
554
+ limit: 300,
555
+ shape: "title"
556
+ };
557
+ const shareKitThreads = {
558
+ actions: {
559
+ desktop: ["open-composer"],
560
+ mobile: ["share-image", "open-composer"]
561
+ },
562
+ composer: ({ text }) => withQuery("https://www.threads.com/intent/post", { text }),
563
+ count: shareKitCountUtf8,
564
+ id: "threads",
565
+ images: [shareKitPortraitFormat],
566
+ label: "Threads",
567
+ limit: 500,
568
+ shape: "full"
569
+ };
570
+ const shareKitX = {
571
+ actions: {
572
+ desktop: ["open-composer"],
573
+ mobile: ["open-composer"]
574
+ },
575
+ composer: ({ text }) => withQuery("https://x.com/intent/tweet", { text }),
576
+ count: withLinkCost(shareKitCountWeighted, fixedLinkCost, xLinkPattern),
577
+ id: "x",
578
+ images: [shareKitLandscapeFormat, shareKitPortraitFormat],
579
+ label: "X",
580
+ limit: 280,
581
+ shape: "full"
582
+ };
583
+ function getDestinationUrl(url, { id, utmSource = id }, utmMedium) {
584
+ if (!utmMedium || utmSource === false || !URL.canParse(url)) return url;
585
+ return withQuery(url, {
586
+ utm_medium: utmMedium,
587
+ utm_source: utmSource
588
+ });
589
+ }
590
+ function canRun(action, input) {
591
+ switch (action) {
592
+ case "copy-caption": return true;
593
+ case "open-composer": return Boolean(input.composerUrl);
594
+ case "share-image": return input.canShareFiles && input.hasSuggestedImage;
595
+ case "share-link":
596
+ case "share-text": return input.canShareText;
597
+ }
598
+ }
599
+ function getPrimaryAction(actions, input) {
600
+ return actions.find((action) => canRun(action, input)) ?? "copy-caption";
601
+ }
472
602
  // src/dom.ts
473
603
  function createElement(tag, attributes = {}, children = []) {
474
604
  const element = document.createElement(tag);
@@ -480,18 +610,31 @@ function joinClasses(...classes) {
480
610
  return classes.filter(Boolean).join(" ");
481
611
  }
482
612
  const svgNamespace = "http://www.w3.org/2000/svg";
483
- function createIcon(path, size) {
613
+ const iconSize = 24;
614
+ function createIcon(path) {
484
615
  const svg = document.createElementNS(svgNamespace, "svg");
485
616
  const shape = document.createElementNS(svgNamespace, "path");
486
617
  svg.setAttribute("aria-hidden", "true");
487
- svg.setAttribute("height", String(size));
618
+ svg.setAttribute("height", String(iconSize));
488
619
  svg.setAttribute("viewBox", "0 0 24 24");
489
- svg.setAttribute("width", String(size));
620
+ svg.setAttribute("width", String(iconSize));
490
621
  shape.setAttribute("d", path);
491
622
  shape.setAttribute("fill", "currentColor");
492
623
  svg.append(shape);
493
624
  return svg;
494
625
  }
626
+ function createIconSlot(name, path, fallback) {
627
+ return createElement("span", {
628
+ class: "share-kit-icon",
629
+ "data-share-kit-icon": name
630
+ }, [path ? createIcon(path) : fallback]);
631
+ }
632
+ function patchIcons(root, icons) {
633
+ for (const slot of root.querySelectorAll("[data-share-kit-icon]")) {
634
+ const path = slot.dataset.shareKitIcon ? icons[slot.dataset.shareKitIcon] : void 0;
635
+ if (path && !slot.querySelector("svg")) slot.replaceChildren(createIcon(path));
636
+ }
637
+ }
495
638
  function isOnBackdrop(dialog, event) {
496
639
  if (event.target !== dialog) return false;
497
640
  const rect = dialog.getBoundingClientRect();
@@ -569,61 +712,53 @@ var ShareFeedback = class {
569
712
  }, flashDurationMs);
570
713
  }
571
714
  };
572
- // src/strings.ts
573
- const shareKitStringDefaults = {
574
- assetCopy: "Copy",
575
- assetSave: "Save",
576
- assetShare: "Share",
577
- captionCopy: "Copy caption",
578
- captionOver: "{count} over the limit for {destination}",
579
- captionReset: "Reset",
580
- captionTitle: "Caption",
581
- close: "Close",
582
- copied: "Copied",
583
- copyManual: "Couldn't copy. The caption is selected, so you can copy it yourself.",
584
- "destination.any": "Anywhere",
585
- "destination.bluesky": "Bluesky",
586
- "destination.facebook": "Facebook",
587
- "destination.instagram": "Instagram",
588
- "destination.instagram-story": "Story",
589
- "destination.linkedin": "LinkedIn",
590
- "destination.mastodon": "Mastodon",
591
- "destination.messages": "Messages",
592
- "destination.pinterest": "Pinterest",
593
- "destination.reddit": "Reddit",
594
- "destination.threads": "Threads",
595
- "destination.x": "X",
596
- destinationsMore: "More",
597
- destinationsTitle: "Post to",
598
- error: "Something went wrong. Try saving instead.",
599
- "hint.facebook": "Facebook only takes the link. Your caption is copied, so paste it into your post.",
600
- "hint.instagram": "Links in Instagram captions aren't clickable. Point people to the link in your bio.",
601
- "hint.instagram-story": "Add the link to your Story with a link sticker.",
602
- "hint.linkedin": "LinkedIn only takes the link. Your caption is copied, so paste it into your post.",
603
- "hint.reddit": "Reddit takes a title and the link.",
604
- imagesTitle: "Images",
605
- linkCopy: "Copy link",
606
- linkTitle: "Link",
607
- primaryCopy: "Copy caption",
608
- primaryOpen: "Open {destination}",
609
- primaryShareImage: "Share image",
610
- primaryShareLink: "Share link",
611
- primaryShareText: "Share",
612
- qrAlt: "QR code for this page",
613
- qrTitle: "Scan to continue on your phone",
614
- qrToggle: "Continue on your phone",
615
- retry: "Ready. Tap again to share.",
616
- saved: "Saved",
617
- saveError: "Couldn't save. Try again.",
618
- suggested: "Suggested",
619
- title: "Share this page"
715
+ // src/icons.ts
716
+ const shareKitInterfaceIconNames = [
717
+ "close",
718
+ "more",
719
+ "qr"
720
+ ];
721
+ const shareKitInterfaceIcons = {
722
+ 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",
723
+ 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",
724
+ 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",
725
+ 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",
726
+ 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"
727
+ };
728
+ var ShareIconSource = class {
729
+ get icons() {
730
+ return this.#icons;
731
+ }
732
+ get isLoading() {
733
+ return !this.#isSettled;
734
+ }
735
+ #icons = {};
736
+ #isSettled = false;
737
+ #loader;
738
+ #pending;
739
+ constructor(option) {
740
+ if (typeof option === "function") {
741
+ this.#loader = option;
742
+ return;
743
+ }
744
+ this.#icons = option;
745
+ this.#isSettled = true;
746
+ }
747
+ load() {
748
+ if (!this.#pending) this.#pending = this.#load();
749
+ return this.#pending;
750
+ }
751
+ async #load() {
752
+ if (!this.#loader) return this.#icons;
753
+ try {
754
+ this.#icons = await this.#loader();
755
+ } catch (error) {
756
+ console.warn("share-kit: the icons loader failed, so the dialog keeps its text labels", error);
757
+ }
758
+ this.#isSettled = true;
759
+ return this.#icons;
760
+ }
620
761
  };
621
- function isShareStringKey(key) {
622
- return Object.hasOwn(shareKitStringDefaults, key);
623
- }
624
- function formatShareString(template, values) {
625
- return template.replaceAll(/\{(\w+)\}/gu, (match, name) => values[name] ?? match);
626
- }
627
762
  // src/payload.ts
628
763
  function isPayload(value) {
629
764
  if (typeof value !== "object" || value === null) return false;
@@ -643,25 +778,42 @@ function readSharePayload(host) {
643
778
  return;
644
779
  }
645
780
  }
646
- function getShareStrings(overrides = {}) {
647
- const strings = { ...shareKitStringDefaults };
648
- for (const [key, value] of Object.entries(overrides)) if (value !== void 0 && isShareStringKey(key)) strings[key] = value;
649
- return strings;
650
- }
651
781
  function getIds(value) {
652
782
  if (!Array.isArray(value)) return [];
653
- return [...new Set(value)].filter((id) => typeof id === "string" && isShareDestinationId(id));
654
- }
655
- function getDestinationLists({ destinations, destinationsMore }) {
656
- const shown = getIds(destinations);
657
- const main = shown.length > 0 ? shown : ["any"];
658
- return {
659
- main,
660
- more: getIds(destinationsMore).filter((id) => !main.includes(id))
783
+ return [...new Set(value)];
784
+ }
785
+ function getDestinationLists({ destinations, destinationsMore }, catalogue) {
786
+ const unknown = [];
787
+ const resolve = (ids) => ids.flatMap((id) => {
788
+ const destination = typeof id === "string" ? catalogue.get(id) : void 0;
789
+ if (!destination) unknown.push(String(id));
790
+ return destination ? [destination] : [];
791
+ });
792
+ const shown = resolve(getIds(destinations));
793
+ const rest = resolve(getIds(destinationsMore)).filter((destination) => !shown.includes(destination));
794
+ if (unknown.length > 0) console.warn(`share-kit: unregistered destinations dropped: ${unknown.join(", ")}`);
795
+ if (shown.length > 0) return {
796
+ main: shown,
797
+ more: rest
661
798
  };
799
+ if (rest.length > 0) return {
800
+ main: rest,
801
+ more: []
802
+ };
803
+ console.warn("share-kit: no registered destinations to show");
804
+ }
805
+ function getShareAssets(assets) {
806
+ const seen = /* @__PURE__ */ new Set();
807
+ const kept = assets.filter((asset) => {
808
+ const id = asset.id;
809
+ if (typeof id !== "string" || id === "" || seen.has(id)) return false;
810
+ seen.add(id);
811
+ return true;
812
+ });
813
+ if (kept.length < assets.length) console.warn("share-kit: images with an empty or repeated id dropped");
814
+ return kept;
662
815
  }
663
816
  // src/qr.ts
664
- const iconSize = 24;
665
817
  const qrSize = 200;
666
818
  async function createQrSource(text) {
667
819
  const [{ generate }, { toSvgDataURL }] = await Promise.all([import("lean-qr"), import("lean-qr/extras/svg")]);
@@ -701,7 +853,7 @@ var ShareQrDialog = class {
701
853
  class: "share-kit-icon-button",
702
854
  title: strings.close,
703
855
  type: "submit"
704
- }, [closeIcon ? createIcon(closeIcon, iconSize) : "×"])]), this.#image]);
856
+ }, [createIconSlot("close", closeIcon, "×")])]), this.#image]);
705
857
  polyfillLightDismiss(this.dialog, signal);
706
858
  }
707
859
  async open() {
@@ -716,14 +868,74 @@ function getQrUrl(url, openHash) {
716
868
  return target.href;
717
869
  }
718
870
  function createShareQr({ capabilities, payload, ...input }) {
719
- if (capabilities.has("handheld")) return;
871
+ if (capabilities.has("mobile")) return;
720
872
  return new ShareQrDialog({
721
873
  ...input,
722
874
  url: getQrUrl(payload.url, payload.settings.openHash)
723
875
  });
724
876
  }
877
+ // src/strings.ts
878
+ const shareKitStringDefaults = {
879
+ assetCopy: "Copy",
880
+ assetSave: "Save",
881
+ assetShare: "Share",
882
+ captionCopy: "Copy caption",
883
+ captionOver: "{count} over the limit for {destination}",
884
+ captionReset: "Reset",
885
+ captionTitle: "Caption",
886
+ close: "Close",
887
+ copied: "Copied",
888
+ copyManual: "Couldn't copy. The caption is selected, so you can copy it yourself.",
889
+ destinationsMore: "More",
890
+ destinationsTitle: "Post to",
891
+ error: "Something went wrong. Try saving instead.",
892
+ imagesTitle: "Images",
893
+ linkCopy: "Copy link",
894
+ linkTitle: "Link",
895
+ primaryCopy: "Copy caption",
896
+ primaryOpen: "Open {destination}",
897
+ primaryShareImage: "Share image",
898
+ primaryShareLink: "Share link",
899
+ primaryShareText: "Share",
900
+ qrAlt: "QR code for this page",
901
+ qrTitle: "Scan to continue on your phone",
902
+ qrToggle: "Continue on your phone",
903
+ retry: "Ready. Tap again to share.",
904
+ saved: "Saved",
905
+ saveError: "Couldn't save. Try again.",
906
+ suggested: "Suggested",
907
+ title: "Share this page"
908
+ };
909
+ const destinationStringPattern = /^(?:destination|hint)\.(.+)$/u;
910
+ function isShareStringKey(key) {
911
+ return Object.hasOwn(shareKitStringDefaults, key);
912
+ }
913
+ function isDestinationStringKey(key, ids) {
914
+ const id = destinationStringPattern.exec(key)?.[1];
915
+ return id !== void 0 && ids.has(id);
916
+ }
917
+ function getShareStrings(overrides, ids) {
918
+ const strings = { ...shareKitStringDefaults };
919
+ for (const [key, value] of Object.entries(overrides)) {
920
+ if (typeof value !== "string") continue;
921
+ if (isShareStringKey(key) || isDestinationStringKey(key, ids)) strings[key] = value;
922
+ }
923
+ return strings;
924
+ }
925
+ function getDestinationLabel(strings, { id, label }) {
926
+ return strings[`destination.${id}`] ?? label;
927
+ }
928
+ function getDestinationHint(strings, { hint, id }) {
929
+ return strings[`hint.${id}`] ?? hint;
930
+ }
931
+ function formatShareString(template, values) {
932
+ return template.replaceAll(/\{(\w+)\}/gu, (match, name) => values[name] ?? match);
933
+ }
725
934
  // src/render.ts
726
- const destinationIconSize = 24;
935
+ function renderDestinationIcon({ icons, isIconsLoading }, name) {
936
+ const path = icons[name];
937
+ return path || isIconsLoading ? createIconSlot(name, path) : void 0;
938
+ }
727
939
  function renderAction({ classNames }, { action, describedBy, label }) {
728
940
  return createElement("button", {
729
941
  "aria-describedby": describedBy,
@@ -738,7 +950,7 @@ function renderHeading({ classNames }, children, id) {
738
950
  id
739
951
  }, children);
740
952
  }
741
- function renderIconButton({ action, attributes, fallback, icon, label }) {
953
+ function renderIconButton({ icons }, { action, attributes, fallback, icon, label }) {
742
954
  return createElement("button", {
743
955
  ...attributes,
744
956
  "aria-label": label,
@@ -746,52 +958,51 @@ function renderIconButton({ action, attributes, fallback, icon, label }) {
746
958
  "data-share-kit-action": action,
747
959
  title: label,
748
960
  type: "button"
749
- }, [icon ? createIcon(icon, destinationIconSize) : fallback]);
961
+ }, [createIconSlot(icon, icons[icon], fallback)]);
750
962
  }
751
963
  function renderHeader(context) {
752
- const { capabilities, icons, id, strings } = context;
964
+ const { capabilities, id, strings } = context;
753
965
  const heading = createElement("h2", {
754
966
  class: "share-kit-title",
755
967
  id: `${id}-title`,
756
968
  tabindex: "-1"
757
969
  }, [strings.title]);
758
970
  return {
759
- header: createElement("header", { class: "share-kit-header" }, [heading, createElement("div", { class: "share-kit-header-actions" }, [capabilities.has("handheld") ? void 0 : renderIconButton({
971
+ header: createElement("header", { class: "share-kit-header" }, [heading, createElement("div", { class: "share-kit-header-actions" }, [capabilities.has("mobile") ? void 0 : renderIconButton(context, {
760
972
  action: "qr",
761
973
  attributes: { "aria-haspopup": "dialog" },
762
974
  fallback: "QR",
763
- icon: icons.qr,
975
+ icon: "qr",
764
976
  label: strings.qrToggle
765
- }), renderIconButton({
977
+ }), renderIconButton(context, {
766
978
  action: "close",
767
979
  fallback: "×",
768
- icon: icons.close,
980
+ icon: "close",
769
981
  label: strings.close
770
982
  })])]),
771
983
  heading
772
984
  };
773
985
  }
774
986
  function renderDestination(context, destination) {
775
- const { classNames, icons, strings } = context;
776
- const icon = icons[destination];
987
+ const { classNames, strings } = context;
777
988
  return createElement("button", {
778
989
  "aria-checked": "false",
779
990
  class: joinClasses("share-kit-destination", classNames.destination),
780
991
  "data-share-kit-action": "destination",
781
- "data-share-kit-destination": destination,
992
+ "data-share-kit-destination": destination.id,
782
993
  role: "radio",
783
994
  tabindex: "-1",
784
995
  type: "button"
785
- }, [icon ? createIcon(icon, destinationIconSize) : void 0, createElement("span", {}, [strings[`destination.${destination}`]])]);
996
+ }, [renderDestinationIcon(context, destination.id), createElement("span", {}, [getDestinationLabel(strings, destination)])]);
786
997
  }
787
998
  function renderDestinations(context) {
788
- const { destinations, destinationsMore, icons, id, strings } = context;
999
+ const { destinations, destinationsMore, id, strings } = context;
789
1000
  const headingId = `${id}-destinations`;
790
1001
  const more = destinationsMore.length > 0 ? createElement("button", {
791
1002
  class: joinClasses("share-kit-destination", context.classNames.destination),
792
1003
  "data-share-kit-action": "more",
793
1004
  type: "button"
794
- }, [icons.more ? createIcon(icons.more, destinationIconSize) : void 0, createElement("span", {}, [strings.destinationsMore])]) : void 0;
1005
+ }, [renderDestinationIcon(context, "more"), createElement("span", {}, [strings.destinationsMore])]) : void 0;
795
1006
  const extra = destinationsMore.map((destination) => {
796
1007
  const button = renderDestination(context, destination);
797
1008
  button.hidden = true;
@@ -848,14 +1059,13 @@ function renderCaption(context) {
848
1059
  ])
849
1060
  };
850
1061
  }
851
- function renderTile(context, { actions, asset, key }) {
852
- const labelId = `${context.id}-asset-${key}`;
1062
+ function renderTile(context, { actions, asset, index }) {
1063
+ const labelId = `${context.id}-asset-${String(index)}`;
853
1064
  const badge = createElement("span", { class: "share-kit-badge" }, [context.strings.suggested]);
854
1065
  badge.hidden = true;
855
1066
  return createElement("li", {
856
1067
  class: "share-kit-tile",
857
- "data-share-kit-asset": key,
858
- "data-share-kit-role": asset.role
1068
+ "data-share-kit-asset": asset.id
859
1069
  }, [
860
1070
  createElement("img", {
861
1071
  alt: asset.alt,
@@ -878,25 +1088,19 @@ function getAssetActions({ capabilities, strings }) {
878
1088
  const actions = [];
879
1089
  const canShare = capabilities.has("files");
880
1090
  if (canShare) actions.push(["share", strings.assetShare]);
881
- if (capabilities.has("copy-image") && !(canShare && capabilities.has("handheld"))) actions.push(["copy", strings.assetCopy]);
1091
+ if (capabilities.has("copy-image") && !(canShare && capabilities.has("mobile"))) actions.push(["copy", strings.assetCopy]);
882
1092
  actions.push(["save", strings.assetSave]);
883
1093
  return actions;
884
1094
  }
885
1095
  function renderImages(context) {
886
1096
  const { payload, strings } = context;
887
1097
  const actions = getAssetActions(context);
888
- const counts = /* @__PURE__ */ new Map();
889
1098
  const assets = /* @__PURE__ */ new Map();
890
- for (const asset of payload.assets) {
891
- const number = (counts.get(asset.role) ?? 0) + 1;
892
- const key = asset.role === "photo" ? `photo-${String(number)}` : asset.role;
893
- counts.set(asset.role, number);
894
- assets.set(renderTile(context, {
895
- actions,
896
- asset,
897
- key
898
- }), asset);
899
- }
1099
+ for (const [index, asset] of payload.assets.entries()) assets.set(renderTile(context, {
1100
+ actions,
1101
+ asset,
1102
+ index
1103
+ }), asset);
900
1104
  const grid = createElement("ul", { class: "share-kit-grid" }, [...assets.keys()]);
901
1105
  return {
902
1106
  assets,
@@ -939,8 +1143,8 @@ function renderShareKit(input) {
939
1143
  createElement("div", { class: "share-kit-scroll" }, [
940
1144
  destinations.section,
941
1145
  caption.section,
942
- images.section,
943
- renderLink(context)
1146
+ renderLink(context),
1147
+ images.section
944
1148
  ]),
945
1149
  createElement("footer", { class: "share-kit-footer" }, [status, primary])
946
1150
  ])]);
@@ -967,15 +1171,11 @@ const primaryLabels = {
967
1171
  "share-link": "primaryShareLink",
968
1172
  "share-text": "primaryShareText"
969
1173
  };
970
- function getSuggestedAsset(assets, destination) {
971
- const { assetRole } = getShareDestination(destination);
972
- return assets.find((asset) => asset.dataset.shareKitRole === assetRole) ?? assets.find((asset) => asset.dataset.shareKitRole === "landscape") ?? assets[0];
973
- }
974
1174
  function syncCaptionView({ destination, parts, primaryAction, strings }) {
975
- const { limit } = getShareDestination(destination);
976
- const count = countCaption(parts.caption.value, destination);
1175
+ const { limit } = destination;
1176
+ const count = destination.count(parts.caption.value);
977
1177
  const isOver = limit !== void 0 && count > limit;
978
- const label = strings[`destination.${destination}`];
1178
+ const label = getDestinationLabel(strings, destination);
979
1179
  parts.count.textContent = limit === void 0 ? String(count) : `${String(count)} / ${String(limit)}`;
980
1180
  parts.count.toggleAttribute("data-share-kit-over", isOver);
981
1181
  parts.caption.setAttribute("aria-invalid", String(isOver));
@@ -991,12 +1191,11 @@ function syncCaptionView({ destination, parts, primaryAction, strings }) {
991
1191
  }
992
1192
  function syncDestinationView({ assets, destination, parts, strings, suggested }) {
993
1193
  for (const radio of parts.dialog.querySelectorAll("[role=\"radio\"]")) {
994
- const isSelected = radio.dataset.shareKitDestination === destination;
1194
+ const isSelected = radio.dataset.shareKitDestination === destination.id;
995
1195
  radio.setAttribute("aria-checked", String(isSelected));
996
1196
  radio.tabIndex = isSelected ? 0 : -1;
997
1197
  }
998
- const hintKey = `hint.${destination}`;
999
- parts.hint.textContent = isShareStringKey(hintKey) ? strings[hintKey] : "";
1198
+ parts.hint.textContent = getDestinationHint(strings, destination) ?? "";
1000
1199
  parts.hint.hidden = parts.hint.textContent === "";
1001
1200
  for (const asset of assets) {
1002
1201
  const badge = asset.querySelector(".share-kit-badge");
@@ -1008,6 +1207,11 @@ function syncDestinationView({ assets, destination, parts, strings, suggested })
1008
1207
  // src/types.ts
1009
1208
  const shareKitActionEventName = "share-kit:action";
1010
1209
  // src/element.ts
1210
+ const iconIntentEvents = [
1211
+ "focusin",
1212
+ "pointerdown",
1213
+ "pointerover"
1214
+ ];
1011
1215
  const outcomeMessages = {
1012
1216
  error: "error",
1013
1217
  retry: "retry",
@@ -1020,7 +1224,8 @@ function isKeyOf(record, key) {
1020
1224
  }
1021
1225
  const BaseElement = typeof HTMLElement === "undefined" ? Object : HTMLElement;
1022
1226
  var ShareKitElement = class extends BaseElement {
1023
- icons = {};
1227
+ catalogue = /* @__PURE__ */ new Map();
1228
+ iconSource = new ShareIconSource({});
1024
1229
  #abortController;
1025
1230
  #actions = {
1026
1231
  close: () => {
@@ -1040,9 +1245,9 @@ var ShareKitElement = class extends BaseElement {
1040
1245
  this.#feedback?.copyText(this.#payload?.url ?? "", button);
1041
1246
  },
1042
1247
  destination: (button) => {
1043
- const id = button.dataset.shareKitDestination;
1044
- if (!id || !isShareDestinationId(id)) return;
1045
- this.#selectDestination(id);
1248
+ const destination = this.#getRendered(button.dataset.shareKitDestination);
1249
+ if (!destination) return;
1250
+ this.#selectDestination(destination);
1046
1251
  this.#track("destination");
1047
1252
  },
1048
1253
  more: (button) => {
@@ -1059,18 +1264,20 @@ var ShareKitElement = class extends BaseElement {
1059
1264
  this.#syncDestination();
1060
1265
  },
1061
1266
  save: (_button, tile) => {
1062
- if (tile) this.#saveAsset(tile);
1267
+ if (tile) this.#settle("save", this.#files?.save(tile), tile);
1063
1268
  },
1064
1269
  share: (_button, tile) => {
1065
- if (tile) this.#shareAssets([tile]);
1270
+ if (tile) this.#settle("share", this.#files?.share([tile]), tile);
1066
1271
  }
1067
1272
  };
1068
1273
  #capabilities = /* @__PURE__ */ new Set();
1069
- #destination = "any";
1274
+ #destination;
1070
1275
  #feedback;
1071
1276
  #files;
1072
1277
  #isCaptionEdited = false;
1278
+ #isIconsRequested = false;
1073
1279
  #isOver = false;
1280
+ #lists;
1074
1281
  #parts;
1075
1282
  #payload;
1076
1283
  #primaryActions = {
@@ -1079,25 +1286,25 @@ var ShareKitElement = class extends BaseElement {
1079
1286
  this.#copyCaption();
1080
1287
  },
1081
1288
  "open-composer": () => {
1082
- const url = this.#getComposerUrl();
1083
- if (!url) return;
1289
+ const href = this.#getComposerUrl();
1290
+ if (!href) return;
1084
1291
  this.#track("open-composer");
1085
1292
  this.#copyCaption();
1086
- window.open(url, "_blank", "noopener");
1293
+ openComposer(href);
1087
1294
  },
1088
1295
  "share-image": () => {
1089
1296
  const tile = this.#getSuggestedAsset();
1090
1297
  if (!tile) return;
1091
1298
  this.#copyCaption();
1092
- this.#shareAssets([tile]);
1299
+ this.#settle("share", this.#files?.share([tile]), tile);
1093
1300
  },
1094
1301
  "share-link": () => {
1095
1302
  this.#copyCaption();
1096
- this.#shareData("share-link", { url: this.#getUrl() });
1303
+ this.#settle("share-link", shareData({ url: this.#getUrl() }));
1097
1304
  },
1098
1305
  "share-text": () => {
1099
1306
  const text = this.#parts?.caption.value;
1100
- if (text) this.#shareData("share-text", { text });
1307
+ if (text) this.#settle("share-text", shareData({ text }));
1101
1308
  }
1102
1309
  };
1103
1310
  #qr;
@@ -1109,9 +1316,15 @@ var ShareKitElement = class extends BaseElement {
1109
1316
  this.#retryWhenParsed();
1110
1317
  return;
1111
1318
  }
1319
+ const lists = getDestinationLists(payload.settings, this.catalogue);
1320
+ if (!lists) return;
1112
1321
  this.#abortController = new AbortController();
1113
- this.#payload = payload;
1114
- this.#strings = getShareStrings(payload.strings);
1322
+ this.#lists = lists;
1323
+ this.#payload = {
1324
+ ...payload,
1325
+ assets: getShareAssets(payload.assets)
1326
+ };
1327
+ this.#strings = getShareStrings(payload.strings ?? {}, new Set(this.catalogue.keys()));
1115
1328
  this.#feedback = new ShareFeedback(() => this.#parts?.status, this.#strings);
1116
1329
  const { signal } = this.#abortController;
1117
1330
  this.#capabilities = new Set(getShareCapabilities(this.dataset.can));
@@ -1128,6 +1341,7 @@ var ShareKitElement = class extends BaseElement {
1128
1341
  signal
1129
1342
  });
1130
1343
  this.addEventListener("pointerover", ({ target }) => this.#files?.warm(target), { signal });
1344
+ for (const type of iconIntentEvents) this.addEventListener(type, this.#handleTriggerIntent, { signal });
1131
1345
  window.addEventListener("hashchange", this.#handleHashChange, { signal });
1132
1346
  this.querySelector("[data-share-kit-trigger]")?.toggleAttribute("disabled", false);
1133
1347
  queueMicrotask(() => {
@@ -1144,44 +1358,82 @@ var ShareKitElement = class extends BaseElement {
1144
1358
  this.#feedback = void 0;
1145
1359
  this.#files?.dispose();
1146
1360
  this.#files = void 0;
1147
- this.#destination = "any";
1361
+ this.#destination = void 0;
1362
+ this.#lists = void 0;
1148
1363
  this.#isCaptionEdited = false;
1364
+ this.#isIconsRequested = false;
1149
1365
  this.#isOver = false;
1150
1366
  }
1151
1367
  async #copyCaption(button) {
1152
1368
  const caption = this.#parts?.caption;
1153
1369
  if (caption) await this.#feedback?.copyText(caption.value, button, caption);
1154
1370
  }
1371
+ #dispatch(detail) {
1372
+ this.dispatchEvent(new CustomEvent(shareKitActionEventName, {
1373
+ bubbles: true,
1374
+ composed: true,
1375
+ detail
1376
+ }));
1377
+ }
1155
1378
  #getAssets() {
1156
1379
  return (this.#parts?.tiles ?? []).filter((tile) => tile.dataset.shareKitState !== "failed");
1157
1380
  }
1158
1381
  #getComposerUrl() {
1159
1382
  const parts = this.#parts;
1160
- if (!parts) return;
1383
+ const payload = this.#payload;
1384
+ const composer = this.#destination?.composer;
1385
+ if (!parts || !payload || !composer) return;
1161
1386
  const suggested = this.#getSuggestedAsset();
1162
1387
  const media = suggested ? parts.assets.get(suggested)?.src : void 0;
1163
- return getShareDestination(this.#destination).getComposerUrl?.({
1164
- media: media ? new URL(media, location.href).href : void 0,
1388
+ return composer({
1389
+ ...payload.description === void 0 ? {} : { description: payload.description },
1390
+ device: this.#getDevice(),
1391
+ ...media === void 0 ? {} : { media: new URL(media, location.href).href },
1165
1392
  text: parts.caption.value,
1393
+ title: payload.title,
1166
1394
  url: this.#getUrl()
1167
1395
  });
1168
1396
  }
1397
+ #getDetail(action, tile) {
1398
+ if (!this.#destination) return;
1399
+ const detail = {
1400
+ action,
1401
+ destination: this.#destination.id
1402
+ };
1403
+ if (tile?.dataset.shareKitAsset) detail.asset = tile.dataset.shareKitAsset;
1404
+ return detail;
1405
+ }
1406
+ #getDevice() {
1407
+ return this.#capabilities.has("mobile") ? "mobile" : "desktop";
1408
+ }
1169
1409
  #getPrimaryAction() {
1170
- return getPrimaryAction({
1171
- canShareFiles: this.#capabilities.has("files") && this.#getSuggestedAsset() !== void 0,
1410
+ const destination = this.#destination;
1411
+ if (!destination) return "copy-caption";
1412
+ return getPrimaryAction(destination.actions[this.#getDevice()], {
1413
+ canShareFiles: this.#capabilities.has("files"),
1172
1414
  canShareText: this.#capabilities.has("link"),
1173
- hasComposerUrl: this.#getComposerUrl() !== void 0,
1174
- id: this.#destination,
1175
- isHandheld: this.#capabilities.has("handheld")
1415
+ composerUrl: this.#getComposerUrl(),
1416
+ hasSuggestedImage: this.#getSuggestedAsset() !== void 0
1176
1417
  });
1177
1418
  }
1419
+ #getRendered(id) {
1420
+ const lists = this.#lists;
1421
+ if (!id || !lists) return;
1422
+ return [...lists.main, ...lists.more].find((destination) => destination.id === id);
1423
+ }
1178
1424
  #getSuggestedAsset() {
1179
- return getSuggestedAsset(this.#getAssets(), this.#destination);
1425
+ const parts = this.#parts;
1426
+ const destination = this.#destination;
1427
+ if (!parts || !destination) return;
1428
+ const tiles = this.#getAssets();
1429
+ const suggested = getSuggestedImage(tiles.flatMap((tile) => parts.assets.get(tile) ?? []), destination.images);
1430
+ return tiles.find((tile) => parts.assets.get(tile) === suggested);
1180
1431
  }
1181
1432
  #getUrl() {
1182
1433
  const payload = this.#payload;
1183
- if (!payload) return "";
1184
- return getDestinationUrl(payload.url, this.#destination, payload.settings.utmMedium);
1434
+ const destination = this.#destination;
1435
+ if (!payload || !destination) return payload?.url ?? "";
1436
+ return getDestinationUrl(payload.url, destination, payload.settings.utmMedium);
1185
1437
  }
1186
1438
  #handleClick = (event) => {
1187
1439
  if (!(event.target instanceof Element)) return;
@@ -1209,10 +1461,10 @@ var ShareKitElement = class extends BaseElement {
1209
1461
  if (!move || !(event.target instanceof HTMLElement) || event.target.role !== "radio") return;
1210
1462
  const radios = [...this.querySelectorAll("[role=\"radio\"]:not([hidden])")];
1211
1463
  const next = radios[move(radios.indexOf(event.target), radios.length)];
1212
- const id = next?.dataset.shareKitDestination;
1213
- if (!next || !id || !isShareDestinationId(id)) return;
1464
+ const destination = this.#getRendered(next?.dataset.shareKitDestination);
1465
+ if (!next || !destination) return;
1214
1466
  event.preventDefault();
1215
- this.#selectDestination(id);
1467
+ this.#selectDestination(destination);
1216
1468
  next.focus();
1217
1469
  };
1218
1470
  #handlePreviewError = (event) => {
@@ -1222,7 +1474,19 @@ var ShareKitElement = class extends BaseElement {
1222
1474
  tile.dataset.shareKitState = "failed";
1223
1475
  this.#syncDestination();
1224
1476
  };
1477
+ #handleTriggerIntent = ({ target }) => {
1478
+ if (target instanceof Element && target.closest("[data-share-kit-trigger]")) this.#loadIcons();
1479
+ };
1480
+ #loadIcons() {
1481
+ const signal = this.#abortController?.signal;
1482
+ if (!signal || this.#isIconsRequested) return;
1483
+ this.#isIconsRequested = true;
1484
+ this.iconSource.load().then((icons) => {
1485
+ if (!signal.aborted && this.#parts) patchIcons(this.#parts.dialog, icons);
1486
+ });
1487
+ }
1225
1488
  #open() {
1489
+ this.#loadIcons();
1226
1490
  const parts = this.#parts ?? this.#render();
1227
1491
  if (!parts || parts.dialog.open) return;
1228
1492
  parts.dialog.showModal();
@@ -1240,29 +1504,32 @@ var ShareKitElement = class extends BaseElement {
1240
1504
  }
1241
1505
  }
1242
1506
  #prefetch() {
1243
- if (!this.#capabilities.has("files") || !this.#capabilities.has("handheld")) return;
1507
+ if (!this.#capabilities.has("files") || !this.#capabilities.has("mobile")) return;
1244
1508
  const tile = this.#getSuggestedAsset();
1245
1509
  if (tile) this.#files?.load(tile);
1246
1510
  }
1247
1511
  #render() {
1248
1512
  const payload = this.#payload;
1513
+ const lists = this.#lists;
1249
1514
  const signal = this.#abortController?.signal;
1250
- if (!payload || !signal) return;
1251
- const { main, more } = getDestinationLists(payload.settings);
1515
+ if (!payload || !lists || !signal) return;
1516
+ const { main, more } = lists;
1517
+ const { icons, isLoading } = this.iconSource;
1252
1518
  dialogCount += 1;
1253
1519
  const id = `share-kit-${String(dialogCount)}`;
1254
1520
  const parts = renderShareKit({
1255
1521
  capabilities: this.#capabilities,
1256
1522
  destinations: main,
1257
1523
  destinationsMore: more,
1258
- icons: this.icons,
1524
+ icons,
1259
1525
  id,
1526
+ isIconsLoading: isLoading,
1260
1527
  payload,
1261
1528
  strings: this.#strings
1262
1529
  });
1263
1530
  this.#qr = createShareQr({
1264
1531
  capabilities: this.#capabilities,
1265
- closeIcon: this.icons.close,
1532
+ closeIcon: icons.close,
1266
1533
  id: `${id}-qr`,
1267
1534
  payload,
1268
1535
  signal,
@@ -1273,7 +1540,7 @@ var ShareKitElement = class extends BaseElement {
1273
1540
  polyfillLightDismiss(parts.dialog, signal);
1274
1541
  this.append(parts.dialog);
1275
1542
  this.#parts = parts;
1276
- this.#destination = main[0] ?? "any";
1543
+ this.#destination = main[0];
1277
1544
  this.#syncDestination();
1278
1545
  return parts;
1279
1546
  }
@@ -1286,33 +1553,25 @@ var ShareKitElement = class extends BaseElement {
1286
1553
  if (this.isConnected) this.connectedCallback();
1287
1554
  }, { once: true });
1288
1555
  }
1289
- async #saveAsset(tile) {
1290
- this.#track("save", tile);
1291
- this.#report(await this.#files?.save(tile));
1292
- }
1293
- #selectDestination(id) {
1556
+ #selectDestination(destination) {
1294
1557
  const previousUrl = this.#getUrl();
1295
1558
  const caption = this.#parts?.caption;
1296
- this.#destination = id;
1559
+ this.#destination = destination;
1297
1560
  if (caption && this.#isCaptionEdited) {
1298
1561
  const url = this.#getUrl();
1299
1562
  caption.value = caption.value.replaceAll(previousUrl, () => url);
1300
1563
  }
1301
1564
  this.#syncDestination();
1302
1565
  }
1303
- async #shareAssets(tiles) {
1304
- const [first] = tiles;
1305
- if (!first) return;
1306
- this.#track("share", first);
1307
- this.#report(await this.#files?.share(tiles));
1308
- }
1309
- async #shareData(action, data) {
1310
- this.#track(action);
1311
- try {
1312
- await navigator.share(data);
1313
- } catch (error) {
1314
- if (!isDomError(error, "AbortError")) this.#feedback?.announce(this.#strings.error);
1315
- }
1566
+ async #settle(action, pending, tile) {
1567
+ const detail = this.#getDetail(action, tile);
1568
+ const outcome = await pending;
1569
+ this.#report(outcome);
1570
+ if (!detail || !outcome) return;
1571
+ this.#dispatch({
1572
+ ...detail,
1573
+ outcome: outcome === "unsaved" ? "error" : outcome
1574
+ });
1316
1575
  }
1317
1576
  #showMore(button) {
1318
1577
  const hidden = [...this.querySelectorAll("[role=\"radio\"][hidden]")];
@@ -1322,9 +1581,10 @@ var ShareKitElement = class extends BaseElement {
1322
1581
  }
1323
1582
  #syncCaption() {
1324
1583
  const parts = this.#parts;
1325
- if (!parts) return;
1584
+ const destination = this.#destination;
1585
+ if (!parts || !destination) return;
1326
1586
  const { isOver, message } = syncCaptionView({
1327
- destination: this.#destination,
1587
+ destination,
1328
1588
  parts,
1329
1589
  primaryAction: this.#getPrimaryAction(),
1330
1590
  strings: this.#strings
@@ -1335,10 +1595,11 @@ var ShareKitElement = class extends BaseElement {
1335
1595
  #syncDestination() {
1336
1596
  const parts = this.#parts;
1337
1597
  const payload = this.#payload;
1338
- if (!parts || !payload) return;
1598
+ const destination = this.#destination;
1599
+ if (!parts || !payload || !destination) return;
1339
1600
  syncDestinationView({
1340
1601
  assets: this.#getAssets(),
1341
- destination: this.#destination,
1602
+ destination,
1342
1603
  parts,
1343
1604
  strings: this.#strings,
1344
1605
  suggested: this.#getSuggestedAsset()
@@ -1347,39 +1608,52 @@ var ShareKitElement = class extends BaseElement {
1347
1608
  description: payload.description,
1348
1609
  title: payload.title,
1349
1610
  url: this.#getUrl()
1350
- }, this.#destination, payload.locale).text;
1611
+ }, destination, payload.locale).text;
1351
1612
  this.#syncCaption();
1352
1613
  this.#prefetch();
1353
1614
  }
1354
1615
  #track(action, tile) {
1355
- const detail = {
1356
- action,
1357
- destination: this.#destination
1358
- };
1359
- if (tile?.dataset.shareKitAsset) detail.asset = tile.dataset.shareKitAsset;
1360
- this.dispatchEvent(new CustomEvent(shareKitActionEventName, {
1361
- bubbles: true,
1362
- composed: true,
1363
- detail
1364
- }));
1616
+ const detail = this.#getDetail(action, tile);
1617
+ if (detail) this.#dispatch(detail);
1365
1618
  }
1366
1619
  };
1367
1620
  // src/define.ts
1368
1621
  const tagName = "share-kit";
1369
- function defineShareKit({ icons = {} } = {}) {
1370
- if (customElements.get(tagName)) return;
1371
- customElements.define(tagName, class extends ShareKitElement {
1372
- icons = icons;
1373
- });
1622
+ const reservedIds = new Set(shareKitInterfaceIconNames);
1623
+ function getCatalogue(destinations) {
1624
+ const catalogue = /* @__PURE__ */ new Map();
1625
+ for (const destination of destinations) {
1626
+ if (reservedIds.has(destination.id) || catalogue.has(destination.id)) {
1627
+ console.error(`share-kit: destination id "${destination.id}" is repeated or reserved for an icon, so <share-kit> is not defined`);
1628
+ return;
1629
+ }
1630
+ catalogue.set(destination.id, destination);
1631
+ }
1632
+ return catalogue;
1374
1633
  }
1375
- // src/icons.ts
1376
- const shareKitInterfaceIcons = {
1377
- 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",
1378
- 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",
1379
- 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",
1380
- 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",
1381
- 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"
1382
- };
1383
- export { defineShareKit, serializeShareKitPayload, shareKitActionEventName, shareKitInterfaceIcons };
1634
+ function warnMissingComposers(destinations) {
1635
+ for (const { actions, composer, id } of destinations) if ([...actions.desktop, ...actions.mobile].includes("open-composer") && !composer) console.warn(`share-kit: "${id}" lists open-composer but has no composer`);
1636
+ }
1637
+ function createElementClass(catalogue, iconSource) {
1638
+ return class extends ShareKitElement {
1639
+ catalogue = catalogue;
1640
+ iconSource = iconSource;
1641
+ };
1642
+ }
1643
+ function defineShareKit({ destinations, icons = {} }) {
1644
+ if (customElements.get(tagName)) {
1645
+ console.warn("share-kit: <share-kit> is already defined, so this defineShareKit call is ignored");
1646
+ return;
1647
+ }
1648
+ if (destinations.length === 0) {
1649
+ console.error("share-kit: no destinations registered, so <share-kit> is not defined");
1650
+ return;
1651
+ }
1652
+ const catalogue = getCatalogue(destinations);
1653
+ if (!catalogue) return;
1654
+ warnMissingComposers(destinations);
1655
+ customElements.define(tagName, createElementClass(catalogue, new ShareIconSource(icons)));
1656
+ }
1657
+ export { defineShareKit, defineShareKitDestination, getShareKitImageFormats, serializeShareKitPayload, shareKitActionEventName, shareKitAnywhere, shareKitBluesky, shareKitCountGraphemes, shareKitCountLength, shareKitCountStringz, shareKitCountUtf8, shareKitCountWeighted, shareKitFacebook, shareKitInstagram, shareKitInstagramStory, shareKitInterfaceIcons, shareKitLandscapeFormat, shareKitLine, shareKitLinkedin, shareKitMastodon, shareKitMessages, shareKitPinFormat, shareKitPinterest, shareKitPortraitFormat, shareKitReddit, shareKitShortenedLinkCost, shareKitStoryFormat, shareKitThreads, shareKitWithLinkCost, shareKitX };
1384
1658
 
1385
1659
  //# sourceMappingURL=index.mjs.map