@xsynaptic/share-kit 0.2.1 → 0.3.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,95 @@
1
+ // src/count.ts
2
+ const urlPattern = /https?:\/\/[\w!#$%&'()*+,./:;=?@~-]+/giu;
3
+ const urlTrailingPunctuation = /[!'),.:;?]+$/u;
4
+ const graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
5
+ const utf8Encoder = new TextEncoder();
6
+ const latinCombiningMarkRanges = [
7
+ [768, 879],
8
+ [6832, 6911],
9
+ [7616, 7679],
10
+ [8400, 8447],
11
+ [65056, 65071]
12
+ ];
13
+ function getEmojiPattern() {
14
+ try {
15
+ return new RegExp(String.raw`^\p{RGI_Emoji}$`, "v");
16
+ } catch {
17
+ return;
18
+ }
19
+ }
20
+ const emojiPattern = getEmojiPattern();
21
+ function getGraphemes(text) {
22
+ return Array.from(graphemeSegmenter.segment(text), ({ segment }) => segment);
23
+ }
24
+ function isLightCodePoint(codePoint) {
25
+ return codePoint <= 4351 || codePoint >= 8192 && codePoint <= 8205 || codePoint >= 8208 && codePoint <= 8223 || codePoint >= 8242 && codePoint <= 8247;
26
+ }
27
+ function shareKitCountWeighted(text) {
28
+ const graphemes = getGraphemes(text.normalize("NFC"));
29
+ let total = 0;
30
+ for (const grapheme of graphemes) {
31
+ if (emojiPattern?.test(grapheme)) {
32
+ total += 2;
33
+ continue;
34
+ }
35
+ for (const character of grapheme) total += isLightCodePoint(character.codePointAt(0) ?? 0) ? 1 : 2;
36
+ }
37
+ return total;
38
+ }
39
+ function isLatinCombiningMark(codePoint) {
40
+ return latinCombiningMarkRanges.some(([start, end]) => codePoint >= start && codePoint <= end);
41
+ }
42
+ function shareKitCountStringz(text) {
43
+ let total = 0;
44
+ for (const grapheme of getGraphemes(text)) {
45
+ if (emojiPattern?.test(grapheme)) {
46
+ total += 1;
47
+ continue;
48
+ }
49
+ for (const character of grapheme) if (!isLatinCombiningMark(character.codePointAt(0) ?? 0)) total += 1;
50
+ }
51
+ return total;
52
+ }
53
+ function shareKitShortenedLinkCost(url) {
54
+ if (!URL.canParse(url)) return getGraphemes(url).length;
55
+ const { hash, host, pathname, search } = new URL(url);
56
+ const path = `${pathname === "/" ? "" : pathname}${search}${hash}`;
57
+ return host.length + Math.min(path.length, 16);
58
+ }
59
+ function shareKitCountLength(text) {
60
+ return text.length;
61
+ }
62
+ function shareKitCountGraphemes(text) {
63
+ return getGraphemes(text).length;
64
+ }
65
+ function shareKitCountUtf8(text) {
66
+ return utf8Encoder.encode(text).length;
67
+ }
68
+ function splitLinks(text) {
69
+ const links = [];
70
+ return {
71
+ links,
72
+ rest: text.replaceAll(urlPattern, (match) => {
73
+ const trailing = urlTrailingPunctuation.exec(match)?.[0] ?? "";
74
+ links.push(match.slice(0, match.length - trailing.length));
75
+ return trailing;
76
+ })
77
+ };
78
+ }
79
+ function shareKitWithLinkCost(count, cost) {
80
+ return (text) => {
81
+ const { links, rest } = splitLinks(text);
82
+ let total = count(rest);
83
+ for (const link of links) total += typeof cost === "number" ? cost : cost(link);
84
+ return total;
85
+ };
86
+ }
1
87
  // src/actions.ts
2
88
  const shareCapabilities = [
3
89
  "files",
4
90
  "link",
5
91
  "copy-image",
6
- "handheld"
92
+ "mobile"
7
93
  ];
8
94
  const pngType = "image/png";
9
95
  function canShareFiles() {
@@ -17,14 +103,19 @@ function canCopyImage() {
17
103
  const capabilityTests = {
18
104
  "copy-image": canCopyImage,
19
105
  files: canShareFiles,
20
- handheld: () => matchMedia("(pointer: coarse)").matches,
21
- link: () => "share" in navigator
106
+ link: () => "share" in navigator,
107
+ mobile: () => matchMedia("(pointer: coarse)").matches
22
108
  };
23
109
  function isShareCapability(value) {
24
110
  return shareCapabilities.some((capability) => capability === value);
25
111
  }
26
112
  function getShareCapabilities(preset) {
27
- if (preset !== void 0) return preset.split(" ").filter(isShareCapability);
113
+ if (preset !== void 0) {
114
+ const tokens = preset.split(/\s+/u).filter(Boolean);
115
+ const unknown = tokens.filter((token) => !isShareCapability(token));
116
+ if (unknown.length > 0) console.warn(`share-kit: unknown data-can tokens ignored: ${unknown.join(", ")}`);
117
+ return tokens.filter(isShareCapability);
118
+ }
28
119
  return shareCapabilities.filter((capability) => capabilityTests[capability]());
29
120
  }
30
121
  function isDomError(error, name) {
@@ -70,6 +161,14 @@ function clearOpenHash(openHash) {
70
161
  if (!isOpenHash(openHash)) return;
71
162
  history.replaceState(history.state, "", `${location.pathname}${location.search}`);
72
163
  }
164
+ function openComposer(href) {
165
+ const { protocol } = new URL(href, location.href);
166
+ if (protocol !== "http:" && protocol !== "https:") {
167
+ location.assign(href);
168
+ return;
169
+ }
170
+ window.open(href, "_blank", "noopener");
171
+ }
73
172
  // src/assets.ts
74
173
  function isFile(file) {
75
174
  return file !== void 0;
@@ -138,234 +237,6 @@ var ShareAssetFiles = class {
138
237
  }
139
238
  }
140
239
  };
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
240
  // src/caption.ts
370
241
  const separator = "\n\n";
371
242
  const ellipsis = "…";
@@ -442,11 +313,7 @@ function fitParts(input) {
442
313
  const bare = join([title, link]);
443
314
  return canFit(bare) ? bare : join([fitTitle(input), link]);
444
315
  }
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);
316
+ function fitCaption({ description, title, url }, { count, limit, shape }, locale = "en") {
450
317
  const link = shape === "full" ? url : void 0;
451
318
  const body = shape === "title" ? void 0 : description?.trim() || void 0;
452
319
  const whole = shape === "url" ? url : join([
@@ -454,7 +321,7 @@ function fitCaption({ description, title, url }, id, locale = "en") {
454
321
  body,
455
322
  link
456
323
  ]);
457
- const canFit = (text) => limit === void 0 || countCaption(text, id) <= limit;
324
+ const canFit = (text) => limit === void 0 || count(text) <= limit;
458
325
  const text = canFit(whole) ? whole : fitParts({
459
326
  body,
460
327
  canFit,
@@ -463,12 +330,251 @@ function fitCaption({ description, title, url }, id, locale = "en") {
463
330
  title
464
331
  });
465
332
  return {
466
- count: countCaption(text, id),
333
+ count: count(text),
467
334
  isTruncated: text !== whole,
468
335
  limit,
469
336
  text
470
337
  };
471
338
  }
339
+ // src/formats.ts
340
+ const shareKitLandscapeFormat = {
341
+ height: 630,
342
+ id: "landscape",
343
+ width: 1200
344
+ };
345
+ const shareKitPortraitFormat = {
346
+ height: 1350,
347
+ id: "portrait",
348
+ width: 1080
349
+ };
350
+ const shareKitStoryFormat = {
351
+ height: 1920,
352
+ id: "story",
353
+ width: 1080
354
+ };
355
+ const shareKitPinFormat = {
356
+ height: 1500,
357
+ id: "pin",
358
+ width: 1e3
359
+ };
360
+ const fitTolerance = .02;
361
+ function getRatioDistance(image, format) {
362
+ return Math.abs(Math.log(image.width / image.height / (format.width / format.height)));
363
+ }
364
+ function isFormatFit(image, format) {
365
+ return getRatioDistance(image, format) <= fitTolerance;
366
+ }
367
+ function getSuggestedImage(images, formats) {
368
+ const candidates = images.filter((image) => image.isSuggestable !== false);
369
+ for (const format of formats) {
370
+ const match = candidates.find((image) => isFormatFit(image, format));
371
+ if (match) return match;
372
+ }
373
+ let nearest;
374
+ let nearestDistance = 1e400;
375
+ for (const image of candidates) {
376
+ const distance = getRatioDistance(image, formats[0]);
377
+ if (!(distance < nearestDistance)) continue;
378
+ nearest = image;
379
+ nearestDistance = distance;
380
+ }
381
+ return nearest;
382
+ }
383
+ function getShareKitImageFormats(destinations) {
384
+ const formats = /* @__PURE__ */ new Map();
385
+ for (const { images } of destinations) if (!formats.has(images[0].id)) formats.set(images[0].id, images[0]);
386
+ return [...formats.values()];
387
+ }
388
+ // src/destinations.ts
389
+ function defineShareKitDestination(destination) {
390
+ return destination;
391
+ }
392
+ function withQuery(base, parameters) {
393
+ const url = new URL(base);
394
+ for (const [name, value] of Object.entries(parameters)) if (value) url.searchParams.set(name, value);
395
+ return url.href;
396
+ }
397
+ const fixedLinkCost = 23;
398
+ const shareKitAnywhere = {
399
+ actions: {
400
+ desktop: [],
401
+ mobile: ["share-text"]
402
+ },
403
+ count: shareKitCountLength,
404
+ id: "any",
405
+ images: [shareKitLandscapeFormat],
406
+ label: "Anywhere",
407
+ shape: "full",
408
+ utmSource: false
409
+ };
410
+ const shareKitBluesky = {
411
+ actions: {
412
+ desktop: ["open-composer"],
413
+ mobile: ["share-image", "open-composer"]
414
+ },
415
+ composer: ({ text }) => withQuery("https://bsky.app/intent/compose", { text }),
416
+ count: shareKitWithLinkCost(shareKitCountGraphemes, shareKitShortenedLinkCost),
417
+ id: "bluesky",
418
+ images: [shareKitPortraitFormat],
419
+ label: "Bluesky",
420
+ limit: 300,
421
+ shape: "full"
422
+ };
423
+ const shareKitFacebook = {
424
+ actions: {
425
+ desktop: ["open-composer"],
426
+ mobile: ["share-link", "open-composer"]
427
+ },
428
+ composer: ({ url }) => withQuery("https://www.facebook.com/sharer/sharer.php", { u: url }),
429
+ count: shareKitCountLength,
430
+ hint: "Facebook only takes the link. Your caption is copied, so paste it into your post.",
431
+ id: "facebook",
432
+ images: [shareKitLandscapeFormat, shareKitPortraitFormat],
433
+ label: "Facebook",
434
+ limit: 63206,
435
+ shape: "full"
436
+ };
437
+ const shareKitInstagram = {
438
+ actions: {
439
+ desktop: [],
440
+ mobile: ["share-image"]
441
+ },
442
+ count: shareKitCountLength,
443
+ hint: "Links in Instagram captions aren't clickable. Point people to the link in your bio.",
444
+ id: "instagram",
445
+ images: [shareKitPortraitFormat],
446
+ label: "Instagram",
447
+ limit: 2200,
448
+ shape: "text"
449
+ };
450
+ const shareKitInstagramStory = {
451
+ actions: {
452
+ desktop: [],
453
+ mobile: ["share-image"]
454
+ },
455
+ count: shareKitCountLength,
456
+ hint: "Add the link to your Story with a link sticker.",
457
+ id: "instagram-story",
458
+ images: [shareKitStoryFormat, shareKitPortraitFormat],
459
+ label: "Story",
460
+ shape: "url"
461
+ };
462
+ const shareKitLinkedin = {
463
+ actions: {
464
+ desktop: ["open-composer"],
465
+ mobile: ["share-link", "open-composer"]
466
+ },
467
+ composer: ({ url }) => withQuery("https://www.linkedin.com/sharing/share-offsite/", { url }),
468
+ count: shareKitCountLength,
469
+ hint: "LinkedIn only takes the link. Your caption is copied, so paste it into your post.",
470
+ id: "linkedin",
471
+ images: [shareKitLandscapeFormat],
472
+ label: "LinkedIn",
473
+ limit: 3e3,
474
+ shape: "full"
475
+ };
476
+ const shareKitMastodon = {
477
+ actions: {
478
+ desktop: [],
479
+ mobile: ["share-image"]
480
+ },
481
+ count: shareKitWithLinkCost(shareKitCountStringz, fixedLinkCost),
482
+ id: "mastodon",
483
+ images: [shareKitPortraitFormat],
484
+ label: "Mastodon",
485
+ limit: 500,
486
+ shape: "full"
487
+ };
488
+ const shareKitMessages = {
489
+ actions: {
490
+ desktop: ["share-text"],
491
+ mobile: ["share-text"]
492
+ },
493
+ count: shareKitCountLength,
494
+ id: "messages",
495
+ images: [shareKitLandscapeFormat],
496
+ label: "Messages",
497
+ shape: "full"
498
+ };
499
+ const shareKitPinterest = {
500
+ actions: {
501
+ desktop: ["open-composer"],
502
+ mobile: ["open-composer"]
503
+ },
504
+ composer: ({ media, text, url }) => withQuery("https://www.pinterest.com/pin/create/button/", {
505
+ description: text,
506
+ media,
507
+ url
508
+ }),
509
+ count: shareKitCountLength,
510
+ id: "pinterest",
511
+ images: [shareKitPinFormat, shareKitPortraitFormat],
512
+ label: "Pinterest",
513
+ limit: 800,
514
+ shape: "text"
515
+ };
516
+ const shareKitReddit = {
517
+ actions: {
518
+ desktop: ["open-composer"],
519
+ mobile: ["open-composer"]
520
+ },
521
+ composer: ({ text, url }) => withQuery("https://www.reddit.com/submit", {
522
+ title: text,
523
+ url
524
+ }),
525
+ count: shareKitCountLength,
526
+ hint: "Reddit takes a title and the link.",
527
+ id: "reddit",
528
+ images: [shareKitLandscapeFormat],
529
+ label: "Reddit",
530
+ limit: 300,
531
+ shape: "title"
532
+ };
533
+ const shareKitThreads = {
534
+ actions: {
535
+ desktop: ["open-composer"],
536
+ mobile: ["share-image", "open-composer"]
537
+ },
538
+ composer: ({ text }) => withQuery("https://www.threads.com/intent/post", { text }),
539
+ count: shareKitCountUtf8,
540
+ id: "threads",
541
+ images: [shareKitPortraitFormat],
542
+ label: "Threads",
543
+ limit: 500,
544
+ shape: "full"
545
+ };
546
+ const shareKitX = {
547
+ actions: {
548
+ desktop: ["open-composer"],
549
+ mobile: ["open-composer"]
550
+ },
551
+ composer: ({ text }) => withQuery("https://x.com/intent/tweet", { text }),
552
+ count: shareKitWithLinkCost(shareKitCountWeighted, fixedLinkCost),
553
+ id: "x",
554
+ images: [shareKitLandscapeFormat, shareKitPortraitFormat],
555
+ label: "X",
556
+ limit: 280,
557
+ shape: "full"
558
+ };
559
+ function getDestinationUrl(url, { id, utmSource = id }, utmMedium) {
560
+ if (!utmMedium || utmSource === false || !URL.canParse(url)) return url;
561
+ return withQuery(url, {
562
+ utm_medium: utmMedium,
563
+ utm_source: utmSource
564
+ });
565
+ }
566
+ function canRun(action, input) {
567
+ switch (action) {
568
+ case "copy-caption": return true;
569
+ case "open-composer": return Boolean(input.composerUrl);
570
+ case "share-image": return input.canShareFiles && input.hasSuggestedImage;
571
+ case "share-link":
572
+ case "share-text": return input.canShareText;
573
+ }
574
+ }
575
+ function getPrimaryAction(actions, input) {
576
+ return actions.find((action) => canRun(action, input)) ?? "copy-caption";
577
+ }
472
578
  // src/dom.ts
473
579
  function createElement(tag, attributes = {}, children = []) {
474
580
  const element = document.createElement(tag);
@@ -480,18 +586,31 @@ function joinClasses(...classes) {
480
586
  return classes.filter(Boolean).join(" ");
481
587
  }
482
588
  const svgNamespace = "http://www.w3.org/2000/svg";
483
- function createIcon(path, size) {
589
+ const iconSize = 24;
590
+ function createIcon(path) {
484
591
  const svg = document.createElementNS(svgNamespace, "svg");
485
592
  const shape = document.createElementNS(svgNamespace, "path");
486
593
  svg.setAttribute("aria-hidden", "true");
487
- svg.setAttribute("height", String(size));
594
+ svg.setAttribute("height", String(iconSize));
488
595
  svg.setAttribute("viewBox", "0 0 24 24");
489
- svg.setAttribute("width", String(size));
596
+ svg.setAttribute("width", String(iconSize));
490
597
  shape.setAttribute("d", path);
491
598
  shape.setAttribute("fill", "currentColor");
492
599
  svg.append(shape);
493
600
  return svg;
494
601
  }
602
+ function createIconSlot(name, path, fallback) {
603
+ return createElement("span", {
604
+ class: "share-kit-icon",
605
+ "data-share-kit-icon": name
606
+ }, [path ? createIcon(path) : fallback]);
607
+ }
608
+ function patchIcons(root, icons) {
609
+ for (const slot of root.querySelectorAll("[data-share-kit-icon]")) {
610
+ const path = slot.dataset.shareKitIcon ? icons[slot.dataset.shareKitIcon] : void 0;
611
+ if (path && !slot.querySelector("svg")) slot.replaceChildren(createIcon(path));
612
+ }
613
+ }
495
614
  function isOnBackdrop(dialog, event) {
496
615
  if (event.target !== dialog) return false;
497
616
  const rect = dialog.getBoundingClientRect();
@@ -569,61 +688,53 @@ var ShareFeedback = class {
569
688
  }, flashDurationMs);
570
689
  }
571
690
  };
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"
691
+ // src/icons.ts
692
+ const shareKitInterfaceIconNames = [
693
+ "close",
694
+ "more",
695
+ "qr"
696
+ ];
697
+ const shareKitInterfaceIcons = {
698
+ 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",
699
+ 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",
700
+ 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",
701
+ 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",
702
+ 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"
703
+ };
704
+ var ShareIconSource = class {
705
+ get icons() {
706
+ return this.#icons;
707
+ }
708
+ get isLoading() {
709
+ return !this.#isSettled;
710
+ }
711
+ #icons = {};
712
+ #isSettled = false;
713
+ #loader;
714
+ #pending;
715
+ constructor(option) {
716
+ if (typeof option === "function") {
717
+ this.#loader = option;
718
+ return;
719
+ }
720
+ this.#icons = option;
721
+ this.#isSettled = true;
722
+ }
723
+ load() {
724
+ if (!this.#pending) this.#pending = this.#load();
725
+ return this.#pending;
726
+ }
727
+ async #load() {
728
+ if (!this.#loader) return this.#icons;
729
+ try {
730
+ this.#icons = await this.#loader();
731
+ } catch (error) {
732
+ console.warn("share-kit: the icons loader failed, so the dialog keeps its text labels", error);
733
+ }
734
+ this.#isSettled = true;
735
+ return this.#icons;
736
+ }
620
737
  };
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
738
  // src/payload.ts
628
739
  function isPayload(value) {
629
740
  if (typeof value !== "object" || value === null) return false;
@@ -643,25 +754,42 @@ function readSharePayload(host) {
643
754
  return;
644
755
  }
645
756
  }
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
757
  function getIds(value) {
652
758
  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))
759
+ return [...new Set(value)];
760
+ }
761
+ function getDestinationLists({ destinations, destinationsMore }, catalogue) {
762
+ const unknown = [];
763
+ const resolve = (ids) => ids.flatMap((id) => {
764
+ const destination = typeof id === "string" ? catalogue.get(id) : void 0;
765
+ if (!destination) unknown.push(String(id));
766
+ return destination ? [destination] : [];
767
+ });
768
+ const shown = resolve(getIds(destinations));
769
+ const rest = resolve(getIds(destinationsMore)).filter((destination) => !shown.includes(destination));
770
+ if (unknown.length > 0) console.warn(`share-kit: unregistered destinations dropped: ${unknown.join(", ")}`);
771
+ if (shown.length > 0) return {
772
+ main: shown,
773
+ more: rest
774
+ };
775
+ if (rest.length > 0) return {
776
+ main: rest,
777
+ more: []
661
778
  };
779
+ console.warn("share-kit: no registered destinations to show");
780
+ }
781
+ function getShareAssets(assets) {
782
+ const seen = /* @__PURE__ */ new Set();
783
+ const kept = assets.filter((asset) => {
784
+ const id = asset.id;
785
+ if (typeof id !== "string" || id === "" || seen.has(id)) return false;
786
+ seen.add(id);
787
+ return true;
788
+ });
789
+ if (kept.length < assets.length) console.warn("share-kit: images with an empty or repeated id dropped");
790
+ return kept;
662
791
  }
663
792
  // src/qr.ts
664
- const iconSize = 24;
665
793
  const qrSize = 200;
666
794
  async function createQrSource(text) {
667
795
  const [{ generate }, { toSvgDataURL }] = await Promise.all([import("lean-qr"), import("lean-qr/extras/svg")]);
@@ -701,7 +829,7 @@ var ShareQrDialog = class {
701
829
  class: "share-kit-icon-button",
702
830
  title: strings.close,
703
831
  type: "submit"
704
- }, [closeIcon ? createIcon(closeIcon, iconSize) : "×"])]), this.#image]);
832
+ }, [createIconSlot("close", closeIcon, "×")])]), this.#image]);
705
833
  polyfillLightDismiss(this.dialog, signal);
706
834
  }
707
835
  async open() {
@@ -716,14 +844,74 @@ function getQrUrl(url, openHash) {
716
844
  return target.href;
717
845
  }
718
846
  function createShareQr({ capabilities, payload, ...input }) {
719
- if (capabilities.has("handheld")) return;
847
+ if (capabilities.has("mobile")) return;
720
848
  return new ShareQrDialog({
721
849
  ...input,
722
850
  url: getQrUrl(payload.url, payload.settings.openHash)
723
851
  });
724
852
  }
853
+ // src/strings.ts
854
+ const shareKitStringDefaults = {
855
+ assetCopy: "Copy",
856
+ assetSave: "Save",
857
+ assetShare: "Share",
858
+ captionCopy: "Copy caption",
859
+ captionOver: "{count} over the limit for {destination}",
860
+ captionReset: "Reset",
861
+ captionTitle: "Caption",
862
+ close: "Close",
863
+ copied: "Copied",
864
+ copyManual: "Couldn't copy. The caption is selected, so you can copy it yourself.",
865
+ destinationsMore: "More",
866
+ destinationsTitle: "Post to",
867
+ error: "Something went wrong. Try saving instead.",
868
+ imagesTitle: "Images",
869
+ linkCopy: "Copy link",
870
+ linkTitle: "Link",
871
+ primaryCopy: "Copy caption",
872
+ primaryOpen: "Open {destination}",
873
+ primaryShareImage: "Share image",
874
+ primaryShareLink: "Share link",
875
+ primaryShareText: "Share",
876
+ qrAlt: "QR code for this page",
877
+ qrTitle: "Scan to continue on your phone",
878
+ qrToggle: "Continue on your phone",
879
+ retry: "Ready. Tap again to share.",
880
+ saved: "Saved",
881
+ saveError: "Couldn't save. Try again.",
882
+ suggested: "Suggested",
883
+ title: "Share this page"
884
+ };
885
+ const destinationStringPattern = /^(?:destination|hint)\.(.+)$/u;
886
+ function isShareStringKey(key) {
887
+ return Object.hasOwn(shareKitStringDefaults, key);
888
+ }
889
+ function isDestinationStringKey(key, ids) {
890
+ const id = destinationStringPattern.exec(key)?.[1];
891
+ return id !== void 0 && ids.has(id);
892
+ }
893
+ function getShareStrings(overrides, ids) {
894
+ const strings = { ...shareKitStringDefaults };
895
+ for (const [key, value] of Object.entries(overrides)) {
896
+ if (typeof value !== "string") continue;
897
+ if (isShareStringKey(key) || isDestinationStringKey(key, ids)) strings[key] = value;
898
+ }
899
+ return strings;
900
+ }
901
+ function getDestinationLabel(strings, { id, label }) {
902
+ return strings[`destination.${id}`] ?? label;
903
+ }
904
+ function getDestinationHint(strings, { hint, id }) {
905
+ return strings[`hint.${id}`] ?? hint;
906
+ }
907
+ function formatShareString(template, values) {
908
+ return template.replaceAll(/\{(\w+)\}/gu, (match, name) => values[name] ?? match);
909
+ }
725
910
  // src/render.ts
726
- const destinationIconSize = 24;
911
+ function renderDestinationIcon({ icons, isIconsLoading }, name) {
912
+ const path = icons[name];
913
+ return path || isIconsLoading ? createIconSlot(name, path) : void 0;
914
+ }
727
915
  function renderAction({ classNames }, { action, describedBy, label }) {
728
916
  return createElement("button", {
729
917
  "aria-describedby": describedBy,
@@ -738,7 +926,7 @@ function renderHeading({ classNames }, children, id) {
738
926
  id
739
927
  }, children);
740
928
  }
741
- function renderIconButton({ action, attributes, fallback, icon, label }) {
929
+ function renderIconButton({ icons }, { action, attributes, fallback, icon, label }) {
742
930
  return createElement("button", {
743
931
  ...attributes,
744
932
  "aria-label": label,
@@ -746,52 +934,51 @@ function renderIconButton({ action, attributes, fallback, icon, label }) {
746
934
  "data-share-kit-action": action,
747
935
  title: label,
748
936
  type: "button"
749
- }, [icon ? createIcon(icon, destinationIconSize) : fallback]);
937
+ }, [createIconSlot(icon, icons[icon], fallback)]);
750
938
  }
751
939
  function renderHeader(context) {
752
- const { capabilities, icons, id, strings } = context;
940
+ const { capabilities, id, strings } = context;
753
941
  const heading = createElement("h2", {
754
942
  class: "share-kit-title",
755
943
  id: `${id}-title`,
756
944
  tabindex: "-1"
757
945
  }, [strings.title]);
758
946
  return {
759
- header: createElement("header", { class: "share-kit-header" }, [heading, createElement("div", { class: "share-kit-header-actions" }, [capabilities.has("handheld") ? void 0 : renderIconButton({
947
+ header: createElement("header", { class: "share-kit-header" }, [heading, createElement("div", { class: "share-kit-header-actions" }, [capabilities.has("mobile") ? void 0 : renderIconButton(context, {
760
948
  action: "qr",
761
949
  attributes: { "aria-haspopup": "dialog" },
762
950
  fallback: "QR",
763
- icon: icons.qr,
951
+ icon: "qr",
764
952
  label: strings.qrToggle
765
- }), renderIconButton({
953
+ }), renderIconButton(context, {
766
954
  action: "close",
767
955
  fallback: "×",
768
- icon: icons.close,
956
+ icon: "close",
769
957
  label: strings.close
770
958
  })])]),
771
959
  heading
772
960
  };
773
961
  }
774
962
  function renderDestination(context, destination) {
775
- const { classNames, icons, strings } = context;
776
- const icon = icons[destination];
963
+ const { classNames, strings } = context;
777
964
  return createElement("button", {
778
965
  "aria-checked": "false",
779
966
  class: joinClasses("share-kit-destination", classNames.destination),
780
967
  "data-share-kit-action": "destination",
781
- "data-share-kit-destination": destination,
968
+ "data-share-kit-destination": destination.id,
782
969
  role: "radio",
783
970
  tabindex: "-1",
784
971
  type: "button"
785
- }, [icon ? createIcon(icon, destinationIconSize) : void 0, createElement("span", {}, [strings[`destination.${destination}`]])]);
972
+ }, [renderDestinationIcon(context, destination.id), createElement("span", {}, [getDestinationLabel(strings, destination)])]);
786
973
  }
787
974
  function renderDestinations(context) {
788
- const { destinations, destinationsMore, icons, id, strings } = context;
975
+ const { destinations, destinationsMore, id, strings } = context;
789
976
  const headingId = `${id}-destinations`;
790
977
  const more = destinationsMore.length > 0 ? createElement("button", {
791
978
  class: joinClasses("share-kit-destination", context.classNames.destination),
792
979
  "data-share-kit-action": "more",
793
980
  type: "button"
794
- }, [icons.more ? createIcon(icons.more, destinationIconSize) : void 0, createElement("span", {}, [strings.destinationsMore])]) : void 0;
981
+ }, [renderDestinationIcon(context, "more"), createElement("span", {}, [strings.destinationsMore])]) : void 0;
795
982
  const extra = destinationsMore.map((destination) => {
796
983
  const button = renderDestination(context, destination);
797
984
  button.hidden = true;
@@ -848,14 +1035,13 @@ function renderCaption(context) {
848
1035
  ])
849
1036
  };
850
1037
  }
851
- function renderTile(context, { actions, asset, key }) {
852
- const labelId = `${context.id}-asset-${key}`;
1038
+ function renderTile(context, { actions, asset, index }) {
1039
+ const labelId = `${context.id}-asset-${String(index)}`;
853
1040
  const badge = createElement("span", { class: "share-kit-badge" }, [context.strings.suggested]);
854
1041
  badge.hidden = true;
855
1042
  return createElement("li", {
856
1043
  class: "share-kit-tile",
857
- "data-share-kit-asset": key,
858
- "data-share-kit-role": asset.role
1044
+ "data-share-kit-asset": asset.id
859
1045
  }, [
860
1046
  createElement("img", {
861
1047
  alt: asset.alt,
@@ -878,25 +1064,19 @@ function getAssetActions({ capabilities, strings }) {
878
1064
  const actions = [];
879
1065
  const canShare = capabilities.has("files");
880
1066
  if (canShare) actions.push(["share", strings.assetShare]);
881
- if (capabilities.has("copy-image") && !(canShare && capabilities.has("handheld"))) actions.push(["copy", strings.assetCopy]);
1067
+ if (capabilities.has("copy-image") && !(canShare && capabilities.has("mobile"))) actions.push(["copy", strings.assetCopy]);
882
1068
  actions.push(["save", strings.assetSave]);
883
1069
  return actions;
884
1070
  }
885
1071
  function renderImages(context) {
886
1072
  const { payload, strings } = context;
887
1073
  const actions = getAssetActions(context);
888
- const counts = /* @__PURE__ */ new Map();
889
1074
  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
- }
1075
+ for (const [index, asset] of payload.assets.entries()) assets.set(renderTile(context, {
1076
+ actions,
1077
+ asset,
1078
+ index
1079
+ }), asset);
900
1080
  const grid = createElement("ul", { class: "share-kit-grid" }, [...assets.keys()]);
901
1081
  return {
902
1082
  assets,
@@ -967,15 +1147,11 @@ const primaryLabels = {
967
1147
  "share-link": "primaryShareLink",
968
1148
  "share-text": "primaryShareText"
969
1149
  };
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
1150
  function syncCaptionView({ destination, parts, primaryAction, strings }) {
975
- const { limit } = getShareDestination(destination);
976
- const count = countCaption(parts.caption.value, destination);
1151
+ const { limit } = destination;
1152
+ const count = destination.count(parts.caption.value);
977
1153
  const isOver = limit !== void 0 && count > limit;
978
- const label = strings[`destination.${destination}`];
1154
+ const label = getDestinationLabel(strings, destination);
979
1155
  parts.count.textContent = limit === void 0 ? String(count) : `${String(count)} / ${String(limit)}`;
980
1156
  parts.count.toggleAttribute("data-share-kit-over", isOver);
981
1157
  parts.caption.setAttribute("aria-invalid", String(isOver));
@@ -991,12 +1167,11 @@ function syncCaptionView({ destination, parts, primaryAction, strings }) {
991
1167
  }
992
1168
  function syncDestinationView({ assets, destination, parts, strings, suggested }) {
993
1169
  for (const radio of parts.dialog.querySelectorAll("[role=\"radio\"]")) {
994
- const isSelected = radio.dataset.shareKitDestination === destination;
1170
+ const isSelected = radio.dataset.shareKitDestination === destination.id;
995
1171
  radio.setAttribute("aria-checked", String(isSelected));
996
1172
  radio.tabIndex = isSelected ? 0 : -1;
997
1173
  }
998
- const hintKey = `hint.${destination}`;
999
- parts.hint.textContent = isShareStringKey(hintKey) ? strings[hintKey] : "";
1174
+ parts.hint.textContent = getDestinationHint(strings, destination) ?? "";
1000
1175
  parts.hint.hidden = parts.hint.textContent === "";
1001
1176
  for (const asset of assets) {
1002
1177
  const badge = asset.querySelector(".share-kit-badge");
@@ -1008,6 +1183,11 @@ function syncDestinationView({ assets, destination, parts, strings, suggested })
1008
1183
  // src/types.ts
1009
1184
  const shareKitActionEventName = "share-kit:action";
1010
1185
  // src/element.ts
1186
+ const iconIntentEvents = [
1187
+ "focusin",
1188
+ "pointerdown",
1189
+ "pointerover"
1190
+ ];
1011
1191
  const outcomeMessages = {
1012
1192
  error: "error",
1013
1193
  retry: "retry",
@@ -1020,7 +1200,8 @@ function isKeyOf(record, key) {
1020
1200
  }
1021
1201
  const BaseElement = typeof HTMLElement === "undefined" ? Object : HTMLElement;
1022
1202
  var ShareKitElement = class extends BaseElement {
1023
- icons = {};
1203
+ catalogue = /* @__PURE__ */ new Map();
1204
+ iconSource = new ShareIconSource({});
1024
1205
  #abortController;
1025
1206
  #actions = {
1026
1207
  close: () => {
@@ -1040,9 +1221,9 @@ var ShareKitElement = class extends BaseElement {
1040
1221
  this.#feedback?.copyText(this.#payload?.url ?? "", button);
1041
1222
  },
1042
1223
  destination: (button) => {
1043
- const id = button.dataset.shareKitDestination;
1044
- if (!id || !isShareDestinationId(id)) return;
1045
- this.#selectDestination(id);
1224
+ const destination = this.#getRendered(button.dataset.shareKitDestination);
1225
+ if (!destination) return;
1226
+ this.#selectDestination(destination);
1046
1227
  this.#track("destination");
1047
1228
  },
1048
1229
  more: (button) => {
@@ -1066,11 +1247,13 @@ var ShareKitElement = class extends BaseElement {
1066
1247
  }
1067
1248
  };
1068
1249
  #capabilities = /* @__PURE__ */ new Set();
1069
- #destination = "any";
1250
+ #destination;
1070
1251
  #feedback;
1071
1252
  #files;
1072
1253
  #isCaptionEdited = false;
1254
+ #isIconsRequested = false;
1073
1255
  #isOver = false;
1256
+ #lists;
1074
1257
  #parts;
1075
1258
  #payload;
1076
1259
  #primaryActions = {
@@ -1079,11 +1262,11 @@ var ShareKitElement = class extends BaseElement {
1079
1262
  this.#copyCaption();
1080
1263
  },
1081
1264
  "open-composer": () => {
1082
- const url = this.#getComposerUrl();
1083
- if (!url) return;
1265
+ const href = this.#getComposerUrl();
1266
+ if (!href) return;
1084
1267
  this.#track("open-composer");
1085
1268
  this.#copyCaption();
1086
- window.open(url, "_blank", "noopener");
1269
+ openComposer(href);
1087
1270
  },
1088
1271
  "share-image": () => {
1089
1272
  const tile = this.#getSuggestedAsset();
@@ -1109,9 +1292,15 @@ var ShareKitElement = class extends BaseElement {
1109
1292
  this.#retryWhenParsed();
1110
1293
  return;
1111
1294
  }
1295
+ const lists = getDestinationLists(payload.settings, this.catalogue);
1296
+ if (!lists) return;
1112
1297
  this.#abortController = new AbortController();
1113
- this.#payload = payload;
1114
- this.#strings = getShareStrings(payload.strings);
1298
+ this.#lists = lists;
1299
+ this.#payload = {
1300
+ ...payload,
1301
+ assets: getShareAssets(payload.assets)
1302
+ };
1303
+ this.#strings = getShareStrings(payload.strings ?? {}, new Set(this.catalogue.keys()));
1115
1304
  this.#feedback = new ShareFeedback(() => this.#parts?.status, this.#strings);
1116
1305
  const { signal } = this.#abortController;
1117
1306
  this.#capabilities = new Set(getShareCapabilities(this.dataset.can));
@@ -1128,6 +1317,7 @@ var ShareKitElement = class extends BaseElement {
1128
1317
  signal
1129
1318
  });
1130
1319
  this.addEventListener("pointerover", ({ target }) => this.#files?.warm(target), { signal });
1320
+ for (const type of iconIntentEvents) this.addEventListener(type, this.#handleTriggerIntent, { signal });
1131
1321
  window.addEventListener("hashchange", this.#handleHashChange, { signal });
1132
1322
  this.querySelector("[data-share-kit-trigger]")?.toggleAttribute("disabled", false);
1133
1323
  queueMicrotask(() => {
@@ -1144,8 +1334,10 @@ var ShareKitElement = class extends BaseElement {
1144
1334
  this.#feedback = void 0;
1145
1335
  this.#files?.dispose();
1146
1336
  this.#files = void 0;
1147
- this.#destination = "any";
1337
+ this.#destination = void 0;
1338
+ this.#lists = void 0;
1148
1339
  this.#isCaptionEdited = false;
1340
+ this.#isIconsRequested = false;
1149
1341
  this.#isOver = false;
1150
1342
  }
1151
1343
  async #copyCaption(button) {
@@ -1157,31 +1349,51 @@ var ShareKitElement = class extends BaseElement {
1157
1349
  }
1158
1350
  #getComposerUrl() {
1159
1351
  const parts = this.#parts;
1160
- if (!parts) return;
1352
+ const payload = this.#payload;
1353
+ const composer = this.#destination?.composer;
1354
+ if (!parts || !payload || !composer) return;
1161
1355
  const suggested = this.#getSuggestedAsset();
1162
1356
  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,
1357
+ return composer({
1358
+ ...payload.description === void 0 ? {} : { description: payload.description },
1359
+ device: this.#getDevice(),
1360
+ ...media === void 0 ? {} : { media: new URL(media, location.href).href },
1165
1361
  text: parts.caption.value,
1362
+ title: payload.title,
1166
1363
  url: this.#getUrl()
1167
1364
  });
1168
1365
  }
1366
+ #getDevice() {
1367
+ return this.#capabilities.has("mobile") ? "mobile" : "desktop";
1368
+ }
1169
1369
  #getPrimaryAction() {
1170
- return getPrimaryAction({
1171
- canShareFiles: this.#capabilities.has("files") && this.#getSuggestedAsset() !== void 0,
1370
+ const destination = this.#destination;
1371
+ if (!destination) return "copy-caption";
1372
+ return getPrimaryAction(destination.actions[this.#getDevice()], {
1373
+ canShareFiles: this.#capabilities.has("files"),
1172
1374
  canShareText: this.#capabilities.has("link"),
1173
- hasComposerUrl: this.#getComposerUrl() !== void 0,
1174
- id: this.#destination,
1175
- isHandheld: this.#capabilities.has("handheld")
1375
+ composerUrl: this.#getComposerUrl(),
1376
+ hasSuggestedImage: this.#getSuggestedAsset() !== void 0
1176
1377
  });
1177
1378
  }
1379
+ #getRendered(id) {
1380
+ const lists = this.#lists;
1381
+ if (!id || !lists) return;
1382
+ return [...lists.main, ...lists.more].find((destination) => destination.id === id);
1383
+ }
1178
1384
  #getSuggestedAsset() {
1179
- return getSuggestedAsset(this.#getAssets(), this.#destination);
1385
+ const parts = this.#parts;
1386
+ const destination = this.#destination;
1387
+ if (!parts || !destination) return;
1388
+ const tiles = this.#getAssets();
1389
+ const suggested = getSuggestedImage(tiles.flatMap((tile) => parts.assets.get(tile) ?? []), destination.images);
1390
+ return tiles.find((tile) => parts.assets.get(tile) === suggested);
1180
1391
  }
1181
1392
  #getUrl() {
1182
1393
  const payload = this.#payload;
1183
- if (!payload) return "";
1184
- return getDestinationUrl(payload.url, this.#destination, payload.settings.utmMedium);
1394
+ const destination = this.#destination;
1395
+ if (!payload || !destination) return payload?.url ?? "";
1396
+ return getDestinationUrl(payload.url, destination, payload.settings.utmMedium);
1185
1397
  }
1186
1398
  #handleClick = (event) => {
1187
1399
  if (!(event.target instanceof Element)) return;
@@ -1209,10 +1421,10 @@ var ShareKitElement = class extends BaseElement {
1209
1421
  if (!move || !(event.target instanceof HTMLElement) || event.target.role !== "radio") return;
1210
1422
  const radios = [...this.querySelectorAll("[role=\"radio\"]:not([hidden])")];
1211
1423
  const next = radios[move(radios.indexOf(event.target), radios.length)];
1212
- const id = next?.dataset.shareKitDestination;
1213
- if (!next || !id || !isShareDestinationId(id)) return;
1424
+ const destination = this.#getRendered(next?.dataset.shareKitDestination);
1425
+ if (!next || !destination) return;
1214
1426
  event.preventDefault();
1215
- this.#selectDestination(id);
1427
+ this.#selectDestination(destination);
1216
1428
  next.focus();
1217
1429
  };
1218
1430
  #handlePreviewError = (event) => {
@@ -1222,7 +1434,19 @@ var ShareKitElement = class extends BaseElement {
1222
1434
  tile.dataset.shareKitState = "failed";
1223
1435
  this.#syncDestination();
1224
1436
  };
1437
+ #handleTriggerIntent = ({ target }) => {
1438
+ if (target instanceof Element && target.closest("[data-share-kit-trigger]")) this.#loadIcons();
1439
+ };
1440
+ #loadIcons() {
1441
+ const signal = this.#abortController?.signal;
1442
+ if (!signal || this.#isIconsRequested) return;
1443
+ this.#isIconsRequested = true;
1444
+ this.iconSource.load().then((icons) => {
1445
+ if (!signal.aborted && this.#parts) patchIcons(this.#parts.dialog, icons);
1446
+ });
1447
+ }
1225
1448
  #open() {
1449
+ this.#loadIcons();
1226
1450
  const parts = this.#parts ?? this.#render();
1227
1451
  if (!parts || parts.dialog.open) return;
1228
1452
  parts.dialog.showModal();
@@ -1240,29 +1464,32 @@ var ShareKitElement = class extends BaseElement {
1240
1464
  }
1241
1465
  }
1242
1466
  #prefetch() {
1243
- if (!this.#capabilities.has("files") || !this.#capabilities.has("handheld")) return;
1467
+ if (!this.#capabilities.has("files") || !this.#capabilities.has("mobile")) return;
1244
1468
  const tile = this.#getSuggestedAsset();
1245
1469
  if (tile) this.#files?.load(tile);
1246
1470
  }
1247
1471
  #render() {
1248
1472
  const payload = this.#payload;
1473
+ const lists = this.#lists;
1249
1474
  const signal = this.#abortController?.signal;
1250
- if (!payload || !signal) return;
1251
- const { main, more } = getDestinationLists(payload.settings);
1475
+ if (!payload || !lists || !signal) return;
1476
+ const { main, more } = lists;
1477
+ const { icons, isLoading } = this.iconSource;
1252
1478
  dialogCount += 1;
1253
1479
  const id = `share-kit-${String(dialogCount)}`;
1254
1480
  const parts = renderShareKit({
1255
1481
  capabilities: this.#capabilities,
1256
1482
  destinations: main,
1257
1483
  destinationsMore: more,
1258
- icons: this.icons,
1484
+ icons,
1259
1485
  id,
1486
+ isIconsLoading: isLoading,
1260
1487
  payload,
1261
1488
  strings: this.#strings
1262
1489
  });
1263
1490
  this.#qr = createShareQr({
1264
1491
  capabilities: this.#capabilities,
1265
- closeIcon: this.icons.close,
1492
+ closeIcon: icons.close,
1266
1493
  id: `${id}-qr`,
1267
1494
  payload,
1268
1495
  signal,
@@ -1273,7 +1500,7 @@ var ShareKitElement = class extends BaseElement {
1273
1500
  polyfillLightDismiss(parts.dialog, signal);
1274
1501
  this.append(parts.dialog);
1275
1502
  this.#parts = parts;
1276
- this.#destination = main[0] ?? "any";
1503
+ this.#destination = main[0];
1277
1504
  this.#syncDestination();
1278
1505
  return parts;
1279
1506
  }
@@ -1290,10 +1517,10 @@ var ShareKitElement = class extends BaseElement {
1290
1517
  this.#track("save", tile);
1291
1518
  this.#report(await this.#files?.save(tile));
1292
1519
  }
1293
- #selectDestination(id) {
1520
+ #selectDestination(destination) {
1294
1521
  const previousUrl = this.#getUrl();
1295
1522
  const caption = this.#parts?.caption;
1296
- this.#destination = id;
1523
+ this.#destination = destination;
1297
1524
  if (caption && this.#isCaptionEdited) {
1298
1525
  const url = this.#getUrl();
1299
1526
  caption.value = caption.value.replaceAll(previousUrl, () => url);
@@ -1322,9 +1549,10 @@ var ShareKitElement = class extends BaseElement {
1322
1549
  }
1323
1550
  #syncCaption() {
1324
1551
  const parts = this.#parts;
1325
- if (!parts) return;
1552
+ const destination = this.#destination;
1553
+ if (!parts || !destination) return;
1326
1554
  const { isOver, message } = syncCaptionView({
1327
- destination: this.#destination,
1555
+ destination,
1328
1556
  parts,
1329
1557
  primaryAction: this.#getPrimaryAction(),
1330
1558
  strings: this.#strings
@@ -1335,10 +1563,11 @@ var ShareKitElement = class extends BaseElement {
1335
1563
  #syncDestination() {
1336
1564
  const parts = this.#parts;
1337
1565
  const payload = this.#payload;
1338
- if (!parts || !payload) return;
1566
+ const destination = this.#destination;
1567
+ if (!parts || !payload || !destination) return;
1339
1568
  syncDestinationView({
1340
1569
  assets: this.#getAssets(),
1341
- destination: this.#destination,
1570
+ destination,
1342
1571
  parts,
1343
1572
  strings: this.#strings,
1344
1573
  suggested: this.#getSuggestedAsset()
@@ -1347,14 +1576,15 @@ var ShareKitElement = class extends BaseElement {
1347
1576
  description: payload.description,
1348
1577
  title: payload.title,
1349
1578
  url: this.#getUrl()
1350
- }, this.#destination, payload.locale).text;
1579
+ }, destination, payload.locale).text;
1351
1580
  this.#syncCaption();
1352
1581
  this.#prefetch();
1353
1582
  }
1354
1583
  #track(action, tile) {
1584
+ if (!this.#destination) return;
1355
1585
  const detail = {
1356
1586
  action,
1357
- destination: this.#destination
1587
+ destination: this.#destination.id
1358
1588
  };
1359
1589
  if (tile?.dataset.shareKitAsset) detail.asset = tile.dataset.shareKitAsset;
1360
1590
  this.dispatchEvent(new CustomEvent(shareKitActionEventName, {
@@ -1366,20 +1596,41 @@ var ShareKitElement = class extends BaseElement {
1366
1596
  };
1367
1597
  // src/define.ts
1368
1598
  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
- });
1599
+ const reservedIds = new Set(shareKitInterfaceIconNames);
1600
+ function getCatalogue(destinations) {
1601
+ const catalogue = /* @__PURE__ */ new Map();
1602
+ for (const destination of destinations) {
1603
+ if (reservedIds.has(destination.id) || catalogue.has(destination.id)) {
1604
+ console.error(`share-kit: destination id "${destination.id}" is repeated or reserved for an icon, so <share-kit> is not defined`);
1605
+ return;
1606
+ }
1607
+ catalogue.set(destination.id, destination);
1608
+ }
1609
+ return catalogue;
1374
1610
  }
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 };
1611
+ function warnMissingComposers(destinations) {
1612
+ 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`);
1613
+ }
1614
+ function createElementClass(catalogue, iconSource) {
1615
+ return class extends ShareKitElement {
1616
+ catalogue = catalogue;
1617
+ iconSource = iconSource;
1618
+ };
1619
+ }
1620
+ function defineShareKit({ destinations, icons = {} }) {
1621
+ if (customElements.get(tagName)) {
1622
+ console.warn("share-kit: <share-kit> is already defined, so this defineShareKit call is ignored");
1623
+ return;
1624
+ }
1625
+ if (destinations.length === 0) {
1626
+ console.error("share-kit: no destinations registered, so <share-kit> is not defined");
1627
+ return;
1628
+ }
1629
+ const catalogue = getCatalogue(destinations);
1630
+ if (!catalogue) return;
1631
+ warnMissingComposers(destinations);
1632
+ customElements.define(tagName, createElementClass(catalogue, new ShareIconSource(icons)));
1633
+ }
1634
+ export { defineShareKit, defineShareKitDestination, getShareKitImageFormats, serializeShareKitPayload, shareKitActionEventName, shareKitAnywhere, shareKitBluesky, shareKitCountGraphemes, shareKitCountLength, shareKitCountStringz, shareKitCountUtf8, shareKitCountWeighted, shareKitFacebook, shareKitInstagram, shareKitInstagramStory, shareKitInterfaceIcons, shareKitLandscapeFormat, shareKitLinkedin, shareKitMastodon, shareKitMessages, shareKitPinFormat, shareKitPinterest, shareKitPortraitFormat, shareKitReddit, shareKitShortenedLinkCost, shareKitStoryFormat, shareKitThreads, shareKitWithLinkCost, shareKitX };
1384
1635
 
1385
1636
  //# sourceMappingURL=index.mjs.map