react-smart-copy 1.13.2 → 1.14.1

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