react-smart-copy 1.13.1 → 1.14.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/link.cjs ADDED
@@ -0,0 +1,651 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/core/errors.ts
3
+ function createCopyError(type, message, cause) {
4
+ return cause === void 0 ? {
5
+ type,
6
+ message
7
+ } : {
8
+ type,
9
+ message,
10
+ cause
11
+ };
12
+ }
13
+ /**
14
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
15
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
16
+ */
17
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
18
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
19
+ var CopyFailure = class extends Error {
20
+ constructor(copyError) {
21
+ super(copyError.message);
22
+ this[COPY_FAILURE_BRAND] = true;
23
+ this.name = "CopyFailure";
24
+ this.copyError = copyError;
25
+ }
26
+ };
27
+ /** Shorthand for throwing a classified failure. */
28
+ function copyFailure(type, message, cause) {
29
+ return new CopyFailure(createCopyError(type, message, cause));
30
+ }
31
+ //#endregion
32
+ //#region src/link/url.ts
33
+ /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
34
+ const DEFAULT_LINK_PROTOCOLS = Object.freeze([
35
+ "https:",
36
+ "http:",
37
+ "mailto:",
38
+ "tel:"
39
+ ]);
40
+ /**
41
+ * Query parameters that only track where a click came from: the defaults of
42
+ * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
43
+ */
44
+ const TRACKING_PARAMETERS = Object.freeze([
45
+ "utm_",
46
+ "fbclid",
47
+ "gclid",
48
+ "gclsrc",
49
+ "dclid",
50
+ "gbraid",
51
+ "wbraid",
52
+ "msclkid",
53
+ "yclid",
54
+ "twclid",
55
+ "ttclid",
56
+ "li_fat_id",
57
+ "igshid",
58
+ "igsh",
59
+ "mc_cid",
60
+ "mc_eid",
61
+ "_hsenc",
62
+ "_hsmi",
63
+ "mkt_tok",
64
+ "oly_anon_id",
65
+ "oly_enc_id",
66
+ "vero_id",
67
+ "wickedid",
68
+ "_gl"
69
+ ]);
70
+ const invalid$2 = (message) => copyFailure("invalid-payload", message);
71
+ function baseUrl(base) {
72
+ if (base !== void 0) {
73
+ if (typeof base === "string" || base instanceof URL) return String(base);
74
+ throw invalid$2("`base` must be a string or a URL.");
75
+ }
76
+ return typeof location === "undefined" ? void 0 : location.href;
77
+ }
78
+ function protocolSet(protocols) {
79
+ const list = protocols ?? DEFAULT_LINK_PROTOCOLS;
80
+ const valid = (protocol) => typeof protocol === "string" && /^[a-z][a-z\d+.-]*:$/i.test(protocol);
81
+ if (!Array.isArray(list) || list.length === 0 || !list.every(valid)) throw invalid$2("`protocols` must be a non-empty list of schemes with their colon, like \"https:\".");
82
+ return new Set(list.map((protocol) => protocol.toLowerCase()));
83
+ }
84
+ function matcher(params) {
85
+ const list = params ?? TRACKING_PARAMETERS;
86
+ if (!Array.isArray(list) || !list.every((param) => typeof param === "string" || param instanceof RegExp)) throw invalid$2("`clean.params` must be a list of strings and regular expressions.");
87
+ return (name) => {
88
+ const lower = name.toLowerCase();
89
+ return list.some((param) => {
90
+ if (typeof param !== "string") return new RegExp(param.source, param.flags.replace(/[gy]/g, "")).test(name);
91
+ const wanted = param.toLowerCase();
92
+ return wanted.endsWith("_") ? lower.startsWith(wanted) : lower === wanted;
93
+ });
94
+ };
95
+ }
96
+ /** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */
97
+ function cleaner(option) {
98
+ const cleaning = option ?? false;
99
+ if (cleaning === false) return null;
100
+ if (cleaning !== true && (typeof cleaning !== "object" || cleaning === null)) throw invalid$2("`clean` must be a boolean or an options object.");
101
+ const settings = cleaning === true ? {} : cleaning;
102
+ const tracking = matcher(settings.params);
103
+ const keep = settings.keep ?? [];
104
+ if (!Array.isArray(keep) || !keep.every((name) => typeof name === "string")) throw invalid$2("`clean.keep` must be a list of strings.");
105
+ const kept = new Set(keep.map((name) => name.toLowerCase()));
106
+ return (url) => {
107
+ for (const name of [...new Set(url.searchParams.keys())]) if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);
108
+ };
109
+ }
110
+ /**
111
+ * Validates `options` once (throwing a typed `invalid-payload` error for invalid
112
+ * ones) and returns a resolver that throws only for invalid links.
113
+ * @internal
114
+ */
115
+ function linkUrlResolver(options = {}) {
116
+ const protocols = protocolSet(options.protocols);
117
+ const base = baseUrl(options.base);
118
+ const clean = cleaner(options.clean);
119
+ return (input) => {
120
+ if (typeof input !== "string" && !(input instanceof URL)) throw invalid$2("A link must be a string or a URL.");
121
+ const raw = String(input).trim();
122
+ if (raw === "") throw invalid$2("A link must not be empty.");
123
+ let url;
124
+ try {
125
+ url = new URL(raw, base);
126
+ } catch (cause) {
127
+ throw copyFailure("invalid-payload", `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);
128
+ }
129
+ if (!protocols.has(url.protocol)) throw invalid$2(`Links with the scheme "${url.protocol}" are not allowed (allowed: ${[...protocols].join(", ")}).`);
130
+ url.username = "";
131
+ url.password = "";
132
+ clean?.(url);
133
+ return url.href;
134
+ };
135
+ }
136
+ /**
137
+ * The link as an absolute, safe URL string, or a typed `invalid-payload` error:
138
+ * relative links are resolved, the scheme must be allowed, user names and
139
+ * passwords are always removed, and tracking parameters optionally.
140
+ */
141
+ function resolveLinkUrl(input, options = {}) {
142
+ return linkUrlResolver(options)(input);
143
+ }
144
+ /**
145
+ * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping
146
+ * everything else, including the fragment. Also validates it like every link here.
147
+ *
148
+ * @example
149
+ * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'
150
+ */
151
+ function cleanLinkUrl(url, options = {}) {
152
+ const { params, keep, ...rest } = options;
153
+ return resolveLinkUrl(url, {
154
+ ...rest,
155
+ clean: {
156
+ ...params === void 0 ? {} : { params },
157
+ ...keep === void 0 ? {} : { keep }
158
+ }
159
+ });
160
+ }
161
+ //#endregion
162
+ //#region src/link/payload.ts
163
+ const DEFAULT_LINK_TITLE_LENGTH = 300;
164
+ const invalid$1 = (message) => copyFailure("invalid-payload", message);
165
+ /**
166
+ * Characters a title never keeps: controls, bidi overrides and isolates (which can
167
+ * make a title read differently), and zero-width characters.
168
+ */
169
+ const HIDDEN = /[\0-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u061C\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
170
+ /** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */
171
+ function cleanTitle(title, maxLength) {
172
+ const clean = title.replace(HIDDEN, "").replace(/\s+/g, " ").trim();
173
+ if (clean.length <= maxLength) return clean;
174
+ return `${Array.from(clean).slice(0, maxLength - 1).join("").trimEnd()}\u2026`;
175
+ }
176
+ function maxTitle(value) {
177
+ if (value === void 0) return 300;
178
+ if (Number.isInteger(value) && value >= 1) return value;
179
+ throw invalid$1(`\`maxTitleLength\` must be a positive integer (received ${String(value)}).`);
180
+ }
181
+ function isAnchor(source) {
182
+ return typeof source === "object" && source !== null && source.nodeName === "A" && typeof source.href === "string";
183
+ }
184
+ /**
185
+ * Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.
186
+ * An `<a>` element gives its `href` and its text (or `title` attribute).
187
+ */
188
+ function resolveLink(source, options = {}) {
189
+ let url;
190
+ let title;
191
+ if (typeof source === "string" || source instanceof URL) url = source;
192
+ else if (isAnchor(source)) {
193
+ url = source.getAttribute("href") ?? "";
194
+ title = source.textContent.trim() !== "" ? source.textContent : source.getAttribute("title") ?? void 0;
195
+ if (url !== "" && options.base === void 0) url = source.href;
196
+ } else if (typeof source === "object" && source !== null && "url" in source) {
197
+ url = source.url;
198
+ title = source.title;
199
+ } else throw invalid$1("A link must be a URL, a { url, title } object or an <a> element.");
200
+ if (title !== void 0 && typeof title !== "string") throw invalid$1("A link title must be a string.");
201
+ const href = resolveLinkUrl(url, options);
202
+ const clean = title === void 0 ? "" : cleanTitle(title, maxTitle(options.maxTitleLength));
203
+ return {
204
+ url: href,
205
+ title: clean === "" ? href : clean,
206
+ titled: clean !== ""
207
+ };
208
+ }
209
+ const escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
210
+ /** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */
211
+ function markdownLink(link) {
212
+ return `[${link.title.replace(/[\\[\]]/g, "\\$&")}](${link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)})`;
213
+ }
214
+ function plainText(link, format) {
215
+ switch (format) {
216
+ case "url": return link.url;
217
+ case "title": return link.title;
218
+ case "title-and-url": return link.titled ? `${link.title}\n${link.url}` : link.url;
219
+ case "markdown": return markdownLink(link);
220
+ default: throw invalid$1(`\`text\` must be "url", "title", "title-and-url" or "markdown" (received ${JSON.stringify(format)}).`);
221
+ }
222
+ }
223
+ function linkPayload(source, options = {}) {
224
+ const target = options.target ?? "clipboard";
225
+ if (target !== "drag" && target !== "clipboard") throw invalid$1("`target` must be \"clipboard\" or \"drag\".");
226
+ const link = resolveLink(source, options);
227
+ const text = plainText(link, options.text ?? "url");
228
+ const html = `<a href="${escapeHtml(link.url)}">${escapeHtml(link.title)}</a>`;
229
+ if (target === "clipboard") return {
230
+ kind: "html",
231
+ html,
232
+ text
233
+ };
234
+ return {
235
+ kind: "multi",
236
+ items: [
237
+ {
238
+ mimeType: "text/plain",
239
+ data: text
240
+ },
241
+ {
242
+ mimeType: "text/html",
243
+ data: html
244
+ },
245
+ {
246
+ mimeType: "text/uri-list",
247
+ data: link.url,
248
+ optional: true
249
+ },
250
+ {
251
+ mimeType: "text/x-moz-url",
252
+ data: `${link.url}\n${link.title}`,
253
+ optional: true
254
+ }
255
+ ]
256
+ };
257
+ }
258
+ //#endregion
259
+ //#region src/link/fragment.ts
260
+ const invalid = (message) => copyFailure("invalid-payload", message);
261
+ const collapse = (text) => text.replace(/\s+/g, " ").trim();
262
+ const words = (text) => collapse(text).split(" ").filter((word) => word !== "");
263
+ /**
264
+ * Percent-encodes a directive term. `encodeURIComponent` leaves `-` alone, but the
265
+ * directive syntax uses it (`prefix-,` and `,-suffix`), so it is encoded too.
266
+ */
267
+ function encodeTerm(term) {
268
+ return encodeURIComponent(term).replace(/-/g, "%2D");
269
+ }
270
+ /** The `text=` directive for a fragment. */
271
+ function textDirective(fragment) {
272
+ const terms = [];
273
+ if (fragment.prefix !== void 0 && fragment.prefix !== "") terms.push(`${encodeTerm(fragment.prefix)}-`);
274
+ terms.push(encodeTerm(fragment.start));
275
+ if (fragment.end !== void 0 && fragment.end !== "") terms.push(encodeTerm(fragment.end));
276
+ if (fragment.suffix !== void 0 && fragment.suffix !== "") terms.push(`-${encodeTerm(fragment.suffix)}`);
277
+ return `text=${terms.join(",")}`;
278
+ }
279
+ function positive(value, fallback, name) {
280
+ if (value === void 0) return fallback;
281
+ if (Number.isInteger(value) && value >= 1) return value;
282
+ throw invalid(`\`${name}\` must be a positive integer (received ${String(value)}).`);
283
+ }
284
+ /** Elements that start a new block: text fragment terms never span them. */
285
+ const BLOCK = /* @__PURE__ */ new Set([
286
+ "address",
287
+ "article",
288
+ "aside",
289
+ "blockquote",
290
+ "body",
291
+ "caption",
292
+ "dd",
293
+ "details",
294
+ "dialog",
295
+ "div",
296
+ "dl",
297
+ "dt",
298
+ "fieldset",
299
+ "figcaption",
300
+ "figure",
301
+ "footer",
302
+ "form",
303
+ "h1",
304
+ "h2",
305
+ "h3",
306
+ "h4",
307
+ "h5",
308
+ "h6",
309
+ "header",
310
+ "hgroup",
311
+ "hr",
312
+ "li",
313
+ "main",
314
+ "nav",
315
+ "ol",
316
+ "p",
317
+ "pre",
318
+ "section",
319
+ "summary",
320
+ "table",
321
+ "td",
322
+ "th",
323
+ "tr",
324
+ "ul"
325
+ ]);
326
+ /** The nearest block around `node`, or the top of its tree (a detached node's fragment, or the page body). */
327
+ function blockOf(node) {
328
+ let top = node;
329
+ for (let current = node; current !== null; current = current.parentNode) {
330
+ if (current.nodeType === 1 && BLOCK.has(current.localName)) return current;
331
+ top = current;
332
+ }
333
+ if (top.nodeType !== 9) return top;
334
+ const body = top.body;
335
+ return body instanceof Node ? body : top;
336
+ }
337
+ /** The text of `block` from its start to (`before`) or from (`after`) a boundary point. */
338
+ function around(block, container, offset, side) {
339
+ const range = container.ownerDocument.createRange();
340
+ range.selectNodeContents(block);
341
+ if (side === "before") range.setEnd(container, offset);
342
+ else range.setStart(container, offset);
343
+ return range.toString();
344
+ }
345
+ const count = (haystack, needle) => {
346
+ let found = 0;
347
+ for (let at = haystack.indexOf(needle); at !== -1 && found < 2; at = haystack.indexOf(needle, at + 1)) found += 1;
348
+ return found;
349
+ };
350
+ function rootText(root) {
351
+ const node = root ?? (typeof document === "undefined" ? void 0 : document.body);
352
+ if (node === void 0) return null;
353
+ const range = (node.ownerDocument ?? node).createRange();
354
+ range.selectNodeContents(node);
355
+ return collapse(range.toString()).toLowerCase();
356
+ }
357
+ /** Splits a passage into a directive: whole when short, first and last words when long. */
358
+ function fromText(text, maxWords, contextWords) {
359
+ const all = words(text);
360
+ if (all.length === 0) throw invalid("A text fragment needs some text.");
361
+ if (all.length <= maxWords) return { start: all.join(" ") };
362
+ return {
363
+ start: all.slice(0, contextWords).join(" "),
364
+ end: all.slice(-contextWords).join(" ")
365
+ };
366
+ }
367
+ /** A fragment for a selected range: terms taken from within their own blocks, context added when the passage repeats. */
368
+ function fromRange(range, maxWords, contextWords, root) {
369
+ const startBlock = blockOf(range.startContainer);
370
+ const endBlock = blockOf(range.endContainer);
371
+ const text = collapse(range.toString());
372
+ if (text === "") throw invalid("A text fragment needs some text: the range is empty.");
373
+ let fragment;
374
+ if (startBlock === endBlock) fragment = fromText(text, maxWords, contextWords);
375
+ else {
376
+ const head = words(around(startBlock, range.startContainer, range.startOffset, "after")).slice(0, contextWords);
377
+ const tail = words(around(endBlock, range.endContainer, range.endOffset, "before")).slice(-contextWords);
378
+ fragment = head.length === 0 || tail.length === 0 ? fromText(text, maxWords, contextWords) : {
379
+ start: head.join(" "),
380
+ end: tail.join(" ")
381
+ };
382
+ }
383
+ const page = rootText(root);
384
+ if (page !== null && count(page, fragment.start.toLowerCase()) < 2) return fragment;
385
+ const prefix = words(around(startBlock, range.startContainer, range.startOffset, "before")).slice(-contextWords).join(" ");
386
+ const suffix = words(around(endBlock, range.endContainer, range.endOffset, "after")).slice(0, contextWords).join(" ");
387
+ return {
388
+ ...fragment,
389
+ prefix,
390
+ suffix
391
+ };
392
+ }
393
+ /** A caller's fragment with each term on one line; empty optional terms are left out of the directive. */
394
+ function fromObject(passage) {
395
+ const term = (value) => typeof value === "string" ? collapse(value) : "";
396
+ const start = term(passage.start);
397
+ if (start === "") throw invalid("A text fragment needs a non-empty `start`.");
398
+ return {
399
+ start,
400
+ end: term(passage.end),
401
+ prefix: term(passage.prefix),
402
+ suffix: term(passage.suffix)
403
+ };
404
+ }
405
+ function isRange(value) {
406
+ return typeof value === "object" && value !== null && typeof value.cloneContents === "function" && "startContainer" in value;
407
+ }
408
+ /**
409
+ * A link that scrolls to, and highlights, a passage of the page: the
410
+ * [text fragment](https://wicg.github.io/scroll-to-text-fragment/) syntax
411
+ * (`#:~:text=`), supported by Chromium, Safari and Firefox. Browsers without it
412
+ * open the page at its normal position (or its existing `#section`).
413
+ *
414
+ * The passage is a string, a {@link TextFragment}, or a DOM `Range` (the user's
415
+ * selection): long passages link by their first and last words, and the words
416
+ * around a passage are added when it appears more than once on the page.
417
+ *
418
+ * @example
419
+ * textFragmentUrl(location.href, window.getSelection()!.getRangeAt(0));
420
+ * textFragmentUrl('https://example.com/docs#install', 'npm install react-smart-copy');
421
+ */
422
+ function textFragmentUrl(url, passage, options = {}) {
423
+ const maxWords = positive(options.maxWords, 10, "maxWords");
424
+ const contextWords = positive(options.contextWords, 4, "contextWords");
425
+ let fragment;
426
+ if (typeof passage === "string") fragment = fromText(passage, maxWords, contextWords);
427
+ else if (isRange(passage)) fragment = fromRange(passage, maxWords, contextWords, options.root);
428
+ else if (typeof passage === "object" && passage !== null && typeof passage.start === "string") fragment = fromObject(passage);
429
+ else throw invalid("The passage must be a string, a TextFragment or a Range.");
430
+ const href = resolveLinkUrl(url, options);
431
+ const hashAt = href.indexOf("#");
432
+ return `${hashAt === -1 ? href : href.slice(0, hashAt)}#${hashAt === -1 ? "" : href.slice(hashAt + 1).split(":~:")[0]}:~:${textDirective(fragment)}`;
433
+ }
434
+ /** Whether this browser scrolls to text fragments (`document.fragmentDirective`). */
435
+ function supportsTextFragments() {
436
+ return typeof document !== "undefined" && "fragmentDirective" in document;
437
+ }
438
+ //#endregion
439
+ //#region src/core/text-field.ts
440
+ const TEXT_INPUTS = /* @__PURE__ */ new Set([
441
+ "text",
442
+ "search",
443
+ "url",
444
+ "tel",
445
+ "password"
446
+ ]);
447
+ function asTextField(target) {
448
+ if (typeof target !== "object" || target === null) return null;
449
+ const element = target;
450
+ if (element.nodeName === "TEXTAREA") return target;
451
+ if (element.nodeName === "INPUT" && typeof element.type === "string" && TEXT_INPUTS.has(element.type)) return target;
452
+ return null;
453
+ }
454
+ /**
455
+ * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the
456
+ * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still
457
+ * works, `input` events fire (so React and other frameworks see the change),
458
+ * and `maxlength` is respected. Returns `false` for disabled or read-only fields.
459
+ */
460
+ function insertText(field, text) {
461
+ if (field.disabled || field.readOnly) return false;
462
+ const value = field.nodeName === "INPUT" ? text.replace(/[ \t]*(?:\r\n|\r|\n)+[ \t]*/g, " ") : text;
463
+ const doc = field.ownerDocument;
464
+ field.focus();
465
+ const start = field.selectionStart;
466
+ const end = field.selectionEnd;
467
+ try {
468
+ if (start !== null && end !== null) field.setSelectionRange(start, end);
469
+ if (doc.activeElement === field && doc.execCommand("insertText", false, value)) return true;
470
+ } catch {}
471
+ const from = start ?? field.value.length;
472
+ const to = end ?? from;
473
+ let insert = value;
474
+ if (field.maxLength >= 0) {
475
+ const room = Math.max(0, field.maxLength - (field.value.length - (to - from)));
476
+ insert = insert.slice(0, room);
477
+ if (/[\ud800-\udbff]$/.test(insert)) insert = insert.slice(0, -1);
478
+ }
479
+ if (start === null) setNativeValue(field, field.value + insert);
480
+ else field.setRangeText(insert, from, to, "end");
481
+ const view = doc.defaultView;
482
+ const event = view !== null && typeof view.InputEvent === "function" ? new view.InputEvent("input", {
483
+ bubbles: true,
484
+ inputType: "insertFromPaste",
485
+ data: insert
486
+ }) : new Event("input", { bubbles: true });
487
+ field.dispatchEvent(event);
488
+ return true;
489
+ }
490
+ /**
491
+ * Sets a field's value through the prototype's setter. React tracks the value
492
+ * set on the element itself; going around it lets React see the change and
493
+ * call `onChange` for the `input` event that follows.
494
+ */
495
+ function setNativeValue(field, next) {
496
+ const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(field), "value")?.set;
497
+ if (setter) setter.call(field, next);
498
+ else field.value = next;
499
+ }
500
+ //#endregion
501
+ //#region src/link/paste.ts
502
+ /** One URL with no spaces, as a whole pasted text (surrounding whitespace allowed). */
503
+ const SINGLE_URL = /^\s*<?([a-z][a-z\d+.-]*:[^\s<>]+?)>?\s*$/i;
504
+ /** The URL, or `null` when the clipboard content is not a valid, allowed link. */
505
+ function tryUrl(resolve, candidate) {
506
+ try {
507
+ return resolve(candidate);
508
+ } catch {
509
+ return null;
510
+ }
511
+ }
512
+ function fromUriList(list, resolve) {
513
+ const first = list.split(/\r?\n/).find((line) => line.trim() !== "" && !line.startsWith("#"));
514
+ return first === void 0 ? null : tryUrl(resolve, first.trim());
515
+ }
516
+ /** The single link in pasted HTML (one `<a href>` and nothing else visible besides its text), parsed inertly. */
517
+ function fromHtml(html, resolve) {
518
+ if (typeof DOMParser === "undefined" || html.trim() === "") return null;
519
+ const body = new DOMParser().parseFromString(html.slice(0, 1e5), "text/html").body;
520
+ const anchors = body.querySelectorAll("a[href]");
521
+ if (anchors.length !== 1) return null;
522
+ const anchor = anchors[0];
523
+ const visible = body.textContent.replace(/\s+/g, " ").trim();
524
+ const label = anchor.textContent.replace(/\s+/g, " ").trim();
525
+ if (visible !== label) return null;
526
+ const url = tryUrl(resolve, String(anchor.getAttribute("href")));
527
+ if (url === null) return null;
528
+ const title = cleanTitle(label, 300);
529
+ return {
530
+ url,
531
+ title: title === "" ? url : title,
532
+ titled: title !== "" && title !== url
533
+ };
534
+ }
535
+ /**
536
+ * The link the clipboard (or a drop) holds, or `null`: from `text/uri-list`,
537
+ * from HTML that is exactly one link (keeping its title), or from text that is
538
+ * exactly one URL. Every URL is validated: allowed schemes only (never
539
+ * `javascript:`), credentials removed. Never throws for clipboard content.
540
+ *
541
+ * @example
542
+ * usePaste({ accept: ['text', 'html', 'text/uri-list'], onPaste: (result) => {
543
+ * const link = readLink(result);
544
+ * if (link) addBookmark(link.url, link.title);
545
+ * } });
546
+ */
547
+ function readLink(source, options = {}) {
548
+ return readWith(source, linkUrlResolver(options));
549
+ }
550
+ function readWith(source, resolve) {
551
+ const uriList = source.uriList ?? source.items?.find((item) => item.type === "text/uri-list" && typeof item.data === "string")?.data;
552
+ if (typeof uriList === "string") {
553
+ const url = fromUriList(uriList, resolve);
554
+ if (url !== null) {
555
+ const fromMarkup = typeof source.html === "string" ? fromHtml(source.html, resolve) : null;
556
+ return fromMarkup?.url === url ? fromMarkup : {
557
+ url,
558
+ title: url,
559
+ titled: false
560
+ };
561
+ }
562
+ }
563
+ if (typeof source.html === "string") {
564
+ const link = fromHtml(source.html, resolve);
565
+ if (link !== null) return link;
566
+ }
567
+ const match = typeof source.text === "string" ? SINGLE_URL.exec(source.text) : null;
568
+ const url = match === null ? null : tryUrl(resolve, match[1]);
569
+ return url === null ? null : {
570
+ url,
571
+ title: url,
572
+ titled: false
573
+ };
574
+ }
575
+ /**
576
+ * A paste handler for text fields: pasting a link over selected text turns the
577
+ * selection into a link (`[selected text](url)` by default), as GitHub, Slack
578
+ * and Notion do. Everything else is left to the browser: pasting with nothing
579
+ * selected, pasting over a URL, or pasting something that is not one link. The
580
+ * browser's undo still works. Returns whether it handled the paste.
581
+ *
582
+ * @example
583
+ * <textarea onPaste={pasteAsLink} />
584
+ */
585
+ function pasteAsLink(event, options = {}) {
586
+ const { format, ...urlOptions } = options;
587
+ const resolve = linkUrlResolver(urlOptions);
588
+ if (event.defaultPrevented || event.clipboardData === null) return false;
589
+ const field = asTextField(event.currentTarget) ?? asTextField(event.target);
590
+ if (field === null || field.disabled || field.readOnly || field.selectionStart === null || field.selectionEnd === null) return false;
591
+ const selection = field.value.slice(field.selectionStart, field.selectionEnd);
592
+ if (selection.trim() === "" || SINGLE_URL.test(selection)) return false;
593
+ const data = event.clipboardData;
594
+ const link = readWith({
595
+ text: data.getData("text/plain"),
596
+ html: data.getData("text/html"),
597
+ uriList: data.getData("text/uri-list")
598
+ }, resolve);
599
+ if (link === null) return false;
600
+ const text = format === void 0 ? markdownLink({
601
+ ...link,
602
+ title: selection,
603
+ titled: true
604
+ }) : format(selection, link);
605
+ if (typeof text !== "string") throw copyFailure("invalid-payload", "`format` must return a string.");
606
+ event.preventDefault();
607
+ return insertText(field, text);
608
+ }
609
+ /**
610
+ * A link to the passage the user has selected (a text fragment link), with the
611
+ * page title and the quote, or `null` when nothing is selected. Pass it to
612
+ * `linkPayload` to copy it.
613
+ *
614
+ * @example
615
+ * const link = selectionLink();
616
+ * if (link) copy(() => linkPayload(link));
617
+ */
618
+ function selectionLink(options = {}) {
619
+ if (typeof window === "undefined" || typeof document === "undefined") return null;
620
+ const selection = window.getSelection();
621
+ if (selection === null || selection.rangeCount === 0 || selection.isCollapsed) return null;
622
+ const range = selection.getRangeAt(0);
623
+ const quote = range.toString().replace(/\s+/g, " ").trim();
624
+ if (quote === "") return null;
625
+ const { url = location.href, title = document.title, ...fragmentOptions } = options;
626
+ const href = textFragmentUrl(url, range, fragmentOptions);
627
+ const clean = cleanTitle(title, 300);
628
+ return {
629
+ url: href,
630
+ title: clean === "" ? href : clean,
631
+ titled: clean !== "",
632
+ quote
633
+ };
634
+ }
635
+ //#endregion
636
+ exports.DEFAULT_LINK_PROTOCOLS = DEFAULT_LINK_PROTOCOLS;
637
+ exports.DEFAULT_LINK_TITLE_LENGTH = DEFAULT_LINK_TITLE_LENGTH;
638
+ exports.TRACKING_PARAMETERS = TRACKING_PARAMETERS;
639
+ exports.cleanLinkUrl = cleanLinkUrl;
640
+ exports.insertText = insertText;
641
+ exports.linkPayload = linkPayload;
642
+ exports.markdownLink = markdownLink;
643
+ exports.pasteAsLink = pasteAsLink;
644
+ exports.readLink = readLink;
645
+ exports.resolveLink = resolveLink;
646
+ exports.resolveLinkUrl = resolveLinkUrl;
647
+ exports.selectionLink = selectionLink;
648
+ exports.supportsTextFragments = supportsTextFragments;
649
+ exports.textFragmentUrl = textFragmentUrl;
650
+
651
+ //# sourceMappingURL=link.cjs.map